{"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * Version: MPL 1.1 \/ GPLv3+ \/ LGPLv3+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * The Initial Developer of the Original Code is\n * Caolán McNamara (Red Hat, Inc.)\n * Portions created by the Initial Developer are Copyright (C) 2012 the\n * Initial Developer. All Rights Reserved.\n *\n * Contributor(s): Caolán McNamara \n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 3 or later (the \"GPLv3+\"), or\n * the GNU Lesser General Public License Version 3 or later (the \"LGPLv3+\"),\n * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable\n * instead of those above.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nVclBuilder::VclBuilder(Window *pParent, rtl::OUString sUri)\n{\n xmlreader::XmlReader reader(sUri);\n\n handleChild(pParent, reader);\n\n for (std::vector::iterator aI = m_aChildren.begin(),\n aEnd = m_aChildren.end(); aI != aEnd; ++aI)\n {\n Window *pWindow = *aI;\n if (pWindow)\n {\n pWindow->Show();\n }\n }\n}\n\nVclBuilder::~VclBuilder()\n{\n for (std::vector::reverse_iterator aI = m_aChildren.rbegin(),\n aEnd = m_aChildren.rend(); aI != aEnd; ++aI)\n {\n Window *pWindow = *aI;\n delete pWindow;\n }\n}\n\nWindow *VclBuilder::makeObject(Window *pParent, const rtl::OString &name, bool bVertical)\n{\n Window *pWindow = NULL;\n if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkDialog\")))\n {\n pWindow = new Dialog(pParent, WB_SIZEMOVE);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkBox\")))\n {\n if (bVertical)\n pWindow = new VclVBox(pParent);\n else\n pWindow = new VclHBox(pParent);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkButtonBox\")))\n {\n if (bVertical)\n pWindow = new VclVButtonBox(pParent);\n else\n pWindow = new VclHButtonBox(pParent);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkButton\")))\n {\n pWindow = new PushButton(pParent, WB_CENTER|WB_VCENTER|WB_3DLOOK);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkRadioButton\")))\n {\n pWindow = new RadioButton(pParent, WB_CENTER|WB_VCENTER|WB_3DLOOK);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkCheckButton\")))\n {\n pWindow = new CheckBox(pParent, WB_CENTER|WB_VCENTER|WB_3DLOOK);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkSpinButton\")))\n {\n pWindow = new NumericField(pParent, WB_RIGHT|WB_SPIN|WB_BORDER|WB_3DLOOK);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkComboBox\")))\n {\n pWindow = new ListBox(pParent, WB_DROPDOWN|WB_CENTER|WB_VCENTER|WB_3DLOOK);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkLabel\")))\n {\n pWindow = new FixedText(pParent, WB_CENTER|WB_VCENTER|WB_3DLOOK);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkEntry\")))\n {\n pWindow = new Edit(pParent, WB_LEFT|WB_VCENTER|WB_BORDER|WB_3DLOOK );\n }\n else\n {\n fprintf(stderr, \"TO-DO, implement %s\\n\", name.getStr());\n }\n fprintf(stderr, \"for %s, created %p child of %p\\n\", name.getStr(), pWindow, pParent);\n return pWindow;\n}\n\nWindow *VclBuilder::insertObject(Window *pParent, const rtl::OString &rClass, stringmap &rMap)\n{\n bool bVertical = false;\n stringmap::iterator aFind = rMap.find(rtl::OString(RTL_CONSTASCII_STRINGPARAM(\"orientation\")));\n if (aFind != rMap.end())\n bVertical = aFind->second.equalsIgnoreAsciiCaseL(RTL_CONSTASCII_STRINGPARAM(\"vertical\"));\n\n Window *pCurrentChild = makeObject(pParent, rClass, bVertical);\n if (!pCurrentChild)\n {\n fprintf(stderr, \"missing object!\\n\");\n }\n\n if (pCurrentChild)\n {\n m_aChildren.push_back(pCurrentChild);\n\n for (stringmap::iterator aI = rMap.begin(), aEnd = rMap.end(); aI != aEnd; ++aI)\n {\n const rtl::OString &rKey = aI->first;\n const rtl::OString &rValue = aI->second;\n if (rKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"label\")))\n pCurrentChild->SetText(rtl::OStringToOUString(rValue, RTL_TEXTENCODING_UTF8));\n else if (rKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"visible\")))\n {\n bool bIsVisible = (rValue[0] == 't' || rValue[0] == 'T' || rValue[0] == '1');\n pCurrentChild->Show(bIsVisible);\n }\n else if (rKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"xalign\")))\n {\n WinBits nBits = pCurrentChild->GetStyle();\n nBits &= ~(WB_LEFT | WB_CENTER | WB_RIGHT);\n\n float f = rValue.toFloat();\n if (f == 0.0)\n nBits |= WB_LEFT;\n else if (f == 1.0)\n nBits |= WB_RIGHT;\n else if (f == 0.5)\n nBits |= WB_CENTER;\n\n pCurrentChild->SetStyle(nBits);\n }\n else if (rKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"yalign\")))\n {\n WinBits nBits = pCurrentChild->GetStyle();\n nBits &= ~(WB_TOP | WB_VCENTER | WB_BOTTOM);\n\n float f = rValue.toFloat();\n if (f == 0.0)\n nBits |= WB_TOP;\n else if (f == 1.0)\n nBits |= WB_BOTTOM;\n else if (f == 0.5)\n nBits |= WB_CENTER;\n\n pCurrentChild->SetStyle(nBits);\n }\n else if (rKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"text\")))\n pCurrentChild->SetText(rtl::OStringToOUString(rValue, RTL_TEXTENCODING_UTF8));\n else\n fprintf(stderr, \"unhandled property %s\\n\", rKey.getStr());\n }\n }\n\n if (!pCurrentChild)\n {\n fprintf(stderr, \"missing object!\\n\");\n pCurrentChild = m_aChildren.empty() ? pParent : m_aChildren.back();\n }\n rMap.clear();\n return pCurrentChild;\n}\n\nvoid VclBuilder::handleChild(Window *pParent, xmlreader::XmlReader &reader)\n{\n int nLevel = 1;\n\n Window *pCurrentChild = NULL;\n\n while(1)\n {\n xmlreader::Span name;\n int nsId;\n xmlreader::XmlReader::Result res = reader.nextItem(\n xmlreader::XmlReader::TEXT_NONE, &name, &nsId);\n\n if (res == xmlreader::XmlReader::RESULT_BEGIN)\n {\n if (name.equals(RTL_CONSTASCII_STRINGPARAM(\"object\")))\n {\n pCurrentChild = handleObject(pParent, reader);\n\n if (pCurrentChild)\n {\n rtl::OString sPosition(RTL_CONSTASCII_STRINGPARAM(\"position\"));\n std::vector aChilds;\n for (Window* pChild = pCurrentChild->GetWindow(WINDOW_FIRSTCHILD); pChild;\n pChild = pChild->GetWindow(WINDOW_NEXT))\n {\n aChilds.push_back(pChild);\n }\n\n for (size_t i = 0; i < aChilds.size(); ++i)\n {\n sal_uInt16 nPosition = aChilds[i]->getWidgetProperty(sPosition);\n aChilds[i]->reorderWithinParent(nPosition);\n }\n }\n }\n else if (name.equals(RTL_CONSTASCII_STRINGPARAM(\"packing\")))\n {\n handlePacking(pCurrentChild, reader);\n }\n else\n ++nLevel;\n }\n\n if (res == xmlreader::XmlReader::RESULT_END)\n {\n --nLevel;\n }\n\n if (!nLevel)\n break;\n\n if (res == xmlreader::XmlReader::RESULT_DONE)\n break;\n }\n}\n\nWindow* VclBuilder::handleObject(Window *pParent, xmlreader::XmlReader &reader)\n{\n rtl::OString sClass;\n\n xmlreader::Span name;\n int nsId;\n\n while (reader.nextAttribute(&nsId, &name))\n {\n if (name.equals(RTL_CONSTASCII_STRINGPARAM(\"class\")))\n {\n name = reader.getAttributeValue(false);\n sClass = rtl::OString(name.begin, name.length);\n }\n }\n\n int nLevel = 1;\n\n stringmap aProperties;\n\n Window *pCurrentChild = NULL;\n while(1)\n {\n xmlreader::XmlReader::Result res = reader.nextItem(\n xmlreader::XmlReader::TEXT_NONE, &name, &nsId);\n\n if (res == xmlreader::XmlReader::RESULT_DONE)\n break;\n\n if (res == xmlreader::XmlReader::RESULT_BEGIN)\n {\n if (name.equals(RTL_CONSTASCII_STRINGPARAM(\"child\")))\n {\n if (!pCurrentChild)\n pCurrentChild = insertObject(pParent, sClass, aProperties);\n handleChild(pCurrentChild, reader);\n }\n else\n {\n ++nLevel;\n if (name.equals(RTL_CONSTASCII_STRINGPARAM(\"property\")))\n collectProperty(reader, aProperties);\n }\n }\n\n if (res == xmlreader::XmlReader::RESULT_END)\n {\n --nLevel;\n }\n\n if (!nLevel)\n break;\n }\n\n if (!pCurrentChild)\n pCurrentChild = insertObject(pParent, sClass, aProperties);\n\n return pCurrentChild;\n}\n\nvoid VclBuilder::handlePacking(Window *pCurrent, xmlreader::XmlReader &reader)\n{\n xmlreader::Span name;\n int nsId;\n\n int nLevel = 1;\n\n while(1)\n {\n xmlreader::XmlReader::Result res = reader.nextItem(\n xmlreader::XmlReader::TEXT_NONE, &name, &nsId);\n\n if (res == xmlreader::XmlReader::RESULT_DONE)\n break;\n\n if (res == xmlreader::XmlReader::RESULT_BEGIN)\n {\n ++nLevel;\n if (name.equals(RTL_CONSTASCII_STRINGPARAM(\"property\")))\n applyPackingProperty(pCurrent, reader);\n }\n\n if (res == xmlreader::XmlReader::RESULT_END)\n {\n --nLevel;\n }\n\n if (!nLevel)\n break;\n }\n}\n\nvoid VclBuilder::applyPackingProperty(Window *pCurrent,\n xmlreader::XmlReader &reader)\n{\n xmlreader::Span name;\n int nsId;\n\n if (!pCurrent)\n return;\n\n while (reader.nextAttribute(&nsId, &name))\n {\n if (name.equals(RTL_CONSTASCII_STRINGPARAM(\"name\")))\n {\n name = reader.getAttributeValue(false);\n rtl::OString sKey(name.begin, name.length);\n reader.nextItem(\n xmlreader::XmlReader::TEXT_NORMALIZED, &name, &nsId);\n rtl::OString sValue(name.begin, name.length);\n\n if ( sKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"expand\")) ||\n sKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"fill\")) )\n {\n bool bTrue = (sValue[0] == 't' || sValue[0] == 'T' || sValue[0] == '1');\n pCurrent->setChildProperty(sKey, bTrue);\n }\n else if (sKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"position\")))\n {\n pCurrent->setChildProperty(sKey, static_cast(sValue.toInt32()));\n }\n else if (sKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"pack_type\")))\n {\n sal_Int32 nPackType = (sValue[0] == 'e' || sValue[0] == 'e') ? VCL_PACK_END : VCL_PACK_START;\n pCurrent->setChildProperty(rtl::OString(\"pack-type\"), nPackType);\n }\n else\n fprintf(stderr, \"unknown packing %s\\n\", sKey.getStr());\n }\n }\n}\n\nvoid VclBuilder::collectProperty(xmlreader::XmlReader &reader, stringmap &rMap)\n{\n xmlreader::Span name;\n int nsId;\n\n while (reader.nextAttribute(&nsId, &name))\n {\n if (name.equals(RTL_CONSTASCII_STRINGPARAM(\"name\")))\n {\n name = reader.getAttributeValue(false);\n rtl::OString sProperty(name.begin, name.length);\n reader.nextItem(\n xmlreader::XmlReader::TEXT_NORMALIZED, &name, &nsId);\n rtl::OString sValue(name.begin, name.length);\n rMap[sProperty] = sValue;\n }\n }\n}\n\n\nWindow *VclBuilder::get_widget_root()\n{\n return m_aChildren.empty() ? NULL : m_aChildren[0];\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nfollow theme by default for Dialogs\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * Version: MPL 1.1 \/ GPLv3+ \/ LGPLv3+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * The Initial Developer of the Original Code is\n * Caolán McNamara (Red Hat, Inc.)\n * Portions created by the Initial Developer are Copyright (C) 2012 the\n * Initial Developer. All Rights Reserved.\n *\n * Contributor(s): Caolán McNamara \n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 3 or later (the \"GPLv3+\"), or\n * the GNU Lesser General Public License Version 3 or later (the \"LGPLv3+\"),\n * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable\n * instead of those above.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nVclBuilder::VclBuilder(Window *pParent, rtl::OUString sUri)\n{\n xmlreader::XmlReader reader(sUri);\n\n handleChild(pParent, reader);\n\n for (std::vector::iterator aI = m_aChildren.begin(),\n aEnd = m_aChildren.end(); aI != aEnd; ++aI)\n {\n Window *pWindow = *aI;\n if (pWindow)\n {\n pWindow->Show();\n }\n }\n}\n\nVclBuilder::~VclBuilder()\n{\n for (std::vector::reverse_iterator aI = m_aChildren.rbegin(),\n aEnd = m_aChildren.rend(); aI != aEnd; ++aI)\n {\n Window *pWindow = *aI;\n delete pWindow;\n }\n}\n\nWindow *VclBuilder::makeObject(Window *pParent, const rtl::OString &name, bool bVertical)\n{\n Window *pWindow = NULL;\n if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkDialog\")))\n {\n pWindow = new Dialog(pParent, WB_SIZEMOVE|WB_3DLOOK);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkBox\")))\n {\n if (bVertical)\n pWindow = new VclVBox(pParent);\n else\n pWindow = new VclHBox(pParent);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkButtonBox\")))\n {\n if (bVertical)\n pWindow = new VclVButtonBox(pParent);\n else\n pWindow = new VclHButtonBox(pParent);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkButton\")))\n {\n pWindow = new PushButton(pParent, WB_CENTER|WB_VCENTER|WB_3DLOOK);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkRadioButton\")))\n {\n pWindow = new RadioButton(pParent, WB_CENTER|WB_VCENTER|WB_3DLOOK);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkCheckButton\")))\n {\n pWindow = new CheckBox(pParent, WB_CENTER|WB_VCENTER|WB_3DLOOK);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkSpinButton\")))\n {\n pWindow = new NumericField(pParent, WB_RIGHT|WB_SPIN|WB_BORDER|WB_3DLOOK);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkComboBox\")))\n {\n pWindow = new ListBox(pParent, WB_DROPDOWN|WB_CENTER|WB_VCENTER|WB_3DLOOK);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkLabel\")))\n {\n pWindow = new FixedText(pParent, WB_CENTER|WB_VCENTER|WB_3DLOOK);\n }\n else if (name.equalsL(RTL_CONSTASCII_STRINGPARAM(\"GtkEntry\")))\n {\n pWindow = new Edit(pParent, WB_LEFT|WB_VCENTER|WB_BORDER|WB_3DLOOK );\n }\n else\n {\n fprintf(stderr, \"TO-DO, implement %s\\n\", name.getStr());\n }\n fprintf(stderr, \"for %s, created %p child of %p\\n\", name.getStr(), pWindow, pParent);\n return pWindow;\n}\n\nWindow *VclBuilder::insertObject(Window *pParent, const rtl::OString &rClass, stringmap &rMap)\n{\n bool bVertical = false;\n stringmap::iterator aFind = rMap.find(rtl::OString(RTL_CONSTASCII_STRINGPARAM(\"orientation\")));\n if (aFind != rMap.end())\n bVertical = aFind->second.equalsIgnoreAsciiCaseL(RTL_CONSTASCII_STRINGPARAM(\"vertical\"));\n\n Window *pCurrentChild = makeObject(pParent, rClass, bVertical);\n if (!pCurrentChild)\n {\n fprintf(stderr, \"missing object!\\n\");\n }\n\n if (pCurrentChild)\n {\n m_aChildren.push_back(pCurrentChild);\n\n for (stringmap::iterator aI = rMap.begin(), aEnd = rMap.end(); aI != aEnd; ++aI)\n {\n const rtl::OString &rKey = aI->first;\n const rtl::OString &rValue = aI->second;\n if (rKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"label\")))\n pCurrentChild->SetText(rtl::OStringToOUString(rValue, RTL_TEXTENCODING_UTF8));\n else if (rKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"visible\")))\n {\n bool bIsVisible = (rValue[0] == 't' || rValue[0] == 'T' || rValue[0] == '1');\n pCurrentChild->Show(bIsVisible);\n }\n else if (rKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"xalign\")))\n {\n WinBits nBits = pCurrentChild->GetStyle();\n nBits &= ~(WB_LEFT | WB_CENTER | WB_RIGHT);\n\n float f = rValue.toFloat();\n if (f == 0.0)\n nBits |= WB_LEFT;\n else if (f == 1.0)\n nBits |= WB_RIGHT;\n else if (f == 0.5)\n nBits |= WB_CENTER;\n\n pCurrentChild->SetStyle(nBits);\n }\n else if (rKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"yalign\")))\n {\n WinBits nBits = pCurrentChild->GetStyle();\n nBits &= ~(WB_TOP | WB_VCENTER | WB_BOTTOM);\n\n float f = rValue.toFloat();\n if (f == 0.0)\n nBits |= WB_TOP;\n else if (f == 1.0)\n nBits |= WB_BOTTOM;\n else if (f == 0.5)\n nBits |= WB_CENTER;\n\n pCurrentChild->SetStyle(nBits);\n }\n else if (rKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"text\")))\n pCurrentChild->SetText(rtl::OStringToOUString(rValue, RTL_TEXTENCODING_UTF8));\n else\n fprintf(stderr, \"unhandled property %s\\n\", rKey.getStr());\n }\n }\n\n if (!pCurrentChild)\n {\n fprintf(stderr, \"missing object!\\n\");\n pCurrentChild = m_aChildren.empty() ? pParent : m_aChildren.back();\n }\n rMap.clear();\n return pCurrentChild;\n}\n\nvoid VclBuilder::handleChild(Window *pParent, xmlreader::XmlReader &reader)\n{\n int nLevel = 1;\n\n Window *pCurrentChild = NULL;\n\n while(1)\n {\n xmlreader::Span name;\n int nsId;\n xmlreader::XmlReader::Result res = reader.nextItem(\n xmlreader::XmlReader::TEXT_NONE, &name, &nsId);\n\n if (res == xmlreader::XmlReader::RESULT_BEGIN)\n {\n if (name.equals(RTL_CONSTASCII_STRINGPARAM(\"object\")))\n {\n pCurrentChild = handleObject(pParent, reader);\n\n if (pCurrentChild)\n {\n rtl::OString sPosition(RTL_CONSTASCII_STRINGPARAM(\"position\"));\n std::vector aChilds;\n for (Window* pChild = pCurrentChild->GetWindow(WINDOW_FIRSTCHILD); pChild;\n pChild = pChild->GetWindow(WINDOW_NEXT))\n {\n aChilds.push_back(pChild);\n }\n\n for (size_t i = 0; i < aChilds.size(); ++i)\n {\n sal_uInt16 nPosition = aChilds[i]->getWidgetProperty(sPosition);\n aChilds[i]->reorderWithinParent(nPosition);\n }\n }\n }\n else if (name.equals(RTL_CONSTASCII_STRINGPARAM(\"packing\")))\n {\n handlePacking(pCurrentChild, reader);\n }\n else\n ++nLevel;\n }\n\n if (res == xmlreader::XmlReader::RESULT_END)\n {\n --nLevel;\n }\n\n if (!nLevel)\n break;\n\n if (res == xmlreader::XmlReader::RESULT_DONE)\n break;\n }\n}\n\nWindow* VclBuilder::handleObject(Window *pParent, xmlreader::XmlReader &reader)\n{\n rtl::OString sClass;\n\n xmlreader::Span name;\n int nsId;\n\n while (reader.nextAttribute(&nsId, &name))\n {\n if (name.equals(RTL_CONSTASCII_STRINGPARAM(\"class\")))\n {\n name = reader.getAttributeValue(false);\n sClass = rtl::OString(name.begin, name.length);\n }\n }\n\n int nLevel = 1;\n\n stringmap aProperties;\n\n Window *pCurrentChild = NULL;\n while(1)\n {\n xmlreader::XmlReader::Result res = reader.nextItem(\n xmlreader::XmlReader::TEXT_NONE, &name, &nsId);\n\n if (res == xmlreader::XmlReader::RESULT_DONE)\n break;\n\n if (res == xmlreader::XmlReader::RESULT_BEGIN)\n {\n if (name.equals(RTL_CONSTASCII_STRINGPARAM(\"child\")))\n {\n if (!pCurrentChild)\n pCurrentChild = insertObject(pParent, sClass, aProperties);\n handleChild(pCurrentChild, reader);\n }\n else\n {\n ++nLevel;\n if (name.equals(RTL_CONSTASCII_STRINGPARAM(\"property\")))\n collectProperty(reader, aProperties);\n }\n }\n\n if (res == xmlreader::XmlReader::RESULT_END)\n {\n --nLevel;\n }\n\n if (!nLevel)\n break;\n }\n\n if (!pCurrentChild)\n pCurrentChild = insertObject(pParent, sClass, aProperties);\n\n return pCurrentChild;\n}\n\nvoid VclBuilder::handlePacking(Window *pCurrent, xmlreader::XmlReader &reader)\n{\n xmlreader::Span name;\n int nsId;\n\n int nLevel = 1;\n\n while(1)\n {\n xmlreader::XmlReader::Result res = reader.nextItem(\n xmlreader::XmlReader::TEXT_NONE, &name, &nsId);\n\n if (res == xmlreader::XmlReader::RESULT_DONE)\n break;\n\n if (res == xmlreader::XmlReader::RESULT_BEGIN)\n {\n ++nLevel;\n if (name.equals(RTL_CONSTASCII_STRINGPARAM(\"property\")))\n applyPackingProperty(pCurrent, reader);\n }\n\n if (res == xmlreader::XmlReader::RESULT_END)\n {\n --nLevel;\n }\n\n if (!nLevel)\n break;\n }\n}\n\nvoid VclBuilder::applyPackingProperty(Window *pCurrent,\n xmlreader::XmlReader &reader)\n{\n xmlreader::Span name;\n int nsId;\n\n if (!pCurrent)\n return;\n\n while (reader.nextAttribute(&nsId, &name))\n {\n if (name.equals(RTL_CONSTASCII_STRINGPARAM(\"name\")))\n {\n name = reader.getAttributeValue(false);\n rtl::OString sKey(name.begin, name.length);\n reader.nextItem(\n xmlreader::XmlReader::TEXT_NORMALIZED, &name, &nsId);\n rtl::OString sValue(name.begin, name.length);\n\n if ( sKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"expand\")) ||\n sKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"fill\")) )\n {\n bool bTrue = (sValue[0] == 't' || sValue[0] == 'T' || sValue[0] == '1');\n pCurrent->setChildProperty(sKey, bTrue);\n }\n else if (sKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"position\")))\n {\n pCurrent->setChildProperty(sKey, static_cast(sValue.toInt32()));\n }\n else if (sKey.equalsL(RTL_CONSTASCII_STRINGPARAM(\"pack_type\")))\n {\n sal_Int32 nPackType = (sValue[0] == 'e' || sValue[0] == 'e') ? VCL_PACK_END : VCL_PACK_START;\n pCurrent->setChildProperty(rtl::OString(\"pack-type\"), nPackType);\n }\n else\n fprintf(stderr, \"unknown packing %s\\n\", sKey.getStr());\n }\n }\n}\n\nvoid VclBuilder::collectProperty(xmlreader::XmlReader &reader, stringmap &rMap)\n{\n xmlreader::Span name;\n int nsId;\n\n while (reader.nextAttribute(&nsId, &name))\n {\n if (name.equals(RTL_CONSTASCII_STRINGPARAM(\"name\")))\n {\n name = reader.getAttributeValue(false);\n rtl::OString sProperty(name.begin, name.length);\n reader.nextItem(\n xmlreader::XmlReader::TEXT_NORMALIZED, &name, &nsId);\n rtl::OString sValue(name.begin, name.length);\n rMap[sProperty] = sValue;\n }\n }\n}\n\n\nWindow *VclBuilder::get_widget_root()\n{\n return m_aChildren.empty() ? NULL : m_aChildren[0];\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"forgot to remove the env variable based OpenGL setting<|endoftext|>"} {"text":"\/\/ Copyright 2013 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\/\/ Font management utilities\n\n#include \".\/font.h\"\n\n#include \n\n#include \".\/buffer.h\"\n#include \".\/port.h\"\n#include \".\/store_bytes.h\"\n#include \".\/table_tags.h\"\n#include \".\/woff2_common.h\"\n\nnamespace woff2 {\n\nFont::Table* Font::FindTable(uint32_t tag) {\n std::map::iterator it = tables.find(tag);\n return it == tables.end() ? 0 : &it->second;\n}\n\nconst Font::Table* Font::FindTable(uint32_t tag) const {\n std::map::const_iterator it = tables.find(tag);\n return it == tables.end() ? 0 : &it->second;\n}\n\nstd::vector Font::OutputOrderedTags() const {\n std::vector output_order;\n\n for (const auto& i : tables) {\n const Font::Table& table = i.second;\n \/\/ This is a transformed table, we will write it together with the\n \/\/ original version.\n if (table.tag & 0x80808080) {\n continue;\n }\n output_order.push_back(table.tag);\n }\n\n \/\/ Alphabetize then put loca immediately after glyf\n auto glyf_loc = std::find(output_order.begin(), output_order.end(),\n kGlyfTableTag);\n auto loca_loc = std::find(output_order.begin(), output_order.end(),\n kLocaTableTag);\n if (glyf_loc != output_order.end() && loca_loc != output_order.end()) {\n output_order.erase(loca_loc);\n output_order.insert(std::find(output_order.begin(), output_order.end(),\n kGlyfTableTag) + 1, kLocaTableTag);\n }\n\n return output_order;\n}\n\nbool ReadTrueTypeFont(Buffer* file, const uint8_t* data, size_t len,\n Font* font) {\n \/\/ We don't care about the search_range, entry_selector and range_shift\n \/\/ fields, they will always be computed upon writing the font.\n if (!file->ReadU16(&font->num_tables) ||\n !file->Skip(6)) {\n return FONT_COMPRESSION_FAILURE();\n }\n\n std::map intervals;\n for (uint16_t i = 0; i < font->num_tables; ++i) {\n Font::Table table;\n table.flag_byte = 0;\n table.reuse_of = NULL;\n if (!file->ReadU32(&table.tag) ||\n !file->ReadU32(&table.checksum) ||\n !file->ReadU32(&table.offset) ||\n !file->ReadU32(&table.length)) {\n return FONT_COMPRESSION_FAILURE();\n }\n if ((table.offset & 3) != 0 ||\n table.length > len ||\n len - table.length < table.offset) {\n return FONT_COMPRESSION_FAILURE();\n }\n intervals[table.offset] = table.length;\n table.data = data + table.offset;\n if (font->tables.find(table.tag) != font->tables.end()) {\n return FONT_COMPRESSION_FAILURE();\n }\n font->tables[table.tag] = table;\n }\n\n \/\/ Check that tables are non-overlapping.\n uint32_t last_offset = 12UL + 16UL * font->num_tables;\n for (const auto& i : intervals) {\n if (i.first < last_offset || i.first + i.second < i.first) {\n return FONT_COMPRESSION_FAILURE();\n }\n last_offset = i.first + i.second;\n }\n\n \/\/ Sanity check key tables\n const Font::Table* head_table = font->FindTable(kHeadTableTag);\n if (head_table != NULL && head_table->length < 52) {\n return FONT_COMPRESSION_FAILURE();\n }\n\n return true;\n}\n\nbool ReadCollectionFont(Buffer* file, const uint8_t* data, size_t len,\n Font* font,\n std::map* all_tables) {\n if (!file->ReadU32(&font->flavor)) {\n return FONT_COMPRESSION_FAILURE();\n }\n if (!ReadTrueTypeFont(file, data, len, font)) {\n return FONT_COMPRESSION_FAILURE();\n }\n\n for (auto& entry : font->tables) {\n Font::Table& table = entry.second;\n\n if (all_tables->find(table.offset) == all_tables->end()) {\n (*all_tables)[table.offset] = font->FindTable(table.tag);\n } else {\n table.reuse_of = (*all_tables)[table.offset];\n }\n\n }\n return true;\n}\n\nbool ReadTrueTypeCollection(Buffer* file, const uint8_t* data, size_t len,\n FontCollection* font_collection) {\n uint32_t num_fonts;\n\n if (!file->ReadU32(&font_collection->header_version) ||\n !file->ReadU32(&num_fonts)) {\n return FONT_COMPRESSION_FAILURE();\n }\n\n std::vector offsets;\n for (size_t i = 0; i < num_fonts; i++) {\n uint32_t offset;\n if (!file->ReadU32(&offset)) {\n return FONT_COMPRESSION_FAILURE();\n }\n offsets.push_back(offset);\n }\n\n font_collection->fonts.resize(offsets.size());\n std::vector::iterator font_it = font_collection->fonts.begin();\n\n std::map all_tables;\n for (const auto offset : offsets) {\n file->set_offset(offset);\n Font& font = *font_it++;\n if (!ReadCollectionFont(file, data, len, &font, &all_tables)) {\n return FONT_COMPRESSION_FAILURE();\n }\n }\n\n return true;\n}\n\nbool ReadFont(const uint8_t* data, size_t len, Font* font) {\n Buffer file(data, len);\n\n if (!file.ReadU32(&font->flavor)) {\n return FONT_COMPRESSION_FAILURE();\n }\n\n if (font->flavor == kTtcFontFlavor) {\n return FONT_COMPRESSION_FAILURE();\n }\n return ReadTrueTypeFont(&file, data, len, font);\n}\n\nbool ReadFontCollection(const uint8_t* data, size_t len,\n FontCollection* font_collection) {\n Buffer file(data, len);\n\n if (!file.ReadU32(&font_collection->flavor)) {\n return FONT_COMPRESSION_FAILURE();\n }\n\n if (font_collection->flavor != kTtcFontFlavor) {\n font_collection->fonts.resize(1);\n Font& font = font_collection->fonts[0];\n font.flavor = font_collection->flavor;\n return ReadTrueTypeFont(&file, data, len, &font);\n }\n return ReadTrueTypeCollection(&file, data, len, font_collection);\n}\n\nsize_t FontFileSize(const Font& font) {\n size_t max_offset = 12ULL + 16ULL * font.num_tables;\n for (const auto& i : font.tables) {\n const Font::Table& table = i.second;\n size_t padding_size = (4 - (table.length & 3)) & 3;\n size_t end_offset = (padding_size + table.offset) + table.length;\n max_offset = std::max(max_offset, end_offset);\n }\n return max_offset;\n}\n\nsize_t FontCollectionFileSize(const FontCollection& font_collection) {\n size_t max_offset = 0;\n for (auto& font : font_collection.fonts) {\n \/\/ font file size actually just finds max offset\n max_offset = std::max(max_offset, FontFileSize(font));\n }\n return max_offset;\n}\n\nbool WriteFont(const Font& font, uint8_t* dst, size_t dst_size) {\n size_t offset = 0;\n return WriteFont(font, &offset, dst, dst_size);\n}\n\nbool WriteTableRecord(const Font::Table* table, size_t* offset, uint8_t* dst,\n size_t dst_size) {\n if (dst_size < *offset + kSfntEntrySize) {\n return FONT_COMPRESSION_FAILURE();\n }\n if (table->IsReused()) {\n table = table->reuse_of;\n }\n StoreU32(table->tag, offset, dst);\n StoreU32(table->checksum, offset, dst);\n StoreU32(table->offset, offset, dst);\n StoreU32(table->length, offset, dst);\n return true;\n}\n\nbool WriteTable(const Font::Table& table, size_t* offset, uint8_t* dst,\n size_t dst_size) {\n if (!WriteTableRecord(&table, offset, dst, dst_size)) {\n return false;\n }\n\n \/\/ Write the actual table data if it's the first time we've seen it\n if (!table.IsReused()) {\n if (table.offset + table.length < table.offset ||\n dst_size < table.offset + table.length) {\n return FONT_COMPRESSION_FAILURE();\n }\n memcpy(dst + table.offset, table.data, table.length);\n size_t padding_size = (4 - (table.length & 3)) & 3;\n if (table.offset + table.length + padding_size < padding_size ||\n dst_size < table.offset + table.length + padding_size) {\n return FONT_COMPRESSION_FAILURE();\n }\n memset(dst + table.offset + table.length, 0, padding_size);\n }\n return true;\n}\n\nbool WriteFont(const Font& font, size_t* offset, uint8_t* dst,\n size_t dst_size) {\n if (dst_size < 12ULL + 16ULL * font.num_tables) {\n return FONT_COMPRESSION_FAILURE();\n }\n StoreU32(font.flavor, offset, dst);\n Store16(font.num_tables, offset, dst);\n uint16_t max_pow2 = font.num_tables ? Log2Floor(font.num_tables) : 0;\n uint16_t search_range = max_pow2 ? 1 << (max_pow2 + 4) : 0;\n uint16_t range_shift = (font.num_tables << 4) - search_range;\n Store16(search_range, offset, dst);\n Store16(max_pow2, offset, dst);\n Store16(range_shift, offset, dst);\n\n for (const auto& i : font.tables) {\n if (!WriteTable(i.second, offset, dst, dst_size)) {\n return false;\n }\n }\n\n return true;\n}\n\nbool WriteFontCollection(const FontCollection& font_collection, uint8_t* dst,\n size_t dst_size) {\n size_t offset = 0;\n\n \/\/ It's simpler if this just a simple sfnt\n if (font_collection.flavor != kTtcFontFlavor) {\n return WriteFont(font_collection.fonts[0], &offset, dst, dst_size);\n }\n\n \/\/ Write TTC header\n StoreU32(kTtcFontFlavor, &offset, dst);\n StoreU32(font_collection.header_version, &offset, dst);\n StoreU32(font_collection.fonts.size(), &offset, dst);\n\n \/\/ Offset Table, zeroed for now\n size_t offset_table = offset; \/\/ where to write offsets later\n for (size_t i = 0; i < font_collection.fonts.size(); i++) {\n StoreU32(0, &offset, dst);\n }\n\n if (font_collection.header_version == 0x00020000) {\n StoreU32(0, &offset, dst); \/\/ ulDsigTag\n StoreU32(0, &offset, dst); \/\/ ulDsigLength\n StoreU32(0, &offset, dst); \/\/ ulDsigOffset\n }\n\n \/\/ Write fonts and their offsets.\n for (size_t i = 0; i < font_collection.fonts.size(); i++) {\n const auto& font = font_collection.fonts[i];\n StoreU32(offset, &offset_table, dst);\n if (!WriteFont(font, &offset, dst, dst_size)) {\n return false;\n }\n }\n\n return true;\n}\n\nint NumGlyphs(const Font& font) {\n const Font::Table* head_table = font.FindTable(kHeadTableTag);\n const Font::Table* loca_table = font.FindTable(kLocaTableTag);\n if (head_table == NULL || loca_table == NULL || head_table->length < 52) {\n return 0;\n }\n int index_fmt = IndexFormat(font);\n int num_glyphs = (loca_table->length \/ (index_fmt == 0 ? 2 : 4)) - 1;\n return num_glyphs;\n}\n\nint IndexFormat(const Font& font) {\n const Font::Table* head_table = font.FindTable(kHeadTableTag);\n if (head_table == NULL) {\n return 0;\n }\n return head_table->data[51];\n}\n\nbool Font::Table::IsReused() const {\n return this->reuse_of != NULL;\n}\n\nbool GetGlyphData(const Font& font, int glyph_index,\n const uint8_t** glyph_data, size_t* glyph_size) {\n if (glyph_index < 0) {\n return FONT_COMPRESSION_FAILURE();\n }\n const Font::Table* head_table = font.FindTable(kHeadTableTag);\n const Font::Table* loca_table = font.FindTable(kLocaTableTag);\n const Font::Table* glyf_table = font.FindTable(kGlyfTableTag);\n if (head_table == NULL || loca_table == NULL || glyf_table == NULL ||\n head_table->length < 52) {\n return FONT_COMPRESSION_FAILURE();\n }\n\n int index_fmt = IndexFormat(font);\n\n Buffer loca_buf(loca_table->data, loca_table->length);\n if (index_fmt == 0) {\n uint16_t offset1, offset2;\n if (!loca_buf.Skip(2 * glyph_index) ||\n !loca_buf.ReadU16(&offset1) ||\n !loca_buf.ReadU16(&offset2) ||\n offset2 < offset1 ||\n 2 * offset2 > glyf_table->length) {\n return FONT_COMPRESSION_FAILURE();\n }\n *glyph_data = glyf_table->data + 2 * offset1;\n *glyph_size = 2 * (offset2 - offset1);\n } else {\n uint32_t offset1, offset2;\n if (!loca_buf.Skip(4 * glyph_index) ||\n !loca_buf.ReadU32(&offset1) ||\n !loca_buf.ReadU32(&offset2) ||\n offset2 < offset1 ||\n offset2 > glyf_table->length) {\n return FONT_COMPRESSION_FAILURE();\n }\n *glyph_data = glyf_table->data + offset1;\n *glyph_size = offset2 - offset1;\n }\n return true;\n}\n\nbool RemoveDigitalSignature(Font* font) {\n std::map::iterator it =\n font->tables.find(kDsigTableTag);\n if (it != font->tables.end()) {\n font->tables.erase(it);\n font->num_tables = font->tables.size();\n }\n return true;\n}\n\n} \/\/ namespace woff2\nFix a crash in the woff2 encoder when it encounters a loca table with a length of zero.\/\/ Copyright 2013 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\/\/ Font management utilities\n\n#include \".\/font.h\"\n\n#include \n\n#include \".\/buffer.h\"\n#include \".\/port.h\"\n#include \".\/store_bytes.h\"\n#include \".\/table_tags.h\"\n#include \".\/woff2_common.h\"\n\nnamespace woff2 {\n\nFont::Table* Font::FindTable(uint32_t tag) {\n std::map::iterator it = tables.find(tag);\n return it == tables.end() ? 0 : &it->second;\n}\n\nconst Font::Table* Font::FindTable(uint32_t tag) const {\n std::map::const_iterator it = tables.find(tag);\n return it == tables.end() ? 0 : &it->second;\n}\n\nstd::vector Font::OutputOrderedTags() const {\n std::vector output_order;\n\n for (const auto& i : tables) {\n const Font::Table& table = i.second;\n \/\/ This is a transformed table, we will write it together with the\n \/\/ original version.\n if (table.tag & 0x80808080) {\n continue;\n }\n output_order.push_back(table.tag);\n }\n\n \/\/ Alphabetize then put loca immediately after glyf\n auto glyf_loc = std::find(output_order.begin(), output_order.end(),\n kGlyfTableTag);\n auto loca_loc = std::find(output_order.begin(), output_order.end(),\n kLocaTableTag);\n if (glyf_loc != output_order.end() && loca_loc != output_order.end()) {\n output_order.erase(loca_loc);\n output_order.insert(std::find(output_order.begin(), output_order.end(),\n kGlyfTableTag) + 1, kLocaTableTag);\n }\n\n return output_order;\n}\n\nbool ReadTrueTypeFont(Buffer* file, const uint8_t* data, size_t len,\n Font* font) {\n \/\/ We don't care about the search_range, entry_selector and range_shift\n \/\/ fields, they will always be computed upon writing the font.\n if (!file->ReadU16(&font->num_tables) ||\n !file->Skip(6)) {\n return FONT_COMPRESSION_FAILURE();\n }\n\n std::map intervals;\n for (uint16_t i = 0; i < font->num_tables; ++i) {\n Font::Table table;\n table.flag_byte = 0;\n table.reuse_of = NULL;\n if (!file->ReadU32(&table.tag) ||\n !file->ReadU32(&table.checksum) ||\n !file->ReadU32(&table.offset) ||\n !file->ReadU32(&table.length)) {\n return FONT_COMPRESSION_FAILURE();\n }\n if ((table.offset & 3) != 0 ||\n table.length > len ||\n len - table.length < table.offset) {\n return FONT_COMPRESSION_FAILURE();\n }\n intervals[table.offset] = table.length;\n table.data = data + table.offset;\n if (font->tables.find(table.tag) != font->tables.end()) {\n return FONT_COMPRESSION_FAILURE();\n }\n font->tables[table.tag] = table;\n }\n\n \/\/ Check that tables are non-overlapping.\n uint32_t last_offset = 12UL + 16UL * font->num_tables;\n for (const auto& i : intervals) {\n if (i.first < last_offset || i.first + i.second < i.first) {\n return FONT_COMPRESSION_FAILURE();\n }\n last_offset = i.first + i.second;\n }\n\n \/\/ Sanity check key tables\n const Font::Table* head_table = font->FindTable(kHeadTableTag);\n if (head_table != NULL && head_table->length < 52) {\n return FONT_COMPRESSION_FAILURE();\n }\n\n return true;\n}\n\nbool ReadCollectionFont(Buffer* file, const uint8_t* data, size_t len,\n Font* font,\n std::map* all_tables) {\n if (!file->ReadU32(&font->flavor)) {\n return FONT_COMPRESSION_FAILURE();\n }\n if (!ReadTrueTypeFont(file, data, len, font)) {\n return FONT_COMPRESSION_FAILURE();\n }\n\n for (auto& entry : font->tables) {\n Font::Table& table = entry.second;\n\n if (all_tables->find(table.offset) == all_tables->end()) {\n (*all_tables)[table.offset] = font->FindTable(table.tag);\n } else {\n table.reuse_of = (*all_tables)[table.offset];\n }\n\n }\n return true;\n}\n\nbool ReadTrueTypeCollection(Buffer* file, const uint8_t* data, size_t len,\n FontCollection* font_collection) {\n uint32_t num_fonts;\n\n if (!file->ReadU32(&font_collection->header_version) ||\n !file->ReadU32(&num_fonts)) {\n return FONT_COMPRESSION_FAILURE();\n }\n\n std::vector offsets;\n for (size_t i = 0; i < num_fonts; i++) {\n uint32_t offset;\n if (!file->ReadU32(&offset)) {\n return FONT_COMPRESSION_FAILURE();\n }\n offsets.push_back(offset);\n }\n\n font_collection->fonts.resize(offsets.size());\n std::vector::iterator font_it = font_collection->fonts.begin();\n\n std::map all_tables;\n for (const auto offset : offsets) {\n file->set_offset(offset);\n Font& font = *font_it++;\n if (!ReadCollectionFont(file, data, len, &font, &all_tables)) {\n return FONT_COMPRESSION_FAILURE();\n }\n }\n\n return true;\n}\n\nbool ReadFont(const uint8_t* data, size_t len, Font* font) {\n Buffer file(data, len);\n\n if (!file.ReadU32(&font->flavor)) {\n return FONT_COMPRESSION_FAILURE();\n }\n\n if (font->flavor == kTtcFontFlavor) {\n return FONT_COMPRESSION_FAILURE();\n }\n return ReadTrueTypeFont(&file, data, len, font);\n}\n\nbool ReadFontCollection(const uint8_t* data, size_t len,\n FontCollection* font_collection) {\n Buffer file(data, len);\n\n if (!file.ReadU32(&font_collection->flavor)) {\n return FONT_COMPRESSION_FAILURE();\n }\n\n if (font_collection->flavor != kTtcFontFlavor) {\n font_collection->fonts.resize(1);\n Font& font = font_collection->fonts[0];\n font.flavor = font_collection->flavor;\n return ReadTrueTypeFont(&file, data, len, &font);\n }\n return ReadTrueTypeCollection(&file, data, len, font_collection);\n}\n\nsize_t FontFileSize(const Font& font) {\n size_t max_offset = 12ULL + 16ULL * font.num_tables;\n for (const auto& i : font.tables) {\n const Font::Table& table = i.second;\n size_t padding_size = (4 - (table.length & 3)) & 3;\n size_t end_offset = (padding_size + table.offset) + table.length;\n max_offset = std::max(max_offset, end_offset);\n }\n return max_offset;\n}\n\nsize_t FontCollectionFileSize(const FontCollection& font_collection) {\n size_t max_offset = 0;\n for (auto& font : font_collection.fonts) {\n \/\/ font file size actually just finds max offset\n max_offset = std::max(max_offset, FontFileSize(font));\n }\n return max_offset;\n}\n\nbool WriteFont(const Font& font, uint8_t* dst, size_t dst_size) {\n size_t offset = 0;\n return WriteFont(font, &offset, dst, dst_size);\n}\n\nbool WriteTableRecord(const Font::Table* table, size_t* offset, uint8_t* dst,\n size_t dst_size) {\n if (dst_size < *offset + kSfntEntrySize) {\n return FONT_COMPRESSION_FAILURE();\n }\n if (table->IsReused()) {\n table = table->reuse_of;\n }\n StoreU32(table->tag, offset, dst);\n StoreU32(table->checksum, offset, dst);\n StoreU32(table->offset, offset, dst);\n StoreU32(table->length, offset, dst);\n return true;\n}\n\nbool WriteTable(const Font::Table& table, size_t* offset, uint8_t* dst,\n size_t dst_size) {\n if (!WriteTableRecord(&table, offset, dst, dst_size)) {\n return false;\n }\n\n \/\/ Write the actual table data if it's the first time we've seen it\n if (!table.IsReused()) {\n if (table.offset + table.length < table.offset ||\n dst_size < table.offset + table.length) {\n return FONT_COMPRESSION_FAILURE();\n }\n memcpy(dst + table.offset, table.data, table.length);\n size_t padding_size = (4 - (table.length & 3)) & 3;\n if (table.offset + table.length + padding_size < padding_size ||\n dst_size < table.offset + table.length + padding_size) {\n return FONT_COMPRESSION_FAILURE();\n }\n memset(dst + table.offset + table.length, 0, padding_size);\n }\n return true;\n}\n\nbool WriteFont(const Font& font, size_t* offset, uint8_t* dst,\n size_t dst_size) {\n if (dst_size < 12ULL + 16ULL * font.num_tables) {\n return FONT_COMPRESSION_FAILURE();\n }\n StoreU32(font.flavor, offset, dst);\n Store16(font.num_tables, offset, dst);\n uint16_t max_pow2 = font.num_tables ? Log2Floor(font.num_tables) : 0;\n uint16_t search_range = max_pow2 ? 1 << (max_pow2 + 4) : 0;\n uint16_t range_shift = (font.num_tables << 4) - search_range;\n Store16(search_range, offset, dst);\n Store16(max_pow2, offset, dst);\n Store16(range_shift, offset, dst);\n\n for (const auto& i : font.tables) {\n if (!WriteTable(i.second, offset, dst, dst_size)) {\n return false;\n }\n }\n\n return true;\n}\n\nbool WriteFontCollection(const FontCollection& font_collection, uint8_t* dst,\n size_t dst_size) {\n size_t offset = 0;\n\n \/\/ It's simpler if this just a simple sfnt\n if (font_collection.flavor != kTtcFontFlavor) {\n return WriteFont(font_collection.fonts[0], &offset, dst, dst_size);\n }\n\n \/\/ Write TTC header\n StoreU32(kTtcFontFlavor, &offset, dst);\n StoreU32(font_collection.header_version, &offset, dst);\n StoreU32(font_collection.fonts.size(), &offset, dst);\n\n \/\/ Offset Table, zeroed for now\n size_t offset_table = offset; \/\/ where to write offsets later\n for (size_t i = 0; i < font_collection.fonts.size(); i++) {\n StoreU32(0, &offset, dst);\n }\n\n if (font_collection.header_version == 0x00020000) {\n StoreU32(0, &offset, dst); \/\/ ulDsigTag\n StoreU32(0, &offset, dst); \/\/ ulDsigLength\n StoreU32(0, &offset, dst); \/\/ ulDsigOffset\n }\n\n \/\/ Write fonts and their offsets.\n for (size_t i = 0; i < font_collection.fonts.size(); i++) {\n const auto& font = font_collection.fonts[i];\n StoreU32(offset, &offset_table, dst);\n if (!WriteFont(font, &offset, dst, dst_size)) {\n return false;\n }\n }\n\n return true;\n}\n\nint NumGlyphs(const Font& font) {\n const Font::Table* head_table = font.FindTable(kHeadTableTag);\n const Font::Table* loca_table = font.FindTable(kLocaTableTag);\n if (head_table == NULL || loca_table == NULL || head_table->length < 52) {\n return 0;\n }\n int index_fmt = IndexFormat(font);\n int loca_record_size = (index_fmt == 0 ? 2 : 4);\n if (loca_table->length < loca_record_size) {\n return 0;\n }\n return (loca_table->length \/ loca_record_size) - 1;\n}\n\nint IndexFormat(const Font& font) {\n const Font::Table* head_table = font.FindTable(kHeadTableTag);\n if (head_table == NULL) {\n return 0;\n }\n return head_table->data[51];\n}\n\nbool Font::Table::IsReused() const {\n return this->reuse_of != NULL;\n}\n\nbool GetGlyphData(const Font& font, int glyph_index,\n const uint8_t** glyph_data, size_t* glyph_size) {\n if (glyph_index < 0) {\n return FONT_COMPRESSION_FAILURE();\n }\n const Font::Table* head_table = font.FindTable(kHeadTableTag);\n const Font::Table* loca_table = font.FindTable(kLocaTableTag);\n const Font::Table* glyf_table = font.FindTable(kGlyfTableTag);\n if (head_table == NULL || loca_table == NULL || glyf_table == NULL ||\n head_table->length < 52) {\n return FONT_COMPRESSION_FAILURE();\n }\n\n int index_fmt = IndexFormat(font);\n\n Buffer loca_buf(loca_table->data, loca_table->length);\n if (index_fmt == 0) {\n uint16_t offset1, offset2;\n if (!loca_buf.Skip(2 * glyph_index) ||\n !loca_buf.ReadU16(&offset1) ||\n !loca_buf.ReadU16(&offset2) ||\n offset2 < offset1 ||\n 2 * offset2 > glyf_table->length) {\n return FONT_COMPRESSION_FAILURE();\n }\n *glyph_data = glyf_table->data + 2 * offset1;\n *glyph_size = 2 * (offset2 - offset1);\n } else {\n uint32_t offset1, offset2;\n if (!loca_buf.Skip(4 * glyph_index) ||\n !loca_buf.ReadU32(&offset1) ||\n !loca_buf.ReadU32(&offset2) ||\n offset2 < offset1 ||\n offset2 > glyf_table->length) {\n return FONT_COMPRESSION_FAILURE();\n }\n *glyph_data = glyf_table->data + offset1;\n *glyph_size = offset2 - offset1;\n }\n return true;\n}\n\nbool RemoveDigitalSignature(Font* font) {\n std::map::iterator it =\n font->tables.find(kDsigTableTag);\n if (it != font->tables.end()) {\n font->tables.erase(it);\n font->num_tables = font->tables.size();\n }\n return true;\n}\n\n} \/\/ namespace woff2\n<|endoftext|>"} {"text":"\/*\n * Copyright 2020 Tom van Dijk\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 \"fpj.hpp\"\n#include \"uintqueue.hpp\"\n\nnamespace pg {\n\nFPJSolver::FPJSolver(Oink *oink, Game *game) : Solver(oink, game)\n{\n}\n\nFPJSolver::~FPJSolver()\n{\n}\n\n\/**\n * Variation 1: greedy justification\n *\/\nvoid\nFPJSolver::runSeqGreedy()\n{\n \/**\n * Allocate and initialize data structures\n *\/\n\n int *strategy = new int[nodecount()]; \/\/ the current strategy\n bitset justified(nodecount()); \/\/ whether a vertex is justified\n bitset distraction(nodecount()); \/\/ whether a vertex is won by the opponent\n\n bitset parity(nodecount()); \/\/ optimization: precompute the parity of every vertex's priority\n for (int v=0; v= 2) logger << \"\\033[31;1mresetting\\033[m \" << label_vertex(from) << std::endl;\n#endif\n justified[from] = false;\n distraction[from] = false; \/\/ reset it\n Q.push(from);\n if (from < i) i = from; \/\/ afterwards, continue at lowest unjustified vertex\n }\n }\n }\n }\n#ifndef NDEBUG\n if (trace) logger << \"restarting after finding distractions of prio \" << priority(i-1) << std::endl;\n#endif\n iterations++;\n blockchanged = false;\n }\n\n if (i == nodecount()) break; \/\/ in case the last block didn't result in unjustifications\n\n \/\/ continue with the new block, update the current parity\n cur_parity = parity[i];\n }\n\n \/\/ if the current vertex is justified, we don't need to check it\n if (justified[i]) { i++; continue; }\n justified[i] = true;\n\n \/\/ compute one step winner of and update the strategy\n int onestep_winner, str = -1;\n if (owner(i) == 0) {\n \/\/ see if player Even can go to a vertex currently good for Even\n onestep_winner = 1;\n for (auto curedge = outs(i); *curedge != -1; curedge++) {\n int to = *curedge;\n if (disabled[to]) continue;\n const int winner_to = parity[to] ^ distraction[to];\n if (winner_to == 0) {\n \/\/ good for player Even\n onestep_winner = 0;\n \/\/ and set the strategy\n str = to;\n break;\n }\n }\n } else {\n \/\/ see if player Odd can go to a vertex currently good for Odd\n onestep_winner = 0;\n for (auto curedge = outs(i); *curedge != -1; curedge++) {\n int to = *curedge;\n if (disabled[to]) continue;\n const int winner_to = parity[to] ^ distraction[to];\n if (winner_to == 1) {\n \/\/ good for player Odd\n onestep_winner = 1;\n \/\/ and set the strategy\n str = to;\n break;\n }\n }\n }\n\n strategy[i] = str;\n\n \/\/ evaluation stays the same\n if (cur_parity != onestep_winner) {\n Q.push(i); \/\/ add to the Queue, because all justified predecessors are now invalid\n distraction[i] = true;\n blockchanged = true;\n#ifndef NDEBUG\n if (trace >= 2) {\n logger << \"\\033[38;5;165;1mjustified*\\033[m \" << label_vertex(i);\n if (strategy[i] != -1) logger << \" => \" << label_vertex(strategy[i]);\n logger << std::endl;\n }\n#endif\n } else {\n if (trace >= 2) {\n logger << \"\\033[38;5;165;1mjustified\\033[m \" << label_vertex(i);\n if (strategy[i] != -1) logger << \" => \" << label_vertex(strategy[i]);\n logger << std::endl;\n }\n }\n\n i++;\n }\n\n \/\/ done\n for (int v=0; vsolve(v, winner, winner == owner(v) ? strategy[v] : -1);\n }\n\n \/\/ free allocated data structures\n delete[] strategy;\n\n logger << \"solved with \" << iterations << \" iterations.\" << std::endl;\n}\n\n\nvoid\nFPJSolver::runSeq()\n{\n \/**\n * Allocate and initialize data structures\n *\/\n\n int *strategy = new int[nodecount()]; \/\/ the current strategy\n bitset justified(nodecount()); \/\/ whether a vertex is justified\n bitset distraction(nodecount()); \/\/ whether a vertex is won by the opponent\n\n bitset parity(nodecount()); \/\/ optimization: precompute the parity of every vertex's priority\n for (int v=0; v= 2) logger << \"\\033[31;1mresetting\\033[m \" << label_vertex(from) << std::endl;\n#endif\n justified[from] = false;\n distraction[from] = false; \/\/ reset it\n Q.push(from);\n if (from < i) i = from; \/\/ afterwards, continue at lowest unjustified vertex\n }\n }\n }\n }\n#ifndef NDEBUG\n if (trace) logger << \"restarting after finding distractions of prio \" << priority(i-1) << std::endl;\n#endif\n iterations++;\n blockchanged = false;\n if (i > blockstart) i = blockstart;\n } else {\n \/\/ We now know that the current strategy of all unjustified vertices of the block is justified\n for (int v=blockstart; v= 2) {\n logger << \"\\033[38;5;165;1mjustified\\033[m \" << label_vertex(v);\n if (strategy[v] != -1) logger << \" => \" << label_vertex(strategy[v]);\n logger << std::endl;\n }\n }\n }\n }\n\n if (i == nodecount()) break; \/\/ in case the last block didn't result in unjustifications\n\n \/\/ continue with the new block, update the current parity\n cur_parity = parity[i];\n blockstart = i;\n }\n\n \/\/ if the current vertex is justified, we don't need to check it\n if (justified[i]) { i++; continue; }\n\n \/\/ compute one step winner of and update the strategy\n int onestep_winner, str = -1;\n if (owner(i) == 0) {\n \/\/ see if player Even can go to a vertex currently good for Even\n onestep_winner = 1;\n for (auto curedge = outs(i); *curedge != -1; curedge++) {\n int to = *curedge;\n if (disabled[to]) continue;\n const int winner_to = parity[to] ^ distraction[to];\n if (winner_to == 0) {\n \/\/ good for player Even\n onestep_winner = 0;\n \/\/ and set the strategy\n str = to;\n break;\n }\n }\n } else {\n \/\/ see if player Odd can go to a vertex currently good for Odd\n onestep_winner = 0;\n for (auto curedge = outs(i); *curedge != -1; curedge++) {\n int to = *curedge;\n if (disabled[to]) continue;\n const int winner_to = parity[to] ^ distraction[to];\n if (winner_to == 1) {\n \/\/ good for player Odd\n onestep_winner = 1;\n \/\/ and set the strategy\n str = to;\n break;\n }\n }\n }\n\n strategy[i] = str;\n\n \/\/ evaluation stays the same\n if (cur_parity != onestep_winner) {\n Q.push(i); \/\/ add to the Queue, because all justified predecessors are now invalid\n distraction[i] = true;\n justified[i] = true;\n blockchanged = true;\n#ifndef NDEBUG\n if (trace >= 2) {\n logger << \"\\033[38;5;165;1mjustified*\\033[m \" << label_vertex(i);\n if (strategy[i] != -1) logger << \" => \" << label_vertex(strategy[i]);\n logger << std::endl;\n }\n#endif\n }\n\n i++;\n }\n\n \/\/ done\n for (int v=0; vsolve(v, winner, winner == owner(v) ? strategy[v] : -1);\n }\n\n \/\/ free allocated data structures\n delete[] strategy;\n\n logger << \"solved with \" << iterations << \" iterations.\" << std::endl;\n}\n\nvoid\nFPJSolver::run()\n{\n if (greedy) runSeqGreedy();\n else runSeq();\n}\n\n}\nSmall improvements to FPJ\/*\n * Copyright 2020 Tom van Dijk\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 \"fpj.hpp\"\n#include \"uintqueue.hpp\"\n\nnamespace pg {\n\nFPJSolver::FPJSolver(Oink *oink, Game *game) : Solver(oink, game)\n{\n}\n\nFPJSolver::~FPJSolver()\n{\n}\n\n\/**\n * Variation 1: greedy justification\n *\/\nvoid\nFPJSolver::runSeqGreedy()\n{\n \/**\n * Allocate and initialize data structures\n *\/\n\n int *strategy = new int[nodecount()]; \/\/ the current strategy\n bitset justified(nodecount()); \/\/ whether a vertex is justified\n bitset distraction(nodecount()); \/\/ whether a vertex is won by the opponent\n\n bitset parity(nodecount()); \/\/ optimization: precompute the parity of every vertex's priority\n for (int v=0; v= 2) logger << \"\\033[31;1mresetting\\033[m \" << label_vertex(from) << std::endl;\n#endif\n justified[from] = false;\n distraction[from] = false; \/\/ reset it\n Q.push(from);\n if (from < i) i = from; \/\/ afterwards, continue at lowest unjustified vertex\n }\n }\n }\n#ifndef NDEBUG\n if (trace) logger << \"restarting after finding distractions of prio \" << priority(i-1) << std::endl;\n#endif\n iterations++;\n }\n\n if (i == nodecount()) break; \/\/ in case the last block didn't result in unjustifications\n\n \/\/ continue with the new block, update the current parity\n cur_parity = parity[i];\n }\n\n \/\/ if the current vertex is justified, we don't need to check it\n if (justified[i]) { i++; continue; }\n justified[i] = true;\n\n \/\/ compute one step winner of and update the strategy\n int onestep_winner, str = -1;\n if (owner(i) == 0) {\n \/\/ see if player Even can go to a vertex currently good for Even\n onestep_winner = 1;\n for (auto curedge = outs(i); *curedge != -1; curedge++) {\n int to = *curedge;\n if (disabled[to]) continue;\n const int winner_to = parity[to] ^ distraction[to];\n if (winner_to == 0) {\n \/\/ good for player Even\n onestep_winner = 0;\n \/\/ and set the strategy\n str = to;\n break;\n }\n }\n } else {\n \/\/ see if player Odd can go to a vertex currently good for Odd\n onestep_winner = 0;\n for (auto curedge = outs(i); *curedge != -1; curedge++) {\n int to = *curedge;\n if (disabled[to]) continue;\n const int winner_to = parity[to] ^ distraction[to];\n if (winner_to == 1) {\n \/\/ good for player Odd\n onestep_winner = 1;\n \/\/ and set the strategy\n str = to;\n break;\n }\n }\n }\n\n strategy[i] = str;\n\n \/\/ evaluation stays the same\n if (cur_parity != onestep_winner) {\n Q.push(i); \/\/ add to Q\n#ifndef NDEBUG\n if (trace >= 2) {\n logger << \"\\033[38;5;165;1mjustified*\\033[m \" << label_vertex(i);\n if (strategy[i] != -1) logger << \" => \" << label_vertex(strategy[i]);\n logger << std::endl;\n }\n#endif\n } else {\n if (trace >= 2) {\n logger << \"\\033[38;5;165;1mjustified\\033[m \" << label_vertex(i);\n if (strategy[i] != -1) logger << \" => \" << label_vertex(strategy[i]);\n logger << std::endl;\n }\n }\n\n i++;\n }\n\n \/\/ done\n for (int v=0; vsolve(v, winner, winner == owner(v) ? strategy[v] : -1);\n }\n\n \/\/ free allocated data structures\n delete[] strategy;\n\n logger << \"solved with \" << iterations << \" iterations.\" << std::endl;\n}\n\n\nvoid\nFPJSolver::runSeq()\n{\n \/**\n * Allocate and initialize data structures\n *\/\n\n int *strategy = new int[nodecount()]; \/\/ the current strategy\n bitset justified(nodecount()); \/\/ whether a vertex is justified\n bitset distraction(nodecount()); \/\/ whether a vertex is won by the opponent\n\n bitset parity(nodecount()); \/\/ optimization: precompute the parity of every vertex's priority\n for (int v=0; v= 2) logger << \"\\033[31;1mresetting\\033[m \" << label_vertex(from) << std::endl;\n#endif\n justified[from] = false; \/\/ no longer justified\n distraction[from] = false; \/\/ reset it\n Q.push(from);\n if (from < i) i = from; \/\/ afterwards, continue at lowest unjustified vertex\n }\n }\n }\n }\n#ifndef NDEBUG\n if (trace) logger << \"restarting after finding distractions of prio \" << priority(i-1) << std::endl;\n#endif\n iterations++;\n if (i > blockstart) i = blockstart;\n } else {\n \/\/ We now know that the current strategy of all unjustified vertices of the block is justified\n for (int v=blockstart; v= 2) {\n logger << \"\\033[38;5;165;1mjustified\\033[m \" << label_vertex(v);\n if (strategy[v] != -1) logger << \" => \" << label_vertex(strategy[v]);\n logger << std::endl;\n }\n }\n }\n }\n\n if (i == nodecount()) break; \/\/ in case the last block didn't result in unjustifications\n\n \/\/ continue with the new block, update the current parity\n cur_parity = parity[i];\n blockstart = i;\n }\n\n \/\/ if the current vertex is justified, we don't need to check it\n if (justified[i]) {\n i++;\n continue;\n }\n\n \/\/ compute one step winner of and update the strategy\n int onestep_winner, str = -1;\n if (owner(i) == 0) {\n \/\/ see if player Even can go to a vertex currently good for Even\n onestep_winner = 1;\n for (auto curedge = outs(i); *curedge != -1; curedge++) {\n int to = *curedge;\n if (disabled[to]) continue;\n const int winner_to = parity[to] ^ distraction[to];\n if (winner_to == 0) {\n \/\/ good for player Even\n onestep_winner = 0;\n \/\/ and set the strategy\n str = to;\n break;\n }\n }\n } else {\n \/\/ see if player Odd can go to a vertex currently good for Odd\n onestep_winner = 0;\n for (auto curedge = outs(i); *curedge != -1; curedge++) {\n int to = *curedge;\n if (disabled[to]) continue;\n const int winner_to = parity[to] ^ distraction[to];\n if (winner_to == 1) {\n \/\/ good for player Odd\n onestep_winner = 1;\n \/\/ and set the strategy\n str = to;\n break;\n }\n }\n }\n\n strategy[i] = str;\n\n \/\/ evaluation stays the same\n if (cur_parity != onestep_winner) {\n Q.push(i); \/\/ add to the Queue, because all justified predecessors are now invalid\n#ifndef NDEBUG\n if (trace >= 2) {\n logger << \"\\033[38;5;165;1mjustified*\\033[m \" << label_vertex(i);\n if (strategy[i] != -1) logger << \" => \" << label_vertex(strategy[i]);\n logger << std::endl;\n }\n#endif\n }\n\n i++;\n }\n\n \/\/ done\n for (int v=0; vsolve(v, winner, winner == owner(v) ? strategy[v] : -1);\n }\n\n \/\/ free allocated data structures\n delete[] strategy;\n\n logger << \"solved with \" << iterations << \" iterations.\" << std::endl;\n}\n\nvoid\nFPJSolver::run()\n{\n if (greedy) runSeqGreedy();\n else runSeq();\n}\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2012 The Bitcoin developers\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 \n\n#include \n#include \n\n#include \"key.h\"\n\n\/\/ Generate a private key from just the secret parameter\nint EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)\n{\n int ok = 0;\n BN_CTX *ctx = NULL;\n EC_POINT *pub_key = NULL;\n\n if (!eckey) return 0;\n\n const EC_GROUP *group = EC_KEY_get0_group(eckey);\n\n if ((ctx = BN_CTX_new()) == NULL)\n goto err;\n\n pub_key = EC_POINT_new(group);\n\n if (pub_key == NULL)\n goto err;\n\n if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))\n goto err;\n\n EC_KEY_set_private_key(eckey,priv_key);\n EC_KEY_set_public_key(eckey,pub_key);\n\n ok = 1;\n\nerr:\n\n if (pub_key)\n EC_POINT_free(pub_key);\n if (ctx != NULL)\n BN_CTX_free(ctx);\n\n return(ok);\n}\n\n\/\/ Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields\n\/\/ recid selects which key is recovered\n\/\/ if check is nonzero, additional checks are performed\nint ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)\n{\n if (!eckey) return 0;\n\n int ret = 0;\n BN_CTX *ctx = NULL;\n\n BIGNUM *x = NULL;\n BIGNUM *e = NULL;\n BIGNUM *order = NULL;\n BIGNUM *sor = NULL;\n BIGNUM *eor = NULL;\n BIGNUM *field = NULL;\n EC_POINT *R = NULL;\n EC_POINT *O = NULL;\n EC_POINT *Q = NULL;\n BIGNUM *rr = NULL;\n BIGNUM *zero = NULL;\n int n = 0;\n int i = recid \/ 2;\n\n const EC_GROUP *group = EC_KEY_get0_group(eckey);\n if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }\n BN_CTX_start(ctx);\n order = BN_CTX_get(ctx);\n if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }\n x = BN_CTX_get(ctx);\n if (!BN_copy(x, order)) { ret=-1; goto err; }\n if (!BN_mul_word(x, i)) { ret=-1; goto err; }\n if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }\n field = BN_CTX_get(ctx);\n if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }\n if (BN_cmp(x, field) >= 0) { ret=0; goto err; }\n if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }\n if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }\n if (check)\n {\n if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }\n if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }\n if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }\n }\n if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }\n n = EC_GROUP_get_degree(group);\n e = BN_CTX_get(ctx);\n if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }\n if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));\n zero = BN_CTX_get(ctx);\n if (!BN_zero(zero)) { ret=-1; goto err; }\n if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }\n rr = BN_CTX_get(ctx);\n if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }\n sor = BN_CTX_get(ctx);\n if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }\n eor = BN_CTX_get(ctx);\n if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }\n if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }\n if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }\n\n ret = 1;\n\nerr:\n if (ctx) {\n BN_CTX_end(ctx);\n BN_CTX_free(ctx);\n }\n if (R != NULL) EC_POINT_free(R);\n if (O != NULL) EC_POINT_free(O);\n if (Q != NULL) EC_POINT_free(Q);\n return ret;\n}\n\nvoid CKey::SetCompressedPubKey()\n{\n EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);\n fCompressedPubKey = true;\n}\n\nvoid CKey::Reset()\n{\n fCompressedPubKey = false;\n pkey = EC_KEY_new_by_curve_name(NID_secp256k1);\n if (pkey == NULL)\n throw key_error(\"CKey::CKey() : EC_KEY_new_by_curve_name failed\");\n fSet = false;\n}\n\nCKey::CKey()\n{\n Reset();\n}\n\nCKey::CKey(const CKey& b)\n{\n pkey = EC_KEY_dup(b.pkey);\n if (pkey == NULL)\n throw key_error(\"CKey::CKey(const CKey&) : EC_KEY_dup failed\");\n fSet = b.fSet;\n}\n\nCKey& CKey::operator=(const CKey& b)\n{\n if (!EC_KEY_copy(pkey, b.pkey))\n throw key_error(\"CKey::operator=(const CKey&) : EC_KEY_copy failed\");\n fSet = b.fSet;\n return (*this);\n}\n\nCKey::~CKey()\n{\n EC_KEY_free(pkey);\n}\n\nbool CKey::IsNull() const\n{\n return !fSet;\n}\n\nbool CKey::IsCompressed() const\n{\n return fCompressedPubKey;\n}\n\nvoid CKey::MakeNewKey(bool fCompressed)\n{\n if (!EC_KEY_generate_key(pkey))\n throw key_error(\"CKey::MakeNewKey() : EC_KEY_generate_key failed\");\n if (fCompressed)\n SetCompressedPubKey();\n fSet = true;\n}\n\nbool CKey::SetPrivKey(const CPrivKey& vchPrivKey)\n{\n const unsigned char* pbegin = &vchPrivKey[0];\n if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))\n return false;\n fSet = true;\n return true;\n}\n\nbool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)\n{\n EC_KEY_free(pkey);\n pkey = EC_KEY_new_by_curve_name(NID_secp256k1);\n if (pkey == NULL)\n throw key_error(\"CKey::SetSecret() : EC_KEY_new_by_curve_name failed\");\n if (vchSecret.size() != 32)\n throw key_error(\"CKey::SetSecret() : secret must be 32 bytes\");\n BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());\n if (bn == NULL)\n throw key_error(\"CKey::SetSecret() : BN_bin2bn failed\");\n if (!EC_KEY_regenerate_key(pkey,bn))\n {\n BN_clear_free(bn);\n throw key_error(\"CKey::SetSecret() : EC_KEY_regenerate_key failed\");\n }\n BN_clear_free(bn);\n fSet = true;\n if (fCompressed || fCompressedPubKey)\n SetCompressedPubKey();\n return true;\n}\n\nCSecret CKey::GetSecret(bool &fCompressed) const\n{\n CSecret vchRet;\n vchRet.resize(32);\n const BIGNUM *bn = EC_KEY_get0_private_key(pkey);\n int nBytes = BN_num_bytes(bn);\n if (bn == NULL)\n throw key_error(\"CKey::GetSecret() : EC_KEY_get0_private_key failed\");\n int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);\n if (n != nBytes)\n throw key_error(\"CKey::GetSecret(): BN_bn2bin failed\");\n fCompressed = fCompressedPubKey;\n return vchRet;\n}\n\nCPrivKey CKey::GetPrivKey() const\n{\n int nSize = i2d_ECPrivateKey(pkey, NULL);\n if (!nSize)\n throw key_error(\"CKey::GetPrivKey() : i2d_ECPrivateKey failed\");\n CPrivKey vchPrivKey(nSize, 0);\n unsigned char* pbegin = &vchPrivKey[0];\n if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)\n throw key_error(\"CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size\");\n return vchPrivKey;\n}\n\nbool CKey::SetPubKey(const CPubKey& vchPubKey)\n{\n const unsigned char* pbegin = &vchPubKey.vchPubKey[0];\n if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))\n return false;\n fSet = true;\n if (vchPubKey.vchPubKey.size() == 33)\n SetCompressedPubKey();\n return true;\n}\n\nCPubKey CKey::GetPubKey() const\n{\n int nSize = i2o_ECPublicKey(pkey, NULL);\n if (!nSize)\n throw key_error(\"CKey::GetPubKey() : i2o_ECPublicKey failed\");\n std::vector vchPubKey(nSize, 0);\n unsigned char* pbegin = &vchPubKey[0];\n if (i2o_ECPublicKey(pkey, &pbegin) != nSize)\n throw key_error(\"CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size\");\n return CPubKey(vchPubKey);\n}\n\nbool CKey::Sign(uint256 hash, std::vector& vchSig)\n{\n unsigned int nSize = ECDSA_size(pkey);\n vchSig.resize(nSize); \/\/ Make sure it is big enough\n if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey))\n {\n vchSig.clear();\n return false;\n }\n vchSig.resize(nSize); \/\/ Shrink to fit actual size\n return true;\n}\n\n\/\/ create a compact signature (65 bytes), which allows reconstructing the used public key\n\/\/ The format is one header byte, followed by two times 32 bytes for the serialized r and s values.\n\/\/ The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,\n\/\/ 0x1D = second key with even y, 0x1E = second key with odd y\nbool CKey::SignCompact(uint256 hash, std::vector& vchSig)\n{\n bool fOk = false;\n ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);\n if (sig==NULL)\n return false;\n vchSig.clear();\n vchSig.resize(65,0);\n int nBitsR = BN_num_bits(sig->r);\n int nBitsS = BN_num_bits(sig->s);\n if (nBitsR <= 256 && nBitsS <= 256)\n {\n int nRecId = -1;\n for (int i=0; i<4; i++)\n {\n CKey keyRec;\n keyRec.fSet = true;\n if (fCompressedPubKey)\n keyRec.SetCompressedPubKey();\n if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)\n if (keyRec.GetPubKey() == this->GetPubKey())\n {\n nRecId = i;\n break;\n }\n }\n\n if (nRecId == -1)\n throw key_error(\"CKey::SignCompact() : unable to construct recoverable key\");\n\n vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);\n BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)\/8]);\n BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)\/8]);\n fOk = true;\n }\n ECDSA_SIG_free(sig);\n return fOk;\n}\n\n\/\/ reconstruct public key from a compact signature\n\/\/ This is only slightly more CPU intensive than just verifying it.\n\/\/ If this function succeeds, the recovered public key is guaranteed to be valid\n\/\/ (the signature is a valid signature of the given data for that key)\nbool CKey::SetCompactSignature(uint256 hash, const std::vector& vchSig)\n{\n if (vchSig.size() != 65)\n return false;\n int nV = vchSig[0];\n if (nV<27 || nV>=35)\n return false;\n ECDSA_SIG *sig = ECDSA_SIG_new();\n BN_bin2bn(&vchSig[1],32,sig->r);\n BN_bin2bn(&vchSig[33],32,sig->s);\n\n EC_KEY_free(pkey);\n pkey = EC_KEY_new_by_curve_name(NID_secp256k1);\n if (nV >= 31)\n {\n SetCompressedPubKey();\n nV -= 4;\n }\n if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)\n {\n fSet = true;\n ECDSA_SIG_free(sig);\n return true;\n }\n return false;\n}\n\nbool CKey::Verify(uint256 hash, const std::vector& vchSig)\n{\n \/\/ -1 = error, 0 = bad sig, 1 = good\n if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)\n return false;\n\n return true;\n}\n\nbool CKey::VerifyCompact(uint256 hash, const std::vector& vchSig)\n{\n CKey key;\n if (!key.SetCompactSignature(hash, vchSig))\n return false;\n if (GetPubKey() != key.GetPubKey())\n return false;\n\n return true;\n}\n\nbool CKey::IsValid()\n{\n if (!fSet)\n return false;\n\n bool fCompr;\n CSecret secret = GetSecret(fCompr);\n CKey key2;\n key2.SetSecret(secret, fCompr);\n return GetPubKey() == key2.GetPubKey();\n}\nfix a memory leak in key.cpp\/\/ Copyright (c) 2009-2012 The Bitcoin developers\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 \n\n#include \n#include \n\n#include \"key.h\"\n\n\/\/ Generate a private key from just the secret parameter\nint EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)\n{\n int ok = 0;\n BN_CTX *ctx = NULL;\n EC_POINT *pub_key = NULL;\n\n if (!eckey) return 0;\n\n const EC_GROUP *group = EC_KEY_get0_group(eckey);\n\n if ((ctx = BN_CTX_new()) == NULL)\n goto err;\n\n pub_key = EC_POINT_new(group);\n\n if (pub_key == NULL)\n goto err;\n\n if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))\n goto err;\n\n EC_KEY_set_private_key(eckey,priv_key);\n EC_KEY_set_public_key(eckey,pub_key);\n\n ok = 1;\n\nerr:\n\n if (pub_key)\n EC_POINT_free(pub_key);\n if (ctx != NULL)\n BN_CTX_free(ctx);\n\n return(ok);\n}\n\n\/\/ Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields\n\/\/ recid selects which key is recovered\n\/\/ if check is nonzero, additional checks are performed\nint ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)\n{\n if (!eckey) return 0;\n\n int ret = 0;\n BN_CTX *ctx = NULL;\n\n BIGNUM *x = NULL;\n BIGNUM *e = NULL;\n BIGNUM *order = NULL;\n BIGNUM *sor = NULL;\n BIGNUM *eor = NULL;\n BIGNUM *field = NULL;\n EC_POINT *R = NULL;\n EC_POINT *O = NULL;\n EC_POINT *Q = NULL;\n BIGNUM *rr = NULL;\n BIGNUM *zero = NULL;\n int n = 0;\n int i = recid \/ 2;\n\n const EC_GROUP *group = EC_KEY_get0_group(eckey);\n if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }\n BN_CTX_start(ctx);\n order = BN_CTX_get(ctx);\n if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }\n x = BN_CTX_get(ctx);\n if (!BN_copy(x, order)) { ret=-1; goto err; }\n if (!BN_mul_word(x, i)) { ret=-1; goto err; }\n if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }\n field = BN_CTX_get(ctx);\n if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }\n if (BN_cmp(x, field) >= 0) { ret=0; goto err; }\n if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }\n if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }\n if (check)\n {\n if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }\n if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }\n if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }\n }\n if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }\n n = EC_GROUP_get_degree(group);\n e = BN_CTX_get(ctx);\n if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }\n if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));\n zero = BN_CTX_get(ctx);\n if (!BN_zero(zero)) { ret=-1; goto err; }\n if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }\n rr = BN_CTX_get(ctx);\n if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }\n sor = BN_CTX_get(ctx);\n if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }\n eor = BN_CTX_get(ctx);\n if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }\n if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }\n if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }\n\n ret = 1;\n\nerr:\n if (ctx) {\n BN_CTX_end(ctx);\n BN_CTX_free(ctx);\n }\n if (R != NULL) EC_POINT_free(R);\n if (O != NULL) EC_POINT_free(O);\n if (Q != NULL) EC_POINT_free(Q);\n return ret;\n}\n\nvoid CKey::SetCompressedPubKey()\n{\n EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);\n fCompressedPubKey = true;\n}\n\nvoid CKey::Reset()\n{\n fCompressedPubKey = false;\n if (pkey != NULL)\n EC_KEY_free(pkey);\n pkey = EC_KEY_new_by_curve_name(NID_secp256k1);\n if (pkey == NULL)\n throw key_error(\"CKey::CKey() : EC_KEY_new_by_curve_name failed\");\n fSet = false;\n}\n\nCKey::CKey()\n{\n pkey = NULL;\n Reset();\n}\n\nCKey::CKey(const CKey& b)\n{\n pkey = EC_KEY_dup(b.pkey);\n if (pkey == NULL)\n throw key_error(\"CKey::CKey(const CKey&) : EC_KEY_dup failed\");\n fSet = b.fSet;\n}\n\nCKey& CKey::operator=(const CKey& b)\n{\n if (!EC_KEY_copy(pkey, b.pkey))\n throw key_error(\"CKey::operator=(const CKey&) : EC_KEY_copy failed\");\n fSet = b.fSet;\n return (*this);\n}\n\nCKey::~CKey()\n{\n EC_KEY_free(pkey);\n}\n\nbool CKey::IsNull() const\n{\n return !fSet;\n}\n\nbool CKey::IsCompressed() const\n{\n return fCompressedPubKey;\n}\n\nvoid CKey::MakeNewKey(bool fCompressed)\n{\n if (!EC_KEY_generate_key(pkey))\n throw key_error(\"CKey::MakeNewKey() : EC_KEY_generate_key failed\");\n if (fCompressed)\n SetCompressedPubKey();\n fSet = true;\n}\n\nbool CKey::SetPrivKey(const CPrivKey& vchPrivKey)\n{\n const unsigned char* pbegin = &vchPrivKey[0];\n if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))\n return false;\n fSet = true;\n return true;\n}\n\nbool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)\n{\n EC_KEY_free(pkey);\n pkey = EC_KEY_new_by_curve_name(NID_secp256k1);\n if (pkey == NULL)\n throw key_error(\"CKey::SetSecret() : EC_KEY_new_by_curve_name failed\");\n if (vchSecret.size() != 32)\n throw key_error(\"CKey::SetSecret() : secret must be 32 bytes\");\n BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());\n if (bn == NULL)\n throw key_error(\"CKey::SetSecret() : BN_bin2bn failed\");\n if (!EC_KEY_regenerate_key(pkey,bn))\n {\n BN_clear_free(bn);\n throw key_error(\"CKey::SetSecret() : EC_KEY_regenerate_key failed\");\n }\n BN_clear_free(bn);\n fSet = true;\n if (fCompressed || fCompressedPubKey)\n SetCompressedPubKey();\n return true;\n}\n\nCSecret CKey::GetSecret(bool &fCompressed) const\n{\n CSecret vchRet;\n vchRet.resize(32);\n const BIGNUM *bn = EC_KEY_get0_private_key(pkey);\n int nBytes = BN_num_bytes(bn);\n if (bn == NULL)\n throw key_error(\"CKey::GetSecret() : EC_KEY_get0_private_key failed\");\n int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);\n if (n != nBytes)\n throw key_error(\"CKey::GetSecret(): BN_bn2bin failed\");\n fCompressed = fCompressedPubKey;\n return vchRet;\n}\n\nCPrivKey CKey::GetPrivKey() const\n{\n int nSize = i2d_ECPrivateKey(pkey, NULL);\n if (!nSize)\n throw key_error(\"CKey::GetPrivKey() : i2d_ECPrivateKey failed\");\n CPrivKey vchPrivKey(nSize, 0);\n unsigned char* pbegin = &vchPrivKey[0];\n if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)\n throw key_error(\"CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size\");\n return vchPrivKey;\n}\n\nbool CKey::SetPubKey(const CPubKey& vchPubKey)\n{\n const unsigned char* pbegin = &vchPubKey.vchPubKey[0];\n if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))\n return false;\n fSet = true;\n if (vchPubKey.vchPubKey.size() == 33)\n SetCompressedPubKey();\n return true;\n}\n\nCPubKey CKey::GetPubKey() const\n{\n int nSize = i2o_ECPublicKey(pkey, NULL);\n if (!nSize)\n throw key_error(\"CKey::GetPubKey() : i2o_ECPublicKey failed\");\n std::vector vchPubKey(nSize, 0);\n unsigned char* pbegin = &vchPubKey[0];\n if (i2o_ECPublicKey(pkey, &pbegin) != nSize)\n throw key_error(\"CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size\");\n return CPubKey(vchPubKey);\n}\n\nbool CKey::Sign(uint256 hash, std::vector& vchSig)\n{\n unsigned int nSize = ECDSA_size(pkey);\n vchSig.resize(nSize); \/\/ Make sure it is big enough\n if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey))\n {\n vchSig.clear();\n return false;\n }\n vchSig.resize(nSize); \/\/ Shrink to fit actual size\n return true;\n}\n\n\/\/ create a compact signature (65 bytes), which allows reconstructing the used public key\n\/\/ The format is one header byte, followed by two times 32 bytes for the serialized r and s values.\n\/\/ The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,\n\/\/ 0x1D = second key with even y, 0x1E = second key with odd y\nbool CKey::SignCompact(uint256 hash, std::vector& vchSig)\n{\n bool fOk = false;\n ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);\n if (sig==NULL)\n return false;\n vchSig.clear();\n vchSig.resize(65,0);\n int nBitsR = BN_num_bits(sig->r);\n int nBitsS = BN_num_bits(sig->s);\n if (nBitsR <= 256 && nBitsS <= 256)\n {\n int nRecId = -1;\n for (int i=0; i<4; i++)\n {\n CKey keyRec;\n keyRec.fSet = true;\n if (fCompressedPubKey)\n keyRec.SetCompressedPubKey();\n if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)\n if (keyRec.GetPubKey() == this->GetPubKey())\n {\n nRecId = i;\n break;\n }\n }\n\n if (nRecId == -1)\n throw key_error(\"CKey::SignCompact() : unable to construct recoverable key\");\n\n vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);\n BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)\/8]);\n BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)\/8]);\n fOk = true;\n }\n ECDSA_SIG_free(sig);\n return fOk;\n}\n\n\/\/ reconstruct public key from a compact signature\n\/\/ This is only slightly more CPU intensive than just verifying it.\n\/\/ If this function succeeds, the recovered public key is guaranteed to be valid\n\/\/ (the signature is a valid signature of the given data for that key)\nbool CKey::SetCompactSignature(uint256 hash, const std::vector& vchSig)\n{\n if (vchSig.size() != 65)\n return false;\n int nV = vchSig[0];\n if (nV<27 || nV>=35)\n return false;\n ECDSA_SIG *sig = ECDSA_SIG_new();\n BN_bin2bn(&vchSig[1],32,sig->r);\n BN_bin2bn(&vchSig[33],32,sig->s);\n\n EC_KEY_free(pkey);\n pkey = EC_KEY_new_by_curve_name(NID_secp256k1);\n if (nV >= 31)\n {\n SetCompressedPubKey();\n nV -= 4;\n }\n if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)\n {\n fSet = true;\n ECDSA_SIG_free(sig);\n return true;\n }\n return false;\n}\n\nbool CKey::Verify(uint256 hash, const std::vector& vchSig)\n{\n \/\/ -1 = error, 0 = bad sig, 1 = good\n if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)\n return false;\n\n return true;\n}\n\nbool CKey::VerifyCompact(uint256 hash, const std::vector& vchSig)\n{\n CKey key;\n if (!key.SetCompactSignature(hash, vchSig))\n return false;\n if (GetPubKey() != key.GetPubKey())\n return false;\n\n return true;\n}\n\nbool CKey::IsValid()\n{\n if (!fSet)\n return false;\n\n bool fCompr;\n CSecret secret = GetSecret(fCompr);\n CKey key2;\n key2.SetSecret(secret, fCompr);\n return GetPubKey() == key2.GetPubKey();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2014 The Bitcoin 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 \"key.h\"\n\n#include \"crypto\/hmac_sha512.h\"\n#include \"crypto\/rfc6979_hmac_sha256.h\"\n#include \"eccryptoverify.h\"\n#include \"pubkey.h\"\n#include \"random.h\"\n\n#include \n#include \"ecwrapper.h\"\n\n\/\/! anonymous namespace\nnamespace {\n\nclass CSecp256k1Init {\npublic:\n CSecp256k1Init() {\n secp256k1_start(SECP256K1_START_SIGN);\n }\n ~CSecp256k1Init() {\n secp256k1_stop();\n }\n};\nstatic CSecp256k1Init instance_of_csecp256k1;\n\n} \/\/ anon namespace\n\nbool CKey::Check(const unsigned char *vch) {\n return eccrypto::Check(vch);\n}\n\nvoid CKey::MakeNewKey(bool fCompressedIn) {\n do {\n GetRandBytes(vch, sizeof(vch));\n } while (!Check(vch));\n fValid = true;\n fCompressed = fCompressedIn;\n}\n\nbool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) {\n if (!secp256k1_ec_privkey_import((unsigned char*)begin(), &privkey[0], privkey.size()))\n return false;\n fCompressed = fCompressedIn;\n fValid = true;\n return true;\n}\n\nCPrivKey CKey::GetPrivKey() const {\n assert(fValid);\n CPrivKey privkey;\n int privkeylen, ret;\n privkey.resize(279);\n privkeylen = 279;\n ret = secp256k1_ec_privkey_export(begin(), (unsigned char*)&privkey[0], &privkeylen, fCompressed);\n assert(ret);\n privkey.resize(privkeylen);\n return privkey;\n}\n\nCPubKey CKey::GetPubKey() const {\n assert(fValid);\n CPubKey result;\n int clen = 65;\n int ret = secp256k1_ec_pubkey_create((unsigned char*)result.begin(), &clen, begin(), fCompressed);\n assert((int)result.size() == clen);\n assert(ret);\n assert(result.IsValid());\n return result;\n}\n\nbool CKey::Sign(const uint256 &hash, std::vector& vchSig, uint32_t test_case) const {\n if (!fValid)\n return false;\n vchSig.resize(72);\n RFC6979_HMAC_SHA256 prng(begin(), 32, (unsigned char*)&hash, 32);\n do {\n uint256 nonce;\n prng.Generate((unsigned char*)&nonce, 32);\n nonce += test_case;\n int nSigLen = 72;\n int ret = secp256k1_ecdsa_sign((const unsigned char*)&hash, 32, (unsigned char*)&vchSig[0], &nSigLen, begin(), (unsigned char*)&nonce);\n vchSig.resize(nSigLen);\n nonce = 0;\n if (ret)\n return true;\n } while(true);\n}\n\nbool CKey::SignCompact(const uint256 &hash, std::vector& vchSig) const {\n if (!fValid)\n return false;\n vchSig.resize(65);\n int rec = -1;\n RFC6979_HMAC_SHA256 prng(begin(), 32, (unsigned char*)&hash, 32);\n do {\n uint256 nonce;\n prng.Generate((unsigned char*)&nonce, 32);\n int ret = secp256k1_ecdsa_sign_compact((const unsigned char*)&hash, 32, &vchSig[1], begin(), (unsigned char*)&nonce, &rec);\n nonce = 0;\n if (ret)\n break;\n } while(true);\n assert(rec != -1);\n vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);\n return true;\n}\n\nbool CKey::Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck=false) {\n if (!secp256k1_ec_privkey_import((unsigned char*)begin(), &privkey[0], privkey.size()))\n return false;\n fCompressed = vchPubKey.IsCompressed();\n fValid = true;\n\n if (fSkipCheck)\n return true;\n\n if (GetPubKey() != vchPubKey)\n return false;\n\n return true;\n}\n\nbool CKey::Derive(CKey& keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const {\n assert(IsValid());\n assert(IsCompressed());\n unsigned char out[64];\n LockObject(out);\n if ((nChild >> 31) == 0) {\n CPubKey pubkey = GetPubKey();\n assert(pubkey.begin() + 33 == pubkey.end());\n BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, out);\n } else {\n assert(begin() + 32 == end());\n BIP32Hash(cc, nChild, 0, begin(), out);\n }\n memcpy(ccChild, out+32, 32);\n memcpy((unsigned char*)keyChild.begin(), begin(), 32);\n bool ret = secp256k1_ec_privkey_tweak_add((unsigned char*)keyChild.begin(), out);\n UnlockObject(out);\n keyChild.fCompressed = true;\n keyChild.fValid = ret;\n return ret;\n}\n\nbool CExtKey::Derive(CExtKey &out, unsigned int nChild) const {\n out.nDepth = nDepth + 1;\n CKeyID id = key.GetPubKey().GetID();\n memcpy(&out.vchFingerprint[0], &id, 4);\n out.nChild = nChild;\n return key.Derive(out.key, out.vchChainCode, nChild, vchChainCode);\n}\n\nvoid CExtKey::SetMaster(const unsigned char *seed, unsigned int nSeedLen) {\n static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};\n unsigned char out[64];\n LockObject(out);\n CHMAC_SHA512(hashkey, sizeof(hashkey)).Write(seed, nSeedLen).Finalize(out);\n key.Set(&out[0], &out[32], true);\n memcpy(vchChainCode, &out[32], 32);\n UnlockObject(out);\n nDepth = 0;\n nChild = 0;\n memset(vchFingerprint, 0, sizeof(vchFingerprint));\n}\n\nCExtPubKey CExtKey::Neuter() const {\n CExtPubKey ret;\n ret.nDepth = nDepth;\n memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4);\n ret.nChild = nChild;\n ret.pubkey = key.GetPubKey();\n memcpy(&ret.vchChainCode[0], &vchChainCode[0], 32);\n return ret;\n}\n\nvoid CExtKey::Encode(unsigned char code[74]) const {\n code[0] = nDepth;\n memcpy(code+1, vchFingerprint, 4);\n code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;\n code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;\n memcpy(code+9, vchChainCode, 32);\n code[41] = 0;\n assert(key.size() == 32);\n memcpy(code+42, key.begin(), 32);\n}\n\nvoid CExtKey::Decode(const unsigned char code[74]) {\n nDepth = code[0];\n memcpy(vchFingerprint, code+1, 4);\n nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];\n memcpy(vchChainCode, code+9, 32);\n key.Set(code+42, code+74, true);\n}\n\nbool ECC_InitSanityCheck() {\n return CECKey::SanityCheck();\n}\nResize after succesful result\/\/ Copyright (c) 2009-2014 The Bitcoin 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 \"key.h\"\n\n#include \"crypto\/hmac_sha512.h\"\n#include \"crypto\/rfc6979_hmac_sha256.h\"\n#include \"eccryptoverify.h\"\n#include \"pubkey.h\"\n#include \"random.h\"\n\n#include \n#include \"ecwrapper.h\"\n\n\/\/! anonymous namespace\nnamespace {\n\nclass CSecp256k1Init {\npublic:\n CSecp256k1Init() {\n secp256k1_start(SECP256K1_START_SIGN);\n }\n ~CSecp256k1Init() {\n secp256k1_stop();\n }\n};\nstatic CSecp256k1Init instance_of_csecp256k1;\n\n} \/\/ anon namespace\n\nbool CKey::Check(const unsigned char *vch) {\n return eccrypto::Check(vch);\n}\n\nvoid CKey::MakeNewKey(bool fCompressedIn) {\n do {\n GetRandBytes(vch, sizeof(vch));\n } while (!Check(vch));\n fValid = true;\n fCompressed = fCompressedIn;\n}\n\nbool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) {\n if (!secp256k1_ec_privkey_import((unsigned char*)begin(), &privkey[0], privkey.size()))\n return false;\n fCompressed = fCompressedIn;\n fValid = true;\n return true;\n}\n\nCPrivKey CKey::GetPrivKey() const {\n assert(fValid);\n CPrivKey privkey;\n int privkeylen, ret;\n privkey.resize(279);\n privkeylen = 279;\n ret = secp256k1_ec_privkey_export(begin(), (unsigned char*)&privkey[0], &privkeylen, fCompressed);\n assert(ret);\n privkey.resize(privkeylen);\n return privkey;\n}\n\nCPubKey CKey::GetPubKey() const {\n assert(fValid);\n CPubKey result;\n int clen = 65;\n int ret = secp256k1_ec_pubkey_create((unsigned char*)result.begin(), &clen, begin(), fCompressed);\n assert((int)result.size() == clen);\n assert(ret);\n assert(result.IsValid());\n return result;\n}\n\nbool CKey::Sign(const uint256 &hash, std::vector& vchSig, uint32_t test_case) const {\n if (!fValid)\n return false;\n vchSig.resize(72);\n RFC6979_HMAC_SHA256 prng(begin(), 32, (unsigned char*)&hash, 32);\n do {\n uint256 nonce;\n prng.Generate((unsigned char*)&nonce, 32);\n nonce += test_case;\n int nSigLen = 72;\n int ret = secp256k1_ecdsa_sign((const unsigned char*)&hash, 32, (unsigned char*)&vchSig[0], &nSigLen, begin(), (unsigned char*)&nonce);\n nonce = 0;\n if (ret) {\n vchSig.resize(nSigLen);\n return true;\n }\n } while(true);\n}\n\nbool CKey::SignCompact(const uint256 &hash, std::vector& vchSig) const {\n if (!fValid)\n return false;\n vchSig.resize(65);\n int rec = -1;\n RFC6979_HMAC_SHA256 prng(begin(), 32, (unsigned char*)&hash, 32);\n do {\n uint256 nonce;\n prng.Generate((unsigned char*)&nonce, 32);\n int ret = secp256k1_ecdsa_sign_compact((const unsigned char*)&hash, 32, &vchSig[1], begin(), (unsigned char*)&nonce, &rec);\n nonce = 0;\n if (ret)\n break;\n } while(true);\n assert(rec != -1);\n vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);\n return true;\n}\n\nbool CKey::Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck=false) {\n if (!secp256k1_ec_privkey_import((unsigned char*)begin(), &privkey[0], privkey.size()))\n return false;\n fCompressed = vchPubKey.IsCompressed();\n fValid = true;\n\n if (fSkipCheck)\n return true;\n\n if (GetPubKey() != vchPubKey)\n return false;\n\n return true;\n}\n\nbool CKey::Derive(CKey& keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const {\n assert(IsValid());\n assert(IsCompressed());\n unsigned char out[64];\n LockObject(out);\n if ((nChild >> 31) == 0) {\n CPubKey pubkey = GetPubKey();\n assert(pubkey.begin() + 33 == pubkey.end());\n BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, out);\n } else {\n assert(begin() + 32 == end());\n BIP32Hash(cc, nChild, 0, begin(), out);\n }\n memcpy(ccChild, out+32, 32);\n memcpy((unsigned char*)keyChild.begin(), begin(), 32);\n bool ret = secp256k1_ec_privkey_tweak_add((unsigned char*)keyChild.begin(), out);\n UnlockObject(out);\n keyChild.fCompressed = true;\n keyChild.fValid = ret;\n return ret;\n}\n\nbool CExtKey::Derive(CExtKey &out, unsigned int nChild) const {\n out.nDepth = nDepth + 1;\n CKeyID id = key.GetPubKey().GetID();\n memcpy(&out.vchFingerprint[0], &id, 4);\n out.nChild = nChild;\n return key.Derive(out.key, out.vchChainCode, nChild, vchChainCode);\n}\n\nvoid CExtKey::SetMaster(const unsigned char *seed, unsigned int nSeedLen) {\n static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};\n unsigned char out[64];\n LockObject(out);\n CHMAC_SHA512(hashkey, sizeof(hashkey)).Write(seed, nSeedLen).Finalize(out);\n key.Set(&out[0], &out[32], true);\n memcpy(vchChainCode, &out[32], 32);\n UnlockObject(out);\n nDepth = 0;\n nChild = 0;\n memset(vchFingerprint, 0, sizeof(vchFingerprint));\n}\n\nCExtPubKey CExtKey::Neuter() const {\n CExtPubKey ret;\n ret.nDepth = nDepth;\n memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4);\n ret.nChild = nChild;\n ret.pubkey = key.GetPubKey();\n memcpy(&ret.vchChainCode[0], &vchChainCode[0], 32);\n return ret;\n}\n\nvoid CExtKey::Encode(unsigned char code[74]) const {\n code[0] = nDepth;\n memcpy(code+1, vchFingerprint, 4);\n code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;\n code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;\n memcpy(code+9, vchChainCode, 32);\n code[41] = 0;\n assert(key.size() == 32);\n memcpy(code+42, key.begin(), 32);\n}\n\nvoid CExtKey::Decode(const unsigned char code[74]) {\n nDepth = code[0];\n memcpy(vchFingerprint, code+1, 4);\n nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];\n memcpy(vchChainCode, code+9, 32);\n key.Set(code+42, code+74, true);\n}\n\nbool ECC_InitSanityCheck() {\n return CECKey::SanityCheck();\n}\n<|endoftext|>"} {"text":"#include \"eval.hh\"\n#include \"live.hh\"\n#include \"utils.hh\"\n#include \n\nstruct passed_data_t {\n term_t *const program;\n const std::string definition;\n std::vector frequencies;\n passed_data_t(term_t *const program, const std::string &definition)\n : program(program)\n , definition(definition) {\n }\n};\n\nstatic double note_to_freq(char note, int octave, int accidental_offset) {\n const std::map semitone_offset = {\n { 'C', -9 },\n { 'D', -7 },\n { 'E', -5 },\n { 'F', -4 },\n { 'G', -2 },\n { 'A', 0 },\n { 'B', 2 }\n };\n int octave_diff = octave - 4, semitone_diff = semitone_offset.at(note)\n + accidental_offset;\n return 440. * pow(2., octave_diff) * pow(2., semitone_diff \/ 12.);\n}\n\nstatic void audio_callback(void *userdata, uint8_t *stream, int len) {\n passed_data_t *passed_data = (passed_data_t*)userdata;\n static uint64_t c = 0;\n float *stream_ptr = (float*)stream;\n for (int i = 0; i < 4096; ++i) {\n double t = (double)(c++) * 1. \/ 48000.;\n *stream_ptr = 0;\n for (double f : passed_data->frequencies) {\n printf(\"f=%f\\n\", f);\n float value = (float)evaluate_definition(passed_data->program\n , passed_data->definition, f, t);\n *stream_ptr += 0.2f * value;\n }\n ++stream_ptr;\n }\n}\n\nvoid live(term_t *const program, const std::string &definition) {\n if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO) != 0)\n die(\"Failed to initialize SDL\");\n\n int window_width = 600, window_height = (3. \/ 4.) * (double)window_width;\n SDL_Window *window = SDL_CreateWindow(\"Sythin live\", SDL_WINDOWPOS_CENTERED\n , SDL_WINDOWPOS_CENTERED, window_width, window_height, 0);\n if (!window)\n die(\"failed to create window\");\n\n SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0);\n SDL_SetRenderDrawColor(renderer, 19, 19, 19, 255);\n\n passed_data_t passed_data(program, definition);\n\n SDL_AudioSpec want, have;\n SDL_memset(&want, 0, sizeof(want));\n want.freq = 48000;\n want.format = AUDIO_F32;\n want.channels = 1;\n want.samples = 4096;\n want.callback = audio_callback;\n want.userdata = (void*)&passed_data;\n\n SDL_AudioDeviceID dev = SDL_OpenAudioDevice(nullptr, 0, &want, &have\n , SDL_AUDIO_ALLOW_ANY_CHANGE);\n if (dev == 0)\n die(\"failed to open audio device: %s\", SDL_GetError());\n\n SDL_PauseAudioDevice(dev, 0);\n\n std::map key_frequencies = {\n { SDLK_z, note_to_freq('A', 4, 0) },\n { SDLK_x, note_to_freq('A', 4, 1) },\n { SDLK_c, note_to_freq('B', 4, 0) },\n { SDLK_v, note_to_freq('C', 5, 0) }\n };\n\n bool quit = false;\n while (!quit) {\n passed_data.frequencies.clear();\n\n SDL_Event event;\n while (SDL_PollEvent(&event))\n if (event.type == SDL_QUIT\n || (event.type == SDL_KEYUP && event.key.keysym.sym == SDLK_ESCAPE))\n quit = true;\n else if (event.type == SDL_KEYDOWN)\n if (key_frequencies.count(event.key.keysym.sym)) {\n printf(\"set %f\\n\", key_frequencies[event.key.keysym.sym]);\n passed_data.frequencies.push_back(key_frequencies[event.key.keysym.sym]);\n }\n\n SDL_RenderClear(renderer);\n SDL_RenderPresent(renderer);\n }\n\n SDL_DestroyRenderer(renderer);\n SDL_DestroyWindow(window);\n SDL_CloseAudioDevice(dev);\n SDL_Quit();\n}\n\nAdd playback#include \"eval.hh\"\n#include \"live.hh\"\n#include \"utils.hh\"\n#include \n\nstruct passed_data_t {\n term_t *const program;\n const std::string definition;\n std::map frequencies;\n passed_data_t(term_t *const program, const std::string &definition)\n : program(program)\n , definition(definition) {\n }\n};\n\nstatic double note_to_freq(char note, int octave, int accidental_offset) {\n const std::map semitone_offset = {\n { 'C', -9 },\n { 'D', -7 },\n { 'E', -5 },\n { 'F', -4 },\n { 'G', -2 },\n { 'A', 0 },\n { 'B', 2 }\n };\n int octave_diff = octave - 4, semitone_diff = semitone_offset.at(note)\n + accidental_offset;\n return 440. * pow(2., octave_diff) * pow(2., semitone_diff \/ 12.);\n}\n\nstatic void audio_callback(void *userdata, uint8_t *stream, int len) {\n passed_data_t *passed_data = (passed_data_t*)userdata;\n static uint64_t c = 0;\n float *stream_ptr = (float*)stream;\n for (int i = 0; i < 4096; ++i) {\n double t = (double)(c++) * 1. \/ 48000.;\n *stream_ptr = 0;\n for (const std::pair freq_pair : passed_data->frequencies) {\n if (freq_pair.second) {\n float value = (float)evaluate_definition(passed_data->program\n , passed_data->definition, freq_pair.first, t);\n *stream_ptr += 0.2f * value;\n }\n }\n ++stream_ptr;\n }\n}\n\nvoid live(term_t *const program, const std::string &definition) {\n if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO) != 0)\n die(\"Failed to initialize SDL\");\n\n int window_width = 600, window_height = (3. \/ 4.) * (double)window_width;\n SDL_Window *window = SDL_CreateWindow(\"Sythin live\", SDL_WINDOWPOS_CENTERED\n , SDL_WINDOWPOS_CENTERED, window_width, window_height, 0);\n if (!window)\n die(\"failed to create window\");\n\n SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0);\n SDL_SetRenderDrawColor(renderer, 19, 19, 19, 255);\n\n passed_data_t passed_data(program, definition);\n\n SDL_AudioSpec want, have;\n SDL_memset(&want, 0, sizeof(want));\n want.freq = 48000;\n want.format = AUDIO_F32;\n want.channels = 1;\n want.samples = 4096;\n want.callback = audio_callback;\n want.userdata = (void*)&passed_data;\n\n SDL_AudioDeviceID dev = SDL_OpenAudioDevice(nullptr, 0, &want, &have\n , SDL_AUDIO_ALLOW_ANY_CHANGE);\n if (dev == 0)\n die(\"failed to open audio device: %s\", SDL_GetError());\n\n SDL_PauseAudioDevice(dev, 0);\n\n std::map key_frequencies = {\n { SDLK_z, note_to_freq('A', 4, 0) },\n { SDLK_x, note_to_freq('A', 4, 1) },\n { SDLK_c, note_to_freq('B', 4, 0) },\n { SDLK_v, note_to_freq('C', 5, 0) }\n };\n\n bool quit = false;\n while (!quit) {\n SDL_Event event;\n while (SDL_PollEvent(&event))\n if (event.type == SDL_QUIT\n || (event.type == SDL_KEYUP && event.key.keysym.sym == SDLK_ESCAPE))\n quit = true;\n else if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP)\n if (key_frequencies.count(event.key.keysym.sym))\n passed_data.frequencies[key_frequencies[event.key.keysym.sym]]\n = event.type == SDL_KEYDOWN;\n\n SDL_RenderClear(renderer);\n SDL_RenderPresent(renderer);\n }\n\n SDL_DestroyRenderer(renderer);\n SDL_DestroyWindow(window);\n SDL_CloseAudioDevice(dev);\n SDL_Quit();\n}\n\n<|endoftext|>"} {"text":"\/**\n * \\file RMF\/Category.h\n * \\brief Handle read\/write of Model data from\/to files.\n *\n * Copyright 2007-2012 IMP Inventors. All rights reserved.\n *\n *\/\n#include \n#include \n#if RMF_HAS_LOG4CXX\n#include \n#include \n#include \n#include \n#include \n#endif\n\nnamespace RMF {\n#if RMF_HAS_LOG4CXX\nnamespace {\nstruct Configurator {\n Configurator(log4cxx::ConsoleAppenderPtr ptr) {\n log4cxx::BasicConfigurator::configure(ptr);\n }\n};\nvoid init_logger() {\n \/\/ \"%-4r [%t] %-5p %c %x - %m%n\"\n static log4cxx::PatternLayoutPtr layout\n = new log4cxx::PatternLayout(\"%-6r %-5p %c- %m%n\");\n static log4cxx::ConsoleAppenderPtr appender\n = new log4cxx::ConsoleAppender(layout);\n static Configurator config(appender);\n}\n}\nlog4cxx::LoggerPtr get_logger() {\n init_logger();\n static log4cxx::LoggerPtr ret = log4cxx::Logger::getLogger(\"RMF\");\n return ret;\n}\nlog4cxx::LoggerPtr get_avro_logger() {\n init_logger();\n static log4cxx::LoggerPtr ret = log4cxx::Logger::getLogger(\"RMF.avro\");\n return ret;\n}\nlog4cxx::LoggerPtr get_hdf5_logger() {\n init_logger();\n static log4cxx::LoggerPtr ret = log4cxx::Logger::getLogger(\"RMF.hdf5\");\n return ret;\n}\nvoid set_log_level(std::string str) {\n try {\n get_logger()->setLevel(log4cxx::Level::toLevel(str));\n } catch (log4cxx::helpers::Exception &e) {\n RMF_THROW(Message(\"Invalid log level\"), UsageException);\n }\n}\n#else\nvoid set_log_level(std::string str) {\n}\n#endif\n\n\n}\nonly initialize logging if it is not already\/**\n * \\file RMF\/Category.h\n * \\brief Handle read\/write of Model data from\/to files.\n *\n * Copyright 2007-2012 IMP Inventors. All rights reserved.\n *\n *\/\n#include \n#include \n#if RMF_HAS_LOG4CXX\n#include \n#include \n#include \n#include \n#include \n#endif\n\nnamespace RMF {\n#if RMF_HAS_LOG4CXX\nnamespace {\nstruct Configurator {\n Configurator(log4cxx::ConsoleAppenderPtr ptr) {\n log4cxx::BasicConfigurator::configure(ptr);\n }\n};\n\nvoid do_init() {\n \/\/ \"%-4r [%t] %-5p %c %x - %m%n\"\n static log4cxx::PatternLayoutPtr layout\n = new log4cxx::PatternLayout(\"%-6r %-5p %c- %m%n\");\n static log4cxx::ConsoleAppenderPtr appender\n = new log4cxx::ConsoleAppender(layout);\n static Configurator config(appender);\n}\n\nvoid init_logger() {\n log4cxx::LoggerPtr rootLogger =\n log4cxx::Logger::getRootLogger();\n bool uninit = rootLogger->getAllAppenders().empty() ? true : false;\n if (uninit) do_init();\n}\n}\nlog4cxx::LoggerPtr get_logger() {\n init_logger();\n static log4cxx::LoggerPtr ret = log4cxx::Logger::getLogger(\"RMF\");\n return ret;\n}\nlog4cxx::LoggerPtr get_avro_logger() {\n init_logger();\n static log4cxx::LoggerPtr ret = log4cxx::Logger::getLogger(\"RMF.avro\");\n return ret;\n}\nlog4cxx::LoggerPtr get_hdf5_logger() {\n init_logger();\n static log4cxx::LoggerPtr ret = log4cxx::Logger::getLogger(\"RMF.hdf5\");\n return ret;\n}\nvoid set_log_level(std::string str) {\n try {\n get_logger()->setLevel(log4cxx::Level::toLevel(str));\n get_avro_logger()->setLevel(log4cxx::Level::toLevel(str));\n get_hdf5_logger()->setLevel(log4cxx::Level::toLevel(str));\n } catch (log4cxx::helpers::Exception &e) {\n RMF_THROW(Message(\"Invalid log level\"), UsageException);\n }\n}\n#else\nvoid set_log_level(std::string str) {\n}\n#endif\n\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2016 Zeex\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#include \n#include \"configreader.h\"\n#include \"log.h\"\n#include \"logprintf.h\"\n\nnamespace {\n\nclass Log {\n public:\n Log(): file_(0) {\n ConfigReader server_cfg(\"server.cfg\");\n std::string filename = server_cfg.GetValueWithDefault(\"crashdetect_log\");\n if (!filename.empty()) {\n file_ = std::fopen(filename.c_str(), \"a\");\n }\n if (file_ != 0) {\n time_format_ =\n server_cfg.GetValueWithDefault(\"logtimeformat\", \"[%H:%M:%S]\");\n }\n }\n\n ~Log() {\n if (file_ != 0) {\n std::fclose(file_);\n }\n }\n\n void PrintV(const char *prefix,\n const char *format,\n std::va_list va) {\n std::string new_format;\n\n if (file_ != 0) {\n if (!time_format_.empty()) {\n char time_buffer[128];\n std::time_t time = std::time(0);\n std::strftime(time_buffer,\n sizeof(time_buffer),\n time_format_.c_str(),\n std::localtime(&time));\n new_format.append(time_buffer);\n new_format.append(\" \");\n }\n } else {\n new_format.append(prefix);\n }\n\n new_format.append(format);\n\n if (file_ != 0) {\n new_format.append(\"\\n\");\n vfprintf(file_, new_format.c_str(), va);\n } else {\n vlogprintf(new_format.c_str(), va);\n }\n }\n\n void Flush() {\n if (file_ != 0) {\n std::fflush(file_);\n }\n }\n\n private:\n std::FILE *file_;\n std::string time_format_;\n};\n\nLog global_log;\n\n} \/\/ namespace\n\nvoid LogPrintV(const char *prefix, const char *format, std::va_list va) {\n global_log.PrintV(prefix, format, va);\n}\n\nvoid LogTracePrint(const char *format, ...) {\n std::va_list va;\n va_start(va, format);\n LogPrintV(\"[trace] \", format, va);\n va_end(va);\n}\n\nvoid LogDebugPrint(const char *format, ...) {\n std::va_list va;\n va_start(va, format);\n LogPrintV(\"[debug] \", format, va);\n va_end(va);\n}\n\nvoid LogFlush() {\n global_log.Flush();\n}\nFix compile errors on Linux\/\/ Copyright (c) 2016 Zeex\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#include \n#include \n\n#include \n\n#include \"log.h\"\n#include \"logprintf.h\"\n\nnamespace {\n\nclass Log {\n public:\n Log(): file_(0) {\n ConfigReader server_cfg(\"server.cfg\");\n std::string filename = server_cfg.GetValueWithDefault(\"crashdetect_log\");\n if (!filename.empty()) {\n file_ = std::fopen(filename.c_str(), \"a\");\n }\n if (file_ != 0) {\n time_format_ =\n server_cfg.GetValueWithDefault(\"logtimeformat\", \"[%H:%M:%S]\");\n }\n }\n\n ~Log() {\n if (file_ != 0) {\n std::fclose(file_);\n }\n }\n\n void PrintV(const char *prefix,\n const char *format,\n std::va_list va) {\n std::string new_format;\n\n if (file_ != 0) {\n if (!time_format_.empty()) {\n char time_buffer[128];\n std::time_t time = std::time(0);\n std::strftime(time_buffer,\n sizeof(time_buffer),\n time_format_.c_str(),\n std::localtime(&time));\n new_format.append(time_buffer);\n new_format.append(\" \");\n }\n } else {\n new_format.append(prefix);\n }\n\n new_format.append(format);\n\n if (file_ != 0) {\n new_format.append(\"\\n\");\n vfprintf(file_, new_format.c_str(), va);\n } else {\n vlogprintf(new_format.c_str(), va);\n }\n }\n\n void Flush() {\n if (file_ != 0) {\n std::fflush(file_);\n }\n }\n\n private:\n std::FILE *file_;\n std::string time_format_;\n};\n\nLog global_log;\n\n} \/\/ namespace\n\nvoid LogPrintV(const char *prefix, const char *format, std::va_list va) {\n global_log.PrintV(prefix, format, va);\n}\n\nvoid LogTracePrint(const char *format, ...) {\n std::va_list va;\n va_start(va, format);\n LogPrintV(\"[trace] \", format, va);\n va_end(va);\n}\n\nvoid LogDebugPrint(const char *format, ...) {\n std::va_list va;\n va_start(va, format);\n LogPrintV(\"[debug] \", format, va);\n va_end(va);\n}\n\nvoid LogFlush() {\n global_log.Flush();\n}\n<|endoftext|>"} {"text":"\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#include \n#include \n#include \n\n#define AREA_RANGE 200.0\n\nusing std::weak_ptr;\nusing std::shared_ptr;\nusing std::unique_ptr;\nusing std::make_shared;\nusing std::cout;\nusing std::endl;\nusing ugdk::action::mode3d::Element;\nusing ugdk::action::mode3d::component::PhysicsBody;\nusing ugdk::action::mode3d::component::Body;\nusing ugdk::action::mode3d::component::View;\nusing ugdk::action::mode3d::component::CollisionAction;\nusing ugdk::action::mode3d::component::ElementPtr;\nusing ugdk::action::mode3d::component::ContactPointVector;\n\nnamespace {\n\nugdk::action::mode3d::Scene3D *ourscene;\n\nstruct {\n double angle;\n} player;\n\n} \/\/ unnamed namespace\n\n#define BIT(x) (1<<(x))\nenum CollisionGroup {\n HEADS = BIT(6),\n WALLS = BIT(7),\n WAT2 = BIT(8),\n WAT3 = BIT(9),\n WAT4 = BIT(10)\n};\n\nshared_ptr createOgreHead(const std::string& name, bool useBox=false) {\n Ogre::SceneManager *mSceneMgr = ourscene->manager();\n \/\/ Element\n auto head = ourscene->AddElement();\n \/\/ View\n auto headEnt = mSceneMgr->createEntity(name, \"Mage.mesh\");\n head->AddComponent(make_shared());\n head->component()->AddEntity(headEnt);\n \/\/ Body\n PhysicsBody::PhysicsData headData;\n auto meshShapeConv = BtOgre::StaticMeshToShapeConverter(headEnt);\n if (useBox)\n headData.shape = meshShapeConv.createBox();\n else\n headData.shape = meshShapeConv.createSphere();\n headData.mass = 80;\n headData.collision_group = CollisionGroup::HEADS;\n headData.collides_with = CollisionGroup::WALLS | CollisionGroup::HEADS;\n headData.apply_orientation = false;\n head->AddComponent(make_shared(*ourscene->physics(), headData));\n head->component()->set_damping(.4, .4);\n return head;\n}\n\nshared_ptr createWall(const std::string& name, const Ogre::Vector3& dir, double dist, double width = AREA_RANGE, double height = AREA_RANGE) {\n Ogre::SceneManager *mSceneMgr = ourscene->manager();\n \/\/ Element\n auto wall = ourscene->AddElement();\n \/\/ View\n Ogre::Plane plane(dir, dist);\n auto mesh_ptr = Ogre::MeshManager::getSingleton().createPlane(name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,\n plane, width, height, 5, 5, true, 1, 5, 5, dir.perpendicular());\n const std::string wat = name + \"Entity\";\n Ogre::Entity* wallEnt = mSceneMgr->createEntity(wat, mesh_ptr);\n wallEnt->setMaterialName(\"Ogre\/Tusks\");\n wall->AddComponent(make_shared());\n wall->component()->AddEntity(wallEnt);\n \/\/ Body\n PhysicsBody::PhysicsData wallData;\n wallData.shape = new btStaticPlaneShape(btVector3(dir.x, dir.y, dir.z), dist);\n wallData.mass = 0;\n wallData.collision_group = CollisionGroup::WALLS;\n wallData.collides_with = CollisionGroup::HEADS;\n wall->AddComponent(make_shared(*ourscene->physics(), wallData));\n wall->component()->set_friction(10);\n return wall;\n}\n\nint main(int argc, char* argv[]) {\n using Ogre::Vector3;\n\n ugdk::system::Configuration config;\n config.base_path = \"assets\/\";\n ugdk::system::Initialize(config);\n ourscene = new ugdk::action::mode3d::Scene3D(btVector3(0.0, -10.0, 0.0));\n \n ourscene->physics()->set_debug_draw_enabled(true);\n ourscene->ShowFrameStats();\n\n {\n player.angle = 0.0;\n weak_ptr head1 = createOgreHead(\"Head\");\n weak_ptr head2 = createOgreHead(\"Head2\", true);\n auto body2 = head2.lock()->component();\n body2->Translate(0, 0, 80);\n body2->set_angular_factor(0.0, 0.0, 0.0);\n\n body2->AddCollisionAction(CollisionGroup::HEADS, \n [](const ElementPtr& self, const ElementPtr& target, const ContactPointVector& pts) {\n cout << \"CARAS COLIDINDO MANO (\" << pts.size() << \")\" << endl;\n });\n\n weak_ptr wall = createWall(\"ground\", Vector3::UNIT_Y, -5.0);\n\n ourscene->camera()->AttachTo(*head2.lock());\n ourscene->camera()->SetParameters(Vector3::UNIT_Y*10.0, 5000.0);\n ourscene->camera()->SetDistance(80.0);\n ourscene->camera()->Rotate(0.0, Ogre::Degree(20.0).valueDegrees());\n \n ourscene->AddTask(ugdk::system::Task(\n [head2, body2](double dt) {\n auto& keyboard = ugdk::input::manager()->keyboard();\n Vector3 move = Vector3::ZERO;\n if (keyboard.IsDown(ugdk::input::Scancode::RIGHT))\n player.angle -= dt*90.0;\n else if (keyboard.IsDown(ugdk::input::Scancode::LEFT))\n player.angle += dt*90.0;\n if (keyboard.IsDown(ugdk::input::Scancode::UP))\n move.z += 1.0;\n else if (keyboard.IsDown(ugdk::input::Scancode::DOWN))\n move.z += -1.0;\n\n Ogre::Quaternion rot(Ogre::Degree(player.angle), Vector3::UNIT_Y);\n move.normalise();\n move = rot * move;\n move.y = 0.0;\n move.normalise();\n\n body2->ApplyImpulse((move * 80));\n Ogre::SceneNode &node = head2.lock()->node();\n node.setOrientation(rot);\n \/\/ Now update camera\n Ogre::SceneNode &cam_node = ourscene->camera()->node();\n }));\n\n ourscene->event_handler().AddListener(\n [] (const ugdk::input::KeyPressedEvent& ev) -> void {\n if (ev.scancode == ugdk::input::Scancode::ESCAPE)\n ourscene->Finish();\n });\n \/\/ourscene->event_handler().AddListener(\n \/\/ [] (const ugdk::input::MouseMotionEvent& ev) -> void {\n \/\/ ourscene->camera()->Rotate(-ev.motion.x, ev.motion.y);\n \/\/ });\n\n ourscene->manager()->setAmbientLight(Ogre::ColourValue(.7, .7, .7));\n\n ugdk::system::PushScene(unique_ptr(ourscene));\n\n }\n\n ugdk::system::Run();\n ugdk::system::Release();\n return 0;\n}\nAdjustments to friction\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#include \n#include \n#include \n\n#define AREA_RANGE 200.0\n\nusing std::weak_ptr;\nusing std::shared_ptr;\nusing std::unique_ptr;\nusing std::make_shared;\nusing std::cout;\nusing std::endl;\nusing ugdk::action::mode3d::Element;\nusing ugdk::action::mode3d::component::PhysicsBody;\nusing ugdk::action::mode3d::component::Body;\nusing ugdk::action::mode3d::component::View;\nusing ugdk::action::mode3d::component::CollisionAction;\nusing ugdk::action::mode3d::component::ElementPtr;\nusing ugdk::action::mode3d::component::ContactPointVector;\n\nnamespace {\n\nugdk::action::mode3d::Scene3D *ourscene;\n\nstruct {\n double angle;\n} player;\n\n} \/\/ unnamed namespace\n\n#define BIT(x) (1<<(x))\nenum CollisionGroup {\n HEADS = BIT(6),\n WALLS = BIT(7),\n WAT2 = BIT(8),\n WAT3 = BIT(9),\n WAT4 = BIT(10)\n};\n\nshared_ptr createOgreHead(const std::string& name, bool useBox=false) {\n Ogre::SceneManager *mSceneMgr = ourscene->manager();\n \/\/ Element\n auto head = ourscene->AddElement();\n \/\/ View\n auto headEnt = mSceneMgr->createEntity(name, \"Mage.mesh\");\n head->AddComponent(make_shared());\n head->component()->AddEntity(headEnt);\n \/\/ Body\n PhysicsBody::PhysicsData headData;\n auto meshShapeConv = BtOgre::StaticMeshToShapeConverter(headEnt);\n if (useBox)\n headData.shape = meshShapeConv.createBox();\n else\n headData.shape = meshShapeConv.createSphere();\n headData.mass = 80;\n headData.collision_group = CollisionGroup::HEADS;\n headData.collides_with = CollisionGroup::WALLS | CollisionGroup::HEADS;\n headData.apply_orientation = false;\n head->AddComponent(make_shared(*ourscene->physics(), headData));\n head->component()->set_damping(.8, .8);\n return head;\n}\n\nshared_ptr createWall(const std::string& name, const Ogre::Vector3& dir, double dist, double width = AREA_RANGE, double height = AREA_RANGE) {\n Ogre::SceneManager *mSceneMgr = ourscene->manager();\n \/\/ Element\n auto wall = ourscene->AddElement();\n \/\/ View\n Ogre::Plane plane(dir, dist);\n auto mesh_ptr = Ogre::MeshManager::getSingleton().createPlane(name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,\n plane, width, height, 5, 5, true, 1, 5, 5, dir.perpendicular());\n const std::string wat = name + \"Entity\";\n Ogre::Entity* wallEnt = mSceneMgr->createEntity(wat, mesh_ptr);\n wallEnt->setMaterialName(\"Ogre\/Tusks\");\n wall->AddComponent(make_shared());\n wall->component()->AddEntity(wallEnt);\n \/\/ Body\n PhysicsBody::PhysicsData wallData;\n wallData.shape = new btStaticPlaneShape(btVector3(dir.x, dir.y, dir.z), dist);\n wallData.mass = 0;\n wallData.collision_group = CollisionGroup::WALLS;\n wallData.collides_with = CollisionGroup::HEADS;\n wall->AddComponent(make_shared(*ourscene->physics(), wallData));\n wall->component()->set_friction(20);\n return wall;\n}\n\nint main(int argc, char* argv[]) {\n using Ogre::Vector3;\n\n ugdk::system::Configuration config;\n config.base_path = \"assets\/\";\n ugdk::system::Initialize(config);\n ourscene = new ugdk::action::mode3d::Scene3D(btVector3(0.0, -10.0, 0.0));\n \n ourscene->physics()->set_debug_draw_enabled(true);\n ourscene->ShowFrameStats();\n\n {\n player.angle = 0.0;\n weak_ptr head1 = createOgreHead(\"Head\");\n weak_ptr head2 = createOgreHead(\"Head2\", true);\n auto body2 = head2.lock()->component();\n body2->Translate(0, 0, 80);\n body2->set_angular_factor(0.0, 0.0, 0.0);\n\n body2->AddCollisionAction(CollisionGroup::HEADS, \n [](const ElementPtr& self, const ElementPtr& target, const ContactPointVector& pts) {\n cout << \"CARAS COLIDINDO MANO (\" << pts.size() << \")\" << endl;\n });\n\n weak_ptr wall = createWall(\"ground\", Vector3::UNIT_Y, -5.0);\n\n ourscene->camera()->AttachTo(*head2.lock());\n ourscene->camera()->SetParameters(Vector3::UNIT_Y*10.0, 5000.0);\n ourscene->camera()->SetDistance(80.0);\n ourscene->camera()->Rotate(0.0, Ogre::Degree(20.0).valueDegrees());\n \n ourscene->AddTask(ugdk::system::Task(\n [head2, body2](double dt) {\n auto& keyboard = ugdk::input::manager()->keyboard();\n Vector3 move = Vector3::ZERO;\n if (keyboard.IsDown(ugdk::input::Scancode::RIGHT))\n player.angle -= dt*135.0;\n else if (keyboard.IsDown(ugdk::input::Scancode::LEFT))\n player.angle += dt*135.0;\n if (keyboard.IsDown(ugdk::input::Scancode::UP))\n move.z += 1.0;\n else if (keyboard.IsDown(ugdk::input::Scancode::DOWN))\n move.z += -1.0;\n\n Ogre::Quaternion rot(Ogre::Degree(player.angle), Vector3::UNIT_Y);\n move.normalise();\n move = rot * move;\n move.y = 0.0;\n move.normalise();\n\n body2->ApplyImpulse(move * 200);\n Ogre::SceneNode &node = head2.lock()->node();\n node.setOrientation(rot);\n }));\n\n ourscene->event_handler().AddListener(\n [] (const ugdk::input::KeyPressedEvent& ev) -> void {\n if (ev.scancode == ugdk::input::Scancode::ESCAPE)\n ourscene->Finish();\n });\n \/\/ourscene->event_handler().AddListener(\n \/\/ [] (const ugdk::input::MouseMotionEvent& ev) -> void {\n \/\/ ourscene->camera()->Rotate(-ev.motion.x, ev.motion.y);\n \/\/ });\n\n ourscene->manager()->setAmbientLight(Ogre::ColourValue(.7, .7, .7));\n\n ugdk::system::PushScene(unique_ptr(ourscene));\n\n }\n\n ugdk::system::Run();\n ugdk::system::Release();\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"gameboy.h\"\n#include \"cartridge.h\"\n#include \"video\/screen.h\"\n#include \"util\/log.h\"\n\n#include \"video\/screens\/null_screen.h\"\n#include \"video\/screens\/sfml_screen.h\"\n\nstruct Options {\n bool debugger;\n bool trace;\n std::string filename;\n};\n\nstatic bool flag_set(char** begin, char** end, const std::string& short_option, const std::string& long_option) {\n bool short_option_found = std::find(begin, end, short_option) != end;\n bool long_option_found = std::find(begin, end, long_option) != end;\n return short_option_found || long_option_found;\n}\n\nstatic Options get_options(int argc, char* argv[]) {\n char** begin = argv;\n char** end = argv + argc;\n\n if (argc < 2) {\n log_error(\"Please provide a ROM file to run\");\n fatal_error();\n }\n\n bool debugger = flag_set(begin, end, \"-d\", \"--debug\");\n bool trace = flag_set(begin, end, \"-t\", \"--trace\");\n\n std::string filename = argv[1];\n\n return Options { debugger, trace, filename };\n}\n\nint main(int argc, char* argv[]) {\n Options options = get_options(argc, argv);\n\n auto log_level = options.trace ?\n LogLevel::Trace : LogLevel::Debug;\n\n log_set_level(log_level);\n\n Cartridge cartridge(options.filename);\n SFMLScreen screen;\n\n Gameboy gameboy(screen, cartridge, options.debugger);\n gameboy.run();\n}\nAdd a flag (--nolog\/-n) to disable all logging#include \"gameboy.h\"\n#include \"cartridge.h\"\n#include \"video\/screen.h\"\n#include \"util\/log.h\"\n\n#include \"video\/screens\/null_screen.h\"\n#include \"video\/screens\/sfml_screen.h\"\n\nstruct Options {\n bool debugger;\n bool trace;\n bool disable_logs;\n std::string filename;\n};\n\nstatic bool flag_set(char** begin, char** end, const std::string& short_option, const std::string& long_option) {\n bool short_option_found = std::find(begin, end, short_option) != end;\n bool long_option_found = std::find(begin, end, long_option) != end;\n return short_option_found || long_option_found;\n}\n\nstatic Options get_options(int argc, char* argv[]) {\n char** begin = argv;\n char** end = argv + argc;\n\n if (argc < 2) {\n log_error(\"Please provide a ROM file to run\");\n fatal_error();\n }\n\n bool debugger = flag_set(begin, end, \"-d\", \"--debug\");\n bool trace = flag_set(begin, end, \"-t\", \"--trace\");\n bool disable_logs = flag_set(begin, end, \"-n\", \"--nolog\");\n\n std::string filename = argv[1];\n\n return Options { debugger, trace, disable_logs, filename };\n}\n\nint main(int argc, char* argv[]) {\n Options options = get_options(argc, argv);\n\n auto log_level = options.trace ?\n LogLevel::Trace : LogLevel::Debug;\n\n log_set_level(log_level);\n\n if (options.disable_logs) log_set_level(LogLevel::Error);\n\n Cartridge cartridge(options.filename);\n SFMLScreen screen;\n\n Gameboy gameboy(screen, cartridge, options.debugger);\n gameboy.run();\n}\n<|endoftext|>"} {"text":"#include \n#include \"mainwindow.h\"\n\nint main(int argc, char *argv[])\n{\n QApplication app(argc, argv);\n\n app.setAttribute(Qt::AA_UseHighDpiPixmaps);\n\n QIcon appIcon;\n appIcon.addFile(\":\/Icons\/AppIcon32\");\n appIcon.addFile(\":\/Icons\/AppIcon128\");\n app.setWindowIcon(appIcon);\n\n MainWindow mainWindow;\n mainWindow.show();\n return app.exec();\n}\nAdd comment about Retina display support#include \n#include \"mainwindow.h\"\n\nint main(int argc, char *argv[])\n{\n QApplication app(argc, argv);\n\n \/\/ Retina display support for Mac OS, iOS and X11:\n \/\/ http:\/\/blog.qt.digia.com\/blog\/2013\/04\/25\/retina-display-support-for-mac-os-ios-and-x11\/\n \/\/\n \/\/ AA_UseHighDpiPixmaps attribute is off by default in Qt 5.1 but will most\n \/\/ likely be on by default in a future release of Qt.\n app.setAttribute(Qt::AA_UseHighDpiPixmaps);\n\n QIcon appIcon;\n appIcon.addFile(\":\/Icons\/AppIcon32\");\n appIcon.addFile(\":\/Icons\/AppIcon128\");\n app.setWindowIcon(appIcon);\n\n MainWindow mainWindow;\n mainWindow.show();\n return app.exec();\n}\n<|endoftext|>"} {"text":"\r\n#include \r\n#include \r\n\r\n#include \"jet\/Utf8String.h\"\r\n#include \"jet\/File.h\"\r\n#include \"jet\/Exception.h\"\r\n\r\n#include \"Parser.h\"\r\n\r\n\r\nusing namespace std;\r\nusing namespace jet;\r\nusing namespace jet::modeler;\r\n\r\n\r\ntemplate< class T >\r\nvoid print_as_binary( T value, ostream& output_stream ){\r\n\r\n bitset< sizeof(T) * 8 > x( value );\r\n\r\n output_stream << x ;\r\n\r\n}\r\n\r\n\r\nvoid show_usage(){\r\n\r\n cout << \"Usage: jm \" << endl;\r\n\r\n}\r\n\r\n\r\nvoid red( Utf8String text ){\r\n\r\n cout << \"\\033[1;31m\" << text << \"\\033[0m\";\r\n\r\n}\r\n\r\n\r\n\r\nint main( int argc, char** argv ){\r\n\r\n\r\n if( argc < 2 ){\r\n show_usage();\r\n return 1;\r\n }\r\n\r\n Utf8String *filename = NULL;\r\n File *file = NULL;\r\n Utf8String *contents = NULL;\r\n Parser *parser = NULL;\r\n\r\n try{\r\n\r\n filename = new Utf8String( argv[1] );\r\n\r\n file = new File( *filename );\r\n\r\n contents = new Utf8String;\r\n *contents = file->getContents();\r\n\r\n parser = new Parser;\r\n parser->parse( contents );\r\n\r\n cout << endl;\r\n\r\n parser->printModels();\r\n parser->writeModelFiles();\r\n\r\n }catch( Exception *e ){\r\n\r\n red( Utf8String(\"[Exception] \") );\r\n cout << \"- \" << e->message << endl;\r\n\r\n }\r\n\r\n if( parser != NULL ) delete parser;\r\n if( contents != NULL ) delete contents;\r\n if( file != NULL ) delete file;\r\n if( filename != NULL ) delete filename;\r\n\r\n\r\n\r\n\r\n\r\n\r\n \/*\r\n Utf8String my_string( \"Hello\", 5 );\r\n\r\n cout << my_string << endl;\r\n\r\n\r\n unsigned char current_byte = 0;\r\n\r\n unsigned int value = 0x80 >> 7;\r\n\r\n int shift_bytes = sizeof(unsigned int) - 1;\r\n\r\n current_byte = value;\r\n\r\n cout << shift_bytes << endl;\r\n\r\n \/\/cout << value << endl;\r\n\r\n \/\/cout << current_byte << endl;\r\n\r\n cout << \"Value as Binary: \";\r\n print_as_binary( value, cout );\r\n cout << endl;\r\n\r\n cout << \"Current Byte as Binary: \";\r\n print_as_binary( current_byte, cout );\r\n cout << endl;\r\n\r\n cout << \"Shift Bytes as Binary: \";\r\n print_as_binary( shift_bytes, cout );\r\n cout << endl;\r\n\r\n cout << \"Literal as Binary: \";\r\n print_as_binary( 0x01, cout );\r\n cout << endl;\r\n\r\n \/\/print_as_binary( my_string, cout );\r\n\r\n *\/\r\n\r\n\r\n\r\n\r\n\r\n return 0;\r\n\r\n}\r\nCleaned up main to actually do something.\r\n#include \r\n#include \r\n\r\n#include \"jet\/Utf8String.h\"\r\n#include \"jet\/File.h\"\r\n#include \"jet\/Exception.h\"\r\n\r\n\r\nusing namespace std;\r\nusing namespace jet;\r\n\r\n\r\ntemplate< class T >\r\nvoid print_as_binary( T value, ostream& output_stream ){\r\n\r\n bitset< sizeof(T) * 8 > x( value );\r\n\r\n output_stream << x ;\r\n\r\n}\r\n\r\n\r\nvoid show_usage(){\r\n\r\n cout << \"Usage: my_exe \" << endl;\r\n\r\n}\r\n\r\n\r\nvoid red( Utf8String text ){\r\n\r\n cout << \"\\033[1;31m\" << text << \"\\033[0m\";\r\n\r\n}\r\n\r\n\r\n\r\nint main( int argc, char** argv ){\r\n\r\n\r\n if( argc < 2 ){\r\n show_usage();\r\n return 1;\r\n }\r\n\r\n Utf8String *filename = NULL;\r\n File *file = NULL;\r\n Utf8String *contents = NULL;\r\n\r\n try{\r\n\r\n filename = new Utf8String( argv[1] );\r\n\r\n file = new File( *filename );\r\n\r\n contents = new Utf8String;\r\n *contents = file->getContents();\r\n\r\n cout << *contents;\r\n\r\n }catch( Exception *e ){\r\n\r\n red( Utf8String(\"[Exception] \") );\r\n cout << \"- \" << e->message << endl;\r\n\r\n }\r\n\r\n if( contents != NULL ) delete contents;\r\n if( file != NULL ) delete file;\r\n if( filename != NULL ) delete filename;\r\n\r\n\r\n\r\n\r\n\r\n\r\n \/*\r\n Utf8String my_string( \"Hello\", 5 );\r\n\r\n cout << my_string << endl;\r\n\r\n\r\n unsigned char current_byte = 0;\r\n\r\n unsigned int value = 0x80 >> 7;\r\n\r\n int shift_bytes = sizeof(unsigned int) - 1;\r\n\r\n current_byte = value;\r\n\r\n cout << shift_bytes << endl;\r\n\r\n \/\/cout << value << endl;\r\n\r\n \/\/cout << current_byte << endl;\r\n\r\n cout << \"Value as Binary: \";\r\n print_as_binary( value, cout );\r\n cout << endl;\r\n\r\n cout << \"Current Byte as Binary: \";\r\n print_as_binary( current_byte, cout );\r\n cout << endl;\r\n\r\n cout << \"Shift Bytes as Binary: \";\r\n print_as_binary( shift_bytes, cout );\r\n cout << endl;\r\n\r\n cout << \"Literal as Binary: \";\r\n print_as_binary( 0x01, cout );\r\n cout << endl;\r\n\r\n \/\/print_as_binary( my_string, cout );\r\n\r\n *\/\r\n\r\n\r\n\r\n\r\n\r\n return 0;\r\n\r\n}\r\n<|endoftext|>"} {"text":"\/\/============================================================================\n\/\/ Name : pel.cpp\n\/\/ Author : Joe Selman\n\/\/ Version :\n\n\/\/============================================================================\n\n#ifdef HAVE_CONFIG_H\n#include \"..\/config.h\"\n#endif\n\n#ifndef PACKAGE_STRING\n#define PACKAGE_STRING \"pel 0.8-svn\"\n#endif\n\n#include \nnamespace po = boost::program_options;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"fol\/fol.h\"\n#include \"fol\/folparser.h\"\n#include \"fol\/domain.h\"\n#include \"log.h\"\n#include \"fol\/moves.h\"\n#include \"fol\/maxwalksat.h\"\n#include \"fol\/formulaset.h\"\n\nint main(int argc, char* argv[]) {\n\t\/\/ Declare the supported options.\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t (\"help\", \"produce help message\")\n\t (\"version,v\", \"print version and exit\")\n\t (\"max\", po::value(), \"maximum value an interval endpoint can take\")\n\t (\"min\", po::value(), \"minimum value an interval endpoint can take\")\n\t (\"evalModel,e\", \"simply print the model weight of the facts file\")\n\t (\"prob,p\", po::value()->default_value(0.25), \"probability of taking a random move\")\n\t (\"iterations,i\", po::value()->default_value(1000), \"number of iterations before returning a model\")\n\t (\"output,o\", po::value(), \"output model file\")\n\t;\n\n\tpo::options_description hidden(\"Hidden options\");\n\thidden.add_options()\n\t\t(\"facts-file\", po::value(), \"facts file\")\n\t\t(\"formula-file\", po::value(), \"formula file\")\n\t;\n\tpo::positional_options_description p;\n\tp.add(\"facts-file\", 1);\n\tp.add(\"formula-file\", 1);\n\n\tpo::options_description cmdline_options;\n\tcmdline_options.add(desc).add(hidden);\n\n\tpo::variables_map vm;\n\tpo::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"version\")) {\n\t\tstd::cout << PACKAGE_STRING << std::endl;\n\t\treturn 0;\n\t}\n\n\tif (vm.count(\"help\") || !vm.count(\"facts-file\") || !vm.count(\"formula-file\")) {\n\t std::cout << \"Usage: pel [OPTION]... FACT-FILE FORMULA-FILE\" << std::endl;\n\t\tstd::cout << desc << std::endl;\n\t return 1;\n\t}\n\n\t\/\/ setup our logging facilities\n\tFILE* debugFile = fopen(\"debug.log\", \"w\");\n\tif (!debugFile) std::cerr << \"unable to open debug.log for logging - logging to stderr\";\n\telse FilePolicy::stream() = debugFile;\n\tFileLog::globalLogLevel() = LOG_DEBUG;\n\n\tLOG(LOG_INFO) << \"Opened log file for new session\";\n\n\t\/\/ make sure we can open the output model file, if specified\n\tFILE* outputFile = NULL;\n\tif (vm.count(\"output\")) {\n\t\toutputFile = fopen(vm[\"output\"].as().c_str(), \"w\");\n\t\tif (!outputFile) {\n\t\t\tstd::cerr << \"unable to open output file \\\"\" << vm[\"output\"].as() << \"\\\" for writing.\" << std::endl;\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tboost::shared_ptr d = FOLParse::loadDomainFromFiles(vm[\"facts-file\"].as(), vm[\"formula-file\"].as());\n\tif (vm.count(\"max\") || vm.count(\"min\")) {\n\t\tInterval maxInt = d->maxInterval();\n\t\tif (vm.count(\"max\")) maxInt.setFinish(vm[\"max\"].as());\n\t\tif (vm.count(\"min\")) maxInt.setStart(vm[\"min\"].as());\n\t\td->setMaxInterval(maxInt);\n\t}\n\n\tModel model = d->defaultModel();\n\n\tLOG_PRINT(LOG_INFO) << \"model size: \" << model.size();\n\tLOG(LOG_DEBUG) << \"observation predicates: \";\n\tfor(std::map::const_iterator it = d->observedPredicates().begin();\n\t\t\tit != d->observedPredicates().end();\n\t\t\tit++) {\n\t\tLOG(LOG_DEBUG) << \"\\t\" << it->first;\n\t}\n\n\tif (vm.count(\"evalModel\")) {\n\t\tLOG(LOG_INFO) << \"evaluating model...\";\n\t\tunsigned long sum = 0;\n\t\t\/\/ evaluate the weight of each formula in the domain\n\t\tfor(FormulaSet::const_iterator it = d->formulaSet().begin(); it != d->formulaSet().end(); it++) {\n\t\t\tWSentence formula = *it;\n\t\t\tSISet satisfied = d->satisfied(*(formula.sentence()), model);\n\t\t\tunsigned long weight = d->score(formula, model);\n\t\t\tsum += weight;\n\t\t\tLOG_PRINT(LOG_INFO) << \"formula: (\" << formula.sentence()->toString() << \")\";\n\t\t\tLOG_PRINT(LOG_INFO) << \"\\tsatisfied @ \" << satisfied.toString();\n\t\t\tLOG_PRINT(LOG_INFO) << \"\\tscore contributed: \" << weight;\n\t\t}\n\t\tLOG_PRINT(LOG_INFO) << \"total score of model: \" << sum;\n\t} else {\n\t\tdouble p = vm[\"prob\"].as();\n\t\tunsigned int iterations = vm[\"iterations\"].as();\n\n\t\tLOG(LOG_INFO) << \"searching for a maximum-weight model, with p=\" << p << \" and iterations=\" << iterations;\n\t\tModel defModel = d->defaultModel();\n\t\tModel maxModel = maxWalkSat(*d, iterations, p, &defModel);\n\t\tLOG_PRINT(LOG_INFO) << \"Best model found: \" << std::endl;\n\t\tLOG_PRINT(LOG_INFO) << maxModel.toString();\n\t\tif (vm.count(\"output\")) {\n\t\t\t\/\/ log it to the output file as well\n\t\t\tfprintf(outputFile, \"# generated from fact file \\\"%s\\\" and formula file \\\"%s\\\"\\n\",\n\t\t\t\t\tvm[\"facts-file\"].as().c_str(),\n\t\t\t\t\tvm[\"formula-file\"].as().c_str());\n\t\t\tstd::string timeStr;\n\t\t\t{\n\t\t\t\ttime_t rawtime;\n\t\t\t\tstruct tm * timeinfo;\n\t\t\t\ttime (&rawtime);\n\t\t\t\ttimeinfo = localtime (&rawtime);\n\t\t\t\ttimeStr = asctime(timeinfo);\n\t\t\t}\n\t\t\tfprintf(outputFile, \"# generated on %s\\n\", timeStr.c_str());\n\t\t\tfprintf(outputFile, \"# run with %d iterations and %g chance of choosing a random move\\n\",\n\t\t\t\t\titerations,\n\t\t\t\t\tp);\n\t\t\tfputs(maxModel.toString().c_str(), outputFile);\n\t\t}\n\t}\n\n\t\/\/ Should be good and close files?\n\treturn 0;\n}\ncode now uses correct package name\/\/============================================================================\n\/\/ Name : pel.cpp\n\/\/ Author : Joe Selman\n\/\/ Version :\n\n\/\/============================================================================\n\n#include \"PELConfig.h\"\n\n#include \nnamespace po = boost::program_options;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"fol\/fol.h\"\n#include \"fol\/folparser.h\"\n#include \"fol\/domain.h\"\n#include \"log.h\"\n#include \"fol\/moves.h\"\n#include \"fol\/maxwalksat.h\"\n#include \"fol\/formulaset.h\"\n\nint main(int argc, char* argv[]) {\n\t\/\/ Declare the supported options.\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t (\"help\", \"produce help message\")\n\t (\"version,v\", \"print version and exit\")\n\t (\"max\", po::value(), \"maximum value an interval endpoint can take\")\n\t (\"min\", po::value(), \"minimum value an interval endpoint can take\")\n\t (\"evalModel,e\", \"simply print the model weight of the facts file\")\n\t (\"prob,p\", po::value()->default_value(0.25), \"probability of taking a random move\")\n\t (\"iterations,i\", po::value()->default_value(1000), \"number of iterations before returning a model\")\n\t (\"output,o\", po::value(), \"output model file\")\n\t;\n\n\tpo::options_description hidden(\"Hidden options\");\n\thidden.add_options()\n\t\t(\"facts-file\", po::value(), \"facts file\")\n\t\t(\"formula-file\", po::value(), \"formula file\")\n\t;\n\tpo::positional_options_description p;\n\tp.add(\"facts-file\", 1);\n\tp.add(\"formula-file\", 1);\n\n\tpo::options_description cmdline_options;\n\tcmdline_options.add(desc).add(hidden);\n\n\tpo::variables_map vm;\n\tpo::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"version\")) {\n\t\tstd::cout << \"pelmap version \" << PEL_VERSION_MAJOR << \".\" << PEL_VERSION_MINOR << std::endl;\n\t\treturn 0;\n\t}\n\n\tif (vm.count(\"help\") || !vm.count(\"facts-file\") || !vm.count(\"formula-file\")) {\n\t std::cout << \"Usage: pelmap [OPTION]... FACT-FILE FORMULA-FILE\" << std::endl;\n\t\tstd::cout << desc << std::endl;\n\t return 1;\n\t}\n\n\t\/\/ setup our logging facilities\n\tFILE* debugFile = fopen(\"debug.log\", \"w\");\n\tif (!debugFile) std::cerr << \"unable to open debug.log for logging - logging to stderr\";\n\telse FilePolicy::stream() = debugFile;\n\tFileLog::globalLogLevel() = LOG_DEBUG;\n\n\tLOG(LOG_INFO) << \"Opened log file for new session\";\n\n\t\/\/ make sure we can open the output model file, if specified\n\tFILE* outputFile = NULL;\n\tif (vm.count(\"output\")) {\n\t\toutputFile = fopen(vm[\"output\"].as().c_str(), \"w\");\n\t\tif (!outputFile) {\n\t\t\tstd::cerr << \"unable to open output file \\\"\" << vm[\"output\"].as() << \"\\\" for writing.\" << std::endl;\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tboost::shared_ptr d = FOLParse::loadDomainFromFiles(vm[\"facts-file\"].as(), vm[\"formula-file\"].as());\n\tif (vm.count(\"max\") || vm.count(\"min\")) {\n\t\tInterval maxInt = d->maxInterval();\n\t\tif (vm.count(\"max\")) maxInt.setFinish(vm[\"max\"].as());\n\t\tif (vm.count(\"min\")) maxInt.setStart(vm[\"min\"].as());\n\t\td->setMaxInterval(maxInt);\n\t}\n\n\tModel model = d->defaultModel();\n\n\tLOG_PRINT(LOG_INFO) << \"model size: \" << model.size();\n\tLOG(LOG_DEBUG) << \"observation predicates: \";\n\tfor(std::map::const_iterator it = d->observedPredicates().begin();\n\t\t\tit != d->observedPredicates().end();\n\t\t\tit++) {\n\t\tLOG(LOG_DEBUG) << \"\\t\" << it->first;\n\t}\n\n\tif (vm.count(\"evalModel\")) {\n\t\tLOG(LOG_INFO) << \"evaluating model...\";\n\t\tunsigned long sum = 0;\n\t\t\/\/ evaluate the weight of each formula in the domain\n\t\tfor(FormulaSet::const_iterator it = d->formulaSet().begin(); it != d->formulaSet().end(); it++) {\n\t\t\tWSentence formula = *it;\n\t\t\tSISet satisfied = d->satisfied(*(formula.sentence()), model);\n\t\t\tunsigned long weight = d->score(formula, model);\n\t\t\tsum += weight;\n\t\t\tLOG_PRINT(LOG_INFO) << \"formula: (\" << formula.sentence()->toString() << \")\";\n\t\t\tLOG_PRINT(LOG_INFO) << \"\\tsatisfied @ \" << satisfied.toString();\n\t\t\tLOG_PRINT(LOG_INFO) << \"\\tscore contributed: \" << weight;\n\t\t}\n\t\tLOG_PRINT(LOG_INFO) << \"total score of model: \" << sum;\n\t} else {\n\t\tdouble p = vm[\"prob\"].as();\n\t\tunsigned int iterations = vm[\"iterations\"].as();\n\n\t\tLOG(LOG_INFO) << \"searching for a maximum-weight model, with p=\" << p << \" and iterations=\" << iterations;\n\t\tModel defModel = d->defaultModel();\n\t\tModel maxModel = maxWalkSat(*d, iterations, p, &defModel);\n\t\tLOG_PRINT(LOG_INFO) << \"Best model found: \" << std::endl;\n\t\tLOG_PRINT(LOG_INFO) << maxModel.toString();\n\t\tif (vm.count(\"output\")) {\n\t\t\t\/\/ log it to the output file as well\n\t\t\tfprintf(outputFile, \"# generated from fact file \\\"%s\\\" and formula file \\\"%s\\\"\\n\",\n\t\t\t\t\tvm[\"facts-file\"].as().c_str(),\n\t\t\t\t\tvm[\"formula-file\"].as().c_str());\n\t\t\tstd::string timeStr;\n\t\t\t{\n\t\t\t\ttime_t rawtime;\n\t\t\t\tstruct tm * timeinfo;\n\t\t\t\ttime (&rawtime);\n\t\t\t\ttimeinfo = localtime (&rawtime);\n\t\t\t\ttimeStr = asctime(timeinfo);\n\t\t\t}\n\t\t\tfprintf(outputFile, \"# generated on %s\\n\", timeStr.c_str());\n\t\t\tfprintf(outputFile, \"# run with %d iterations and %g chance of choosing a random move\\n\",\n\t\t\t\t\titerations,\n\t\t\t\t\tp);\n\t\t\tfputs(maxModel.toString().c_str(), outputFile);\n\t\t}\n\t}\n\n\t\/\/ Should be good and close files?\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2018 The Bitcoin 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\n#include \n#include \n#include \n#include \n\n\/\/ ppcoin: find last block index up to pindex\nconst CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)\n{\n \/\/CBlockIndex will be updated with information about the proof type later\n while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))\n pindex = pindex->pprev;\n return pindex;\n}\n\ninline arith_uint256 GetLimit(const Consensus::Params& params, bool fProofOfStake)\n{\n return fProofOfStake ? UintToArith256(params.posLimit) : UintToArith256(params.powLimit);\n}\n\nunsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params, bool fProofOfStake)\n{\n\n unsigned int nTargetLimit = GetLimit(params, fProofOfStake).GetCompact();\n\n \/\/ genesis block\n if (pindexLast == NULL)\n return nTargetLimit;\n\n \/\/ first block\n const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);\n if (pindexPrev->pprev == NULL)\n return nTargetLimit;\n\n \/\/ second block\n const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);\n if (pindexPrevPrev->pprev == NULL)\n return nTargetLimit;\n\n \/\/ min difficulty\n if (params.fPowAllowMinDifficultyBlocks)\n {\n \/\/ Special difficulty rule for testnet:\n \/\/ If the new block's timestamp is more than 2* 10 minutes\n \/\/ then allow mining of a min-difficulty block.\n if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)\n return nTargetLimit;\n else\n {\n \/\/ Return the last non-special-min-difficulty-rules-block\n const CBlockIndex* pindex = pindexLast;\n while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval(pindex->nHeight) != 0 && pindex->nBits == nTargetLimit)\n pindex = pindex->pprev;\n return pindex->nBits;\n }\n return pindexLast->nBits;\n }\n\n return CalculateNextWorkRequired(pindexPrev, pindexPrevPrev->GetBlockTime(), params, fProofOfStake);\n}\n\nunsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params, bool fProofOfStake)\n{\n if(fProofOfStake){\n if (params.fPoSNoRetargeting)\n return pindexLast->nBits;\n }else{\n if (params.fPowNoRetargeting)\n return pindexLast->nBits;\n }\n \/\/ Limit adjustment step\n int64_t nTargetSpacing = params.nPowTargetSpacing;\n int64_t nActualSpacing = pindexLast->GetBlockTime() - nFirstBlockTime;\n if (nActualSpacing < 0)\n nActualSpacing = nTargetSpacing;\n if (nActualSpacing > nTargetSpacing * 10)\n nActualSpacing = nTargetSpacing * 10;\n\n\t\/\/ Retarget\n const arith_uint256 bnTargetLimit = GetLimit(params, fProofOfStake);\n \/\/ ppcoin: target change every block\n \/\/ ppcoin: retarget with exponential moving toward target spacing\n arith_uint256 bnNew;\n bnNew.SetCompact(pindexLast->nBits);\n int64_t nInterval = params.DifficultyAdjustmentInterval(pindexLast->nHeight);\n bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);\n bnNew \/= ((nInterval + 1) * nTargetSpacing);\n\n if (bnNew <= 0 || bnNew > bnTargetLimit)\n bnNew = bnTargetLimit;\n\n return bnNew.GetCompact();\n}\n\nbool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params, bool fProofOfStake)\n{\n bool fNegative;\n bool fOverflow;\n arith_uint256 bnTarget;\n\n bnTarget.SetCompact(nBits, &fNegative, &fOverflow);\n\n \/\/ Check range\n if (fNegative || bnTarget == 0 || fOverflow || bnTarget > GetLimit(params, fProofOfStake))\n return false;\n\n \/\/ Check proof of work matches claimed amount\n if (UintToArith256(hash) > bnTarget)\n return false;\n\n return true;\n}\nfix block height\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2018 The Bitcoin 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\n#include \n#include \n#include \n#include \n\n\/\/ ppcoin: find last block index up to pindex\nconst CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)\n{\n \/\/CBlockIndex will be updated with information about the proof type later\n while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))\n pindex = pindex->pprev;\n return pindex;\n}\n\ninline arith_uint256 GetLimit(const Consensus::Params& params, bool fProofOfStake)\n{\n return fProofOfStake ? UintToArith256(params.posLimit) : UintToArith256(params.powLimit);\n}\n\nunsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params, bool fProofOfStake)\n{\n\n unsigned int nTargetLimit = GetLimit(params, fProofOfStake).GetCompact();\n\n \/\/ genesis block\n if (pindexLast == NULL)\n return nTargetLimit;\n\n \/\/ first block\n const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);\n if (pindexPrev->pprev == NULL)\n return nTargetLimit;\n\n \/\/ second block\n const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);\n if (pindexPrevPrev->pprev == NULL)\n return nTargetLimit;\n\n \/\/ min difficulty\n if (params.fPowAllowMinDifficultyBlocks)\n {\n \/\/ Special difficulty rule for testnet:\n \/\/ If the new block's timestamp is more than 2* 10 minutes\n \/\/ then allow mining of a min-difficulty block.\n if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)\n return nTargetLimit;\n else\n {\n \/\/ Return the last non-special-min-difficulty-rules-block\n const CBlockIndex* pindex = pindexLast;\n while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval(pindex->nHeight) != 0 && pindex->nBits == nTargetLimit)\n pindex = pindex->pprev;\n return pindex->nBits;\n }\n return pindexLast->nBits;\n }\n\n return CalculateNextWorkRequired(pindexPrev, pindexPrevPrev->GetBlockTime(), params, fProofOfStake);\n}\n\nunsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params, bool fProofOfStake)\n{\n if(fProofOfStake){\n if (params.fPoSNoRetargeting)\n return pindexLast->nBits;\n }else{\n if (params.fPowNoRetargeting)\n return pindexLast->nBits;\n }\n \/\/ Limit adjustment step\n int64_t nTargetSpacing = params.nPowTargetSpacing;\n int64_t nActualSpacing = pindexLast->GetBlockTime() - nFirstBlockTime;\n if (nActualSpacing < 0)\n nActualSpacing = nTargetSpacing;\n if (nActualSpacing > nTargetSpacing * 10)\n nActualSpacing = nTargetSpacing * 10;\n\n\t\/\/ Retarget\n const arith_uint256 bnTargetLimit = GetLimit(params, fProofOfStake);\n \/\/ ppcoin: target change every block\n \/\/ ppcoin: retarget with exponential moving toward target spacing\n arith_uint256 bnNew;\n bnNew.SetCompact(pindexLast->nBits);\n int64_t nInterval = params.DifficultyAdjustmentInterval(pindexLast->nHeight + 1);\n bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);\n bnNew \/= ((nInterval + 1) * nTargetSpacing);\n\n if (bnNew <= 0 || bnNew > bnTargetLimit)\n bnNew = bnTargetLimit;\n\n return bnNew.GetCompact();\n}\n\nbool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params, bool fProofOfStake)\n{\n bool fNegative;\n bool fOverflow;\n arith_uint256 bnTarget;\n\n bnTarget.SetCompact(nBits, &fNegative, &fOverflow);\n\n \/\/ Check range\n if (fNegative || bnTarget == 0 || fOverflow || bnTarget > GetLimit(params, fProofOfStake))\n return false;\n\n \/\/ Check proof of work matches claimed amount\n if (UintToArith256(hash) > bnTarget)\n return false;\n\n return true;\n}\n<|endoftext|>"} {"text":"\/* \n * File: qpp.cpp\n * Author: vlad\n *\n * Created on December 12, 2013, 10:43 PM\n *\/\n\n#include \n#include \"qpp.h\"\n\nnamespace qpp\n{\n\n\/\/ Random number initialization\nstd::random_device stat::_rd; \/\/ make the random_device generator visible\nstd::mt19937 stat::_rng(_rd()); \/\/ make the mt19937 generator visible\n\n\/\/ Various gates (declared extern in \"gates.h\"); make them visible\nnamespace gt\n{\nEigen::MatrixXcd H, Id2, X, Y, Z, S, T;\nEigen::MatrixXcd CNOT, CP;\nEigen::MatrixXcd TOF(8, 8);\n}\n\n\/\/ initialize the library\nint _init()\n{\n\t\/\/ initialize the gates\n\tgt::_init_gates();\n\n\/\/ seed the standard random number generator (needed by Eigen)\n\tstd::srand(static_cast(stat::_rd()));\n\n\treturn 0;\n}\n\n}\ncommit\/* \n * File: qpp.cpp\n * Author: vlad\n *\n * Created on December 12, 2013, 10:43 PM\n *\/\n\n#include \n#include \"qpp.h\"\n\nnamespace qpp\n{\n\n\/\/ Random number initialization\nstd::random_device stat::_rd; \/\/ make the random_device generator visible\nstd::mt19937 stat::_rng(_rd()); \/\/ make the mt19937 generator visible, seed it\n\n\/\/ Various gates (declared extern in \"gates.h\"); make them visible\nnamespace gt\n{\nEigen::MatrixXcd H, Id2, X, Y, Z, S, T;\nEigen::MatrixXcd CNOT, CP;\nEigen::MatrixXcd TOF(8, 8);\n}\n\n\/\/ initialize the library\nint _init()\n{\n\t\/\/ initialize the gates\n\tgt::_init_gates();\n\n\/\/ seed the standard random number generator (needed by Eigen)\n\tstd::srand(static_cast(stat::_rd()));\n\n\treturn 0;\n}\n\n}\n<|endoftext|>"} {"text":"#include \"ray.hpp\"\n\n#include \n#include \n#include \n\n#include \"constants.hpp\"\n#include \"box2d.hpp\"\n\n\nvoid Ray::swap(Ray & rhs)\n{\n std::swap(m_origin, rhs.m_origin);\n std::swap(m_direction, rhs.m_direction);\n}\n\nRay::Ray(Ray && rhs)\n{\n swap(rhs);\n}\n\nRay & Ray::operator=(Ray && rhs)\n{\n swap(rhs);\n return *this;\n}\n\nbool Ray::operator ==(Ray const & rhs) const\n{\n if (this == &rhs) { return true; }\n\n if (this->m_direction != rhs.direction()) { return false; }\n if (this->m_origin != rhs.origin()) { return false; }\n\n return true;\n}\n\nbool Ray::operator !=(Ray const & rhs) const\n{\n return !(this->operator ==(rhs));\n}\n\nRay & Ray::operator=(const Ray & rhs)\n{\n Ray tmp(rhs);\n swap(tmp);\n return *this;\n}\n\nbool Ray::checkIntersection(\n Ray const & ray,\n Box2D const & box)\n{\n \/\/ Check if a point inside a box.\n if (Box2D::checkInside(box, ray.origin()))\n {\n return true;\n }\n\n bool is_special = false;\n\n \/\/ Recalculate box points.\n \/\/ Use the point as an origin of a coordinate system for the box.\n float x_1_n = box.boxMin().x() - ray.origin().x();\n float x_2_n = box.boxMax().x() - ray.origin().x();\n\n float y_1_n = box.boxMin().y() - ray.origin().y();\n float y_2_n = box.boxMax().y() - ray.origin().y();\n\n float x_3_n = x_1_n;\n float y_3_n = y_2_n;\n\n float x_4_n = x_2_n;\n float y_4_n = y_1_n;\n\n float x_ray = ray.direction().x();\n float y_ray = ray.direction().y();\n\n \/\/ It handels special case when rectangle intersepts x-axis\n \/\/ to the right from an origin point of a ray.\n if (x_ray < x_1_n && x_ray < x_2_n)\n {\n is_special = true;\n }\n\n \/\/ Check if the x coordinate is zero.\n x_ray = checkZeroDenominator(x_ray);\n x_1_n = checkZeroDenominator(x_1_n);\n x_2_n = checkZeroDenominator(x_2_n);\n x_3_n = checkZeroDenominator(x_3_n);\n x_4_n = checkZeroDenominator(x_4_n);\n\n \/\/ Calculate an anlge for the current point\n \/\/ and convert the angle to degrees.\n float angle_ray = convertRadianToDegrees(\n std::atan(y_ray \/ x_ray));\n float angle_1_n = convertRadianToDegrees(\n std::atan(y_1_n \/ x_1_n));\n float angle_2_n = convertRadianToDegrees(\n std::atan(y_2_n \/ x_2_n));\n float angle_3_n = convertRadianToDegrees(\n std::atan(y_3_n \/ x_3_n));\n float angle_4_n = convertRadianToDegrees(\n std::atan(y_4_n \/ x_4_n));\n\n \/\/ Correct a value of the angle if needed.\n angle_ray = recalculateAngle(x_ray, y_ray, angle_ray);\n angle_1_n = recalculateAngle(x_1_n, y_1_n, angle_1_n);\n angle_2_n = recalculateAngle(x_2_n, y_2_n, angle_2_n);\n angle_3_n = recalculateAngle(x_3_n, y_3_n, angle_3_n);\n angle_4_n = recalculateAngle(x_4_n, y_4_n, angle_4_n);\n\n \/\/ Combine all angles for the box points.\n std::array angles = {\n angle_1_n, angle_2_n, angle_3_n, angle_4_n\n };\n\n if (is_special)\n {\n \/\/ It finds to angles.\n \/\/ Maximum angle in the first quater\n \/\/ and the minimun angle in the fouth quater.\n float angle_max_first_quater = 0.0f;\n float angle_min_fourth_quater = 360.0f;\n\n for (auto const & item : angles)\n {\n if (item < 90.0f)\n {\n if (angle_max_first_quater < item)\n {\n angle_max_first_quater = item;\n }\n }\n else if (item > 270.0f)\n {\n if (angle_min_fourth_quater > item)\n {\n angle_min_fourth_quater = item;\n }\n }\n }\n\n \/\/ Compare the ray angle with\n \/\/ the max angle in the first quater\n \/\/ and the min angle in the fouth quater.\n if (angle_ray <= angle_max_first_quater &&\n angle_ray >= angle_min_fourth_quater) {\n return true;\n }\n }\n else\n {\n \/\/ Find a min and max angles for the box points.\n auto result = std::minmax_element(\n std::begin(angles), std::end(angles));\n\n \/\/ Compare the ray angle with the min\n \/\/ and max angles for the box points.\n if (*result.first <= angle_ray &&\n angle_ray <= *result.second) {\n return true;\n }\n }\n\n return false;\n}\n\nfloat Ray::convertRadianToDegrees(float const & angle)\n{\n return angle \/ Constants::PI * 180;\n}\n\nfloat Ray::recalculateAngle(float const & x,\n float const & y,\n float const & angle)\n{\n float angle_n = 0.0f;\n\n \/\/ The second quarter.\n if (y > (0.0f - Constants::kEps) &&\n x < (0.0f + Constants::kEps))\n {\n angle_n = 180.0f - abs(angle);\n }\n\n \/\/ The third quarter.\n if (y < 0.0f &&\n x < (0.0f + Constants::kEps))\n {\n angle_n = 180.0f + abs(angle);\n }\n\n \/\/ The fouth quarter.\n if (y < 0.0f &&\n x > 0.0f)\n {\n angle_n = 360.0f - abs(angle);\n }\n\n return angle_n;\n}\n\nfloat Ray::checkZeroDenominator(float const & value)\n{\n float tmp = value;\n\n if (abs(tmp) < Constants::kEps)\n {\n tmp = Constants::kEps;\n }\n\n return tmp;\n}\n\nvoid Ray::setOrigin(const Point2D & origin)\n{\n m_origin = origin;\n}\n\nvoid Ray::setDirection(const Point2D & direction)\n{\n m_direction = direction;\n}\n\nstd::ostream & operator <<(std::ostream & os,\n Ray const & rhs)\n{\n os << \"origin: \" << rhs.origin() << \"; \"\n << \"direction: \" << rhs.direction() << std::endl;\n return os;\n}\nrefactor the code: rename point and angle names#include \"ray.hpp\"\n\n#include \n#include \n#include \n\n#include \"constants.hpp\"\n#include \"box2d.hpp\"\n\n\nvoid Ray::swap(Ray & rhs)\n{\n std::swap(m_origin, rhs.m_origin);\n std::swap(m_direction, rhs.m_direction);\n}\n\nRay::Ray(Ray && rhs)\n{\n swap(rhs);\n}\n\nRay & Ray::operator=(Ray && rhs)\n{\n swap(rhs);\n return *this;\n}\n\nbool Ray::operator ==(Ray const & rhs) const\n{\n if (this == &rhs) { return true; }\n\n if (this->m_direction != rhs.direction()) { return false; }\n if (this->m_origin != rhs.origin()) { return false; }\n\n return true;\n}\n\nbool Ray::operator !=(Ray const & rhs) const\n{\n return !(this->operator ==(rhs));\n}\n\nRay & Ray::operator=(const Ray & rhs)\n{\n Ray tmp(rhs);\n swap(tmp);\n return *this;\n}\n\nbool Ray::checkIntersection(\n Ray const & ray,\n Box2D const & box)\n{\n \/\/ Check if a point inside a box.\n if (Box2D::checkInside(box, ray.origin()))\n {\n return true;\n }\n\n bool isSpecial = false;\n\n \/\/ Recalculate box points.\n \/\/ Use the point as an origin of a coordinate system for the box.\n float xBoxMinLower = box.boxMin().x() - ray.origin().x();\n float xBoxMaxUpper = box.boxMax().x() - ray.origin().x();\n\n float yBoxMinLower = box.boxMin().y() - ray.origin().y();\n float yBoxMaxUpper = box.boxMax().y() - ray.origin().y();\n\n float xBoxMinUpper = xBoxMinLower;\n float yBoxMinUpper = yBoxMaxUpper;\n\n float xBoxMaxLower = xBoxMaxUpper;\n float yBoxMaxLower = yBoxMinLower;\n\n float xRay = ray.direction().x();\n float yRay = ray.direction().y();\n\n \/\/ It handels special case when rectangle intersepts x-axis\n \/\/ to the right from an origin point of a ray.\n if (xRay < xBoxMinLower)\n {\n isSpecial = true;\n }\n\n \/\/ Check if the x coordinate is zero.\n xRay = checkZeroDenominator(xRay);\n xBoxMinLower = checkZeroDenominator(xBoxMinLower);\n xBoxMaxUpper = checkZeroDenominator(xBoxMaxUpper);\n xBoxMinUpper = checkZeroDenominator(xBoxMinUpper);\n xBoxMaxLower = checkZeroDenominator(xBoxMaxLower);\n\n \/\/ Calculate an anlge for the current point\n \/\/ and convert the angle to degrees.\n float angleRay = convertRadianToDegrees(\n std::atan(yRay \/ xRay));\n\n float angleBoxMinLower = convertRadianToDegrees(\n std::atan(yBoxMinLower \/ xBoxMinLower));\n\n float angleBoxMaxUpper = convertRadianToDegrees(\n std::atan(yBoxMaxUpper \/ xBoxMaxUpper));\n\n float angleBoxMinUpper = convertRadianToDegrees(\n std::atan(yBoxMinUpper \/ xBoxMinUpper));\n\n float angleBoxMaxLower = convertRadianToDegrees(\n std::atan(yBoxMaxLower \/ xBoxMaxLower));\n\n \/\/ Correct a value of the angle if needed.\n angleRay = recalculateAngle(\n xRay, yRay, angleRay);\n\n angleBoxMinLower = recalculateAngle(\n xBoxMinLower, yBoxMinLower, angleBoxMinLower);\n\n angleBoxMaxUpper = recalculateAngle(\n xBoxMaxUpper, yBoxMaxUpper, angleBoxMaxUpper);\n\n angleBoxMinUpper = recalculateAngle(\n xBoxMinUpper, yBoxMinUpper, angleBoxMinUpper);\n\n angleBoxMaxLower = recalculateAngle(\n xBoxMaxLower, yBoxMaxLower, angleBoxMaxLower);\n\n \/\/ Combine all angles for the box points.\n std::array angles = {\n angleBoxMinLower, angleBoxMaxUpper,\n angleBoxMinUpper, angleBoxMaxLower\n };\n\n if (isSpecial)\n {\n \/\/ It finds to angles.\n \/\/ Maximum angle in the first quater\n \/\/ and the minimun angle in the fouth quater.\n float angleMaxFirstQuater = 0.0f;\n float angleMinFourthQuater = 360.0f;\n\n for (auto const & item : angles)\n {\n if (item < 90.0f)\n {\n if (angleMaxFirstQuater < item)\n {\n angleMaxFirstQuater = item;\n }\n }\n else if (item > 270.0f)\n {\n if (angleMinFourthQuater > item)\n {\n angleMinFourthQuater = item;\n }\n }\n }\n\n \/\/ Compare the ray angle with\n \/\/ the max angle in the first quater\n \/\/ and the min angle in the fouth quater.\n if (angleRay <= angleMaxFirstQuater &&\n angleRay >= angleMinFourthQuater) {\n return true;\n }\n }\n else\n {\n \/\/ Find a min and max angles for the box points.\n auto result = std::minmax_element(\n std::begin(angles), std::end(angles));\n\n \/\/ Compare the ray angle with the min\n \/\/ and max angles for the box points.\n if (*result.first <= angleRay &&\n angleRay <= *result.second) {\n return true;\n }\n }\n\n return false;\n}\n\nfloat Ray::convertRadianToDegrees(float const & angle)\n{\n return angle \/ Constants::PI * 180;\n}\n\nfloat Ray::recalculateAngle(float const & x,\n float const & y,\n float const & angle)\n{\n float correctedAngle = 0.0f;\n\n \/\/ The second quarter.\n if (y > (0.0f - Constants::kEps) &&\n x < (0.0f + Constants::kEps))\n {\n correctedAngle = 180.0f - abs(angle);\n }\n\n \/\/ The third quarter.\n if (y < 0.0f &&\n x < (0.0f + Constants::kEps))\n {\n correctedAngle = 180.0f + abs(angle);\n }\n\n \/\/ The fouth quarter.\n if (y < 0.0f &&\n x > 0.0f)\n {\n correctedAngle = 360.0f - abs(angle);\n }\n\n return correctedAngle;\n}\n\nfloat Ray::checkZeroDenominator(float const & value)\n{\n float tmp = value;\n\n if (abs(tmp) < Constants::kEps)\n {\n tmp = Constants::kEps;\n }\n\n return tmp;\n}\n\nvoid Ray::setOrigin(const Point2D & origin)\n{\n m_origin = origin;\n}\n\nvoid Ray::setDirection(const Point2D & direction)\n{\n m_direction = direction;\n}\n\nstd::ostream & operator <<(std::ostream & os,\n Ray const & rhs)\n{\n os << \"origin: \" << rhs.origin() << \"; \"\n << \"direction: \" << rhs.direction() << std::endl;\n return os;\n}\n<|endoftext|>"} {"text":"#include \"mainwindow\/mainWindow.h\"\n#include \"thirdparty\/windowsmodernstyle.h\"\n\n#include \n#include \n\nusing namespace qReal;\n\nint main(int argc, char *argv[])\n{\n\tint ERROR = trololo;\n\n\tQApplication app(argc, argv);\n\n\tQTranslator appTranslator;\n\tif (app.arguments().count() <= 1 || app.arguments().at(1) != \"--no-locale\") {\n\t\tappTranslator.load(\":\/qrgui_\" + QLocale::system().name());\n\t\tapp.installTranslator(&appTranslator);\n\t}\n\n#ifndef NO_STYLE_WINDOWSMODERN\n\tapp.setStyle(new WindowsModernStyle());\n#endif\n\n\tMainWindow window;\n\tif (window.isVisible())\n\t\treturn app.exec();\n\telse \/\/ The window decided to not show itself, exiting now.\n\t\treturn 0;\n}\njenins fail test fixed#include \"mainwindow\/mainWindow.h\"\n#include \"thirdparty\/windowsmodernstyle.h\"\n\n#include \n#include \n\nusing namespace qReal;\n\nint main(int argc, char *argv[])\n{\n\tQApplication app(argc, argv);\n\n\tQTranslator appTranslator;\n\tif (app.arguments().count() <= 1 || app.arguments().at(1) != \"--no-locale\") {\n\t\tappTranslator.load(\":\/qrgui_\" + QLocale::system().name());\n\t\tapp.installTranslator(&appTranslator);\n\t}\n\n#ifndef NO_STYLE_WINDOWSMODERN\n\tapp.setStyle(new WindowsModernStyle());\n#endif\n\n\tMainWindow window;\n\tif (window.isVisible())\n\t\treturn app.exec();\n\telse \/\/ The window decided to not show itself, exiting now.\n\t\treturn 0;\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\/\r\n\/* *\/\r\n\/* *\/\r\n\/* (c) Copyright 2001 by *\/\r\n\/* SINTEF, Oslo, Norway *\/\r\n\/* All rights reserved. See the copyright.h for more details. *\/\r\n\/* *\/\r\n\/*****************************************************************************\/\r\n\r\n#include \"copyright.h\"\r\n\r\n\/*\r\n *\r\n * $$\r\n *\r\n *\/\r\n#define S1518\r\n\r\n#include \"sislP.h\"\r\n\r\n\f\r\n#if defined(SISLNEEDPROTOTYPES)\r\nvoid \r\ns1518(SISLSurf *surf, double point[], double dir[], double epsge,\r\n\t double start[], double end[], double parin[], double parout[],\r\n\t int *stat)\r\n#else\r\nvoid s1518(surf, point, dir, epsge, start, end, parin, parout, stat)\r\n SISLSurf *surf;\r\n double point[];\r\n double dir[];\r\n double epsge;\r\n double start[];\r\n double end[];\r\n double parin[];\r\n double parout[];\r\n int *stat;\r\n#endif\r\n\/*\r\n*********************************************************************\r\n*\r\n*********************************************************************\r\n*\r\n* PURPOSE : Newton iteration on the intersection between\r\n* a 3D NURBS surface and a line.\r\n* If a good initial guess is given, the intersection will\r\n* be found quickly. However if a bad initial guess is given,\r\n* the iteration might not converge.\r\n* We only search in the rectangular subdomain specified\r\n* by \"start\" and \"end\". This can be the whole domain if desired.\r\n*\r\n*\r\n* INPUT : surf - The NURBS surface.\r\n* point - A point on the line.\r\n* dir - The vector direction of the line\r\n* (not necessarily normalized).\r\n* epsge - Geometric resolution.\r\n* start - Lower limits of search rectangle (umin, vmin).\r\n* end - Upper limits of search rectangle (umax, vmax).\r\n* parin - Initial guess (u0,v0) for parameter point of\r\n* intersection (which should be inside the\r\n* search rectangle).\r\n*\r\n*\r\n*\r\n* OUTPUT : parout - Parameter point (u,v) of intersection.\r\n* jstat - status messages \r\n* = 1 : Intersection found.\r\n* < 0 : error.\r\n*\r\n*\r\n* METHOD : Newton iteration: we assume the surface is close to\r\n* the tangent plane through the current estimate s(u_0,v_0)\r\n* and use the intersection of the line with that (parametric)\r\n* plane to make the next estimate (u_1,v_1).\r\n*\r\n*\r\n* REFERENCES :\r\n*\r\n*\r\n* WRITTEN BY : Michael Floater, SINTEF Oslo, September 2001.\r\n*\r\n*********************************************************************\r\n*\/ \r\n{ \r\n int i,j; \/* For loops. *\/\r\n int kstat = 0; \/* Local status variable. *\/\r\n int kpos = 0; \/* Error indicator. *\/\r\n int num_its = 30; \/* Max number of Newton iterations allowed. *\/\r\n double norm1[3]; \/* 1st vector normal to dir. *\/\r\n double norm2[3]; \/* 2nd vector normal to dir. *\/\r\n int kleft1=0; \/* Index of knot interval. *\/\r\n int kleft2=0; \/* Index of knot interval. *\/\r\n int nder=1; \/* evaluate up to derivs of order 1. *\/\r\n double parpoint[3]; \/* current parameter point. *\/\r\n double der[9]; \/* surface position and two partial derivatives. *\/\r\n double norm[3]; \/* surface normal. *\/\r\n double a11,a12,a21,a22; \/* Elements of matrix A. *\/\r\n double b1,b2; \/* Elements of column vector b. *\/\r\n double det; \/* Determinant of A. *\/\r\n double du,dv; \/* Increment in parameter point. *\/\r\n double su[3],sv[3]; \/* two partial derivatives of surface. *\/\r\n double pminuss[3]; \/* p - s. *\/\r\n double epsge2; \/* square of epsge. *\/\r\n\r\n if(surf->idim != 3) goto error;\r\n if(start[0] < surf->et1[surf->ik1 - 1]) goto error;\r\n if(end[0] > surf->et1[surf->in1]) goto error;\r\n if(start[1] < surf->et2[surf->ik2 - 1]) goto error;\r\n if(end[1] > surf->et2[surf->in2]) goto error;\r\n if(parin[0] < start[0] || parin[0] > end[0]) goto error;\r\n if(parin[1] < start[1] || parin[1] > end[1]) goto error;\r\n\r\n \/* Represent line as intersection of two planes, i.e. find\r\n two vectors norm1 and norm2 of length one,\r\n perpendicular to the line. *\/\r\n\r\n s6twonorm(dir,norm1,norm2,&kstat);\r\n if(kstat < 0) goto error;\r\n\r\n printf(\"norm1 = %lf %lf %lf\\n\",norm1[0],norm1[1],norm1[2]);\r\n printf(\"norm2 = %lf %lf %lf\\n\",norm2[0],norm2[1],norm2[2]);\r\n\r\n epsge2 = epsge * epsge;\r\n\r\n parpoint[0] = parin[0];\r\n parpoint[1] = parin[1];\r\n\r\n printf(\"parpoint = %lf %lf\\n\",parpoint[0],parpoint[1]);\r\n\r\n for(i=0; i< num_its; i++)\r\n {\r\n \/* Evaluate position and 1st derivatives of surface *\/\r\n \r\n s1421(surf,nder,parpoint,&kleft1,&kleft2,der,norm,&kstat);\r\n if (kstat < 0) goto error;\r\n\r\n printf(\"pos = %lf %lf %lf\\n\",der[0],der[1],der[2]);\r\n printf(\"s_u = %lf %lf %lf\\n\",der[3],der[4],der[5]);\r\n printf(\"s_v = %lf %lf %lf\\n\",der[6],der[7],der[8]);\r\n printf(\"norm = %lf %lf %lf\\n\",norm[0],norm[1],norm[2]);\r\n \r\n \/* We assume that s(u,v) is close to the\r\n parametric plane s(u_0,v_0) + (u-u_0) * s_u + (v-v_0) * s_v,\r\n i.e. the tangent plane to s at (u_0,v_0).\r\n We then find (u_1,v_1) where this plane intersects the\r\n given straight line. We have represented the line as\r\n those points x in 3D such that\r\n \r\n (x - p) . n1 = 0 (1)\r\n (x - p) . n2 = 0 (2)\r\n \r\n where p is \"point\" and n1 = \"norm1\", \"n2 = norm2\".\r\n Thus we solve\r\n \r\n (s(u_0,v_0) + (u_1-u_0) * s_u + (v_1-v_0) * s_v - p) . n1 = 0 (3)\r\n (s(u_0,v_0) + (u_1-u_0) * s_u + (v_1-v_0) * s_v - p) . n2 = 0 (4)\r\n \r\n which is a 2*2 linear system in the unknowns u_1,v_1.\r\n This can be written as\r\n \r\n A u = b\r\n \r\n where A = | s_u . n1 s_v . n1 | b = | (p - s) . n1 |\r\n | s_u . n2 s_v . n2 | | (p - s) . n2 |\r\n \r\n and u = | du |\r\n | dv |\r\n \r\n and where du = u_1 - u_0, dv = v_1 - v_0.\r\n We solve the system for du, dv and find u_1 and v_1 afterwards.\r\n\r\n Note that the distance of the point s(u0,v0) to\r\n the line is precisely the Euclidean norm of the\r\n right hand side b. Thus if this is within the\r\n geometric tolerance, we can stop iterating.\r\n *\/\r\n\r\n for(j=0; j<3; j++)\r\n {\r\n su[j] = der[j+3];\r\n sv[j] = der[j+6];\r\n pminuss[j] = point[j] - der[j];\r\n }\r\n \r\n b1 = s6scpr(pminuss,norm1,3);\r\n b2 = s6scpr(pminuss,norm2,3);\r\n\r\n if(b1 * b1 + b2 * b2 <= epsge2) break;\r\n\r\n a11 = s6scpr(su,norm1,3);\r\n a12 = s6scpr(sv,norm1,3);\r\n a21 = s6scpr(su,norm2,3);\r\n a22 = s6scpr(sv,norm2,3);\r\n \r\n det = a11 * a22 - a21 * a12;\r\n du = (b1 * a22 - b2 * a12) \/ det;\r\n dv = (a11 * b2 - a21 * b1) \/ det;\r\n \r\n \/* Having now found the increments du,dv, update\r\n the current parameter point. *\/\r\n \r\n parpoint[0] += du; \/* u1 = u0 + du; *\/\r\n parpoint[1] += dv; \/* v1 = v0 + dv; *\/\r\n\r\n printf(\"parpoint = %lf %lf\\n\",parpoint[0],parpoint[1]);\r\n\r\n if(surf->cuopen_1 == 1)\r\n {\r\n if(parpoint[0] < start[0]) parpoint[0] = start[0];\r\n if(parpoint[0] > end[0]) parpoint[0] = end[0];\r\n }\r\n else \/\/ closed in u direction\r\n {\r\n if(parpoint[0] < start[0]) parpoint[0] = end[0];\r\n if(parpoint[0] > end[0]) parpoint[0] = start[0];\r\n }\r\n\r\n if(surf->cuopen_2 == 1)\r\n {\r\n if(parpoint[1] < start[1]) parpoint[1] = start[1];\r\n if(parpoint[1] > end[1]) parpoint[1] = end[1];\r\n }\r\n else \/\/ closed in v direction\r\n {\r\n if(parpoint[1] < start[1]) parpoint[1] = end[1];\r\n if(parpoint[1] > end[1]) parpoint[1] = start[1];\r\n }\r\n\r\n }\r\n\r\n parout[0] = parpoint[0];\r\n parout[1] = parpoint[1];\r\n\r\n printf(\"parout = %lf %lf\\n\\n\",parout[0],parout[1]);\r\n\r\n goto out;\r\n\r\n \/* Error in lower level routine. *\/\r\n\r\n error :\r\n *stat = kstat;\r\n s6err(\"s1518\", *stat, kpos);\r\n goto out;\r\n\r\n out: \r\n\r\n return;\r\n}\r\n\r\nRenamed to s1518.c (since it really is c, not c++).<|endoftext|>"} {"text":"\/************************************************************************************\n * Author: Hunter Jones\n * Date: 04\/23\/2017\n * File Name: ush.cpp\n * Purpose: ush is a lightweight command line shell utility for unix, the entire\n * program is contained in this source file. It acts as a minimalistic alternative\n * to shells like bash, zsh, sh and so on.\n * Notes: This C++ file uses features from the C++11 standard, attempting to compile\n * against the C++98 libraries will certainly fail. On some older systems, the\n * C++11 standard is referred to as c++0x.\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/BSD Libedit\n#include \n\/\/Different paths on BSD and Linux\n#if defined __FreeBSD__ || defined __NetBSD__ || defined __OpenBSD__\n#include \n#else\n#include \n#endif\n\nusing namespace std;\n\nstring userPrompt = \"ush-> \"; \/\/command line prompt, PS1 to use unix terms\nvoid printPrompt();\nvoid setPath(vector& answer);\nvector findCommand();\nbool fileExists(string filename);\n\n\n\nint main(int argc, char** argv) {\n \/**\n * Main function consists entirely of an infinite while loop. The loop consists of\n * three distinct subroutines (i could have refactored them into seperate functions\n * but decided that this was more readable). The first subroutine is to search the $PATH\n * for a program that matches the user specified command. The second is to combine this\n * generated path to the executable with the args specified by the user. Lastly, the shell\n * forks off a process which runs the program with the specified args.\n *\/\n while(1) { \/\/Main loop begin\n \/\/Initializer Area\n string current{}; \/\/holds the string just recieved from user input\n vector tokenized;\n char* userArgs[100] = {NULL}; \/\/array contains the 'argv' of the program to be run\n\n \/\/Search $PATH for a program matching users selection\n try{\n tokenized = findCommand();\n }\n catch(const char* msg) {\n cerr << msg << endl;\n continue; \/\/so that the user is able to continue using the command line after a bad input.\n }\n \n for(unsigned int i = 0; i < tokenized.size() && i < 100; i++) {\n userArgs[i] = (char*)tokenized.at(i).c_str();\n }\n\n \/\/Forking off to run program\n pid_t pid = fork();\n if(pid > 0) { \/\/Parent runs this\n int statusnum;\n waitpid(pid, &statusnum, 0);\n }\n else { \/\/child runs this\n execv(userArgs[0], userArgs); \/\/execute the program\n exit(-1); \/\/if child reached this something is really amiss.\n }\n } \/\/end of main loop\n return 0;\n} \/\/End main\n\nvoid printPrompt() {\n \/**\n * Simply prints the command line prompt to console, could have\n * just used a variable, but left open for possible setPrompt\n *\/\n cout << userPrompt;\n}\n\nvoid setPath(vector& answer) {\n \/**\n * Converts PATH from a single string to a tokenized vector via ':' delimeter\n *\/\n string current{};\n stringstream x{getenv(\"PATH\")}; \/\/User binary path\n while(x) {\n getline(x,current,':');\n answer.push_back(string{current});\n }\n}\n\nstring getLineRead() {\n \/\/Uses editline lib\n static char *linebuff = (char *)NULL;\n if(linebuff) {\n free(linebuff);\n linebuff = (char*) NULL;\n }\n linebuff = readline(userPrompt.c_str());\n return string{linebuff};\n}\n\nvector findCommand() {\n \/**\n * Takes users command input, and finds the appropriate executable file to run.\n * Working directory (if program starts with .\/), $PATH variable, and missing files\n * are all taken into account\n *\/\n \/\/Initializers\n string userInput = getLineRead();;\n vector tokenized{};\n vector path;\n unsigned int wordStart{0};\n\n \/\/Tokenize the line into a vector of args\n for(unsigned int i = 0; i < userInput.length(); i++) {\n if(userInput.at(i) == ' ') {\n tokenized.push_back(userInput.substr(wordStart,i-wordStart));\n wordStart = i+1;\n }\n }\n tokenized.push_back(userInput.substr(wordStart,userInput.length()));\n\n \/\/Check for builtin commands, should probably be refactored out later\n if(tokenized.at(0) == \"exit\") \/\/Exit command input by user\n exit(0);\n if((tokenized.at(0).substr(0,2) == \".\/\") && (fileExists(tokenized.at(0)))) \/\/Command is selected from current dir\n return tokenized;\n if(tokenized.at(0) == \"cd\") { \/\/has to be implemented in shell, no external commands for it.\n if(chdir(tokenized.at(1).c_str()))\n throw \"Error: file not found\";\n return tokenized;\n }\n\n \/\/Search the path for the command and retrieve its full path\n setPath(path);\n for(string x : path) { \/\/Iterate through the path looking for matching files\n if(fileExists(x + \"\/\" + tokenized.at(0))) {\n tokenized.at(0) = x + \"\/\" + tokenized.at(0);\n return tokenized;\n }\n }\n throw \"Error: File not found\"; \/\/No matches found\n} \/\/End findCommand\n\nbool fileExists(string filename) {\n \/**\n * Checks if the specified file exists, and returns the result of said test\n * as a boolean. Pretty standard really.\n *\/\n if(fopen(filename.c_str(),\"r\") == 0)\n return false;\n else\n return true;\n}\ncommand line arg validation\/************************************************************************************\n * Author: Hunter Jones\n * Date: 04\/23\/2017\n * File Name: ush.cpp\n * Purpose: ush is a lightweight command line shell utility for unix, the entire\n * program is contained in this source file. It acts as a minimalistic alternative\n * to shells like bash, zsh, sh and so on.\n * Notes: This C++ file uses features from the C++11 standard, attempting to compile\n * against the C++98 libraries will certainly fail. On some older systems, the\n * C++11 standard is referred to as c++0x.\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/BSD Libedit\n#include \n\/\/Different paths on BSD and Linux\n#if defined __FreeBSD__ || defined __NetBSD__ || defined __OpenBSD__\n#include \n#else\n#include \n#endif\n\nusing namespace std;\n\nstring userPrompt = \"ush-> \"; \/\/command line prompt, PS1 to use unix terms\nvoid printPrompt();\nvoid setPath(vector& answer);\nvector findCommand();\nbool fileExists(string filename);\n\n\n\nint main(int argc, char** argv) {\n \/**\n * Main function consists entirely of an infinite while loop. The loop consists of\n * three distinct subroutines (i could have refactored them into seperate functions\n * but decided that this was more readable). The first subroutine is to search the $PATH\n * for a program that matches the user specified command. The second is to combine this\n * generated path to the executable with the args specified by the user. Lastly, the shell\n * forks off a process which runs the program with the specified args.\n *\/\n\n if(argc > 1) {\n cerr << \"Usage: \" << argv[0] << endl;\n return EXIT_FAILURE;\n }\n while(1) { \/\/Main loop begin\n \/\/Initializer Area\n string current{}; \/\/holds the string just recieved from user input\n vector tokenized;\n char* userArgs[100] = {NULL}; \/\/array contains the 'argv' of the program to be run\n\n \/\/Search $PATH for a program matching users selection\n try{\n tokenized = findCommand();\n }\n catch(const char* msg) {\n cerr << msg << endl;\n continue; \/\/so that the user is able to continue using the command line after a bad input.\n }\n \n for(unsigned int i = 0; i < tokenized.size() && i < 100; i++) {\n userArgs[i] = (char*)tokenized.at(i).c_str();\n }\n\n \/\/Forking off to run program\n pid_t pid = fork();\n if(pid > 0) { \/\/Parent runs this\n int statusnum;\n waitpid(pid, &statusnum, 0);\n }\n else { \/\/child runs this\n execv(userArgs[0], userArgs); \/\/execute the program\n exit(-1); \/\/if child reached this something is really amiss.\n }\n } \/\/end of main loop\n return 0;\n} \/\/End main\n\nvoid printPrompt() {\n \/**\n * Simply prints the command line prompt to console, could have\n * just used a variable, but left open for possible setPrompt\n *\/\n cout << userPrompt;\n}\n\nvoid setPath(vector& answer) {\n \/**\n * Converts PATH from a single string to a tokenized vector via ':' delimeter\n *\/\n string current{};\n stringstream x{getenv(\"PATH\")}; \/\/User binary path\n while(x) {\n getline(x,current,':');\n answer.push_back(string{current});\n }\n}\n\nstring getLineRead() {\n \/\/Uses editline lib\n static char *linebuff = (char *)NULL;\n if(linebuff) {\n free(linebuff);\n linebuff = (char*) NULL;\n }\n linebuff = readline(userPrompt.c_str());\n return string{linebuff};\n}\n\nvector findCommand() {\n \/**\n * Takes users command input, and finds the appropriate executable file to run.\n * Working directory (if program starts with .\/), $PATH variable, and missing files\n * are all taken into account\n *\/\n \/\/Initializers\n string userInput = getLineRead();;\n vector tokenized{};\n vector path;\n unsigned int wordStart{0};\n\n \/\/Tokenize the line into a vector of args\n for(unsigned int i = 0; i < userInput.length(); i++) {\n if(userInput.at(i) == ' ') {\n tokenized.push_back(userInput.substr(wordStart,i-wordStart));\n wordStart = i+1;\n }\n }\n tokenized.push_back(userInput.substr(wordStart,userInput.length()));\n\n \/\/Check for builtin commands, should probably be refactored out later\n if(tokenized.at(0) == \"exit\") \/\/Exit command input by user\n exit(0);\n if((tokenized.at(0).substr(0,2) == \".\/\") && (fileExists(tokenized.at(0)))) \/\/Command is selected from current dir\n return tokenized;\n if(tokenized.at(0) == \"cd\") { \/\/has to be implemented in shell, no external commands for it.\n if(chdir(tokenized.at(1).c_str()))\n throw \"Error: file not found\";\n return tokenized;\n }\n\n \/\/Search the path for the command and retrieve its full path\n setPath(path);\n for(string x : path) { \/\/Iterate through the path looking for matching files\n if(fileExists(x + \"\/\" + tokenized.at(0))) {\n tokenized.at(0) = x + \"\/\" + tokenized.at(0);\n return tokenized;\n }\n }\n throw \"Error: File not found\"; \/\/No matches found\n} \/\/End findCommand\n\nbool fileExists(string filename) {\n \/**\n * Checks if the specified file exists, and returns the result of said test\n * as a boolean. Pretty standard really.\n *\/\n if(fopen(filename.c_str(),\"r\") == 0)\n return false;\n else\n return true;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"vast\/aliases.h\"\n#include \"vast\/announce.h\"\n#include \"vast\/banner.h\"\n#include \"vast\/filesystem.h\"\n#include \"vast\/logger.h\"\n#include \"vast\/uuid.h\"\n#include \"vast\/actor\/accountant.h\"\n#include \"vast\/actor\/atoms.h\"\n#include \"vast\/actor\/exit.h\"\n#include \"vast\/actor\/sink\/spawn.h\"\n#include \"vast\/actor\/source\/spawn.h\"\n#include \"vast\/concept\/printable\/to_string.h\"\n#include \"vast\/concept\/printable\/vast\/error.h\"\n#include \"vast\/concept\/printable\/vast\/uuid.h\"\n#include \"vast\/detail\/adjust_resource_consumption.h\"\n#include \"vast\/util\/endpoint.h\"\n#include \"vast\/util\/string.h\"\n\nusing namespace vast;\nusing namespace std::string_literals;\n\nint main(int argc, char *argv[])\n{\n if (! detail::adjust_resource_consumption())\n return 1;\n caf::set_scheduler<>(2, -1);\n std::vector commands = {\n \"connect\",\n \"disconnect\",\n \"export\",\n \"import\",\n \"quit\",\n \"peer\",\n \"send\",\n \"show\",\n \"spawn\",\n \"stop\"\n };\n std::vector command_line(argv + 1, argv + argc);\n auto cmd = std::find_first_of(command_line.begin(), command_line.end(),\n commands.begin(), commands.end());\n \/\/ Parse and validate command line.\n auto log_level = 3;\n auto dir = \".\"s;\n auto endpoint = \"\"s;\n auto host = \"127.0.0.1\"s;\n auto port = uint16_t{42000};\n auto r = caf::message_builder(command_line.begin(), cmd).extract_opts({\n {\"dir,d\", \"directory for logs and client state\", dir},\n {\"endpoint,e\", \"node endpoint\", endpoint},\n {\"log-level,l\", \"verbosity of console and\/or log file\", log_level},\n {\"version,v\", \"print version and exit\"}\n });\n if (! r.error.empty())\n {\n std::cerr << r.error << std::endl;\n return 1;\n }\n if (r.opts.count(\"version\") > 0)\n {\n std::cout << VAST_VERSION << std::endl;\n return 0;\n }\n if (r.opts.count(\"help\") > 0)\n {\n std::cout << banner() << \"\\n\\n\" << r.helptext;\n return 0;\n }\n if (r.opts.count(\"endpoint\") > 0\n && ! util::parse_endpoint(endpoint, host, port))\n {\n std::cout << \"invalid endpoint: \" << endpoint << std::endl;\n return 1;\n }\n if (! r.remainder.empty())\n {\n auto invalid_cmd = r.remainder.get_as(0);\n std::cerr << \"invalid command: \" << invalid_cmd << std::endl;\n return 1;\n }\n if (cmd == command_line.end())\n {\n std::cerr << \"missing command\" << std::endl;\n return 1;\n }\n \/\/ Initialize logger.\n auto colorized = true;\n auto verbosity = static_cast(log_level);\n if (! logger::console(verbosity, colorized))\n {\n std::cerr << \"failed to initialize logger console backend\" << std::endl;\n return 1;\n }\n if (! logger::file(logger::quiet))\n {\n std::cerr << \"failed to reset logger file backend\" << std::endl;\n return 1;\n }\n \/\/ Establish connection to remote node.\n auto guard = caf::detail::make_scope_guard(\n [] { caf::shutdown(); logger::destruct(); }\n );\n announce_types();\n caf::actor node;\n try\n {\n VAST_VERBOSE(\"connecting to\", host << ':' << port);\n node = caf::io::remote_actor(host.c_str(), port);\n }\n catch (caf::network_error const& e)\n {\n VAST_ERROR(\"failed to connect to\", host << ':' << port);\n return 1;\n }\n \/\/ Process commands.\n caf::scoped_actor self;\n auto accounting_log = path(dir) \/ \"accounting.log\";\n if (*cmd == \"import\")\n {\n \/\/ 1. Spawn a SOURCE.\n caf::message_builder mb;\n auto i = cmd + 1;\n while (i != command_line.end())\n mb.append(*i++);\n auto src = source::spawn(mb.to_message());\n if (! src)\n {\n VAST_ERROR(\"failed to spawn source:\", src.error());\n return 1;\n }\n auto source_guard = caf::detail::make_scope_guard(\n [=] { anon_send_exit(*src, exit::kill); }\n );\n auto acc = self->spawn>(accounting_log);\n acc->link_to(*src);\n self->send(*src, put_atom::value, accountant_atom::value, acc);\n \/\/ 2. Find the next-best IMPORTER.\n caf::actor importer;\n self->sync_send(node, store_atom::value).await(\n [&](caf::actor const& store) {\n self->sync_send(store, list_atom::value, \"actors\").await(\n [&](std::map& m) {\n for (auto& p : m)\n \/\/ TODO: as opposed to taking the first importer available, it\n \/\/ could make sense to take the one which faces the least load.\n if (p.second.get_as(1) == \"importer\")\n {\n importer = p.second.get_as(0);\n return;\n }\n }\n );\n }\n );\n if (! importer)\n {\n VAST_ERROR(\"could not obtain importer from node\");\n return 1;\n }\n \/\/ 3. Connect SOURCE and IMPORTER.\n VAST_DEBUG(\"connecting source with remote importer\");\n auto msg = make_message(put_atom::value, sink_atom::value, importer);\n self->send(*src, std::move(msg));\n \/\/ 4. Run the SOURCE.\n VAST_DEBUG(\"running source\");\n self->send(*src, run_atom::value);\n source_guard.disable();\n }\n else if (*cmd == \"export\")\n {\n if (cmd + 1 == command_line.end())\n {\n VAST_ERROR(\"missing sink format\");\n return 1;\n }\n else if (cmd + 2 == command_line.end())\n {\n VAST_ERROR(\"missing query arguments\");\n return 1;\n }\n \/\/ 1. Spawn a SINK.\n auto snk = sink::spawn(caf::make_message(*(cmd + 1)));\n if (! snk)\n {\n VAST_ERROR(\"failed to spawn sink:\", snk.error());\n return 1;\n }\n auto acc = self->spawn>(accounting_log);\n acc->link_to(*snk);\n self->send(*snk, put_atom::value, accountant_atom::value, acc);\n auto sink_guard = caf::detail::make_scope_guard(\n [snk=*snk] { anon_send_exit(snk, exit::kill); }\n );\n \/\/ 2. Spawn an EXPORTER.\n caf::message_builder mb;\n auto label = \"exporter-\" + to_string(uuid::random()).substr(0, 7);\n mb.append(\"spawn\");\n mb.append(\"-l\");\n mb.append(label);\n mb.append(\"exporter\");\n auto i = cmd + 2;\n mb.append(*i++);\n while (i != command_line.end())\n mb.append(*i++);\n caf::actor exporter;\n self->sync_send(node, mb.to_message()).await(\n [&](caf::actor const& actor) {\n exporter = actor;\n },\n [&](error const& e) {\n VAST_ERROR(\"failed to spawn exporter:\", e);\n },\n caf::others >> [&] {\n VAST_ERROR(\"got unexpected message:\",\n caf::to_string(self->current_message()));\n }\n );\n if (! exporter)\n return 1;\n \/\/ 3. Connect EXPORTER with ARCHIVEs and INDEXes.\n VAST_DEBUG(\"retrieving topology to connect exporter with archive\/index\");\n self->sync_send(node, store_atom::value).await(\n [&](caf::actor const& store) {\n self->sync_send(store, list_atom::value, \"actors\").await(\n [&](std::map& m) {\n for (auto& p : m)\n if (p.second.get_as(1) == \"archive\")\n self->send(exporter, put_atom::value, archive_atom::value,\n p.second.get_as(0));\n else if (p.second.get_as(1) == \"index\")\n self->send(exporter, put_atom::value, index_atom::value,\n p.second.get_as(0));\n }\n );\n }\n );\n \/\/ 4. Connect EXPORTER with SINK.\n self->send(exporter, put_atom::value, sink_atom::value, *snk);\n \/\/ 5. Run the EXPORTER.\n VAST_DEBUG(\"running exporter\");\n self->send(exporter, stop_atom::value);\n self->send(exporter, run_atom::value);\n sink_guard.disable();\n }\n else\n {\n auto args = std::vector(cmd + 1, command_line.end());\n caf::message_builder mb;\n mb.append(*cmd);\n for (auto& a : args)\n mb.append(std::move(a));\n auto cmd_line = *cmd + util::join(args, \" \");\n auto exit_code = 0;\n self->sync_send(node, mb.to_message()).await(\n [&](ok_atom)\n {\n VAST_VERBOSE(\"successfully executed command:\", cmd_line);\n },\n [&](caf::actor const&)\n {\n VAST_VERBOSE(\"successfully executed command:\", cmd_line);\n },\n [&](std::string const& str)\n {\n VAST_VERBOSE(\"successfully executed command:\", cmd_line);\n std::cout << str << std::endl;\n },\n [&](error const& e)\n {\n VAST_ERROR(\"failed to execute command:\", cmd_line);\n VAST_ERROR(e);\n exit_code = 1;\n },\n caf::others >> [&]\n {\n auto msg = to_string(self->current_message());\n VAST_ERROR(\"got unexpected reply:\", msg);\n exit_code = 1;\n }\n );\n if (exit_code != 0)\n return exit_code;\n }\n self->await_all_other_actors_done();\n return 0;\n}\nSupport multiple importers (and exporters)#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"vast\/aliases.h\"\n#include \"vast\/announce.h\"\n#include \"vast\/banner.h\"\n#include \"vast\/filesystem.h\"\n#include \"vast\/logger.h\"\n#include \"vast\/uuid.h\"\n#include \"vast\/actor\/accountant.h\"\n#include \"vast\/actor\/atoms.h\"\n#include \"vast\/actor\/exit.h\"\n#include \"vast\/actor\/sink\/spawn.h\"\n#include \"vast\/actor\/source\/spawn.h\"\n#include \"vast\/concept\/printable\/to_string.h\"\n#include \"vast\/concept\/printable\/vast\/error.h\"\n#include \"vast\/concept\/printable\/vast\/uuid.h\"\n#include \"vast\/detail\/adjust_resource_consumption.h\"\n#include \"vast\/util\/endpoint.h\"\n#include \"vast\/util\/string.h\"\n\nusing namespace vast;\nusing namespace std::string_literals;\n\nint main(int argc, char *argv[])\n{\n if (! detail::adjust_resource_consumption())\n return 1;\n caf::set_scheduler<>(2, -1);\n std::vector commands = {\n \"connect\",\n \"disconnect\",\n \"export\",\n \"import\",\n \"quit\",\n \"peer\",\n \"send\",\n \"show\",\n \"spawn\",\n \"stop\"\n };\n std::vector command_line(argv + 1, argv + argc);\n auto cmd = std::find_first_of(command_line.begin(), command_line.end(),\n commands.begin(), commands.end());\n \/\/ Parse and validate command line.\n auto log_level = 3;\n auto dir = \".\"s;\n auto endpoint = \"\"s;\n auto host = \"127.0.0.1\"s;\n auto port = uint16_t{42000};\n auto r = caf::message_builder(command_line.begin(), cmd).extract_opts({\n {\"dir,d\", \"directory for logs and client state\", dir},\n {\"endpoint,e\", \"node endpoint\", endpoint},\n {\"log-level,l\", \"verbosity of console and\/or log file\", log_level},\n {\"version,v\", \"print version and exit\"}\n });\n if (! r.error.empty())\n {\n std::cerr << r.error << std::endl;\n return 1;\n }\n if (r.opts.count(\"version\") > 0)\n {\n std::cout << VAST_VERSION << std::endl;\n return 0;\n }\n if (r.opts.count(\"help\") > 0)\n {\n std::cout << banner() << \"\\n\\n\" << r.helptext;\n return 0;\n }\n if (r.opts.count(\"endpoint\") > 0\n && ! util::parse_endpoint(endpoint, host, port))\n {\n std::cout << \"invalid endpoint: \" << endpoint << std::endl;\n return 1;\n }\n if (! r.remainder.empty())\n {\n auto invalid_cmd = r.remainder.get_as(0);\n std::cerr << \"invalid command: \" << invalid_cmd << std::endl;\n return 1;\n }\n if (cmd == command_line.end())\n {\n std::cerr << \"missing command\" << std::endl;\n return 1;\n }\n \/\/ Initialize logger.\n auto colorized = true;\n auto verbosity = static_cast(log_level);\n if (! logger::console(verbosity, colorized))\n {\n std::cerr << \"failed to initialize logger console backend\" << std::endl;\n return 1;\n }\n if (! logger::file(logger::quiet))\n {\n std::cerr << \"failed to reset logger file backend\" << std::endl;\n return 1;\n }\n \/\/ Establish connection to remote node.\n auto guard = caf::detail::make_scope_guard(\n [] { caf::shutdown(); logger::destruct(); }\n );\n announce_types();\n caf::actor node;\n try\n {\n VAST_VERBOSE(\"connecting to\", host << ':' << port);\n node = caf::io::remote_actor(host.c_str(), port);\n }\n catch (caf::network_error const& e)\n {\n VAST_ERROR(\"failed to connect to\", host << ':' << port);\n return 1;\n }\n \/\/ Process commands.\n caf::scoped_actor self;\n auto accounting_log = path(dir) \/ \"accounting.log\";\n if (*cmd == \"import\")\n {\n \/\/ 1. Spawn a SOURCE.\n caf::message_builder mb;\n auto i = cmd + 1;\n while (i != command_line.end())\n mb.append(*i++);\n auto src = source::spawn(mb.to_message());\n if (! src)\n {\n VAST_ERROR(\"failed to spawn source:\", src.error());\n return 1;\n }\n auto source_guard = caf::detail::make_scope_guard(\n [=] { anon_send_exit(*src, exit::kill); }\n );\n auto acc = self->spawn>(accounting_log);\n acc->link_to(*src);\n self->send(*src, put_atom::value, accountant_atom::value, acc);\n \/\/ 2. Find all next-best IMPORTERs.\n std::vector importers;\n self->sync_send(node, store_atom::value).await(\n [&](caf::actor const& store) {\n self->sync_send(store, list_atom::value, \"actors\/\").await(\n [&](std::map& m) {\n for (auto& p : m)\n if (p.second.get_as(1) == \"importer\") {\n auto imp = p.second.get_as(0);\n if (imp != caf::invalid_actor)\n importers.push_back(imp);\n }\n }\n );\n }\n );\n if (importers.empty())\n {\n VAST_ERROR(\"no importers found\");\n return 1;\n }\n \/\/ 3. Connect SOURCE and IMPORTERs.\n for (auto& imp : importers)\n {\n \/\/VAST_ASSERT(imp != caf::invalid_actor);\n VAST_DEBUG(\"connecting source with importer\", imp);\n self->send(*src, put_atom::value, sink_atom::value, imp);\n }\n \/\/ 4. Run the SOURCE.\n VAST_DEBUG(\"running source\");\n self->send(*src, run_atom::value);\n source_guard.disable();\n }\n else if (*cmd == \"export\")\n {\n if (cmd + 1 == command_line.end())\n {\n VAST_ERROR(\"missing sink format\");\n return 1;\n }\n else if (cmd + 2 == command_line.end())\n {\n VAST_ERROR(\"missing query arguments\");\n return 1;\n }\n \/\/ 1. Spawn a SINK.\n auto snk = sink::spawn(caf::make_message(*(cmd + 1)));\n if (! snk)\n {\n VAST_ERROR(\"failed to spawn sink:\", snk.error());\n return 1;\n }\n auto acc = self->spawn>(accounting_log);\n acc->link_to(*snk);\n self->send(*snk, put_atom::value, accountant_atom::value, acc);\n auto sink_guard = caf::detail::make_scope_guard(\n [snk=*snk] { anon_send_exit(snk, exit::kill); }\n );\n \/\/ 2. Spawn an EXPORTER.\n caf::message_builder mb;\n auto label = \"exporter-\" + to_string(uuid::random()).substr(0, 7);\n mb.append(\"spawn\");\n mb.append(\"-l\");\n mb.append(label);\n mb.append(\"exporter\");\n auto i = cmd + 2;\n mb.append(*i++);\n while (i != command_line.end())\n mb.append(*i++);\n caf::actor exporter;\n self->sync_send(node, mb.to_message()).await(\n [&](caf::actor const& actor) {\n exporter = actor;\n },\n [&](error const& e) {\n VAST_ERROR(\"failed to spawn exporter:\", e);\n },\n caf::others >> [&] {\n VAST_ERROR(\"got unexpected message:\",\n caf::to_string(self->current_message()));\n }\n );\n if (! exporter)\n return 1;\n \/\/ 3. Connect EXPORTER with ARCHIVEs and INDEXes.\n std::vector archives;\n std::vector indexes;\n VAST_DEBUG(\"retrieving topology to connect exporter with archive\/index\");\n self->sync_send(node, store_atom::value).await(\n [&](caf::actor const& store) {\n self->sync_send(store, list_atom::value, \"actors\").await(\n [&](std::map& m) {\n for (auto& p : m)\n if (p.second.get_as(1) == \"archive\")\n archives.push_back(p.second.get_as(0));\n else if (p.second.get_as(1) == \"index\")\n indexes.push_back(p.second.get_as(0));\n }\n );\n }\n );\n if (archives.empty())\n {\n VAST_ERROR(\"no archives found\");\n return 1;\n }\n if (indexes.empty())\n {\n VAST_ERROR(\"no indexes found\");\n return 1;\n }\n for (auto& archive : archives)\n self->send(exporter, put_atom::value, archive_atom::value, archive);\n for (auto& index : indexes)\n self->send(exporter, put_atom::value, index_atom::value, index);\n \/\/ 4. Connect EXPORTER with SINK.\n self->send(exporter, put_atom::value, sink_atom::value, *snk);\n \/\/ 5. Run the EXPORTER.\n VAST_DEBUG(\"running exporter\");\n self->send(exporter, stop_atom::value);\n self->send(exporter, run_atom::value);\n sink_guard.disable();\n }\n else\n {\n auto args = std::vector(cmd + 1, command_line.end());\n caf::message_builder mb;\n mb.append(*cmd);\n for (auto& a : args)\n mb.append(std::move(a));\n auto cmd_line = *cmd + util::join(args, \" \");\n auto exit_code = 0;\n self->sync_send(node, mb.to_message()).await(\n [&](ok_atom)\n {\n VAST_VERBOSE(\"successfully executed command:\", cmd_line);\n },\n [&](caf::actor const&)\n {\n VAST_VERBOSE(\"successfully executed command:\", cmd_line);\n },\n [&](std::string const& str)\n {\n VAST_VERBOSE(\"successfully executed command:\", cmd_line);\n std::cout << str << std::endl;\n },\n [&](error const& e)\n {\n VAST_ERROR(\"failed to execute command:\", cmd_line);\n VAST_ERROR(e);\n exit_code = 1;\n },\n caf::others >> [&]\n {\n auto msg = to_string(self->current_message());\n VAST_ERROR(\"got unexpected reply:\", msg);\n exit_code = 1;\n }\n );\n if (exit_code != 0)\n return exit_code;\n }\n self->await_all_other_actors_done();\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * IceWM\n *\n * Copyright (C) 1998-2002 Marko Macek\n *\/\n#include \"config.h\"\n#include \"yapp.h\"\n\n#include \"ypoll.h\"\n#include \"ytimer.h\"\n#include \"yprefs.h\"\n\n#include \"sysdep.h\"\n\n#include \"intl.h\"\n\nextern char const *ApplicationName;\nchar const *&YApplication::Name = ApplicationName;\n\nYApplication *app = 0;\nstatic int signalPipe[2] = { 0, 0 };\nstatic sigset_t oldSignalMask;\nstatic sigset_t signalMask;\n\nvoid initSignals() {\n sigemptyset(&signalMask);\n sigaddset(&signalMask, SIGHUP);\n sigprocmask(SIG_BLOCK, &signalMask, &oldSignalMask);\n sigemptyset(&signalMask);\n sigprocmask(SIG_BLOCK, &signalMask, &oldSignalMask);\n\n if (pipe(signalPipe) != 0)\n die(2, _(\"Failed to create anonymous pipe (errno=%d).\"), errno);\n fcntl(signalPipe[1], F_SETFL, O_NONBLOCK);\n fcntl(signalPipe[0], F_SETFD, FD_CLOEXEC);\n fcntl(signalPipe[1], F_SETFD, FD_CLOEXEC);\n}\n\nconst char *YApplication::getPrivConfDir() {\n static char cfgdir[PATH_MAX] = \"\";\n \n if (*cfgdir == '\\0') {\n \tconst char *env = getenv(\"ICEWM_PRIVCFG\");\n\n\tif (NULL == env) {\n\t env = getenv(\"HOME\");\n\t strcpy(cfgdir, env ? env : \"\");\n\t strcat(cfgdir, \"\/.icewm\");\n\t} else {\n\t strcpy(cfgdir, env);\n\t}\n\t\n msg(\"using %s for private configuration files\", cfgdir);\n }\n \n return cfgdir;\n}\n\nchar *YApplication::findConfigFile(const char *name) {\n return findConfigFile(name, R_OK);\n}\n\nchar *YApplication::findConfigFile(const char *name, int mode) {\n char *p;\n\n if (name[0] == '\/')\n return newstr(name);\n\n p = strJoin(getPrivConfDir(), \"\/\", name, NULL);\n if (access(p, mode) == 0) return p;\n delete[] p;\n\n p = strJoin(configDir, \"\/\", name, NULL);\n if (access(p, mode) == 0) return p;\n delete[] p;\n\n p = strJoin(REDIR_ROOT(libDir), \"\/\", name, NULL);\n if (access(p, mode) == 0) return p;\n delete[] p;\n\n return 0;\n}\n\nYApplication::YApplication(int *argc, char ***argv) {\n app = this;\n fLoopLevel = 0;\n fExitApp = 0;\n fFirstTimer = fLastTimer = 0;\n fFirstPoll = fLastPoll = 0;\n\n {\n\tchar const * cmd(**argv);\n\tchar cwd[PATH_MAX + 1];\n\n\tif ('\/' == *cmd)\n\t fExecutable = newstr(cmd);\n\telse if (strchr (cmd, '\/'))\n\t fExecutable = strJoin(getcwd(cwd, sizeof(cwd)), \"\/\", cmd, NULL);\n\telse\n\t fExecutable = findPath(getenv(\"PATH\"), X_OK, cmd);\n }\n\n initSignals();\n#if 0\n struct sigaction sig;\n sig.sa_handler = SIG_IGN;\n sigemptyset(&sig.sa_mask);\n sig.sa_flags = 0;\n sigaction(SIGCHLD, &sig, &oldSignalCHLD);\n#endif\n}\n\nYApplication::~YApplication() {\n delete[] fExecutable;\n\n app = NULL;\n}\n\nvoid YApplication::registerTimer(YTimer *t) {\n t->fPrev = 0;\n t->fNext = fFirstTimer;\n if (fFirstTimer)\n fFirstTimer->fPrev = t;\n else\n fLastTimer = t;\n fFirstTimer = t;\n}\n\nvoid YApplication::unregisterTimer(YTimer *t) {\n if (t->fPrev)\n t->fPrev->fNext = t->fNext;\n else\n fFirstTimer = t->fNext;\n if (t->fNext)\n t->fNext->fPrev = t->fPrev;\n else\n fLastTimer = t->fPrev;\n t->fPrev = t->fNext = 0;\n}\n\nvoid YApplication::getTimeout(struct timeval *timeout) {\n YTimer *t;\n struct timeval curtime;\n bool fFirst = true;\n\n gettimeofday(&curtime, 0);\n timeout->tv_sec += curtime.tv_sec;\n timeout->tv_usec += curtime.tv_usec;\n while (timeout->tv_usec >= 1000000) {\n timeout->tv_usec -= 1000000;\n timeout->tv_sec++;\n }\n\n t = fFirstTimer;\n while (t) {\n if (t->isRunning() && (fFirst || timercmp(timeout, &t->timeout, >))) {\n *timeout = t->timeout;\n fFirst = false;\n }\n t = t->fNext;\n }\n if ((curtime.tv_sec == timeout->tv_sec &&\n curtime.tv_usec == timeout->tv_usec)\n || timercmp(&curtime, timeout, >))\n {\n timeout->tv_sec = 0;\n timeout->tv_usec = 1;\n } else {\n timeout->tv_sec -= curtime.tv_sec;\n timeout->tv_usec -= curtime.tv_usec;\n while (timeout->tv_usec < 0) {\n timeout->tv_usec += 1000000;\n timeout->tv_sec--;\n }\n }\n \/\/msg(\"set: %d %d\", timeout->tv_sec, timeout->tv_usec);\n PRECONDITION(timeout->tv_sec >= 0);\n PRECONDITION(timeout->tv_usec >= 0);\n}\n\nvoid YApplication::handleTimeouts() {\n YTimer *t, *n;\n struct timeval curtime;\n gettimeofday(&curtime, 0);\n\n t = fFirstTimer;\n while (t) {\n n = t->fNext;\n if (t->isRunning() && timercmp(&curtime, &t->timeout, >)) {\n YTimerListener *l = t->getTimerListener();\n t->stopTimer();\n if (l && l->handleTimer(t))\n t->startTimer();\n }\n t = n;\n }\n}\n\nvoid YApplication::registerPoll(YPoll *t) {\n PRECONDITION(t->fd != -1);\n t->fPrev = 0;\n t->fNext = fFirstPoll;\n if (fFirstPoll)\n fFirstPoll->fPrev = t;\n else\n fLastPoll = t;\n fFirstPoll = t;\n}\n\nvoid YApplication::unregisterPoll(YPoll *t) {\n if (t->fPrev)\n t->fPrev->fNext = t->fNext;\n else\n fFirstPoll = t->fNext;\n if (t->fNext)\n t->fNext->fPrev = t->fPrev;\n else\n fLastPoll = t->fPrev;\n t->fPrev = t->fNext = 0;\n}\n\nstruct timeval idletime;\n\nint YApplication::mainLoop() {\n fLoopLevel++;\n if (!fExitApp)\n fExitLoop = 0;\n\n gettimeofday(&idletime, 0);\n\n struct timeval timeout, *tp;\n\n while (!fExitApp && !fExitLoop) {\n if (handleXEvents()) {\n } else {\n int rc;\n fd_set read_fds;\n fd_set write_fds;\n\n handleIdle();\n gettimeofday(&idletime, 0);\n\n FD_ZERO(&read_fds);\n FD_ZERO(&write_fds);\n if (readFDCheckX() != -1)\n FD_SET(readFDCheckX(), &read_fds);\n if (signalPipe[0] != -1)\n FD_SET(signalPipe[0], &read_fds);\n\n#warning \"make this more general\"\n int IceSMfd = readFdCheckSM();\n if (IceSMfd != -1)\n FD_SET(IceSMfd, &read_fds);\n\n {\n for (YPoll *s = fFirstPoll; s; s = s->fNext) {\n PRECONDITION(s->fd != -1);\n if (s->forRead()) {\n FD_SET(s->fd, &read_fds);\n MSG((\"wait read\"));\n }\n if (s->forWrite()) {\n FD_SET(s->fd, &write_fds);\n MSG((\"wait connect\"));\n }\n }\n }\n\n timeout.tv_sec = 0;\n timeout.tv_usec = 0;\n getTimeout(&timeout);\n tp = 0;\n if (timeout.tv_sec != 0 || timeout.tv_usec != 0)\n tp = &timeout;\n else\n tp = 0;\n\n sigprocmask(SIG_UNBLOCK, &signalMask, NULL);\n\n rc = select(sizeof(fd_set),\n SELECT_TYPE_ARG234 &read_fds,\n SELECT_TYPE_ARG234 &write_fds,\n 0,\n tp);\n\n sigprocmask(SIG_BLOCK, &signalMask, NULL);\n#if 0\n sigset_t mask;\n sigpending(&mask);\n if (sigismember(&mask, SIGINT))\n handleSignal(SIGINT);\n if (sigismember(&mask, SIGTERM))\n handleSignal(SIGTERM);\n if (sigismember(&mask, SIGHUP))\n handleSignal(SIGHUP);\n#endif\n\n if (rc == 0) {\n handleTimeouts();\n } else if (rc == -1) {\n if (errno != EINTR)\n warn(_(\"Message Loop: select failed (errno=%d)\"), errno);\n } else {\n if (signalPipe[0] != -1) {\n if (FD_ISSET(signalPipe[0], &read_fds)) {\n unsigned char sig;\n if (read(signalPipe[0], &sig, 1) == 1) {\n handleSignal(sig);\n }\n }\n }\n {\n for (YPoll *s = fFirstPoll; s; s = s->fNext) {\n PRECONDITION(s->fd != -1);\n int fd = s->fd;\n if (FD_ISSET(fd, &read_fds)) {\n MSG((\"got read\"));\n s->notifyRead();\n }\n if (FD_ISSET(fd, &write_fds)) {\n MSG((\"got connect\"));\n s->notifyWrite();\n }\n }\n }\n if (IceSMfd != -1 && FD_ISSET(IceSMfd, &read_fds)) {\n readFdActionSM();\n }\n }\n }\n }\n fLoopLevel--;\n return fExitCode;\n}\n\nvoid YApplication::exitLoop(int exitCode) {\n fExitLoop = 1;\n fExitCode = exitCode;\n}\n\nvoid YApplication::exit(int exitCode) {\n fExitApp = 1;\n exitLoop(exitCode);\n}\n\nvoid YApplication::handleSignal(int sig) {\n if (sig == SIGCHLD) {\n int s, rc;\n do {\n rc = waitpid(-1, &s, WNOHANG);\n } while (rc > 0);\n }\n}\n\nvoid YApplication::handleIdle() {\n}\n\nvoid sig_handler(int sig) {\n unsigned char uc = sig;\n static const char *s = \"icewm: signal error\\n\";\n if (write(signalPipe[1], &uc, 1) != 1)\n write(2, s, strlen(s));\n}\n\nvoid YApplication::catchSignal(int sig) {\n sigaddset(&signalMask, sig);\n sigprocmask(SIG_BLOCK, &signalMask, NULL);\n\n struct sigaction sa;\n sa.sa_handler = sig_handler;\n sigemptyset(&sa.sa_mask);\n sa.sa_flags = 0;\n sigaction(sig, &sa, NULL);\n}\n\nvoid YApplication::resetSignals() {\n sigset_t mask;\n \/\/struct sigaction old_sig;\n\n \/\/sigaction(SIGCHLD, &oldSignalCHLD, &old_sig);\n sigprocmask(SIG_SETMASK, &oldSignalMask, &mask);\n}\n\nint YApplication::runProgram(const char *path, const char *const *args) {\n flushXEvents();\n\n int cpid = -1;\n if (path && (cpid = fork()) == 0) {\n app->resetSignals();\n sigemptyset(&signalMask);\n sigaddset(&signalMask, SIGHUP);\n sigprocmask(SIG_UNBLOCK, &signalMask, NULL);\n\n \/* perhaps the right thing to to:\n create ptys .. and show console window when an application\n attempts to use it (how do we detect input with no output?) *\/\n setsid();\n#if 0\n close(0);\n if (open(\"\/dev\/null\", O_RDONLY) != 0)\n _exit(1);\n#endif\n#if 1 \/* for now, some debugging code *\/\n {\n \/* close all files *\/\n\n int i, max = 1024;\n struct rlimit lim;\n\n if (getrlimit(RLIMIT_NOFILE, &lim) == 0)\n max = lim.rlim_max;\n\n for (i = 3; i < max; i++) {\n int fl;\n if (fcntl(i, F_GETFD, &fl) == 0) {\n if (!(fl & FD_CLOEXEC)) {\n warn(\"file descriptor still open: %d. \"\n \" Check \/proc\/$icewmpid\/fd\/%d when running next time. \"\n \"Please report a bug (perhaps not an icewm problem)!\", i, i);\n }\n }\n close (i);\n }\n }\n#endif\n\n if (args)\n execvp(path, (char **)args);\n else\n execlp(path, path, 0);\n\n _exit(99);\n }\n return cpid;\n}\n\nint YApplication::waitProgram(int p) {\n int status;\n\n if (p == -1)\n return -1;\n\n if (waitpid(p, &status, 0) != p)\n return -1;\n return status;\n}\n\nvoid YApplication::runCommand(const char *cmdline) {\n#warning calling \/bin\/sh is considered to be bloat\n char const * argv[] = { \"\/bin\/sh\", \"-c\", cmdline, NULL };\n runProgram(argv[0], argv);\n}\n\n#ifndef NO_CONFIGURE\nbool YApplication::loadConfig(struct cfoption *options, const char *name) {\n char *configFile = YApplication::findConfigFile(name);\n bool rc = false;\n if (configFile) {\n ::loadConfig(options, configFile);\n delete[] configFile;\n rc = true;\n }\n return rc;\n}\n#endif\nbuild fix\/*\n * IceWM\n *\n * Copyright (C) 1998-2002 Marko Macek\n *\/\n#include \"config.h\"\n#include \"yapp.h\"\n\n#include \"ypoll.h\"\n#include \"ytimer.h\"\n#include \"yprefs.h\"\n\n#include \"sysdep.h\"\n#include \"sys\/resource.h\"\n\n#include \"intl.h\"\n\nextern char const *ApplicationName;\nchar const *&YApplication::Name = ApplicationName;\n\nYApplication *app = 0;\nstatic int signalPipe[2] = { 0, 0 };\nstatic sigset_t oldSignalMask;\nstatic sigset_t signalMask;\n\nvoid initSignals() {\n sigemptyset(&signalMask);\n sigaddset(&signalMask, SIGHUP);\n sigprocmask(SIG_BLOCK, &signalMask, &oldSignalMask);\n sigemptyset(&signalMask);\n sigprocmask(SIG_BLOCK, &signalMask, &oldSignalMask);\n\n if (pipe(signalPipe) != 0)\n die(2, _(\"Failed to create anonymous pipe (errno=%d).\"), errno);\n fcntl(signalPipe[1], F_SETFL, O_NONBLOCK);\n fcntl(signalPipe[0], F_SETFD, FD_CLOEXEC);\n fcntl(signalPipe[1], F_SETFD, FD_CLOEXEC);\n}\n\nconst char *YApplication::getPrivConfDir() {\n static char cfgdir[PATH_MAX] = \"\";\n \n if (*cfgdir == '\\0') {\n \tconst char *env = getenv(\"ICEWM_PRIVCFG\");\n\n\tif (NULL == env) {\n\t env = getenv(\"HOME\");\n\t strcpy(cfgdir, env ? env : \"\");\n\t strcat(cfgdir, \"\/.icewm\");\n\t} else {\n\t strcpy(cfgdir, env);\n\t}\n\t\n msg(\"using %s for private configuration files\", cfgdir);\n }\n \n return cfgdir;\n}\n\nchar *YApplication::findConfigFile(const char *name) {\n return findConfigFile(name, R_OK);\n}\n\nchar *YApplication::findConfigFile(const char *name, int mode) {\n char *p;\n\n if (name[0] == '\/')\n return newstr(name);\n\n p = strJoin(getPrivConfDir(), \"\/\", name, NULL);\n if (access(p, mode) == 0) return p;\n delete[] p;\n\n p = strJoin(configDir, \"\/\", name, NULL);\n if (access(p, mode) == 0) return p;\n delete[] p;\n\n p = strJoin(REDIR_ROOT(libDir), \"\/\", name, NULL);\n if (access(p, mode) == 0) return p;\n delete[] p;\n\n return 0;\n}\n\nYApplication::YApplication(int *argc, char ***argv) {\n app = this;\n fLoopLevel = 0;\n fExitApp = 0;\n fFirstTimer = fLastTimer = 0;\n fFirstPoll = fLastPoll = 0;\n\n {\n\tchar const * cmd(**argv);\n\tchar cwd[PATH_MAX + 1];\n\n\tif ('\/' == *cmd)\n\t fExecutable = newstr(cmd);\n\telse if (strchr (cmd, '\/'))\n\t fExecutable = strJoin(getcwd(cwd, sizeof(cwd)), \"\/\", cmd, NULL);\n\telse\n\t fExecutable = findPath(getenv(\"PATH\"), X_OK, cmd);\n }\n\n initSignals();\n#if 0\n struct sigaction sig;\n sig.sa_handler = SIG_IGN;\n sigemptyset(&sig.sa_mask);\n sig.sa_flags = 0;\n sigaction(SIGCHLD, &sig, &oldSignalCHLD);\n#endif\n}\n\nYApplication::~YApplication() {\n delete[] fExecutable;\n\n app = NULL;\n}\n\nvoid YApplication::registerTimer(YTimer *t) {\n t->fPrev = 0;\n t->fNext = fFirstTimer;\n if (fFirstTimer)\n fFirstTimer->fPrev = t;\n else\n fLastTimer = t;\n fFirstTimer = t;\n}\n\nvoid YApplication::unregisterTimer(YTimer *t) {\n if (t->fPrev)\n t->fPrev->fNext = t->fNext;\n else\n fFirstTimer = t->fNext;\n if (t->fNext)\n t->fNext->fPrev = t->fPrev;\n else\n fLastTimer = t->fPrev;\n t->fPrev = t->fNext = 0;\n}\n\nvoid YApplication::getTimeout(struct timeval *timeout) {\n YTimer *t;\n struct timeval curtime;\n bool fFirst = true;\n\n gettimeofday(&curtime, 0);\n timeout->tv_sec += curtime.tv_sec;\n timeout->tv_usec += curtime.tv_usec;\n while (timeout->tv_usec >= 1000000) {\n timeout->tv_usec -= 1000000;\n timeout->tv_sec++;\n }\n\n t = fFirstTimer;\n while (t) {\n if (t->isRunning() && (fFirst || timercmp(timeout, &t->timeout, >))) {\n *timeout = t->timeout;\n fFirst = false;\n }\n t = t->fNext;\n }\n if ((curtime.tv_sec == timeout->tv_sec &&\n curtime.tv_usec == timeout->tv_usec)\n || timercmp(&curtime, timeout, >))\n {\n timeout->tv_sec = 0;\n timeout->tv_usec = 1;\n } else {\n timeout->tv_sec -= curtime.tv_sec;\n timeout->tv_usec -= curtime.tv_usec;\n while (timeout->tv_usec < 0) {\n timeout->tv_usec += 1000000;\n timeout->tv_sec--;\n }\n }\n \/\/msg(\"set: %d %d\", timeout->tv_sec, timeout->tv_usec);\n PRECONDITION(timeout->tv_sec >= 0);\n PRECONDITION(timeout->tv_usec >= 0);\n}\n\nvoid YApplication::handleTimeouts() {\n YTimer *t, *n;\n struct timeval curtime;\n gettimeofday(&curtime, 0);\n\n t = fFirstTimer;\n while (t) {\n n = t->fNext;\n if (t->isRunning() && timercmp(&curtime, &t->timeout, >)) {\n YTimerListener *l = t->getTimerListener();\n t->stopTimer();\n if (l && l->handleTimer(t))\n t->startTimer();\n }\n t = n;\n }\n}\n\nvoid YApplication::registerPoll(YPoll *t) {\n PRECONDITION(t->fd != -1);\n t->fPrev = 0;\n t->fNext = fFirstPoll;\n if (fFirstPoll)\n fFirstPoll->fPrev = t;\n else\n fLastPoll = t;\n fFirstPoll = t;\n}\n\nvoid YApplication::unregisterPoll(YPoll *t) {\n if (t->fPrev)\n t->fPrev->fNext = t->fNext;\n else\n fFirstPoll = t->fNext;\n if (t->fNext)\n t->fNext->fPrev = t->fPrev;\n else\n fLastPoll = t->fPrev;\n t->fPrev = t->fNext = 0;\n}\n\nstruct timeval idletime;\n\nint YApplication::mainLoop() {\n fLoopLevel++;\n if (!fExitApp)\n fExitLoop = 0;\n\n gettimeofday(&idletime, 0);\n\n struct timeval timeout, *tp;\n\n while (!fExitApp && !fExitLoop) {\n if (handleXEvents()) {\n } else {\n int rc;\n fd_set read_fds;\n fd_set write_fds;\n\n handleIdle();\n gettimeofday(&idletime, 0);\n\n FD_ZERO(&read_fds);\n FD_ZERO(&write_fds);\n if (readFDCheckX() != -1)\n FD_SET(readFDCheckX(), &read_fds);\n if (signalPipe[0] != -1)\n FD_SET(signalPipe[0], &read_fds);\n\n#warning \"make this more general\"\n int IceSMfd = readFdCheckSM();\n if (IceSMfd != -1)\n FD_SET(IceSMfd, &read_fds);\n\n {\n for (YPoll *s = fFirstPoll; s; s = s->fNext) {\n PRECONDITION(s->fd != -1);\n if (s->forRead()) {\n FD_SET(s->fd, &read_fds);\n MSG((\"wait read\"));\n }\n if (s->forWrite()) {\n FD_SET(s->fd, &write_fds);\n MSG((\"wait connect\"));\n }\n }\n }\n\n timeout.tv_sec = 0;\n timeout.tv_usec = 0;\n getTimeout(&timeout);\n tp = 0;\n if (timeout.tv_sec != 0 || timeout.tv_usec != 0)\n tp = &timeout;\n else\n tp = 0;\n\n sigprocmask(SIG_UNBLOCK, &signalMask, NULL);\n\n rc = select(sizeof(fd_set),\n SELECT_TYPE_ARG234 &read_fds,\n SELECT_TYPE_ARG234 &write_fds,\n 0,\n tp);\n\n sigprocmask(SIG_BLOCK, &signalMask, NULL);\n#if 0\n sigset_t mask;\n sigpending(&mask);\n if (sigismember(&mask, SIGINT))\n handleSignal(SIGINT);\n if (sigismember(&mask, SIGTERM))\n handleSignal(SIGTERM);\n if (sigismember(&mask, SIGHUP))\n handleSignal(SIGHUP);\n#endif\n\n if (rc == 0) {\n handleTimeouts();\n } else if (rc == -1) {\n if (errno != EINTR)\n warn(_(\"Message Loop: select failed (errno=%d)\"), errno);\n } else {\n if (signalPipe[0] != -1) {\n if (FD_ISSET(signalPipe[0], &read_fds)) {\n unsigned char sig;\n if (read(signalPipe[0], &sig, 1) == 1) {\n handleSignal(sig);\n }\n }\n }\n {\n for (YPoll *s = fFirstPoll; s; s = s->fNext) {\n PRECONDITION(s->fd != -1);\n int fd = s->fd;\n if (FD_ISSET(fd, &read_fds)) {\n MSG((\"got read\"));\n s->notifyRead();\n }\n if (FD_ISSET(fd, &write_fds)) {\n MSG((\"got connect\"));\n s->notifyWrite();\n }\n }\n }\n if (IceSMfd != -1 && FD_ISSET(IceSMfd, &read_fds)) {\n readFdActionSM();\n }\n }\n }\n }\n fLoopLevel--;\n return fExitCode;\n}\n\nvoid YApplication::exitLoop(int exitCode) {\n fExitLoop = 1;\n fExitCode = exitCode;\n}\n\nvoid YApplication::exit(int exitCode) {\n fExitApp = 1;\n exitLoop(exitCode);\n}\n\nvoid YApplication::handleSignal(int sig) {\n if (sig == SIGCHLD) {\n int s, rc;\n do {\n rc = waitpid(-1, &s, WNOHANG);\n } while (rc > 0);\n }\n}\n\nvoid YApplication::handleIdle() {\n}\n\nvoid sig_handler(int sig) {\n unsigned char uc = sig;\n static const char *s = \"icewm: signal error\\n\";\n if (write(signalPipe[1], &uc, 1) != 1)\n write(2, s, strlen(s));\n}\n\nvoid YApplication::catchSignal(int sig) {\n sigaddset(&signalMask, sig);\n sigprocmask(SIG_BLOCK, &signalMask, NULL);\n\n struct sigaction sa;\n sa.sa_handler = sig_handler;\n sigemptyset(&sa.sa_mask);\n sa.sa_flags = 0;\n sigaction(sig, &sa, NULL);\n}\n\nvoid YApplication::resetSignals() {\n sigset_t mask;\n \/\/struct sigaction old_sig;\n\n \/\/sigaction(SIGCHLD, &oldSignalCHLD, &old_sig);\n sigprocmask(SIG_SETMASK, &oldSignalMask, &mask);\n}\n\nint YApplication::runProgram(const char *path, const char *const *args) {\n flushXEvents();\n\n int cpid = -1;\n if (path && (cpid = fork()) == 0) {\n app->resetSignals();\n sigemptyset(&signalMask);\n sigaddset(&signalMask, SIGHUP);\n sigprocmask(SIG_UNBLOCK, &signalMask, NULL);\n\n \/* perhaps the right thing to to:\n create ptys .. and show console window when an application\n attempts to use it (how do we detect input with no output?) *\/\n setsid();\n#if 0\n close(0);\n if (open(\"\/dev\/null\", O_RDONLY) != 0)\n _exit(1);\n#endif\n#if 1 \/* for now, some debugging code *\/\n {\n \/* close all files *\/\n\n int i, max = 1024;\n struct rlimit lim;\n\n if (getrlimit(RLIMIT_NOFILE, &lim) == 0)\n max = lim.rlim_max;\n\n for (i = 3; i < max; i++) {\n int fl;\n if (fcntl(i, F_GETFD, &fl) == 0) {\n if (!(fl & FD_CLOEXEC)) {\n warn(\"file descriptor still open: %d. \"\n \" Check \/proc\/$icewmpid\/fd\/%d when running next time. \"\n \"Please report a bug (perhaps not an icewm problem)!\", i, i);\n }\n }\n close (i);\n }\n }\n#endif\n\n if (args)\n execvp(path, (char **)args);\n else\n execlp(path, path, 0);\n\n _exit(99);\n }\n return cpid;\n}\n\nint YApplication::waitProgram(int p) {\n int status;\n\n if (p == -1)\n return -1;\n\n if (waitpid(p, &status, 0) != p)\n return -1;\n return status;\n}\n\nvoid YApplication::runCommand(const char *cmdline) {\n#warning calling \/bin\/sh is considered to be bloat\n char const * argv[] = { \"\/bin\/sh\", \"-c\", cmdline, NULL };\n runProgram(argv[0], argv);\n}\n\n#ifndef NO_CONFIGURE\nbool YApplication::loadConfig(struct cfoption *options, const char *name) {\n char *configFile = YApplication::findConfigFile(name);\n bool rc = false;\n if (configFile) {\n ::loadConfig(options, configFile);\n delete[] configFile;\n rc = true;\n }\n return rc;\n}\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#pragma once\n\n#include \"core\/sstring.hh\"\n\n#include \n\nnamespace json {\n\ntemplate\ninline sstring to_json(const Map& map) {\n Json::Value root(Json::arrayValue);\n for (auto&& kv : map) {\n Json::Value obj_value(Json::objectValue);\n obj_value[kv.first] = Json::Value(kv.second);\n root.append(obj_value);\n }\n Json::FastWriter writer;\n return writer.write(root);\n}\n\ninline std::map to_map(const sstring& raw) {\n Json::Value root;\n Json::Reader reader;\n reader.parse(std::string{raw}, root);\n std::map map;\n for (Json::ArrayIndex idx = 0; idx < root.size(); idx++) {\n auto item = root[idx];\n for (auto&& member : item.getMemberNames()) {\n map.emplace(member, item[member].asString());\n }\n }\n return map;\n}\n\n}\njson: fix (de)serialization of map\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#pragma once\n\n#include \"core\/sstring.hh\"\n\n#include \n\nnamespace json {\n\ntemplate\ninline sstring to_json(const Map& map) {\n Json::Value root;\n for (auto&& kv : map) {\n root[kv.first] = Json::Value(kv.second);\n }\n Json::FastWriter writer;\n return writer.write(root);\n}\n\ninline std::map to_map(const sstring& raw) {\n Json::Value root;\n Json::Reader reader;\n reader.parse(std::string{raw}, root);\n std::map map;\n for (auto&& member : root.getMemberNames()) {\n map.emplace(member, root[member].asString());\n }\n return map;\n}\n\n}\n<|endoftext|>"} {"text":"\/* $Id: $ *\/\n\/* $Log$ *\/\n\n\/\/------------------------------------\n\/\/ Configuration macro example:\n\/\/\n\/\/ Do photon identification analysis with Generator data\n\/\/ Gamma in PHOS. For EMCAL clusters change \n\/\/ PHOS by EMCAL where necessary\n\/\/\n\/\/ Author : Gustavo Conesa Balbastre (INFN-LNF)\n\/\/------------------------------------\n\nAliAnaPartCorrMaker* ConfigAnalysis()\n{\n \/\/\n \/\/ Configuration goes here\n \/\/ \n printf(\"======================== \\n\");\n printf(\"ConfigAnalysis() \\n\");\n printf(\"======================== \\n\");\n \n \n \/\/Detector Fidutial Cuts\n AliFidutialCut * fidCut = new AliFidutialCut();\n fidCut->DoCTSFidutialCut(kTRUE) ;\n fidCut->DoEMCALFidutialCut(kTRUE) ;\n fidCut->DoPHOSFidutialCut(kTRUE) ;\n \n \/\/fidCut->SetSimpleCTSFidutialCut(0.9,0.,360.);\n \/\/fidCut->SetSimpleEMCALFidutialCut(0.7,80.,190.);\n \/\/fidCut->SetSimplePHOSFidutialCut(0.13,220.,320.);\n \n fidCut->Print(\"\");\n \n \/\/----------------------------------------------------------- \n \/\/ Reader\n \/\/-----------------------------------------------------------\n AliCaloTrackESDReader *reader = new AliCaloTrackESDReader();\n reader->SetDebug(-1);\n\n \/\/Switch on or off the detectors information that you want\n reader->SwitchOffEMCAL();\n reader->SwitchOffCTS();\n reader->SwitchOnPHOS();\n \n \/\/Min particle pT\n \/\/reader->SetEMCALPtMin(0.5); \n reader->SetPHOSPtMin(0.5);\n \/\/reader->SetCTSPtMin(0.2);\n reader->SwitchOnStack(); \/\/On by default, remember to SwitchOnMCData() in analysis classes\n \/\/In case of generating jet events (with PYTHIA), if pt hard bin is small\n \/\/reject events with large difference between ptHard and triggered jet\t\n \/\/reader->SetPtHardAndJetPtComparison(kTRUE);\n\t\n reader->SetFidutialCut(fidCut);\n\n \/\/Anaysis of final particles, not pi0\/eta etc.\n TArrayI statusArray(1) ;\n statusArray.SetAt(1,0); \n reader->AddStatusArray(statusArray) ;\n reader->SwitchOnStatusSelection() ;\n\n \/\/Keep pi0 in the list and not the 2 photon if decay angle is small.\n reader->SwitchOffOverlapCheck(); \t\n\t\n reader->Print(\"\");\n \n \n \/\/---------------------------------------------------------------------\n \/\/ Analysis algorithm\n \/\/---------------------------------------------------------------------\n \n \/\/Detector Fidutial Cuts for analysis part\n AliFidutialCut * fidCut2 = new AliFidutialCut();\n fidCut2->DoCTSFidutialCut(kFALSE) ;\n fidCut2->DoEMCALFidutialCut(kFALSE) ;\n fidCut2->DoPHOSFidutialCut(kFALSE) ;\n \n \/\/fidCut2->SetSimpleCTSFidutialCut(0.9,0.,360.);\n \/\/fidCut2->SetSimpleEMCALFidutialCut(0.7,80.,190.);\n \/\/fidCut2->SetSimplePHOSFidutialCut(0.13,220.,320.);\n\n fidCut2->Print(\"\");\n\n\n AliAnaPhoton *ana = new AliAnaPhoton();\n ana->SetDebug(-1);\n ana->SetMinPt(5.);\n ana->SetMinDistanceToBadChannel(2, 4, 5);\n ana->SetCaloPID(pid);\n ana->SetFidutialCut(fidCut2);\n ana->SetCalorimeter(\"PHOS\");\n ana->SwitchOnDataMC() ;\/\/Access MC stack and fill more histograms\n ana->SwitchOffCaloPID(); \/\/No need with MC reader\n ana->SwitchOffCaloPIDRecalculation(); \/\/recommended for EMCAL, no need with MC reader\n ana->SwitchOffTrackMatchRejection(); \/\/Only in use when OnCaloPID\n ana->SwitchOffFidutialCut();\n ana->SetOutputAODName(\"Photons\");\n ana->SetOutputAODClassName(\"AliAODPWG4Particle\");\n \/\/Set Histrograms bins and ranges\n\/\/\tana->SetHistoPtRangeAndNBins(0, 50, 100) ;\n\/\/\tana->SetHistoPhiRangeAndNBins(0, TMath::TwoPi(), 100) ;\n\/\/\tana->SetHistoEtaRangeAndNBins(-0.7, 0.7, 100) ;\n ana->Print(\"\");\n\n \/\/---------------------------------------------------------------------\n \/\/ Set analysis algorithm and reader\n \/\/---------------------------------------------------------------------\n maker = new AliAnaPartCorrMaker();\n maker->SetReader(reader);\/\/pointer to reader\n maker->AddAnalysis(ana,0);\n maker->SetAnaDebug(-1) ;\n maker->SwitchOnHistogramsMaker() ;\n maker->SwitchOnAODsMaker() ;\n \n maker->Print(\"\");\n \/\/\n printf(\"======================== \\n\");\n printf(\"END ConfigAnalysis() \\n\");\n printf(\"======================== \\n\");\n return maker ;\n}\nCorrect reader initialization to MCReader and remove line with setting PID\/* $Id: $ *\/\n\/* $Log$ *\/\n\n\/\/------------------------------------\n\/\/ Configuration macro example:\n\/\/\n\/\/ Do photon identification analysis with Generator data\n\/\/ Gamma in PHOS. For EMCAL clusters change \n\/\/ PHOS by EMCAL where necessary\n\/\/\n\/\/ Author : Gustavo Conesa Balbastre (INFN-LNF)\n\/\/------------------------------------\n\nAliAnaPartCorrMaker* ConfigAnalysis()\n{\n \/\/\n \/\/ Configuration goes here\n \/\/ \n printf(\"======================== \\n\");\n printf(\"ConfigAnalysis() \\n\");\n printf(\"======================== \\n\");\n \n \n \/\/Detector Fidutial Cuts\n AliFidutialCut * fidCut = new AliFidutialCut();\n fidCut->DoCTSFidutialCut(kTRUE) ;\n fidCut->DoEMCALFidutialCut(kTRUE) ;\n fidCut->DoPHOSFidutialCut(kTRUE) ;\n \n \/\/fidCut->SetSimpleCTSFidutialCut(0.9,0.,360.);\n \/\/fidCut->SetSimpleEMCALFidutialCut(0.7,80.,190.);\n \/\/fidCut->SetSimplePHOSFidutialCut(0.13,220.,320.);\n \n fidCut->Print(\"\");\n \n \/\/----------------------------------------------------------- \n \/\/ Reader\n \/\/-----------------------------------------------------------\n AliCaloTrackMCReader *reader = new AliCaloTrackMCReader();\n reader->SetDebug(-1);\n\n \/\/Switch on or off the detectors information that you want\n reader->SwitchOffEMCAL();\n reader->SwitchOffCTS();\n reader->SwitchOnPHOS();\n \n \/\/Min particle pT\n \/\/reader->SetEMCALPtMin(0.5); \n reader->SetPHOSPtMin(0.5);\n \/\/reader->SetCTSPtMin(0.2);\n reader->SwitchOnStack(); \/\/On by default, remember to SwitchOnMCData() in analysis classes\n \/\/In case of generating jet events (with PYTHIA), if pt hard bin is small\n \/\/reject events with large difference between ptHard and triggered jet\t\n \/\/reader->SetPtHardAndJetPtComparison(kTRUE);\n\t\n reader->SetFidutialCut(fidCut);\n\n \/\/Anaysis of final particles, not pi0\/eta etc.\n TArrayI statusArray(1) ;\n statusArray.SetAt(1,0); \n reader->AddStatusArray(statusArray) ;\n reader->SwitchOnStatusSelection() ;\n\n \/\/Keep pi0 in the list and not the 2 photon if decay angle is small.\n reader->SwitchOffOverlapCheck(); \t\n\t\n reader->Print(\"\");\n \n \n \/\/---------------------------------------------------------------------\n \/\/ Analysis algorithm\n \/\/---------------------------------------------------------------------\n \n \/\/Detector Fidutial Cuts for analysis part\n AliFidutialCut * fidCut2 = new AliFidutialCut();\n fidCut2->DoCTSFidutialCut(kFALSE) ;\n fidCut2->DoEMCALFidutialCut(kFALSE) ;\n fidCut2->DoPHOSFidutialCut(kFALSE) ;\n \n \/\/fidCut2->SetSimpleCTSFidutialCut(0.9,0.,360.);\n \/\/fidCut2->SetSimpleEMCALFidutialCut(0.7,80.,190.);\n \/\/fidCut2->SetSimplePHOSFidutialCut(0.13,220.,320.);\n\n fidCut2->Print(\"\");\n\n AliAnaPhoton *ana = new AliAnaPhoton();\n ana->SetDebug(-1);\n ana->SetMinPt(5.);\n ana->SetMinDistanceToBadChannel(2, 4, 5);\n ana->SetFidutialCut(fidCut2);\n ana->SetCalorimeter(\"PHOS\");\n ana->SwitchOnDataMC() ;\/\/Access MC stack and fill more histograms\n ana->SwitchOffCaloPID(); \/\/No need with MC reader\n ana->SwitchOffCaloPIDRecalculation(); \/\/recommended for EMCAL, no need with MC reader\n ana->SwitchOffTrackMatchRejection(); \/\/Only in use when OnCaloPID\n ana->SwitchOffFidutialCut();\n ana->SetOutputAODName(\"Photons\");\n ana->SetOutputAODClassName(\"AliAODPWG4Particle\");\n \/\/Set Histrograms bins and ranges\n\/\/\tana->SetHistoPtRangeAndNBins(0, 50, 100) ;\n\/\/\tana->SetHistoPhiRangeAndNBins(0, TMath::TwoPi(), 100) ;\n\/\/\tana->SetHistoEtaRangeAndNBins(-0.7, 0.7, 100) ;\n ana->Print(\"\");\n\n \/\/---------------------------------------------------------------------\n \/\/ Set analysis algorithm and reader\n \/\/---------------------------------------------------------------------\n maker = new AliAnaPartCorrMaker();\n maker->SetReader(reader);\/\/pointer to reader\n maker->AddAnalysis(ana,0);\n maker->SetAnaDebug(-1) ;\n maker->SwitchOnHistogramsMaker() ;\n maker->SwitchOnAODsMaker() ;\n \n maker->Print(\"\");\n \/\/\n printf(\"======================== \\n\");\n printf(\"END ConfigAnalysis() \\n\");\n printf(\"======================== \\n\");\n return maker ;\n}\n<|endoftext|>"} {"text":"AliAnalysisTaskSEDs *AddTaskDs(Int_t storeNtuple=1,Bool_t readMC=kFALSE,\n\t\t\t\t TString filename=\"DstoKKpiCuts.root\")\n{\n \/\/ \n \/\/ Test macro for the AliAnalysisTaskSE for Ds candidates \n\n \/\/Invariant mass histogram and \n \/\/ association with MC truth (using MC info in AOD) \n \/\/ Origin: R. Bala, bala@to.infn.it \n \/\/ Modified for Ds meson: G.M. Innocenti innocent@to.infn.it\n \/\/ Get the pointer to the existing analysis manager via the static access method. \n \/\/============================================================================== \n\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskDs\", \"No analysis manager to connect to.\");\n }\n\n\n TFile* filecuts=TFile::Open(filename.Data());\n if(!filecuts ||(filecuts&& !filecuts->IsOpen())){\n cout<<\"Error: Input file not found!\"<Get(\"AnalysisCuts\");\n\n AliAnalysisTaskSEDs *dsTask = new AliAnalysisTaskSEDs(\"DsAnalysis\",analysiscuts,storeNtuple);\n\n dsTask->SetReadMC(readMC);\n \/\/dsTask->SetDoLikeSign(kTRUE);\n \/\/ dsTask->SetUseTPCpid(kTRUE);\n \/\/dsTask->SetUseTOFpid(kTRUE);\n dsTask->SetDebugLevel(10);\n dsTask->SetUseSelectionBit(kTRUE);\n \/\/dsTask->SetMassLimits(0.2);\n mgr->AddTask(dsTask);\n \n \/\/ Create containers for input\/output \n \n AliAnalysisDataContainer *cinputDs = mgr->CreateContainer(\"cinputDs\",TChain::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kInputContainer);\n TString outputfile = AliAnalysisManager::GetCommonFileName();\n outputfile += \":PWG3_D2H_InvMassDs\";\n \n AliAnalysisDataContainer *coutputDsCuts = mgr->CreateContainer(\"coutputDsCuts\",TList::Class(),\n\t\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t\t outputfile.Data());\n \n AliAnalysisDataContainer *coutputDs = mgr->CreateContainer(\"coutputDs\",TList::Class(),\n\t\t\t\t\t\t\t\tAliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t\toutputfile.Data());\n AliAnalysisDataContainer *coutputDsNorm = mgr->CreateContainer(\"coutputDsNorm\",AliNormalizationCounter::Class(),\n\t\t\t\t\t\t\t\tAliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t\toutputfile.Data());\n \n if(storeNtuple){\n AliAnalysisDataContainer *coutputDs2 = mgr->CreateContainer(\"coutputDs2\",TNtuple::Class(),\n\t\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t\t outputfile.Data());\n \n coutputDs2->SetSpecialOutput();\n }\n \n mgr->ConnectInput(dsTask,0,mgr->GetCommonInputContainer());\n \n mgr->ConnectOutput(dsTask,1,coutputDs);\n \n mgr->ConnectOutput(dsTask,2,coutputDsCuts);\n\n mgr->ConnectOutput(dsTask,3,coutputDsNorm); \n \n if(storeNtuple){\n mgr->ConnectOutput(dsTask,4,coutputDs2);\n }\n \n return dsTask;\n}\nAddTacksDs adapted for running on lego train (Gian Michele)AliAnalysisTaskSEDs *AddTaskDs(Int_t system=0\/*0=pp,1=PbPb*\/,\n Int_t storeNtuple=0,Bool_t readMC=kFALSE,\n\t\t\t\t TString filename=\"\")\n{\n \/\/ \n \/\/ Test macro for the AliAnalysisTaskSE for Ds candidates \n\n \/\/Invariant mass histogram and \n \/\/ association with MC truth (using MC info in AOD) \n \/\/ Origin: R. Bala, bala@to.infn.it \n \/\/ Modified for Ds meson: G.M. Innocenti innocent@to.infn.it\n \/\/ Get the pointer to the existing analysis manager via the static access method. \n \/\/============================================================================== \n\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskDs\", \"No analysis manager to connect to.\");\n }\n \n Bool_t stdcuts=kFALSE;\n TFile* filecuts;\n if( filename.EqualTo(\"\") ) {\n stdcuts=kTRUE; \n } else {\n filecuts=TFile::Open(filename.Data());\n if(!filecuts ||(filecuts&& !filecuts->IsOpen())){\n\t AliFatal(\"Cut object not found: analysis will not start!\\n\");\n }\n else printf(\"Cut object correctly found\\n\");\n }\n \n \/\/Analysis Task\n\n AliRDHFCutsDstoKKpi* analysiscuts=new AliRDHFCutsDstoKKpi();\n \n if(stdcuts) {\n if(system==0) {\n printf(\"Cut object not found: standard pp cut object used\\n\");\n analysiscuts->SetStandardCutsPP2010();\n }\n else AliFatal(\"Standard cut object not available for PbPb: analysis will not start!\\n\");\n }\n else analysiscuts = (AliRDHFCutsDstoKKpi*)filecuts->Get(\"AnalysisCuts\");\n \n AliAnalysisTaskSEDs *dsTask = new AliAnalysisTaskSEDs(\"DsAnalysis\",analysiscuts,storeNtuple);\n\n dsTask->SetReadMC(readMC);\n \/\/dsTask->SetDoLikeSign(kTRUE);\n \/\/ dsTask->SetUseTPCpid(kTRUE);\n \/\/dsTask->SetUseTOFpid(kTRUE);\n dsTask->SetDebugLevel(10);\n dsTask->SetUseSelectionBit(kTRUE);\n \/\/dsTask->SetMassLimits(0.2);\n mgr->AddTask(dsTask);\n \n \/\/ Create containers for input\/output \n \n AliAnalysisDataContainer *cinputDs = mgr->CreateContainer(\"cinputDs\",TChain::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kInputContainer);\n TString outputfile = AliAnalysisManager::GetCommonFileName();\n outputfile += \":PWG3_D2H_InvMassDs\";\n \n AliAnalysisDataContainer *coutputDsCuts = mgr->CreateContainer(\"coutputDsCuts\",TList::Class(),\n\t\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t\t outputfile.Data());\n \n AliAnalysisDataContainer *coutputDs = mgr->CreateContainer(\"coutputDs\",TList::Class(),\n\t\t\t\t\t\t\t\tAliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t\toutputfile.Data());\n AliAnalysisDataContainer *coutputDsNorm = mgr->CreateContainer(\"coutputDsNorm\",AliNormalizationCounter::Class(),\n\t\t\t\t\t\t\t\tAliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t\toutputfile.Data());\n \n if(storeNtuple){\n AliAnalysisDataContainer *coutputDs2 = mgr->CreateContainer(\"coutputDs2\",TNtuple::Class(),\n\t\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t\t outputfile.Data());\n \n coutputDs2->SetSpecialOutput();\n }\n \n mgr->ConnectInput(dsTask,0,mgr->GetCommonInputContainer());\n \n mgr->ConnectOutput(dsTask,1,coutputDs);\n \n mgr->ConnectOutput(dsTask,2,coutputDsCuts);\n\n mgr->ConnectOutput(dsTask,3,coutputDsNorm); \n \n if(storeNtuple){\n mgr->ConnectOutput(dsTask,4,coutputDs2);\n }\n \n return dsTask;\n}\n<|endoftext|>"} {"text":"#include \"plant_printer.h\"\n\n#include \n#include \n\n#include \"asdf_multiplat\/main\/asdf_defs.h\"\n\nusing namespace std;\nusing namespace plantgen;\n\nnamespace plant_printer\n{\n namespace\n {\n constexpr char string_var_delimiter = '%';\n }\n\n\n string_var_locations_t parse_print_string(string const& print_string)\n {\n string_var_locations_t var_locations;\n\n size_t pos = 0;\n size_t endpos = 0;\n\n while(true)\n {\n pos = print_string.find(string_var_delimiter, endpos);\n if(pos == string::npos)\n break;\n\n endpos = print_string.find(string_var_delimiter, pos+1);\n\n if(endpos == string::npos)\n {\n EXPLODE(\"unmached %%\");\n }\n\n ASSERT(endpos > pos, \"\");\n ASSERT(endpos-pos >= 1, \"\");\n std::string key = print_string.substr(pos+1, endpos-pos-1);\n var_locations.insert({key,pos});\n\n endpos++; \/\/move it past the percent sign for the next find call\n }\n\n return var_locations;\n }\n\n\n struct sorted_range_value_t\n {\n int percentage;\n std::string range_string;\n };\n\n std::vector get_sorted_range(generated_node_t const& node)\n {\n if(node.generated_values.size() == 0)\n return std::vector();\n\n \/\/ASSERT(node.generated_values.size() > 0, \"expected some flavors to sort\");\n std::vector sorted_values;\n sorted_values.reserve(node.generated_values.size());\n \n for(auto const& val : node.generated_values)\n {\n auto percent_sign_pos = val.find('%');\n\n ASSERT(percent_sign_pos != std::string::npos, \"\");\n if(percent_sign_pos != std::string::npos)\n {\n sorted_range_value_t sv =\n {\n stoi(val.substr(0, percent_sign_pos)),\n val.substr(percent_sign_pos + 2)\n };\n\n sorted_values.push_back(sv);\n }\n }\n\n std::sort(sorted_values.begin(), sorted_values.end(),\n [](sorted_range_value_t const& lhs, sorted_range_value_t const& rhs)\n {\n return lhs.percentage > rhs.percentage;\n });\n\n return sorted_values;\n }\n\n\n string print_range_value(generated_node_t const& range)\n {\n auto sorted_values = get_sorted_range(range);\n\n ASSERT(sorted_values.size() > 0, \"\");\n\n if(sorted_values[0].percentage >= 95)\n {\n return \"completely \" + sorted_values[0].range_string;\n }\n else if(sorted_values[0].percentage >= 90)\n {\n return \"very \" + sorted_values[0].range_string;\n }\n else if(sorted_values[0].percentage >= 70)\n {\n std::string ret = \"mostly \" + sorted_values[0].range_string;\n\n if(sorted_values.size() >= 2 && sorted_values[1].percentage > 20)\n {\n ret += \" and slightly \" + sorted_values[1].range_string;\n }\n\n return ret;\n }\n \/\/else if(sorted_values[0].percentage >= 50)\n else\n {\n std::string ret = \"somewhat \" + sorted_values[0].range_string;\n\n if(sorted_values.size() >= 2 && sorted_values[1].percentage > 20)\n {\n ret += \" and slightly \" + sorted_values[1].range_string;\n }\n\n return ret;\n }\n }\n\n string print_multi_value(generated_node_t const& node)\n {\n if(node.generated_values.empty())\n return \"\";\n\n string property_string;\/\/ = node.name + \" that is \";\n\n if(node.generated_values.size() == 1)\n return node.generated_values[0];\n\n for(size_t i = 0; i < node.generated_values.size() - 1; ++i)\n {\n property_string += node.generated_values[i] + \", \";\n }\n\n property_string.resize(property_string.size() - 2);\n property_string += \" and \" + node.generated_values.back();\n\n return property_string;\n }\n\n string print_basic_property(generated_node_t const& node)\n {\n ASSERT(node.children.empty(), \"\");\n\n if(node.generated_values.size() == 1)\n {\n return node.generated_values[0];\n }\n else if(node.generated_values.size() > 1)\n {\n \/\/ if there is a % in the first few characters\n \/\/ (ie: if its XXX% or XX% or X%)\n if(node.generated_values[0].find('%') <= 3)\n {\n return print_range_value(node);\n }\n else\n {\n return print_multi_value(node);\n }\n }\n\n return \"\";\n }\n\n string print_sub_property(generated_node_t const& node, size_t level)\n {\n std::string summary;\n\n if(node.print_string.size() > 0)\n {\n summary += print_property_with_string(node);\n }\n else\n {\n if(node.children.empty() && node.value_nodes.empty())\n {\n return print_basic_property(node);\n }\n else\n {\n summary += to_string(node, level + 1, level); \/\/ depth of level + 1 (ie: only print this node, not its subnodes)\n\n for(auto const& child : node.children)\n summary += print_sub_property(child, level + 1) + \"\\n\";\n for(auto const& vn : node.value_nodes)\n summary += print_sub_property(vn, level + 1) + \"\\n\";\n }\n }\n\n return summary;\n }\n\n\n \/\/\/ TODO: move to util file\n \/\/\/ https:\/\/stackoverflow.com\/a\/5056797\n template\n std::pair flip_pair(const std::pair &p)\n {\n return std::pair(p.second, p.first);\n }\n\n template\n std::multimap flip_map(const std::map &src)\n {\n std::multimap dst;\n std::transform(src.begin(), src.end(), std::inserter(dst, dst.begin()), \n flip_pair);\n return dst;\n }\n \/\/\/\n\n\n\n string print_property_with_string(generated_node_t const& node)\n {\n WARN_IF(node.print_string.empty(), \"node has no print string in a function that is based around having one\");\n return print_property_with_string(node, node.print_string);\n }\n\n string print_property_with_string(generated_node_t const& node, string const& print_string)\n {\n if(print_string.empty())\n return \"\";\n\n std::string final_string = print_string;\n\n \/\/ sort locations by string position (earliest to latest)\n \/\/ so that I can adjust the string replacement positions\n \/\/ as the string changes size\n auto var_locations = parse_print_string(print_string);\n auto sorted_locs = flip_map(var_locations);\n int adjust = 0;\n\n for(auto const& var_loc : sorted_locs)\n {\n std::string var_str;\n auto prev_size = final_string.size();\n\n if(var_loc.second == \"Name\")\n {\n final_string.replace(var_loc.first + adjust, 4+2, node.name);\n }\n else\n {\n for(generated_node_t const& child : node.children)\n {\n if(var_loc.second == child.name)\n {\n \/\/string str = str_for_var(child);\n string str = print_sub_property(child);\n final_string.replace(var_loc.first + adjust, var_loc.second.size()+2, str);\n break;\n }\n }\n }\n\n adjust += int(final_string.size()) - int(prev_size);\n }\n\n return final_string;\n }\n\n\n string print_plant(generated_node_t const& plant_node)\n {\n return \"This \" + plant_node.name + \" \" + print_sub_property(plant_node);\n }\n}minor changes to printing sub-properties that have no PrintString#include \"plant_printer.h\"\n\n#include \n#include \n\n#include \"asdf_multiplat\/main\/asdf_defs.h\"\n\nusing namespace std;\nusing namespace plantgen;\n\nnamespace plant_printer\n{\n namespace\n {\n constexpr char string_var_delimiter = '%';\n }\n\n\n string_var_locations_t parse_print_string(string const& print_string)\n {\n string_var_locations_t var_locations;\n\n size_t pos = 0;\n size_t endpos = 0;\n\n while(true)\n {\n pos = print_string.find(string_var_delimiter, endpos);\n if(pos == string::npos)\n break;\n\n endpos = print_string.find(string_var_delimiter, pos+1);\n\n if(endpos == string::npos)\n {\n EXPLODE(\"unmached %%\");\n }\n\n ASSERT(endpos > pos, \"\");\n ASSERT(endpos-pos >= 1, \"\");\n std::string key = print_string.substr(pos+1, endpos-pos-1);\n var_locations.insert({key,pos});\n\n endpos++; \/\/move it past the percent sign for the next find call\n }\n\n return var_locations;\n }\n\n\n struct sorted_range_value_t\n {\n int percentage;\n std::string range_string;\n };\n\n std::vector get_sorted_range(generated_node_t const& node)\n {\n if(node.generated_values.size() == 0)\n return std::vector();\n\n \/\/ASSERT(node.generated_values.size() > 0, \"expected some flavors to sort\");\n std::vector sorted_values;\n sorted_values.reserve(node.generated_values.size());\n \n for(auto const& val : node.generated_values)\n {\n auto percent_sign_pos = val.find('%');\n\n ASSERT(percent_sign_pos != std::string::npos, \"\");\n if(percent_sign_pos != std::string::npos)\n {\n sorted_range_value_t sv =\n {\n stoi(val.substr(0, percent_sign_pos)),\n val.substr(percent_sign_pos + 2)\n };\n\n sorted_values.push_back(sv);\n }\n }\n\n std::sort(sorted_values.begin(), sorted_values.end(),\n [](sorted_range_value_t const& lhs, sorted_range_value_t const& rhs)\n {\n return lhs.percentage > rhs.percentage;\n });\n\n return sorted_values;\n }\n\n\n string print_range_value(generated_node_t const& range)\n {\n auto sorted_values = get_sorted_range(range);\n\n ASSERT(sorted_values.size() > 0, \"\");\n\n if(sorted_values[0].percentage >= 95)\n {\n return \"completely \" + sorted_values[0].range_string;\n }\n else if(sorted_values[0].percentage >= 90)\n {\n return \"very \" + sorted_values[0].range_string;\n }\n else if(sorted_values[0].percentage >= 70)\n {\n std::string ret = \"mostly \" + sorted_values[0].range_string;\n\n if(sorted_values.size() >= 2 && sorted_values[1].percentage > 20)\n {\n ret += \" and slightly \" + sorted_values[1].range_string;\n }\n\n return ret;\n }\n \/\/else if(sorted_values[0].percentage >= 50)\n else\n {\n std::string ret = \"somewhat \" + sorted_values[0].range_string;\n\n if(sorted_values.size() >= 2 && sorted_values[1].percentage > 20)\n {\n ret += \" and slightly \" + sorted_values[1].range_string;\n }\n\n return ret;\n }\n }\n\n string print_multi_value(generated_node_t const& node)\n {\n if(node.generated_values.empty())\n return \"\";\n\n string property_string;\/\/ = node.name + \" that is \";\n\n if(node.generated_values.size() == 1)\n return node.generated_values[0];\n\n for(size_t i = 0; i < node.generated_values.size() - 1; ++i)\n {\n property_string += node.generated_values[i] + \", \";\n }\n\n property_string.resize(property_string.size() - 2);\n property_string += \" and \" + node.generated_values.back();\n\n return property_string;\n }\n\n string print_basic_property(generated_node_t const& node)\n {\n ASSERT(node.children.empty(), \"\");\n\n if(node.generated_values.size() == 1)\n {\n return node.generated_values[0];\n }\n else if(node.generated_values.size() > 1)\n {\n \/\/ if there is a % in the first few characters\n \/\/ (ie: if its XXX% or XX% or X%)\n if(node.generated_values[0].find('%') <= 3)\n {\n return print_range_value(node);\n }\n else\n {\n return print_multi_value(node);\n }\n }\n\n return \"\";\n }\n\n string print_sub_property(generated_node_t const& node, size_t level)\n {\n std::string summary;\n\n if(node.print_string.size() > 0)\n {\n summary += print_property_with_string(node);\n }\n else\n {\n if(node.children.empty() && node.value_nodes.empty())\n {\n return print_basic_property(node);\n }\n else\n {\n summary += node.name_string() + \"\\n\";\n\n for(auto const& child : node.children)\n summary += print_sub_property(child, level + 1) + \"; \";\n for(auto const& vn : node.value_nodes)\n summary += print_sub_property(vn, level + 1) + \"; \";\n\n summary.resize(summary.size() - 1);\n summary.back() = '\\n';\n }\n }\n\n return summary;\n }\n\n\n \/\/\/ TODO: move to util file\n \/\/\/ https:\/\/stackoverflow.com\/a\/5056797\n template\n std::pair flip_pair(const std::pair &p)\n {\n return std::pair(p.second, p.first);\n }\n\n template\n std::multimap flip_map(const std::map &src)\n {\n std::multimap dst;\n std::transform(src.begin(), src.end(), std::inserter(dst, dst.begin()), \n flip_pair);\n return dst;\n }\n \/\/\/\n\n\n\n string print_property_with_string(generated_node_t const& node)\n {\n WARN_IF(node.print_string.empty(), \"node has no print string in a function that is based around having one\");\n return print_property_with_string(node, node.print_string);\n }\n\n string print_property_with_string(generated_node_t const& node, string const& print_string)\n {\n if(print_string.empty())\n return \"\";\n\n std::string final_string = print_string;\n\n \/\/ sort locations by string position (earliest to latest)\n \/\/ so that I can adjust the string replacement positions\n \/\/ as the string changes size\n auto var_locations = parse_print_string(print_string);\n auto sorted_locs = flip_map(var_locations);\n int adjust = 0;\n\n for(auto const& var_loc : sorted_locs)\n {\n std::string var_str;\n auto prev_size = final_string.size();\n\n if(var_loc.second == \"Name\")\n {\n final_string.replace(var_loc.first + adjust, 4+2, node.name);\n }\n else\n {\n for(generated_node_t const& child : node.children)\n {\n if(var_loc.second == child.name)\n {\n \/\/string str = str_for_var(child);\n string str = print_sub_property(child);\n final_string.replace(var_loc.first + adjust, var_loc.second.size()+2, str);\n break;\n }\n }\n }\n\n adjust += int(final_string.size()) - int(prev_size);\n }\n\n return final_string;\n }\n\n\n string print_plant(generated_node_t const& plant_node)\n {\n return \"This \" + plant_node.name + \" \" + print_sub_property(plant_node);\n }\n}<|endoftext|>"} {"text":"#include \"XInputFetcher.h\"\r\n\r\nint XInputFetcher::s_btnMaskMap[InputHelper::NUM_XBOX360_CONTROLLER_DIGITALS] = \r\n{\r\n\tXINPUT_GAMEPAD_DPAD_UP,\r\n\tXINPUT_GAMEPAD_DPAD_DOWN,\r\n\tXINPUT_GAMEPAD_DPAD_LEFT, \r\n\tXINPUT_GAMEPAD_DPAD_RIGHT,\r\n\tXINPUT_GAMEPAD_START,\r\n\tXINPUT_GAMEPAD_BACK,\r\n\tXINPUT_GAMEPAD_LEFT_THUMB,\r\n\tXINPUT_GAMEPAD_RIGHT_THUMB,\r\n\tXINPUT_GAMEPAD_LEFT_SHOULDER,\r\n\tXINPUT_GAMEPAD_RIGHT_SHOULDER,\r\n\tXINPUT_GAMEPAD_A,\r\n\tXINPUT_GAMEPAD_B,\r\n\tXINPUT_GAMEPAD_X,\r\n\tXINPUT_GAMEPAD_Y\r\n};\r\n\r\nXInputFetcher::XInputFetcher()\r\n{\r\n\tDWORD dwResult; \r\n\tXINPUT_STATE state;\r\n\tZeroMemory( &state, sizeof(XINPUT_STATE) );\r\n\r\n\t\/\/ Simply get the state of the controller from XInput.\r\n\tdwResult = XInputGetState( 0, &state );\r\n\r\n\tif( dwResult == ERROR_SUCCESS )\r\n\t{\r\n\t\tint korv = 1;\r\n\t\t\/\/ Controller is connected \r\n\t}\r\n\telse\r\n\t{\r\n\t\tint korv = 0;\r\n\t\t\/\/ Controller is not connected \r\n\t}\r\n}\r\n\r\nXInputFetcher::~XInputFetcher()\r\n{\r\n}\r\n\r\nvoid XInputFetcher::update()\r\n{\r\n\tXINPUT_STATE newState;\r\n\tXInputGetState( 0, &newState );\r\n\tfor( int i=0; iFixed bug where input were recorded when no gamepad was connected#include \"XInputFetcher.h\"\r\n\r\nint XInputFetcher::s_btnMaskMap[InputHelper::NUM_XBOX360_CONTROLLER_DIGITALS] = \r\n{\r\n\tXINPUT_GAMEPAD_DPAD_UP,\r\n\tXINPUT_GAMEPAD_DPAD_DOWN,\r\n\tXINPUT_GAMEPAD_DPAD_LEFT, \r\n\tXINPUT_GAMEPAD_DPAD_RIGHT,\r\n\tXINPUT_GAMEPAD_START,\r\n\tXINPUT_GAMEPAD_BACK,\r\n\tXINPUT_GAMEPAD_LEFT_THUMB,\r\n\tXINPUT_GAMEPAD_RIGHT_THUMB,\r\n\tXINPUT_GAMEPAD_LEFT_SHOULDER,\r\n\tXINPUT_GAMEPAD_RIGHT_SHOULDER,\r\n\tXINPUT_GAMEPAD_A,\r\n\tXINPUT_GAMEPAD_B,\r\n\tXINPUT_GAMEPAD_X,\r\n\tXINPUT_GAMEPAD_Y\r\n};\r\n\r\nXInputFetcher::XInputFetcher()\r\n{\r\n\tZeroMemory( &m_currentState, sizeof(XINPUT_STATE) );\r\n}\r\n\r\nXInputFetcher::~XInputFetcher()\r\n{\r\n}\r\n\r\nvoid XInputFetcher::update()\r\n{\r\n\t\/\/XINPUT_STATE newState;\r\n\tZeroMemory( &m_currentState, sizeof(XINPUT_STATE) );\r\n\tunsigned long result = XInputGetState( 0, &m_currentState );\r\n\tif( result == ERROR_SUCCESS )\r\n\t{\r\n\t\tfor( int i=0; i"} {"text":"\/*\n * Copyright 2014 Cloudius Systems\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\n#include \"database.hh\"\n#include \"core\/app-template.hh\"\n#include \"core\/distributed.hh\"\n#include \"thrift\/server.hh\"\n#include \"transport\/server.hh\"\n#include \"http\/httpd.hh\"\n#include \"api\/api.hh\"\n#include \"db\/config.hh\"\n#include \"service\/storage_service.hh\"\n#include \"service\/migration_manager.hh\"\n#include \"streaming\/stream_session.hh\"\n#include \"db\/system_keyspace.hh\"\n#include \"db\/batchlog_manager.hh\"\n#include \"db\/commitlog\/commitlog.hh\"\n#include \"db\/commitlog\/commitlog_replayer.hh\"\n#include \"utils\/runtime.hh\"\n#include \"utils\/file_lock.hh\"\n#include \"dns.hh\"\n#include \"log.hh\"\n#include \"debug.hh\"\n#include \"init.hh\"\n#include \"release.hh\"\n#include \n\nlogging::logger startlog(\"init\");\n\nnamespace bpo = boost::program_options;\n\nstatic future<>\nread_config(bpo::variables_map& opts, db::config& cfg) {\n sstring file;\n\n if (opts.count(\"options-file\") > 0) {\n file = opts[\"options-file\"].as();\n } else {\n sstring confdir;\n auto* cd = std::getenv(\"SCYLLA_CONF\");\n if (cd != nullptr) {\n confdir = cd;\n } else {\n auto* p = std::getenv(\"SCYLLA_HOME\");\n if (p != nullptr) {\n confdir = sstring(p) + \"\/\";\n }\n confdir += \"conf\";\n }\n file = confdir + \"\/scylla.yaml\";\n }\n return cfg.read_from_file(file).handle_exception([file](auto ep) {\n startlog.error(\"Could not read configuration file {}: {}\", file, ep);\n return make_exception_future<>(ep);\n });\n}\n\nstatic void do_help_loggers() {\n print(\"Available loggers:\\n\");\n for (auto&& name : logging::logger_registry().get_all_logger_names()) {\n print(\" %s\\n\", name);\n }\n}\n\nstatic logging::log_level to_loglevel(sstring level) {\n try {\n return boost::lexical_cast(std::string(level));\n } catch(boost::bad_lexical_cast e) {\n throw std::runtime_error(\"Unknown log level '\" + level + \"'\");\n }\n}\n\nstatic void apply_logger_settings(sstring default_level, db::config::string_map levels,\n bool log_to_stdout, bool log_to_syslog) {\n logging::logger_registry().set_all_loggers_level(to_loglevel(default_level));\n for (auto&& kv: levels) {\n auto&& k = kv.first;\n auto&& v = kv.second;\n try {\n logging::logger_registry().set_logger_level(k, to_loglevel(v));\n } catch(std::out_of_range e) {\n throw std::runtime_error(\"Unknown logger '\" + k + \"'. Use --help-loggers to list available loggers.\");\n }\n }\n logging::logger::set_stdout_enabled(log_to_stdout);\n logging::logger::set_syslog_enabled(log_to_syslog);\n}\n\nclass directories {\npublic:\n future<> touch_and_lock(sstring path) {\n return recursive_touch_directory(path).then_wrapped([this, path] (future<> f) {\n try {\n f.get();\n return utils::file_lock::acquire(path + \"\/.lock\").then([this](utils::file_lock lock) {\n _locks.emplace_back(std::move(lock));\n }).handle_exception([path](auto ep) {\n \/\/ only do this because \"normal\" unhandled exception exit in seastar\n \/\/ _drops_ system_error message (\"what()\") and thus does not quite deliver\n \/\/ the relevant info to the user\n try {\n std::rethrow_exception(ep);\n } catch (std::exception& e) {\n startlog.error(\"Could not initialize {}: {}\", path, e.what());\n throw;\n } catch (...) {\n throw;\n }\n });\n } catch (std::system_error& e) {\n startlog.error(\"Directory '{}' not found. Tried to created it but failed: {}\", path, e.what());\n throw;\n }\n });\n }\n template\n future<> touch_and_lock(_Iter i, _Iter e) {\n return parallel_for_each(i, e, [this](sstring path) {\n return touch_and_lock(std::move(path));\n });\n }\n template\n future<> touch_and_lock(_Range&& r) {\n return touch_and_lock(std::begin(r), std::end(r));\n }\nprivate:\n std::vector\n _locks;\n};\n\nint main(int ac, char** av) {\n runtime::init_uptime();\n std::setvbuf(stdout, nullptr, _IOLBF, 1000);\n app_template app;\n auto opt_add = app.add_options();\n\n auto cfg = make_lw_shared();\n bool help_loggers = false;\n cfg->add_options(opt_add)\n \/\/ TODO : default, always read?\n (\"options-file\", bpo::value(), \"configuration file (i.e. \/conf\/scylla.yaml)\")\n (\"help-loggers\", bpo::bool_switch(&help_loggers), \"print a list of logger names and exit\")\n ;\n\n distributed db;\n debug::db = &db;\n distributed qp;\n auto& proxy = service::get_storage_proxy();\n auto& mm = service::get_migration_manager();\n api::http_context ctx(db, proxy);\n directories dirs;\n\n return app.run_deprecated(ac, av, [&] {\n if (help_loggers) {\n do_help_loggers();\n engine().exit(1);\n return make_ready_future<>();\n }\n print(\"Scylla version %s starting ...\\n\", scylla_version());\n auto&& opts = app.configuration();\n\n \/\/ Do this first once set log applied from command line so for example config\n \/\/ parse can get right log level.\n apply_logger_settings(cfg->default_log_level(), cfg->logger_log_level(),\n cfg->log_to_stdout(), cfg->log_to_syslog());\n\n return read_config(opts, *cfg).then([&cfg, &db, &qp, &proxy, &mm, &ctx, &opts, &dirs]() {\n apply_logger_settings(cfg->default_log_level(), cfg->logger_log_level(),\n cfg->log_to_stdout(), cfg->log_to_syslog());\n dht::set_global_partitioner(cfg->partitioner());\n auto start_thrift = cfg->start_rpc();\n uint16_t thrift_port = cfg->rpc_port();\n uint16_t cql_port = cfg->native_transport_port();\n uint16_t api_port = cfg->api_port();\n ctx.api_dir = cfg->api_ui_dir();\n ctx.api_doc = cfg->api_doc_dir();\n sstring cluster_name = cfg->cluster_name();\n sstring listen_address = cfg->listen_address();\n sstring rpc_address = cfg->rpc_address();\n sstring api_address = cfg->api_address() != \"\" ? cfg->api_address() : rpc_address;\n auto seed_provider= cfg->seed_provider();\n using namespace locator;\n return i_endpoint_snitch::create_snitch(cfg->endpoint_snitch()).then([] {\n \/\/ #293 - do not stop anything\n \/\/ engine().at_exit([] { return i_endpoint_snitch::stop_snitch(); });\n }).then([&db] {\n return init_storage_service(db);\n }).then([&db, cfg] {\n return db.start(std::move(*cfg)).then([&db] {\n engine().at_exit([&db] {\n\n \/\/ #293 - do not stop anything - not even db (for real)\n \/\/return db.stop();\n \/\/ call stop on each db instance, but leave the shareded pointers alive.\n return db.invoke_on_all([](auto& db) {\n return db.stop();\n }).then([] {\n ::_exit(3);\n });\n });\n });\n }).then([listen_address, seed_provider, cluster_name] {\n return init_ms_fd_gossiper(listen_address, seed_provider, cluster_name);\n }).then([&db] {\n return streaming::stream_session::init_streaming_service(db);\n }).then([&proxy, &db] {\n return proxy.start(std::ref(db)).then([&proxy] {\n \/\/ #293 - do not stop anything\n \/\/ engine().at_exit([&proxy] { return proxy.stop(); });\n });\n }).then([&mm] {\n return mm.start().then([&mm] {\n \/\/ #293 - do not stop anything\n \/\/ engine().at_exit([&mm] { return mm.stop(); });\n });\n }).then([&db, &proxy, &qp] {\n return qp.start(std::ref(proxy), std::ref(db)).then([&qp] {\n \/\/ #293 - do not stop anything\n \/\/ engine().at_exit([&qp] { return qp.stop(); });\n });\n }).then([&qp] {\n return db::get_batchlog_manager().start(std::ref(qp)).then([] {\n \/\/ #293 - do not stop anything\n \/\/ engine().at_exit([] { return db::get_batchlog_manager().stop(); });\n });\n }).then([&db, &dirs] {\n return dirs.touch_and_lock(db.local().get_config().data_file_directories());\n }).then([&db, &dirs] {\n return dirs.touch_and_lock(db.local().get_config().commitlog_directory());\n }).then([&db] {\n return db.invoke_on_all([] (database& db) {\n return db.init_system_keyspace();\n });\n }).then([&db, &proxy] {\n return db.invoke_on_all([&proxy] (database& db) {\n return db.load_sstables(proxy);\n });\n }).then([&db, &qp] {\n return db::system_keyspace::setup(db, qp);\n }).then([&db, &qp] {\n auto cl = db.local().commitlog();\n if (cl == nullptr) {\n return make_ready_future<>();\n }\n return cl->list_existing_segments().then([&db, &qp](auto paths) {\n if (paths.empty()) {\n return make_ready_future<>();\n }\n return db::commitlog_replayer::create_replayer(qp).then([paths](auto rp) {\n return do_with(std::move(rp), [paths = std::move(paths)](auto& rp) {\n return rp.recover(paths);\n });\n }).then([&db] {\n return db.invoke_on_all([] (database& db) {\n return db.flush_all_memtables();\n });\n }).then([paths] {\n for (auto& path : paths) {\n ::unlink(path.c_str());\n }\n });\n });\n }).then([] {\n auto& ss = service::get_local_storage_service();\n return ss.init_server();\n }).then([rpc_address] {\n return dns::gethostbyname(rpc_address);\n }).then([&db, &proxy, &qp, rpc_address, cql_port, thrift_port, start_thrift] (dns::hostent e) {\n auto ip = e.addresses[0].in.s_addr;\n auto cserver = new distributed;\n cserver->start(std::ref(proxy), std::ref(qp)).then([server = std::move(cserver), cql_port, rpc_address, ip] () mutable {\n \/\/ #293 - do not stop anything\n \/\/engine().at_exit([server] {\n \/\/ return server->stop();\n \/\/});\n server->invoke_on_all(&transport::cql_server::listen, ipv4_addr{ip, cql_port});\n }).then([rpc_address, cql_port] {\n print(\"Starting listening for CQL clients on %s:%s...\\n\", rpc_address, cql_port);\n });\n if (start_thrift) {\n auto tserver = new distributed;\n tserver->start(std::ref(db)).then([server = std::move(tserver), thrift_port, rpc_address, ip] () mutable {\n \/\/ #293 - do not stop anything\n \/\/engine().at_exit([server] {\n \/\/ return server->stop();\n \/\/});\n server->invoke_on_all(&thrift_server::listen, ipv4_addr{ip, thrift_port});\n }).then([rpc_address, thrift_port] {\n print(\"Thrift server listening on %s:%s ...\\n\", rpc_address, thrift_port);\n });\n }\n }).then([api_address] {\n return dns::gethostbyname(api_address);\n }).then([&db, api_address, api_port, &ctx] (dns::hostent e){\n auto ip = e.addresses[0].in.s_addr;\n ctx.http_server.start().then([api_address, api_port, ip, &ctx] {\n return set_server(ctx);\n }).then([api_address, api_port, ip, &ctx] {\n ctx.http_server.listen(ipv4_addr{ip, api_port});\n }).then([api_address, api_port] {\n print(\"Seastar HTTP server listening on %s:%s ...\\n\", api_address, api_port);\n });\n });\n }).or_terminate();\n });\n}\n\nnamespace debug {\n\nseastar::sharded* db;\n\n}\nwarn users on 100 % CPU usage\/*\n * Copyright 2014 Cloudius Systems\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\n#include \"database.hh\"\n#include \"core\/app-template.hh\"\n#include \"core\/distributed.hh\"\n#include \"thrift\/server.hh\"\n#include \"transport\/server.hh\"\n#include \"http\/httpd.hh\"\n#include \"api\/api.hh\"\n#include \"db\/config.hh\"\n#include \"service\/storage_service.hh\"\n#include \"service\/migration_manager.hh\"\n#include \"streaming\/stream_session.hh\"\n#include \"db\/system_keyspace.hh\"\n#include \"db\/batchlog_manager.hh\"\n#include \"db\/commitlog\/commitlog.hh\"\n#include \"db\/commitlog\/commitlog_replayer.hh\"\n#include \"utils\/runtime.hh\"\n#include \"utils\/file_lock.hh\"\n#include \"dns.hh\"\n#include \"log.hh\"\n#include \"debug.hh\"\n#include \"init.hh\"\n#include \"release.hh\"\n#include \n\nlogging::logger startlog(\"init\");\n\nnamespace bpo = boost::program_options;\n\nstatic future<>\nread_config(bpo::variables_map& opts, db::config& cfg) {\n sstring file;\n\n if (opts.count(\"options-file\") > 0) {\n file = opts[\"options-file\"].as();\n } else {\n sstring confdir;\n auto* cd = std::getenv(\"SCYLLA_CONF\");\n if (cd != nullptr) {\n confdir = cd;\n } else {\n auto* p = std::getenv(\"SCYLLA_HOME\");\n if (p != nullptr) {\n confdir = sstring(p) + \"\/\";\n }\n confdir += \"conf\";\n }\n file = confdir + \"\/scylla.yaml\";\n }\n return cfg.read_from_file(file).handle_exception([file](auto ep) {\n startlog.error(\"Could not read configuration file {}: {}\", file, ep);\n return make_exception_future<>(ep);\n });\n}\n\nstatic void do_help_loggers() {\n print(\"Available loggers:\\n\");\n for (auto&& name : logging::logger_registry().get_all_logger_names()) {\n print(\" %s\\n\", name);\n }\n}\n\nstatic logging::log_level to_loglevel(sstring level) {\n try {\n return boost::lexical_cast(std::string(level));\n } catch(boost::bad_lexical_cast e) {\n throw std::runtime_error(\"Unknown log level '\" + level + \"'\");\n }\n}\n\nstatic void apply_logger_settings(sstring default_level, db::config::string_map levels,\n bool log_to_stdout, bool log_to_syslog) {\n logging::logger_registry().set_all_loggers_level(to_loglevel(default_level));\n for (auto&& kv: levels) {\n auto&& k = kv.first;\n auto&& v = kv.second;\n try {\n logging::logger_registry().set_logger_level(k, to_loglevel(v));\n } catch(std::out_of_range e) {\n throw std::runtime_error(\"Unknown logger '\" + k + \"'. Use --help-loggers to list available loggers.\");\n }\n }\n logging::logger::set_stdout_enabled(log_to_stdout);\n logging::logger::set_syslog_enabled(log_to_syslog);\n}\n\nclass directories {\npublic:\n future<> touch_and_lock(sstring path) {\n return recursive_touch_directory(path).then_wrapped([this, path] (future<> f) {\n try {\n f.get();\n return utils::file_lock::acquire(path + \"\/.lock\").then([this](utils::file_lock lock) {\n _locks.emplace_back(std::move(lock));\n }).handle_exception([path](auto ep) {\n \/\/ only do this because \"normal\" unhandled exception exit in seastar\n \/\/ _drops_ system_error message (\"what()\") and thus does not quite deliver\n \/\/ the relevant info to the user\n try {\n std::rethrow_exception(ep);\n } catch (std::exception& e) {\n startlog.error(\"Could not initialize {}: {}\", path, e.what());\n throw;\n } catch (...) {\n throw;\n }\n });\n } catch (std::system_error& e) {\n startlog.error(\"Directory '{}' not found. Tried to created it but failed: {}\", path, e.what());\n throw;\n }\n });\n }\n template\n future<> touch_and_lock(_Iter i, _Iter e) {\n return parallel_for_each(i, e, [this](sstring path) {\n return touch_and_lock(std::move(path));\n });\n }\n template\n future<> touch_and_lock(_Range&& r) {\n return touch_and_lock(std::begin(r), std::end(r));\n }\nprivate:\n std::vector\n _locks;\n};\n\nint main(int ac, char** av) {\n runtime::init_uptime();\n std::setvbuf(stdout, nullptr, _IOLBF, 1000);\n app_template app;\n auto opt_add = app.add_options();\n\n auto cfg = make_lw_shared();\n bool help_loggers = false;\n cfg->add_options(opt_add)\n \/\/ TODO : default, always read?\n (\"options-file\", bpo::value(), \"configuration file (i.e. \/conf\/scylla.yaml)\")\n (\"help-loggers\", bpo::bool_switch(&help_loggers), \"print a list of logger names and exit\")\n ;\n\n distributed db;\n debug::db = &db;\n distributed qp;\n auto& proxy = service::get_storage_proxy();\n auto& mm = service::get_migration_manager();\n api::http_context ctx(db, proxy);\n directories dirs;\n\n return app.run_deprecated(ac, av, [&] {\n if (help_loggers) {\n do_help_loggers();\n engine().exit(1);\n return make_ready_future<>();\n }\n print(\"Scylla version %s starting ...\\n\", scylla_version());\n auto&& opts = app.configuration();\n\n \/\/ Do this first once set log applied from command line so for example config\n \/\/ parse can get right log level.\n apply_logger_settings(cfg->default_log_level(), cfg->logger_log_level(),\n cfg->log_to_stdout(), cfg->log_to_syslog());\n\n return read_config(opts, *cfg).then([&cfg, &db, &qp, &proxy, &mm, &ctx, &opts, &dirs]() {\n apply_logger_settings(cfg->default_log_level(), cfg->logger_log_level(),\n cfg->log_to_stdout(), cfg->log_to_syslog());\n dht::set_global_partitioner(cfg->partitioner());\n auto start_thrift = cfg->start_rpc();\n uint16_t thrift_port = cfg->rpc_port();\n uint16_t cql_port = cfg->native_transport_port();\n uint16_t api_port = cfg->api_port();\n ctx.api_dir = cfg->api_ui_dir();\n ctx.api_doc = cfg->api_doc_dir();\n sstring cluster_name = cfg->cluster_name();\n sstring listen_address = cfg->listen_address();\n sstring rpc_address = cfg->rpc_address();\n sstring api_address = cfg->api_address() != \"\" ? cfg->api_address() : rpc_address;\n auto seed_provider= cfg->seed_provider();\n using namespace locator;\n return i_endpoint_snitch::create_snitch(cfg->endpoint_snitch()).then([] {\n \/\/ #293 - do not stop anything\n \/\/ engine().at_exit([] { return i_endpoint_snitch::stop_snitch(); });\n }).then([&db] {\n return init_storage_service(db);\n }).then([&db, cfg] {\n return db.start(std::move(*cfg)).then([&db] {\n engine().at_exit([&db] {\n\n \/\/ #293 - do not stop anything - not even db (for real)\n \/\/return db.stop();\n \/\/ call stop on each db instance, but leave the shareded pointers alive.\n return db.invoke_on_all([](auto& db) {\n return db.stop();\n }).then([] {\n ::_exit(3);\n });\n });\n });\n }).then([listen_address, seed_provider, cluster_name] {\n return init_ms_fd_gossiper(listen_address, seed_provider, cluster_name);\n }).then([&db] {\n return streaming::stream_session::init_streaming_service(db);\n }).then([&proxy, &db] {\n return proxy.start(std::ref(db)).then([&proxy] {\n \/\/ #293 - do not stop anything\n \/\/ engine().at_exit([&proxy] { return proxy.stop(); });\n });\n }).then([&mm] {\n return mm.start().then([&mm] {\n \/\/ #293 - do not stop anything\n \/\/ engine().at_exit([&mm] { return mm.stop(); });\n });\n }).then([&db, &proxy, &qp] {\n return qp.start(std::ref(proxy), std::ref(db)).then([&qp] {\n \/\/ #293 - do not stop anything\n \/\/ engine().at_exit([&qp] { return qp.stop(); });\n });\n }).then([&qp] {\n return db::get_batchlog_manager().start(std::ref(qp)).then([] {\n \/\/ #293 - do not stop anything\n \/\/ engine().at_exit([] { return db::get_batchlog_manager().stop(); });\n });\n }).then([&db, &dirs] {\n return dirs.touch_and_lock(db.local().get_config().data_file_directories());\n }).then([&db, &dirs] {\n return dirs.touch_and_lock(db.local().get_config().commitlog_directory());\n }).then([&db] {\n return db.invoke_on_all([] (database& db) {\n return db.init_system_keyspace();\n });\n }).then([&db, &proxy] {\n return db.invoke_on_all([&proxy] (database& db) {\n return db.load_sstables(proxy);\n });\n }).then([&db, &qp] {\n return db::system_keyspace::setup(db, qp);\n }).then([&db, &qp] {\n auto cl = db.local().commitlog();\n if (cl == nullptr) {\n return make_ready_future<>();\n }\n return cl->list_existing_segments().then([&db, &qp](auto paths) {\n if (paths.empty()) {\n return make_ready_future<>();\n }\n return db::commitlog_replayer::create_replayer(qp).then([paths](auto rp) {\n return do_with(std::move(rp), [paths = std::move(paths)](auto& rp) {\n return rp.recover(paths);\n });\n }).then([&db] {\n return db.invoke_on_all([] (database& db) {\n return db.flush_all_memtables();\n });\n }).then([paths] {\n for (auto& path : paths) {\n ::unlink(path.c_str());\n }\n });\n });\n }).then([] {\n auto& ss = service::get_local_storage_service();\n return ss.init_server();\n }).then([rpc_address] {\n return dns::gethostbyname(rpc_address);\n }).then([&db, &proxy, &qp, rpc_address, cql_port, thrift_port, start_thrift] (dns::hostent e) {\n auto ip = e.addresses[0].in.s_addr;\n auto cserver = new distributed;\n cserver->start(std::ref(proxy), std::ref(qp)).then([server = std::move(cserver), cql_port, rpc_address, ip] () mutable {\n \/\/ #293 - do not stop anything\n \/\/engine().at_exit([server] {\n \/\/ return server->stop();\n \/\/});\n server->invoke_on_all(&transport::cql_server::listen, ipv4_addr{ip, cql_port});\n }).then([rpc_address, cql_port] {\n print(\"Starting listening for CQL clients on %s:%s...\\n\", rpc_address, cql_port);\n });\n if (start_thrift) {\n auto tserver = new distributed;\n tserver->start(std::ref(db)).then([server = std::move(tserver), thrift_port, rpc_address, ip] () mutable {\n \/\/ #293 - do not stop anything\n \/\/engine().at_exit([server] {\n \/\/ return server->stop();\n \/\/});\n server->invoke_on_all(&thrift_server::listen, ipv4_addr{ip, thrift_port});\n }).then([rpc_address, thrift_port] {\n print(\"Thrift server listening on %s:%s ...\\n\", rpc_address, thrift_port);\n });\n }\n }).then([api_address] {\n return dns::gethostbyname(api_address);\n }).then([&db, api_address, api_port, &ctx] (dns::hostent e){\n auto ip = e.addresses[0].in.s_addr;\n ctx.http_server.start().then([api_address, api_port, ip, &ctx] {\n return set_server(ctx);\n }).then([api_address, api_port, ip, &ctx] {\n ctx.http_server.listen(ipv4_addr{ip, api_port});\n }).then([api_address, api_port] {\n print(\"Seastar HTTP server listening on %s:%s ...\\n\", api_address, api_port);\n });\n }).then([] {\n startlog.warn(\"Polling mode enabled. ScyllaDB will use 100% of all your CPUs.\\nSee https:\/\/github.com\/scylladb\/scylla\/issues\/417 for a more detailed explanation\");\n });\n }).or_terminate();\n });\n}\n\nnamespace debug {\n\nseastar::sharded* db;\n\n}\n<|endoftext|>"} {"text":"\/\/===-- main.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 \n#include \n\nint main(int argc, char const *argv[])\n{\n getchar();\n printf(\"Set a breakpoint here.\\n\");\n return 0;\n}\n\nFix breakpoint_set_restart test for Windows\/\/===-- main.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 \n#include \n#include \n\n\nint main(int argc, char const *argv[])\n{\n static bool done = false;\n while (!done)\n {\n std::this_thread::sleep_for(std::chrono::milliseconds{100});\n }\n printf(\"Set a breakpoint here.\\n\");\n return 0;\n}\n\n<|endoftext|>"} {"text":"#ifndef __PARSE_TOOL_HPP__\n#define __PARSE_TOOL_HPP__\n\n#include \nusing namespace std;\n\n\/\/ data type: Maybe\ntemplate\nstruct Maybe{\nprivate:\n bool const nil;\n T const val;\npublic:\n using data_type = T;\n constexpr Maybe(): nil(true) {}\n constexpr Maybe(T const & val): val(val), nil(false) {}\n bool Nil() const { return this->nil; }\n T Val() const { if (this->nil) { throw val; } else { return val; } }\n constexpr operator bool () const { return this->nil == false; }\n};\ntemplate\nconstexpr Maybe const Just(T const & val) {\n return Maybe(val);\n}\ntemplate\nconstexpr Maybe const Nothing() {\n return Maybe();\n}\ntemplate\nconstexpr T const FromJust(Maybe const & wrapper) {\n return wrapper.Val();\n}\n\n\/**\n * The result representation of a parser. `Success` and `Failure` are used to construct Value object, while\n * `Aggregate` is used to accmulate two Value object into one.\n *\/\ntemplate\nstruct ValueT {\n bool const status;\n pair loc;\n int len;\n V const actual;\n string expected;\n bool strict;\n\n string to_string(int n) const { return ::to_string(n); }\n string to_string(char c) const { return string(1, c); }\n string to_string(string s) const { return s; }\n string to_string(vector vec) const { string ans = \"vector char: \"; for (char c: vec) { ans.push_back(c); ans.push_back(','); } return ans; }\n string to_string(vector vec) const { string ans = \"vector string: \"; for (string s: vec) { ans += s + \",\"; } return ans; }\n\n string name() const {\n return \"stream @ \" + ::to_string(loc.first) + \":\" + ::to_string(loc.second)\n + \", \" + (status ? \"true\" : \"false\") + \", length: \" + ::to_string(len) + \"\\n\"\n + \" actual: \" + to_string(actual) + \"\\n\"\n + \" expected: \" + to_string(expected) + \"\\n\";\n }\n\n ValueT(bool status, pair loc, int len, V const & actual, string const & expected, bool const & strict = false)\n : status(status), loc(loc), len(len), actual(actual), expected(expected), strict(strict) {}\n\n static ValueT Success(pair loc, int len, V const & actual, string const & expected, bool const & strict = false) {\n return ValueT(true, loc, len, actual, expected, strict);\n }\n\n static ValueT Failure(pair loc, int len, V const & actual, string const & expected, bool const & strict = false) {\n return ValueT(false, loc, len, actual, expected, strict);\n }\n};\n\nstruct ParseError: public exception {\n string const sname, message;\n pair const loc;\n ParseError(string const & sname, string const & message, pair const loc): exception(), sname(sname), message(message), loc(loc) {}\n const char *what() const noexcept { return (sname + \": \" + message).c_str(); }\n};\n\n\n\/**\n * Parser model, wraps a function parse a Value object from a stream at specified position.\n *\/\ntemplate\nstruct ParsecT {\nprivate:\n P const parser;\npublic:\n using V = typename P::parser_type;\n constexpr ParsecT(P const & parser): parser(parser) {}\n string name() const { return \"ParsecT\"; }\n ValueT parse(input_t *text) const {\n pair loc = make_pair(1, 1);\n tuple res;\n try { \/\/ try exception throwed during operating the stream object.\n res = parser(text);\n } catch (std::exception & e) {\n cout << string(\"!!!Exception: \") + string(e.what()) << endl;\n res = make_tuple(-1, V(), \"!!!Exception: \" + string(e.what()));\n } catch (...) {\n cout << string(\"!!!Exception: \") + \"unknown exception.\" << endl;\n }\n text = text->next(std::get<0>(res)); \/\/ move ahead offset.\n if (!text->empty()) {\n \/\/ cout << \"NOT COMSUME ALL TOKEN IN THE INPUT STREAM!\" << endl;\n \/\/ cout << \" in stream: \" << (*text) << endl;\n }\n return ValueT(std::get<0>(res) != -1, loc, std::get<0>(res), std::get<1>(res), std::get<2>(res), text->empty());\n }\n ValueT operator () (input_t *text) const {\n return this->parse(text);\n }\n};\n\ntemplate\nclass parser_t {\nprivate:\n pair loc;\n string const desc;\n function(input_t *)> fn;\npublic:\n using parser_type = T;\n parser_t(string const desc): desc(desc) {}\n parser_t(string const desc, function(input_t *)> fn): desc(desc), fn(fn) {}\n ~parser_t() {}\n void setfn(function(input_t *)> const & fn) {\n this->fn = fn;\n }\n tuple operator () (input_t *text) const {\n auto res = this->fn(text);\n return make_tuple(res.first, res.second, this->name());\n }\n string const name() const { return this->desc; }\n};\n\n\n#endif \/* __PARSE_TOOL_HPP__ *\/\nFix a bug.#ifndef __PARSE_TOOL_HPP__\n#define __PARSE_TOOL_HPP__\n\n#include \n#include \nusing namespace std;\n\n\/\/ data type: Maybe\ntemplate\nstruct Maybe{\nprivate:\n bool const nil;\n T const val;\npublic:\n using data_type = T;\n constexpr Maybe(): nil(true) {}\n constexpr Maybe(T const & val): val(val), nil(false) {}\n bool Nil() const { return this->nil; }\n T Val() const { if (this->nil) { throw val; } else { return val; } }\n constexpr operator bool () const { return this->nil == false; }\n};\ntemplate\nconstexpr Maybe const Just(T const & val) {\n return Maybe(val);\n}\ntemplate\nconstexpr Maybe const Nothing() {\n return Maybe();\n}\ntemplate\nconstexpr T const FromJust(Maybe const & wrapper) {\n return wrapper.Val();\n}\n\n\/**\n * The result representation of a parser. `Success` and `Failure` are used to construct Value object, while\n * `Aggregate` is used to accmulate two Value object into one.\n *\/\ntemplate\nstruct ValueT {\n bool const status;\n pair loc;\n int len;\n V const actual;\n string expected;\n bool strict;\n\n string to_string(int n) const { return ::to_string(n); }\n string to_string(char c) const { return string(1, c); }\n string to_string(string s) const { return s; }\n string to_string(vector vec) const { string ans = \"vector char: \"; for (char c: vec) { ans.push_back(c); ans.push_back(','); } return ans; }\n string to_string(vector vec) const { string ans = \"vector string: \"; for (string s: vec) { ans += s + \",\"; } return ans; }\n\n string name() const {\n return \"stream @ \" + ::to_string(loc.first) + \":\" + ::to_string(loc.second)\n + \", \" + (status ? \"true\" : \"false\") + \", length: \" + ::to_string(len) + \"\\n\"\n + \" actual: \" + to_string(actual) + \"\\n\"\n + \" expected: \" + to_string(expected) + \"\\n\";\n }\n\n ValueT(bool status, pair loc, int len, V const & actual, string const & expected, bool const & strict = false)\n : status(status), loc(loc), len(len), actual(actual), expected(expected), strict(strict) {}\n\n static ValueT Success(pair loc, int len, V const & actual, string const & expected, bool const & strict = false) {\n return ValueT(true, loc, len, actual, expected, strict);\n }\n\n static ValueT Failure(pair loc, int len, V const & actual, string const & expected, bool const & strict = false) {\n return ValueT(false, loc, len, actual, expected, strict);\n }\n};\n\nstruct ParseError: public exception {\n string const sname, message;\n pair const loc;\n ParseError(string const & sname, string const & message, pair const loc): exception(), sname(sname), message(message), loc(loc) {}\n const char *what() const noexcept { return (sname + \": \" + message).c_str(); }\n};\n\n\n\/**\n * Parser model, wraps a function parse a Value object from a stream at specified position.\n *\/\ntemplate\nstruct ParsecT {\nprivate:\n P const parser;\npublic:\n using V = typename P::parser_type;\n constexpr ParsecT(P const & parser): parser(parser) {}\n string name() const { return \"ParsecT\"; }\n ValueT parse(input_t *text) const {\n pair loc = make_pair(1, 1);\n tuple res;\n try { \/\/ try exception throwed during operating the stream object.\n res = parser(text);\n } catch (std::exception & e) {\n cout << string(\"!!!Exception: \") + string(e.what()) << endl;\n res = make_tuple(-1, V(), \"!!!Exception: \" + string(e.what()));\n } catch (...) {\n cout << string(\"!!!Exception: \") + \"unknown exception.\" << endl;\n }\n text = text->next(std::get<0>(res)); \/\/ move ahead offset.\n if (!text->empty()) {\n \/\/ cout << \"NOT COMSUME ALL TOKEN IN THE INPUT STREAM!\" << endl;\n \/\/ cout << \" in stream: \" << (*text) << endl;\n }\n return ValueT(std::get<0>(res) != -1, loc, std::get<0>(res), std::get<1>(res), std::get<2>(res), text->empty());\n }\n ValueT operator () (input_t *text) const {\n return this->parse(text);\n }\n};\n\ntemplate\nclass parser_t {\nprivate:\n pair loc;\n string const desc;\n function(input_t *)> fn;\npublic:\n using parser_type = T;\n parser_t(string const desc): desc(desc) {}\n parser_t(string const desc, function(input_t *)> fn): desc(desc), fn(fn) {}\n ~parser_t() {}\n void setfn(function(input_t *)> const & fn) {\n this->fn = fn;\n }\n tuple operator () (input_t *text) const {\n auto res = this->fn(text);\n return make_tuple(res.first, res.second, this->name());\n }\n string const name() const { return this->desc; }\n};\n\n\n#endif \/* __PARSE_TOOL_HPP__ *\/\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\n\/\/ Blueberry\n#include \n#include \n#include \n\n\/\/ Qmitk\n#include \"QmitkStochasticFiberTrackingView.h\"\n#include \"QmitkStdMultiWidget.h\"\n\n\/\/ Qt\n#include \n\n\/\/ MITK\n#include \n#include \n\n\/\/ VTK\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nconst std::string QmitkStochasticFiberTrackingView::VIEW_ID = \"org.mitk.views.stochasticfibertracking\";\nconst std::string id_DataManager = \"org.mitk.views.datamanager\";\nusing namespace berry;\n\nQmitkStochasticFiberTrackingView::QmitkStochasticFiberTrackingView()\n : QmitkFunctionality()\n , m_Controls( 0 )\n , m_MultiWidget( NULL )\n , m_SeedRoi( NULL )\n , m_DiffusionImage( NULL )\n{\n}\n\n\/\/ Destructor\nQmitkStochasticFiberTrackingView::~QmitkStochasticFiberTrackingView()\n{\n\n}\n\nvoid QmitkStochasticFiberTrackingView::CreateQtPartControl( QWidget *parent )\n{\n if ( !m_Controls )\n {\n \/\/ create GUI widgets from the Qt Designer's .ui file\n m_Controls = new Ui::QmitkStochasticFiberTrackingViewControls;\n m_Controls->setupUi( parent );\n\n connect( m_Controls->commandLinkButton, SIGNAL(clicked()), this, SLOT(DoFiberTracking()) );\n connect( m_Controls->m_SeedsPerVoxelSlider, SIGNAL(valueChanged(int)), this, SLOT(OnSeedsPerVoxelChanged(int)) );\n connect( m_Controls->m_MaxCacheSizeSlider, SIGNAL(valueChanged(int)), this, SLOT(OnMaxCacheSizeChanged(int)) );\n connect( m_Controls->m_MaxTractLengthSlider, SIGNAL(valueChanged(int)), this, SLOT(OnMaxTractLengthChanged(int)) );\n }\n}\n\nvoid QmitkStochasticFiberTrackingView::OnSeedsPerVoxelChanged(int value)\n{\n m_Controls->m_SeedsPerVoxelLabel->setText(QString(\"Seeds per Voxel: \")+QString::number(value));\n}\n\nvoid QmitkStochasticFiberTrackingView::OnMaxTractLengthChanged(int value)\n{\n m_Controls->m_MaxTractLengthLabel->setText(QString(\"Max. Tract Length: \")+QString::number(value));\n}\n\nvoid QmitkStochasticFiberTrackingView::OnMaxCacheSizeChanged(int value)\n{\n m_Controls->m_MaxCacheSizeLabel->setText(QString(\"Max. Cache Size: \")+QString::number(value)+\"GB\");\n}\n\nvoid QmitkStochasticFiberTrackingView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget)\n{\n m_MultiWidget = &stdMultiWidget;\n}\n\n\nvoid QmitkStochasticFiberTrackingView::StdMultiWidgetNotAvailable()\n{\n m_MultiWidget = NULL;\n}\n\nvoid QmitkStochasticFiberTrackingView::OnSelectionChanged( std::vector nodes )\n{\n m_DiffusionImageNode = NULL;\n m_DiffusionImage = NULL;\n m_SeedRoi = NULL;\n m_Controls->m_DiffusionImageLabel->setText(\"mandatory<\/font>\");\n m_Controls->m_RoiImageLabel->setText(\"mandatory<\/font>\");\n\n for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it )\n {\n mitk::DataNode::Pointer node = *it;\n\n if( node.IsNotNull() && dynamic_cast(node->GetData()) )\n {\n if( dynamic_cast*>(node->GetData()) )\n {\n m_DiffusionImageNode = node;\n m_DiffusionImage = dynamic_cast*>(node->GetData());\n m_Controls->m_DiffusionImageLabel->setText(node->GetName().c_str());\n }\n else\n {\n bool isBinary = false;\n node->GetPropertyValue(\"binary\", isBinary);\n if (isBinary)\n {\n m_SeedRoi = dynamic_cast(node->GetData());\n m_Controls->m_RoiImageLabel->setText(node->GetName().c_str());\n }\n }\n }\n }\n\n if(m_DiffusionImage.IsNotNull() && m_SeedRoi.IsNotNull())\n {\n m_Controls->m_InputData->setTitle(\"Input Data\");\n m_Controls->commandLinkButton->setEnabled(true);\n }\n else\n {\n m_Controls->m_InputData->setTitle(\"Please Select Input Data\");\n m_Controls->commandLinkButton->setEnabled(false);\n }\n}\n\n\n\nvoid QmitkStochasticFiberTrackingView::DoFiberTracking()\n{\n typedef itk::VectorImage< short int, 3 > DWIVectorImageType;\n typedef itk::Image< float, 3 > FloatImageType;\n typedef itk::Image< unsigned int, 3 > CImageType;\n typedef itk::StochasticTractographyFilter< DWIVectorImageType, FloatImageType, CImageType > TrackingFilterType;\n typedef itk::DTITubeSpatialObject<3> DTITubeType;\n typedef itk::DTITubeSpatialObjectPoint<3> DTITubePointType;\n typedef itk::SceneSpatialObject<3> SceneSpatialObjectType;\n\n \/* get Gradients\/Direction of dwi *\/\n itk::VectorContainer< unsigned int, vnl_vector_fixed >::Pointer Pdir = m_DiffusionImage->GetDirections();\n\n \/* bValueContainer, Container includes b-values according to corresponding gradient-direction*\/\n TrackingFilterType::bValueContainerType::Pointer vecCont = TrackingFilterType::bValueContainerType::New();\n\n \/* for each gradient set b-Value; for 0-gradient set b-value eq. 0 *\/\n for ( int i=0; i<(int)Pdir->size(); ++i)\n {\n vnl_vector_fixed valsGrad = Pdir->at(i);\n if (valsGrad.get(0) == 0 && valsGrad.get(1) == 0 && valsGrad.get(2) == 0)\n { \/\/set 0-Gradient to bValue 0\n vecCont->InsertElement(i,0);\n }else{\n vecCont->InsertElement(i,m_DiffusionImage->GetB_Value());\n }\n }\n\n \/* define measurement frame (identity-matrix 3x3) *\/\n TrackingFilterType::MeasurementFrameType measurement_frame = m_DiffusionImage->GetMeasurementFrame();\n\n \/* generate white matterImage (dummy?)*\/\n FloatImageType::Pointer wmImage = FloatImageType::New();\n wmImage->SetSpacing( m_DiffusionImage->GetVectorImage()->GetSpacing() );\n wmImage->SetOrigin( m_DiffusionImage->GetVectorImage()->GetOrigin() );\n wmImage->SetDirection( m_DiffusionImage->GetVectorImage()->GetDirection() );\n wmImage->SetLargestPossibleRegion( m_DiffusionImage->GetVectorImage()->GetLargestPossibleRegion() );\n wmImage->SetBufferedRegion( wmImage->GetLargestPossibleRegion() );\n wmImage->SetRequestedRegion( wmImage->GetLargestPossibleRegion() );\n wmImage->Allocate();\n\n itk::ImageRegionIterator ot(wmImage, wmImage->GetLargestPossibleRegion() );\n while (!ot.IsAtEnd())\n {\n ot.Set(1);\n ++ot;\n }\n\n \/* init TractographyFilter *\/\n TrackingFilterType::Pointer trackingFilter = TrackingFilterType::New();\n trackingFilter->SetInput(m_DiffusionImage->GetVectorImage().GetPointer());\n trackingFilter->SetbValues(vecCont);\n trackingFilter->SetGradients(Pdir);\n trackingFilter->SetMeasurementFrame(measurement_frame);\n trackingFilter->SetWhiteMatterProbabilityImage(wmImage);\n trackingFilter->SetTotalTracts(m_Controls->m_SeedsPerVoxelSlider->value());\n trackingFilter->SetMaxLikelihoodCacheSize(m_Controls->m_MaxCacheSizeSlider->value()*1000);\n trackingFilter->SetMaxTractLength(m_Controls->m_MaxTractLengthSlider->value());\n\n \/\/itk::Image< char, 3 >\n mitk::ImageToItk< itk::Image< unsigned char, 3 > >::Pointer binaryImageToItk1 = mitk::ImageToItk< itk::Image< unsigned char, 3 > >::New();\n binaryImageToItk1->SetInput( m_SeedRoi );\n binaryImageToItk1->Update();\n\n vtkSmartPointer vPoints = vtkSmartPointer::New();\n vtkSmartPointer vCellArray = vtkSmartPointer::New();\n\n itk::ImageRegionConstIterator< BinaryImageType > it(binaryImageToItk1->GetOutput(), binaryImageToItk1->GetOutput()->GetRequestedRegion());\n it.GoToBegin();\n mitk::Geometry3D* geom = m_DiffusionImage->GetGeometry();\n\n while(!it.IsAtEnd())\n {\n itk::ImageConstIterator::PixelType tmpPxValue = it.Get();\n\n if(tmpPxValue != 0){\n mitk::Point3D point;\n itk::ImageRegionConstIterator< BinaryImageType >::IndexType seedIdx = it.GetIndex();\n trackingFilter->SetSeedIndex(seedIdx);\n trackingFilter->Update();\n\n\n \/* get results from Filter *\/\n \/* write each single tract into member container *\/\n TrackingFilterType::TractContainerType::Pointer container_tmp = trackingFilter->GetOutputTractContainer();\n TrackingFilterType::TractContainerType::Iterator elIt = container_tmp->Begin();\n TrackingFilterType::TractContainerType::Iterator end = container_tmp->End();\n bool addTract = true;\n\n while( elIt != end ){\n TrackingFilterType::TractContainerType::Element tract = elIt.Value();\n TrackingFilterType::TractContainerType::Element::ObjectType::VertexListType::ConstPointer vertexlist = tract->GetVertexList();\n\n vtkSmartPointer vPolyLine = vtkSmartPointer::New();\n for( int j=0; j<(int)vertexlist->Size(); j++)\n {\n TrackingFilterType::TractContainerType::Element::ObjectType::VertexListType::Element vertex = vertexlist->GetElement(j);\n mitk::Point3D index;\n index[0] = (float)vertex[0];\n index[1] = (float)vertex[1];\n index[2] = (float)vertex[2];\n\n if (geom->IsIndexInside(index))\n {\n geom->IndexToWorld(index, point);\n vtkIdType id = vPoints->InsertNextPoint(point.GetDataPointer());\n vPolyLine->GetPointIds()->InsertNextId(id);\n }\n else\n {\n addTract = false;\n break;\n }\n }\n\n if (addTract)\n vCellArray->InsertNextCell(vPolyLine);\n\n ++elIt;\n }\n }\n ++it;\n }\n\n vtkSmartPointer fiberPolyData = vtkSmartPointer::New();\n fiberPolyData->SetPoints(vPoints);\n fiberPolyData->SetLines(vCellArray);\n\n mitk::FiberBundleX::Pointer fib = mitk::FiberBundleX::New(fiberPolyData);\n mitk::DataNode::Pointer fbNode = mitk::DataNode::New();\n fbNode->SetData(fib);\n QString name(\"FiberBundle_\");\n name += m_DiffusionImageNode->GetName().c_str();\n name += \"_Probabilistic\";\n fbNode->SetName(name.toStdString());\n fbNode->SetVisibility(true);\n GetDataStorage()->Add(fbNode, m_DiffusionImageNode);\n}\n\n\nUsage of itkStochasticTractographyFilter changed, so SetInput is now SetPrimaryInput.\/*===================================================================\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\n\/\/ Blueberry\n#include \n#include \n#include \n\n\/\/ Qmitk\n#include \"QmitkStochasticFiberTrackingView.h\"\n#include \"QmitkStdMultiWidget.h\"\n\n\/\/ Qt\n#include \n\n\/\/ MITK\n#include \n#include \n\n\/\/ VTK\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nconst std::string QmitkStochasticFiberTrackingView::VIEW_ID = \"org.mitk.views.stochasticfibertracking\";\nconst std::string id_DataManager = \"org.mitk.views.datamanager\";\nusing namespace berry;\n\nQmitkStochasticFiberTrackingView::QmitkStochasticFiberTrackingView()\n : QmitkFunctionality()\n , m_Controls( 0 )\n , m_MultiWidget( NULL )\n , m_SeedRoi( NULL )\n , m_DiffusionImage( NULL )\n{\n}\n\n\/\/ Destructor\nQmitkStochasticFiberTrackingView::~QmitkStochasticFiberTrackingView()\n{\n\n}\n\nvoid QmitkStochasticFiberTrackingView::CreateQtPartControl( QWidget *parent )\n{\n if ( !m_Controls )\n {\n \/\/ create GUI widgets from the Qt Designer's .ui file\n m_Controls = new Ui::QmitkStochasticFiberTrackingViewControls;\n m_Controls->setupUi( parent );\n\n connect( m_Controls->commandLinkButton, SIGNAL(clicked()), this, SLOT(DoFiberTracking()) );\n connect( m_Controls->m_SeedsPerVoxelSlider, SIGNAL(valueChanged(int)), this, SLOT(OnSeedsPerVoxelChanged(int)) );\n connect( m_Controls->m_MaxCacheSizeSlider, SIGNAL(valueChanged(int)), this, SLOT(OnMaxCacheSizeChanged(int)) );\n connect( m_Controls->m_MaxTractLengthSlider, SIGNAL(valueChanged(int)), this, SLOT(OnMaxTractLengthChanged(int)) );\n }\n}\n\nvoid QmitkStochasticFiberTrackingView::OnSeedsPerVoxelChanged(int value)\n{\n m_Controls->m_SeedsPerVoxelLabel->setText(QString(\"Seeds per Voxel: \")+QString::number(value));\n}\n\nvoid QmitkStochasticFiberTrackingView::OnMaxTractLengthChanged(int value)\n{\n m_Controls->m_MaxTractLengthLabel->setText(QString(\"Max. Tract Length: \")+QString::number(value));\n}\n\nvoid QmitkStochasticFiberTrackingView::OnMaxCacheSizeChanged(int value)\n{\n m_Controls->m_MaxCacheSizeLabel->setText(QString(\"Max. Cache Size: \")+QString::number(value)+\"GB\");\n}\n\nvoid QmitkStochasticFiberTrackingView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget)\n{\n m_MultiWidget = &stdMultiWidget;\n}\n\n\nvoid QmitkStochasticFiberTrackingView::StdMultiWidgetNotAvailable()\n{\n m_MultiWidget = NULL;\n}\n\nvoid QmitkStochasticFiberTrackingView::OnSelectionChanged( std::vector nodes )\n{\n m_DiffusionImageNode = NULL;\n m_DiffusionImage = NULL;\n m_SeedRoi = NULL;\n m_Controls->m_DiffusionImageLabel->setText(\"mandatory<\/font>\");\n m_Controls->m_RoiImageLabel->setText(\"mandatory<\/font>\");\n\n for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it )\n {\n mitk::DataNode::Pointer node = *it;\n\n if( node.IsNotNull() && dynamic_cast(node->GetData()) )\n {\n if( dynamic_cast*>(node->GetData()) )\n {\n m_DiffusionImageNode = node;\n m_DiffusionImage = dynamic_cast*>(node->GetData());\n m_Controls->m_DiffusionImageLabel->setText(node->GetName().c_str());\n }\n else\n {\n bool isBinary = false;\n node->GetPropertyValue(\"binary\", isBinary);\n if (isBinary)\n {\n m_SeedRoi = dynamic_cast(node->GetData());\n m_Controls->m_RoiImageLabel->setText(node->GetName().c_str());\n }\n }\n }\n }\n\n if(m_DiffusionImage.IsNotNull() && m_SeedRoi.IsNotNull())\n {\n m_Controls->m_InputData->setTitle(\"Input Data\");\n m_Controls->commandLinkButton->setEnabled(true);\n }\n else\n {\n m_Controls->m_InputData->setTitle(\"Please Select Input Data\");\n m_Controls->commandLinkButton->setEnabled(false);\n }\n}\n\n\n\nvoid QmitkStochasticFiberTrackingView::DoFiberTracking()\n{\n typedef itk::VectorImage< short int, 3 > DWIVectorImageType;\n typedef itk::Image< float, 3 > FloatImageType;\n typedef itk::Image< unsigned int, 3 > CImageType;\n typedef itk::StochasticTractographyFilter< DWIVectorImageType, FloatImageType, CImageType > TrackingFilterType;\n typedef itk::DTITubeSpatialObject<3> DTITubeType;\n typedef itk::DTITubeSpatialObjectPoint<3> DTITubePointType;\n typedef itk::SceneSpatialObject<3> SceneSpatialObjectType;\n\n \/* get Gradients\/Direction of dwi *\/\n itk::VectorContainer< unsigned int, vnl_vector_fixed >::Pointer Pdir = m_DiffusionImage->GetDirections();\n\n \/* bValueContainer, Container includes b-values according to corresponding gradient-direction*\/\n TrackingFilterType::bValueContainerType::Pointer vecCont = TrackingFilterType::bValueContainerType::New();\n\n \/* for each gradient set b-Value; for 0-gradient set b-value eq. 0 *\/\n for ( int i=0; i<(int)Pdir->size(); ++i)\n {\n vnl_vector_fixed valsGrad = Pdir->at(i);\n if (valsGrad.get(0) == 0 && valsGrad.get(1) == 0 && valsGrad.get(2) == 0)\n { \/\/set 0-Gradient to bValue 0\n vecCont->InsertElement(i,0);\n }else{\n vecCont->InsertElement(i,m_DiffusionImage->GetB_Value());\n }\n }\n\n \/* define measurement frame (identity-matrix 3x3) *\/\n TrackingFilterType::MeasurementFrameType measurement_frame = m_DiffusionImage->GetMeasurementFrame();\n\n \/* generate white matterImage (dummy?)*\/\n FloatImageType::Pointer wmImage = FloatImageType::New();\n wmImage->SetSpacing( m_DiffusionImage->GetVectorImage()->GetSpacing() );\n wmImage->SetOrigin( m_DiffusionImage->GetVectorImage()->GetOrigin() );\n wmImage->SetDirection( m_DiffusionImage->GetVectorImage()->GetDirection() );\n wmImage->SetLargestPossibleRegion( m_DiffusionImage->GetVectorImage()->GetLargestPossibleRegion() );\n wmImage->SetBufferedRegion( wmImage->GetLargestPossibleRegion() );\n wmImage->SetRequestedRegion( wmImage->GetLargestPossibleRegion() );\n wmImage->Allocate();\n\n itk::ImageRegionIterator ot(wmImage, wmImage->GetLargestPossibleRegion() );\n while (!ot.IsAtEnd())\n {\n ot.Set(1);\n ++ot;\n }\n\n \/* init TractographyFilter *\/\n TrackingFilterType::Pointer trackingFilter = TrackingFilterType::New();\n trackingFilter->SetPrimaryInput(m_DiffusionImage->GetVectorImage().GetPointer());\n trackingFilter->SetbValues(vecCont);\n trackingFilter->SetGradients(Pdir);\n trackingFilter->SetMeasurementFrame(measurement_frame);\n trackingFilter->SetWhiteMatterProbabilityImage(wmImage);\n trackingFilter->SetTotalTracts(m_Controls->m_SeedsPerVoxelSlider->value());\n trackingFilter->SetMaxLikelihoodCacheSize(m_Controls->m_MaxCacheSizeSlider->value()*1000);\n trackingFilter->SetMaxTractLength(m_Controls->m_MaxTractLengthSlider->value());\n\n \/\/itk::Image< char, 3 >\n mitk::ImageToItk< itk::Image< unsigned char, 3 > >::Pointer binaryImageToItk1 = mitk::ImageToItk< itk::Image< unsigned char, 3 > >::New();\n binaryImageToItk1->SetInput( m_SeedRoi );\n binaryImageToItk1->Update();\n\n vtkSmartPointer vPoints = vtkSmartPointer::New();\n vtkSmartPointer vCellArray = vtkSmartPointer::New();\n\n itk::ImageRegionConstIterator< BinaryImageType > it(binaryImageToItk1->GetOutput(), binaryImageToItk1->GetOutput()->GetRequestedRegion());\n it.GoToBegin();\n mitk::Geometry3D* geom = m_DiffusionImage->GetGeometry();\n\n while(!it.IsAtEnd())\n {\n itk::ImageConstIterator::PixelType tmpPxValue = it.Get();\n\n if(tmpPxValue != 0){\n mitk::Point3D point;\n itk::ImageRegionConstIterator< BinaryImageType >::IndexType seedIdx = it.GetIndex();\n trackingFilter->SetSeedIndex(seedIdx);\n trackingFilter->Update();\n\n\n \/* get results from Filter *\/\n \/* write each single tract into member container *\/\n TrackingFilterType::TractContainerType::Pointer container_tmp = trackingFilter->GetOutputTractContainer();\n TrackingFilterType::TractContainerType::Iterator elIt = container_tmp->Begin();\n TrackingFilterType::TractContainerType::Iterator end = container_tmp->End();\n bool addTract = true;\n\n while( elIt != end ){\n TrackingFilterType::TractContainerType::Element tract = elIt.Value();\n TrackingFilterType::TractContainerType::Element::ObjectType::VertexListType::ConstPointer vertexlist = tract->GetVertexList();\n\n vtkSmartPointer vPolyLine = vtkSmartPointer::New();\n for( int j=0; j<(int)vertexlist->Size(); j++)\n {\n TrackingFilterType::TractContainerType::Element::ObjectType::VertexListType::Element vertex = vertexlist->GetElement(j);\n mitk::Point3D index;\n index[0] = (float)vertex[0];\n index[1] = (float)vertex[1];\n index[2] = (float)vertex[2];\n\n if (geom->IsIndexInside(index))\n {\n geom->IndexToWorld(index, point);\n vtkIdType id = vPoints->InsertNextPoint(point.GetDataPointer());\n vPolyLine->GetPointIds()->InsertNextId(id);\n }\n else\n {\n addTract = false;\n break;\n }\n }\n\n if (addTract)\n vCellArray->InsertNextCell(vPolyLine);\n\n ++elIt;\n }\n }\n ++it;\n }\n\n vtkSmartPointer fiberPolyData = vtkSmartPointer::New();\n fiberPolyData->SetPoints(vPoints);\n fiberPolyData->SetLines(vCellArray);\n\n mitk::FiberBundleX::Pointer fib = mitk::FiberBundleX::New(fiberPolyData);\n mitk::DataNode::Pointer fbNode = mitk::DataNode::New();\n fbNode->SetData(fib);\n QString name(\"FiberBundle_\");\n name += m_DiffusionImageNode->GetName().c_str();\n name += \"_Probabilistic\";\n fbNode->SetName(name.toStdString());\n fbNode->SetVisibility(true);\n GetDataStorage()->Add(fbNode, m_DiffusionImageNode);\n}\n\n\n<|endoftext|>"} {"text":"\/\/ Harshad Kasture, Jason Miller, Chris Celio, Charles Gruenwald,\n\/\/ Nathan Beckmann, George Kurian, David Wentzlaff, James Psota\n\/\/ 10.12.08\n\/\/\n\/\/ Carbon Computer Simulator\n\/\/\n\/\/ This simulator models future multi-core computers with thousands of cores.\n\/\/ It runs on today's x86 multicores and will scale as more and more cores\n\/\/ and better inter-core communications mechanisms become available.\n\/\/ The simulator provides a platform for research in processor architecture,\n\/\/ compilers, network interconnect topologies, and some OS.\n\/\/\n\/\/ The simulator runs on top of Intel's Pin dynamic binary instrumention engine.\n\/\/ Application code in the absence of instrumentation runs more or less\n\/\/ natively and is thus high performance. When instrumentation is used, models\n\/\/ can be hot-swapped or dynamically enabled and disabled as desired so that\n\/\/ performance tracks the level of simulation detail needed.\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"pin.H\"\n#include \"log.h\"\n#include \"routine_replace.h\"\n\n\/\/ FIXME: This list could probably be trimmed down a lot.\n#include \"simulator.h\"\n#include \"core_manager.h\"\n#include \"config.h\"\n#include \"core.h\"\n#include \"syscall_model.h\"\n#include \"thread_manager.h\"\n#include \"config_file.hpp\"\n#include \"handle_args.h\"\n#include \"thread_start.h\"\n#include \"pin_config.h\"\n#include \"log.h\"\n#include \"vm_manager.h\"\n#include \"instruction_modeling.h\"\n#include \"progress_trace.h\"\n#include \"clock_skew_minimization.h\"\n\n#include \"redirect_memory.h\"\n#include \"handle_syscalls.h\"\n#include \"opcodes.h\"\n#include \n\n\/\/ lite directories\n#include \"lite\/routine_replace.h\"\n#include \"lite\/memory_modeling.h\"\n\n\/\/ ---------------------------------------------------------------\n\/\/ FIXME: \n\/\/ There should be a better place to keep these globals\n\/\/ -- a PinSimulator class or smthg\nbool done_app_initialization = false;\nconfig::ConfigFile *cfg;\n\n\/\/ clone stuff\nextern int *parent_tidptr;\n#ifdef TARGET_IA32\nextern struct user_desc *newtls;\n#endif\nextern int *child_tidptr;\n\nextern PIN_LOCK clone_memory_update_lock;\n\/\/ ---------------------------------------------------------------\n\nmap rtn_map;\nPIN_LOCK rtn_map_lock;\n\nvoid printRtn (ADDRINT rtn_addr, bool enter)\n{\n GetLock (&rtn_map_lock, 1);\n map::iterator it = rtn_map.find (rtn_addr);\n\n string point = enter ? \"Enter\" : \"Exit\";\n if (it != rtn_map.end())\n {\n LOG_PRINT (\"Stack trace : %s %s\", point.c_str(), (it->second).c_str());\n }\n else\n {\n LOG_PRINT (\"Stack trace : %s UNKNOWN\", point.c_str());\n }\n \n ReleaseLock (&rtn_map_lock);\n}\n\nVOID printInsInfo(CONTEXT* ctxt)\n{\n __attribute(__unused__) ADDRINT reg_inst_ptr = PIN_GetContextReg(ctxt, REG_INST_PTR);\n __attribute(__unused__) ADDRINT reg_stack_ptr = PIN_GetContextReg(ctxt, REG_STACK_PTR);\n\n LOG_PRINT(\"eip = %#llx, esp = %#llx\", reg_inst_ptr, reg_stack_ptr);\n}\n\nvoid initializeSyscallModeling ()\n{\n InitLock (&clone_memory_update_lock);\n}\n\nvoid routineCallback(RTN rtn, void *v)\n{\n string rtn_name = RTN_Name(rtn);\n \n replaceUserAPIFunction(rtn, rtn_name);\n\n \/\/ ---------------------------------------------------------------\n\n std::string module = Log::getSingleton()->getModule(__FILE__);\n if (Log::getSingleton()->isEnabled(module.c_str()) &&\n Sim()->getCfg()->getBool(\"log\/stack_trace\",false))\n {\n RTN_Open (rtn);\n \n ADDRINT rtn_addr = RTN_Address (rtn);\n \n GetLock (&rtn_map_lock, 1);\n \n rtn_map.insert (make_pair (rtn_addr, rtn_name));\n\n ReleaseLock (&rtn_map_lock);\n \n RTN_InsertCall (rtn, IPOINT_BEFORE,\n AFUNPTR (printRtn),\n IARG_ADDRINT, rtn_addr,\n IARG_BOOL, true,\n IARG_END);\n\n RTN_InsertCall (rtn, IPOINT_AFTER,\n AFUNPTR (printRtn),\n IARG_ADDRINT, rtn_addr,\n IARG_BOOL, false,\n IARG_END);\n\n RTN_Close (rtn);\n }\n\n \/\/ ---------------------------------------------------------------\n\n if (rtn_name == \"CarbonSpawnThreadSpawner\")\n {\n RTN_Open (rtn);\n\n RTN_InsertCall (rtn, IPOINT_BEFORE,\n AFUNPTR (setupCarbonSpawnThreadSpawnerStack),\n IARG_CONTEXT,\n IARG_END);\n\n RTN_Close (rtn);\n }\n\n else if (rtn_name == \"CarbonThreadSpawner\")\n {\n RTN_Open (rtn);\n\n RTN_InsertCall (rtn, IPOINT_BEFORE,\n AFUNPTR (setupCarbonThreadSpawnerStack),\n IARG_CONTEXT,\n IARG_END);\n\n RTN_Close(rtn);\n }\n}\n\nvoid showInstructionInfo(INS ins)\n{\n if (Sim()->getCoreManager()->getCurrentCore()->getId() != 0)\n return;\n printf(\"\\t\");\n if (INS_IsMemoryRead(ins) || INS_IsMemoryWrite(ins))\n printf(\"* \");\n else\n printf(\" \");\n\/\/ printf(\"%d - %s \", INS_Category(ins), CATEGORY_StringShort(INS_Category(ins)).c_str());\n printf(\"%x - %s \", INS_Opcode(ins), OPCODE_StringShort(INS_Opcode(ins)).c_str());\n printf(\" %s \", INS_Disassemble(ins).c_str());\n printf(\"\\n\");\n}\n\nVOID instructionCallback (INS ins, void *v)\n{\n \/\/ Debugging Functions\n \/\/ showInstructionInfo(ins);\n if (Log::getSingleton()->isLoggingEnabled())\n {\n INS_InsertCall(ins, IPOINT_BEFORE,\n AFUNPTR(printInsInfo),\n IARG_CALL_ORDER, CALL_ORDER_FIRST,\n IARG_CONTEXT,\n IARG_END);\n }\n\n \/\/ Core Performance Modeling\n if (Config::getSingleton()->getEnablePerformanceModeling())\n addInstructionModeling(ins);\n\n \/\/ Progress Trace\n addProgressTrace(ins);\n \/\/ Clock Skew Minimization\n addPeriodicSync(ins);\n\n if (Sim()->getConfig()->getSimulationMode() == Config::FULL)\n {\n \/\/ Special handling for futex syscall because of internal Pin lock\n if (INS_IsSyscall(ins))\n {\n INS_InsertCall(ins, IPOINT_BEFORE,\n AFUNPTR(handleFutexSyscall),\n IARG_CONTEXT,\n IARG_END);\n }\n\n \/\/ Emulate(\/Rewrite) String, Stack and Memory Operations\n if (rewriteStringOp (ins));\n else if (rewriteStackOp (ins));\n else rewriteMemOp (ins);\n }\n else \/\/ Sim()->getConfig()->getSimulationMode() == Config::LITE\n {\n \/\/ Instrument Memory Operations\n lite::addMemoryModeling(ins);\n }\n}\n\n\/\/ syscall model wrappers\n\nvoid SyscallEntry(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, void *v)\n{\n syscallEnterRunModel (ctxt, std);\n}\n\nvoid SyscallExit(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, void *v)\n{\n syscallExitRunModel (ctxt, std);\n}\n\nvoid ApplicationStart()\n{\n}\n\nvoid ApplicationExit(int, void*)\n{\n LOG_PRINT(\"Application exit.\");\n Simulator::release();\n shutdownProgressTrace();\n delete cfg;\n}\n\nVOID threadStartCallback(THREADID threadIndex, CONTEXT *ctxt, INT32 flags, VOID *v)\n{\n threadStartProgressTrace();\n\n \/\/ Conditions under which we must initialize a core\n \/\/ 1) (!done_app_initialization) && (curr_process_num == 0)\n \/\/ 2) (done_app_initialization) && (!thread_spawner)\n\n if (! done_app_initialization)\n {\n UInt32 curr_process_num = Sim()->getConfig()->getCurrentProcessNum();\n\n if (Sim()->getConfig()->getSimulationMode() == Config::LITE)\n {\n LOG_ASSERT_ERROR(curr_process_num == 0, \"Lite mode can only be run with 1 process\");\n Sim()->getCoreManager()->initializeThread(0);\n }\n else \/\/ Sim()->getConfig()->getSimulationMode() == Config::FULL\n { \n ADDRINT reg_esp = PIN_GetContextReg(ctxt, REG_STACK_PTR);\n allocateStackSpace();\n \n if (curr_process_num == 0)\n {\n Sim()->getCoreManager()->initializeThread(0);\n\n ADDRINT reg_eip = PIN_GetContextReg(ctxt, REG_INST_PTR);\n \/\/ 1) Copying over Static Data\n \/\/ Get the image first\n PIN_LockClient();\n IMG img = IMG_FindByAddress(reg_eip);\n PIN_UnlockClient();\n\n LOG_PRINT(\"Process: 0, Start Copying Static Data\");\n copyStaticData(img);\n LOG_PRINT(\"Process: 0, Finished Copying Static Data\");\n\n \/\/ 2) Copying over initial stack data\n LOG_PRINT(\"Process: 0, Start Copying Initial Stack Data\");\n copyInitialStackData(reg_esp, 0);\n LOG_PRINT(\"Process: 0, Finished Copying Initial Stack Data\");\n }\n else\n {\n core_id_t core_id = Sim()->getConfig()->getCurrentThreadSpawnerCoreNum();\n Sim()->getCoreManager()->initializeThread(core_id);\n \n Core *core = Sim()->getCoreManager()->getCurrentCore();\n\n \/\/ main thread clock is not affected by start-up time of other processes\n core->getNetwork()->netRecv (0, SYSTEM_INITIALIZATION_NOTIFY);\n\n LOG_PRINT(\"Process: %i, Start Copying Initial Stack Data\");\n copyInitialStackData(reg_esp, core_id);\n LOG_PRINT(\"Process: %i, Finished Copying Initial Stack Data\");\n }\n\n \/\/ Set the current ESP accordingly\n PIN_SetContextReg(ctxt, REG_STACK_PTR, reg_esp);\n }\n \n \/\/ All the real initialization is done in \n \/\/ replacement_start at the moment\n done_app_initialization = true;\n }\n else\n {\n \/\/ This is NOT the main thread\n \/\/ 'application' thread or 'thread spawner'\n\n if (Sim()->getConfig()->getSimulationMode() == Config::LITE)\n {\n ThreadSpawnRequest req;\n Sim()->getThreadManager()->getThreadToSpawn(&req);\n Sim()->getThreadManager()->dequeueThreadSpawnReq(&req);\n\n LOG_ASSERT_ERROR(req.core_id < SInt32(Config::getSingleton()->getApplicationCores()),\n \"req.core_id(%i), num application cores(%u)\", req.core_id, Config::getSingleton()->getApplicationCores());\n Sim()->getThreadManager()->onThreadStart(&req);\n }\n else \/\/ Sim()->getConfig()->getSimulationMode() == Config::FULL\n {\n ADDRINT reg_esp = PIN_GetContextReg(ctxt, REG_STACK_PTR);\n core_id_t core_id = PinConfig::getSingleton()->getCoreIDFromStackPtr(reg_esp);\n\n LOG_ASSERT_ERROR(core_id != -1, \"All application threads and thread spawner are cores now\");\n\n if (core_id == Sim()->getConfig()->getCurrentThreadSpawnerCoreNum())\n {\n \/\/ 'Thread Spawner' thread\n Sim()->getCoreManager()->initializeThread(core_id);\n }\n else\n {\n \/\/ 'Application' thread\n ThreadSpawnRequest* req = Sim()->getThreadManager()->getThreadSpawnReq();\n\n LOG_ASSERT_ERROR (req != NULL, \"ThreadSpawnRequest is NULL !!\");\n\n \/\/ This is an application thread\n LOG_ASSERT_ERROR(core_id == req->core_id, \"Got 2 different core_ids: req->core_id = %i, core_id = %i\", req->core_id, core_id);\n\n Sim()->getThreadManager()->onThreadStart(req);\n }\n\n#ifdef TARGET_IA32 \n \/\/ Restore the clone syscall arguments\n PIN_SetContextReg (ctxt, REG_GDX, (ADDRINT) parent_tidptr);\n PIN_SetContextReg (ctxt, REG_GSI, (ADDRINT) newtls);\n PIN_SetContextReg (ctxt, REG_GDI, (ADDRINT) child_tidptr);\n#endif\n\n#ifdef TARGET_X86_64\n \/\/ Restore the clone syscall arguments\n PIN_SetContextReg (ctxt, REG_GDX, (ADDRINT) parent_tidptr);\n PIN_SetContextReg (ctxt, LEVEL_BASE::REG_R10, (ADDRINT) child_tidptr);\n#endif\n\n __attribute(__unused__) Core *core = Sim()->getCoreManager()->getCurrentCore();\n LOG_ASSERT_ERROR(core, \"core(NULL)\");\n\n \/\/ Wait to make sure that the spawner has written stuff back to memory\n \/\/ FIXME: What is this for(?) This seems arbitrary\n GetLock (&clone_memory_update_lock, 2);\n ReleaseLock (&clone_memory_update_lock);\n }\n }\n}\n\nVOID threadFiniCallback(THREADID threadIndex, const CONTEXT *ctxt, INT32 flags, VOID *v)\n{\n Sim()->getThreadManager()->onThreadExit();\n}\n\nint main(int argc, char *argv[])\n{\n \/\/ ---------------------------------------------------------------\n \/\/ FIXME: \n InitLock (&rtn_map_lock);\n \/\/ ---------------------------------------------------------------\n\n \/\/ Global initialization\n PIN_InitSymbols();\n PIN_Init(argc,argv);\n\n string_vec args;\n\n \/\/ Set the default config path if it isn't \n \/\/ overwritten on the command line.\n std::string config_path = \"carbon_sim.cfg\";\n\n parse_args(args, config_path, argc, argv);\n\n cfg = new config::ConfigFile();\n cfg->load(config_path);\n\n handle_args(args, *cfg);\n\n Simulator::setConfig(cfg);\n\n Simulator::allocate();\n Sim()->start();\n\n if (Sim()->getConfig()->getSimulationMode() == Config::FULL)\n PinConfig::allocate();\n\n \/\/ Instrumentation\n LOG_PRINT(\"Start of instrumentation.\");\n \n if (Sim()->getConfig()->getSimulationMode() == Config::FULL)\n RTN_AddInstrumentFunction(routineCallback, 0);\n else \/\/ Sim()->getConfig()->getSimulationMode() == Config::LITE\n RTN_AddInstrumentFunction(lite::routineCallback, 0);\n\n PIN_AddThreadStartFunction (threadStartCallback, 0);\n PIN_AddThreadFiniFunction (threadFiniCallback, 0);\n \n if ((cfg->getBool(\"general\/enable_syscall_modeling\")) && \\\n (Sim()->getConfig()->getSimulationMode() == Config::FULL))\n {\n initializeSyscallModeling();\n\n PIN_AddSyscallEntryFunction(SyscallEntry, 0);\n PIN_AddSyscallExitFunction(SyscallExit, 0);\n PIN_AddContextChangeFunction(contextChange, NULL);\n }\n\n INS_AddInstrumentFunction(instructionCallback, 0);\n\n initProgressTrace();\n\n PIN_AddFiniFunction(ApplicationExit, 0);\n\n \/\/ Just in case ... might not be strictly necessary\n Transport::getSingleton()->barrier();\n\n \/\/ Never returns\n LOG_PRINT(\"Running program...\");\n PIN_StartProgram();\n\n return 0;\n}\n[pin_sim] Some changes to pin\/pin_sim.cc\/\/ Harshad Kasture, Jason Miller, Chris Celio, Charles Gruenwald,\n\/\/ Nathan Beckmann, George Kurian, David Wentzlaff, James Psota\n\/\/ 10.12.08\n\/\/\n\/\/ Carbon Computer Simulator\n\/\/\n\/\/ This simulator models future multi-core computers with thousands of cores.\n\/\/ It runs on today's x86 multicores and will scale as more and more cores\n\/\/ and better inter-core communications mechanisms become available.\n\/\/ The simulator provides a platform for research in processor architecture,\n\/\/ compilers, network interconnect topologies, and some OS.\n\/\/\n\/\/ The simulator runs on top of Intel's Pin dynamic binary instrumention engine.\n\/\/ Application code in the absence of instrumentation runs more or less\n\/\/ natively and is thus high performance. When instrumentation is used, models\n\/\/ can be hot-swapped or dynamically enabled and disabled as desired so that\n\/\/ performance tracks the level of simulation detail needed.\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"pin.H\"\n#include \"log.h\"\n#include \"routine_replace.h\"\n\n\/\/ FIXME: This list could probably be trimmed down a lot.\n#include \"simulator.h\"\n#include \"core_manager.h\"\n#include \"config.h\"\n#include \"core.h\"\n#include \"syscall_model.h\"\n#include \"thread_manager.h\"\n#include \"config_file.hpp\"\n#include \"handle_args.h\"\n#include \"thread_start.h\"\n#include \"pin_config.h\"\n#include \"log.h\"\n#include \"vm_manager.h\"\n#include \"instruction_modeling.h\"\n#include \"progress_trace.h\"\n#include \"clock_skew_minimization.h\"\n\n#include \"redirect_memory.h\"\n#include \"handle_syscalls.h\"\n#include \"opcodes.h\"\n#include \n\n\/\/ lite directories\n#include \"lite\/routine_replace.h\"\n#include \"lite\/memory_modeling.h\"\n\n\/\/ ---------------------------------------------------------------\n\/\/ FIXME: \n\/\/ There should be a better place to keep these globals\n\/\/ -- a PinSimulator class or smthg\nbool done_app_initialization = false;\nconfig::ConfigFile *cfg;\n\n\/\/ clone stuff\nextern int *parent_tidptr;\n#ifdef TARGET_IA32\nextern struct user_desc *newtls;\n#endif\nextern int *child_tidptr;\n\nextern PIN_LOCK clone_memory_update_lock;\n\/\/ ---------------------------------------------------------------\n\nmap rtn_map;\nPIN_LOCK rtn_map_lock;\n\nvoid printRtn (ADDRINT rtn_addr, bool enter)\n{\n GetLock (&rtn_map_lock, 1);\n map::iterator it = rtn_map.find (rtn_addr);\n\n string point = enter ? \"Enter\" : \"Exit\";\n if (it != rtn_map.end())\n {\n LOG_PRINT (\"Stack trace : %s %s\", point.c_str(), (it->second).c_str());\n }\n else\n {\n LOG_PRINT (\"Stack trace : %s UNKNOWN\", point.c_str());\n }\n \n ReleaseLock (&rtn_map_lock);\n}\n\nVOID printInsInfo(CONTEXT* ctxt)\n{\n __attribute(__unused__) ADDRINT reg_inst_ptr = PIN_GetContextReg(ctxt, REG_INST_PTR);\n __attribute(__unused__) ADDRINT reg_stack_ptr = PIN_GetContextReg(ctxt, REG_STACK_PTR);\n\n LOG_PRINT(\"eip = %#llx, esp = %#llx\", reg_inst_ptr, reg_stack_ptr);\n}\n\nvoid initializeSyscallModeling ()\n{\n InitLock (&clone_memory_update_lock);\n}\n\nvoid routineCallback(RTN rtn, void *v)\n{\n string rtn_name = RTN_Name(rtn);\n \n replaceUserAPIFunction(rtn, rtn_name);\n\n \/\/ ---------------------------------------------------------------\n\n std::string module = Log::getSingleton()->getModule(__FILE__);\n if (Log::getSingleton()->isEnabled(module.c_str()) &&\n Sim()->getCfg()->getBool(\"log\/stack_trace\",false))\n {\n RTN_Open (rtn);\n \n ADDRINT rtn_addr = RTN_Address (rtn);\n \n GetLock (&rtn_map_lock, 1);\n \n rtn_map.insert (make_pair (rtn_addr, rtn_name));\n\n ReleaseLock (&rtn_map_lock);\n \n RTN_InsertCall (rtn, IPOINT_BEFORE,\n AFUNPTR (printRtn),\n IARG_ADDRINT, rtn_addr,\n IARG_BOOL, true,\n IARG_END);\n\n RTN_InsertCall (rtn, IPOINT_AFTER,\n AFUNPTR (printRtn),\n IARG_ADDRINT, rtn_addr,\n IARG_BOOL, false,\n IARG_END);\n\n RTN_Close (rtn);\n }\n\n \/\/ ---------------------------------------------------------------\n\n if (rtn_name == \"CarbonSpawnThreadSpawner\")\n {\n RTN_Open (rtn);\n\n RTN_InsertCall (rtn, IPOINT_BEFORE,\n AFUNPTR (setupCarbonSpawnThreadSpawnerStack),\n IARG_CONTEXT,\n IARG_END);\n\n RTN_Close (rtn);\n }\n\n else if (rtn_name == \"CarbonThreadSpawner\")\n {\n RTN_Open (rtn);\n\n RTN_InsertCall (rtn, IPOINT_BEFORE,\n AFUNPTR (setupCarbonThreadSpawnerStack),\n IARG_CONTEXT,\n IARG_END);\n\n RTN_Close(rtn);\n }\n}\n\nvoid showInstructionInfo(INS ins)\n{\n if (Sim()->getCoreManager()->getCurrentCore()->getId() != 0)\n return;\n printf(\"\\t\");\n if (INS_IsMemoryRead(ins) || INS_IsMemoryWrite(ins))\n printf(\"* \");\n else\n printf(\" \");\n\/\/ printf(\"%d - %s \", INS_Category(ins), CATEGORY_StringShort(INS_Category(ins)).c_str());\n printf(\"%x - %s \", INS_Opcode(ins), OPCODE_StringShort(INS_Opcode(ins)).c_str());\n printf(\" %s \", INS_Disassemble(ins).c_str());\n printf(\"\\n\");\n}\n\nVOID instructionCallback (INS ins, void *v)\n{\n \/\/ Debugging Functions\n \/\/ showInstructionInfo(ins);\n if (Log::getSingleton()->isLoggingEnabled())\n {\n INS_InsertCall(ins, IPOINT_BEFORE,\n AFUNPTR(printInsInfo),\n IARG_CALL_ORDER, CALL_ORDER_FIRST,\n IARG_CONTEXT,\n IARG_END);\n }\n\n \/\/ Core Performance Modeling\n if (Config::getSingleton()->getEnablePerformanceModeling())\n addInstructionModeling(ins);\n\n \/\/ Progress Trace\n addProgressTrace(ins);\n \/\/ Clock Skew Minimization\n addPeriodicSync(ins);\n\n if (Sim()->getConfig()->getSimulationMode() == Config::FULL)\n {\n \/\/ Special handling for futex syscall because of internal Pin lock\n if (INS_IsSyscall(ins))\n {\n INS_InsertCall(ins, IPOINT_BEFORE,\n AFUNPTR(handleFutexSyscall),\n IARG_CONTEXT,\n IARG_END);\n }\n\n \/\/ Emulate(\/Rewrite) String, Stack and Memory Operations\n if (rewriteStringOp (ins));\n else if (rewriteStackOp (ins));\n else rewriteMemOp (ins);\n }\n else \/\/ Sim()->getConfig()->getSimulationMode() == Config::LITE\n {\n \/\/ Instrument Memory Operations\n lite::addMemoryModeling(ins);\n }\n}\n\n\/\/ syscall model wrappers\n\nvoid SyscallEntry(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, void *v)\n{\n syscallEnterRunModel (ctxt, std);\n}\n\nvoid SyscallExit(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, void *v)\n{\n syscallExitRunModel (ctxt, std);\n}\n\nvoid ApplicationStart()\n{\n}\n\nvoid ApplicationExit(int, void*)\n{\n LOG_PRINT(\"Application exit.\");\n Simulator::release();\n shutdownProgressTrace();\n delete cfg;\n}\n\nVOID threadStartCallback(THREADID threadIndex, CONTEXT *ctxt, INT32 flags, VOID *v)\n{\n threadStartProgressTrace();\n\n \/\/ Conditions under which we must initialize a core\n \/\/ 1) (!done_app_initialization) && (curr_process_num == 0)\n \/\/ 2) (done_app_initialization) && (!thread_spawner)\n\n if (! done_app_initialization)\n {\n UInt32 curr_process_num = Sim()->getConfig()->getCurrentProcessNum();\n\n if (Sim()->getConfig()->getSimulationMode() == Config::LITE)\n {\n LOG_ASSERT_ERROR(curr_process_num == 0, \"Lite mode can only be run with 1 process\");\n Sim()->getCoreManager()->initializeThread(0);\n }\n else \/\/ Sim()->getConfig()->getSimulationMode() == Config::FULL\n { \n ADDRINT reg_esp = PIN_GetContextReg(ctxt, REG_STACK_PTR);\n allocateStackSpace();\n \n if (curr_process_num == 0)\n {\n Sim()->getCoreManager()->initializeThread(0);\n\n ADDRINT reg_eip = PIN_GetContextReg(ctxt, REG_INST_PTR);\n \/\/ 1) Copying over Static Data\n \/\/ Get the image first\n PIN_LockClient();\n IMG img = IMG_FindByAddress(reg_eip);\n PIN_UnlockClient();\n\n LOG_PRINT(\"Process: 0, Start Copying Static Data\");\n copyStaticData(img);\n LOG_PRINT(\"Process: 0, Finished Copying Static Data\");\n\n \/\/ 2) Copying over initial stack data\n LOG_PRINT(\"Process: 0, Start Copying Initial Stack Data\");\n copyInitialStackData(reg_esp, 0);\n LOG_PRINT(\"Process: 0, Finished Copying Initial Stack Data\");\n }\n else\n {\n core_id_t core_id = Sim()->getConfig()->getCurrentThreadSpawnerCoreNum();\n Sim()->getCoreManager()->initializeThread(core_id);\n \n Core *core = Sim()->getCoreManager()->getCurrentCore();\n\n \/\/ main thread clock is not affected by start-up time of other processes\n core->getNetwork()->netRecv (0, SYSTEM_INITIALIZATION_NOTIFY);\n\n LOG_PRINT(\"Process: %i, Start Copying Initial Stack Data\");\n copyInitialStackData(reg_esp, core_id);\n LOG_PRINT(\"Process: %i, Finished Copying Initial Stack Data\");\n }\n\n \/\/ Set the current ESP accordingly\n PIN_SetContextReg(ctxt, REG_STACK_PTR, reg_esp);\n }\n \n \/\/ All the real initialization is done in \n \/\/ replacement_start at the moment\n done_app_initialization = true;\n }\n else\n {\n \/\/ This is NOT the main thread\n \/\/ 'application' thread or 'thread spawner'\n\n if (Sim()->getConfig()->getSimulationMode() == Config::LITE)\n {\n ThreadSpawnRequest req;\n Sim()->getThreadManager()->getThreadToSpawn(&req);\n Sim()->getThreadManager()->dequeueThreadSpawnReq(&req);\n\n LOG_ASSERT_ERROR(req.core_id < SInt32(Config::getSingleton()->getApplicationCores()),\n \"req.core_id(%i), num application cores(%u)\", req.core_id, Config::getSingleton()->getApplicationCores());\n Sim()->getThreadManager()->onThreadStart(&req);\n }\n else \/\/ Sim()->getConfig()->getSimulationMode() == Config::FULL\n {\n ADDRINT reg_esp = PIN_GetContextReg(ctxt, REG_STACK_PTR);\n core_id_t core_id = PinConfig::getSingleton()->getCoreIDFromStackPtr(reg_esp);\n\n LOG_ASSERT_ERROR(core_id != -1, \"All application threads and thread spawner are cores now\");\n\n if (core_id == Sim()->getConfig()->getCurrentThreadSpawnerCoreNum())\n {\n \/\/ 'Thread Spawner' thread\n Sim()->getCoreManager()->initializeThread(core_id);\n }\n else\n {\n \/\/ 'Application' thread\n ThreadSpawnRequest* req = Sim()->getThreadManager()->getThreadSpawnReq();\n\n LOG_ASSERT_ERROR (req != NULL, \"ThreadSpawnRequest is NULL !!\");\n\n \/\/ This is an application thread\n LOG_ASSERT_ERROR(core_id == req->core_id, \"Got 2 different core_ids: req->core_id = %i, core_id = %i\", req->core_id, core_id);\n\n Sim()->getThreadManager()->onThreadStart(req);\n }\n\n#ifdef TARGET_IA32 \n \/\/ Restore the clone syscall arguments\n PIN_SetContextReg (ctxt, REG_GDX, (ADDRINT) parent_tidptr);\n PIN_SetContextReg (ctxt, REG_GSI, (ADDRINT) newtls);\n PIN_SetContextReg (ctxt, REG_GDI, (ADDRINT) child_tidptr);\n#endif\n\n#ifdef TARGET_X86_64\n \/\/ Restore the clone syscall arguments\n PIN_SetContextReg (ctxt, REG_GDX, (ADDRINT) parent_tidptr);\n PIN_SetContextReg (ctxt, LEVEL_BASE::REG_R10, (ADDRINT) child_tidptr);\n#endif\n\n __attribute(__unused__) Core *core = Sim()->getCoreManager()->getCurrentCore();\n LOG_ASSERT_ERROR(core, \"core(NULL)\");\n\n \/\/ Copy over thread stack data\n \/\/ copySpawnedThreadStackData(reg_esp);\n\n \/\/ Wait to make sure that the spawner has written stuff back to memory\n \/\/ FIXME: What is this for(?) This seems arbitrary\n GetLock (&clone_memory_update_lock, 2);\n ReleaseLock (&clone_memory_update_lock);\n }\n }\n}\n\nVOID threadFiniCallback(THREADID threadIndex, const CONTEXT *ctxt, INT32 flags, VOID *v)\n{\n Sim()->getThreadManager()->onThreadExit();\n}\n\nint main(int argc, char *argv[])\n{\n \/\/ ---------------------------------------------------------------\n \/\/ FIXME: \n InitLock (&rtn_map_lock);\n \/\/ ---------------------------------------------------------------\n\n \/\/ Global initialization\n PIN_InitSymbols();\n PIN_Init(argc,argv);\n\n string_vec args;\n\n \/\/ Set the default config path if it isn't \n \/\/ overwritten on the command line.\n std::string config_path = \"carbon_sim.cfg\";\n\n parse_args(args, config_path, argc, argv);\n\n cfg = new config::ConfigFile();\n cfg->load(config_path);\n\n handle_args(args, *cfg);\n\n Simulator::setConfig(cfg);\n\n Simulator::allocate();\n Sim()->start();\n\n if (Sim()->getConfig()->getSimulationMode() == Config::FULL)\n PinConfig::allocate();\n\n \/\/ Instrumentation\n LOG_PRINT(\"Start of instrumentation.\");\n \n if (Sim()->getConfig()->getSimulationMode() == Config::FULL)\n RTN_AddInstrumentFunction(routineCallback, 0);\n else \/\/ Sim()->getConfig()->getSimulationMode() == Config::LITE\n RTN_AddInstrumentFunction(lite::routineCallback, 0);\n\n PIN_AddThreadStartFunction (threadStartCallback, 0);\n PIN_AddThreadFiniFunction (threadFiniCallback, 0);\n \n if ((cfg->getBool(\"general\/enable_syscall_modeling\")) && \\\n (Sim()->getConfig()->getSimulationMode() == Config::FULL))\n {\n initializeSyscallModeling();\n\n PIN_AddSyscallEntryFunction(SyscallEntry, 0);\n PIN_AddSyscallExitFunction(SyscallExit, 0);\n PIN_AddContextChangeFunction(contextChange, NULL);\n }\n\n INS_AddInstrumentFunction(instructionCallback, 0);\n\n initProgressTrace();\n\n PIN_AddFiniFunction(ApplicationExit, 0);\n\n \/\/ Just in case ... might not be strictly necessary\n Transport::getSingleton()->barrier();\n\n \/\/ Never returns\n LOG_PRINT(\"Running program...\");\n PIN_StartProgram();\n\n return 0;\n}\n<|endoftext|>"} {"text":"#ifndef __PML_FACTOR__\n#define __PML_FACTOR__\n\n#include \n\n#include \"prime.hpp\"\n\ninline uint64_t gdc(uint64_t a, uint64_t b)\n{\n if (a < b)\n return gdc(b, a);\n\n uint64_t mod;\n while (b != 0)\n {\n mod = a % b;\n a = b;\n b = mod;\n }\n return a;\n}\n\ninline uint64_t lcm(uint64_t a, uint64_t b)\n{\n if (a == 0 && b == 0)\n return 0;\n\n uint64_t num = a * b;\n return num \/ gdc(a, b);\n}\n\ninline uint64_t rho_f(uint64_t val)\n{\n if (val == 0)\n return 1;\n\n uint64_t x_fixed = 2;\n uint64_t x = 2;\n uint64_t cycles = 2;\n uint64_t factor = 1;\n\n while (factor == 1)\n {\n for (unsigned i = 0; i < cycles && factor <= 1; i++)\n {\n x = (x * x + 1) % val; \n factor = gdc(x - x_fixed, val);\n }\n\n cycles *= 2;\n x_fixed = x;\n }\n\n return factor;\n}\n\ninline std::vector rho(uint64_t val)\n{\n std::vector factors;\n \n if (val == 0)\n return factors;\n \n const uint64_t MAX_REDUCE = 100000;\n std::vector primes;\n\n uint64_t fac;\n std::vector tmp_factor;\n while (val != 1)\n {\n fac = rho_f(val);\n if (fac != 1) {\n if (fac < MAX_REDUCE) {\n if (primes.size() == 0)\n primes = prime_sieve(MAX_REDUCE);\n tmp_factor = factorize(fac, primes);\n } else {\n if (fac == val)\n tmp_factor = {fac};\n else\n factors.push_back(fac);\n }\n factors.insert(factors.begin(), tmp_factor.begin(),\n tmp_factor.end());\n val \/= fac;\n } else {\n break;\n }\n }\n\n return factors;\n}\n\ninline std::vector quick_factorize(uint64_t val)\n{\n std::vector factors;\n if (val == 0)\n return factors;\n\n while ((val & 0x01) == 0)\n {\n val >>= 1;\n factors.push_back(2);\n }\n \n std::vector other_factors = rho(val);\n factors.insert(factors.end(), other_factors.begin(), \n other_factors.end());\n \n uint64_t mul = 1;\n for (uint64_t u : factors)\n mul *= u;\n\n if (mul != val) {\n other_factors = factorize(val \/ mul);\n factors.insert(factors.end(), other_factors.begin(), \n other_factors.end());\n }\n\n std::sort(factors.begin(), factors.end());\n\n return factors;\n}\n\n#endif\nimproved speed of rho function#ifndef __PML_FACTOR__\n#define __PML_FACTOR__\n\n#include \n\n#include \"prime.hpp\"\n\ninline uint64_t gdc(uint64_t a, uint64_t b)\n{\n if (a < b)\n return gdc(b, a);\n\n uint64_t mod;\n while (b != 0)\n {\n mod = a % b;\n a = b;\n b = mod;\n }\n return a;\n}\n\ninline uint64_t lcm(uint64_t a, uint64_t b)\n{\n if (a == 0 && b == 0)\n return 0;\n\n uint64_t num = a * b;\n return num \/ gdc(a, b);\n}\n\ninline uint64_t rho_f(uint64_t val)\n{\n if (val == 0)\n return 1;\n\n uint64_t x_fixed = 2;\n uint64_t x = 2;\n uint64_t cycles = 2;\n uint64_t factor = 1;\n\n while (factor == 1)\n {\n for (unsigned i = 0; i < cycles && factor <= 1; i++)\n {\n x = (x * x + 1) % val; \n factor = gdc(x - x_fixed, val);\n }\n\n cycles *= 2;\n x_fixed = x;\n }\n\n return factor;\n}\n\ninline std::vector rho(uint64_t val)\n{\n std::vector factors;\n \n if (val == 0)\n return factors;\n \n uint64_t fac;\n std::vector tmp_factor;\n while (val != 1)\n {\n fac = rho_f(val);\n if (fac != 1) {\n if (fac == val)\n tmp_factor = {fac};\n else\n factors.push_back(fac);\n factors.insert(factors.begin(), tmp_factor.begin(),\n tmp_factor.end());\n val \/= fac;\n } else {\n break;\n }\n }\n\n return factors;\n}\n\ninline std::vector quick_factorize(uint64_t val)\n{\n std::vector factors;\n if (val == 0)\n return factors;\n\n while ((val & 0x01) == 0)\n {\n val >>= 1;\n factors.push_back(2);\n }\n \n std::vector other_factors = rho(val);\n factors.insert(factors.end(), other_factors.begin(), \n other_factors.end());\n \n uint64_t mul = 1;\n for (uint64_t u : factors)\n mul *= u;\n\n if (mul != val) {\n other_factors = factorize(val \/ mul);\n factors.insert(factors.end(), other_factors.begin(), \n other_factors.end());\n }\n\n std::sort(factors.begin(), factors.end());\n\n return factors;\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/\n\/\/ Created by Dennis Goldfarb on 1\/3\/17.\n\/\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"FASTAParser.h\"\n\nstatic const ElementDB* elementDB = ElementDB::getInstance();\nstatic const OpenMS::ResidueDB* residueDB = OpenMS::ResidueDB::getInstance();\n\nstatic std::string AMINO_ACIDS = \"ADEFGHIKLNPQRSTVWYCM\";\nstatic std::string AMINO_ACIDS_NO_SULFUR = \"ADEFGHIKLNPQRSTVWY\";\nstatic std::string AMINO_ACIDS_SULFUR = \"CM\";\n\nstd::random_device rd;\nstd::mt19937 gen(rd());\nstd::uniform_real_distribution<> dis_AA(0,1);\nstd::uniform_int_distribution<> dis_SULFUR(0,1);\n\nstd::ofstream* openOutputFiles(std::string base_path, int max_depth, bool write_sulfur)\n{\n \/\/ create all output files and write header to each\n std::ofstream* outfiles = new std::ofstream[max_depth];\n for (int precursor_isotope = 0; precursor_isotope < max_depth; ++precursor_isotope)\n {\n std::string filename = \"Precursor\" + std::to_string(precursor_isotope) + \".tab\";\n\n\n outfiles[precursor_isotope].open(base_path + filename);\n if (write_sulfur) {\n outfiles[precursor_isotope] << \"probability\" << \"\\tprecursor.mass\" << \"\\tsulfur\" << std::endl;\n } else {\n outfiles[precursor_isotope] << \"probability\" << \"\\tprecursor.mass\" << std::endl;\n }\n }\n\n return outfiles;\n}\n\nvoid closeOutputFiles(std::ofstream* outfiles, int max_depth)\n{\n \/\/ close all output files\n for (int precursor_isotope = 0; precursor_isotope < max_depth; ++precursor_isotope)\n {\n outfiles[precursor_isotope].close();\n }\n delete[] outfiles;\n}\n\nvoid write_distribution(const OpenMS::AASequence &p, std::ofstream* outfiles, int max_depth, bool mono, bool write_sulfur, bool exact)\n{\n OpenMS::EmpiricalFormula precursor_ef = p.getFormula();\n double mass = mono ? precursor_ef.getMonoWeight() : precursor_ef.getAverageWeight();\n\n OpenMS::IsotopeDistribution precursor_id;\n if (exact) {\n precursor_id = precursor_ef.getIsotopeDistribution(0);\n } else {\n precursor_id.estimateFromPeptideWeight(mass);\n }\n\n for (int precursor_isotope = 0; precursor_isotope < max_depth && precursor_isotope < precursor_id.size(); ++precursor_isotope)\n {\n if (write_sulfur) {\n int num_sulfur = precursor_ef.getNumberOf(elementDB->getElement(\"Sulfur\"));\n outfiles[precursor_isotope] << precursor_id.getContainer()[precursor_isotope].second << \"\\t\" << mass << \"\\t\" << num_sulfur << std::endl;\n } else {\n outfiles[precursor_isotope] << precursor_id.getContainer()[precursor_isotope].second << \"\\t\" << mass << std::endl;\n }\n }\n}\n\nvoid proteome_isotopic_distributions(std::string base_path, std::string fasta_path, float max_mass, int max_depth, bool mono)\n{\n std::ofstream* outfiles = openOutputFiles(base_path, max_depth, true);\n\n\n FASTAParser parser(fasta_path, max_mass, 1, 150);\n for (auto itr = parser.begin(); itr != parser.end(); ++itr)\n {\n write_distribution(*itr, outfiles, max_depth, mono, true, true);\n }\n\n closeOutputFiles(outfiles, max_depth);\n\n}\n\nvoid averagine_isotopic_distributions(std::string base_path, float max_mass, int max_depth, bool mono)\n{\n std::ofstream* outfiles_averagine = openOutputFiles(base_path+\"averagine\/\", max_depth, false);\n\n for (double mass = 50; mass < max_mass; ++mass)\n {\n OpenMS::IsotopeDistribution precursor_id;\n\n precursor_id.estimateFromPeptideWeight(mass);\n\n for (int precursor_isotope = 0; precursor_isotope < max_depth && precursor_isotope < precursor_id.size(); ++precursor_isotope)\n {\n outfiles_averagine[precursor_isotope] << precursor_id.getContainer()[precursor_isotope].second << \"\\t\" << mass << std::endl;\n }\n }\n\n closeOutputFiles(outfiles_averagine, max_depth);\n}\n\nOpenMS::AASequence create_random_peptide_sequence(int peptide_length, std::vector aa2prob, int num_sulfurs)\n{\n OpenMS::AASequence random_peptide;\n\n if (num_sulfurs < 0)\n {\n for (int aa_index = 0; aa_index < peptide_length; ++aa_index)\n {\n double rand = dis_AA(gen);\n int index = std::lower_bound(aa2prob.begin(), aa2prob.end(), rand) - aa2prob.begin() - 1;\n random_peptide += residueDB->getResidue(AMINO_ACIDS[index]);\n }\n }\n else\n {\n \/\/ for insertion of sulfur containing amino acids\n for (int i = 0; i < num_sulfurs; ++i)\n {\n random_peptide += residueDB->getResidue(AMINO_ACIDS_SULFUR[dis_SULFUR(gen)]);\n }\n\n \/\/ random amino acid insertion (non Sulfur and Selenium amino acids)\n for (int aa_index = 0; aa_index < peptide_length; ++aa_index)\n {\n double rand = dis_AA(gen);\n int index = std::lower_bound(aa2prob.begin(), aa2prob.end(), rand) - aa2prob.begin() - 1;\n random_peptide += residueDB->getResidue(AMINO_ACIDS_NO_SULFUR[index]);\n }\n }\n\n return random_peptide;\n}\n\n\nstd::map getAAProbabilities(std::string fasta_path, bool sulfur)\n{\n std::map aa2prob;\n for (char aa : AMINO_ACIDS)\n {\n aa2prob[aa] = 0.0;\n }\n\n std::vector proteins;\n FASTAFile().load(fasta_path, proteins);\n\n int count = 0;\n for (Size i = 0; i < proteins.size(); ++i)\n {\n for (int j = 0; j < proteins[i].sequence.size(); ++j)\n {\n char aa = proteins[i].sequence[j];\n if ((sulfur && AMINO_ACIDS.find(aa) != -1) || (!sulfur && AMINO_ACIDS_NO_SULFUR.find(aa) != -1))\n {\n aa2prob[aa]++;\n count++;\n }\n }\n }\n\n for (auto &aa : aa2prob)\n {\n aa.second \/= count;\n }\n\n return aa2prob;\n}\n\nstd::vector calcPrefixSum(std::map aa2prob, bool sulfur)\n{\n std::string AAs = sulfur ? AMINO_ACIDS : AMINO_ACIDS_NO_SULFUR;\n std::vector prefixSum;\n\n prefixSum.push_back(0);\n\n for (int i = 0; i < AAs.size(); ++i)\n {\n prefixSum.push_back(aa2prob[AAs[i]] + prefixSum[i]);\n }\n\n return prefixSum;\n}\n\nvoid sample_isotopic_distributions(std::string base_path, std::string fasta_path, float max_mass, int num_sulfurs, int num_samples, int max_depth, bool mono)\n{\n\n std::vector aa2prob = calcPrefixSum(getAAProbabilities(fasta_path, num_sulfurs == -1), num_sulfurs == -1);\n\n std::ofstream* outfiles = openOutputFiles(base_path, max_depth, false);\n\n int max_length = max_mass\/100;\n\n\n for (int peptide_length = 1; peptide_length <= max_length; ++peptide_length)\n {\n for (int sample = 0; sample < num_samples; ++sample)\n {\n OpenMS::AASequence random_sequence = create_random_peptide_sequence(peptide_length, aa2prob, num_sulfurs);\n\n if (random_sequence.size() > 0 && random_sequence.getMonoWeight() <= max_mass)\n {\n write_distribution(random_sequence, outfiles, max_depth, mono, false, true);\n }\n }\n }\n\n closeOutputFiles(outfiles, max_depth);\n}\n\n\n\n\n\n\nvoid usage()\n{\n std::cout << \"GenerateTrainingData fasta_path out_path max_mass S num_samples max_depth mono\" << std::endl;\n std::cout << \"fasta_path: The path to the fasta file to train the splines on.\" << std::endl;\n std::cout << \"out_path: The path to the directory that will store the training data, e.g. ~\/data\/\" << std::endl;\n std::cout << \"max_mass: maximum mass allowed for sampled peptides, e.g. 8500\" << std::endl;\n std::cout << \"max_depth: The number of isotopes to generate training data for, e.g. 3 = M0,M1,M2\" << std::endl;\n std::cout << \"mono: should monoisotopic masses be used or average? 1=mono, 0=average\" << std::endl;\n std::cout << \"S: number of sulfurs that should be in the fragment ion. Use -1 for all (e.g. 0,1,2..)\" << std::endl;\n std::cout << \"num_samples: number of random peptides to make for each peptide length\" << std::endl;\n\n std::cout << std::endl;\n}\n\n\nint main(int argc, const char ** argv)\n{\n if (argc != 8 && argc != 6)\n {\n usage();\n return 0;\n }\n\n std::string fasta_path = argv[1];\n std::string out_path = argv[2];\n float max_mass = atof(argv[3]);\n int max_depth = atoi(argv[4]);\n bool mono = strncmp(argv[5], \"1\", 1) == 0 ? true : false;\n\n if (argc == 8) {\n int S = atoi(argv[6]);\n int num_samples = atoi(argv[7]);\n sample_isotopic_distributions(out_path, fasta_path, max_mass, S, num_samples, max_depth, mono);\n } else {\n proteome_isotopic_distributions(out_path, fasta_path, max_mass, max_depth, mono);\n averagine_isotopic_distributions(out_path, max_mass, max_depth, mono);\n }\n\n return 0;\n}plots\/\/\n\/\/ Created by Dennis Goldfarb on 1\/3\/17.\n\/\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"FASTAParser.h\"\n\nstatic const ElementDB* elementDB = ElementDB::getInstance();\nstatic const OpenMS::ResidueDB* residueDB = OpenMS::ResidueDB::getInstance();\n\nstatic std::string AMINO_ACIDS = \"ADEFGHIKLNPQRSTVWYCM\";\nstatic std::string AMINO_ACIDS_NO_SULFUR = \"ADEFGHIKLNPQRSTVWY\";\nstatic std::string AMINO_ACIDS_SULFUR = \"CM\";\n\nstd::random_device rd;\nstd::mt19937 gen(rd());\nstd::uniform_real_distribution<> dis_AA(0,1);\nstd::uniform_int_distribution<> dis_SULFUR(0,1);\n\nstd::ofstream* openOutputFiles(std::string base_path, int max_depth, bool write_sulfur)\n{\n \/\/ create all output files and write header to each\n std::ofstream* outfiles = new std::ofstream[max_depth];\n for (int precursor_isotope = 0; precursor_isotope < max_depth; ++precursor_isotope)\n {\n std::string filename = \"Precursor\" + std::to_string(precursor_isotope) + \".tab\";\n\n\n outfiles[precursor_isotope].open(base_path + filename);\n if (write_sulfur) {\n outfiles[precursor_isotope] << \"probability\" << \"\\tprecursor.mass\" << \"\\tsulfur\" << std::endl;\n } else {\n outfiles[precursor_isotope] << \"probability\" << \"\\tprecursor.mass\" << std::endl;\n }\n }\n\n return outfiles;\n}\n\nvoid closeOutputFiles(std::ofstream* outfiles, int max_depth)\n{\n \/\/ close all output files\n for (int precursor_isotope = 0; precursor_isotope < max_depth; ++precursor_isotope)\n {\n outfiles[precursor_isotope].close();\n }\n delete[] outfiles;\n}\n\nvoid write_distribution(const OpenMS::AASequence &p, std::ofstream* outfiles, int max_depth, bool mono, bool write_sulfur, bool exact)\n{\n OpenMS::EmpiricalFormula precursor_ef = p.getFormula();\n double mass = mono ? precursor_ef.getMonoWeight() : precursor_ef.getAverageWeight();\n\n OpenMS::IsotopeDistribution precursor_id;\n if (exact) {\n precursor_id = precursor_ef.getIsotopeDistribution(0);\n } else {\n precursor_id.estimateFromPeptideWeight(mass);\n }\n\n for (int precursor_isotope = 0; precursor_isotope < max_depth && precursor_isotope < precursor_id.size(); ++precursor_isotope)\n {\n if (write_sulfur) {\n int num_sulfur = precursor_ef.getNumberOf(elementDB->getElement(\"Sulfur\"));\n outfiles[precursor_isotope] << precursor_id.getContainer()[precursor_isotope].second << \"\\t\" << mass << \"\\t\" << num_sulfur << std::endl;\n } else {\n outfiles[precursor_isotope] << precursor_id.getContainer()[precursor_isotope].second << \"\\t\" << mass << std::endl;\n }\n }\n}\n\nvoid proteome_isotopic_distributions(std::string base_path, std::string fasta_path, float max_mass, int max_depth, bool mono)\n{\n std::ofstream* outfiles = openOutputFiles(base_path, max_depth, true);\n\n FASTAParser parser(fasta_path, max_mass, 1, 150);\n for (auto itr = parser.begin(); itr != parser.end(); ++itr)\n {\n write_distribution(*itr, outfiles, max_depth, mono, true, true);\n }\n\n closeOutputFiles(outfiles, max_depth);\n\n}\n\nvoid averagine_isotopic_distributions(std::string base_path, float max_mass, int max_depth)\n{\n std::ofstream* outfiles_averagine = openOutputFiles(base_path+\"averagine\/\", max_depth, false);\n\n for (double mass = 50; mass < max_mass; mass+=1)\n {\n OpenMS::IsotopeDistribution precursor_id;\n\n precursor_id.estimateFromPeptideWeight(mass);\n\n for (int precursor_isotope = 0; precursor_isotope < max_depth && precursor_isotope < precursor_id.size(); ++precursor_isotope)\n {\n outfiles_averagine[precursor_isotope] << precursor_id.getContainer()[precursor_isotope].second << \"\\t\" << mass << std::endl;\n }\n }\n\n closeOutputFiles(outfiles_averagine, max_depth);\n}\n\nOpenMS::AASequence create_random_peptide_sequence(int peptide_length, std::vector aa2prob, int num_sulfurs)\n{\n OpenMS::AASequence random_peptide;\n\n if (num_sulfurs < 0)\n {\n for (int aa_index = 0; aa_index < peptide_length; ++aa_index)\n {\n double rand = dis_AA(gen);\n int index = std::lower_bound(aa2prob.begin(), aa2prob.end(), rand) - aa2prob.begin() - 1;\n random_peptide += residueDB->getResidue(AMINO_ACIDS[index]);\n }\n }\n else\n {\n \/\/ for insertion of sulfur containing amino acids\n for (int i = 0; i < num_sulfurs; ++i)\n {\n random_peptide += residueDB->getResidue(AMINO_ACIDS_SULFUR[dis_SULFUR(gen)]);\n }\n\n \/\/ random amino acid insertion (non Sulfur and Selenium amino acids)\n for (int aa_index = 0; aa_index < peptide_length; ++aa_index)\n {\n double rand = dis_AA(gen);\n int index = std::lower_bound(aa2prob.begin(), aa2prob.end(), rand) - aa2prob.begin() - 1;\n random_peptide += residueDB->getResidue(AMINO_ACIDS_NO_SULFUR[index]);\n }\n }\n\n return random_peptide;\n}\n\n\nstd::map getAAProbabilities(std::string fasta_path, bool sulfur)\n{\n std::map aa2prob;\n for (char aa : AMINO_ACIDS)\n {\n aa2prob[aa] = 0.0;\n }\n\n std::vector proteins;\n FASTAFile().load(fasta_path, proteins);\n\n int count = 0;\n for (Size i = 0; i < proteins.size(); ++i)\n {\n for (int j = 0; j < proteins[i].sequence.size(); ++j)\n {\n char aa = proteins[i].sequence[j];\n if ((sulfur && AMINO_ACIDS.find(aa) != -1) || (!sulfur && AMINO_ACIDS_NO_SULFUR.find(aa) != -1))\n {\n aa2prob[aa]++;\n count++;\n }\n }\n }\n\n for (auto &aa : aa2prob)\n {\n aa.second \/= count;\n }\n\n return aa2prob;\n}\n\nstd::vector calcPrefixSum(std::map aa2prob, bool sulfur)\n{\n std::string AAs = sulfur ? AMINO_ACIDS : AMINO_ACIDS_NO_SULFUR;\n std::vector prefixSum;\n\n prefixSum.push_back(0);\n\n for (int i = 0; i < AAs.size(); ++i)\n {\n prefixSum.push_back(aa2prob[AAs[i]] + prefixSum[i]);\n }\n\n return prefixSum;\n}\n\nvoid sample_isotopic_distributions(std::string base_path, std::string fasta_path, float max_mass, int num_sulfurs, int num_samples, int max_depth, bool mono)\n{\n\n std::vector aa2prob = calcPrefixSum(getAAProbabilities(fasta_path, num_sulfurs == -1), num_sulfurs == -1);\n\n std::ofstream* outfiles = openOutputFiles(base_path, max_depth, false);\n\n int max_length = max_mass\/100;\n\n\n for (int peptide_length = 1; peptide_length <= max_length; ++peptide_length)\n {\n for (int sample = 0; sample < num_samples; ++sample)\n {\n OpenMS::AASequence random_sequence = create_random_peptide_sequence(peptide_length, aa2prob, num_sulfurs);\n\n if (random_sequence.size() > 0 && random_sequence.getMonoWeight() <= max_mass)\n {\n write_distribution(random_sequence, outfiles, max_depth, mono, false, true);\n }\n }\n }\n\n closeOutputFiles(outfiles, max_depth);\n}\n\n\n\n\n\n\nvoid usage()\n{\n std::cout << \"GenerateTrainingData fasta_path out_path max_mass S num_samples max_depth mono\" << std::endl;\n std::cout << \"fasta_path: The path to the fasta file to train the splines on.\" << std::endl;\n std::cout << \"out_path: The path to the directory that will store the training data, e.g. ~\/data\/\" << std::endl;\n std::cout << \"max_mass: maximum mass allowed for sampled peptides, e.g. 8500\" << std::endl;\n std::cout << \"max_depth: The number of isotopes to generate training data for, e.g. 3 = M0,M1,M2\" << std::endl;\n std::cout << \"mono: should monoisotopic masses be used or average? 1=mono, 0=average\" << std::endl;\n std::cout << \"S: number of sulfurs that should be in the fragment ion. Use -1 for all (e.g. 0,1,2..)\" << std::endl;\n std::cout << \"num_samples: number of random peptides to make for each peptide length\" << std::endl;\n\n std::cout << std::endl;\n}\n\n\nint main(int argc, const char ** argv)\n{\n if (argc != 8 && argc != 6)\n {\n usage();\n return 0;\n }\n\n std::string fasta_path = argv[1];\n std::string out_path = argv[2];\n float max_mass = atof(argv[3]);\n int max_depth = atoi(argv[4]);\n bool mono = strncmp(argv[5], \"1\", 1) == 0 ? true : false;\n\n if (argc == 8) {\n int S = atoi(argv[6]);\n int num_samples = atoi(argv[7]);\n sample_isotopic_distributions(out_path, fasta_path, max_mass, S, num_samples, max_depth, mono);\n } else {\n proteome_isotopic_distributions(out_path, fasta_path, max_mass, max_depth, mono);\n averagine_isotopic_distributions(out_path, max_mass, max_depth);\n }\n\n return 0;\n}<|endoftext|>"} {"text":"#ifndef MOB_HPP \n#define MOB_HPP\n\n#include \n\nclass Mob\n{\npublic:\n mob(std::string, std::string std::string, int, int, int, int);\n\n void setName(std::string);\n void setArea(std::string);\n void setSkill(std::string);\n\n void setLevel(int);\n void setEXP(int);\n void setHP(int);\n void setMaxHealth(int);\n\n void setDamage();\n void setEXP();\n \n std::string getName;\n std::string getArea;\n\n int getLevel();\n int getEXP();\n int getHP();\n int getMaxHealth();\n int getDamage();\n int getEXP();\n\nprivate:\n std::string mobName;\n std::string mobArea;\n int mobLevel;\n int mobHealth;\n int mobMaxHealth;\n int mobDamage;\n int mobEXP;\n};\n\n#endif\n\n\n\n\nDelete mob.hpp<|endoftext|>"} {"text":"Make DML operator registration constexpr (#4219)<|endoftext|>"} {"text":"#include \n#include \n\n#include \"polynomial.h\"\n\nusing std::copy_n;\n\nnamespace gpu_poly\n{\n\npolynomial::polynomial(const unsigned* coeffs, unsigned degree, unsigned charecteristic) :\n\tcoeffs(new unsigned[degree+1]), degree(degree), charecteristic(charecteristic)\n{\n\tcopy_n(coeffs, degree + 1, this -> coeffs);\n}\n\npolynomial::polynomial(polynomial&& move_me) : coeffs(std::move(move_me.coeffs)),\n\tdegree(move_me.degree), charecteristic(move_me.charecteristic)\n{\n}\n\npolynomial::~polynomial()\n{\n\tdelete coeffs;\n}\n\nunsigned* polynomial::get_coeffs()\n{\n\tunsigned* copy_coeffs(new unsigned[degree + 1]);\n\tcopy_n(coeffs, degree + 1, copy_coeffs);\n}\n\nunsigned polynomial::get_charecteristic()\n{\n\treturn charecteristic;\n}\n\nunsigned polynomial::get_degree()\n{\n\treturn degree;\n}\n\npolynomial& polynomial::copy()\n{\n\treturn polynomial(coeffs, degree, charecteristic);\n}\n\nstatic polynomial& polynomial::operator+(const polynomial& p, const polynomial& q)\n{\n\tunsigned\t\tcharecteristic(p.charecteristic);\n\tconst unsigned\t*p_co(p.coeffs), *q_co(q.coeffs), *b_co;\n\tint\t\t\t\tp_deg(p.degree), q_deg(q.degree);\n\t\n\t\/\/ Find min and max\n\tint\t\t\tdiff\t\t= p_deg - q_deg;\n\tint\t\t\tsum\t\t\t= p_deg + q_deg;\n\tunsigned\tabs_diff\t= (unsigned) sqrt(diff*diff);\n\tunsigned\tmax\t\t\t= (sum + abs_diff)\/2, maxp1 = max + 1;\n\tunsigned\tmin\t\t\t= (sum - abs_diff)\/2, minp1 = min + 1;\n\t\n\tunsigned\tr_co[max + 1];\n\t\n\t\/\/ Sum shared\n\tfor ( unsigned i = 0 ; i < minp1 ; i++ )\n\t\tr_co[i] = (p_co[i] + q_co[i]) % charecteristic;\n\t\n\tb_co\t= ( (p_deg == max) ? p_co : q_co );\n\t\n\t\/\/ Copy big\n\tfor ( unsigned i = minp1 ; i < maxp1 ; i++ )\n\t\tr_co[i] = b_co[i];\n\t\t\n\tunsigned\tr_deg(max);\n\t\n\t\/\/ Find the degree of the new polynomial\n\twhile ( r_co[r_deg] == 0 && r_deg > 0 )\n\t\tr_deg--;\n\t\n\treturn polynomial(r_co, r_deg, charecteristic);\n}\n\nstatic polynomial& polynomial::operator-(const polynomial& p, const polynomial& q)\n{\n\tunsigned\t\tcharecteristic(p.charecteristic);\n\tconst unsigned\t*q_co(q.coeffs);\n\tint\t\t\t\tq_deg(q.degree), q_deg_p1 = q_deg+1;\n\tunsigned\t\tr_co[q_deg+1];\n\t\n\t\/\/ Flip everythin in q\n\tfor ( i = 0 ; i < q_deg_p1 ; i++ )\n\t\tr_co[i] = (-1 * q_co[i]) % charecteristic;\n\t\t\n\treturn p + polynomial(r_co, q_deg, charecteristic);\n}\n\nstatic polynomial& polynomial::operator*(const polynomial& p, const polynomial& q)\n{\n\tconst unsigned\t*p_co(p.coeffs),\t*q_co(q.coeffs);\n\tunsigned\t\tp_deg(p.degree),\tq_deg(q.degree);\n\tunsigned\t\tp_deg_p1(p_deg+1),\tq_deg_p1(q_deg+1);\n\tunsigned\t\tr_deg(p_deg+q_deg),\tr_deg_p1(r_deg+1);\n\tunsigned\t\tcharecteristic(p.charecteristic);\n\t\n\tunsigned\t\tr_co[r_deg_p1];\n\t\n\t\/\/ Compute the new vector of coefficients\n\tfor ( i = 0 ; i < p_deg_p1 ; i++)\n\t\tfor ( j = 0 ; j < q_deg_p1 ; j++)\n\t\t\tr_co[i+j] = p_co[i] + q_co[j];\n\t\n\treturn polynomial(r_co, r_deg, charecteristic);\n}\n\nstatic polynomial& polynomial::operator*(int n, const polynomial& p)\n{\n\tunsigned\t\tcharecteristic(p.charecteristic);\n\tconst unsigned\t*p_co(p.coeffs);\n\tint\t\t\t\tp_deg(p.degree), p_deg_p1 = p_deg+1;\n\tunsigned\t\tr_co[q_deg+1];\n\t\n\t\/\/ Multiply everythin in p\n\tfor ( i = 0 ; i < p_deg_p1 ; i++ )\n\t\tr_co[i] = (n*p_co[i])%charecteristic;\n\t\t\n\treturn p + polynomial(r_co, q_deg, charecteristic);\n}\n\n}\nDid some stuff#include \n#include \n\n#include \"polynomial.h\"\n\nusing std::copy_n;\n\nnamespace gpu_poly\n{\n\npolynomial::polynomial(const unsigned* coeffs, unsigned degree, unsigned charecteristic) :\n\tcoeffs(new unsigned[degree+1]), degree(degree), charecteristic(charecteristic)\n{\n\tcopy_n(coeffs, degree + 1, this -> coeffs);\n}\n\npolynomial::polynomial(polynomial&& move_me) : coeffs(std::move(move_me.coeffs)),\n\tdegree(move_me.degree), charecteristic(move_me.charecteristic)\n{\n}\n\npolynomial::~polynomial()\n{\n\tdelete coeffs;\n}\n\nunsigned* polynomial::get_coeffs()\n{\n\tunsigned* copy_coeffs(new unsigned[degree + 1]);\n\tcopy_n(coeffs, degree + 1, copy_coeffs);\n}\n\nunsigned polynomial::get_charecteristic()\n{\n\treturn charecteristic;\n}\n\nunsigned polynomial::get_degree()\n{\n\treturn degree;\n}\n\npolynomial& polynomial::copy()\n{\n\treturn polynomial(coeffs, degree, charecteristic);\n}\n\nstatic polynomial& polynomial::operator+(const polynomial& p, const polynomial& q)\n{\n\tunsigned\t\tcharecteristic(p.charecteristic);\n\tconst unsigned\t*p_co(p.coeffs), *q_co(q.coeffs), *b_co;\n\tint\t\t\t\tp_deg(p.degree), q_deg(q.degree);\n\t\n\t\/\/ Find min and max\n\tint\t\t\tdiff\t\t= p_deg - q_deg;\n\tint\t\t\tsum\t\t\t= p_deg + q_deg;\n\tunsigned\tabs_diff\t= (unsigned) sqrt(diff*diff);\n\tunsigned\tmax\t\t\t= (sum + abs_diff)\/2, maxp1 = max + 1;\n\tunsigned\tmin\t\t\t= (sum - abs_diff)\/2, minp1 = min + 1;\n\t\n\tunsigned\tr_co[max + 1];\n\t\n\t\/\/ Sum shared\n\tfor ( unsigned i = 0 ; i < minp1 ; i++ )\n\t\tr_co[i] = (p_co[i] + q_co[i]) % charecteristic;\n\t\n\tb_co\t= ( (p_deg == max) ? p_co : q_co );\n\t\n\t\/\/ Copy big\n\tfor ( unsigned i = minp1 ; i < maxp1 ; i++ )\n\t\tr_co[i] = b_co[i];\n\t\t\n\tunsigned\tr_deg(max);\n\t\n\t\/\/ Find the degree of the new polynomial\n\twhile ( r_co[r_deg] == 0 && r_deg > 0 )\n\t\tr_deg--;\n\t\n\treturn polynomial(r_co, r_deg, charecteristic);\n}\n\nstatic polynomial& polynomial::operator-(const polynomial& p, const polynomial& q)\n{\n\tunsigned\t\tcharecteristic(p.charecteristic);\n\tconst unsigned\t*q_co(q.coeffs);\n\tint\t\t\t\tq_deg(q.degree), q_deg_p1 = q_deg+1;\n\tunsigned\t\tr_co[q_deg+1];\n\t\n\t\/\/ Flip everythin in q\n\tfor ( i = 0 ; i < q_deg_p1 ; i++ )\n\t\tr_co[i] = (-1 * q_co[i]) % charecteristic;\n\t\t\n\treturn p + polynomial(r_co, q_deg, charecteristic);\n}\n\nstatic polynomial& polynomial::operator-(const polynomial& p, const polynomial& q)\n{\n\tunsigned\t\tcharecteristic(p.charecteristic);\n\tconst unsigned\t*p_co(p.coeffs), *q_co(q.coeffs), *b_co;\n\tint\t\t\t\tp_deg(p.degree), q_deg(q.degree);\n\t\n\t\/\/ Find min and max\n\tint\t\t\tdiff\t\t= p_deg - q_deg;\n\tint\t\t\tsum\t\t\t= p_deg + q_deg;\n\tunsigned\tabs_diff\t= (unsigned) sqrt(diff*diff);\n\tunsigned\tmax\t\t\t= (sum + abs_diff)\/2, maxp1 = max + 1;\n\tunsigned\tmin\t\t\t= (sum - abs_diff)\/2, minp1 = min + 1;\n\t\n\tunsigned\tr_co[max + 1];\n\t\n\t\/\/ Sum shared\n\tfor ( unsigned i = 0 ; i < minp1 ; i++ )\n\t\tr_co[i] = (p_co[i] - q_co[i]) % charecteristic;\n\t\n\tb_co\t= ( (p_deg == max) ? p_co : q_co );\n\t\n\t\/\/ Copy big\n\tfor ( unsigned i = minp1 ; i < maxp1 ; i++ )\n\t\tr_co[i] = b_co[i];\n\t\t\n\tunsigned\tr_deg(max);\n\t\n\t\/\/ Find the degree of the new polynomial\n\twhile ( r_co[r_deg] == 0 && r_deg > 0 )\n\t\tr_deg--;\n\t\n\treturn polynomial(r_co, r_deg, charecteristic);\n}\n\nstatic polynomial& polynomial::operator*(const polynomial& p, const polynomial& q)\n{\n\tconst unsigned\t*p_co(p.coeffs),\t*q_co(q.coeffs);\n\tunsigned\t\tp_deg(p.degree),\tq_deg(q.degree);\n\tunsigned\t\tp_deg_p1(p_deg+1),\tq_deg_p1(q_deg+1);\n\tunsigned\t\tr_deg(p_deg+q_deg),\tr_deg_p1(r_deg+1);\n\tunsigned\t\tcharecteristic(p.charecteristic);\n\t\n\tunsigned\t\tr_co[r_deg_p1];\n\t\n\t\/\/ Compute the new vector of coefficients\n\tfor ( i = 0 ; i < p_deg_p1 ; i++)\n\t\tfor ( j = 0 ; j < q_deg_p1 ; j++)\n\t\t\tr_co[i+j] = p_co[i] + q_co[j];\n\t\n\treturn polynomial(r_co, r_deg, charecteristic);\n}\n\nstatic polynomial& polynomial::operator*(int n, const polynomial& p)\n{\n\tunsigned\t\tcharecteristic(p.charecteristic);\n\tconst unsigned\t*p_co(p.coeffs);\n\tint\t\t\t\tp_deg(p.degree), p_deg_p1 = p_deg+1;\n\tunsigned\t\tr_co[q_deg+1];\n\t\n\t\/\/ Multiply everythin in p\n\tfor ( i = 0 ; i < p_deg_p1 ; i++ )\n\t\tr_co[i] = (n*p_co[i])%charecteristic;\n\t\t\n\treturn p + polynomial(r_co, q_deg, charecteristic);\n}\n\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: BaseListBox.hxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-18 16:29:04 $\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 _FORMS_BASELISTBOX_HXX_\n#define _FORMS_BASELISTBOX_HXX_\n\n\/\/.........................................................................\nnamespace frm\n{\n\nconst sal_uInt16 ENTRY_NOT_FOUND = 0xFFFF;\nconst sal_uInt16 BOUNDCOLUMN = 0x0001;\n\n\/\/.........................................................................\n}\n\/\/.........................................................................\n\n#endif \/\/ _FORMS_BASELISTBOX_HXX_\n\nINTEGRATION: CWS ooo19126 (1.1.1.1.370); FILE MERGED 2005\/09\/05 13:50:12 rt 1.1.1.1.370.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: BaseListBox.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 22:33:29 $\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 _FORMS_BASELISTBOX_HXX_\n#define _FORMS_BASELISTBOX_HXX_\n\n\/\/.........................................................................\nnamespace frm\n{\n\nconst sal_uInt16 ENTRY_NOT_FOUND = 0xFFFF;\nconst sal_uInt16 BOUNDCOLUMN = 0x0001;\n\n\/\/.........................................................................\n}\n\/\/.........................................................................\n\n#endif \/\/ _FORMS_BASELISTBOX_HXX_\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nenum FileAction {\n\tNone, Compress, Decompress\n};\n\nstatic bool codec_timing;\nstatic Timer codec_timer;\n\nstatic void compress(int, int, XCodec *);\nstatic void decompress(int, int, XCodec *);\nstatic bool fill(int, Buffer *);\nstatic void flush(int, Buffer *);\nstatic void process_files(int, char *[], FileAction, XCodec *, bool);\nstatic void time_samples(void);\nstatic void time_stats(void);\nstatic void usage(void);\n\nint\nmain(int argc, char *argv[])\n{\n\tUUID uuid;\n\tuuid.generate();\n\n\tXCodecCache *cache = XCodecCache::lookup(uuid);\n\tXCodec codec(cache);\n\n\tbool quiet_output, samples, verbose;\n\tFileAction action;\n\tint ch;\n\n\taction = None;\n\tquiet_output = false;\n\tsamples = false;\n\tverbose = false;\n\n\twhile ((ch = getopt(argc, argv, \"?cdvQST\")) != -1) {\n\t\tswitch (ch) {\n\t\tcase 'c':\n\t\t\taction = Compress;\n\t\t\tbreak;\n\t\tcase 'd':\n\t\t\taction = Decompress;\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tverbose = true;\n\t\t\tbreak;\n\t\tcase 'Q':\n\t\t\tquiet_output = true;\n\t\t\tbreak;\n\t\tcase 'S':\n\t\t\tsamples = true;\n\t\t\tbreak;\n\t\tcase 'T':\n\t\t\tcodec_timing = true;\n\t\t\tbreak;\n\t\tcase '?':\n\t\tdefault:\n\t\t\tusage();\n\t\t}\n\t}\n\targc -= optind;\n\targv += optind;\n\n\tif (verbose) {\n\t\tLog::mask(\".?\", Log::Debug);\n\t} else {\n\t\tLog::mask(\".?\", Log::Info);\n\t}\n\n\tswitch (action) {\n\tcase None:\n\t\tusage();\n\tcase Compress:\n\tcase Decompress:\n\t\tprocess_files(argc, argv, action, &codec, quiet_output);\n\t\tif (samples)\n\t\t\ttime_samples();\n\t\tif (codec_timing)\n\t\t\ttime_stats();\n\t\tbreak;\n\tdefault:\n\t\tNOTREACHED();\n\t}\n\n\treturn (0);\n}\n\nstatic void\ncompress(int ifd, int ofd, XCodec *codec)\n{\n\tXCodecEncoder encoder(codec->cache());\n\tBuffer input, output;\n\n\twhile (fill(ifd, &input)) {\n\t\tif (codec_timing)\n\t\t\tcodec_timer.start();\n\t\tencoder.encode(&output, &input);\n\t\tif (codec_timing)\n\t\t\tcodec_timer.stop();\n\t\tflush(ofd, &output);\n\t}\n\tASSERT(input.empty());\n\tASSERT(output.empty());\n}\n\nstatic void\ndecompress(int ifd, int ofd, XCodec *codec)\n{\n\tstd::set unknown_hashes;\n\tXCodecDecoder decoder(codec->cache());\n\tBuffer input, output;\n\n\t(void)codec;\n\n\twhile (fill(ifd, &input)) {\n\t\tif (codec_timing)\n\t\t\tcodec_timer.start();\n\t\tif (!decoder.decode(&output, &input, unknown_hashes)) {\n\t\t\tERROR(\"\/decompress\") << \"Decode failed.\";\n\t\t\treturn;\n\t\t}\n\t\tif (codec_timing)\n\t\t\tcodec_timer.stop();\n\t\tif (!unknown_hashes.empty()) {\n\t\t\tERROR(\"\/decompress\") << \"Cannot decode stream with unknown hashes.\";\n\t\t\treturn;\n\t\t}\n\t\tflush(ofd, &output);\n\t}\n\tASSERT(input.empty());\n\tASSERT(output.empty());\n}\n\nstatic bool\nfill(int fd, Buffer *input)\n{\n\tuint8_t data[65536];\n\tssize_t len;\n\n\tlen = read(fd, data, sizeof data);\n\tif (len == -1)\n\t\tHALT(\"\/fill\") << \"read failed.\";\n\tif (len == 0)\n\t\treturn (false);\n\tinput->append(data, len);\n\treturn (true);\n}\n\nstatic void\nflush(int fd, Buffer *output)\n{\n\tssize_t len;\n\n\tif (fd == -1) {\n\t\toutput->clear();\n\t\treturn;\n\t}\n\n\tfor (;;) {\n\t\tBuffer::SegmentIterator iter = output->segments();\n\t\tif (iter.end())\n\t\t\tbreak;\n\n\t\tconst BufferSegment *seg = *iter;\n\n\t\tlen = write(fd, seg->data(), seg->length());\n\t\tif (len != (ssize_t)seg->length())\n\t\t\tHALT(\"\/output\") << \"write failed.\";\n\t\toutput->skip((size_t)len);\n\t}\n\tASSERT(output->empty());\n}\n\nstatic void\nprocess_file(int ifd, int ofd, FileAction action, XCodec *codec)\n{\n\tswitch (action) {\n\tcase Compress:\n\t\tcompress(ifd, ofd, codec);\n\t\tbreak;\n\tcase Decompress:\n\t\tdecompress(ifd, ofd, codec);\n\t\tbreak;\n\tdefault:\n\t\tNOTREACHED();\n\t}\n}\n\nstatic void\nprocess_files(int argc, char *argv[], FileAction action, XCodec *codec, bool quiet)\n{\n\tint ifd, ofd;\n\n\tif (argc == 0) {\n\t\tifd = STDIN_FILENO;\n\t\tif (quiet)\n\t\t\tofd = -1;\n\t\telse\n\t\t\tofd = STDOUT_FILENO;\n\t\tprocess_file(ifd, ofd, action, codec);\n\t} else {\n\t\twhile (argc--) {\n\t\t\tconst char *file = *argv++;\n\n\t\t\tifd = open(file, O_RDONLY);\n\t\t\tASSERT(ifd != -1);\n\t\t\tif (quiet)\n\t\t\t\tofd = -1;\n\t\t\telse\n\t\t\t\tofd = STDOUT_FILENO;\n\n\t\t\tprocess_file(ifd, ofd, action, codec);\n\t\t}\n\t}\n}\n\nstatic void\ntime_samples(void)\n{\n\tstd::vector samples = codec_timer.samples();\n\tstd::vector::iterator it;\n\n\tfor (it = samples.begin(); it != samples.end(); ++it)\n\t\tfprintf(stderr, \"%ju\\n\", *it);\n}\n\nstatic void\ntime_stats(void)\n{\n\tstd::vector samples = codec_timer.samples();\n\tstd::vector::iterator it;\n\tLogHandle log(\"\/codec_timer\");\n\tuintmax_t microseconds;\n\n\tINFO(log) << samples.size() << \" timer samples.\";\n\tmicroseconds = 0;\n\tfor (it = samples.begin(); it != samples.end(); ++it)\n\t\tmicroseconds += *it;\n\tINFO(log) << microseconds << \" total runtime.\";\n\tINFO(log) << (microseconds \/ samples.size()) << \" mean microseconds\/call.\";\n}\n\nstatic void\nusage(void)\n{\n\tfprintf(stderr,\n\"usage: tack [-vQST] -c [file ...]\\n\"\n\" tack [-vQST] -d [file ...]\\n\");\n\texit(1);\n}\nGet rid of global variables.#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nenum FileAction {\n\tNone, Compress, Decompress\n};\n\nstatic void compress(int, int, XCodec *, bool, Timer *);\nstatic void decompress(int, int, XCodec *, bool, Timer *);\nstatic bool fill(int, Buffer *);\nstatic void flush(int, Buffer *);\nstatic void process_file(int, int, FileAction, XCodec *, bool, Timer *);\nstatic void process_files(int, char *[], FileAction, XCodec *, bool, bool, Timer *);\nstatic void time_samples(Timer *);\nstatic void time_stats(Timer *);\nstatic void usage(void);\n\nint\nmain(int argc, char *argv[])\n{\n\tUUID uuid;\n\tuuid.generate();\n\n\tXCodecCache *cache = XCodecCache::lookup(uuid);\n\tXCodec codec(cache);\n\n\tbool codec_timing, quiet_output, samples, verbose;\n\tFileAction action;\n\tint ch;\n\n\taction = None;\n\tcodec_timing = false;\n\tquiet_output = false;\n\tsamples = false;\n\tverbose = false;\n\n\twhile ((ch = getopt(argc, argv, \"?cdvQST\")) != -1) {\n\t\tswitch (ch) {\n\t\tcase 'c':\n\t\t\taction = Compress;\n\t\t\tbreak;\n\t\tcase 'd':\n\t\t\taction = Decompress;\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tverbose = true;\n\t\t\tbreak;\n\t\tcase 'Q':\n\t\t\tquiet_output = true;\n\t\t\tbreak;\n\t\tcase 'S':\n\t\t\tsamples = true;\n\t\t\tbreak;\n\t\tcase 'T':\n\t\t\tcodec_timing = true;\n\t\t\tbreak;\n\t\tcase '?':\n\t\tdefault:\n\t\t\tusage();\n\t\t}\n\t}\n\targc -= optind;\n\targv += optind;\n\n\tif (verbose) {\n\t\tLog::mask(\".?\", Log::Debug);\n\t} else {\n\t\tLog::mask(\".?\", Log::Info);\n\t}\n\n\tTimer codec_timer;\n\n\tswitch (action) {\n\tcase None:\n\t\tusage();\n\tcase Compress:\n\tcase Decompress:\n\t\tprocess_files(argc, argv, action, &codec, quiet_output, codec_timing, &codec_timer);\n\t\tif (samples)\n\t\t\ttime_samples(&codec_timer);\n\t\tif (codec_timing)\n\t\t\ttime_stats(&codec_timer);\n\t\tbreak;\n\tdefault:\n\t\tNOTREACHED();\n\t}\n\n\treturn (0);\n}\n\nstatic void\ncompress(int ifd, int ofd, XCodec *codec, bool timing, Timer *timer)\n{\n\tXCodecEncoder encoder(codec->cache());\n\tBuffer input, output;\n\n\twhile (fill(ifd, &input)) {\n\t\tif (timing)\n\t\t\ttimer->start();\n\t\tencoder.encode(&output, &input);\n\t\tif (timing)\n\t\t\ttimer->stop();\n\t\tflush(ofd, &output);\n\t}\n\tASSERT(input.empty());\n\tASSERT(output.empty());\n}\n\nstatic void\ndecompress(int ifd, int ofd, XCodec *codec, bool timing, Timer *timer)\n{\n\tstd::set unknown_hashes;\n\tXCodecDecoder decoder(codec->cache());\n\tBuffer input, output;\n\n\t(void)codec;\n\n\twhile (fill(ifd, &input)) {\n\t\tif (timing)\n\t\t\ttimer->start();\n\t\tif (!decoder.decode(&output, &input, unknown_hashes)) {\n\t\t\tERROR(\"\/decompress\") << \"Decode failed.\";\n\t\t\treturn;\n\t\t}\n\t\tif (timing)\n\t\t\ttimer->stop();\n\t\tif (!unknown_hashes.empty()) {\n\t\t\tERROR(\"\/decompress\") << \"Cannot decode stream with unknown hashes.\";\n\t\t\treturn;\n\t\t}\n\t\tflush(ofd, &output);\n\t}\n\tASSERT(input.empty());\n\tASSERT(output.empty());\n}\n\nstatic bool\nfill(int fd, Buffer *input)\n{\n\tuint8_t data[65536];\n\tssize_t len;\n\n\tlen = read(fd, data, sizeof data);\n\tif (len == -1)\n\t\tHALT(\"\/fill\") << \"read failed.\";\n\tif (len == 0)\n\t\treturn (false);\n\tinput->append(data, len);\n\treturn (true);\n}\n\nstatic void\nflush(int fd, Buffer *output)\n{\n\tssize_t len;\n\n\tif (fd == -1) {\n\t\toutput->clear();\n\t\treturn;\n\t}\n\n\tfor (;;) {\n\t\tBuffer::SegmentIterator iter = output->segments();\n\t\tif (iter.end())\n\t\t\tbreak;\n\n\t\tconst BufferSegment *seg = *iter;\n\n\t\tlen = write(fd, seg->data(), seg->length());\n\t\tif (len != (ssize_t)seg->length())\n\t\t\tHALT(\"\/output\") << \"write failed.\";\n\t\toutput->skip((size_t)len);\n\t}\n\tASSERT(output->empty());\n}\n\nstatic void\nprocess_file(int ifd, int ofd, FileAction action, XCodec *codec, bool timing, Timer *timer)\n{\n\tswitch (action) {\n\tcase Compress:\n\t\tcompress(ifd, ofd, codec, timing, timer);\n\t\tbreak;\n\tcase Decompress:\n\t\tdecompress(ifd, ofd, codec, timing, timer);\n\t\tbreak;\n\tdefault:\n\t\tNOTREACHED();\n\t}\n}\n\nstatic void\nprocess_files(int argc, char *argv[], FileAction action, XCodec *codec, bool quiet, bool timing, Timer *timer)\n{\n\tint ifd, ofd;\n\n\tif (argc == 0) {\n\t\tifd = STDIN_FILENO;\n\t\tif (quiet)\n\t\t\tofd = -1;\n\t\telse\n\t\t\tofd = STDOUT_FILENO;\n\t\tprocess_file(ifd, ofd, action, codec, timing, timer);\n\t} else {\n\t\twhile (argc--) {\n\t\t\tconst char *file = *argv++;\n\n\t\t\tifd = open(file, O_RDONLY);\n\t\t\tASSERT(ifd != -1);\n\t\t\tif (quiet)\n\t\t\t\tofd = -1;\n\t\t\telse\n\t\t\t\tofd = STDOUT_FILENO;\n\n\t\t\tprocess_file(ifd, ofd, action, codec, timing, timer);\n\t\t}\n\t}\n}\n\nstatic void\ntime_samples(Timer *timer)\n{\n\tstd::vector samples = timer->samples();\n\tstd::vector::iterator it;\n\n\tfor (it = samples.begin(); it != samples.end(); ++it)\n\t\tfprintf(stderr, \"%ju\\n\", *it);\n}\n\nstatic void\ntime_stats(Timer *timer)\n{\n\tstd::vector samples = timer->samples();\n\tstd::vector::iterator it;\n\tLogHandle log(\"\/codec_timer\");\n\tuintmax_t microseconds;\n\n\tINFO(log) << samples.size() << \" timer samples.\";\n\tmicroseconds = 0;\n\tfor (it = samples.begin(); it != samples.end(); ++it)\n\t\tmicroseconds += *it;\n\tINFO(log) << microseconds << \" total runtime.\";\n\tINFO(log) << (microseconds \/ samples.size()) << \" mean microseconds\/call.\";\n}\n\nstatic void\nusage(void)\n{\n\tfprintf(stderr,\n\"usage: tack [-vQST] -c [file ...]\\n\"\n\" tack [-vQST] -d [file ...]\\n\");\n\texit(1);\n}\n<|endoftext|>"} {"text":"\/***************************************************************************\n * Copyright (C) 2006 by FThauer FHammer *\n * f.thauer@web.de *\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 *\n * Free Software Foundation, Inc., *\n * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *\n ***************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef __APPLE__\n\t#include \n#endif\n\n#include \n\n#include \"session.h\"\n#include \"startwindowimpl.h\"\n#include \"configfile.h\"\n#include \"startsplash.h\"\n#include \"game_defs.h\"\n#include \n#include \n\n#ifdef _MSC_VER\n\t#ifdef _DEBUG\n\t\t#define _CRTDBG_MAP_ALLOC\n\t\t#include \n\n\t\t#define ENABLE_LEAK_CHECK() \\\n\t\t\t{ \\\n\t\t\t\tint tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); \\\n\t\t\t\ttmpFlag |= _CRTDBG_LEAK_CHECK_DF; \\\n\t\t\t\t_CrtSetDbgFlag(tmpFlag); \\\n\t\t\t}\n\t#endif\n#endif\n\n#ifndef ENABLE_LEAK_CHECK\n\t#define ENABLE_LEAK_CHECK()\n#endif\n\n\/\/Uncomment this for RELEASE on Linux\/Unix\/BSD (static Qt only)\n\/\/#include \n\/\/Q_IMPORT_PLUGIN(qjpeg)\n\/\/Q_IMPORT_PLUGIN(qgif)\n\n\n#ifdef _WIN32 \/\/ Always use static Qt on Windows.\n#include \nQ_IMPORT_PLUGIN(qjpeg)\nQ_IMPORT_PLUGIN(qgif)\n#endif\n\nusing namespace std;\n\nclass startWindowImpl;\nclass Game;\n\nint main( int argc, char **argv )\n{\n\t\n\t\/\/ENABLE_LEAK_CHECK();\n\n\t\/\/_CrtSetBreakAlloc(49937);\n\tsocket_startup();\n\tcurl_global_init(CURL_GLOBAL_NOTHING);\n\n\t\/\/\/\/\/\/\/ can be removed for non-qt-guis \/\/\/\/\/\/\/\/\/\/\/\/\n\tQtSingleApplication a( argc, argv );\n\n\tif (a.sendMessage(\"Wake up!\")) {\n\t\treturn 0;\n\t }\n\n#ifdef __APPLE__\n\t\/\/ The following needs to be done directly after the application is created.\n\tQDir dir(QApplication::applicationDirPath());\n\tdir.cdUp();\n\tdir.cd(\"plugins\");\n\tQApplication::setLibraryPaths(QStringList(dir.absolutePath()));\n#endif\n\n\t\/\/create defaultconfig\n\tConfigFile *myConfig = new ConfigFile(argv[0], false);\n\n\t\/\/ set PlastiqueStyle even for mac-version to prevent artefacts on styled widgets\n\ta.setStyle(new QPlastiqueStyle);\n\n\tQString\tmyAppDataPath = QString::fromUtf8(myConfig->readConfigString(\"AppDataDir\").c_str());\n\t\/\/set QApplication default font\t\n\n\tQFontDatabase::addApplicationFont (myAppDataPath +\"fonts\/n019003l.pfb\");\n\tQFontDatabase::addApplicationFont (myAppDataPath +\"fonts\/VeraBd.ttf\");\t\n\tQFontDatabase::addApplicationFont (myAppDataPath +\"fonts\/c059013l.pfb\");\n\n#ifdef _WIN32\n\tQString font1String(\"font-family: \\\"Arial\\\";\");\n\ta.setStyleSheet(\"QApplication, QWidget, QDialog { \" + font1String + \" font-size: 12px; }\");\n#else \n\/\/ \t\tQString font1String(\"font-family: \\\"Lucida Grande\\\";\");\n\tQString font1String(\"font-family: \\\"Nimbus Sans L\\\";\");\n\n #ifdef __APPLE__\n a.setStyleSheet(\"QApplication, QWidget, QDialog { \" + font1String + \" font-size: 10px; }\");\n #else\n a.setStyleSheet(\"QApplication, QWidget, QDialog { \" + font1String + \" font-size: 12px; }\");\n #endif\n#endif\t\n\ta.setStyleSheet(\"QDialogButtonBox, QMessageBox { dialogbuttonbox-buttons-have-icons: 1; dialog-ok-icon: url(:\/gfx\/dialog_ok_apply.png); dialog-cancel-icon: url(:\/gfx\/dialog_close.png); dialog-close-icon: url(:\/gfx\/dialog_close.png); dialog-yes-icon: url(:\/gfx\/dialog_ok_apply.png); dialog-no-icon: url(:\/gfx\/dialog_close.png) }\");\n\n\tQPixmap *pixmap = new QPixmap(myAppDataPath + \"gfx\/gui\/misc\/welcomepokerth.png\");\n\tStartSplash splash(*pixmap);\n\tif(!myConfig->readConfigInt(\"DisableSplashScreenOnStartup\")) {\n\t\tsplash.show();\n\t\tsplash.showMessage(QString(\"Version %1\").arg(POKERTH_BETA_RELEASE_STRING), 0x0042, QColor(153,213,0));\n\t}\n\t\n\t\/\/Set translations\n\tQTranslator qtTranslator;\n qtTranslator.load(QString(myAppDataPath +\"translations\/qt_\") + QString::fromStdString(myConfig->readConfigString(\"Language\")));\n a.installTranslator(&qtTranslator);\n\n\tQTranslator translator;\n\ttranslator.load(QString(myAppDataPath +\"translations\/pokerth_\") + QString::fromStdString(myConfig->readConfigString(\"Language\")));\n\ta.installTranslator(&translator);\n\n\tqRegisterMetaType(\"unsigned\");\n\tqRegisterMetaType >(\"boost::shared_ptr\");\n\tqRegisterMetaType(\"ServerStats\");\n qRegisterMetaType(\"DenyGameInvitationReason\");\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\t\n\n startWindowImpl mainWin(myConfig);\n a.setActivationWindow(&mainWin, true);\n\n\tint retVal = a.exec();\n\t\n\tcurl_global_cleanup();\n\tsocket_cleanup();\n \n \n\treturn retVal;\n\t\n}\nmac font fix\/***************************************************************************\n * Copyright (C) 2006 by FThauer FHammer *\n * f.thauer@web.de *\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 *\n * Free Software Foundation, Inc., *\n * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *\n ***************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef __APPLE__\n\t#include \n#endif\n\n#include \n\n#include \"session.h\"\n#include \"startwindowimpl.h\"\n#include \"configfile.h\"\n#include \"startsplash.h\"\n#include \"game_defs.h\"\n#include \n#include \n\n#ifdef _MSC_VER\n\t#ifdef _DEBUG\n\t\t#define _CRTDBG_MAP_ALLOC\n\t\t#include \n\n\t\t#define ENABLE_LEAK_CHECK() \\\n\t\t\t{ \\\n\t\t\t\tint tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); \\\n\t\t\t\ttmpFlag |= _CRTDBG_LEAK_CHECK_DF; \\\n\t\t\t\t_CrtSetDbgFlag(tmpFlag); \\\n\t\t\t}\n\t#endif\n#endif\n\n#ifndef ENABLE_LEAK_CHECK\n\t#define ENABLE_LEAK_CHECK()\n#endif\n\n\/\/Uncomment this for RELEASE on Linux\/Unix\/BSD (static Qt only)\n\/\/#include \n\/\/Q_IMPORT_PLUGIN(qjpeg)\n\/\/Q_IMPORT_PLUGIN(qgif)\n\n\n#ifdef _WIN32 \/\/ Always use static Qt on Windows.\n#include \nQ_IMPORT_PLUGIN(qjpeg)\nQ_IMPORT_PLUGIN(qgif)\n#endif\n\nusing namespace std;\n\nclass startWindowImpl;\nclass Game;\n\nint main( int argc, char **argv )\n{\n\t\n\t\/\/ENABLE_LEAK_CHECK();\n\n\t\/\/_CrtSetBreakAlloc(49937);\n\tsocket_startup();\n\tcurl_global_init(CURL_GLOBAL_NOTHING);\n\n\t\/\/\/\/\/\/\/ can be removed for non-qt-guis \/\/\/\/\/\/\/\/\/\/\/\/\n\tQtSingleApplication a( argc, argv );\n\n\tif (a.sendMessage(\"Wake up!\")) {\n\t\treturn 0;\n\t }\n\n#ifdef __APPLE__\n\t\/\/ The following needs to be done directly after the application is created.\n\tQDir dir(QApplication::applicationDirPath());\n\tdir.cdUp();\n\tdir.cd(\"plugins\");\n\tQApplication::setLibraryPaths(QStringList(dir.absolutePath()));\n#endif\n\n\t\/\/create defaultconfig\n\tConfigFile *myConfig = new ConfigFile(argv[0], false);\n\n\t\/\/ set PlastiqueStyle even for mac-version to prevent artefacts on styled widgets\n\ta.setStyle(new QPlastiqueStyle);\n\n\tQString\tmyAppDataPath = QString::fromUtf8(myConfig->readConfigString(\"AppDataDir\").c_str());\n\t\/\/set QApplication default font\t\n\n\tQFontDatabase::addApplicationFont (myAppDataPath +\"fonts\/n019003l.pfb\");\n\tQFontDatabase::addApplicationFont (myAppDataPath +\"fonts\/VeraBd.ttf\");\t\n\tQFontDatabase::addApplicationFont (myAppDataPath +\"fonts\/c059013l.pfb\");\n\n#ifdef _WIN32\n\tQString font1String(\"font-family: \\\"Arial\\\";\");\n\ta.setStyleSheet(\"QApplication, QWidget, QDialog { \" + font1String + \" font-size: 12px; }\");\n#else \n\/\/ \t\tQString font1String(\"font-family: \\\"Lucida Grande\\\";\");\n\tQString font1String(\"font-family: \\\"Nimbus Sans L\\\";\");\n\n #ifdef __APPLE__\n a.setStyleSheet(\"QApplication, QWidget, QDialog { \" + font1String + \" font-size: 10pt; }\");\n #else\n a.setStyleSheet(\"QApplication, QWidget, QDialog { \" + font1String + \" font-size: 12px; }\");\n #endif\n#endif\t\n\ta.setStyleSheet(\"QDialogButtonBox, QMessageBox { dialogbuttonbox-buttons-have-icons: 1; dialog-ok-icon: url(:\/gfx\/dialog_ok_apply.png); dialog-cancel-icon: url(:\/gfx\/dialog_close.png); dialog-close-icon: url(:\/gfx\/dialog_close.png); dialog-yes-icon: url(:\/gfx\/dialog_ok_apply.png); dialog-no-icon: url(:\/gfx\/dialog_close.png) }\");\n\n\tQPixmap *pixmap = new QPixmap(myAppDataPath + \"gfx\/gui\/misc\/welcomepokerth.png\");\n\tStartSplash splash(*pixmap);\n\tif(!myConfig->readConfigInt(\"DisableSplashScreenOnStartup\")) {\n\t\tsplash.show();\n\t\tsplash.showMessage(QString(\"Version %1\").arg(POKERTH_BETA_RELEASE_STRING), 0x0042, QColor(153,213,0));\n\t}\n\t\n\t\/\/Set translations\n\tQTranslator qtTranslator;\n qtTranslator.load(QString(myAppDataPath +\"translations\/qt_\") + QString::fromStdString(myConfig->readConfigString(\"Language\")));\n a.installTranslator(&qtTranslator);\n\n\tQTranslator translator;\n\ttranslator.load(QString(myAppDataPath +\"translations\/pokerth_\") + QString::fromStdString(myConfig->readConfigString(\"Language\")));\n\ta.installTranslator(&translator);\n\n\tqRegisterMetaType(\"unsigned\");\n\tqRegisterMetaType >(\"boost::shared_ptr\");\n\tqRegisterMetaType(\"ServerStats\");\n qRegisterMetaType(\"DenyGameInvitationReason\");\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\t\n\n startWindowImpl mainWin(myConfig);\n a.setActivationWindow(&mainWin, true);\n\n\tint retVal = a.exec();\n\t\n\tcurl_global_cleanup();\n\tsocket_cleanup();\n \n \n\treturn retVal;\n\t\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\/filerepository.h\"\n#include \"fnord-base\/io\/fileutil.h\"\n#include \"fnord-base\/io\/mmappedfile.h\"\n#include \"fnord-base\/application.h\"\n#include \"fnord-base\/logging.h\"\n#include \"fnord-base\/random.h\"\n#include \"fnord-base\/thread\/eventloop.h\"\n#include \"fnord-base\/thread\/threadpool.h\"\n#include \"fnord-base\/wallclock.h\"\n#include \"fnord-rpc\/ServerGroup.h\"\n#include \"fnord-rpc\/RPC.h\"\n#include \"fnord-rpc\/RPCClient.h\"\n#include \"fnord-base\/cli\/flagparser.h\"\n#include \"fnord-json\/json.h\"\n#include \"fnord-json\/jsonrpc.h\"\n#include \"fnord-http\/httprouter.h\"\n#include \"fnord-http\/httpserver.h\"\n#include \"fnord-feeds\/FeedService.h\"\n#include \"fnord-feeds\/RemoteFeedFactory.h\"\n#include \"fnord-feeds\/RemoteFeedReader.h\"\n#include \"fnord-base\/stats\/statsdagent.h\"\n#include \"fnord-base\/RadixTree.h\"\n#include \"fnord-mdb\/MDB.h\"\n#include \"CustomerNamespace.h\"\n#include \"FeatureSchema.h\"\n#include \"FeaturePack.h\"\n#include \"PackedExample.h\"\n#include \"FeatureIndex.h\"\n#include \"JoinedQuery.h\"\n\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 \"cmdata\",\n cli::FlagParser::T_STRING,\n true,\n NULL,\n NULL,\n \"clickmatcher app data dir\",\n \"\");\n\n flags.defineFlag(\n \"cmcustomer\",\n cli::FlagParser::T_STRING,\n true,\n NULL,\n NULL,\n \"clickmatcher customer\",\n \"\");\n\n flags.defineFlag(\n \"features\",\n fnord::cli::FlagParser::T_STRING,\n true,\n \"f\",\n NULL,\n \"features file\",\n \"\");\n\n flags.defineFlag(\n \"input\",\n fnord::cli::FlagParser::T_STRING,\n true,\n \"i\",\n NULL,\n \"input file\",\n \"\");\n\n flags.defineFlag(\n \"output\",\n fnord::cli::FlagParser::T_STRING,\n true,\n \"o\",\n NULL,\n \"output file\",\n \"\");\n\n flags.defineFlag(\n \"separator\",\n fnord::cli::FlagParser::T_STRING,\n false,\n \"s\",\n \"\\n\",\n \"separator\",\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 \/* args *\/\n auto cmcustomer = flags.getString(\"cmcustomer\");\n auto featurefile_path = flags.getString(\"features\");\n auto inputfile_path = flags.getString(\"input\");\n auto outputfile_path = flags.getString(\"output\");\n\n auto separator_str = flags.getString(\"separator\");\n if (separator_str.length() != 1) {\n \/\/ print usage\n return 1;\n }\n\n char separator = separator_str[0];\n\n \/* set up and read output feature schema *\/\n cm::FeatureSchema output_feature_schema;\n output_feature_schema.load(FileUtil::read(featurefile_path));\n\n \/* set up featuredb schema *\/\n cm::FeatureSchema featuredb_schema;\n featuredb_schema.registerFeature(\"shop_id\", 1, 1);\n featuredb_schema.registerFeature(\"category1\", 2, 1);\n featuredb_schema.registerFeature(\"category2\", 3, 1);\n featuredb_schema.registerFeature(\"category3\", 4, 1);\n\n \/* set up cmdata *\/\n auto cmdata_path = flags.getString(\"cmdata\");\n if (!FileUtil::isDirectory(cmdata_path)) {\n RAISEF(kIOError, \"no such directory: $0\", cmdata_path);\n }\n\n \/* open featuredb *\/\n auto featuredb_path = FileUtil::joinPaths(\n cmdata_path,\n StringUtil::format(\"index\/$0\/db\", cmcustomer));\n\n auto featuredb = mdb::MDB::open(featuredb_path, true);\n cm::FeatureIndex feature_index(featuredb, &featuredb_schema);\n auto featuredb_txn = featuredb->startTransaction(true);\n\n \/* open output file *\/\n auto outfile = File::openFile(\n outputfile_path,\n File::O_READ | File::O_WRITE | File::O_CREATE);\n\n \/* mmap input file *\/\n io::MmappedFile mmap(File::openFile(inputfile_path, File::O_READ));\n madvise(mmap.data(), mmap.size(), MADV_WILLNEED);\n\n auto begin = (char *) mmap.begin();\n auto cur = begin;\n auto end = (char *) mmap.end();\n auto last = cur;\n uint64_t total_entries = 0;\n uint64_t total_bytes = 0;\n auto start_time = WallClock::now().unixMicros();\n auto last_status_line = start_time;\n\n \/* status line *\/\n auto status_line = [\n begin,\n end,\n &cur,\n &total_bytes,\n &total_entries,\n &start_time,\n &last_status_line] {\n auto now = WallClock::now().unixMicros();\n if (now - last_status_line < 10000) {\n return;\n }\n\n last_status_line = now;\n auto runtime = (now - start_time) \/ 1000000;\n int percent = ((double) (cur - begin) \/ (double) (end - begin)) * 100;\n uint64_t bandwidth = total_bytes \/ (runtime + 1);\n\n auto str = StringUtil::format(\n \"\\r[$0%] scanning: entries=$1 bytes=$2B time=$3s bw=$4B\/s\" \\\n \" \",\n percent,\n total_entries,\n total_bytes,\n runtime,\n bandwidth);\n\n write(0, str.c_str(), str.length());\n fflush(0);\n };\n\n HashMap feature_counts;\n\n \/* scan entries *\/\n for (; cur != end; ++cur) {\n status_line();\n\n if (*cur != separator) {\n continue;\n }\n\n if (cur > last + 1) {\n try {\n auto query = json::fromJSON(String(last, cur - last));\n\n for (const auto& item : query.items) {\n if (item.position > 16) {\n continue;\n }\n\n cm::Example ex;\n ex.label = item.clicked ? 1.0 : -1.0;\n ex.features = joinedQueryItemFeatures(\n query,\n item,\n &featuredb_schema,\n &feature_index,\n featuredb_txn.get());\n\n auto ex_str = exampleToSVMLight(ex, &output_feature_schema);\n if (ex_str.length() > 0) {\n outfile.write(ex_str + \"\\n\");\n }\n }\n } catch (const Exception& e) {\n fnord::logError(\"cm.featuredump\", e, \"error\");\n }\n\n total_bytes += cur - last;\n ++total_entries;\n }\n\n last = cur + 1;\n }\n\n status_line();\n write(0, \"\\n\", 1);\n fflush(0);\n\n \/* clean up *\/\n featuredb_txn->abort();\n exit(0);\n}\n\ncount feature observations in cm-featuredump\/**\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 \"common.h\"\n\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 \"output_file\",\n fnord::cli::FlagParser::T_STRING,\n true,\n \"o\",\n NULL,\n \"output file\",\n \"\");\n\n flags.defineFlag(\n \"min_observations\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"100\",\n \"minimum nuber of feature observations\",\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 auto sstables = flags.getArgv();\n if (sstables.size() == 0) {\n fnord::logCritical(\"cm.featuredump\", \"No input tables, exiting\");\n return 1;\n }\n\n \/* read input meta tables and count features *\/\n HashMap feature_counts;\n for (int tbl_idx = 0; tbl_idx < sstables.size(); ++tbl_idx) {\n String sstable = sstables[tbl_idx];\n StringUtil::replaceAll(&sstable, \".sstable\", \"_meta.sstable\");\n fnord::logInfo(\"cm.featuredump\", \"Importing sstable: $0\", sstable);\n\n \/* read sstable heade r*\/\n sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));\n sstable::SSTableColumnSchema schema;\n schema.loadIndex(&reader);\n\n if (reader.bodySize() == 0) {\n fnord::logCritical(\"cm.featuredump\", \"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 int row_idx = 0;\n\n \/* status line *\/\n util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {\n fnord::logInfo(\n \"cm.featuredump\",\n \"[$1\/$2] [$0%] Reading sstable... rows=$3\",\n (size_t) ((cursor->position() \/ (double) body_size) * 100),\n tbl_idx + 1, sstables.size(), 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\n sstable::SSTableColumnReader cols(&schema, val);\n auto cnt = cols.getUInt64Column(schema.columnID(\"count\"));\n\n feature_counts[key] += cnt;\n\n if (!cursor->next()) {\n break;\n }\n }\n\n status_line.runForce();\n }\n\n \/* select features for export *\/\n Set features;\n auto orig_count = feature_counts.size();\n auto min_count = flags.getInt(\"min_observations\");\n for (auto iter = feature_counts.begin(); iter != feature_counts.end(); ) {\n if (iter->second > min_count) {\n features.emplace(iter->first);\n }\n\n iter = feature_counts.erase(iter);\n }\n\n feature_counts.clear();\n\n fnord::logInfo(\n \"cm.featuredump\",\n \"Exporting $1\/$0 features\",\n orig_count,\n features.size());\n\n return 0;\n}\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_numadimprs_col(1, 1, 250);\n cstable::BitPackedIntColumnWriter jq_numadclicks_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.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 \/* queries.num_item_clicks, queries.num_items *\/\n size_t nitems = 0;\n size_t nclicks = 0;\n size_t nads = 0;\n size_t nadclicks = 0;\n for (const auto& i : q.items) {\n \/\/ DAWANDA HACK\n if (i.position >= 1 && i.position <= 4) {\n ++nads;\n nadclicks += i.clicked;\n }\n \/\/ EOF DAWANDA HACK\n\n ++nitems;\n nclicks += i.clicked;\n }\n\n if (nadclicks > 0 && lang != Language::DE) {\n abort();\n }\n\n jq_numitems_col.addDatum(r, 1, nitems);\n jq_numitemclicks_col.addDatum(r, 1, nclicks);\n jq_numadimprs_col.addDatum(r, 1, nads);\n jq_numadclicks_col.addDatum(r, 1, nadclicks);\n\n \/* queries.page *\/\n auto pg_str = cm::extractAttr(q.attrs, \"pg\");\n if (pg_str.isEmpty()) {\n jq_page_col.addNull(r, 0);\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\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.num_ad_impressions\", &jq_numadimprs_col);\n writer.addColumn(\"queries.num_ad_clicks\", &jq_numadclicks_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 \/\/ auto lcol = aq.fetchColumn(\"queries.language\");\n \/\/ auto ccol = aq.fetchColumn(\"queries.num_ad_clicks\");\n\n \/\/ aq.onQuery([&] () {\n \/\/ auto l = languageToString((Language) lcol->getUInt32());\n \/\/ auto c = ccol->getUInt32();\n \/\/ fnord::iputs(\"lang: $0 -> $1\", l, c);\n \/\/ });\n\n \/\/ aq.scanTable(&reader);\n \/\/ \/\/cm::CTRByGroupResult res;\n \/\/ \/\/cm::CTRByPositionQuery q(&aq, &res);\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\nfixes\/**\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_numadimprs_col(1, 1, 250);\n cstable::BitPackedIntColumnWriter jq_numadclicks_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.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 \/* queries.num_item_clicks, queries.num_items *\/\n size_t nitems = 0;\n size_t nclicks = 0;\n size_t nads = 0;\n size_t nadclicks = 0;\n for (const auto& i : q.items) {\n \/\/ DAWANDA HACK\n if (i.position >= 1 && i.position <= 4) {\n ++nads;\n nadclicks += i.clicked;\n }\n \/\/ EOF DAWANDA HACK\n\n ++nitems;\n nclicks += i.clicked;\n }\n\n if (nadclicks > 0 && lang != Language::DE) {\n abort();\n }\n\n jq_numitems_col.addDatum(r, 1, nitems);\n jq_numitemclicks_col.addDatum(r, 1, nclicks);\n jq_numadimprs_col.addDatum(r, 1, nads);\n jq_numadclicks_col.addDatum(r, 1, nadclicks);\n\n \/* queries.page *\/\n auto pg_str = cm::extractAttr(q.attrs, \"pg\");\n if (pg_str.isEmpty()) {\n jq_page_col.addNull(r, 0);\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, 0);\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, 0);\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, 0);\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, 0);\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\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.num_ad_impressions\", &jq_numadimprs_col);\n writer.addColumn(\"queries.num_ad_clicks\", &jq_numadclicks_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 \/\/ auto lcol = aq.fetchColumn(\"queries.language\");\n \/\/ auto ccol = aq.fetchColumn(\"queries.num_ad_clicks\");\n\n \/\/ aq.onQuery([&] () {\n \/\/ auto l = languageToString((Language) lcol->getUInt32());\n \/\/ auto c = ccol->getUInt32();\n \/\/ fnord::iputs(\"lang: $0 -> $1\", l, c);\n \/\/ });\n\n \/\/ aq.scanTable(&reader);\n \/\/ \/\/cm::CTRByGroupResult res;\n \/\/ \/\/cm::CTRByPositionQuery q(&aq, &res);\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":"\/\/ kate: indent-mode cstyle; indent-width 4; tab-width 4; space-indent false;\n\/\/ vim:ai ts=4 et\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \"MainWindow.hpp\"\n\nusing namespace std;\n\nvoid usage(const char* prog)\n{\n\tprintf(\"usage: %s <-y|-b> [-ng] [-p ] [-f] [-c ]\\n\", prog);\n\tprintf(\"\\t-y: run as the yellow team\\n\");\n\tprintf(\"\\t-b: run as the blue team\\n\");\n\tprintf(\"\\t-ng: no goalie\\n\");\n\tprintf(\"\\t-c: specify the configuration file\\n\");\n\tprintf(\"\\t-f: flip field\\n\");\n\texit(1);\n}\n\nint main (int argc, char* argv[])\n{\n\t\/\/ Seed the large random number generator\n\tlong int seed = 0;\n\tint fd = open(\"\/dev\/random\", O_RDONLY);\n\tif (fd)\n\t{\n\t\tif (read(fd, &seed, sizeof(seed)) == sizeof(seed))\n\t\t{\n\t\t\tprintf(\"seed %016lx\\n\", seed);\n\t\t\tsrand48(seed);\n\t\t} else {\n\t\t\tfprintf(stderr, \"Can't read \/dev\/random: %m\\n\");\n\t\t}\n\t\tclose(fd);\n\t} else {\n\t\tfprintf(stderr, \"Can't open \/dev\/random: %m\\n\");\n\t}\n\t\n\tQApplication app(argc, argv);\n\n\tTeam team = UnknownTeam;\n\tQString cfgFile = \"\";\n\tvector playDirs;\n\n\tbool useGoalie = true;\n\tbool flip = false;\n\tfor (int i=1 ; i= argc)\n\t\t\t{\n\t\t\t\tprintf(\"no config file specified after -c\");\n\t\t\t\tusage(argv[0]);\n\t\t\t}\n\t\t\t\n\t\t\ti++;\n\t\t\tcfgFile = argv[i];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintf(\"Not a valid flag: %s\\n\", argv[i]);\n\t\t\tusage(argv[0]);\n\t\t}\n\t}\n\n\tif (team == UnknownTeam)\n\t{\n\t\tprintf(\"Error: No team specified\\n\");\n\t\tusage(argv[0]);\n\t\treturn 0;\n\t}\n\t\n\tMainWindow win(team, cfgFile);\n\t\n\tif (useGoalie)\n\t{\n\t\twin.processor()->gameplayModule()->createGoalie();\n\t}\n\t\n\twin.processor()->flip_field(flip);\n\t\n\twin.showMaximized();\n\n\treturn app.exec();\n}\nRemoved usage flag for plays folder\/\/ kate: indent-mode cstyle; indent-width 4; tab-width 4; space-indent false;\n\/\/ vim:ai ts=4 et\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \"MainWindow.hpp\"\n\nusing namespace std;\n\nvoid usage(const char* prog)\n{\n\tprintf(\"usage: %s <-y|-b> [-ng] [-f] [-c ]\\n\", prog);\n\tprintf(\"\\t-y: run as the yellow team\\n\");\n\tprintf(\"\\t-b: run as the blue team\\n\");\n\tprintf(\"\\t-ng: no goalie\\n\");\n\tprintf(\"\\t-c: specify the configuration file\\n\");\n\tprintf(\"\\t-f: flip field\\n\");\n\texit(1);\n}\n\nint main (int argc, char* argv[])\n{\n\t\/\/ Seed the large random number generator\n\tlong int seed = 0;\n\tint fd = open(\"\/dev\/random\", O_RDONLY);\n\tif (fd)\n\t{\n\t\tif (read(fd, &seed, sizeof(seed)) == sizeof(seed))\n\t\t{\n\t\t\tprintf(\"seed %016lx\\n\", seed);\n\t\t\tsrand48(seed);\n\t\t} else {\n\t\t\tfprintf(stderr, \"Can't read \/dev\/random: %m\\n\");\n\t\t}\n\t\tclose(fd);\n\t} else {\n\t\tfprintf(stderr, \"Can't open \/dev\/random: %m\\n\");\n\t}\n\t\n\tQApplication app(argc, argv);\n\n\tTeam team = UnknownTeam;\n\tQString cfgFile = \"\";\n\tvector playDirs;\n\n\tbool useGoalie = true;\n\tbool flip = false;\n\tfor (int i=1 ; i= argc)\n\t\t\t{\n\t\t\t\tprintf(\"no config file specified after -c\");\n\t\t\t\tusage(argv[0]);\n\t\t\t}\n\t\t\t\n\t\t\ti++;\n\t\t\tcfgFile = argv[i];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintf(\"Not a valid flag: %s\\n\", argv[i]);\n\t\t\tusage(argv[0]);\n\t\t}\n\t}\n\n\tif (team == UnknownTeam)\n\t{\n\t\tprintf(\"Error: No team specified\\n\");\n\t\tusage(argv[0]);\n\t\treturn 0;\n\t}\n\t\n\tMainWindow win(team, cfgFile);\n\t\n\tif (useGoalie)\n\t{\n\t\twin.processor()->gameplayModule()->createGoalie();\n\t}\n\t\n\twin.processor()->flip_field(flip);\n\t\n\twin.showMaximized();\n\n\treturn app.exec();\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_numadimprs_col(1, 1, 250);\n cstable::BitPackedIntColumnWriter jq_numadclicks_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.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 \/* queries.num_item_clicks, queries.num_items *\/\n size_t nitems = 0;\n size_t nclicks = 0;\n size_t nads = 0;\n size_t nadclicks = 0;\n for (const auto& i : q.items) {\n \/\/ DAWANDA HACK\n if (i.position >= 1 && i.position <= 4) {\n ++nads;\n nadclicks += i.clicked;\n }\n \/\/ EOF DAWANDA HACK\n\n ++nitems;\n nclicks += i.clicked;\n }\n\n if (nadclicks > 0 && lang != Language::DE) {\n abort();\n }\n\n jq_numitems_col.addDatum(r, 1, nitems);\n jq_numitemclicks_col.addDatum(r, 1, nclicks);\n jq_numadimprs_col.addDatum(r, 1, nads);\n jq_numadclicks_col.addDatum(r, 1, nadclicks);\n\n \/* queries.page *\/\n auto pg_str = cm::extractAttr(q.attrs, \"pg\");\n if (pg_str.isEmpty()) {\n jq_page_col.addNull(r, 0);\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\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.num_ad_impressions\", &jq_numadimprs_col);\n writer.addColumn(\"queries.num_ad_clicks\", &jq_numadclicks_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 \/\/ auto lcol = aq.fetchColumn(\"queries.language\");\n \/\/ auto ccol = aq.fetchColumn(\"queries.num_ad_clicks\");\n\n \/\/ aq.onQuery([&] () {\n \/\/ auto l = languageToString((Language) lcol->getUInt32());\n \/\/ auto c = ccol->getUInt32();\n \/\/ fnord::iputs(\"lang: $0 -> $1\", l, c);\n \/\/ });\n\n \/\/ aq.scanTable(&reader);\n \/\/ \/\/cm::CTRByGroupResult res;\n \/\/ \/\/cm::CTRByPositionQuery q(&aq, &res);\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\nfixes\/**\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_numadimprs_col(1, 1, 250);\n cstable::BitPackedIntColumnWriter jq_numadclicks_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.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 \/* queries.num_item_clicks, queries.num_items *\/\n size_t nitems = 0;\n size_t nclicks = 0;\n size_t nads = 0;\n size_t nadclicks = 0;\n for (const auto& i : q.items) {\n \/\/ DAWANDA HACK\n if (i.position >= 1 && i.position <= 4) {\n ++nads;\n nadclicks += i.clicked;\n }\n \/\/ EOF DAWANDA HACK\n\n ++nitems;\n nclicks += i.clicked;\n }\n\n if (nadclicks > 0 && lang != Language::DE) {\n abort();\n }\n\n jq_numitems_col.addDatum(r, 1, nitems);\n jq_numitemclicks_col.addDatum(r, 1, nclicks);\n jq_numadimprs_col.addDatum(r, 1, nads);\n jq_numadclicks_col.addDatum(r, 1, nadclicks);\n\n \/* queries.page *\/\n auto pg_str = cm::extractAttr(q.attrs, \"pg\");\n if (pg_str.isEmpty()) {\n jq_page_col.addNull(r, 0);\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, 0);\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, 0);\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, 0);\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, 0);\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\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.num_ad_impressions\", &jq_numadimprs_col);\n writer.addColumn(\"queries.num_ad_clicks\", &jq_numadclicks_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 \/\/ auto lcol = aq.fetchColumn(\"queries.language\");\n \/\/ auto ccol = aq.fetchColumn(\"queries.num_ad_clicks\");\n\n \/\/ aq.onQuery([&] () {\n \/\/ auto l = languageToString((Language) lcol->getUInt32());\n \/\/ auto c = ccol->getUInt32();\n \/\/ fnord::iputs(\"lang: $0 -> $1\", l, c);\n \/\/ });\n\n \/\/ aq.scanTable(&reader);\n \/\/ \/\/cm::CTRByGroupResult res;\n \/\/ \/\/cm::CTRByPositionQuery q(&aq, &res);\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":"\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\n#include \"PlayConfigTab.hpp\"\n#include \"MainWindow.hpp\"\n\/\/#include \"debug.hpp\"\n#include \"Configuration.hpp\"\n\nusing namespace std;\n\n\/\/\/\/BEGIN memory debugging\n\/\/static void *(*old_malloc_hook)(size_t, const void *) = 0;\n\/\/static void *(*old_realloc_hook)(void *, size_t, const void *) = 0;\n\/\/static void (*old_free_hook)(void *, const void *) = 0;\n\/\/\n\/\/static void *md_malloc(size_t size, const void *caller);\n\/\/static void *md_realloc(void *ptr, size_t size, const void *caller);\n\/\/static void md_free(void *ptr, const void *caller);\n\/\/\n\/\/pthread_mutex_t md_mutex = PTHREAD_MUTEX_INITIALIZER;\n\/\/\n\/\/volatile bool barrier = false;\n\/\/\n\/\/static void *md_malloc(size_t size, const void *caller)\n\/\/{\n\/\/\tpthread_mutex_lock(&md_mutex);\n\/\/\t__malloc_hook = old_malloc_hook;\n\/\/\t__realloc_hook = old_realloc_hook;\n\/\/\t__free_hook = old_free_hook;\n\/\/\tassert(!barrier);\n\/\/\tbarrier = true;\n\/\/\tvoid *result = malloc(size);\n\/\/\told_malloc_hook = __malloc_hook;\n\/\/\t__malloc_hook = md_malloc;\n\/\/\t__realloc_hook = md_realloc;\n\/\/\t__free_hook = md_free;\n\/\/\tbarrier = false;\n\/\/\tpthread_mutex_unlock(&md_mutex);\n\/\/\treturn result;\n\/\/}\n\/\/\n\/\/static void *md_realloc(void *ptr, size_t size, const void *caller)\n\/\/{\n\/\/\tpthread_mutex_lock(&md_mutex);\n\/\/\t__malloc_hook = old_malloc_hook;\n\/\/\t__realloc_hook = old_realloc_hook;\n\/\/\t__free_hook = old_free_hook;\n\/\/\tassert(!barrier);\n\/\/\tbarrier = true;\n\/\/\tassert(size < 1048576 * 100);\n\/\/\tvoid *result = realloc(ptr, size);\n\/\/\t__malloc_hook = md_malloc;a\n\/\/\t__realloc_hook = md_realloc;\n\/\/\t__free_hook = md_free;\n\/\/\tbarrier = false;\n\/\/\tpthread_mutex_unlock(&md_mutex);\n\/\/\treturn result;\n\/\/}\n\/\/\n\/\/static void md_free(void *ptr, const void *caller)\n\/\/{\n\/\/\tpthread_mutex_lock(&md_mutex);\n\/\/\t__malloc_hook = old_malloc_hook;\n\/\/\t__realloc_hook = old_realloc_hook;\n\/\/\t__free_hook = old_free_hook;\n\/\/\tassert(!barrier);\n\/\/\tbarrier = true;\n\/\/\tif (!ptr)\n\/\/\t{\n\/\/\/\/ \t\tprintf(\"Free zero from %p\\n\", caller);\n\/\/\t} else {\n\/\/\t\tfree(ptr);\n\/\/\t}\n\/\/\t__malloc_hook = md_malloc;\n\/\/\t__realloc_hook = md_realloc;\n\/\/\t__free_hook = md_free;\n\/\/\tbarrier = false;\n\/\/\tpthread_mutex_unlock(&md_mutex);\n\/\/}\n\/\/\n\/\/static void md_init_hook()\n\/\/{\n\/\/\told_malloc_hook = __malloc_hook;\n\/\/\told_realloc_hook = __realloc_hook;\n\/\/\told_free_hook = __free_hook;\n\/\/\t__malloc_hook = md_malloc;\n\/\/\t__realloc_hook = md_realloc;\n\/\/\t__free_hook = md_free;\n\/\/\tfprintf(stderr, \"Memory debugging initialized: %p %p %p\\n\", old_malloc_hook, old_realloc_hook, old_free_hook);\n\/\/}\n\/\/\n\/\/void (*__malloc_initialize_hook)(void) = md_init_hook;\n\/\/\/\/END memory debugging\n\nvoid usage(const char* prog)\n{\n\tfprintf(stderr, \"usage: %s [options...]\\n\", prog);\n\tfprintf(stderr, \"\\t-y: run as the yellow team\\n\");\n\tfprintf(stderr, \"\\t-b: run as the blue team\\n\");\n\tfprintf(stderr, \"\\t-c : specify the configuration file\\n\");\n\tfprintf(stderr, \"\\t-s : set random seed (hexadecimal)\\n\");\n\tfprintf(stderr, \"\\t-p : load playbook\\n\");\n\tfprintf(stderr, \"\\t-pp : enable named play\\n\");\n\tfprintf(stderr, \"\\t-ng: no goalie\\n\");\n\tfprintf(stderr, \"\\t-sim: use simulator\\n\");\n\tfprintf(stderr, \"\\t-freq: specify radio frequency (906 or 904)\\n\");\n\tfprintf(stderr, \"\\t-nolog: don't write log files\\n\");\n\texit(1);\n}\n\nint main (int argc, char* argv[])\n{\n\tprintf(\"Starting Soccer...\\n\");\n\n\/\/\tdebugInit(argv[0]); \/\/ FIXME: re-enable debugging\n\n\t\/\/ Seed the large random number generator\n\tlong int seed = 0;\n\tint fd = open(\"\/dev\/random\", O_RDONLY);\n\tif (fd >= 0)\n\t{\n\t\tif (read(fd, &seed, sizeof(seed)) != sizeof(seed))\n\t\t{\n\t\t\tfprintf(stderr, \"Can't read \/dev\/random, using zero seed: %m\\n\");\n\t\t}\n\t\tclose(fd);\n\t} else {\n\t\tfprintf(stderr, \"Can't open \/dev\/random, using zero seed: %m\\n\");\n\t}\n\n\n\tQApplication app(argc, argv);\n\n\tbool blueTeam = false;\n\tQString cfgFile;\n\tQString playbook;\n\tvector playDirs;\n\tvector extraPlays;\n\tbool goalie = true;\n\tbool sim = false;\n\tbool log = true;\n QString radioFreq;\n\t\n\tfor (int i=1 ; i= argc)\n {\n printf(\"No radio frequency specified after -freq\");\n usage(argv[0]);\n }\n\n i++;\n radioFreq = argv[i];\n }\n\t\telse if(strcmp(var, \"-c\") == 0)\n\t\t{\n\t\t\tif (i+1 >= argc)\n\t\t\t{\n\t\t\t\tprintf(\"no config file specified after -c\");\n\t\t\t\tusage(argv[0]);\n\t\t\t}\n\t\t\t\n\t\t\ti++;\n\t\t\tcfgFile = argv[i];\n\t\t}\n\t\telse if(strcmp(var, \"-s\") == 0)\n\t\t{\n\t\t\tif (i+1 >= argc)\n\t\t\t{\n\t\t\t\tprintf(\"no seed specified after -s\");\n\t\t\t\tusage(argv[0]);\n\t\t\t}\n\t\t\t\n\t\t\ti++;\n\t\t\tseed = strtol(argv[i], 0, 16);\n\t\t}\n\t\telse if(strcmp(var, \"-pp\") == 0)\n\t\t{\n\t\t\tif (i+1 >= argc)\n\t\t\t{\n\t\t\t\tprintf(\"no play specified after -pp\");\n\t\t\t\tusage(argv[0]);\n\t\t\t}\n\t\t\t\n\t\t\ti++;\n\t\t\textraPlays.push_back(argv[i]);\n\t\t}\n\t\telse if(strcmp(var, \"-p\") == 0)\n\t\t{\n\t\t\tif (i+1 >= argc)\n\t\t\t{\n\t\t\t\tprintf(\"no playbook file specified after -p\");\n\t\t\t\tusage(argv[0]);\n\t\t\t}\n\t\t\t\n\t\t\ti++;\n\t\t\tplaybook = argv[i];\n }\n\t\telse\n\t\t{\n\t\t\tprintf(\"Not a valid flag: %s\\n\", argv[i]);\n\t\t\tusage(argv[0]);\n\t\t}\n\t}\n\t\n\n\n\tprintf(\"Running on %s\\n\", sim ? \"simulation\" : \"real hardware\");\n\t\n\tprintf(\"seed %016lx\\n\", seed);\n\tsrand48(seed);\n\t\n\t\/\/ Default config file name\n\tif (cfgFile.isNull())\n\t{\n\t\tcfgFile = sim ? \"soccer-sim.cfg\" : \"soccer-real.cfg\";\n\t}\n\t\n\tConfiguration config;\n\n\tProcessor *processor = new Processor(sim);\n\tprocessor->blueTeam(blueTeam);\n\n\tBOOST_FOREACH(Configurable *obj, Configurable::configurables())\n\t{\n\t\tobj->createConfiguration(&config);\n\t}\n\t\n\t\/\/ Load config file\n\tQString error;\n\tif (!config.load(cfgFile, error))\n\t{\n\t\tQMessageBox::critical(0, \"Soccer\",\n\t\t\tQString(\"Can't read initial configuration %1:\\n%2\").arg(cfgFile, error));\n\t}\n\n\tMainWindow *win = new MainWindow;\n\twin->configuration(&config);\n\twin->processor(processor);\n\t\n\tif (!playbook.isNull())\n\t{\n\t\twin->playConfigTab()->load(playbook);\n\t} else if (extraPlays.empty())\n\t{\n\t\t\/\/ Try to load a default playbook\n\t\twin->playConfigTab()->load(\"default.pbk\");\n\t}\n\t\n\tBOOST_FOREACH(const QString &str, extraPlays)\n\t{\n\t\twin->playConfigTab()->enable(str);\n\t}\n\t\n\tif (!QDir(\"logs\").exists())\n\t{\n\t\tfprintf(stderr, \"No logs\/ directory - not writing log file\\n\");\n\t} else if (!log)\n\t{\n\t\tfprintf(stderr, \"Not writing log file\\n\");\n\t} else {\n\t\tQString logFile = QString(\"logs\/\") + QDateTime::currentDateTime().toString(\"yyyyMMdd-hhmmss.log\");\n\t\tif (!processor->openLog(logFile))\n\t\t{\n\t\t\tprintf(\"Failed to open %s: %m\\n\", (const char *)logFile.toAscii());\n\t\t}\n\t}\n\n if(!radioFreq.isEmpty())\n {\n if(radioFreq == \"904\")\n win->setRadioChannel(RadioChannels::MHz_904);\n else if(radioFreq == \"906\")\n win->setRadioChannel(RadioChannels::MHz_906);\n else\n printf(\"Cannot recognize radio frequency : %s\\n\", radioFreq.toStdString().c_str());\n }\n\n\twin->logFileChanged();\n\t\n\tprocessor->start();\n\t\n\twin->showMaximized();\n\n\tint ret = app.exec();\n\tprocessor->stop();\n\t\n\tdelete win;\n\tdelete processor;\n\t\n\treturn ret;\n}\nREVERTME - added some test stuff to main.cpp\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\n#include \"PlayConfigTab.hpp\"\n#include \"MainWindow.hpp\"\n\/\/#include \"debug.hpp\"\n#include \"Configuration.hpp\"\n\n\n#include \"python\/EmbeddedInstance.hpp\"\t\/\/\tTODO: remove\n\nusing namespace std;\n\n\/\/\/\/BEGIN memory debugging\n\/\/static void *(*old_malloc_hook)(size_t, const void *) = 0;\n\/\/static void *(*old_realloc_hook)(void *, size_t, const void *) = 0;\n\/\/static void (*old_free_hook)(void *, const void *) = 0;\n\/\/\n\/\/static void *md_malloc(size_t size, const void *caller);\n\/\/static void *md_realloc(void *ptr, size_t size, const void *caller);\n\/\/static void md_free(void *ptr, const void *caller);\n\/\/\n\/\/pthread_mutex_t md_mutex = PTHREAD_MUTEX_INITIALIZER;\n\/\/\n\/\/volatile bool barrier = false;\n\/\/\n\/\/static void *md_malloc(size_t size, const void *caller)\n\/\/{\n\/\/\tpthread_mutex_lock(&md_mutex);\n\/\/\t__malloc_hook = old_malloc_hook;\n\/\/\t__realloc_hook = old_realloc_hook;\n\/\/\t__free_hook = old_free_hook;\n\/\/\tassert(!barrier);\n\/\/\tbarrier = true;\n\/\/\tvoid *result = malloc(size);\n\/\/\told_malloc_hook = __malloc_hook;\n\/\/\t__malloc_hook = md_malloc;\n\/\/\t__realloc_hook = md_realloc;\n\/\/\t__free_hook = md_free;\n\/\/\tbarrier = false;\n\/\/\tpthread_mutex_unlock(&md_mutex);\n\/\/\treturn result;\n\/\/}\n\/\/\n\/\/static void *md_realloc(void *ptr, size_t size, const void *caller)\n\/\/{\n\/\/\tpthread_mutex_lock(&md_mutex);\n\/\/\t__malloc_hook = old_malloc_hook;\n\/\/\t__realloc_hook = old_realloc_hook;\n\/\/\t__free_hook = old_free_hook;\n\/\/\tassert(!barrier);\n\/\/\tbarrier = true;\n\/\/\tassert(size < 1048576 * 100);\n\/\/\tvoid *result = realloc(ptr, size);\n\/\/\t__malloc_hook = md_malloc;a\n\/\/\t__realloc_hook = md_realloc;\n\/\/\t__free_hook = md_free;\n\/\/\tbarrier = false;\n\/\/\tpthread_mutex_unlock(&md_mutex);\n\/\/\treturn result;\n\/\/}\n\/\/\n\/\/static void md_free(void *ptr, const void *caller)\n\/\/{\n\/\/\tpthread_mutex_lock(&md_mutex);\n\/\/\t__malloc_hook = old_malloc_hook;\n\/\/\t__realloc_hook = old_realloc_hook;\n\/\/\t__free_hook = old_free_hook;\n\/\/\tassert(!barrier);\n\/\/\tbarrier = true;\n\/\/\tif (!ptr)\n\/\/\t{\n\/\/\/\/ \t\tprintf(\"Free zero from %p\\n\", caller);\n\/\/\t} else {\n\/\/\t\tfree(ptr);\n\/\/\t}\n\/\/\t__malloc_hook = md_malloc;\n\/\/\t__realloc_hook = md_realloc;\n\/\/\t__free_hook = md_free;\n\/\/\tbarrier = false;\n\/\/\tpthread_mutex_unlock(&md_mutex);\n\/\/}\n\/\/\n\/\/static void md_init_hook()\n\/\/{\n\/\/\told_malloc_hook = __malloc_hook;\n\/\/\told_realloc_hook = __realloc_hook;\n\/\/\told_free_hook = __free_hook;\n\/\/\t__malloc_hook = md_malloc;\n\/\/\t__realloc_hook = md_realloc;\n\/\/\t__free_hook = md_free;\n\/\/\tfprintf(stderr, \"Memory debugging initialized: %p %p %p\\n\", old_malloc_hook, old_realloc_hook, old_free_hook);\n\/\/}\n\/\/\n\/\/void (*__malloc_initialize_hook)(void) = md_init_hook;\n\/\/\/\/END memory debugging\n\nvoid usage(const char* prog)\n{\n\tfprintf(stderr, \"usage: %s [options...]\\n\", prog);\n\tfprintf(stderr, \"\\t-y: run as the yellow team\\n\");\n\tfprintf(stderr, \"\\t-b: run as the blue team\\n\");\n\tfprintf(stderr, \"\\t-c : specify the configuration file\\n\");\n\tfprintf(stderr, \"\\t-s : set random seed (hexadecimal)\\n\");\n\tfprintf(stderr, \"\\t-p : load playbook\\n\");\n\tfprintf(stderr, \"\\t-pp : enable named play\\n\");\n\tfprintf(stderr, \"\\t-ng: no goalie\\n\");\n\tfprintf(stderr, \"\\t-sim: use simulator\\n\");\n\tfprintf(stderr, \"\\t-freq: specify radio frequency (906 or 904)\\n\");\n\tfprintf(stderr, \"\\t-nolog: don't write log files\\n\");\n\texit(1);\n}\n\nint main (int argc, char* argv[])\n{\n\tprintf(\"Starting Soccer...\\n\");\n\n\/\/\tdebugInit(argv[0]); \/\/ FIXME: re-enable debugging\n\n\t\/\/ Seed the large random number generator\n\tlong int seed = 0;\n\tint fd = open(\"\/dev\/random\", O_RDONLY);\n\tif (fd >= 0)\n\t{\n\t\tif (read(fd, &seed, sizeof(seed)) != sizeof(seed))\n\t\t{\n\t\t\tfprintf(stderr, \"Can't read \/dev\/random, using zero seed: %m\\n\");\n\t\t}\n\t\tclose(fd);\n\t} else {\n\t\tfprintf(stderr, \"Can't open \/dev\/random, using zero seed: %m\\n\");\n\t}\n\n\n\tQApplication app(argc, argv);\n\n\tbool blueTeam = false;\n\tQString cfgFile;\n\tQString playbook;\n\tvector playDirs;\n\tvector extraPlays;\n\tbool goalie = true;\n\tbool sim = false;\n\tbool log = true;\n QString radioFreq;\n\t\n\tfor (int i=1 ; i= argc)\n {\n printf(\"No radio frequency specified after -freq\");\n usage(argv[0]);\n }\n\n i++;\n radioFreq = argv[i];\n }\n\t\telse if(strcmp(var, \"-c\") == 0)\n\t\t{\n\t\t\tif (i+1 >= argc)\n\t\t\t{\n\t\t\t\tprintf(\"no config file specified after -c\");\n\t\t\t\tusage(argv[0]);\n\t\t\t}\n\t\t\t\n\t\t\ti++;\n\t\t\tcfgFile = argv[i];\n\t\t}\n\t\telse if(strcmp(var, \"-s\") == 0)\n\t\t{\n\t\t\tif (i+1 >= argc)\n\t\t\t{\n\t\t\t\tprintf(\"no seed specified after -s\");\n\t\t\t\tusage(argv[0]);\n\t\t\t}\n\t\t\t\n\t\t\ti++;\n\t\t\tseed = strtol(argv[i], 0, 16);\n\t\t}\n\t\telse if(strcmp(var, \"-pp\") == 0)\n\t\t{\n\t\t\tif (i+1 >= argc)\n\t\t\t{\n\t\t\t\tprintf(\"no play specified after -pp\");\n\t\t\t\tusage(argv[0]);\n\t\t\t}\n\t\t\t\n\t\t\ti++;\n\t\t\textraPlays.push_back(argv[i]);\n\t\t}\n\t\telse if(strcmp(var, \"-p\") == 0)\n\t\t{\n\t\t\tif (i+1 >= argc)\n\t\t\t{\n\t\t\t\tprintf(\"no playbook file specified after -p\");\n\t\t\t\tusage(argv[0]);\n\t\t\t}\n\t\t\t\n\t\t\ti++;\n\t\t\tplaybook = argv[i];\n }\n\t\telse\n\t\t{\n\t\t\tprintf(\"Not a valid flag: %s\\n\", argv[i]);\n\t\t\tusage(argv[0]);\n\t\t}\n\t}\n\t\n\n\n\tprintf(\"Running on %s\\n\", sim ? \"simulation\" : \"real hardware\");\n\t\n\tprintf(\"seed %016lx\\n\", seed);\n\tsrand48(seed);\n\t\n\t\/\/ Default config file name\n\tif (cfgFile.isNull())\n\t{\n\t\tcfgFile = sim ? \"soccer-sim.cfg\" : \"soccer-real.cfg\";\n\t}\n\t\n\tConfiguration config;\n\n\tProcessor *processor = new Processor(sim);\n\tprocessor->blueTeam(blueTeam);\n\n\tBOOST_FOREACH(Configurable *obj, Configurable::configurables())\n\t{\n\t\tobj->createConfiguration(&config);\n\t}\n\t\n\t\/\/ Load config file\n\tQString error;\n\tif (!config.load(cfgFile, error))\n\t{\n\t\tQMessageBox::critical(0, \"Soccer\",\n\t\t\tQString(\"Can't read initial configuration %1:\\n%2\").arg(cfgFile, error));\n\t}\n\n\tMainWindow *win = new MainWindow;\n\twin->configuration(&config);\n\twin->processor(processor);\n\t\n\tif (!playbook.isNull())\n\t{\n\t\twin->playConfigTab()->load(playbook);\n\t} else if (extraPlays.empty())\n\t{\n\t\t\/\/ Try to load a default playbook\n\t\twin->playConfigTab()->load(\"default.pbk\");\n\t}\n\t\n\tBOOST_FOREACH(const QString &str, extraPlays)\n\t{\n\t\twin->playConfigTab()->enable(str);\n\t}\n\t\n\tif (!QDir(\"logs\").exists())\n\t{\n\t\tfprintf(stderr, \"No logs\/ directory - not writing log file\\n\");\n\t} else if (!log)\n\t{\n\t\tfprintf(stderr, \"Not writing log file\\n\");\n\t} else {\n\t\tQString logFile = QString(\"logs\/\") + QDateTime::currentDateTime().toString(\"yyyyMMdd-hhmmss.log\");\n\t\tif (!processor->openLog(logFile))\n\t\t{\n\t\t\tprintf(\"Failed to open %s: %m\\n\", (const char *)logFile.toAscii());\n\t\t}\n\t}\n\n if(!radioFreq.isEmpty())\n {\n if(radioFreq == \"904\")\n win->setRadioChannel(RadioChannels::MHz_904);\n else if(radioFreq == \"906\")\n win->setRadioChannel(RadioChannels::MHz_906);\n else\n printf(\"Cannot recognize radio frequency : %s\\n\", radioFreq.toStdString().c_str());\n }\n\n\twin->logFileChanged();\n\t\n\tprocessor->start();\n\t\n\twin->showMaximized();\n\n\n\t\/\/\tTODO: remove\n\tEmbeddedInstance::initialize();\n\n\tint ret = app.exec();\n\tprocessor->stop();\n\t\n\tdelete win;\n\tdelete processor;\n\t\n\treturn ret;\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#include \n\nint main(int argc, char* argv[]) {\n const char* infile = nullptr;\n bool object = false;\n bool trace = false;\n for (int i = 1; i < argc; ++i) {\n if (argv[i][0] != '-') {\n infile = argv[i];\n } else {\n for (int j = 1; argv[i][j]; ++j) {\n if (argv[i][j] == 'o') object = true;\n if (argv[i][j] == 't') trace = true;\n }\n }\n }\n if (infile) {\n H(2) << \"nyi: qc file (work-around: redirect to stdin)\\n\" << flush;\n return EXIT_FAILURE;\n }\n\n KV module(init_module(S(0)));\n L infix_words{\"in\"_s};\n if (isatty(0)) H(1) << \" \" << flush;\n L line = getline();\n for (; trim(line) != \"\\\\\\\\\"; line = getline()) {\n try {\n O ast(parse(line, infix_words));\n O flattened_ast(compile(ast, trace));\n gen(module, flattened_ast, trace);\n L code(module[\"code\"_s]);\n if (object) H(1) << code;\n else H(1) << disassemble(code);\n H(1) << flush;\n } catch (const Exception& e) {\n H(2) << e.what() << '\\n' << flush;\n }\n if (isatty(0)) H(1) << \" \" << flush;\n }\n\n return EXIT_SUCCESS;\n}\nAdd newline to qc object output#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\nint main(int argc, char* argv[]) {\n const char* infile = nullptr;\n bool object = false;\n bool trace = false;\n for (int i = 1; i < argc; ++i) {\n if (argv[i][0] != '-') {\n infile = argv[i];\n } else {\n for (int j = 1; argv[i][j]; ++j) {\n if (argv[i][j] == 'o') object = true;\n if (argv[i][j] == 't') trace = true;\n }\n }\n }\n if (infile) {\n H(2) << \"nyi: qc file (work-around: redirect to stdin)\\n\" << flush;\n return EXIT_FAILURE;\n }\n\n KV module(init_module(S(0)));\n L infix_words{\"in\"_s};\n if (isatty(0)) H(1) << \" \" << flush;\n L line = getline();\n for (; trim(line) != \"\\\\\\\\\"; line = getline()) {\n try {\n O ast(parse(line, infix_words));\n O flattened_ast(compile(ast, trace));\n gen(module, flattened_ast, trace);\n L code(module[\"code\"_s]);\n if (object) H(1) << code << '\\n';\n else H(1) << disassemble(code);\n H(1) << flush;\n } catch (const Exception& e) {\n H(2) << e.what() << '\\n' << flush;\n }\n if (isatty(0)) H(1) << \" \" << flush;\n }\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n * This file is part of the libqgit2 library\n * Copyright (c) 2011 Laszlo Papp \n * Copyright (C) 2013 Leonardo Giordani\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 \"qgitoid.h\"\n#include \"qgitexception.h\"\n\nnamespace LibQGit2\n{\n\nOId::OId(const git_oid* oid)\n : d(GIT_OID_RAWSZ, 0)\n{\n if (oid != 0) {\n git_oid_cpy(data(), oid);\n }\n}\n\nOId::OId(const OId& other)\n : d(other.d)\n{\n}\n\nOId::~OId()\n{\n}\n\nbool OId::isValid() const\n{\n return ( !d.isEmpty() &&\n (d.length() <= GIT_OID_RAWSZ) &&\n (d != QByteArray(GIT_OID_RAWSZ, 0))\n );\n}\n\nOId OId::fromString(const QByteArray& string)\n{\n int len = qMin(string.length(), GIT_OID_HEXSZ);\n OId oid;\n qGitThrow(git_oid_fromstrn(oid.data(), string.constData(), len));\n oid.d.resize(len \/ 2);\n return oid;\n}\n\nOId OId::fromRawData(const QByteArray& raw)\n{\n OId oid;\n oid.d = raw;\n return oid;\n}\n\nQByteArray OId::format() const\n{\n QByteArray ba(GIT_OID_HEXSZ, Qt::Uninitialized);\n git_oid_fmt(ba.data(), constData());\n return ba;\n}\n\nQByteArray OId::pathFormat() const\n{\n QByteArray ba(GIT_OID_HEXSZ+1, Qt::Uninitialized);\n git_oid_pathfmt(ba.data(), constData());\n return ba;\n}\n\ngit_oid* OId::data()\n{\n return reinterpret_cast(d.data());\n}\n\nconst git_oid* OId::constData() const\n{\n return reinterpret_cast(d.constData());\n}\n\nbool operator ==(const OId &oid1, const OId &oid2)\n{\n return git_oid_cmp(oid1.constData(), oid2.constData()) == 0;\n}\n\nbool operator !=(const OId &oid1, const OId &oid2)\n{\n return !(operator ==(oid1, oid2));\n}\n\nint OId::length() const\n{\n return d.length() * 2;\n}\n\n} \/\/ LibQGit2\nReview of conversion functions\/******************************************************************************\n * This file is part of the libqgit2 library\n * Copyright (c) 2011 Laszlo Papp \n * Copyright (C) 2013 Leonardo Giordani\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 \"qgitoid.h\"\n#include \"qgitexception.h\"\n\nnamespace LibQGit2\n{\n\nOId::OId(const git_oid* oid)\n : d(GIT_OID_RAWSZ, 0)\n{\n if (oid != 0) {\n git_oid_cpy(data(), oid);\n }\n}\n\nOId::OId(const OId& other)\n : d(other.d)\n{\n}\n\nOId::~OId()\n{\n}\n\nbool OId::isValid() const\n{\n return ( !d.isEmpty() &&\n (d.length() <= GIT_OID_RAWSZ) &&\n (d != QByteArray(GIT_OID_RAWSZ, 0))\n );\n}\n\nvoid OId::fromHex(const QByteArray& hex)\n{\n int len = qMin(hex.length(), GIT_OID_HEXSZ);\n qGitThrow(git_oid_fromstrn(data(), hex.constData(), len));\n d.resize(len \/ 2);\n}\n\nvoid OId::fromString(const QString& string)\n{\n fromHex(string.toUtf8());\n}\n\n\nvoid OId::fromRawData(const QByteArray& raw)\n{\n qGitThrow(raw.length() < GIT_OID_HEXSZ);\n d = raw;\n}\n\nOId OId::stringToOid(const QByteArray& string)\n{\n int len = qMin(string.length(), GIT_OID_HEXSZ);\n OId oid;\n qGitThrow(git_oid_fromstrn(oid.data(), string.constData(), len));\n oid.d.resize(len \/ 2);\n return oid;\n}\n\nOId OId::rawDataToOid(const QByteArray& raw)\n{\n OId oid;\n oid.d = raw;\n return oid;\n}\n\nQByteArray OId::format() const\n{\n QByteArray ba(GIT_OID_HEXSZ, Qt::Uninitialized);\n git_oid_fmt(ba.data(), constData());\n return ba;\n}\n\nQByteArray OId::pathFormat() const\n{\n QByteArray ba(GIT_OID_HEXSZ+1, Qt::Uninitialized);\n git_oid_pathfmt(ba.data(), constData());\n return ba;\n}\n\ngit_oid* OId::data()\n{\n return reinterpret_cast(d.data());\n}\n\nconst git_oid* OId::constData() const\n{\n return reinterpret_cast(d.constData());\n}\n\nbool operator ==(const OId &oid1, const OId &oid2)\n{\n return git_oid_cmp(oid1.constData(), oid2.constData()) == 0;\n}\n\nbool operator !=(const OId &oid1, const OId &oid2)\n{\n return !(operator ==(oid1, oid2));\n}\n\nint OId::length() const\n{\n return d.length() * 2;\n}\n\n} \/\/ LibQGit2\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: idlccompile.cxx,v $\n *\n * $Revision: 1.23 $\n *\n * last change: $Author: ihi $ $Date: 2008-02-04 13:44:58 $\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_idlc.hxx\"\n#ifndef _IDLC_IDLC_HXX_\n#include \n#endif\n#ifndef _RTL_USTRING_HXX_\n#include \n#endif\n#ifndef _RTL_STRBUF_HXX_\n#include \n#endif\n\n#ifndef _OSL_PROCESS_H_\n#include \n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include \n#endif\n#ifndef _OSL_THREAD_H_\n#include \n#endif\n#ifndef _OSL_FILE_HXX_\n#include \n#endif\n\n#if defined(SAL_W32) || defined(SAL_OS2)\n#include \n#endif\n\n#ifdef SAL_UNX\n#include \n#if defined(MACOSX) || defined(FREEBSD) || defined(NETBSD)\n#include \n#else\n#include \n#endif\n#endif\n\n#include \n\nusing namespace ::rtl;\nusing namespace ::osl;\n\nextern int yyparse();\nextern FILE* yyin;\nextern int yydebug;\n\nsal_Int32 lineNumber = 1;\n\n\nstatic OUString TMP(RTL_CONSTASCII_USTRINGPARAM(\"TMP\"));\nstatic OUString TEMP(RTL_CONSTASCII_USTRINGPARAM(\"TEMP\"));\nstatic sal_Char tmpFilePattern[512];\n\nsal_Bool isFileUrl(const OString& fileName)\n{\n if (fileName.indexOf(\"file:\/\/\") == 0 )\n return sal_True;\n return sal_False;\n}\n\nOString convertToAbsoluteSystemPath(const OString& fileName)\n{\n OUString uSysFileName;\n OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());\n if ( isFileUrl(fileName) )\n {\n if (FileBase::getSystemPathFromFileURL(uFileName, uSysFileName)\n != FileBase::E_None)\n {\n OSL_ASSERT(false);\n }\n } else\n {\n OUString uWorkingDir, uUrlFileName, uTmp;\n if (osl_getProcessWorkingDir(&uWorkingDir.pData) != osl_Process_E_None)\n {\n OSL_ASSERT(false);\n }\n if (FileBase::getFileURLFromSystemPath(uFileName, uTmp)\n != FileBase::E_None)\n {\n OSL_ASSERT(false);\n }\n if (FileBase::getAbsoluteFileURL(uWorkingDir, uTmp, uUrlFileName)\n != FileBase::E_None)\n {\n OSL_ASSERT(false);\n }\n if (FileBase::getSystemPathFromFileURL(uUrlFileName, uSysFileName)\n != FileBase::E_None)\n {\n OSL_ASSERT(false);\n }\n }\n\n return OUStringToOString(uSysFileName, osl_getThreadTextEncoding());\n}\n\nOString convertToFileUrl(const OString& fileName)\n{\n if ( !isFileUrl(fileName) )\n {\n OString tmp = convertToAbsoluteSystemPath(fileName);\n OUString uFileName(tmp.getStr(), tmp.getLength(), osl_getThreadTextEncoding());\n OUString uUrlFileName;\n if (FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName)\n != FileBase::E_None)\n {\n OSL_ASSERT(false);\n }\n return OUStringToOString(uUrlFileName, osl_getThreadTextEncoding());\n }\n\n return fileName;\n}\n\nOString makeTempName(const OString& prefix)\n{\n OUString uTmpPath;\n OString tmpPath;\n\n if ( osl_getEnvironment(TMP.pData, &uTmpPath.pData) != osl_Process_E_None )\n {\n if ( osl_getEnvironment(TEMP.pData, &uTmpPath.pData) != osl_Process_E_None )\n {\n#if defined(SAL_W32)\n tmpPath = OString(\"c:\\\\temp\");\n#else\n tmpPath = OString(\"\/tmp\");\n#endif\n }\n }\n\n if ( uTmpPath.getLength() )\n tmpPath = OUStringToOString(uTmpPath, RTL_TEXTENCODING_UTF8);\n\n#if defined(SAL_W32) || defined(SAL_UNX) || defined(SAL_OS2)\n\n OSL_ASSERT( sizeof(tmpFilePattern) > ( strlen(tmpPath)\n + RTL_CONSTASCII_LENGTH(\n PATH_SEPARATOR )\n + prefix.getLength()\n + RTL_CONSTASCII_LENGTH(\n \"XXXXXX\") ) );\n\n tmpFilePattern[ sizeof(tmpFilePattern)-1 ] = '\\0';\n strncpy(tmpFilePattern, tmpPath, sizeof(tmpFilePattern)-1);\n strncat(tmpFilePattern, PATH_SEPARATOR, sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));\n strncat(tmpFilePattern, prefix.getStr(), sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));\n strncat(tmpFilePattern, \"XXXXXX\", sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));\n\n#ifdef SAL_UNX\n int nDescriptor = mkstemp(tmpFilePattern);\n if( -1 == nDescriptor )\n {\n fprintf( stderr,\"idlc: couldn't create temporary file\\n\" );\n exit( 1 );\n }\n \/\/ the file shall later be reopened by stdio functions\n close( nDescriptor );\n#else\n (void) mktemp(tmpFilePattern);\n#endif\n#endif\n\n return OString(tmpFilePattern);\n}\n\nsal_Bool copyFile(const OString* source, const OString& target)\n{\n sal_Bool bRet = sal_True;\n\n FILE* pSource = source == 0 ? stdin : fopen(source->getStr(), \"rb\");\n\n if ( !pSource )\n return sal_False;\n\n FILE* pTarget = fopen(target.getStr(), \"wb\");\n\n if ( !pTarget )\n {\n fclose(pSource);\n return sal_False;\n }\n\n size_t totalSize = 512;\n size_t readSize = 0;\n size_t writeSize = 0;\n char pBuffer[513];\n\n while ( !feof(pSource) )\n {\n if ( (readSize = fread(pBuffer, 1, totalSize, pSource)) > 0 && !ferror(pSource) )\n {\n if ( (writeSize = fwrite(pBuffer, 1, readSize, pTarget)) != readSize || ferror(pTarget) )\n {\n if (source != 0) {\n fclose(pSource);\n }\n fclose(pTarget);\n return sal_False;\n }\n }\n }\n\n if (source != 0) {\n fclose(pSource);\n }\n if ( fflush(pTarget) )\n bRet = sal_False;\n fclose(pTarget);\n\n return bRet;\n}\n\nsal_Int32 compileFile(const OString * pathname)\n{\n \/\/ preprocess input file\n OString tmpFile = makeTempName(OString(\"idli_\"));\n OString preprocFile = makeTempName(OString(\"idlf_\"));\n\n OString fileName;\n if (pathname == 0) {\n fileName = \"stdin\";\n } else {\n fileName = *pathname;\n }\n\n if ( !copyFile(pathname, tmpFile) )\n {\n fprintf(stderr, \"%s: could not copy %s%s to %s\\n\",\n idlc()->getOptions()->getProgramName().getStr(),\n pathname == 0 ? \"\" : \"file \", fileName.getStr(),\n tmpFile.getStr());\n exit(99);\n }\n\n idlc()->setFileName(fileName);\n idlc()->setMainFileName(fileName);\n idlc()->setRealFileName(tmpFile);\n\n OStringBuffer cppArgs(512);\n cppArgs.append(\"-DIDL -Xi -Xc -+ -I.\");\n Options* pOptions = idlc()->getOptions();\n\n OString filePath;\n sal_Int32 index = fileName.lastIndexOf(SEPARATOR);\n\n if ( index > 0)\n {\n filePath = fileName.copy(0, index);\n\n if ( filePath.getLength() )\n {\n cppArgs.append(\" -I\\\"\");\n cppArgs.append(filePath);\n cppArgs.append(\"\\\"\");\n }\n }\n\n if ( pOptions->isValid(\"-D\") )\n {\n cppArgs.append(\" \");\n cppArgs.append(pOptions->getOption(\"-D\"));\n }\n if ( pOptions->isValid(\"-I\") )\n {\n cppArgs.append(\" \");\n cppArgs.append(pOptions->getOption(\"-I\"));\n }\n\n cppArgs.append(\" \\\"\");\n cppArgs.append(tmpFile);\n cppArgs.append(\"\\\" \\\"\");\n cppArgs.append(preprocFile);\n cppArgs.append(\"\\\"\");\n\n OString cmdFileName = makeTempName(OString(\"idlc_\"));\n FILE* pCmdFile = fopen(cmdFileName, \"w\");\n\n if ( !pCmdFile )\n {\n fprintf(stderr, \"%s: couldn't open temporary file for preprocessor commands: %s\\n\",\n idlc()->getOptions()->getProgramName().getStr(), cmdFileName.getStr());\n exit(99);\n }\n#ifdef SAL_OS2_00\n char* tok = strtok( (char*)cppArgs.getStr(), \" \\t\\n\\r\");\n while( tok) {\n if (tok[strlen(tok)-1] == '\\\"')\n tok[strlen(tok)-1] = '\\0';\n if (*tok == '\\\"')\n memcpy( tok, tok+1, strlen(tok));\n if (strlen(tok)>0) {\n fputs(tok, pCmdFile);\n fputc('\\n', pCmdFile);\n }\n tok = strtok( NULL, \" \\t\\n\\r\");\n }\n#else\n fprintf(pCmdFile, \"%s\", cppArgs.getStr());\n#endif\n fclose(pCmdFile);\n\n OUString cmdArg(RTL_CONSTASCII_USTRINGPARAM(\"@\"));\n cmdArg += OStringToOUString(cmdFileName, RTL_TEXTENCODING_UTF8);\n\n OUString cpp;\n OUString startDir;\n if (osl_getExecutableFile(&cpp.pData) != osl_Process_E_None) {\n OSL_ASSERT(false);\n }\n\n sal_Int32 idx= cpp.lastIndexOf(OUString( RTL_CONSTASCII_USTRINGPARAM(\"idlc\")) );\n cpp = cpp.copy(0, idx);\n\n#if defined(SAL_W32) || defined(SAL_OS2)\n cpp += OUString( RTL_CONSTASCII_USTRINGPARAM(\"idlcpp.exe\"));\n#else\n cpp += OUString( RTL_CONSTASCII_USTRINGPARAM(\"idlcpp\"));\n#endif\n\n oslProcess hProcess = NULL;\n oslProcessError procError = osl_Process_E_None;\n\n procError = osl_executeProcess(cpp.pData, &cmdArg.pData, 1, osl_Process_WAIT,\n 0, startDir.pData, 0, 0, &hProcess);\n\n oslProcessInfo hInfo;\n hInfo.Size = (sal_uInt32)(sizeof(oslProcessInfo));\n if (osl_getProcessInfo(hProcess, osl_Process_EXITCODE, &hInfo)\n != osl_Process_E_None)\n {\n OSL_ASSERT(false);\n }\n\n if ( procError || (hInfo.Code != 0) )\n {\n if ( procError != osl_Process_E_None )\n fprintf(stderr, \"%s: starting preprocessor failed\\n\", pOptions->getProgramName().getStr());\n else\n fprintf(stderr, \"%s: preprocessing %s%s failed\\n\",\n pOptions->getProgramName().getStr(),\n pathname == 0 ? \"\" : \"file \", fileName.getStr());\n\n unlink(tmpFile.getStr());\n unlink(preprocFile.getStr());\n unlink(cmdFileName.getStr());\n osl_freeProcessHandle(hProcess);\n exit(hInfo.Code ? hInfo.Code : 99);\n }\n osl_freeProcessHandle(hProcess);\n\n if (unlink(tmpFile.getStr()) != 0)\n {\n fprintf(stderr, \"%s: Could not remove cpp input file %s\\n\",\n pOptions->getProgramName().getStr(), tmpFile.getStr());\n exit(99);\n }\n\n if (unlink(cmdFileName.getStr()) != 0)\n {\n fprintf(stderr, \"%s: Could not remove unocpp command file %s\\n\",\n pOptions->getProgramName().getStr(), cmdFileName.getStr());\n\n exit(99);\n }\n\n if ( pOptions->isValid(\"-E\") )\n {\n if (unlink(preprocFile) != 0)\n {\n fprintf(stderr, \"%s: Could not remove parser input file %s\\n\",\n pOptions->getProgramName().getStr(), preprocFile.getStr());\n exit(99);\n }\n exit(0);\n }\n\n \/\/ parse file\n yyin = fopen(preprocFile.getStr(), \"r\");\n if (yyin == NULL)\n {\n fprintf(stderr, \"%s: Could not open cpp output file %s\\n\",\n pOptions->getProgramName().getStr(), preprocFile.getStr());\n exit(99);\n }\n\n \/\/yydebug = 0 no trace information\n \/\/yydebug = 1 parser produce trace information\n yydebug = 0;\n\n sal_Int32 nErrors = yyparse();\n nErrors = idlc()->getErrorCount();\n\n fclose(yyin);\n if (unlink(preprocFile.getStr()) != 0)\n {\n fprintf(stderr, \"%s: Could not remove parser input file %s\\n\",\n pOptions->getProgramName().getStr(), preprocFile.getStr());\n exit(99);\n }\n\n return nErrors;\n}\nINTEGRATION: CWS changefileheader (1.23.8); FILE MERGED 2008\/04\/01 15:20:34 thb 1.23.8.3: #i85898# Stripping all external header guards 2008\/04\/01 12:31:29 thb 1.23.8.2: #i85898# Stripping all external header guards 2008\/03\/31 07:23:51 rt 1.23.8.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: idlccompile.cxx,v $\n * $Revision: 1.24 $\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_idlc.hxx\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if defined(SAL_W32) || defined(SAL_OS2)\n#include \n#endif\n\n#ifdef SAL_UNX\n#include \n#if defined(MACOSX) || defined(FREEBSD) || defined(NETBSD)\n#include \n#else\n#include \n#endif\n#endif\n\n#include \n\nusing namespace ::rtl;\nusing namespace ::osl;\n\nextern int yyparse();\nextern FILE* yyin;\nextern int yydebug;\n\nsal_Int32 lineNumber = 1;\n\n\nstatic OUString TMP(RTL_CONSTASCII_USTRINGPARAM(\"TMP\"));\nstatic OUString TEMP(RTL_CONSTASCII_USTRINGPARAM(\"TEMP\"));\nstatic sal_Char tmpFilePattern[512];\n\nsal_Bool isFileUrl(const OString& fileName)\n{\n if (fileName.indexOf(\"file:\/\/\") == 0 )\n return sal_True;\n return sal_False;\n}\n\nOString convertToAbsoluteSystemPath(const OString& fileName)\n{\n OUString uSysFileName;\n OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());\n if ( isFileUrl(fileName) )\n {\n if (FileBase::getSystemPathFromFileURL(uFileName, uSysFileName)\n != FileBase::E_None)\n {\n OSL_ASSERT(false);\n }\n } else\n {\n OUString uWorkingDir, uUrlFileName, uTmp;\n if (osl_getProcessWorkingDir(&uWorkingDir.pData) != osl_Process_E_None)\n {\n OSL_ASSERT(false);\n }\n if (FileBase::getFileURLFromSystemPath(uFileName, uTmp)\n != FileBase::E_None)\n {\n OSL_ASSERT(false);\n }\n if (FileBase::getAbsoluteFileURL(uWorkingDir, uTmp, uUrlFileName)\n != FileBase::E_None)\n {\n OSL_ASSERT(false);\n }\n if (FileBase::getSystemPathFromFileURL(uUrlFileName, uSysFileName)\n != FileBase::E_None)\n {\n OSL_ASSERT(false);\n }\n }\n\n return OUStringToOString(uSysFileName, osl_getThreadTextEncoding());\n}\n\nOString convertToFileUrl(const OString& fileName)\n{\n if ( !isFileUrl(fileName) )\n {\n OString tmp = convertToAbsoluteSystemPath(fileName);\n OUString uFileName(tmp.getStr(), tmp.getLength(), osl_getThreadTextEncoding());\n OUString uUrlFileName;\n if (FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName)\n != FileBase::E_None)\n {\n OSL_ASSERT(false);\n }\n return OUStringToOString(uUrlFileName, osl_getThreadTextEncoding());\n }\n\n return fileName;\n}\n\nOString makeTempName(const OString& prefix)\n{\n OUString uTmpPath;\n OString tmpPath;\n\n if ( osl_getEnvironment(TMP.pData, &uTmpPath.pData) != osl_Process_E_None )\n {\n if ( osl_getEnvironment(TEMP.pData, &uTmpPath.pData) != osl_Process_E_None )\n {\n#if defined(SAL_W32)\n tmpPath = OString(\"c:\\\\temp\");\n#else\n tmpPath = OString(\"\/tmp\");\n#endif\n }\n }\n\n if ( uTmpPath.getLength() )\n tmpPath = OUStringToOString(uTmpPath, RTL_TEXTENCODING_UTF8);\n\n#if defined(SAL_W32) || defined(SAL_UNX) || defined(SAL_OS2)\n\n OSL_ASSERT( sizeof(tmpFilePattern) > ( strlen(tmpPath)\n + RTL_CONSTASCII_LENGTH(\n PATH_SEPARATOR )\n + prefix.getLength()\n + RTL_CONSTASCII_LENGTH(\n \"XXXXXX\") ) );\n\n tmpFilePattern[ sizeof(tmpFilePattern)-1 ] = '\\0';\n strncpy(tmpFilePattern, tmpPath, sizeof(tmpFilePattern)-1);\n strncat(tmpFilePattern, PATH_SEPARATOR, sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));\n strncat(tmpFilePattern, prefix.getStr(), sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));\n strncat(tmpFilePattern, \"XXXXXX\", sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));\n\n#ifdef SAL_UNX\n int nDescriptor = mkstemp(tmpFilePattern);\n if( -1 == nDescriptor )\n {\n fprintf( stderr,\"idlc: couldn't create temporary file\\n\" );\n exit( 1 );\n }\n \/\/ the file shall later be reopened by stdio functions\n close( nDescriptor );\n#else\n (void) mktemp(tmpFilePattern);\n#endif\n#endif\n\n return OString(tmpFilePattern);\n}\n\nsal_Bool copyFile(const OString* source, const OString& target)\n{\n sal_Bool bRet = sal_True;\n\n FILE* pSource = source == 0 ? stdin : fopen(source->getStr(), \"rb\");\n\n if ( !pSource )\n return sal_False;\n\n FILE* pTarget = fopen(target.getStr(), \"wb\");\n\n if ( !pTarget )\n {\n fclose(pSource);\n return sal_False;\n }\n\n size_t totalSize = 512;\n size_t readSize = 0;\n size_t writeSize = 0;\n char pBuffer[513];\n\n while ( !feof(pSource) )\n {\n if ( (readSize = fread(pBuffer, 1, totalSize, pSource)) > 0 && !ferror(pSource) )\n {\n if ( (writeSize = fwrite(pBuffer, 1, readSize, pTarget)) != readSize || ferror(pTarget) )\n {\n if (source != 0) {\n fclose(pSource);\n }\n fclose(pTarget);\n return sal_False;\n }\n }\n }\n\n if (source != 0) {\n fclose(pSource);\n }\n if ( fflush(pTarget) )\n bRet = sal_False;\n fclose(pTarget);\n\n return bRet;\n}\n\nsal_Int32 compileFile(const OString * pathname)\n{\n \/\/ preprocess input file\n OString tmpFile = makeTempName(OString(\"idli_\"));\n OString preprocFile = makeTempName(OString(\"idlf_\"));\n\n OString fileName;\n if (pathname == 0) {\n fileName = \"stdin\";\n } else {\n fileName = *pathname;\n }\n\n if ( !copyFile(pathname, tmpFile) )\n {\n fprintf(stderr, \"%s: could not copy %s%s to %s\\n\",\n idlc()->getOptions()->getProgramName().getStr(),\n pathname == 0 ? \"\" : \"file \", fileName.getStr(),\n tmpFile.getStr());\n exit(99);\n }\n\n idlc()->setFileName(fileName);\n idlc()->setMainFileName(fileName);\n idlc()->setRealFileName(tmpFile);\n\n OStringBuffer cppArgs(512);\n cppArgs.append(\"-DIDL -Xi -Xc -+ -I.\");\n Options* pOptions = idlc()->getOptions();\n\n OString filePath;\n sal_Int32 index = fileName.lastIndexOf(SEPARATOR);\n\n if ( index > 0)\n {\n filePath = fileName.copy(0, index);\n\n if ( filePath.getLength() )\n {\n cppArgs.append(\" -I\\\"\");\n cppArgs.append(filePath);\n cppArgs.append(\"\\\"\");\n }\n }\n\n if ( pOptions->isValid(\"-D\") )\n {\n cppArgs.append(\" \");\n cppArgs.append(pOptions->getOption(\"-D\"));\n }\n if ( pOptions->isValid(\"-I\") )\n {\n cppArgs.append(\" \");\n cppArgs.append(pOptions->getOption(\"-I\"));\n }\n\n cppArgs.append(\" \\\"\");\n cppArgs.append(tmpFile);\n cppArgs.append(\"\\\" \\\"\");\n cppArgs.append(preprocFile);\n cppArgs.append(\"\\\"\");\n\n OString cmdFileName = makeTempName(OString(\"idlc_\"));\n FILE* pCmdFile = fopen(cmdFileName, \"w\");\n\n if ( !pCmdFile )\n {\n fprintf(stderr, \"%s: couldn't open temporary file for preprocessor commands: %s\\n\",\n idlc()->getOptions()->getProgramName().getStr(), cmdFileName.getStr());\n exit(99);\n }\n#ifdef SAL_OS2_00\n char* tok = strtok( (char*)cppArgs.getStr(), \" \\t\\n\\r\");\n while( tok) {\n if (tok[strlen(tok)-1] == '\\\"')\n tok[strlen(tok)-1] = '\\0';\n if (*tok == '\\\"')\n memcpy( tok, tok+1, strlen(tok));\n if (strlen(tok)>0) {\n fputs(tok, pCmdFile);\n fputc('\\n', pCmdFile);\n }\n tok = strtok( NULL, \" \\t\\n\\r\");\n }\n#else\n fprintf(pCmdFile, \"%s\", cppArgs.getStr());\n#endif\n fclose(pCmdFile);\n\n OUString cmdArg(RTL_CONSTASCII_USTRINGPARAM(\"@\"));\n cmdArg += OStringToOUString(cmdFileName, RTL_TEXTENCODING_UTF8);\n\n OUString cpp;\n OUString startDir;\n if (osl_getExecutableFile(&cpp.pData) != osl_Process_E_None) {\n OSL_ASSERT(false);\n }\n\n sal_Int32 idx= cpp.lastIndexOf(OUString( RTL_CONSTASCII_USTRINGPARAM(\"idlc\")) );\n cpp = cpp.copy(0, idx);\n\n#if defined(SAL_W32) || defined(SAL_OS2)\n cpp += OUString( RTL_CONSTASCII_USTRINGPARAM(\"idlcpp.exe\"));\n#else\n cpp += OUString( RTL_CONSTASCII_USTRINGPARAM(\"idlcpp\"));\n#endif\n\n oslProcess hProcess = NULL;\n oslProcessError procError = osl_Process_E_None;\n\n procError = osl_executeProcess(cpp.pData, &cmdArg.pData, 1, osl_Process_WAIT,\n 0, startDir.pData, 0, 0, &hProcess);\n\n oslProcessInfo hInfo;\n hInfo.Size = (sal_uInt32)(sizeof(oslProcessInfo));\n if (osl_getProcessInfo(hProcess, osl_Process_EXITCODE, &hInfo)\n != osl_Process_E_None)\n {\n OSL_ASSERT(false);\n }\n\n if ( procError || (hInfo.Code != 0) )\n {\n if ( procError != osl_Process_E_None )\n fprintf(stderr, \"%s: starting preprocessor failed\\n\", pOptions->getProgramName().getStr());\n else\n fprintf(stderr, \"%s: preprocessing %s%s failed\\n\",\n pOptions->getProgramName().getStr(),\n pathname == 0 ? \"\" : \"file \", fileName.getStr());\n\n unlink(tmpFile.getStr());\n unlink(preprocFile.getStr());\n unlink(cmdFileName.getStr());\n osl_freeProcessHandle(hProcess);\n exit(hInfo.Code ? hInfo.Code : 99);\n }\n osl_freeProcessHandle(hProcess);\n\n if (unlink(tmpFile.getStr()) != 0)\n {\n fprintf(stderr, \"%s: Could not remove cpp input file %s\\n\",\n pOptions->getProgramName().getStr(), tmpFile.getStr());\n exit(99);\n }\n\n if (unlink(cmdFileName.getStr()) != 0)\n {\n fprintf(stderr, \"%s: Could not remove unocpp command file %s\\n\",\n pOptions->getProgramName().getStr(), cmdFileName.getStr());\n\n exit(99);\n }\n\n if ( pOptions->isValid(\"-E\") )\n {\n if (unlink(preprocFile) != 0)\n {\n fprintf(stderr, \"%s: Could not remove parser input file %s\\n\",\n pOptions->getProgramName().getStr(), preprocFile.getStr());\n exit(99);\n }\n exit(0);\n }\n\n \/\/ parse file\n yyin = fopen(preprocFile.getStr(), \"r\");\n if (yyin == NULL)\n {\n fprintf(stderr, \"%s: Could not open cpp output file %s\\n\",\n pOptions->getProgramName().getStr(), preprocFile.getStr());\n exit(99);\n }\n\n \/\/yydebug = 0 no trace information\n \/\/yydebug = 1 parser produce trace information\n yydebug = 0;\n\n sal_Int32 nErrors = yyparse();\n nErrors = idlc()->getErrorCount();\n\n fclose(yyin);\n if (unlink(preprocFile.getStr()) != 0)\n {\n fprintf(stderr, \"%s: Could not remove parser input file %s\\n\",\n pOptions->getProgramName().getStr(), preprocFile.getStr());\n exit(99);\n }\n\n return nErrors;\n}\n<|endoftext|>"} {"text":"\n#include \"filesystem.h\"\n\n#include \n\n#include \n#include \n\nFileSystem::FileSystem(const std::string &partfname):partfilename(partfname){\n}\n\nFileSystem::~FileSystem(){\n}\n\nvoid FileSystem::debug(){\n\n std::cout << \"Debugging the filesystem class...\" << std::endl;\n this->init();\n\n}\n\nint FileSystem::init(){\n\n FILE* fd = fopen(partfilename.c_str(), \"wb+\");\n\n \/\/ step 1: writeout 1024 0xbb's\n unsigned char bootblock[1024];\n memset(bootblock, 0xbb, sizeof(bootblock));\n fwrite(bootblock, 1, sizeof(bootblock), fd);\n\n \/\/ step 2: writeout the fat \"header\"\n unsigned char fatheader[20] = {0xff, 0xfd,\n 0xff, 0xfe,\n 0xff, 0xfe,\n 0xff, 0xfe,\n 0xff, 0xfe,\n 0xff, 0xfe,\n 0xff, 0xfe,\n 0xff, 0xfe,\n 0xff, 0xfe,\n 0xff, 0xff};\n\n fwrite(fatheader, 1, sizeof(fatheader), fd);\n\n \/\/ step 3: writeout blank rest\n unsigned char blankrest[4193260];\n memset(blankrest, 0x00, sizeof(blankrest));\n fwrite(blankrest, 1, sizeof(blankrest), fd);\n\n fclose(fd);\n\n return RET_OK;\n\n}\n\nint FileSystem::load(){\n\n \/\/ mvtodo: load fat into ram \n\n return RET_OK;\n}\n\nint FileSystem::listdir(const std::string &path, std::vector &result){\n (void)path;\n (void)result;\n return -1;\n}\n\nint FileSystem::makedir(const std::string &path){\n (void)path;\n return -1;\n}\n\nint FileSystem::createfile(const std::string &path){\n (void)path;\n return -1;\n}\n\nint FileSystem::unlink(const std::string &path){\n (void)path;\n return -1;\n}\n\nint FileSystem::write(const std::string &path, const std::string &content){\n (void)path;\n (void)content;\n return -1;\n}\n\nint FileSystem::append(const std::string &path, const std::string &content){\n (void)path;\n (void)content;\n return -1;\n}\n\nint FileSystem::read(const std::string &path, std::string &content){\n (void)path;\n (void)content;\n return -1;\n}\n\nsecond operation: read fat into RAM\n#include \"filesystem.h\"\n\n#include \n\n#include \n#include \n\nFileSystem::FileSystem(const std::string &partfname):partfilename(partfname){\n}\n\nFileSystem::~FileSystem(){\n}\n\nvoid FileSystem::debug(){\n\n std::cout << \"Debugging the filesystem class...\" << std::endl;\n this->init();\n this->load();\n\n}\n\nint FileSystem::init(){\n\n FILE* fd = fopen(partfilename.c_str(), \"wb+\");\n\n \/\/ step 1: writeout 1024 0xbb's\n unsigned char bootblock[1024];\n memset(bootblock, 0xbb, sizeof(bootblock));\n fwrite(bootblock, 1, sizeof(bootblock), fd);\n\n \/\/ step 2: writeout the fat \"header\"\n unsigned char fatheader[20] = {0xff, 0xfd,\n 0xff, 0xfe,\n 0xff, 0xfe,\n 0xff, 0xfe,\n 0xff, 0xfe,\n 0xff, 0xfe,\n 0xff, 0xfe,\n 0xff, 0xfe,\n 0xff, 0xfe,\n 0xff, 0xff};\n\n fwrite(fatheader, 1, sizeof(fatheader), fd);\n\n \/\/ step 3: writeout blank rest\n unsigned char blankrest[4193260];\n memset(blankrest, 0x00, sizeof(blankrest));\n fwrite(blankrest, 1, sizeof(blankrest), fd);\n\n fclose(fd);\n\n return RET_OK;\n\n}\n\nint FileSystem::load(){\n\n \/\/ mvtodo: load fat into ram \n\n FILE* fd = fopen(partfilename.c_str(), \"rb+\");\n fseek(fd, 1024, SEEK_SET);\n fread(fat, 1, sizeof(fat), fd);\n fclose(fd);\n\n return RET_OK;\n\n}\n\nint FileSystem::listdir(const std::string &path, std::vector &result){\n (void)path;\n (void)result;\n return -1;\n}\n\nint FileSystem::makedir(const std::string &path){\n (void)path;\n return -1;\n}\n\nint FileSystem::createfile(const std::string &path){\n (void)path;\n return -1;\n}\n\nint FileSystem::unlink(const std::string &path){\n (void)path;\n return -1;\n}\n\nint FileSystem::write(const std::string &path, const std::string &content){\n (void)path;\n (void)content;\n return -1;\n}\n\nint FileSystem::append(const std::string &path, const std::string &content){\n (void)path;\n (void)content;\n return -1;\n}\n\nint FileSystem::read(const std::string &path, std::string &content){\n (void)path;\n (void)content;\n return -1;\n}\n\n<|endoftext|>"} {"text":"\/* Copyright 2019 Google LLC. 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\n#include \"tensorflow\/lite\/experimental\/ruy\/block_map.h\"\n\n#include \"profiling\/instrumentation.h\"\n#include \"tensorflow\/lite\/experimental\/ruy\/check_macros.h\"\n#include \"tensorflow\/lite\/experimental\/ruy\/opt_set.h\"\n#include \"tensorflow\/lite\/experimental\/ruy\/size_util.h\"\n\nnamespace ruy {\n\nvoid GetBlockByIndex(const BlockMap& block_map, int index,\n SidePair* block) {\n gemmlowp::ScopedProfilingLabel label(\"GetBlockByIndex\");\n const std::uint32_t index_u32 = index;\n const std::uint32_t rectr =\n index_u32 & ((1u << block_map.rectangularness_log2[Side::kLhs]) - 1);\n const std::uint32_t rectc =\n index_u32 & ((1u << block_map.rectangularness_log2[Side::kRhs]) - 1);\n\n const std::uint32_t n1 =\n index_u32 >> (block_map.rectangularness_log2[Side::kLhs] +\n block_map.rectangularness_log2[Side::kRhs]);\n RUY_DCHECK_EQ(index_u32,\n (n1 << (block_map.rectangularness_log2[Side::kLhs] +\n block_map.rectangularness_log2[Side::kRhs])) +\n rectr + rectc);\n\n std::uint32_t br, bc;\n if (block_map.traversal_order == BlockMapTraversalOrder::kLinear) {\n br = n1 & ((1u << block_map.num_blocks_base_log2) - 1);\n bc = n1 >> block_map.num_blocks_base_log2;\n } else {\n \/\/ Decode fractal z-order\n const std::uint32_t n2 = (n1 & 0x99999999u) | ((n1 & 0x44444444u) >> 1) |\n ((n1 & 0x22222222u) << 1);\n const std::uint32_t n4 = (n2 & 0xc3c3c3c3u) | ((n2 & 0x30303030u) >> 2) |\n ((n2 & 0x0c0c0c0cu) << 2);\n const std::uint32_t n8 = (n4 & 0xf00ff00fu) | ((n4 & 0x0f000f00u) >> 4) |\n ((n4 & 0x00f000f0u) << 4);\n const std::uint32_t n16 = (n8 & 0xff0000ffu) | ((n8 & 0x00ff0000u) >> 8) |\n ((n8 & 0x0000ff00u) << 8);\n\n br = n16 & 0xffff;\n bc = n16 >> 16;\n if (block_map.traversal_order == BlockMapTraversalOrder::kFractalU) {\n \/\/ Change fractal z-order to u-order\n br ^= bc;\n }\n }\n\n br = (br << block_map.rectangularness_log2[Side::kLhs]) + rectr;\n bc = (bc << block_map.rectangularness_log2[Side::kRhs]) + rectc;\n\n \/\/ Store\n (*block)[Side::kLhs] = br;\n (*block)[Side::kRhs] = bc;\n}\n\nnamespace {\n\nint floor_log2_quotient(int num, int denom) {\n if (num <= denom) {\n return 0;\n }\n int log2_quotient = floor_log2(num) - ceil_log2(denom);\n if ((denom << (log2_quotient + 1)) <= num) {\n log2_quotient++;\n }\n return log2_quotient;\n}\n\n} \/\/ namespace\n\nvoid MakeBlockMap(int rows, int cols, int depth, int kernel_rows,\n int kernel_cols, int lhs_scalar_size, int rhs_scalar_size,\n int cache_friendly_traversal_threshold, BlockMap* block_map) {\n gemmlowp::ScopedProfilingLabel label(\"MakeBlockMap\");\n RUY_DCHECK_GE(rows, kernel_rows);\n RUY_DCHECK_GE(cols, kernel_cols);\n RUY_DCHECK_EQ(rows % kernel_rows, 0);\n RUY_DCHECK_EQ(cols % kernel_cols, 0);\n\n block_map->traversal_order = BlockMapTraversalOrder::kLinear;\n if (RUY_OPT_ENABLED(RUY_OPT_FRACTAL) &&\n (rows * lhs_scalar_size + cols * rhs_scalar_size) * depth >=\n cache_friendly_traversal_threshold) {\n block_map->traversal_order = RUY_OPT_ENABLED(RUY_OPT_FRACTAL_U)\n ? BlockMapTraversalOrder::kFractalU\n : BlockMapTraversalOrder::kFractalZ;\n }\n\n \/\/ See the comment on BlockMap in block_map.h.\n \/\/ The destination matrix shape (rows x cols) is to be subdivided into a\n \/\/ square (N x N) grid of blocks, whose shapes must be multiples of the\n \/\/ kernel block shape (kernel_rows x kernel_cols).\n \/\/ Inside each of these N*N blocks, we may have one further level of\n \/\/ subdivision either along rows or along cols but not both, to handle\n \/\/ better the highly rectangular cases. That is what we call\n \/\/ 'rectangularness'. This extra level of subdivision is into\n \/\/ (1 << rows_rectangularness_log2) blocks along rows dimension, or into\n \/\/ (1 << cols_rectangularness_log2) blocks along cols dimension.\n int rows_rectangularness_log2 = 0;\n int cols_rectangularness_log2 = 0;\n \/\/ In order to compute these rectangularness values, we need to divide\n \/\/ the destination matrix's aspect ratio,\n \/\/ rows \/ cols\n \/\/ by the kernel block's aspect ratio,\n \/\/ kernel_block_rows \/ kernel_block_cols.\n \/\/ The quotient of these two quotients simplifies to\n \/\/ (rows * kernel_cols) \/ (cols * kernel_rows)\n \/\/ Whence the introduction of the following products:\n const int rows_times_kernel_cols = rows * kernel_cols;\n const int cols_times_kernel_rows = cols * kernel_rows;\n if (rows_times_kernel_cols > cols_times_kernel_rows) {\n rows_rectangularness_log2 =\n floor_log2_quotient(rows_times_kernel_cols, cols_times_kernel_rows);\n \/\/ Sanity check that we did not over-estimate rows_rectangularness_log2.\n RUY_DCHECK_GE(rows_times_kernel_cols >> rows_rectangularness_log2,\n cols_times_kernel_rows);\n } else if (cols_times_kernel_rows > rows_times_kernel_cols) {\n cols_rectangularness_log2 =\n floor_log2_quotient(cols_times_kernel_rows, rows_times_kernel_cols);\n \/\/ Sanity check that we did not over-estimate cols_rectangularness_log2.\n RUY_DCHECK_GE(cols_times_kernel_rows >> cols_rectangularness_log2,\n rows_times_kernel_cols);\n }\n\n RUY_DCHECK(!rows_rectangularness_log2 || !cols_rectangularness_log2);\n\n const int size = std::min(rows, cols);\n const int size_floor_log2 = floor_log2(size);\n const int depth_ceil_log2 = ceil_log2(depth);\n const int kernel_width_log2 = ceil_log2(std::max(kernel_cols, kernel_rows));\n\n \/\/ l1_size_log2 was originally, coarsely speaking the number of rows of LHS,\n \/\/ or the number of columns of RHS in a matrix multiplication that we expect,\n \/\/ to fit in L1 cache.\n \/\/\n \/\/ This initial rationale is not necessarily still relevant. The logic below\n \/\/ was determined empirically, not in a principled way.\n int l1_size_log2;\n if (size_floor_log2 <= 3) {\n l1_size_log2 = size_floor_log2;\n } else if (size_floor_log2 <= 6) {\n l1_size_log2 = 4;\n } else {\n l1_size_log2 = 5;\n }\n\n \/\/ The 15 here implicitly encodes target a 32k L1 cache (2^15 == 32k).\n \/\/ Once again this only has a distant memory of being originally motivated\n \/\/ by such clear principles linking this logic to cache sizes.\n l1_size_log2 = std::min(\n l1_size_log2, 15 - depth_ceil_log2 -\n ceil_log2(std::max(lhs_scalar_size, rhs_scalar_size)));\n l1_size_log2 = std::max(l1_size_log2, kernel_width_log2);\n l1_size_log2 = std::min(l1_size_log2, size_floor_log2);\n\n int num_blocks_base_log2 = size_floor_log2 - l1_size_log2;\n RUY_DCHECK_GE(num_blocks_base_log2, 0);\n\n const int num_blocks_of_rows_log2 =\n num_blocks_base_log2 + rows_rectangularness_log2;\n const int num_blocks_of_cols_log2 =\n num_blocks_base_log2 + cols_rectangularness_log2;\n\n const int smallr =\n round_down_pot(rows >> num_blocks_of_rows_log2, kernel_rows);\n const int smallc =\n round_down_pot(cols >> num_blocks_of_cols_log2, kernel_cols);\n const int missr =\n round_up_pot(rows - (smallr << num_blocks_of_rows_log2), kernel_rows) \/\n kernel_rows;\n const int missc =\n round_up_pot(cols - (smallc << num_blocks_of_cols_log2), kernel_cols) \/\n kernel_cols;\n\n block_map->dims[Side::kLhs] = rows;\n block_map->dims[Side::kRhs] = cols;\n block_map->kernel_dims[Side::kLhs] = kernel_rows;\n block_map->kernel_dims[Side::kRhs] = kernel_cols;\n block_map->num_blocks_base_log2 = num_blocks_base_log2;\n block_map->rectangularness_log2[Side::kLhs] = rows_rectangularness_log2;\n block_map->rectangularness_log2[Side::kRhs] = cols_rectangularness_log2;\n block_map->small_block_dims[Side::kLhs] = smallr;\n block_map->small_block_dims[Side::kRhs] = smallc;\n block_map->large_blocks[Side::kLhs] = missr;\n block_map->large_blocks[Side::kRhs] = missc;\n}\n\nvoid GetBlockMatrixCoords(Side side, const BlockMap& block_map, int block,\n int* start, int* end) {\n gemmlowp::ScopedProfilingLabel label(\"GetBlockMatrixCoords\");\n *start = block * block_map.small_block_dims[side] +\n std::min(block, block_map.large_blocks[side]) *\n block_map.kernel_dims[side];\n *end =\n *start + block_map.small_block_dims[side] +\n (block < block_map.large_blocks[side] ? block_map.kernel_dims[side] : 0);\n\n RUY_DCHECK_EQ(0, *start % block_map.kernel_dims[side]);\n RUY_DCHECK_EQ(0, *end % block_map.kernel_dims[side]);\n RUY_DCHECK_LE(*end, block_map.dims[side]);\n RUY_DCHECK_LT(*start, *end);\n RUY_DCHECK_GE(*start, 0);\n}\n\nvoid GetBlockMatrixCoords(const BlockMap& block_map, const SidePair& block,\n SidePair* start, SidePair* end) {\n for (Side side : {Side::kLhs, Side::kRhs}) {\n GetBlockMatrixCoords(side, block_map, block[side], &(*start)[side],\n &(*end)[side]);\n }\n}\n\n} \/\/ namespace ruy\nAvoid divisions when the divisor is a power of two.\/* Copyright 2019 Google LLC. 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\n#include \"tensorflow\/lite\/experimental\/ruy\/block_map.h\"\n\n#include \"profiling\/instrumentation.h\"\n#include \"tensorflow\/lite\/experimental\/ruy\/check_macros.h\"\n#include \"tensorflow\/lite\/experimental\/ruy\/opt_set.h\"\n#include \"tensorflow\/lite\/experimental\/ruy\/size_util.h\"\n\nnamespace ruy {\n\nvoid GetBlockByIndex(const BlockMap& block_map, int index,\n SidePair* block) {\n gemmlowp::ScopedProfilingLabel label(\"GetBlockByIndex\");\n const std::uint32_t index_u32 = index;\n const std::uint32_t rectr =\n index_u32 & ((1u << block_map.rectangularness_log2[Side::kLhs]) - 1);\n const std::uint32_t rectc =\n index_u32 & ((1u << block_map.rectangularness_log2[Side::kRhs]) - 1);\n\n const std::uint32_t n1 =\n index_u32 >> (block_map.rectangularness_log2[Side::kLhs] +\n block_map.rectangularness_log2[Side::kRhs]);\n RUY_DCHECK_EQ(index_u32,\n (n1 << (block_map.rectangularness_log2[Side::kLhs] +\n block_map.rectangularness_log2[Side::kRhs])) +\n rectr + rectc);\n\n std::uint32_t br, bc;\n if (block_map.traversal_order == BlockMapTraversalOrder::kLinear) {\n br = n1 & ((1u << block_map.num_blocks_base_log2) - 1);\n bc = n1 >> block_map.num_blocks_base_log2;\n } else {\n \/\/ Decode fractal z-order\n const std::uint32_t n2 = (n1 & 0x99999999u) | ((n1 & 0x44444444u) >> 1) |\n ((n1 & 0x22222222u) << 1);\n const std::uint32_t n4 = (n2 & 0xc3c3c3c3u) | ((n2 & 0x30303030u) >> 2) |\n ((n2 & 0x0c0c0c0cu) << 2);\n const std::uint32_t n8 = (n4 & 0xf00ff00fu) | ((n4 & 0x0f000f00u) >> 4) |\n ((n4 & 0x00f000f0u) << 4);\n const std::uint32_t n16 = (n8 & 0xff0000ffu) | ((n8 & 0x00ff0000u) >> 8) |\n ((n8 & 0x0000ff00u) << 8);\n\n br = n16 & 0xffff;\n bc = n16 >> 16;\n if (block_map.traversal_order == BlockMapTraversalOrder::kFractalU) {\n \/\/ Change fractal z-order to u-order\n br ^= bc;\n }\n }\n\n br = (br << block_map.rectangularness_log2[Side::kLhs]) + rectr;\n bc = (bc << block_map.rectangularness_log2[Side::kRhs]) + rectc;\n\n \/\/ Store\n (*block)[Side::kLhs] = br;\n (*block)[Side::kRhs] = bc;\n}\n\nnamespace {\n\nint floor_log2_quotient(int num, int denom) {\n if (num <= denom) {\n return 0;\n }\n int log2_quotient = floor_log2(num) - ceil_log2(denom);\n if ((denom << (log2_quotient + 1)) <= num) {\n log2_quotient++;\n }\n return log2_quotient;\n}\n\n} \/\/ namespace\n\nvoid MakeBlockMap(int rows, int cols, int depth, int kernel_rows,\n int kernel_cols, int lhs_scalar_size, int rhs_scalar_size,\n int cache_friendly_traversal_threshold, BlockMap* block_map) {\n gemmlowp::ScopedProfilingLabel label(\"MakeBlockMap\");\n RUY_DCHECK_GE(rows, kernel_rows);\n RUY_DCHECK_GE(cols, kernel_cols);\n RUY_DCHECK_EQ(rows % kernel_rows, 0);\n RUY_DCHECK_EQ(cols % kernel_cols, 0);\n\n block_map->traversal_order = BlockMapTraversalOrder::kLinear;\n if (RUY_OPT_ENABLED(RUY_OPT_FRACTAL) &&\n (rows * lhs_scalar_size + cols * rhs_scalar_size) * depth >=\n cache_friendly_traversal_threshold) {\n block_map->traversal_order = RUY_OPT_ENABLED(RUY_OPT_FRACTAL_U)\n ? BlockMapTraversalOrder::kFractalU\n : BlockMapTraversalOrder::kFractalZ;\n }\n\n \/\/ See the comment on BlockMap in block_map.h.\n \/\/ The destination matrix shape (rows x cols) is to be subdivided into a\n \/\/ square (N x N) grid of blocks, whose shapes must be multiples of the\n \/\/ kernel block shape (kernel_rows x kernel_cols).\n \/\/ Inside each of these N*N blocks, we may have one further level of\n \/\/ subdivision either along rows or along cols but not both, to handle\n \/\/ better the highly rectangular cases. That is what we call\n \/\/ 'rectangularness'. This extra level of subdivision is into\n \/\/ (1 << rows_rectangularness_log2) blocks along rows dimension, or into\n \/\/ (1 << cols_rectangularness_log2) blocks along cols dimension.\n int rows_rectangularness_log2 = 0;\n int cols_rectangularness_log2 = 0;\n \/\/ In order to compute these rectangularness values, we need to divide\n \/\/ the destination matrix's aspect ratio,\n \/\/ rows \/ cols\n \/\/ by the kernel block's aspect ratio,\n \/\/ kernel_block_rows \/ kernel_block_cols.\n \/\/ The quotient of these two quotients simplifies to\n \/\/ (rows * kernel_cols) \/ (cols * kernel_rows)\n \/\/ Whence the introduction of the following products:\n const int rows_times_kernel_cols = rows * kernel_cols;\n const int cols_times_kernel_rows = cols * kernel_rows;\n if (rows_times_kernel_cols > cols_times_kernel_rows) {\n rows_rectangularness_log2 =\n floor_log2_quotient(rows_times_kernel_cols, cols_times_kernel_rows);\n \/\/ Sanity check that we did not over-estimate rows_rectangularness_log2.\n RUY_DCHECK_GE(rows_times_kernel_cols >> rows_rectangularness_log2,\n cols_times_kernel_rows);\n } else if (cols_times_kernel_rows > rows_times_kernel_cols) {\n cols_rectangularness_log2 =\n floor_log2_quotient(cols_times_kernel_rows, rows_times_kernel_cols);\n \/\/ Sanity check that we did not over-estimate cols_rectangularness_log2.\n RUY_DCHECK_GE(cols_times_kernel_rows >> cols_rectangularness_log2,\n rows_times_kernel_cols);\n }\n\n RUY_DCHECK(!rows_rectangularness_log2 || !cols_rectangularness_log2);\n\n const int size = std::min(rows, cols);\n const int size_floor_log2 = floor_log2(size);\n const int depth_ceil_log2 = ceil_log2(depth);\n const int kernel_width_log2 = ceil_log2(std::max(kernel_cols, kernel_rows));\n\n \/\/ l1_size_log2 was originally, coarsely speaking the number of rows of LHS,\n \/\/ or the number of columns of RHS in a matrix multiplication that we expect,\n \/\/ to fit in L1 cache.\n \/\/\n \/\/ This initial rationale is not necessarily still relevant. The logic below\n \/\/ was determined empirically, not in a principled way.\n int l1_size_log2;\n if (size_floor_log2 <= 3) {\n l1_size_log2 = size_floor_log2;\n } else if (size_floor_log2 <= 6) {\n l1_size_log2 = 4;\n } else {\n l1_size_log2 = 5;\n }\n\n \/\/ The 15 here implicitly encodes target a 32k L1 cache (2^15 == 32k).\n \/\/ Once again this only has a distant memory of being originally motivated\n \/\/ by such clear principles linking this logic to cache sizes.\n l1_size_log2 = std::min(\n l1_size_log2, 15 - depth_ceil_log2 -\n ceil_log2(std::max(lhs_scalar_size, rhs_scalar_size)));\n l1_size_log2 = std::max(l1_size_log2, kernel_width_log2);\n l1_size_log2 = std::min(l1_size_log2, size_floor_log2);\n\n int num_blocks_base_log2 = size_floor_log2 - l1_size_log2;\n RUY_DCHECK_GE(num_blocks_base_log2, 0);\n\n const int num_blocks_of_rows_log2 =\n num_blocks_base_log2 + rows_rectangularness_log2;\n const int num_blocks_of_cols_log2 =\n num_blocks_base_log2 + cols_rectangularness_log2;\n\n const int smallr =\n round_down_pot(rows >> num_blocks_of_rows_log2, kernel_rows);\n const int smallc =\n round_down_pot(cols >> num_blocks_of_cols_log2, kernel_cols);\n const int missr =\n round_up_pot(rows - (smallr << num_blocks_of_rows_log2), kernel_rows) >>\n floor_log2(kernel_rows);\n const int missc =\n round_up_pot(cols - (smallc << num_blocks_of_cols_log2), kernel_cols) >>\n floor_log2(kernel_cols);\n\n block_map->dims[Side::kLhs] = rows;\n block_map->dims[Side::kRhs] = cols;\n block_map->kernel_dims[Side::kLhs] = kernel_rows;\n block_map->kernel_dims[Side::kRhs] = kernel_cols;\n block_map->num_blocks_base_log2 = num_blocks_base_log2;\n block_map->rectangularness_log2[Side::kLhs] = rows_rectangularness_log2;\n block_map->rectangularness_log2[Side::kRhs] = cols_rectangularness_log2;\n block_map->small_block_dims[Side::kLhs] = smallr;\n block_map->small_block_dims[Side::kRhs] = smallc;\n block_map->large_blocks[Side::kLhs] = missr;\n block_map->large_blocks[Side::kRhs] = missc;\n}\n\nvoid GetBlockMatrixCoords(Side side, const BlockMap& block_map, int block,\n int* start, int* end) {\n gemmlowp::ScopedProfilingLabel label(\"GetBlockMatrixCoords\");\n *start = block * block_map.small_block_dims[side] +\n std::min(block, block_map.large_blocks[side]) *\n block_map.kernel_dims[side];\n *end =\n *start + block_map.small_block_dims[side] +\n (block < block_map.large_blocks[side] ? block_map.kernel_dims[side] : 0);\n\n RUY_DCHECK_EQ(0, *start % block_map.kernel_dims[side]);\n RUY_DCHECK_EQ(0, *end % block_map.kernel_dims[side]);\n RUY_DCHECK_LE(*end, block_map.dims[side]);\n RUY_DCHECK_LT(*start, *end);\n RUY_DCHECK_GE(*start, 0);\n}\n\nvoid GetBlockMatrixCoords(const BlockMap& block_map, const SidePair& block,\n SidePair* start, SidePair* end) {\n for (Side side : {Side::kLhs, Side::kRhs}) {\n GetBlockMatrixCoords(side, block_map, block[side], &(*start)[side],\n &(*end)[side]);\n }\n}\n\n} \/\/ namespace ruy\n<|endoftext|>"} {"text":"\/* ux++ - ux implementation for C++ *\/\n\n\/* LICENSE - The MIT License (MIT)\n\nCopyright (c) 2013 Tomona Nanase\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject 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, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#ifndef ENVELOPEOPERATE_H\n#define\tENVELOPEOPERATE_H\n\n#include \n#include \n#include \"EnumBase.hpp\"\n\nusing namespace std;\n\nnamespace uxpp {\n\n \/**\n * エンベロープの状態を表す列挙体です。\n *\/\n class EnvelopeOperate : public EnumBase {\n public:\n\n \/\/ \n\n enum values {\n \/**\n * オプションなし。\n * これは音源に対するオプションと組み合わせるために用意されています。\n *\/\n none = 0x00,\n\n \/**\n * アタック時間。\n *\/\n attack = 0x01,\n\n \/**\n * ピーク時間。\n *\/\n peak = 0x02,\n\n \/**\n * ディケイ時間。\n *\/\n decay = 0x03,\n\n \/**\n * サスティンレベル。\n *\/\n sustain = 0x04,\n\n \/**\n * リリース時間。\n *\/\n release = 0x05,\n };\n\n \/\/ <\/editor-fold>\n\n \/\/ \n\n _key_exists_impl(EnvelopeOperate);\n _value_exists_impl(EnvelopeOperate);\n _toString_impl(EnvelopeOperate);\n _tryParse_impl(EnvelopeOperate);\n \/\/ <\/editor-fold>\n\n private:\n static const unordered_map map;\n };\n\n const unordered_map\n EnvelopeOperate::map = {\n {\"none\", none},\n {\"attack\", attack},\n {\"peak\", peak},\n {\"decay\", decay},\n {\"sustain\", sustain},\n {\"release\", release},\n {\"a\", attack},\n {\"p\", peak},\n {\"d\", decay},\n {\"s\", sustain},\n {\"r\", release},\n };\n}\n\n#endif\t\/* ENVELOPEOPERATE_H *\/\n\nEnvelopeOperateクラスのusingディレクティブを削除\/* ux++ - ux implementation for C++ *\/\n\n\/* LICENSE - The MIT License (MIT)\n\nCopyright (c) 2013 Tomona Nanase\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject 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, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#ifndef ENVELOPEOPERATE_H\n#define\tENVELOPEOPERATE_H\n\n#include \n#include \n#include \"EnumBase.hpp\"\n\nnamespace uxpp {\n\n \/**\n * エンベロープの状態を表す列挙体です。\n *\/\n class EnvelopeOperate : public EnumBase {\n public:\n\n \/\/ \n\n enum values {\n \/**\n * オプションなし。\n * これは音源に対するオプションと組み合わせるために用意されています。\n *\/\n none = 0x00,\n\n \/**\n * アタック時間。\n *\/\n attack = 0x01,\n\n \/**\n * ピーク時間。\n *\/\n peak = 0x02,\n\n \/**\n * ディケイ時間。\n *\/\n decay = 0x03,\n\n \/**\n * サスティンレベル。\n *\/\n sustain = 0x04,\n\n \/**\n * リリース時間。\n *\/\n release = 0x05,\n };\n\n \/\/ <\/editor-fold>\n\n \/\/ \n\n _key_exists_impl(EnvelopeOperate);\n _value_exists_impl(EnvelopeOperate);\n _toString_impl(EnvelopeOperate);\n _tryParse_impl(EnvelopeOperate);\n \/\/ <\/editor-fold>\n\n private:\n static const std::unordered_map map;\n };\n\n const std::unordered_map\n EnvelopeOperate::map = {\n {\"none\", none},\n {\"attack\", attack},\n {\"peak\", peak},\n {\"decay\", decay},\n {\"sustain\", sustain},\n {\"release\", release},\n {\"a\", attack},\n {\"p\", peak},\n {\"d\", decay},\n {\"s\", sustain},\n {\"r\", release},\n };\n}\n\n#endif\t\/* ENVELOPEOPERATE_H *\/\n\n<|endoftext|>"} {"text":"#include \"IwGx.h\"\n#include \"IwTween.h\"\n#include \"audio.h\"\n#include \"scene.h\"\n#include \"grid.h\"\n#include \"game.h\"\n#include \"blankObject.h\"\n#include \"resources.h\"\n#include \"main.h\"\n\nusing namespace IwTween;\n\nGrid::Grid(CNode* scene, int num_columns, int num_rows, int offset_x, int offset_y, int grid_width)\n{\n\tint map[11][17] = {\n\t\t{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n\t\t{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }\n\t};\n\n\tWidth = num_columns;\n\tHeight = num_rows;\n\tGameObjects = new GameObject* [num_columns * (num_rows + 1)];\n\n\tint bm_width = (int)g_pResources->GetRock()->GetWidth();\n\tGameObjectSize = (IwGxGetScreenWidth() * bm_width) \/ GRAPHIC_DESIGN_WIDTH;\n\n\tfloat gem_scale = (float)GameObjectSize \/ bm_width;\n\n\tGridOriginX = offset_x;\n\tGridOriginY = IwGxGetScreenHeight() - (num_rows * GameObjectSize) - offset_y;\n\n\tfor (int y = 0; y < num_rows; y++)\n\t{\n\t\tfor (int x = 0; x < num_columns; x++)\n\t\t{\n\t\t\tswitch (map[x][y])\n\t\t\t{\n\t\t\tcase 0:\n\t\t\t\tIwTrace(APP, (\"GameObject[%d], Id(%d)\", x + Width*y, 0));\n\t\t\t\tGameObjects[x + Width*y] = new BlankObject();\n\t\t\t\tGameObjects[x + Width*y]->setId(0);\n\t\t\t\tGameObjects[x + Width*y]->setGridCoords(x, y);\n\t\t\t\tGameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetBlank());\n\t\t\t\tscene->AddChild(GameObjects[x + Width*y]);\n\t\t\t\tbreak;\n\n\t\t\tcase 1:\n\t\t\t\tIwTrace(APP, (\"GameObject[%d], Id(%d)\", x + Width*y, 1));\n\t\t\t\tGameObjects[x + Width*y] = new Rock();\n\t\t\t\tGameObjects[x + Width*y]->setId(1);\n\t\t\t\tGameObjects[x + Width*y]->setGridCoords(x, y);\n\t\t\t\tGameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetRock());\n\t\t\t\tGameObjects[x + Width*y]->m_ScaleX = gem_scale;\n\t\t\t\tGameObjects[x + Width*y]->m_ScaleY = gem_scale;\n\t\t\t\tscene->AddChild(GameObjects[x + Width*y]);\n\t\t\t\tbreak;\n\n\t\t\tcase 2:\n\t\t\t\tIwTrace(APP, (\"GameObject[%d], Id(%d)\", x + Width*y, 2));\n\t\t\t\tGameObjects[x + Width*y] = new Player();\n\t\t\t\tGameObjects[x + Width*y]->setId(2);\n\t\t\t\tGameObjects[x + Width*y]->setGridCoords(x, y);\n\t\t\t\tGameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetPlayer());\n\t\t\t\tGameObjects[x + Width*y]->m_ScaleX = gem_scale;\n\t\t\t\tGameObjects[x + Width*y]->m_ScaleY = gem_scale;\n\t\t\t\tscene->AddChild(GameObjects[x + Width*y]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nGrid::~Grid()\n{\n\tif (GameObjects != 0)\n\t\tdelete[] GameObjects;\n}\n\nvoid Grid::movePlayerLeft()\n{\n\tint index = 0;\n\n\tfor (int y = 0; y < Height; y++)\n\t{\n\t\tfor (int x = 0; x < Width; x++)\n\t\t{\n\t\t\tif (GameObjects[x + Width * y]->getId() == 2)\n\t\t\t{\n\t\t\t\tindex = x + Width * y;\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::pair coords = GameObjects[index]->getCoords();\n\tint x = coords.first;\n\tint y = coords.second;\n\n\tIwTrace(APP, (\"coords [%d][%d]\", x, y));\n\n\tint distance = 0;\n\n\twhile (GameObjects[(x - (distance + 1)) + Width*y]->getId() == 0) {\n\t\tdistance++;\n\t}\n\n\tIwTrace(APP, (\"distance = %d\", distance));\n\t\n\t\/\/cleanup\n}\n\nvoid Grid::movePlayerRight()\n{\n}\n\nvoid Grid::movePlayerUp()\n{\n}\n\nvoid Grid::movePlayerDown()\n{\n}\n\nint Grid::getDistance(Grid::Direction dir)\n{\n\tint distance = 0;\n\n\tswitch (dir)\n\t{\n\tcase LEFT:\n\t\tbreak;\n\tcase RIGHT:\n\t\tbreak;\n\tcase UP:\n\t\tbreak;\n\tcase DOWN:\n\t\tbreak;\n\t}\n\n\treturn 0;\n}\nplayer sliding left#include \"IwGx.h\"\n#include \"IwTween.h\"\n#include \"audio.h\"\n#include \"scene.h\"\n#include \"grid.h\"\n#include \"game.h\"\n#include \"blankObject.h\"\n#include \"resources.h\"\n#include \"main.h\"\n\nusing namespace IwTween;\n\nGrid::Grid(CNode* scene, int num_columns, int num_rows, int offset_x, int offset_y, int grid_width)\n{\n\tint map[11][17] = {\n\t\t{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n\t\t{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n\t\t{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }\n\t};\n\n\tWidth = num_columns;\n\tHeight = num_rows;\n\tGameObjects = new GameObject* [num_columns * (num_rows + 1)];\n\n\tint bm_width = (int)g_pResources->GetRock()->GetWidth();\n\tGameObjectSize = (IwGxGetScreenWidth() * bm_width) \/ GRAPHIC_DESIGN_WIDTH;\n\n\tfloat gem_scale = (float)GameObjectSize \/ bm_width;\n\n\tGridOriginX = offset_x;\n\tGridOriginY = IwGxGetScreenHeight() - (num_rows * GameObjectSize) - offset_y;\n\n\tfor (int y = 0; y < num_rows; y++)\n\t{\n\t\tfor (int x = 0; x < num_columns; x++)\n\t\t{\n\t\t\tswitch (map[x][y])\n\t\t\t{\n\t\t\tcase 0:\n\t\t\t\tIwTrace(APP, (\"GameObject[%d], Id(%d)\", x + Width*y, 0));\n\t\t\t\tGameObjects[x + Width*y] = new BlankObject();\n\t\t\t\tGameObjects[x + Width*y]->setId(0);\n\t\t\t\tGameObjects[x + Width*y]->setGridCoords(x, y);\n\t\t\t\tGameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetBlank());\n\t\t\t\tscene->AddChild(GameObjects[x + Width*y]);\n\t\t\t\tbreak;\n\n\t\t\tcase 1:\n\t\t\t\tIwTrace(APP, (\"GameObject[%d], Id(%d)\", x + Width*y, 1));\n\t\t\t\tGameObjects[x + Width*y] = new Rock();\n\t\t\t\tGameObjects[x + Width*y]->setId(1);\n\t\t\t\tGameObjects[x + Width*y]->setGridCoords(x, y);\n\t\t\t\tGameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetRock());\n\t\t\t\tGameObjects[x + Width*y]->m_ScaleX = gem_scale;\n\t\t\t\tGameObjects[x + Width*y]->m_ScaleY = gem_scale;\n\t\t\t\tscene->AddChild(GameObjects[x + Width*y]);\n\t\t\t\tbreak;\n\n\t\t\tcase 2:\n\t\t\t\tIwTrace(APP, (\"GameObject[%d], Id(%d)\", x + Width*y, 2));\n\t\t\t\tGameObjects[x + Width*y] = new Player();\n\t\t\t\tGameObjects[x + Width*y]->setId(2);\n\t\t\t\tGameObjects[x + Width*y]->setGridCoords(x, y);\n\t\t\t\tGameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetPlayer());\n\t\t\t\tGameObjects[x + Width*y]->m_ScaleX = gem_scale;\n\t\t\t\tGameObjects[x + Width*y]->m_ScaleY = gem_scale;\n\t\t\t\tscene->AddChild(GameObjects[x + Width*y]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nGrid::~Grid()\n{\n\tif (GameObjects != 0)\n\t\tdelete[] GameObjects;\n}\n\nvoid Grid::movePlayerLeft()\n{\n\tint index = 0;\n\n\tfor (int y = 0; y < Height; y++)\n\t{\n\t\tfor (int x = 0; x < Width; x++)\n\t\t{\n\t\t\tif (GameObjects[x + Width * y]->getId() == 2)\n\t\t\t{\n\t\t\t\tindex = x + Width * y;\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::pair coords = GameObjects[index]->getCoords();\n\tint x = coords.first;\n\tint y = coords.second;\n\n\tIwTrace(APP, (\"coords [%d][%d]\", x, y));\n\n\tint distance = 0;\n\n\twhile (GameObjects[(x - (distance + 1)) + Width*y]->getId() == 0) {\n\t\tdistance++;\n\t}\n\n\tIwTrace(APP, (\"distance = %d\", distance));\n\n\tfloat new_X = GameObjects[index]->m_X - (distance * GameObjectSize);\n\n\tGame* game = (Game*)g_pSceneManager->Find(\"game\");\n\n\tgame->GetTweener().Tween(0.5f,\n\t\tFLOAT, &GameObjects[index]->m_X, new_X,\n\t\tEASING, Ease::sineInOut,\n\t\tEND);\n}\n\nvoid Grid::movePlayerRight()\n{\n}\n\nvoid Grid::movePlayerUp()\n{\n}\n\nvoid Grid::movePlayerDown()\n{\n}\n\nint Grid::getDistance(Grid::Direction dir)\n{\n\tint distance = 0;\n\n\tswitch (dir)\n\t{\n\tcase LEFT:\n\t\tbreak;\n\tcase RIGHT:\n\t\tbreak;\n\tcase UP:\n\t\tbreak;\n\tcase DOWN:\n\t\tbreak;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\n#include \"leaf.h\"\n#include \"composite.h\"\n#include \"component.h\"\n\nint main (void)\n{\n\n}\nInstantiation of all 3 classes as a first test\n#include \"leaf.h\"\n#include \"composite.h\"\n#include \"component.h\"\n\nint main (void)\n{\n\tKompositum::Component component(0);\n\tKompositum::Composite composite(1);\n\tKompositum::Leaf leaf(2);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2015 C. Brett Witherspoon\n *\/\n\n#ifndef OSCILLATOR_HPP_\n#define OSCILLATOR_HPP_\n\n#include \n\nnamespace comm {\n\ntemplate\nclass oscillator\n{\npublic:\n using sample_type = T;\n\n oscillator(double frequency, double sample_rate, double amplitude=1)\n : m_freq(frequency),\n m_rate(sample_rate),\n m_ampl(amplitude)\n {\n static_assert(std::is_floating_point::value,\n \"Sample type must be a floating point type\");\n\n m_y1 = 0;\n m_y2 = -m_ampl * sin(2 * M_PI * m_freq \/ m_rate);\n m_2cos_omega = 2 * cos(2 * M_PI * m_freq \/ m_rate);\n }\n\n template\n void operator()(std::array &output)\n {\n for (auto &y0 : output)\n {\n y0 = m_2cos_omega * m_y1 - m_y2;\n m_y2 = m_y1;\n m_y1 = y0;\n }\n }\n\n double frequency() { return m_freq; }\n\n double sample_rate() { return m_rate; }\n\n double amplitude() { return m_ampl; }\n\nprivate:\n double m_freq;\n double m_rate;\n double m_ampl;\n\n double m_y1;\n double m_y2;\n double m_2cos_omega;\n};\n\ntemplate<>\ntemplate\nclass oscillator>\n{\npublic:\n using sample_type = std::complex;\n\n oscillator(double frequency, double sample_rate, double amplitude = 1)\n : m_freq(frequency),\n m_rate(sample_rate),\n m_ampl(amplitude)\n {\n static_assert(std::is_floating_point::value,\n \"Sample type must be a floating point type\");\n\n m_cos_omega = cos(2 * M_PI * m_freq \/ m_rate);\n m_sin_omega = sin(2 * M_PI * m_freq \/ m_rate);\n m_cos1 = m_ampl * m_cos_omega;\n m_sin1 = -m_ampl * m_sin_omega;\n }\n\n template\n void operator()(std::array &output)\n {\n T cos0;\n T sin0;\n\n for (auto &out : output)\n {\n cos0 = m_cos_omega * m_cos1 - m_sin_omega * m_sin1;\n sin0 = m_sin_omega * m_cos1 + m_cos_omega * m_sin1;\n m_cos1 = cos0;\n m_sin1 = sin0;\n out = std::complex(cos0, sin0);\n }\n }\n\n double frequency() { return m_freq; }\n\n double sample_rate() { return m_rate; }\n\n double amplitude() { return m_ampl; }\n\nprivate:\n double m_freq;\n double m_rate;\n double m_ampl;\n\n double m_cos1;\n double m_sin1;\n double m_cos_omega;\n double m_sin_omega;\n};\n\n} \/* namespace comm *\/\n\n#endif \/* OSCILLATOR_HPP_ *\/\noscillator: refactor\/*\n * Copyright 2015 C. Brett Witherspoon\n *\/\n\n#ifndef OSCILLATOR_HPP_\n#define OSCILLATOR_HPP_\n\n#include \n\nnamespace comm\n{\n\/**\n *\n *\/\ntemplate\nclass oscillator\n{\npublic:\n using sample_type = T;\n\n oscillator(T frequency, T sample_rate, T amplitude = 1);\n\n template void operator()(U& output);\n\n T frequency() { return m_freq; }\n\n T sample_rate() { return m_rate; }\n\n T amplitude() { return m_ampl; }\n\nprivate:\n T m_freq;\n T m_rate;\n T m_ampl;\n T m_out1;\n T m_out2;\n T m_2cos_omega;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate\noscillator::oscillator(T frequency, T sample_rate, T amplitude)\n : m_freq(frequency),\n m_rate(sample_rate),\n m_ampl(amplitude)\n{\n static_assert(std::is_floating_point::value,\n \"Sample type must be a floating point type\");\n\n m_out1 = 0;\n m_out2 = -m_ampl * sin(2 * M_PI * m_freq \/ m_rate);\n m_2cos_omega = 2 * cos(2 * M_PI * m_freq \/ m_rate);\n}\n\ntemplate\ntemplate\nvoid oscillator::operator()(U& output)\n{\n for (auto &out0 : output)\n {\n out0 = m_2cos_omega * m_out1 - m_out2;\n m_out2 = m_out1;\n m_out1 = out0;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/**\n *\n *\/\ntemplate\nclass oscillator>\n{\npublic:\n using sample_type = std::complex;\n\n oscillator(T frequency, T sample_rate, T amplitude = 1);\n\n template void operator()(U& output);\n\n T frequency() { return m_freq; }\n\n T sample_rate() { return m_rate; }\n\n T amplitude() { return m_ampl; }\n\nprivate:\n T m_freq;\n T m_rate;\n T m_ampl;\n T m_cos1;\n T m_sin1;\n T m_cos_omega;\n T m_sin_omega;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate\noscillator>::oscillator(T frequency, T sample_rate, T amplitude)\n : m_freq(frequency),\n m_rate(sample_rate),\n m_ampl(amplitude)\n{\n static_assert(std::is_floating_point::value,\n \"Sample type must be a floating point type\");\n\n m_cos_omega = cos(2 * M_PI * m_freq \/ m_rate);\n m_sin_omega = sin(2 * M_PI * m_freq \/ m_rate);\n m_cos1 = m_ampl * m_cos_omega;\n m_sin1 = -m_ampl * m_sin_omega;\n}\n\ntemplate\ntemplate\nvoid oscillator>::operator()(U& output)\n{\n T cos0;\n T sin0;\n\n for (auto &out : output)\n {\n cos0 = m_cos_omega * m_cos1 - m_sin_omega * m_sin1;\n sin0 = m_sin_omega * m_cos1 + m_cos_omega * m_sin1;\n m_cos1 = cos0;\n m_sin1 = sin0;\n out = std::complex(cos0, sin0);\n }\n}\n\n} \/* namespace comm *\/\n\n#endif \/* OSCILLATOR_HPP_ *\/\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright (c) 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#ifndef CPM_CPM_SUPPORT_HPP\n#define CPM_CPM_SUPPORT_HPP\n\n#include \"..\/..\/lib\/cxxopts\/src\/cxxopts.hpp\"\n\nnamespace cpm {\n\nstruct cpm_registry {\n cpm_registry(void (*function)(cpm::benchmark<>&)){\n benchs.emplace_back(function);\n }\n\n static std::vector&)> benchs;\n};\n\ntemplate class TT, typename T>\nstruct is_specialization_of : std::false_type {};\n\ntemplate class TT, typename... Args>\nstruct is_specialization_of> : std::true_type {};\n\ntemplate\nstruct is_section : is_specialization_of> {};\n\n} \/\/end of namespace cpm\n\n\/\/Internal helpers\n\n#define CPM_UNIQUE_DETAIL(x, y) x##y\n#define CPM_UNIQUE(x, y) CPM_UNIQUE_DETAIL(x, y)\n#define CPM_UNIQUE_NAME(x) CPM_UNIQUE(x, __LINE__)\n\n\/\/Declarations of benchs functions\n\n#define CPM_BENCH() \\\n void CPM_UNIQUE_NAME(bench_) (cpm::benchmark<>& bench); \\\n namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(bench_)); } \\\n void CPM_UNIQUE_NAME(bench_) (cpm::benchmark<>& bench)\n\n\/\/Declaration of section functions\n\n#define CPM_SECTION(name) \\\n void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master); \\\n namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); } \\\n void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) { \\\n auto bench = master.multi(name);\n\n#define CPM_SECTION_O(name, W, R) \\\n void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master); \\\n namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); } \\\n void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) { \\\n auto bench = master.multi(name); \\\n bench.warmup = W; \\\n bench.repeat = R;\n\n#define CPM_SECTION_P(name, policy) \\\n void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master); \\\n namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); } \\\n void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) { \\\n auto bench = master.multi(name);\n\n#define CPM_SECTION_PO(name, policy, W, R) \\\n void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master); \\\n namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); } \\\n void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) { \\\n auto bench = master.multi(name); \\\n bench.warmup = W; \\\n bench.repeat = R;\n\n\/\/Normal versions for simple bench\n#define CPM_SIMPLE(...) bench.measure_simple(__VA_ARGS__);\n#define CPM_GLOBAL(...) bench.measure_global(__VA_ARGS__);\n#define CPM_TWO_PASS(...) bench.measure_two_pass(__VA_ARGS__);\n#define CPM_TWO_PASS_NS(...) bench.measure_two_pass(__VA_ARGS__);\n\n\/\/Versions with policies\n\n#define CPM_SIMPLE_P(policy, ...) \\\n static_assert(!cpm::is_section::value, \"CPM_SIMPLE_P cannot be used inside CPM_SECTION\"); \\\n bench.measure_simple(__VA_ARGS__);\n\n#define CPM_GLOBAL_P(policy, ...) \\\n static_assert(!cpm::is_section::value, \"CPM_GLOBAL_P cannot be used inside CPM_SECTION\"); \\\n bench.measure_global(__VA_ARGS__);\n\n#define CPM_TWO_PASS_P(policy, ...) \\\n static_assert(!cpm::is_section::value, \"CPM_TWO_PASS_P cannot be used inside CPM_SECTION\"); \\\n bench.measure_two_pass(__VA_ARGS__);\n\n#define CPM_TWO_PASS_NS_P(policy, ...) \\\n static_assert(!cpm::is_section::value, \"CPM_TWO_PASS_NS_P cannot be used inside CPM_SECTION\"); \\\n bench.template measure_two_pass(__VA_ARGS__);\n\n\/\/Direct bench functions\n\n#define CPM_DIRECT_BENCH_SIMPLE(...) CPM_BENCH() { CPM_SIMPLE(__VA_ARGS__); }\n#define CPM_DIRECT_BENCH_TWO_PASS(...) CPM_BENCH() { CPM_TWO_PASS(__VA_ARGS__); }\n#define CPM_DIRECT_BENCH_TWO_PASS_NS(...) CPM_BENCH() { CPM_TWO_PASS_NS(__VA_ARGS__); }\n\n\/\/Direct bench functions with policies\n\n#define CPM_DIRECT_BENCH_SIMPLE_P(policy,...) CPM_BENCH() { CPM_SIMPLE_P(POLICY(policy),__VA_ARGS__); }\n#define CPM_DIRECT_BENCH_TWO_PASS_P(policy,...) CPM_BENCH() { CPM_TWO_PASS_P(POLICY(policy),__VA_ARGS__); }\n#define CPM_DIRECT_BENCH_TWO_PASS_NS_P(policy,...) CPM_BENCH() { CPM_TWO_PASS_NS_P(POLICY(policy),__VA_ARGS__); }\n\n\/\/Direct section functions\n\n#define FE_1(WHAT, X) WHAT(X)\n#define FE_2(WHAT, X, ...) WHAT(X)FE_1(WHAT, __VA_ARGS__)\n#define FE_3(WHAT, X, ...) WHAT(X)FE_2(WHAT, __VA_ARGS__)\n#define FE_4(WHAT, X, ...) WHAT(X)FE_3(WHAT, __VA_ARGS__)\n#define FE_5(WHAT, X, ...) WHAT(X)FE_4(WHAT, __VA_ARGS__)\n#define FE_6(WHAT, X, ...) WHAT(X)FE_5(WHAT, __VA_ARGS__)\n#define FE_7(WHAT, X, ...) WHAT(X)FE_6(WHAT, __VA_ARGS__)\n#define FE_8(WHAT, X, ...) WHAT(X)FE_7(WHAT, __VA_ARGS__)\n\n#define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,NAME,...) NAME\n\n#define FOR_EACH(action,...) \\\n GET_MACRO(__VA_ARGS__,FE_8,FE_7,FE_6,FE_5,FE_4,FE_3,FE_2,FE_1)(action,__VA_ARGS__)\n\n#define FFE_1(WHAT, I, X) WHAT(I,X)\n#define FFE_2(WHAT, I, X, ...) WHAT(I,X)FFE_1(WHAT, I, __VA_ARGS__)\n#define FFE_3(WHAT, I, X, ...) WHAT(I,X)FFE_2(WHAT, I, __VA_ARGS__)\n#define FFE_4(WHAT, I, X, ...) WHAT(I,X)FFE_3(WHAT, I, __VA_ARGS__)\n#define FFE_5(WHAT, I, X, ...) WHAT(I,X)FFE_4(WHAT, I, __VA_ARGS__)\n#define FFE_6(WHAT, I, X, ...) WHAT(I,X)FFE_5(WHAT, I, __VA_ARGS__)\n#define FFE_7(WHAT, I, X, ...) WHAT(I,X)FFE_6(WHAT, I, __VA_ARGS__)\n#define FFE_8(WHAT, I, X, ...) WHAT(I,X)FFE_7(WHAT, I, __VA_ARGS__)\n\n#define F_FOR_EACH(action,I,...) \\\n GET_MACRO(__VA_ARGS__,FFE_8,FFE_7,FFE_6,FFE_5,FFE_4,FFE_3,FFE_2,FFE_1)(action,I,__VA_ARGS__)\n\n#define EMIT_TWO_PASS(init, X) CPM_TWO_PASS((X).first, init, (X).second);\n#define EMIT_TWO_PASS_NS(init, X) CPM_TWO_PASS_NS((X).first, init, (X).second);\n\n#define CPM_SECTION_FUNCTOR(name, ...) \\\n (std::make_pair(name, (__VA_ARGS__)))\n\n#define CPM_DIRECT_SECTION_TWO_PASS(name, init, ...) \\\n CPM_SECTION(name) \\\n F_FOR_EACH(EMIT_TWO_PASS, init, __VA_ARGS__) \\\n }\n\n#define CPM_DIRECT_SECTION_TWO_PASS_P(name, policy, init, ...) \\\n CPM_SECTION_P(name, POLICY(policy)) \\\n F_FOR_EACH(EMIT_TWO_PASS, init, __VA_ARGS__) \\\n }\n\n#define CPM_DIRECT_SECTION_TWO_PASS_NS(name, init, ...) \\\n CPM_SECTION(name) \\\n F_FOR_EACH(EMIT_TWO_PASS_NS, init, __VA_ARGS__) \\\n }\n\n#define CPM_DIRECT_SECTION_TWO_PASS_NS_P(name, policy, init, ...) \\\n CPM_SECTION_P(name, POLICY(policy)) \\\n F_FOR_EACH(EMIT_TWO_PASS_NS, init, __VA_ARGS__) \\\n }\n\n#define CPM_SECTION_INIT(...) (__VA_ARGS__)\n\n\/\/Helpers to create policy\n#define POLICY(...) __VA_ARGS__\n#define VALUES_POLICY(...) cpm::values_policy<__VA_ARGS__>\n#define NARY_POLICY(...) cpm::simple_nary_policy<__VA_ARGS__>\n#define STD_STOP_POLICY cpm::std_stop_policy\n#define STOP_POLICY(start, stop, add, mul) cpm::increasing_policy\n#define TIMEOUT_POLICY(start, stop, add, mul) cpm::increasing_policy\n\n#ifdef CPM_BENCHMARK\n\nint main(int argc, char* argv[]){\n cxxopts::Options options(argv[0], \"\");\n\n try {\n options.add_options()\n (\"n,name\", \"Benchmark name\", cxxopts::value())\n (\"t,tag\", \"Tag name\", cxxopts::value())\n (\"c,configuration\", \"Configuration\", cxxopts::value())\n (\"o,output\", \"Output folder\", cxxopts::value())\n (\"h,help\", \"Print help\")\n ;\n\n options.parse(argc, argv);\n\n if (options.count(\"help\")){\n std::cout << options.help({\"\"}) << std::endl;\n return 0;\n }\n\n } catch (const cxxopts::OptionException& e){\n std::cout << \"cpm: error parsing options: \" << e.what() << std::endl;\n return -1;\n }\n\n std::string output_folder{\".\/results\"};\n\n if (options.count(\"output\")){\n output_folder = options[\"output\"].as();\n }\n\n std::string benchmark_name{CPM_BENCHMARK};\n\n if (options.count(\"name\")){\n benchmark_name = options[\"name\"].as();\n }\n\n std::string tag;\n\n if (options.count(\"tag\")){\n tag = options[\"tag\"].as();\n }\n\n std::string configuration;\n\n if (options.count(\"configuration\")){\n configuration = options[\"configuration\"].as();\n }\n\n cpm::benchmark<> bench(benchmark_name, output_folder, tag, configuration);\n\n#ifdef CPM_WARMUP\n bench.warmup = CPM_WARMUP;\n#endif\n\n#ifdef CPM_REPEAT\n bench.repeat = CPM_REPEAT;\n#endif\n\n bench.begin();\n\n for(auto f : cpm::cpm_registry::benchs){\n f(bench);\n }\n\n return 0;\n}\n\nstd::vector&)> cpm::cpm_registry::benchs;\n\n#endif \/\/CPM_BENCHMARK\n\n#endif \/\/CPM_CPM_SUPPORT_HPP\nFix global construction dependency order\/\/=======================================================================\n\/\/ Copyright (c) 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#ifndef CPM_CPM_SUPPORT_HPP\n#define CPM_CPM_SUPPORT_HPP\n\n#include \"..\/..\/lib\/cxxopts\/src\/cxxopts.hpp\"\n\nnamespace cpm {\n\nstruct cpm_registry {\n cpm_registry(void (*function)(cpm::benchmark<>&)){\n benchs().emplace_back(function);\n }\n\n static std::vector&)>& benchs(){\n static std::vector&)> vec;\n return vec;\n }\n};\n\ntemplate class TT, typename T>\nstruct is_specialization_of : std::false_type {};\n\ntemplate class TT, typename... Args>\nstruct is_specialization_of> : std::true_type {};\n\ntemplate\nstruct is_section : is_specialization_of> {};\n\n} \/\/end of namespace cpm\n\n\/\/Internal helpers\n\n#define CPM_UNIQUE_DETAIL(x, y) x##y\n#define CPM_UNIQUE(x, y) CPM_UNIQUE_DETAIL(x, y)\n#define CPM_UNIQUE_NAME(x) CPM_UNIQUE(x, __LINE__)\n\n\/\/Declarations of benchs functions\n\n#define CPM_BENCH() \\\n void CPM_UNIQUE_NAME(bench_) (cpm::benchmark<>& bench); \\\n namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(bench_)); } \\\n void CPM_UNIQUE_NAME(bench_) (cpm::benchmark<>& bench)\n\n\/\/Declaration of section functions\n\n#define CPM_SECTION(name) \\\n void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master); \\\n namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); } \\\n void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) { \\\n auto bench = master.multi(name);\n\n#define CPM_SECTION_O(name, W, R) \\\n void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master); \\\n namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); } \\\n void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) { \\\n auto bench = master.multi(name); \\\n bench.warmup = W; \\\n bench.repeat = R;\n\n#define CPM_SECTION_P(name, policy) \\\n void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master); \\\n namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); } \\\n void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) { \\\n auto bench = master.multi(name);\n\n#define CPM_SECTION_PO(name, policy, W, R) \\\n void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master); \\\n namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); } \\\n void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) { \\\n auto bench = master.multi(name); \\\n bench.warmup = W; \\\n bench.repeat = R;\n\n\/\/Normal versions for simple bench\n#define CPM_SIMPLE(...) bench.measure_simple(__VA_ARGS__);\n#define CPM_GLOBAL(...) bench.measure_global(__VA_ARGS__);\n#define CPM_TWO_PASS(...) bench.measure_two_pass(__VA_ARGS__);\n#define CPM_TWO_PASS_NS(...) bench.measure_two_pass(__VA_ARGS__);\n\n\/\/Versions with policies\n\n#define CPM_SIMPLE_P(policy, ...) \\\n static_assert(!cpm::is_section::value, \"CPM_SIMPLE_P cannot be used inside CPM_SECTION\"); \\\n bench.measure_simple(__VA_ARGS__);\n\n#define CPM_GLOBAL_P(policy, ...) \\\n static_assert(!cpm::is_section::value, \"CPM_GLOBAL_P cannot be used inside CPM_SECTION\"); \\\n bench.measure_global(__VA_ARGS__);\n\n#define CPM_TWO_PASS_P(policy, ...) \\\n static_assert(!cpm::is_section::value, \"CPM_TWO_PASS_P cannot be used inside CPM_SECTION\"); \\\n bench.measure_two_pass(__VA_ARGS__);\n\n#define CPM_TWO_PASS_NS_P(policy, ...) \\\n static_assert(!cpm::is_section::value, \"CPM_TWO_PASS_NS_P cannot be used inside CPM_SECTION\"); \\\n bench.template measure_two_pass(__VA_ARGS__);\n\n\/\/Direct bench functions\n\n#define CPM_DIRECT_BENCH_SIMPLE(...) CPM_BENCH() { CPM_SIMPLE(__VA_ARGS__); }\n#define CPM_DIRECT_BENCH_TWO_PASS(...) CPM_BENCH() { CPM_TWO_PASS(__VA_ARGS__); }\n#define CPM_DIRECT_BENCH_TWO_PASS_NS(...) CPM_BENCH() { CPM_TWO_PASS_NS(__VA_ARGS__); }\n\n\/\/Direct bench functions with policies\n\n#define CPM_DIRECT_BENCH_SIMPLE_P(policy,...) CPM_BENCH() { CPM_SIMPLE_P(POLICY(policy),__VA_ARGS__); }\n#define CPM_DIRECT_BENCH_TWO_PASS_P(policy,...) CPM_BENCH() { CPM_TWO_PASS_P(POLICY(policy),__VA_ARGS__); }\n#define CPM_DIRECT_BENCH_TWO_PASS_NS_P(policy,...) CPM_BENCH() { CPM_TWO_PASS_NS_P(POLICY(policy),__VA_ARGS__); }\n\n\/\/Direct section functions\n\n#define FE_1(WHAT, X) WHAT(X)\n#define FE_2(WHAT, X, ...) WHAT(X)FE_1(WHAT, __VA_ARGS__)\n#define FE_3(WHAT, X, ...) WHAT(X)FE_2(WHAT, __VA_ARGS__)\n#define FE_4(WHAT, X, ...) WHAT(X)FE_3(WHAT, __VA_ARGS__)\n#define FE_5(WHAT, X, ...) WHAT(X)FE_4(WHAT, __VA_ARGS__)\n#define FE_6(WHAT, X, ...) WHAT(X)FE_5(WHAT, __VA_ARGS__)\n#define FE_7(WHAT, X, ...) WHAT(X)FE_6(WHAT, __VA_ARGS__)\n#define FE_8(WHAT, X, ...) WHAT(X)FE_7(WHAT, __VA_ARGS__)\n\n#define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,NAME,...) NAME\n\n#define FOR_EACH(action,...) \\\n GET_MACRO(__VA_ARGS__,FE_8,FE_7,FE_6,FE_5,FE_4,FE_3,FE_2,FE_1)(action,__VA_ARGS__)\n\n#define FFE_1(WHAT, I, X) WHAT(I,X)\n#define FFE_2(WHAT, I, X, ...) WHAT(I,X)FFE_1(WHAT, I, __VA_ARGS__)\n#define FFE_3(WHAT, I, X, ...) WHAT(I,X)FFE_2(WHAT, I, __VA_ARGS__)\n#define FFE_4(WHAT, I, X, ...) WHAT(I,X)FFE_3(WHAT, I, __VA_ARGS__)\n#define FFE_5(WHAT, I, X, ...) WHAT(I,X)FFE_4(WHAT, I, __VA_ARGS__)\n#define FFE_6(WHAT, I, X, ...) WHAT(I,X)FFE_5(WHAT, I, __VA_ARGS__)\n#define FFE_7(WHAT, I, X, ...) WHAT(I,X)FFE_6(WHAT, I, __VA_ARGS__)\n#define FFE_8(WHAT, I, X, ...) WHAT(I,X)FFE_7(WHAT, I, __VA_ARGS__)\n\n#define F_FOR_EACH(action,I,...) \\\n GET_MACRO(__VA_ARGS__,FFE_8,FFE_7,FFE_6,FFE_5,FFE_4,FFE_3,FFE_2,FFE_1)(action,I,__VA_ARGS__)\n\n#define EMIT_TWO_PASS(init, X) CPM_TWO_PASS((X).first, init, (X).second);\n#define EMIT_TWO_PASS_NS(init, X) CPM_TWO_PASS_NS((X).first, init, (X).second);\n\n#define CPM_SECTION_FUNCTOR(name, ...) \\\n (std::make_pair(name, (__VA_ARGS__)))\n\n#define CPM_DIRECT_SECTION_TWO_PASS(name, init, ...) \\\n CPM_SECTION(name) \\\n F_FOR_EACH(EMIT_TWO_PASS, init, __VA_ARGS__) \\\n }\n\n#define CPM_DIRECT_SECTION_TWO_PASS_P(name, policy, init, ...) \\\n CPM_SECTION_P(name, POLICY(policy)) \\\n F_FOR_EACH(EMIT_TWO_PASS, init, __VA_ARGS__) \\\n }\n\n#define CPM_DIRECT_SECTION_TWO_PASS_NS(name, init, ...) \\\n CPM_SECTION(name) \\\n F_FOR_EACH(EMIT_TWO_PASS_NS, init, __VA_ARGS__) \\\n }\n\n#define CPM_DIRECT_SECTION_TWO_PASS_NS_P(name, policy, init, ...) \\\n CPM_SECTION_P(name, POLICY(policy)) \\\n F_FOR_EACH(EMIT_TWO_PASS_NS, init, __VA_ARGS__) \\\n }\n\n#define CPM_SECTION_INIT(...) (__VA_ARGS__)\n\n\/\/Helpers to create policy\n#define POLICY(...) __VA_ARGS__\n#define VALUES_POLICY(...) cpm::values_policy<__VA_ARGS__>\n#define NARY_POLICY(...) cpm::simple_nary_policy<__VA_ARGS__>\n#define STD_STOP_POLICY cpm::std_stop_policy\n#define STOP_POLICY(start, stop, add, mul) cpm::increasing_policy\n#define TIMEOUT_POLICY(start, stop, add, mul) cpm::increasing_policy\n\n#ifdef CPM_BENCHMARK\n\nint main(int argc, char* argv[]){\n cxxopts::Options options(argv[0], \"\");\n\n try {\n options.add_options()\n (\"n,name\", \"Benchmark name\", cxxopts::value())\n (\"t,tag\", \"Tag name\", cxxopts::value())\n (\"c,configuration\", \"Configuration\", cxxopts::value())\n (\"o,output\", \"Output folder\", cxxopts::value())\n (\"h,help\", \"Print help\")\n ;\n\n options.parse(argc, argv);\n\n if (options.count(\"help\")){\n std::cout << options.help({\"\"}) << std::endl;\n return 0;\n }\n\n } catch (const cxxopts::OptionException& e){\n std::cout << \"cpm: error parsing options: \" << e.what() << std::endl;\n return -1;\n }\n\n std::string output_folder{\".\/results\"};\n\n if (options.count(\"output\")){\n output_folder = options[\"output\"].as();\n }\n\n std::string benchmark_name{CPM_BENCHMARK};\n\n if (options.count(\"name\")){\n benchmark_name = options[\"name\"].as();\n }\n\n std::string tag;\n\n if (options.count(\"tag\")){\n tag = options[\"tag\"].as();\n }\n\n std::string configuration;\n\n if (options.count(\"configuration\")){\n configuration = options[\"configuration\"].as();\n }\n\n cpm::benchmark<> bench(benchmark_name, output_folder, tag, configuration);\n\n#ifdef CPM_WARMUP\n bench.warmup = CPM_WARMUP;\n#endif\n\n#ifdef CPM_REPEAT\n bench.repeat = CPM_REPEAT;\n#endif\n\n bench.begin();\n\n for(auto f : cpm::cpm_registry::benchs()){\n f(bench);\n }\n\n return 0;\n}\n\n#endif \/\/CPM_BENCHMARK\n\n#endif \/\/CPM_CPM_SUPPORT_HPP\n<|endoftext|>"} {"text":"#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n\r\n#include \r\n#include \r\n\r\n#include \r\n\r\ntypedef enum {\r\n INSTALL_CIA,\r\n DELETE_CIA,\r\n DELETE_TITLE,\r\n LAUNCH_TITLE\r\n} Mode;\r\n\r\nint main(int argc, char **argv) {\r\n if(!platformInit()) {\r\n return 0;\r\n }\r\n\r\n bool ninjhax = platformIsNinjhax();\r\n\r\n std::vector extensions;\r\n extensions.push_back(\"cia\");\r\n\r\n MediaType destination = SD;\r\n Mode mode = INSTALL_CIA;\r\n bool exit = false;\r\n bool netInstall = false;\r\n u64 freeSpace = fsGetFreeSpace(destination);\r\n auto onLoop = [&]() {\r\n if(ninjhax && inputIsPressed(BUTTON_START)) {\r\n exit = true;\r\n return true;\r\n }\r\n\r\n bool breakLoop = false;\r\n\r\n if(inputIsPressed(BUTTON_L)) {\r\n if(destination == SD) {\r\n destination = NAND;\r\n } else {\r\n destination = SD;\r\n }\r\n\r\n freeSpace = fsGetFreeSpace(destination);\r\n if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {\r\n breakLoop = true;\r\n }\r\n }\r\n\r\n if(inputIsPressed(BUTTON_R)) {\r\n if(mode == INSTALL_CIA) {\r\n mode = DELETE_CIA;\r\n } else if(mode == DELETE_CIA) {\r\n mode = DELETE_TITLE;\r\n breakLoop = true;\r\n } else if(mode == DELETE_TITLE) {\r\n mode = LAUNCH_TITLE;\r\n } else if(mode == LAUNCH_TITLE) {\r\n mode = INSTALL_CIA;\r\n breakLoop = true;\r\n }\r\n }\r\n\r\n if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {\r\n netInstall = true;\r\n breakLoop = true;\r\n }\r\n\r\n std::stringstream stream;\r\n stream << \"Free Space: \" << freeSpace << \" bytes (\" << std::fixed << std::setprecision(2) << freeSpace \/ 1024.0f \/ 1024.0f << \"MB)\" << \"\\n\";\r\n stream << \"Destination: \" << (destination == NAND ? \"NAND\" : \"SD\") << \", Mode: \" << (mode == INSTALL_CIA ? \"Install CIA\" : mode == DELETE_CIA ? \"Delete CIA\" : mode == DELETE_TITLE ? \"Delete Title\" : \"Launch Title\") << \"\\n\";\r\n stream << \"L - Switch Destination, R - Switch Mode\" << \"\\n\";\r\n if(mode == INSTALL_CIA) {\r\n stream << \"X - Install all CIAs in the current directory\" << \"\\n\";\r\n stream << \"Y - Receive an app over the network\" << \"\\n\";\r\n } else if(mode == DELETE_CIA) {\r\n stream << \"X - Delete all CIAs in the current directory\" << \"\\n\";\r\n }\r\n\r\n if(ninjhax) {\r\n stream << \"START - Exit to launcher\" << \"\\n\";\r\n }\r\n\r\n std::string str = stream.str();\r\n screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) \/ 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);\r\n\r\n return breakLoop;\r\n };\r\n\r\n auto onProgress = [&](u64 pos, u64 totalSize) {\r\n std::stringstream details;\r\n details << \"(\" << std::fixed << std::setprecision(2) << ((double) pos \/ 1024.0 \/ 1024.0) << \"MB \/ \" << std::fixed << std::setprecision(2) << ((double) totalSize \/ 1024.0 \/ 1024.0) << \"MB)\" << \"\\n\";\r\n details << \"Press B to cancel.\";\r\n\r\n u32 progress = (u32) (((double) pos \/ (double) totalSize) * 100);\r\n uiDisplayProgress(TOP_SCREEN, \"Installing\", details.str(), true, progress);\r\n inputPoll();\r\n return !inputIsPressed(BUTTON_B);\r\n };\r\n\r\n while(platformIsRunning()) {\r\n std::string fileTarget;\r\n App appTarget;\r\n if(mode == INSTALL_CIA || mode == DELETE_CIA) {\r\n uiSelectFile(&fileTarget, \"\/\", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {\r\n if(inputIsPressed(BUTTON_X)) {\r\n std::stringstream confirmMsg;\r\n if(mode == INSTALL_CIA) {\r\n confirmMsg << \"Install \";\r\n } else {\r\n confirmMsg << \"Delete \";\r\n }\r\n\r\n confirmMsg << \"all CIAs in the current directory?\";\r\n if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {\r\n bool failed = false;\r\n std::vector contents = fsGetDirectoryContents(currDirectory);\r\n for(std::vector::iterator it = contents.begin(); it != contents.end(); it++) {\r\n std::string path = (*it).path;\r\n std::string fileName = (*it).name;\r\n if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {\r\n if(mode == INSTALL_CIA) {\r\n AppResult ret = appInstallFile(destination, path, onProgress);\r\n if(ret != APP_SUCCESS) {\r\n std::stringstream resultMsg;\r\n resultMsg << \"Install failed!\" << \"\\n\";\r\n resultMsg << fileName << \"\\n\";\r\n resultMsg << appGetResultString(ret) << \"\\n\";\r\n uiPrompt(TOP_SCREEN, resultMsg.str(), false);\r\n failed = true;\r\n break;\r\n }\r\n } else {\r\n if(!fsDelete(path)) {\r\n std::stringstream resultMsg;\r\n resultMsg << \"Delete failed!\" << \"\\n\";\r\n resultMsg << fileName << \"\\n\";\r\n resultMsg << platformGetErrorString(platformGetError()) << \"\\n\";\r\n uiPrompt(TOP_SCREEN, resultMsg.str(), false);\r\n failed = true;\r\n break;\r\n } else {\r\n updateList = true;\r\n }\r\n }\r\n }\r\n }\r\n\r\n if(!failed) {\r\n uiPrompt(TOP_SCREEN, \"Install succeeded!\\n\", false);\r\n }\r\n\r\n freeSpace = fsGetFreeSpace(destination);\r\n }\r\n }\r\n\r\n return onLoop();\r\n }, [&](const std::string path, bool &updateList) {\r\n std::stringstream confirmMsg;\r\n if(mode == INSTALL_CIA) {\r\n confirmMsg << \"Install \";\r\n } else {\r\n confirmMsg << \"Delete \";\r\n }\r\n\r\n confirmMsg << \"the selected CIA?\";\r\n if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {\r\n std::stringstream resultMsg;\r\n if(mode == INSTALL_CIA) {\r\n resultMsg << \"Install \";\r\n } else {\r\n resultMsg << \"Delete \";\r\n }\r\n\r\n if(mode == INSTALL_CIA) {\r\n AppResult ret = appInstallFile(destination, path, onProgress);\r\n if(ret == APP_SUCCESS) {\r\n resultMsg << \"succeeded!\";\r\n } else {\r\n resultMsg << \"failed!\" << \"\\n\";\r\n resultMsg << appGetResultString(ret) << \"\\n\";\r\n }\r\n } else {\r\n if(fsDelete(path)) {\r\n updateList = true;\r\n resultMsg << \"succeeded!\";\r\n } else {\r\n resultMsg << \"failed!\" << \"\\n\";\r\n resultMsg << platformGetErrorString(platformGetError()) << \"\\n\";\r\n }\r\n }\r\n\r\n uiPrompt(TOP_SCREEN, resultMsg.str(), false);\r\n\r\n freeSpace = fsGetFreeSpace(destination);\r\n }\r\n\r\n return false;\r\n });\r\n } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {\r\n uiDisplayMessage(BOTTOM_SCREEN, \"Loading title list...\");\r\n uiSelectApp(&appTarget, destination, [&](bool &updateList) {\r\n return onLoop();\r\n }, [&](App app, bool &updateList) {\r\n if(mode == DELETE_TITLE) {\r\n if(uiPrompt(TOP_SCREEN, \"Delete the selected title?\", true)) {\r\n updateList = true;\r\n uiDisplayMessage(TOP_SCREEN, \"Deleting title...\");\r\n AppResult ret = appDelete(app);\r\n\r\n std::stringstream resultMsg;\r\n resultMsg << \"Delete \";\r\n if(ret == APP_SUCCESS) {\r\n resultMsg << \"succeeded!\";\r\n } else {\r\n resultMsg << \"failed!\" << \"\\n\";\r\n resultMsg << appGetResultString(ret) << \"\\n\";\r\n }\r\n\r\n uiPrompt(TOP_SCREEN, resultMsg.str(), false);\r\n\r\n freeSpace = fsGetFreeSpace(destination);\r\n }\r\n } else if(mode == LAUNCH_TITLE) {\r\n if(uiPrompt(TOP_SCREEN, \"Launch the selected title?\", true)) {\r\n updateList = true;\r\n uiDisplayMessage(TOP_SCREEN, \"Launching title...\");\r\n AppResult ret = appLaunch(app);\r\n\r\n if(ret != APP_SUCCESS) {\r\n std::stringstream resultMsg;\r\n resultMsg << \"Launch failed!\" << \"\\n\";\r\n resultMsg << appGetResultString(ret) << \"\\n\";\r\n uiPrompt(TOP_SCREEN, resultMsg.str(), false);\r\n } else {\r\n while(true) {\r\n }\r\n }\r\n }\r\n }\r\n\r\n return false;\r\n });\r\n }\r\n\r\n if(netInstall && !exit) {\r\n netInstall = false;\r\n\r\n screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);\r\n\r\n RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);\r\n if(file.fd == NULL) {\r\n continue;\r\n }\r\n\r\n std::stringstream confirmStream;\r\n confirmStream << \"Install the received application?\" << \"\\n\";\r\n confirmStream << \"Size: \" << file.fileSize << \" bytes (\" << std::fixed << std::setprecision(2) << file.fileSize \/ 1024.0f \/ 1024.0f << \"MB)\" << \"\\n\";\r\n if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {\r\n AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);\r\n std::stringstream resultMsg;\r\n resultMsg << \"Install \";\r\n if(ret == APP_SUCCESS) {\r\n resultMsg << \"succeeded!\";\r\n } else {\r\n resultMsg << \"failed!\" << \"\\n\";\r\n resultMsg << appGetResultString(ret) << \"\\n\";\r\n }\r\n\r\n uiPrompt(TOP_SCREEN, resultMsg.str(), false);\r\n }\r\n\r\n fclose(file.fd);\r\n continue;\r\n }\r\n\r\n if(exit) {\r\n break;\r\n }\r\n }\r\n\r\n platformCleanup();\r\n return 0;\r\n}\r\nAdd NAND delete warning, return to network install screen after a successful network install.#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n\r\n#include \r\n#include \r\n\r\n#include \r\n\r\ntypedef enum {\r\n INSTALL_CIA,\r\n DELETE_CIA,\r\n DELETE_TITLE,\r\n LAUNCH_TITLE\r\n} Mode;\r\n\r\nint main(int argc, char **argv) {\r\n if(!platformInit()) {\r\n return 0;\r\n }\r\n\r\n bool ninjhax = platformIsNinjhax();\r\n\r\n std::vector extensions;\r\n extensions.push_back(\"cia\");\r\n\r\n MediaType destination = SD;\r\n Mode mode = INSTALL_CIA;\r\n bool exit = false;\r\n bool netInstall = false;\r\n u64 freeSpace = fsGetFreeSpace(destination);\r\n auto onLoop = [&]() {\r\n if(ninjhax && inputIsPressed(BUTTON_START)) {\r\n exit = true;\r\n return true;\r\n }\r\n\r\n bool breakLoop = false;\r\n\r\n if(inputIsPressed(BUTTON_L)) {\r\n if(destination == SD) {\r\n destination = NAND;\r\n } else {\r\n destination = SD;\r\n }\r\n\r\n freeSpace = fsGetFreeSpace(destination);\r\n if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {\r\n breakLoop = true;\r\n }\r\n }\r\n\r\n if(inputIsPressed(BUTTON_R)) {\r\n if(mode == INSTALL_CIA) {\r\n mode = DELETE_CIA;\r\n } else if(mode == DELETE_CIA) {\r\n mode = DELETE_TITLE;\r\n breakLoop = true;\r\n } else if(mode == DELETE_TITLE) {\r\n mode = LAUNCH_TITLE;\r\n } else if(mode == LAUNCH_TITLE) {\r\n mode = INSTALL_CIA;\r\n breakLoop = true;\r\n }\r\n }\r\n\r\n if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {\r\n netInstall = true;\r\n breakLoop = true;\r\n }\r\n\r\n std::stringstream stream;\r\n stream << \"Free Space: \" << freeSpace << \" bytes (\" << std::fixed << std::setprecision(2) << freeSpace \/ 1024.0f \/ 1024.0f << \"MB)\" << \"\\n\";\r\n stream << \"Destination: \" << (destination == NAND ? \"NAND\" : \"SD\") << \", Mode: \" << (mode == INSTALL_CIA ? \"Install CIA\" : mode == DELETE_CIA ? \"Delete CIA\" : mode == DELETE_TITLE ? \"Delete Title\" : \"Launch Title\") << \"\\n\";\r\n stream << \"L - Switch Destination, R - Switch Mode\" << \"\\n\";\r\n if(mode == INSTALL_CIA) {\r\n stream << \"X - Install all CIAs in the current directory\" << \"\\n\";\r\n stream << \"Y - Receive an app over the network\" << \"\\n\";\r\n } else if(mode == DELETE_CIA) {\r\n stream << \"X - Delete all CIAs in the current directory\" << \"\\n\";\r\n }\r\n\r\n if(ninjhax) {\r\n stream << \"START - Exit to launcher\" << \"\\n\";\r\n }\r\n\r\n std::string str = stream.str();\r\n screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) \/ 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);\r\n\r\n return breakLoop;\r\n };\r\n\r\n auto onProgress = [&](u64 pos, u64 totalSize) {\r\n std::stringstream details;\r\n details << \"(\" << std::fixed << std::setprecision(2) << ((double) pos \/ 1024.0 \/ 1024.0) << \"MB \/ \" << std::fixed << std::setprecision(2) << ((double) totalSize \/ 1024.0 \/ 1024.0) << \"MB)\" << \"\\n\";\r\n details << \"Press B to cancel.\";\r\n\r\n u32 progress = (u32) (((double) pos \/ (double) totalSize) * 100);\r\n uiDisplayProgress(TOP_SCREEN, \"Installing\", details.str(), true, progress);\r\n inputPoll();\r\n return !inputIsPressed(BUTTON_B);\r\n };\r\n\r\n while(platformIsRunning()) {\r\n std::string fileTarget;\r\n App appTarget;\r\n if(mode == INSTALL_CIA || mode == DELETE_CIA) {\r\n if(netInstall && !exit) {\r\n screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);\r\n\r\n RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);\r\n if(file.fd == NULL) {\r\n netInstall = false;\r\n continue;\r\n }\r\n\r\n std::stringstream confirmStream;\r\n confirmStream << \"Install the received application?\" << \"\\n\";\r\n confirmStream << \"Size: \" << file.fileSize << \" bytes (\" << std::fixed << std::setprecision(2) << file.fileSize \/ 1024.0f \/ 1024.0f << \"MB)\" << \"\\n\";\r\n if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {\r\n AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);\r\n std::stringstream resultMsg;\r\n resultMsg << \"Install \";\r\n if(ret == APP_SUCCESS) {\r\n resultMsg << \"succeeded!\";\r\n } else {\r\n resultMsg << \"failed!\" << \"\\n\";\r\n resultMsg << appGetResultString(ret) << \"\\n\";\r\n }\r\n\r\n uiPrompt(TOP_SCREEN, resultMsg.str(), false);\r\n }\r\n\r\n fclose(file.fd);\r\n continue;\r\n }\r\n\r\n uiSelectFile(&fileTarget, \"\/\", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {\r\n if(inputIsPressed(BUTTON_X)) {\r\n std::stringstream confirmMsg;\r\n if(mode == INSTALL_CIA) {\r\n confirmMsg << \"Install \";\r\n } else {\r\n confirmMsg << \"Delete \";\r\n }\r\n\r\n confirmMsg << \"all CIAs in the current directory?\";\r\n if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {\r\n bool failed = false;\r\n std::vector contents = fsGetDirectoryContents(currDirectory);\r\n for(std::vector::iterator it = contents.begin(); it != contents.end(); it++) {\r\n std::string path = (*it).path;\r\n std::string fileName = (*it).name;\r\n if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {\r\n if(mode == INSTALL_CIA) {\r\n AppResult ret = appInstallFile(destination, path, onProgress);\r\n if(ret != APP_SUCCESS) {\r\n std::stringstream resultMsg;\r\n resultMsg << \"Install failed!\" << \"\\n\";\r\n resultMsg << fileName << \"\\n\";\r\n resultMsg << appGetResultString(ret) << \"\\n\";\r\n uiPrompt(TOP_SCREEN, resultMsg.str(), false);\r\n failed = true;\r\n break;\r\n }\r\n } else {\r\n if(!fsDelete(path)) {\r\n std::stringstream resultMsg;\r\n resultMsg << \"Delete failed!\" << \"\\n\";\r\n resultMsg << fileName << \"\\n\";\r\n resultMsg << platformGetErrorString(platformGetError()) << \"\\n\";\r\n uiPrompt(TOP_SCREEN, resultMsg.str(), false);\r\n failed = true;\r\n break;\r\n } else {\r\n updateList = true;\r\n }\r\n }\r\n }\r\n }\r\n\r\n if(!failed) {\r\n uiPrompt(TOP_SCREEN, \"Install succeeded!\\n\", false);\r\n }\r\n\r\n freeSpace = fsGetFreeSpace(destination);\r\n }\r\n }\r\n\r\n return onLoop();\r\n }, [&](const std::string path, bool &updateList) {\r\n std::stringstream confirmMsg;\r\n if(mode == INSTALL_CIA) {\r\n confirmMsg << \"Install \";\r\n } else {\r\n confirmMsg << \"Delete \";\r\n }\r\n\r\n confirmMsg << \"the selected CIA?\";\r\n if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {\r\n std::stringstream resultMsg;\r\n if(mode == INSTALL_CIA) {\r\n resultMsg << \"Install \";\r\n } else {\r\n resultMsg << \"Delete \";\r\n }\r\n\r\n if(mode == INSTALL_CIA) {\r\n AppResult ret = appInstallFile(destination, path, onProgress);\r\n if(ret == APP_SUCCESS) {\r\n resultMsg << \"succeeded!\";\r\n } else {\r\n resultMsg << \"failed!\" << \"\\n\";\r\n resultMsg << appGetResultString(ret) << \"\\n\";\r\n }\r\n } else {\r\n if(fsDelete(path)) {\r\n updateList = true;\r\n resultMsg << \"succeeded!\";\r\n } else {\r\n resultMsg << \"failed!\" << \"\\n\";\r\n resultMsg << platformGetErrorString(platformGetError()) << \"\\n\";\r\n }\r\n }\r\n\r\n uiPrompt(TOP_SCREEN, resultMsg.str(), false);\r\n\r\n freeSpace = fsGetFreeSpace(destination);\r\n }\r\n\r\n return false;\r\n });\r\n } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {\r\n uiDisplayMessage(BOTTOM_SCREEN, \"Loading title list...\");\r\n uiSelectApp(&appTarget, destination, [&](bool &updateList) {\r\n return onLoop();\r\n }, [&](App app, bool &updateList) {\r\n if(mode == DELETE_TITLE) {\r\n if(uiPrompt(TOP_SCREEN, \"Delete the selected title?\", true) && (destination != NAND || uiPrompt(TOP_SCREEN, \"You are about to delete a title from the NAND.\\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\\nAre you sure you wish to continue?\", true))) {\r\n updateList = true;\r\n uiDisplayMessage(TOP_SCREEN, \"Deleting title...\");\r\n AppResult ret = appDelete(app);\r\n\r\n std::stringstream resultMsg;\r\n resultMsg << \"Delete \";\r\n if(ret == APP_SUCCESS) {\r\n resultMsg << \"succeeded!\";\r\n } else {\r\n resultMsg << \"failed!\" << \"\\n\";\r\n resultMsg << appGetResultString(ret) << \"\\n\";\r\n }\r\n\r\n uiPrompt(TOP_SCREEN, resultMsg.str(), false);\r\n\r\n freeSpace = fsGetFreeSpace(destination);\r\n }\r\n } else if(mode == LAUNCH_TITLE) {\r\n if(uiPrompt(TOP_SCREEN, \"Launch the selected title?\", true)) {\r\n updateList = true;\r\n uiDisplayMessage(TOP_SCREEN, \"Launching title...\");\r\n AppResult ret = appLaunch(app);\r\n\r\n if(ret != APP_SUCCESS) {\r\n std::stringstream resultMsg;\r\n resultMsg << \"Launch failed!\" << \"\\n\";\r\n resultMsg << appGetResultString(ret) << \"\\n\";\r\n uiPrompt(TOP_SCREEN, resultMsg.str(), false);\r\n } else {\r\n while(true) {\r\n }\r\n }\r\n }\r\n }\r\n\r\n return false;\r\n });\r\n }\r\n\r\n if(exit) {\r\n break;\r\n }\r\n }\r\n\r\n platformCleanup();\r\n return 0;\r\n}\r\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\n#ifdef __GNUG__\n#pragma implementation \"list.h\"\n#endif\n\n#include \"condor_common.h\"\n#include \"condor_config.h\"\n#include \"condor_network.h\"\n#include \"condor_io.h\"\n#include \"sched.h\"\n#include \"alloc.h\"\n#include \"get_daemon_addr.h\"\n#include \"condor_attributes.h\"\n#include \"list.h\"\n\nstatic char *_FileName_ = __FILE__;\t\t\/* Used by EXCEPT (see except.h) *\/\n\n#include \"condor_qmgr.h\"\n\ntemplate class List;\ntemplate class Item;\n\nchar\t*MyName;\nBOOLEAN\tTroubleReported;\nBOOLEAN All = FALSE;\nint nToProcess = 0;\nList ToProcess;\n\n\t\/\/ Prototypes of local interest\nvoid ProcArg(const char*);\nvoid notify_schedd();\nvoid usage();\nvoid handle_all();\n\nchar* DaemonName = NULL;\n\nint mode;\n\nvoid\nusage()\n{\n\tfprintf( stderr,\n\t\t\"Usage: %s [-n schedd_name] { -a | cluster | cluster.proc | user } ... \\n\",\n\t\tMyName\n\t);\n\texit( 1 );\n}\n\n\nint\nmain( int argc, char *argv[] )\n{\n\tchar\t*arg;\n\tchar\t**args = (char **)malloc(sizeof(char *)*(argc - 1)); \/\/ args of jobs to be deleted\n\tint\t\t\t\t\tnArgs = 0;\t\t\t\t\/\/ number of args to be deleted\n\tint\t\t\t\t\ti;\n\tQmgr_connection*\tq;\n\tchar*\tdaemonname;\n\tchar*\tcmd_str;\n\n\tMyName = strrchr( argv[0], DIR_DELIM_CHAR );\n\tif( !MyName ) {\n\t\tMyName = argv[0];\n\t} else {\n\t\tMyName++;\n\t}\n\n\tcmd_str = strchr( MyName, '_');\n\tif (cmd_str && strcmp(cmd_str, \"_hold\") == MATCH) {\n\t\tmode = HELD;\n\t} else {\n\t\tmode = REMOVED;\n\t}\n\n\tconfig( 0 );\n\n\tif( argc < 2 ) {\n\t\tusage();\n\t}\n\n#if !defined(WIN32)\n\tinstall_sig_handler(SIGPIPE, SIG_IGN );\n#endif\n\n\tfor( argv++; arg = *argv; argv++ ) {\n\t\tif( arg[0] == '-' && arg[1] == 'a' ) {\n\t\t\tAll = TRUE;\n\t\t} else {\n\t\t\tif( All ) {\n\t\t\t\tusage();\n\t\t\t}\n\t\t\tif ( arg[0] == '-' && arg[1] == 'n' ) {\n\t\t\t\t\/\/ use the given name as the schedd name to connect to\n\t\t\t\targv++;\n\t\t\t\tif( ! *argv ) {\n\t\t\t\t\tfprintf( stderr, \"%s: -n requires another argument\\n\", \n\t\t\t\t\t\t\t MyName);\n\t\t\t\t\texit(1);\n\t\t\t\t}\t\t\t\t\n\t\t\t\tif( !(DaemonName = get_daemon_name(*argv)) ) { \n\t\t\t\t\tfprintf( stderr, \"%s: unknown host %s\\n\", \n\t\t\t\t\t\t\t MyName, get_host_part(*argv) );\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\targs[nArgs] = arg;\n\t\t\t\tnArgs++;\n\t\t\t}\n\t\t}\n\t}\n\n\t\t\/\/ Open job queue \n\tq = ConnectQ(DaemonName);\n\tif( !q ) {\n\t\tif( DaemonName ) {\n\t\t\tfprintf( stderr, \"Failed to connect to queue manager %s\\n\", \n\t\t\t\t\t DaemonName );\n\t\t} else {\n\t\t\tfprintf( stderr, \"Failed to connect to local queue manager\\n\" );\n\t\t}\n\t\texit(1);\n\t}\n\n\tif( All ) {\n\t\thandle_all();\n\t} else {\n\t\t\t\/\/ Set status of requested jobs to REMOVED\/HELD\n\t\tfor(i = 0; i < nArgs; i++) {\n\t\t\tProcArg(args[i]);\n\t\t}\n\t}\n\n\t\/\/ Close job queue\n\tDisconnectQ(q);\n\n\t\/\/ Now tell the schedd what we did. We send the schedd the\n\t\/\/ KILL_FRGN_JOB command. We pass the number of jobs to\n\t\/\/ remove\/hold _unless_ one or more of the jobs are to be\n\t\/\/ removed\/held via cluster or via user name, in which case we say\n\t\/\/ \"-1\" jobs to remove\/hold. Telling the schedd there are \"-1\"\n\t\/\/ jobs to remove forces the schedd to scan the queue looking for\n\t\/\/ jobs which have a REMOVED\/HELD status. If all jobs to be removed\/held\n\t\/\/ are via a cluster.proc, we then send the schedd all the\n\t\/\/ cluster.proc numbers to save the schedd from having to scan the\n\t\/\/ entire queue.\n\tif ( nToProcess != 0 )\n\t\tnotify_schedd();\n\n#if defined(ALLOC_DEBUG)\n\tprint_alloc_stats();\n#endif\n\n\treturn 0;\n}\n\n\nextern \"C\" int SetSyscalls( int foo ) { return foo; }\n\n\nvoid\nnotify_schedd()\n{\n\tReliSock\t*sock;\n\tchar\t\t*scheddAddr;\n\tint\t\t\tcmd;\n\tPROC_ID\t\t*job_id;\n\tint \t\ti;\n\n\tif( (scheddAddr = get_schedd_addr(DaemonName)) == NULL ) {\n\t\tif( *DaemonName ) {\n\t\t\tfprintf( stderr, \"Can't find schedd address of %s\\n\", DaemonName);\n\t\t} else {\n\t\t\tfprintf( stderr, \"Can't find address of local schedd\\n\" );\n\t\t}\n\t\texit(1);\n\t}\n\n\t\t\/* Connect to the schedd *\/\n\tsock = new ReliSock;\n\tif(!sock->connect(scheddAddr)) {\n\t\tif( !TroubleReported ) {\n\t\t\tif( *DaemonName ) {\n\t\t\t\tfprintf( stderr, \"Error: Can't connect to schedd %s\\n\", \n\t\t\t\t\t\t DaemonName );\n\t\t\t} else {\n\t\t\t\tfprintf( stderr, \"Error: Can't connect to local schedd\\n\" );\n\t\t\t}\n\t\t\tTroubleReported = 1;\n\t\t}\n\t\tdelete sock;\n\t\treturn;\n\t}\n\n\tsock->encode();\n\n\tcmd = KILL_FRGN_JOB;\n\tif( !sock->code(cmd) ) {\n\t\tfprintf( stderr,\n\t\t\t\"Warning: can't send KILL_JOB command to condor scheduler\\n\" );\n\t\tdelete sock;\n\t\treturn;\n\t}\n\n\tif( !sock->code(nToProcess) ) {\n\t\tfprintf( stderr,\n\t\t\t\"Warning: can't send num jobs to process to schedd (%d)\\n\",nToProcess );\n\t\tdelete sock;\n\t\treturn;\n\t}\n\n\tToProcess.Rewind();\n\tfor (i=0;icode(*job_id) ) {\n\t\t\tfprintf( stderr,\n\t\t\t\t\"Error: can't send a proc_id to condor scheduler\\n\" );\n\t\t\tdelete sock;\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif( !sock->end_of_message() ) {\n\t\tfprintf( stderr,\n\t\t\t\"Warning: can't send end of message to condor scheduler\\n\" );\n\t\tdelete sock;\n\t\treturn;\n\t}\n\n\tdelete sock;\n}\n\n\nvoid ProcArg(const char* arg)\n{\n\tint\t\tc, p;\t\t\t\t\t\t\t\t\/\/ cluster\/proc #\n\tchar*\ttmp;\n\tPROC_ID *id;\n\n\tif(isdigit(*arg))\n\t\/\/ delete by cluster\/proc #\n\t{\n\t\tc = strtol(arg, &tmp, 10);\n\t\tif(c <= 0)\n\t\t{\n\t\t\tfprintf(stderr, \"Invalid cluster # from %s.\\n\", arg);\n\t\t\treturn;\n\t\t}\n\t\tif(*tmp == '\\0')\n\t\t\/\/ delete the cluster\n\t\t{\n\t\t\tchar constraint[250];\n\n\t\t\tsprintf(constraint, \"%s == %d\", ATTR_CLUSTER_ID, c);\n\n\t\t\tif (SetAttributeIntByConstraint(constraint,ATTR_JOB_STATUS,mode) < 0)\n\t\t\t{\n\t\t\t\tfprintf( stderr, \"Couldn't find\/%s cluster %d.\\n\",\n\t\t\t\t\t\t (mode==REMOVED)?\"remove\":\"hold\", c);\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"Cluster %d %s.\\n\", c,\n\t\t\t\t\t\t(mode==REMOVED)?\"removed\":\"held\");\n\t\t\t\tnToProcess = -1;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif(*tmp == '.')\n\t\t{\n\t\t\tp = strtol(tmp + 1, &tmp, 10);\n\t\t\tif(p < 0)\n\t\t\t{\n\t\t\t\tfprintf( stderr, \"Invalid proc # from %s.\\n\", arg);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(*tmp == '\\0')\n\t\t\t\/\/ delete a proc\n\t\t\t{\n\t\t\t\tif(SetAttributeInt(c, p, ATTR_JOB_STATUS, mode ) < 0)\n\t\t\t\t{\n\t\t\t\t\tfprintf( stderr, \"Couldn't find\/%s job %d.%d.\\n\",\n\t\t\t\t\t\t\t (mode==REMOVED)?\"remove\":\"hold\", c, p );\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(stdout, \"Job %d.%d %s.\\n\", c, p,\n\t\t\t\t\t\t\t(mode==REMOVED)?\"removed\":\"held\");\n\t\t\t\t\tif ( nToProcess != -1 ) {\n\t\t\t\t\t\tnToProcess++;\n\t\t\t\t\t\tid = new PROC_ID;\n\t\t\t\t\t\tid->proc = p;\n\t\t\t\t\t\tid->cluster = c;\n\t\t\t\t\t\tToProcess.Append(id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfprintf( stderr, \"Warning: unrecognized \\\"%s\\\" skipped.\\n\", arg );\n\t\t\treturn;\n\t\t}\n\t\tfprintf( stderr, \"Warning: unrecognized \\\"%s\\\" skipped.\\n\", arg );\n\t}\n\telse if(isalpha(*arg))\n\t\/\/ delete by user name\n\t{\n\t\tchar\tconstraint[1000];\n\n\t\tsprintf(constraint, \"Owner == \\\"%s\\\"\", arg);\n\t\tif(SetAttributeIntByConstraint(constraint,ATTR_JOB_STATUS,mode) < 0)\n\t\t{\n\t\t\tfprintf( stderr, \"Couldn't find\/%s user %s's job(s).\\n\",\n\t\t\t\t\t (mode==REMOVED)?\"remove\":\"hold\", arg );\n\t\t} else {\n\t\t\tfprintf(stdout, \"User %s's job(s) %s.\\n\", arg,\n\t\t\t\t\t(mode==REMOVED)?\"removed\":\"held\");\n\t\t\tnToProcess = -1;\n\t\t}\n\t}\n\telse \n\t{\n\t\tfprintf( stderr, \"Warning: unrecognized \\\"%s\\\" skipped.\\n\", arg );\n\t}\n}\n\nvoid\nhandle_all()\n{\n\tchar\tconstraint[1000];\n\n\t\t\/\/ Remove\/Hold all jobs... let queue management code decide\n\t\t\/\/ which ones we can and can not remove.\n\tsprintf(constraint, \"%s >= %d\", ATTR_CLUSTER_ID, 0 );\n\tif( SetAttributeIntByConstraint(constraint,ATTR_JOB_STATUS,mode) < 0 ) {\n\t\tfprintf( stdout, \"%s all of your jobs.\\n\",\n\t\t\t\t (mode==REMOVED)?\"Removed\":\"Held\" );\n\t} else {\n\t\tfprintf( stdout, \"%s all jobs.\\n\",\n\t\t\t\t (mode==REMOVED)?\"Removed\":\"Held\" );\n\t}\n\tnToProcess = -1;\n}\nremove unused daemonname parameter; include sig_install.h to get prototype of install_sig_handler\/***************************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\n#ifdef __GNUG__\n#pragma implementation \"list.h\"\n#endif\n\n#include \"condor_common.h\"\n#include \"condor_config.h\"\n#include \"condor_network.h\"\n#include \"condor_io.h\"\n#include \"sched.h\"\n#include \"alloc.h\"\n#include \"get_daemon_addr.h\"\n#include \"condor_attributes.h\"\n#include \"list.h\"\n#include \"sig_install.h\"\n\nstatic char *_FileName_ = __FILE__;\t\t\/* Used by EXCEPT (see except.h) *\/\n\n#include \"condor_qmgr.h\"\n\ntemplate class List;\ntemplate class Item;\n\nchar\t*MyName;\nBOOLEAN\tTroubleReported;\nBOOLEAN All = FALSE;\nint nToProcess = 0;\nList ToProcess;\n\n\t\/\/ Prototypes of local interest\nvoid ProcArg(const char*);\nvoid notify_schedd();\nvoid usage();\nvoid handle_all();\n\nchar* DaemonName = NULL;\n\nint mode;\n\nvoid\nusage()\n{\n\tfprintf( stderr,\n\t\t\"Usage: %s [-n schedd_name] { -a | cluster | cluster.proc | user } ... \\n\",\n\t\tMyName\n\t);\n\texit( 1 );\n}\n\n\nint\nmain( int argc, char *argv[] )\n{\n\tchar\t*arg;\n\tchar\t**args = (char **)malloc(sizeof(char *)*(argc - 1)); \/\/ args of jobs to be deleted\n\tint\t\t\t\t\tnArgs = 0;\t\t\t\t\/\/ number of args to be deleted\n\tint\t\t\t\t\ti;\n\tQmgr_connection*\tq;\n\tchar*\tcmd_str;\n\n\tMyName = strrchr( argv[0], DIR_DELIM_CHAR );\n\tif( !MyName ) {\n\t\tMyName = argv[0];\n\t} else {\n\t\tMyName++;\n\t}\n\n\tcmd_str = strchr( MyName, '_');\n\tif (cmd_str && strcmp(cmd_str, \"_hold\") == MATCH) {\n\t\tmode = HELD;\n\t} else {\n\t\tmode = REMOVED;\n\t}\n\n\tconfig( 0 );\n\n\tif( argc < 2 ) {\n\t\tusage();\n\t}\n\n#if !defined(WIN32)\n\tinstall_sig_handler(SIGPIPE, SIG_IGN );\n#endif\n\n\tfor( argv++; arg = *argv; argv++ ) {\n\t\tif( arg[0] == '-' && arg[1] == 'a' ) {\n\t\t\tAll = TRUE;\n\t\t} else {\n\t\t\tif( All ) {\n\t\t\t\tusage();\n\t\t\t}\n\t\t\tif ( arg[0] == '-' && arg[1] == 'n' ) {\n\t\t\t\t\/\/ use the given name as the schedd name to connect to\n\t\t\t\targv++;\n\t\t\t\tif( ! *argv ) {\n\t\t\t\t\tfprintf( stderr, \"%s: -n requires another argument\\n\", \n\t\t\t\t\t\t\t MyName);\n\t\t\t\t\texit(1);\n\t\t\t\t}\t\t\t\t\n\t\t\t\tif( !(DaemonName = get_daemon_name(*argv)) ) { \n\t\t\t\t\tfprintf( stderr, \"%s: unknown host %s\\n\", \n\t\t\t\t\t\t\t MyName, get_host_part(*argv) );\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\targs[nArgs] = arg;\n\t\t\t\tnArgs++;\n\t\t\t}\n\t\t}\n\t}\n\n\t\t\/\/ Open job queue \n\tq = ConnectQ(DaemonName);\n\tif( !q ) {\n\t\tif( DaemonName ) {\n\t\t\tfprintf( stderr, \"Failed to connect to queue manager %s\\n\", \n\t\t\t\t\t DaemonName );\n\t\t} else {\n\t\t\tfprintf( stderr, \"Failed to connect to local queue manager\\n\" );\n\t\t}\n\t\texit(1);\n\t}\n\n\tif( All ) {\n\t\thandle_all();\n\t} else {\n\t\t\t\/\/ Set status of requested jobs to REMOVED\/HELD\n\t\tfor(i = 0; i < nArgs; i++) {\n\t\t\tProcArg(args[i]);\n\t\t}\n\t}\n\n\t\/\/ Close job queue\n\tDisconnectQ(q);\n\n\t\/\/ Now tell the schedd what we did. We send the schedd the\n\t\/\/ KILL_FRGN_JOB command. We pass the number of jobs to\n\t\/\/ remove\/hold _unless_ one or more of the jobs are to be\n\t\/\/ removed\/held via cluster or via user name, in which case we say\n\t\/\/ \"-1\" jobs to remove\/hold. Telling the schedd there are \"-1\"\n\t\/\/ jobs to remove forces the schedd to scan the queue looking for\n\t\/\/ jobs which have a REMOVED\/HELD status. If all jobs to be removed\/held\n\t\/\/ are via a cluster.proc, we then send the schedd all the\n\t\/\/ cluster.proc numbers to save the schedd from having to scan the\n\t\/\/ entire queue.\n\tif ( nToProcess != 0 )\n\t\tnotify_schedd();\n\n#if defined(ALLOC_DEBUG)\n\tprint_alloc_stats();\n#endif\n\n\treturn 0;\n}\n\n\nextern \"C\" int SetSyscalls( int foo ) { return foo; }\n\n\nvoid\nnotify_schedd()\n{\n\tReliSock\t*sock;\n\tchar\t\t*scheddAddr;\n\tint\t\t\tcmd;\n\tPROC_ID\t\t*job_id;\n\tint \t\ti;\n\n\tif( (scheddAddr = get_schedd_addr(DaemonName)) == NULL ) {\n\t\tif( *DaemonName ) {\n\t\t\tfprintf( stderr, \"Can't find schedd address of %s\\n\", DaemonName);\n\t\t} else {\n\t\t\tfprintf( stderr, \"Can't find address of local schedd\\n\" );\n\t\t}\n\t\texit(1);\n\t}\n\n\t\t\/* Connect to the schedd *\/\n\tsock = new ReliSock;\n\tif(!sock->connect(scheddAddr)) {\n\t\tif( !TroubleReported ) {\n\t\t\tif( *DaemonName ) {\n\t\t\t\tfprintf( stderr, \"Error: Can't connect to schedd %s\\n\", \n\t\t\t\t\t\t DaemonName );\n\t\t\t} else {\n\t\t\t\tfprintf( stderr, \"Error: Can't connect to local schedd\\n\" );\n\t\t\t}\n\t\t\tTroubleReported = 1;\n\t\t}\n\t\tdelete sock;\n\t\treturn;\n\t}\n\n\tsock->encode();\n\n\tcmd = KILL_FRGN_JOB;\n\tif( !sock->code(cmd) ) {\n\t\tfprintf( stderr,\n\t\t\t\"Warning: can't send KILL_JOB command to condor scheduler\\n\" );\n\t\tdelete sock;\n\t\treturn;\n\t}\n\n\tif( !sock->code(nToProcess) ) {\n\t\tfprintf( stderr,\n\t\t\t\"Warning: can't send num jobs to process to schedd (%d)\\n\",nToProcess );\n\t\tdelete sock;\n\t\treturn;\n\t}\n\n\tToProcess.Rewind();\n\tfor (i=0;icode(*job_id) ) {\n\t\t\tfprintf( stderr,\n\t\t\t\t\"Error: can't send a proc_id to condor scheduler\\n\" );\n\t\t\tdelete sock;\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif( !sock->end_of_message() ) {\n\t\tfprintf( stderr,\n\t\t\t\"Warning: can't send end of message to condor scheduler\\n\" );\n\t\tdelete sock;\n\t\treturn;\n\t}\n\n\tdelete sock;\n}\n\n\nvoid ProcArg(const char* arg)\n{\n\tint\t\tc, p;\t\t\t\t\t\t\t\t\/\/ cluster\/proc #\n\tchar*\ttmp;\n\tPROC_ID *id;\n\n\tif(isdigit(*arg))\n\t\/\/ delete by cluster\/proc #\n\t{\n\t\tc = strtol(arg, &tmp, 10);\n\t\tif(c <= 0)\n\t\t{\n\t\t\tfprintf(stderr, \"Invalid cluster # from %s.\\n\", arg);\n\t\t\treturn;\n\t\t}\n\t\tif(*tmp == '\\0')\n\t\t\/\/ delete the cluster\n\t\t{\n\t\t\tchar constraint[250];\n\n\t\t\tsprintf(constraint, \"%s == %d\", ATTR_CLUSTER_ID, c);\n\n\t\t\tif (SetAttributeIntByConstraint(constraint,ATTR_JOB_STATUS,mode) < 0)\n\t\t\t{\n\t\t\t\tfprintf( stderr, \"Couldn't find\/%s cluster %d.\\n\",\n\t\t\t\t\t\t (mode==REMOVED)?\"remove\":\"hold\", c);\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"Cluster %d %s.\\n\", c,\n\t\t\t\t\t\t(mode==REMOVED)?\"removed\":\"held\");\n\t\t\t\tnToProcess = -1;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif(*tmp == '.')\n\t\t{\n\t\t\tp = strtol(tmp + 1, &tmp, 10);\n\t\t\tif(p < 0)\n\t\t\t{\n\t\t\t\tfprintf( stderr, \"Invalid proc # from %s.\\n\", arg);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(*tmp == '\\0')\n\t\t\t\/\/ delete a proc\n\t\t\t{\n\t\t\t\tif(SetAttributeInt(c, p, ATTR_JOB_STATUS, mode ) < 0)\n\t\t\t\t{\n\t\t\t\t\tfprintf( stderr, \"Couldn't find\/%s job %d.%d.\\n\",\n\t\t\t\t\t\t\t (mode==REMOVED)?\"remove\":\"hold\", c, p );\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(stdout, \"Job %d.%d %s.\\n\", c, p,\n\t\t\t\t\t\t\t(mode==REMOVED)?\"removed\":\"held\");\n\t\t\t\t\tif ( nToProcess != -1 ) {\n\t\t\t\t\t\tnToProcess++;\n\t\t\t\t\t\tid = new PROC_ID;\n\t\t\t\t\t\tid->proc = p;\n\t\t\t\t\t\tid->cluster = c;\n\t\t\t\t\t\tToProcess.Append(id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfprintf( stderr, \"Warning: unrecognized \\\"%s\\\" skipped.\\n\", arg );\n\t\t\treturn;\n\t\t}\n\t\tfprintf( stderr, \"Warning: unrecognized \\\"%s\\\" skipped.\\n\", arg );\n\t}\n\telse if(isalpha(*arg))\n\t\/\/ delete by user name\n\t{\n\t\tchar\tconstraint[1000];\n\n\t\tsprintf(constraint, \"Owner == \\\"%s\\\"\", arg);\n\t\tif(SetAttributeIntByConstraint(constraint,ATTR_JOB_STATUS,mode) < 0)\n\t\t{\n\t\t\tfprintf( stderr, \"Couldn't find\/%s user %s's job(s).\\n\",\n\t\t\t\t\t (mode==REMOVED)?\"remove\":\"hold\", arg );\n\t\t} else {\n\t\t\tfprintf(stdout, \"User %s's job(s) %s.\\n\", arg,\n\t\t\t\t\t(mode==REMOVED)?\"removed\":\"held\");\n\t\t\tnToProcess = -1;\n\t\t}\n\t}\n\telse \n\t{\n\t\tfprintf( stderr, \"Warning: unrecognized \\\"%s\\\" skipped.\\n\", arg );\n\t}\n}\n\nvoid\nhandle_all()\n{\n\tchar\tconstraint[1000];\n\n\t\t\/\/ Remove\/Hold all jobs... let queue management code decide\n\t\t\/\/ which ones we can and can not remove.\n\tsprintf(constraint, \"%s >= %d\", ATTR_CLUSTER_ID, 0 );\n\tif( SetAttributeIntByConstraint(constraint,ATTR_JOB_STATUS,mode) < 0 ) {\n\t\tfprintf( stdout, \"%s all of your jobs.\\n\",\n\t\t\t\t (mode==REMOVED)?\"Removed\":\"Held\" );\n\t} else {\n\t\tfprintf( stdout, \"%s all jobs.\\n\",\n\t\t\t\t (mode==REMOVED)?\"Removed\":\"Held\" );\n\t}\n\tnToProcess = -1;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include <3ds.h>\n\n#include \"constants.h\"\n#include \"patches.h\"\n\n#define log(...) fprintf(stderr, __VA_ARGS__)\n\nint main(int argc, char** argv)\n{\n\tgfxInitDefault();\n\tconsoleInit(GFX_TOP, NULL);\n\tGetVersionConstants();\n PatchSrvAccess();\n\n\/\/ ONLY UNCOMMENT AFTER CUSTOMIZING PatchProcessWrapper\n \/\/ svcBackdoor(PatchProcessWrapper);\n \/\/ log(\"[0x%08X] - Patched process\\n\", ret);\n\n\t\/\/ Main loop\n\twhile (aptMainLoop())\n\t{\n\t\thidScanInput();\n\n\t\tu32 kDown = hidKeysDown();\n\t\tif (kDown & KEY_START)\n\t\t\tbreak;\n\t\tgspWaitForVBlank();\n\t}\n\n\tgfxExit();\n\treturn 0;\n}\nmain.cpp: Fix indentation#include \n#include \n#include \n\n#include <3ds.h>\n\n#include \"constants.h\"\n#include \"patches.h\"\n\n#define log(...) fprintf(stderr, __VA_ARGS__)\n\nint main(int argc, char** argv)\n{\n gfxInitDefault();\n consoleInit(GFX_TOP, NULL);\n GetVersionConstants();\n PatchSrvAccess();\n\n\/\/ ONLY UNCOMMENT AFTER CUSTOMIZING PatchProcessWrapper\n \/\/ svcBackdoor(PatchProcessWrapper);\n \/\/ log(\"[0x%08X] - Patched process\\n\", ret);\n\n \/\/ Main loop\n while (aptMainLoop())\n {\n hidScanInput();\n\n u32 kDown = hidKeysDown();\n if (kDown & KEY_START)\n break;\n gspWaitForVBlank();\n }\n\n gfxExit();\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2015 Aldebaran\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#ifndef ROS_ENV_HPP\n#define ROS_ENV_HPP\n\n\/*\n* ROS includes\n*\/\n#include \n\n\n\/*\n* ALDEBARAN includes\n*\/\n#include \n\n#include \n\n#include \n\nnamespace alros\n{\nnamespace ros_env\n{\n\n\/** Queries NAOqi to get the IP\n * @param network_interface the name of the network interface to use. \"eth0\" by default. If you put your NAO in\n * tethering mode, you will need to put \"tether\"\n *\/\nstatic std::string getROSIP(std::string network_interface)\n{\n if (network_interface.empty())\n network_interface = \"eth0\";\n typedef std::map< std::string, std::vector > Map_IP;\n static const std::string ip = static_cast(qi::os::hostIPAddrs())[network_interface][0];\n return ip;\n}\n\nstatic std::string getPrefix()\n{\n return \"alrosbridge\";\n}\n\nstatic void setMasterURI( const std::string& uri, const std::string& network_interface )\n{\n if (ros::isInitialized() )\n {\n std::cout << \"stopping ros init\" << std::endl;\n ros::shutdown();\n }\n\n setenv(\"ROS_MASTER_URI\", uri.c_str(), 1);\n\n std::string my_master = \"__master=\"+uri;\n std::map< std::string, std::string > remap;\n remap[\"__master\"] = uri;\n remap[\"__ip\"] = ::alros::ros_env::getROSIP(network_interface);\n \/\/ init ros without a sigint-handler in order to shutdown correctly by naoqi\n ros::init( remap, ::alros::ros_env::getPrefix(), ros::init_options::NoSigintHandler );\n \/\/ to prevent shutdown based on no existing nodehandle\n ros::start();\n\n std::cout << \"using master ip: \" << ros::master::getURI() << std::endl;\n}\n\nstatic std::string getMasterURI( )\n{\n return getenv(\"ROS_MASTER_URI\");\n}\n\nstatic std::string getCMakePrefixPath()\n{\n char *cMakePrefixPath = getenv( \"CMAKE_PREFIX_PATH\" );\n if (cMakePrefixPath != NULL) {\n return getenv( \"CMAKE_PREFIX_PATH\" );\n }\n return \"\";\n}\n\nstatic void adjustSDKPrefix()\n{\n std::string cmake_prefix = alros::ros_env::getCMakePrefixPath();\n std::vector prefixes;\n boost::split( prefixes, cmake_prefix, boost::is_any_of(\":\") );\n\n for (size_t i=0; iros_env.hpp write error message when network interface is not found\/*\n * Copyright 2015 Aldebaran\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#ifndef ROS_ENV_HPP\n#define ROS_ENV_HPP\n\n\/*\n* ROS includes\n*\/\n#include \n\n\n\/*\n* ALDEBARAN includes\n*\/\n#include \n\n#include \n\n#include \n\nnamespace alros\n{\nnamespace ros_env\n{\n\n\/** Queries NAOqi to get the IP\n * @param network_interface the name of the network interface to use. \"eth0\" by default. If you put your NAO in\n * tethering mode, you will need to put \"tether\"\n *\/\nstatic std::string getROSIP(std::string network_interface)\n{\n if (network_interface.empty())\n network_interface = \"eth0\";\n\n typedef std::map< std::string, std::vector > Map_IP;\n Map_IP map_ip = static_cast(qi::os::hostIPAddrs());\n if ( map_ip.find(network_interface) == map_ip.end() ) {\n std::cerr << \"Could not find network interface named \" << network_interface << \", pssible interfaces are ... \";\n for (Map_IP::iterator it=map_ip.begin(); it!=map_ip.end(); ++it) std::cerr << it->first << \" \";\n std::cerr << std::endl;\n exit(1);\n }\n\n static const std::string ip = map_ip[network_interface][0];\n return ip;\n}\n\nstatic std::string getPrefix()\n{\n return \"alrosbridge\";\n}\n\nstatic void setMasterURI( const std::string& uri, const std::string& network_interface )\n{\n if (ros::isInitialized() )\n {\n std::cout << \"stopping ros init\" << std::endl;\n ros::shutdown();\n }\n\n setenv(\"ROS_MASTER_URI\", uri.c_str(), 1);\n\n std::string my_master = \"__master=\"+uri;\n std::map< std::string, std::string > remap;\n remap[\"__master\"] = uri;\n remap[\"__ip\"] = ::alros::ros_env::getROSIP(network_interface);\n \/\/ init ros without a sigint-handler in order to shutdown correctly by naoqi\n ros::init( remap, ::alros::ros_env::getPrefix(), ros::init_options::NoSigintHandler );\n \/\/ to prevent shutdown based on no existing nodehandle\n ros::start();\n\n std::cout << \"using master ip: \" << ros::master::getURI() << std::endl;\n}\n\nstatic std::string getMasterURI( )\n{\n return getenv(\"ROS_MASTER_URI\");\n}\n\nstatic std::string getCMakePrefixPath()\n{\n char *cMakePrefixPath = getenv( \"CMAKE_PREFIX_PATH\" );\n if (cMakePrefixPath != NULL) {\n return getenv( \"CMAKE_PREFIX_PATH\" );\n }\n return \"\";\n}\n\nstatic void adjustSDKPrefix()\n{\n std::string cmake_prefix = alros::ros_env::getCMakePrefixPath();\n std::vector prefixes;\n boost::split( prefixes, cmake_prefix, boost::is_any_of(\":\") );\n\n for (size_t i=0; i"} {"text":"\/*!\n \\file path.inl\n \\brief Filesystem path wrapper inline implementation\n \\author Ivan Shynkarenka\n \\date 11.08.2016\n \\copyright MIT License\n*\/\n\nnamespace CppCommon {\n\ninline Path& Path::operator\/=(const std::string& path)\n{\n if (_path.empty())\n _path = path;\n else\n {\n char last = _path[_path.size() - 1];\n if ((last == '\\\\') || (last == '\/'))\n _path += path;\n else\n {\n _path += separator();\n _path += path;\n }\n }\n}\n\ninline char Path::separator()\n{\n#if defined(_WIN32) || defined(_WIN64)\n return '\\\\';\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n return '\/';\n#endif\n}\n\ninline void swap(Path& path1, Path& path2)\n{\n using std::swap;\n swap(path1._path, path2._path);\n}\n\n} \/\/ namespace CppCommon\nBugfix\/*!\n \\file path.inl\n \\brief Filesystem path wrapper inline implementation\n \\author Ivan Shynkarenka\n \\date 11.08.2016\n \\copyright MIT License\n*\/\n\nnamespace CppCommon {\n\ninline Path& Path::operator\/=(const std::string& path)\n{\n if (_path.empty())\n _path = path;\n else\n {\n char last = _path[_path.size() - 1];\n if ((last == '\\\\') || (last == '\/'))\n _path += path;\n else\n {\n _path += separator();\n _path += path;\n }\n }\n\n return *this;\n}\n\ninline char Path::separator()\n{\n#if defined(_WIN32) || defined(_WIN64)\n return '\\\\';\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n return '\/';\n#endif\n}\n\ninline void swap(Path& path1, Path& path2)\n{\n using std::swap;\n swap(path1._path, path2._path);\n}\n\n} \/\/ namespace CppCommon\n<|endoftext|>"} {"text":"\/\/ This file is part of NameTag.\n\/\/\n\/\/ Copyright 2013 by Institute of Formal and Applied Linguistics, Faculty of\n\/\/ Mathematics and Physics, Charles University in Prague, Czech Republic.\n\/\/\n\/\/ NameTag 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\/\/ NameTag 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 NameTag. If not, see .\n\n#include \n#include \n#include \n\n#include \"ner\/ner.h\"\n#include \"utils\/input.h\"\n\nusing namespace ufal::nametag;\n\nstatic void recognize_vertical(const ner& recognizer);\nstatic void recognize_untokenized(const ner& recognizer);\n\nint main(int argc, char* argv[]) {\n bool use_vertical = false;\n\n int argi = 1;\n if (argi < argc && strcmp(argv[argi], \"-v\") == 0) argi++, use_vertical = true;\n if (argi >= argc) runtime_errorf(\"Usage: %s [-v] ner_model\", argv[0]);\n\n eprintf(\"Loading ner: \");\n unique_ptr recognizer(ner::load(argv[argi]));\n if (!recognizer) runtime_errorf(\"Cannot load ner from file '%s'!\", argv[argi]);\n eprintf(\"done\\n\");\n\n eprintf(\"Recognizing: \");\n clock_t now = clock();\n if (use_vertical) recognize_vertical(*recognizer);\n else recognize_untokenized(*recognizer);\n eprintf(\"done, in %.3f seconds.\\n\", (clock() - now) \/ double(CLOCKS_PER_SEC));\n\n return 0;\n}\n\nvoid recognize_vertical(const ner& recognizer) {\n string line;\n unsigned total_lines = 0;\n\n vector words;\n vector forms;\n vector entities;\n string entity_ids, entity_text;\n\n for (bool not_eof = true; not_eof; ) {\n \/\/ Read sentence\n words.clear();\n forms.clear();\n while ((not_eof = getline(stdin, line)) && !line.empty()) {\n auto tab = line.find('\\t');\n words.emplace_back(tab == string::npos ? line : line.substr(0, tab));\n forms.emplace_back(words.back());\n }\n\n \/\/ Find named entities in the sentence\n if (!forms.empty()) {\n recognizer.recognize(forms, entities);\n\n for (auto& entity : entities) {\n entity_ids.clear();\n entity_text.clear();\n for (auto i = entity.start; i < entity.start + entity.length; i++) {\n if (i > entity.start) {\n entity_ids += ',';\n entity_text += ' ';\n }\n entity_ids += to_string(total_lines + i + 1);\n entity_text += words[i];\n }\n printf(\"%s\\t%s\\t%s\\n\", entity_ids.c_str(), entity.type.c_str(), entity_text.c_str());\n }\n }\n\n total_lines += forms.size() + 1;\n }\n}\n\nstatic void encode_entities_and_print(const char* text, size_t length);\n\nvoid recognize_untokenized(const ner& recognizer) {\n string line, text;\n vector entities;\n vector entity_ends;\n\n for (bool not_eof = true; not_eof; ) {\n \/\/ Read block of text\n text.clear();\n while ((not_eof = getline(stdin, line)) && !line.empty()) {\n text += line;\n text += '\\n';\n }\n if (not_eof) text += '\\n';\n\n \/\/ Tokenize the text and find named entities\n size_t unprinted = 0;\n recognizer.tokenize_and_recognize(text.c_str(), entities);\n for (auto& entity : entities) {\n \/\/ Close entities that end sooned than current entity\n while (!entity_ends.empty() && entity_ends.back() < entity.start) {\n if (unprinted < entity_ends.back()) encode_entities_and_print(text.c_str() + unprinted, entity_ends.back() - unprinted);\n unprinted = entity_ends.back();\n entity_ends.pop_back();\n fputs(\"<\/ne>\", stdout);\n }\n\n \/\/ Print text just before the entity, open it and add end to the stack\n if (unprinted < entity.start) encode_entities_and_print(text.c_str() + unprinted, entity.start - unprinted);\n unprinted = entity.start;\n printf(\"\", entity.type.c_str());\n entity_ends.push_back(entity.start + entity.length);\n }\n\n \/\/ Close unclosed entities\n while (!entity_ends.empty()) {\n if (unprinted < entity_ends.back()) encode_entities_and_print(text.c_str() + unprinted, entity_ends.back() - unprinted);\n unprinted = entity_ends.back();\n entity_ends.pop_back();\n fputs(\"<\/ne>\", stdout);\n }\n \/\/ Write rest of the text (should be just spaces)\n if (unprinted < text.size()) encode_entities_and_print(text.c_str() + unprinted, text.size() - unprinted);\n\n if (not_eof) printf(\"\\n\");\n }\n}\n\nvoid encode_entities_and_print(const char* text, size_t length) {\n const char* to_print = text;\n while (length) {\n while (length && *text != '<' && *text != '>' && *text != '&' && *text != '\"')\n text++, length--;\n\n if (length) {\n if (to_print < text) fwrite(to_print, 1, text - to_print, stdout);\n fputs(*text == '<' ? \"<\" : *text == '>' ? \">\" : *text == '&' ? \"&\" : \""\", stdout);\n text++, length--;\n to_print = text;\n }\n }\n if (to_print < text) fwrite(to_print, 1, text - to_print, stdout);\n}\nRemove surplus printf(\"\\n\"), use quotation marks...\/\/ This file is part of NameTag.\n\/\/\n\/\/ Copyright 2013 by Institute of Formal and Applied Linguistics, Faculty of\n\/\/ Mathematics and Physics, Charles University in Prague, Czech Republic.\n\/\/\n\/\/ NameTag 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\/\/ NameTag 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 NameTag. If not, see .\n\n#include \n#include \n#include \n\n#include \"ner\/ner.h\"\n#include \"utils\/input.h\"\n\nusing namespace ufal::nametag;\n\nstatic void recognize_vertical(const ner& recognizer);\nstatic void recognize_untokenized(const ner& recognizer);\n\nint main(int argc, char* argv[]) {\n bool use_vertical = false;\n\n int argi = 1;\n if (argi < argc && strcmp(argv[argi], \"-v\") == 0) argi++, use_vertical = true;\n if (argi >= argc) runtime_errorf(\"Usage: %s [-v] ner_model\", argv[0]);\n\n eprintf(\"Loading ner: \");\n unique_ptr recognizer(ner::load(argv[argi]));\n if (!recognizer) runtime_errorf(\"Cannot load ner from file '%s'!\", argv[argi]);\n eprintf(\"done\\n\");\n\n eprintf(\"Recognizing: \");\n clock_t now = clock();\n if (use_vertical) recognize_vertical(*recognizer);\n else recognize_untokenized(*recognizer);\n eprintf(\"done, in %.3f seconds.\\n\", (clock() - now) \/ double(CLOCKS_PER_SEC));\n\n return 0;\n}\n\nvoid recognize_vertical(const ner& recognizer) {\n string line;\n unsigned total_lines = 0;\n\n vector words;\n vector forms;\n vector entities;\n string entity_ids, entity_text;\n\n for (bool not_eof = true; not_eof; ) {\n \/\/ Read sentence\n words.clear();\n forms.clear();\n while ((not_eof = getline(stdin, line)) && !line.empty()) {\n auto tab = line.find('\\t');\n words.emplace_back(tab == string::npos ? line : line.substr(0, tab));\n forms.emplace_back(words.back());\n }\n\n \/\/ Find named entities in the sentence\n if (!forms.empty()) {\n recognizer.recognize(forms, entities);\n\n for (auto& entity : entities) {\n entity_ids.clear();\n entity_text.clear();\n for (auto i = entity.start; i < entity.start + entity.length; i++) {\n if (i > entity.start) {\n entity_ids += ',';\n entity_text += ' ';\n }\n entity_ids += to_string(total_lines + i + 1);\n entity_text += words[i];\n }\n printf(\"%s\\t%s\\t%s\\n\", entity_ids.c_str(), entity.type.c_str(), entity_text.c_str());\n }\n }\n\n total_lines += forms.size() + 1;\n }\n}\n\nstatic void encode_entities_and_print(const char* text, size_t length);\n\nvoid recognize_untokenized(const ner& recognizer) {\n string line, text;\n vector entities;\n vector entity_ends;\n\n for (bool not_eof = true; not_eof; ) {\n \/\/ Read block of text\n text.clear();\n while ((not_eof = getline(stdin, line)) && !line.empty()) {\n text += line;\n text += '\\n';\n }\n if (not_eof) text += '\\n';\n\n \/\/ Tokenize the text and find named entities\n size_t unprinted = 0;\n recognizer.tokenize_and_recognize(text.c_str(), entities);\n for (auto& entity : entities) {\n \/\/ Close entities that end sooned than current entity\n while (!entity_ends.empty() && entity_ends.back() < entity.start) {\n if (unprinted < entity_ends.back()) encode_entities_and_print(text.c_str() + unprinted, entity_ends.back() - unprinted);\n unprinted = entity_ends.back();\n entity_ends.pop_back();\n fputs(\"<\/ne>\", stdout);\n }\n\n \/\/ Print text just before the entity, open it and add end to the stack\n if (unprinted < entity.start) encode_entities_and_print(text.c_str() + unprinted, entity.start - unprinted);\n unprinted = entity.start;\n printf(\"\", entity.type.c_str());\n entity_ends.push_back(entity.start + entity.length);\n }\n\n \/\/ Close unclosed entities\n while (!entity_ends.empty()) {\n if (unprinted < entity_ends.back()) encode_entities_and_print(text.c_str() + unprinted, entity_ends.back() - unprinted);\n unprinted = entity_ends.back();\n entity_ends.pop_back();\n fputs(\"<\/ne>\", stdout);\n }\n \/\/ Write rest of the text (should be just spaces)\n if (unprinted < text.size()) encode_entities_and_print(text.c_str() + unprinted, text.size() - unprinted);\n }\n}\n\nvoid encode_entities_and_print(const char* text, size_t length) {\n const char* to_print = text;\n while (length) {\n while (length && *text != '<' && *text != '>' && *text != '&' && *text != '\"')\n text++, length--;\n\n if (length) {\n if (to_print < text) fwrite(to_print, 1, text - to_print, stdout);\n fputs(*text == '<' ? \"<\" : *text == '>' ? \">\" : *text == '&' ? \"&\" : \""\", stdout);\n text++, length--;\n to_print = text;\n }\n }\n if (to_print < text) fwrite(to_print, 1, text - to_print, stdout);\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\tnamespace detail\n\t{\n\t\tinline SILICIUM_NORETURN void throw_system_error(boost::system::error_code error)\n\t\t{\n\t\t\tboost::throw_exception(boost::system::system_error(error));\n\t\t}\n\n\t\tinline SILICIUM_NORETURN void throw_system_error(std::error_code error)\n\t\t{\n\t\t\tboost::throw_exception(std::system_error(error));\n\t\t}\n\t}\n\n\ttemplate \n\tstruct error_or\n\t{\n\t\terror_or() BOOST_NOEXCEPT\n\t\t{\n\t\t}\n\n\t\terror_or(Value value) BOOST_NOEXCEPT\n\t\t\t: storage(std::move(value))\n\t\t{\n\t\t}\n\n\t\terror_or(Error error) BOOST_NOEXCEPT\n\t\t\t: storage(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: storage(std::move(other.storage))\n\t\t{\n\t\t}\n\n\t\terror_or(error_or const &other)\n\t\t\t: storage(other.storage)\n\t\t{\n\t\t}\n\n\t\terror_or &operator = (error_or &&other) BOOST_NOEXCEPT\n\t\t{\n\t\t\tstorage = std::move(other.storage);\n\t\t\treturn *this;\n\t\t}\n\n\t\terror_or &operator = (error_or const &other)\n\t\t{\n\t\t\tstorage = other.storage;\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 Si::visit(\n\t\t\t\t\t\tstorage,\n\t\t\t\t\t\t[](Value const &) { return false; },\n\t\t\t\t\t\t[](Error const &) { return true; });\n\t\t}\n\n\t\tSi::optional error() const BOOST_NOEXCEPT\n\t\t{\n\t\t\treturn Si::visit>(\n\t\t\t\t\t\tstorage,\n\t\t\t\t\t\t[](Value const &) { return Si::optional(); },\n\t\t\t\t\t\t[](Error const &e) { return e; });\n\t\t}\n\n#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER\n\t\tValue &get() &\n\t\t{\n\t\t\treturn Si::visit(\n\t\t\t\t\t\tstorage,\n\t\t\t\t\t\t[](Value &value) -> Value & { return value; },\n\t\t\t\t\t\t[](Error const &e) -> Value & { detail::throw_system_error(e); });\n\t\t}\n#endif\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\treturn Si::visit(\n\t\t\t\t\t\tstorage,\n\t\t\t\t\t\t[](Value &value) -> Value && { return std::move(value); },\n\t\t\t\t\t\t[](Error const &e) -> Value && { detail::throw_system_error(e); });\n\t\t}\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\treturn Si::visit(\n\t\t\t\t\t\tstorage,\n\t\t\t\t\t\t[](Value const &value) -> Value const & { return value; },\n\t\t\t\t\t\t[](Error const &e) -> Value const & { detail::throw_system_error(e); });\n\t\t}\n\n\t\tValue *get_ptr() BOOST_NOEXCEPT\n\t\t{\n\t\t\treturn Si::visit(\n\t\t\t\t\t\tstorage,\n\t\t\t\t\t\t[](Value &value) -> Value * { return &value; },\n\t\t\t\t\t\t[](Error const &) -> Value * { return nullptr; });\n\t\t}\n\n\t\tValue const *get_ptr() const BOOST_NOEXCEPT\n\t\t{\n\t\t\treturn Si::visit(\n\t\t\t\t\t\tstorage,\n\t\t\t\t\t\t[](Value const &value) -> Value const * { return &value; },\n\t\t\t\t\t\t[](Error const &) -> Value const * { return nullptr; });\n\t\t}\n\n\tprivate:\n\n\t\tfast_variant storage;\n\t};\n}\n\n#endif\nadd operator -> and get_optional to error_or#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\tnamespace detail\n\t{\n\t\tinline SILICIUM_NORETURN void throw_system_error(boost::system::error_code error)\n\t\t{\n\t\t\tboost::throw_exception(boost::system::system_error(error));\n\t\t}\n\n\t\tinline SILICIUM_NORETURN void throw_system_error(std::error_code error)\n\t\t{\n\t\t\tboost::throw_exception(std::system_error(error));\n\t\t}\n\t}\n\n\ttemplate \n\tstruct error_or\n\t{\n\t\terror_or() BOOST_NOEXCEPT\n\t\t{\n\t\t}\n\n\t\terror_or(Value value) BOOST_NOEXCEPT\n\t\t\t: storage(std::move(value))\n\t\t{\n\t\t}\n\n\t\terror_or(Error error) BOOST_NOEXCEPT\n\t\t\t: storage(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: storage(std::move(other.storage))\n\t\t{\n\t\t}\n\n\t\terror_or(error_or const &other)\n\t\t\t: storage(other.storage)\n\t\t{\n\t\t}\n\n\t\terror_or &operator = (error_or &&other) BOOST_NOEXCEPT\n\t\t{\n\t\t\tstorage = std::move(other.storage);\n\t\t\treturn *this;\n\t\t}\n\n\t\terror_or &operator = (error_or const &other)\n\t\t{\n\t\t\tstorage = other.storage;\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 Si::visit(\n\t\t\t\t\t\tstorage,\n\t\t\t\t\t\t[](Value const &) { return false; },\n\t\t\t\t\t\t[](Error const &) { return true; });\n\t\t}\n\n\t\tSi::optional error() const BOOST_NOEXCEPT\n\t\t{\n\t\t\treturn Si::visit>(\n\t\t\t\t\t\tstorage,\n\t\t\t\t\t\t[](Value const &) { return Si::optional(); },\n\t\t\t\t\t\t[](Error const &e) { return e; });\n\t\t}\n\n#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER\n\t\tValue &get() &\n\t\t{\n\t\t\treturn Si::visit(\n\t\t\t\t\t\tstorage,\n\t\t\t\t\t\t[](Value &value) -> Value & { return value; },\n\t\t\t\t\t\t[](Error const &e) -> Value & { detail::throw_system_error(e); });\n\t\t}\n#endif\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\treturn Si::visit(\n\t\t\t\t\t\tstorage,\n\t\t\t\t\t\t[](Value &value) -> Value && { return std::move(value); },\n\t\t\t\t\t\t[](Error const &e) -> Value && { detail::throw_system_error(e); });\n\t\t}\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\treturn Si::visit(\n\t\t\t\t\t\tstorage,\n\t\t\t\t\t\t[](Value const &value) -> Value const & { return value; },\n\t\t\t\t\t\t[](Error const &e) -> Value const & { detail::throw_system_error(e); });\n\t\t}\n\n\t\tValue *get_ptr() BOOST_NOEXCEPT\n\t\t{\n\t\t\treturn Si::visit(\n\t\t\t\t\t\tstorage,\n\t\t\t\t\t\t[](Value &value) -> Value * { return &value; },\n\t\t\t\t\t\t[](Error const &) -> Value * { return nullptr; });\n\t\t}\n\n\t\tValue const *get_ptr() const BOOST_NOEXCEPT\n\t\t{\n\t\t\treturn Si::visit(\n\t\t\t\t\t\tstorage,\n\t\t\t\t\t\t[](Value const &value) -> Value const * { return &value; },\n\t\t\t\t\t\t[](Error const &) -> Value const * { return nullptr; });\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\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\tprivate:\n\n\t\tfast_variant storage;\n\t};\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright 2010 2011 2012 Helge Bahmann \n * Copyright 2011 2012 2013 2014 2015 Nico Reißmann \n * See COPYING for terms of redistribution.\n *\/\n\n#ifndef JIVE_RVSDG_TYPE_HPP\n#define JIVE_RVSDG_TYPE_HPP\n\n#include \n#include \n\nnamespace jive {\n\nclass type {\npublic:\n\tvirtual\n\t~type() noexcept;\n\nprotected:\n\tinline constexpr\n\ttype() noexcept\n\t{}\n\npublic:\n\tvirtual bool\n\toperator==(const jive::type & other) const noexcept = 0;\n\n\tinline bool\n\toperator!=(const jive::type & other) const noexcept\n\t{\n\t\treturn !(*this == other);\n\t}\n\n\tvirtual std::unique_ptr\n\tcopy() const = 0;\n\n\tvirtual std::string\n\tdebug_string() const = 0;\n};\n\nclass valuetype : public jive::type {\npublic:\n\tvirtual\n\t~valuetype() noexcept;\n\nprotected:\n\tinline constexpr\n\tvaluetype() noexcept\n\t: jive::type()\n\t{}\n};\n\nclass statetype : public jive::type {\npublic:\n\tvirtual\n\t~statetype() noexcept;\n\nprotected:\n\tinline constexpr\n\tstatetype() noexcept\n\t: jive::type()\n\t{}\n};\n\n}\n\n#endif\nrvsdg: add is function for types\/*\n * Copyright 2010 2011 2012 Helge Bahmann \n * Copyright 2011 2012 2013 2014 2015 Nico Reißmann \n * See COPYING for terms of redistribution.\n *\/\n\n#ifndef JIVE_RVSDG_TYPE_HPP\n#define JIVE_RVSDG_TYPE_HPP\n\n#include \n#include \n\nnamespace jive {\n\nclass type {\npublic:\n\tvirtual\n\t~type() noexcept;\n\nprotected:\n\tinline constexpr\n\ttype() noexcept\n\t{}\n\npublic:\n\tvirtual bool\n\toperator==(const jive::type & other) const noexcept = 0;\n\n\tinline bool\n\toperator!=(const jive::type & other) const noexcept\n\t{\n\t\treturn !(*this == other);\n\t}\n\n\tvirtual std::unique_ptr\n\tcopy() const = 0;\n\n\tvirtual std::string\n\tdebug_string() const = 0;\n};\n\nclass valuetype : public jive::type {\npublic:\n\tvirtual\n\t~valuetype() noexcept;\n\nprotected:\n\tinline constexpr\n\tvaluetype() noexcept\n\t: jive::type()\n\t{}\n};\n\nclass statetype : public jive::type {\npublic:\n\tvirtual\n\t~statetype() noexcept;\n\nprotected:\n\tinline constexpr\n\tstatetype() noexcept\n\t: jive::type()\n\t{}\n};\n\ntemplate static inline bool\nis(const jive::type & type) noexcept\n{\n\tstatic_assert(std::is_base_of::value,\n\t\t\"Template parameter T must be derived from jive::type.\");\n\n\treturn dynamic_cast(&type) != nullptr;\n}\n\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ File: btBoostDynamicsCollisionDispatcher.hpp\n#ifndef _btBoostDynamicsCollisionDispatcher_hpp\n#define _btBoostDynamicsCollisionDispatcher_hpp\n\n#include \n#include \n#include \n\nusing namespace boost::python;\n\nbtCollisionDispatcher*\nmake_CollisionDispatcher(btCollisionConfiguration& config)\n{\n\treturn new btCollisionDispatcher(&config);\n}\n\nvoid defineCollisionDispatcher()\n{\n enum_(\"DispatcherFlags\")\n .value(\"CD_STATIC_STATIC_REPORTED\",\n \tbtCollisionDispatcher::CD_STATIC_STATIC_REPORTED)\n .value(\"CD_USE_RELATIVE_CONTACT_BREAKING_THRESHOLD\",\n \tbtCollisionDispatcher::CD_USE_RELATIVE_CONTACT_BREAKING_THRESHOLD)\n .value(\"CD_DISABLE_CONTACTPOOL_DYNAMIC_ALLOCATION\",\n \tbtCollisionDispatcher::CD_DISABLE_CONTACTPOOL_DYNAMIC_ALLOCATION)\n .export_values()\n ;\n\n class_ >\n (\"btCollisionDispatcher\", no_init)\n \t.def(\"__init__\", make_constructor(&make_CollisionDispatcher))\n \t.add_property(\"flags\",\n \t\t&btCollisionDispatcher::getDispatcherFlags,\n \t\t&btCollisionDispatcher::setDispatcherFlags)\n ;\n}\n\n#endif \/\/ _btBoostDynamicsCollisionDispatcher_hpp\nAdd pure abstract base class and mark noncopyable\/\/ File: btBoostDynamicsCollisionDispatcher.hpp\n#ifndef _btBoostDynamicsCollisionDispatcher_hpp\n#define _btBoostDynamicsCollisionDispatcher_hpp\n\n#include \n#include \n#include \n\nusing namespace boost::python;\n\nbtCollisionDispatcher*\nmake_CollisionDispatcher(btCollisionConfiguration& config)\n{\n\treturn new btCollisionDispatcher(&config);\n}\n\nvoid defineCollisionDispatcher()\n{\n enum_(\"DispatcherFlags\")\n .value(\"CD_STATIC_STATIC_REPORTED\",\n \tbtCollisionDispatcher::CD_STATIC_STATIC_REPORTED)\n .value(\"CD_USE_RELATIVE_CONTACT_BREAKING_THRESHOLD\",\n \tbtCollisionDispatcher::CD_USE_RELATIVE_CONTACT_BREAKING_THRESHOLD)\n .value(\"CD_DISABLE_CONTACTPOOL_DYNAMIC_ALLOCATION\",\n \tbtCollisionDispatcher::CD_DISABLE_CONTACTPOOL_DYNAMIC_ALLOCATION)\n .export_values()\n ;\n\n class_(\"btDispatcher\", no_init);\n\n class_, boost::noncopyable>\n (\"btCollisionDispatcher\", no_init)\n \t.def(\"__init__\", make_constructor(&make_CollisionDispatcher))\n \t.add_property(\"flags\",\n \t\t&btCollisionDispatcher::getDispatcherFlags,\n \t\t&btCollisionDispatcher::setDispatcherFlags)\n ;\n}\n\n#endif \/\/ _btBoostDynamicsCollisionDispatcher_hpp\n<|endoftext|>"} {"text":"\/*\n * Copyright 2016 The Cartographer 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\n#include \n#include \n#include \n\n#include \"Eigen\/Core\"\n#include \"Eigen\/Geometry\"\n#include \"cairo\/cairo.h\"\n#include \"cartographer\/common\/mutex.h\"\n#include \"cartographer\/common\/port.h\"\n#include \"cartographer\/io\/image.h\"\n#include \"cartographer\/mapping\/id.h\"\n#include \"cartographer\/transform\/rigid_transform.h\"\n#include \"cartographer_ros\/msg_conversion.h\"\n#include \"cartographer_ros\/node_constants.h\"\n#include \"cartographer_ros\/ros_log_sink.h\"\n#include \"cartographer_ros\/submap.h\"\n#include \"cartographer_ros_msgs\/SubmapList.h\"\n#include \"cartographer_ros_msgs\/SubmapQuery.h\"\n#include \"gflags\/gflags.h\"\n#include \"nav_msgs\/OccupancyGrid.h\"\n#include \"ros\/ros.h\"\n\nDEFINE_double(resolution, 0.05,\n \"Resolution of a grid cell in the published occupancy grid.\");\n\nnamespace cartographer_ros {\nnamespace {\n\nusing ::cartographer::mapping::SubmapId;\n\nconstexpr cairo_format_t kCairoFormat = CAIRO_FORMAT_ARGB32;\n\nEigen::Affine3d ToEigen(const ::cartographer::transform::Rigid3d& rigid3) {\n return Eigen::Translation3d(rigid3.translation()) * rigid3.rotation();\n}\n\nstruct SubmapState {\n SubmapState()\n : surface(::cartographer::io::MakeUniqueCairoSurfacePtr(nullptr)) {}\n\n \/\/ Texture data.\n int width;\n int height;\n int version;\n double resolution;\n ::cartographer::transform::Rigid3d slice_pose;\n ::cartographer::io::UniqueCairoSurfacePtr surface;\n \/\/ Pixel data used by 'surface'. Must outlive 'surface'.\n std::vector cairo_data;\n\n \/\/ Metadata.\n ::cartographer::transform::Rigid3d pose;\n int metadata_version = -1;\n};\n\nvoid CairoDrawEachSubmap(\n const double scale, std::map* submaps, cairo_t* cr,\n std::function draw_callback) {\n cairo_scale(cr, scale, scale);\n\n for (auto& pair : *submaps) {\n auto& submap_state = pair.second;\n if (submap_state.surface == nullptr) {\n return;\n }\n const Eigen::Matrix4d homo =\n ToEigen(submap_state.pose * submap_state.slice_pose).matrix();\n\n cairo_save(cr);\n cairo_matrix_t matrix;\n cairo_matrix_init(&matrix, homo(1, 0), homo(0, 0), -homo(1, 1), -homo(0, 1),\n homo(0, 3), -homo(1, 3));\n cairo_transform(cr, &matrix);\n\n const double submap_resolution = submap_state.resolution;\n cairo_scale(cr, submap_resolution, submap_resolution);\n draw_callback(submap_state);\n cairo_restore(cr);\n }\n}\n\nclass Node {\n public:\n explicit Node(double resolution);\n ~Node() {}\n\n Node(const Node&) = delete;\n Node& operator=(const Node&) = delete;\n\n private:\n void HandleSubmapList(const cartographer_ros_msgs::SubmapList::ConstPtr& msg);\n void DrawAndPublish(const string& frame_id, const ros::Time& time);\n void PublishOccupancyGrid(const string& frame_id, const ros::Time& time,\n const Eigen::Array2f& origin,\n const Eigen::Array2i& size,\n cairo_surface_t* surface);\n\n ::ros::NodeHandle node_handle_;\n const double resolution_;\n\n ::cartographer::common::Mutex mutex_;\n ::ros::ServiceClient client_ GUARDED_BY(mutex_);\n ::ros::Subscriber submap_list_subscriber_ GUARDED_BY(mutex_);\n ::ros::Publisher occupancy_grid_publisher_ GUARDED_BY(mutex_);\n std::map submaps_ GUARDED_BY(mutex_);\n};\n\nNode::Node(const double resolution)\n : resolution_(resolution),\n client_(node_handle_.serviceClient<::cartographer_ros_msgs::SubmapQuery>(\n kSubmapQueryServiceName)),\n submap_list_subscriber_(node_handle_.subscribe(\n kSubmapListTopic, kLatestOnlyPublisherQueueSize,\n boost::function(\n [this](const cartographer_ros_msgs::SubmapList::ConstPtr& msg) {\n HandleSubmapList(msg);\n }))),\n occupancy_grid_publisher_(\n node_handle_.advertise<::nav_msgs::OccupancyGrid>(\n kOccupancyGridTopic, kLatestOnlyPublisherQueueSize,\n true \/* latched *\/))\n\n{}\n\nvoid Node::HandleSubmapList(\n const cartographer_ros_msgs::SubmapList::ConstPtr& msg) {\n ::cartographer::common::MutexLocker locker(&mutex_);\n\n \/\/ We do not do any work if nobody listens.\n if (occupancy_grid_publisher_.getNumSubscribers() == 0) {\n return;\n }\n for (const auto& submap_msg : msg->submap) {\n const SubmapId id{submap_msg.trajectory_id, submap_msg.submap_index};\n SubmapState& submap_state = submaps_[id];\n submap_state.pose = ToRigid3d(submap_msg.pose);\n submap_state.metadata_version = submap_msg.submap_version;\n if (submap_state.surface != nullptr &&\n submap_state.version == submap_msg.submap_version) {\n continue;\n }\n\n auto fetched_texture = ::cartographer_ros::FetchSubmapTexture(id, &client_);\n if (fetched_texture == nullptr) {\n continue;\n }\n submap_state.width = fetched_texture->width;\n submap_state.height = fetched_texture->height;\n submap_state.version = fetched_texture->version;\n submap_state.slice_pose = fetched_texture->slice_pose;\n submap_state.resolution = fetched_texture->resolution;\n\n \/\/ Properly dealing with a non-common stride would make this code much more\n \/\/ complicated. Let's check that it is not needed.\n const int expected_stride = 4 * submap_state.width;\n CHECK_EQ(expected_stride,\n cairo_format_stride_for_width(kCairoFormat, submap_state.width));\n submap_state.cairo_data.clear();\n for (size_t i = 0; i < fetched_texture->intensity.size(); ++i) {\n \/\/ We use the red channel to track intensity information. The green\n \/\/ channel we use to track if a cell was ever observed.\n const uint8_t intensity = fetched_texture->intensity.at(i);\n const uint8_t alpha = fetched_texture->alpha.at(i);\n const uint8_t observed = (intensity == 0 && alpha == 0) ? 0 : 255;\n submap_state.cairo_data.push_back((alpha << 24) | (intensity << 16) |\n (observed << 8) | 0);\n }\n\n submap_state.surface = ::cartographer::io::MakeUniqueCairoSurfacePtr(\n cairo_image_surface_create_for_data(\n reinterpret_cast(submap_state.cairo_data.data()),\n kCairoFormat, submap_state.width, submap_state.height,\n expected_stride));\n CHECK_EQ(cairo_surface_status(submap_state.surface.get()),\n CAIRO_STATUS_SUCCESS)\n << cairo_status_to_string(\n cairo_surface_status(submap_state.surface.get()));\n }\n DrawAndPublish(msg->header.frame_id, msg->header.stamp);\n}\n\nvoid Node::DrawAndPublish(const string& frame_id, const ros::Time& time) {\n if (submaps_.empty()) {\n return;\n }\n\n Eigen::AlignedBox2f bounding_box;\n {\n auto surface = ::cartographer::io::MakeUniqueCairoSurfacePtr(\n cairo_image_surface_create(kCairoFormat, 1, 1));\n auto cr =\n ::cartographer::io::MakeUniqueCairoPtr(cairo_create(surface.get()));\n const auto update_bounding_box = [&bounding_box, &cr](double x, double y) {\n cairo_user_to_device(cr.get(), &x, &y);\n bounding_box.extend(Eigen::Vector2f(x, y));\n };\n\n CairoDrawEachSubmap(\n 1. \/ resolution_, &submaps_, cr.get(),\n [&update_bounding_box, &bounding_box](const SubmapState& submap_state) {\n update_bounding_box(0, 0);\n update_bounding_box(submap_state.width, 0);\n update_bounding_box(0, submap_state.height);\n update_bounding_box(submap_state.width, submap_state.height);\n });\n }\n\n const int kPaddingPixel = 5;\n const Eigen::Array2i size(\n std::ceil(bounding_box.sizes().x()) + 2 * kPaddingPixel,\n std::ceil(bounding_box.sizes().y()) + 2 * kPaddingPixel);\n const Eigen::Array2f origin(-bounding_box.min().x() + kPaddingPixel,\n -bounding_box.min().y() + kPaddingPixel);\n\n {\n auto surface = ::cartographer::io::MakeUniqueCairoSurfacePtr(\n cairo_image_surface_create(kCairoFormat, size.x(), size.y()));\n auto cr =\n ::cartographer::io::MakeUniqueCairoPtr(cairo_create(surface.get()));\n cairo_set_source_rgba(cr.get(), 0.5, 0.0, 0.0, 1.);\n cairo_paint(cr.get());\n cairo_translate(cr.get(), origin.x(), origin.y());\n CairoDrawEachSubmap(1. \/ resolution_, &submaps_, cr.get(),\n [&cr](const SubmapState& submap_state) {\n cairo_set_source_surface(\n cr.get(), submap_state.surface.get(), 0., 0.);\n cairo_paint(cr.get());\n });\n cairo_surface_flush(surface.get());\n PublishOccupancyGrid(frame_id, time, origin, size, surface.get());\n }\n}\n\nvoid Node::PublishOccupancyGrid(const string& frame_id, const ros::Time& time,\n const Eigen::Array2f& origin,\n const Eigen::Array2i& size,\n cairo_surface_t* surface) {\n nav_msgs::OccupancyGrid occupancy_grid;\n occupancy_grid.header.stamp = time;\n occupancy_grid.header.frame_id = frame_id;\n occupancy_grid.info.map_load_time = time;\n occupancy_grid.info.resolution = resolution_;\n occupancy_grid.info.width = size.x();\n occupancy_grid.info.height = size.y();\n occupancy_grid.info.origin.position.x = -origin.x() * resolution_;\n occupancy_grid.info.origin.position.y =\n (-size.y() + origin.y()) * resolution_;\n occupancy_grid.info.origin.position.z = 0.;\n occupancy_grid.info.origin.orientation.w = 1.;\n occupancy_grid.info.origin.orientation.x = 0.;\n occupancy_grid.info.origin.orientation.y = 0.;\n occupancy_grid.info.origin.orientation.z = 0.;\n\n const uint32* pixel_data =\n reinterpret_cast(cairo_image_surface_get_data(surface));\n occupancy_grid.data.reserve(size.x() * size.y());\n for (int y = size.y() - 1; y >= 0; --y) {\n for (int x = 0; x < size.x(); ++x) {\n const uint32 packed = pixel_data[y * size.x() + x];\n const unsigned char color = packed >> 16;\n const unsigned char observed = packed >> 8;\n const int value =\n observed == 0\n ? -1\n : ::cartographer::common::RoundToInt((1. - color \/ 255.) * 100.);\n CHECK_LE(-1, value);\n CHECK_GE(100, value);\n occupancy_grid.data.push_back(value);\n }\n }\n occupancy_grid_publisher_.publish(occupancy_grid);\n}\n\n} \/\/ namespace\n} \/\/ namespace cartographer_ros\n\nint main(int argc, char** argv) {\n google::InitGoogleLogging(argv[0]);\n google::ParseCommandLineFlags(&argc, &argv, true);\n\n ::ros::init(argc, argv, \"cartographer_occupancy_grid_node\");\n ::ros::start();\n\n cartographer_ros::ScopedRosLogSink ros_log_sink;\n ::cartographer_ros::Node node(FLAGS_resolution);\n\n ::ros::spin();\n ::ros::shutdown();\n}\nConfigurable occupancy grid publishing speed (#504)\/*\n * Copyright 2016 The Cartographer 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\n#include \n#include \n#include \n\n#include \"Eigen\/Core\"\n#include \"Eigen\/Geometry\"\n#include \"cairo\/cairo.h\"\n#include \"cartographer\/common\/mutex.h\"\n#include \"cartographer\/common\/port.h\"\n#include \"cartographer\/io\/image.h\"\n#include \"cartographer\/mapping\/id.h\"\n#include \"cartographer\/transform\/rigid_transform.h\"\n#include \"cartographer_ros\/msg_conversion.h\"\n#include \"cartographer_ros\/node_constants.h\"\n#include \"cartographer_ros\/ros_log_sink.h\"\n#include \"cartographer_ros\/submap.h\"\n#include \"cartographer_ros_msgs\/SubmapList.h\"\n#include \"cartographer_ros_msgs\/SubmapQuery.h\"\n#include \"gflags\/gflags.h\"\n#include \"nav_msgs\/OccupancyGrid.h\"\n#include \"ros\/ros.h\"\n\nDEFINE_double(resolution, 0.05,\n \"Resolution of a grid cell in the published occupancy grid.\");\nDEFINE_double(publish_period_sec, 1.0, \"OccupancyGrid publishing period.\");\n\nnamespace cartographer_ros {\nnamespace {\n\nusing ::cartographer::mapping::SubmapId;\n\nconstexpr cairo_format_t kCairoFormat = CAIRO_FORMAT_ARGB32;\n\nEigen::Affine3d ToEigen(const ::cartographer::transform::Rigid3d& rigid3) {\n return Eigen::Translation3d(rigid3.translation()) * rigid3.rotation();\n}\n\nstruct SubmapState {\n SubmapState()\n : surface(::cartographer::io::MakeUniqueCairoSurfacePtr(nullptr)) {}\n\n \/\/ Texture data.\n int width;\n int height;\n int version;\n double resolution;\n ::cartographer::transform::Rigid3d slice_pose;\n ::cartographer::io::UniqueCairoSurfacePtr surface;\n \/\/ Pixel data used by 'surface'. Must outlive 'surface'.\n std::vector cairo_data;\n\n \/\/ Metadata.\n ::cartographer::transform::Rigid3d pose;\n int metadata_version = -1;\n};\n\nvoid CairoDrawEachSubmap(\n const double scale, std::map* submaps, cairo_t* cr,\n std::function draw_callback) {\n cairo_scale(cr, scale, scale);\n\n for (auto& pair : *submaps) {\n auto& submap_state = pair.second;\n if (submap_state.surface == nullptr) {\n return;\n }\n const Eigen::Matrix4d homo =\n ToEigen(submap_state.pose * submap_state.slice_pose).matrix();\n\n cairo_save(cr);\n cairo_matrix_t matrix;\n cairo_matrix_init(&matrix, homo(1, 0), homo(0, 0), -homo(1, 1), -homo(0, 1),\n homo(0, 3), -homo(1, 3));\n cairo_transform(cr, &matrix);\n\n const double submap_resolution = submap_state.resolution;\n cairo_scale(cr, submap_resolution, submap_resolution);\n draw_callback(submap_state);\n cairo_restore(cr);\n }\n}\n\nclass Node {\n public:\n explicit Node(double resolution, double publish_period_sec);\n ~Node() {}\n\n Node(const Node&) = delete;\n Node& operator=(const Node&) = delete;\n\n private:\n void HandleSubmapList(const cartographer_ros_msgs::SubmapList::ConstPtr& msg);\n void DrawAndPublish(const ::ros::WallTimerEvent& timer_event);\n void PublishOccupancyGrid(const string& frame_id, const ros::Time& time,\n const Eigen::Array2f& origin,\n const Eigen::Array2i& size,\n cairo_surface_t* surface);\n\n ::ros::NodeHandle node_handle_;\n const double resolution_;\n\n ::cartographer::common::Mutex mutex_;\n ::ros::ServiceClient client_ GUARDED_BY(mutex_);\n ::ros::Subscriber submap_list_subscriber_ GUARDED_BY(mutex_);\n ::ros::Publisher occupancy_grid_publisher_ GUARDED_BY(mutex_);\n std::map submaps_ GUARDED_BY(mutex_);\n ::ros::WallTimer occupancy_grid_publisher_timer_;\n std::string last_frame_id_;\n ros::Time last_timestamp_;\n};\n\nNode::Node(const double resolution, const double publish_period_sec)\n : resolution_(resolution),\n client_(node_handle_.serviceClient<::cartographer_ros_msgs::SubmapQuery>(\n kSubmapQueryServiceName)),\n submap_list_subscriber_(node_handle_.subscribe(\n kSubmapListTopic, kLatestOnlyPublisherQueueSize,\n boost::function(\n [this](const cartographer_ros_msgs::SubmapList::ConstPtr& msg) {\n HandleSubmapList(msg);\n }))),\n occupancy_grid_publisher_(\n node_handle_.advertise<::nav_msgs::OccupancyGrid>(\n kOccupancyGridTopic, kLatestOnlyPublisherQueueSize,\n true \/* latched *\/)),\n occupancy_grid_publisher_timer_(\n node_handle_.createWallTimer(::ros::WallDuration(publish_period_sec),\n &Node::DrawAndPublish, this)) {}\n\nvoid Node::HandleSubmapList(\n const cartographer_ros_msgs::SubmapList::ConstPtr& msg) {\n ::cartographer::common::MutexLocker locker(&mutex_);\n\n \/\/ We do not do any work if nobody listens.\n if (occupancy_grid_publisher_.getNumSubscribers() == 0) {\n return;\n }\n for (const auto& submap_msg : msg->submap) {\n const SubmapId id{submap_msg.trajectory_id, submap_msg.submap_index};\n SubmapState& submap_state = submaps_[id];\n submap_state.pose = ToRigid3d(submap_msg.pose);\n submap_state.metadata_version = submap_msg.submap_version;\n if (submap_state.surface != nullptr &&\n submap_state.version == submap_msg.submap_version) {\n continue;\n }\n\n auto fetched_texture = ::cartographer_ros::FetchSubmapTexture(id, &client_);\n if (fetched_texture == nullptr) {\n continue;\n }\n submap_state.width = fetched_texture->width;\n submap_state.height = fetched_texture->height;\n submap_state.version = fetched_texture->version;\n submap_state.slice_pose = fetched_texture->slice_pose;\n submap_state.resolution = fetched_texture->resolution;\n\n \/\/ Properly dealing with a non-common stride would make this code much more\n \/\/ complicated. Let's check that it is not needed.\n const int expected_stride = 4 * submap_state.width;\n CHECK_EQ(expected_stride,\n cairo_format_stride_for_width(kCairoFormat, submap_state.width));\n submap_state.cairo_data.clear();\n for (size_t i = 0; i < fetched_texture->intensity.size(); ++i) {\n \/\/ We use the red channel to track intensity information. The green\n \/\/ channel we use to track if a cell was ever observed.\n const uint8_t intensity = fetched_texture->intensity.at(i);\n const uint8_t alpha = fetched_texture->alpha.at(i);\n const uint8_t observed = (intensity == 0 && alpha == 0) ? 0 : 255;\n submap_state.cairo_data.push_back((alpha << 24) | (intensity << 16) |\n (observed << 8) | 0);\n }\n\n submap_state.surface = ::cartographer::io::MakeUniqueCairoSurfacePtr(\n cairo_image_surface_create_for_data(\n reinterpret_cast(submap_state.cairo_data.data()),\n kCairoFormat, submap_state.width, submap_state.height,\n expected_stride));\n CHECK_EQ(cairo_surface_status(submap_state.surface.get()),\n CAIRO_STATUS_SUCCESS)\n << cairo_status_to_string(\n cairo_surface_status(submap_state.surface.get()));\n }\n last_timestamp_ = msg->header.stamp;\n last_frame_id_ = msg->header.frame_id;\n}\n\nvoid Node::DrawAndPublish(const ::ros::WallTimerEvent& unused_timer_event) {\n if (submaps_.empty() || last_frame_id_.empty()) {\n return;\n }\n\n ::cartographer::common::MutexLocker locker(&mutex_);\n Eigen::AlignedBox2f bounding_box;\n {\n auto surface = ::cartographer::io::MakeUniqueCairoSurfacePtr(\n cairo_image_surface_create(kCairoFormat, 1, 1));\n auto cr =\n ::cartographer::io::MakeUniqueCairoPtr(cairo_create(surface.get()));\n const auto update_bounding_box = [&bounding_box, &cr](double x, double y) {\n cairo_user_to_device(cr.get(), &x, &y);\n bounding_box.extend(Eigen::Vector2f(x, y));\n };\n\n CairoDrawEachSubmap(\n 1. \/ resolution_, &submaps_, cr.get(),\n [&update_bounding_box, &bounding_box](const SubmapState& submap_state) {\n update_bounding_box(0, 0);\n update_bounding_box(submap_state.width, 0);\n update_bounding_box(0, submap_state.height);\n update_bounding_box(submap_state.width, submap_state.height);\n });\n }\n\n const int kPaddingPixel = 5;\n const Eigen::Array2i size(\n std::ceil(bounding_box.sizes().x()) + 2 * kPaddingPixel,\n std::ceil(bounding_box.sizes().y()) + 2 * kPaddingPixel);\n const Eigen::Array2f origin(-bounding_box.min().x() + kPaddingPixel,\n -bounding_box.min().y() + kPaddingPixel);\n\n {\n auto surface = ::cartographer::io::MakeUniqueCairoSurfacePtr(\n cairo_image_surface_create(kCairoFormat, size.x(), size.y()));\n auto cr =\n ::cartographer::io::MakeUniqueCairoPtr(cairo_create(surface.get()));\n cairo_set_source_rgba(cr.get(), 0.5, 0.0, 0.0, 1.);\n cairo_paint(cr.get());\n cairo_translate(cr.get(), origin.x(), origin.y());\n CairoDrawEachSubmap(1. \/ resolution_, &submaps_, cr.get(),\n [&cr](const SubmapState& submap_state) {\n cairo_set_source_surface(\n cr.get(), submap_state.surface.get(), 0., 0.);\n cairo_paint(cr.get());\n });\n cairo_surface_flush(surface.get());\n PublishOccupancyGrid(last_frame_id_, last_timestamp_, origin, size,\n surface.get());\n }\n}\n\nvoid Node::PublishOccupancyGrid(const string& frame_id, const ros::Time& time,\n const Eigen::Array2f& origin,\n const Eigen::Array2i& size,\n cairo_surface_t* surface) {\n nav_msgs::OccupancyGrid occupancy_grid;\n occupancy_grid.header.stamp = time;\n occupancy_grid.header.frame_id = frame_id;\n occupancy_grid.info.map_load_time = time;\n occupancy_grid.info.resolution = resolution_;\n occupancy_grid.info.width = size.x();\n occupancy_grid.info.height = size.y();\n occupancy_grid.info.origin.position.x = -origin.x() * resolution_;\n occupancy_grid.info.origin.position.y =\n (-size.y() + origin.y()) * resolution_;\n occupancy_grid.info.origin.position.z = 0.;\n occupancy_grid.info.origin.orientation.w = 1.;\n occupancy_grid.info.origin.orientation.x = 0.;\n occupancy_grid.info.origin.orientation.y = 0.;\n occupancy_grid.info.origin.orientation.z = 0.;\n\n const uint32* pixel_data =\n reinterpret_cast(cairo_image_surface_get_data(surface));\n occupancy_grid.data.reserve(size.x() * size.y());\n for (int y = size.y() - 1; y >= 0; --y) {\n for (int x = 0; x < size.x(); ++x) {\n const uint32 packed = pixel_data[y * size.x() + x];\n const unsigned char color = packed >> 16;\n const unsigned char observed = packed >> 8;\n const int value =\n observed == 0\n ? -1\n : ::cartographer::common::RoundToInt((1. - color \/ 255.) * 100.);\n CHECK_LE(-1, value);\n CHECK_GE(100, value);\n occupancy_grid.data.push_back(value);\n }\n }\n occupancy_grid_publisher_.publish(occupancy_grid);\n}\n\n} \/\/ namespace\n} \/\/ namespace cartographer_ros\n\nint main(int argc, char** argv) {\n google::InitGoogleLogging(argv[0]);\n google::ParseCommandLineFlags(&argc, &argv, true);\n\n ::ros::init(argc, argv, \"cartographer_occupancy_grid_node\");\n ::ros::start();\n\n cartographer_ros::ScopedRosLogSink ros_log_sink;\n ::cartographer_ros::Node node(FLAGS_resolution, FLAGS_publish_period_sec);\n\n ::ros::spin();\n ::ros::shutdown();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"RendererOGLAndroid.h\"\n#include \"core\/android\/ApplicationAndroid.h\"\n#include \"utils\/Log.h\"\n\nnamespace ouzel\n{\n namespace graphics\n {\n RendererOGLAndroid::~RendererOGLAndroid()\n {\n }\n\n bool RendererOGLAndroid::init(Window* newWindow,\n const Size2& newSize,\n uint32_t newSampleCount,\n Texture::Filter newTextureFilter,\n PixelFormat newBackBufferFormat,\n bool newVerticalSync,\n bool newDepth)\n {\n ApplicationAndroid* applicationAndroid = static_cast(sharedApplication);\n JavaVM* javaVM = applicationAndroid->getJavaVM();\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast(&jniEnv), JNI_VERSION_1_6) != JNI_OK)\n {\n Log(Log::Level::ERR) << \"Failed to get JNI environment\";\n }\n\n jobject mainActivity = applicationAndroid->getMainActivity();\n jmethodID createSurfaceMethod = applicationAndroid->getCreateSurfaceMethod();\n jniEnv->CallVoidMethod(mainActivity, createSurfaceMethod, 8, 8, 8, 8, newDepth ? 24 : 0, 0, (newSampleCount > 1) ? 1 : 0, newSampleCount);\n\n apiMajorVersion = 2;\n apiMinorVersion = 0;\n\n return RendererOGL::init(newWindow, newSize, newSampleCount, newTextureFilter, newBackBufferFormat, newVerticalSync, newDepth);\n }\n } \/\/ namespace graphics\n} \/\/ namespace ouzel\nReturn false if failed to get Java VM\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"RendererOGLAndroid.h\"\n#include \"core\/android\/ApplicationAndroid.h\"\n#include \"utils\/Log.h\"\n\nnamespace ouzel\n{\n namespace graphics\n {\n RendererOGLAndroid::~RendererOGLAndroid()\n {\n }\n\n bool RendererOGLAndroid::init(Window* newWindow,\n const Size2& newSize,\n uint32_t newSampleCount,\n Texture::Filter newTextureFilter,\n PixelFormat newBackBufferFormat,\n bool newVerticalSync,\n bool newDepth)\n {\n ApplicationAndroid* applicationAndroid = static_cast(sharedApplication);\n JavaVM* javaVM = applicationAndroid->getJavaVM();\n JNIEnv* jniEnv;\n\n if (javaVM->GetEnv(reinterpret_cast(&jniEnv), JNI_VERSION_1_6) != JNI_OK)\n {\n Log(Log::Level::ERR) << \"Failed to get JNI environment\";\n return false;\n }\n\n jobject mainActivity = applicationAndroid->getMainActivity();\n jmethodID createSurfaceMethod = applicationAndroid->getCreateSurfaceMethod();\n jniEnv->CallVoidMethod(mainActivity, createSurfaceMethod, 8, 8, 8, 8, newDepth ? 24 : 0, 0, (newSampleCount > 1) ? 1 : 0, newSampleCount);\n\n apiMajorVersion = 2;\n apiMinorVersion = 0;\n\n return RendererOGL::init(newWindow, newSize, newSampleCount, newTextureFilter, newBackBufferFormat, newVerticalSync, newDepth);\n }\n } \/\/ namespace graphics\n} \/\/ namespace ouzel\n<|endoftext|>"} {"text":"\/*\n * TP1.cpp\n *\n * Created on: 02\/02\/2015\n * Author: vagner\n *\/\n\n#include \"TP0.h\"\n#include \"..\/lib\/TrabalhoPratico.h\"\n#include \n#include \"..\/lib\/PAAException.h\"\n#include \n#include \n#include \n\nnamespace PAA {\n\nTP0::TP0():TrabalhoPratico()\n{\n \/\/Do nothing\n\n\n}\n\nTP0::~TP0() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\nvoid TP0::run(void ){\n\ttry {\n\t\t\tthis->showUserMessage(\"Iniciando a execução do TP1\");\n\n\t\t\tthis->showUserMessage(\"Ola Mundo\");\n\n\t\t\tsleep(5);\n\n\t\t\tthis->showUserMessage(\"Finalizando a execução do TP1\");\n\n\t\t\tthis->setFinalTime();\n\n\t} catch (const std::exception& e) {\n\n\t\tstd::stringstream ss;\n\t\tss << \"Erro durante a alocaco de memoria. Tipo de excecao: \" << e.what();\n\t\tthrow PAA::PAAException(ss.str());\n\n\n\t}\n\n\n}\n\nvoid TP0::showUserMessage(const std::string& message){\n\n\tPAA::TrabalhoPratico::showUserMessage(message);\n\n}\n\nvoid TP0::showStatistics(void){\n\n\tPAA::TrabalhoPratico::showStatistics();\n}\n\nvoid TP0::setFinalTime(void){\n\n\tPAA::TrabalhoPratico::setFinalTime();\n\n}\n\n}\/* namespace PAA *\/\nAlteração no arquivo TP0.cpp aumentando o tempo de 'sleep' para 10 segundos\/*\n * TP1.cpp\n *\n * Created on: 02\/02\/2015\n * Author: vagner\n *\/\n\n#include \"TP0.h\"\n#include \"..\/lib\/TrabalhoPratico.h\"\n#include \n#include \"..\/lib\/PAAException.h\"\n#include \n#include \n#include \n\nnamespace PAA {\n\nTP0::TP0():TrabalhoPratico()\n{\n \/\/Do nothing\n\n\n}\n\nTP0::~TP0() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\nvoid TP0::run(void ){\n\ttry {\n\t\t\tthis->showUserMessage(\"Iniciando a execução do TP1\");\n\n\t\t\tthis->showUserMessage(\"Ola Mundo\");\n\n\t\t\tsleep(10);\n\n\t\t\tthis->showUserMessage(\"Finalizando a execução do TP1\");\n\n\t\t\tthis->setFinalTime();\n\n\t} catch (const std::exception& e) {\n\n\t\tstd::stringstream ss;\n\t\tss << \"Erro durante a alocaco de memoria. Tipo de excecao: \" << e.what();\n\t\tthrow PAA::PAAException(ss.str());\n\n\n\t}\n\n\n}\n\nvoid TP0::showUserMessage(const std::string& message){\n\n\tPAA::TrabalhoPratico::showUserMessage(message);\n\n}\n\nvoid TP0::showStatistics(void){\n\n\tPAA::TrabalhoPratico::showStatistics();\n}\n\nvoid TP0::setFinalTime(void){\n\n\tPAA::TrabalhoPratico::setFinalTime();\n\n}\n\n}\/* namespace PAA *\/\n<|endoftext|>"} {"text":"\/**\n* Copyright (c) 2014-2016 Dallin Wellington\n*\n*\/\n\n\n#include \n\n#ifdef MONSOON_OS_WINDOWS\n\n#define WIN32_LEAN_AND_MEAN\n#include \n\n#include \n#include \n\nusing namespace Monsoon;\n\nclass PrimitivesApplication : public Application\n{\npublic:\n\tPrimitivesApplication()\n\t\t: Application((Renderer::Renderer*)(new Renderer::D3D11Renderer(Renderer::RendererSettings(), &mEventManager, &mTransformSystem))) {\n\n\t}\n\n\t~PrimitivesApplication() {\n\n\t}\n\nprotected:\n\tfloat cameraTheta;\n\n\tvoid OnInitialize() {\n\t\tRenderer::VertexBufferHandle pyramidVB = mRenderer->CreatePyramid(1.75f, 1.75f);\n\t\tRenderer::VertexBufferHandle cubeVB = mRenderer->CreateCube(1.0f);\n\t\tRenderer::VertexBufferHandle planeVB = mRenderer->CreatePlane(10.0f, 7.0f);\n\n\n\t\tRenderer::MeshComponent triangle_one;\n\t\tScene::TransformComponent triangleOnePosition;\n\t\ttriangle_one.VertexBuffer = pyramidVB;\n\t\ttriangleOnePosition.position = Math::Vector3(2.0f, 0.0f, 0.0f);\n\t\tmRenderer->AttachMeshComponent(0, triangle_one);\n\t\tmTransformSystem.AttachComponent(0, triangleOnePosition);\n\n\t\tRenderer::MeshComponent cube_one;\n\t\tScene::TransformComponent cubeOnePosition;\n\t\tcube_one.VertexBuffer = cubeVB;\n\t\tcubeOnePosition.position = Math::Vector3(-2.0f, 0.0f, 0.0f);\n\t\tmRenderer->AttachMeshComponent(1, cube_one);\n\t\tmTransformSystem.AttachComponent(1, cubeOnePosition);\n\n\t\tRenderer::MeshComponent plane;\n\t\tScene::TransformComponent planeOnePosition;\n\t\tplane.VertexBuffer = planeVB;\n\t\tplaneOnePosition.position = Math::Vector3(0.0f, -1.0f, 0.0f);\n\t\tplaneOnePosition.pitch = 1.57f;\n\t\tplane.TextureId = -1;\n\t\tmRenderer->AttachMeshComponent(2, plane);\n\t\tmTransformSystem.AttachComponent(2, planeOnePosition);\n\n\t\tcameraTheta = 0.0f;\n\t}\n\n\tvoid OnUpdate() {\n\t\tRenderer::Camera& camera = mRenderer->GetCamera();\n\n\t\tmTransformSystem.Rotate(0, Math::Vector3(0.0f, mGameClock.getDeltaTime() * 2.0f, 0.0f));\n\t\tmTransformSystem.SetPosition(0, Math::Vector3(mTransformSystem.GetPosition(0).mX, (cos(cameraTheta) + 1.0f), mTransformSystem.GetPosition(0).mZ));\n\n\t\tcamera.x = cos(cameraTheta) * 15.0f;\n\t\tcamera.y = 8.0f;\n\t\tcamera.z = sin(cameraTheta) * 15.0f;\n\n\t\tcameraTheta += mGameClock.getDeltaTime();\n\t}\n\n\tvoid OnShutdown() {\n\t\tmTransformSystem.DetachComponent(2);\n\t\tmRenderer->DetachMeshComponent(2);\n\n\t\tmTransformSystem.DetachComponent(1);\n\t\tmRenderer->DetachMeshComponent(1);\n\n\t\tmTransformSystem.DetachComponent(0);\n\t\tmRenderer->DetachMeshComponent(0);\n\n\t\tmRenderer->ReleaseTexture(0);\n\t}\n\n};\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdshow) {\n\tPrimitivesApplication application;\n\tapplication.Run();\n\treturn 0;\n}\n\n#endifPrimitives sample now quits on ESC key event.\/**\n* Copyright (c) 2014-2016 Dallin Wellington\n*\n*\/\n\n\n#include \n\n#ifdef MONSOON_OS_WINDOWS\n\n#define WIN32_LEAN_AND_MEAN\n#include \n\n#include \n#include \n\nusing namespace Monsoon;\n\nclass PrimitivesApplication : public Application\n{\npublic:\n\tPrimitivesApplication()\n\t\t: Application((Renderer::Renderer*)(new Renderer::D3D11Renderer(Renderer::RendererSettings(), &mEventManager, &mTransformSystem))) {\n\n\t}\n\n\t~PrimitivesApplication() {\n\n\t}\n\nprotected:\n\tfloat cameraTheta;\n\n\tvoid OnInitialize() {\n\t\tRenderer::VertexBufferHandle pyramidVB = mRenderer->CreatePyramid(1.75f, 1.75f);\n\t\tRenderer::VertexBufferHandle cubeVB = mRenderer->CreateCube(1.0f);\n\t\tRenderer::VertexBufferHandle planeVB = mRenderer->CreatePlane(10.0f, 7.0f);\n\n\n\t\tRenderer::MeshComponent triangle_one;\n\t\tScene::TransformComponent triangleOnePosition;\n\t\ttriangle_one.VertexBuffer = pyramidVB;\n\t\ttriangleOnePosition.position = Math::Vector3(2.0f, 0.0f, 0.0f);\n\t\tmRenderer->AttachMeshComponent(0, triangle_one);\n\t\tmTransformSystem.AttachComponent(0, triangleOnePosition);\n\n\t\tRenderer::MeshComponent cube_one;\n\t\tScene::TransformComponent cubeOnePosition;\n\t\tcube_one.VertexBuffer = cubeVB;\n\t\tcubeOnePosition.position = Math::Vector3(-2.0f, 0.0f, 0.0f);\n\t\tmRenderer->AttachMeshComponent(1, cube_one);\n\t\tmTransformSystem.AttachComponent(1, cubeOnePosition);\n\n\t\tRenderer::MeshComponent plane;\n\t\tScene::TransformComponent planeOnePosition;\n\t\tplane.VertexBuffer = planeVB;\n\t\tplaneOnePosition.position = Math::Vector3(0.0f, -1.0f, 0.0f);\n\t\tplaneOnePosition.pitch = 1.57f;\n\t\tplane.TextureId = -1;\n\t\tmRenderer->AttachMeshComponent(2, plane);\n\t\tmTransformSystem.AttachComponent(2, planeOnePosition);\n\n\t\tcameraTheta = 0.0f;\n\t}\n\n\tvoid OnUpdate() {\n\t\tRenderer::Camera& camera = mRenderer->GetCamera();\n\n\t\tmTransformSystem.Rotate(0, Math::Vector3(0.0f, mGameClock.getDeltaTime() * 2.0f, 0.0f));\n\t\tmTransformSystem.SetPosition(0, Math::Vector3(mTransformSystem.GetPosition(0).mX, (cos(cameraTheta) + 1.0f), mTransformSystem.GetPosition(0).mZ));\n\n\t\tcamera.x = cos(cameraTheta) * 15.0f;\n\t\tcamera.y = 8.0f;\n\t\tcamera.z = sin(cameraTheta) * 15.0f;\n\n\t\tcameraTheta += mGameClock.getDeltaTime();\n\n\t\tif (GetAsyncKeyState(VK_ESCAPE))\n\t\t\tQuit();\n\t}\n\n\tvoid OnShutdown() {\n\t\tmTransformSystem.DetachComponent(2);\n\t\tmRenderer->DetachMeshComponent(2);\n\n\t\tmTransformSystem.DetachComponent(1);\n\t\tmRenderer->DetachMeshComponent(1);\n\n\t\tmTransformSystem.DetachComponent(0);\n\t\tmRenderer->DetachMeshComponent(0);\n\t}\n\n};\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdshow) {\n\tPrimitivesApplication application;\n\tapplication.Run();\n\treturn 0;\n}\n\n#endif<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright Antoine Leblanc 2010 - 2015\n\/\/ Distributed under the MIT license.\n\/\/\n\/\/ http:\/\/nauths.fr\n\/\/ http:\/\/github.com\/nicuveo\n\/\/ mailto:\/\/antoine.jp.leblanc@gmail.com\n\/\/\n\n#ifndef NPL_RANGE_HH_\n# define NPL_RANGE_HH_\n\n\n\n\/\/HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH\n\/\/ Includes\n\n# include \"nauths\/npl\/pair.hh\"\n\n\n\n\/\/HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH\n\/\/ Declarations\n\nnamespace npl\n{\n\n template \n class Range : public std::pair\n {\n public:\n using std::pair::pair;\n\n T const& begin() const { return this->first; }\n T const& end() const { return this->second; }\n };\n\n template \n Range range(C const& c)\n {\n return Range(c.begin(), c.end());\n }\n\n template \n Range range(C& c)\n {\n return Range(c.begin(), c.end());\n }\n\n template \n Range rrange(C const& c)\n {\n return Range(c.rbegin(), c.rend());\n }\n\n template \n Range rrange(C& c)\n {\n return Range(c.rbegin(), c.rend());\n }\n\n}\n\n\n\n#endif \/* !NPL_RANGE_HH_ *\/\nFixed range functions template.\/\/\n\/\/ Copyright Antoine Leblanc 2010 - 2015\n\/\/ Distributed under the MIT license.\n\/\/\n\/\/ http:\/\/nauths.fr\n\/\/ http:\/\/github.com\/nicuveo\n\/\/ mailto:\/\/antoine.jp.leblanc@gmail.com\n\/\/\n\n#ifndef NPL_RANGE_HH_\n# define NPL_RANGE_HH_\n\n\n\n\/\/HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH\n\/\/ Includes\n\n# include \"nauths\/npl\/pair.hh\"\n\n\n\n\/\/HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH\n\/\/ Declarations\n\nnamespace npl\n{\n\n template \n class Range : public std::pair\n {\n public:\n using std::pair::pair;\n\n T const& begin() const { return this->first; }\n T const& end() const { return this->second; }\n };\n\n template \n Range range(C const& c)\n {\n return Range(c.begin(), c.end());\n }\n\n template \n Range range(C& c)\n {\n return Range(c.begin(), c.end());\n }\n\n template \n Range rrange(C const& c)\n {\n return Range(c.rbegin(), c.rend());\n }\n\n template \n Range rrange(C& c)\n {\n return Range(c.rbegin(), c.rend());\n }\n\n}\n\n\n\n#endif \/* !NPL_RANGE_HH_ *\/\n<|endoftext|>"} {"text":"#ifndef LIBTEN_TASK_CONTEXT_HH\n#define LIBTEN_TASK_CONTEXT_HH\n\n\/\/! \\file\n\/\/! context handles switching stacks\n\/\/\n\/\/! there are two implementations, ucontext\n\/\/! and fcontext. ucontext is slower because it\n\/\/! also saves and restores the signal handler state\n\/\/! this requires system calls. fcontext only saves\n\/\/! the bare minimum register states.\n\n#if USE_BOOST_FCONTEXT\n#include \n#include \n\nnamespace ten {\n\nstruct context : boost::ctx::fcontext_t {\n typedef void (*proc)(void *);\n typedef void (*proc_ctx)(intptr_t);\n intptr_t arg;\n\n void init(proc f=nullptr, void *arg_=nullptr, char *stack=nullptr, size_t stack_size=0) {\n memset(this, 0, sizeof(context));\n arg = (intptr_t)arg_;\n if (f && stack && stack_size) {\n fc_stack.base = stack;\n \/\/ stack grows down\n fc_stack.limit = stack-stack_size;\n boost::ctx::make_fcontext(this, (proc_ctx)f);\n }\n }\n\n void swap(context *other) {\n boost::ctx::jump_fcontext(this, other, other->arg);\n }\n};\n\n} \/\/ end namespace ten \n\n#else\n#error \"no context implementation chosen\"\n#endif\n\n#endif \/\/ LIBTEN_TASK_CONTEXT_HH\nsupport boost 1.52#ifndef LIBTEN_TASK_CONTEXT_HH\n#define LIBTEN_TASK_CONTEXT_HH\n\n\/\/! \\file\n\/\/! context handles switching stacks\n\/\/\n\/\/! there are two implementations, ucontext\n\/\/! and fcontext. ucontext is slower because it\n\/\/! also saves and restores the signal handler state\n\/\/! this requires system calls. fcontext only saves\n\/\/! the bare minimum register states.\n\n#if USE_BOOST_FCONTEXT\n#include \n#include \n#include \n\nnamespace ten {\n\n#if BOOST_VERSION == 105100\nstruct context : boost::ctx::fcontext_t {\n typedef void (*proc)(void *);\n typedef void (*proc_ctx)(intptr_t);\n intptr_t arg;\n\n void init(proc f=nullptr, void *arg_=nullptr, char *stack=nullptr, size_t stack_size=0) {\n memset(this, 0, sizeof(context));\n arg = (intptr_t)arg_;\n if (f && stack && stack_size) {\n fc_stack.base = stack;\n \/\/ stack grows down\n fc_stack.limit = stack-stack_size;\n boost::ctx::make_fcontext(this, (proc_ctx)f);\n }\n }\n\n void swap(context *other) {\n boost::ctx::jump_fcontext(this, other, other->arg);\n }\n};\n#elif BOOST_VERSION >= 105200\nstruct context : boost::context::fcontext_t {\n typedef void (*proc)(void *);\n typedef void (*proc_ctx)(intptr_t);\n intptr_t arg;\n boost::context::fcontext_t *ctx;\n\n void init(proc f=nullptr, void *arg_=nullptr, char *stack=nullptr, size_t stack_size=0) {\n memset(this, 0, sizeof(context));\n arg = (intptr_t)arg_;\n if (f && stack && stack_size) {\n ctx = boost::context::make_fcontext(stack, stack_size, (proc_ctx)f);\n } else {\n ctx = this;\n }\n }\n\n void swap(context *other) {\n boost::context::jump_fcontext(ctx, other->ctx, other->arg);\n }\n};\n#endif\n\n} \/\/ end namespace ten \n\n#else\n#error \"no context implementation chosen\"\n#endif\n\n#endif \/\/ LIBTEN_TASK_CONTEXT_HH\n<|endoftext|>"} {"text":"\/* t-encrypt.cpp\n\n This file is part of qgpgme, the Qt API binding for gpgme\n Copyright (c) 2016 Intevation GmbH\n\n QGpgME 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 QGpgME 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 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 In addition, as a special exception, the copyright holders give\n permission to link the code of this program with any edition of\n the Qt library by Trolltech AS, Norway (or with modified versions\n of Qt that use the same license as Qt), and distribute linked\n combinations including the two. You must obey the GNU General\n Public License in all respects for all of the code used other than\n Qt. If you modify this file, you may extend this exception to\n your version of the file, but you are not obligated to do so. If\n you do not wish to do so, delete this exception statement from\n your version.\n*\/\n#ifdef HAVE_CONFIG_H\n #include \"config.h\"\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \"keylistjob.h\"\n#include \"encryptjob.h\"\n#include \"signencryptjob.h\"\n#include \"signingresult.h\"\n#include \"qgpgmeencryptjob.h\"\n#include \"encryptionresult.h\"\n#include \"decryptionresult.h\"\n#include \"qgpgmedecryptjob.h\"\n#include \"qgpgmebackend.h\"\n#include \"keylistresult.h\"\n#include \"engineinfo.h\"\n#include \"verifyopaquejob.h\"\n#include \"t-support.h\"\n\n#define PROGRESS_TEST_SIZE 1 * 1024 * 1024\n\nusing namespace QGpgME;\nusing namespace GpgME;\n\nstatic bool decryptSupported()\n{\n \/* With GnuPG 2.0.x (at least 2.0.26 by default on jessie)\n * the passphrase_cb does not work. So the test popped up\n * a pinentry. So tests requiring decryption don't work. *\/\n static auto version = GpgME::engineInfo(GpgME::GpgEngine).engineVersion();\n if (version < \"2.0.0\") {\n \/* With 1.4 it just works *\/\n return true;\n }\n if (version < \"2.1.0\") {\n \/* With 2.1 it works with loopback mode *\/\n return false;\n }\n return true;\n}\n\nclass EncryptionTest : public QGpgMETest\n{\n Q_OBJECT\n\nQ_SIGNALS:\n void asyncDone();\n\nprivate Q_SLOTS:\n\n void testSimpleEncryptDecrypt()\n {\n auto listjob = openpgp()->keyListJob(false, false, false);\n std::vector keys;\n auto keylistresult = listjob->exec(QStringList() << QStringLiteral(\"alfa@example.net\"),\n false, keys);\n QVERIFY(!keylistresult.error());\n QVERIFY(keys.size() == 1);\n delete listjob;\n\n auto job = openpgp()->encryptJob(\/*ASCII Armor *\/true, \/* Textmode *\/ true);\n QVERIFY(job);\n QByteArray cipherText;\n auto result = job->exec(keys, QStringLiteral(\"Hello World\").toUtf8(), Context::AlwaysTrust, cipherText);\n delete job;\n QVERIFY(!result.error());\n const auto cipherString = QString::fromUtf8(cipherText);\n QVERIFY(cipherString.startsWith(\"-----BEGIN PGP MESSAGE-----\"));\n\n \/* Now decrypt *\/\n if (!decryptSupported()) {\n return;\n }\n auto ctx = Context::createForProtocol(OpenPGP);\n TestPassphraseProvider provider;\n ctx->setPassphraseProvider(&provider);\n ctx->setPinentryMode(Context::PinentryLoopback);\n auto decJob = new QGpgMEDecryptJob(ctx);\n QByteArray plainText;\n auto decResult = decJob->exec(cipherText, plainText);\n QVERIFY(!decResult.error());\n QVERIFY(QString::fromUtf8(plainText) == QStringLiteral(\"Hello World\"));\n delete decJob;\n }\n\n void testProgress()\n {\n if (GpgME::engineInfo(GpgME::GpgEngine).engineVersion() < \"2.1.15\") {\n \/\/ We can only test the progress with 2.1.15 as this started to\n \/\/ have total progress for memory callbacks\n return;\n }\n auto listjob = openpgp()->keyListJob(false, false, false);\n std::vector keys;\n auto keylistresult = listjob->exec(QStringList() << QStringLiteral(\"alfa@example.net\"),\n false, keys);\n QVERIFY(!keylistresult.error());\n QVERIFY(keys.size() == 1);\n delete listjob;\n\n auto job = openpgp()->encryptJob(\/*ASCII Armor *\/false, \/* Textmode *\/ false);\n QVERIFY(job);\n QByteArray plainBa;\n plainBa.fill('X', PROGRESS_TEST_SIZE);\n QByteArray cipherText;\n\n bool initSeen = false;\n bool finishSeen = false;\n connect(job, &Job::progress, this, [this, &initSeen, &finishSeen] (const QString&, int current, int total) {\n \/\/ We only check for progress 0 and max progress as the other progress\n \/\/ lines depend on the system speed and are as such unreliable to test.\n QVERIFY(total == PROGRESS_TEST_SIZE);\n if (current == 0) {\n initSeen = true;\n }\n if (current == total) {\n finishSeen = true;\n }\n QVERIFY(current >= 0 && current <= total);\n });\n connect(job, &EncryptJob::result, this, [this, &initSeen, &finishSeen] (const GpgME::EncryptionResult &,\n const QByteArray &,\n const QString,\n const GpgME::Error) {\n QVERIFY(initSeen);\n QVERIFY(finishSeen);\n Q_EMIT asyncDone();\n });\n\n auto inptr = std::shared_ptr(new QBuffer(&plainBa));\n inptr->open(QIODevice::ReadOnly);\n auto outptr = std::shared_ptr(new QBuffer(&cipherText));\n outptr->open(QIODevice::WriteOnly);\n\n job->start(keys, inptr, outptr, Context::AlwaysTrust);\n QSignalSpy spy (this, SIGNAL(asyncDone()));\n QVERIFY(spy.wait(QSIGNALSPY_TIMEOUT));\n }\n\n void testSymmetricEncryptDecrypt()\n {\n if (!decryptSupported()) {\n return;\n }\n auto ctx = Context::createForProtocol(OpenPGP);\n TestPassphraseProvider provider;\n ctx->setPassphraseProvider(&provider);\n ctx->setPinentryMode(Context::PinentryLoopback);\n ctx->setArmor(true);\n ctx->setTextMode(true);\n auto job = new QGpgMEEncryptJob(ctx);\n QByteArray cipherText;\n auto result = job->exec(std::vector(), QStringLiteral(\"Hello symmetric World\").toUtf8(), Context::AlwaysTrust, cipherText);\n delete job;\n QVERIFY(!result.error());\n const auto cipherString = QString::fromUtf8(cipherText);\n QVERIFY(cipherString.startsWith(\"-----BEGIN PGP MESSAGE-----\"));\n\n killAgent(mDir.path());\n\n auto ctx2 = Context::createForProtocol(OpenPGP);\n ctx2->setPassphraseProvider(&provider);\n ctx2->setPinentryMode(Context::PinentryLoopback);\n auto decJob = new QGpgMEDecryptJob(ctx2);\n QByteArray plainText;\n auto decResult = decJob->exec(cipherText, plainText);\n QVERIFY(!result.error());\n QVERIFY(QString::fromUtf8(plainText) == QStringLiteral(\"Hello symmetric World\"));\n delete decJob;\n }\n\nprivate:\n \/* This apparently does not work under ASAN currently. TODO fix and reeanble *\/\n void testEncryptDecryptNowrap()\n {\n \/* Now decrypt *\/\n if (!decryptSupported()) {\n return;\n }\n auto listjob = openpgp()->keyListJob(false, false, false);\n std::vector keys;\n auto keylistresult = listjob->exec(QStringList() << QStringLiteral(\"alfa@example.net\"),\n false, keys);\n QVERIFY(!keylistresult.error());\n QVERIFY(keys.size() == 1);\n delete listjob;\n\n auto job = openpgp()->signEncryptJob(\/*ASCII Armor *\/true, \/* Textmode *\/ true);\n\n auto encSignCtx = Job::context(job);\n TestPassphraseProvider provider1;\n encSignCtx->setPassphraseProvider(&provider1);\n encSignCtx->setPinentryMode(Context::PinentryLoopback);\n\n QVERIFY(job);\n QByteArray cipherText;\n auto result = job->exec(keys, keys, QStringLiteral(\"Hello World\").toUtf8(), Context::AlwaysTrust, cipherText);\n delete job;\n QVERIFY(!result.first.error());\n QVERIFY(!result.second.error());\n const auto cipherString = QString::fromUtf8(cipherText);\n QVERIFY(cipherString.startsWith(\"-----BEGIN PGP MESSAGE-----\"));\n\n \/* Now decrypt *\/\n if (!decryptSupported()) {\n return;\n }\n auto ctx = Context::createForProtocol(OpenPGP);\n TestPassphraseProvider provider;\n ctx->setPassphraseProvider(&provider);\n ctx->setPinentryMode(Context::PinentryLoopback);\n ctx->setDecryptionFlags(Context::DecryptUnwrap);\n\n auto decJob = new QGpgMEDecryptJob(ctx);\n QByteArray plainText;\n auto decResult = decJob->exec(cipherText, plainText);\n\n QVERIFY(!decResult.error());\n\n delete decJob;\n\n \/\/ Now verify the unwrapeped data.\n auto verifyJob = openpgp()->verifyOpaqueJob(true);\n QByteArray verified;\n\n auto verResult = verifyJob->exec(plainText, verified);\n QVERIFY(!verResult.error());\n delete verifyJob;\n\n QVERIFY(verResult.numSignatures() == 1);\n auto sig = verResult.signatures()[0];\n\n QVERIFY(verified == QStringLiteral(\"Hello World\"));\n }\n\nprivate:\n \/* Loopback and passphrase provider don't work for mixed encryption.\n * So this test is disabled until gnupg(?) is fixed for this. *\/\n void testMixedEncryptDecrypt()\n {\n if (!decryptSupported()) {\n return;\n }\n auto listjob = openpgp()->keyListJob(false, false, false);\n std::vector keys;\n auto keylistresult = listjob->exec(QStringList() << QStringLiteral(\"alfa@example.net\"),\n false, keys);\n QVERIFY(!keylistresult.error());\n QVERIFY(keys.size() == 1);\n delete listjob;\n\n auto ctx = Context::createForProtocol(OpenPGP);\n ctx->setPassphraseProvider(new TestPassphraseProvider);\n ctx->setPinentryMode(Context::PinentryLoopback);\n ctx->setArmor(true);\n ctx->setTextMode(true);\n auto job = new QGpgMEEncryptJob(ctx);\n QByteArray cipherText;\n printf(\"Before exec, flags: %x\\n\", Context::Symmetric | Context::AlwaysTrust);\n auto result = job->exec(keys, QStringLiteral(\"Hello symmetric World\").toUtf8(),\n static_cast(Context::Symmetric | Context::AlwaysTrust),\n cipherText);\n printf(\"After exec\\n\");\n delete job;\n QVERIFY(!result.error());\n printf(\"Cipher:\\n%s\\n\", cipherText.constData());\n const auto cipherString = QString::fromUtf8(cipherText);\n QVERIFY(cipherString.startsWith(\"-----BEGIN PGP MESSAGE-----\"));\n\n killAgent(mDir.path());\n\n \/* Now create a new homedir which with we test symetric decrypt. *\/\n QTemporaryDir tmp;\n qputenv(\"GNUPGHOME\", tmp.path().toUtf8());\n QFile agentConf(tmp.path() + QStringLiteral(\"\/gpg-agent.conf\"));\n QVERIFY(agentConf.open(QIODevice::WriteOnly));\n agentConf.write(\"allow-loopback-pinentry\");\n agentConf.close();\n\n auto ctx2 = Context::createForProtocol(OpenPGP);\n ctx2->setPassphraseProvider(new TestPassphraseProvider);\n ctx2->setPinentryMode(Context::PinentryLoopback);\n ctx2->setTextMode(true);\n auto decJob = new QGpgMEDecryptJob(ctx2);\n QByteArray plainText;\n auto decResult = decJob->exec(cipherText, plainText);\n QVERIFY(!decResult.error());\n qDebug() << \"Plain: \" << plainText;\n QVERIFY(QString::fromUtf8(plainText) == QStringLiteral(\"Hello symmetric World\"));\n delete decJob;\n\n killAgent(tmp.path());\n qputenv(\"GNUPGHOME\", mDir.path().toUtf8());\n }\n\npublic Q_SLOT:\n\n void initTestCase()\n {\n QGpgMETest::initTestCase();\n const QString gpgHome = qgetenv(\"GNUPGHOME\");\n qputenv(\"GNUPGHOME\", mDir.path().toUtf8());\n QVERIFY(mDir.isValid());\n QFile agentConf(mDir.path() + QStringLiteral(\"\/gpg-agent.conf\"));\n QVERIFY(agentConf.open(QIODevice::WriteOnly));\n agentConf.write(\"allow-loopback-pinentry\");\n agentConf.close();\n QVERIFY(copyKeyrings(gpgHome, mDir.path()));\n }\n\nprivate:\n QTemporaryDir mDir;\n};\n\nQTEST_MAIN(EncryptionTest)\n\n#include \"t-encrypt.moc\"\nRevert \"qt: Disable testEncryptDecryptNowrap\"\/* t-encrypt.cpp\n\n This file is part of qgpgme, the Qt API binding for gpgme\n Copyright (c) 2016 Intevation GmbH\n\n QGpgME 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 QGpgME 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 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 In addition, as a special exception, the copyright holders give\n permission to link the code of this program with any edition of\n the Qt library by Trolltech AS, Norway (or with modified versions\n of Qt that use the same license as Qt), and distribute linked\n combinations including the two. You must obey the GNU General\n Public License in all respects for all of the code used other than\n Qt. If you modify this file, you may extend this exception to\n your version of the file, but you are not obligated to do so. If\n you do not wish to do so, delete this exception statement from\n your version.\n*\/\n#ifdef HAVE_CONFIG_H\n #include \"config.h\"\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \"keylistjob.h\"\n#include \"encryptjob.h\"\n#include \"signencryptjob.h\"\n#include \"signingresult.h\"\n#include \"qgpgmeencryptjob.h\"\n#include \"encryptionresult.h\"\n#include \"decryptionresult.h\"\n#include \"qgpgmedecryptjob.h\"\n#include \"qgpgmebackend.h\"\n#include \"keylistresult.h\"\n#include \"engineinfo.h\"\n#include \"verifyopaquejob.h\"\n#include \"t-support.h\"\n\n#define PROGRESS_TEST_SIZE 1 * 1024 * 1024\n\nusing namespace QGpgME;\nusing namespace GpgME;\n\nstatic bool decryptSupported()\n{\n \/* With GnuPG 2.0.x (at least 2.0.26 by default on jessie)\n * the passphrase_cb does not work. So the test popped up\n * a pinentry. So tests requiring decryption don't work. *\/\n static auto version = GpgME::engineInfo(GpgME::GpgEngine).engineVersion();\n if (version < \"2.0.0\") {\n \/* With 1.4 it just works *\/\n return true;\n }\n if (version < \"2.1.0\") {\n \/* With 2.1 it works with loopback mode *\/\n return false;\n }\n return true;\n}\n\nclass EncryptionTest : public QGpgMETest\n{\n Q_OBJECT\n\nQ_SIGNALS:\n void asyncDone();\n\nprivate Q_SLOTS:\n\n void testSimpleEncryptDecrypt()\n {\n auto listjob = openpgp()->keyListJob(false, false, false);\n std::vector keys;\n auto keylistresult = listjob->exec(QStringList() << QStringLiteral(\"alfa@example.net\"),\n false, keys);\n QVERIFY(!keylistresult.error());\n QVERIFY(keys.size() == 1);\n delete listjob;\n\n auto job = openpgp()->encryptJob(\/*ASCII Armor *\/true, \/* Textmode *\/ true);\n QVERIFY(job);\n QByteArray cipherText;\n auto result = job->exec(keys, QStringLiteral(\"Hello World\").toUtf8(), Context::AlwaysTrust, cipherText);\n delete job;\n QVERIFY(!result.error());\n const auto cipherString = QString::fromUtf8(cipherText);\n QVERIFY(cipherString.startsWith(\"-----BEGIN PGP MESSAGE-----\"));\n\n \/* Now decrypt *\/\n if (!decryptSupported()) {\n return;\n }\n auto ctx = Context::createForProtocol(OpenPGP);\n TestPassphraseProvider provider;\n ctx->setPassphraseProvider(&provider);\n ctx->setPinentryMode(Context::PinentryLoopback);\n auto decJob = new QGpgMEDecryptJob(ctx);\n QByteArray plainText;\n auto decResult = decJob->exec(cipherText, plainText);\n QVERIFY(!decResult.error());\n QVERIFY(QString::fromUtf8(plainText) == QStringLiteral(\"Hello World\"));\n delete decJob;\n }\n\n void testProgress()\n {\n if (GpgME::engineInfo(GpgME::GpgEngine).engineVersion() < \"2.1.15\") {\n \/\/ We can only test the progress with 2.1.15 as this started to\n \/\/ have total progress for memory callbacks\n return;\n }\n auto listjob = openpgp()->keyListJob(false, false, false);\n std::vector keys;\n auto keylistresult = listjob->exec(QStringList() << QStringLiteral(\"alfa@example.net\"),\n false, keys);\n QVERIFY(!keylistresult.error());\n QVERIFY(keys.size() == 1);\n delete listjob;\n\n auto job = openpgp()->encryptJob(\/*ASCII Armor *\/false, \/* Textmode *\/ false);\n QVERIFY(job);\n QByteArray plainBa;\n plainBa.fill('X', PROGRESS_TEST_SIZE);\n QByteArray cipherText;\n\n bool initSeen = false;\n bool finishSeen = false;\n connect(job, &Job::progress, this, [this, &initSeen, &finishSeen] (const QString&, int current, int total) {\n \/\/ We only check for progress 0 and max progress as the other progress\n \/\/ lines depend on the system speed and are as such unreliable to test.\n QVERIFY(total == PROGRESS_TEST_SIZE);\n if (current == 0) {\n initSeen = true;\n }\n if (current == total) {\n finishSeen = true;\n }\n QVERIFY(current >= 0 && current <= total);\n });\n connect(job, &EncryptJob::result, this, [this, &initSeen, &finishSeen] (const GpgME::EncryptionResult &,\n const QByteArray &,\n const QString,\n const GpgME::Error) {\n QVERIFY(initSeen);\n QVERIFY(finishSeen);\n Q_EMIT asyncDone();\n });\n\n auto inptr = std::shared_ptr(new QBuffer(&plainBa));\n inptr->open(QIODevice::ReadOnly);\n auto outptr = std::shared_ptr(new QBuffer(&cipherText));\n outptr->open(QIODevice::WriteOnly);\n\n job->start(keys, inptr, outptr, Context::AlwaysTrust);\n QSignalSpy spy (this, SIGNAL(asyncDone()));\n QVERIFY(spy.wait(QSIGNALSPY_TIMEOUT));\n }\n\n void testSymmetricEncryptDecrypt()\n {\n if (!decryptSupported()) {\n return;\n }\n auto ctx = Context::createForProtocol(OpenPGP);\n TestPassphraseProvider provider;\n ctx->setPassphraseProvider(&provider);\n ctx->setPinentryMode(Context::PinentryLoopback);\n ctx->setArmor(true);\n ctx->setTextMode(true);\n auto job = new QGpgMEEncryptJob(ctx);\n QByteArray cipherText;\n auto result = job->exec(std::vector(), QStringLiteral(\"Hello symmetric World\").toUtf8(), Context::AlwaysTrust, cipherText);\n delete job;\n QVERIFY(!result.error());\n const auto cipherString = QString::fromUtf8(cipherText);\n QVERIFY(cipherString.startsWith(\"-----BEGIN PGP MESSAGE-----\"));\n\n killAgent(mDir.path());\n\n auto ctx2 = Context::createForProtocol(OpenPGP);\n ctx2->setPassphraseProvider(&provider);\n ctx2->setPinentryMode(Context::PinentryLoopback);\n auto decJob = new QGpgMEDecryptJob(ctx2);\n QByteArray plainText;\n auto decResult = decJob->exec(cipherText, plainText);\n QVERIFY(!result.error());\n QVERIFY(QString::fromUtf8(plainText) == QStringLiteral(\"Hello symmetric World\"));\n delete decJob;\n }\n\n void testEncryptDecryptNowrap()\n {\n \/* Now decrypt *\/\n if (!decryptSupported()) {\n return;\n }\n auto listjob = openpgp()->keyListJob(false, false, false);\n std::vector keys;\n auto keylistresult = listjob->exec(QStringList() << QStringLiteral(\"alfa@example.net\"),\n false, keys);\n QVERIFY(!keylistresult.error());\n QVERIFY(keys.size() == 1);\n delete listjob;\n\n auto job = openpgp()->signEncryptJob(\/*ASCII Armor *\/true, \/* Textmode *\/ true);\n\n auto encSignCtx = Job::context(job);\n TestPassphraseProvider provider1;\n encSignCtx->setPassphraseProvider(&provider1);\n encSignCtx->setPinentryMode(Context::PinentryLoopback);\n\n QVERIFY(job);\n QByteArray cipherText;\n auto result = job->exec(keys, keys, QStringLiteral(\"Hello World\").toUtf8(), Context::AlwaysTrust, cipherText);\n delete job;\n QVERIFY(!result.first.error());\n QVERIFY(!result.second.error());\n const auto cipherString = QString::fromUtf8(cipherText);\n QVERIFY(cipherString.startsWith(\"-----BEGIN PGP MESSAGE-----\"));\n\n \/* Now decrypt *\/\n if (!decryptSupported()) {\n return;\n }\n auto ctx = Context::createForProtocol(OpenPGP);\n TestPassphraseProvider provider;\n ctx->setPassphraseProvider(&provider);\n ctx->setPinentryMode(Context::PinentryLoopback);\n ctx->setDecryptionFlags(Context::DecryptUnwrap);\n\n auto decJob = new QGpgMEDecryptJob(ctx);\n QByteArray plainText;\n auto decResult = decJob->exec(cipherText, plainText);\n\n QVERIFY(!decResult.error());\n\n delete decJob;\n\n \/\/ Now verify the unwrapeped data.\n auto verifyJob = openpgp()->verifyOpaqueJob(true);\n QByteArray verified;\n\n auto verResult = verifyJob->exec(plainText, verified);\n QVERIFY(!verResult.error());\n delete verifyJob;\n\n QVERIFY(verResult.numSignatures() == 1);\n auto sig = verResult.signatures()[0];\n\n QVERIFY(verified == QStringLiteral(\"Hello World\"));\n }\n\nprivate:\n \/* Loopback and passphrase provider don't work for mixed encryption.\n * So this test is disabled until gnupg(?) is fixed for this. *\/\n void testMixedEncryptDecrypt()\n {\n if (!decryptSupported()) {\n return;\n }\n auto listjob = openpgp()->keyListJob(false, false, false);\n std::vector keys;\n auto keylistresult = listjob->exec(QStringList() << QStringLiteral(\"alfa@example.net\"),\n false, keys);\n QVERIFY(!keylistresult.error());\n QVERIFY(keys.size() == 1);\n delete listjob;\n\n auto ctx = Context::createForProtocol(OpenPGP);\n ctx->setPassphraseProvider(new TestPassphraseProvider);\n ctx->setPinentryMode(Context::PinentryLoopback);\n ctx->setArmor(true);\n ctx->setTextMode(true);\n auto job = new QGpgMEEncryptJob(ctx);\n QByteArray cipherText;\n printf(\"Before exec, flags: %x\\n\", Context::Symmetric | Context::AlwaysTrust);\n auto result = job->exec(keys, QStringLiteral(\"Hello symmetric World\").toUtf8(),\n static_cast(Context::Symmetric | Context::AlwaysTrust),\n cipherText);\n printf(\"After exec\\n\");\n delete job;\n QVERIFY(!result.error());\n printf(\"Cipher:\\n%s\\n\", cipherText.constData());\n const auto cipherString = QString::fromUtf8(cipherText);\n QVERIFY(cipherString.startsWith(\"-----BEGIN PGP MESSAGE-----\"));\n\n killAgent(mDir.path());\n\n \/* Now create a new homedir which with we test symetric decrypt. *\/\n QTemporaryDir tmp;\n qputenv(\"GNUPGHOME\", tmp.path().toUtf8());\n QFile agentConf(tmp.path() + QStringLiteral(\"\/gpg-agent.conf\"));\n QVERIFY(agentConf.open(QIODevice::WriteOnly));\n agentConf.write(\"allow-loopback-pinentry\");\n agentConf.close();\n\n auto ctx2 = Context::createForProtocol(OpenPGP);\n ctx2->setPassphraseProvider(new TestPassphraseProvider);\n ctx2->setPinentryMode(Context::PinentryLoopback);\n ctx2->setTextMode(true);\n auto decJob = new QGpgMEDecryptJob(ctx2);\n QByteArray plainText;\n auto decResult = decJob->exec(cipherText, plainText);\n QVERIFY(!decResult.error());\n qDebug() << \"Plain: \" << plainText;\n QVERIFY(QString::fromUtf8(plainText) == QStringLiteral(\"Hello symmetric World\"));\n delete decJob;\n\n killAgent(tmp.path());\n qputenv(\"GNUPGHOME\", mDir.path().toUtf8());\n }\n\npublic Q_SLOT:\n\n void initTestCase()\n {\n QGpgMETest::initTestCase();\n const QString gpgHome = qgetenv(\"GNUPGHOME\");\n qputenv(\"GNUPGHOME\", mDir.path().toUtf8());\n QVERIFY(mDir.isValid());\n QFile agentConf(mDir.path() + QStringLiteral(\"\/gpg-agent.conf\"));\n QVERIFY(agentConf.open(QIODevice::WriteOnly));\n agentConf.write(\"allow-loopback-pinentry\");\n agentConf.close();\n QVERIFY(copyKeyrings(gpgHome, mDir.path()));\n }\n\nprivate:\n QTemporaryDir mDir;\n};\n\nQTEST_MAIN(EncryptionTest)\n\n#include \"t-encrypt.moc\"\n<|endoftext|>"} {"text":"\/** \n * @file llthread.cpp\n *\n * $LicenseInfo:firstyear=2004&license=viewerlgpl$\n * Second Life Viewer Source Code\n * Copyright (C) 2010-2013, Linden Research, Inc.\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;\n * version 2.1 of the License only.\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 * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA\n * $\/LicenseInfo$\n *\/\n\n#include \"linden_common.h\"\n#include \"llapr.h\"\n\n#include \"apr_portable.h\"\n\n#include \"llthread.h\"\n#include \"llmutex.h\"\n\n#include \"lltimer.h\"\n#include \"lltrace.h\"\n#include \"lltracethreadrecorder.h\"\n\n#if LL_LINUX || LL_SOLARIS\n#include \n#endif\n\n\n#ifdef LL_WINDOWS\nconst DWORD MS_VC_EXCEPTION=0x406D1388;\n\n#pragma pack(push,8)\ntypedef struct tagTHREADNAME_INFO\n{\n\tDWORD dwType; \/\/ Must be 0x1000.\n\tLPCSTR szName; \/\/ Pointer to name (in user addr space).\n\tDWORD dwThreadID; \/\/ Thread ID (-1=caller thread).\n\tDWORD dwFlags; \/\/ Reserved for future use, must be zero.\n} THREADNAME_INFO;\n#pragma pack(pop)\n\nvoid set_thread_name( DWORD dwThreadID, const char* threadName)\n{\n\tTHREADNAME_INFO info;\n\tinfo.dwType = 0x1000;\n\tinfo.szName = threadName;\n\tinfo.dwThreadID = dwThreadID;\n\tinfo.dwFlags = 0;\n\n\t__try\n\t{\n\t\t\/\/ Proper arguments for RaiseException\n\t\t\/\/ ::RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)\/sizeof(DWORD), (DWORD*)&info );\n\t\t::RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)\/sizeof(DWORD), (ULONG_PTR*)&info );\n\t\t\/\/ <\/FS:ND>\n\t}\n\t__except(EXCEPTION_CONTINUE_EXECUTION)\n\t{\n\t}\n}\n#endif\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Usage:\n\/\/ void run_func(LLThread* thread)\n\/\/ {\n\/\/ }\n\/\/ LLThread* thread = new LLThread();\n\/\/ thread->run(run_func);\n\/\/ ...\n\/\/ thread->setQuitting();\n\/\/ while(!timeout)\n\/\/ {\n\/\/ if (thread->isStopped())\n\/\/ {\n\/\/ delete thread;\n\/\/ break;\n\/\/ }\n\/\/ }\n\/\/ \n\/\/----------------------------------------------------------------------------\n\n#if LL_DARWIN\n\/\/ statically allocated thread local storage not supported in Darwin executable formats\n#elif LL_WINDOWS\nU32 __declspec(thread) sThreadID = 0;\n#elif LL_LINUX\nU32 __thread sThreadID = 0;\n#endif \n\nU32 LLThread::sIDIter = 0;\n\n\nLL_COMMON_API void assert_main_thread()\n{\n\tstatic uintptr_t s_thread_id = LLThread::currentID();\n\tif (LLThread::currentID() != s_thread_id)\n\t{\n\t\tLL_WARNS() << \"Illegal execution from thread id \" << (intrptr_t) LLThread::currentID()\n\t\t\t<< \" outside main thread \" << (intrptr_t) s_thread_id << LL_ENDL;\n\t}\n}\n\nvoid LLThread::registerThreadID()\n{\n#if !LL_DARWIN\n\tsThreadID = ++sIDIter;\n#endif\n}\n\n\/\/\n\/\/ Handed to the APR thread creation function\n\/\/\nvoid *APR_THREAD_FUNC LLThread::staticRun(apr_thread_t *apr_threadp, void *datap)\n{\n\tLLThread *threadp = (LLThread *)datap;\n\n#ifdef LL_WINDOWS\n\tset_thread_name(-1, threadp->mName.c_str());\n#endif\n\n\t\/\/ for now, hard code all LLThreads to report to single master thread recorder, which is known to be running on main thread\n\tthreadp->mRecorder = new LLTrace::ThreadRecorder(*LLTrace::get_master_thread_recorder());\n\n#if !LL_DARWIN\n\tsThreadID = threadp->mID;\n#endif\n\n\t\/\/ Run the user supplied function\n\tthreadp->run();\n\n\t\/\/LL_INFOS() << \"LLThread::staticRun() Exiting: \" << threadp->mName << LL_ENDL;\n\t\n\tdelete threadp->mRecorder;\n\tthreadp->mRecorder = NULL;\n\t\n\t\/\/ We're done with the run function, this thread is done executing now.\n\t\/\/NB: we are using this flag to sync across threads...we really need memory barriers here\n\tthreadp->mStatus = STOPPED;\n\n\treturn NULL;\n}\n\nLLThread::LLThread(const std::string& name, apr_pool_t *poolp) :\n\tmPaused(FALSE),\n\tmName(name),\n\tmAPRThreadp(NULL),\n\tmStatus(STOPPED),\n\tmRecorder(NULL)\n{\n\n\tmID = ++sIDIter;\n\n\t\/\/ Thread creation probably CAN be paranoid about APR being initialized, if necessary\n\tif (poolp)\n\t{\n\t\tmIsLocalPool = FALSE;\n\t\tmAPRPoolp = poolp;\n\t}\n\telse\n\t{\n\t\tmIsLocalPool = TRUE;\n\t\tapr_pool_create(&mAPRPoolp, NULL); \/\/ Create a subpool for this thread\n\t}\n\tmRunCondition = new LLCondition(mAPRPoolp);\n\tmDataLock = new LLMutex(mAPRPoolp);\n\tmLocalAPRFilePoolp = NULL ;\n}\n\n\nLLThread::~LLThread()\n{\n\tshutdown();\n\n\tif(mLocalAPRFilePoolp)\n\t{\n\t\tdelete mLocalAPRFilePoolp ;\n\t\tmLocalAPRFilePoolp = NULL ;\n\t}\n}\n\nvoid LLThread::shutdown()\n{\n\t\/\/ Warning! If you somehow call the thread destructor from itself,\n\t\/\/ the thread will die in an unclean fashion!\n\tif (mAPRThreadp)\n\t{\n\t\tif (!isStopped())\n\t\t{\n\t\t\t\/\/ The thread isn't already stopped\n\t\t\t\/\/ First, set the flag that indicates that we're ready to die\n\t\t\tsetQuitting();\n\n\t\t\t\/\/LL_INFOS() << \"LLThread::~LLThread() Killing thread \" << mName << \" Status: \" << mStatus << LL_ENDL;\n\t\t\t\/\/ Now wait a bit for the thread to exit\n\t\t\t\/\/ It's unclear whether I should even bother doing this - this destructor\n\t\t\t\/\/ should never get called unless we're already stopped, really...\n\t\t\tS32 counter = 0;\n\t\t\tconst S32 MAX_WAIT = 600;\n\t\t\twhile (counter < MAX_WAIT)\n\t\t\t{\n\t\t\t\tif (isStopped())\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\/\/ Sleep for a tenth of a second\n\t\t\t\tms_sleep(100);\n\t\t\t\tyield();\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\n\t\tif (!isStopped())\n\t\t{\n\t\t\t\/\/ This thread just wouldn't stop, even though we gave it time\n\t\t\t\/\/LL_WARNS() << \"LLThread::~LLThread() exiting thread before clean exit!\" << LL_ENDL;\n\t\t\t\/\/ Put a stake in its heart.\n\t\t\tdelete mRecorder;\n\n\t\t\tapr_thread_exit(mAPRThreadp, -1);\n\t\t\treturn;\n\t\t}\n\t\tmAPRThreadp = NULL;\n\t}\n\n\tdelete mRunCondition;\n\tmRunCondition = NULL;\n\n\tdelete mDataLock;\n\tmDataLock = NULL;\n\t\n\tif (mIsLocalPool && mAPRPoolp)\n\t{\n\t\tapr_pool_destroy(mAPRPoolp);\n\t\tmAPRPoolp = 0;\n\t}\n\n\tif (mRecorder)\n\t{\n\t\t\/\/ missed chance to properly shut down recorder (needs to be done in thread context)\n\t\t\/\/ probably due to abnormal thread termination\n\t\t\/\/ so just leak it and remove it from parent\n\t\tLLTrace::get_master_thread_recorder()->removeChildRecorder(mRecorder);\n\t}\n}\n\n\nvoid LLThread::start()\n{\n\tllassert(isStopped());\n\t\n\t\/\/ Set thread state to running\n\tmStatus = RUNNING;\n\n\tapr_status_t status =\n\t\tapr_thread_create(&mAPRThreadp, NULL, staticRun, (void *)this, mAPRPoolp);\n\t\n\tif(status == APR_SUCCESS)\n\t{\t\n\t\t\/\/ We won't bother joining\n\t\tapr_thread_detach(mAPRThreadp);\n\t}\n\telse\n\t{\n\t\tmStatus = STOPPED;\n\t\tLL_WARNS() << \"failed to start thread \" << mName << LL_ENDL;\n\t\tll_apr_warn_status(status);\n\t}\n\n}\n\n\/\/============================================================================\n\/\/ Called from MAIN THREAD.\n\n\/\/ Request that the thread pause\/resume.\n\/\/ The thread will pause when (and if) it calls checkPause()\nvoid LLThread::pause()\n{\n\tif (!mPaused)\n\t{\n\t\t\/\/ this will cause the thread to stop execution as soon as checkPause() is called\n\t\tmPaused = 1;\t\t\/\/ Does not need to be atomic since this is only set\/unset from the main thread\n\t}\t\n}\n\nvoid LLThread::unpause()\n{\n\tif (mPaused)\n\t{\n\t\tmPaused = 0;\n\t}\n\n\twake(); \/\/ wake up the thread if necessary\n}\n\n\/\/ virtual predicate function -- returns true if the thread should wake up, false if it should sleep.\nbool LLThread::runCondition(void)\n{\n\t\/\/ by default, always run. Handling of pause\/unpause is done regardless of this function's result.\n\treturn true;\n}\n\n\/\/============================================================================\n\/\/ Called from run() (CHILD THREAD).\n\/\/ Stop thread execution if requested until unpaused.\nvoid LLThread::checkPause()\n{\n\tmDataLock->lock();\n\n\t\/\/ This is in a while loop because the pthread API allows for spurious wakeups.\n\twhile(shouldSleep())\n\t{\n\t\tmDataLock->unlock();\n\t\tmRunCondition->wait(); \/\/ unlocks mRunCondition\n\t\tmDataLock->lock();\n\t\t\/\/ mRunCondition is locked when the thread wakes up\n\t}\n\t\n \tmDataLock->unlock();\n}\n\n\/\/============================================================================\n\nvoid LLThread::setQuitting()\n{\n\tmDataLock->lock();\n\tif (mStatus == RUNNING)\n\t{\n\t\tmStatus = QUITTING;\n\t}\n\tmDataLock->unlock();\n\twake();\n}\n\n\/\/ static\nuintptr_t LLThread::currentID()\n{\n#if LL_DARWIN\n\t\/\/ statically allocated thread local storage not supported in Darwin executable formats\n\treturn (uintptr_t)apr_os_thread_current();\n#else\n\treturn sThreadID;\n#endif\n\n}\n\n\/\/ static\nvoid LLThread::yield()\n{\n#if LL_LINUX || LL_SOLARIS\n\tsched_yield(); \/\/ annoyingly, apr_thread_yield is a noop on linux...\n#else\n\tapr_thread_yield();\n#endif\n}\n\nvoid LLThread::wake()\n{\n\tmDataLock->lock();\n\tif(!shouldSleep())\n\t{\n\t\tmRunCondition->signal();\n\t}\n\tmDataLock->unlock();\n}\n\nvoid LLThread::wakeLocked()\n{\n\tif(!shouldSleep())\n\t{\n\t\tmRunCondition->signal();\n\t}\n}\n\n\/\/============================================================================\n\n\/\/----------------------------------------------------------------------------\n\n\/\/static\nLLMutex* LLThreadSafeRefCount::sMutex = 0;\n\n\/\/static\nvoid LLThreadSafeRefCount::initThreadSafeRefCount()\n{\n\tif (!sMutex)\n\t{\n\t\tsMutex = new LLMutex(0);\n\t}\n}\n\n\/\/static\nvoid LLThreadSafeRefCount::cleanupThreadSafeRefCount()\n{\n\tdelete sMutex;\n\tsMutex = NULL;\n}\n\t\n\n\/\/----------------------------------------------------------------------------\n\nLLThreadSafeRefCount::LLThreadSafeRefCount() :\n\tmRef(0)\n{\n}\n\nLLThreadSafeRefCount::LLThreadSafeRefCount(const LLThreadSafeRefCount& src)\n{\n\tmRef = 0;\n}\n\nLLThreadSafeRefCount::~LLThreadSafeRefCount()\n{ \n\tif (mRef != 0)\n\t{\n\t\tLL_ERRS() << \"deleting non-zero reference\" << LL_ENDL;\n\t}\n}\n\n\/\/============================================================================\n\nLLResponder::~LLResponder()\n{\n}\n\n\/\/============================================================================\nFix for typo during merge.\/** \n * @file llthread.cpp\n *\n * $LicenseInfo:firstyear=2004&license=viewerlgpl$\n * Second Life Viewer Source Code\n * Copyright (C) 2010-2013, Linden Research, Inc.\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;\n * version 2.1 of the License only.\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 * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA\n * $\/LicenseInfo$\n *\/\n\n#include \"linden_common.h\"\n#include \"llapr.h\"\n\n#include \"apr_portable.h\"\n\n#include \"llthread.h\"\n#include \"llmutex.h\"\n\n#include \"lltimer.h\"\n#include \"lltrace.h\"\n#include \"lltracethreadrecorder.h\"\n\n#if LL_LINUX || LL_SOLARIS\n#include \n#endif\n\n\n#ifdef LL_WINDOWS\nconst DWORD MS_VC_EXCEPTION=0x406D1388;\n\n#pragma pack(push,8)\ntypedef struct tagTHREADNAME_INFO\n{\n\tDWORD dwType; \/\/ Must be 0x1000.\n\tLPCSTR szName; \/\/ Pointer to name (in user addr space).\n\tDWORD dwThreadID; \/\/ Thread ID (-1=caller thread).\n\tDWORD dwFlags; \/\/ Reserved for future use, must be zero.\n} THREADNAME_INFO;\n#pragma pack(pop)\n\nvoid set_thread_name( DWORD dwThreadID, const char* threadName)\n{\n\tTHREADNAME_INFO info;\n\tinfo.dwType = 0x1000;\n\tinfo.szName = threadName;\n\tinfo.dwThreadID = dwThreadID;\n\tinfo.dwFlags = 0;\n\n\t__try\n\t{\n\t\t\/\/ Proper arguments for RaiseException\n\t\t\/\/ ::RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)\/sizeof(DWORD), (DWORD*)&info );\n\t\t::RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)\/sizeof(DWORD), (ULONG_PTR*)&info );\n\t\t\/\/ <\/FS:ND>\n\t}\n\t__except(EXCEPTION_CONTINUE_EXECUTION)\n\t{\n\t}\n}\n#endif\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Usage:\n\/\/ void run_func(LLThread* thread)\n\/\/ {\n\/\/ }\n\/\/ LLThread* thread = new LLThread();\n\/\/ thread->run(run_func);\n\/\/ ...\n\/\/ thread->setQuitting();\n\/\/ while(!timeout)\n\/\/ {\n\/\/ if (thread->isStopped())\n\/\/ {\n\/\/ delete thread;\n\/\/ break;\n\/\/ }\n\/\/ }\n\/\/ \n\/\/----------------------------------------------------------------------------\n\n#if LL_DARWIN\n\/\/ statically allocated thread local storage not supported in Darwin executable formats\n#elif LL_WINDOWS\nU32 __declspec(thread) sThreadID = 0;\n#elif LL_LINUX\nU32 __thread sThreadID = 0;\n#endif \n\nU32 LLThread::sIDIter = 0;\n\n\nLL_COMMON_API void assert_main_thread()\n{\n\tstatic uintptr_t s_thread_id = LLThread::currentID();\n\tif (LLThread::currentID() != s_thread_id)\n\t{\n\t\tLL_WARNS() << \"Illegal execution from thread id \" << (intptr_t) LLThread::currentID()\n\t\t\t<< \" outside main thread \" << (intptr_t) s_thread_id << LL_ENDL;\n\t}\n}\n\nvoid LLThread::registerThreadID()\n{\n#if !LL_DARWIN\n\tsThreadID = ++sIDIter;\n#endif\n}\n\n\/\/\n\/\/ Handed to the APR thread creation function\n\/\/\nvoid *APR_THREAD_FUNC LLThread::staticRun(apr_thread_t *apr_threadp, void *datap)\n{\n\tLLThread *threadp = (LLThread *)datap;\n\n#ifdef LL_WINDOWS\n\tset_thread_name(-1, threadp->mName.c_str());\n#endif\n\n\t\/\/ for now, hard code all LLThreads to report to single master thread recorder, which is known to be running on main thread\n\tthreadp->mRecorder = new LLTrace::ThreadRecorder(*LLTrace::get_master_thread_recorder());\n\n#if !LL_DARWIN\n\tsThreadID = threadp->mID;\n#endif\n\n\t\/\/ Run the user supplied function\n\tthreadp->run();\n\n\t\/\/LL_INFOS() << \"LLThread::staticRun() Exiting: \" << threadp->mName << LL_ENDL;\n\t\n\tdelete threadp->mRecorder;\n\tthreadp->mRecorder = NULL;\n\t\n\t\/\/ We're done with the run function, this thread is done executing now.\n\t\/\/NB: we are using this flag to sync across threads...we really need memory barriers here\n\tthreadp->mStatus = STOPPED;\n\n\treturn NULL;\n}\n\nLLThread::LLThread(const std::string& name, apr_pool_t *poolp) :\n\tmPaused(FALSE),\n\tmName(name),\n\tmAPRThreadp(NULL),\n\tmStatus(STOPPED),\n\tmRecorder(NULL)\n{\n\n\tmID = ++sIDIter;\n\n\t\/\/ Thread creation probably CAN be paranoid about APR being initialized, if necessary\n\tif (poolp)\n\t{\n\t\tmIsLocalPool = FALSE;\n\t\tmAPRPoolp = poolp;\n\t}\n\telse\n\t{\n\t\tmIsLocalPool = TRUE;\n\t\tapr_pool_create(&mAPRPoolp, NULL); \/\/ Create a subpool for this thread\n\t}\n\tmRunCondition = new LLCondition(mAPRPoolp);\n\tmDataLock = new LLMutex(mAPRPoolp);\n\tmLocalAPRFilePoolp = NULL ;\n}\n\n\nLLThread::~LLThread()\n{\n\tshutdown();\n\n\tif(mLocalAPRFilePoolp)\n\t{\n\t\tdelete mLocalAPRFilePoolp ;\n\t\tmLocalAPRFilePoolp = NULL ;\n\t}\n}\n\nvoid LLThread::shutdown()\n{\n\t\/\/ Warning! If you somehow call the thread destructor from itself,\n\t\/\/ the thread will die in an unclean fashion!\n\tif (mAPRThreadp)\n\t{\n\t\tif (!isStopped())\n\t\t{\n\t\t\t\/\/ The thread isn't already stopped\n\t\t\t\/\/ First, set the flag that indicates that we're ready to die\n\t\t\tsetQuitting();\n\n\t\t\t\/\/LL_INFOS() << \"LLThread::~LLThread() Killing thread \" << mName << \" Status: \" << mStatus << LL_ENDL;\n\t\t\t\/\/ Now wait a bit for the thread to exit\n\t\t\t\/\/ It's unclear whether I should even bother doing this - this destructor\n\t\t\t\/\/ should never get called unless we're already stopped, really...\n\t\t\tS32 counter = 0;\n\t\t\tconst S32 MAX_WAIT = 600;\n\t\t\twhile (counter < MAX_WAIT)\n\t\t\t{\n\t\t\t\tif (isStopped())\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\/\/ Sleep for a tenth of a second\n\t\t\t\tms_sleep(100);\n\t\t\t\tyield();\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\n\t\tif (!isStopped())\n\t\t{\n\t\t\t\/\/ This thread just wouldn't stop, even though we gave it time\n\t\t\t\/\/LL_WARNS() << \"LLThread::~LLThread() exiting thread before clean exit!\" << LL_ENDL;\n\t\t\t\/\/ Put a stake in its heart.\n\t\t\tdelete mRecorder;\n\n\t\t\tapr_thread_exit(mAPRThreadp, -1);\n\t\t\treturn;\n\t\t}\n\t\tmAPRThreadp = NULL;\n\t}\n\n\tdelete mRunCondition;\n\tmRunCondition = NULL;\n\n\tdelete mDataLock;\n\tmDataLock = NULL;\n\t\n\tif (mIsLocalPool && mAPRPoolp)\n\t{\n\t\tapr_pool_destroy(mAPRPoolp);\n\t\tmAPRPoolp = 0;\n\t}\n\n\tif (mRecorder)\n\t{\n\t\t\/\/ missed chance to properly shut down recorder (needs to be done in thread context)\n\t\t\/\/ probably due to abnormal thread termination\n\t\t\/\/ so just leak it and remove it from parent\n\t\tLLTrace::get_master_thread_recorder()->removeChildRecorder(mRecorder);\n\t}\n}\n\n\nvoid LLThread::start()\n{\n\tllassert(isStopped());\n\t\n\t\/\/ Set thread state to running\n\tmStatus = RUNNING;\n\n\tapr_status_t status =\n\t\tapr_thread_create(&mAPRThreadp, NULL, staticRun, (void *)this, mAPRPoolp);\n\t\n\tif(status == APR_SUCCESS)\n\t{\t\n\t\t\/\/ We won't bother joining\n\t\tapr_thread_detach(mAPRThreadp);\n\t}\n\telse\n\t{\n\t\tmStatus = STOPPED;\n\t\tLL_WARNS() << \"failed to start thread \" << mName << LL_ENDL;\n\t\tll_apr_warn_status(status);\n\t}\n\n}\n\n\/\/============================================================================\n\/\/ Called from MAIN THREAD.\n\n\/\/ Request that the thread pause\/resume.\n\/\/ The thread will pause when (and if) it calls checkPause()\nvoid LLThread::pause()\n{\n\tif (!mPaused)\n\t{\n\t\t\/\/ this will cause the thread to stop execution as soon as checkPause() is called\n\t\tmPaused = 1;\t\t\/\/ Does not need to be atomic since this is only set\/unset from the main thread\n\t}\t\n}\n\nvoid LLThread::unpause()\n{\n\tif (mPaused)\n\t{\n\t\tmPaused = 0;\n\t}\n\n\twake(); \/\/ wake up the thread if necessary\n}\n\n\/\/ virtual predicate function -- returns true if the thread should wake up, false if it should sleep.\nbool LLThread::runCondition(void)\n{\n\t\/\/ by default, always run. Handling of pause\/unpause is done regardless of this function's result.\n\treturn true;\n}\n\n\/\/============================================================================\n\/\/ Called from run() (CHILD THREAD).\n\/\/ Stop thread execution if requested until unpaused.\nvoid LLThread::checkPause()\n{\n\tmDataLock->lock();\n\n\t\/\/ This is in a while loop because the pthread API allows for spurious wakeups.\n\twhile(shouldSleep())\n\t{\n\t\tmDataLock->unlock();\n\t\tmRunCondition->wait(); \/\/ unlocks mRunCondition\n\t\tmDataLock->lock();\n\t\t\/\/ mRunCondition is locked when the thread wakes up\n\t}\n\t\n \tmDataLock->unlock();\n}\n\n\/\/============================================================================\n\nvoid LLThread::setQuitting()\n{\n\tmDataLock->lock();\n\tif (mStatus == RUNNING)\n\t{\n\t\tmStatus = QUITTING;\n\t}\n\tmDataLock->unlock();\n\twake();\n}\n\n\/\/ static\nuintptr_t LLThread::currentID()\n{\n#if LL_DARWIN\n\t\/\/ statically allocated thread local storage not supported in Darwin executable formats\n\treturn (uintptr_t)apr_os_thread_current();\n#else\n\treturn sThreadID;\n#endif\n\n}\n\n\/\/ static\nvoid LLThread::yield()\n{\n#if LL_LINUX || LL_SOLARIS\n\tsched_yield(); \/\/ annoyingly, apr_thread_yield is a noop on linux...\n#else\n\tapr_thread_yield();\n#endif\n}\n\nvoid LLThread::wake()\n{\n\tmDataLock->lock();\n\tif(!shouldSleep())\n\t{\n\t\tmRunCondition->signal();\n\t}\n\tmDataLock->unlock();\n}\n\nvoid LLThread::wakeLocked()\n{\n\tif(!shouldSleep())\n\t{\n\t\tmRunCondition->signal();\n\t}\n}\n\n\/\/============================================================================\n\n\/\/----------------------------------------------------------------------------\n\n\/\/static\nLLMutex* LLThreadSafeRefCount::sMutex = 0;\n\n\/\/static\nvoid LLThreadSafeRefCount::initThreadSafeRefCount()\n{\n\tif (!sMutex)\n\t{\n\t\tsMutex = new LLMutex(0);\n\t}\n}\n\n\/\/static\nvoid LLThreadSafeRefCount::cleanupThreadSafeRefCount()\n{\n\tdelete sMutex;\n\tsMutex = NULL;\n}\n\t\n\n\/\/----------------------------------------------------------------------------\n\nLLThreadSafeRefCount::LLThreadSafeRefCount() :\n\tmRef(0)\n{\n}\n\nLLThreadSafeRefCount::LLThreadSafeRefCount(const LLThreadSafeRefCount& src)\n{\n\tmRef = 0;\n}\n\nLLThreadSafeRefCount::~LLThreadSafeRefCount()\n{ \n\tif (mRef != 0)\n\t{\n\t\tLL_ERRS() << \"deleting non-zero reference\" << LL_ENDL;\n\t}\n}\n\n\/\/============================================================================\n\nLLResponder::~LLResponder()\n{\n}\n\n\/\/============================================================================\n<|endoftext|>"} {"text":"#include \"schandler.h\"\n\nSCHandler::SCHandler(QObject *parent)\n{\n raw_results = QJsonArray();\n}\n\n\nSCHandler::~SCHandler()\n{\n\n}\n\n\n\/\/category: artist, title, user,\nint SCHandler::query(QString key, QString value){\n\n if(value == NULL)\n return -1;\n if(key == NULL)\n return -1;\n \/\/check to prevent same query twice? nah don't be dumb\n\n \/\/ create custom temporary event loop on stack\n QEventLoop eventLoop;\n QUrl url(SC_TRACKS_URL);\n QUrlQuery query;\n query.addQueryItem(\"downloadable\", \"true\");\n query.addQueryItem(key, value);\n\n query.addQueryItem(\"client_id\", SC_CLIENT_ID);\n\n\n\n url.setQuery(query.query());\n qDebug() << url;\n\n \/\/ \"quit()\" the event-loop, when the network request \"finished()\"\n QNetworkAccessManager mgr;\n QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));\n\n \/\/ the HTTP request\n QNetworkRequest req(url);\n QNetworkReply *reply = mgr.get(req);\n eventLoop.exec(); \/\/ blocks stack until \"finished()\" has been called\n\n if (reply->error() == QNetworkReply::NoError) {\n QJsonParseError err;\n QJsonDocument jsondoc = QJsonDocument(QJsonDocument::fromJson(QString(reply->readAll()).toUtf8(), &err)); \/\/raw string to qtstring to bytecode to jsondoc fucking shit\n raw_results = jsondoc.array(); \/\/take the pile of responses and make them an array so you can fucking do something with the\n\/\/ qDebug() << raw_results;\n\n return raw_results.size();\n\n }\n else {\n \/\/failure\n qDebug() << \"Failed query: \" <errorString();\n delete reply;\n return -1;\n }\n}\n\nQJsonValue SCHandler::format(QJsonValue initial){\n QJsonObject jobj = initial.toObject();\n QString length;\n if (jobj[\"duration\"].toInt() > 0){\n QString minutes;\n QString seconds;\n int duration = jobj[\"duration\"].toInt()\/1000; \/\/ain't nobody got time for accuracy\n minutes = QString::number(duration\/60);\n seconds = QString::number(duration%60);\n if(duration\/60 < 10)\n minutes = QString(\"0\"+minutes);\n if(duration%60 < 10)\n seconds = QString(\"0\"+seconds);\n\n length = QString(minutes+\":\"+seconds);\n }\n\n QJsonObject media{\n {\"hash\", jobj[\"download_url\"].toString()},\n {\"order\",\"\"},\n };\n\n QJsonObject meta{\n {\"title\", jobj[\"title\"].toString()},\n {\"album\",\"\"}, \/\/nope because soundcloud\n {\"artist\", jobj[\"user\"].toObject()[\"username\"].toString()},\n {\"track_number\", 0},\n {\"length\", length}, \/\/get from fucking duration\n {\"genre\", jobj[\"genre\"].toString()}\n };\n \/\/add meta to media\n media[\"metadata\"] = meta;\n\n return QJsonValue(media);\n}\n\nQJsonArray SCHandler::search(QString value, QString key){\n QJsonArray results = QJsonArray();\n QJsonObject jobj;\n QString result;\n int num_queried = query(key, value);\n for(int i=0; i results.size())\n count = results.size();\n for(int i=0; ierror() == QNetworkReply::NoError) {\n \/\/get temp download url as json\n QJsonDocument jsondoc = QJsonDocument(QJsonDocument::fromJson(QString(reply->readAll()).toUtf8()));\n QJsonObject jobj = jsondoc.object();\n QString download_url = jobj[\"location\"].toString();\n\n \/\/download\n if (reply->error() == QNetworkReply::NoError) {\n req_url = download_url;\n QUrl url(req_url);\n QNetworkRequest req(url);\n req.setRawHeader(\"User-Agent\",USER_AGENT);\n QNetworkReply *reply = mgr.get(req);\n eventLoop.exec();\n\n return reply->readAll();\n\n }\n else{\n qDebug() << \"Failure on download request\" <errorString();\n delete reply;\n return NULL;\n }\n\n }\n else {\n \/\/failure\n qDebug() << \"Failure on initial request\" <errorString();\n delete reply;\n return NULL;\n }\n}\n\n\nFixed minor bug in schandler#include \"schandler.h\"\n\nSCHandler::SCHandler(QObject *parent)\n{\n raw_results = QJsonArray();\n}\n\n\nSCHandler::~SCHandler()\n{\n\n}\n\n\n\/\/category: artist, title, user,\nint SCHandler::query(QString key, QString value){\n\n if(value == NULL)\n return -1;\n if(key == NULL)\n return -1;\n \/\/check to prevent same query twice? nah don't be dumb\n\n \/\/ create custom temporary event loop on stack\n QEventLoop eventLoop;\n QUrl url(SC_TRACKS_URL);\n QUrlQuery query;\n query.addQueryItem(\"downloadable\", \"true\");\n query.addQueryItem(key, value);\n\n query.addQueryItem(\"client_id\", SC_CLIENT_ID);\n\n\n\n url.setQuery(query.query());\n qDebug() << url;\n\n \/\/ \"quit()\" the event-loop, when the network request \"finished()\"\n QNetworkAccessManager mgr;\n QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));\n\n \/\/ the HTTP request\n QNetworkRequest req(url);\n QNetworkReply *reply = mgr.get(req);\n eventLoop.exec(); \/\/ blocks stack until \"finished()\" has been called\n\n if (reply->error() == QNetworkReply::NoError) {\n QJsonParseError err;\n QJsonDocument jsondoc = QJsonDocument(QJsonDocument::fromJson(QString(reply->readAll()).toUtf8(), &err)); \/\/raw string to qtstring to bytecode to jsondoc fucking shit\n raw_results = jsondoc.array(); \/\/take the pile of responses and make them an array so you can fucking do something with the\n\/\/ qDebug() << raw_results;\n\n return raw_results.size();\n\n }\n else {\n \/\/failure\n qDebug() << \"Failed query: \" <errorString();\n delete reply;\n return -1;\n }\n}\n\nQJsonValue SCHandler::format(QJsonValue initial){\n QJsonObject jobj = initial.toObject();\n QString length;\n if (jobj[\"duration\"].toInt() > 0){\n QString minutes;\n QString seconds;\n int duration = jobj[\"duration\"].toInt()\/1000; \/\/ain't nobody got time for accuracy\n minutes = QString::number(duration\/60);\n seconds = QString::number(duration%60);\n if(duration\/60 < 10)\n minutes = QString(\"0\"+minutes);\n if(duration%60 < 10)\n seconds = QString(\"0\"+seconds);\n\n length = QString(minutes+\":\"+seconds);\n }\n\n QJsonObject media{\n {\"hash\", jobj[\"download_url\"].toString()},\n {\"order\",\"\"},\n };\n\n QJsonObject meta{\n {\"title\", jobj[\"title\"].toString()},\n {\"album\",\"\"}, \/\/nope because soundcloud\n {\"artist\", jobj[\"user\"].toObject()[\"username\"].toString()},\n {\"track_number\", 0},\n {\"length\", length}, \/\/get from fucking duration\n {\"genre\", jobj[\"genre\"].toString()}\n };\n \/\/add meta to media\n media[\"metadata\"] = meta;\n\n return QJsonValue(media);\n}\n\nQJsonArray SCHandler::search(QString value, QString key){\n QJsonArray results = QJsonArray();\n QJsonObject jobj;\n QString result;\n int num_queried = query(key, value);\n for(int i=0; i results.size())\n count = results.size();\n for(int i=0; ierror() == QNetworkReply::NoError) {\n \/\/get temp download url as json\n QJsonDocument jsondoc = QJsonDocument(QJsonDocument::fromJson(QString(reply->readAll()).toUtf8()));\n QJsonObject jobj = jsondoc.object();\n QString download_url = jobj[\"location\"].toString();\n\n \/\/download\n if (reply->error() == QNetworkReply::NoError) {\n req_url = download_url;\n QUrl url(req_url);\n QNetworkRequest req(url);\n req.setRawHeader(\"User-Agent\",USER_AGENT);\n QNetworkReply *reply = mgr.get(req);\n eventLoop.exec();\n\n return reply->readAll();\n\n }\n else{\n qDebug() << \"Failure on download request\" <errorString();\n delete reply;\n return NULL;\n }\n\n }\n else {\n \/\/failure\n qDebug() << \"Failure on initial request\" <errorString();\n delete reply;\n return NULL;\n }\n}\n\n\n<|endoftext|>"} {"text":"#include \"schandler.h\"\n\nSCHandler::SCHandler(QObject *parent)\n{\n raw_results = QJsonArray();\n}\n\n\nSCHandler::~SCHandler()\n{\n\n}\n\n\n\/\/category: artist, title, user,\nint SCHandler::query(QString key, QString value){\n\n if(value == NULL)\n return -1;\n if(key == NULL)\n return -1;\n \/\/check to prevent same query twice? nah don't be dumb\n\n \/\/ create custom temporary event loop on stack\n QEventLoop eventLoop;\n QUrl url(SC_TRACKS_URL);\n QUrlQuery query;\n query.addQueryItem(\"downloadable\", \"true\");\n query.addQueryItem(key, value);\n\n query.addQueryItem(\"client_id\", SC_CLIENT_ID);\n\n\n\n url.setQuery(query.query());\n qDebug() << url;\n\n \/\/ \"quit()\" the event-loop, when the network request \"finished()\"\n QNetworkAccessManager mgr;\n QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));\n\n \/\/ the HTTP request\n QNetworkRequest req(url);\n QNetworkReply *reply = mgr.get(req);\n eventLoop.exec(); \/\/ blocks stack until \"finished()\" has been called\n\n if (reply->error() == QNetworkReply::NoError) {\n QJsonParseError err;\n QJsonDocument jsondoc = QJsonDocument(QJsonDocument::fromJson(QString(reply->readAll()).toUtf8(), &err)); \/\/raw string to qtstring to bytecode to jsondoc fucking shit\n raw_results = jsondoc.array(); \/\/take the pile of responses and make them an array so you can fucking do something with the\n\/\/ qDebug() << raw_results;\n\n return raw_results.size();\n\n }\n else {\n \/\/failure\n qDebug() << \"Failed query: \" <errorString();\n delete reply;\n return -1;\n }\n}\n\nQJsonValue SCHandler::format(QJsonValue initial){\n QJsonObject jobj = initial.toObject();\n QString length;\n if (jobj[\"duration\"].toInt() > 0){\n QString minutes;\n QString seconds;\n int duration = jobj[\"duration\"].toInt()\/1000; \/\/ain't nobody got time for accuracy\n minutes = QString::number(duration\/60);\n seconds = QString::number(duration%60);\n if(duration\/60 < 10)\n minutes = QString(\"0\"+minutes);\n if(duration%60 < 10)\n seconds = QString(\"0\"+seconds);\n\n length = QString(minutes+\":\"+seconds);\n }\n\n QJsonObject media{\n {\"hash\", jobj[\"download_url\"].toString()},\n {\"order\",\"\"},\n };\n\n QJsonObject meta{\n {\"title\", jobj[\"title\"].toString()},\n {\"album\",\"\"}, \/\/nope because soundcloud\n {\"artist\", jobj[\"user\"].toObject()[\"username\"].toString()},\n {\"track_number\", 0},\n {\"length\", length}, \/\/get from fucking duration\n {\"genre\", jobj[\"genre\"].toString()}\n };\n \/\/add meta to media\n media[\"metadata\"] = meta;\n\n return QJsonValue(media);\n}\n\nQJsonArray SCHandler::search(QString value, QString key){\n QJsonArray results = QJsonArray();\n QJsonObject jobj;\n QString result;\n int num_queried = query(key, value);\n for(int i=0; i num_queried)\n count = num_queried;\n for(int i=0; i<40; i++){\n results.append(format(raw_results[i]));\n }\n emit onSearchComplete(&results);\n return results;\n}\n\nQByteArray SCHandler::request_song(QString download_url){\n \/\/ create custom temporary event loop on stack\n QNetworkRequest request;\n request.setRawHeader(\"User-Agent\", USER_AGENT);\n QEventLoop eventLoop;\n QString req_url = download_url;\n QUrl url(req_url);\n QUrlQuery query;\n\n query.addQueryItem(\"client_id\", SC_CLIENT_ID);\n\n url.setQuery(query.query());\n\n \/\/ \"quit()\" the event-loop, when the network request \"finished()\"\n QNetworkAccessManager mgr;\n QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));\n\n \/\/ the HTTP request\n QNetworkRequest req(url);\n\n \/\/req.setRawHeader();\n QNetworkReply *reply = mgr.get(req);\n eventLoop.exec(); \/\/ blocks stack until \"finished()\" has been called\n\n\n\n if (reply->error() == QNetworkReply::NoError) {\n \/\/get temp download url as json\n QJsonDocument jsondoc = QJsonDocument(QJsonDocument::fromJson(QString(reply->readAll()).toUtf8()));\n QJsonObject jobj = jsondoc.object();\n QString download_url = jobj[\"location\"].toString();\n\n \/\/download\n if (reply->error() == QNetworkReply::NoError) {\n req_url = download_url;\n QUrl url(req_url);\n QNetworkRequest req(url);\n req.setRawHeader(\"User-Agent\",USER_AGENT);\n QNetworkReply *reply = mgr.get(req);\n eventLoop.exec();\n\n return reply->readAll();\n\n }\n else{\n qDebug() << \"Failure on download request\" <errorString();\n delete reply;\n return NULL;\n }\n\n }\n else {\n \/\/failure\n qDebug() << \"Failure on initial request\" <errorString();\n delete reply;\n return NULL;\n }\n}\n\n\nfixed search(int count...) function. Updated comments to reflect. Still janky. Still works.#include \"schandler.h\"\n\nSCHandler::SCHandler(QObject *parent)\n{\n raw_results = QJsonArray();\n}\n\n\nSCHandler::~SCHandler()\n{\n\n}\n\n\n\/\/category: artist, title, user,\nint SCHandler::query(QString key, QString value){\n\n if(value == NULL)\n return -1;\n if(key == NULL)\n return -1;\n \/\/check to prevent same query twice? nah don't be dumb\n\n \/\/ create custom temporary event loop on stack\n QEventLoop eventLoop;\n QUrl url(SC_TRACKS_URL);\n QUrlQuery query;\n query.addQueryItem(\"downloadable\", \"true\");\n query.addQueryItem(key, value);\n\n query.addQueryItem(\"client_id\", SC_CLIENT_ID);\n\n\n\n url.setQuery(query.query());\n qDebug() << url;\n\n \/\/ \"quit()\" the event-loop, when the network request \"finished()\"\n QNetworkAccessManager mgr;\n QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));\n\n \/\/ the HTTP request\n QNetworkRequest req(url);\n QNetworkReply *reply = mgr.get(req);\n eventLoop.exec(); \/\/ blocks stack until \"finished()\" has been called\n\n if (reply->error() == QNetworkReply::NoError) {\n QJsonParseError err;\n QJsonDocument jsondoc = QJsonDocument(QJsonDocument::fromJson(QString(reply->readAll()).toUtf8(), &err)); \/\/raw string to qtstring to bytecode to jsondoc fucking shit\n raw_results = jsondoc.array(); \/\/take the pile of responses and make them an array so you can fucking do something with the\n\/\/ qDebug() << raw_results;\n\n return raw_results.size();\n\n }\n else {\n \/\/failure\n qDebug() << \"Failed query: \" <errorString();\n delete reply;\n return -1;\n }\n}\n\nQJsonValue SCHandler::format(QJsonValue initial){\n QJsonObject jobj = initial.toObject();\n QString length;\n if (jobj[\"duration\"].toInt() > 0){\n QString minutes;\n QString seconds;\n int duration = jobj[\"duration\"].toInt()\/1000; \/\/ain't nobody got time for accuracy\n minutes = QString::number(duration\/60);\n seconds = QString::number(duration%60);\n if(duration\/60 < 10)\n minutes = QString(\"0\"+minutes);\n if(duration%60 < 10)\n seconds = QString(\"0\"+seconds);\n\n length = QString(minutes+\":\"+seconds);\n }\n\n QJsonObject media{\n {\"hash\", jobj[\"download_url\"].toString()},\n {\"order\",\"\"},\n };\n\n QJsonObject meta{\n {\"title\", jobj[\"title\"].toString()},\n {\"album\",\"\"}, \/\/nope because soundcloud\n {\"artist\", jobj[\"user\"].toObject()[\"username\"].toString()},\n {\"track_number\", 0},\n {\"length\", length}, \/\/get from fucking duration\n {\"genre\", jobj[\"genre\"].toString()}\n };\n \/\/add meta to media\n media[\"metadata\"] = meta;\n\n return QJsonValue(media);\n}\n\nQJsonArray SCHandler::search(QString value, QString key){\n QJsonArray results = QJsonArray();\n QJsonObject jobj;\n QString result;\n int num_queried = query(key, value);\n for(int i=0; i results.size())\n count = results.size();\n for(int i=0; ierror() == QNetworkReply::NoError) {\n \/\/get temp download url as json\n QJsonDocument jsondoc = QJsonDocument(QJsonDocument::fromJson(QString(reply->readAll()).toUtf8()));\n QJsonObject jobj = jsondoc.object();\n QString download_url = jobj[\"location\"].toString();\n\n \/\/download\n if (reply->error() == QNetworkReply::NoError) {\n req_url = download_url;\n QUrl url(req_url);\n QNetworkRequest req(url);\n req.setRawHeader(\"User-Agent\",USER_AGENT);\n QNetworkReply *reply = mgr.get(req);\n eventLoop.exec();\n\n return reply->readAll();\n\n }\n else{\n qDebug() << \"Failure on download request\" <errorString();\n delete reply;\n return NULL;\n }\n\n }\n else {\n \/\/failure\n qDebug() << \"Failure on initial request\" <errorString();\n delete reply;\n return NULL;\n }\n}\n\n\n<|endoftext|>"} {"text":"\/** \n * @file llagentui.cpp\n * @brief Utility methods to process agent's data as slurl's etc. before displaying\n *\n * $LicenseInfo:firstyear=2009&license=viewergpl$\n * \n * Copyright (c) 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\"\n\n#include \"llagentui.h\"\n\n\/\/ Library includes\n#include \"llparcel.h\"\n\n\/\/ Viewer includes\n#include \"llagent.h\"\n#include \"llviewercontrol.h\"\n#include \"llviewerregion.h\"\n#include \"llviewerparcelmgr.h\"\n#include \"llvoavatarself.h\"\n#include \"llslurl.h\"\n\n\/\/static\nvoid LLAgentUI::buildName(std::string& name)\n{\n\tname.clear();\n\n\tLLVOAvatarSelf* avatar_object = gAgent.getAvatarObject();\n\tif (avatar_object)\n\t{\n\t\tLLNameValue *first_nv = avatar_object->getNVPair(\"FirstName\");\n\t\tLLNameValue *last_nv = avatar_object->getNVPair(\"LastName\");\n\t\tif (first_nv && last_nv)\n\t\t{\n\t\t\tname = first_nv->printData() + \" \" + last_nv->printData();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tllwarns << \"Agent is missing FirstName and\/or LastName nv pair.\" << llendl;\n\t\t}\n\t}\n\telse\n\t{\n\t\tname = gSavedSettings.getString(\"FirstName\") + \" \" + gSavedSettings.getString(\"LastName\");\n\t}\n}\n\n\/\/static\nvoid LLAgentUI::buildFullname(std::string& name)\n{\n\tif (gAgent.getAvatarObject()) name = gAgent.getAvatarObject()->getFullname();\n}\n\n\/\/static\nstd::string LLAgentUI::buildSLURL(const bool escaped \/*= true*\/)\n{\n\tstd::string slurl;\n\tLLViewerRegion *regionp = gAgent.getRegion();\n\tif (regionp)\n\t{\n\t\tLLVector3d agentPos = gAgent.getPositionGlobal();\n\t\tslurl = LLSLURL::buildSLURLfromPosGlobal(regionp->getName(), agentPos, escaped);\n\t}\n\treturn slurl;\n}\n\n\/\/static\nBOOL LLAgentUI::checkAgentDistance(const LLVector3& pole, F32 radius)\n{\n\tF32 delta_x = gAgent.getPositionAgent().mV[VX] - pole.mV[VX];\n\tF32 delta_y = gAgent.getPositionAgent().mV[VY] - pole.mV[VY];\n\t\n\treturn sqrt( delta_x* delta_x + delta_y* delta_y ) < radius;\n}\nBOOL LLAgentUI::buildLocationString(std::string& str, ELocationFormat fmt,const LLVector3& agent_pos_region)\n{\n\tLLViewerRegion* region = gAgent.getRegion();\n\tLLParcel* parcel = LLViewerParcelMgr::getInstance()->getAgentParcel();\n\n\tif (!region || !parcel) return FALSE;\n\n\tS32 pos_x = S32(agent_pos_region.mV[VX]);\n\tS32 pos_y = S32(agent_pos_region.mV[VY]);\n\tS32 pos_z = S32(agent_pos_region.mV[VZ]);\n\n\t\/\/ Round the numbers based on the velocity\n\tF32 velocity_mag_sq = gAgent.getVelocity().magVecSquared();\n\n\tconst F32 FLY_CUTOFF = 6.f;\t\t\/\/ meters\/sec\n\tconst F32 FLY_CUTOFF_SQ = FLY_CUTOFF * FLY_CUTOFF;\n\tconst F32 WALK_CUTOFF = 1.5f;\t\/\/ meters\/sec\n\tconst F32 WALK_CUTOFF_SQ = WALK_CUTOFF * WALK_CUTOFF;\n\n\tif (velocity_mag_sq > FLY_CUTOFF_SQ)\n\t{\n\t\tpos_x -= pos_x % 4;\n\t\tpos_y -= pos_y % 4;\n\t}\n\telse if (velocity_mag_sq > WALK_CUTOFF_SQ)\n\t{\n\t\tpos_x -= pos_x % 2;\n\t\tpos_y -= pos_y % 2;\n\t}\n\n\t\/\/ create a default name and description for the landmark\n\tstd::string parcel_name = LLViewerParcelMgr::getInstance()->getAgentParcelName();\n\tstd::string region_name = region->getName();\n\tstd::string sim_access_string = region->getSimAccessString();\n\tstd::string buffer;\n\tif( parcel_name.empty() )\n\t{\n\t\t\/\/ the parcel doesn't have a name\n\t\tswitch (fmt)\n\t\t{\n\t\tcase LOCATION_FORMAT_LANDMARK:\n\t\t\tbuffer = llformat(\"%.100s\", region_name.c_str());\n\t\t\tbreak;\n\t\tcase LOCATION_FORMAT_NORMAL:\n\t\t\tbuffer = llformat(\"%s\", region_name.c_str());\n\t\t\tbreak;\n\t\tcase LOCATION_FORMAT_NO_COORDS:\n\t\t\tbuffer = llformat(\"%s%s%s\",\n\t\t\t\tregion_name.c_str(),\n\t\t\t\tsim_access_string.empty() ? \"\" : \" - \",\n\t\t\t\tsim_access_string.c_str());\n\t\t\tbreak;\n\t\tcase LOCATION_FORMAT_NO_MATURITY:\n\t\tcase LOCATION_FORMAT_FULL:\n\t\t\tbuffer = llformat(\"%s (%d, %d, %d)\",\n\t\t\t\tregion_name.c_str(),\n\t\t\t\tpos_x, pos_y, pos_z);\n\t\t\tbreak;\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ the parcel has a name, so include it in the landmark name\n\t\tswitch (fmt)\n\t\t{\n\t\tcase LOCATION_FORMAT_LANDMARK:\n\t\t\tbuffer = llformat(\"%.100s\", parcel_name.c_str());\n\t\t\tbreak;\n\t\tcase LOCATION_FORMAT_NORMAL:\n\t\t\tbuffer = llformat(\"%s, %s\", parcel_name.c_str(), region_name.c_str());\n\t\t\tbreak;\n\t\tcase LOCATION_FORMAT_NO_MATURITY:\n\t\t\tbuffer = llformat(\"%s, %s (%d, %d, %d)\",\n\t\t\t\tparcel_name.c_str(),\n\t\t\t\tregion_name.c_str(),\n\t\t\t\tpos_x, pos_y, pos_z);\n\t\t\tbreak;\n\t\tcase LOCATION_FORMAT_NO_COORDS:\n\t\t\tbuffer = llformat(\"%s, %s%s%s\",\n\t\t\t\t\t\t\t parcel_name.c_str(),\n\t\t\t\t\t\t\t region_name.c_str(),\n\t\t\t\t\t\t\t sim_access_string.empty() ? \"\" : \" - \",\n\t\t\t\t\t\t\t sim_access_string.c_str());\n\t\t\t\tbreak;\n\t\tcase LOCATION_FORMAT_FULL:\n\t\t\tbuffer = llformat(\"%s, %s (%d, %d, %d)%s%s\",\n\t\t\t\tparcel_name.c_str(),\n\t\t\t\tregion_name.c_str(),\n\t\t\t\tpos_x, pos_y, pos_z,\n\t\t\t\tsim_access_string.empty() ? \"\" : \" - \",\n\t\t\t\tsim_access_string.c_str());\n\t\t\tbreak;\n\t\t}\n\t}\n\tstr = buffer;\n\treturn TRUE;\n}\nBOOL LLAgentUI::buildLocationString(std::string& str, ELocationFormat fmt)\n{\n\treturn buildLocationString(str,fmt, gAgent.getPositionAgent());\n}\nFixed normal bug EXT-5207 - Region Maturity level not displayed on nav bar when coordinates are enabled and parcel got no name. Added maturity rating to full location string in case parcel name is empty.\/** \n * @file llagentui.cpp\n * @brief Utility methods to process agent's data as slurl's etc. before displaying\n *\n * $LicenseInfo:firstyear=2009&license=viewergpl$\n * \n * Copyright (c) 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\"\n\n#include \"llagentui.h\"\n\n\/\/ Library includes\n#include \"llparcel.h\"\n\n\/\/ Viewer includes\n#include \"llagent.h\"\n#include \"llviewercontrol.h\"\n#include \"llviewerregion.h\"\n#include \"llviewerparcelmgr.h\"\n#include \"llvoavatarself.h\"\n#include \"llslurl.h\"\n\n\/\/static\nvoid LLAgentUI::buildName(std::string& name)\n{\n\tname.clear();\n\n\tLLVOAvatarSelf* avatar_object = gAgent.getAvatarObject();\n\tif (avatar_object)\n\t{\n\t\tLLNameValue *first_nv = avatar_object->getNVPair(\"FirstName\");\n\t\tLLNameValue *last_nv = avatar_object->getNVPair(\"LastName\");\n\t\tif (first_nv && last_nv)\n\t\t{\n\t\t\tname = first_nv->printData() + \" \" + last_nv->printData();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tllwarns << \"Agent is missing FirstName and\/or LastName nv pair.\" << llendl;\n\t\t}\n\t}\n\telse\n\t{\n\t\tname = gSavedSettings.getString(\"FirstName\") + \" \" + gSavedSettings.getString(\"LastName\");\n\t}\n}\n\n\/\/static\nvoid LLAgentUI::buildFullname(std::string& name)\n{\n\tif (gAgent.getAvatarObject()) name = gAgent.getAvatarObject()->getFullname();\n}\n\n\/\/static\nstd::string LLAgentUI::buildSLURL(const bool escaped \/*= true*\/)\n{\n\tstd::string slurl;\n\tLLViewerRegion *regionp = gAgent.getRegion();\n\tif (regionp)\n\t{\n\t\tLLVector3d agentPos = gAgent.getPositionGlobal();\n\t\tslurl = LLSLURL::buildSLURLfromPosGlobal(regionp->getName(), agentPos, escaped);\n\t}\n\treturn slurl;\n}\n\n\/\/static\nBOOL LLAgentUI::checkAgentDistance(const LLVector3& pole, F32 radius)\n{\n\tF32 delta_x = gAgent.getPositionAgent().mV[VX] - pole.mV[VX];\n\tF32 delta_y = gAgent.getPositionAgent().mV[VY] - pole.mV[VY];\n\t\n\treturn sqrt( delta_x* delta_x + delta_y* delta_y ) < radius;\n}\nBOOL LLAgentUI::buildLocationString(std::string& str, ELocationFormat fmt,const LLVector3& agent_pos_region)\n{\n\tLLViewerRegion* region = gAgent.getRegion();\n\tLLParcel* parcel = LLViewerParcelMgr::getInstance()->getAgentParcel();\n\n\tif (!region || !parcel) return FALSE;\n\n\tS32 pos_x = S32(agent_pos_region.mV[VX]);\n\tS32 pos_y = S32(agent_pos_region.mV[VY]);\n\tS32 pos_z = S32(agent_pos_region.mV[VZ]);\n\n\t\/\/ Round the numbers based on the velocity\n\tF32 velocity_mag_sq = gAgent.getVelocity().magVecSquared();\n\n\tconst F32 FLY_CUTOFF = 6.f;\t\t\/\/ meters\/sec\n\tconst F32 FLY_CUTOFF_SQ = FLY_CUTOFF * FLY_CUTOFF;\n\tconst F32 WALK_CUTOFF = 1.5f;\t\/\/ meters\/sec\n\tconst F32 WALK_CUTOFF_SQ = WALK_CUTOFF * WALK_CUTOFF;\n\n\tif (velocity_mag_sq > FLY_CUTOFF_SQ)\n\t{\n\t\tpos_x -= pos_x % 4;\n\t\tpos_y -= pos_y % 4;\n\t}\n\telse if (velocity_mag_sq > WALK_CUTOFF_SQ)\n\t{\n\t\tpos_x -= pos_x % 2;\n\t\tpos_y -= pos_y % 2;\n\t}\n\n\t\/\/ create a default name and description for the landmark\n\tstd::string parcel_name = LLViewerParcelMgr::getInstance()->getAgentParcelName();\n\tstd::string region_name = region->getName();\n\tstd::string sim_access_string = region->getSimAccessString();\n\tstd::string buffer;\n\tif( parcel_name.empty() )\n\t{\n\t\t\/\/ the parcel doesn't have a name\n\t\tswitch (fmt)\n\t\t{\n\t\tcase LOCATION_FORMAT_LANDMARK:\n\t\t\tbuffer = llformat(\"%.100s\", region_name.c_str());\n\t\t\tbreak;\n\t\tcase LOCATION_FORMAT_NORMAL:\n\t\t\tbuffer = llformat(\"%s\", region_name.c_str());\n\t\t\tbreak;\n\t\tcase LOCATION_FORMAT_NO_COORDS:\n\t\t\tbuffer = llformat(\"%s%s%s\",\n\t\t\t\tregion_name.c_str(),\n\t\t\t\tsim_access_string.empty() ? \"\" : \" - \",\n\t\t\t\tsim_access_string.c_str());\n\t\t\tbreak;\n\t\tcase LOCATION_FORMAT_NO_MATURITY:\n\t\t\tbuffer = llformat(\"%s (%d, %d, %d)\",\n\t\t\t\tregion_name.c_str(),\n\t\t\t\tpos_x, pos_y, pos_z);\n\t\t\tbreak;\n\t\tcase LOCATION_FORMAT_FULL:\n\t\t\tbuffer = llformat(\"%s (%d, %d, %d)%s%s\",\n\t\t\t\tregion_name.c_str(),\n\t\t\t\tpos_x, pos_y, pos_z,\n\t\t\t\tsim_access_string.empty() ? \"\" : \" - \",\n\t\t\t\tsim_access_string.c_str());\n\t\t\tbreak;\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ the parcel has a name, so include it in the landmark name\n\t\tswitch (fmt)\n\t\t{\n\t\tcase LOCATION_FORMAT_LANDMARK:\n\t\t\tbuffer = llformat(\"%.100s\", parcel_name.c_str());\n\t\t\tbreak;\n\t\tcase LOCATION_FORMAT_NORMAL:\n\t\t\tbuffer = llformat(\"%s, %s\", parcel_name.c_str(), region_name.c_str());\n\t\t\tbreak;\n\t\tcase LOCATION_FORMAT_NO_MATURITY:\n\t\t\tbuffer = llformat(\"%s, %s (%d, %d, %d)\",\n\t\t\t\tparcel_name.c_str(),\n\t\t\t\tregion_name.c_str(),\n\t\t\t\tpos_x, pos_y, pos_z);\n\t\t\tbreak;\n\t\tcase LOCATION_FORMAT_NO_COORDS:\n\t\t\tbuffer = llformat(\"%s, %s%s%s\",\n\t\t\t\t\t\t\t parcel_name.c_str(),\n\t\t\t\t\t\t\t region_name.c_str(),\n\t\t\t\t\t\t\t sim_access_string.empty() ? \"\" : \" - \",\n\t\t\t\t\t\t\t sim_access_string.c_str());\n\t\t\t\tbreak;\n\t\tcase LOCATION_FORMAT_FULL:\n\t\t\tbuffer = llformat(\"%s, %s (%d, %d, %d)%s%s\",\n\t\t\t\tparcel_name.c_str(),\n\t\t\t\tregion_name.c_str(),\n\t\t\t\tpos_x, pos_y, pos_z,\n\t\t\t\tsim_access_string.empty() ? \"\" : \" - \",\n\t\t\t\tsim_access_string.c_str());\n\t\t\tbreak;\n\t\t}\n\t}\n\tstr = buffer;\n\treturn TRUE;\n}\nBOOL LLAgentUI::buildLocationString(std::string& str, ELocationFormat fmt)\n{\n\treturn buildLocationString(str,fmt, gAgent.getPositionAgent());\n}\n<|endoftext|>"} {"text":"\/**\n * Implements generally useful functions.\n *\n * @file\n *\/\n\n#include \/* std::underlying_type *\/\n#include \/* std::from_chars() *\/\n#include \/* std::isspace() *\/\n#include \n\n#include \/* snprintf() *\/\n\n#ifndef _POWERDXX_UTILITY_HPP_\n#define _POWERDXX_UTILITY_HPP_\n\n\/**\n * A collection of generally useful functions.\n *\/\nnamespace utility {\n\n\/**\n * Like sizeof(), but it returns the number of elements an array consists\n * of instead of the number of bytes.\n *\n * @tparam T,Count\n *\tThe type and number of array elements\n * @return\n *\tThe number of array entries\n *\/\ntemplate \nconstexpr size_t countof(T (&)[Count]) { return Count; }\n\n\/**\n * This is a safeguard against accidentally using sprintf().\n *\n * Using it triggers a static_assert(), preventing compilation.\n *\n * @tparam Args\n *\tCatch all arguments\n *\/\ntemplate \ninline void sprintf(Args...) {\n\t\/* Assert depends on Args so it can only be determined if\n\t * the function is actually instantiated. *\/\n\tstatic_assert(sizeof...(Args) && false,\n\t \"Use of sprintf() is unsafe, use sprintf_safe() instead\");\n}\n\n\/**\n * A wrapper around snprintf() that automatically pulls in the\n * destination buffer size.\n *\n * @tparam Size\n *\tThe destination buffer size\n * @tparam Args\n *\tThe types of the arguments\n * @param dst\n *\tA reference to the destination buffer\n * @param format\n *\tA printf style formatting string\n * @param args\n *\tThe printf arguments\n * @return\n *\tThe number of characters in the resulting string, regardless of the\n *\tavailable space\n *\/\ntemplate \ninline int sprintf_safe(char (& dst)[Size], char const * const format,\n Args const... args) {\n\treturn snprintf(dst, Size, format, args...);\n}\n\n\/**\n * Casts an enum to its underlying value.\n *\n * @tparam ET,VT\n *\tThe enum and value type\n * @param op\n *\tThe operand to convert\n * @return\n *\tThe integer representation of the operand\n *\/\ntemplate ::type>\nconstexpr VT to_value(ET const op) {\n\treturn static_cast(op);\n}\n\n\/**\n * A formatting wrapper around string literals.\n *\n * Overloads operator (), which treats the string as a printf formatting\n * string, the arguments represent the data to format.\n *\n * In combination with the literal _fmt, it can be used like this:\n *\n * ~~~ c++\n * std::cout << \"%-15.15s %#018p\\n\"_fmt(\"Address:\", this);\n * ~~~\n *\n * @tparam BufSize\n *\tThe buffer size for formatting, resulting strings cannot\n *\tgrow beyond `BufSize - 1`\n *\/\ntemplate \nclass Formatter {\n\tprivate:\n\t\/**\n\t * Pointer to the string literal.\n\t *\/\n\tchar const * const fmt;\n\n\tpublic:\n\t\/**\n\t * Construct from string literal.\n\t *\/\n\tconstexpr Formatter(char const * const fmt) : fmt{fmt} {}\n\n\t\/**\n\t * Returns a formatted string.\n\t *\n\t * @tparam ArgTs\n\t *\tVariadic argument types\n\t * @param args\n\t *\tVariadic arguments\n\t * @return\n\t *\tAn std::string formatted according to fmt\n\t *\/\n\ttemplate \n\tstd::string operator ()(ArgTs const &... args) const {\n\t\tchar buf[BufSize];\n\t\tauto count = sprintf_safe(buf, this->fmt, args...);\n\t\tif (count < 0) {\n\t\t\t\/* encoding error *\/\n\t\t\treturn {};\n\t\t} else if (static_cast(count) >= BufSize) {\n\t\t\t\/* does not fit into buffer *\/\n\t\t\treturn {buf, BufSize - 1};\n\t\t}\n\t\treturn {buf, static_cast(count)};\n\t}\n};\n\n\/**\n * Contains literal operators.\n *\/\nnamespace literals {\n\/**\n * Literal to convert a string literal to a Formatter instance.\n *\n * @param fmt\n *\tA printf style format string\n * @return\n *\tA Formatter instance\n *\/\nconstexpr Formatter<16384> operator \"\" _fmt(char const * const fmt, size_t const) {\n\treturn {fmt};\n}\n} \/* namespace literals *\/\n\n\/**\n * A simple value container only allowing += and copy assignment.\n *\n * @tparam T\n *\tThe value type\n *\/\ntemplate \nclass Sum {\n\tprivate:\n\t\/**\n\t * The sum of values accumulated.\n\t *\/\n\tT value;\n\n\tpublic:\n\t\/**\n\t * Construct from an initial value.\n\t *\n\t * @param value\n\t *\tThe initial value\n\t *\/\n\texplicit constexpr Sum(T const & value) : value{value} {}\n\n\t\/**\n\t * Default construct.\n\t *\/\n\tconstexpr Sum() : Sum{0} {}\n\n\t\/**\n\t * Returns the current sum of values.\n\t *\n\t * @return\n\t *\tThe sum of values by const reference\n\t *\/\n\tconstexpr operator T const &() const {\n\t\treturn this->value;\n\t}\n\n\t\/**\n\t * Add a value to the sum.\n\t *\n\t * @param value\n\t *\tThe value to add to the current sum\n\t * @return\n\t *\tA self reference\n\t *\/\n\tconstexpr Sum & operator +=(T const & value) {\n\t\tthis->value += value;\n\t\treturn *this;\n\t}\n};\n\n\/**\n * A simple value container that provides the minimum of assigned values.\n *\n * @tparam T\n *\tThe value type\n *\/\ntemplate \nclass Min {\n\tprivate:\n\t\/**\n\t * The minimum of the assigned values.\n\t *\/\n\tT value;\n\n\tpublic:\n\t\/**\n\t * Construct from an initial value.\n\t *\n\t * @param value\n\t *\tThe initial value\n\t *\/\n\texplicit constexpr Min(T const & value) : value{value} {}\n\n\t\/**\n\t * Returns the current minimum.\n\t *\n\t * @return\n\t *\tThe minimum by const reference\n\t *\/\n\tconstexpr operator T const &() const {\n\t\treturn this->value;\n\t}\n\n\t\/**\n\t * Assign a new value, if it is less than the current value.\n\t *\n\t * @param value\n\t *\tThe value to assign\n\t * @return\n\t *\tA self reference\n\t *\/\n\tconstexpr Min & operator =(T const & value) {\n\t\tthis->value = this->value <= value ? this->value : value;\n\t\treturn *this;\n\t}\n};\n\n\/**\n * A simple value container that provides the maximum of assigned values.\n *\n * @tparam T\n *\tThe value type\n *\/\ntemplate \nclass Max {\n\tprivate:\n\t\/**\n\t * The maximum of the assigned values.\n\t *\/\n\tT value;\n\n\tpublic:\n\t\/**\n\t * Construct from an initial value.\n\t *\n\t * @param value\n\t *\tThe initial value\n\t *\/\n\texplicit constexpr Max(T const & value) : value{value} {}\n\n\t\/**\n\t * Returns the current maximum.\n\t *\n\t * @return\n\t *\tThe maximum by const reference\n\t *\/\n\tconstexpr operator T const &() const {\n\t\treturn this->value;\n\t}\n\n\t\/**\n\t * Assign a new value, if it is greater than the current value.\n\t *\n\t * @param value\n\t *\tThe value to assign\n\t * @return\n\t *\tA self reference\n\t *\/\n\tconstexpr Max & operator =(T const & value) {\n\t\tthis->value = this->value >= value ? this->value : value;\n\t\treturn *this;\n\t}\n};\n\n\/**\n * A functor for reading numerical values from a string or character\n * array.\n *\/\nstruct FromChars {\n\t\/**\n\t * The next character to read.\n\t *\/\n\tchar const * it;\n\n\t\/**\n\t * The first character of the same array that may not be read,\n\t * this should usually point to a terminating zero or behind\n\t * a buffer.\n\t *\/\n\tchar const * const end;\n\n\t\/**\n\t * Retrieve an integral or floating point value from the array.\n\t *\n\t * The operation may fail for multiple reasons:\n\t *\n\t * - No more characters left to read, in that case the functor\n\t * will equal false\n\t * - The given characters do not represent a valid value, in\n\t * that case the functor will equal true\n\t *\n\t * @tparam T\n\t *\tThe value type to retrieve\n\t * @param dst\n\t *\tThe lvalue to assign to\n\t * @retval true\n\t *\tThe numerical value was successfully read from the array\n\t * @retval false\n\t *\tThe numerical value could not be read from the array\n\t *\/\n\ttemplate \n\t[[nodiscard]] bool operator ()(T & dst) {\n\t\tif (!this->it) {\n\t\t\treturn false;\n\t\t}\n\t\tauto [p, ec] = std::from_chars(this->it, this->end, dst);\n\t\tif (this->it == p) {\n\t\t\treturn false;\n\t\t}\n\t\tfor (; p != this->end && std::isspace(*p); ++p);\n\t\tthis->it = p;\n\t\treturn true;\n\t}\n\n\t\/**\n\t * Check if unread characters remain.\n\t *\n\t * @retval false\n\t *\tAll characters have been read\n\t * @retval true\n\t *\tCharacters remain to be read\n\t *\/\n\toperator bool() const {\n\t\treturn this->it && this->end != this->it && *this->it;\n\t}\n\n\t\/**\n\t * Range based constructor.\n\t *\n\t * @param start,end\n\t *\tThe character array range\n\t *\/\n\tFromChars(char const * const start, char const * const end) :\n\t it{start}, end{end} {\n\t\tfor (; this->it != end && std::isspace(*this->it); ++this->it);\n\t}\n\n\t\/**\n\t * Construct from a character array.\n\t *\n\t * @tparam CountV\n\t *\tThe number of characters\n\t * @param str\n\t *\tTha character array to parse from\n\t * @param terminator\n\t *\tIndicates whether the character array has a terminating\n\t *\tnull character.\n\t *\/\n\ttemplate \n\tFromChars(char const (& str)[CountV], bool terminator = true) :\n\t FromChars{str, str + CountV - terminator} {}\n\n\t\/**\n\t * Construct functor from a string.\n\t *\n\t * Note that changing the string during the lifetime of the\n\t * functor may silently invalidate the functor's state and\n\t * thus invoke undefined behaviour.\n\t *\n\t * @param str\n\t *\tThe string to parse from\n\t *\/\n\tFromChars(std::string const & str) :\n\t FromChars{str.data(), str.data() + str.size()} {}\n};\n\n} \/* namespace utility *\/\n\n#endif \/* _POWERDXX_UTILITY_HPP_ *\/\nFix typos\/**\n * Implements generally useful functions.\n *\n * @file\n *\/\n\n#include \/* std::underlying_type *\/\n#include \/* std::from_chars() *\/\n#include \/* std::isspace() *\/\n#include \n\n#include \/* snprintf() *\/\n\n#ifndef _POWERDXX_UTILITY_HPP_\n#define _POWERDXX_UTILITY_HPP_\n\n\/**\n * A collection of generally useful functions.\n *\/\nnamespace utility {\n\n\/**\n * Like sizeof(), but it returns the number of elements an array consists\n * of instead of the number of bytes.\n *\n * @tparam T,Count\n *\tThe type and number of array elements\n * @return\n *\tThe number of array entries\n *\/\ntemplate \nconstexpr size_t countof(T (&)[Count]) { return Count; }\n\n\/**\n * This is a safeguard against accidentally using sprintf().\n *\n * Using it triggers a static_assert(), preventing compilation.\n *\n * @tparam Args\n *\tCatch all arguments\n *\/\ntemplate \ninline void sprintf(Args...) {\n\t\/* Assert depends on Args so it can only be determined if\n\t * the function is actually instantiated. *\/\n\tstatic_assert(sizeof...(Args) && false,\n\t \"Use of sprintf() is unsafe, use sprintf_safe() instead\");\n}\n\n\/**\n * A wrapper around snprintf() that automatically pulls in the\n * destination buffer size.\n *\n * @tparam Size\n *\tThe destination buffer size\n * @tparam Args\n *\tThe types of the arguments\n * @param dst\n *\tA reference to the destination buffer\n * @param format\n *\tA printf style formatting string\n * @param args\n *\tThe printf arguments\n * @return\n *\tThe number of characters in the resulting string, regardless of the\n *\tavailable space\n *\/\ntemplate \ninline int sprintf_safe(char (& dst)[Size], char const * const format,\n Args const... args) {\n\treturn snprintf(dst, Size, format, args...);\n}\n\n\/**\n * Casts an enum to its underlying value.\n *\n * @tparam ET,VT\n *\tThe enum and value type\n * @param op\n *\tThe operand to convert\n * @return\n *\tThe integer representation of the operand\n *\/\ntemplate ::type>\nconstexpr VT to_value(ET const op) {\n\treturn static_cast(op);\n}\n\n\/**\n * A formatting wrapper around string literals.\n *\n * Overloads operator (), which treats the string as a printf formatting\n * string, the arguments represent the data to format.\n *\n * In combination with the literal _fmt, it can be used like this:\n *\n * ~~~ c++\n * std::cout << \"%-15.15s %#018p\\n\"_fmt(\"Address:\", this);\n * ~~~\n *\n * @tparam BufSize\n *\tThe buffer size for formatting, resulting strings cannot\n *\tgrow beyond `BufSize - 1`\n *\/\ntemplate \nclass Formatter {\n\tprivate:\n\t\/**\n\t * Pointer to the string literal.\n\t *\/\n\tchar const * const fmt;\n\n\tpublic:\n\t\/**\n\t * Construct from string literal.\n\t *\/\n\tconstexpr Formatter(char const * const fmt) : fmt{fmt} {}\n\n\t\/**\n\t * Returns a formatted string.\n\t *\n\t * @tparam ArgTs\n\t *\tVariadic argument types\n\t * @param args\n\t *\tVariadic arguments\n\t * @return\n\t *\tAn std::string formatted according to fmt\n\t *\/\n\ttemplate \n\tstd::string operator ()(ArgTs const &... args) const {\n\t\tchar buf[BufSize];\n\t\tauto count = sprintf_safe(buf, this->fmt, args...);\n\t\tif (count < 0) {\n\t\t\t\/* encoding error *\/\n\t\t\treturn {};\n\t\t} else if (static_cast(count) >= BufSize) {\n\t\t\t\/* does not fit into buffer *\/\n\t\t\treturn {buf, BufSize - 1};\n\t\t}\n\t\treturn {buf, static_cast(count)};\n\t}\n};\n\n\/**\n * Contains literal operators.\n *\/\nnamespace literals {\n\/**\n * Literal to convert a string literal to a Formatter instance.\n *\n * @param fmt\n *\tA printf style format string\n * @return\n *\tA Formatter instance\n *\/\nconstexpr Formatter<16384> operator \"\" _fmt(char const * const fmt, size_t const) {\n\treturn {fmt};\n}\n} \/* namespace literals *\/\n\n\/**\n * A simple value container only allowing += and copy assignment.\n *\n * @tparam T\n *\tThe value type\n *\/\ntemplate \nclass Sum {\n\tprivate:\n\t\/**\n\t * The sum of values accumulated.\n\t *\/\n\tT value;\n\n\tpublic:\n\t\/**\n\t * Construct from an initial value.\n\t *\n\t * @param value\n\t *\tThe initial value\n\t *\/\n\texplicit constexpr Sum(T const & value) : value{value} {}\n\n\t\/**\n\t * Default construct.\n\t *\/\n\tconstexpr Sum() : Sum{0} {}\n\n\t\/**\n\t * Returns the current sum of values.\n\t *\n\t * @return\n\t *\tThe sum of values by const reference\n\t *\/\n\tconstexpr operator T const &() const {\n\t\treturn this->value;\n\t}\n\n\t\/**\n\t * Add a value to the sum.\n\t *\n\t * @param value\n\t *\tThe value to add to the current sum\n\t * @return\n\t *\tA self reference\n\t *\/\n\tconstexpr Sum & operator +=(T const & value) {\n\t\tthis->value += value;\n\t\treturn *this;\n\t}\n};\n\n\/**\n * A simple value container that provides the minimum of assigned values.\n *\n * @tparam T\n *\tThe value type\n *\/\ntemplate \nclass Min {\n\tprivate:\n\t\/**\n\t * The minimum of the assigned values.\n\t *\/\n\tT value;\n\n\tpublic:\n\t\/**\n\t * Construct from an initial value.\n\t *\n\t * @param value\n\t *\tThe initial value\n\t *\/\n\texplicit constexpr Min(T const & value) : value{value} {}\n\n\t\/**\n\t * Returns the current minimum.\n\t *\n\t * @return\n\t *\tThe minimum by const reference\n\t *\/\n\tconstexpr operator T const &() const {\n\t\treturn this->value;\n\t}\n\n\t\/**\n\t * Assign a new value, if it is less than the current value.\n\t *\n\t * @param value\n\t *\tThe value to assign\n\t * @return\n\t *\tA self reference\n\t *\/\n\tconstexpr Min & operator =(T const & value) {\n\t\tthis->value = this->value <= value ? this->value : value;\n\t\treturn *this;\n\t}\n};\n\n\/**\n * A simple value container that provides the maximum of assigned values.\n *\n * @tparam T\n *\tThe value type\n *\/\ntemplate \nclass Max {\n\tprivate:\n\t\/**\n\t * The maximum of the assigned values.\n\t *\/\n\tT value;\n\n\tpublic:\n\t\/**\n\t * Construct from an initial value.\n\t *\n\t * @param value\n\t *\tThe initial value\n\t *\/\n\texplicit constexpr Max(T const & value) : value{value} {}\n\n\t\/**\n\t * Returns the current maximum.\n\t *\n\t * @return\n\t *\tThe maximum by const reference\n\t *\/\n\tconstexpr operator T const &() const {\n\t\treturn this->value;\n\t}\n\n\t\/**\n\t * Assign a new value, if it is greater than the current value.\n\t *\n\t * @param value\n\t *\tThe value to assign\n\t * @return\n\t *\tA self reference\n\t *\/\n\tconstexpr Max & operator =(T const & value) {\n\t\tthis->value = this->value >= value ? this->value : value;\n\t\treturn *this;\n\t}\n};\n\n\/**\n * A functor for reading numerical values from a string or character\n * array.\n *\/\nstruct FromChars {\n\t\/**\n\t * The next character to read.\n\t *\/\n\tchar const * it;\n\n\t\/**\n\t * The first character of the same array that may not be read,\n\t * this should usually point to a terminating zero or behind\n\t * a buffer.\n\t *\/\n\tchar const * const end;\n\n\t\/**\n\t * Retrieve an integral or floating point value from the array.\n\t *\n\t * The operation may fail for multiple reasons:\n\t *\n\t * - No more characters left to read, in that case the functor\n\t * will equal false\n\t * - The given characters do not represent a valid value, in\n\t * that case the functor will equal true\n\t *\n\t * @tparam T\n\t *\tThe value type to retrieve\n\t * @param dst\n\t *\tThe lvalue to assign to\n\t * @retval true\n\t *\tThe numerical value was successfully read from the array\n\t * @retval false\n\t *\tThe numerical value could not be read from the array\n\t *\/\n\ttemplate \n\t[[nodiscard]] bool operator ()(T & dst) {\n\t\tif (!this->it) {\n\t\t\treturn false;\n\t\t}\n\t\tauto [p, ec] = std::from_chars(this->it, this->end, dst);\n\t\tif (this->it == p) {\n\t\t\treturn false;\n\t\t}\n\t\tfor (; p != this->end && std::isspace(*p); ++p);\n\t\tthis->it = p;\n\t\treturn true;\n\t}\n\n\t\/**\n\t * Check if unread characters remain.\n\t *\n\t * @retval false\n\t *\tAll characters have been read\n\t * @retval true\n\t *\tCharacters remain to be read\n\t *\/\n\toperator bool() const {\n\t\treturn this->it && this->end != this->it && *this->it;\n\t}\n\n\t\/**\n\t * Range based constructor.\n\t *\n\t * @param start,end\n\t *\tThe character array range\n\t *\/\n\tFromChars(char const * const start, char const * const end) :\n\t it{start}, end{end} {\n\t\tfor (; this->it != end && std::isspace(*this->it); ++this->it);\n\t}\n\n\t\/**\n\t * Construct from a character array.\n\t *\n\t * @tparam CountV\n\t *\tThe number of characters\n\t * @param str\n\t *\tThe character array to parse from\n\t * @param terminator\n\t *\tIndicates whether the character array has a terminating\n\t *\tnull character.\n\t *\/\n\ttemplate \n\tFromChars(char const (& str)[CountV], bool const terminator = true) :\n\t FromChars{str, str + CountV - terminator} {}\n\n\t\/**\n\t * Construct functor from a string.\n\t *\n\t * Note that changing the string during the lifetime of the\n\t * functor may silently invalidate the functor's state and\n\t * thus invoke undefined behaviour.\n\t *\n\t * @param str\n\t *\tThe string to parse from\n\t *\/\n\tFromChars(std::string const & str) :\n\t FromChars{str.data(), str.data() + str.size()} {}\n};\n\n} \/* namespace utility *\/\n\n#endif \/* _POWERDXX_UTILITY_HPP_ *\/\n<|endoftext|>"} {"text":"#ifndef UTILITY_HPP\n#define UTILITY_HPP\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 \"MDL\/mdl_file.hpp\"\n#include \"vector.hpp\"\n#include \"SDL2\/SDL.h\"\n\nnamespace tz\n{\t\n\tnamespace consts\n\t{\n\t\t\/\/\/ 3.14159...\n\t\tconstexpr double pi = 4 * std::atan(1);\n\t\t\/\/\/ 2.17...\n\t\tconstexpr double e = std::exp(1);\n\t}\n\tnamespace literals\n\t{\n\t\t\/**\n\t\t* Convert a mass in metric kilograms (kg) to imperial pounds (lb).\n\t\t*\/\n\t\tinline long double operator\"\"_lb(long double mass)\n\t\t{\n\t\t\treturn mass * 0.45359237;\n\t\t}\n\t\t\/**\n\t\t* Convert a mass in metric kilograms(kg) to imperial stone (st).\n\t\t*\/\n\t\tinline long double operator\"\"_st(long double mass)\n\t\t{\n\t\t\tusing namespace tz::literals;\n\t\t\treturn operator\"\"_lb(mass * 14.0);\n\t\t}\n\t\t\/**\n\t\t* Convert an angle in degrees to an angle in radians.\n\t\t* i.e: 180_deg = π\n\t\t*\/\n\t\tinline long double operator\"\"_deg(long double angle)\n\t\t{\n\t\t\treturn angle * tz::consts::pi \/ 180.0;\n\t\t}\n\t\t\/**\n\t\t* Convert an angle in radians to an angle in degrees.\n\t\t* i.e: π_rad = 180\n\t\t*\/\n\t\tinline long double operator\"\"_rad(long double angle)\n\t\t{\n\t\t\treturn angle * 180.0 \/ tz::consts::pi;\n\t\t}\n\t}\n\tnamespace util\n\t{\n\t\t\/**\n\t\t * Given a container, find the size, in bytes, of an element in the container.\n\t\t * @tparam Container - Container type.\n\t\t * @param element_list - Container of elements.\n\t\t * @return\n\t\t *\/\n\t\ttemplate\n\t\tconstexpr std::size_t sizeof_element(Container element_list);\n\t\t\n\t\tnamespace cast\n\t\t{\n\t\t\t\/**\n\t\t\t* Convert anything that can be converted into an std::string, into an std::string.\n\t\t\t*\/\n\t\t\ttemplate \n\t\t\tinline std::string to_string(T&& obj);\n\t\t\t\/**\n\t\t\t* Convert an std::string to any value, if it can.\n\t\t\t*\/\n\t\t\ttemplate \n\t\t\tinline T from_string(const std::string& s);\n\t\t}\n\t\t\n\t\t\/**\n\t\t* Perform processing on std::strings with these utility functions.\n\t\t*\/\n\t\tnamespace string\n\t\t{\n\t\t\tinline std::string to_lower(std::string data);\n\t\t\tinline std::string to_upper(std::string data);\n\t\t\tinline bool begins_with(const std::string& what, const std::string& with_what);\n\t\t\tinline bool ends_with(const std::string& what, const std::string& with_what);\n\t\t\tinline bool contains(const std::string& what, char withwhat);\n\t\t\tinline std::vector split_string(const std::string& s, const std::string& delim);\n\t\t\tinline std::vector split_string(const std::string& s, char delim);\n\t\t\tinline std::string replace_all_char(const std::string& str, char toreplace, const std::string& replacewith);\n\t\t\tinline std::string replace_all(std::string str, const std::string& to_replace, const std::string& replace_with);\n\t\t\tinline std::string substring(const std::string& str, std::size_t begin, std::size_t end);\n\t\t\tinline std::string format(const std::vector& split);\n\t\t\tinline std::vector deformat(const std::string& str);\n\t\t\ttemplate\n\t\t\tinline Vector3 vectorise_list_3(const std::vector& list);\n\t\t\ttemplate\n\t\t\tinline std::vector devectorise_list_3(Vector3 v);\n\t\t}\n\n\t\t\/**\n\t\t* Log to the console variadically.\n\t\t* Like printf, but without the formatting and with type-safety.\n\t\t*\/\n\t\tnamespace log\n\t\t{\n\t\t\tinline void silent();\n\t\t\ttemplate\n\t\t\tinline void silent(FirstArg arg, Args... args);\n\t\t\ttemplate\n\t\t\tinline void message(FirstArg arg, Args... args);\n\t\t\ttemplate\n\t\t\tinline void warning(FirstArg arg, Args... args);\n\t\t\ttemplate\n\t\t\tinline void error(FirstArg arg, Args... args);\n\t\t}\n\t\t\n\t\tnamespace scheduler\n\t\t{\n\t\t\t\/**\n\t\t\t* Invokes std::functions synchronously (pretty much just runs a function for you) or asynchronously (runs the function in another thread as to not impede current processing).\n\t\t\t* You may well find this incredibly useful, however it does contain some overhead and therefore is not recommended for small, menial tasks.\n\t\t\t* For smaller and simpler tasks, it is highly recommended that you instead use tz::util::scheduler::[a]sync_delayed_functor(TrivialFunctor), in command.hpp.\n\t\t\t*\/\n\t\t\ttemplate\n\t\t\tinline void sync_delayed_function(unsigned int milliseconds_delay, std::function f, Args... args);\n\t\t\ttemplate\n\t\t\tinline void async_delayed_function(unsigned int milliseconds_delay, std::function f, Args... args);\n\t\t}\n\t\t\ttemplate\n\t\t\tinline Number random();\n\t}\n}\n\n\/**\n* Generate a random number using any of the C++ standard library random engines.\n* Using default template arguments yields implementation-defined behaviour, but normally is a linear-congruentional engine.\n*\/\ntemplate\nclass Random\n{\npublic:\n\tRandom(EngineResultType seed = std::random_device()());\n\tRandom(const Random& copy);\n\tRandom(Random&& move) = default;\n\t~Random() = default;\n\tRandom& operator=(const Random& rhs) = default;\n\t\n\tconst EngineResultType& get_seed() const;\n\tconst Engine& get_engine() const;\n\tint next_int(int min = 0, int max = std::numeric_limits::max());\n\tfloat next_float(float min = 0, float max = std::numeric_limits::max());\n\ttemplate \n\tinline Number operator()(Number min = Number(), Number max = std::numeric_limits::max());\nprivate:\n\tconst EngineResultType seed;\n\tEngine random_engine;\n};\n\n\/**\n* Template specialisation of Random, using the C++ mersenne-twister functionality.\n* More expensive than a linear-congruentional approach, but does provide higher-quality pseudorandomness.\n*\/\nusing MersenneTwister = Random;\n\n\/**\n * Wrapper for a function with variadic arguments. Unlike TrivialFunctor, cannot be inserted into a CommandExecutor.\n *\/\ntemplate\nclass Functor\n{\npublic:\n\tFunctor(FunctorT functor);\n\ttemplate\n\tvoid operator()(FunctorParameters... parameters);\nprivate:\n\tFunctorT functor;\n};\n#include \"utility.inl\"\n#endifutility.hpp completely documented now I think. It was horrific#ifndef UTILITY_HPP\n#define UTILITY_HPP\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 \"MDL\/mdl_file.hpp\"\n#include \"vector.hpp\"\n#include \"SDL2\/SDL.h\"\n\nnamespace tz\n{\t\n\tnamespace consts\n\t{\n\t\t\/\/\/ 3.14159...\n\t\tconstexpr double pi = 4 * std::atan(1);\n\t\t\/\/\/ 2.17...\n\t\tconstexpr double e = std::exp(1);\n\t}\n\tnamespace literals\n\t{\n\t\t\/**\n\t\t* Convert a mass in metric kilograms (kg) to imperial pounds (lb).\n\t\t*\/\n\t\tinline long double operator\"\"_lb(long double mass)\n\t\t{\n\t\t\treturn mass * 0.45359237;\n\t\t}\n\t\t\/**\n\t\t* Convert a mass in metric kilograms(kg) to imperial stone (st).\n\t\t*\/\n\t\tinline long double operator\"\"_st(long double mass)\n\t\t{\n\t\t\tusing namespace tz::literals;\n\t\t\treturn operator\"\"_lb(mass * 14.0);\n\t\t}\n\t\t\/**\n\t\t* Convert an angle in degrees to an angle in radians.\n\t\t* i.e: 180_deg = π\n\t\t*\/\n\t\tinline long double operator\"\"_deg(long double angle)\n\t\t{\n\t\t\treturn angle * tz::consts::pi \/ 180.0;\n\t\t}\n\t\t\/**\n\t\t* Convert an angle in radians to an angle in degrees.\n\t\t* i.e: π_rad = 180\n\t\t*\/\n\t\tinline long double operator\"\"_rad(long double angle)\n\t\t{\n\t\t\treturn angle * 180.0 \/ tz::consts::pi;\n\t\t}\n\t}\n\tnamespace util\n\t{\n\t\t\/**\n\t\t * Given a container, find the size, in bytes, of an element in the container.\n\t\t * @tparam Container - Container type.\n\t\t * @param element_list - Container of elements.\n\t\t * @return\n\t\t *\/\n\t\ttemplate\n\t\tconstexpr std::size_t sizeof_element(Container element_list);\n\t\t\n\t\tnamespace cast\n\t\t{\n\t\t\t\/**\n\t\t\t * (Attempt to) Convert an object to a std::string.\n\t\t\t * @tparam T - Type of the object to convert\n\t\t\t * @param obj - The object to convert\n\t\t\t * @return - The object, converted to a string\n\t\t\t *\/\n\t\t\ttemplate \n\t\t\tinline std::string to_string(T&& obj);\n\t\t\t\/**\n\t\t\t * (Attempt to) Convert an std::string to an object of specified type.\n\t\t\t * @tparam T - Type of the object to convert to\n\t\t\t * @param s - The object to convert to\n\t\t\t * @return - The object that the string was converted to\n\t\t\t *\/\n\t\t\ttemplate \n\t\t\tinline T from_string(const std::string& s);\n\t\t}\n\t\t\n\t\t\/**\n\t\t* Perform processing on std::strings with these utility functions.\n\t\t*\/\n\t\tnamespace string\n\t\t{\n\t\t \/**\n\t\t * Convert the input string to lower-case.\n\t\t * @param data - The string to convert to lower-case\n\t\t * @return - data, in lower-case\n\t\t *\/\n\t\t\tinline std::string to_lower(std::string data);\n \/**\n * Convert the input string to upper-case.\n * @param data - The string to convert to upper-case\n * @return - data, in upper-case\n *\/\n\t\t\tinline std::string to_upper(std::string data);\n\t\t\t\/**\n\t\t\t * Query whether an existing string begins with another.\n\t\t\t * @param what - The string to query\n\t\t\t * @param with_what - The prefix to equate\n\t\t\t * @return - True if with starts with with_what. False otherwise\n\t\t\t *\/\n\t\t\tinline bool begins_with(const std::string& what, const std::string& with_what);\n \/**\n * Query whether an existing string ends with another.\n * @param what - The string to query\n * @param with_what - The suffix to equate\n * @return - True if with ends with with_what. False otherwise\n *\/\n\t\t\tinline bool ends_with(const std::string& what, const std::string& with_what);\n\t\t\t\/**\n\t\t\t * Query whether an existing string contains another substring.\n\t\t\t * @param what - The string to query\n\t\t\t * @param withwhat - The substring to query for containment\n\t\t\t * @return - True if what contains the substring withwhat. False otherwise\n\t\t\t *\/\n\t\t\tinline bool contains(const std::string& what, char withwhat);\n\t\t\t\/**\n\t\t\t * Split an existing string with a specified delimiter.\n\t\t\t * @param s - The string to perform on\n\t\t\t * @param delim - The delimiter to use\n\t\t\t * @return - Container of strings, split from the source string via the specified delimiter\n\t\t\t *\/\n\t\t\tinline std::vector split_string(const std::string& s, const std::string& delim);\n \/**\n * Split an existing string with a specified delimiter.\n * @param s - The string to perform on\n * @param delim - The delimiter to use\n * @return - Container of strings, split from the source string via the specified delimiter\n *\/\n\t\t\tinline std::vector split_string(const std::string& s, char delim);\n\t\t\t\/**\n\t\t\t * Replace all instances of a character in a specified string with a replacement string.\n\t\t\t * @param str - The specified string\n\t\t\t * @param toreplace - The character to be replaced\n\t\t\t * @param replacewith - The replacement string\n\t\t\t * @return - The edited source string\n\t\t\t *\/\n\t\t\tinline std::string replace_all_char(const std::string& str, char toreplace, const std::string& replacewith);\n\t\t\t\/**\n\t\t\t * Replace all instances of a string in a specified string with a replacement string.\n\t\t\t * @param str - The specified string\n\t\t\t * @param to_replace - The string to be replaced\n\t\t\t * @param replace_with - The replacement string\n\t\t\t * @return - The edited source string\n\t\t\t *\/\n\t\t\tinline std::string replace_all(std::string str, const std::string& to_replace, const std::string& replace_with);\n\t\t\t\/**\n\t\t\t * Construct a substring from an existing string between two indices.\n\t\t\t * @param str - The source string\n\t\t\t * @param begin - The first index\n\t\t\t * @param end - The second index\n\t\t\t * @return - The substring\n\t\t\t *\/\n\t\t\tinline std::string substring(const std::string& str, std::size_t begin, std::size_t end);\n\t\t\t\/**\n\t\t\t * Emplace all elements of a container of strings within the following string:\n\t\t\t * [element0, element1, etc...]\n\t\t\t * @param split - The container of strings to format\n\t\t\t * @return - The formatted container of strings\n\t\t\t *\/\n\t\t\tinline std::string format(const std::vector& split);\n\t\t\t\/**\n\t\t\t * Given a formatted string, extract all the elements contained within the formatted string.\n\t\t\t * @param str - The formatted string\n\t\t\t * @return - Container of the strings in the formatted string\n\t\t\t *\/\n\t\t\tinline std::vector deformat(const std::string& str);\n\t\t\t\/**\n\t\t\t * Convert the first three elements of a container of strings into the type T, and place into a 3-dimensional Vector.\n\t\t\t * @tparam T - The type to store into the 3-dimensional Vector\n\t\t\t * @param list - The container of strings\n\t\t\t * @return - The resultant 3-dimensional Vector\n\t\t\t *\/\n\t\t\ttemplate\n\t\t\tinline Vector3 vectorise_list_3(const std::vector& list);\n\t\t\t\/**\n\t\t\t * Given a 3-dimensional Vector containing types T, convert them into a string and place within a container.\n\t\t\t * @tparam T - Type of the elements in the 3-dimensional Vector\n\t\t\t * @param v - The 3-dimensional Vector to extract from\n\t\t\t * @return - The resultant container of strings\n\t\t\t *\/\n\t\t\ttemplate\n\t\t\tinline std::vector devectorise_list_3(Vector3 v);\n\t\t}\n\n\t\t\/**\n\t\t* Log to the console variadically.\n\t\t* Like printf, but without the formatting and with type-safety.\n\t\t*\/\n\t\tnamespace log\n\t\t{\n\t\t \/\/\/ Base-case for log::silent, log::message, log::warning and log::error.\n\t\t\tinline void silent();\n\t\t\t\/**\n\t\t\t * Essentially a printf but without formatting. Prints the parameters to the standard output.\n\t\t\t * @tparam FirstArg - Type of the first argument\n\t\t\t * @tparam Args - Type of the remaining arguments\n\t\t\t * @param arg - The first argument\n\t\t\t * @param args - The remaining arguments\n\t\t\t *\/\n\t\t\ttemplate\n\t\t\tinline void silent(FirstArg arg, Args... args);\n\t\t\t\/**\n\t\t\t * Print the parameters with Topaz-formatting to the standard output.\n\t\t\t * Output: [Message]: parameters\n\t\t\t * @tparam FirstArg - Type of the first argument\n\t\t\t * @tparam Args - Type of the remaining arguments\n\t\t\t * @param arg - The first argument\n\t\t\t * @param args - The remaining arguments\n\t\t\t *\/\n\t\t\ttemplate\n\t\t\tinline void message(FirstArg arg, Args... args);\n \/**\n * Print the parameters with Topaz-formatting to the standard output.\n * Output: [Warning]: parameters\n * @tparam FirstArg - Type of the first argument\n * @tparam Args - Type of the remaining arguments\n * @param arg - The first argument\n * @param args - The remaining arguments\n *\/\n\t\t\ttemplate\n\t\t\tinline void warning(FirstArg arg, Args... args);\n \/**\n * Print the parameters with Topaz-formatting to the standard output.\n * Output: [Error]: parameters\n * @tparam FirstArg - Type of the first argument\n * @tparam Args - Type of the remaining arguments\n * @param arg - The first argument\n * @param args - The remaining arguments\n *\/\n\t\t\ttemplate\n\t\t\tinline void error(FirstArg arg, Args... args);\n\t\t}\n\t\t\n\t\tnamespace scheduler\n\t\t{\n\t\t\t\/**\n\t\t\t * Invokes a function synchronously with specified arguments after a specified delay.\n\t\t\t * @tparam ReturnType - Return type of the function\n\t\t\t * @tparam Args - Argument types of the function\n\t\t\t * @param milliseconds_delay - Number of milliseconds to elapse before executing the function.\n\t\t\t * @param f - The function to execute\n\t\t\t * @param args - Arguments to emplace into the function invocation\n\t\t\t *\/\n\t\t\ttemplate\n\t\t\tinline void sync_delayed_function(unsigned int milliseconds_delay, std::function f, Args... args);\n \/**\n * Invokes a function asynchronously with specified arguments after a specified delay.\n * @tparam ReturnType - Return type of the function\n * @tparam Args - Argument types of the function\n * @param milliseconds_delay - Number of milliseconds to elapse before executing the function.\n * @param f - The function to execute\n * @param args - Arguments to emplace into the function invocation\n *\/\n\t\t\ttemplate\n\t\t\tinline void async_delayed_function(unsigned int milliseconds_delay, std::function f, Args... args);\n\t\t}\n\n\t\t\/**\n\t\t * Generate a random number.\n\t\t * @tparam Number - Type of the number\n\t\t * @return - The random number generated\n\t\t *\/\n\t\ttemplate\n inline Number random();\n\t}\n}\n\n\/**\n * Object to generate random numbers with a given RNG-engine.\n * @tparam Engine - Random engine device\n * @tparam EngineResultType - Return type of the engine's productions\n *\/\ntemplate\nclass Random\n{\npublic:\n \/**\n * Generate a Random from a seed.\n * @param seed - The seed for the RNG engine\n *\/\n\tRandom(EngineResultType seed = std::random_device()());\n\t\/**\n\t * Construct a Random from an existing, using their seed and engine.\n\t * @param copy - Random object to copy the seed and engine from.\n\t *\/\n\tRandom(const Random& copy);\n\n\t\/**\n\t * Get the value of the seed to this engine.\n\t * @return - The seed value\n\t *\/\n\tconst EngineResultType& get_seed() const;\n\t\/**\n\t * Read-only access to the underlying random engine.\n\t * @return - The random engine being used\n\t *\/\n\tconst Engine& get_engine() const;\n\t\/**\n\t * Generate a random signed integer between specified limits.\n\t * @param min - The minimum result of the integer\n\t * @param max - The maximum result of the integer\n\t * @return\n\t *\/\n\tint next_int(int min = 0, int max = std::numeric_limits::max());\n \/**\n * Generate a random float between specified limits.\n * @param min - The minimum result of the float\n * @param max - The maximum result of the float\n * @return\n *\/\n\tfloat next_float(float min = 0, float max = std::numeric_limits::max());\n \/**\n * Generate a random number between specified limits.\n * @tparam Number - The type of value to generate\n * @param min - The minimum result of the number\n * @param max - The maximum result of the number\n * @return\n *\/\n\ttemplate \n\tinline Number operator()(Number min = Number(), Number max = std::numeric_limits::max());\nprivate:\n \/\/\/ Stores the seed used for this Random object.\n\tconst EngineResultType seed;\n \/\/\/ Stores the underlying RNG engine for this Random object.\n\tEngine random_engine;\n};\n\n\/**\n* Template specialisation of Random, using the C++ mersenne-twister functionality.\n* More expensive than a linear-congruentional approach, but does provide higher-quality pseudorandomness.\n*\/\nusing MersenneTwister = Random;\n\n\/**\n * Wrapper for a Functor, using variadic arguments.\n * @tparam FunctorT - Type of the functor\n *\/\ntemplate\nclass Functor\n{\npublic:\n \/**\n * Generate a Functor directly from a callable type.\n * @param functor - The functor value\n *\/\n\tFunctor(FunctorT functor);\n\t\/**\n\t * Execute the functor, providing all parameter values\n\t * @tparam FunctorParameters - Types of the functor parameters\n\t * @param parameters - Values of the functor parameters\n\t *\/\n\ttemplate\n\tvoid operator()(FunctorParameters... parameters);\nprivate:\n \/\/\/ The underlying functor.\n\tFunctorT functor;\n};\n#include \"utility.inl\"\n#endif<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 Hewlett-Packard Development Company, L.P. 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 \n#include \"canvas.h\"\n#include \"console.h\"\n#include \"webgl_rendering_context.h\"\n\nnamespace v8_webgl {\n\nstatic Factory* s_factory = 0;\nstatic v8::Persistent s_global;\n\nv8::Persistent Initialize(Factory* factory) {\n if (!s_global.IsEmpty())\n return s_global;\n\n s_factory = factory;\n\n v8::HandleScope scope;\n v8::Local global = v8::ObjectTemplate::New();\n s_global = v8::Persistent::New(global);\n\n Console::Initialize(s_global);\n Canvas::Initialize(s_global);\n WebGLRenderingContext::Initialize(s_global);\n \/\/XXX initialize webgl classes with global\n\n return s_global;\n}\n\nvoid Uninitialize() {\n if (s_global.IsEmpty())\n return;\n s_global.Dispose();\n s_global.Clear();\n\n delete s_factory;\n s_factory = 0;\n\n Console::Uninitialize();\n Canvas::Uninitialize();\n WebGLRenderingContext::Uninitialize();\n \/\/XXX uninitialize webgl classes\n\n v8::V8::Dispose();\n}\n\nFactory* GetFactory() {\n return s_factory;\n}\n\n}\nTry to GC everything when shutting down.\/\/ Copyright (c) 2012 Hewlett-Packard Development Company, L.P. 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 \n#include \"canvas.h\"\n#include \"console.h\"\n#include \"webgl_rendering_context.h\"\n\nnamespace v8_webgl {\n\nstatic Factory* s_factory = 0;\nstatic v8::Persistent s_global;\n\nv8::Persistent Initialize(Factory* factory) {\n if (!s_global.IsEmpty())\n return s_global;\n\n s_factory = factory;\n\n v8::HandleScope scope;\n v8::Local global = v8::ObjectTemplate::New();\n s_global = v8::Persistent::New(global);\n\n Console::Initialize(s_global);\n Canvas::Initialize(s_global);\n WebGLRenderingContext::Initialize(s_global);\n \/\/XXX initialize webgl classes with global\n\n return s_global;\n}\n\nvoid Uninitialize() {\n if (s_global.IsEmpty())\n return;\n s_global.Dispose();\n s_global.Clear();\n\n delete s_factory;\n s_factory = 0;\n\n Console::Uninitialize();\n Canvas::Uninitialize();\n WebGLRenderingContext::Uninitialize();\n \/\/XXX uninitialize webgl classes\n\n \/\/ Run GC until everything is freed\n while (!v8::V8::IdleNotification()) {}\n v8::V8::Dispose();\n}\n\nFactory* GetFactory() {\n return s_factory;\n}\n\n}\n<|endoftext|>"} {"text":"\/* FMINST -- simple FM instrument\n \n p0 = start time\n p1 = duration\n p2 = amp *\n p3 = frequency of carrier (Hz or oct.pc **)\n p4 = frequency of modulator (Hz or oct.pct)\n p5 = FM index low point\n p6 = FM index high point\n p7 = pan (in percent-to-left form: 0-1) [optional; default is 0]\n p8 = reference to wavetable [optional; if missing, must use gen 2 ***]\n p9 = index guide [optional; if missing, must use gen 3 ****]\n\n p2 (amplitude), p3 (carrier freq), p4 (modulator freq), p5 (index low),\n p6 (index high), p7 (pan) and p9 (index guide) can receive dynamic updates\n from a table or real-time control source.\n\n * If an old-style gen table 1 is present, its values will be multiplied\n by p2 (amp), even if the latter is dynamic.\n\n ** oct.pc format generally will not work as you expect for p3 and p4\n (osc freq) if the pfield changes dynamically. Use Hz instead in that case.\n\n *** If p8 is missing, you must use an old-style gen table 2 for the\n oscillator waveform.\n\n **** If p9 is missing, you must use an old-style gen table 3 for the\n index guide function.\n\n rev for v4, JGG, 7\/12\/04\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \t\t\/\/ for fastUpdate\n#include \"FMINST.h\"\n#include \n#include \n\n#define AMP_GEN_SLOT 1\n#define WAVET_GEN_SLOT 2\n#define INDEX_GEN_SLOT 3\n\n\nFMINST::FMINST() : Instrument()\n{\n\tindexenv = NULL;\n\tbranch = 0;\n}\n\nFMINST::~FMINST()\n{\n\tdelete carosc;\n\tdelete modosc;\n}\n\n\/\/ In fastUpdate mode, we skip doupdate() entirely, instead updating only amp,\n\/\/ and only from a table. The table can be a makegen or a PField table. PField\n\/\/ tables must be \"flattened\" using copytable if they are compound (e.g. passed\n\/\/ through a PField filter or multiplied by a constant). We use p[ampindex] as\n\/\/ an amp multiplier, unless using a PField table, in which case there is no amp\n\/\/ multiplier -- the p[ampindex] value is the first table value. -JGG\n\nvoid FMINST::initamp(float dur, double p[], int ampindex, int ampgenslot)\n{\n\tfastUpdate = Option::fastUpdate();\n\tif (fastUpdate) {\n\t\t\/\/ Prefer PField table, otherwise makegen\n\t\tint tablen = 0;\n\t\tamptable = (double *) getPFieldTable(ampindex, &tablen);\n\t\tif (amptable)\n\t\t\tampmult = 1.0f;\n\t\telse {\n\t\t\tampmult = p[ampindex];\n\t\t\tamptable = floc(ampgenslot);\n\t\t\tif (amptable)\n\t\t\t\ttablen = fsize(ampgenslot);\n\t\t}\n\t\tif (amptable)\n\t\t\ttableset(SR, dur, tablen, amptabs);\n\t\telse\n\t\t\tamp = ampmult;\n\t}\n\telse {\n\t\t\/\/ NB: ampmult never used, first amp set in doupdate\n\t\tamptable = floc(ampgenslot);\n\t\tif (amptable) {\n\t\t\tint tablen = fsize(ampgenslot);\n\t\t\ttableset(SR, dur, tablen, amptabs);\n\t\t}\n\t}\n}\n\nint FMINST::init(double p[], int n_args)\n{\n\tnargs = n_args;\n\tfloat outskip = p[0];\n\tfloat dur = p[1];\n\n\tif (rtsetoutput(outskip, dur, this) == -1)\n\t\treturn DONT_SCHEDULE;\n\tif (outputChannels() > 2)\n\t\treturn die(\"FMINST\", \"Can't handle more than 2 output channels.\");\n\n\tcarfreqraw = p[3];\n\tif (carfreqraw < 15.0)\n\t\tcarfreq = cpspch(carfreqraw);\n\telse\n\t\tcarfreq = carfreqraw;\n\n\tmodfreqraw = p[4];\n\tif (modfreqraw < 15.0)\n\t\tmodfreq = cpspch(modfreqraw);\n\telse\n\t\tmodfreq = modfreqraw;\n\n\tdouble *wavetable = NULL;\n\tint tablelen = 0;\n\tif (n_args > 8) { \/\/ handle table coming in as optional p8 TablePField\n\t\twavetable = (double *) getPFieldTable(8, &tablelen);\n\t}\n\tif (wavetable == NULL) {\n\t\twavetable = floc(WAVET_GEN_SLOT);\n\t\tif (wavetable == NULL)\n\t\t\treturn die(\"FMINST\", \"Either use the wavetable pfield (p8) or make \"\n \"an old-style gen function in slot %d.\", WAVET_GEN_SLOT);\n\t\ttablelen = fsize(WAVET_GEN_SLOT);\n\t}\n\tif (tablelen > 32767)\n\t\treturn die(\"FMINST\", \"wavetable must have fewer than 32768 samples.\");\n\n\tcarosc = new Ooscili(SR, carfreq, wavetable, tablelen);\n\tmodosc = new Ooscili(SR, modfreq, wavetable, tablelen);\n\n\tif (n_args < 10) {\t\t\/\/ no p9 guide PField, must use gen table\n\t\tindexenv = floc(INDEX_GEN_SLOT);\n\t\tif (indexenv == NULL)\n\t\t\treturn die(\"FMINST\", \"Either use the index guide pfield (p9) or make \"\n \"an old-style gen function in slot %d.\", INDEX_GEN_SLOT);\n\t\tint len = fsize(INDEX_GEN_SLOT);\n\t\ttableset(SR, dur, len, indtabs);\n\t}\n\n\tinitamp(dur, p, 2, 1);\n\tif (fastUpdate) {\n\t\tminindex = p[5];\n\t\tindexdiff = p[6] - minindex;\n\t\tpan = p[7];\n\t}\n\n\treturn nSamps();\n}\n\nvoid FMINST::doupdate()\n{\n double p[10];\n update(p, 10);\n\n\tamp = p[2];\n\tif (amptable)\n\t\tamp *= tablei(currentFrame(), amptable, amptabs);\n\n\tif (p[3] != carfreqraw) {\n\t\tcarfreqraw = p[3];\n\t\tif (carfreqraw < 15.0)\n\t\t\tcarfreq = cpspch(carfreqraw);\n\t\telse\n\t\t\tcarfreq = carfreqraw;\n\t}\n\tif (p[4] != modfreqraw) {\n\t\tmodfreqraw = p[4];\n\t\tif (modfreqraw < 15.0)\n\t\t\tmodfreq = cpspch(modfreqraw);\n\t\telse\n\t\t\tmodfreq = modfreqraw;\n\t\tmodosc->setfreq(modfreq);\n\t}\n\n\tminindex = p[5];\n\tfloat maxindex = p[6];\n\tif (minindex > maxindex) {\t\t\/\/ swap if wrong order\n\t\tfloat tmp = minindex;\n\t\tminindex = maxindex;\n\t\tmaxindex = tmp;\n\t}\n\tfloat guide;\n\tif (nargs > 9)\t\t\t\/\/ guide pfield is present\n\t\tguide = p[9];\n\telse \/\/ backward-compatible gen table\n\t\tguide = tablei(currentFrame(), indexenv, indtabs);\n\tfloat index = minindex + ((maxindex - minindex) * guide);\n\tpeakdev = index * modfreq;\n\n\tpan = p[7];\n}\n\nint FMINST::run()\n{\n\tconst int nframes = framesToRun();\n\tfor (int i = 0; i < nframes; i++) {\n\t\tif (--branch <= 0) {\n\t\t\tif (fastUpdate) {\n\t\t\t\tif (amptable)\n\t\t\t\t\tamp = ampmult * tablei(currentFrame(), amptable, amptabs);\n\t\t\t\tfloat guide = tablei(currentFrame(), indexenv, indtabs);\n\t\t\t\tpeakdev = modfreq * (minindex + (indexdiff * guide));\n\t\t\t}\n\t\t\telse\n\t\t\t\tdoupdate();\n\t\t\tbranch = getSkip();\n\t\t}\n\n\t\tfloat out[2];\n\n\t\tfloat modsig = modosc->next() * peakdev;\n\t\tcarosc->setfreq(carfreq + modsig);\n\t\tout[0] = carosc->next() * amp;\n\n\t\tif (outputChannels() == 2) {\n\t\t\tout[1] = (1.0 - pan) * out[0];\n\t\t\tout[0] *= pan;\n\t\t}\n\n\t\trtaddout(out);\n\t\tincrement();\n\t}\n\treturn framesToRun();\n}\n\nInstrument *makeFMINST()\n{\n\tFMINST *inst;\n\n\tinst = new FMINST();\n\tinst->set_bus_config(\"FMINST\");\n\n\treturn inst;\n}\n\nvoid rtprofile()\n{\n\tRT_INTRO(\"FMINST\",makeFMINST);\n}\n\nBGG: removed tablelen restriction (no longer valid), 1\/12\/2011\/* FMINST -- simple FM instrument\n \n p0 = start time\n p1 = duration\n p2 = amp *\n p3 = frequency of carrier (Hz or oct.pc **)\n p4 = frequency of modulator (Hz or oct.pct)\n p5 = FM index low point\n p6 = FM index high point\n p7 = pan (in percent-to-left form: 0-1) [optional; default is 0]\n p8 = reference to wavetable [optional; if missing, must use gen 2 ***]\n p9 = index guide [optional; if missing, must use gen 3 ****]\n\n p2 (amplitude), p3 (carrier freq), p4 (modulator freq), p5 (index low),\n p6 (index high), p7 (pan) and p9 (index guide) can receive dynamic updates\n from a table or real-time control source.\n\n * If an old-style gen table 1 is present, its values will be multiplied\n by p2 (amp), even if the latter is dynamic.\n\n ** oct.pc format generally will not work as you expect for p3 and p4\n (osc freq) if the pfield changes dynamically. Use Hz instead in that case.\n\n *** If p8 is missing, you must use an old-style gen table 2 for the\n oscillator waveform.\n\n **** If p9 is missing, you must use an old-style gen table 3 for the\n index guide function.\n\n rev for v4, JGG, 7\/12\/04\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \t\t\/\/ for fastUpdate\n#include \"FMINST.h\"\n#include \n#include \n\n#define AMP_GEN_SLOT 1\n#define WAVET_GEN_SLOT 2\n#define INDEX_GEN_SLOT 3\n\n\nFMINST::FMINST() : Instrument()\n{\n\tindexenv = NULL;\n\tbranch = 0;\n}\n\nFMINST::~FMINST()\n{\n\tdelete carosc;\n\tdelete modosc;\n}\n\n\/\/ In fastUpdate mode, we skip doupdate() entirely, instead updating only amp,\n\/\/ and only from a table. The table can be a makegen or a PField table. PField\n\/\/ tables must be \"flattened\" using copytable if they are compound (e.g. passed\n\/\/ through a PField filter or multiplied by a constant). We use p[ampindex] as\n\/\/ an amp multiplier, unless using a PField table, in which case there is no amp\n\/\/ multiplier -- the p[ampindex] value is the first table value. -JGG\n\nvoid FMINST::initamp(float dur, double p[], int ampindex, int ampgenslot)\n{\n\tfastUpdate = Option::fastUpdate();\n\tif (fastUpdate) {\n\t\t\/\/ Prefer PField table, otherwise makegen\n\t\tint tablen = 0;\n\t\tamptable = (double *) getPFieldTable(ampindex, &tablen);\n\t\tif (amptable)\n\t\t\tampmult = 1.0f;\n\t\telse {\n\t\t\tampmult = p[ampindex];\n\t\t\tamptable = floc(ampgenslot);\n\t\t\tif (amptable)\n\t\t\t\ttablen = fsize(ampgenslot);\n\t\t}\n\t\tif (amptable)\n\t\t\ttableset(SR, dur, tablen, amptabs);\n\t\telse\n\t\t\tamp = ampmult;\n\t}\n\telse {\n\t\t\/\/ NB: ampmult never used, first amp set in doupdate\n\t\tamptable = floc(ampgenslot);\n\t\tif (amptable) {\n\t\t\tint tablen = fsize(ampgenslot);\n\t\t\ttableset(SR, dur, tablen, amptabs);\n\t\t}\n\t}\n}\n\nint FMINST::init(double p[], int n_args)\n{\n\tnargs = n_args;\n\tfloat outskip = p[0];\n\tfloat dur = p[1];\n\n\tif (rtsetoutput(outskip, dur, this) == -1)\n\t\treturn DONT_SCHEDULE;\n\tif (outputChannels() > 2)\n\t\treturn die(\"FMINST\", \"Can't handle more than 2 output channels.\");\n\n\tcarfreqraw = p[3];\n\tif (carfreqraw < 15.0)\n\t\tcarfreq = cpspch(carfreqraw);\n\telse\n\t\tcarfreq = carfreqraw;\n\n\tmodfreqraw = p[4];\n\tif (modfreqraw < 15.0)\n\t\tmodfreq = cpspch(modfreqraw);\n\telse\n\t\tmodfreq = modfreqraw;\n\n\tdouble *wavetable = NULL;\n\tint tablelen = 0;\n\tif (n_args > 8) { \/\/ handle table coming in as optional p8 TablePField\n\t\twavetable = (double *) getPFieldTable(8, &tablelen);\n\t}\n\tif (wavetable == NULL) {\n\t\twavetable = floc(WAVET_GEN_SLOT);\n\t\tif (wavetable == NULL)\n\t\t\treturn die(\"FMINST\", \"Either use the wavetable pfield (p8) or make \"\n \"an old-style gen function in slot %d.\", WAVET_GEN_SLOT);\n\t\ttablelen = fsize(WAVET_GEN_SLOT);\n\t}\n\n\tcarosc = new Ooscili(SR, carfreq, wavetable, tablelen);\n\tmodosc = new Ooscili(SR, modfreq, wavetable, tablelen);\n\n\tif (n_args < 10) {\t\t\/\/ no p9 guide PField, must use gen table\n\t\tindexenv = floc(INDEX_GEN_SLOT);\n\t\tif (indexenv == NULL)\n\t\t\treturn die(\"FMINST\", \"Either use the index guide pfield (p9) or make \"\n \"an old-style gen function in slot %d.\", INDEX_GEN_SLOT);\n\t\tint len = fsize(INDEX_GEN_SLOT);\n\t\ttableset(SR, dur, len, indtabs);\n\t}\n\n\tinitamp(dur, p, 2, 1);\n\tif (fastUpdate) {\n\t\tminindex = p[5];\n\t\tindexdiff = p[6] - minindex;\n\t\tpan = p[7];\n\t}\n\n\treturn nSamps();\n}\n\nvoid FMINST::doupdate()\n{\n double p[10];\n update(p, 10);\n\n\tamp = p[2];\n\tif (amptable)\n\t\tamp *= tablei(currentFrame(), amptable, amptabs);\n\n\tif (p[3] != carfreqraw) {\n\t\tcarfreqraw = p[3];\n\t\tif (carfreqraw < 15.0)\n\t\t\tcarfreq = cpspch(carfreqraw);\n\t\telse\n\t\t\tcarfreq = carfreqraw;\n\t}\n\tif (p[4] != modfreqraw) {\n\t\tmodfreqraw = p[4];\n\t\tif (modfreqraw < 15.0)\n\t\t\tmodfreq = cpspch(modfreqraw);\n\t\telse\n\t\t\tmodfreq = modfreqraw;\n\t\tmodosc->setfreq(modfreq);\n\t}\n\n\tminindex = p[5];\n\tfloat maxindex = p[6];\n\tif (minindex > maxindex) {\t\t\/\/ swap if wrong order\n\t\tfloat tmp = minindex;\n\t\tminindex = maxindex;\n\t\tmaxindex = tmp;\n\t}\n\tfloat guide;\n\tif (nargs > 9)\t\t\t\/\/ guide pfield is present\n\t\tguide = p[9];\n\telse \/\/ backward-compatible gen table\n\t\tguide = tablei(currentFrame(), indexenv, indtabs);\n\tfloat index = minindex + ((maxindex - minindex) * guide);\n\tpeakdev = index * modfreq;\n\n\tpan = p[7];\n}\n\nint FMINST::run()\n{\n\tconst int nframes = framesToRun();\n\tfor (int i = 0; i < nframes; i++) {\n\t\tif (--branch <= 0) {\n\t\t\tif (fastUpdate) {\n\t\t\t\tif (amptable)\n\t\t\t\t\tamp = ampmult * tablei(currentFrame(), amptable, amptabs);\n\t\t\t\tfloat guide = tablei(currentFrame(), indexenv, indtabs);\n\t\t\t\tpeakdev = modfreq * (minindex + (indexdiff * guide));\n\t\t\t}\n\t\t\telse\n\t\t\t\tdoupdate();\n\t\t\tbranch = getSkip();\n\t\t}\n\n\t\tfloat out[2];\n\n\t\tfloat modsig = modosc->next() * peakdev;\n\t\tcarosc->setfreq(carfreq + modsig);\n\t\tout[0] = carosc->next() * amp;\n\n\t\tif (outputChannels() == 2) {\n\t\t\tout[1] = (1.0 - pan) * out[0];\n\t\t\tout[0] *= pan;\n\t\t}\n\n\t\trtaddout(out);\n\t\tincrement();\n\t}\n\treturn framesToRun();\n}\n\nInstrument *makeFMINST()\n{\n\tFMINST *inst;\n\n\tinst = new FMINST();\n\tinst->set_bus_config(\"FMINST\");\n\n\treturn inst;\n}\n\nvoid rtprofile()\n{\n\tRT_INTRO(\"FMINST\",makeFMINST);\n}\n\n<|endoftext|>"} {"text":"#include \"chimera\/visitor.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace chimera;\nusing namespace clang;\nusing boost::algorithm::join;\n\nchimera::Visitor::Visitor(clang::CompilerInstance *ci,\n std::unique_ptr cc)\n: context_(&(ci->getASTContext()))\n, config_(std::move(cc))\n{\n \/\/ Do nothing.\n}\n\nbool chimera::Visitor::VisitDecl(Decl *decl)\n{\n if (!decl->isCanonicalDecl())\n return true;\n\n if (!IsEnclosed(decl))\n return true;\n\n if (isa(decl))\n GenerateCXXRecord(cast(decl));\n\n return true;\n}\n\nvoid chimera::Visitor::GenerateCXXRecord(CXXRecordDecl *const decl)\n{\n if (!decl->hasDefinition())\n return;\n\n const YAML::Node &node = config_->GetDeclaration(decl);\n\n std::cout\n << \"::boost::python::class_<\"\n << decl->getQualifiedNameAsString();\n\n const YAML::Node &noncopyable_node = node[\"noncopyable\"];\n if (const bool noncopyable = noncopyable_node && noncopyable_node.as(false))\n std::cout << \", ::boost::python::noncopyable\";\n\n if (const YAML::Node &held_type_node = node[\"held_type\"])\n std::cout << \", \" << held_type_node.as();\n\n std::vector base_names;\n\n if (const YAML::Node &bases_node = node[\"bases\"])\n base_names = bases_node.as >();\n else\n base_names = GetBaseClassNames(decl);\n\n if (!base_names.empty())\n {\n std::cout << \", ::boost::python::bases<\"\n << join(base_names, \", \") << \" >\";\n }\n\n std::cout << \" >\\n\";\n\n for (CXXMethodDecl *method_decl : decl->methods())\n {\n if (isa(method_decl))\n ; \/\/ do nothing\n else if (isa(method_decl))\n ; \/\/ do nothing\n else if (isa(method_decl))\n ; \/\/ TODO: Wrap constructors.\n else if (method_decl->isOverloadedOperator())\n ; \/\/ TODO: Wrap overloaded operators.\n else if (method_decl->isStatic())\n ; \/\/ TODO: Wrap static functions\n else\n GenerateCXXMethod(decl, method_decl);\n }\n}\n\nvoid chimera::Visitor::GenerateCXXMethod(\n CXXRecordDecl *class_decl, CXXMethodDecl *decl)\n{\n decl = decl->getCanonicalDecl();\n\n const QualType pointer_type = context_->getMemberPointerType(\n decl->getType(), class_decl->getTypeForDecl());\n const Type *return_type = decl->getReturnType().getTypePtr();\n\n const YAML::Node &node = config_->GetDeclaration(decl);\n const YAML::Node &rvp_node = node[\"return_value_policy\"];\n\n if (!rvp_node)\n {\n if (return_type->isReferenceType())\n {\n std::cerr\n << \"Warning: Skipped method '\"\n << decl->getQualifiedNameAsString()\n << \"' because it returns a reference and no\"\n \" 'return_value_policy' was specified.\\n\";\n return;\n }\n else if (return_type->isPointerType())\n {\n std::cerr\n << \"Warning: Skipped method '\"\n << decl->getQualifiedNameAsString()\n << \"' because it returns a pointer and no\"\n \" 'return_value_policy' was specified.\\n\";\n return;\n }\n\n \/\/ TODO: Check if return_type is non-copyable.\n }\n\n std::cout\n << \".def(\\\"\" << decl->getNameAsString() << \"\\\"\"\n << \", static_cast<\" << pointer_type.getAsString() << \">(&\"\n << decl->getQualifiedNameAsString() << \")\";\n\n if (rvp_node)\n {\n std::cout << \", boost::python::return_value_policy<\"\n << rvp_node.as() << \" >\";\n }\n\n const auto params = GetParameterNames(decl);\n if (!params.empty())\n {\n \/\/ TODO: Supress any default parameters that occur after the first\n \/\/ non-default to default transition. This can only occur if evaluating\n \/\/ the default value of one or more parameters failed.\n\n std::vector python_args;\n for (const auto ¶m : params)\n {\n std::stringstream python_arg;\n python_arg << \"boost::python::arg(\\\"\" << param.first << \"\\\")\";\n\n if (!param.second.empty())\n python_arg << \" = \" << param.second;\n\n python_args.push_back(python_arg.str());\n }\n\n std::cout << \", (\" << join(python_args, \", \") << \")\";\n }\n\n std::cout << \")\\n\";\n}\n\nstd::vector chimera::Visitor::GetBaseClassNames(\n CXXRecordDecl *decl) const\n{\n std::vector base_names;\n\n for (CXXBaseSpecifier &base_decl : decl->bases())\n {\n if (base_decl.getAccessSpecifier() != AS_public)\n continue;\n\n \/\/ TODO: Filter out transitive base classes.\n\n CXXRecordDecl *const base_record_decl\n = base_decl.getType()->getAsCXXRecordDecl();\n base_names.push_back(base_record_decl->getQualifiedNameAsString());\n }\n\n return base_names;\n}\n\nstd::vector>\n chimera::Visitor::GetParameterNames(clang::CXXMethodDecl *decl) const\n{\n std::vector> params;\n\n for (ParmVarDecl *param_decl : decl->params())\n {\n const std::string param_name = param_decl->getNameAsString();\n const Type *param_type = param_decl->getType().getTypePtr();\n std::string param_value;\n\n if (param_decl->hasDefaultArg())\n {\n Expr *default_expr = param_decl->getDefaultArg();\n Expr::EvalResult result;\n bool success;\n\n if (param_type->isReferenceType())\n success = default_expr->EvaluateAsLValue(result, *context_);\n else\n success = default_expr->EvaluateAsRValue(result, *context_);\n\n if (success)\n {\n param_value = result.Val.getAsString(\n *context_, param_decl->getType());\n }\n else if (default_expr->hasNonTrivialCall(*context_))\n {\n \/\/ TODO: How do we print the decl with argument + return types?\n std::cerr\n << \"Warning: Unable to evaluate non-trivial call in default\"\n \" value for parameter\"\n << \" '\" << param_name << \"' of method\"\n << \" '\" << decl->getQualifiedNameAsString() << \"'.\\n\";\n }\n else\n {\n \/\/ TODO: How do we print the decl with argument + return types?\n std::cerr\n << \"Warning: Failed to evaluate default value for parameter\"\n << \" '\" << param_name << \"' of method\"\n << \" '\" << decl->getQualifiedNameAsString() << \"'.\\n\";\n }\n }\n\n params.push_back(std::make_pair(param_name, param_value));\n }\n\n return params;\n}\n\nbool chimera::Visitor::IsEnclosed(Decl *decl) const\n{\n \/\/ Filter over the namespaces and only traverse ones that are enclosed\n \/\/ by one of the configuration namespaces.\n for (const auto &it : config_->GetNamespaces())\n {\n if (decl->getDeclContext() && it->Encloses(decl->getDeclContext()))\n {\n return true;\n }\n }\n return false;\n}\nAnother TODO.#include \"chimera\/visitor.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace chimera;\nusing namespace clang;\nusing boost::algorithm::join;\n\nchimera::Visitor::Visitor(clang::CompilerInstance *ci,\n std::unique_ptr cc)\n: context_(&(ci->getASTContext()))\n, config_(std::move(cc))\n{\n \/\/ Do nothing.\n}\n\nbool chimera::Visitor::VisitDecl(Decl *decl)\n{\n if (!decl->isCanonicalDecl())\n return true;\n\n if (!IsEnclosed(decl))\n return true;\n\n if (isa(decl))\n GenerateCXXRecord(cast(decl));\n\n return true;\n}\n\nvoid chimera::Visitor::GenerateCXXRecord(CXXRecordDecl *const decl)\n{\n if (!decl->hasDefinition())\n return;\n\n const YAML::Node &node = config_->GetDeclaration(decl);\n\n std::cout\n << \"::boost::python::class_<\"\n << decl->getQualifiedNameAsString();\n\n const YAML::Node &noncopyable_node = node[\"noncopyable\"];\n if (const bool noncopyable = noncopyable_node && noncopyable_node.as(false))\n std::cout << \", ::boost::python::noncopyable\";\n\n if (const YAML::Node &held_type_node = node[\"held_type\"])\n std::cout << \", \" << held_type_node.as();\n\n std::vector base_names;\n\n if (const YAML::Node &bases_node = node[\"bases\"])\n base_names = bases_node.as >();\n else\n base_names = GetBaseClassNames(decl);\n\n if (!base_names.empty())\n {\n std::cout << \", ::boost::python::bases<\"\n << join(base_names, \", \") << \" >\";\n }\n\n std::cout << \" >\\n\";\n\n for (CXXMethodDecl *method_decl : decl->methods())\n {\n if (isa(method_decl))\n ; \/\/ do nothing\n else if (isa(method_decl))\n ; \/\/ do nothing\n else if (isa(method_decl))\n ; \/\/ TODO: Wrap constructors.\n else if (method_decl->isOverloadedOperator())\n ; \/\/ TODO: Wrap overloaded operators.\n else if (method_decl->isStatic())\n ; \/\/ TODO: Wrap static functions\n else\n GenerateCXXMethod(decl, method_decl);\n }\n}\n\nvoid chimera::Visitor::GenerateCXXMethod(\n CXXRecordDecl *class_decl, CXXMethodDecl *decl)\n{\n decl = decl->getCanonicalDecl();\n\n const QualType pointer_type = context_->getMemberPointerType(\n decl->getType(), class_decl->getTypeForDecl());\n const Type *return_type = decl->getReturnType().getTypePtr();\n\n const YAML::Node &node = config_->GetDeclaration(decl);\n const YAML::Node &rvp_node = node[\"return_value_policy\"];\n\n if (!rvp_node)\n {\n if (return_type->isReferenceType())\n {\n std::cerr\n << \"Warning: Skipped method '\"\n << decl->getQualifiedNameAsString()\n << \"' because it returns a reference and no\"\n \" 'return_value_policy' was specified.\\n\";\n return;\n }\n else if (return_type->isPointerType())\n {\n std::cerr\n << \"Warning: Skipped method '\"\n << decl->getQualifiedNameAsString()\n << \"' because it returns a pointer and no\"\n \" 'return_value_policy' was specified.\\n\";\n return;\n }\n\n \/\/ TODO: Check if return_type is non-copyable.\n }\n\n std::cout\n << \".def(\\\"\" << decl->getNameAsString() << \"\\\"\"\n << \", static_cast<\" << pointer_type.getAsString() << \">(&\"\n << decl->getQualifiedNameAsString() << \")\";\n\n if (rvp_node)\n {\n std::cout << \", boost::python::return_value_policy<\"\n << rvp_node.as() << \" >\";\n }\n\n const auto params = GetParameterNames(decl);\n if (!params.empty())\n {\n \/\/ TODO: Supress any default parameters that occur after the first\n \/\/ non-default to default transition. This can only occur if evaluating\n \/\/ the default value of one or more parameters failed.\n\n \/\/ TODO: Assign names to unnamed arguments.\n\n std::vector python_args;\n for (const auto ¶m : params)\n {\n std::stringstream python_arg;\n python_arg << \"boost::python::arg(\\\"\" << param.first << \"\\\")\";\n\n if (!param.second.empty())\n python_arg << \" = \" << param.second;\n\n python_args.push_back(python_arg.str());\n }\n\n std::cout << \", (\" << join(python_args, \", \") << \")\";\n }\n\n std::cout << \")\\n\";\n}\n\nstd::vector chimera::Visitor::GetBaseClassNames(\n CXXRecordDecl *decl) const\n{\n std::vector base_names;\n\n for (CXXBaseSpecifier &base_decl : decl->bases())\n {\n if (base_decl.getAccessSpecifier() != AS_public)\n continue;\n\n \/\/ TODO: Filter out transitive base classes.\n\n CXXRecordDecl *const base_record_decl\n = base_decl.getType()->getAsCXXRecordDecl();\n base_names.push_back(base_record_decl->getQualifiedNameAsString());\n }\n\n return base_names;\n}\n\nstd::vector>\n chimera::Visitor::GetParameterNames(clang::CXXMethodDecl *decl) const\n{\n std::vector> params;\n\n for (ParmVarDecl *param_decl : decl->params())\n {\n const std::string param_name = param_decl->getNameAsString();\n const Type *param_type = param_decl->getType().getTypePtr();\n std::string param_value;\n\n if (param_decl->hasDefaultArg())\n {\n Expr *default_expr = param_decl->getDefaultArg();\n Expr::EvalResult result;\n bool success;\n\n if (param_type->isReferenceType())\n success = default_expr->EvaluateAsLValue(result, *context_);\n else\n success = default_expr->EvaluateAsRValue(result, *context_);\n\n if (success)\n {\n param_value = result.Val.getAsString(\n *context_, param_decl->getType());\n }\n else if (default_expr->hasNonTrivialCall(*context_))\n {\n \/\/ TODO: How do we print the decl with argument + return types?\n std::cerr\n << \"Warning: Unable to evaluate non-trivial call in default\"\n \" value for parameter\"\n << \" '\" << param_name << \"' of method\"\n << \" '\" << decl->getQualifiedNameAsString() << \"'.\\n\";\n }\n else\n {\n \/\/ TODO: How do we print the decl with argument + return types?\n std::cerr\n << \"Warning: Failed to evaluate default value for parameter\"\n << \" '\" << param_name << \"' of method\"\n << \" '\" << decl->getQualifiedNameAsString() << \"'.\\n\";\n }\n }\n\n params.push_back(std::make_pair(param_name, param_value));\n }\n\n return params;\n}\n\nbool chimera::Visitor::IsEnclosed(Decl *decl) const\n{\n \/\/ Filter over the namespaces and only traverse ones that are enclosed\n \/\/ by one of the configuration namespaces.\n for (const auto &it : config_->GetNamespaces())\n {\n if (decl->getDeclContext() && it->Encloses(decl->getDeclContext()))\n {\n return true;\n }\n }\n return false;\n}\n<|endoftext|>"} {"text":"#include \"EntityManager.h\"\n#include \"Kernel.h\"\n#include \"StateManager.h\"\n\nEntityManager::EntityManager(GameStateManager *gsm) : mStateManager(gsm) {\n ASSERT(gsm != NULL);\n entityNumber = EID_MIN;\n entityCount = 0;\n}\n\nvoid EntityManager::DeleteEntity(EID id) {\n deadEntities.insert(id);\n entityCount -= 1;\n}\n\nunsigned int EntityManager::GetEntityCount() { return entityCount; }\n\nvoid EntityManager::DispatchEvent(const Event *event) {\n for (auto i = componentsRegistered.begin(); i != componentsRegistered.end();\n i++) {\n i->second->HandleEvent(event);\n }\n}\n\nvoid EntityManager::BroadcastEvent(const Event *event) {\n \/\/ Send to state\n mStateManager->HandleEvent(event);\n for (auto i = componentsRegistered.begin(); i != componentsRegistered.end();\n i++) {\n i->second->BroadcastEvent(event);\n }\n}\n\nvoid EntityManager::Cleanup() {\n if (deadEntities.empty()) {\n return;\n }\n\n for (auto i = deadEntities.begin(); i != deadEntities.end(); i++) {\n EID id = *i;\n\n \/\/ Let all entities know that this entity is about to be deleted\n Event event(id, EID_ALLOBJS, Event::MSG::ENTITY_DELETED, \"[DELETED]\");\n BroadcastEvent(&event);\n\n for (auto i = componentsRegistered.begin(); i != componentsRegistered.end();\n i++) {\n i->second->DeleteComponent(id);\n }\n\n if (EIDToName.find(id) != EIDToName.end()) {\n std::string entityName = EIDToName[id];\n EIDToName.erase(id);\n nameToEID.erase(entityName);\n }\n\n reclaimedEIDs.push_back(id);\n }\n\n deadEntities.clear();\n}\n\nvoid EntityManager::RegisterComponentManager(BaseComponentManager *manager,\n int order) {\n if (componentsRegistered.find(order) != componentsRegistered.end()) {\n std::stringstream ss;\n ss << \"Couldn't register component with order: '\" << order\n << \"' order id already taken.\";\n throw Exception(ss.str());\n }\n\n \/\/ Assert that this order not already taken\n ASSERT(componentsRegistered.find(order) == componentsRegistered.end());\n\n componentsRegistered[order] = manager;\n}\n\nEID EntityManager::NewEntity(const std::string &entityName) {\n EID newEntityID = 0;\n\n \/\/ First check if there are any reclaimed eids to use\n if (!reclaimedEIDs.empty()) {\n newEntityID = reclaimedEIDs.back();\n reclaimedEIDs.pop_back();\n }\n \/\/ If there are no old eids to use, make a new one\n else {\n entityNumber++;\n newEntityID = entityNumber;\n }\n\n MapNameToEID(newEntityID, entityName);\n \/\/ Increment number of living entities\n entityCount++;\n\n return newEntityID;\n}\n\nvoid EntityManager::MapNameToEID(EID eid, const std::string &entityName) {\n if (entityName != \"\") {\n \/\/ Stop if in debug mode, this shouldn't happen\n ASSERT(nameToEID.find(entityName) == nameToEID.end());\n \/\/ Defensive programming if not in debug mode\n if (nameToEID.find(entityName) == nameToEID.end()) {\n nameToEID[entityName] = eid;\n EIDToName[eid] = entityName;\n }\n }\n}\n\nvoid EntityManager::ClearAllEntities() {\n for (EID i = EID_MIN; i < entityNumber; i++) {\n DeleteEntity(i);\n }\n}\n\nvoid EntityManager::ClearAllReservedEntities() {\n for (EID i = 0; i < EID_MIN; i++) {\n DeleteEntity(i);\n }\n}\n\nvoid EntityManager::ClearNameMappings() {\n nameToEID.clear();\n EIDToName.clear();\n}\n\nEID EntityManager::GetEIDFromName(const std::string &name) const {\n std::map::const_iterator i = nameToEID.find(name);\n if (i == nameToEID.end()) {\n return 0;\n }\n\n return i->second;\n}\n\nvoid EntityManager::SetParent(EID child, EID parent) {\n for (auto i = componentsRegistered.begin(); i != componentsRegistered.end();\n i++) {\n i->second->SetParent(child, parent);\n }\n}\n\nvoid EntityManager::ActivateAllEntities() {}\n\nvoid EntityManager::ActivateAllEntitiesExcept(std::vector entities) {}\n\nvoid EntityManager::DeactivateAllEntitiesExcept(std::vector entities) {}\n\nvoid EntityManager::DeactivateAllEntities() {}\n\nvoid EntityManager::Activate(std::vector entities) {\n for (auto i = entities.begin(); i != entities.end(); i++) {\n for (auto comp = componentsRegistered.begin();\n comp != componentsRegistered.end(); comp++) {\n comp->second->ActivateComponent(*i);\n }\n }\n}\n\nvoid EntityManager::Deactivate(std::vector entities) {\n for (auto i = entities.begin(); i != entities.end(); i++) {\n for (auto comp = componentsRegistered.begin();\n comp != componentsRegistered.end(); comp++) {\n comp->second->DeactivateComponent(*i);\n }\n }\n}\nFixed EntityManager not deleting final entity#include \"EntityManager.h\"\n#include \"Kernel.h\"\n#include \"StateManager.h\"\n\nEntityManager::EntityManager(GameStateManager *gsm) : mStateManager(gsm) {\n ASSERT(gsm != NULL);\n entityNumber = EID_MIN;\n entityCount = 0;\n}\n\nvoid EntityManager::DeleteEntity(EID id) {\n deadEntities.insert(id);\n entityCount -= 1;\n}\n\nunsigned int EntityManager::GetEntityCount() { return entityCount; }\n\nvoid EntityManager::DispatchEvent(const Event *event) {\n for (auto i = componentsRegistered.begin(); i != componentsRegistered.end();\n i++) {\n i->second->HandleEvent(event);\n }\n}\n\nvoid EntityManager::BroadcastEvent(const Event *event) {\n \/\/ Send to state\n mStateManager->HandleEvent(event);\n for (auto i = componentsRegistered.begin(); i != componentsRegistered.end();\n i++) {\n i->second->BroadcastEvent(event);\n }\n}\n\nvoid EntityManager::Cleanup() {\n if (deadEntities.empty()) {\n return;\n }\n\n for (auto i = deadEntities.begin(); i != deadEntities.end(); i++) {\n EID id = *i;\n\n \/\/ Let all entities know that this entity is about to be deleted\n Event event(id, EID_ALLOBJS, Event::MSG::ENTITY_DELETED, \"[DELETED]\");\n BroadcastEvent(&event);\n\n for (auto i = componentsRegistered.begin(); i != componentsRegistered.end();\n i++) {\n i->second->DeleteComponent(id);\n }\n\n if (EIDToName.find(id) != EIDToName.end()) {\n std::string entityName = EIDToName[id];\n EIDToName.erase(id);\n nameToEID.erase(entityName);\n }\n\n reclaimedEIDs.push_back(id);\n }\n\n deadEntities.clear();\n}\n\nvoid EntityManager::RegisterComponentManager(BaseComponentManager *manager,\n int order) {\n if (componentsRegistered.find(order) != componentsRegistered.end()) {\n std::stringstream ss;\n ss << \"Couldn't register component with order: '\" << order\n << \"' order id already taken.\";\n throw Exception(ss.str());\n }\n\n \/\/ Assert that this order not already taken\n ASSERT(componentsRegistered.find(order) == componentsRegistered.end());\n\n componentsRegistered[order] = manager;\n}\n\nEID EntityManager::NewEntity(const std::string &entityName) {\n EID newEntityID = 0;\n\n \/\/ First check if there are any reclaimed eids to use\n if (!reclaimedEIDs.empty()) {\n newEntityID = reclaimedEIDs.back();\n reclaimedEIDs.pop_back();\n }\n \/\/ If there are no old eids to use, make a new one\n else {\n entityNumber++;\n newEntityID = entityNumber;\n }\n\n MapNameToEID(newEntityID, entityName);\n \/\/ Increment number of living entities\n entityCount++;\n\n return newEntityID;\n}\n\nvoid EntityManager::MapNameToEID(EID eid, const std::string &entityName) {\n if (entityName != \"\") {\n \/\/ Stop if in debug mode, this shouldn't happen\n ASSERT(nameToEID.find(entityName) == nameToEID.end());\n \/\/ Defensive programming if not in debug mode\n if (nameToEID.find(entityName) == nameToEID.end()) {\n nameToEID[entityName] = eid;\n EIDToName[eid] = entityName;\n }\n }\n}\n\nvoid EntityManager::ClearAllEntities() {\n\t\/\/inclusive, entityNumber is the highest eid in use\n for (EID i = EID_MIN; i <= entityNumber; i++) {\n DeleteEntity(i);\n }\n}\n\nvoid EntityManager::ClearAllReservedEntities() {\n for (EID i = 0; i < EID_MIN; i++) {\n DeleteEntity(i);\n }\n}\n\nvoid EntityManager::ClearNameMappings() {\n nameToEID.clear();\n EIDToName.clear();\n}\n\nEID EntityManager::GetEIDFromName(const std::string &name) const {\n std::map::const_iterator i = nameToEID.find(name);\n if (i == nameToEID.end()) {\n return 0;\n }\n\n return i->second;\n}\n\nvoid EntityManager::SetParent(EID child, EID parent) {\n for (auto i = componentsRegistered.begin(); i != componentsRegistered.end();\n i++) {\n i->second->SetParent(child, parent);\n }\n}\n\nvoid EntityManager::ActivateAllEntities() {}\n\nvoid EntityManager::ActivateAllEntitiesExcept(std::vector entities) {}\n\nvoid EntityManager::DeactivateAllEntitiesExcept(std::vector entities) {}\n\nvoid EntityManager::DeactivateAllEntities() {}\n\nvoid EntityManager::Activate(std::vector entities) {\n for (auto i = entities.begin(); i != entities.end(); i++) {\n for (auto comp = componentsRegistered.begin();\n comp != componentsRegistered.end(); comp++) {\n comp->second->ActivateComponent(*i);\n }\n }\n}\n\nvoid EntityManager::Deactivate(std::vector entities) {\n for (auto i = entities.begin(); i != entities.end(); i++) {\n for (auto comp = componentsRegistered.begin();\n comp != componentsRegistered.end(); comp++) {\n comp->second->DeactivateComponent(*i);\n }\n }\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Library\n Module: vlDSRead.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nThis file is part of the Visualization Library. No part of this file\nor its contents may be copied, reproduced or altered in any way\nwithout the express written consent of the authors.\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 \n\n=========================================================================*\/\n#include \"vlDSRead.hh\"\n#include \"vlPolyR.hh\"\n#include \"vlSPtsR.hh\"\n#include \"vlSGridR.hh\"\n#include \"vlUGridR.hh\"\n\n\nvlDataSetReader::vlDataSetReader()\n{\n}\n\nvlDataSetReader::~vlDataSetReader()\n{\n}\n\n\/\/ Description:\n\/\/ Specify file name of vl data file to read.\nvoid vlDataSetReader::SetFilename(char *name) \n{\n this->Reader.SetFilename(name);\n}\nchar *vlDataSetReader::GetFilename() \n{\n return this->Reader.GetFilename();\n}\n\n\/\/ Description:\n\/\/ Get the type of file (ASCII or BINARY)\nint vlDataSetReader::GetFileType() \n{\n return this->Reader.GetFileType();\n}\n\n\/\/ Description:\n\/\/ Set the name of the scalar data to extract. If not specified, first \n\/\/ scalar data encountered is extracted.\nvoid vlDataSetReader::SetScalarsName(char *name) \n{\n this->Reader.SetScalarsName(name);\n}\nchar *vlDataSetReader::GetScalarsName() \n{\n return this->Reader.GetScalarsName();\n}\n\n\/\/ Description:\n\/\/ Set the name of the vector data to extract. If not specified, first \n\/\/ vector data encountered is extracted.\nvoid vlDataSetReader::SetVectorsName(char *name) \n{\n this->Reader.SetVectorsName(name);\n}\nchar *vlDataSetReader::GetVectorsName() \n{\n return this->Reader.GetVectorsName();\n}\n\n\/\/ Description:\n\/\/ Set the name of the tensor data to extract. If not specified, first \n\/\/ tensor data encountered is extracted.\nvoid vlDataSetReader::SetTensorsName(char *name) \n{\n this->Reader.SetTensorsName(name);\n}\nchar *vlDataSetReader::GetTensorsName() \n{\n return this->Reader.GetTensorsName();\n}\n\n\/\/ Description:\n\/\/ Set the name of the normal data to extract. If not specified, first \n\/\/ normal data encountered is extracted.\nvoid vlDataSetReader::SetNormalsName(char *name) \n{\n this->Reader.SetNormalsName(name);\n}\nchar *vlDataSetReader::GetNormalsName() \n{\n return this->Reader.GetNormalsName();\n}\n\n\/\/ Description:\n\/\/ Set the name of the texture coordinate data to extract. If not specified,\n\/\/ first texture coordinate data encountered is extracted.\nvoid vlDataSetReader::SetTCoordsName(char *name) \n{\n this->Reader.SetTCoordsName(name);\n}\nchar *vlDataSetReader::GetTCoordsName() \n{\n return this->Reader.GetTCoordsName();\n}\n\n\/\/ Description:\n\/\/ Set the name of the lookup table data to extract. If not specified, uses \n\/\/ lookup table named by scalar. Otherwise, this specification supersedes.\nvoid vlDataSetReader::SetLookupTableName(char *name) \n{\n this->Reader.SetLookupTableName(name);\n}\nchar *vlDataSetReader::GetLookupTableName() \n{\n return this->Reader.GetLookupTableName();\n}\n\n\nvoid vlDataSetReader::Execute()\n{\n FILE *fp;\n int retStat;\n char line[257];\n vlDataSet *reader;\n\n vlDebugMacro(<<\"Reading vl dataset...\");\n this->Initialize();\n if ( this->Debug ) this->Reader.DebugOn();\n else this->Reader.DebugOff();\n\n if ( !(fp=this->Reader.OpenVLFile()) || !this->Reader.ReadHeader(fp) )\n return;\n\/\/\n\/\/ Determine dataset type\n\/\/\n if ( (retStat=fscanf(fp,\"%256s\",line)) == EOF || retStat < 1 ) \n {\n vlErrorMacro(<< \"Premature EOF reading dataset keyword\");\n return;\n }\n\n if ( !strncmp(this->Reader.LowerCase(line),\"dataset\",(unsigned long)7) )\n {\n\/\/\n\/\/ See if type is recognized.\n\/\/\n if ( (retStat=fscanf(fp,\"%256s\",line)) == EOF || retStat < 1 ) \n {\n vlErrorMacro(<< \"Premature EOF reading type\");\n return;\n }\n\n rewind(fp);\n if ( ! strncmp(this->Reader.LowerCase(line),\"polydata\",8) )\n {\n vlPolyReader *preader = new vlPolyReader;\n preader->SetFilename(this->Reader.GetFilename());\n preader->SetScalarsName(this->Reader.GetScalarsName());\n preader->SetVectorsName(this->Reader.GetVectorsName());\n preader->SetNormalsName(this->Reader.GetNormalsName());\n preader->SetTensorsName(this->Reader.GetTensorsName());\n preader->SetTCoordsName(this->Reader.GetTCoordsName());\n preader->SetLookupTableName(this->Reader.GetLookupTableName());\n preader->Update();\n reader = (vlDataSet *)preader;\n }\n\n else if ( ! strncmp(line,\"structured_points\",17) )\n {\n vlStructuredPointsReader *preader = new vlStructuredPointsReader;\n preader->SetFilename(this->Reader.GetFilename());\n preader->SetScalarsName(this->Reader.GetScalarsName());\n preader->SetVectorsName(this->Reader.GetVectorsName());\n preader->SetNormalsName(this->Reader.GetNormalsName());\n preader->SetTensorsName(this->Reader.GetTensorsName());\n preader->SetTCoordsName(this->Reader.GetTCoordsName());\n preader->SetLookupTableName(this->Reader.GetLookupTableName());\n preader->Update();\n reader = (vlDataSet *)preader;\n }\n\n else if ( ! strncmp(line,\"structured_grid\",15) )\n {\n vlStructuredGridReader *preader = new vlStructuredGridReader;\n preader->SetFilename(this->Reader.GetFilename());\n preader->SetScalarsName(this->Reader.GetScalarsName());\n preader->SetVectorsName(this->Reader.GetVectorsName());\n preader->SetNormalsName(this->Reader.GetNormalsName());\n preader->SetTensorsName(this->Reader.GetTensorsName());\n preader->SetTCoordsName(this->Reader.GetTCoordsName());\n preader->SetLookupTableName(this->Reader.GetLookupTableName());\n preader->Update();\n reader = (vlDataSet *)preader;\n }\n\n else if ( ! strncmp(line,\"unstructured_grid\",17) )\n {\n vlUnstructuredGridReader *preader = new vlUnstructuredGridReader;\n preader->SetFilename(this->Reader.GetFilename());\n preader->SetScalarsName(this->Reader.GetScalarsName());\n preader->SetVectorsName(this->Reader.GetVectorsName());\n preader->SetNormalsName(this->Reader.GetNormalsName());\n preader->SetTensorsName(this->Reader.GetTensorsName());\n preader->SetTCoordsName(this->Reader.GetTCoordsName());\n preader->SetLookupTableName(this->Reader.GetLookupTableName());\n preader->Update();\n reader = (vlDataSet *)preader;\n }\n\n else\n {\n vlErrorMacro(<< \"Cannot read dataset type: \" << line);\n return;\n }\n }\n\/\/\n\/\/ Create appropriate dataset\n\/\/\n if ( this->DataSet ) delete this->DataSet;\n this->DataSet = reader;\n return;\n}\n\nvoid vlDataSetReader::PrintSelf(ostream& os, vlIndent indent)\n{\n vlDataSetSource::PrintSelf(os,indent);\n this->Reader.PrintSelf(os,indent);\n}\nERR: Assign point data appropriately.\/*=========================================================================\n\n Program: Visualization Library\n Module: vlDSRead.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nThis file is part of the Visualization Library. No part of this file\nor its contents may be copied, reproduced or altered in any way\nwithout the express written consent of the authors.\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 \n\n=========================================================================*\/\n#include \"vlDSRead.hh\"\n#include \"vlPolyR.hh\"\n#include \"vlSPtsR.hh\"\n#include \"vlSGridR.hh\"\n#include \"vlUGridR.hh\"\n\n\nvlDataSetReader::vlDataSetReader()\n{\n}\n\nvlDataSetReader::~vlDataSetReader()\n{\n}\n\n\/\/ Description:\n\/\/ Specify file name of vl data file to read.\nvoid vlDataSetReader::SetFilename(char *name) \n{\n this->Reader.SetFilename(name);\n}\nchar *vlDataSetReader::GetFilename() \n{\n return this->Reader.GetFilename();\n}\n\n\/\/ Description:\n\/\/ Get the type of file (ASCII or BINARY)\nint vlDataSetReader::GetFileType() \n{\n return this->Reader.GetFileType();\n}\n\n\/\/ Description:\n\/\/ Set the name of the scalar data to extract. If not specified, first \n\/\/ scalar data encountered is extracted.\nvoid vlDataSetReader::SetScalarsName(char *name) \n{\n this->Reader.SetScalarsName(name);\n}\nchar *vlDataSetReader::GetScalarsName() \n{\n return this->Reader.GetScalarsName();\n}\n\n\/\/ Description:\n\/\/ Set the name of the vector data to extract. If not specified, first \n\/\/ vector data encountered is extracted.\nvoid vlDataSetReader::SetVectorsName(char *name) \n{\n this->Reader.SetVectorsName(name);\n}\nchar *vlDataSetReader::GetVectorsName() \n{\n return this->Reader.GetVectorsName();\n}\n\n\/\/ Description:\n\/\/ Set the name of the tensor data to extract. If not specified, first \n\/\/ tensor data encountered is extracted.\nvoid vlDataSetReader::SetTensorsName(char *name) \n{\n this->Reader.SetTensorsName(name);\n}\nchar *vlDataSetReader::GetTensorsName() \n{\n return this->Reader.GetTensorsName();\n}\n\n\/\/ Description:\n\/\/ Set the name of the normal data to extract. If not specified, first \n\/\/ normal data encountered is extracted.\nvoid vlDataSetReader::SetNormalsName(char *name) \n{\n this->Reader.SetNormalsName(name);\n}\nchar *vlDataSetReader::GetNormalsName() \n{\n return this->Reader.GetNormalsName();\n}\n\n\/\/ Description:\n\/\/ Set the name of the texture coordinate data to extract. If not specified,\n\/\/ first texture coordinate data encountered is extracted.\nvoid vlDataSetReader::SetTCoordsName(char *name) \n{\n this->Reader.SetTCoordsName(name);\n}\nchar *vlDataSetReader::GetTCoordsName() \n{\n return this->Reader.GetTCoordsName();\n}\n\n\/\/ Description:\n\/\/ Set the name of the lookup table data to extract. If not specified, uses \n\/\/ lookup table named by scalar. Otherwise, this specification supersedes.\nvoid vlDataSetReader::SetLookupTableName(char *name) \n{\n this->Reader.SetLookupTableName(name);\n}\nchar *vlDataSetReader::GetLookupTableName() \n{\n return this->Reader.GetLookupTableName();\n}\n\n\nvoid vlDataSetReader::Execute()\n{\n FILE *fp;\n int retStat;\n char line[257];\n vlDataSet *reader;\n\n vlDebugMacro(<<\"Reading vl dataset...\");\n this->Initialize();\n if ( this->Debug ) this->Reader.DebugOn();\n else this->Reader.DebugOff();\n\n if ( !(fp=this->Reader.OpenVLFile()) || !this->Reader.ReadHeader(fp) )\n return;\n\/\/\n\/\/ Determine dataset type\n\/\/\n if ( (retStat=fscanf(fp,\"%256s\",line)) == EOF || retStat < 1 ) \n {\n vlErrorMacro(<< \"Premature EOF reading dataset keyword\");\n return;\n }\n\n if ( !strncmp(this->Reader.LowerCase(line),\"dataset\",(unsigned long)7) )\n {\n\/\/\n\/\/ See if type is recognized.\n\/\/\n if ( (retStat=fscanf(fp,\"%256s\",line)) == EOF || retStat < 1 ) \n {\n vlErrorMacro(<< \"Premature EOF reading type\");\n return;\n }\n\n rewind(fp);\n if ( ! strncmp(this->Reader.LowerCase(line),\"polydata\",8) )\n {\n vlPolyReader *preader = new vlPolyReader;\n preader->SetFilename(this->Reader.GetFilename());\n preader->SetScalarsName(this->Reader.GetScalarsName());\n preader->SetVectorsName(this->Reader.GetVectorsName());\n preader->SetNormalsName(this->Reader.GetNormalsName());\n preader->SetTensorsName(this->Reader.GetTensorsName());\n preader->SetTCoordsName(this->Reader.GetTCoordsName());\n preader->SetLookupTableName(this->Reader.GetLookupTableName());\n preader->Update();\n reader = (vlDataSet *)preader;\n }\n\n else if ( ! strncmp(line,\"structured_points\",17) )\n {\n vlStructuredPointsReader *preader = new vlStructuredPointsReader;\n preader->SetFilename(this->Reader.GetFilename());\n preader->SetScalarsName(this->Reader.GetScalarsName());\n preader->SetVectorsName(this->Reader.GetVectorsName());\n preader->SetNormalsName(this->Reader.GetNormalsName());\n preader->SetTensorsName(this->Reader.GetTensorsName());\n preader->SetTCoordsName(this->Reader.GetTCoordsName());\n preader->SetLookupTableName(this->Reader.GetLookupTableName());\n preader->Update();\n reader = (vlDataSet *)preader;\n }\n\n else if ( ! strncmp(line,\"structured_grid\",15) )\n {\n vlStructuredGridReader *preader = new vlStructuredGridReader;\n preader->SetFilename(this->Reader.GetFilename());\n preader->SetScalarsName(this->Reader.GetScalarsName());\n preader->SetVectorsName(this->Reader.GetVectorsName());\n preader->SetNormalsName(this->Reader.GetNormalsName());\n preader->SetTensorsName(this->Reader.GetTensorsName());\n preader->SetTCoordsName(this->Reader.GetTCoordsName());\n preader->SetLookupTableName(this->Reader.GetLookupTableName());\n preader->Update();\n reader = (vlDataSet *)preader;\n }\n\n else if ( ! strncmp(line,\"unstructured_grid\",17) )\n {\n vlUnstructuredGridReader *preader = new vlUnstructuredGridReader;\n preader->SetFilename(this->Reader.GetFilename());\n preader->SetScalarsName(this->Reader.GetScalarsName());\n preader->SetVectorsName(this->Reader.GetVectorsName());\n preader->SetNormalsName(this->Reader.GetNormalsName());\n preader->SetTensorsName(this->Reader.GetTensorsName());\n preader->SetTCoordsName(this->Reader.GetTCoordsName());\n preader->SetLookupTableName(this->Reader.GetLookupTableName());\n preader->Update();\n reader = (vlDataSet *)preader;\n }\n\n else\n {\n vlErrorMacro(<< \"Cannot read dataset type: \" << line);\n return;\n }\n }\n\/\/\n\/\/ Create appropriate dataset\n\/\/\n if ( this->DataSet ) delete this->DataSet;\n this->DataSet = reader;\n *(this->DataSet->GetPointData()) = *(reader->GetPointData());\n\n return;\n}\n\nvoid vlDataSetReader::PrintSelf(ostream& os, vlIndent indent)\n{\n vlDataSetSource::PrintSelf(os,indent);\n this->Reader.PrintSelf(os,indent);\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkLight.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 \n#include \n#include \"vtkLight.hh\"\n#include \"vtkRenderer.hh\"\n#include \"vtkRenderWindow.hh\"\n#include \"vtkLightDevice.hh\"\n\n\/\/ Description:\n\/\/ Create a light with focal point at origin and position=(0,0,1).\n\/\/ Light color is white, intensity=1, and the light is turned on.\nvtkLight::vtkLight()\n{\n this->FocalPoint[0] = 0.0;\n this->FocalPoint[1] = 0.0;\n this->FocalPoint[2] = 0.0;\n\n this->Position[0] = 0.0;\n this->Position[1] = 0.0;\n this->Position[2] = 1.0;\n\n this->Color[0] = 1.0;\n this->Color[1] = 1.0;\n this->Color[2] = 1.0;\n\n this->Switch = 1;\n\n this->Intensity = 1.0;\n this->Positional = 0;\n this->ConeAngle= 30;\n this->AttenuationValues[0] = 1;\n this->AttenuationValues[1] = 0;\n this->AttenuationValues[2] = 0;\n this->Exponent = 1;\n this->Device = NULL;\n}\n\nvtkLight::~vtkLight()\n{\n if (this->Device)\n {\n this->Device->Delete();\n }\n}\n\nvoid vtkLight::Render(vtkRenderer *ren,int light_index)\n{\n if (!this->Device)\n {\n this->Device = ren->GetRenderWindow()->MakeLight();\n }\n this->Device->Render(this,ren,light_index);\n}\n\nvoid vtkLight::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkObject::PrintSelf(os,indent);\n\n os << indent << \"AttenuationValues: (\" << this->AttenuationValues[0] << \", \" \n << this->AttenuationValues[1] << \", \" << this->AttenuationValues[2] << \")\\n\";\n os << indent << \"Color: (\" << this->Color[0] << \", \" \n << this->Color[1] << \", \" << this->Color[2] << \")\\n\";\n os << indent << \"Cone Angle: \" << this->ConeAngle << \"\\n\";\n if ( this->Device )\n {\n os << indent << \"Device:\\n\";\n this->Device->PrintSelf(os,indent.GetNextIndent());\n }\n else\n {\n os << indent << \"Device: (none)\\n\";\n }\n os << indent << \"Exponent: \" << this->Exponent << \"\\n\";\n os << indent << \"Focal Point: (\" << this->FocalPoint[0] << \", \" \n << this->FocalPoint[1] << \", \" << this->FocalPoint[2] << \")\\n\";\n os << indent << \"Intensity: \" << this->Intensity << \"\\n\";\n os << indent << \"Position: (\" << this->Position[0] << \", \" \n << this->Position[1] << \", \" << this->Position[2] << \")\\n\";\n os << indent << \"Positional: \" << (this->Positional ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Switch: \" << (this->Switch ? \"On\\n\" : \"Off\\n\");\n}\n\n\n\n\nupdated comments\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkLight.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 \n#include \n#include \"vtkLight.hh\"\n#include \"vtkRenderer.hh\"\n#include \"vtkRenderWindow.hh\"\n#include \"vtkLightDevice.hh\"\n\n\/\/ Description:\n\/\/ Create a light with the focal point at the origin and its position\n\/\/ set to (0,0,1). The lights color is white, intensity=1, and the light \n\/\/ is turned on. \nvtkLight::vtkLight()\n{\n this->FocalPoint[0] = 0.0;\n this->FocalPoint[1] = 0.0;\n this->FocalPoint[2] = 0.0;\n\n this->Position[0] = 0.0;\n this->Position[1] = 0.0;\n this->Position[2] = 1.0;\n\n this->Color[0] = 1.0;\n this->Color[1] = 1.0;\n this->Color[2] = 1.0;\n\n this->Switch = 1;\n\n this->Intensity = 1.0;\n this->Positional = 0;\n this->ConeAngle= 30;\n this->AttenuationValues[0] = 1;\n this->AttenuationValues[1] = 0;\n this->AttenuationValues[2] = 0;\n this->Exponent = 1;\n this->Device = NULL;\n}\n\nvtkLight::~vtkLight()\n{\n if (this->Device)\n {\n this->Device->Delete();\n }\n}\n\nvoid vtkLight::Render(vtkRenderer *ren,int light_index)\n{\n if (!this->Device)\n {\n this->Device = ren->GetRenderWindow()->MakeLight();\n }\n this->Device->Render(this,ren,light_index);\n}\n\nvoid vtkLight::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkObject::PrintSelf(os,indent);\n\n os << indent << \"AttenuationValues: (\" << this->AttenuationValues[0] << \", \" \n << this->AttenuationValues[1] << \", \" << this->AttenuationValues[2] << \")\\n\";\n os << indent << \"Color: (\" << this->Color[0] << \", \" \n << this->Color[1] << \", \" << this->Color[2] << \")\\n\";\n os << indent << \"Cone Angle: \" << this->ConeAngle << \"\\n\";\n if ( this->Device )\n {\n os << indent << \"Device:\\n\";\n this->Device->PrintSelf(os,indent.GetNextIndent());\n }\n else\n {\n os << indent << \"Device: (none)\\n\";\n }\n os << indent << \"Exponent: \" << this->Exponent << \"\\n\";\n os << indent << \"Focal Point: (\" << this->FocalPoint[0] << \", \" \n << this->FocalPoint[1] << \", \" << this->FocalPoint[2] << \")\\n\";\n os << indent << \"Intensity: \" << this->Intensity << \"\\n\";\n os << indent << \"Position: (\" << this->Position[0] << \", \" \n << this->Position[1] << \", \" << this->Position[2] << \")\\n\";\n os << indent << \"Positional: \" << (this->Positional ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Switch: \" << (this->Switch ? \"On\\n\" : \"Off\\n\");\n}\n\n\n\n\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkPixel.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 \"vtkPixel.hh\"\n#include \"vtkQuad.hh\"\n#include \"vtkPolygon.hh\"\n#include \"vtkPlane.hh\"\n#include \"vtkMath.hh\"\n#include \"vtkCellArray.hh\"\n#include \"vtkLine.hh\"\n\nstatic vtkMath math;\nstatic vtkPlane plane;\nstatic vtkPolygon poly;\n\n\/\/ Description:\n\/\/ Deep copy of cell.\nvtkPixel::vtkPixel(const vtkPixel& p)\n{\n this->Points = p.Points;\n this->PointIds = p.PointIds;\n}\n\nint vtkPixel::EvaluatePosition(float x[3], float closestPoint[3],\n int& subId, float pcoords[3], \n float& dist2, float *weights)\n{\n float *pt1, *pt2, *pt3;\n int i;\n float p[3], p21[3], p31[3];\n float l21, l31, n[3];\n\n subId = 0;\n pcoords[0] = pcoords[1] = pcoords[2] = 0.0;\n\/\/\n\/\/ Get normal for pixel\n\/\/\n pt1 = this->Points.GetPoint(0);\n pt2 = this->Points.GetPoint(1);\n pt3 = this->Points.GetPoint(2);\n\n poly.ComputeNormal (pt1, pt2, pt3, n);\n\/\/\n\/\/ Project point to plane\n\/\/\n plane.ProjectPoint(x,pt1,n,closestPoint);\n\n for (i=0; i<3; i++)\n {\n p21[i] = pt2[i] - pt1[i];\n p31[i] = pt3[i] - pt1[i];\n p[i] = x[i] - pt1[i];\n }\n\n if ( (l21=math.Norm(p21)) == 0.0 ) l21 = 1.0;\n if ( (l31=math.Norm(p31)) == 0.0 ) l31 = 1.0;\n\n pcoords[0] = math.Dot(p21,p) \/ (l21*l21);\n pcoords[1] = math.Dot(p31,p) \/ (l31*l31);\n\n this->InterpolationFunctions(pcoords, weights);\n\n if ( pcoords[0] >= 0.0 && pcoords[1] <= 1.0 &&\n pcoords[1] >= 0.0 && pcoords[1] <= 1.0 )\n {\n dist2 = math.Distance2BetweenPoints(closestPoint,x); \/\/projection distance\n return 1;\n }\n else\n {\n float pc[3], w[4];\n for (i=0; i<2; i++)\n {\n if (pcoords[i] < 0.0) pc[i] = 0.0;\n else if (pcoords[i] > 1.0) pc[i] = 1.0;\n else pc[i] = pcoords[i];\n }\n this->EvaluateLocation(subId, pc, closestPoint, (float *)w);\n dist2 = math.Distance2BetweenPoints(closestPoint,x);\n return 0;\n }\n}\n\nvoid vtkPixel::EvaluateLocation(int& subId, float pcoords[3], float x[3],\n float *weights)\n{\n float *pt1, *pt2, *pt3;\n int i;\n\n pt1 = this->Points.GetPoint(0);\n pt2 = this->Points.GetPoint(1);\n pt3 = this->Points.GetPoint(2);\n\n for (i=0; i<3; i++)\n {\n x[i] = pt1[i] + pcoords[0]*(pt2[i] - pt1[i]) +\n pcoords[1]*(pt3[i] - pt1[i]);\n }\n\n this->InterpolationFunctions(pcoords, weights);\n}\n\nint vtkPixel::CellBoundary(int subId, float pcoords[3], vtkIdList& pts)\n{\n float t1=pcoords[0]-pcoords[1];\n float t2=1.0-pcoords[0]-pcoords[1];\n\n pts.Reset();\n\n \/\/ compare against two lines in parametric space that divide element\n \/\/ into four pieces.\n if ( t1 >= 0.0 && t2 >= 0.0 )\n {\n pts.SetId(0,this->PointIds.GetId(0));\n pts.SetId(1,this->PointIds.GetId(1));\n }\n\n else if ( t1 >= 0.0 && t2 < 0.0 )\n {\n pts.SetId(0,this->PointIds.GetId(1));\n pts.SetId(1,this->PointIds.GetId(3));\n }\n\n else if ( t1 < 0.0 && t2 < 0.0 )\n {\n pts.SetId(0,this->PointIds.GetId(3));\n pts.SetId(1,this->PointIds.GetId(2));\n }\n\n else \/\/( t1 < 0.0 && t2 >= 0.0 )\n {\n pts.SetId(0,this->PointIds.GetId(2));\n pts.SetId(1,this->PointIds.GetId(0));\n }\n\n if ( pcoords[0] < 0.0 || pcoords[0] > 1.0 ||\n pcoords[1] < 0.0 || pcoords[1] > 1.0 )\n return 0;\n else\n return 1;\n}\n\n\/\/\n\/\/ Marching squares\n\/\/\nstatic int edges[4][2] = { {0,1}, {1,3}, {3,2}, {2,0} };\n\ntypedef int EDGE_LIST;\ntypedef struct {\n EDGE_LIST edges[5];\n} LINE_CASES;\n\nstatic LINE_CASES lineCases[] = { \n {{-1, -1, -1, -1, -1}},\n {{0, 3, -1, -1, -1}},\n {{1, 0, -1, -1, -1}},\n {{1, 3, -1, -1, -1}},\n {{2, 1, -1, -1, -1}},\n {{0, 3, 2, 1, -1}},\n {{2, 0, -1, -1, -1}},\n {{2, 3, -1, -1, -1}},\n {{3, 2, -1, -1, -1}},\n {{0, 2, -1, -1, -1}},\n {{1, 0, 3, 2, -1}},\n {{1, 2, -1, -1, -1}},\n {{3, 1, -1, -1, -1}},\n {{0, 1, -1, -1, -1}},\n {{3, 0, -1, -1, -1}},\n {{-1, -1, -1, -1, -1}}\n};\n\nvoid vtkPixel::Contour(float value, vtkFloatScalars *cellScalars,\n vtkFloatPoints *points, vtkCellArray *verts,\n vtkCellArray *lines, vtkCellArray *polys, \n vtkFloatScalars *scalars)\n{\n static int CASE_MASK[4] = {1,2,8,4}; \/\/note difference!\n LINE_CASES *lineCase;\n EDGE_LIST *edge;\n int i, j, index, *vert;\n int pts[2];\n float t, *x1, *x2, x[3];\n\n \/\/ Build the case table\n for ( i=0, index = 0; i < 4; i++)\n if (cellScalars->GetScalar(i) >= value)\n index |= CASE_MASK[i];\n\n lineCase = lineCases + index;\n edge = lineCase->edges;\n\n for ( ; edge[0] > -1; edge += 2 )\n {\n for (i=0; i<2; i++) \/\/ insert line\n {\n vert = edges[edge[i]];\n t = (value - cellScalars->GetScalar(vert[0])) \/\n (cellScalars->GetScalar(vert[1]) - cellScalars->GetScalar(vert[0]));\n x1 = this->Points.GetPoint(vert[0]);\n x2 = this->Points.GetPoint(vert[1]);\n for (j=0; j<3; j++) x[j] = x1[j] + t * (x2[j] - x1[j]);\n pts[i] = points->InsertNextPoint(x);\n scalars->InsertNextScalar(value);\n }\n lines->InsertNextCell(2,pts);\n }\n}\n\nvtkCell *vtkPixel::GetEdge(int edgeId)\n{\n static vtkLine line;\n int *verts;\n\n verts = edges[edgeId];\n\n \/\/ load point id's\n line.PointIds.SetId(0,this->PointIds.GetId(verts[0]));\n line.PointIds.SetId(1,this->PointIds.GetId(verts[1]));\n\n \/\/ load coordinates\n line.Points.SetPoint(0,this->Points.GetPoint(verts[0]));\n line.Points.SetPoint(1,this->Points.GetPoint(verts[1]));\n\n return &line;\n}\n\/\/\n\/\/ Compute interpolation functions (similar but different than Quad interpolation functions)\n\/\/\nvoid vtkPixel::InterpolationFunctions(float pcoords[3], float sf[4])\n{\n float rm, sm;\n\n rm = 1. - pcoords[0];\n sm = 1. - pcoords[1];\n\n sf[0] = rm * sm;\n sf[1] = pcoords[0] * sm;\n sf[2] = rm * pcoords[1];\n sf[3] = pcoords[0] * pcoords[1];\n}\n\n\/\/ \n\/\/ Intersect plane; see whether point is inside.\n\/\/\nint vtkPixel::IntersectWithLine(float p1[3], float p2[3], float tol, float& t,\n float x[3], float pcoords[3], int& subId)\n{\n float *pt1, *pt2, *pt3, *pt4, n[3];\n float tol2 = tol*tol;\n float closestPoint[3];\n float dist2, weights[4];\n int i;\n\n subId = 0;\n pcoords[0] = pcoords[1] = pcoords[2] = 0.0;\n\/\/\n\/\/ Get normal for triangle\n\/\/\n pt1 = this->Points.GetPoint(0);\n pt2 = this->Points.GetPoint(1);\n pt3 = this->Points.GetPoint(2);\n pt4 = this->Points.GetPoint(3);\n\n n[0] = n[1] = n[2] = 0.0;\n for (i=0; i<3; i++)\n {\n if ( (pt4[i] - pt1[i]) <= 0.0 )\n {\n n[i] = 1.0;\n break;\n }\n }\n\/\/\n\/\/ Intersect plane of pixel with line\n\/\/\n if ( ! plane.IntersectWithLine(p1,p2,n,pt1,t,x) ) return 0;\n\/\/\n\/\/ Use evaluate position\n\/\/\n if (this->EvaluatePosition(x, closestPoint, subId, pcoords, dist2, weights) )\n if ( dist2 <= tol2 ) return 1;\n\n return 0;\n}\n\nint vtkPixel::Triangulate(int index, vtkFloatPoints &pts)\n{\n pts.Reset();\n pts.InsertPoint(0,this->Points.GetPoint(0));\n pts.InsertPoint(1,this->Points.GetPoint(1));\n pts.InsertPoint(2,this->Points.GetPoint(2));\n\n pts.InsertPoint(3,this->Points.GetPoint(1));\n pts.InsertPoint(4,this->Points.GetPoint(3));\n pts.InsertPoint(5,this->Points.GetPoint(2));\n\n return 1;\n}\n\nvoid vtkPixel::Derivatives(int subId, float pcoords[3], float *values, \n int dim, float *derivs)\n{\n int i, idx;\n\n \/\/ The following code is incorrect. Will be fixed in future release.\n for (i=0; ichanged some names to avoid name conflicts on Borland C++\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkPixel.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 \"vtkPixel.hh\"\n#include \"vtkQuad.hh\"\n#include \"vtkPolygon.hh\"\n#include \"vtkPlane.hh\"\n#include \"vtkMath.hh\"\n#include \"vtkCellArray.hh\"\n#include \"vtkLine.hh\"\n\nstatic vtkPlane vtkAPlane;\n\n\/\/ Description:\n\/\/ Deep copy of cell.\nvtkPixel::vtkPixel(const vtkPixel& p)\n{\n this->Points = p.Points;\n this->PointIds = p.PointIds;\n}\n\nint vtkPixel::EvaluatePosition(float x[3], float closestPoint[3],\n int& subId, float pcoords[3], \n float& dist2, float *weights)\n{\n float *pt1, *pt2, *pt3;\n int i;\n float p[3], p21[3], p31[3];\n float l21, l31, n[3];\n static vtkPolygon vtkAPoly;\n static vtkMath vtkAMath;\n\n subId = 0;\n pcoords[0] = pcoords[1] = pcoords[2] = 0.0;\n\/\/\n\/\/ Get normal for pixel\n\/\/\n pt1 = this->Points.GetPoint(0);\n pt2 = this->Points.GetPoint(1);\n pt3 = this->Points.GetPoint(2);\n\n vtkAPoly.ComputeNormal (pt1, pt2, pt3, n);\n\/\/\n\/\/ Project point to plane\n\/\/\n vtkAPlane.ProjectPoint(x,pt1,n,closestPoint);\n\n for (i=0; i<3; i++)\n {\n p21[i] = pt2[i] - pt1[i];\n p31[i] = pt3[i] - pt1[i];\n p[i] = x[i] - pt1[i];\n }\n\n if ( (l21=vtkAMath.Norm(p21)) == 0.0 ) l21 = 1.0;\n if ( (l31=vtkAMath.Norm(p31)) == 0.0 ) l31 = 1.0;\n\n pcoords[0] = vtkAMath.Dot(p21,p) \/ (l21*l21);\n pcoords[1] = vtkAMath.Dot(p31,p) \/ (l31*l31);\n\n this->InterpolationFunctions(pcoords, weights);\n\n if ( pcoords[0] >= 0.0 && pcoords[1] <= 1.0 &&\n pcoords[1] >= 0.0 && pcoords[1] <= 1.0 )\n {\n dist2 = vtkAMath.Distance2BetweenPoints(closestPoint,x); \/\/projection distance\n return 1;\n }\n else\n {\n float pc[3], w[4];\n for (i=0; i<2; i++)\n {\n if (pcoords[i] < 0.0) pc[i] = 0.0;\n else if (pcoords[i] > 1.0) pc[i] = 1.0;\n else pc[i] = pcoords[i];\n }\n this->EvaluateLocation(subId, pc, closestPoint, (float *)w);\n dist2 = vtkAMath.Distance2BetweenPoints(closestPoint,x);\n return 0;\n }\n}\n\nvoid vtkPixel::EvaluateLocation(int& subId, float pcoords[3], float x[3],\n float *weights)\n{\n float *pt1, *pt2, *pt3;\n int i;\n\n pt1 = this->Points.GetPoint(0);\n pt2 = this->Points.GetPoint(1);\n pt3 = this->Points.GetPoint(2);\n\n for (i=0; i<3; i++)\n {\n x[i] = pt1[i] + pcoords[0]*(pt2[i] - pt1[i]) +\n pcoords[1]*(pt3[i] - pt1[i]);\n }\n\n this->InterpolationFunctions(pcoords, weights);\n}\n\nint vtkPixel::CellBoundary(int subId, float pcoords[3], vtkIdList& pts)\n{\n float t1=pcoords[0]-pcoords[1];\n float t2=1.0-pcoords[0]-pcoords[1];\n\n pts.Reset();\n\n \/\/ compare against two lines in parametric space that divide element\n \/\/ into four pieces.\n if ( t1 >= 0.0 && t2 >= 0.0 )\n {\n pts.SetId(0,this->PointIds.GetId(0));\n pts.SetId(1,this->PointIds.GetId(1));\n }\n\n else if ( t1 >= 0.0 && t2 < 0.0 )\n {\n pts.SetId(0,this->PointIds.GetId(1));\n pts.SetId(1,this->PointIds.GetId(3));\n }\n\n else if ( t1 < 0.0 && t2 < 0.0 )\n {\n pts.SetId(0,this->PointIds.GetId(3));\n pts.SetId(1,this->PointIds.GetId(2));\n }\n\n else \/\/( t1 < 0.0 && t2 >= 0.0 )\n {\n pts.SetId(0,this->PointIds.GetId(2));\n pts.SetId(1,this->PointIds.GetId(0));\n }\n\n if ( pcoords[0] < 0.0 || pcoords[0] > 1.0 ||\n pcoords[1] < 0.0 || pcoords[1] > 1.0 )\n return 0;\n else\n return 1;\n}\n\n\/\/\n\/\/ Marching squares\n\/\/\nstatic int edges[4][2] = { {0,1}, {1,3}, {3,2}, {2,0} };\n\ntypedef int EDGE_LIST;\ntypedef struct {\n EDGE_LIST edges[5];\n} LINE_CASES;\n\nstatic LINE_CASES lineCases[] = { \n {{-1, -1, -1, -1, -1}},\n {{0, 3, -1, -1, -1}},\n {{1, 0, -1, -1, -1}},\n {{1, 3, -1, -1, -1}},\n {{2, 1, -1, -1, -1}},\n {{0, 3, 2, 1, -1}},\n {{2, 0, -1, -1, -1}},\n {{2, 3, -1, -1, -1}},\n {{3, 2, -1, -1, -1}},\n {{0, 2, -1, -1, -1}},\n {{1, 0, 3, 2, -1}},\n {{1, 2, -1, -1, -1}},\n {{3, 1, -1, -1, -1}},\n {{0, 1, -1, -1, -1}},\n {{3, 0, -1, -1, -1}},\n {{-1, -1, -1, -1, -1}}\n};\n\nvoid vtkPixel::Contour(float value, vtkFloatScalars *cellScalars,\n vtkFloatPoints *points, vtkCellArray *verts,\n vtkCellArray *lines, vtkCellArray *polys, \n vtkFloatScalars *scalars)\n{\n static int CASE_MASK[4] = {1,2,8,4}; \/\/note difference!\n LINE_CASES *lineCase;\n EDGE_LIST *edge;\n int i, j, index, *vert;\n int pts[2];\n float t, *x1, *x2, x[3];\n\n \/\/ Build the case table\n for ( i=0, index = 0; i < 4; i++)\n if (cellScalars->GetScalar(i) >= value)\n index |= CASE_MASK[i];\n\n lineCase = lineCases + index;\n edge = lineCase->edges;\n\n for ( ; edge[0] > -1; edge += 2 )\n {\n for (i=0; i<2; i++) \/\/ insert line\n {\n vert = edges[edge[i]];\n t = (value - cellScalars->GetScalar(vert[0])) \/\n (cellScalars->GetScalar(vert[1]) - cellScalars->GetScalar(vert[0]));\n x1 = this->Points.GetPoint(vert[0]);\n x2 = this->Points.GetPoint(vert[1]);\n for (j=0; j<3; j++) x[j] = x1[j] + t * (x2[j] - x1[j]);\n pts[i] = points->InsertNextPoint(x);\n scalars->InsertNextScalar(value);\n }\n lines->InsertNextCell(2,pts);\n }\n}\n\nvtkCell *vtkPixel::GetEdge(int edgeId)\n{\n static vtkLine line;\n int *verts;\n\n verts = edges[edgeId];\n\n \/\/ load point id's\n line.PointIds.SetId(0,this->PointIds.GetId(verts[0]));\n line.PointIds.SetId(1,this->PointIds.GetId(verts[1]));\n\n \/\/ load coordinates\n line.Points.SetPoint(0,this->Points.GetPoint(verts[0]));\n line.Points.SetPoint(1,this->Points.GetPoint(verts[1]));\n\n return &line;\n}\n\/\/\n\/\/ Compute interpolation functions (similar but different than Quad interpolation functions)\n\/\/\nvoid vtkPixel::InterpolationFunctions(float pcoords[3], float sf[4])\n{\n float rm, sm;\n\n rm = 1. - pcoords[0];\n sm = 1. - pcoords[1];\n\n sf[0] = rm * sm;\n sf[1] = pcoords[0] * sm;\n sf[2] = rm * pcoords[1];\n sf[3] = pcoords[0] * pcoords[1];\n}\n\n\/\/ \n\/\/ Intersect plane; see whether point is inside.\n\/\/\nint vtkPixel::IntersectWithLine(float p1[3], float p2[3], float tol, float& t,\n float x[3], float pcoords[3], int& subId)\n{\n float *pt1, *pt2, *pt3, *pt4, n[3];\n float tol2 = tol*tol;\n float closestPoint[3];\n float dist2, weights[4];\n int i;\n\n subId = 0;\n pcoords[0] = pcoords[1] = pcoords[2] = 0.0;\n\/\/\n\/\/ Get normal for triangle\n\/\/\n pt1 = this->Points.GetPoint(0);\n pt2 = this->Points.GetPoint(1);\n pt3 = this->Points.GetPoint(2);\n pt4 = this->Points.GetPoint(3);\n\n n[0] = n[1] = n[2] = 0.0;\n for (i=0; i<3; i++)\n {\n if ( (pt4[i] - pt1[i]) <= 0.0 )\n {\n n[i] = 1.0;\n break;\n }\n }\n\/\/\n\/\/ Intersect plane of pixel with line\n\/\/\n if ( ! vtkAPlane.IntersectWithLine(p1,p2,n,pt1,t,x) ) return 0;\n\/\/\n\/\/ Use evaluate position\n\/\/\n if (this->EvaluatePosition(x, closestPoint, subId, pcoords, dist2, weights) )\n if ( dist2 <= tol2 ) return 1;\n\n return 0;\n}\n\nint vtkPixel::Triangulate(int index, vtkFloatPoints &pts)\n{\n pts.Reset();\n pts.InsertPoint(0,this->Points.GetPoint(0));\n pts.InsertPoint(1,this->Points.GetPoint(1));\n pts.InsertPoint(2,this->Points.GetPoint(2));\n\n pts.InsertPoint(3,this->Points.GetPoint(1));\n pts.InsertPoint(4,this->Points.GetPoint(3));\n pts.InsertPoint(5,this->Points.GetPoint(2));\n\n return 1;\n}\n\nvoid vtkPixel::Derivatives(int subId, float pcoords[3], float *values, \n int dim, float *derivs)\n{\n int i, idx;\n\n \/\/ The following code is incorrect. Will be fixed in future release.\n for (i=0; i"} {"text":"\/**************************************************************************\\\n**\n** tVegetation.cpp: Functions for tVegetation and tVegCover classes\n**\n** Classes tVegetation and tVegCover represents the vegetation cover\n** across a terrain. Class tVegCover represents the properties of\n** vegetation at a point on the landscape (e.g., the %cover), while\n** class tVegetation represents the landscape-wide (\"global\")\n** properties (e.g., regrowth coefficient). Class tVegCover is designed\n** to be embedded in a node (in other words, each node \"has a\"\n** vegetation cover).\n**\n** Created January, 2000, GT\n** \n** $Id: tVegetation.cpp,v 1.6 2002-05-01 14:48:32 arnaud Exp $\n\\**************************************************************************\/\n\n#include \"..\/tAssert.h\"\n#include \"tVegetation.h\"\n#include \"..\/tMesh\/tMesh.h\"\n#include \"..\/tMeshList\/tMeshList.h\"\n\n\/**************************************************************************\\\n** FUNCTIONS FOR CLASS tVegetation\n\\**************************************************************************\/\n\n\/**************************************************************************\\\n**\n** tVegetation constructors:\n** 1. Default\n** 2. Input file\n**\n\\**************************************************************************\/\n\ntVegetation::tVegetation()\n :\n mdKvd(0),\n mdTVeg(1),\n mdTauCritBare(0), mdTauCritVeg(0)\n{}\n\ntVegetation::tVegetation( tMesh * meshPtr, tInputFile &infile )\n :\n mdKvd(0),\n mdTVeg(1),\n mdTauCritBare(0), mdTauCritVeg(0)\n{\n mdKvd = infile.ReadItem( mdKvd, \"VEG_KVD\" );\n mdTVeg = infile.ReadItem( mdTVeg, \"VEG_TV\" );\n mdTauCritBare = infile.ReadItem( mdTauCritBare, \"TAUC\" );\n mdTauCritVeg = infile.ReadItem( mdTVeg, \"VEG_TAUCVEG\" );\n\n \/\/ Loop through nodes and set initial vegetation cover & threshold\n \/\/ (for now, assume constant; later need to add restart capability)\n \/\/ Note: assumes initially 100% cover.\n tMeshListIter niter( meshPtr->getNodeList() );\n tLNode * cn; \n\n \/\/ unused\n \/\/ intlVegCover = infile.ReadItem( intlVegCover, \"INTLVEGCOV\" );\n\n for( cn=niter.FirstP(); niter.IsActive(); cn=niter.NextP() )\n {\n cn->getVegCover().mdVeg = 1.0;\n cn->setTauCrit( mdTauCritBare + mdTauCritVeg );\n }\n \n}\n\n\/**************************************************************************\\\n**\n** tVegetation::UpdateVegetation\n**\n** This routine updates the % vegetation cover at each node in response\n** to a storm event and its ensuing interstorm period. It also updates\n** the critical shear stress at each node according to its present\n** vegetation cover.\n**\n** Erosion of vegetation during a storm is computed as:\n** dV\/dt = -Kvd V ( tau - tauc )\n** Where V represents the proportional cover (0 to 1), tau is shear\n** stress, tauc is critical shear stress, and Kvd is a vegetation\n** erodibility coefficient. The equation is solved using an analytical\n** solution, using the expedient approximation that tauc is constant\n** during a given storm.\n**\n** Regrowth of vegetation following a storm is computed as:\n** dV\/dt = 1\/Tv ( 1 - V )\n** where Tv is the timescale of vegetation regrowth. An analytical\n** solution is used to update the vegetation cover.\n**\n** Finally, the critical shear stress is updated at each node using:\n** Tc = Tcb + V Tcv\n** where Tcb is critical shear stress in the absence of cover (bare)\n** and Tcv is critical shear stress under 100% cover.\n**\n** Created January 2000, GT\n**\n\\**************************************************************************\/\n\nvoid tVegetation::UpdateVegetation( tMesh *meshPtr, double stormdur,\n double interstormdur )\n{\n tMeshListIter< tLNode > niter( meshPtr->getNodeList() ); \/\/ Node iterator\n tLNode * cn; \/\/ Ptr to current node\n double tauex, \/\/ Excess shear stress\n veg; \/\/ Fractional vegetation cover\n \n \/\/ Loop on active nodes, computing erosion from the previous storm\n \/\/ and regrowth during the subsequent interstorm period.\n \/\/ Key assumptions: we \"cheat\" by changing the critical shear stress only\n \/\/ \"after\" the storm, using the initial value to calculate the\n \/\/ subsequent, eroded value, rather than solving the full quadratic\n \/\/ equation for vegetation destruction.\n \/\/ For both erosion and regrowth, we use an analytical solution for\n \/\/ veg cover given its initial value and duration of erosion\/regrowth.\n for( cn=niter.FirstP(); niter.IsActive(); cn=niter.NextP() )\n {\n \/\/ Erosion of vegetation during storm (if any)\n tauex = cn->getTau() - cn->getTauCrit();\n veg = cn->getVegCover().getVeg();\n if( tauex>0.0 )\n {\n veg = veg * exp( -mdKvd * tauex * stormdur );\n cn->getVegCover().mdVeg = veg;\n \/\/cout << \"veg after erosion: \" << veg << endl;\n }\n \n \/\/ Regrowth following storm\n \/\/cout << \"veg before regrowth: \" << veg << endl;\n veg = 1.0 - (1.0 - veg) * exp( -interstormdur \/ mdTVeg );\n cn->getVegCover().mdVeg = veg;\n \/\/cout << \"veg after regrowth: \" << veg << endl;\n\n \/\/ Update critical shear stress\n cn->setTauCrit( mdTauCritBare + veg*mdTauCritVeg );\n \/\/cout << \"tau crit: \" << mdTauCritBare + veg*mdTauCritVeg << endl;\n }\n \n}\n\n\n\nArnaud: added \"class\" to make doxygen happy\/**************************************************************************\\\n**\n** tVegetation.cpp: Functions for tVegetation and tVegCover classes\n**\n** Classes tVegetation and tVegCover represents the vegetation cover\n** across a terrain. Class tVegCover represents the properties of\n** vegetation at a point on the landscape (e.g., the %cover), while\n** class tVegetation represents the landscape-wide (\"global\")\n** properties (e.g., regrowth coefficient). Class tVegCover is designed\n** to be embedded in a node (in other words, each node \"has a\"\n** vegetation cover).\n**\n** Created January, 2000, GT\n** \n** $Id: tVegetation.cpp,v 1.7 2003-01-17 11:33:49 childcvs Exp $\n\\**************************************************************************\/\n\n#include \"..\/tAssert.h\"\n#include \"tVegetation.h\"\n#include \"..\/tMesh\/tMesh.h\"\n#include \"..\/tMeshList\/tMeshList.h\"\n\n\/**************************************************************************\\\n** FUNCTIONS FOR CLASS tVegetation\n\\**************************************************************************\/\n\n\/**************************************************************************\\\n**\n** tVegetation constructors:\n** 1. Default\n** 2. Input file\n**\n\\**************************************************************************\/\n\ntVegetation::tVegetation()\n :\n mdKvd(0),\n mdTVeg(1),\n mdTauCritBare(0), mdTauCritVeg(0)\n{}\n\ntVegetation::tVegetation( tMesh * meshPtr, tInputFile &infile )\n :\n mdKvd(0),\n mdTVeg(1),\n mdTauCritBare(0), mdTauCritVeg(0)\n{\n mdKvd = infile.ReadItem( mdKvd, \"VEG_KVD\" );\n mdTVeg = infile.ReadItem( mdTVeg, \"VEG_TV\" );\n mdTauCritBare = infile.ReadItem( mdTauCritBare, \"TAUC\" );\n mdTauCritVeg = infile.ReadItem( mdTVeg, \"VEG_TAUCVEG\" );\n\n \/\/ Loop through nodes and set initial vegetation cover & threshold\n \/\/ (for now, assume constant; later need to add restart capability)\n \/\/ Note: assumes initially 100% cover.\n tMeshListIter niter( meshPtr->getNodeList() );\n tLNode * cn; \n\n \/\/ unused\n \/\/ intlVegCover = infile.ReadItem( intlVegCover, \"INTLVEGCOV\" );\n\n for( cn=niter.FirstP(); niter.IsActive(); cn=niter.NextP() )\n {\n cn->getVegCover().mdVeg = 1.0;\n cn->setTauCrit( mdTauCritBare + mdTauCritVeg );\n }\n \n}\n\n\/**************************************************************************\\\n**\n** tVegetation::UpdateVegetation\n**\n** This routine updates the % vegetation cover at each node in response\n** to a storm event and its ensuing interstorm period. It also updates\n** the critical shear stress at each node according to its present\n** vegetation cover.\n**\n** Erosion of vegetation during a storm is computed as:\n** dV\/dt = -Kvd V ( tau - tauc )\n** Where V represents the proportional cover (0 to 1), tau is shear\n** stress, tauc is critical shear stress, and Kvd is a vegetation\n** erodibility coefficient. The equation is solved using an analytical\n** solution, using the expedient approximation that tauc is constant\n** during a given storm.\n**\n** Regrowth of vegetation following a storm is computed as:\n** dV\/dt = 1\/Tv ( 1 - V )\n** where Tv is the timescale of vegetation regrowth. An analytical\n** solution is used to update the vegetation cover.\n**\n** Finally, the critical shear stress is updated at each node using:\n** Tc = Tcb + V Tcv\n** where Tcb is critical shear stress in the absence of cover (bare)\n** and Tcv is critical shear stress under 100% cover.\n**\n** Created January 2000, GT\n**\n\\**************************************************************************\/\n\nvoid tVegetation::UpdateVegetation( tMesh *meshPtr,\n\t\t\t\t double stormdur,\n double interstormdur )\n{\n tMeshListIter< tLNode > niter( meshPtr->getNodeList() ); \/\/ Node iterator\n tLNode * cn; \/\/ Ptr to current node\n double tauex, \/\/ Excess shear stress\n veg; \/\/ Fractional vegetation cover\n \n \/\/ Loop on active nodes, computing erosion from the previous storm\n \/\/ and regrowth during the subsequent interstorm period.\n \/\/ Key assumptions: we \"cheat\" by changing the critical shear stress only\n \/\/ \"after\" the storm, using the initial value to calculate the\n \/\/ subsequent, eroded value, rather than solving the full quadratic\n \/\/ equation for vegetation destruction.\n \/\/ For both erosion and regrowth, we use an analytical solution for\n \/\/ veg cover given its initial value and duration of erosion\/regrowth.\n for( cn=niter.FirstP(); niter.IsActive(); cn=niter.NextP() )\n {\n \/\/ Erosion of vegetation during storm (if any)\n tauex = cn->getTau() - cn->getTauCrit();\n veg = cn->getVegCover().getVeg();\n if( tauex>0.0 )\n {\n veg = veg * exp( -mdKvd * tauex * stormdur );\n cn->getVegCover().mdVeg = veg;\n \/\/cout << \"veg after erosion: \" << veg << endl;\n }\n \n \/\/ Regrowth following storm\n \/\/cout << \"veg before regrowth: \" << veg << endl;\n veg = 1.0 - (1.0 - veg) * exp( -interstormdur \/ mdTVeg );\n cn->getVegCover().mdVeg = veg;\n \/\/cout << \"veg after regrowth: \" << veg << endl;\n\n \/\/ Update critical shear stress\n cn->setTauCrit( mdTauCritBare + veg*mdTauCritVeg );\n \/\/cout << \"tau crit: \" << mdTauCritBare + veg*mdTauCritVeg << endl;\n }\n \n}\n\n\n\n<|endoftext|>"} {"text":"static int dump_node_ia32(ir_node *n, FILE *F, dump_reason_t reason)\n{\n const char *name, *p;\n ir_mode *mode;\n int bad = 0;\n char buf[1024];\n\n switch (reason) {\n case dump_node_opcode_txt:\n name = get_irn_opname(n);\n fprintf(F, \"%s\", name);\n break;\n case dump_node_mode_txt:\n mode = get_irn_mode(n);\n name = get_irn_opname(n);\n\n if (mode && mode != mode_BB && mode != mode_ANY && mode != mode_BAD && mode != mode_T) {\n p = name + strlen(name) - 2;\n if (p[0] == '_' && p[1] == 'i') {\n tarval_snprintf(buf, sizeof(buf), get_Immop_tarval(n));\n fprintf(F, \"[%s]\", buf);\n }\n\n fprintf(F, \"%s\", get_mode_name(mode));\n }\n break;\n\n case dump_node_nodeattr_txt:\n break;\n }\n return bad;\n}\nimproved dump of node attributesstatic void fprintf_tv(FILE *F, tarval *tv, int brackets) {\n char buf[1024];\n tarval_snprintf(buf, sizeof(buf), tv);\n\n if (brackets)\n fprintf(F, \"[%s]\", buf);\n else\n fprintf(F, \"%s\", buf);\n}\n\nstatic int dump_node_ia32(ir_node *n, FILE *F, dump_reason_t reason) {\n const char *name, *p;\n ir_mode *mode = NULL;\n int bad = 0;\n\n switch (reason) {\n case dump_node_opcode_txt:\n name = get_irn_opname(n);\n fprintf(F, \"%s\", name);\n break;\n\n case dump_node_mode_txt:\n mode = get_irn_mode(n);\n\n if (mode && mode != mode_BB && mode != mode_ANY && mode != mode_BAD && mode != mode_T) {\n \/* dump below *\/\n }\n else if (is_ia32_Load(n)) {\n mode = get_irn_mode(get_irn_n(n, 1));\n }\n else if (is_ia32_Store(n)) {\n mode = get_irn_mode(get_irn_n(n, 2));\n }\n\n if (mode)\n fprintf(F, \"[%s]\", get_mode_name(mode));\n break;\n\n case dump_node_nodeattr_txt:\n name = get_irn_opname(n);\n p = name + strlen(name) - 2;\n if (p[0] == '_' && p[1] == 'i') {\n tarval *tv = get_Immop_tarval(n);\n if (tv)\n fprintf_tv(F, tv, 1);\n else {\n fprintf(F, \"[SymConst]\");\n }\n }\n break;\n\n case dump_node_info_txt:\n if (is_ia32_Lea(n)) {\n tarval *o = get_ia32_Lea_offs(n);\n tarval *tv = get_Immop_tarval(n);\n\n fprintf(F, \"LEA \");\n if (o)\n fprintf_tv(F, o, 0);\n fprintf(F, \"(%s, %s\", get_irn_opname(get_irn_n(n, 0)), get_irn_opname(get_irn_n(n, 1)));\n if (tv) {\n fprintf(F, \", \");\n fprintf_tv(F, tv, 0);\n }\n fprintf(F, \")\\n\");\n }\n break;\n }\n\n return bad;\n}\n<|endoftext|>"} {"text":"#pragma once\n\/* RLTK (RogueLike Tool Kit) 1.00\n * Copyright (c) 2016-Present, Bracket Productions.\n * Licensed under the LGPL - see LICENSE file.\n *\n * Provides a wrapper for bitmap fonts.\n *\/\n\n#include \n#include \"geometry.hpp\"\n\nnamespace rltk {\n\nnamespace visibility_private {\n\ntemplate\nvoid internal_2d_sweep(const location_t_ &position, const location_t_ &destination, const int &range, std::function set_visible, \n\tstd::function is_opaque)\n{\n\tbool blocked = false;\n\tline_func(position.x, position.y, destination.x, destination.y, [&blocked, &is_opaque, &set_visible, &range, &position] (int X, int Y) {\n\t\tfloat distance = distance2d(position.x, position.y, X, Y);\n\t\tif (distance <= range) {\n\t\t\tlocation_t_ pos;\n\t\t\tpos.x = X;\n\t\t\tpos.y = Y;\n\t\t\tif (!blocked) set_visible(pos);\n\t\t\tif (!is_opaque(pos)) blocked = true;\n\t\t}\n\t});\t\n}\n\n}\n\n\/* Simple all-direction visibility sweep in 2 dimensions. This requires that your location_t utilize an x and y\n * component. Parameters:\n * position - where you are sweeping from.\n * range - the number of tiles you can traverse.\n * set_visible - a callback (such as bool set_visible(location_t & loc)) to say \"this is visible\"\n * is_opaque - a callback to ask your map if you can see through a tile.\n *\/\ntemplate\nvoid visibility_sweep_2d(const location_t_ &position, const int &range, std::function set_visible, \n\tstd::function is_opaque)\n{\n\t\/\/ You can always see yourself\n\tset_visible(position);\n\n\t\/\/ Box-sweep\n\tfor (int i=0-range; iImprove box-sweep readability by exposing an offset rather than repeatedly calculating a destination.#pragma once\n\/* RLTK (RogueLike Tool Kit) 1.00\n * Copyright (c) 2016-Present, Bracket Productions.\n * Licensed under the LGPL - see LICENSE file.\n *\n * Provides a wrapper for bitmap fonts.\n *\/\n\n#include \n#include \"geometry.hpp\"\n\nnamespace rltk {\n\nnamespace visibility_private {\n\ntemplate\nvoid internal_2d_sweep(const location_t_ &position, const int &range, std::function set_visible, \n\tstd::function is_opaque, const std::pair offset)\n{\n\tbool blocked = false;\n\tline_func(position.x, position.y, position.x + offset.first, position.y + offset.second, [&blocked, &is_opaque, &set_visible, &range, &position] (int X, int Y) {\n\t\tfloat distance = distance2d(position.x, position.y, X, Y);\n\t\tif (distance <= range) {\n\t\t\tlocation_t_ pos;\n\t\t\tpos.x = X;\n\t\t\tpos.y = Y;\n\t\t\tif (!blocked) set_visible(pos);\n\t\t\tif (!is_opaque(pos)) blocked = true;\n\t\t}\n\t});\t\n}\n\n}\n\n\/* Simple all-direction visibility sweep in 2 dimensions. This requires that your location_t utilize an x and y\n * component. Parameters:\n * position - where you are sweeping from.\n * range - the number of tiles you can traverse.\n * set_visible - a callback (such as bool set_visible(location_t & loc)) to say \"this is visible\"\n * is_opaque - a callback to ask your map if you can see through a tile.\n *\/\ntemplate\nvoid visibility_sweep_2d(const location_t_ &position, const int &range, std::function set_visible, \n\tstd::function is_opaque)\n{\n\t\/\/ You can always see yourself\n\tset_visible(position);\n\n\t\/\/ Box-sweep\n\tfor (int i=0-range; i"} {"text":"#ifndef __RMOL_RMOL_TYPES_HPP\n#define __RMOL_RMOL_TYPES_HPP\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Import section\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ STL\n#include \n#include \n\nnamespace RMOL {\n\n \/\/ \/\/\/\/\/\/\/\/\/ Exceptions \/\/\/\/\/\/\/\/\/\/\/\n class RootException : public std::exception {\n };\n\n class FileNotFoundException : public RootException {\n };\n \n class NonInitialisedServiceException : public RootException {\n };\n\n class MemoryAllocationException : public RootException {\n };\n\n class ObjectNotFoundException : public RootException {\n };\n\n class DocumentNotFoundException : public RootException {\n };\n\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Log \/\/\/\/\/\/\/\/\/\/\/\/\/\n \/** Level of logs. *\/\n namespace LOG {\n typedef enum {\n CRITICAL = 0,\n ERROR,\n NOTIFICATION,\n WARNING,\n DEBUG,\n VERBOSE,\n LAST_VALUE\n } EN_LogLevel;\n }\n\n \/\/ \/\/\/\/\/\/\/\/ Type definitions \/\/\/\/\/\/\/\/\/\n\n\n}\n#endif \/\/ __RMOL_RMOL_TYPES_HPP\nDefined the smart pointer type for RMOL service.#ifndef __RMOL_RMOL_TYPES_HPP\n#define __RMOL_RMOL_TYPES_HPP\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Import section\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ STL\n#include \n#include \n\/\/ Boost\n#include \n\nnamespace RMOL {\n\n \/\/ Forward declarations\n class RMOL_Service;\n\n \/\/ \/\/\/\/\/\/\/\/\/ Exceptions \/\/\/\/\/\/\/\/\/\/\/\n class RootException : public std::exception {\n };\n\n class FileNotFoundException : public RootException {\n };\n \n class NonInitialisedServiceException : public RootException {\n };\n\n class MemoryAllocationException : public RootException {\n };\n\n class ObjectNotFoundException : public RootException {\n };\n\n class DocumentNotFoundException : public RootException {\n };\n\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Log \/\/\/\/\/\/\/\/\/\/\/\/\/\n \/** Level of logs. *\/\n namespace LOG {\n typedef enum {\n CRITICAL = 0,\n ERROR,\n NOTIFICATION,\n WARNING,\n DEBUG,\n VERBOSE,\n LAST_VALUE\n } EN_LogLevel;\n }\n\n \/\/ \/\/\/\/\/\/\/\/ Type definitions \/\/\/\/\/\/\/\/\/\n \/** Pointer on the RMOL Service handler. *\/\n typedef boost::shared_ptr RMOL_ServicePtr_T;\n\n\n}\n#endif \/\/ __RMOL_RMOL_TYPES_HPP\n<|endoftext|>"} {"text":"#include \"thread_pool.h\"\n#include \n#include \n#include \n#include \n#if __APPLE__ || __linux__\n #include \n#endif\n\n#if __has_include(\"debugging.h\")\n# include \"debugging.h\"\n#endif\n\n#define POOL_TASK_DEBUG 0\n\nnamespace rpp\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n static pool_trace_provider TraceProvider;\n static pool_signal_handler SignalHandler = [](const char* what) {\n throw std::runtime_error(what);\n };\n\n#if POOL_TASK_DEBUG\n# ifdef LogWarning\n# define TaskDebug(fmt, ...) LogWarning(fmt, ##__VA_ARGS__)\n# else\n# define TaskDebug(fmt, ...) fprintf(stderr, fmt \"\\n\", ##__VA_ARGS__)\n# endif\n#else\n# define TaskDebug(fmt, ...) \/\/ do nothing\n#endif\n\n#ifdef LogWarning\n# define UnhandledEx(fmt, ...) LogWarning(fmt, ##__VA_ARGS__)\n#else\n# define UnhandledEx(fmt, ...) fprintf(stderr, \"pool_task::unhandled_exception $ \" fmt \"\\n\", ##__VA_ARGS__)\n#endif\n \n pool_task::pool_task()\n {\n th = thread{[this] { run(); }};\n }\n\n pool_task::~pool_task() noexcept\n {\n kill();\n }\n\n void pool_task::max_idle_time(int maxIdleSeconds) { maxIdleTime = maxIdleSeconds; }\n\n void pool_task::run_range(int start, int end, const action& newTask) noexcept\n {\n assert(!taskRunning && \"rpp::pool_task already running! This can cause deadlocks due to abandoned tasks!\");\n\n { lock_guard lock{m};\n trace.clear();\n error = nullptr;\n if (auto tracer = TraceProvider)\n trace = TraceProvider();\n genericTask = {};\n rangeTask = newTask;\n rangeStart = start;\n rangeEnd = end;\n taskRunning = true;\n }\n notify_task();\n }\n\n void pool_task::run_generic(task_delegate&& newTask) noexcept\n {\n assert(!taskRunning && \"rpp::pool_task already running! This can cause deadlocks due to abandoned tasks!\");\n\n \/\/TaskDebug(\"queue task\");\n { lock_guard lock{m};\n trace.clear();\n error = nullptr;\n if (auto tracer = TraceProvider)\n trace = TraceProvider();\n genericTask = move(newTask);\n rangeTask = {};\n rangeStart = 0;\n rangeEnd = 0;\n taskRunning = true;\n }\n notify_task();\n }\n \n void pool_task::notify_task()\n {\n { lock_guard lock{m};\n if (killed) {\n TaskDebug(\"resurrecting task\");\n killed = false;\n if (th.joinable()) th.join();\n th = thread{[this] { run(); }}; \/\/ restart thread if needed\n }\n }\n cv.notify_one();\n }\n\n pool_task::wait_result pool_task::wait(int timeoutMillis)\n {\n unique_lock lock{m};\n while (taskRunning)\n {\n if (timeoutMillis)\n {\n if (cv.wait_for(lock, chrono::milliseconds(timeoutMillis)) == cv_status::timeout)\n return timeout;\n }\n else\n {\n cv.wait(lock);\n }\n }\n if (error) rethrow_exception(error);\n return finished;\n }\n\n pool_task::wait_result pool_task::kill(int timeoutMillis) noexcept\n {\n if (killed) {\n if (th.joinable()) th.join();\n return finished;\n }\n { unique_lock lock{m};\n TaskDebug(\"killing task\");\n killed = true;\n }\n cv.notify_all();\n wait_result result = wait(timeoutMillis);\n if (th.joinable()) {\n if (result == timeout) th.detach();\n else th.join();\n }\n return result;\n }\n\n#if _WIN32\n #ifndef WIN32_LEAN_AND_MEAN\n # define WIN32_LEAN_AND_MEAN 1\n #endif\n #include \n #pragma pack(push,8)\n struct THREADNAME_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 };\n #pragma pack(pop)\n void SetThreadName(const char* threadName)\n {\n THREADNAME_INFO info;\n info.dwType = 0x1000;\n info.szName = threadName;\n info.dwThreadID = (DWORD)-1;\n info.dwFlags = 0;\n\n #pragma warning(push)\n #pragma warning(disable: 6320 6322)\n const DWORD MS_VC_EXCEPTION = 0x406D1388;\n __try {\n RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) \/ sizeof(ULONG_PTR), (ULONG_PTR*)&info);\n } __except (1){}\n #pragma warning(pop)\n }\n#endif\n\n \/\/ really nasty case where OS threads are just abandoned\n \/\/ with none of the destructors being run\n static mutex activeTaskMutex;\n static unordered_map activeTasks;\n static int get_thread_id()\n {\n auto id = this_thread::get_id();\n return *(int*)&id;\n }\n static void register_thread_task(pool_task* task)\n {\n lock_guard lock{ activeTaskMutex };\n activeTasks[get_thread_id()] = task;\n }\n static void erase_thread_task()\n {\n lock_guard lock{ activeTaskMutex };\n activeTasks.erase(get_thread_id());\n }\n\n\n static void segfault(int) { SignalHandler(\"SIGSEGV\"); }\n static void sigterm(int) { SignalHandler(\"SIGTERM\"); }\n static void sigabort(int) { SignalHandler(\"SIGABORT\"); }\n\n\n void pool_task::run() noexcept\n {\n static int pool_task_id;\n char name[32];\n snprintf(name, sizeof(name), \"rpp_task_%d\", pool_task_id++);\n\n #if __APPLE__\n pthread_setname_np(name);\n #elif __linux__\n pthread_setname_np(pthread_self(), name);\n #elif _WIN32\n SetThreadName(name);\n #endif\n \n signal(SIGSEGV, segfault); \/\/ set SIGSEGV handler so we can catch it\n signal(SIGTERM, sigterm);\n signal(SIGABRT, sigabort);\n\n register_thread_task(this);\n\n \/\/ mark all running threads killed during SIGTERM, before dtors run\n static int atExitRegistered;\n if (!atExitRegistered) atExitRegistered = !atexit([] {\n for (auto& task : activeTasks) {\n task.second->killed = true;\n task.second->cv.notify_all();\n }\n activeTasks.clear();\n });\n\n struct thread_exiter {\n pool_task* self;\n ~thread_exiter() {\n erase_thread_task();\n self->killed = true;\n self->taskRunning = false;\n self->cv.notify_all();\n }\n } markKilledOnScopeExit { this }; \/\/ however, this doesn't handle exit(0) where threads are mutilated\n\n \/\/TaskDebug(\"%s start\", name);\n for (;;)\n {\n try\n {\n decltype(rangeTask) range;\n decltype(genericTask) generic;\n \n \/\/ consume the tasks atomically\n { unique_lock lock{m};\n \/\/TaskDebug(\"%s wait for task\", name);\n if (!wait_for_task(lock)) {\n TaskDebug(\"%s stop (%s)\", name, killed ? \"killed\" : \"timeout\");\n return;\n }\n range = move(rangeTask);\n generic = move(genericTask);\n rangeTask = {};\n genericTask = {}; \/\/ BUG: Clang on android doesn't move genericTask properly\n taskRunning = true;\n }\n if (range)\n {\n \/\/TaskDebug(\"%s(range_task[%d,%d))\", name, rangeStart, rangeEnd);\n range(rangeStart, rangeEnd);\n }\n else\n {\n \/\/TaskDebug(\"%s(generic_task)\", name);\n generic();\n }\n }\n \/\/ prevent failures that would terminate the thread\n catch (const exception& e) { unhandled_exception(e.what()); }\n catch (const char* e) { unhandled_exception(e); }\n catch (...) { unhandled_exception(\"\"); }\n { lock_guard lock{m};\n taskRunning = false;\n cv.notify_all();\n }\n }\n }\n\n void pool_task::unhandled_exception(const char* what) noexcept\n {\n error = std::current_exception();\n\n string err = what;\n { lock_guard lock{m};\n if (!trace.empty()) {\n err += \"\\nTask Start Trace:\\n\";\n err += trace;\n }\n }\n UnhandledEx(\"%s\", err.c_str());\n }\n\n bool pool_task::got_task() const noexcept\n {\n return (bool)rangeTask || (bool)genericTask;\n }\n\n bool pool_task::wait_for_task(unique_lock& lock) noexcept\n {\n for (;;)\n {\n if (killed)\n return false;\n if (got_task())\n return true;\n if (maxIdleTime)\n {\n if (cv.wait_for(lock, chrono::seconds(maxIdleTime)) == cv_status::timeout)\n return false;\n }\n else\n {\n cv.wait(lock);\n }\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n thread_pool& thread_pool::global()\n {\n static thread_pool globalPool;\n return globalPool;\n }\n\n#if _WIN32\n static int num_physical_cores()\n {\n DWORD bytes = 0;\n GetLogicalProcessorInformation(nullptr, &bytes);\n vector coreInfo(bytes \/ sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION));\n GetLogicalProcessorInformation(coreInfo.data(), &bytes);\n\n int cores = 0;\n for (auto& info : coreInfo)\n {\n if (info.Relationship == RelationProcessorCore)\n ++cores;\n }\n return cores;\n }\n#else\n static int num_physical_cores()\n {\n return (int)thread::hardware_concurrency();\n }\n#endif\n\n int thread_pool::physical_cores()\n {\n return global().coreCount;\n }\n\n void thread_pool::set_signal_handler(pool_signal_handler signalHandler)\n {\n lock_guard lock{ tasksMutex };\n SignalHandler = signalHandler;\n }\n\n void thread_pool::set_task_tracer(pool_trace_provider traceProvider)\n {\n lock_guard lock{ tasksMutex };\n TraceProvider = traceProvider;\n }\n\n thread_pool::thread_pool()\n {\n coreCount = num_physical_cores();\n }\n\n thread_pool::~thread_pool() noexcept\n {\n \/\/ defined destructor to prevent agressive inlining\n }\n\n int thread_pool::active_tasks() noexcept\n {\n lock_guard lock{tasksMutex};\n int active = 0;\n for (auto& task : tasks) \n if (task->running()) ++active;\n return active;\n }\n\n int thread_pool::idle_tasks() noexcept\n {\n lock_guard lock{tasksMutex};\n int idle = 0;\n for (auto& task : tasks)\n if (!task->running()) ++idle;\n return idle;\n }\n\n int thread_pool::total_tasks() const noexcept\n {\n return (int)tasks.size();\n }\n\n int thread_pool::clear_idle_tasks() noexcept\n {\n lock_guard lock{tasksMutex};\n int cleared = 0;\n for (int i = 0; i < (int)tasks.size();)\n {\n if (!tasks[i]->running())\n {\n swap(tasks[i], tasks.back()); \/\/ erase_swap_last pattern\n tasks.pop_back();\n ++cleared;\n }\n else ++i;\n }\n return cleared;\n }\n\n pool_task* thread_pool::start_range_task(size_t& poolIndex, int rangeStart, int rangeEnd, \n const action& rangeTask) noexcept\n {\n { lock_guard lock{tasksMutex};\n for (; poolIndex < tasks.size(); ++poolIndex)\n {\n pool_task* task = tasks[poolIndex].get();\n if (!task->running())\n {\n ++poolIndex;\n task->run_range(rangeStart, rangeEnd, rangeTask);\n return task;\n }\n }\n }\n\n auto t = make_unique();\n auto* task = t.get();\n task->max_idle_time(taskMaxIdleTime);\n task->run_range(rangeStart, rangeEnd, rangeTask);\n\n lock_guard lock{tasksMutex};\n tasks.emplace_back(move(t));\n return task;\n }\n\n void thread_pool::max_task_idle_time(int maxIdleSeconds) noexcept\n {\n lock_guard lock{tasksMutex};\n taskMaxIdleTime = maxIdleSeconds;\n for (auto& task : tasks)\n task->max_idle_time(taskMaxIdleTime);\n }\n\n void thread_pool::parallel_for(int rangeStart, int rangeEnd, \n const action& rangeTask) noexcept\n {\n assert(!rangeRunning && \"Fatal error: nested parallel loops are forbidden!\");\n assert(coreCount > 0 && \"There appears to be no hardware concurrency\");\n\n const int range = rangeEnd - rangeStart;\n if (range <= 0)\n return;\n\n const int cores = range < coreCount ? range : coreCount;\n const int len = range \/ cores;\n\n \/\/ only one physical core or only one task to run. don't run in a thread\n if (cores <= 1)\n {\n rangeTask(0, len);\n return;\n }\n\n pool_task** active = (pool_task**)alloca(sizeof(pool_task*) * cores);\n \/\/vector active(cores, nullptr);\n {\n rangeRunning = true;\n\n size_t poolIndex = 0;\n for (int i = 0; i < cores; ++i)\n {\n const int start = i * len;\n const int end = i == cores - 1 ? rangeEnd : start + len;\n active[i] = start_range_task(poolIndex, start, end, rangeTask);\n }\n }\n\n for (int i = 0; i < cores; ++i)\n active[i]->wait();\n\n rangeRunning = false;\n }\n\n pool_task* thread_pool::parallel_task(task_delegate&& genericTask) noexcept\n {\n { lock_guard lock{tasksMutex};\n for (unique_ptr& t : tasks)\n {\n pool_task* task = t.get();\n if (!task->running())\n {\n task->run_generic(move(genericTask));\n return task;\n }\n }\n }\n \n \/\/ create and run a new task atomically\n auto t = make_unique();\n auto* task = t.get();\n task->max_idle_time(taskMaxIdleTime);\n task->run_generic(move(genericTask));\n\n lock_guard lock{tasksMutex};\n tasks.emplace_back(move(t));\n return task;\n }\n}\nRemoved SIGABRT and SIGTERM handlers -- they cause unnecessary bugs and issues#include \"thread_pool.h\"\n#include \n#include \n#include \n#include \n#if __APPLE__ || __linux__\n #include \n#endif\n\n#if __has_include(\"debugging.h\")\n# include \"debugging.h\"\n#endif\n\n#define POOL_TASK_DEBUG 0\n\nnamespace rpp\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n static pool_trace_provider TraceProvider;\n static pool_signal_handler SignalHandler = [](const char* what) {\n throw std::runtime_error(what);\n };\n\n#if POOL_TASK_DEBUG\n# ifdef LogWarning\n# define TaskDebug(fmt, ...) LogWarning(fmt, ##__VA_ARGS__)\n# else\n# define TaskDebug(fmt, ...) fprintf(stderr, fmt \"\\n\", ##__VA_ARGS__)\n# endif\n#else\n# define TaskDebug(fmt, ...) \/\/ do nothing\n#endif\n\n#ifdef LogWarning\n# define UnhandledEx(fmt, ...) LogWarning(fmt, ##__VA_ARGS__)\n#else\n# define UnhandledEx(fmt, ...) fprintf(stderr, \"pool_task::unhandled_exception $ \" fmt \"\\n\", ##__VA_ARGS__)\n#endif\n \n pool_task::pool_task()\n {\n th = thread{[this] { run(); }};\n }\n\n pool_task::~pool_task() noexcept\n {\n kill();\n }\n\n void pool_task::max_idle_time(int maxIdleSeconds) { maxIdleTime = maxIdleSeconds; }\n\n void pool_task::run_range(int start, int end, const action& newTask) noexcept\n {\n assert(!taskRunning && \"rpp::pool_task already running! This can cause deadlocks due to abandoned tasks!\");\n\n { lock_guard lock{m};\n trace.clear();\n error = nullptr;\n if (auto tracer = TraceProvider)\n trace = tracer();\n genericTask = {};\n rangeTask = newTask;\n rangeStart = start;\n rangeEnd = end;\n taskRunning = true;\n }\n notify_task();\n }\n\n void pool_task::run_generic(task_delegate&& newTask) noexcept\n {\n assert(!taskRunning && \"rpp::pool_task already running! This can cause deadlocks due to abandoned tasks!\");\n\n \/\/TaskDebug(\"queue task\");\n { lock_guard lock{m};\n trace.clear();\n error = nullptr;\n if (auto tracer = TraceProvider)\n trace = tracer();\n genericTask = move(newTask);\n rangeTask = {};\n rangeStart = 0;\n rangeEnd = 0;\n taskRunning = true;\n }\n notify_task();\n }\n \n void pool_task::notify_task()\n {\n { lock_guard lock{m};\n if (killed) {\n TaskDebug(\"resurrecting task\");\n killed = false;\n if (th.joinable()) th.join();\n th = thread{[this] { run(); }}; \/\/ restart thread if needed\n }\n }\n cv.notify_one();\n }\n\n pool_task::wait_result pool_task::wait(int timeoutMillis)\n {\n unique_lock lock{m};\n while (taskRunning)\n {\n if (timeoutMillis)\n {\n if (cv.wait_for(lock, chrono::milliseconds(timeoutMillis)) == cv_status::timeout)\n return timeout;\n }\n else\n {\n cv.wait(lock);\n }\n }\n if (error) rethrow_exception(error);\n return finished;\n }\n\n pool_task::wait_result pool_task::kill(int timeoutMillis) noexcept\n {\n if (killed) {\n if (th.joinable()) th.join();\n return finished;\n }\n { unique_lock lock{m};\n TaskDebug(\"killing task\");\n killed = true;\n }\n cv.notify_all();\n wait_result result = wait(timeoutMillis);\n if (th.joinable()) {\n if (result == timeout) th.detach();\n else th.join();\n }\n return result;\n }\n\n#if _WIN32\n #ifndef WIN32_LEAN_AND_MEAN\n # define WIN32_LEAN_AND_MEAN 1\n #endif\n #include \n #pragma pack(push,8)\n struct THREADNAME_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 };\n #pragma pack(pop)\n void SetThreadName(const char* threadName)\n {\n THREADNAME_INFO info;\n info.dwType = 0x1000;\n info.szName = threadName;\n info.dwThreadID = (DWORD)-1;\n info.dwFlags = 0;\n\n #pragma warning(push)\n #pragma warning(disable: 6320 6322)\n const DWORD MS_VC_EXCEPTION = 0x406D1388;\n __try {\n RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) \/ sizeof(ULONG_PTR), (ULONG_PTR*)&info);\n } __except (1){}\n #pragma warning(pop)\n }\n#endif\n\n \/\/ really nasty case where OS threads are just abandoned\n \/\/ with none of the destructors being run\n static mutex activeTaskMutex;\n static unordered_map activeTasks;\n static int get_thread_id()\n {\n auto id = this_thread::get_id();\n return *(int*)&id;\n }\n static void register_thread_task(pool_task* task)\n {\n lock_guard lock{ activeTaskMutex };\n activeTasks[get_thread_id()] = task;\n }\n static void erase_thread_task()\n {\n lock_guard lock{ activeTaskMutex };\n activeTasks.erase(get_thread_id());\n }\n\n static void segfault(int) { SignalHandler(\"SIGSEGV\"); }\n\n void pool_task::run() noexcept\n {\n static int pool_task_id;\n char name[32];\n snprintf(name, sizeof(name), \"rpp_task_%d\", pool_task_id++);\n\n #if __APPLE__\n pthread_setname_np(name);\n #elif __linux__\n pthread_setname_np(pthread_self(), name);\n #elif _WIN32\n SetThreadName(name);\n #endif\n \n signal(SIGSEGV, segfault); \/\/ set SIGSEGV handler so we can catch it\n register_thread_task(this);\n\n \/\/ mark all running threads killed during SIGTERM, before dtors run\n static int atExitRegistered;\n if (!atExitRegistered) atExitRegistered = !atexit([] {\n for (auto& task : activeTasks) {\n task.second->killed = true;\n task.second->cv.notify_all();\n }\n activeTasks.clear();\n });\n\n struct thread_exiter {\n pool_task* self;\n ~thread_exiter() {\n erase_thread_task();\n self->killed = true;\n self->taskRunning = false;\n self->cv.notify_all();\n }\n } markKilledOnScopeExit { this }; \/\/ however, this doesn't handle exit(0) where threads are mutilated\n\n \/\/TaskDebug(\"%s start\", name);\n for (;;)\n {\n try\n {\n decltype(rangeTask) range;\n decltype(genericTask) generic;\n \n \/\/ consume the tasks atomically\n { unique_lock lock{m};\n \/\/TaskDebug(\"%s wait for task\", name);\n if (!wait_for_task(lock)) {\n TaskDebug(\"%s stop (%s)\", name, killed ? \"killed\" : \"timeout\");\n return;\n }\n range = move(rangeTask);\n generic = move(genericTask);\n rangeTask = {};\n genericTask = {};\n taskRunning = true;\n }\n if (range)\n {\n \/\/TaskDebug(\"%s(range_task[%d,%d))\", name, rangeStart, rangeEnd);\n range(rangeStart, rangeEnd);\n }\n else\n {\n \/\/TaskDebug(\"%s(generic_task)\", name);\n generic();\n }\n }\n \/\/ prevent failures that would terminate the thread\n catch (const exception& e) { unhandled_exception(e.what()); }\n catch (const char* e) { unhandled_exception(e); }\n catch (...) { unhandled_exception(\"\"); }\n { lock_guard lock{m};\n taskRunning = false;\n cv.notify_all();\n }\n }\n }\n\n void pool_task::unhandled_exception(const char* what) noexcept\n {\n error = std::current_exception();\n\n string err = what;\n { lock_guard lock{m};\n if (!trace.empty()) {\n err += \"\\nTask Start Trace:\\n\";\n err += trace;\n }\n }\n UnhandledEx(\"%s\", err.c_str());\n }\n\n bool pool_task::got_task() const noexcept\n {\n return (bool)rangeTask || (bool)genericTask;\n }\n\n bool pool_task::wait_for_task(unique_lock& lock) noexcept\n {\n for (;;)\n {\n if (killed)\n return false;\n if (got_task())\n return true;\n if (maxIdleTime)\n {\n if (cv.wait_for(lock, chrono::seconds(maxIdleTime)) == cv_status::timeout)\n return false;\n }\n else\n {\n cv.wait(lock);\n }\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n thread_pool& thread_pool::global()\n {\n static thread_pool globalPool;\n return globalPool;\n }\n\n#if _WIN32\n static int num_physical_cores()\n {\n DWORD bytes = 0;\n GetLogicalProcessorInformation(nullptr, &bytes);\n vector coreInfo(bytes \/ sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION));\n GetLogicalProcessorInformation(coreInfo.data(), &bytes);\n\n int cores = 0;\n for (auto& info : coreInfo)\n {\n if (info.Relationship == RelationProcessorCore)\n ++cores;\n }\n return cores;\n }\n#else\n static int num_physical_cores()\n {\n return (int)thread::hardware_concurrency();\n }\n#endif\n\n int thread_pool::physical_cores()\n {\n return global().coreCount;\n }\n\n void thread_pool::set_signal_handler(pool_signal_handler signalHandler)\n {\n lock_guard lock{ tasksMutex };\n SignalHandler = signalHandler;\n }\n\n void thread_pool::set_task_tracer(pool_trace_provider traceProvider)\n {\n lock_guard lock{ tasksMutex };\n TraceProvider = traceProvider;\n }\n\n thread_pool::thread_pool()\n {\n coreCount = num_physical_cores();\n }\n\n thread_pool::~thread_pool() noexcept\n {\n \/\/ defined destructor to prevent agressive inlining\n }\n\n int thread_pool::active_tasks() noexcept\n {\n lock_guard lock{tasksMutex};\n int active = 0;\n for (auto& task : tasks) \n if (task->running()) ++active;\n return active;\n }\n\n int thread_pool::idle_tasks() noexcept\n {\n lock_guard lock{tasksMutex};\n int idle = 0;\n for (auto& task : tasks)\n if (!task->running()) ++idle;\n return idle;\n }\n\n int thread_pool::total_tasks() const noexcept\n {\n return (int)tasks.size();\n }\n\n int thread_pool::clear_idle_tasks() noexcept\n {\n lock_guard lock{tasksMutex};\n int cleared = 0;\n for (int i = 0; i < (int)tasks.size();)\n {\n if (!tasks[i]->running())\n {\n swap(tasks[i], tasks.back()); \/\/ erase_swap_last pattern\n tasks.pop_back();\n ++cleared;\n }\n else ++i;\n }\n return cleared;\n }\n\n pool_task* thread_pool::start_range_task(size_t& poolIndex, int rangeStart, int rangeEnd, \n const action& rangeTask) noexcept\n {\n { lock_guard lock{tasksMutex};\n for (; poolIndex < tasks.size(); ++poolIndex)\n {\n pool_task* task = tasks[poolIndex].get();\n if (!task->running())\n {\n ++poolIndex;\n task->run_range(rangeStart, rangeEnd, rangeTask);\n return task;\n }\n }\n }\n\n auto t = make_unique();\n auto* task = t.get();\n task->max_idle_time(taskMaxIdleTime);\n task->run_range(rangeStart, rangeEnd, rangeTask);\n\n lock_guard lock{tasksMutex};\n tasks.emplace_back(move(t));\n return task;\n }\n\n void thread_pool::max_task_idle_time(int maxIdleSeconds) noexcept\n {\n lock_guard lock{tasksMutex};\n taskMaxIdleTime = maxIdleSeconds;\n for (auto& task : tasks)\n task->max_idle_time(taskMaxIdleTime);\n }\n\n void thread_pool::parallel_for(int rangeStart, int rangeEnd, \n const action& rangeTask) noexcept\n {\n assert(!rangeRunning && \"Fatal error: nested parallel loops are forbidden!\");\n assert(coreCount > 0 && \"There appears to be no hardware concurrency\");\n\n const int range = rangeEnd - rangeStart;\n if (range <= 0)\n return;\n\n const int cores = range < coreCount ? range : coreCount;\n const int len = range \/ cores;\n\n \/\/ only one physical core or only one task to run. don't run in a thread\n if (cores <= 1)\n {\n rangeTask(0, len);\n return;\n }\n\n pool_task** active = (pool_task**)alloca(sizeof(pool_task*) * cores);\n \/\/vector active(cores, nullptr);\n {\n rangeRunning = true;\n\n size_t poolIndex = 0;\n for (int i = 0; i < cores; ++i)\n {\n const int start = i * len;\n const int end = i == cores - 1 ? rangeEnd : start + len;\n active[i] = start_range_task(poolIndex, start, end, rangeTask);\n }\n }\n\n for (int i = 0; i < cores; ++i)\n active[i]->wait();\n\n rangeRunning = false;\n }\n\n pool_task* thread_pool::parallel_task(task_delegate&& genericTask) noexcept\n {\n { lock_guard lock{tasksMutex};\n for (unique_ptr& t : tasks)\n {\n pool_task* task = t.get();\n if (!task->running())\n {\n task->run_generic(move(genericTask));\n return task;\n }\n }\n }\n \n \/\/ create and run a new task atomically\n auto t = make_unique();\n auto* task = t.get();\n task->max_idle_time(taskMaxIdleTime);\n task->run_generic(move(genericTask));\n\n lock_guard lock{tasksMutex};\n tasks.emplace_back(move(t));\n return task;\n }\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2009 Dan Leinir Turthra Jensen \n * Copyright (c) 2009 Kim Jung Nissen \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 \"btnode.h\"\n\n#include \n\nbtNode::btNode(QObject* parent)\n : QObject(parent)\n , m_name(\"\")\n , m_description(\"\")\n , m_className(\"\")\n , m_type(btNode::UnusableNodeType)\n , m_currentChildIndex(0)\n , m_currentChildStatus(btNode::None)\n{\n}\n\nbtNode::~btNode()\n{\n\tqDeleteAll(m_children);\n\tm_children.clear();\n}\n\nvoid btNode::setName(QString name)\n{\n\tm_name = name;\n}\n\nQString btNode::name()\n{\n\treturn m_name;\n}\n\nvoid btNode::setDescription(QString description)\n{\n\tm_description = description;\n}\n\nQString btNode::description()\n{\n\treturn m_description; \n}\n\nvoid btNode::setClassName(QString className)\n{\n\tm_className = className;\n}\n\nQString btNode::className()\n{\n\treturn m_className;\n}\n\t\nvoid btNode::setType(btNode::nodeType type)\n{\n\tm_type = type;\n}\n\nbtNode::nodeType btNode::type()\n{\n\treturn m_type;\n}\n\nint btNode::childCount()\n{\n\treturn m_children.count();\n}\n\nvoid btNode::appendChild(btNode* child) \n{\n\tm_children.append(child);\n\t\/\/has to be in the list, before this function is called\n\tappendingChild(m_children.count()-1);\n}\n\nbtNode* btNode::child(int index)\n{\n\treturn m_children[index];\n}\n\nbtNode::status btNode::run(btCharacter * self)\n{\n qDebug() << \"The btNode \" << className() << \" has either not been registered or implemented\";\n\treturn btNode::Failed;\n}\n\nvoid btNode::setCurrentChildStatus(status nodeStatus)\n{\n\tm_currentChildStatus = nodeStatus;\n}\n\nbtNode::status btNode::currentChildStatus()\n{\n\treturn m_currentChildStatus;\n}\n\nbtNode* btNode::currentChild()\n{\n\treturn m_children[m_currentChildIndex];\n}\n\nvoid btNode::setCurrentChildIndex(int index)\n{\n\tm_currentChildIndex = index;\n}\n\nint btNode::currentChildIndex()\n{\n\treturn m_currentChildIndex;\n}\n\nbtNode::status btNode::runChild()\n{\n\treturn btNode::RunningChild;\n}\n\nbtNode::status btNode::runChild(int index)\n{\n\tm_currentChildIndex = index;\n\treturn btNode::RunningChild;\n}\n\nbtNode* btNode::parentNode()\n{\n\treturn m_parent;\n}\n\nvoid btNode::setParentNode(btNode* parent)\n{\n\tm_parent = parent;\n}\n\nvoid btNode::removeChild(int index)\n{\n\tremovingChild(index);\n\tm_children.removeAt(index);\n}\n\nvoid btNode::removeChild(btNode* child)\n{\n\tfor (int i = 0; i < m_children.count(); i++)\n\t{\n\t\tif(m_children.at(i) == child)\n\t\t{\n\t\t\tremoveChild(i);\n\t\t}\n\t}\n}\n\nvoid btNode::doneParsingChildren()\n{\n\tchildrenAdded();\n}\n\nint btNode::nextChildIndex()\n{\n\tif(m_currentChildStatus == btNode::None)\n\t\treturn m_currentChildIndex;\n\treturn ++m_currentChildIndex;\n}\n\t\nvoid btNode::insertChild(int index, btNode* child)\n{\n\tm_children.insert(index, child);\n appendingChild(index);\n}\n\nint btNode::childIndex(btNode * child)\n{\n for (int i = 0; i < m_children.count(); i++)\n {\n if(m_children.at(i) == child)\n {\n return i;\n }\n }\n \n return -1;\n}\n\n#include \"btnode.moc\"\nInitialize the parent btNode to 0 instead of letting it dangling it\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2009 Dan Leinir Turthra Jensen \n * Copyright (c) 2009 Kim Jung Nissen \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 \"btnode.h\"\n\n#include \n\nbtNode::btNode(QObject* parent)\n : QObject(parent)\n , m_name(\"\")\n , m_description(\"\")\n , m_className(\"\")\n , m_type(btNode::UnusableNodeType)\n , m_parent(0)\n , m_currentChildIndex(0)\n , m_currentChildStatus(btNode::None)\n{\n}\n\nbtNode::~btNode()\n{\n\tqDeleteAll(m_children);\n\tm_children.clear();\n}\n\nvoid btNode::setName(QString name)\n{\n\tm_name = name;\n}\n\nQString btNode::name()\n{\n\treturn m_name;\n}\n\nvoid btNode::setDescription(QString description)\n{\n\tm_description = description;\n}\n\nQString btNode::description()\n{\n\treturn m_description; \n}\n\nvoid btNode::setClassName(QString className)\n{\n\tm_className = className;\n}\n\nQString btNode::className()\n{\n\treturn m_className;\n}\n\t\nvoid btNode::setType(btNode::nodeType type)\n{\n\tm_type = type;\n}\n\nbtNode::nodeType btNode::type()\n{\n\treturn m_type;\n}\n\nint btNode::childCount()\n{\n\treturn m_children.count();\n}\n\nvoid btNode::appendChild(btNode* child) \n{\n\tm_children.append(child);\n\t\/\/has to be in the list, before this function is called\n\tappendingChild(m_children.count()-1);\n}\n\nbtNode* btNode::child(int index)\n{\n\treturn m_children[index];\n}\n\nbtNode::status btNode::run(btCharacter * self)\n{\n qDebug() << \"The btNode \" << className() << \" has either not been registered or implemented\";\n\treturn btNode::Failed;\n}\n\nvoid btNode::setCurrentChildStatus(status nodeStatus)\n{\n\tm_currentChildStatus = nodeStatus;\n}\n\nbtNode::status btNode::currentChildStatus()\n{\n\treturn m_currentChildStatus;\n}\n\nbtNode* btNode::currentChild()\n{\n\treturn m_children[m_currentChildIndex];\n}\n\nvoid btNode::setCurrentChildIndex(int index)\n{\n\tm_currentChildIndex = index;\n}\n\nint btNode::currentChildIndex()\n{\n\treturn m_currentChildIndex;\n}\n\nbtNode::status btNode::runChild()\n{\n\treturn btNode::RunningChild;\n}\n\nbtNode::status btNode::runChild(int index)\n{\n\tm_currentChildIndex = index;\n\treturn btNode::RunningChild;\n}\n\nbtNode* btNode::parentNode()\n{\n\treturn m_parent;\n}\n\nvoid btNode::setParentNode(btNode* parent)\n{\n\tm_parent = parent;\n}\n\nvoid btNode::removeChild(int index)\n{\n\tremovingChild(index);\n\tm_children.removeAt(index);\n}\n\nvoid btNode::removeChild(btNode* child)\n{\n\tfor (int i = 0; i < m_children.count(); i++)\n\t{\n\t\tif(m_children.at(i) == child)\n\t\t{\n\t\t\tremoveChild(i);\n\t\t}\n\t}\n}\n\nvoid btNode::doneParsingChildren()\n{\n\tchildrenAdded();\n}\n\nint btNode::nextChildIndex()\n{\n\tif(m_currentChildStatus == btNode::None)\n\t\treturn m_currentChildIndex;\n\treturn ++m_currentChildIndex;\n}\n\t\nvoid btNode::insertChild(int index, btNode* child)\n{\n\tm_children.insert(index, child);\n appendingChild(index);\n}\n\nint btNode::childIndex(btNode * child)\n{\n for (int i = 0; i < m_children.count(); i++)\n {\n if(m_children.at(i) == child)\n {\n return i;\n }\n }\n \n return -1;\n}\n\n#include \"btnode.moc\"\n<|endoftext|>"} {"text":"PWGPP-426 - adding non persitent data members +bug fix+ new variables<|endoftext|>"} {"text":"\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *\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.1 of the License, or (at *\n* your 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 License *\n* 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*******************************************************************************\n* SOFA :: Plugins *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include \"Binding_Base.h\"\n#include \"Binding_Data.h\"\n#include \"Binding_DisplayFlagsData.h\"\n#include \"Binding_OptionsGroupData.h\"\n#include \"Binding_Link.h\"\n\n#include \n#include \n#include \nusing namespace sofa::core::objectmodel;\n#include \n\n#include \"PythonFactory.h\"\n\nextern \"C\" PyObject * Base_findData(PyObject *self, PyObject *args )\n{\n Base* obj=((PySPtr*)self)->object.get();\n char *dataName;\n if (!PyArg_ParseTuple(args, \"s\",&dataName))\n {\n msg_error(\"Base_findData\") <<\"Base_findData_impl not a string\\n\";\n Py_RETURN_NONE;\n }\n BaseData * data = obj->findData(dataName);\n if (!data)\n {\n if( obj->hasField(dataName) )\n msg_error(\"Base_findData\")<<\"object '\"<getName()<<\"' has a field '\"<getName()<<\"' does no have a field '\"<writeDatas(s,\";\");\n msg_error(\"Base_findData\")<*)self)->object.get();\n char *linkName;\n if (!PyArg_ParseTuple(args, \"s\",&linkName))\n Py_RETURN_NONE;\n BaseLink * link = obj->findLink(linkName);\n if (!link)\n {\n if( obj->hasField(linkName) )\n msg_error(\"Base_findLink\")<<\"object '\"<getName()<<\"' has a field '\"<getName()<<\"' does no have a field '\"<writeDatas(s,\";\");\n msg_error(\"Base_findLink\")<(((PySPtr*)o)->object.get());\n char *attrName = PyString_AsString(attr_name);\n\/\/ printf(\"Base_GetAttr type=%s name=%s attrName=%s\\n\",obj->getClassName().c_str(),obj->getName().c_str(),attrName);\n\n \/\/ see if a Data field has this name...\n BaseData * data = obj->findData(attrName);\n if (data) return GetDataValuePython(data); \/\/ we have our data... let's create the right Python type....\n\n \/\/ see if a Link has this name...\n BaseLink * link = obj->findLink(attrName);\n if (link) return GetLinkValuePython(link); \/\/ we have our link... let's create the right Python type....\n\n \/\/ printf(\"Base_GetAttr ERROR data not found - type=%s name=%s attrName=%s\\n\",obj->getClassName().c_str(),obj->getName().c_str(),attrName);\n return PyObject_GenericGetAttr(o,attr_name);\n}\n\nextern \"C\" int Base_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v)\n{\n \/\/ attribute does not exist: see if a Data field has this name...\n Base* obj=down_cast(((PySPtr*)o)->object.get());\n char *attrName = PyString_AsString(attr_name);\n\n\/\/ printf(\"Base_SetAttr name=%s\\n\",dataName);\n BaseData * data = obj->findData(attrName);\n if (data)\n {\n if (SetDataValuePython(data,v)) return 0;\n else return -1;\n }\n\n BaseLink * link = obj->findLink(attrName);\n if (link)\n {\n if (SetLinkValuePython(link,v)) return 0;\n else return -1;\n }\n\n return PyObject_GenericSetAttr(o,attr_name,v);\n}\n\nextern \"C\" PyObject * Base_getClassName(PyObject * self, PyObject * \/*args*\/)\n{\n \/\/ BaseNode is not bound in SofaPython, so getPathName is bound in Node instead\n Base* node = ((PySPtr*)self)->object.get();\n\n return PyString_FromString(node->getClassName().c_str());\n}\n\nextern \"C\" PyObject * Base_getTemplateName(PyObject * self, PyObject * \/*args*\/)\n{\n \/\/ BaseNode is not bound in SofaPython, so getPathName is bound in Node instead\n Base* node = ((PySPtr*)self)->object.get();\n\n return PyString_FromString(node->getTemplateName().c_str());\n}\n\nextern \"C\" PyObject * Base_getName(PyObject * self, PyObject * \/*args*\/)\n{\n \/\/ BaseNode is not bound in SofaPython, so getPathName is bound in Node instead\n Base* node = ((PySPtr*)self)->object.get();\n\n return PyString_FromString(node->getName().c_str());\n}\n\nextern \"C\" PyObject * Base_getDataFields(PyObject *self, PyObject * \/*args*\/)\n{\n Base * component = ((PySPtr*)self)->object.get();\n\n if(!component)\n {\n PyErr_BadArgument();\n Py_RETURN_NONE;\n }\n\n const sofa::helper::vector dataFields = component->getDataFields();\n\n PyObject * pyDict = PyDict_New();\n for (size_t i=0; igetName().c_str()), GetDataValuePython(dataFields[i]));\n\n return pyDict;\n}\n\nSP_CLASS_METHODS_BEGIN(Base)\nSP_CLASS_METHOD(Base,findData)\nSP_CLASS_METHOD(Base,findLink)\nSP_CLASS_METHOD(Base,getClassName)\nSP_CLASS_METHOD(Base,getTemplateName)\nSP_CLASS_METHOD(Base,getName)\nSP_CLASS_METHOD(Base,getDataFields)\nSP_CLASS_METHODS_END\n\n\/\/SP_CLASS_DATA_ATTRIBUTE(Base,name)\n\nSP_CLASS_ATTRS_BEGIN(Base)\n\/\/SP_CLASS_ATTR(Base,name)\nSP_CLASS_ATTRS_END\n\nSP_CLASS_TYPE_BASE_SPTR_ATTR_GETATTR(Base,Base)\n[SofaPython] cleaning\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *\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.1 of the License, or (at *\n* your 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 License *\n* 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*******************************************************************************\n* SOFA :: Plugins *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include \"Binding_Base.h\"\n#include \"Binding_Data.h\"\n#include \"Binding_Link.h\"\n\n#include \n#include \n#include \nusing namespace sofa::core::objectmodel;\n#include \n\n#include \"PythonFactory.h\"\n\nextern \"C\" PyObject * Base_findData(PyObject *self, PyObject *args )\n{\n Base* obj=((PySPtr*)self)->object.get();\n char *dataName;\n if (!PyArg_ParseTuple(args, \"s\",&dataName))\n {\n msg_error(\"Base_findData\") <<\"Base_findData_impl not a string\\n\";\n Py_RETURN_NONE;\n }\n BaseData * data = obj->findData(dataName);\n if (!data)\n {\n if( obj->hasField(dataName) )\n msg_error(\"Base_findData\")<<\"object '\"<getName()<<\"' has a field '\"<getName()<<\"' does no have a field '\"<writeDatas(s,\";\");\n msg_error(\"Base_findData\")<*)self)->object.get();\n char *linkName;\n if (!PyArg_ParseTuple(args, \"s\",&linkName))\n Py_RETURN_NONE;\n BaseLink * link = obj->findLink(linkName);\n if (!link)\n {\n if( obj->hasField(linkName) )\n msg_error(\"Base_findLink\")<<\"object '\"<getName()<<\"' has a field '\"<getName()<<\"' does no have a field '\"<writeDatas(s,\";\");\n msg_error(\"Base_findLink\")<(((PySPtr*)o)->object.get());\n char *attrName = PyString_AsString(attr_name);\n\/\/ printf(\"Base_GetAttr type=%s name=%s attrName=%s\\n\",obj->getClassName().c_str(),obj->getName().c_str(),attrName);\n\n \/\/ see if a Data field has this name...\n BaseData * data = obj->findData(attrName);\n if (data) return GetDataValuePython(data); \/\/ we have our data... let's create the right Python type....\n\n \/\/ see if a Link has this name...\n BaseLink * link = obj->findLink(attrName);\n if (link) return GetLinkValuePython(link); \/\/ we have our link... let's create the right Python type....\n\n \/\/ printf(\"Base_GetAttr ERROR data not found - type=%s name=%s attrName=%s\\n\",obj->getClassName().c_str(),obj->getName().c_str(),attrName);\n return PyObject_GenericGetAttr(o,attr_name);\n}\n\nextern \"C\" int Base_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v)\n{\n \/\/ attribute does not exist: see if a Data field has this name...\n Base* obj=down_cast(((PySPtr*)o)->object.get());\n char *attrName = PyString_AsString(attr_name);\n\n\/\/ printf(\"Base_SetAttr name=%s\\n\",dataName);\n BaseData * data = obj->findData(attrName);\n if (data)\n {\n if (SetDataValuePython(data,v)) return 0;\n else return -1;\n }\n\n BaseLink * link = obj->findLink(attrName);\n if (link)\n {\n if (SetLinkValuePython(link,v)) return 0;\n else return -1;\n }\n\n return PyObject_GenericSetAttr(o,attr_name,v);\n}\n\nextern \"C\" PyObject * Base_getClassName(PyObject * self, PyObject * \/*args*\/)\n{\n \/\/ BaseNode is not bound in SofaPython, so getPathName is bound in Node instead\n Base* node = ((PySPtr*)self)->object.get();\n\n return PyString_FromString(node->getClassName().c_str());\n}\n\nextern \"C\" PyObject * Base_getTemplateName(PyObject * self, PyObject * \/*args*\/)\n{\n \/\/ BaseNode is not bound in SofaPython, so getPathName is bound in Node instead\n Base* node = ((PySPtr*)self)->object.get();\n\n return PyString_FromString(node->getTemplateName().c_str());\n}\n\nextern \"C\" PyObject * Base_getName(PyObject * self, PyObject * \/*args*\/)\n{\n \/\/ BaseNode is not bound in SofaPython, so getPathName is bound in Node instead\n Base* node = ((PySPtr*)self)->object.get();\n\n return PyString_FromString(node->getName().c_str());\n}\n\nextern \"C\" PyObject * Base_getDataFields(PyObject *self, PyObject * \/*args*\/)\n{\n Base * component = ((PySPtr*)self)->object.get();\n\n if(!component)\n {\n PyErr_BadArgument();\n Py_RETURN_NONE;\n }\n\n const sofa::helper::vector dataFields = component->getDataFields();\n\n PyObject * pyDict = PyDict_New();\n for (size_t i=0; igetName().c_str()), GetDataValuePython(dataFields[i]));\n\n return pyDict;\n}\n\nSP_CLASS_METHODS_BEGIN(Base)\nSP_CLASS_METHOD(Base,findData)\nSP_CLASS_METHOD(Base,findLink)\nSP_CLASS_METHOD(Base,getClassName)\nSP_CLASS_METHOD(Base,getTemplateName)\nSP_CLASS_METHOD(Base,getName)\nSP_CLASS_METHOD(Base,getDataFields)\nSP_CLASS_METHODS_END\n\n\/\/SP_CLASS_DATA_ATTRIBUTE(Base,name)\n\nSP_CLASS_ATTRS_BEGIN(Base)\n\/\/SP_CLASS_ATTR(Base,name)\nSP_CLASS_ATTRS_END\n\nSP_CLASS_TYPE_BASE_SPTR_ATTR_GETATTR(Base,Base)\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2014 The Bitcoin 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 \"key.h\"\n\n#include \"crypto\/sha2.h\"\n#include \"eccryptoverify.h\"\n#include \"pubkey.h\"\n#include \"random.h\"\n\n#include \n#include \"ecwrapper.h\"\n\n\/\/! anonymous namespace\nnamespace {\n\nclass CSecp256k1Init {\npublic:\n CSecp256k1Init() {\n secp256k1_start(SECP256K1_START_SIGN);\n }\n ~CSecp256k1Init() {\n secp256k1_stop();\n }\n};\nstatic CSecp256k1Init instance_of_csecp256k1;\n\n} \/\/ anon namespace\n\nbool CKey::Check(const unsigned char *vch) {\n return eccrypto::Check(vch);\n}\n\nvoid CKey::MakeNewKey(bool fCompressedIn) {\n do {\n GetRandBytes(vch, sizeof(vch));\n } while (!Check(vch));\n fValid = true;\n fCompressed = fCompressedIn;\n}\n\nbool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) {\n if (!secp256k1_ec_privkey_import((unsigned char*)begin(), &privkey[0], privkey.size()))\n return false;\n fCompressed = fCompressedIn;\n fValid = true;\n return true;\n}\n\nCPrivKey CKey::GetPrivKey() const {\n assert(fValid);\n CPrivKey privkey;\n int privkeylen, ret;\n privkey.resize(279);\n privkeylen = 279;\n ret = secp256k1_ec_privkey_export(begin(), (unsigned char*)&privkey[0], &privkeylen, fCompressed);\n assert(ret);\n privkey.resize(privkeylen);\n return privkey;\n}\n\nCPubKey CKey::GetPubKey() const {\n assert(fValid);\n CPubKey result;\n int clen = 65;\n int ret = secp256k1_ec_pubkey_create((unsigned char*)result.begin(), &clen, begin(), fCompressed);\n assert((int)result.size() == clen);\n assert(ret);\n assert(result.IsValid());\n return result;\n}\n\nbool CKey::Sign(const uint256 &hash, std::vector& vchSig) const {\n if (!fValid)\n return false;\n vchSig.resize(72);\n int nSigLen = 72;\n CKey nonce;\n do {\n nonce.MakeNewKey(true);\n if (secp256k1_ecdsa_sign((const unsigned char*)&hash, 32, (unsigned char*)&vchSig[0], &nSigLen, begin(), nonce.begin()))\n break;\n } while(true);\n vchSig.resize(nSigLen);\n return true;\n}\n\nbool CKey::VerifyPubKey(const CPubKey& pubkey) const {\n if (pubkey.IsCompressed() != fCompressed) {\n return false;\n }\n unsigned char rnd[8];\n std::string str = \"Bitcoin key verification\\n\";\n GetRandBytes(rnd, sizeof(rnd));\n uint256 hash;\n CHash256().Write((unsigned char*)str.data(), str.size()).Write(rnd, sizeof(rnd)).Finalize((unsigned char*)&hash);\n std::vector vchSig;\n Sign(hash, vchSig);\n return pubkey.Verify(hash, vchSig);\n}\n\nbool CKey::SignCompact(const uint256 &hash, std::vector& vchSig) const {\n if (!fValid)\n return false;\n vchSig.resize(65);\n int rec = -1;\n CKey nonce;\n do {\n nonce.MakeNewKey(true);\n if (secp256k1_ecdsa_sign_compact((const unsigned char*)&hash, 32, &vchSig[1], begin(), nonce.begin(), &rec))\n break;\n } while(true);\n assert(rec != -1);\n vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);\n return true;\n}\n\nbool CKey::Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck=false) {\n if (!secp256k1_ec_privkey_import((unsigned char*)begin(), &privkey[0], privkey.size()))\n return false;\n fCompressed = vchPubKey.IsCompressed();\n fValid = true;\n\n if (fSkipCheck)\n return true;\n\n return VerifyPubKey(vchPubKey);\n}\n\nbool CKey::Derive(CKey& keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const {\n assert(IsValid());\n assert(IsCompressed());\n unsigned char out[64];\n LockObject(out);\n if ((nChild >> 31) == 0) {\n CPubKey pubkey = GetPubKey();\n assert(pubkey.begin() + 33 == pubkey.end());\n BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, out);\n } else {\n assert(begin() + 32 == end());\n BIP32Hash(cc, nChild, 0, begin(), out);\n }\n memcpy(ccChild, out+32, 32);\n memcpy((unsigned char*)keyChild.begin(), begin(), 32);\n bool ret = secp256k1_ec_privkey_tweak_add((unsigned char*)keyChild.begin(), out);\n UnlockObject(out);\n keyChild.fCompressed = true;\n keyChild.fValid = ret;\n return ret;\n}\n\nbool CExtKey::Derive(CExtKey &out, unsigned int nChild) const {\n out.nDepth = nDepth + 1;\n CKeyID id = key.GetPubKey().GetID();\n memcpy(&out.vchFingerprint[0], &id, 4);\n out.nChild = nChild;\n return key.Derive(out.key, out.vchChainCode, nChild, vchChainCode);\n}\n\nvoid CExtKey::SetMaster(const unsigned char *seed, unsigned int nSeedLen) {\n static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};\n unsigned char out[64];\n LockObject(out);\n CHMAC_SHA512(hashkey, sizeof(hashkey)).Write(seed, nSeedLen).Finalize(out);\n key.Set(&out[0], &out[32], true);\n memcpy(vchChainCode, &out[32], 32);\n UnlockObject(out);\n nDepth = 0;\n nChild = 0;\n memset(vchFingerprint, 0, sizeof(vchFingerprint));\n}\n\nCExtPubKey CExtKey::Neuter() const {\n CExtPubKey ret;\n ret.nDepth = nDepth;\n memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4);\n ret.nChild = nChild;\n ret.pubkey = key.GetPubKey();\n memcpy(&ret.vchChainCode[0], &vchChainCode[0], 32);\n return ret;\n}\n\nvoid CExtKey::Encode(unsigned char code[74]) const {\n code[0] = nDepth;\n memcpy(code+1, vchFingerprint, 4);\n code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;\n code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;\n memcpy(code+9, vchChainCode, 32);\n code[41] = 0;\n assert(key.size() == 32);\n memcpy(code+42, key.begin(), 32);\n}\n\nvoid CExtKey::Decode(const unsigned char code[74]) {\n nDepth = code[0];\n memcpy(vchFingerprint, code+1, 4);\n nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];\n memcpy(vchChainCode, code+9, 32);\n key.Set(code+42, code+74, true);\n}\n\nbool ECC_InitSanityCheck() {\n return CECKey::SanityCheck();\n}\nAdd key generation\/verification to ECC sanity check\/\/ Copyright (c) 2009-2014 The Bitcoin 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 \"key.h\"\n\n#include \"crypto\/sha2.h\"\n#include \"eccryptoverify.h\"\n#include \"pubkey.h\"\n#include \"random.h\"\n\n#include \n#include \"ecwrapper.h\"\n\n\/\/! anonymous namespace\nnamespace {\n\nclass CSecp256k1Init {\npublic:\n CSecp256k1Init() {\n secp256k1_start(SECP256K1_START_SIGN);\n }\n ~CSecp256k1Init() {\n secp256k1_stop();\n }\n};\nstatic CSecp256k1Init instance_of_csecp256k1;\n\n} \/\/ anon namespace\n\nbool CKey::Check(const unsigned char *vch) {\n return eccrypto::Check(vch);\n}\n\nvoid CKey::MakeNewKey(bool fCompressedIn) {\n do {\n GetRandBytes(vch, sizeof(vch));\n } while (!Check(vch));\n fValid = true;\n fCompressed = fCompressedIn;\n}\n\nbool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) {\n if (!secp256k1_ec_privkey_import((unsigned char*)begin(), &privkey[0], privkey.size()))\n return false;\n fCompressed = fCompressedIn;\n fValid = true;\n return true;\n}\n\nCPrivKey CKey::GetPrivKey() const {\n assert(fValid);\n CPrivKey privkey;\n int privkeylen, ret;\n privkey.resize(279);\n privkeylen = 279;\n ret = secp256k1_ec_privkey_export(begin(), (unsigned char*)&privkey[0], &privkeylen, fCompressed);\n assert(ret);\n privkey.resize(privkeylen);\n return privkey;\n}\n\nCPubKey CKey::GetPubKey() const {\n assert(fValid);\n CPubKey result;\n int clen = 65;\n int ret = secp256k1_ec_pubkey_create((unsigned char*)result.begin(), &clen, begin(), fCompressed);\n assert((int)result.size() == clen);\n assert(ret);\n assert(result.IsValid());\n return result;\n}\n\nbool CKey::Sign(const uint256 &hash, std::vector& vchSig) const {\n if (!fValid)\n return false;\n vchSig.resize(72);\n int nSigLen = 72;\n CKey nonce;\n do {\n nonce.MakeNewKey(true);\n if (secp256k1_ecdsa_sign((const unsigned char*)&hash, 32, (unsigned char*)&vchSig[0], &nSigLen, begin(), nonce.begin()))\n break;\n } while(true);\n vchSig.resize(nSigLen);\n return true;\n}\n\nbool CKey::VerifyPubKey(const CPubKey& pubkey) const {\n if (pubkey.IsCompressed() != fCompressed) {\n return false;\n }\n unsigned char rnd[8];\n std::string str = \"Bitcoin key verification\\n\";\n GetRandBytes(rnd, sizeof(rnd));\n uint256 hash;\n CHash256().Write((unsigned char*)str.data(), str.size()).Write(rnd, sizeof(rnd)).Finalize((unsigned char*)&hash);\n std::vector vchSig;\n Sign(hash, vchSig);\n return pubkey.Verify(hash, vchSig);\n}\n\nbool CKey::SignCompact(const uint256 &hash, std::vector& vchSig) const {\n if (!fValid)\n return false;\n vchSig.resize(65);\n int rec = -1;\n CKey nonce;\n do {\n nonce.MakeNewKey(true);\n if (secp256k1_ecdsa_sign_compact((const unsigned char*)&hash, 32, &vchSig[1], begin(), nonce.begin(), &rec))\n break;\n } while(true);\n assert(rec != -1);\n vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);\n return true;\n}\n\nbool CKey::Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck=false) {\n if (!secp256k1_ec_privkey_import((unsigned char*)begin(), &privkey[0], privkey.size()))\n return false;\n fCompressed = vchPubKey.IsCompressed();\n fValid = true;\n\n if (fSkipCheck)\n return true;\n\n return VerifyPubKey(vchPubKey);\n}\n\nbool CKey::Derive(CKey& keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const {\n assert(IsValid());\n assert(IsCompressed());\n unsigned char out[64];\n LockObject(out);\n if ((nChild >> 31) == 0) {\n CPubKey pubkey = GetPubKey();\n assert(pubkey.begin() + 33 == pubkey.end());\n BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, out);\n } else {\n assert(begin() + 32 == end());\n BIP32Hash(cc, nChild, 0, begin(), out);\n }\n memcpy(ccChild, out+32, 32);\n memcpy((unsigned char*)keyChild.begin(), begin(), 32);\n bool ret = secp256k1_ec_privkey_tweak_add((unsigned char*)keyChild.begin(), out);\n UnlockObject(out);\n keyChild.fCompressed = true;\n keyChild.fValid = ret;\n return ret;\n}\n\nbool CExtKey::Derive(CExtKey &out, unsigned int nChild) const {\n out.nDepth = nDepth + 1;\n CKeyID id = key.GetPubKey().GetID();\n memcpy(&out.vchFingerprint[0], &id, 4);\n out.nChild = nChild;\n return key.Derive(out.key, out.vchChainCode, nChild, vchChainCode);\n}\n\nvoid CExtKey::SetMaster(const unsigned char *seed, unsigned int nSeedLen) {\n static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};\n unsigned char out[64];\n LockObject(out);\n CHMAC_SHA512(hashkey, sizeof(hashkey)).Write(seed, nSeedLen).Finalize(out);\n key.Set(&out[0], &out[32], true);\n memcpy(vchChainCode, &out[32], 32);\n UnlockObject(out);\n nDepth = 0;\n nChild = 0;\n memset(vchFingerprint, 0, sizeof(vchFingerprint));\n}\n\nCExtPubKey CExtKey::Neuter() const {\n CExtPubKey ret;\n ret.nDepth = nDepth;\n memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4);\n ret.nChild = nChild;\n ret.pubkey = key.GetPubKey();\n memcpy(&ret.vchChainCode[0], &vchChainCode[0], 32);\n return ret;\n}\n\nvoid CExtKey::Encode(unsigned char code[74]) const {\n code[0] = nDepth;\n memcpy(code+1, vchFingerprint, 4);\n code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;\n code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;\n memcpy(code+9, vchChainCode, 32);\n code[41] = 0;\n assert(key.size() == 32);\n memcpy(code+42, key.begin(), 32);\n}\n\nvoid CExtKey::Decode(const unsigned char code[74]) {\n nDepth = code[0];\n memcpy(vchFingerprint, code+1, 4);\n nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];\n memcpy(vchChainCode, code+9, 32);\n key.Set(code+42, code+74, true);\n}\n\nbool ECC_InitSanityCheck() {\n#if !defined(USE_SECP256K1)\n if (!CECKey::SanityCheck()) {\n return false;\n }\n#endif\n CKey key;\n key.MakeNewKey(true);\n CPubKey pubkey = key.GetPubKey();\n return key.VerifyPubKey(pubkey);\n}\n<|endoftext|>"} {"text":"\n#ifndef V4R_OCTREE_VOXELCENTROID_CONTAINER_HPP\n#define V4R_OCTREE_VOXELCENTROID_CONTAINER_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace pcl\n{\n namespace octree\n {\n \/** \\brief @b Octree pointcloud voxel centroid leaf node class\n * \\note This class implements a leaf node that calculates the mean centroid of PointXYZRGB points added this octree container.\n *\/\n template\n class OctreeVoxelCentroidContainerXYZRGB : public OctreeContainerBase\n {\n public:\n \/** \\brief Class initialization. *\/\n OctreeVoxelCentroidContainerXYZRGB ()\n {\n this->reset();\n }\n\n \/** \\brief Empty class deconstructor. *\/\n virtual ~OctreeVoxelCentroidContainerXYZRGB ()\n {\n }\n\n \/** \\brief deep copy function *\/\n virtual OctreeVoxelCentroidContainerXYZRGB *\n deepCopy () const\n {\n return (new OctreeVoxelCentroidContainerXYZRGB (*this));\n }\n\n \/** \\brief Equal comparison operator - set to false\n *\/\n \/\/ param[in] OctreeVoxelCentroidContainerXYZRGB to compare with\n virtual bool operator==(const OctreeContainerBase&) const\n {\n return ( false );\n }\n\n \/** \\brief Add new point to voxel.\n * \\param[in] new_point the new point to add \n *\/\n void \n addPoint (const PointT& new_point)\n {\n using namespace pcl::common;\n\n ++point_counter_;\n\n pt_[0] += double(new_point.x);\n pt_[1] += double(new_point.y);\n pt_[2] += double(new_point.z);\n r_ += unsigned(new_point.r);\n g_ += unsigned(new_point.g);\n b_ += unsigned(new_point.b);\n }\n\n \/** \\brief Calculate centroid of voxel.\n * \\param[out] centroid_arg the resultant centroid of the voxel \n *\/\n void \n getCentroid (PointT& centroid_arg) const\n {\n using namespace pcl::common;\n\n if (point_counter_)\n {\n centroid_arg.getVector3fMap() = (pt_ \/ static_cast (point_counter_)).cast();\n centroid_arg.r = static_cast(r_ \/ point_counter_);\n centroid_arg.g = static_cast(g_ \/ point_counter_);\n centroid_arg.b = static_cast(b_ \/ point_counter_);\n }\n else\n {\n centroid_arg.x = std::numeric_limits::quiet_NaN();\n centroid_arg.y = std::numeric_limits::quiet_NaN();\n centroid_arg.z = std::numeric_limits::quiet_NaN();\n centroid_arg.r = 0;\n centroid_arg.g = 0;\n centroid_arg.b = 0;\n }\n }\n\n \/** \\brief Reset leaf container. *\/\n virtual void \n reset ()\n {\n using namespace pcl::common;\n\n point_counter_ = 0;\n pt_ = Eigen::Vector3d(0.,0.,0.);\n r_ = g_ = b_ = 0;\n }\n\n private:\n unsigned int point_counter_;\n Eigen::Vector3d pt_;\n unsigned r_, g_, b_;\n };\n\n }\n}\n\n#endif\n\nAdd missing 'template' keyword (causes clang compilation error)\n#ifndef V4R_OCTREE_VOXELCENTROID_CONTAINER_HPP\n#define V4R_OCTREE_VOXELCENTROID_CONTAINER_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace pcl\n{\n namespace octree\n {\n \/** \\brief @b Octree pointcloud voxel centroid leaf node class\n * \\note This class implements a leaf node that calculates the mean centroid of PointXYZRGB points added this octree container.\n *\/\n template\n class OctreeVoxelCentroidContainerXYZRGB : public OctreeContainerBase\n {\n public:\n \/** \\brief Class initialization. *\/\n OctreeVoxelCentroidContainerXYZRGB ()\n {\n this->reset();\n }\n\n \/** \\brief Empty class deconstructor. *\/\n virtual ~OctreeVoxelCentroidContainerXYZRGB ()\n {\n }\n\n \/** \\brief deep copy function *\/\n virtual OctreeVoxelCentroidContainerXYZRGB *\n deepCopy () const\n {\n return (new OctreeVoxelCentroidContainerXYZRGB (*this));\n }\n\n \/** \\brief Equal comparison operator - set to false\n *\/\n \/\/ param[in] OctreeVoxelCentroidContainerXYZRGB to compare with\n virtual bool operator==(const OctreeContainerBase&) const\n {\n return ( false );\n }\n\n \/** \\brief Add new point to voxel.\n * \\param[in] new_point the new point to add \n *\/\n void \n addPoint (const PointT& new_point)\n {\n using namespace pcl::common;\n\n ++point_counter_;\n\n pt_[0] += double(new_point.x);\n pt_[1] += double(new_point.y);\n pt_[2] += double(new_point.z);\n r_ += unsigned(new_point.r);\n g_ += unsigned(new_point.g);\n b_ += unsigned(new_point.b);\n }\n\n \/** \\brief Calculate centroid of voxel.\n * \\param[out] centroid_arg the resultant centroid of the voxel \n *\/\n void \n getCentroid (PointT& centroid_arg) const\n {\n using namespace pcl::common;\n\n if (point_counter_)\n {\n centroid_arg.getVector3fMap() = (pt_ \/ static_cast (point_counter_)).template cast();\n centroid_arg.r = static_cast(r_ \/ point_counter_);\n centroid_arg.g = static_cast(g_ \/ point_counter_);\n centroid_arg.b = static_cast(b_ \/ point_counter_);\n }\n else\n {\n centroid_arg.x = std::numeric_limits::quiet_NaN();\n centroid_arg.y = std::numeric_limits::quiet_NaN();\n centroid_arg.z = std::numeric_limits::quiet_NaN();\n centroid_arg.r = 0;\n centroid_arg.g = 0;\n centroid_arg.b = 0;\n }\n }\n\n \/** \\brief Reset leaf container. *\/\n virtual void \n reset ()\n {\n using namespace pcl::common;\n\n point_counter_ = 0;\n pt_ = Eigen::Vector3d(0.,0.,0.);\n r_ = g_ = b_ = 0;\n }\n\n private:\n unsigned int point_counter_;\n Eigen::Vector3d pt_;\n unsigned r_, g_, b_;\n };\n\n }\n}\n\n#endif\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n *\/\n\n#include \n#include \"log_p.hpp\"\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#ifdef QI_USE_BOOST_LOCK_FREE\n# include \n#else\n# include \n#endif\n#include \n\n#define RTLOG_BUFFERS (128)\n\n#define CAT_SIZE 64\n#define FILE_SIZE 128\n#define FUNC_SIZE 64\n#define LOG_SIZE 2048\n\nnamespace qi {\n namespace detail {\n void cutCat(const char* category, char* res)\n {\n int categorySize = strlen(category);\n if (categorySize < CATSIZEMAX)\n {\n memset(res, ' ', CATSIZEMAX);\n memcpy(res, category, strlen(category));\n }\n else\n {\n memset(res, '.', CATSIZEMAX);\n memcpy(res + 3, category + categorySize - CATSIZEMAX + 3, CATSIZEMAX - 3);\n }\n res[CATSIZEMAX] = '\\0';\n }\n\n std::string logline(const os::timeval date,\n const char *category,\n const char *msg,\n const char *file,\n const char *fct,\n const int line)\n {\n char fixedCategory[CATSIZEMAX + 1];\n fixedCategory[CATSIZEMAX] = '\\0';\n cutCat(category, fixedCategory);\n\n int tid = qi::os::gettid();\n std::stringstream logline;\n\n std::stringstream ss;\n ss << date.tv_sec << \".\"\n << std::setw(7) << std::setfill('0') << date.tv_usec;\n\n switch (qi::log::context())\n {\n case 1:\n logline << fixedCategory << \": \";\n break;\n case 2:\n logline << ss.str() << \" \";\n break;\n case 3:\n if (line != 0)\n logline << file << \"(\" << line << \") \";\n break;\n case 4:\n logline << ss.str() << \" \" << fixedCategory << \": \";\n break;\n case 5:\n if (line == 0)\n logline << ss.str() << \" \";\n else\n logline << ss.str() << \" \" << file << \"(\" << line << \") \";\n break;\n case 6:\n if (line == 0)\n logline << fixedCategory << \": \";\n else\n logline << fixedCategory << \": \" << file << \"(\" << line << \")\";\n break;\n case 7:\n if (line == 0)\n logline << ss.str() << \" \" << tid << \" \" << fixedCategory << \": \" << fct << \" \";\n else\n logline << ss.str() << \" \" << tid << \" \" << fixedCategory << \": \" << file << \"(\" << line << \") \" << fct << \" \";\n break;\n default:\n break;\n }\n logline << msg;\n\n return logline.str();\n }\n }\n\n namespace log {\n\n typedef struct sPrivateLog\n {\n LogLevel _logLevel;\n char _category[CAT_SIZE];\n char _file[FILE_SIZE];\n char _function[FUNC_SIZE];\n int _line;\n char _log[LOG_SIZE];\n qi::os::timeval _date;\n } privateLog;\n\n class Log\n {\n public:\n inline Log();\n inline ~Log();\n\n void run();\n void printLog();\n\n public:\n bool LogInit;\n boost::thread LogThread;\n boost::mutex LogWriteLock;\n boost::mutex LogHandlerLock;\n boost::condition_variable LogReadyCond;\n\n#ifdef QI_USE_BOOST_LOCK_FREE\n boost::lockfree::fifo logs;\n#else\n std::queue logs;\n#endif\n std::map logHandlers;\n };\n\n static LogLevel _glVerbosity = qi::log::info;\n static int _glContext = false;\n static bool _glSyncLog = false;\n static bool _glInit = false;\n static ConsoleLogHandler *_glConsoleLogHandler;\n\n static Log *LogInstance;\n static privateLog LogBuffer[RTLOG_BUFFERS];\n static volatile unsigned long LogPush = 0;\n\n static class DefaultLogInit\n {\n public:\n DefaultLogInit()\n {\n _glInit = false;\n qi::log::init();\n }\n\n ~DefaultLogInit()\n {\n qi::log::destroy();\n };\n } synchLog;\n\n void Log::printLog()\n {\n privateLog* pl;\n boost::mutex::scoped_lock lock(LogHandlerLock);\n#ifdef QI_USE_BOOST_LOCK_FREE\n while (logs.dequeue(&pl))\n {\n\n#else\n while ((pl = logs.front()) != 0)\n {\n logs.pop();\n#endif\n if (!logHandlers.empty())\n {\n std::map::iterator it;\n for (it = logHandlers.begin();\n it != logHandlers.end(); ++it)\n {\n (*it).second(pl->_logLevel,\n pl->_date,\n pl->_category,\n pl->_log,\n pl->_file,\n pl->_function,\n pl->_line);\n }\n }\n }\n }\n\n void Log::run()\n {\n while (LogInit)\n {\n {\n boost::mutex::scoped_lock lock(LogWriteLock);\n LogReadyCond.wait(lock);\n }\n\n printLog();\n }\n }\n\n inline Log::Log()\n {\n LogInit = true;\n if (!_glSyncLog)\n LogThread = boost::thread(&Log::run, this);\n };\n\n inline Log::~Log()\n {\n if (!LogInit)\n return;\n\n LogInit = false;\n\n if (!_glSyncLog)\n {\n LogThread.interrupt();\n LogThread.join();\n\n printLog();\n }\n }\n\n static void my_strcpy_log(char *dst, const char *src, int len) {\n if (!src)\n src = \"(null)\";\n\n int messSize = strlen(src);\n \/\/ check if the last char is a \\n\n if (src[messSize - 1] == '\\n')\n {\n \/\/ Get the size to memcpy (don't forget we need 1 space more for \\0)\n int strSize = messSize < len ? messSize : len - 1;\n #ifndef _WIN32\n memcpy(dst, src, strSize);\n #else\n memcpy_s(dst, len, src, strSize);\n #endif\n dst[strSize] = 0;\n return;\n }\n\n #ifndef _WIN32\n \/\/ Get the size to memcpy (we need 2 spaces more for \\n\\0)\n int strSize = messSize < len - 1 ? messSize : len - 2;\n memcpy(dst, src, strSize);\n dst[strSize] = '\\n';\n dst[strSize + 1] = '\\0';\n #else\n \/\/ Get the size to memcpy (we need 3 spaces more for \\r\\n\\0)\n int strSize = messSize < len - 2 ? messSize : len - 3;\n memcpy_s(dst, len, src, strSize);\n dst[strSize] = '\\r';\n dst[strSize + 1] = '\\n';\n dst[strSize + 2] = '\\0';\n #endif\n }\n\n static void my_strcpy(char *dst, const char *src, int len) {\n if (!src)\n src = \"(null)\";\n #ifdef _MSV_VER\n strncpy_s(dst, len, src, _TRUNCATE);\n #else\n strncpy(dst, src, len);\n dst[len - 1] = 0;\n #endif\n }\n\n void init(qi::log::LogLevel verb,\n int ctx,\n bool synchronous)\n {\n setVerbosity(verb);\n setContext(ctx);\n setSynchronousLog(synchronous);\n\n if (_glInit)\n destroy();\n\n _glConsoleLogHandler = new ConsoleLogHandler;\n LogInstance = new Log;\n addLogHandler(\"consoleloghandler\",\n boost::bind(&ConsoleLogHandler::log,\n _glConsoleLogHandler,\n _1, _2, _3, _4, _5, _6, _7));\n _glInit = true;\n }\n\n void destroy()\n {\n if (!_glInit)\n return;\n _glInit = false;\n LogInstance->printLog();\n delete _glConsoleLogHandler;\n _glConsoleLogHandler = 0;\n delete LogInstance;\n LogInstance = 0;\n }\n\n void flush()\n {\n if (_glInit)\n LogInstance->printLog();\n }\n\n void log(const LogLevel verb,\n const char *category,\n const char *msg,\n const char *file,\n const char *fct,\n const int line)\n {\n if (!LogInstance)\n return;\n if (!LogInstance->LogInit)\n return;\n\n int tmpRtLogPush = ++LogPush % RTLOG_BUFFERS;\n privateLog* pl = &(LogBuffer[tmpRtLogPush]);\n\n qi::os::timeval tv;\n qi::os::gettimeofday(&tv);\n\n pl->_logLevel = verb;\n pl->_line = line;\n pl->_date.tv_sec = tv.tv_sec;\n pl->_date.tv_usec = tv.tv_usec;\n\n my_strcpy(pl->_category, category, CAT_SIZE);\n my_strcpy(pl->_file, file, FILE_SIZE);\n my_strcpy(pl->_function, fct, FUNC_SIZE);\n my_strcpy_log(pl->_log, msg, LOG_SIZE);\n\n if (_glSyncLog)\n {\n if (!LogInstance->logHandlers.empty())\n {\n std::map::iterator it;\n for (it = LogInstance->logHandlers.begin();\n it != LogInstance->logHandlers.end(); ++it)\n {\n (*it).second(pl->_logLevel,\n pl->_date,\n pl->_category,\n pl->_log,\n pl->_file,\n pl->_function,\n pl->_line);\n }\n }\n }\n else\n {\n#ifdef QI_USE_BOOST_LOCK_FREE\n LogInstance->logs.enqueue(pl);\n#else\n LogInstance->logs.push(pl);\n#endif\n LogInstance->LogReadyCond.notify_one();\n }\n }\n\n void addLogHandler(const std::string& name, logFuncHandler fct)\n {\n if (!LogInstance)\n return;\n boost::mutex::scoped_lock l(LogInstance->LogHandlerLock);\n LogInstance->logHandlers[name] = fct;\n }\n\n void removeLogHandler(const std::string& name)\n {\n if (!LogInstance)\n return;\n boost::mutex::scoped_lock l(LogInstance->LogHandlerLock);\n LogInstance->logHandlers.erase(name);\n }\n\n LogLevel stringToLogLevel(const char* verb)\n {\n std::string v(verb);\n if (v == \"silent\")\n return qi::log::silent;\n if (v == \"fatal\")\n return qi::log::fatal;\n if (v == \"error\")\n return qi::log::error;\n if (v == \"warning\")\n return qi::log::warning;\n if (v == \"info\")\n return qi::log::info;\n if (v == \"verbose\")\n return qi::log::verbose;\n if (v == \"debug\")\n return qi::log::debug;\n return qi::log::info;\n }\n\n const char *logLevelToString(const LogLevel verb)\n {\n static const char *sverb[] = {\n \"[SILENT]\", \/\/ never shown\n \"[FATAL]\",\n \"[ERROR]\",\n \"[WARN ]\",\n \"[INFO ]\",\n \"[VERB ]\",\n \"[DEBUG]\"\n };\n return sverb[verb];\n }\n\n void setVerbosity(const LogLevel lv)\n {\n const char *verbose = std::getenv(\"VERBOSE\");\n\n if (verbose)\n _glVerbosity = (LogLevel)atoi(verbose);\n else\n _glVerbosity = lv;\n\n qiLogVerbose(\"qi.log\") << \"Verbosity set to \" << _glVerbosity;\n };\n\n LogLevel verbosity()\n {\n return _glVerbosity;\n };\n\n void setContext(int ctx)\n {\n const char *context = std::getenv(\"CONTEXT\");\n\n if (context)\n _glContext = (atoi(context));\n else\n _glContext = ctx;\n\n qiLogVerbose(\"qi.log\") << \"Context set to \" << _glContext;\n };\n\n int context()\n {\n return _glContext;\n };\n\n void setSynchronousLog(bool sync)\n {\n _glSyncLog = sync;\n };\n\n static void _setVerbosityInt(int v)\n {\n setVerbosity((LogLevel)v);\n }\n\n static void _setVerbose(bool on)\n {\n if (on)\n setVerbosity(verbose);\n }\n static void _setDebug(bool on)\n {\n if (on)\n setVerbosity(debug);\n }\n static void _quiet(bool on)\n {\n if (on)\n removeLogHandler(\"consoleloghandler\");\n }\n\n _QI_COMMAND_LINE_OPTIONS(\n \"Logging options\",\n (\"verbose,v\", bool_switch()->notifier(&_setVerbose), \"Set verbose verbosity.\")\n (\"debug,d\", bool_switch()->notifier(&_setDebug), \"Set debug verbosity.\")\n (\"quiet,q\", bool_switch()->notifier(&_quiet), \"Do not show logs on console.\")\n (\"context,c\", value()->notifier(&setContext), \"Show context logs: [0-7] (0: none, 1: categories, 2: date, 3: file+line, 4: date+categories, 5: date+line+file, 6: categories+line+file, 7: all (date+categories+line+file+function)).\")\n (\"synchronous-log\", bool_switch()->notifier(boost::bind(&setSynchronousLog, true)), \"Activate synchronous logs.\")\n (\"log-level,L\", value()->notifier(&_setVerbosityInt), \"Change the log minimum level: [0-6] (0: silent, 1: fatal, 2: error, 3: warning, 4: info, 5: verbose, 6: debug). Default: 4 (info)\")\n )\n\n } \/\/ namespace log\n} \/\/ namespace qi\n\nAdd logging on Android\/*\n * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n *\/\n\n#include \n#include \"log_p.hpp\"\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#ifdef QI_USE_BOOST_LOCK_FREE\n# include \n#else\n# include \n#endif\n#include \n\n#ifdef ANDROID\n# include \n#endif\n\n#define RTLOG_BUFFERS (128)\n\n#define CAT_SIZE 64\n#define FILE_SIZE 128\n#define FUNC_SIZE 64\n#define LOG_SIZE 2048\n\nnamespace qi {\n namespace detail {\n void cutCat(const char* category, char* res)\n {\n int categorySize = strlen(category);\n if (categorySize < CATSIZEMAX)\n {\n memset(res, ' ', CATSIZEMAX);\n memcpy(res, category, strlen(category));\n }\n else\n {\n memset(res, '.', CATSIZEMAX);\n memcpy(res + 3, category + categorySize - CATSIZEMAX + 3, CATSIZEMAX - 3);\n }\n res[CATSIZEMAX] = '\\0';\n }\n\n std::string logline(const os::timeval date,\n const char *category,\n const char *msg,\n const char *file,\n const char *fct,\n const int line)\n {\n char fixedCategory[CATSIZEMAX + 1];\n fixedCategory[CATSIZEMAX] = '\\0';\n cutCat(category, fixedCategory);\n\n int tid = qi::os::gettid();\n std::stringstream logline;\n\n std::stringstream ss;\n ss << date.tv_sec << \".\"\n << std::setw(7) << std::setfill('0') << date.tv_usec;\n\n switch (qi::log::context())\n {\n case 1:\n logline << fixedCategory << \": \";\n break;\n case 2:\n logline << ss.str() << \" \";\n break;\n case 3:\n if (line != 0)\n logline << file << \"(\" << line << \") \";\n break;\n case 4:\n logline << ss.str() << \" \" << fixedCategory << \": \";\n break;\n case 5:\n if (line == 0)\n logline << ss.str() << \" \";\n else\n logline << ss.str() << \" \" << file << \"(\" << line << \") \";\n break;\n case 6:\n if (line == 0)\n logline << fixedCategory << \": \";\n else\n logline << fixedCategory << \": \" << file << \"(\" << line << \")\";\n break;\n case 7:\n if (line == 0)\n logline << ss.str() << \" \" << tid << \" \" << fixedCategory << \": \" << fct << \" \";\n else\n logline << ss.str() << \" \" << tid << \" \" << fixedCategory << \": \" << file << \"(\" << line << \") \" << fct << \" \";\n break;\n default:\n break;\n }\n logline << msg;\n\n return logline.str();\n }\n }\n\n namespace log {\n\n typedef struct sPrivateLog\n {\n LogLevel _logLevel;\n char _category[CAT_SIZE];\n char _file[FILE_SIZE];\n char _function[FUNC_SIZE];\n int _line;\n char _log[LOG_SIZE];\n qi::os::timeval _date;\n } privateLog;\n\n class Log\n {\n public:\n inline Log();\n inline ~Log();\n\n void run();\n void printLog();\n\n public:\n bool LogInit;\n boost::thread LogThread;\n boost::mutex LogWriteLock;\n boost::mutex LogHandlerLock;\n boost::condition_variable LogReadyCond;\n\n#ifdef QI_USE_BOOST_LOCK_FREE\n boost::lockfree::fifo logs;\n#else\n std::queue logs;\n#endif\n std::map logHandlers;\n };\n\n static LogLevel _glVerbosity = qi::log::info;\n static int _glContext = false;\n static bool _glSyncLog = false;\n static bool _glInit = false;\n static ConsoleLogHandler *_glConsoleLogHandler;\n\n static Log *LogInstance;\n static privateLog LogBuffer[RTLOG_BUFFERS];\n static volatile unsigned long LogPush = 0;\n\n static class DefaultLogInit\n {\n public:\n DefaultLogInit()\n {\n _glInit = false;\n qi::log::init();\n }\n\n ~DefaultLogInit()\n {\n qi::log::destroy();\n };\n } synchLog;\n\n void Log::printLog()\n {\n privateLog* pl;\n boost::mutex::scoped_lock lock(LogHandlerLock);\n#ifdef QI_USE_BOOST_LOCK_FREE\n while (logs.dequeue(&pl))\n {\n\n#else\n while ((pl = logs.front()) != 0)\n {\n logs.pop();\n#endif\n if (!logHandlers.empty())\n {\n std::map::iterator it;\n for (it = logHandlers.begin();\n it != logHandlers.end(); ++it)\n {\n (*it).second(pl->_logLevel,\n pl->_date,\n pl->_category,\n pl->_log,\n pl->_file,\n pl->_function,\n pl->_line);\n }\n }\n }\n }\n\n void Log::run()\n {\n while (LogInit)\n {\n {\n boost::mutex::scoped_lock lock(LogWriteLock);\n LogReadyCond.wait(lock);\n }\n\n printLog();\n }\n }\n\n inline Log::Log()\n {\n LogInit = true;\n if (!_glSyncLog)\n LogThread = boost::thread(&Log::run, this);\n };\n\n inline Log::~Log()\n {\n if (!LogInit)\n return;\n\n LogInit = false;\n\n if (!_glSyncLog)\n {\n LogThread.interrupt();\n LogThread.join();\n\n printLog();\n }\n }\n\n static void my_strcpy_log(char *dst, const char *src, int len) {\n if (!src)\n src = \"(null)\";\n\n int messSize = strlen(src);\n \/\/ check if the last char is a \\n\n if (src[messSize - 1] == '\\n')\n {\n \/\/ Get the size to memcpy (don't forget we need 1 space more for \\0)\n int strSize = messSize < len ? messSize : len - 1;\n #ifndef _WIN32\n memcpy(dst, src, strSize);\n #else\n memcpy_s(dst, len, src, strSize);\n #endif\n dst[strSize] = 0;\n return;\n }\n\n #ifndef _WIN32\n \/\/ Get the size to memcpy (we need 2 spaces more for \\n\\0)\n int strSize = messSize < len - 1 ? messSize : len - 2;\n memcpy(dst, src, strSize);\n dst[strSize] = '\\n';\n dst[strSize + 1] = '\\0';\n #else\n \/\/ Get the size to memcpy (we need 3 spaces more for \\r\\n\\0)\n int strSize = messSize < len - 2 ? messSize : len - 3;\n memcpy_s(dst, len, src, strSize);\n dst[strSize] = '\\r';\n dst[strSize + 1] = '\\n';\n dst[strSize + 2] = '\\0';\n #endif\n }\n\n static void my_strcpy(char *dst, const char *src, int len) {\n if (!src)\n src = \"(null)\";\n #ifdef _MSV_VER\n strncpy_s(dst, len, src, _TRUNCATE);\n #else\n strncpy(dst, src, len);\n dst[len - 1] = 0;\n #endif\n }\n\n void init(qi::log::LogLevel verb,\n int ctx,\n bool synchronous)\n {\n setVerbosity(verb);\n setContext(ctx);\n setSynchronousLog(synchronous);\n\n if (_glInit)\n destroy();\n\n _glConsoleLogHandler = new ConsoleLogHandler;\n LogInstance = new Log;\n addLogHandler(\"consoleloghandler\",\n boost::bind(&ConsoleLogHandler::log,\n _glConsoleLogHandler,\n _1, _2, _3, _4, _5, _6, _7));\n _glInit = true;\n }\n\n void destroy()\n {\n if (!_glInit)\n return;\n _glInit = false;\n LogInstance->printLog();\n delete _glConsoleLogHandler;\n _glConsoleLogHandler = 0;\n delete LogInstance;\n LogInstance = 0;\n }\n\n void flush()\n {\n if (_glInit)\n LogInstance->printLog();\n }\n\n void log(const LogLevel verb,\n const char *category,\n const char *msg,\n const char *file,\n const char *fct,\n const int line)\n {\n #ifdef ANDROID\n std::map _conv;\n\n _conv[silent] = ANDROID_LOG_SILENT;\n _conv[fatal] = ANDROID_LOG_FATAL;\n _conv[error] = ANDROID_LOG_ERROR;\n _conv[warning] = ANDROID_LOG_WARN;\n _conv[info] = ANDROID_LOG_INFO;\n _conv[verbose] = ANDROID_LOG_VERBOSE;\n _conv[debug] = ANDROID_LOG_DEBUG;\n\n __android_log_print(_conv[verb], category, msg);\n return;\n #endif\n\n if (!LogInstance)\n return;\n if (!LogInstance->LogInit)\n return;\n\n int tmpRtLogPush = ++LogPush % RTLOG_BUFFERS;\n privateLog* pl = &(LogBuffer[tmpRtLogPush]);\n\n qi::os::timeval tv;\n qi::os::gettimeofday(&tv);\n\n pl->_logLevel = verb;\n pl->_line = line;\n pl->_date.tv_sec = tv.tv_sec;\n pl->_date.tv_usec = tv.tv_usec;\n\n my_strcpy(pl->_category, category, CAT_SIZE);\n my_strcpy(pl->_file, file, FILE_SIZE);\n my_strcpy(pl->_function, fct, FUNC_SIZE);\n my_strcpy_log(pl->_log, msg, LOG_SIZE);\n\n if (_glSyncLog)\n {\n if (!LogInstance->logHandlers.empty())\n {\n std::map::iterator it;\n for (it = LogInstance->logHandlers.begin();\n it != LogInstance->logHandlers.end(); ++it)\n {\n (*it).second(pl->_logLevel,\n pl->_date,\n pl->_category,\n pl->_log,\n pl->_file,\n pl->_function,\n pl->_line);\n }\n }\n }\n else\n {\n#ifdef QI_USE_BOOST_LOCK_FREE\n LogInstance->logs.enqueue(pl);\n#else\n LogInstance->logs.push(pl);\n#endif\n LogInstance->LogReadyCond.notify_one();\n }\n }\n\n void addLogHandler(const std::string& name, logFuncHandler fct)\n {\n if (!LogInstance)\n return;\n boost::mutex::scoped_lock l(LogInstance->LogHandlerLock);\n LogInstance->logHandlers[name] = fct;\n }\n\n void removeLogHandler(const std::string& name)\n {\n if (!LogInstance)\n return;\n boost::mutex::scoped_lock l(LogInstance->LogHandlerLock);\n LogInstance->logHandlers.erase(name);\n }\n\n LogLevel stringToLogLevel(const char* verb)\n {\n std::string v(verb);\n if (v == \"silent\")\n return qi::log::silent;\n if (v == \"fatal\")\n return qi::log::fatal;\n if (v == \"error\")\n return qi::log::error;\n if (v == \"warning\")\n return qi::log::warning;\n if (v == \"info\")\n return qi::log::info;\n if (v == \"verbose\")\n return qi::log::verbose;\n if (v == \"debug\")\n return qi::log::debug;\n return qi::log::info;\n }\n\n const char *logLevelToString(const LogLevel verb)\n {\n static const char *sverb[] = {\n \"[SILENT]\", \/\/ never shown\n \"[FATAL]\",\n \"[ERROR]\",\n \"[WARN ]\",\n \"[INFO ]\",\n \"[VERB ]\",\n \"[DEBUG]\"\n };\n return sverb[verb];\n }\n\n void setVerbosity(const LogLevel lv)\n {\n const char *verbose = std::getenv(\"VERBOSE\");\n\n if (verbose)\n _glVerbosity = (LogLevel)atoi(verbose);\n else\n _glVerbosity = lv;\n\n qiLogVerbose(\"qi.log\") << \"Verbosity set to \" << _glVerbosity;\n };\n\n LogLevel verbosity()\n {\n return _glVerbosity;\n };\n\n void setContext(int ctx)\n {\n const char *context = std::getenv(\"CONTEXT\");\n\n if (context)\n _glContext = (atoi(context));\n else\n _glContext = ctx;\n\n qiLogVerbose(\"qi.log\") << \"Context set to \" << _glContext;\n };\n\n int context()\n {\n return _glContext;\n };\n\n void setSynchronousLog(bool sync)\n {\n _glSyncLog = sync;\n };\n\n static void _setVerbosityInt(int v)\n {\n setVerbosity((LogLevel)v);\n }\n\n static void _setVerbose(bool on)\n {\n if (on)\n setVerbosity(verbose);\n }\n static void _setDebug(bool on)\n {\n if (on)\n setVerbosity(debug);\n }\n static void _quiet(bool on)\n {\n if (on)\n removeLogHandler(\"consoleloghandler\");\n }\n\n _QI_COMMAND_LINE_OPTIONS(\n \"Logging options\",\n (\"verbose,v\", bool_switch()->notifier(&_setVerbose), \"Set verbose verbosity.\")\n (\"debug,d\", bool_switch()->notifier(&_setDebug), \"Set debug verbosity.\")\n (\"quiet,q\", bool_switch()->notifier(&_quiet), \"Do not show logs on console.\")\n (\"context,c\", value()->notifier(&setContext), \"Show context logs: [0-7] (0: none, 1: categories, 2: date, 3: file+line, 4: date+categories, 5: date+line+file, 6: categories+line+file, 7: all (date+categories+line+file+function)).\")\n (\"synchronous-log\", bool_switch()->notifier(boost::bind(&setSynchronousLog, true)), \"Activate synchronous logs.\")\n (\"log-level,L\", value()->notifier(&_setVerbosityInt), \"Change the log minimum level: [0-6] (0: silent, 1: fatal, 2: error, 3: warning, 4: info, 5: verbose, 6: debug). Default: 4 (info)\")\n )\n\n } \/\/ namespace log\n} \/\/ namespace qi\n\n<|endoftext|>"} {"text":"#include \"myclass.hpp\"\n\n#include \"extern_templates.hpp\"\n\ntemplate \nclass TemplateClass {\npublic:\n TemplateClass () : value_(0.0) {}\n TemplateClass (const T& v) : value_(v) {}\n const T& GetValue (void) { return value_; }\n T value_;\n};\n\ntemplate class TemplateClass>;\n\nint main(int argc, char **argv) {\n \/\/ DELETE THESE. Used to suppress unused variable warnings.\n (void)argc;\n (void)argv;\n\n double d = 10;\n double c = add(d, d);\n d = c;\n\n TemplateClass> ti;\n ti.GetValue();\n\n jim::MyClass mc;\n\n jim::Baseclass *bc = new jim::Subclass1();\n bc->value0_ = 40;\n\n if (argc > 2) {\n mc.value_ = 40;\n }\n\n return 0;\n}\nbreaks on vector#include \n\n#include \"myclass.hpp\"\n\n#include \"extern_templates.hpp\"\n\ntemplate \nclass TemplateClass {\npublic:\n TemplateClass () : value_(0.0) {}\n TemplateClass (const T& v) : value_(v) {}\n const T& GetValue (void) { return value_; }\n T value_;\n};\n\ntemplate class TemplateClass>;\n\nint main(int argc, char **argv) {\n \/\/ DELETE THESE. Used to suppress unused variable warnings.\n (void)argc;\n (void)argv;\n\n double d = 10;\n double c = add(d, d);\n d = c;\n\n TemplateClass> ti;\n ti.GetValue();\n\n jim::MyClass mc;\n\n jim::Baseclass *bc = new jim::Subclass1();\n bc->value0_ = 40;\n\n if (argc > 2) {\n mc.value_ = 40;\n }\n\n std::vector ivec;\n ivec.push_back(10);\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"args.h\"\n#include \"ashuffle.h\"\n#include \"getpass.h\"\n#include \"load.h\"\n#include \"mpd_client.h\"\n#include \"shuffle.h\"\n\nusing namespace ashuffle;\n\nnamespace {\n\nstd::unique_ptr BuildLoader(mpd::MPD* mpd, const Options& opts) {\n if (opts.file_in != nullptr && opts.check_uris) {\n return std::make_unique(mpd, opts.ruleset, opts.group_by,\n opts.file_in);\n } else if (opts.file_in != nullptr) {\n return std::make_unique(opts.file_in);\n }\n\n return std::make_unique(mpd, opts.ruleset, opts.group_by);\n}\n\n} \/\/ namespace\n\nint main(int argc, const char* argv[]) {\n std::variant parse =\n Options::ParseFromC(*mpd::client::Parser(), argv, argc);\n if (ParseError* err = std::get_if(&parse); err != nullptr) {\n switch (err->type) {\n case ParseError::Type::kUnknown:\n std::cerr << \"unknown option parsing error. Please file a bug \"\n << \"at https:\/\/github.com\/joshkunz\/ashuffle\"\n << std::endl;\n break;\n case ParseError::Type::kHelp:\n \/\/ We always print the help, so just break here.\n break;\n case ParseError::Type::kGeneric:\n std::cerr << \"error: \" << err->msg << std::endl;\n break;\n default:\n assert(false && \"unreachable\");\n }\n std::cerr << DisplayHelp;\n exit(EXIT_FAILURE);\n }\n\n Options options = std::move(std::get(parse));\n\n if (!options.check_uris && !options.group_by.empty()) {\n std::cerr << \"-g\/--group-by not supported with no-check\" << std::endl;\n exit(EXIT_FAILURE);\n }\n\n std::function pass_f = [] {\n return GetPass(stdin, stdout, \"mpd password: \");\n };\n \/* attempt to connect to MPD *\/\n std::unique_ptr mpd =\n Connect(*mpd::client::Dialer(), options, pass_f);\n\n ShuffleChain songs((size_t)options.tweak.window_size);\n\n {\n \/\/ We construct the loader in a new scope, since loaders can\n \/\/ consume a lot of memory.\n std::unique_ptr loader = BuildLoader(mpd.get(), options);\n loader->Load(&songs);\n }\n\n \/\/ For integration testing, we sometimes just want to have ashuffle\n \/\/ dump the list of songs in its shuffle chain.\n if (options.test.print_all_songs_and_exit) {\n bool first = true;\n for (auto&& group : songs.Items()) {\n if (!first) {\n std::cout << \"---\" << std::endl;\n }\n first = false;\n for (auto&& song : group) {\n std::cout << song << std::endl;\n }\n }\n exit(EXIT_SUCCESS);\n }\n\n if (songs.Len() == 0) {\n std::cerr << \"Song pool is empty.\" << std::endl;\n exit(EXIT_FAILURE);\n }\n\n if (!options.group_by.empty()) {\n std::cout << absl::StrFormat(\"Picking from %u groups (%u songs).\",\n songs.Len(), songs.LenURIs())\n << std::endl;\n } else {\n std::cout << \"Picking random songs out of a pool of \" << songs.Len()\n << \".\" << std::endl;\n }\n\n \/* do the main action *\/\n if (options.queue_only) {\n size_t number_of_songs{};\n for (unsigned i = 0; i < options.queue_only; i++) {\n auto& picked_songs = songs.Pick();\n number_of_songs += picked_songs.size();\n mpd->Add(picked_songs);\n }\n\n \/* print number of songs or groups (and songs) added *\/\n std::cout << absl::StrFormat(\n \"Added %u %s%s\", options.queue_only,\n options.group_by.empty() ? \"song\" : \"group\",\n options.queue_only > 1 ? \"s\" : \"\");\n if (!options.group_by.empty()) {\n std::cout << absl::StrFormat(\" (%u songs)\", number_of_songs);\n }\n std::cout << \".\" << std::endl;\n\n } else {\n Loop(mpd.get(), &songs, options);\n }\n\n return 0;\n}\ncleanup: Fix nits in main.cc formatting.#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"args.h\"\n#include \"ashuffle.h\"\n#include \"getpass.h\"\n#include \"load.h\"\n#include \"mpd_client.h\"\n#include \"shuffle.h\"\n\nusing namespace ashuffle;\n\nnamespace {\n\nstd::unique_ptr BuildLoader(mpd::MPD* mpd, const Options& opts) {\n if (opts.file_in != nullptr && opts.check_uris) {\n return std::make_unique(mpd, opts.ruleset, opts.group_by,\n opts.file_in);\n } else if (opts.file_in != nullptr) {\n return std::make_unique(opts.file_in);\n }\n\n return std::make_unique(mpd, opts.ruleset, opts.group_by);\n}\n\n} \/\/ namespace\n\nint main(int argc, const char* argv[]) {\n std::variant parse =\n Options::ParseFromC(*mpd::client::Parser(), argv, argc);\n if (ParseError* err = std::get_if(&parse); err != nullptr) {\n switch (err->type) {\n case ParseError::Type::kUnknown:\n std::cerr << \"unknown option parsing error. Please file a bug \"\n << \"at https:\/\/github.com\/joshkunz\/ashuffle\"\n << std::endl;\n break;\n case ParseError::Type::kHelp:\n \/\/ We always print the help, so just break here.\n break;\n case ParseError::Type::kGeneric:\n std::cerr << \"error: \" << err->msg << std::endl;\n break;\n default:\n assert(false && \"unreachable\");\n }\n std::cerr << DisplayHelp;\n exit(EXIT_FAILURE);\n }\n\n Options options = std::move(std::get(parse));\n\n if (!options.check_uris && !options.group_by.empty()) {\n std::cerr << \"-g\/--group-by not supported with no-check\" << std::endl;\n exit(EXIT_FAILURE);\n }\n\n std::function pass_f = [] {\n return GetPass(stdin, stdout, \"mpd password: \");\n };\n \/* attempt to connect to MPD *\/\n std::unique_ptr mpd =\n Connect(*mpd::client::Dialer(), options, pass_f);\n\n ShuffleChain songs((size_t)options.tweak.window_size);\n\n {\n \/\/ We construct the loader in a new scope, since loaders can\n \/\/ consume a lot of memory.\n std::unique_ptr loader = BuildLoader(mpd.get(), options);\n loader->Load(&songs);\n }\n\n \/\/ For integration testing, we sometimes just want to have ashuffle\n \/\/ dump the list of songs in its shuffle chain.\n if (options.test.print_all_songs_and_exit) {\n bool first = true;\n for (auto&& group : songs.Items()) {\n if (!first) {\n std::cout << \"---\" << std::endl;\n }\n first = false;\n for (auto&& song : group) {\n std::cout << song << std::endl;\n }\n }\n exit(EXIT_SUCCESS);\n }\n\n if (songs.Len() == 0) {\n std::cerr << \"Song pool is empty.\" << std::endl;\n exit(EXIT_FAILURE);\n }\n\n if (!options.group_by.empty()) {\n std::cout << absl::StrFormat(\"Picking from %u groups (%u songs).\",\n songs.Len(), songs.LenURIs())\n << std::endl;\n } else {\n std::cout << \"Picking random songs out of a pool of \" << songs.Len()\n << \".\" << std::endl;\n }\n\n \/* do the main action *\/\n if (options.queue_only) {\n size_t number_of_songs;\n for (unsigned i = 0; i < options.queue_only; i++) {\n auto& picked_songs = songs.Pick();\n number_of_songs += picked_songs.size();\n mpd->Add(picked_songs);\n }\n\n \/* print number of songs or groups (and songs) added *\/\n std::cout << absl::StrFormat(\n \"Added %u %s%s\", options.queue_only,\n options.group_by.empty() ? \"song\" : \"group\",\n options.queue_only > 1 ? \"s\" : \"\");\n if (!options.group_by.empty()) {\n std::cout << absl::StrFormat(\" (%u songs)\", number_of_songs);\n }\n std::cout << \".\" << std::endl;\n } else {\n Loop(mpd.get(), &songs, options);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*!\n * \\cond FILEINFO\n ******************************************************************************\n * \\file main.cpp\n ******************************************************************************\n *\n * Copyright (C) ATS Advanced Telematic Systems GmbH GmbH, 2016\n *\n * \\author Moritz Klinger\n *\n ******************************************************************************\n *\n * \\brief The main file of the project.\n *\n *\n ******************************************************************************\n *\n * \\endcond\n *\/\n\n\/*****************************************************************************\/\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"channel.h\"\n#include \"commands.h\"\n#include \"config.h\"\n#include \"events.h\"\n#include \"eventsinterpreter.h\"\n#include \"logger.h\"\n#include \"sotahttpclient.h\"\n#ifdef WITH_GENIVI\n#include \"sotarviclient.h\"\n#endif\n\n#ifdef BUILD_OSTREE\n#include \"crypto.h\"\n#include \"ostree.h\"\n#include \"sotauptaneclient.h\"\n#endif\n\n#include \"utils.h\"\n\n#include \n\n\/*****************************************************************************\/\n\nnamespace bpo = boost::program_options;\n\nbpo::variables_map parse_options(int argc, char *argv[]) {\n bpo::options_description description(\"CommandLine Options\");\n \/\/ clang-format off\n description.add_options()\n (\"help,h\", \"help screen\")\n (\"version,v\", \"Current aktualizr version\")\n (\"loglevel\", bpo::value(), \"set log level 0-4 (trace, debug, warning, info, error)\")\n (\"config,c\", bpo::value()->required(), \"toml configuration file\")\n (\"gateway-http\", bpo::value(), \"enable the http gateway\")\n (\"gateway-rvi\", bpo::value(), \"enable the rvi gateway\")\n (\"gateway-socket\", bpo::value(), \"enable the socket gateway\")\n (\"gateway-dbus\", bpo::value(), \"enable the D-Bus gateway\")\n (\"dbus-system-bus\", \"Use the D-Bus system bus (rather than the session bus)\")\n (\"tls-server\", bpo::value(), \"url, used for auto provisioning\")\n (\"repo-server\", bpo::value(), \"url of the uptane repo repository\")\n (\"director-server\", bpo::value(), \"url of the uptane director repository\")\n (\"ostree-server\", bpo::value(), \"url of the ostree repository\")\n (\"primary-ecu-serial\", bpo::value(), \"serial number of primary ecu\")\n (\"primary-ecu-hardware-id\", bpo::value(), \"hardware id of primary ecu\")\n (\"disable-keyid-validation\", \"Disable keyid validation on client side\" )\n (\"poll-once\", \"Check for updates only once and exit\")\n (\"secondary-config\", bpo::value >()->composing(), \"set config for secondary\");\n \/\/ clang-format on\n\n bpo::variables_map vm;\n try {\n bpo::store(bpo::parse_command_line(argc, argv, description), vm);\n bpo::notify(vm);\n } catch (const bpo::required_option &ex) {\n if (vm.count(\"help\") != 0) {\n std::cout << description << '\\n';\n exit(EXIT_SUCCESS);\n }\n if (vm.count(\"version\") != 0) {\n std::cout << \"Current aktualizr version is: \" << AKTUALIZR_VERSION << \"\\n\";\n exit(EXIT_SUCCESS);\n }\n\n if (ex.get_option_name() == \"--config\") {\n std::cout << ex.get_option_name() << \" is missing.\\nYou have to provide a valid configuration \"\n \"file using toml format. See the example configuration file \"\n \"in config\/config.toml.example\"\n << std::endl;\n exit(EXIT_FAILURE);\n } else {\n \/\/ print the error and append the default commandline option description\n std::cout << ex.what() << std::endl << description;\n exit(EXIT_SUCCESS);\n }\n } catch (const bpo::error &ex) {\n \/\/ log boost error\n LOGGER_LOG(LVL_warning, \"boost command line option error: \" << ex.what());\n\n \/\/ print the error message to the standard output too, as the user provided\n \/\/ a non-supported commandline option\n std::cout << ex.what() << '\\n';\n\n \/\/ set the returnValue, thereby ctest will recognize\n \/\/ that something went wrong\n exit(EXIT_FAILURE);\n }\n\n return vm;\n}\n\n\/*****************************************************************************\/\nint main(int argc, char *argv[]) {\n std::srand(static_cast(std::time(0))); \/\/ seeds pseudo random generator with cuurent time\n\n \/\/ create and initialize the return value to zero (everything is OK)\n int return_value = EXIT_SUCCESS;\n\n loggerInit();\n if (sodium_init() == -1) {\n LOGGER_LOG(LVL_error, \"Unable to initialize libsodium\");\n return EXIT_FAILURE;\n }\n\n bpo::variables_map commandline_map = parse_options(argc, argv);\n\n \/\/ check for loglevel\n if (commandline_map.count(\"loglevel\") != 0) {\n \/\/ set the log level from command line option\n LoggerLevels severity = static_cast(commandline_map[\"loglevel\"].as());\n if (severity < LVL_minimum) {\n LOGGER_LOG(LVL_debug, \"Invalid log level\");\n severity = LVL_trace;\n }\n if (LVL_maximum < severity) {\n LOGGER_LOG(LVL_warning, \"Invalid log level\");\n severity = LVL_error;\n }\n loggerSetSeverity(severity);\n }\n\n \/\/ Initialize config with default values, the update with config, then with cmd\n std::string filename = commandline_map[\"config\"].as();\n Config config(filename, commandline_map);\n\n command::Channel *commands_channel = new command::Channel();\n event::Channel *events_channel = new event::Channel();\n\n EventsInterpreter events_interpreter(config, events_channel, commands_channel);\n \/\/ run events interpreter in background\n events_interpreter.interpret();\n\n if (config.gateway.rvi) {\n#ifdef WITH_GENIVI\n try {\n SotaRVIClient(config, events_channel).runForever(commands_channel);\n } catch (std::runtime_error e) {\n LOGGER_LOG(LVL_error, \"Missing RVI configurations: \" << e.what());\n exit(EXIT_FAILURE);\n }\n#else\n LOGGER_LOG(LVL_error, \"RVI support is not enabled\");\n return EXIT_FAILURE;\n#endif\n } else {\n if (config.core.auth_type == CERTIFICATE) {\n#ifdef BUILD_OSTREE\n\n SotaUptaneClient(config, events_channel).runForever(commands_channel);\n#endif\n } else {\n SotaHttpClient(config, events_channel).runForever(commands_channel);\n }\n }\n\n return return_value;\n}\nUse \/dev\/urandom instead of current time\/*!\n * \\cond FILEINFO\n ******************************************************************************\n * \\file main.cpp\n ******************************************************************************\n *\n * Copyright (C) ATS Advanced Telematic Systems GmbH GmbH, 2016\n *\n * \\author Moritz Klinger\n *\n ******************************************************************************\n *\n * \\brief The main file of the project.\n *\n *\n ******************************************************************************\n *\n * \\endcond\n *\/\n\n\/*****************************************************************************\/\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"channel.h\"\n#include \"commands.h\"\n#include \"config.h\"\n#include \"events.h\"\n#include \"eventsinterpreter.h\"\n#include \"logger.h\"\n#include \"sotahttpclient.h\"\n#ifdef WITH_GENIVI\n#include \"sotarviclient.h\"\n#endif\n\n#ifdef BUILD_OSTREE\n#include \"crypto.h\"\n#include \"ostree.h\"\n#include \"sotauptaneclient.h\"\n#endif\n\n#include \"utils.h\"\n\n#include \n\n\/*****************************************************************************\/\n\nnamespace bpo = boost::program_options;\n\nbpo::variables_map parse_options(int argc, char *argv[]) {\n bpo::options_description description(\"CommandLine Options\");\n \/\/ clang-format off\n description.add_options()\n (\"help,h\", \"help screen\")\n (\"version,v\", \"Current aktualizr version\")\n (\"loglevel\", bpo::value(), \"set log level 0-4 (trace, debug, warning, info, error)\")\n (\"config,c\", bpo::value()->required(), \"toml configuration file\")\n (\"gateway-http\", bpo::value(), \"enable the http gateway\")\n (\"gateway-rvi\", bpo::value(), \"enable the rvi gateway\")\n (\"gateway-socket\", bpo::value(), \"enable the socket gateway\")\n (\"gateway-dbus\", bpo::value(), \"enable the D-Bus gateway\")\n (\"dbus-system-bus\", \"Use the D-Bus system bus (rather than the session bus)\")\n (\"tls-server\", bpo::value(), \"url, used for auto provisioning\")\n (\"repo-server\", bpo::value(), \"url of the uptane repo repository\")\n (\"director-server\", bpo::value(), \"url of the uptane director repository\")\n (\"ostree-server\", bpo::value(), \"url of the ostree repository\")\n (\"primary-ecu-serial\", bpo::value(), \"serial number of primary ecu\")\n (\"primary-ecu-hardware-id\", bpo::value(), \"hardware id of primary ecu\")\n (\"disable-keyid-validation\", \"Disable keyid validation on client side\" )\n (\"poll-once\", \"Check for updates only once and exit\")\n (\"secondary-config\", bpo::value >()->composing(), \"set config for secondary\");\n \/\/ clang-format on\n\n bpo::variables_map vm;\n try {\n bpo::store(bpo::parse_command_line(argc, argv, description), vm);\n bpo::notify(vm);\n } catch (const bpo::required_option &ex) {\n if (vm.count(\"help\") != 0) {\n std::cout << description << '\\n';\n exit(EXIT_SUCCESS);\n }\n if (vm.count(\"version\") != 0) {\n std::cout << \"Current aktualizr version is: \" << AKTUALIZR_VERSION << \"\\n\";\n exit(EXIT_SUCCESS);\n }\n\n if (ex.get_option_name() == \"--config\") {\n std::cout << ex.get_option_name() << \" is missing.\\nYou have to provide a valid configuration \"\n \"file using toml format. See the example configuration file \"\n \"in config\/config.toml.example\"\n << std::endl;\n exit(EXIT_FAILURE);\n } else {\n \/\/ print the error and append the default commandline option description\n std::cout << ex.what() << std::endl << description;\n exit(EXIT_SUCCESS);\n }\n } catch (const bpo::error &ex) {\n \/\/ log boost error\n LOGGER_LOG(LVL_warning, \"boost command line option error: \" << ex.what());\n\n \/\/ print the error message to the standard output too, as the user provided\n \/\/ a non-supported commandline option\n std::cout << ex.what() << '\\n';\n\n \/\/ set the returnValue, thereby ctest will recognize\n \/\/ that something went wrong\n exit(EXIT_FAILURE);\n }\n\n return vm;\n}\n\n\/*****************************************************************************\/\nint main(int argc, char *argv[]) {\n char block[4];\n std::ifstream urandom(\"\/dev\/urandom\", std::ios::in | std::ios::binary);\n urandom.read(block, 4);\n urandom.close();\n std::srand(*(unsigned int *)block); \/\/ seeds pseudo random generator with random number\n\n \/\/ create and initialize the return value to zero (everything is OK)\n int return_value = EXIT_SUCCESS;\n\n loggerInit();\n if (sodium_init() == -1) {\n LOGGER_LOG(LVL_error, \"Unable to initialize libsodium\");\n return EXIT_FAILURE;\n }\n\n bpo::variables_map commandline_map = parse_options(argc, argv);\n\n \/\/ check for loglevel\n if (commandline_map.count(\"loglevel\") != 0) {\n \/\/ set the log level from command line option\n LoggerLevels severity = static_cast(commandline_map[\"loglevel\"].as());\n if (severity < LVL_minimum) {\n LOGGER_LOG(LVL_debug, \"Invalid log level\");\n severity = LVL_trace;\n }\n if (LVL_maximum < severity) {\n LOGGER_LOG(LVL_warning, \"Invalid log level\");\n severity = LVL_error;\n }\n loggerSetSeverity(severity);\n }\n\n \/\/ Initialize config with default values, the update with config, then with cmd\n std::string filename = commandline_map[\"config\"].as();\n Config config(filename, commandline_map);\n\n command::Channel *commands_channel = new command::Channel();\n event::Channel *events_channel = new event::Channel();\n\n EventsInterpreter events_interpreter(config, events_channel, commands_channel);\n \/\/ run events interpreter in background\n events_interpreter.interpret();\n\n if (config.gateway.rvi) {\n#ifdef WITH_GENIVI\n try {\n SotaRVIClient(config, events_channel).runForever(commands_channel);\n } catch (std::runtime_error e) {\n LOGGER_LOG(LVL_error, \"Missing RVI configurations: \" << e.what());\n exit(EXIT_FAILURE);\n }\n#else\n LOGGER_LOG(LVL_error, \"RVI support is not enabled\");\n return EXIT_FAILURE;\n#endif\n } else {\n if (config.core.auth_type == CERTIFICATE) {\n#ifdef BUILD_OSTREE\n\n SotaUptaneClient(config, events_channel).runForever(commands_channel);\n#endif\n } else {\n SotaHttpClient(config, events_channel).runForever(commands_channel);\n }\n }\n\n return return_value;\n}\n<|endoftext|>"} {"text":"\/* \n * File: main.cc\n * Author: collin\n *\n * Created on February 23, 2015, 10:23 AM\n *\/\n\n#include \n#include\n#include\n#include\n#include\n#include\"const.h\"\n#include\"StringSet.h\"\n#include\"StringPartitionSet.h\"\n\/\/#include \"Enumerator.h\"\n\nusing namespace cpb;\n\n\/*\n * \n *\/\nint main(int argc, char** argv)\n{\n unsigned int alphabetSize, length;\n if (argc != 3)\n {\n std::cerr << \"Usage `.\\\\string_partitions s n' where 0(argv[1]);\n length = boost::lexical_cast(argv[2]);\n } catch (boost::bad_lexical_cast e)\n {\n std::cerr << \"Usage `.\\\\enumerator s n' where 0 9)\n {\n std::cerr << \"Usage `.\\\\string_partitions s n' where 0 pairs;\n for (auto wordOne : baseSPS.strings().cset())\n {\n for (auto wordTwo : baseSPS.strings().cset())\n {\n if (wordOne < wordTwo)\n {\n StringSet pairString;\n pairString.insert(wordOne);\n pairString.insert(wordTwo);\n pairs.insert(pairString);\n }\n }\n }\n \n for(auto pair: pairs)\n {std::cout< partitions;\n partitions.insert(baseSPS);\n \n\n std::set workingPartitions;\n workingPartitions = partitions;\n\n std::cout<Will now count automata synchronising on strings of length 0 (there is only one).\/* \n * File: main.cc\n * Author: collin\n *\n * Created on February 23, 2015, 10:23 AM\n *\/\n\n#include \n#include\n#include\n#include\n#include\n#include\"const.h\"\n#include\"StringSet.h\"\n#include\"StringPartitionSet.h\"\n\/\/#include \"Enumerator.h\"\n\nusing namespace cpb;\n\n\/*\n * \n *\/\nint main(int argc, char** argv)\n{\n unsigned int alphabetSize, length;\n if (argc != 3)\n {\n std::cerr << \"Usage `.\\\\string_partitions s n' where 0(argv[1]);\n length = boost::lexical_cast(argv[2]);\n } catch (boost::bad_lexical_cast e)\n {\n std::cerr << \"Usage `.\\\\enumerator s n' where 0 9 || length<0)\n {\n std::cerr << \"Usage `.\\\\string_partitions s n' where 0 pairs;\n for (auto wordOne : baseSPS.strings().cset())\n {\n for (auto wordTwo : baseSPS.strings().cset())\n {\n if (wordOne < wordTwo)\n {\n StringSet pairString;\n pairString.insert(wordOne);\n pairString.insert(wordTwo);\n pairs.insert(pairString);\n }\n }\n }\n \n for(auto pair: pairs)\n {std::cout< partitions;\n partitions.insert(baseSPS);\n \n\n std::set workingPartitions;\n workingPartitions = partitions;\n\n std::cout<"} {"text":"#include \"assert.hh\"\n#include \"buffer.hh\"\n#include \"buffer_manager.hh\"\n#include \"buffer_utils.hh\"\n#include \"client_manager.hh\"\n#include \"color_registry.hh\"\n#include \"command_manager.hh\"\n#include \"commands.hh\"\n#include \"context.hh\"\n#include \"debug.hh\"\n#include \"event_manager.hh\"\n#include \"file.hh\"\n#include \"highlighters.hh\"\n#include \"hook_manager.hh\"\n#include \"ncurses.hh\"\n#include \"option_manager.hh\"\n#include \"keymap_manager.hh\"\n#include \"parameters_parser.hh\"\n#include \"register_manager.hh\"\n#include \"remote.hh\"\n#include \"shell_manager.hh\"\n#include \"string.hh\"\n#include \"window.hh\"\n\n#if defined(__APPLE__)\n#include \n#endif\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace Kakoune;\n\nvoid run_unit_tests();\n\nString runtime_directory()\n{\n char buffer[2048];\n#if defined(__linux__) || defined(__CYGWIN__)\n ssize_t res = readlink(\"\/proc\/self\/exe\", buffer, 2048);\n kak_assert(res != -1);\n buffer[res] = '\\0';\n#elif defined(__APPLE__)\n uint32_t bufsize = 2048;\n _NSGetExecutablePath(buffer, &bufsize);\n char* canonical_path = realpath(buffer, nullptr);\n strncpy(buffer, canonical_path, 2048);\n free(canonical_path);\n#else\n# error \"finding executable path is not implemented on this platform\"\n#endif\n char* ptr = strrchr(buffer, '\/');\n if (not ptr)\n throw runtime_error(\"unable to determine runtime directory\");\n return String(buffer, ptr) + \"\/..\/share\/kak\";\n}\n\nvoid register_env_vars()\n{\n static const struct {\n const char* name;\n String (*func)(StringView, const Context&);\n } env_vars[] = { {\n \"bufname\",\n [](StringView name, const Context& context)\n { return context.buffer().display_name(); }\n }, {\n \"buffile\",\n [](StringView name, const Context& context) -> String\n { return context.buffer().name(); }\n }, {\n \"timestamp\",\n [](StringView name, const Context& context)\n { return to_string(context.buffer().timestamp()); }\n }, {\n \"selection\",\n [](StringView name, const Context& context)\n { const Selection& sel = context.selections().main();\n return content(context.buffer(), sel); }\n }, {\n \"selections\",\n [](StringView name, const Context& context)\n { auto sels = context.selections_content();\n String res;\n for (size_t i = 0; i < sels.size(); ++i)\n {\n res += escape(sels[i], ':', '\\\\');\n if (i != sels.size() - 1)\n res += ':';\n }\n return res; }\n }, {\n \"runtime\",\n [](StringView name, const Context& context)\n { return runtime_directory(); }\n }, {\n \"opt_.+\",\n [](StringView name, const Context& context)\n { return context.options()[name.substr(4_byte)].get_as_string(); }\n }, {\n \"reg_.+\",\n [](StringView name, const Context& context) -> String\n { return RegisterManager::instance()[name[4]].values(context)[0]; }\n }, {\n \"client_env_.+\",\n [](StringView name, const Context& context) -> String\n { return context.client().get_env_var(name.substr(11_byte)); }\n }, {\n \"session\",\n [](StringView name, const Context& context) -> String\n { return Server::instance().session(); }\n }, {\n \"client\",\n [](StringView name, const Context& context) -> String\n { return context.name(); }\n }, {\n \"cursor_line\",\n [](StringView name, const Context& context)\n { return to_string(context.selections().main().cursor().line + 1); }\n }, {\n \"cursor_column\",\n [](StringView name, const Context& context)\n { return to_string(context.selections().main().cursor().column + 1); }\n }, {\n \"cursor_char_column\",\n [](StringView name, const Context& context)\n { auto coord = context.selections().main().cursor();\n return to_string(context.buffer()[coord.line].char_count_to(coord.column) + 1); }\n }, {\n \"selection_desc\",\n [](StringView name, const Context& context)\n { auto& sel = context.selections().main();\n auto beg = sel.min();\n return to_string(beg.line + 1) + ':' + to_string(beg.column + 1) + '+' +\n to_string((int)context.buffer().distance(beg, sel.max())+1); }\n }, {\n \"window_width\",\n [](StringView name, const Context& context)\n { return to_string(context.window().dimensions().column); }\n }, {\n \"window_height\",\n [](StringView name, const Context& context)\n { return to_string(context.window().dimensions().line); }\n } };\n\n ShellManager& shell_manager = ShellManager::instance();\n for (auto& env_var : env_vars)\n shell_manager.register_env_var(env_var.name, env_var.func);\n}\n\nvoid register_registers()\n{\n using StringList = std::vector;\n static const struct {\n char name;\n StringList (*func)(const Context&);\n } dyn_regs[] = {\n { '%', [](const Context& context) { return StringList{{context.buffer().display_name()}}; } },\n { '.', [](const Context& context) { return context.selections_content(); } },\n { '#', [](const Context& context) {\n StringList res;\n for (size_t i = 1; i < context.selections().size(); ++i)\n res.push_back(to_string((int)i));\n return res;\n } }\n };\n\n RegisterManager& register_manager = RegisterManager::instance();\n for (auto& dyn_reg : dyn_regs)\n register_manager.register_dynamic_register(dyn_reg.name, dyn_reg.func);\n\n for (size_t i = 0; i < 10; ++i)\n {\n register_manager.register_dynamic_register('0'+i,\n [i](const Context& context) {\n std::vector result;\n for (auto& sel : context.selections())\n result.emplace_back(i < sel.captures().size() ? sel.captures()[i] : \"\");\n return result;\n });\n }\n}\n\nvoid create_local_client(const String& init_command)\n{\n class LocalNCursesUI : public NCursesUI\n {\n ~LocalNCursesUI()\n {\n if (not ClientManager::instance().empty() and fork())\n {\n this->NCursesUI::~NCursesUI();\n puts(\"detached from terminal\\n\");\n exit(0);\n }\n }\n };\n\n if (not isatty(1))\n throw runtime_error(\"stdout is not a tty\");\n\n if (not isatty(0))\n {\n \/\/ move stdin to another fd, and restore tty as stdin\n int fd = dup(0);\n int tty = open(\"\/dev\/tty\", O_RDONLY);\n dup2(tty, 0);\n close(tty);\n create_fifo_buffer(\"*stdin*\", fd);\n }\n\n UserInterface* ui = new LocalNCursesUI{};\n static Client* client = ClientManager::instance().create_client(\n std::unique_ptr{ui}, get_env_vars(), init_command);\n signal(SIGHUP, [](int) {\n if (client)\n ClientManager::instance().remove_client(*client);\n client = nullptr;\n });\n}\n\nvoid signal_handler(int signal)\n{\n NCursesUI::abort();\n const char* text = nullptr;\n switch (signal)\n {\n case SIGSEGV: text = \"SIGSEGV\"; break;\n case SIGFPE: text = \"SIGFPE\"; break;\n case SIGQUIT: text = \"SIGQUIT\"; break;\n case SIGTERM: text = \"SIGTERM\"; break;\n }\n on_assert_failed(text);\n if (Server::has_instance())\n Server::instance().close_session();\n abort();\n}\n\nint run_client(const String& session, const String& init_command)\n{\n try\n {\n EventManager event_manager;\n auto client = connect_to(session,\n std::unique_ptr{new NCursesUI{}},\n get_env_vars(),\n init_command);\n while (true)\n event_manager.handle_next_events();\n }\n catch (peer_disconnected&)\n {\n fputs(\"disconnected from server\\n\", stderr);\n return -1;\n }\n catch (connection_failed& e)\n {\n fputs(e.what(), stderr);\n return -1;\n }\n return 0;\n}\n\nint kakoune(const ParametersParser& parser)\n{\n if (parser.has_option(\"p\"))\n {\n for (auto opt : { \"c\", \"n\", \"s\", \"d\", \"e\" })\n {\n if (parser.has_option(opt))\n {\n fprintf(stderr, \"error: -%s makes not sense with -p\\n\", opt);\n return -1;\n }\n }\n char buf[512];\n String command;\n while (ssize_t count = read(0, buf, 512))\n {\n if (count < 0)\n {\n fprintf(stderr, \"error while reading stdin\\n\");\n return -1;\n }\n command += String{buf, buf + count};\n }\n try\n {\n send_command(parser.option_value(\"p\"), command);\n }\n catch (connection_failed& e)\n {\n fputs(e.what(), stderr);\n return -1;\n }\n return 0;\n }\n\n String init_command;\n if (parser.has_option(\"e\"))\n init_command = parser.option_value(\"e\");\n\n if (parser.has_option(\"c\"))\n {\n for (auto opt : { \"n\", \"s\", \"d\" })\n {\n if (parser.has_option(opt))\n {\n fprintf(stderr, \"error: -%s makes not sense with -c\\n\", opt);\n return -1;\n }\n }\n return run_client(parser.option_value(\"c\"), init_command);\n }\n\n const bool daemon = parser.has_option(\"d\");\n static bool terminate = false;\n if (daemon)\n {\n if (not parser.has_option(\"s\"))\n {\n fputs(\"-d needs a session name to be specified with -s\\n\", stderr);\n return -1;\n }\n if (pid_t child = fork())\n {\n printf(\"Kakoune forked to background, for session '%s'\\n\"\n \"send SIGTERM to process %d for closing the session\\n\",\n parser.option_value(\"s\").c_str(), child);\n exit(0);\n }\n signal(SIGTERM, [](int) { terminate = true; });\n }\n\n EventManager event_manager;\n GlobalOptions global_options;\n GlobalHooks global_hooks;\n GlobalKeymaps global_keymaps;\n ShellManager shell_manager;\n CommandManager command_manager;\n BufferManager buffer_manager;\n RegisterManager register_manager;\n HighlighterRegistry highlighter_registry;\n DefinedHighlighters defined_highlighters;\n ColorRegistry color_registry;\n ClientManager client_manager;\n\n run_unit_tests();\n\n register_env_vars();\n register_registers();\n register_commands();\n register_highlighters();\n\n write_debug(\"*** This is the debug buffer, where debug info will be written ***\");\n write_debug(\"pid: \" + to_string(getpid()));\n\n Server server(parser.has_option(\"s\") ? parser.option_value(\"s\") : to_string(getpid()));\n write_debug(\"session: \" + server.session());\n\n if (not parser.has_option(\"n\")) try\n {\n Context initialisation_context;\n command_manager.execute(\"source \" + runtime_directory() + \"\/kakrc\",\n initialisation_context);\n }\n catch (Kakoune::runtime_error& error)\n {\n write_debug(\"error while parsing kakrc:\\n \"_str + error.what());\n }\n catch (Kakoune::client_removed&)\n {\n write_debug(\"error while parsing kakrc: asked to quit\");\n }\n\n {\n Context empty_context;\n global_hooks.run_hook(\"KakBegin\", \"\", empty_context);\n }\n\n if (parser.positional_count() != 0) try\n {\n \/\/ create buffers in reverse order so that the first given buffer\n \/\/ is the most recently created one.\n for (int i = parser.positional_count() - 1; i >= 0; --i)\n {\n const String& file = parser[i];\n if (not create_buffer_from_file(file))\n new Buffer(file, Buffer::Flags::New | Buffer::Flags::File);\n }\n }\n catch (Kakoune::runtime_error& error)\n {\n write_debug(\"error while opening command line files: \"_str + error.what());\n }\n else\n new Buffer(\"*scratch*\", Buffer::Flags::None);\n\n if (not daemon)\n create_local_client(init_command);\n\n while (not terminate and (not client_manager.empty() or daemon))\n event_manager.handle_next_events();\n\n {\n Context empty_context;\n global_hooks.run_hook(\"KakEnd\", \"\", empty_context);\n }\n return 0;\n}\n\nint main(int argc, char* argv[])\n{\n setlocale(LC_ALL, \"\");\n\n signal(SIGSEGV, signal_handler);\n signal(SIGFPE, signal_handler);\n signal(SIGQUIT, signal_handler);\n signal(SIGTERM, signal_handler);\n\n std::vector params;\n for (size_t i = 1; i < argc; ++i)\n params.push_back(argv[i]);\n\n const ParameterDesc param_desc{\n SwitchMap{ { \"c\", { true, \"connect to given session\" } },\n { \"e\", { true, \"execute argument on initialisation\" } },\n { \"n\", { false, \"do not source kakrc files on startup\" } },\n { \"s\", { true, \"set session name\" } },\n { \"d\", { false, \"run as a headless session (requires -s)\" } },\n { \"p\", { true, \"just send stdin as commands to the given session\" } } }\n };\n try\n {\n kakoune(ParametersParser(params, param_desc));\n }\n catch (Kakoune::parameter_error& error)\n {\n printf(\"Error: %s\\n\"\n \"Valid switches:\\n\"\n \"%s\",\n error.what(), generate_switches_doc(param_desc.switches).c_str());\n return -1;\n }\n catch (Kakoune::exception& error)\n {\n on_assert_failed((\"uncaught exception:\\n\"_str + error.what()).c_str());\n return -1;\n }\n catch (std::exception& error)\n {\n on_assert_failed((\"uncaught exception:\\n\"_str + error.what()).c_str());\n return -1;\n }\n catch (...)\n {\n on_assert_failed(\"uncaught exception\");\n return -1;\n }\n return 0;\n}\nAdd kak_selections_desc en vars, containing : separated descs#include \"assert.hh\"\n#include \"buffer.hh\"\n#include \"buffer_manager.hh\"\n#include \"buffer_utils.hh\"\n#include \"client_manager.hh\"\n#include \"color_registry.hh\"\n#include \"command_manager.hh\"\n#include \"commands.hh\"\n#include \"context.hh\"\n#include \"debug.hh\"\n#include \"event_manager.hh\"\n#include \"file.hh\"\n#include \"highlighters.hh\"\n#include \"hook_manager.hh\"\n#include \"ncurses.hh\"\n#include \"option_manager.hh\"\n#include \"keymap_manager.hh\"\n#include \"parameters_parser.hh\"\n#include \"register_manager.hh\"\n#include \"remote.hh\"\n#include \"shell_manager.hh\"\n#include \"string.hh\"\n#include \"window.hh\"\n\n#if defined(__APPLE__)\n#include \n#endif\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace Kakoune;\n\nvoid run_unit_tests();\n\nString runtime_directory()\n{\n char buffer[2048];\n#if defined(__linux__) || defined(__CYGWIN__)\n ssize_t res = readlink(\"\/proc\/self\/exe\", buffer, 2048);\n kak_assert(res != -1);\n buffer[res] = '\\0';\n#elif defined(__APPLE__)\n uint32_t bufsize = 2048;\n _NSGetExecutablePath(buffer, &bufsize);\n char* canonical_path = realpath(buffer, nullptr);\n strncpy(buffer, canonical_path, 2048);\n free(canonical_path);\n#else\n# error \"finding executable path is not implemented on this platform\"\n#endif\n char* ptr = strrchr(buffer, '\/');\n if (not ptr)\n throw runtime_error(\"unable to determine runtime directory\");\n return String(buffer, ptr) + \"\/..\/share\/kak\";\n}\n\nvoid register_env_vars()\n{\n static const struct {\n const char* name;\n String (*func)(StringView, const Context&);\n } env_vars[] = { {\n \"bufname\",\n [](StringView name, const Context& context)\n { return context.buffer().display_name(); }\n }, {\n \"buffile\",\n [](StringView name, const Context& context) -> String\n { return context.buffer().name(); }\n }, {\n \"timestamp\",\n [](StringView name, const Context& context)\n { return to_string(context.buffer().timestamp()); }\n }, {\n \"selection\",\n [](StringView name, const Context& context)\n { const Selection& sel = context.selections().main();\n return content(context.buffer(), sel); }\n }, {\n \"selections\",\n [](StringView name, const Context& context)\n { auto sels = context.selections_content();\n String res;\n for (size_t i = 0; i < sels.size(); ++i)\n {\n res += escape(sels[i], ':', '\\\\');\n if (i != sels.size() - 1)\n res += ':';\n }\n return res; }\n }, {\n \"runtime\",\n [](StringView name, const Context& context)\n { return runtime_directory(); }\n }, {\n \"opt_.+\",\n [](StringView name, const Context& context)\n { return context.options()[name.substr(4_byte)].get_as_string(); }\n }, {\n \"reg_.+\",\n [](StringView name, const Context& context) -> String\n { return RegisterManager::instance()[name[4]].values(context)[0]; }\n }, {\n \"client_env_.+\",\n [](StringView name, const Context& context) -> String\n { return context.client().get_env_var(name.substr(11_byte)); }\n }, {\n \"session\",\n [](StringView name, const Context& context) -> String\n { return Server::instance().session(); }\n }, {\n \"client\",\n [](StringView name, const Context& context) -> String\n { return context.name(); }\n }, {\n \"cursor_line\",\n [](StringView name, const Context& context)\n { return to_string(context.selections().main().cursor().line + 1); }\n }, {\n \"cursor_column\",\n [](StringView name, const Context& context)\n { return to_string(context.selections().main().cursor().column + 1); }\n }, {\n \"cursor_char_column\",\n [](StringView name, const Context& context)\n { auto coord = context.selections().main().cursor();\n return to_string(context.buffer()[coord.line].char_count_to(coord.column) + 1); }\n }, {\n \"selection_desc\",\n [](StringView name, const Context& context)\n { auto& sel = context.selections().main();\n auto beg = sel.min();\n return to_string(beg.line + 1) + '.' + to_string(beg.column + 1) + '+' +\n to_string((int)context.buffer().distance(beg, sel.max())+1); }\n }, {\n \"selections_desc\",\n [](StringView name, const Context& context)\n {\n String res;\n for (auto& sel : context.selections())\n {\n auto beg = sel.min();\n if (not res.empty())\n res += ':';\n res += to_string(beg.line + 1) + '.' + to_string(beg.column + 1) + '+' +\n to_string((int)context.buffer().distance(beg, sel.max())+1);\n }\n return res;\n }\n }, {\n \"window_width\",\n [](StringView name, const Context& context)\n { return to_string(context.window().dimensions().column); }\n }, {\n \"window_height\",\n [](StringView name, const Context& context)\n { return to_string(context.window().dimensions().line); }\n } };\n\n ShellManager& shell_manager = ShellManager::instance();\n for (auto& env_var : env_vars)\n shell_manager.register_env_var(env_var.name, env_var.func);\n}\n\nvoid register_registers()\n{\n using StringList = std::vector;\n static const struct {\n char name;\n StringList (*func)(const Context&);\n } dyn_regs[] = {\n { '%', [](const Context& context) { return StringList{{context.buffer().display_name()}}; } },\n { '.', [](const Context& context) { return context.selections_content(); } },\n { '#', [](const Context& context) {\n StringList res;\n for (size_t i = 1; i < context.selections().size(); ++i)\n res.push_back(to_string((int)i));\n return res;\n } }\n };\n\n RegisterManager& register_manager = RegisterManager::instance();\n for (auto& dyn_reg : dyn_regs)\n register_manager.register_dynamic_register(dyn_reg.name, dyn_reg.func);\n\n for (size_t i = 0; i < 10; ++i)\n {\n register_manager.register_dynamic_register('0'+i,\n [i](const Context& context) {\n std::vector result;\n for (auto& sel : context.selections())\n result.emplace_back(i < sel.captures().size() ? sel.captures()[i] : \"\");\n return result;\n });\n }\n}\n\nvoid create_local_client(const String& init_command)\n{\n class LocalNCursesUI : public NCursesUI\n {\n ~LocalNCursesUI()\n {\n if (not ClientManager::instance().empty() and fork())\n {\n this->NCursesUI::~NCursesUI();\n puts(\"detached from terminal\\n\");\n exit(0);\n }\n }\n };\n\n if (not isatty(1))\n throw runtime_error(\"stdout is not a tty\");\n\n if (not isatty(0))\n {\n \/\/ move stdin to another fd, and restore tty as stdin\n int fd = dup(0);\n int tty = open(\"\/dev\/tty\", O_RDONLY);\n dup2(tty, 0);\n close(tty);\n create_fifo_buffer(\"*stdin*\", fd);\n }\n\n UserInterface* ui = new LocalNCursesUI{};\n static Client* client = ClientManager::instance().create_client(\n std::unique_ptr{ui}, get_env_vars(), init_command);\n signal(SIGHUP, [](int) {\n if (client)\n ClientManager::instance().remove_client(*client);\n client = nullptr;\n });\n}\n\nvoid signal_handler(int signal)\n{\n NCursesUI::abort();\n const char* text = nullptr;\n switch (signal)\n {\n case SIGSEGV: text = \"SIGSEGV\"; break;\n case SIGFPE: text = \"SIGFPE\"; break;\n case SIGQUIT: text = \"SIGQUIT\"; break;\n case SIGTERM: text = \"SIGTERM\"; break;\n }\n on_assert_failed(text);\n if (Server::has_instance())\n Server::instance().close_session();\n abort();\n}\n\nint run_client(const String& session, const String& init_command)\n{\n try\n {\n EventManager event_manager;\n auto client = connect_to(session,\n std::unique_ptr{new NCursesUI{}},\n get_env_vars(),\n init_command);\n while (true)\n event_manager.handle_next_events();\n }\n catch (peer_disconnected&)\n {\n fputs(\"disconnected from server\\n\", stderr);\n return -1;\n }\n catch (connection_failed& e)\n {\n fputs(e.what(), stderr);\n return -1;\n }\n return 0;\n}\n\nint kakoune(const ParametersParser& parser)\n{\n if (parser.has_option(\"p\"))\n {\n for (auto opt : { \"c\", \"n\", \"s\", \"d\", \"e\" })\n {\n if (parser.has_option(opt))\n {\n fprintf(stderr, \"error: -%s makes not sense with -p\\n\", opt);\n return -1;\n }\n }\n char buf[512];\n String command;\n while (ssize_t count = read(0, buf, 512))\n {\n if (count < 0)\n {\n fprintf(stderr, \"error while reading stdin\\n\");\n return -1;\n }\n command += String{buf, buf + count};\n }\n try\n {\n send_command(parser.option_value(\"p\"), command);\n }\n catch (connection_failed& e)\n {\n fputs(e.what(), stderr);\n return -1;\n }\n return 0;\n }\n\n String init_command;\n if (parser.has_option(\"e\"))\n init_command = parser.option_value(\"e\");\n\n if (parser.has_option(\"c\"))\n {\n for (auto opt : { \"n\", \"s\", \"d\" })\n {\n if (parser.has_option(opt))\n {\n fprintf(stderr, \"error: -%s makes not sense with -c\\n\", opt);\n return -1;\n }\n }\n return run_client(parser.option_value(\"c\"), init_command);\n }\n\n const bool daemon = parser.has_option(\"d\");\n static bool terminate = false;\n if (daemon)\n {\n if (not parser.has_option(\"s\"))\n {\n fputs(\"-d needs a session name to be specified with -s\\n\", stderr);\n return -1;\n }\n if (pid_t child = fork())\n {\n printf(\"Kakoune forked to background, for session '%s'\\n\"\n \"send SIGTERM to process %d for closing the session\\n\",\n parser.option_value(\"s\").c_str(), child);\n exit(0);\n }\n signal(SIGTERM, [](int) { terminate = true; });\n }\n\n EventManager event_manager;\n GlobalOptions global_options;\n GlobalHooks global_hooks;\n GlobalKeymaps global_keymaps;\n ShellManager shell_manager;\n CommandManager command_manager;\n BufferManager buffer_manager;\n RegisterManager register_manager;\n HighlighterRegistry highlighter_registry;\n DefinedHighlighters defined_highlighters;\n ColorRegistry color_registry;\n ClientManager client_manager;\n\n run_unit_tests();\n\n register_env_vars();\n register_registers();\n register_commands();\n register_highlighters();\n\n write_debug(\"*** This is the debug buffer, where debug info will be written ***\");\n write_debug(\"pid: \" + to_string(getpid()));\n\n Server server(parser.has_option(\"s\") ? parser.option_value(\"s\") : to_string(getpid()));\n write_debug(\"session: \" + server.session());\n\n if (not parser.has_option(\"n\")) try\n {\n Context initialisation_context;\n command_manager.execute(\"source \" + runtime_directory() + \"\/kakrc\",\n initialisation_context);\n }\n catch (Kakoune::runtime_error& error)\n {\n write_debug(\"error while parsing kakrc:\\n \"_str + error.what());\n }\n catch (Kakoune::client_removed&)\n {\n write_debug(\"error while parsing kakrc: asked to quit\");\n }\n\n {\n Context empty_context;\n global_hooks.run_hook(\"KakBegin\", \"\", empty_context);\n }\n\n if (parser.positional_count() != 0) try\n {\n \/\/ create buffers in reverse order so that the first given buffer\n \/\/ is the most recently created one.\n for (int i = parser.positional_count() - 1; i >= 0; --i)\n {\n const String& file = parser[i];\n if (not create_buffer_from_file(file))\n new Buffer(file, Buffer::Flags::New | Buffer::Flags::File);\n }\n }\n catch (Kakoune::runtime_error& error)\n {\n write_debug(\"error while opening command line files: \"_str + error.what());\n }\n else\n new Buffer(\"*scratch*\", Buffer::Flags::None);\n\n if (not daemon)\n create_local_client(init_command);\n\n while (not terminate and (not client_manager.empty() or daemon))\n event_manager.handle_next_events();\n\n {\n Context empty_context;\n global_hooks.run_hook(\"KakEnd\", \"\", empty_context);\n }\n return 0;\n}\n\nint main(int argc, char* argv[])\n{\n setlocale(LC_ALL, \"\");\n\n signal(SIGSEGV, signal_handler);\n signal(SIGFPE, signal_handler);\n signal(SIGQUIT, signal_handler);\n signal(SIGTERM, signal_handler);\n\n std::vector params;\n for (size_t i = 1; i < argc; ++i)\n params.push_back(argv[i]);\n\n const ParameterDesc param_desc{\n SwitchMap{ { \"c\", { true, \"connect to given session\" } },\n { \"e\", { true, \"execute argument on initialisation\" } },\n { \"n\", { false, \"do not source kakrc files on startup\" } },\n { \"s\", { true, \"set session name\" } },\n { \"d\", { false, \"run as a headless session (requires -s)\" } },\n { \"p\", { true, \"just send stdin as commands to the given session\" } } }\n };\n try\n {\n kakoune(ParametersParser(params, param_desc));\n }\n catch (Kakoune::parameter_error& error)\n {\n printf(\"Error: %s\\n\"\n \"Valid switches:\\n\"\n \"%s\",\n error.what(), generate_switches_doc(param_desc.switches).c_str());\n return -1;\n }\n catch (Kakoune::exception& error)\n {\n on_assert_failed((\"uncaught exception:\\n\"_str + error.what()).c_str());\n return -1;\n }\n catch (std::exception& error)\n {\n on_assert_failed((\"uncaught exception:\\n\"_str + error.what()).c_str());\n return -1;\n }\n catch (...)\n {\n on_assert_failed(\"uncaught exception\");\n return -1;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"#include \r\n\r\n#include \r\n#include \r\n\r\nnamespace Ra {\r\nnamespace Core {\r\nnamespace Animation {\r\n\r\n\r\nWeightMatrix extractWeightMatrix(const MeshWeight &weight,\r\n const uint weight_size)\r\n{\r\n WeightMatrix W(weight.size(), weight_size);\r\n W.setZero();\r\n for (uint i = 0; i < weight.size(); ++i)\r\n {\r\n for (const auto& w : weight[i])\r\n {\r\n W.coeffRef(i, w.first) = w.second;\r\n }\r\n }\r\n return W;\r\n}\r\n\r\n\r\nMeshWeight extractMeshWeight(Eigen::Ref matrix)\r\n{\r\n MeshWeight W(matrix.rows());\r\n for (int i = 0; i < matrix.rows(); ++i)\r\n {\r\n for (int j = 0; j < matrix.cols(); ++j)\r\n {\r\n if (matrix.coeff(i, j) != 0.0)\r\n {\r\n std::pair w(uint(j), matrix.coeff(i, j));\r\n W[i].push_back(w);\r\n }\r\n }\r\n }\r\n return W;\r\n}\r\n\r\n\r\n\r\nWeightMatrix partitionOfUnity( Eigen::Ref weights ) {\r\n WeightMatrix W = weights;\r\n normalizeWeights(W);\r\n return W;\r\n}\r\n\r\n\r\nuint getMaxWeightIndex(Eigen::Ref weights,\r\n const uint vertexID ) {\r\n uint maxId = uint( -1 );\r\n VectorN row = weights.row( vertexID );\r\n row.maxCoeff(&maxId);\r\n return maxId;\r\n}\r\n\r\n\r\n\r\nvoid getMaxWeightIndex( Eigen::Ref weights,\r\n std::vector< uint >& handleID ) {\r\n handleID.resize( weights.rows() );\r\n for( int i = 0; i < weights.rows(); ++i ) {\r\n handleID[i] = getMaxWeightIndex( weights, i );\r\n }\r\n}\r\n\r\n\r\n\r\nvoid checkWeightMatrix( Eigen::Ref matrix,\r\n const bool FAIL_ON_ASSERT, const bool MT ) {\r\n if( check_NAN( matrix, FAIL_ON_ASSERT, MT ) ) {\r\n LOG( logDEBUG ) << \"Matrix is good.\";\r\n } else {\r\n LOG( logDEBUG ) << \"Matrix is not good.\";\r\n }\r\n\r\n if( check_NoWeightVertex( matrix, FAIL_ON_ASSERT, MT ) ) {\r\n LOG( logDEBUG ) << \"Matrix is good.\";\r\n } else {\r\n LOG( logDEBUG ) << \"Matrix is not good.\";\r\n }\r\n}\r\n\r\n\r\n\r\nbool RA_CORE_API check_NAN(Eigen::Ref matrix,\r\n const bool FAIL_ON_ASSERT, const bool MT ) {\r\n using Iterator = Eigen::Ref::InnerIterator;\r\n int status = 1;\r\n LOG( logDEBUG ) << \"Searching for nans in the matrix...\";\r\n if( MT ) {\r\n #pragma omp parallel for\r\n for( int k = 0; k < matrix.outerSize(); ++k ) {\r\n for( Iterator it( matrix, k ); it; ++it ) {\r\n const Scalar value = it.value();\r\n const int check = std::isnan( value ) ? 0 : 1;\r\n #pragma omp atomic\r\n status &= check ;\r\n }\r\n }\r\n if( status == 0 ) {\r\n if( FAIL_ON_ASSERT ) {\r\n CORE_ASSERT( false, \"At least an element is nan\" );\r\n } else {\r\n LOG( logDEBUG ) << \"At least an element is nan\";\r\n }\r\n }\r\n } else {\r\n for( int k = 0; k < matrix.outerSize(); ++k ) {\r\n for( Iterator it( matrix, k ); it; ++it ) {\r\n const uint i = it.row();\r\n const uint j = it.col();\r\n const Scalar value = it.value();\r\n const std::string text = \"Element (\" + std::to_string( i ) + \",\" + std::to_string(j) + \") is nan.\";\r\n if( FAIL_ON_ASSERT ) {\r\n CORE_ASSERT( !std::isnan( value ), text.c_str() );\r\n } else {\r\n if( std::isnan( value ) ) {\r\n LOG( logDEBUG ) << text;\r\n status = 0;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return status != 0;\r\n}\r\n\r\nbool RA_CORE_API check_NoWeightVertex( Eigen::Ref matrix,\r\n const bool FAIL_ON_ASSERT, const bool MT ) {\r\n int status = 1;\r\n LOG( logDEBUG ) << \"Searching for empty rows in the matrix...\";\r\n if( MT ) {\r\n #pragma omp parallel for\r\n for( int i = 0; i < matrix.rows(); ++i ) {\r\n Sparse row = matrix.row( i );\r\n const int check = ( row.nonZeros() > 0 ) ? 1 : 0;\r\n #pragma omp atomic\r\n status &= check;\r\n }\r\n if( status == 0 ) {\r\n if( FAIL_ON_ASSERT ) {\r\n CORE_ASSERT( false, \"At least a vertex as no weights\" );\r\n } else {\r\n LOG( logDEBUG ) << \"At least a vertex as no weights\";\r\n }\r\n }\r\n } else {\r\n for( int i = 0; i < matrix.rows(); ++i ) {\r\n Sparse row = matrix.row( i );\r\n if( row.nonZeros() == 0 ) {\r\n const std::string text = \"Vertex \" + std::to_string( i ) + \" has no weights.\";\r\n if( FAIL_ON_ASSERT ) {\r\n CORE_ASSERT( false, text.c_str() );\r\n } else {\r\n status = 0;\r\n LOG( logDEBUG ) << text;\r\n }\r\n }\r\n }\r\n }\r\n return status != 0;\r\n}\r\n\r\nbool RA_CORE_API normalizeWeights(Eigen::Ref matrix, const bool MT)\r\n{\r\n CORE_UNUSED(MT)\r\n\r\n bool skinningWeightOk = true;\r\n\r\n #pragma omp parallel for if(MT)\r\n for (int k = 0; k < matrix.innerSize(); ++k)\r\n {\r\n const Scalar sum = matrix.row( k ).sum();\r\n if(! Ra::Core::Math::areApproxEqual(sum, Scalar(0))){\r\n skinningWeightOk &= Ra::Core::Math::areApproxEqual(sum, Scalar(1));\r\n matrix.row( k ) \/= sum;\r\n }\r\n }\r\n return ! skinningWeightOk;\r\n}\r\n\r\n\r\n} \/\/ namespace Animation\r\n} \/\/ Namespace Core\r\n} \/\/ Namespace Ra\r\nNormalized only when necessary#include \r\n\r\n#include \r\n#include \r\n\r\nnamespace Ra {\r\nnamespace Core {\r\nnamespace Animation {\r\n\r\n\r\nWeightMatrix extractWeightMatrix(const MeshWeight &weight,\r\n const uint weight_size)\r\n{\r\n WeightMatrix W(weight.size(), weight_size);\r\n W.setZero();\r\n for (uint i = 0; i < weight.size(); ++i)\r\n {\r\n for (const auto& w : weight[i])\r\n {\r\n W.coeffRef(i, w.first) = w.second;\r\n }\r\n }\r\n return W;\r\n}\r\n\r\n\r\nMeshWeight extractMeshWeight(Eigen::Ref matrix)\r\n{\r\n MeshWeight W(matrix.rows());\r\n for (int i = 0; i < matrix.rows(); ++i)\r\n {\r\n for (int j = 0; j < matrix.cols(); ++j)\r\n {\r\n if (matrix.coeff(i, j) != 0.0)\r\n {\r\n std::pair w(uint(j), matrix.coeff(i, j));\r\n W[i].push_back(w);\r\n }\r\n }\r\n }\r\n return W;\r\n}\r\n\r\n\r\n\r\nWeightMatrix partitionOfUnity( Eigen::Ref weights ) {\r\n WeightMatrix W = weights;\r\n normalizeWeights(W);\r\n return W;\r\n}\r\n\r\n\r\nuint getMaxWeightIndex(Eigen::Ref weights,\r\n const uint vertexID ) {\r\n uint maxId = uint( -1 );\r\n VectorN row = weights.row( vertexID );\r\n row.maxCoeff(&maxId);\r\n return maxId;\r\n}\r\n\r\n\r\n\r\nvoid getMaxWeightIndex( Eigen::Ref weights,\r\n std::vector< uint >& handleID ) {\r\n handleID.resize( weights.rows() );\r\n for( int i = 0; i < weights.rows(); ++i ) {\r\n handleID[i] = getMaxWeightIndex( weights, i );\r\n }\r\n}\r\n\r\n\r\n\r\nvoid checkWeightMatrix( Eigen::Ref matrix,\r\n const bool FAIL_ON_ASSERT, const bool MT ) {\r\n if( check_NAN( matrix, FAIL_ON_ASSERT, MT ) ) {\r\n LOG( logDEBUG ) << \"Matrix is good.\";\r\n } else {\r\n LOG( logDEBUG ) << \"Matrix is not good.\";\r\n }\r\n\r\n if( check_NoWeightVertex( matrix, FAIL_ON_ASSERT, MT ) ) {\r\n LOG( logDEBUG ) << \"Matrix is good.\";\r\n } else {\r\n LOG( logDEBUG ) << \"Matrix is not good.\";\r\n }\r\n}\r\n\r\n\r\n\r\nbool RA_CORE_API check_NAN(Eigen::Ref matrix,\r\n const bool FAIL_ON_ASSERT, const bool MT ) {\r\n using Iterator = Eigen::Ref::InnerIterator;\r\n int status = 1;\r\n LOG( logDEBUG ) << \"Searching for nans in the matrix...\";\r\n if( MT ) {\r\n #pragma omp parallel for\r\n for( int k = 0; k < matrix.outerSize(); ++k ) {\r\n for( Iterator it( matrix, k ); it; ++it ) {\r\n const Scalar value = it.value();\r\n const int check = std::isnan( value ) ? 0 : 1;\r\n #pragma omp atomic\r\n status &= check ;\r\n }\r\n }\r\n if( status == 0 ) {\r\n if( FAIL_ON_ASSERT ) {\r\n CORE_ASSERT( false, \"At least an element is nan\" );\r\n } else {\r\n LOG( logDEBUG ) << \"At least an element is nan\";\r\n }\r\n }\r\n } else {\r\n for( int k = 0; k < matrix.outerSize(); ++k ) {\r\n for( Iterator it( matrix, k ); it; ++it ) {\r\n const uint i = it.row();\r\n const uint j = it.col();\r\n const Scalar value = it.value();\r\n const std::string text = \"Element (\" + std::to_string( i ) + \",\" + std::to_string(j) + \") is nan.\";\r\n if( FAIL_ON_ASSERT ) {\r\n CORE_ASSERT( !std::isnan( value ), text.c_str() );\r\n } else {\r\n if( std::isnan( value ) ) {\r\n LOG( logDEBUG ) << text;\r\n status = 0;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return status != 0;\r\n}\r\n\r\nbool RA_CORE_API check_NoWeightVertex( Eigen::Ref matrix,\r\n const bool FAIL_ON_ASSERT, const bool MT ) {\r\n int status = 1;\r\n LOG( logDEBUG ) << \"Searching for empty rows in the matrix...\";\r\n if( MT ) {\r\n #pragma omp parallel for\r\n for( int i = 0; i < matrix.rows(); ++i ) {\r\n Sparse row = matrix.row( i );\r\n const int check = ( row.nonZeros() > 0 ) ? 1 : 0;\r\n #pragma omp atomic\r\n status &= check;\r\n }\r\n if( status == 0 ) {\r\n if( FAIL_ON_ASSERT ) {\r\n CORE_ASSERT( false, \"At least a vertex as no weights\" );\r\n } else {\r\n LOG( logDEBUG ) << \"At least a vertex as no weights\";\r\n }\r\n }\r\n } else {\r\n for( int i = 0; i < matrix.rows(); ++i ) {\r\n Sparse row = matrix.row( i );\r\n if( row.nonZeros() == 0 ) {\r\n const std::string text = \"Vertex \" + std::to_string( i ) + \" has no weights.\";\r\n if( FAIL_ON_ASSERT ) {\r\n CORE_ASSERT( false, text.c_str() );\r\n } else {\r\n status = 0;\r\n LOG( logDEBUG ) << text;\r\n }\r\n }\r\n }\r\n }\r\n return status != 0;\r\n}\r\n\r\nbool RA_CORE_API normalizeWeights(Eigen::Ref matrix, const bool MT)\r\n{\r\n CORE_UNUSED(MT);\r\n\r\n bool skinningWeightOk = true;\r\n\r\n #pragma omp parallel for if(MT)\r\n for (int k = 0; k < matrix.innerSize(); ++k)\r\n {\r\n const Scalar sum = matrix.row( k ).sum();\r\n if(! Ra::Core::Math::areApproxEqual(sum, Scalar(0))){\r\n if (! Ra::Core::Math::areApproxEqual(sum, Scalar(1))){\r\n skinningWeightOk = false ;\r\n matrix.row( k ) \/= sum;\r\n }\r\n }\r\n }\r\n return ! skinningWeightOk;\r\n}\r\n\r\n\r\n} \/\/ namespace Animation\r\n} \/\/ Namespace Core\r\n} \/\/ Namespace Ra\r\n<|endoftext|>"} {"text":"\/*\n This file is part of KOrganizer.\n\n Copyright (c) 2003,2004 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 \"resourceview.h\"\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#include \n#include \n#include \n\n#include \"koprefs.h\"\n\nusing namespace KCal;\n\nResourceViewFactory::ResourceViewFactory( KCal::CalendarResources *calendar,\n CalendarView *view )\n : mCalendar( calendar ), mView( view ), mResourceView( 0 )\n{\n}\n\nCalendarViewExtension *ResourceViewFactory::create( QWidget *parent )\n{\n mResourceView = new ResourceView( mCalendar, parent );\n\n QObject::connect( mResourceView, SIGNAL( resourcesChanged() ),\n mView, SLOT( updateView() ) );\n QObject::connect( mResourceView, SIGNAL( resourcesChanged() ),\n mView, SLOT( updateCategories() ) );\n\n QObject::connect( mCalendar,\n SIGNAL( signalResourceAdded( ResourceCalendar * ) ),\n mResourceView,\n SLOT( addResourceItem( ResourceCalendar * ) ) );\n QObject::connect( mCalendar,\n SIGNAL( signalResourceModified( ResourceCalendar * ) ),\n mResourceView,\n SLOT( updateResourceItem( ResourceCalendar * ) ) );\n QObject::connect( mCalendar, SIGNAL( signalResourceAdded( ResourceCalendar * ) ),\n mView, SLOT( updateCategories() ) );\n QObject::connect( mCalendar, SIGNAL( signalResourceModified( ResourceCalendar * ) ),\n mView, SLOT( updateCategories() ) );\n\n return mResourceView;\n}\n\nResourceView *ResourceViewFactory::resourceView() const\n{\n return mResourceView;\n}\n\nResourceItem::ResourceItem( ResourceCalendar *resource, ResourceView *view,\n KListView *parent )\n : QCheckListItem( parent, resource->resourceName(), CheckBox ),\n mResource( resource ), mView( view ), mBlockStateChange( false ),\n mIsSubresource( false ), mResourceIdentifier(),\n mSubItemsCreated( false )\n{\n setGuiState();\n\n if ( mResource->isActive() ) {\n createSubresourceItems();\n }\n}\n\nvoid ResourceItem::createSubresourceItems() {\n const QStringList subresources = mResource->subresources();\n if ( !subresources.isEmpty() ) {\n setOpen( true );\n setExpandable( true );\n \/\/ This resource has subresources\n QStringList::ConstIterator it;\n for ( it=subresources.begin(); it!=subresources.end(); ++it ) {\n ( void )new ResourceItem( mResource, *it, mResource->labelForSubresource( *it ),\n mView, this );\n }\n }\n mSubItemsCreated = true;\n}\n\nResourceItem::ResourceItem( KCal::ResourceCalendar *resource,\n const QString& sub, const QString& label,\n ResourceView *view, ResourceItem* parent )\n\n : QCheckListItem( parent, label, CheckBox ), mResource( resource ),\n mView( view ), mBlockStateChange( false ), mIsSubresource( true ),\n mSubItemsCreated( false )\n{\n mResourceIdentifier = sub;\n setGuiState();\n}\n\nvoid ResourceItem::setGuiState()\n{\n mBlockStateChange = true;\n if ( mIsSubresource )\n setOn( mResource->subresourceActive( mResourceIdentifier ) );\n else\n setOn( mResource->isActive() );\n mBlockStateChange = false;\n}\n\nvoid ResourceItem::stateChange( bool active )\n{\n if ( mBlockStateChange ) return;\n\n if ( mIsSubresource ) {\n mResource->setSubresourceActive( mResourceIdentifier, active );\n } else {\n if ( active ) {\n if ( mResource->load() ) {\n mResource->setActive( true );\n if ( !mSubItemsCreated )\n createSubresourceItems();\n }\n } else {\n if ( mResource->save() ) mResource->setActive( false );\n mView->requestClose( mResource );\n }\n\n setOpen( mResource->isActive() && childCount() > 0 );\n\n setGuiState();\n }\n\n mView->emitResourcesChanged();\n}\n\nvoid ResourceItem::update()\n{\n setGuiState();\n}\n\nResourceView::ResourceView( KCal::CalendarResources *calendar,\n QWidget *parent, const char *name )\n : CalendarViewExtension( parent, name ), mCalendar( calendar )\n{\n QBoxLayout *topLayout = new QVBoxLayout( this );\n\n mListView = new KListView( this );\n mListView->addColumn( i18n(\"Calendar\") );\n mListView->setResizeMode( QListView::LastColumn );\n topLayout->addWidget( mListView );\n\n QHBox *buttonBox = new QHBox( this );\n topLayout->addWidget( buttonBox );\n\n mAddButton = new QPushButton( i18n(\"Add...\"), buttonBox, \"add\" );\n mEditButton = new QPushButton( i18n(\"Edit...\"), buttonBox, \"edit\" );\n mDeleteButton = new QPushButton( i18n(\"Remove\"), buttonBox, \"del\" );\n mDeleteButton->setDisabled( true );\n mEditButton->setDisabled( true );\n\n connect( mListView, SIGNAL( clicked( QListViewItem * ) ),\n SLOT( currentChanged( QListViewItem * ) ) );\n connect( mAddButton, SIGNAL( clicked() ), SLOT( addResource() ) );\n connect( mDeleteButton, SIGNAL( clicked() ), SLOT( removeResource() ) );\n connect( mEditButton, SIGNAL( clicked() ), SLOT( editResource() ) );\n connect( mListView, SIGNAL( doubleClicked ( QListViewItem *, const QPoint &,\n int ) ),\n SLOT( editResource() ) );\n connect( mListView, SIGNAL( contextMenuRequested ( QListViewItem *,\n const QPoint &, int ) ),\n SLOT( contextMenuRequested( QListViewItem *, const QPoint &,\n int ) ) );\n updateView();\n}\n\nResourceView::~ResourceView()\n{\n}\n\nvoid ResourceView::updateView()\n{\n mListView->clear();\n\n KCal::CalendarResourceManager *manager = mCalendar->resourceManager();\n\n KCal::CalendarResourceManager::Iterator it;\n for( it = manager->begin(); it != manager->end(); ++it ) {\n addResourceItem( *it );\n }\n}\n\nvoid ResourceView::emitResourcesChanged()\n{\n emit resourcesChanged();\n}\n\nvoid ResourceView::addResource()\n{\n KCal::CalendarResourceManager *manager = mCalendar->resourceManager();\n\n QStringList types = manager->resourceTypeNames();\n QStringList descs = manager->resourceTypeDescriptions();\n bool ok = false;\n QString desc = KInputDialog::getItem( i18n( \"Resource Configuration\" ),\n i18n( \"Please select type of the new resource:\" ), descs, 0, false, &ok,\n this );\n if ( !ok )\n return;\n\n QString type = types[ descs.findIndex( desc ) ];\n\n \/\/ Create new resource\n ResourceCalendar *resource = manager->createResource( type );\n if( !resource ) {\n KMessageBox::error( this, i18n(\"Unable to create resource of type %1<\/b>.<\/qt>\")\n .arg( type ) );\n return;\n }\n\n resource->setResourceName( i18n(\"%1 resource\").arg( type ) );\n\n KRES::ConfigDialog dlg( this, QString(\"calendar\"), resource,\n \"KRES::ConfigDialog\" );\n\n if ( dlg.exec() ) {\n resource->setTimeZoneId( KOPrefs::instance()->mTimeZoneId );\n if ( resource->isActive() ) {\n resource->open();\n resource->load();\n }\n manager->add( resource );\n addResourceItem( resource );\n } else {\n delete resource;\n resource = 0;\n }\n}\n\nvoid ResourceView::addResourceItem( ResourceCalendar *resource )\n{\n new ResourceItem( resource, this, mListView );\n\n connect( resource, SIGNAL( signalSubresourceAdded( ResourceCalendar *,\n const QString &,\n const QString &,\n const QString & ) ),\n SLOT( slotSubresourceAdded( ResourceCalendar *, const QString &,\n const QString &, const QString & ) ) );\n\n connect( resource, SIGNAL( signalSubresourceAdded( ResourceCalendar *,\n const QString &,\n const QString & ) ),\n SLOT( slotSubresourceAdded( ResourceCalendar *, const QString &,\n const QString & ) ) );\n \n connect( resource, SIGNAL( signalSubresourceRemoved( ResourceCalendar *,\n const QString &,\n const QString & ) ),\n SLOT( slotSubresourceRemoved( ResourceCalendar *, const QString &,\n const QString & ) ) );\n\n connect( resource, SIGNAL( resourceSaved( ResourceCalendar * ) ),\n SLOT( closeResource( ResourceCalendar * ) ) );\n\n emitResourcesChanged();\n}\n\n\n\/\/ FIXME proko2: merge once we are back in HEAD by porting imap resource\nvoid ResourceView::slotSubresourceAdded( ResourceCalendar *calendar,\n const QString& type,\n const QString& resource )\n{\n slotSubresourceAdded( calendar, type, resource, resource );\n}\n\n\/\/ Add a new entry\nvoid ResourceView::slotSubresourceAdded( ResourceCalendar *calendar,\n const QString& \/*type*\/,\n const QString& resource,\n const QString& label)\n{\n QListViewItem *i = mListView->findItem( calendar->resourceName(), 0 );\n if ( !i )\n \/\/ Not found\n return;\n\n ResourceItem *item = static_cast( i );\n ( void )new ResourceItem( calendar, resource, label, this, item );\n}\n\n\/\/ Remove an entry\nvoid ResourceView::slotSubresourceRemoved( ResourceCalendar *\/*calendar*\/,\n const QString &\/*type*\/,\n const QString &resource )\n{\n delete findItemByIdentifier( resource );\n emitResourcesChanged();\n}\n\nvoid ResourceView::closeResource( ResourceCalendar *r )\n{\n if ( mResourcesToClose.find( r ) >= 0 ) {\n r->close();\n mResourcesToClose.remove( r );\n }\n}\n\nvoid ResourceView::updateResourceItem( ResourceCalendar *resource )\n{\n ResourceItem *item = findItem( resource );\n if ( item ) {\n item->update();\n }\n}\n\nResourceItem *ResourceView::currentItem()\n{\n QListViewItem *item = mListView->currentItem();\n ResourceItem *rItem = static_cast( item );\n return rItem;\n}\n\nvoid ResourceView::removeResource()\n{\n ResourceItem *item = currentItem();\n if ( !item ) return;\n\n int km = KMessageBox::warningContinueCancel( this,\n i18n(\"Do you really want to remove the resource %1<\/b>?<\/qt>\")\n .arg( item->text( 0 ) ), \"\",\n KGuiItem( i18n(\"&Remove\" ), \"editdelete\") );\n if ( km == KMessageBox::Cancel ) return;\n\n\/\/ Don't be so restricitve\n#if 0\n if ( item->resource() == mCalendar->resourceManager()->standardResource() ) {\n KMessageBox::sorry( this,\n i18n( \"You cannot remove your standard resource.\" ) );\n return;\n }\n#endif\n if ( item->isSubresource() ) {\n \/\/ TODO delete the folder in KMail\n } else {\n mCalendar->resourceManager()->remove( item->resource() );\n mListView->takeItem( item );\n delete item;\n }\n emitResourcesChanged();\n}\n\nvoid ResourceView::editResource()\n{\n ResourceItem *item = currentItem();\n\n ResourceCalendar *resource = item->resource();\n\n KRES::ConfigDialog dlg( this, QString(\"calendar\"), resource,\n \"KRES::ConfigDialog\" );\n\n if ( dlg.exec() ) {\n item->setText( 0, resource->resourceName() );\n\n mCalendar->resourceManager()->change( resource );\n }\n}\n\nvoid ResourceView::currentChanged( QListViewItem *item)\n{\n ResourceItem *i = currentItem();\n if ( !item || i->isSubresource() ) {\n mDeleteButton->setEnabled( false );\n mEditButton->setEnabled( false );\n } else {\n mDeleteButton->setEnabled( true );\n mEditButton->setEnabled( true );\n }\n}\n\nResourceItem *ResourceView::findItem( ResourceCalendar *r )\n{\n QListViewItem *item;\n ResourceItem *i = 0;\n for( item = mListView->firstChild(); item; item = item->nextSibling() ) {\n i = static_cast( item );\n if ( i->resource() == r ) break;\n }\n return i;\n}\n\nResourceItem *ResourceView::findItemByIdentifier( const QString& id )\n{\n QListViewItem *item;\n ResourceItem *i = 0;\n for( item = mListView->firstChild(); item; item = item->itemBelow() ) {\n i = static_cast( item );\n if ( i->resourceIdentifier() == id )\n return i;\n }\n return 0;\n}\n\n\nvoid ResourceView::contextMenuRequested ( QListViewItem *i,\n const QPoint &pos, int )\n{\n ResourceItem *item = static_cast( i );\n\n QPopupMenu *menu = new QPopupMenu( this );\n connect( menu, SIGNAL( aboutToHide() ), menu, SLOT( deleteLater() ) );\n if ( item ) {\n int reloadId = menu->insertItem( i18n(\"Reload\"), this,\n SLOT( reloadResource() ) );\n menu->setItemEnabled( reloadId, item->resource()->isActive() );\n int saveId = menu->insertItem( i18n(\"Save\"), this,\n SLOT( saveResource() ) );\n menu->setItemEnabled( saveId, item->resource()->isActive() );\n menu->insertSeparator();\n menu->insertItem( i18n(\"Show Info\"), this, SLOT( showInfo() ) );\n if ( !item->isSubresource() ) {\n menu->insertItem( i18n(\"Edit...\"), this, SLOT( editResource() ) );\n menu->insertItem( i18n(\"Remove\"), this, SLOT( removeResource() ) );\n }\n menu->insertSeparator();\n }\n menu->insertItem( i18n(\"Add...\"), this, SLOT( addResource() ) );\n\n menu->popup( pos );\n}\n\nvoid ResourceView::showInfo()\n{\n ResourceItem *item = currentItem();\n if ( !item ) return;\n\n QString txt = \"\" + item->resource()->infoText() + \"<\/qt>\";\n KMessageBox::information( this, txt );\n}\n\nvoid ResourceView::reloadResource()\n{\n ResourceItem *item = currentItem();\n if ( !item ) return;\n\n ResourceCalendar *r = item->resource();\n r->load();\n}\n\nvoid ResourceView::saveResource()\n{\n ResourceItem *item = currentItem();\n if ( !item ) return;\n\n ResourceCalendar *r = item->resource();\n r->save();\n}\n\nvoid ResourceView::showButtons( bool visible )\n{\n if ( visible ) {\n mAddButton->show();\n mDeleteButton->show();\n mEditButton->show();\n } else {\n mAddButton->hide();\n mDeleteButton->hide();\n mEditButton->hide();\n }\n}\n\nvoid ResourceView::requestClose( ResourceCalendar *r )\n{\n mResourcesToClose.append( r );\n}\n\n#include \"resourceview.moc\"\nMake the Add and Remove buttons functional with subresources, in particular, make it possible to add Kolab folders in KMail from within KOrganizer, and remove them.\/*\n This file is part of KOrganizer.\n\n Copyright (c) 2003,2004 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 \"resourceview.h\"\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#include \n#include \n#include \n\n#include \"koprefs.h\"\n\nusing namespace KCal;\n\nResourceViewFactory::ResourceViewFactory( KCal::CalendarResources *calendar,\n CalendarView *view )\n : mCalendar( calendar ), mView( view ), mResourceView( 0 )\n{\n}\n\nCalendarViewExtension *ResourceViewFactory::create( QWidget *parent )\n{\n mResourceView = new ResourceView( mCalendar, parent );\n\n QObject::connect( mResourceView, SIGNAL( resourcesChanged() ),\n mView, SLOT( updateView() ) );\n QObject::connect( mResourceView, SIGNAL( resourcesChanged() ),\n mView, SLOT( updateCategories() ) );\n\n QObject::connect( mCalendar,\n SIGNAL( signalResourceAdded( ResourceCalendar * ) ),\n mResourceView,\n SLOT( addResourceItem( ResourceCalendar * ) ) );\n QObject::connect( mCalendar,\n SIGNAL( signalResourceModified( ResourceCalendar * ) ),\n mResourceView,\n SLOT( updateResourceItem( ResourceCalendar * ) ) );\n QObject::connect( mCalendar, SIGNAL( signalResourceAdded( ResourceCalendar * ) ),\n mView, SLOT( updateCategories() ) );\n QObject::connect( mCalendar, SIGNAL( signalResourceModified( ResourceCalendar * ) ),\n mView, SLOT( updateCategories() ) );\n\n return mResourceView;\n}\n\nResourceView *ResourceViewFactory::resourceView() const\n{\n return mResourceView;\n}\n\nResourceItem::ResourceItem( ResourceCalendar *resource, ResourceView *view,\n KListView *parent )\n : QCheckListItem( parent, resource->resourceName(), CheckBox ),\n mResource( resource ), mView( view ), mBlockStateChange( false ),\n mIsSubresource( false ), mResourceIdentifier(),\n mSubItemsCreated( false )\n{\n setGuiState();\n\n if ( mResource->isActive() ) {\n createSubresourceItems();\n }\n}\n\nvoid ResourceItem::createSubresourceItems() {\n const QStringList subresources = mResource->subresources();\n if ( !subresources.isEmpty() ) {\n setOpen( true );\n setExpandable( true );\n \/\/ This resource has subresources\n QStringList::ConstIterator it;\n for ( it=subresources.begin(); it!=subresources.end(); ++it ) {\n ( void )new ResourceItem( mResource, *it, mResource->labelForSubresource( *it ),\n mView, this );\n }\n }\n mSubItemsCreated = true;\n}\n\nResourceItem::ResourceItem( KCal::ResourceCalendar *resource,\n const QString& sub, const QString& label,\n ResourceView *view, ResourceItem* parent )\n\n : QCheckListItem( parent, label, CheckBox ), mResource( resource ),\n mView( view ), mBlockStateChange( false ), mIsSubresource( true ),\n mSubItemsCreated( false )\n{\n mResourceIdentifier = sub;\n setGuiState();\n}\n\nvoid ResourceItem::setGuiState()\n{\n mBlockStateChange = true;\n if ( mIsSubresource )\n setOn( mResource->subresourceActive( mResourceIdentifier ) );\n else\n setOn( mResource->isActive() );\n mBlockStateChange = false;\n}\n\nvoid ResourceItem::stateChange( bool active )\n{\n if ( mBlockStateChange ) return;\n\n if ( mIsSubresource ) {\n mResource->setSubresourceActive( mResourceIdentifier, active );\n } else {\n if ( active ) {\n if ( mResource->load() ) {\n mResource->setActive( true );\n if ( !mSubItemsCreated )\n createSubresourceItems();\n }\n } else {\n if ( mResource->save() ) mResource->setActive( false );\n mView->requestClose( mResource );\n }\n\n setOpen( mResource->isActive() && childCount() > 0 );\n\n setGuiState();\n }\n\n mView->emitResourcesChanged();\n}\n\nvoid ResourceItem::update()\n{\n setGuiState();\n}\n\nResourceView::ResourceView( KCal::CalendarResources *calendar,\n QWidget *parent, const char *name )\n : CalendarViewExtension( parent, name ), mCalendar( calendar )\n{\n QBoxLayout *topLayout = new QVBoxLayout( this );\n\n mListView = new KListView( this );\n mListView->addColumn( i18n(\"Calendar\") );\n mListView->setResizeMode( QListView::LastColumn );\n topLayout->addWidget( mListView );\n\n QHBox *buttonBox = new QHBox( this );\n topLayout->addWidget( buttonBox );\n\n mAddButton = new QPushButton( i18n(\"Add...\"), buttonBox, \"add\" );\n mEditButton = new QPushButton( i18n(\"Edit...\"), buttonBox, \"edit\" );\n mDeleteButton = new QPushButton( i18n(\"Remove\"), buttonBox, \"del\" );\n mEditButton->setDisabled( true );\n\n connect( mListView, SIGNAL( clicked( QListViewItem * ) ),\n SLOT( currentChanged( QListViewItem * ) ) );\n connect( mAddButton, SIGNAL( clicked() ), SLOT( addResource() ) );\n connect( mDeleteButton, SIGNAL( clicked() ), SLOT( removeResource() ) );\n connect( mEditButton, SIGNAL( clicked() ), SLOT( editResource() ) );\n connect( mListView, SIGNAL( doubleClicked ( QListViewItem *, const QPoint &,\n int ) ),\n SLOT( editResource() ) );\n connect( mListView, SIGNAL( contextMenuRequested ( QListViewItem *,\n const QPoint &, int ) ),\n SLOT( contextMenuRequested( QListViewItem *, const QPoint &,\n int ) ) );\n updateView();\n}\n\nResourceView::~ResourceView()\n{\n}\n\nvoid ResourceView::updateView()\n{\n mListView->clear();\n\n KCal::CalendarResourceManager *manager = mCalendar->resourceManager();\n\n KCal::CalendarResourceManager::Iterator it;\n for( it = manager->begin(); it != manager->end(); ++it ) {\n addResourceItem( *it );\n }\n}\n\nvoid ResourceView::emitResourcesChanged()\n{\n emit resourcesChanged();\n}\n\nvoid ResourceView::addResource()\n{\n bool ok = false;\n KCal::CalendarResourceManager *manager = mCalendar->resourceManager();\n ResourceItem *i = static_cast( mListView->selectedItem() );\n if ( i && ( i->isSubresource() || i->resource()->canHaveSubresources() ) ) {\n const QString folderName = KInputDialog::getText( i18n( \"Add Subresource\" ),\n i18n( \"Please enter a name for the new subresource\" ), QString::null,\n &ok, this );\n if ( !ok )\n return;\n const QString parentId = i->isSubresource() ? i->resourceIdentifier() : QString:: null;\n if ( !i->resource()->addSubresource( folderName, parentId ) ) {\n KMessageBox::error( this, i18n(\"Unable to create subresource %1<\/b>.<\/qt>\")\n .arg( folderName ) );\n }\n return;\n }\n \n QStringList types = manager->resourceTypeNames();\n QStringList descs = manager->resourceTypeDescriptions();\n QString desc = KInputDialog::getItem( i18n( \"Resource Configuration\" ),\n i18n( \"Please select type of the new resource:\" ), descs, 0, false, &ok,\n this );\n if ( !ok )\n return;\n\n QString type = types[ descs.findIndex( desc ) ];\n\n \/\/ Create new resource\n ResourceCalendar *resource = manager->createResource( type );\n if( !resource ) {\n KMessageBox::error( this, i18n(\"Unable to create resource of type %1<\/b>.<\/qt>\")\n .arg( type ) );\n return;\n }\n\n resource->setResourceName( i18n(\"%1 resource\").arg( type ) );\n\n KRES::ConfigDialog dlg( this, QString(\"calendar\"), resource,\n \"KRES::ConfigDialog\" );\n\n if ( dlg.exec() ) {\n resource->setTimeZoneId( KOPrefs::instance()->mTimeZoneId );\n if ( resource->isActive() ) {\n resource->open();\n resource->load();\n }\n manager->add( resource );\n addResourceItem( resource );\n } else {\n delete resource;\n resource = 0;\n }\n}\n\nvoid ResourceView::addResourceItem( ResourceCalendar *resource )\n{\n new ResourceItem( resource, this, mListView );\n\n connect( resource, SIGNAL( signalSubresourceAdded( ResourceCalendar *,\n const QString &,\n const QString &,\n const QString & ) ),\n SLOT( slotSubresourceAdded( ResourceCalendar *, const QString &,\n const QString &, const QString & ) ) );\n\n connect( resource, SIGNAL( signalSubresourceAdded( ResourceCalendar *,\n const QString &,\n const QString & ) ),\n SLOT( slotSubresourceAdded( ResourceCalendar *, const QString &,\n const QString & ) ) );\n \n connect( resource, SIGNAL( signalSubresourceRemoved( ResourceCalendar *,\n const QString &,\n const QString & ) ),\n SLOT( slotSubresourceRemoved( ResourceCalendar *, const QString &,\n const QString & ) ) );\n\n connect( resource, SIGNAL( resourceSaved( ResourceCalendar * ) ),\n SLOT( closeResource( ResourceCalendar * ) ) );\n\n emitResourcesChanged();\n}\n\n\n\/\/ FIXME proko2: merge once we are back in HEAD by porting imap resource\nvoid ResourceView::slotSubresourceAdded( ResourceCalendar *calendar,\n const QString& type,\n const QString& resource )\n{\n slotSubresourceAdded( calendar, type, resource, resource );\n}\n\n\/\/ Add a new entry\nvoid ResourceView::slotSubresourceAdded( ResourceCalendar *calendar,\n const QString& \/*type*\/,\n const QString& resource,\n const QString& label)\n{\n QListViewItem *i = mListView->findItem( calendar->resourceName(), 0 );\n if ( !i )\n \/\/ Not found\n return;\n\n ResourceItem *item = static_cast( i );\n ( void )new ResourceItem( calendar, resource, label, this, item );\n}\n\n\/\/ Remove an entry\nvoid ResourceView::slotSubresourceRemoved( ResourceCalendar *\/*calendar*\/,\n const QString &\/*type*\/,\n const QString &resource )\n{\n delete findItemByIdentifier( resource );\n emitResourcesChanged();\n}\n\nvoid ResourceView::closeResource( ResourceCalendar *r )\n{\n if ( mResourcesToClose.find( r ) >= 0 ) {\n r->close();\n mResourcesToClose.remove( r );\n }\n}\n\nvoid ResourceView::updateResourceItem( ResourceCalendar *resource )\n{\n ResourceItem *item = findItem( resource );\n if ( item ) {\n item->update();\n }\n}\n\nResourceItem *ResourceView::currentItem()\n{\n QListViewItem *item = mListView->currentItem();\n ResourceItem *rItem = static_cast( item );\n return rItem;\n}\n\nvoid ResourceView::removeResource()\n{\n ResourceItem *item = currentItem();\n if ( !item ) return;\n\n const QString warningMsg = item->isSubresource() ?\n i18n(\"Do you really want to remove the subresource %1<\/b>? \"\n \"Note that its contents will be completely deleted. This \"\n \"operation cannot be undone. <\/qt>\").arg( item->text( 0 ) ) :\n i18n(\"Do you really want to remove the resource %1<\/b>?<\/qt>\").arg( item->text( 0 ) );\n\n int km = KMessageBox::warningContinueCancel( this, warningMsg, \"\",\n KGuiItem( i18n(\"&Remove\" ), \"editdelete\") );\n if ( km == KMessageBox::Cancel ) return;\n\n\/\/ Don't be so restricitve\n#if 0\n if ( item->resource() == mCalendar->resourceManager()->standardResource() ) {\n KMessageBox::sorry( this,\n i18n( \"You cannot remove your standard resource.\" ) );\n return;\n }\n#endif\n if ( item->isSubresource() ) {\n if ( !item->resource()->removeSubresource( item->resourceIdentifier() ) )\n KMessageBox::sorry( this,\n i18n (\"Failed to remove the subresource %1<\/b>. The \"\n \"reason could be that it is a built-in one which cannot \"\n \"be removed, or that the removal of the underlying storage \"\n \"folder failed.<\/qt>\").arg( item->resource()->name() ) );\n return;\n } else {\n mCalendar->resourceManager()->remove( item->resource() );\n }\n mListView->takeItem( item );\n delete item;\n emitResourcesChanged();\n}\n\nvoid ResourceView::editResource()\n{\n ResourceItem *item = currentItem();\n\n ResourceCalendar *resource = item->resource();\n\n KRES::ConfigDialog dlg( this, QString(\"calendar\"), resource,\n \"KRES::ConfigDialog\" );\n\n if ( dlg.exec() ) {\n item->setText( 0, resource->resourceName() );\n\n mCalendar->resourceManager()->change( resource );\n }\n}\n\nvoid ResourceView::currentChanged( QListViewItem *item)\n{\n ResourceItem *i = currentItem();\n if ( !item || i->isSubresource() ) {\n mEditButton->setEnabled( false );\n } else {\n mEditButton->setEnabled( true );\n }\n}\n\nResourceItem *ResourceView::findItem( ResourceCalendar *r )\n{\n QListViewItem *item;\n ResourceItem *i = 0;\n for( item = mListView->firstChild(); item; item = item->nextSibling() ) {\n i = static_cast( item );\n if ( i->resource() == r ) break;\n }\n return i;\n}\n\nResourceItem *ResourceView::findItemByIdentifier( const QString& id )\n{\n QListViewItem *item;\n ResourceItem *i = 0;\n for( item = mListView->firstChild(); item; item = item->itemBelow() ) {\n i = static_cast( item );\n if ( i->resourceIdentifier() == id )\n return i;\n }\n return 0;\n}\n\n\nvoid ResourceView::contextMenuRequested ( QListViewItem *i,\n const QPoint &pos, int )\n{\n ResourceItem *item = static_cast( i );\n\n QPopupMenu *menu = new QPopupMenu( this );\n connect( menu, SIGNAL( aboutToHide() ), menu, SLOT( deleteLater() ) );\n if ( item ) {\n int reloadId = menu->insertItem( i18n(\"Reload\"), this,\n SLOT( reloadResource() ) );\n menu->setItemEnabled( reloadId, item->resource()->isActive() );\n int saveId = menu->insertItem( i18n(\"Save\"), this,\n SLOT( saveResource() ) );\n menu->setItemEnabled( saveId, item->resource()->isActive() );\n menu->insertSeparator();\n menu->insertItem( i18n(\"Show Info\"), this, SLOT( showInfo() ) );\n if ( !item->isSubresource() ) {\n menu->insertItem( i18n(\"Edit...\"), this, SLOT( editResource() ) );\n menu->insertItem( i18n(\"Remove\"), this, SLOT( removeResource() ) );\n }\n menu->insertSeparator();\n }\n menu->insertItem( i18n(\"Add...\"), this, SLOT( addResource() ) );\n\n menu->popup( pos );\n}\n\nvoid ResourceView::showInfo()\n{\n ResourceItem *item = currentItem();\n if ( !item ) return;\n\n QString txt = \"\" + item->resource()->infoText() + \"<\/qt>\";\n KMessageBox::information( this, txt );\n}\n\nvoid ResourceView::reloadResource()\n{\n ResourceItem *item = currentItem();\n if ( !item ) return;\n\n ResourceCalendar *r = item->resource();\n r->load();\n}\n\nvoid ResourceView::saveResource()\n{\n ResourceItem *item = currentItem();\n if ( !item ) return;\n\n ResourceCalendar *r = item->resource();\n r->save();\n}\n\nvoid ResourceView::showButtons( bool visible )\n{\n if ( visible ) {\n mAddButton->show();\n mDeleteButton->show();\n mEditButton->show();\n } else {\n mAddButton->hide();\n mDeleteButton->hide();\n mEditButton->hide();\n }\n}\n\nvoid ResourceView::requestClose( ResourceCalendar *r )\n{\n mResourcesToClose.append( r );\n}\n\n#include \"resourceview.moc\"\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2004, Mart Kelder (mart.kde@hccnet.nl)\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\n#include \"kio_single_subject.h\"\n\n#include \"mailsubject.h\"\n#include \"kio_proto.h\"\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\/\/Added by qt3to4:\n#include \n\nKIO_Single_Subject::KIO_Single_Subject( QObject * parent,\n\t\t KUrl &kurl, KIO::MetaData &metadata, const KIO_Protocol * protocol, KIO::Slave *& slave,\n\t\t const QString &url, const long size )\n\t\t: QObject( parent )\n{\n\t_kurl = new KUrl( kurl );\n\t_metadata = new KIO::MetaData( metadata );\n\t_protocol = protocol;\n\t_name = new QString( url );\n\t_size = size;\n\t_message = new QString;\n\n\tinit( slave );\n}\n\nKIO_Single_Subject::~KIO_Single_Subject( )\n{\n\tif( _job )\n\t\tKIO::Scheduler::cancelJob( _job );\n\tdelete _kurl;\n\tdelete _metadata;\n\tdelete _name;\n\tdelete _message;\n}\n\nvoid KIO_Single_Subject::init( KIO::Slave *& slave)\n{\n\t_job = KIO::get( *_kurl, false, false );\n\t_job->addMetaData( *_metadata );\n\n\tconnect( _job, SIGNAL( result( KJob* ) ), this, SLOT( slotResult( KJob* ) ) );\n\tconnect( _job, SIGNAL( data (KIO::Job *, const QByteArray &) ),\n\t this, SLOT( slotData(KIO::Job *, const QByteArray &) ) );\n\n\tif( _protocol->connectionBased( ) && slave )\n\t\tKIO::Scheduler::assignJobToSlave( slave , _job );\n\telse\n\t\tKIO::Scheduler::scheduleJob( _job );\n\n}\n\nvoid KIO_Single_Subject::parseMail( QString * message, KornMailSubject *subject, bool fullMessage )\n{\n\tQTextStream stream( message, QIODevice::ReadOnly );\n\tQString line;\n\tQRegExp rx_sender( \"^[fF]rom: \" ); \/\/Ex: From: ...\n\tQRegExp rx_sender_has_name1( \"^[fF]rom:\\\\s*(\\\\w+[\\\\w\\\\s]*)\\\\<\" ); \/\/Ex: From: A name\n\tQRegExp rx_sender_has_name2( \"^[fF]rom:\\\\s*\\\\\\\"\\\\s*(\\\\w+[\\\\w\\\\s]*)\\\\\\\"\"); \/\/Ex: From: \"A name\"\n\tQRegExp rx_subject( \"^[sS]ubject: \" ); \/\/Ex: Subject: ...\n\tQRegExp rx_date ( \"^[dD]ate: \");\n\tbool inheader = true;\n\tint fieldnumber = 0;\n\n\twhile ( ! stream.atEnd() )\n\t{\n\t\tline = stream.readLine();\n\t\tif( line.isEmpty() && fieldnumber >= 2 )\n\t\t\tinheader = false;\n\n\t\tif( inheader )\n\t\t{\n\t\t\tif( rx_sender.indexIn( line ) == 0 )\n\t\t\t{\n\t\t\t\tif( rx_sender_has_name1.indexIn( line ) == 0 )\n\t\t\t\t\tsubject->setSender( rx_sender_has_name1.cap( 1 ) );\n\t\t\t\telse if(rx_sender_has_name2.indexIn( line ) == 0)\n\t\t\t\t\tsubject->setSender( rx_sender_has_name2.cap( 1 ) );\n\t\t\t\telse\n\t\t\t\t\tsubject->setSender( line.remove( rx_sender ) );\n\t\t\t\t++fieldnumber;\n\t\t\t}\n\t\t\telse if( rx_subject.indexIn( line ) == 0 )\n\t\t\t{\n\t\t\t\tsubject->setSubject( line.remove( rx_subject ) );\n\t\t\t\t++fieldnumber;\n\t\t\t}\n\t\t\telse if( rx_date.indexIn( line ) == 0 )\n\t\t\t{\n\t \tsubject->setDate( KRFCDate::parseDate( line.right( line.length() - 6 ) ) );\n\t\t\t\t++fieldnumber;\n\t\t\t}\n\t\t}\n\t}\n\n\tsubject->setHeader( *message, fullMessage );\n}\n\nvoid KIO_Single_Subject::slotData( KIO::Job* job, const QByteArray& data )\n{\n\tif( job != _job )\n\t\tkWarning() << i18n( \"Got invalid job; something strange happened?\" ) << endl;\n\tif( !data.isEmpty() )\n\t\t_message->append( data );\n}\n\n\/\/KIO::Scheduler::disconnectSlave missing if connection stops\nvoid KIO_Single_Subject::slotResult( KJob *job )\n{\n\tif( job != _job )\n\t\tkWarning() << i18n( \"Got invalid job; something strange happened?\" ) << endl;\n\n\tif( job->error() )\n\t{\n\t\tkWarning() << i18n( \"Error when fetching %1: %2\", *_name, job->errorString() ) << endl;\n\t} else {\n\t\tKornMailSubject * mailSubject = new KornMailSubject( QVariant( *_name ), 0 );\n\t\tparseMail( _message, mailSubject, _protocol->fullMessage() );\n\t\tmailSubject->setSize( _size );\n\t\temit readSubject( mailSubject );\n\t}\n\n\t_job = 0;\n\n\temit finished( this );\n}\n\n#include \"kio_single_subject.moc\"\nport to kdatetime\/*\n * Copyright (C) 2004, Mart Kelder (mart.kde@hccnet.nl)\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\n#include \"kio_single_subject.h\"\n\n#include \"mailsubject.h\"\n#include \"kio_proto.h\"\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\/\/Added by qt3to4:\n#include \n\nKIO_Single_Subject::KIO_Single_Subject( QObject * parent,\n\t\t KUrl &kurl, KIO::MetaData &metadata, const KIO_Protocol * protocol, KIO::Slave *& slave,\n\t\t const QString &url, const long size )\n\t\t: QObject( parent )\n{\n\t_kurl = new KUrl( kurl );\n\t_metadata = new KIO::MetaData( metadata );\n\t_protocol = protocol;\n\t_name = new QString( url );\n\t_size = size;\n\t_message = new QString;\n\n\tinit( slave );\n}\n\nKIO_Single_Subject::~KIO_Single_Subject( )\n{\n\tif( _job )\n\t\tKIO::Scheduler::cancelJob( _job );\n\tdelete _kurl;\n\tdelete _metadata;\n\tdelete _name;\n\tdelete _message;\n}\n\nvoid KIO_Single_Subject::init( KIO::Slave *& slave)\n{\n\t_job = KIO::get( *_kurl, false, false );\n\t_job->addMetaData( *_metadata );\n\n\tconnect( _job, SIGNAL( result( KJob* ) ), this, SLOT( slotResult( KJob* ) ) );\n\tconnect( _job, SIGNAL( data (KIO::Job *, const QByteArray &) ),\n\t this, SLOT( slotData(KIO::Job *, const QByteArray &) ) );\n\n\tif( _protocol->connectionBased( ) && slave )\n\t\tKIO::Scheduler::assignJobToSlave( slave , _job );\n\telse\n\t\tKIO::Scheduler::scheduleJob( _job );\n\n}\n\nvoid KIO_Single_Subject::parseMail( QString * message, KornMailSubject *subject, bool fullMessage )\n{\n\tQTextStream stream( message, QIODevice::ReadOnly );\n\tQString line;\n\tQRegExp rx_sender( \"^[fF]rom: \" ); \/\/Ex: From: ...\n\tQRegExp rx_sender_has_name1( \"^[fF]rom:\\\\s*(\\\\w+[\\\\w\\\\s]*)\\\\<\" ); \/\/Ex: From: A name\n\tQRegExp rx_sender_has_name2( \"^[fF]rom:\\\\s*\\\\\\\"\\\\s*(\\\\w+[\\\\w\\\\s]*)\\\\\\\"\"); \/\/Ex: From: \"A name\"\n\tQRegExp rx_subject( \"^[sS]ubject: \" ); \/\/Ex: Subject: ...\n\tQRegExp rx_date ( \"^[dD]ate: \");\n\tbool inheader = true;\n\tint fieldnumber = 0;\n\n\twhile ( ! stream.atEnd() )\n\t{\n\t\tline = stream.readLine();\n\t\tif( line.isEmpty() && fieldnumber >= 2 )\n\t\t\tinheader = false;\n\n\t\tif( inheader )\n\t\t{\n\t\t\tif( rx_sender.indexIn( line ) == 0 )\n\t\t\t{\n\t\t\t\tif( rx_sender_has_name1.indexIn( line ) == 0 )\n\t\t\t\t\tsubject->setSender( rx_sender_has_name1.cap( 1 ) );\n\t\t\t\telse if(rx_sender_has_name2.indexIn( line ) == 0)\n\t\t\t\t\tsubject->setSender( rx_sender_has_name2.cap( 1 ) );\n\t\t\t\telse\n\t\t\t\t\tsubject->setSender( line.remove( rx_sender ) );\n\t\t\t\t++fieldnumber;\n\t\t\t}\n\t\t\telse if( rx_subject.indexIn( line ) == 0 )\n\t\t\t{\n\t\t\t\tsubject->setSubject( line.remove( rx_subject ) );\n\t\t\t\t++fieldnumber;\n\t\t\t}\n\t\t\telse if( rx_date.indexIn( line ) == 0 )\n\t\t\t{\n\t\t\t\tKDateTime dt = KDateTime::fromString( line.right( line.length() - 6 ),\n\t\t\t\t\t\t\t\t\tKDateTime::RFCDate );\n\t \tsubject->setDate( dt.toTime_t() );\n\t\t\t\t++fieldnumber;\n\t\t\t}\n\t\t}\n\t}\n\n\tsubject->setHeader( *message, fullMessage );\n}\n\nvoid KIO_Single_Subject::slotData( KIO::Job* job, const QByteArray& data )\n{\n\tif( job != _job )\n\t\tkWarning() << i18n( \"Got invalid job; something strange happened?\" ) << endl;\n\tif( !data.isEmpty() )\n\t\t_message->append( data );\n}\n\n\/\/KIO::Scheduler::disconnectSlave missing if connection stops\nvoid KIO_Single_Subject::slotResult( KJob *job )\n{\n\tif( job != _job )\n\t\tkWarning() << i18n( \"Got invalid job; something strange happened?\" ) << endl;\n\n\tif( job->error() )\n\t{\n\t\tkWarning() << i18n( \"Error when fetching %1: %2\", *_name, job->errorString() ) << endl;\n\t} else {\n\t\tKornMailSubject * mailSubject = new KornMailSubject( QVariant( *_name ), 0 );\n\t\tparseMail( _message, mailSubject, _protocol->fullMessage() );\n\t\tmailSubject->setSize( _size );\n\t\temit readSubject( mailSubject );\n\t}\n\n\t_job = 0;\n\n\temit finished( this );\n}\n\n#include \"kio_single_subject.moc\"\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\n\nstatic float CalcRadius(const Mesh* m)\n{\n\tconst Block& b = m->GetRawDatas();\n\tfloat maxSq = 0;\n\tfor (auto& it : b.vertices) {\n\t\tfloat sq = XMVectorGetX(XMVector3LengthSq(XMLoadFloat3(&it.xyz)));\n\t\tmaxSq = std::max(maxSq, sq);\n\t}\n\treturn sqrt(maxSq);\n}\n\nApp::App() : scale(1), lastX(-1), lastY(-1), meshTiny(nullptr)\n{\n\tquat = XMQuaternionIdentity();\n\tZeroMemory(mesh, sizeof(mesh));\n}\n\nApp::~App()\n{\n}\n\nvoid App::Init(const char* fileName)\n{\n\tDestroy();\n\n\tmeshTiny = new MeshX(\"C:\\\\Program Files (x86)\\\\Microsoft DirectX SDK (August 2009)\\\\Samples\\\\Media\\\\Tiny\\\\tiny.x\");\n\n\tif (fileName) {\n\t\tconst char* ext = strrchr(fileName, '.');\n\t\tmesh[0] = new Bvh(fileName);\n\t} else {\n\t\tmesh[0] = new Bvh(\"D:\\\\github\\\\aachan.bvh\");\n\t\tmesh[1] = new Bvh(\"D:\\\\github\\\\kashiyuka.bvh\");\n\t\tmesh[2] = new Bvh(\"D:\\\\github\\\\nocchi.bvh\");\n\t}\n\n\tfloat radius = CalcRadius(mesh[0]);\n\tscale = 1 \/ std::max(0.00001f, radius);\n\n\tmatrixMan.Set(MatrixMan::PROJ, XMMatrixPerspectiveFovLH(45 * XM_PI \/ 180, (float)SCR_W \/ SCR_H, 0.1f, 1000.0f));\n}\n\nvoid App::MouseWheel(float delta)\n{\n\tif (delta > 0) {\n\t\tscale *= 1.1f;\n\t}\n\tif (delta < 0) {\n\t\tscale \/= 1.1f;\n\t}\n}\n\nvoid App::LButtonDown(float x, float y)\n{\n\tlastX = x;\n\tlastY = y;\n}\n\nvoid App::LButtonUp(float x, float y)\n{\n\tMouseMove(x, y);\n\tlastX = lastY = -1;\n}\n\nvoid App::MouseMove(float x, float y)\n{\n\tif (lastX < 0 || lastY < 0) {\n\t\treturn;\n\t}\n\tfloat dx = x - lastX;\n\tfloat dy = - (y - lastY);\n\n\tlastX = x;\n\tlastY = y;\n\n\tXMVECTOR axis = XMVectorSet(-dy, dx, 0, 0);\n\tfloat len = XMVectorGetX(XMVector2Length(axis));\n\tif (!len) {\n\t\treturn;\n\t}\n\n\tXMVECTOR q = XMQuaternionRotationAxis(axis, len * -2 * XM_PI);\n\tquat = XMQuaternionMultiply(quat, q);\n}\n\nvoid App::Draw()\n{\n\tLARGE_INTEGER t, f;\n\tQueryPerformanceCounter(&t);\n\tQueryPerformanceFrequency(&f);\n\tfloat time = (float)((double)t.QuadPart \/ f.QuadPart);\n\n\/\/\tXMMATRIX mRot = XMMatrixRotationQuaternion(XMQuaternionRotationAxis(XMVectorSet(1, 0, 0, 0), time \/ 2 * XM_PI));\n\tXMMATRIX mRot = XMMatrixRotationQuaternion(quat);\n\tXMMATRIX mScale = XMMatrixScaling(scale, scale, scale);\n\n\tmatrixMan.Set(MatrixMan::WORLD, mScale * mRot);\n\n\tfloat dist = 3;\n\/\/\tfloat rot = time \/ 5 * XM_PI;\n\tfloat rot = XM_PI;\n\tmatrixMan.Set(MatrixMan::VIEW, XMMatrixLookAtLH(XMVectorSet(sin(rot) * dist, 0, cos(rot) * dist, 1), XMVectorSet(0, 0, 0, 0), XMVectorSet(0, 1, 0, 0)));\n\n\tfor (auto& it : mesh) {\n\t\tif (it && meshTiny) {\n\/\/\t\t\tit->Draw(0, time);\n\t\t\tmeshTiny->DrawBvh(it, time);\n\t\t}\n\t}\n}\n\nvoid App::Destroy()\n{\n\tSAFE_DELETE(mesh[0]);\n\tSAFE_DELETE(mesh[1]);\n\tSAFE_DELETE(mesh[2]);\n\tSAFE_DELETE(meshTiny);\n}\nfor test#include \"stdafx.h\"\n\nstatic float CalcRadius(const Mesh* m)\n{\n\tconst Block& b = m->GetRawDatas();\n\tfloat maxSq = 0;\n\tfor (auto& it : b.vertices) {\n\t\tfloat sq = XMVectorGetX(XMVector3LengthSq(XMLoadFloat3(&it.xyz)));\n\t\tmaxSq = std::max(maxSq, sq);\n\t}\n\treturn sqrt(maxSq);\n}\n\nApp::App() : scale(1), lastX(-1), lastY(-1), meshTiny(nullptr)\n{\n\tquat = XMQuaternionIdentity();\n\tZeroMemory(mesh, sizeof(mesh));\n}\n\nApp::~App()\n{\n}\n\nvoid App::Init(const char* fileName)\n{\n\tDestroy();\n\n\tmeshTiny = new MeshX(\"C:\\\\Program Files (x86)\\\\Microsoft DirectX SDK (August 2009)\\\\Samples\\\\Media\\\\Tiny\\\\tiny.x\");\n\n\tif (fileName) {\n\t\tconst char* ext = strrchr(fileName, '.');\n\t\tmesh[0] = new Bvh(fileName);\n\t} else {\n\t\tmesh[0] = new Bvh(\"D:\\\\github\\\\aachan.bvh\");\n\t\tmesh[1] = new Bvh(\"D:\\\\github\\\\kashiyuka.bvh\");\n\t\tmesh[2] = new Bvh(\"D:\\\\github\\\\nocchi.bvh\");\n\t}\n\n\tfloat radius = CalcRadius(mesh[0]);\n\tscale = 1 \/ std::max(0.00001f, radius);\n\n\tmatrixMan.Set(MatrixMan::PROJ, XMMatrixPerspectiveFovLH(45 * XM_PI \/ 180, (float)SCR_W \/ SCR_H, 0.1f, 1000.0f));\n}\n\nvoid App::MouseWheel(float delta)\n{\n\tif (delta > 0) {\n\t\tscale *= 1.1f;\n\t}\n\tif (delta < 0) {\n\t\tscale \/= 1.1f;\n\t}\n}\n\nvoid App::LButtonDown(float x, float y)\n{\n\tlastX = x;\n\tlastY = y;\n}\n\nvoid App::LButtonUp(float x, float y)\n{\n\tMouseMove(x, y);\n\tlastX = lastY = -1;\n}\n\nvoid App::MouseMove(float x, float y)\n{\n\tif (lastX < 0 || lastY < 0) {\n\t\treturn;\n\t}\n\tfloat dx = x - lastX;\n\tfloat dy = - (y - lastY);\n\n\tlastX = x;\n\tlastY = y;\n\n\tXMVECTOR axis = XMVectorSet(-dy, dx, 0, 0);\n\tfloat len = XMVectorGetX(XMVector2Length(axis));\n\tif (!len) {\n\t\treturn;\n\t}\n\n\tXMVECTOR q = XMQuaternionRotationAxis(axis, len * -2 * XM_PI);\n\tquat = XMQuaternionMultiply(quat, q);\n}\n\nvoid App::Draw()\n{\n\tLARGE_INTEGER t, f;\n\tQueryPerformanceCounter(&t);\n\tQueryPerformanceFrequency(&f);\n\tfloat time = (float)((double)t.QuadPart \/ f.QuadPart);\n\n\/\/\tXMMATRIX mRot = XMMatrixRotationQuaternion(XMQuaternionRotationAxis(XMVectorSet(1, 0, 0, 0), time \/ 2 * XM_PI));\n\tXMMATRIX mRot = XMMatrixRotationQuaternion(quat);\n\tXMMATRIX mScale = XMMatrixScaling(scale, scale, scale);\n\n\tmatrixMan.Set(MatrixMan::WORLD, mScale * mRot);\n\n\tfloat dist = 3;\n\/\/\tfloat rot = time \/ 5 * XM_PI;\n\tfloat rot = XM_PI;\n\tmatrixMan.Set(MatrixMan::VIEW, XMMatrixLookAtLH(XMVectorSet(sin(rot) * dist, 0, cos(rot) * dist, 1), XMVectorSet(0, 0, 0, 0), XMVectorSet(0, 1, 0, 0)));\n\n\tfor (auto& it : mesh) {\n\t\tif (it && meshTiny) {\n\t\t\tit->Draw(0, time);\n\t\t\tmeshTiny->DrawBvh(it, time);\n\t\t}\n\t}\n}\n\nvoid App::Destroy()\n{\n\tSAFE_DELETE(mesh[0]);\n\tSAFE_DELETE(mesh[1]);\n\tSAFE_DELETE(mesh[2]);\n\tSAFE_DELETE(meshTiny);\n}\n<|endoftext|>"} {"text":"#include \"Camera.hpp\"\n\nCamera::Camera() {\n\t\/\/ TODO: Should be defined dynamically\n\tm_inputModel.bindKey(GLFW_KEY_W,\n\t [&]() { m_spatialModel.translate(1.0f, 0.0f, 0.0f); });\n\n\tm_inputModel.bindKey(GLFW_KEY_A,\n\t [&]() { m_spatialModel.translate(0.0f, 1.0f, 0.0f); });\n\n\tm_inputModel.bindKey(GLFW_KEY_S,\n\t [&]() { m_spatialModel.translate(-1.0f, 0.0f, 0.0f); });\n\n\tm_inputModel.bindKey(GLFW_KEY_D,\n\t [&]() { m_spatialModel.translate(0.0f, -1.0f, 0.0f); });\n\n\tm_inputModel.bindKey(GLFW_KEY_Z,\n\t [&]() { m_spatialModel.translate(0.0f, 0.0f, 1.0f); });\n\n\tm_inputModel.bindKey(GLFW_KEY_X,\n\t [&]() { m_spatialModel.translate(0.0f, 0.0f, -1.0f); });\n\n\tm_inputModel.bindMouse([&](glm::dvec2 lastPos, glm::dvec2 newPos) {\n\t\tm_spatialModel.rotate(0.0f,\n\t\t -((newPos.y - lastPos.y) \/ 128.0f),\n\t\t -((newPos.x - lastPos.x) \/ 128.0f));\n\t\tstd::stringstream message;\n\t\tmessage << \"Mouse moved: \" << lastPos.x << \",\" << lastPos.y << \" -> \"\n\t\t << newPos.x << \",\" << newPos.y;\n\t\tg_logger->write(Logger::LOG_DEBUG, message.str());\n\t});\n}\n\nglm::vec4 Camera::getPosition() { return m_spatialModel.position(); }\n\nglm::mat4 Camera::getViewMatrix() {\n\tglm::mat4 orientationMatrix = glm::mat4_cast(m_spatialModel.orientation());\n\n\tglm::vec4 forward = orientationMatrix * SpatialModel::canonicalForward;\n\tglm::vec4 up = orientationMatrix * SpatialModel::canonicalUp;\n\n\tm_viewMatrix = glm::lookAt(glm::vec3(m_spatialModel.position()),\n\t glm::vec3(m_spatialModel.position() + forward),\n\t glm::vec3(up));\n\n\treturn m_viewMatrix;\n}\n\nvoid Camera::processInput(GLFWwindow& window) { m_inputModel.update(window); }\nRemove old, noisy debug message#include \"Camera.hpp\"\n\nCamera::Camera() {\n\t\/\/ TODO: Should be defined dynamically\n\tm_inputModel.bindKey(GLFW_KEY_W,\n\t [&]() { m_spatialModel.translate(1.0f, 0.0f, 0.0f); });\n\n\tm_inputModel.bindKey(GLFW_KEY_A,\n\t [&]() { m_spatialModel.translate(0.0f, 1.0f, 0.0f); });\n\n\tm_inputModel.bindKey(GLFW_KEY_S,\n\t [&]() { m_spatialModel.translate(-1.0f, 0.0f, 0.0f); });\n\n\tm_inputModel.bindKey(GLFW_KEY_D,\n\t [&]() { m_spatialModel.translate(0.0f, -1.0f, 0.0f); });\n\n\tm_inputModel.bindKey(GLFW_KEY_Z,\n\t [&]() { m_spatialModel.translate(0.0f, 0.0f, 1.0f); });\n\n\tm_inputModel.bindKey(GLFW_KEY_X,\n\t [&]() { m_spatialModel.translate(0.0f, 0.0f, -1.0f); });\n\n\tm_inputModel.bindMouse([&](glm::dvec2 lastPos, glm::dvec2 newPos) {\n\t\tm_spatialModel.rotate(0.0f,\n\t\t -((newPos.y - lastPos.y) \/ 128.0f),\n\t\t -((newPos.x - lastPos.x) \/ 128.0f));\n\t});\n}\n\nglm::vec4 Camera::getPosition() { return m_spatialModel.position(); }\n\nglm::mat4 Camera::getViewMatrix() {\n\tglm::mat4 orientationMatrix = glm::mat4_cast(m_spatialModel.orientation());\n\n\tglm::vec4 forward = orientationMatrix * SpatialModel::canonicalForward;\n\tglm::vec4 up = orientationMatrix * SpatialModel::canonicalUp;\n\n\tm_viewMatrix = glm::lookAt(glm::vec3(m_spatialModel.position()),\n\t glm::vec3(m_spatialModel.position() + forward),\n\t glm::vec3(up));\n\n\treturn m_viewMatrix;\n}\n\nvoid Camera::processInput(GLFWwindow& window) { m_inputModel.update(window); }\n<|endoftext|>"} {"text":"#ifndef _ESP_BRACZ_DEADRAIL_PROTO_HARDWARE_HXX_\n#define _ESP_BRACZ_DEADRAIL_PROTO_HARDWARE_HXX_\n\n#include \"freertos_drivers\/esp8266\/Esp8266Gpio.hxx\"\n#include \"freertos_drivers\/common\/BlinkerGPIO.hxx\"\n#include \"freertos_drivers\/common\/DummyGPIO.hxx\"\n#include \"utils\/GpioInitializer.hxx\"\n\nstruct HW\n{\n GPIO_PIN(BLINKER_RAW, GpioOutputSafeHigh, 2);\n static constexpr bool blinker_invert = true;\n\n GPIO_PIN(MOT_A_HI, GpioOutputSafeLow, 14);\n GPIO_PIN(MOT_A_LO, GpioOutputSafeLow, 12);\n\n GPIO_PIN(MOT_B_HI, GpioOutputSafeLow, 5);\n GPIO_PIN(MOT_B_LO, GpioOutputSafeLow, 13);\n\n static constexpr bool invertLow = false;\n\n \/\/ forward: A=HI B=LO\n\n \/\/ typedef BLINKER_Pin LIGHT_FRONT_Pin;\n typedef DummyPin LIGHT_BACK_Pin;\n \/\/GPIO_PIN(LIGHT_BACK, GpioOutputSafeLow, ??? RX pin);\n \/\/typedef DummyPin LIGHT_FRONT_Pin;\n \/\/GPIO_PIN(LIGHT_FRONT, GpioOutputSafeLow, 4);\n GPIO_PIN(LIGHT_FRONT, GpioOutputSafeLow, 4);\n typedef DummyPin F1_Pin;\n\n \/\/ Doubles as manual request pin.\n GPIO_PIN(REQ_BLOAD, GpioInputPU, 4);\n\n GPIO_PIN(ASEL1, GpioOutputSafeHigh, 0);\n typedef BLINKER_Pin ASEL2_Pin;\n \/\/GPIO_PIN(ASEL2, GpioOutputSafeHigh, 2);\n\n GPIO_PIN(CHRG_EN, GpioOutputSafeLow, 15);\n\n typedef DummyPin BootloaderActivePin;\n\n typedef GpioInitializer< \/\/\n MOT_A_HI_Pin, MOT_A_LO_Pin, \/\/\n MOT_B_HI_Pin, MOT_B_LO_Pin, \/\/\n LIGHT_FRONT_Pin, LIGHT_BACK_Pin, \/\/\n ASEL1_Pin, ASEL2_Pin, \/\/\n CHRG_EN_Pin> GpioInit;\n\n\n typedef GpioInitializer< \/\/\n MOT_A_HI_Pin, MOT_A_LO_Pin, \/\/\n MOT_B_HI_Pin, MOT_B_LO_Pin, \/\/\n \/\/LIGHT_FRONT_Pin, LIGHT_BACK_Pin, \/\/\n ASEL1_Pin, ASEL2_Pin, \/\/\n REQ_BLOAD_Pin, \/\/\n CHRG_EN_Pin> GpioBootloaderInit;\n\n};\n\n\n#endif \/\/ _ESP_DEADRAIL_PROTO_HARDWARE_HXX_\nSwitch motor outputs.#ifndef _ESP_BRACZ_DEADRAIL_PROTO_HARDWARE_HXX_\n#define _ESP_BRACZ_DEADRAIL_PROTO_HARDWARE_HXX_\n\n#include \"freertos_drivers\/esp8266\/Esp8266Gpio.hxx\"\n#include \"freertos_drivers\/common\/BlinkerGPIO.hxx\"\n#include \"freertos_drivers\/common\/DummyGPIO.hxx\"\n#include \"utils\/GpioInitializer.hxx\"\n\nstruct HW\n{\n GPIO_PIN(BLINKER_RAW, GpioOutputSafeHigh, 2);\n static constexpr bool blinker_invert = true;\n\n GPIO_PIN(MOT_A_HI, GpioOutputSafeLow, 5);\n GPIO_PIN(MOT_A_LO, GpioOutputSafeLow, 13);\n\n GPIO_PIN(MOT_B_HI, GpioOutputSafeLow, 14);\n GPIO_PIN(MOT_B_LO, GpioOutputSafeLow, 12);\n\n static constexpr bool invertLow = false;\n\n \/\/ forward: A=HI B=LO\n\n \/\/ typedef BLINKER_Pin LIGHT_FRONT_Pin;\n typedef DummyPin LIGHT_BACK_Pin;\n \/\/GPIO_PIN(LIGHT_BACK, GpioOutputSafeLow, ??? RX pin);\n \/\/typedef DummyPin LIGHT_FRONT_Pin;\n \/\/GPIO_PIN(LIGHT_FRONT, GpioOutputSafeLow, 4);\n GPIO_PIN(LIGHT_FRONT, GpioOutputSafeLow, 4);\n typedef DummyPin F1_Pin;\n\n \/\/ Doubles as manual request pin.\n GPIO_PIN(REQ_BLOAD, GpioInputPU, 4);\n\n GPIO_PIN(ASEL1, GpioOutputSafeHigh, 0);\n typedef BLINKER_Pin ASEL2_Pin;\n \/\/GPIO_PIN(ASEL2, GpioOutputSafeHigh, 2);\n\n GPIO_PIN(CHRG_EN, GpioOutputSafeLow, 15);\n\n typedef DummyPin BootloaderActivePin;\n\n typedef GpioInitializer< \/\/\n MOT_A_HI_Pin, MOT_A_LO_Pin, \/\/\n MOT_B_HI_Pin, MOT_B_LO_Pin, \/\/\n LIGHT_FRONT_Pin, LIGHT_BACK_Pin, \/\/\n ASEL1_Pin, ASEL2_Pin, \/\/\n CHRG_EN_Pin> GpioInit;\n\n\n typedef GpioInitializer< \/\/\n MOT_A_HI_Pin, MOT_A_LO_Pin, \/\/\n MOT_B_HI_Pin, MOT_B_LO_Pin, \/\/\n \/\/LIGHT_FRONT_Pin, LIGHT_BACK_Pin, \/\/\n ASEL1_Pin, ASEL2_Pin, \/\/\n REQ_BLOAD_Pin, \/\/\n CHRG_EN_Pin> GpioBootloaderInit;\n\n};\n\n\n#endif \/\/ _ESP_DEADRAIL_PROTO_HARDWARE_HXX_\n<|endoftext|>"} {"text":"#include \"cppjson.h\"\n#include \n#include \n\nvoid verify(const json::Value &value, const char *encoded)\n{\n\t\/* try to encode the value and verify that it decodes to the same *\/\n\tstd::ostringstream ss;\n\tvalue.write(ss);\n\tjson::Value value2;\n\tstd::istringstream parser(ss.str());\n\tvalue2.load_all(parser);\n\tassert(value == value2);\n\n\t\/* try to load the JSON string, and check that it is equal *\/\n\tparser.str(encoded);\n\tparser.clear();\n\tvalue2.load_all(parser);\n\tassert(value == value2);\n\n\t\/* Verify lazy loading *\/\n\tparser.str(encoded);\n\tparser.clear();\n\tvalue2.load_all(parser, true);\n}\n\nvoid verify_error(const char *s, const char *error)\n{\n\tjson::Value val;\n\tstd::istringstream ss(s);\n\ttry {\n\t\tval.load_all(ss);\n\t\t\/* should always raise an exception *\/\n\t\tassert(0);\n\t} catch (const json::decode_error &e) {\n\t\tassert(e.what() == std::string(error));\n\t}\n}\n\nvoid test_lazy_array()\n{\n\tstd::istringstream parser(\"{\\\"a\\\": [1, \\\"foo\\\"], \\\"b\\\": [2, \\\"bar\\\"]}\");\n\tjson::Value value;\n\tvalue.load_all(parser, true);\n\tjson::Value &a = value.get(\"a\");\n\tjson::Value &b = value.get(\"b\");\n\tassert(a.load_next().as_integer() == 1);\n\tassert(b.load_next().as_integer() == 2);\n\tassert(a.load_next().as_string() == \"foo\");\n\tbool end = false;\n\ta.load_next(&end);\n\tassert(end);\n\tassert(b.load_next().as_string() == \"bar\");\n\tb.load_next(&end);\n\tassert(end);\n}\n\nint main()\n{\n\tconst uint8_t snowman[] = {0xE2, 0x98, 0x83, 0};\n\n\tverify(1234, \"1234\");\n\tverify(-1234, \"-1234\");\n\tverify(1234, \"1234.\");\n\tverify(1234, \"1234 \/\/ a comment\\n\\n\");\n\tverify(1234, \"\/\/a comment\\n\\n1234\");\n\tverify(1234, \"\/\/\\n1234\");\n\tverify(1234.0, \"1234\");\n\tverify(1234.56, \"1234.56\");\n\tverify(-1234.56, \"-1234.56\");\n\tverify(1234, \"\\t1234 \\n\");\n\tverify(\"foobar\", \"\\\"foobar\\\"\");\n\tverify(\"snow\" + std::string((char *) snowman) + \"man\", \"\\\"snow\\u2603man\\\"\");\n\tverify(\"\", \"\\\"\\\"\");\n\tverify(\" \/\\r\\n \\\"\\\\\", \"\\\" \\\\\/\\\\r\\\\n \\\\\\\"\\\\\\\\\\\" \");\n\tverify(true, \"true\");\n\tverify(false, \"false\");\n\n\tstd::vector arr;\n\tverify(arr, \"[] \");\n\n\tarr.push_back(\"foo\");\n\tarr.push_back(1234);\n\tarr.push_back(-1234.56);\n\tarr.push_back(true);\n\tverify(arr, \"[\\\"foo\\\",\\n 1234,\\t-1234.56\\n, true] \");\n\n\tjson::object_map_t obj;\n\tverify(obj, \"{}\");\n\tobj[\"bar\"] = arr;\n\tobj[\"foo\"] = \"test\";\n\tverify(obj, \"{\\\"bar\\\" :[ \\\"foo\\\" ,1234,-1234.56, true, ], \\\"foo\\\": \\\"test\\\"}\\n\");\n\n\tstd::vector arr2;\n\tarr2.push_back(obj);\n\tarr2.push_back(123);\n\tverify(arr2, \"[{\\\"bar\\\":[\\\"foo\\\",1234 ,-1234.56,true],\\\"foo\\\":\\\"test\\\"} ,123\\n]\");\n\n\tverify_error(\"foobar\", \"Unknown keyword in input\");\n\tverify_error(\"-foo\", \"Expected a digit\");\n\tverify_error(\"trueorfalse\", \"Unknown keyword in input\");\n\tverify_error(\"\\\"foobar\", \"Unexpected end of input\");\n\tverify_error(\"[,] \", \"Unknown character in input\");\n\tverify_error(\"[1234, \", \"Unexpected end of input\");\n\tverify_error(\" [1 2]\", \"Expected ',' or ']'\");\n\tverify_error(\"{\\\"foo\\\": ,} \", \"Unknown character in input\");\n\tverify_error(\"{ \\\"foo\\\": 1234, \", \"Unexpected end of input\");\n\tverify_error(\"{1234.56}\", \"Expected a string\");\n\tverify_error(\"{\\\"a\\\": [] \", \"Expected ',' or '}'\");\n\tverify_error(\"{\\\"a\\\" 5 \", \"Expected ':'\");\n\tverify_error(\"11111111111111111111\", \"Invalid integer\");\n\tverify_error(\" \/\", \"Expected '\/'\");\n\n\ttest_lazy_array();\n\n\tprintf(\"ok\\n\");\n\treturn 0;\n}\nFix UTF-8 test case [CORRECTIVE]#include \"cppjson.h\"\n#include \n#include \n\nvoid verify(const json::Value &value, const char *encoded)\n{\n\t\/* try to encode the value and verify that it decodes to the same *\/\n\tstd::ostringstream ss;\n\tvalue.write(ss);\n\tjson::Value value2;\n\tstd::istringstream parser(ss.str());\n\tvalue2.load_all(parser);\n\tassert(value == value2);\n\n\t\/* try to load the JSON string, and check that it is equal *\/\n\tparser.str(encoded);\n\tparser.clear();\n\tvalue2.load_all(parser);\n\tassert(value == value2);\n\n\t\/* Verify lazy loading *\/\n\tparser.str(encoded);\n\tparser.clear();\n\tvalue2.load_all(parser, true);\n}\n\nvoid verify_error(const char *s, const char *error)\n{\n\tjson::Value val;\n\tstd::istringstream ss(s);\n\ttry {\n\t\tval.load_all(ss);\n\t\t\/* should always raise an exception *\/\n\t\tassert(0);\n\t} catch (const json::decode_error &e) {\n\t\tassert(e.what() == std::string(error));\n\t}\n}\n\nvoid test_lazy_array()\n{\n\tstd::istringstream parser(\"{\\\"a\\\": [1, \\\"foo\\\"], \\\"b\\\": [2, \\\"bar\\\"]}\");\n\tjson::Value value;\n\tvalue.load_all(parser, true);\n\tjson::Value &a = value.get(\"a\");\n\tjson::Value &b = value.get(\"b\");\n\tassert(a.load_next().as_integer() == 1);\n\tassert(b.load_next().as_integer() == 2);\n\tassert(a.load_next().as_string() == \"foo\");\n\tbool end = false;\n\ta.load_next(&end);\n\tassert(end);\n\tassert(b.load_next().as_string() == \"bar\");\n\tb.load_next(&end);\n\tassert(end);\n}\n\nint main()\n{\n\tconst uint8_t snowman[] = {0xE2, 0x98, 0x83, 0};\n\n\tverify(1234, \"1234\");\n\tverify(-1234, \"-1234\");\n\tverify(1234, \"1234.\");\n\tverify(1234, \"1234 \/\/ a comment\\n\\n\");\n\tverify(1234, \"\/\/a comment\\n\\n1234\");\n\tverify(1234, \"\/\/\\n1234\");\n\tverify(1234.0, \"1234\");\n\tverify(1234.56, \"1234.56\");\n\tverify(-1234.56, \"-1234.56\");\n\tverify(1234, \"\\t1234 \\n\");\n\tverify(\"foobar\", \"\\\"foobar\\\"\");\n\tverify(\"snow\" + std::string((char *) snowman) + \"man\", \"\\\"snow\\\\u2603man\\\"\");\n\tverify(\"\", \"\\\"\\\"\");\n\tverify(\" \/\\r\\n \\\"\\\\\", \"\\\" \\\\\/\\\\r\\\\n \\\\\\\"\\\\\\\\\\\" \");\n\tverify(true, \"true\");\n\tverify(false, \"false\");\n\n\tstd::vector arr;\n\tverify(arr, \"[] \");\n\n\tarr.push_back(\"foo\");\n\tarr.push_back(1234);\n\tarr.push_back(-1234.56);\n\tarr.push_back(true);\n\tverify(arr, \"[\\\"foo\\\",\\n 1234,\\t-1234.56\\n, true] \");\n\n\tjson::object_map_t obj;\n\tverify(obj, \"{}\");\n\tobj[\"bar\"] = arr;\n\tobj[\"foo\"] = \"test\";\n\tverify(obj, \"{\\\"bar\\\" :[ \\\"foo\\\" ,1234,-1234.56, true, ], \\\"foo\\\": \\\"test\\\"}\\n\");\n\n\tstd::vector arr2;\n\tarr2.push_back(obj);\n\tarr2.push_back(123);\n\tverify(arr2, \"[{\\\"bar\\\":[\\\"foo\\\",1234 ,-1234.56,true],\\\"foo\\\":\\\"test\\\"} ,123\\n]\");\n\n\tverify_error(\"foobar\", \"Unknown keyword in input\");\n\tverify_error(\"-foo\", \"Expected a digit\");\n\tverify_error(\"trueorfalse\", \"Unknown keyword in input\");\n\tverify_error(\"\\\"foobar\", \"Unexpected end of input\");\n\tverify_error(\"[,] \", \"Unknown character in input\");\n\tverify_error(\"[1234, \", \"Unexpected end of input\");\n\tverify_error(\" [1 2]\", \"Expected ',' or ']'\");\n\tverify_error(\"{\\\"foo\\\": ,} \", \"Unknown character in input\");\n\tverify_error(\"{ \\\"foo\\\": 1234, \", \"Unexpected end of input\");\n\tverify_error(\"{1234.56}\", \"Expected a string\");\n\tverify_error(\"{\\\"a\\\": [] \", \"Expected ',' or '}'\");\n\tverify_error(\"{\\\"a\\\" 5 \", \"Expected ':'\");\n\tverify_error(\"11111111111111111111\", \"Invalid integer\");\n\tverify_error(\" \/\", \"Expected '\/'\");\n\n\ttest_lazy_array();\n\n\tprintf(\"ok\\n\");\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/* Copyright 2019 Google LLC. 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\n#include \"wait.h\"\n\n#include \/\/ NOLINT(build\/c++11)\n#include \n#include \/\/ NOLINT(build\/c++11)\n\n#include \"time.h\"\n\nnamespace ruy {\n\nvoid WaitUntil(const std::function& condition,\n const Duration& spin_duration, std::condition_variable* condvar,\n std::mutex* mutex) {\n \/\/ First, trivial case where the `condition` is already true;\n if (condition()) {\n return;\n }\n\n \/\/ Then try busy-waiting.\n const TimePoint wait_start = Clock::now();\n while (Clock::now() - wait_start < spin_duration) {\n if (condition()) {\n return;\n }\n }\n\n \/\/ Finally, do real passive waiting.\n \/\/\n \/\/ TODO(b\/135624397): We really want wait_until(TimePoint::max()) but that\n \/\/ runs into a libc++ bug at the moment, see b\/135624397 and\n \/\/ https:\/\/bugs.llvm.org\/show_bug.cgi?id=21395#c5. We pick a duration large\n \/\/ enough to appear infinite in practice and small enough to avoid such\n \/\/ overflow bugs...\n const Duration& timeout = DurationFromSeconds(1e6);\n std::unique_lock lock(*mutex);\n condvar->wait_for(lock, timeout, condition);\n}\n\nvoid WaitUntil(const std::function& condition,\n std::condition_variable* condvar, std::mutex* mutex) {\n \/\/ This value was empirically derived with some microbenchmark, we don't have\n \/\/ high confidence in it.\n \/\/\n \/\/ TODO(b\/135595069): make this value configurable at runtime.\n \/\/ I almost wanted to file another bug to ask for experimenting in a more\n \/\/ principled way to tune this value better, but this would have to be tuned\n \/\/ on real end-to-end applications and we'd expect different applications to\n \/\/ require different tunings. So the more important point is the need for\n \/\/ this to be controllable by the application.\n \/\/\n \/\/ That this value means that we may be sleeping substantially longer\n \/\/ than a scheduler timeslice's duration is not necessarily surprising. The\n \/\/ idea is to pick up quickly new work after having finished the previous\n \/\/ workload. When it's new work within the same GEMM as the previous work, the\n \/\/ time interval that we might be busy-waiting is very small, so for that\n \/\/ purpose it would be more than enough to sleep for 1 ms.\n \/\/ That is all what we would observe on a GEMM benchmark. However, in a real\n \/\/ application, after having finished a GEMM, we might do unrelated work for\n \/\/ a little while, then start on a new GEMM. In that case the wait interval\n \/\/ may be a little longer. There may also not be another GEMM for a long time,\n \/\/ in which case we'll end up passively waiting below.\n const double kMaxBusyWaitSeconds = 2e-3;\n const Duration spin_duration = DurationFromSeconds(kMaxBusyWaitSeconds);\n WaitUntil(condition, spin_duration, condvar, mutex);\n}\n\n} \/\/ namespace ruy\nUse condition_variable::wait, it has an overload taking a predicate that was what I wanted all along.\/* Copyright 2019 Google LLC. 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\n#include \"wait.h\"\n\n#include \/\/ NOLINT(build\/c++11)\n#include \n#include \/\/ NOLINT(build\/c++11)\n\n#include \"time.h\"\n\nnamespace ruy {\n\nvoid WaitUntil(const std::function& condition,\n const Duration& spin_duration, std::condition_variable* condvar,\n std::mutex* mutex) {\n \/\/ First, trivial case where the `condition` is already true;\n if (condition()) {\n return;\n }\n\n \/\/ Then try busy-waiting.\n const TimePoint wait_start = Clock::now();\n while (Clock::now() - wait_start < spin_duration) {\n if (condition()) {\n return;\n }\n }\n\n \/\/ Finally, do real passive waiting.\n std::unique_lock lock(*mutex);\n condvar->wait(lock, condition);\n}\n\nvoid WaitUntil(const std::function& condition,\n std::condition_variable* condvar, std::mutex* mutex) {\n \/\/ This value was empirically derived with some microbenchmark, we don't have\n \/\/ high confidence in it.\n \/\/\n \/\/ TODO(b\/135595069): make this value configurable at runtime.\n \/\/ I almost wanted to file another bug to ask for experimenting in a more\n \/\/ principled way to tune this value better, but this would have to be tuned\n \/\/ on real end-to-end applications and we'd expect different applications to\n \/\/ require different tunings. So the more important point is the need for\n \/\/ this to be controllable by the application.\n \/\/\n \/\/ That this value means that we may be sleeping substantially longer\n \/\/ than a scheduler timeslice's duration is not necessarily surprising. The\n \/\/ idea is to pick up quickly new work after having finished the previous\n \/\/ workload. When it's new work within the same GEMM as the previous work, the\n \/\/ time interval that we might be busy-waiting is very small, so for that\n \/\/ purpose it would be more than enough to sleep for 1 ms.\n \/\/ That is all what we would observe on a GEMM benchmark. However, in a real\n \/\/ application, after having finished a GEMM, we might do unrelated work for\n \/\/ a little while, then start on a new GEMM. In that case the wait interval\n \/\/ may be a little longer. There may also not be another GEMM for a long time,\n \/\/ in which case we'll end up passively waiting below.\n const double kMaxBusyWaitSeconds = 2e-3;\n const Duration spin_duration = DurationFromSeconds(kMaxBusyWaitSeconds);\n WaitUntil(condition, spin_duration, condvar, mutex);\n}\n\n} \/\/ namespace ruy\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\nnamespace {\n\nvoid out(const char* c) { std::cout << c << std::flush; }\nvoid clear(int n) { for (int i = 0; i < n; ++i) out(\"\\b\"); }\n\nstruct Kirby final {\n Kirby() : state{hand::mid} { out(visual::mid); }\n\n void left() {\n clear(visual::size);\n out(visual::left);\n state = hand::left;\n }\n\n void mid() {\n clear(visual::size);\n out(visual::mid);\n state = hand::mid;\n }\n\n void right() {\n clear(visual::size);\n out(visual::right);\n state = hand::right;\n }\n\nprivate:\n enum class hand { left, mid, right } state;\n\n struct visual {\n static const int size;\n static const char* left;\n static const char* mid;\n static const char* right;\n };\n};\n\nconst int Kirby::visual::size = 7;\nconst char* Kirby::visual::left = \"<(^-^<)\";\nconst char* Kirby::visual::mid = \"<(^-^)>\";\nconst char* Kirby::visual::right = \"(>^-^)>\";\n\n\ntemplate \nvoid seq(Fn fn) {\n std::this_thread::sleep_for(std::chrono::seconds{N});\n fn();\n}\n\ntemplate \nvoid seq(Fn fn, Fns... rest) {\n seq(fn);\n seq(rest...);\n}\n\n} \/\/ ns\n\n\nint main() {\n Kirby k;\n\n for (int i = 0; i < 2; ++i)\n seq<1>([&] { k.left(); }, [&] { k.mid(); }, [&] { k.right(); }, [&] { k.mid(); });\n}\nStateless#include \n#include \n#include \n#include \n\nnamespace {\n\nvoid out(const char* c) { std::cout << c << std::flush; }\nvoid clear(int n) { for (int i = 0; i < n; ++i) out(\"\\b\"); }\n\nstruct Kirby final {\n Kirby() { out(visual::mid); }\n\n void left() {\n clear(visual::size);\n out(visual::left);\n }\n\n void mid() {\n clear(visual::size);\n out(visual::mid);\n }\n\n void right() {\n clear(visual::size);\n out(visual::right);\n }\n\nprivate:\n struct visual {\n static const int size;\n static const char* left;\n static const char* mid;\n static const char* right;\n };\n};\n\nconst int Kirby::visual::size = 7;\nconst char* Kirby::visual::left = \"<(^-^<)\";\nconst char* Kirby::visual::mid = \"<(^-^)>\";\nconst char* Kirby::visual::right = \"(>^-^)>\";\n\n\ntemplate \nvoid seq(Fn fn) {\n std::this_thread::sleep_for(std::chrono::seconds{N});\n fn();\n}\n\ntemplate \nvoid seq(Fn fn, Fns... rest) {\n seq(fn);\n seq(rest...);\n}\n\n} \/\/ ns\n\n\nint main() {\n Kirby k;\n\n for (int i = 0; i < 2; ++i)\n seq<1>([&] { k.left(); }, [&] { k.mid(); }, [&] { k.right(); }, [&] { k.mid(); });\n}\n<|endoftext|>"} {"text":"#include \"Tape.h\"\r\n#include \"constants.h\"\r\n\r\nTape::Tape() \r\n{\r\n this->tape.push_back(BLANK_SYMBOL);\r\n this->stylus = tape.begin();\r\n}\r\n\r\nTape::Tape(int* symbols, int size, int position)\r\n{\r\n for (int i = 0; i < size; i++)\r\n {\r\n this->tape.push_back(symbols[i]);\r\n if (i == position) this->stylus = tape.end();\r\n }\r\n}\r\n\r\nint Tape::getValue() \r\n{\r\n return *(this->stylus);\r\n}\r\n\r\nvoid Tape::setValue(int symbol)\r\n{\r\n *(this->stylus) = symbol;\r\n}\r\n\r\nvoid Tape::moveStylusRight()\r\n{\r\n if (this->stylus == this->tape.end())\r\n this->tape.push_back(BLANK_SYMBOL);\r\n (this->stylus)++;\r\n}\r\n\r\nvoid Tape::moveStylusLeft()\r\n{\r\n if (this->stylus == this->tape.begin())\r\n this->tape.push_front(BLANK_SYMBOL);\r\n (this->stylus)--;\r\n}\r\n\r\nint * Tape::getTape(int x, int y)\r\n{}\r\n\r\nFix iterator dereferencing bug#include \"Tape.h\"\r\n#include \"constants.h\"\r\n\r\nTape::Tape() \r\n{\r\n this->tape.push_back(BLANK_SYMBOL);\r\n this->stylus = tape.begin();\r\n}\r\n\r\nTape::Tape(int* symbols, int size, int position)\r\n{\r\n for (int i = 0; i < size; i++)\r\n {\r\n this->tape.push_back(symbols[i]);\r\n if (i == position)\r\n {\r\n this->stylus = tape.end();\r\n (this->stylus)--; \/\/ end() returns the \"past the end\" object in the list\r\n }\r\n }\r\n}\r\n\r\nint Tape::getValue() \r\n{\r\n return *(this->stylus);\r\n}\r\n\r\nvoid Tape::setValue(int symbol)\r\n{\r\n *(this->stylus) = symbol;\r\n}\r\n\r\nvoid Tape::moveStylusRight()\r\n{\r\n if (this->stylus == this->tape.end())\r\n this->tape.push_back(BLANK_SYMBOL);\r\n (this->stylus)++;\r\n}\r\n\r\nvoid Tape::moveStylusLeft()\r\n{\r\n if (this->stylus == this->tape.begin())\r\n this->tape.push_front(BLANK_SYMBOL);\r\n (this->stylus)--;\r\n}\r\n\r\nint * Tape::getTape(int x, int y)\r\n{}\r\n\r\n<|endoftext|>"} {"text":"\/*\n\tproxyImage.hpp\n\tArsh Chauhan\n\t05\/02\/2016\n\n\tCS372 Assignment 4\n\tHeader for Proxyimage class.\n\tCreate a proxy image.\n\tDoes not perform any hypothtical disk access \n\tunless display is called. Saves unnecessary disk\n\toperations. \n*\/\n\n#ifndef PROXYIMAGE_HPP\n#define PROXYIMAGE_HPP\n\n#include \"realImage.hpp\"\n\nclass Proxyimage:public Image\n{\n\tstring fileName_;\n\tRealimage realImage_;\n\npublic:\n\tProxyimage(string fileName);\n\tvoid display() override;\n\n\n\n\n};\n\n#endifComment readability improved:\/*\n\tproxyImage.hpp\n\tArsh Chauhan\n\t05\/02\/2016\n\n\tCS372 Assignment 4\n\tHeader for Proxyimage class.\n\tCreate a proxy image.\n\tDoes not perform any hypothtical disk access \n\tunless display is called. \n\tSaves unnecessary disk operations. \n*\/\n\n#ifndef PROXYIMAGE_HPP\n#define PROXYIMAGE_HPP\n\n#include \"realImage.hpp\"\n\nclass Proxyimage:public Image\n{\n\tstring fileName_;\n\tRealimage realImage_;\n\npublic:\n\tProxyimage(string fileName);\n\tvoid display() override;\n\n\n\n\n};\n\n#endif<|endoftext|>"} {"text":"\n#include \"generated\/services.h\"\n\n#include \n\n\/**\n * @brief Constructs UserStore object.\n * @param host\n * www.evernote.com or sandbox.evernote.com\n * @param authenticationToken\n * This token that will be used as the default token.\n *\/\nqevercloud::UserStore::UserStore(QString host, QString authenticationToken, QObject *parent): QObject(parent)\n{\n QUrl url;\n url.setScheme(\"https\");\n url.setHost(host);\n url.setPath(\"\/edam\/user\");\n url_ = url.toString(QUrl::StripTrailingSlash);\n setAuthenticationToken(authenticationToken);\n}\n\n\/**\n * Constructs NoteStore object.\n * @param noteStoreUrl\n * EDAM NoteStore service url. In general it's different for different users.\n * @param authenticationToken\n * This token that will be used as the default token.\n *\n *\/\nqevercloud::NoteStore::NoteStore(QString noteStoreUrl, QString authenticationToken, QObject *parent): QObject(parent)\n{\n setNoteStoreUrl(noteStoreUrl);\n setAuthenticationToken(authenticationToken);\n}\n\n\/**\n * Constructs NoteStore object.\n *\n * noteStoreUrl and possibly authenticationToken are expected to be specified later.\n *\/\nqevercloud::NoteStore::NoteStore(QObject *parent): QObject(parent)\n{\n\n}\n\n\/** @fn qevercloud::UserStore:setAuthenticationToken\n * Sets a value that will be used as the default token.\n * *\/\n\n\/** @fn qevercloud::UserStore:authenticationToken\n * @returns the default authentication token value.\n * *\/\n\n\/** @fn qevercloud::NoteStore:setAuthenticationToken\n * Sets a value that will be used as the default token.\n * *\/\n\n\/** @fn qevercloud::NoteStore:authenticationToken\n * @returns the default authentication token value.\n * *\/\n\n\/** @fn qevercloud::NoteStore:setNoteStoreUrl\n * Sets a value that will be used as EDAM NoteStore service url by this object.\n * *\/\n\n\/** @fn qevercloud::NoteStore:authenticationToken\n * @returns EDAM NoteStore service url that is used by this NoteStore object.\n * *\/\nfix doc\n#include \"generated\/services.h\"\n\n#include \n\n\/**\n * @brief Constructs UserStore object.\n * @param host\n * www.evernote.com or sandbox.evernote.com\n * @param authenticationToken\n * This token that will be used as the default token.\n *\/\nqevercloud::UserStore::UserStore(QString host, QString authenticationToken, QObject *parent): QObject(parent)\n{\n QUrl url;\n url.setScheme(\"https\");\n url.setHost(host);\n url.setPath(\"\/edam\/user\");\n url_ = url.toString(QUrl::StripTrailingSlash);\n setAuthenticationToken(authenticationToken);\n}\n\n\/**\n * Constructs NoteStore object.\n * @param noteStoreUrl\n * EDAM NoteStore service url. In general it's different for different users.\n * @param authenticationToken\n * This token that will be used as the default token.\n *\n *\/\nqevercloud::NoteStore::NoteStore(QString noteStoreUrl, QString authenticationToken, QObject *parent): QObject(parent)\n{\n setNoteStoreUrl(noteStoreUrl);\n setAuthenticationToken(authenticationToken);\n}\n\n\/**\n * Constructs NoteStore object.\n *\n * noteStoreUrl and possibly authenticationToken are expected to be specified later.\n *\/\nqevercloud::NoteStore::NoteStore(QObject *parent): QObject(parent)\n{\n\n}\n\n\/** @fn qevercloud::UserStore::setAuthenticationToken\n * Sets a value that will be used as the default token.\n * *\/\n\n\/** @fn qevercloud::UserStore::authenticationToken\n * @returns the default authentication token value.\n * *\/\n\n\/** @fn qevercloud::NoteStore::setAuthenticationToken\n * Sets a value that will be used as the default token.\n * *\/\n\n\/** @fn qevercloud::NoteStore::authenticationToken\n * @returns the default authentication token value.\n * *\/\n\n\/** @fn qevercloud::NoteStore::setNoteStoreUrl\n * Sets a value that will be used as EDAM NoteStore service url by this object.\n * *\/\n\n\/** @fn qevercloud::NoteStore::authenticationToken\n * @returns EDAM NoteStore service url that is used by this NoteStore object.\n * *\/\n<|endoftext|>"} {"text":"#include \"prochelper.hpp\"\n#include \"glx.hpp\"\n#include \"input.hpp\"\n#include \"sound.hpp\"\n\nnamespace rs {\n\t\/\/ ------------------------------ DrawProc ------------------------------\n\tbool DrawProc::runU(uint64_t accum, bool bSkip) {\n\t\tauto lk = sharedbase.lock();\n\t\tauto& fx = *lk->hlFx.ref();\n\t\tif(!bSkip) {\n\t\t\tlk->fps.update();\n\t\t\tfx.execTask();\n\t\t}\n\t\treturn !bSkip;\n\t}\n\t\/\/ ------------------------------ MainProc ------------------------------\n\tMainProc::MainProc(const rs::SPWindow& sp, bool bInitInput):\n\t\t_bFirstScene(false)\n\t{\n\t\tauto lk = sharedbase.lock();\n\t\tlk->spWindow = sp;\n\t\tlk->screenSize *= 0;\n\t\tif(bInitInput)\n\t\t\t_initInput();\n\t}\n\tvoid MainProc::_pushFirstScene(rs::HObj hObj) {\n\t\tAssert(Trap, !_bFirstScene, \"pushed first scene twice\")\n\t\tmgr_scene.setPushScene(hObj);\n\t\t_bFirstScene = true;\n\t}\n\tvoid MainProc::_initInput() {\n\t\t\/\/ キーバインディング\n\t\tauto lk = sharedbase.lock();\n\t\tlk->hlIk = rs::Keyboard::OpenKeyboard();\n\t\tlk->hlIm = rs::Mouse::OpenMouse(0);\n\t\tauto& mouse = *lk->hlIm.ref();\n\t\tmouse.setMouseMode(rs::MouseMode::Absolute);\n\t\tmouse.setDeadZone(0, 1.f, 0.f);\n\t\tmouse.setDeadZone(1, 1.f, 0.f);\n\t}\n\n\tbool MainProc::runU(Query& q) {\n\t\tif(!MainProc::_beginProc())\n\t\t\treturn false;\n\n\t\tbool b = userRunU();\n\t\tif(b && q.canDraw()) {\n\t\t\tmgr_scene.onDraw();\n\t\t\tq.setDraw(true);\n\t\t}\n\t\t_endProc();\n\t\treturn b;\n\t}\n\tbool MainProc::_beginProc() {\n\t\tAssert(Trap, _bFirstScene, \"not pushed first scene yet\")\n\n\t\tmgr_sound.update();\n\t\t\/\/ 描画コマンド\n\t\tauto lk = sharedbase.lock();\n\t\trs::GLEffect& fx = *lk->hlFx.ref();\n\t\t\/\/ 描画スレッドの処理が遅過ぎたらここでウェイトがかかる\n\t\tfx.beginTask();\n\t\tif(mgr_scene.onUpdate()) {\n\t\t\t_endProc();\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ 画面のサイズとアスペクト比合わせ\n\t\tauto& scs = lk->screenSize;\n\t\tauto sz = lk->spWindow->getSize();\n\t\tif(scs != sz) {\n\t\t\tscs = sz;\n\t\t\tGL.glViewport(0,0, sz.width, sz.height);\n\t\t}\n\t\treturn true;\n\t}\n\tvoid MainProc::_endProc() {\n\t\tauto& fx = sharedbase.lock()->hlFx.ref();\n\t\tfx->endTask();\n\t}\n\tvoid MainProc::onPause() {\n\t\tmgr_scene.onPause(); }\n\tvoid MainProc::onResume() {\n\t\tmgr_scene.onResume(); }\n\tvoid MainProc::onStop() {\n\t\tauto lk = sharedbase.lock();\n\t\tlk->hlFx.ref()->clearTask();\n\t\tmgr_scene.onStop();\n\t}\n\tvoid MainProc::onReStart() {\n\t\tmgr_scene.onReStart(); }\n}\n\nsharedbaseのロックタイミングによるデッドロックを解消#include \"prochelper.hpp\"\n#include \"glx.hpp\"\n#include \"input.hpp\"\n#include \"sound.hpp\"\n\nnamespace rs {\n\t\/\/ ------------------------------ DrawProc ------------------------------\n\tbool DrawProc::runU(uint64_t accum, bool bSkip) {\n\t\tauto lk = sharedbase.lock();\n\t\tauto& fx = *lk->hlFx.ref();\n\t\tif(!bSkip) {\n\t\t\tlk->fps.update();\n\t\t\tfx.execTask();\n\t\t}\n\t\treturn !bSkip;\n\t}\n\t\/\/ ------------------------------ MainProc ------------------------------\n\tMainProc::MainProc(const rs::SPWindow& sp, bool bInitInput):\n\t\t_bFirstScene(false)\n\t{\n\t\tauto lk = sharedbase.lock();\n\t\tlk->spWindow = sp;\n\t\tlk->screenSize *= 0;\n\t\tif(bInitInput)\n\t\t\t_initInput();\n\t}\n\tvoid MainProc::_pushFirstScene(rs::HObj hObj) {\n\t\tAssert(Trap, !_bFirstScene, \"pushed first scene twice\")\n\t\tmgr_scene.setPushScene(hObj);\n\t\t_bFirstScene = true;\n\t}\n\tvoid MainProc::_initInput() {\n\t\t\/\/ キーバインディング\n\t\tauto lk = sharedbase.lock();\n\t\tlk->hlIk = rs::Keyboard::OpenKeyboard();\n\t\tlk->hlIm = rs::Mouse::OpenMouse(0);\n\t\tauto& mouse = *lk->hlIm.ref();\n\t\tmouse.setMouseMode(rs::MouseMode::Absolute);\n\t\tmouse.setDeadZone(0, 1.f, 0.f);\n\t\tmouse.setDeadZone(1, 1.f, 0.f);\n\t}\n\n\tbool MainProc::runU(Query& q) {\n\t\tif(!MainProc::_beginProc())\n\t\t\treturn false;\n\n\t\tbool b = userRunU();\n\t\tif(b && q.canDraw()) {\n\t\t\tmgr_scene.onDraw();\n\t\t\tq.setDraw(true);\n\t\t}\n\t\t_endProc();\n\t\treturn b;\n\t}\n\tbool MainProc::_beginProc() {\n\t\tAssert(Trap, _bFirstScene, \"not pushed first scene yet\")\n\n\t\tmgr_sound.update();\n\t\t\/\/ 描画コマンド\n\t\trs::GLEffect* fx;\n\t\t{\n\t\t\tauto lk = sharedbase.lock();\n\t\t\tfx = lk->hlFx->get();\n\t\t}\n\t\t\/\/ 描画スレッドの処理が遅過ぎたらここでウェイトがかかる\n\t\tfx->beginTask();\n\t\tif(mgr_scene.onUpdate()) {\n\t\t\t_endProc();\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ 画面のサイズとアスペクト比合わせ\n\t\t{\n\t\t\tauto lk = sharedbase.lock();\n\t\t\tauto& scs = lk->screenSize;\n\t\t\tauto sz = lk->spWindow->getSize();\n\t\t\tif(scs != sz) {\n\t\t\t\tscs = sz;\n\t\t\t\tGL.glViewport(0,0, sz.width, sz.height);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\tvoid MainProc::_endProc() {\n\t\tauto& fx = sharedbase.lock()->hlFx.ref();\n\t\tfx->endTask();\n\t}\n\tvoid MainProc::onPause() {\n\t\tmgr_scene.onPause(); }\n\tvoid MainProc::onResume() {\n\t\tmgr_scene.onResume(); }\n\tvoid MainProc::onStop() {\n\t\tauto lk = sharedbase.lock();\n\t\tlk->hlFx.ref()->clearTask();\n\t\tmgr_scene.onStop();\n\t}\n\tvoid MainProc::onReStart() {\n\t\tmgr_scene.onReStart(); }\n}\n\n<|endoftext|>"} {"text":"\/*\r\n * Copyright (c) 2016-2018 dresden elektronik ingenieurtechnik gmbh.\r\n * All rights reserved.\r\n *\r\n * The software in this package is published under the terms of the BSD\r\n * style license a copy of which has been included with this distribution in\r\n * the LICENSE.txt file.\r\n *\r\n *\/\r\n#include \"de_web_plugin.h\"\r\n#include \"de_web_plugin_private.h\"\r\n\r\n\/*! Inits permit join manager.\r\n\r\n The manager will observe and ensure the global permit join state.\r\n *\/\r\nvoid DeRestPluginPrivate::initPermitJoin()\r\n{\r\n permitJoinFlag = false;\r\n permitJoinTimer = new QTimer(this);\r\n permitJoinTimer->setSingleShot(false);\r\n connect(permitJoinTimer, SIGNAL(timeout()),\r\n this, SLOT(permitJoinTimerFired()));\r\n permitJoinTimer->start(1000);\r\n permitJoinLastSendTime = QTime::currentTime();\r\n\r\n resendPermitJoinTimer = new QTimer(this);\r\n resendPermitJoinTimer->setSingleShot(true);\r\n connect(resendPermitJoinTimer, SIGNAL(timeout()),\r\n this, SLOT(resendPermitJoinTimerFired()));\r\n}\r\n\r\n\/*! Sets the permit join interval\r\n\r\n \\param duration specifies the interval in which joining is enabled\r\n - 0 disabled\r\n - 1..254 duration in seconds until joining will be disabled\r\n - 255 always permit\r\n * \\return\r\n *\/\r\nbool DeRestPluginPrivate::setPermitJoinDuration(uint8_t duration)\r\n{\r\n if (gwPermitJoinDuration != duration)\r\n {\r\n gwPermitJoinDuration = duration;\r\n }\r\n\r\n \/\/ force resend\r\n permitJoinLastSendTime = QTime();\r\n return true;\r\n}\r\n\r\n\/*! Send Commissioning Mode command to GP proxy device.\r\n *\/\r\nbool DeRestPluginPrivate::sendGPProxyCommissioningMode()\r\n{\r\n deCONZ::ApsDataRequest req;\r\n\r\n req.setDstAddressMode(deCONZ::ApsNwkAddress);\r\n req.dstAddress().setNwk(deCONZ::BroadcastRouters);\r\n req.setProfileId(GP_PROFILE_ID);\r\n req.setClusterId(GREEN_POWER_CLUSTER_ID);\r\n req.setDstEndpoint(GREEN_POWER_ENDPOINT);\r\n req.setSrcEndpoint(GREEN_POWER_ENDPOINT);\r\n req.setTxOptions(nullptr);\r\n req.setRadius(0);\r\n\r\n QDataStream stream(&req.asdu(), QIODevice::WriteOnly);\r\n stream.setByteOrder(QDataStream::LittleEndian);\r\n\r\n deCONZ::ZclFrame zclFrame;\r\n\r\n zclFrame.setSequenceNumber(zclSeq++);\r\n zclFrame.setCommandId(0x02); \/\/ commissioning mode\r\n zclFrame.setFrameControl(deCONZ::ZclFCClusterCommand |\r\n deCONZ::ZclFCDirectionServerToClient |\r\n deCONZ::ZclFCDisableDefaultResponse);\r\n\r\n { \/\/ payload\r\n QDataStream stream(&zclFrame.payload(), QIODevice::WriteOnly);\r\n stream.setByteOrder(QDataStream::LittleEndian);\r\n\r\n quint8 options = 0x0b; \/\/ enter commissioning mode, exit on window expire\r\n quint16 window = 40;\r\n stream << options;\r\n stream << window;\r\n }\r\n\r\n { \/\/ ZCL frame\r\n\r\n QDataStream stream(&req.asdu(), QIODevice::WriteOnly);\r\n stream.setByteOrder(QDataStream::LittleEndian);\r\n zclFrame.writeToStream(stream);\r\n }\r\n\r\n \/\/ broadcast\r\n if (apsCtrl->apsdeDataRequest(req) == deCONZ::Success)\r\n {\r\n DBG_Printf(DBG_INFO, \"send GP proxy commissioning mode\\n\");\r\n return true;\r\n }\r\n\r\n DBG_Printf(DBG_INFO, \"send GP proxy commissioning mode failed\\n\");\r\n return false;\r\n}\r\n\r\n\/*! Send Pair command to GP proxy device.\r\n *\/\r\nbool DeRestPluginPrivate::sendGPPairing(quint32 gpdSrcId, quint16 sinkGroupId, quint8 deviceId, quint32 frameCounter, const quint8 *key)\r\n{\r\n deCONZ::ApsDataRequest req;\r\n\r\n req.setDstAddressMode(deCONZ::ApsNwkAddress);\r\n req.dstAddress().setNwk(deCONZ::BroadcastRouters);\r\n req.setProfileId(GP_PROFILE_ID);\r\n req.setClusterId(GREEN_POWER_CLUSTER_ID);\r\n req.setDstEndpoint(GREEN_POWER_ENDPOINT);\r\n req.setSrcEndpoint(GREEN_POWER_ENDPOINT);\r\n req.setTxOptions(nullptr);\r\n req.setRadius(0);\r\n\r\n QDataStream stream(&req.asdu(), QIODevice::WriteOnly);\r\n stream.setByteOrder(QDataStream::LittleEndian);\r\n\r\n deCONZ::ZclFrame zclFrame;\r\n\r\n zclFrame.setSequenceNumber(zclSeq++);\r\n zclFrame.setCommandId(0x01); \/\/ pairing\r\n zclFrame.setFrameControl(deCONZ::ZclFCClusterCommand |\r\n deCONZ::ZclFCDirectionServerToClient |\r\n deCONZ::ZclFCDisableDefaultResponse);\r\n\r\n { \/\/ payload\r\n QDataStream stream(&zclFrame.payload(), QIODevice::WriteOnly);\r\n stream.setByteOrder(QDataStream::LittleEndian);\r\n\r\n frameCounter = 0;\r\n\r\n quint8 options0 = 0x48; \/\/ enter commissioning mode, exit on window expire\r\n \/\/quint8 options1 = key ? 0xe5 : 0x65;\r\n quint8 options1 = 0x40;\r\n quint8 options2 = 0x00;\r\n stream << options0;\r\n stream << options1;\r\n stream << options2;\r\n stream << gpdSrcId;\r\n stream << sinkGroupId;\r\n stream << deviceId;\r\n stream << frameCounter;\r\n\r\n if (key)\r\n {\r\n\/\/ for (size_t i = 0; i < 16; i++)\r\n\/\/ {\r\n\/\/ stream << (quint8)key[i];\r\n\/\/ }\r\n }\r\n }\r\n\r\n { \/\/ ZCL frame\r\n\r\n QDataStream stream(&req.asdu(), QIODevice::WriteOnly);\r\n stream.setByteOrder(QDataStream::LittleEndian);\r\n zclFrame.writeToStream(stream);\r\n }\r\n\r\n \/\/ broadcast\r\n if (apsCtrl->apsdeDataRequest(req) == deCONZ::Success)\r\n {\r\n DBG_Printf(DBG_INFO, \"send GP pairing\\n\");\r\n return true;\r\n }\r\n\r\n DBG_Printf(DBG_INFO, \"send GP pairing\\n\");\r\n return false;\r\n}\r\n\r\n\/*! Handle broadcasting of permit join interval.\r\n\r\n This is done every PERMIT_JOIN_SEND_INTERVAL to ensure\r\n any node in the network has the same settings.\r\n *\/\r\nvoid DeRestPluginPrivate::permitJoinTimerFired()\r\n{\r\n Q_Q(DeRestPlugin);\r\n if (!q->pluginActive() || !apsCtrl)\r\n {\r\n return;\r\n }\r\n\r\n if ((gwPermitJoinDuration > 0) && (gwPermitJoinDuration < 255))\r\n {\r\n permitJoinFlag = true;\r\n gwPermitJoinDuration--;\r\n\r\n if ((gwPermitJoinDuration % 10) == 0)\r\n {\r\n \/\/ try to add light nodes even if they existed in deCONZ bevor and therefore\r\n \/\/ no node added event will be triggert in this phase\r\n int i = 0;\r\n const deCONZ::Node *node = nullptr;\r\n while (apsCtrl->getNode(i, &node) == 0)\r\n {\r\n if (node && !node->isZombie() &&\r\n !node->nodeDescriptor().isNull() && node->nodeDescriptor().receiverOnWhenIdle())\r\n {\r\n addLightNode(node);\r\n }\r\n i++;\r\n }\r\n }\r\n else if ((gwPermitJoinDuration % 15) == 0)\r\n {\r\n for (LightNode &l : nodes)\r\n {\r\n if (l.isAvailable() && l.modelId().isEmpty())\r\n {\r\n queuePollNode(&l);\r\n }\r\n }\r\n }\r\n\r\n updateEtag(gwConfigEtag); \/\/ update Etag so that webApp can count down permitJoin duration\r\n }\r\n\r\n if (gwPermitJoinDuration == 0 && permitJoinFlag)\r\n {\r\n permitJoinFlag = false;\r\n }\r\n\r\n if (!isInNetwork())\r\n {\r\n return;\r\n }\r\n\r\n\/\/ if (gwPermitJoinDuration == 0 && otauLastBusyTimeDelta() < (60 * 5))\r\n\/\/ {\r\n\/\/ \/\/ don't pollute channel while OTA is running\r\n\/\/ return;\r\n\/\/ }\r\n\r\n QTime now = QTime::currentTime();\r\n int diff = permitJoinLastSendTime.msecsTo(now);\r\n\r\n if (!permitJoinLastSendTime.isValid() || (diff > PERMIT_JOIN_SEND_INTERVAL))\r\n {\r\n deCONZ::ApsDataRequest apsReq;\r\n quint8 tcSignificance = 0x01;\r\n\r\n apsReq.setDstAddressMode(deCONZ::ApsNwkAddress);\r\n apsReq.dstAddress().setNwk(deCONZ::BroadcastRouters);\r\n apsReq.setProfileId(ZDP_PROFILE_ID);\r\n apsReq.setClusterId(ZDP_MGMT_PERMIT_JOINING_REQ_CLID);\r\n apsReq.setDstEndpoint(ZDO_ENDPOINT);\r\n apsReq.setSrcEndpoint(ZDO_ENDPOINT);\r\n apsReq.setTxOptions(0);\r\n apsReq.setRadius(0);\r\n\r\n QDataStream stream(&apsReq.asdu(), QIODevice::WriteOnly);\r\n stream.setByteOrder(QDataStream::LittleEndian);\r\n\r\n stream << (uint8_t)now.second(); \/\/ seqno\r\n stream << gwPermitJoinDuration;\r\n stream << tcSignificance;\r\n\r\n DBG_Assert(apsCtrl != 0);\r\n\r\n if (!apsCtrl)\r\n {\r\n return;\r\n }\r\n\r\n \/\/ set for own node\r\n apsCtrl->setPermitJoin(gwPermitJoinDuration);\r\n\r\n \/\/ broadcast\r\n if (apsCtrl->apsdeDataRequest(apsReq) == deCONZ::Success)\r\n {\r\n DBG_Printf(DBG_INFO, \"send permit join, duration: %d\\n\", gwPermitJoinDuration);\r\n permitJoinLastSendTime = now;\r\n\r\n if (gwPermitJoinDuration > 0)\r\n {\r\n \/\/ sendGPProxyCommissioningMode(); TODO enable when GP security is implemented\r\n }\r\n }\r\n else\r\n {\r\n DBG_Printf(DBG_INFO, \"send permit join failed\\n\");\r\n }\r\n }\r\n}\r\n\r\n\/*! Check if permitJoin is > 60 seconds then resend permitjoin with 60 seconds\r\n *\/\r\nvoid DeRestPluginPrivate::resendPermitJoinTimerFired()\r\n{\r\n resendPermitJoinTimer->stop();\r\n if (gwPermitJoinDuration <= 1)\r\n {\r\n if (gwPermitJoinResend > 0)\r\n {\r\n if (gwPermitJoinResend >= 60)\r\n {\r\n setPermitJoinDuration(60);\r\n }\r\n else\r\n {\r\n setPermitJoinDuration(gwPermitJoinResend);\r\n }\r\n gwPermitJoinResend -= 60;\r\n updateEtag(gwConfigEtag);\r\n if (gwPermitJoinResend <= 0)\r\n {\r\n gwPermitJoinResend = 0;\r\n return;\r\n }\r\n\r\n }\r\n else if (gwPermitJoinResend == 0)\r\n {\r\n setPermitJoinDuration(0);\r\n return;\r\n }\r\n }\r\n else if (gwPermitJoinResend == 0)\r\n {\r\n setPermitJoinDuration(0);\r\n return;\r\n }\r\n resendPermitJoinTimer->start(1000);\r\n}\r\nFix permit join not reset to 0\/*\r\n * Copyright (c) 2016-2018 dresden elektronik ingenieurtechnik gmbh.\r\n * All rights reserved.\r\n *\r\n * The software in this package is published under the terms of the BSD\r\n * style license a copy of which has been included with this distribution in\r\n * the LICENSE.txt file.\r\n *\r\n *\/\r\n#include \"de_web_plugin.h\"\r\n#include \"de_web_plugin_private.h\"\r\n\r\n\/*! Inits permit join manager.\r\n\r\n The manager will observe and ensure the global permit join state.\r\n *\/\r\nvoid DeRestPluginPrivate::initPermitJoin()\r\n{\r\n permitJoinFlag = false;\r\n permitJoinTimer = new QTimer(this);\r\n permitJoinTimer->setSingleShot(false);\r\n connect(permitJoinTimer, SIGNAL(timeout()),\r\n this, SLOT(permitJoinTimerFired()));\r\n permitJoinTimer->start(1000);\r\n permitJoinLastSendTime = QTime::currentTime();\r\n\r\n resendPermitJoinTimer = new QTimer(this);\r\n resendPermitJoinTimer->setSingleShot(true);\r\n connect(resendPermitJoinTimer, SIGNAL(timeout()),\r\n this, SLOT(resendPermitJoinTimerFired()));\r\n}\r\n\r\n\/*! Sets the permit join interval\r\n\r\n \\param duration specifies the interval in which joining is enabled\r\n - 0 disabled\r\n - 1..254 duration in seconds until joining will be disabled\r\n - 255 always permit\r\n * \\return\r\n *\/\r\nbool DeRestPluginPrivate::setPermitJoinDuration(uint8_t duration)\r\n{\r\n if (gwPermitJoinDuration != duration)\r\n {\r\n gwPermitJoinDuration = duration;\r\n }\r\n\r\n \/\/ force resend\r\n permitJoinLastSendTime = QTime();\r\n return true;\r\n}\r\n\r\n\/*! Send Commissioning Mode command to GP proxy device.\r\n *\/\r\nbool DeRestPluginPrivate::sendGPProxyCommissioningMode()\r\n{\r\n deCONZ::ApsDataRequest req;\r\n\r\n req.setDstAddressMode(deCONZ::ApsNwkAddress);\r\n req.dstAddress().setNwk(deCONZ::BroadcastRouters);\r\n req.setProfileId(GP_PROFILE_ID);\r\n req.setClusterId(GREEN_POWER_CLUSTER_ID);\r\n req.setDstEndpoint(GREEN_POWER_ENDPOINT);\r\n req.setSrcEndpoint(GREEN_POWER_ENDPOINT);\r\n req.setTxOptions(nullptr);\r\n req.setRadius(0);\r\n\r\n QDataStream stream(&req.asdu(), QIODevice::WriteOnly);\r\n stream.setByteOrder(QDataStream::LittleEndian);\r\n\r\n deCONZ::ZclFrame zclFrame;\r\n\r\n zclFrame.setSequenceNumber(zclSeq++);\r\n zclFrame.setCommandId(0x02); \/\/ commissioning mode\r\n zclFrame.setFrameControl(deCONZ::ZclFCClusterCommand |\r\n deCONZ::ZclFCDirectionServerToClient |\r\n deCONZ::ZclFCDisableDefaultResponse);\r\n\r\n { \/\/ payload\r\n QDataStream stream(&zclFrame.payload(), QIODevice::WriteOnly);\r\n stream.setByteOrder(QDataStream::LittleEndian);\r\n\r\n quint8 options = 0x0b; \/\/ enter commissioning mode, exit on window expire\r\n quint16 window = 40;\r\n stream << options;\r\n stream << window;\r\n }\r\n\r\n { \/\/ ZCL frame\r\n\r\n QDataStream stream(&req.asdu(), QIODevice::WriteOnly);\r\n stream.setByteOrder(QDataStream::LittleEndian);\r\n zclFrame.writeToStream(stream);\r\n }\r\n\r\n \/\/ broadcast\r\n if (apsCtrl->apsdeDataRequest(req) == deCONZ::Success)\r\n {\r\n DBG_Printf(DBG_INFO, \"send GP proxy commissioning mode\\n\");\r\n return true;\r\n }\r\n\r\n DBG_Printf(DBG_INFO, \"send GP proxy commissioning mode failed\\n\");\r\n return false;\r\n}\r\n\r\n\/*! Send Pair command to GP proxy device.\r\n *\/\r\nbool DeRestPluginPrivate::sendGPPairing(quint32 gpdSrcId, quint16 sinkGroupId, quint8 deviceId, quint32 frameCounter, const quint8 *key)\r\n{\r\n deCONZ::ApsDataRequest req;\r\n\r\n req.setDstAddressMode(deCONZ::ApsNwkAddress);\r\n req.dstAddress().setNwk(deCONZ::BroadcastRouters);\r\n req.setProfileId(GP_PROFILE_ID);\r\n req.setClusterId(GREEN_POWER_CLUSTER_ID);\r\n req.setDstEndpoint(GREEN_POWER_ENDPOINT);\r\n req.setSrcEndpoint(GREEN_POWER_ENDPOINT);\r\n req.setTxOptions(nullptr);\r\n req.setRadius(0);\r\n\r\n QDataStream stream(&req.asdu(), QIODevice::WriteOnly);\r\n stream.setByteOrder(QDataStream::LittleEndian);\r\n\r\n deCONZ::ZclFrame zclFrame;\r\n\r\n zclFrame.setSequenceNumber(zclSeq++);\r\n zclFrame.setCommandId(0x01); \/\/ pairing\r\n zclFrame.setFrameControl(deCONZ::ZclFCClusterCommand |\r\n deCONZ::ZclFCDirectionServerToClient |\r\n deCONZ::ZclFCDisableDefaultResponse);\r\n\r\n { \/\/ payload\r\n QDataStream stream(&zclFrame.payload(), QIODevice::WriteOnly);\r\n stream.setByteOrder(QDataStream::LittleEndian);\r\n\r\n frameCounter = 0;\r\n\r\n quint8 options0 = 0x48; \/\/ enter commissioning mode, exit on window expire\r\n \/\/quint8 options1 = key ? 0xe5 : 0x65;\r\n quint8 options1 = 0x40;\r\n quint8 options2 = 0x00;\r\n stream << options0;\r\n stream << options1;\r\n stream << options2;\r\n stream << gpdSrcId;\r\n stream << sinkGroupId;\r\n stream << deviceId;\r\n stream << frameCounter;\r\n\r\n if (key)\r\n {\r\n\/\/ for (size_t i = 0; i < 16; i++)\r\n\/\/ {\r\n\/\/ stream << (quint8)key[i];\r\n\/\/ }\r\n }\r\n }\r\n\r\n { \/\/ ZCL frame\r\n\r\n QDataStream stream(&req.asdu(), QIODevice::WriteOnly);\r\n stream.setByteOrder(QDataStream::LittleEndian);\r\n zclFrame.writeToStream(stream);\r\n }\r\n\r\n \/\/ broadcast\r\n if (apsCtrl->apsdeDataRequest(req) == deCONZ::Success)\r\n {\r\n DBG_Printf(DBG_INFO, \"send GP pairing\\n\");\r\n return true;\r\n }\r\n\r\n DBG_Printf(DBG_INFO, \"send GP pairing\\n\");\r\n return false;\r\n}\r\n\r\n\/*! Handle broadcasting of permit join interval.\r\n\r\n This is done every PERMIT_JOIN_SEND_INTERVAL to ensure\r\n any node in the network has the same settings.\r\n *\/\r\nvoid DeRestPluginPrivate::permitJoinTimerFired()\r\n{\r\n Q_Q(DeRestPlugin);\r\n if (!q->pluginActive() || !apsCtrl)\r\n {\r\n return;\r\n }\r\n\r\n if ((gwPermitJoinDuration > 0) && (gwPermitJoinDuration < 255))\r\n {\r\n permitJoinFlag = true;\r\n gwPermitJoinDuration--;\r\n\r\n if ((gwPermitJoinDuration % 10) == 0)\r\n {\r\n \/\/ try to add light nodes even if they existed in deCONZ bevor and therefore\r\n \/\/ no node added event will be triggert in this phase\r\n int i = 0;\r\n const deCONZ::Node *node = nullptr;\r\n while (apsCtrl->getNode(i, &node) == 0)\r\n {\r\n if (node && !node->isZombie() &&\r\n !node->nodeDescriptor().isNull() && node->nodeDescriptor().receiverOnWhenIdle())\r\n {\r\n addLightNode(node);\r\n }\r\n i++;\r\n }\r\n }\r\n else if ((gwPermitJoinDuration % 15) == 0)\r\n {\r\n for (LightNode &l : nodes)\r\n {\r\n if (l.isAvailable() && l.modelId().isEmpty())\r\n {\r\n queuePollNode(&l);\r\n }\r\n }\r\n }\r\n\r\n updateEtag(gwConfigEtag); \/\/ update Etag so that webApp can count down permitJoin duration\r\n }\r\n\r\n if (gwPermitJoinDuration == 0 && permitJoinFlag)\r\n {\r\n permitJoinFlag = false;\r\n }\r\n\r\n if (!isInNetwork())\r\n {\r\n return;\r\n }\r\n\r\n auto ctrlPermitJoin = apsCtrl->getParameter(deCONZ::ParamPermitJoin);\r\n if (ctrlPermitJoin > 0 && gwPermitJoinDuration == 0)\r\n {\r\n \/\/ workaround since the firmware reports cached value instead hot value\r\n apsCtrl->setPermitJoin(gwPermitJoinDuration);\r\n permitJoinLastSendTime = {}; \/\/ force broadcast\r\n }\r\n\r\n\/\/ if (gwPermitJoinDuration == 0 && otauLastBusyTimeDelta() < (60 * 5))\r\n\/\/ {\r\n\/\/ \/\/ don't pollute channel while OTA is running\r\n\/\/ return;\r\n\/\/ }\r\n\r\n QTime now = QTime::currentTime();\r\n int diff = permitJoinLastSendTime.msecsTo(now);\r\n\r\n if (!permitJoinLastSendTime.isValid() || (diff > PERMIT_JOIN_SEND_INTERVAL))\r\n {\r\n deCONZ::ApsDataRequest apsReq;\r\n quint8 tcSignificance = 0x01;\r\n\r\n apsReq.setDstAddressMode(deCONZ::ApsNwkAddress);\r\n apsReq.dstAddress().setNwk(deCONZ::BroadcastRouters);\r\n apsReq.setProfileId(ZDP_PROFILE_ID);\r\n apsReq.setClusterId(ZDP_MGMT_PERMIT_JOINING_REQ_CLID);\r\n apsReq.setDstEndpoint(ZDO_ENDPOINT);\r\n apsReq.setSrcEndpoint(ZDO_ENDPOINT);\r\n apsReq.setTxOptions(0);\r\n apsReq.setRadius(0);\r\n\r\n QDataStream stream(&apsReq.asdu(), QIODevice::WriteOnly);\r\n stream.setByteOrder(QDataStream::LittleEndian);\r\n\r\n stream << (uint8_t)now.second(); \/\/ seqno\r\n stream << gwPermitJoinDuration;\r\n stream << tcSignificance;\r\n\r\n DBG_Assert(apsCtrl != 0);\r\n\r\n if (!apsCtrl)\r\n {\r\n return;\r\n }\r\n\r\n \/\/ set for own node\r\n apsCtrl->setPermitJoin(gwPermitJoinDuration);\r\n\r\n \/\/ broadcast\r\n if (apsCtrl->apsdeDataRequest(apsReq) == deCONZ::Success)\r\n {\r\n DBG_Printf(DBG_INFO, \"send permit join, duration: %d\\n\", gwPermitJoinDuration);\r\n permitJoinLastSendTime = now;\r\n\r\n if (gwPermitJoinDuration > 0)\r\n {\r\n \/\/ sendGPProxyCommissioningMode(); TODO enable when GP security is implemented\r\n }\r\n }\r\n else\r\n {\r\n DBG_Printf(DBG_INFO, \"send permit join failed\\n\");\r\n }\r\n }\r\n}\r\n\r\n\/*! Check if permitJoin is > 60 seconds then resend permitjoin with 60 seconds\r\n *\/\r\nvoid DeRestPluginPrivate::resendPermitJoinTimerFired()\r\n{\r\n resendPermitJoinTimer->stop();\r\n if (gwPermitJoinDuration <= 1)\r\n {\r\n if (gwPermitJoinResend > 0)\r\n {\r\n if (gwPermitJoinResend >= 60)\r\n {\r\n setPermitJoinDuration(60);\r\n }\r\n else\r\n {\r\n setPermitJoinDuration(gwPermitJoinResend);\r\n }\r\n gwPermitJoinResend -= 60;\r\n updateEtag(gwConfigEtag);\r\n if (gwPermitJoinResend <= 0)\r\n {\r\n gwPermitJoinResend = 0;\r\n return;\r\n }\r\n\r\n }\r\n else if (gwPermitJoinResend == 0)\r\n {\r\n setPermitJoinDuration(0);\r\n return;\r\n }\r\n }\r\n else if (gwPermitJoinResend == 0)\r\n {\r\n setPermitJoinDuration(0);\r\n return;\r\n }\r\n resendPermitJoinTimer->start(1000);\r\n}\r\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 \"webrtc\/video_engine\/vie_base_impl.h\"\n\n#include \n#include \n\n#include \"webrtc\/engine_configurations.h\"\n#include \"webrtc\/modules\/rtp_rtcp\/interface\/rtp_rtcp.h\"\n#include \"webrtc\/modules\/video_coding\/main\/interface\/video_coding.h\"\n#include \"webrtc\/modules\/video_processing\/main\/interface\/video_processing.h\"\n#include \"webrtc\/modules\/video_render\/include\/video_render.h\"\n#include \"webrtc\/system_wrappers\/interface\/critical_section_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/logging.h\"\n#include \"webrtc\/video_engine\/include\/vie_errors.h\"\n#include \"webrtc\/video_engine\/vie_capturer.h\"\n#include \"webrtc\/video_engine\/vie_channel.h\"\n#include \"webrtc\/video_engine\/vie_channel_manager.h\"\n#include \"webrtc\/video_engine\/vie_defines.h\"\n#include \"webrtc\/video_engine\/vie_encoder.h\"\n#include \"webrtc\/video_engine\/vie_impl.h\"\n#include \"webrtc\/video_engine\/vie_input_manager.h\"\n#include \"webrtc\/video_engine\/vie_shared_data.h\"\n\nnamespace webrtc {\n\nViEBase* ViEBase::GetInterface(VideoEngine* video_engine) {\n if (!video_engine) {\n return NULL;\n }\n VideoEngineImpl* vie_impl = static_cast(video_engine);\n ViEBaseImpl* vie_base_impl = vie_impl;\n (*vie_base_impl)++; \/\/ Increase ref count.\n\n return vie_base_impl;\n}\n\nint ViEBaseImpl::Release() {\n (*this)--; \/\/ Decrease ref count.\n\n int32_t ref_count = GetCount();\n if (ref_count < 0) {\n LOG(LS_WARNING) << \"ViEBase released too many times.\";\n return -1;\n }\n return ref_count;\n}\n\nViEBaseImpl::ViEBaseImpl(const Config& config)\n : shared_data_(config) {}\n\nViEBaseImpl::~ViEBaseImpl() {}\n\nint ViEBaseImpl::Init() {\n return 0;\n}\n\nint ViEBaseImpl::SetVoiceEngine(VoiceEngine* voice_engine) {\n LOG_F(LS_INFO) << \"SetVoiceEngine\";\n if (shared_data_.channel_manager()->SetVoiceEngine(voice_engine) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::RegisterCpuOveruseObserver(int video_channel,\n CpuOveruseObserver* observer) {\n LOG_F(LS_INFO) << \"RegisterCpuOveruseObserver on channel \" << video_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder);\n\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n ViECapturer* capturer = is.Capture(provider->Id());\n assert(capturer);\n capturer->RegisterCpuOveruseObserver(observer);\n }\n\n shared_data_.overuse_observers()->insert(\n std::pair(video_channel, observer));\n return 0;\n}\n\nint ViEBaseImpl::SetCpuOveruseOptions(int video_channel,\n const CpuOveruseOptions& options) {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder);\n\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n ViECapturer* capturer = is.Capture(provider->Id());\n if (capturer) {\n capturer->SetCpuOveruseOptions(options);\n return 0;\n }\n }\n return -1;\n}\n\nint ViEBaseImpl::GetCpuOveruseMetrics(int video_channel,\n CpuOveruseMetrics* metrics) {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder);\n\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n ViECapturer* capturer = is.Capture(provider->Id());\n if (capturer) {\n capturer->GetCpuOveruseMetrics(metrics);\n return 0;\n }\n }\n return -1;\n}\n\nvoid ViEBaseImpl::RegisterSendSideDelayObserver(\n int channel, SendSideDelayObserver* observer) {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(channel);\n assert(vie_channel);\n vie_channel->RegisterSendSideDelayObserver(observer);\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel) { \/\/ NOLINT\n return CreateChannel(video_channel, static_cast(NULL));\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel, \/\/ NOLINT\n const Config* config) {\n if (shared_data_.channel_manager()->CreateChannel(&video_channel,\n config) == -1) {\n video_channel = -1;\n shared_data_.SetLastError(kViEBaseChannelCreationFailed);\n return -1;\n }\n LOG(LS_INFO) << \"Video channel created: \" << video_channel;\n return 0;\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel, \/\/ NOLINT\n int original_channel) {\n return CreateChannel(video_channel, original_channel, true, false);\n}\n\nint ViEBaseImpl::CreateChannelWithoutDefaultEncoder(\n int& video_channel, \/\/ NOLINT\n int original_channel) {\n return CreateChannel(video_channel, original_channel, true, true);\n}\n\nint ViEBaseImpl::CreateReceiveChannel(int& video_channel, \/\/ NOLINT\n int original_channel) {\n return CreateChannel(video_channel, original_channel, false, true);\n}\n\nint ViEBaseImpl::DeleteChannel(const int video_channel) {\n {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n \/\/ Deregister the ViEEncoder if no other channel is using it.\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n if (cs.ChannelUsingViEEncoder(video_channel) == false) {\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n provider->DeregisterFrameCallback(vie_encoder);\n }\n }\n }\n\n if (shared_data_.channel_manager()->DeleteChannel(video_channel) == -1) {\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n LOG(LS_INFO) << \"Channel deleted \" << video_channel;\n return 0;\n}\n\nint ViEBaseImpl::ConnectAudioChannel(const int video_channel,\n const int audio_channel) {\n LOG_F(LS_INFO) << \"ConnectAudioChannel, video channel \" << video_channel\n << \", audio channel \" << audio_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(video_channel)) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->ConnectVoiceChannel(video_channel,\n audio_channel) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::DisconnectAudioChannel(const int video_channel) {\n LOG_F(LS_INFO) << \"DisconnectAudioChannel \" << video_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(video_channel)) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->DisconnectVoiceChannel(\n video_channel) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StartSend(const int video_channel) {\n LOG_F(LS_INFO) << \"StartSend: \" << video_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder != NULL);\n if (vie_encoder->Owner() != video_channel) {\n LOG_F(LS_ERROR) << \"Can't start send on a receive only channel.\";\n shared_data_.SetLastError(kViEBaseReceiveOnlyChannel);\n return -1;\n }\n\n \/\/ Pause and trigger a key frame.\n vie_encoder->Pause();\n int32_t error = vie_channel->StartSend();\n if (error != 0) {\n vie_encoder->Restart();\n if (error == kViEBaseAlreadySending) {\n shared_data_.SetLastError(kViEBaseAlreadySending);\n }\n LOG_F(LS_ERROR) << \"Could not start sending \" << video_channel;\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n vie_encoder->SendKeyFrame();\n vie_encoder->Restart();\n return 0;\n}\n\nint ViEBaseImpl::StopSend(const int video_channel) {\n LOG_F(LS_INFO) << \"StopSend \" << video_channel;\n\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n int32_t error = vie_channel->StopSend();\n if (error != 0) {\n if (error == kViEBaseNotSending) {\n shared_data_.SetLastError(kViEBaseNotSending);\n } else {\n LOG_F(LS_ERROR) << \"Could not stop sending \" << video_channel;\n shared_data_.SetLastError(kViEBaseUnknownError);\n }\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StartReceive(const int video_channel) {\n LOG_F(LS_INFO) << \"StartReceive \" << video_channel;\n\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n if (vie_channel->StartReceive() != 0) {\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StopReceive(const int video_channel) {\n LOG_F(LS_INFO) << \"StopReceive \" << video_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n if (vie_channel->StopReceive() != 0) {\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::GetVersion(char version[1024]) {\n assert(version != NULL);\n strcpy(version, \"VideoEngine 41\");\n return 0;\n}\n\nint ViEBaseImpl::LastError() {\n return shared_data_.LastErrorInternal();\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel, \/\/ NOLINT\n int original_channel,\n bool sender,\n bool disable_default_encoder) {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(original_channel)) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->CreateChannel(\n &video_channel, original_channel, sender, disable_default_encoder) ==\n -1) {\n video_channel = -1;\n shared_data_.SetLastError(kViEBaseChannelCreationFailed);\n return -1;\n }\n LOG_F(LS_INFO) << \"VideoChannel created: \" << video_channel\n << \", base channel \" << original_channel\n << \", is send channel : \" << sender;\n return 0;\n}\n\nvoid ViEBaseImpl::RegisterSendStatisticsProxy(\n int channel,\n SendStatisticsProxy* send_statistics_proxy) {\n LOG_F(LS_VERBOSE) << \"RegisterSendStatisticsProxy on channel \" << channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return;\n }\n ViEEncoder* vie_encoder = cs.Encoder(channel);\n assert(vie_encoder);\n\n vie_encoder->RegisterSendStatisticsProxy(send_statistics_proxy);\n}\n\nvoid ViEBaseImpl::RegisterReceiveStatisticsProxy(\n int channel,\n ReceiveStatisticsProxy* receive_statistics_proxy) {\n LOG_F(LS_VERBOSE) << \"RegisterReceiveStatisticsProxy on channel \" << channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return;\n }\n vie_channel->RegisterReceiveStatisticsProxy(receive_statistics_proxy);\n}\n} \/\/ namespace webrtc\nBump to version 42.\/*\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 \"webrtc\/video_engine\/vie_base_impl.h\"\n\n#include \n#include \n\n#include \"webrtc\/engine_configurations.h\"\n#include \"webrtc\/modules\/rtp_rtcp\/interface\/rtp_rtcp.h\"\n#include \"webrtc\/modules\/video_coding\/main\/interface\/video_coding.h\"\n#include \"webrtc\/modules\/video_processing\/main\/interface\/video_processing.h\"\n#include \"webrtc\/modules\/video_render\/include\/video_render.h\"\n#include \"webrtc\/system_wrappers\/interface\/critical_section_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/logging.h\"\n#include \"webrtc\/video_engine\/include\/vie_errors.h\"\n#include \"webrtc\/video_engine\/vie_capturer.h\"\n#include \"webrtc\/video_engine\/vie_channel.h\"\n#include \"webrtc\/video_engine\/vie_channel_manager.h\"\n#include \"webrtc\/video_engine\/vie_defines.h\"\n#include \"webrtc\/video_engine\/vie_encoder.h\"\n#include \"webrtc\/video_engine\/vie_impl.h\"\n#include \"webrtc\/video_engine\/vie_input_manager.h\"\n#include \"webrtc\/video_engine\/vie_shared_data.h\"\n\nnamespace webrtc {\n\nViEBase* ViEBase::GetInterface(VideoEngine* video_engine) {\n if (!video_engine) {\n return NULL;\n }\n VideoEngineImpl* vie_impl = static_cast(video_engine);\n ViEBaseImpl* vie_base_impl = vie_impl;\n (*vie_base_impl)++; \/\/ Increase ref count.\n\n return vie_base_impl;\n}\n\nint ViEBaseImpl::Release() {\n (*this)--; \/\/ Decrease ref count.\n\n int32_t ref_count = GetCount();\n if (ref_count < 0) {\n LOG(LS_WARNING) << \"ViEBase released too many times.\";\n return -1;\n }\n return ref_count;\n}\n\nViEBaseImpl::ViEBaseImpl(const Config& config)\n : shared_data_(config) {}\n\nViEBaseImpl::~ViEBaseImpl() {}\n\nint ViEBaseImpl::Init() {\n return 0;\n}\n\nint ViEBaseImpl::SetVoiceEngine(VoiceEngine* voice_engine) {\n LOG_F(LS_INFO) << \"SetVoiceEngine\";\n if (shared_data_.channel_manager()->SetVoiceEngine(voice_engine) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::RegisterCpuOveruseObserver(int video_channel,\n CpuOveruseObserver* observer) {\n LOG_F(LS_INFO) << \"RegisterCpuOveruseObserver on channel \" << video_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder);\n\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n ViECapturer* capturer = is.Capture(provider->Id());\n assert(capturer);\n capturer->RegisterCpuOveruseObserver(observer);\n }\n\n shared_data_.overuse_observers()->insert(\n std::pair(video_channel, observer));\n return 0;\n}\n\nint ViEBaseImpl::SetCpuOveruseOptions(int video_channel,\n const CpuOveruseOptions& options) {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder);\n\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n ViECapturer* capturer = is.Capture(provider->Id());\n if (capturer) {\n capturer->SetCpuOveruseOptions(options);\n return 0;\n }\n }\n return -1;\n}\n\nint ViEBaseImpl::GetCpuOveruseMetrics(int video_channel,\n CpuOveruseMetrics* metrics) {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder);\n\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n ViECapturer* capturer = is.Capture(provider->Id());\n if (capturer) {\n capturer->GetCpuOveruseMetrics(metrics);\n return 0;\n }\n }\n return -1;\n}\n\nvoid ViEBaseImpl::RegisterSendSideDelayObserver(\n int channel, SendSideDelayObserver* observer) {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(channel);\n assert(vie_channel);\n vie_channel->RegisterSendSideDelayObserver(observer);\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel) { \/\/ NOLINT\n return CreateChannel(video_channel, static_cast(NULL));\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel, \/\/ NOLINT\n const Config* config) {\n if (shared_data_.channel_manager()->CreateChannel(&video_channel,\n config) == -1) {\n video_channel = -1;\n shared_data_.SetLastError(kViEBaseChannelCreationFailed);\n return -1;\n }\n LOG(LS_INFO) << \"Video channel created: \" << video_channel;\n return 0;\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel, \/\/ NOLINT\n int original_channel) {\n return CreateChannel(video_channel, original_channel, true, false);\n}\n\nint ViEBaseImpl::CreateChannelWithoutDefaultEncoder(\n int& video_channel, \/\/ NOLINT\n int original_channel) {\n return CreateChannel(video_channel, original_channel, true, true);\n}\n\nint ViEBaseImpl::CreateReceiveChannel(int& video_channel, \/\/ NOLINT\n int original_channel) {\n return CreateChannel(video_channel, original_channel, false, true);\n}\n\nint ViEBaseImpl::DeleteChannel(const int video_channel) {\n {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n \/\/ Deregister the ViEEncoder if no other channel is using it.\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n if (cs.ChannelUsingViEEncoder(video_channel) == false) {\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n provider->DeregisterFrameCallback(vie_encoder);\n }\n }\n }\n\n if (shared_data_.channel_manager()->DeleteChannel(video_channel) == -1) {\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n LOG(LS_INFO) << \"Channel deleted \" << video_channel;\n return 0;\n}\n\nint ViEBaseImpl::ConnectAudioChannel(const int video_channel,\n const int audio_channel) {\n LOG_F(LS_INFO) << \"ConnectAudioChannel, video channel \" << video_channel\n << \", audio channel \" << audio_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(video_channel)) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->ConnectVoiceChannel(video_channel,\n audio_channel) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::DisconnectAudioChannel(const int video_channel) {\n LOG_F(LS_INFO) << \"DisconnectAudioChannel \" << video_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(video_channel)) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->DisconnectVoiceChannel(\n video_channel) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StartSend(const int video_channel) {\n LOG_F(LS_INFO) << \"StartSend: \" << video_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder != NULL);\n if (vie_encoder->Owner() != video_channel) {\n LOG_F(LS_ERROR) << \"Can't start send on a receive only channel.\";\n shared_data_.SetLastError(kViEBaseReceiveOnlyChannel);\n return -1;\n }\n\n \/\/ Pause and trigger a key frame.\n vie_encoder->Pause();\n int32_t error = vie_channel->StartSend();\n if (error != 0) {\n vie_encoder->Restart();\n if (error == kViEBaseAlreadySending) {\n shared_data_.SetLastError(kViEBaseAlreadySending);\n }\n LOG_F(LS_ERROR) << \"Could not start sending \" << video_channel;\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n vie_encoder->SendKeyFrame();\n vie_encoder->Restart();\n return 0;\n}\n\nint ViEBaseImpl::StopSend(const int video_channel) {\n LOG_F(LS_INFO) << \"StopSend \" << video_channel;\n\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n int32_t error = vie_channel->StopSend();\n if (error != 0) {\n if (error == kViEBaseNotSending) {\n shared_data_.SetLastError(kViEBaseNotSending);\n } else {\n LOG_F(LS_ERROR) << \"Could not stop sending \" << video_channel;\n shared_data_.SetLastError(kViEBaseUnknownError);\n }\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StartReceive(const int video_channel) {\n LOG_F(LS_INFO) << \"StartReceive \" << video_channel;\n\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n if (vie_channel->StartReceive() != 0) {\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StopReceive(const int video_channel) {\n LOG_F(LS_INFO) << \"StopReceive \" << video_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n if (vie_channel->StopReceive() != 0) {\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::GetVersion(char version[1024]) {\n assert(version != NULL);\n strcpy(version, \"VideoEngine 42\");\n return 0;\n}\n\nint ViEBaseImpl::LastError() {\n return shared_data_.LastErrorInternal();\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel, \/\/ NOLINT\n int original_channel,\n bool sender,\n bool disable_default_encoder) {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(original_channel)) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->CreateChannel(\n &video_channel, original_channel, sender, disable_default_encoder) ==\n -1) {\n video_channel = -1;\n shared_data_.SetLastError(kViEBaseChannelCreationFailed);\n return -1;\n }\n LOG_F(LS_INFO) << \"VideoChannel created: \" << video_channel\n << \", base channel \" << original_channel\n << \", is send channel : \" << sender;\n return 0;\n}\n\nvoid ViEBaseImpl::RegisterSendStatisticsProxy(\n int channel,\n SendStatisticsProxy* send_statistics_proxy) {\n LOG_F(LS_VERBOSE) << \"RegisterSendStatisticsProxy on channel \" << channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return;\n }\n ViEEncoder* vie_encoder = cs.Encoder(channel);\n assert(vie_encoder);\n\n vie_encoder->RegisterSendStatisticsProxy(send_statistics_proxy);\n}\n\nvoid ViEBaseImpl::RegisterReceiveStatisticsProxy(\n int channel,\n ReceiveStatisticsProxy* receive_statistics_proxy) {\n LOG_F(LS_VERBOSE) << \"RegisterReceiveStatisticsProxy on channel \" << channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return;\n }\n vie_channel->RegisterReceiveStatisticsProxy(receive_statistics_proxy);\n}\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"\/*\n\tCopyright (c) 2017-2018 Andrew Depke\n*\/\n#include \"LinuxHardware.h\"\n\n#include \"..\/..\/Core\/Platform.h\"\n\n#include \/\/ std::memcpy()\n#include \n#include \n#include \n#include \n\nnamespace Red\n{\n\tstd::string LinuxSystemHardware::GetOSName()\n\t{\n#if OS_LINUX\n\t\treturn \"Linux\";\n#elif OS_ANDROID\n\t\treturn \"Android\";\n#elif OS_BSD\n\t\treturn \"BSD\";\n#else\n\t\treturn \"Unknown\";\n#endif\n\t}\n\n\tuint8_t LinuxSystemHardware::GetArchitecture()\n\t{\n#if defined(__x86_64__) || defined(__ppc64__)\n\t\treturn 64;\n#else\n\t\treturn 32;\n#endif\n\t}\n\n\tstd::string LinuxSystemHardware::GetCPUVendor()\n\t{\n\t\tunsigned int Data[4] = { 0 };\n\t\tchar Vendor[13] = { 0 };\n\n\t\tif (__get_cpuid(0, &Data[0], &Data[1], &Data[2], &Data[3]) != 0)\n\t\t{\n\t\t\t\/\/ CPU vendor is stored in EBX EDX ECX (ASCII)\n\t\t\tstd::memcpy(Vendor + 0, &Data[1], 4); \/\/ EBX\n\t\t\tstd::memcpy(Vendor + 4, &Data[3], 4); \/\/ ECX\n\t\t\tstd::memcpy(Vendor + 8, &Data[2], 4); \/\/ EDX\n\t\t}\n\n\t\telse\n\t\t{\n\t\t\treturn \"Error\";\n\t\t}\n\n\t\tVendor[12] = '\\0';\n\n\t\treturn Vendor;\n\t}\n\n\tstd::string LinuxSystemHardware::GetCPUBrand()\n\t{\n\t\tunsigned int Data[4] = { 0 };\n\t\tchar Brand[49] = { 0 };\n\n\t\tif (__get_cpuid(0x80000002, &Data[0], &Data[1], &Data[2], &Data[3]) != 0)\n\t\t{\n\t\t\tstd::memcpy(Brand + 0, &Data[0], 4);\n\t\t\tstd::memcpy(Brand + 4, &Data[1], 4);\n\t\t\tstd::memcpy(Brand + 8, &Data[2], 4);\n\t\t\tstd::memcpy(Brand + 12, &Data[3], 4);\n\t\t}\n\n\t\telse\n\t\t{\n\t\t\treturn \"Error\";\n\t\t}\n\n\t\tif (__get_cpuid(0x80000003, &Data[0], &Data[1], &Data[2], &Data[3]) != 0)\n\t\t{\n\t\t\tstd::memcpy(Brand + 16, &Data[0], 4);\n\t\t\tstd::memcpy(Brand + 20, &Data[1], 4);\n\t\t\tstd::memcpy(Brand + 24, &Data[2], 4);\n\t\t\tstd::memcpy(Brand + 28, &Data[3], 4);\n\t\t}\n\n\t\telse\n\t\t{\n\t\t\treturn \"Error\";\n\t\t}\n\n\t\tif (__get_cpuid(0x80000004, &Data[0], &Data[1], &Data[2], &Data[3]) != 0)\n\t\t{\n\t\t\tstd::memcpy(Brand + 32, &Data[0], 4);\n\t\t\tstd::memcpy(Brand + 36, &Data[1], 4);\n\t\t\tstd::memcpy(Brand + 40, &Data[2], 4);\n\t\t\tstd::memcpy(Brand + 44, &Data[3], 4);\n\t\t}\n\n\t\telse\n\t\t{\n\t\t\treturn \"Error\";\n\t\t}\n\n\t\tBrand[48] = '\\0';\n\n\t\treturn Brand;\n\t}\n\n\tunsigned int LinuxSystemHardware::GetCPUCoreCount()\n\t{\n\t\treturn std::thread::hardware_concurrency();\n\t}\n\n\tunsigned long int LinuxSystemHardware::GetPhysicalMemory()\n\t{\n\t\treturn (sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGE_SIZE));\n\t}\n\n\tunsigned long int LinuxSystemHardware::GetDiskSpace()\n\t{\n\t\tchar Directory[PATH_MAX];\n\n\t\tif (getcwd(Directory, sizeof(Directory)))\n\t\t{\n\t\t\tstruct statfs FileSystemStats = { 0 };\n\n\t\t\tif (statfs(Directory, &FileSystemStats) == 0)\n\t\t\t{\n\t\t\t\treturn (FileSystemStats.f_blocks * FileSystemStats.f_bsize \/ 1024);\n\t\t\t}\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tunsigned long int LinuxSystemHardware::GetDiskSpaceAvailable()\n\t{\n\t\tchar Directory[1024];\n\n\t\tgetcwd(Directory, sizeof(Directory));\n\n\t\tstruct statfs FileSystemStats = { 0 };\n\n\t\tif (statfs(Directory, &FileSystemStats) == 0)\n\t\t{\n\t\t\treturn (FileSystemStats.f_bavail * FileSystemStats.f_bsize \/ 1024);\n\t\t}\n\n\t\treturn 0;\n\t}\n} \/\/ namespace Red\nFixed Unused Return Value Warning\/*\n\tCopyright (c) 2017-2018 Andrew Depke\n*\/\n#include \"LinuxHardware.h\"\n\n#include \"..\/..\/Core\/Platform.h\"\n\n#include \/\/ std::memcpy()\n#include \n#include \n#include \n#include \n\nnamespace Red\n{\n\tstd::string LinuxSystemHardware::GetOSName()\n\t{\n#if OS_LINUX\n\t\treturn \"Linux\";\n#elif OS_ANDROID\n\t\treturn \"Android\";\n#elif OS_BSD\n\t\treturn \"BSD\";\n#else\n\t\treturn \"Unknown\";\n#endif\n\t}\n\n\tuint8_t LinuxSystemHardware::GetArchitecture()\n\t{\n#if defined(__x86_64__) || defined(__ppc64__)\n\t\treturn 64;\n#else\n\t\treturn 32;\n#endif\n\t}\n\n\tstd::string LinuxSystemHardware::GetCPUVendor()\n\t{\n\t\tunsigned int Data[4] = { 0 };\n\t\tchar Vendor[13] = { 0 };\n\n\t\tif (__get_cpuid(0, &Data[0], &Data[1], &Data[2], &Data[3]) != 0)\n\t\t{\n\t\t\t\/\/ CPU vendor is stored in EBX EDX ECX (ASCII)\n\t\t\tstd::memcpy(Vendor + 0, &Data[1], 4); \/\/ EBX\n\t\t\tstd::memcpy(Vendor + 4, &Data[3], 4); \/\/ ECX\n\t\t\tstd::memcpy(Vendor + 8, &Data[2], 4); \/\/ EDX\n\t\t}\n\n\t\telse\n\t\t{\n\t\t\treturn \"Error\";\n\t\t}\n\n\t\tVendor[12] = '\\0';\n\n\t\treturn Vendor;\n\t}\n\n\tstd::string LinuxSystemHardware::GetCPUBrand()\n\t{\n\t\tunsigned int Data[4] = { 0 };\n\t\tchar Brand[49] = { 0 };\n\n\t\tif (__get_cpuid(0x80000002, &Data[0], &Data[1], &Data[2], &Data[3]) != 0)\n\t\t{\n\t\t\tstd::memcpy(Brand + 0, &Data[0], 4);\n\t\t\tstd::memcpy(Brand + 4, &Data[1], 4);\n\t\t\tstd::memcpy(Brand + 8, &Data[2], 4);\n\t\t\tstd::memcpy(Brand + 12, &Data[3], 4);\n\t\t}\n\n\t\telse\n\t\t{\n\t\t\treturn \"Error\";\n\t\t}\n\n\t\tif (__get_cpuid(0x80000003, &Data[0], &Data[1], &Data[2], &Data[3]) != 0)\n\t\t{\n\t\t\tstd::memcpy(Brand + 16, &Data[0], 4);\n\t\t\tstd::memcpy(Brand + 20, &Data[1], 4);\n\t\t\tstd::memcpy(Brand + 24, &Data[2], 4);\n\t\t\tstd::memcpy(Brand + 28, &Data[3], 4);\n\t\t}\n\n\t\telse\n\t\t{\n\t\t\treturn \"Error\";\n\t\t}\n\n\t\tif (__get_cpuid(0x80000004, &Data[0], &Data[1], &Data[2], &Data[3]) != 0)\n\t\t{\n\t\t\tstd::memcpy(Brand + 32, &Data[0], 4);\n\t\t\tstd::memcpy(Brand + 36, &Data[1], 4);\n\t\t\tstd::memcpy(Brand + 40, &Data[2], 4);\n\t\t\tstd::memcpy(Brand + 44, &Data[3], 4);\n\t\t}\n\n\t\telse\n\t\t{\n\t\t\treturn \"Error\";\n\t\t}\n\n\t\tBrand[48] = '\\0';\n\n\t\treturn Brand;\n\t}\n\n\tunsigned int LinuxSystemHardware::GetCPUCoreCount()\n\t{\n\t\treturn std::thread::hardware_concurrency();\n\t}\n\n\tunsigned long int LinuxSystemHardware::GetPhysicalMemory()\n\t{\n\t\treturn (sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGE_SIZE));\n\t}\n\n\tunsigned long int LinuxSystemHardware::GetDiskSpace()\n\t{\n\t\tchar Directory[PATH_MAX];\n\n\t\tif (getcwd(Directory, sizeof(Directory)))\n\t\t{\n\t\t\tstruct statfs FileSystemStats = { 0 };\n\n\t\t\tif (statfs(Directory, &FileSystemStats) == 0)\n\t\t\t{\n\t\t\t\treturn (FileSystemStats.f_blocks * FileSystemStats.f_bsize \/ 1024);\n\t\t\t}\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tunsigned long int LinuxSystemHardware::GetDiskSpaceAvailable()\n\t{\n\t\tchar Directory[PATH_MAX];\n\n\t\tif (getcwd(Directory, sizeof(Directory)))\n\t\t{\n\t\t\tstruct statfs FileSystemStats = { 0 };\n\n\t\t\tif (statfs(Directory, &FileSystemStats) == 0)\n\t\t\t{\n\t\t\t\treturn (FileSystemStats.f_bavail * FileSystemStats.f_bsize \/ 1024);\n\t\t\t}\n\t\t}\n\n\t\treturn 0;\n\t}\n} \/\/ namespace Red\n<|endoftext|>"} {"text":"\/*=========================================================================\n \n Program: Visualization Toolkit\n Module: vtkInputPort.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n \nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \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\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\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 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"vtkInputPort.h\"\n#include \"vtkOutputPort.h\"\n#include \"vtkMultiProcessController.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkUnstructuredGrid.h\"\n#include \"vtkStructuredGrid.h\"\n#include \"vtkRectilinearGrid.h\"\n#include \"vtkStructuredPoints.h\"\n#include \"vtkImageData.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkCommand.h\"\n\n\n\/\/----------------------------------------------------------------------------\nvtkInputPort* vtkInputPort::New()\n{\n \/\/ First try to create the object from the vtkObjectFactory\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkInputPort\");\n if(ret)\n {\n return (vtkInputPort*)ret;\n }\n \/\/ If the factory was unable to create the object, then create it here.\n return new vtkInputPort;\n}\n\n\n\n\n\n\/\/----------------------------------------------------------------------------\nvtkInputPort::vtkInputPort()\n{\n this->RemoteProcessId = 0;\n this->Tag = 0;\n \n \/\/ Controller keeps a reference to this object as well.\n this->Controller = NULL;\n this->SetController(vtkMultiProcessController::GetGlobalController());\n\n \/\/ State variables.\n this->TransferNeeded = 0;\n this->DataTime = 0;\n\n this->DoUpdateInformation = 1;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ We need to have a \"GetNetReferenceCount\" to avoid memory leaks.\nvtkInputPort::~vtkInputPort()\n{\n this->SetController(0);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInputPort::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkSource::PrintSelf(os,indent);\n os << indent << \"RemoteProcessId: \" << this->RemoteProcessId << endl;\n os << indent << \"Tag: \" << this->Tag << endl;\n os << indent << \"Controller: (\" << this->Controller << \")\\n\";\n os << indent << \"DataTime: \" << this->DataTime << endl;\n os << indent << \"TransferNeeded: \" << this->TransferNeeded << endl; \n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Maybe we can come up with a way to check the type of the upstream port's\n\/\/ input here. While we are at it, we could automatically generate a tag.\nvtkPolyData *vtkInputPort::GetPolyDataOutput()\n{\n vtkDataObject *output = NULL;\n \n \/\/ If there is already an output, I hope it is a vtkPolyData.\n if (this->Outputs)\n {\n output = this->Outputs[0];\n }\n if (output)\n {\n if (output->GetDataObjectType() == VTK_POLY_DATA)\n {\n return (vtkPolyData*)(output);\n }\n else\n {\n vtkWarningMacro(\"vtkInputPort: Changing data type of output.\");\n }\n }\n \n output = vtkPolyData::New();\n output->ReleaseData();\n this->vtkSource::SetNthOutput(0, output);\n output->Delete();\n return (vtkPolyData*)(output);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Maybe we can come up with a way to check the type of the upstream port's\n\/\/ input here. While we are at it, we could automatically generate a tag.\nvtkUnstructuredGrid *vtkInputPort::GetUnstructuredGridOutput()\n{\n vtkDataObject *output = NULL;\n \n \/\/ If there is already an output, I hope it is a vtkPolyData.\n if (this->Outputs)\n {\n output = this->Outputs[0];\n }\n if (output)\n {\n if (output->GetDataObjectType() == VTK_UNSTRUCTURED_GRID)\n {\n return (vtkUnstructuredGrid*)(output);\n }\n else\n {\n vtkWarningMacro(\"vtkInputPort: Changing data type of output.\");\n }\n }\n \n output = vtkUnstructuredGrid::New();\n output->ReleaseData();\n this->vtkSource::SetNthOutput(0, output);\n output->Delete();\n return (vtkUnstructuredGrid*)(output);\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Maybe we can come up with a way to check the type of the upstream port's\n\/\/ input here. While we are at it, we could automatically generate a tag.\nvtkStructuredGrid *vtkInputPort::GetStructuredGridOutput()\n{\n vtkDataObject *output = NULL;\n \n \/\/ If there is already an output, I hope it is a vtkPolyData.\n if (this->Outputs)\n {\n output = this->Outputs[0];\n }\n if (output)\n {\n if (output->GetDataObjectType() == VTK_STRUCTURED_GRID)\n {\n return (vtkStructuredGrid*)(output);\n }\n else\n {\n vtkWarningMacro(\"vtkInputPort: Changing data type of output.\");\n }\n }\n \n output = vtkStructuredGrid::New();\n output->ReleaseData();\n this->vtkSource::SetNthOutput(0, output);\n output->Delete();\n return (vtkStructuredGrid*)(output);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Maybe we can come up with a way to check the type of the upstream port's\n\/\/ input here. While we are at it, we could automatically generate a tag.\nvtkRectilinearGrid *vtkInputPort::GetRectilinearGridOutput()\n{\n vtkDataObject *output = NULL;\n \n \/\/ If there is already an output, I hope it is a vtkPolyData.\n if (this->Outputs)\n {\n output = this->Outputs[0];\n }\n if (output)\n {\n if (output->GetDataObjectType() == VTK_RECTILINEAR_GRID)\n {\n return (vtkRectilinearGrid*)(output);\n }\n else\n {\n vtkWarningMacro(\"vtkInputPort: Changing data type of output.\");\n }\n }\n \n output = vtkRectilinearGrid::New();\n output->ReleaseData();\n this->vtkSource::SetNthOutput(0, output);\n output->Delete();\n return (vtkRectilinearGrid*)(output);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Maybe we can come up with a way to check the type of the upstream port's\n\/\/ input here. While we are at it, we could automatically generate a tag.\nvtkStructuredPoints *vtkInputPort::GetStructuredPointsOutput()\n{\n vtkDataObject *output = NULL;\n \n \/\/ If there is already an output, I hope it is a vtkPolyData.\n if (this->Outputs)\n {\n output = this->Outputs[0];\n }\n if (output)\n {\n if (output->GetDataObjectType() == VTK_STRUCTURED_POINTS)\n {\n return (vtkStructuredPoints*)(output);\n }\n else\n {\n vtkWarningMacro(\"vtkInputPort: Changing data type of output.\");\n }\n }\n \n output = vtkStructuredPoints::New();\n output->ReleaseData();\n this->vtkSource::SetNthOutput(0, output);\n output->Delete();\n return (vtkStructuredPoints*)(output);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Maybe we can come up with a way to check the type of the upstream port's\n\/\/ input here. While we are at it, we could automatically generate a tag.\nvtkImageData *vtkInputPort::GetImageDataOutput()\n{\n vtkDataObject *output = NULL;\n \n \/\/ If there is already an output, I hope it is a vtkImageData.\n if (this->Outputs)\n {\n output = this->Outputs[0];\n }\n if (output)\n {\n if (output->GetDataObjectType() == VTK_IMAGE_DATA)\n {\n return (vtkImageData*)(output);\n }\n else\n {\n vtkWarningMacro(\"vtkInputPort: Changing data type of output.\");\n }\n }\n \n output = vtkImageData::New();\n output->ReleaseData();\n this->vtkSource::SetNthOutput(0, output);\n output->Delete();\n return (vtkImageData*)(output);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ The only tricky thing here is the translation of the PipelineMTime\n\/\/ into a value meaningful to this process.\nvoid vtkInputPort::UpdateInformation()\n{\n vtkDataObject *output;\n unsigned long pmt;\n \n if (!this->DoUpdateInformation)\n {\n return;\n }\n\n if (this->Outputs == NULL || this->Outputs[0] == NULL)\n {\n vtkErrorMacro(\"No output.\");\n return;\n }\n\n output = this->Outputs[0];\n \n \/\/ Trigger UpdateInformation in remotePort.\n \/\/ Up-stream port should have the same tag.\n this->Controller->TriggerRMI(this->RemoteProcessId, this->Tag);\n \n \/\/ Now receive the information\n int wholeInformation[7];\n this->Controller->Receive( wholeInformation, 7, \n this->RemoteProcessId,\n vtkInputPort::INFORMATION_TRANSFER_TAG);\n\n this->Controller->Receive( &pmt, 1, \n this->RemoteProcessId,\n vtkInputPort::INFORMATION_TRANSFER_TAG);\n\n output->SetWholeExtent( wholeInformation );\n \n \/\/ Save the upstream PMT for execute check (this may not be necessary)\n this->UpStreamMTime = pmt;\n\n \/\/ !!! Make sure that Update is called if data is released. !!!\n if (pmt > this->DataTime || output->GetDataReleased())\n {\n \/\/ Our data is out of data. We will need a transfer.\n \/\/ This Modified call will ensure Update will get called.\n this->Modified();\n }\n output->SetPipelineMTime(this->GetMTime());\n \/\/ Locality has to be changed too.\n output->SetLocality(1.0);\n \n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ The only tricky thing here is the translation of the PipelineMTime\n\/\/ into a value meaningful to this process.\nvoid vtkInputPort::TriggerAsynchronousUpdate()\n{\n \/\/ This should be cleared by this point.\n \/\/ UpdateInformation and Update calls need to be made in pairs.\n if (this->TransferNeeded)\n {\n vtkWarningMacro(\"Transfer should have been received.\");\n return;\n }\n\n vtkDataObject *output = this->Outputs[0];\n\n \/\/ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n \/\/ This would normally be done in the Update method, but since\n \/\/ we want task parallelism with multiple input filters, \n \/\/ it needs to be here.\n\n \/\/ Do we need to update?\n \/\/ !!! I am uneasy about the Released check. Although a new update extent\n \/\/ will cause the data to be released, released data does not imply \n \/\/ Update will be called !!!!\n if (this->UpStreamMTime <= this->DataTime && ! output->GetDataReleased())\n { \n \/\/ No, we do not need to update.\n return;\n }\n\n \/\/ Trigger Update in remotePort.\n \/\/ remotePort should have the same tag.\n this->Controller->TriggerRMI(this->RemoteProcessId, this->Tag+1);\n \n \/\/ Send the UpdateExtent request. The first 6 ints are the 3d extent, the next\n \/\/ to are the pieces extent (we don't know which type it is - just send both)\n int extent[9];\n output->GetUpdateExtent( extent );\n extent[6] = output->GetUpdatePiece();\n extent[7] = output->GetUpdateNumberOfPieces(); \n extent[8] = output->GetUpdateGhostLevel(); \n this->Controller->Send( extent, 9, this->RemoteProcessId, \n vtkInputPort::UPDATE_EXTENT_TAG);\n\n \/\/ This is for pipeline parallism.\n \/\/ The Upstream port may or may not promote its data (execute).\n \/\/ It needs the data time of our output to compare to the mtime\n \/\/ of its input to determine if it should send the data (execute).\n this->Controller->Send( &(this->DataTime), 1, this->RemoteProcessId,\n\t\t\t vtkInputPort::NEW_DATA_TIME_TAG);\n \n \/\/ This automatically causes to remotePort to send the data.\n \/\/ Tell the update method to receive the data.\n this->TransferNeeded = 1;\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInputPort::UpdateData(vtkDataObject *output)\n{\n\n if (this->UpStreamMTime <= this->DataTime && ! output->GetDataReleased())\n { \n \/\/ No, we do not need to update.\n return;\n }\n\n if ( ! this->TransferNeeded)\n {\n \/\/ If something unexpected happened, let me know.\n vtkWarningMacro(\"UpdateData was called when no data was needed.\");\n return;\n }\n \n this->InvokeEvent(vtkCommand::StartEvent,NULL);\n\n \/\/ Well here is a bit of a hack.\n \/\/ Since the reader will overwrite whole extents, we need to save the whole\n \/\/ extent and reset it.\n int wholeExtent[6];\n output->GetWholeExtent(wholeExtent);\n \/\/ receive the data\n\n this->Controller->Receive(output, this->RemoteProcessId,\n\t\t\t vtkInputPort::DATA_TRANSFER_TAG);\n\n output->SetWholeExtent( wholeExtent );\n\n this->InvokeEvent(vtkCommand::EndEvent,NULL);\n\n \/\/ Receive the data time\n this->Controller->Receive( &(this->DataTime), 1, this->RemoteProcessId,\n\t\t\t vtkInputPort::NEW_DATA_TIME_TAG);\n \n this->TransferNeeded = 0;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nUnnecessary warnings.\/*=========================================================================\n \n Program: Visualization Toolkit\n Module: vtkInputPort.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n \nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \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\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\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 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"vtkInputPort.h\"\n#include \"vtkOutputPort.h\"\n#include \"vtkMultiProcessController.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkUnstructuredGrid.h\"\n#include \"vtkStructuredGrid.h\"\n#include \"vtkRectilinearGrid.h\"\n#include \"vtkStructuredPoints.h\"\n#include \"vtkImageData.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkCommand.h\"\n\n\n\/\/----------------------------------------------------------------------------\nvtkInputPort* vtkInputPort::New()\n{\n \/\/ First try to create the object from the vtkObjectFactory\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkInputPort\");\n if(ret)\n {\n return (vtkInputPort*)ret;\n }\n \/\/ If the factory was unable to create the object, then create it here.\n return new vtkInputPort;\n}\n\n\n\/\/----------------------------------------------------------------------------\nvtkInputPort::vtkInputPort()\n{\n this->RemoteProcessId = 0;\n this->Tag = 0;\n \n \/\/ Controller keeps a reference to this object as well.\n this->Controller = NULL;\n this->SetController(vtkMultiProcessController::GetGlobalController());\n\n \/\/ State variables.\n this->TransferNeeded = 0;\n this->DataTime = 0;\n\n this->DoUpdateInformation = 1;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ We need to have a \"GetNetReferenceCount\" to avoid memory leaks.\nvtkInputPort::~vtkInputPort()\n{\n this->SetController(0);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInputPort::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkSource::PrintSelf(os,indent);\n os << indent << \"RemoteProcessId: \" << this->RemoteProcessId << endl;\n os << indent << \"Tag: \" << this->Tag << endl;\n os << indent << \"Controller: (\" << this->Controller << \")\\n\";\n os << indent << \"DataTime: \" << this->DataTime << endl;\n os << indent << \"TransferNeeded: \" << this->TransferNeeded << endl; \n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Maybe we can come up with a way to check the type of the upstream port's\n\/\/ input here. While we are at it, we could automatically generate a tag.\nvtkPolyData *vtkInputPort::GetPolyDataOutput()\n{\n vtkDataObject *output = NULL;\n \n \/\/ If there is already an output, I hope it is a vtkPolyData.\n if (this->Outputs)\n {\n output = this->Outputs[0];\n }\n if (output)\n {\n if (output->GetDataObjectType() == VTK_POLY_DATA)\n {\n return (vtkPolyData*)(output);\n }\n\/\/ else\n\/\/ {\n\/\/ vtkWarningMacro(\"vtkInputPort: Changing data type of output.\");\n\/\/ }\n }\n \n output = vtkPolyData::New();\n output->ReleaseData();\n this->vtkSource::SetNthOutput(0, output);\n output->Delete();\n return (vtkPolyData*)(output);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Maybe we can come up with a way to check the type of the upstream port's\n\/\/ input here. While we are at it, we could automatically generate a tag.\nvtkUnstructuredGrid *vtkInputPort::GetUnstructuredGridOutput()\n{\n vtkDataObject *output = NULL;\n \n \/\/ If there is already an output, I hope it is a vtkPolyData.\n if (this->Outputs)\n {\n output = this->Outputs[0];\n }\n if (output)\n {\n if (output->GetDataObjectType() == VTK_UNSTRUCTURED_GRID)\n {\n return (vtkUnstructuredGrid*)(output);\n }\n\/\/ else\n\/\/ {\n\/\/ vtkWarningMacro(\"vtkInputPort: Changing data type of output.\");\n\/\/ }\n }\n \n output = vtkUnstructuredGrid::New();\n output->ReleaseData();\n this->vtkSource::SetNthOutput(0, output);\n output->Delete();\n return (vtkUnstructuredGrid*)(output);\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Maybe we can come up with a way to check the type of the upstream port's\n\/\/ input here. While we are at it, we could automatically generate a tag.\nvtkStructuredGrid *vtkInputPort::GetStructuredGridOutput()\n{\n vtkDataObject *output = NULL;\n \n \/\/ If there is already an output, I hope it is a vtkPolyData.\n if (this->Outputs)\n {\n output = this->Outputs[0];\n }\n if (output)\n {\n if (output->GetDataObjectType() == VTK_STRUCTURED_GRID)\n {\n return (vtkStructuredGrid*)(output);\n }\n\/\/ else\n\/\/ {\n\/\/ vtkWarningMacro(\"vtkInputPort: Changing data type of output.\");\n\/\/ }\n }\n \n output = vtkStructuredGrid::New();\n output->ReleaseData();\n this->vtkSource::SetNthOutput(0, output);\n output->Delete();\n return (vtkStructuredGrid*)(output);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Maybe we can come up with a way to check the type of the upstream port's\n\/\/ input here. While we are at it, we could automatically generate a tag.\nvtkRectilinearGrid *vtkInputPort::GetRectilinearGridOutput()\n{\n vtkDataObject *output = NULL;\n \n \/\/ If there is already an output, I hope it is a vtkPolyData.\n if (this->Outputs)\n {\n output = this->Outputs[0];\n }\n if (output)\n {\n if (output->GetDataObjectType() == VTK_RECTILINEAR_GRID)\n {\n return (vtkRectilinearGrid*)(output);\n }\n\/\/ else\n\/\/ {\n\/\/ vtkWarningMacro(\"vtkInputPort: Changing data type of output.\");\n\/\/ }\n }\n \n output = vtkRectilinearGrid::New();\n output->ReleaseData();\n this->vtkSource::SetNthOutput(0, output);\n output->Delete();\n return (vtkRectilinearGrid*)(output);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Maybe we can come up with a way to check the type of the upstream port's\n\/\/ input here. While we are at it, we could automatically generate a tag.\nvtkStructuredPoints *vtkInputPort::GetStructuredPointsOutput()\n{\n vtkDataObject *output = NULL;\n \n \/\/ If there is already an output, I hope it is a vtkPolyData.\n if (this->Outputs)\n {\n output = this->Outputs[0];\n }\n if (output)\n {\n if (output->GetDataObjectType() == VTK_STRUCTURED_POINTS)\n {\n return (vtkStructuredPoints*)(output);\n }\n\/\/ else\n\/\/ {\n\/\/ vtkWarningMacro(\"vtkInputPort: Changing data type of output.\");\n\/\/ }\n }\n \n output = vtkStructuredPoints::New();\n output->ReleaseData();\n this->vtkSource::SetNthOutput(0, output);\n output->Delete();\n return (vtkStructuredPoints*)(output);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Maybe we can come up with a way to check the type of the upstream port's\n\/\/ input here. While we are at it, we could automatically generate a tag.\nvtkImageData *vtkInputPort::GetImageDataOutput()\n{\n vtkDataObject *output = NULL;\n \n \/\/ If there is already an output, I hope it is a vtkImageData.\n if (this->Outputs)\n {\n output = this->Outputs[0];\n }\n if (output)\n {\n if (output->GetDataObjectType() == VTK_IMAGE_DATA)\n {\n return (vtkImageData*)(output);\n }\n\/\/ else\n\/\/ {\n\/\/ vtkWarningMacro(\"vtkInputPort: Changing data type of output.\");\n\/\/ }\n }\n \n output = vtkImageData::New();\n output->ReleaseData();\n this->vtkSource::SetNthOutput(0, output);\n output->Delete();\n return (vtkImageData*)(output);\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ The only tricky thing here is the translation of the PipelineMTime\n\/\/ into a value meaningful to this process.\nvoid vtkInputPort::UpdateInformation()\n{\n vtkDataObject *output;\n unsigned long pmt;\n \n if (!this->DoUpdateInformation)\n {\n return;\n }\n\n if (this->Outputs == NULL || this->Outputs[0] == NULL)\n {\n vtkErrorMacro(\"No output.\");\n return;\n }\n\n output = this->Outputs[0];\n \n \/\/ Trigger UpdateInformation in remotePort.\n \/\/ Up-stream port should have the same tag.\n this->Controller->TriggerRMI(this->RemoteProcessId, this->Tag);\n \n \/\/ Now receive the information\n int wholeInformation[7];\n this->Controller->Receive( wholeInformation, 7, \n this->RemoteProcessId,\n vtkInputPort::INFORMATION_TRANSFER_TAG);\n\n this->Controller->Receive( &pmt, 1, \n this->RemoteProcessId,\n vtkInputPort::INFORMATION_TRANSFER_TAG);\n\n output->SetWholeExtent( wholeInformation );\n \n \/\/ Save the upstream PMT for execute check (this may not be necessary)\n this->UpStreamMTime = pmt;\n\n \/\/ !!! Make sure that Update is called if data is released. !!!\n if (pmt > this->DataTime || output->GetDataReleased())\n {\n \/\/ Our data is out of data. We will need a transfer.\n \/\/ This Modified call will ensure Update will get called.\n this->Modified();\n }\n output->SetPipelineMTime(this->GetMTime());\n \/\/ Locality has to be changed too.\n output->SetLocality(1.0);\n \n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ The only tricky thing here is the translation of the PipelineMTime\n\/\/ into a value meaningful to this process.\nvoid vtkInputPort::TriggerAsynchronousUpdate()\n{\n \/\/ This should be cleared by this point.\n \/\/ UpdateInformation and Update calls need to be made in pairs.\n if (this->TransferNeeded)\n {\n vtkWarningMacro(\"Transfer should have been received.\");\n return;\n }\n\n vtkDataObject *output = this->Outputs[0];\n\n \/\/ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n \/\/ This would normally be done in the Update method, but since\n \/\/ we want task parallelism with multiple input filters, \n \/\/ it needs to be here.\n\n \/\/ Do we need to update?\n \/\/ !!! I am uneasy about the Released check. Although a new update extent\n \/\/ will cause the data to be released, released data does not imply \n \/\/ Update will be called !!!!\n if (this->UpStreamMTime <= this->DataTime && ! output->GetDataReleased())\n { \n \/\/ No, we do not need to update.\n return;\n }\n\n \/\/ Trigger Update in remotePort.\n \/\/ remotePort should have the same tag.\n this->Controller->TriggerRMI(this->RemoteProcessId, this->Tag+1);\n \n \/\/ Send the UpdateExtent request. The first 6 ints are the 3d extent, the next\n \/\/ to are the pieces extent (we don't know which type it is - just send both)\n int extent[9];\n output->GetUpdateExtent( extent );\n extent[6] = output->GetUpdatePiece();\n extent[7] = output->GetUpdateNumberOfPieces(); \n extent[8] = output->GetUpdateGhostLevel(); \n this->Controller->Send( extent, 9, this->RemoteProcessId, \n vtkInputPort::UPDATE_EXTENT_TAG);\n\n \/\/ This is for pipeline parallism.\n \/\/ The Upstream port may or may not promote its data (execute).\n \/\/ It needs the data time of our output to compare to the mtime\n \/\/ of its input to determine if it should send the data (execute).\n this->Controller->Send( &(this->DataTime), 1, this->RemoteProcessId,\n\t\t\t vtkInputPort::NEW_DATA_TIME_TAG);\n \n \/\/ This automatically causes to remotePort to send the data.\n \/\/ Tell the update method to receive the data.\n this->TransferNeeded = 1;\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInputPort::UpdateData(vtkDataObject *output)\n{\n\n if (this->UpStreamMTime <= this->DataTime && ! output->GetDataReleased())\n { \n \/\/ No, we do not need to update.\n return;\n }\n\n if ( ! this->TransferNeeded)\n {\n \/\/ If something unexpected happened, let me know.\n vtkWarningMacro(\"UpdateData was called when no data was needed.\");\n return;\n }\n \n this->InvokeEvent(vtkCommand::StartEvent,NULL);\n\n \/\/ Well here is a bit of a hack.\n \/\/ Since the reader will overwrite whole extents, we need to save the whole\n \/\/ extent and reset it.\n int wholeExtent[6];\n output->GetWholeExtent(wholeExtent);\n \/\/ receive the data\n\n this->Controller->Receive(output, this->RemoteProcessId,\n\t\t\t vtkInputPort::DATA_TRANSFER_TAG);\n\n output->SetWholeExtent( wholeExtent );\n\n this->InvokeEvent(vtkCommand::EndEvent,NULL);\n\n \/\/ Receive the data time\n this->Controller->Receive( &(this->DataTime), 1, this->RemoteProcessId,\n\t\t\t vtkInputPort::NEW_DATA_TIME_TAG);\n \n this->TransferNeeded = 0;\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":"#pragma once\n\n#include \n#include \n#include \n\n#include \"DataSpec\/DNACommon\/GX.hpp\"\n\n#include \"Runtime\/CRandom16.hpp\"\n#include \"Runtime\/CToken.hpp\"\n#include \"Runtime\/Graphics\/CLineRenderer.hpp\"\n#include \"Runtime\/Graphics\/CTexture.hpp\"\n#include \"Runtime\/Graphics\/Shaders\/CParticleSwooshShaders.hpp\"\n#include \"Runtime\/Particle\/CParticleGen.hpp\"\n#include \"Runtime\/Particle\/CUVElement.hpp\"\n\n#include \n#include \n#include \n\nnamespace urde {\nclass CSwooshDescription;\n\nclass CParticleSwoosh : public CParticleGen {\n friend class CParticleSwooshShaders;\n\n struct SSwooshData {\n bool x0_active;\n float x4_leftRad;\n float x8_rightRad;\n zeus::CVector3f xc_translation; \/\/ Updated by system's velocity sources or user code\n zeus::CVector3f x18_offset; \/\/ Updated by POFS once per system update (also resets x24_useOffset)\n zeus::CVector3f x24_useOffset; \/\/ Combination of POFS and NPOS, once per particle instance\n float x30_irot; \/\/ Rotation bias once per system update\n float x34_rotm; \/\/ Rotation bias once per particle instance\n zeus::CTransform x38_orientation; \/\/ Updated by user code\n int x68_frame; \/\/ Frame index of evaluated data\n zeus::CColor x6c_color; \/\/ Updated by COLR\n int x70_startFrame;\n zeus::CVector3f x74_velocity;\n\n SSwooshData(const zeus::CVector3f& translation, const zeus::CVector3f& offset, float irot, float rotm,\n int startFrame, bool active, const zeus::CTransform& orient, const zeus::CVector3f& vel, float leftRad,\n float rightRad, const zeus::CColor& color)\n : x0_active(active)\n , x4_leftRad(leftRad)\n , x8_rightRad(rightRad)\n , xc_translation(translation)\n , x18_offset(offset)\n , x24_useOffset(offset)\n , x30_irot(irot)\n , x34_rotm(rotm)\n , x38_orientation(orient)\n , x6c_color(color)\n , x70_startFrame(startFrame)\n , x74_velocity(vel) {}\n };\n\n TLockedToken x1c_desc;\n u32 x28_curFrame = 0;\n int x2c_PSLT = 0;\n double x30_curTime = 0.0;\n zeus::CVector3f x38_translation;\n zeus::CTransform x44_orientation;\n zeus::CTransform x74_invOrientation;\n zeus::CVector3f xa4_globalTranslation;\n zeus::CTransform xb0_globalOrientation;\n zeus::CVector3f xe0_globalScale = {1.f, 1.f, 1.f};\n zeus::CTransform xec_scaleXf;\n zeus::CTransform x11c_invScaleXf;\n zeus::CVector3f x14c_localScale = {1.f, 1.f, 1.f};\n u32 x158_curParticle = 0;\n std::vector x15c_swooshes;\n std::vector x16c_p0;\n std::vector x17c_p1;\n std::vector x18c_p2;\n std::vector x19c_p3;\n u32 x1ac_particleCount = 0;\n int x1b0_SPLN = 0;\n int x1b4_LENG = 0;\n int x1b8_SIDE = 0;\n GX::Primitive x1bc_prim;\n CRandom16 x1c0_rand;\n float x1c4_ = 0.f;\n float x1c8_ = 0.f;\n float x1cc_TSPN;\n bool x1d0_24_emitting : 1;\n bool x1d0_25_AALP : 1;\n bool x1d0_26_forceOneUpdate : 1;\n bool x1d0_27_renderGaps : 1;\n bool x1d0_28_LLRD : 1;\n bool x1d0_29_VLS1 : 1;\n bool x1d0_30_VLS2 : 1;\n bool x1d0_31_constantTex : 1;\n bool x1d1_24_constantUv : 1;\n\n SUVElementSet x1d4_uvs = {};\n CTexture* x1e4_tex = nullptr;\n float x1e8_uvSpan = 1.f;\n int x1ec_TSPN = 0;\n zeus::CVector3f x1f0_aabbMin;\n zeus::CVector3f x1fc_aabbMax;\n float x208_maxRadius = 0.f;\n zeus::CColor x20c_moduColor = zeus::skWhite;\n\n std::array, 2> m_dataBind;\n boo::ObjToken m_vertBuf;\n boo::ObjToken m_uniformBuf;\n std::unique_ptr m_lineRenderer;\n std::vector m_cachedVerts;\n\n static int g_ParticleSystemAliveCount;\n\n bool IsValid() const { return x1b4_LENG >= 2 && x1b8_SIDE >= 2; }\n void UpdateMaxRadius(float r);\n void UpdateBounds(const zeus::CVector3f& pos);\n float GetLeftRadius(size_t i) const;\n float GetRightRadius(size_t i) const;\n void UpdateSwooshTranslation(const zeus::CVector3f& translation);\n void UpdateTranslationAndOrientation();\n\n static zeus::CVector3f GetSplinePoint(const zeus::CVector3f& p0, const zeus::CVector3f& p1, const zeus::CVector3f& p2,\n const zeus::CVector3f& p3, float t);\n int WrapIndex(int i) const;\n void RenderNSidedSpline();\n void RenderNSidedNoSpline();\n void Render3SidedSolidSpline();\n void Render3SidedSolidNoSplineNoGaps();\n void Render2SidedSpline();\n void Render2SidedNoSplineGaps();\n void Render2SidedNoSplineNoGaps();\n\npublic:\n CParticleSwoosh(const TToken& desc, int);\n ~CParticleSwoosh() override;\n\n CSwooshDescription* GetDesc() { return x1c_desc.GetObj(); }\n\n bool Update(double) override;\n void Render(const CActorLights* = nullptr) override;\n void SetOrientation(const zeus::CTransform&) override;\n void SetTranslation(const zeus::CVector3f&) override;\n void SetGlobalOrientation(const zeus::CTransform&) override;\n void SetGlobalTranslation(const zeus::CVector3f&) override;\n void SetGlobalScale(const zeus::CVector3f&) override;\n void SetLocalScale(const zeus::CVector3f&) override;\n void SetParticleEmission(bool) override;\n void SetModulationColor(const zeus::CColor&) override;\n const zeus::CTransform& GetOrientation() const override;\n const zeus::CVector3f& GetTranslation() const override;\n const zeus::CTransform& GetGlobalOrientation() const override;\n const zeus::CVector3f& GetGlobalTranslation() const override;\n const zeus::CVector3f& GetGlobalScale() const override;\n const zeus::CColor& GetModulationColor() const override;\n bool IsSystemDeletable() const override;\n std::optional GetBounds() const override;\n u32 GetParticleCount() const override;\n bool SystemHasLight() const override;\n CLight GetLight() const override;\n bool GetParticleEmission() const override;\n void DestroyParticles() override;\n void Reset() override {}\n FourCC Get4CharId() const override { return FOURCC('SWHC'); }\n void SetRenderGaps(bool r) { x1d0_27_renderGaps = r; }\n\n void DoWarmupUpdate() {\n x1d0_26_forceOneUpdate = true;\n Update(0.0);\n }\n\n void DoElectricWarmup() {\n for (size_t i = 0; i < x15c_swooshes.size(); ++i) {\n x1d0_26_forceOneUpdate = true;\n Update(0.0);\n }\n }\n\n void DoElectricCreate(const std::vector& offsets) {\n u32 curIdx = x158_curParticle;\n for (size_t i = 0; i < x15c_swooshes.size(); ++i) {\n curIdx = u32((curIdx + 1) % x15c_swooshes.size());\n x15c_swooshes[curIdx].xc_translation = offsets[i];\n }\n }\n\n void DoGrappleWarmup() {\n for (size_t i = 0; i < x15c_swooshes.size() - 1; ++i) {\n x1d0_26_forceOneUpdate = true;\n Update(0.0);\n }\n }\n\n void DoGrappleUpdate(const zeus::CVector3f& beamGunPos, const zeus::CTransform& rotation, float anglePhase,\n float xAmplitude, float zAmplitude, const zeus::CVector3f& swooshSegDelta) {\n float rot = x15c_swooshes.back().x30_irot;\n zeus::CVector3f trans = beamGunPos;\n for (size_t i = 0; i < x15c_swooshes.size(); ++i) {\n SSwooshData& data = x15c_swooshes[i];\n zeus::CVector3f vec;\n if (i > 0)\n vec = rotation * zeus::CVector3f(std::cos(i + anglePhase) * xAmplitude, 0.f, std::sin(float(i)) * zAmplitude);\n data.xc_translation = trans + vec;\n trans += swooshSegDelta;\n std::swap(rot, data.x30_irot);\n }\n }\n\n void DoSpiderBallWarmup(zeus::CVector3f& translation, const zeus::CVector3f& transInc) {\n SetOrientation(zeus::lookAt(zeus::skZero3f, transInc));\n for (int i = 0; i < 6; ++i) {\n SetTranslation(translation);\n x1d0_26_forceOneUpdate = true;\n Update(0.0);\n translation += transInc;\n }\n }\n};\n\n} \/\/ namespace urde\nCParticleSwoosh: Initialize x68_frame on construction#pragma once\n\n#include \n#include \n#include \n\n#include \"DataSpec\/DNACommon\/GX.hpp\"\n\n#include \"Runtime\/CRandom16.hpp\"\n#include \"Runtime\/CToken.hpp\"\n#include \"Runtime\/Graphics\/CLineRenderer.hpp\"\n#include \"Runtime\/Graphics\/CTexture.hpp\"\n#include \"Runtime\/Graphics\/Shaders\/CParticleSwooshShaders.hpp\"\n#include \"Runtime\/Particle\/CParticleGen.hpp\"\n#include \"Runtime\/Particle\/CUVElement.hpp\"\n\n#include \n#include \n#include \n\nnamespace urde {\nclass CSwooshDescription;\n\nclass CParticleSwoosh : public CParticleGen {\n friend class CParticleSwooshShaders;\n\n struct SSwooshData {\n bool x0_active;\n float x4_leftRad;\n float x8_rightRad;\n zeus::CVector3f xc_translation; \/\/ Updated by system's velocity sources or user code\n zeus::CVector3f x18_offset; \/\/ Updated by POFS once per system update (also resets x24_useOffset)\n zeus::CVector3f x24_useOffset; \/\/ Combination of POFS and NPOS, once per particle instance\n float x30_irot; \/\/ Rotation bias once per system update\n float x34_rotm; \/\/ Rotation bias once per particle instance\n zeus::CTransform x38_orientation; \/\/ Updated by user code\n int x68_frame = 0; \/\/ Frame index of evaluated data\n zeus::CColor x6c_color; \/\/ Updated by COLR\n int x70_startFrame;\n zeus::CVector3f x74_velocity;\n\n SSwooshData(const zeus::CVector3f& translation, const zeus::CVector3f& offset, float irot, float rotm,\n int startFrame, bool active, const zeus::CTransform& orient, const zeus::CVector3f& vel, float leftRad,\n float rightRad, const zeus::CColor& color)\n : x0_active(active)\n , x4_leftRad(leftRad)\n , x8_rightRad(rightRad)\n , xc_translation(translation)\n , x18_offset(offset)\n , x24_useOffset(offset)\n , x30_irot(irot)\n , x34_rotm(rotm)\n , x38_orientation(orient)\n , x6c_color(color)\n , x70_startFrame(startFrame)\n , x74_velocity(vel) {}\n };\n\n TLockedToken x1c_desc;\n u32 x28_curFrame = 0;\n int x2c_PSLT = 0;\n double x30_curTime = 0.0;\n zeus::CVector3f x38_translation;\n zeus::CTransform x44_orientation;\n zeus::CTransform x74_invOrientation;\n zeus::CVector3f xa4_globalTranslation;\n zeus::CTransform xb0_globalOrientation;\n zeus::CVector3f xe0_globalScale = {1.f, 1.f, 1.f};\n zeus::CTransform xec_scaleXf;\n zeus::CTransform x11c_invScaleXf;\n zeus::CVector3f x14c_localScale = {1.f, 1.f, 1.f};\n u32 x158_curParticle = 0;\n std::vector x15c_swooshes;\n std::vector x16c_p0;\n std::vector x17c_p1;\n std::vector x18c_p2;\n std::vector x19c_p3;\n u32 x1ac_particleCount = 0;\n int x1b0_SPLN = 0;\n int x1b4_LENG = 0;\n int x1b8_SIDE = 0;\n GX::Primitive x1bc_prim;\n CRandom16 x1c0_rand;\n float x1c4_ = 0.f;\n float x1c8_ = 0.f;\n float x1cc_TSPN;\n bool x1d0_24_emitting : 1;\n bool x1d0_25_AALP : 1;\n bool x1d0_26_forceOneUpdate : 1;\n bool x1d0_27_renderGaps : 1;\n bool x1d0_28_LLRD : 1;\n bool x1d0_29_VLS1 : 1;\n bool x1d0_30_VLS2 : 1;\n bool x1d0_31_constantTex : 1;\n bool x1d1_24_constantUv : 1;\n\n SUVElementSet x1d4_uvs = {};\n CTexture* x1e4_tex = nullptr;\n float x1e8_uvSpan = 1.f;\n int x1ec_TSPN = 0;\n zeus::CVector3f x1f0_aabbMin;\n zeus::CVector3f x1fc_aabbMax;\n float x208_maxRadius = 0.f;\n zeus::CColor x20c_moduColor = zeus::skWhite;\n\n std::array, 2> m_dataBind;\n boo::ObjToken m_vertBuf;\n boo::ObjToken m_uniformBuf;\n std::unique_ptr m_lineRenderer;\n std::vector m_cachedVerts;\n\n static int g_ParticleSystemAliveCount;\n\n bool IsValid() const { return x1b4_LENG >= 2 && x1b8_SIDE >= 2; }\n void UpdateMaxRadius(float r);\n void UpdateBounds(const zeus::CVector3f& pos);\n float GetLeftRadius(size_t i) const;\n float GetRightRadius(size_t i) const;\n void UpdateSwooshTranslation(const zeus::CVector3f& translation);\n void UpdateTranslationAndOrientation();\n\n static zeus::CVector3f GetSplinePoint(const zeus::CVector3f& p0, const zeus::CVector3f& p1, const zeus::CVector3f& p2,\n const zeus::CVector3f& p3, float t);\n int WrapIndex(int i) const;\n void RenderNSidedSpline();\n void RenderNSidedNoSpline();\n void Render3SidedSolidSpline();\n void Render3SidedSolidNoSplineNoGaps();\n void Render2SidedSpline();\n void Render2SidedNoSplineGaps();\n void Render2SidedNoSplineNoGaps();\n\npublic:\n CParticleSwoosh(const TToken& desc, int);\n ~CParticleSwoosh() override;\n\n CSwooshDescription* GetDesc() { return x1c_desc.GetObj(); }\n\n bool Update(double) override;\n void Render(const CActorLights* = nullptr) override;\n void SetOrientation(const zeus::CTransform&) override;\n void SetTranslation(const zeus::CVector3f&) override;\n void SetGlobalOrientation(const zeus::CTransform&) override;\n void SetGlobalTranslation(const zeus::CVector3f&) override;\n void SetGlobalScale(const zeus::CVector3f&) override;\n void SetLocalScale(const zeus::CVector3f&) override;\n void SetParticleEmission(bool) override;\n void SetModulationColor(const zeus::CColor&) override;\n const zeus::CTransform& GetOrientation() const override;\n const zeus::CVector3f& GetTranslation() const override;\n const zeus::CTransform& GetGlobalOrientation() const override;\n const zeus::CVector3f& GetGlobalTranslation() const override;\n const zeus::CVector3f& GetGlobalScale() const override;\n const zeus::CColor& GetModulationColor() const override;\n bool IsSystemDeletable() const override;\n std::optional GetBounds() const override;\n u32 GetParticleCount() const override;\n bool SystemHasLight() const override;\n CLight GetLight() const override;\n bool GetParticleEmission() const override;\n void DestroyParticles() override;\n void Reset() override {}\n FourCC Get4CharId() const override { return FOURCC('SWHC'); }\n void SetRenderGaps(bool r) { x1d0_27_renderGaps = r; }\n\n void DoWarmupUpdate() {\n x1d0_26_forceOneUpdate = true;\n Update(0.0);\n }\n\n void DoElectricWarmup() {\n for (size_t i = 0; i < x15c_swooshes.size(); ++i) {\n x1d0_26_forceOneUpdate = true;\n Update(0.0);\n }\n }\n\n void DoElectricCreate(const std::vector& offsets) {\n u32 curIdx = x158_curParticle;\n for (size_t i = 0; i < x15c_swooshes.size(); ++i) {\n curIdx = u32((curIdx + 1) % x15c_swooshes.size());\n x15c_swooshes[curIdx].xc_translation = offsets[i];\n }\n }\n\n void DoGrappleWarmup() {\n for (size_t i = 0; i < x15c_swooshes.size() - 1; ++i) {\n x1d0_26_forceOneUpdate = true;\n Update(0.0);\n }\n }\n\n void DoGrappleUpdate(const zeus::CVector3f& beamGunPos, const zeus::CTransform& rotation, float anglePhase,\n float xAmplitude, float zAmplitude, const zeus::CVector3f& swooshSegDelta) {\n float rot = x15c_swooshes.back().x30_irot;\n zeus::CVector3f trans = beamGunPos;\n for (size_t i = 0; i < x15c_swooshes.size(); ++i) {\n SSwooshData& data = x15c_swooshes[i];\n zeus::CVector3f vec;\n if (i > 0)\n vec = rotation * zeus::CVector3f(std::cos(i + anglePhase) * xAmplitude, 0.f, std::sin(float(i)) * zAmplitude);\n data.xc_translation = trans + vec;\n trans += swooshSegDelta;\n std::swap(rot, data.x30_irot);\n }\n }\n\n void DoSpiderBallWarmup(zeus::CVector3f& translation, const zeus::CVector3f& transInc) {\n SetOrientation(zeus::lookAt(zeus::skZero3f, transInc));\n for (int i = 0; i < 6; ++i) {\n SetTranslation(translation);\n x1d0_26_forceOneUpdate = true;\n Update(0.0);\n translation += transInc;\n }\n }\n};\n\n} \/\/ namespace urde\n<|endoftext|>"} {"text":"\/*\nCopyright(c) 2016-2017 Panos Karabelas\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 furnished\nto do so, subject to the following conditions :\n\nThe above copyright notice and this permission notice shall be included in\nall copies 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, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n\/\/= INCLUDES ==================\n#include \"ScriptInstance.h\"\n#include \n#include \"Module.h\"\n#include \"..\/Core\/Helper.h\"\n#include \"..\/FileSystem\/FileSystem.h\"\n#include \"..\/Logging\/Log.h\"\n#include \"..\/Core\/GameObject.h\"\n\/\/=============================\n\n\/\/= NAMESPACES =====\nusing namespace std;\n\/\/==================\n\nScriptInstance::ScriptInstance()\n{\n\tm_gameObject = nullptr;\n\tm_constructorFunction = nullptr;\n\tm_startFunction = nullptr;\n\tm_updateFunction = nullptr;\n\tm_scriptObject = nullptr;\n\tm_module = nullptr;\n\tm_scriptEngine = nullptr;\n\tm_isInstantiated = false;\n}\n\nScriptInstance::~ScriptInstance()\n{\n\tSafeRelease(m_scriptObject);\n\n\tm_gameObject = nullptr;\n\tm_constructorFunction = nullptr;\n\tm_startFunction = nullptr;\n\tm_updateFunction = nullptr;\n\tm_scriptEngine = nullptr;\n\tm_isInstantiated = false;\n}\n\nbool ScriptInstance::Instantiate(const string& path, GameObject* gameObject, ScriptEngine* scriptEngine)\n{\n\tm_scriptEngine = scriptEngine;\n\n\t\/\/ Extract properties from path\n\tm_scriptPath = path;\n\tm_gameObject = gameObject;\n\tm_className = FileSystem::GetFileNameNoExtensionFromPath(m_scriptPath);\n\tm_moduleName = m_className + m_gameObject->GetID();\n\tm_constructorDeclaration = m_className + \" @\" + m_className + \"(GameObject @)\";\n\n\t\/\/ Instantiate the script\n\tm_isInstantiated = CreateScriptObject();\n\n\treturn m_isInstantiated;\n}\n\nbool ScriptInstance::IsInstantiated()\n{\n\treturn m_isInstantiated;\n}\n\nstring ScriptInstance::GetScriptPath()\n{\n\treturn m_scriptPath;\n}\n\nvoid ScriptInstance::ExecuteStart()\n{\n\tm_scriptEngine->ExecuteCall(m_startFunction, m_scriptObject);\n}\n\nvoid ScriptInstance::ExecuteUpdate()\n{\n\tm_scriptEngine->ExecuteCall(m_updateFunction, m_scriptObject);\n}\n\nbool ScriptInstance::CreateScriptObject()\n{\n\t\/\/ create module\n\tm_module = make_shared(m_moduleName, m_scriptEngine);\n\tbool result = m_module->LoadScript(m_scriptPath);\n\tif (!result) \n\t\treturn false;\n\n\tauto type_id = m_module->GetAsIScriptModule()->GetTypeIdByDecl(m_className.c_str());\n\tasITypeInfo* type = m_scriptEngine->GetAsIScriptEngine()->GetTypeInfoById(type_id);\n\tif (!type) \n\t\treturn false;\n\n\tm_startFunction = type->GetMethodByDecl(\"void Start()\"); \/\/ Get the Start function from the script\n\tm_updateFunction = type->GetMethodByDecl(\"void Update()\"); \/\/ Get the Update function from the script\n\tm_constructorFunction = type->GetFactoryByDecl(m_constructorDeclaration.c_str()); \/\/ Get the constructor function from the script\n\tif (!m_constructorFunction)\n\t{\n\t\tLOG_ERROR(\"Couldn't find the appropriate factory for the type '\" + m_className + \"'\");\n\t\treturn false;\n\t}\n\n\tasIScriptContext* context = m_scriptEngine->RequestContext(); \/\/ request a context\n\tint r = context->Prepare(m_constructorFunction); \/\/ prepare the context to call the factory function\n\tif (r < 0) return false;\n\n\tr = context->SetArgObject(0, m_gameObject); \/\/ Pass the gameobject as the constructor's parameter\n\tif (r < 0) return false;\n\n\tr = context->Execute(); \/\/ execute the call\n\tif (r < 0) return false;\n\n\t\/\/ get the object that was created\n\tm_scriptObject = *static_cast(context->GetAddressOfReturnValue());\n\n\t\/\/ if you're going to store the object you must increase the reference,\n\t\/\/ otherwise it will be destroyed when the context is reused or destroyed.\n\tm_scriptObject->AddRef();\n\n\t\/\/ return context\n\tm_scriptEngine->ReturnContext(context);\n\n\treturn true;\n}\nFixed a bug when upon releasing a script object, it would fail to get deleted because of an external reference to another object.\/*\nCopyright(c) 2016-2017 Panos Karabelas\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 furnished\nto do so, subject to the following conditions :\n\nThe above copyright notice and this permission notice shall be included in\nall copies 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, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n\/\/= INCLUDES ==================\n#include \"ScriptInstance.h\"\n#include \n#include \"Module.h\"\n#include \"..\/Core\/Helper.h\"\n#include \"..\/FileSystem\/FileSystem.h\"\n#include \"..\/Logging\/Log.h\"\n#include \"..\/Core\/GameObject.h\"\n\/\/=============================\n\n\/\/= NAMESPACES =====\nusing namespace std;\n\/\/==================\n\nScriptInstance::ScriptInstance()\n{\n\tm_gameObject = nullptr;\n\tm_constructorFunction = nullptr;\n\tm_startFunction = nullptr;\n\tm_updateFunction = nullptr;\n\tm_scriptObject = nullptr;\n\tm_module = nullptr;\n\tm_scriptEngine = nullptr;\n\tm_isInstantiated = false;\n}\n\nScriptInstance::~ScriptInstance()\n{\n\t\/\/ For some weird reason, it only\n\t\/\/ get's released when called twice...\n\tm_scriptObject->Release();\n\tm_scriptObject->Release();\n\n\tm_gameObject = nullptr;\n\tm_constructorFunction = nullptr;\n\tm_startFunction = nullptr;\n\tm_updateFunction = nullptr;\n\tm_scriptEngine = nullptr;\n\tm_isInstantiated = false;\n}\n\nbool ScriptInstance::Instantiate(const string& path, GameObject* gameObject, ScriptEngine* scriptEngine)\n{\n\tm_scriptEngine = scriptEngine;\n\n\t\/\/ Extract properties from path\n\tm_scriptPath = path;\n\tm_gameObject = gameObject;\n\tm_className = FileSystem::GetFileNameNoExtensionFromPath(m_scriptPath);\n\tm_moduleName = m_className + m_gameObject->GetID();\n\tm_constructorDeclaration = m_className + \" @\" + m_className + \"(GameObject @)\";\n\n\t\/\/ Instantiate the script\n\tm_isInstantiated = CreateScriptObject();\n\n\treturn m_isInstantiated;\n}\n\nbool ScriptInstance::IsInstantiated()\n{\n\treturn m_isInstantiated;\n}\n\nstring ScriptInstance::GetScriptPath()\n{\n\treturn m_scriptPath;\n}\n\nvoid ScriptInstance::ExecuteStart()\n{\n\tm_scriptEngine->ExecuteCall(m_startFunction, m_scriptObject);\n}\n\nvoid ScriptInstance::ExecuteUpdate()\n{\n\tm_scriptEngine->ExecuteCall(m_updateFunction, m_scriptObject);\n}\n\nbool ScriptInstance::CreateScriptObject()\n{\n\t\/\/ Create module\n\tm_module = make_shared(m_moduleName, m_scriptEngine);\n\tbool result = m_module->LoadScript(m_scriptPath);\n\tif (!result) \n\t\treturn false;\n\n\t\/\/ Get type\n\tauto type_id = m_module->GetAsIScriptModule()->GetTypeIdByDecl(m_className.c_str());\n\tasITypeInfo* type = m_scriptEngine->GetAsIScriptEngine()->GetTypeInfoById(type_id);\n\tif (!type) \n\t\treturn false;\n\n\t\/\/ Get functions in the script\n\tm_startFunction = type->GetMethodByDecl(\"void Start()\"); \/\/ Get the Start function from the script\n\tm_updateFunction = type->GetMethodByDecl(\"void Update()\"); \/\/ Get the Update function from the script\n\tm_constructorFunction = type->GetFactoryByDecl(m_constructorDeclaration.c_str()); \/\/ Get the constructor function from the script\n\tif (!m_constructorFunction)\n\t{\n\t\tLOG_ERROR(\"Couldn't find the appropriate factory for the type '\" + m_className + \"'\");\n\t\treturn false;\n\t}\n\n\tasIScriptContext* context = m_scriptEngine->RequestContext(); \/\/ request a context\n\tint r = context->Prepare(m_constructorFunction); \/\/ prepare the context to call the factory function\n\tif (r < 0) return false;\n\n\tr = context->SetArgObject(0, m_gameObject); \/\/ Pass the gameobject as the constructor's parameter\n\tif (r < 0) return false;\n\n\tr = context->Execute(); \/\/ execute the call\n\tif (r < 0) return false;\n\t\n\t\/\/ get the object that was created\n\tm_scriptObject = *static_cast(context->GetAddressOfReturnValue());\n\n\t\/\/ if you're going to store the object you must increase the reference,\n\t\/\/ otherwise it will be destroyed when the context is reused or destroyed.\n\tm_scriptObject->AddRef();\n\t\n\t\/\/ return context\n\tm_scriptEngine->ReturnContext(context);\n\n\treturn true;\n}\n<|endoftext|>"} {"text":"\/\/ RUN: rm -rf %t\n\/\/ RUN: mkdir %t\n\/\/ RUN: echo 'extern int a; template int a2 = T::error;' > %t\/a.h\n\/\/ RUN: echo 'extern int b;' > %t\/b.h\n\/\/ RUN: echo 'extern int c = 0;' > %t\/c.h\n\/\/ RUN: echo 'module a { header \"a.h\" header \"b.h\" header \"c.h\" }' > %t\/modulemap\n\/\/ RUN: echo 'module other {}' > %t\/other.modulemap\n\n\/\/ We lazily check that the files referenced by an explicitly-specified .pcm\n\/\/ file exist. Test this by removing files and ensuring that the compilation\n\/\/ still succeeds.\n\/\/\n\/\/ RUN: %clang_cc1 -fmodules -I %t -emit-module -fmodule-name=a -x c++ %t\/modulemap -o %t\/a.pcm \\\n\/\/ RUN: -fmodule-map-file=%t\/other.modulemap \\\n\/\/ RUN: -fmodules-embed-file=%t\/modulemap -fmodules-embed-file=%t\/other.modulemap\n\/\/ RUN: %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s\n\/\/ RUN: not %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s -DERRORS 2>&1 | FileCheck %s\n\/\/ RUN: rm %t\/modulemap\n\/\/ RUN: %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s\n\/\/ RUN: not %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s -DERRORS 2>&1 | FileCheck %s\n\/\/ RUN: rm %t\/other.modulemap\n\/\/ RUN: %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s\n\/\/ RUN: not %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s -DERRORS 2>&1 | FileCheck %s\n\/\/ RUN: rm %t\/b.h\n\/\/ RUN: %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s\n\/\/ RUN: not %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s -DERRORS 2>&1 | FileCheck %s --check-prefix=MISSING-B\n\/\/ RUN: rm %t\/a.h\n\/\/ RUN: %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s -verify\n\n#include \"a.h\" \/\/ expected-error {{file not found}}\nint x = b;\n\n#ifdef ERRORS\nint y = a2;\n\/\/ CHECK: In module 'a':\n\/\/ CHECK-NEXT: a.h:1:45: error:\n\n\/\/ MISSING-B: could not find file '{{.*}}b.h'\n\/\/ MISSING-B-NOT: please delete the module cache\n#endif\n\n\/\/ RUN: not %clang_cc1 -fmodules -I %t -emit-module -fmodule-name=a -x c++ \/dev\/null -o %t\/a.pcm \\\n\/\/ RUN: -fmodules-embed-file=%t\/does-not-exist 2>&1 | FileCheck %s --check-prefix=MISSING-EMBED\n\/\/ MISSING-EMBED: fatal error: file '{{.*}}does-not-exist' specified by '-fmodules-embed-file=' not found\nDon't run explicit-modules-missing-files.cpp on Windows\/\/ RUN: rm -rf %t\n\/\/ RUN: mkdir %t\n\/\/ RUN: echo 'extern int a; template int a2 = T::error;' > %t\/a.h\n\/\/ RUN: echo 'extern int b;' > %t\/b.h\n\/\/ RUN: echo 'extern int c = 0;' > %t\/c.h\n\/\/ RUN: echo 'module a { header \"a.h\" header \"b.h\" header \"c.h\" }' > %t\/modulemap\n\/\/ RUN: echo 'module other {}' > %t\/other.modulemap\n\n\/\/ We lazily check that the files referenced by an explicitly-specified .pcm\n\/\/ file exist. Test this by removing files and ensuring that the compilation\n\/\/ still succeeds.\n\/\/\n\/\/ RUN: %clang_cc1 -fmodules -I %t -emit-module -fmodule-name=a -x c++ %t\/modulemap -o %t\/a.pcm \\\n\/\/ RUN: -fmodule-map-file=%t\/other.modulemap \\\n\/\/ RUN: -fmodules-embed-file=%t\/modulemap -fmodules-embed-file=%t\/other.modulemap\n\/\/ RUN: %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s\n\/\/ RUN: not %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s -DERRORS 2>&1 | FileCheck %s\n\/\/ RUN: rm %t\/modulemap\n\/\/ RUN: %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s\n\/\/ RUN: not %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s -DERRORS 2>&1 | FileCheck %s\n\/\/ RUN: rm %t\/other.modulemap\n\/\/ RUN: %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s\n\/\/ RUN: not %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s -DERRORS 2>&1 | FileCheck %s\n\/\/ RUN: rm %t\/b.h\n\/\/ RUN: %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s\n\/\/ RUN: not %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s -DERRORS 2>&1 | FileCheck %s --check-prefix=MISSING-B\n\/\/ RUN: rm %t\/a.h\n\/\/ RUN: %clang_cc1 -fmodules -I %t -fmodule-file=%t\/a.pcm %s -verify\n\n\/\/ Oftentimes on Windows there are open handles, and deletion will fail.\n\/\/ REQUIRES: can-remove-opened-file\n\n#include \"a.h\" \/\/ expected-error {{file not found}}\nint x = b;\n\n#ifdef ERRORS\nint y = a2;\n\/\/ CHECK: In module 'a':\n\/\/ CHECK-NEXT: a.h:1:45: error:\n\n\/\/ MISSING-B: could not find file '{{.*}}b.h'\n\/\/ MISSING-B-NOT: please delete the module cache\n#endif\n\n\/\/ RUN: not %clang_cc1 -fmodules -I %t -emit-module -fmodule-name=a -x c++ \/dev\/null -o %t\/a.pcm \\\n\/\/ RUN: -fmodules-embed-file=%t\/does-not-exist 2>&1 | FileCheck %s --check-prefix=MISSING-EMBED\n\/\/ MISSING-EMBED: fatal error: file '{{.*}}does-not-exist' specified by '-fmodules-embed-file=' not found\n<|endoftext|>"} {"text":"\/** @file\n *\n * @ingroup spatdiflib\n *\n * @brief\n *\n * @details\n *\n * @authors Chikashi Miyama, Trond Lossius\n *\n * @copyright Copyright (C) 2013 - 2014 Zurich University of the Arts, Institute for Computer Music and Sound Technology @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 \n#include \n#include \n#include \n#include \n#include \"sdMain.h\"\n#include \"tinyxml2.h\"\n#include \"JSONNode.h\"\n#include \"sdSaver.h\"\n\nusing namespace tinyxml2;\n\nXMLDeclaration* sdXMLSaver::XMLDeclarationSection(XMLDocument &xml){\n XMLDeclaration* decl = xml.NewDeclaration();\n decl->SetValue(\"xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" standalone=\\\"yes\\\"\");\n return decl;\n}\n\nXMLElement* sdXMLSaver::XMLOrderingSection(XMLDocument &xml, const sdScene &scene){\n XMLElement* ordering = xml.NewElement(\"ordering\");\n XMLText* orderingText = xml.NewText(scene.getOrderingAsString().c_str());\n ordering->InsertEndChild(orderingText);\n return ordering;\n}\n\nXMLElement* sdXMLSaver::XMLMetaSection(XMLDocument &xml, const sdScene &scene){\n\n XMLElement* metaSection = xml.NewElement(\"meta\");\n\n \/\/ add info section to meta\n std::vector extensions = sdSpec::getDataSetEnabledExtensions();\n for(auto &extension : extensions){\n std::unordered_set identifiers = scene.getIdentifiers(extension);\n if(identifiers.empty()) continue;\n for(auto &identifier : identifiers){\n std::shared_ptr protoDataSet = scene.getProtoDataSet(extension, identifier);\n std::unordered_set keys = protoDataSet->getKeys();\n XMLElement * extensionElement = xml.NewElement(sdSpec::extensionToString(extension).c_str());\n \n for(auto &key : keys){\n std::string descriptorString = sdSpec::descriptorToString(key);\n std::string value = protoDataSet->getValueAsString(key);\n XMLElement * datasetElement = xml.NewElement(descriptorString.c_str());\n if(!datasetElement) continue;\n XMLText * text = xml.NewText(value.c_str());\n if(!text) continue;\n\n datasetElement->InsertEndChild(text);\n extensionElement->InsertEndChild(datasetElement);\n }\n metaSection->InsertEndChild(extensionElement);\n }\n }\n \n \/\/ add extensions to meta\n size_t num = scene.getNumberOfActivatedExtensions();\n if(num > 0){\n XMLElement* extensions = xml.NewElement(\"extensions\");\n std::string extString;\n auto extensionNames = scene.getActivatedExtensionsAsStrings();\n std::for_each(extensionNames.begin(), extensionNames.end(),[&extString](std::string ext){\n EExtension extension = sdSpec::stringToExtension(ext);\n if(!sdSpec::isCoreSpec(extension)){\n extString = ext;\n extString += \" \";\n }\n });\n extString.erase(extString.size()-1, extString.size()-1);\n XMLText* extensionsText = xml.NewText(extString.c_str());\n extensions->InsertEndChild(extensionsText);\n metaSection->InsertEndChild(extensions);\n }\n \n \/\/ add other meta infomation such as constant position or sound file definition\n auto allMetas = scene.getAllMetas();\n \n std::for_each(allMetas.begin(), allMetas.end(), [&](std::pair> metaPair ) {\n auto entity = metaPair.first;\n auto meta = metaPair.second;\n std::string previousName;\n std::string previousExtension;\n sdProtoEntity * previousEntity = nullptr;\n XMLElement* kind;\n XMLElement* extension;\n\n \/\/event\n \/\/kind = xml.NewElement(entity->getKindAsString().c_str());\n kind = xml.NewElement(std::string(\"source\").c_str());\n\n \/\/ the name of entity always comes first\n XMLElement* name = xml.NewElement(\"name\"); \/\/ entity name\n auto entityName = scene.getEntityName(entity);\n XMLText* nameText = xml.NewText(entityName.c_str());\n name->InsertEndChild(nameText);\n kind->InsertEndChild(name);\n \n \/\/ packaging - combining element and text (value)\n XMLElement* element = xml.NewElement(meta->getDescriptorAsString().c_str());\n XMLText* text = xml.NewText(meta->getValueAsString().c_str());\n element->InsertEndChild(text);\n \n std::string relevantExtension = sdSpec::extensionToString(sdSpec::getExtensionOfDescriptor(meta->getDescriptor()));\n \n if(relevantExtension == \"core\"){\n kind->InsertEndChild(element);\n metaSection->InsertEndChild(kind);\n }else{\n \n if( (entity != previousEntity ) || (previousExtension != relevantExtension)){\n \/\/ if different entity, time, or extension from the previous put extension tag\n extension = xml.NewElement((relevantExtension).c_str());\n }\n extension->InsertEndChild(element);\n kind->InsertEndChild(extension);\n metaSection->InsertEndChild(kind);\n }\n \n previousEntity = entity; \/\/ store current name in order to avoid the dupplication.\n previousExtension = relevantExtension;\n });\n\n \/\/ add ordering\n metaSection->InsertEndChild(XMLOrderingSection(xml, scene));\n\n return metaSection;\n}\n\nstd::string sdXMLSaver::toString(const sdScene &scene){\n \n XMLDocument xml;\n xml.InsertEndChild(XMLDeclarationSection(xml));\n \n XMLElement* spatdif = xml.NewElement(\"spatdif\");\n spatdif->SetAttribute(\"version\", \"0.4\");\n xml.InsertEndChild(spatdif);\n \n spatdif->InsertEndChild(sdXMLSaver::XMLMetaSection(xml, scene));\n\n std::unordered_map entities = scene.getEntities();\n \n \/\/ TIME Section\n \/* ordered by time *\/\n if(scene.getOrdering() == EOrdering::SD_TIME){\n auto eventTime = scene.getNextEventTime(-1.0);\n while(eventTime.second){\n \n \/\/ add