text
stringlengths
54
60.6k
<commit_before>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com> // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #include "Texture.h" #include <nvmath/Vector.h> #include <nvmath/Matrix.h> #include <nvimage/Filter.h> using namespace nv; using namespace nvtt; namespace { // 1 -> 1, 2 -> 2, 3 -> 2, 4 -> 4, 5 -> 4, ... static uint previousPowerOfTwo(const uint v) { return nextPowerOfTwo(v + 1) / 2; } static uint nearestPowerOfTwo(const uint v) { const uint np2 = nextPowerOfTwo(v); const uint pp2 = previousPowerOfTwo(v); if (np2 - v <= v - pp2) { return np2; } else { return pp2; } } } Texture::Texture() : m(new Texture::Private()) { } Texture::Texture(const Texture & tex) : m(tex.m) { m->addRef(); } Texture::~Texture() { m->release(); m = NULL; } void Texture::operator=(const Texture & tex) { tex.m->addRef(); m = tex.m; m->release(); } void Texture::detach() { if (m->refCount() > 1) { m = new Texture::Private(*m); m->addRef(); nvDebugCheck(m->refCount() == 1); } } void Texture::setType(TextureType type) { if (m->type != type) { detach(); m->type = type; } } void Texture::setWrapMode(WrapMode wrapMode) { if (m->wrapMode != wrapMode) { detach(); m->wrapMode = wrapMode; } } void Texture::setAlphaMode(AlphaMode alphaMode) { if (m->alphaMode != alphaMode) { detach(); m->alphaMode = alphaMode; } } void Texture::setNormalMap(bool isNormalMap) { if (m->isNormalMap != isNormalMap) { detach(); m->isNormalMap = isNormalMap; } } bool Texture::load(const char * fileName) { // @@ Not implemented. return false; } void Texture::setTexture2D(InputFormat format, int w, int h, int idx, void * data) { // @@ Not implemented. } void Texture::resize(int w, int h, ResizeFilter filter) { if (m->imageArray.count() > 0) { if (w == m->imageArray[0].width() && h == m->imageArray[0].height()) return; } // @TODO: if cubemap, make sure w == h. detach(); foreach(i, m->imageArray) { FloatImage::WrapMode wrapMode = (FloatImage::WrapMode)m->wrapMode; if (m->alphaMode == AlphaMode_Transparency) { if (filter == ResizeFilter_Box) { BoxFilter filter; m->imageArray[i].resize(filter, w, h, wrapMode, 3); } else if (filter == ResizeFilter_Triangle) { TriangleFilter filter; m->imageArray[i].resize(filter, w, h, wrapMode, 3); } else if (filter == ResizeFilter_Kaiser) { //KaiserFilter filter(inputOptions.kaiserWidth); //filter.setParameters(inputOptions.kaiserAlpha, inputOptions.kaiserStretch); KaiserFilter filter(3); m->imageArray[i].resize(filter, w, h, wrapMode, 3); } else //if (filter == ResizeFilter_Mitchell) { nvDebugCheck(filter == ResizeFilter_Mitchell); MitchellFilter filter; m->imageArray[i].resize(filter, w, h, wrapMode, 3); } } else { if (filter == ResizeFilter_Box) { BoxFilter filter; m->imageArray[i].resize(filter, w, h, wrapMode); } else if (filter == ResizeFilter_Triangle) { TriangleFilter filter; m->imageArray[i].resize(filter, w, h, wrapMode); } else if (filter == ResizeFilter_Kaiser) { //KaiserFilter filter(inputOptions.kaiserWidth); //filter.setParameters(inputOptions.kaiserAlpha, inputOptions.kaiserStretch); KaiserFilter filter(3); m->imageArray[i].resize(filter, w, h, wrapMode); } else //if (filter == ResizeFilter_Mitchell) { nvDebugCheck(filter == ResizeFilter_Mitchell); MitchellFilter filter; m->imageArray[i].resize(filter, w, h, wrapMode); } } } } void Texture::resize(int maxExtent, RoundMode roundMode, ResizeFilter filter) { if (m->imageArray.count() > 0) { int w = m->imageArray[0].width(); int h = m->imageArray[0].height(); nvDebugCheck(w > 0); nvDebugCheck(h > 0); if (roundMode != RoundMode_None) { // rounded max extent should never be higher than original max extent. maxExtent = previousPowerOfTwo(maxExtent); } // Scale extents without changing aspect ratio. uint maxwh = max(w, h); if (maxExtent != 0 && maxwh > maxExtent) { w = max((w * maxExtent) / maxwh, 1U); h = max((h * maxExtent) / maxwh, 1U); } // Round to power of two. if (roundMode == RoundMode_ToNextPowerOfTwo) { w = nextPowerOfTwo(w); h = nextPowerOfTwo(h); } else if (roundMode == RoundMode_ToNearestPowerOfTwo) { w = nearestPowerOfTwo(w); h = nearestPowerOfTwo(h); } else if (roundMode == RoundMode_ToPreviousPowerOfTwo) { w = previousPowerOfTwo(w); h = previousPowerOfTwo(h); } resize(w, h, filter); } } bool Texture::buildNextMipmap(MipmapFilter filter) { detach(); foreach(i, m->imageArray) { FloatImage::WrapMode wrapMode = (FloatImage::WrapMode)m->wrapMode; if (m->alphaMode == AlphaMode_Transparency) { if (filter == MipmapFilter_Box) { BoxFilter filter; m->imageArray[i].downSample(filter, wrapMode, 3); } else if (filter == MipmapFilter_Triangle) { TriangleFilter filter; m->imageArray[i].downSample(filter, wrapMode, 3); } else if (filter == MipmapFilter_Kaiser) { nvDebugCheck(filter == MipmapFilter_Kaiser); //KaiserFilter filter(inputOptions.kaiserWidth); //filter.setParameters(inputOptions.kaiserAlpha, inputOptions.kaiserStretch); KaiserFilter filter(3); m->imageArray[i].downSample(filter, wrapMode, 3); } } else { if (filter == MipmapFilter_Box) { m->imageArray[i].fastDownSample(); } else if (filter == MipmapFilter_Triangle) { TriangleFilter filter; m->imageArray[i].downSample(filter, wrapMode); } else //if (filter == MipmapFilter_Kaiser) { nvDebugCheck(filter == MipmapFilter_Kaiser); //KaiserFilter filter(inputOptions.kaiserWidth); //filter.setParameters(inputOptions.kaiserAlpha, inputOptions.kaiserStretch); KaiserFilter filter(3); m->imageArray[i].downSample(filter, wrapMode); } } } } // Color transforms. void Texture::toLinear(float gamma) { if (equal(gamma, 1.0f)) return; detach(); foreach(i, m->imageArray) { m->imageArray[i].toLinear(0, 3, gamma); } } void Texture::toGamma(float gamma) { if (equal(gamma, 1.0f)) return; detach(); foreach(i, m->imageArray) { m->imageArray[i].toGamma(0, 3, gamma); } } void Texture::transform(const float w0[4], const float w1[4], const float w2[4], const float w3[4], const float offset[4]) { detach(); Matrix xform( Vector4(w0[0], w0[1], w0[2], w0[3]), Vector4(w1[0], w1[1], w1[2], w1[3]), Vector4(w2[0], w2[1], w2[2], w2[3]), Vector4(w3[0], w3[1], w3[2], w3[3])); Vector4 voffset(offset[0], offset[1], offset[2], offset[3]); foreach(i, m->imageArray) { m->imageArray[i].transform(0, xform, voffset); } } void Texture::swizzle(int r, int g, int b, int a) { if (r == 0 && g == 1 && b == 2 && a == 3) return; detach(); foreach(i, m->imageArray) { m->imageArray[i].swizzle(0, r, g, b, a); } } void Texture::scaleBias(int channel, float scale, float bias) { if (equal(scale, 1.0f) && equal(bias, 0.0f)) return; detach(); foreach(i, m->imageArray) { m->imageArray[i].scaleBias(channel, 1, scale, bias); } } void Texture::normalizeNormals() { detach(); foreach(i, m->imageArray) { m->imageArray[i].normalize(0); } } void Texture::blend(float r, float g, float b, float a) { detach(); foreach(i, m->imageArray) { // @@ Not implemented. } } void Texture::premultiplyAlpha() { detach(); // @@ Not implemented. } <commit_msg>Eliminate some warnings with MSVC.<commit_after>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com> // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #include "Texture.h" #include <nvmath/Vector.h> #include <nvmath/Matrix.h> #include <nvimage/Filter.h> using namespace nv; using namespace nvtt; namespace { // 1 -> 1, 2 -> 2, 3 -> 2, 4 -> 4, 5 -> 4, ... static uint previousPowerOfTwo(const uint v) { return nextPowerOfTwo(v + 1) / 2; } static uint nearestPowerOfTwo(const uint v) { const uint np2 = nextPowerOfTwo(v); const uint pp2 = previousPowerOfTwo(v); if (np2 - v <= v - pp2) { return np2; } else { return pp2; } } } Texture::Texture() : m(new Texture::Private()) { } Texture::Texture(const Texture & tex) : m(tex.m) { m->addRef(); } Texture::~Texture() { m->release(); m = NULL; } void Texture::operator=(const Texture & tex) { tex.m->addRef(); m = tex.m; m->release(); } void Texture::detach() { if (m->refCount() > 1) { m = new Texture::Private(*m); m->addRef(); nvDebugCheck(m->refCount() == 1); } } void Texture::setType(TextureType type) { if (m->type != type) { detach(); m->type = type; } } void Texture::setWrapMode(WrapMode wrapMode) { if (m->wrapMode != wrapMode) { detach(); m->wrapMode = wrapMode; } } void Texture::setAlphaMode(AlphaMode alphaMode) { if (m->alphaMode != alphaMode) { detach(); m->alphaMode = alphaMode; } } void Texture::setNormalMap(bool isNormalMap) { if (m->isNormalMap != isNormalMap) { detach(); m->isNormalMap = isNormalMap; } } bool Texture::load(const char * fileName) { // @@ Not implemented. return false; } void Texture::setTexture2D(InputFormat format, int w, int h, int idx, void * data) { // @@ Not implemented. } void Texture::resize(int w, int h, ResizeFilter filter) { if (m->imageArray.count() > 0) { if (w == m->imageArray[0].width() && h == m->imageArray[0].height()) return; } // @TODO: if cubemap, make sure w == h. detach(); foreach(i, m->imageArray) { FloatImage::WrapMode wrapMode = (FloatImage::WrapMode)m->wrapMode; if (m->alphaMode == AlphaMode_Transparency) { if (filter == ResizeFilter_Box) { BoxFilter filter; m->imageArray[i].resize(filter, w, h, wrapMode, 3); } else if (filter == ResizeFilter_Triangle) { TriangleFilter filter; m->imageArray[i].resize(filter, w, h, wrapMode, 3); } else if (filter == ResizeFilter_Kaiser) { //KaiserFilter filter(inputOptions.kaiserWidth); //filter.setParameters(inputOptions.kaiserAlpha, inputOptions.kaiserStretch); KaiserFilter filter(3); m->imageArray[i].resize(filter, w, h, wrapMode, 3); } else //if (filter == ResizeFilter_Mitchell) { nvDebugCheck(filter == ResizeFilter_Mitchell); MitchellFilter filter; m->imageArray[i].resize(filter, w, h, wrapMode, 3); } } else { if (filter == ResizeFilter_Box) { BoxFilter filter; m->imageArray[i].resize(filter, w, h, wrapMode); } else if (filter == ResizeFilter_Triangle) { TriangleFilter filter; m->imageArray[i].resize(filter, w, h, wrapMode); } else if (filter == ResizeFilter_Kaiser) { //KaiserFilter filter(inputOptions.kaiserWidth); //filter.setParameters(inputOptions.kaiserAlpha, inputOptions.kaiserStretch); KaiserFilter filter(3); m->imageArray[i].resize(filter, w, h, wrapMode); } else //if (filter == ResizeFilter_Mitchell) { nvDebugCheck(filter == ResizeFilter_Mitchell); MitchellFilter filter; m->imageArray[i].resize(filter, w, h, wrapMode); } } } } void Texture::resize(int maxExtent, RoundMode roundMode, ResizeFilter filter) { if (m->imageArray.count() > 0) { int w = m->imageArray[0].width(); int h = m->imageArray[0].height(); nvDebugCheck(w > 0); nvDebugCheck(h > 0); if (roundMode != RoundMode_None) { // rounded max extent should never be higher than original max extent. maxExtent = previousPowerOfTwo(maxExtent); } // Scale extents without changing aspect ratio. int maxwh = max(w, h); if (maxExtent != 0 && maxwh > maxExtent) { w = max((w * maxExtent) / maxwh, 1); h = max((h * maxExtent) / maxwh, 1); } // Round to power of two. if (roundMode == RoundMode_ToNextPowerOfTwo) { w = nextPowerOfTwo(w); h = nextPowerOfTwo(h); } else if (roundMode == RoundMode_ToNearestPowerOfTwo) { w = nearestPowerOfTwo(w); h = nearestPowerOfTwo(h); } else if (roundMode == RoundMode_ToPreviousPowerOfTwo) { w = previousPowerOfTwo(w); h = previousPowerOfTwo(h); } resize(w, h, filter); } } bool Texture::buildNextMipmap(MipmapFilter filter) { if (m->imageArray.count() > 0) { int w = m->imageArray[0].width(); int h = m->imageArray[0].height(); nvDebugCheck(w > 0); nvDebugCheck(h > 0); if (w == 1 && h == 1) { return false; } } detach(); foreach(i, m->imageArray) { FloatImage::WrapMode wrapMode = (FloatImage::WrapMode)m->wrapMode; if (m->alphaMode == AlphaMode_Transparency) { if (filter == MipmapFilter_Box) { BoxFilter filter; m->imageArray[i].downSample(filter, wrapMode, 3); } else if (filter == MipmapFilter_Triangle) { TriangleFilter filter; m->imageArray[i].downSample(filter, wrapMode, 3); } else if (filter == MipmapFilter_Kaiser) { nvDebugCheck(filter == MipmapFilter_Kaiser); //KaiserFilter filter(inputOptions.kaiserWidth); //filter.setParameters(inputOptions.kaiserAlpha, inputOptions.kaiserStretch); KaiserFilter filter(3); m->imageArray[i].downSample(filter, wrapMode, 3); } } else { if (filter == MipmapFilter_Box) { m->imageArray[i].fastDownSample(); } else if (filter == MipmapFilter_Triangle) { TriangleFilter filter; m->imageArray[i].downSample(filter, wrapMode); } else //if (filter == MipmapFilter_Kaiser) { nvDebugCheck(filter == MipmapFilter_Kaiser); //KaiserFilter filter(inputOptions.kaiserWidth); //filter.setParameters(inputOptions.kaiserAlpha, inputOptions.kaiserStretch); KaiserFilter filter(3); m->imageArray[i].downSample(filter, wrapMode); } } } return true; } // Color transforms. void Texture::toLinear(float gamma) { if (equal(gamma, 1.0f)) return; detach(); foreach(i, m->imageArray) { m->imageArray[i].toLinear(0, 3, gamma); } } void Texture::toGamma(float gamma) { if (equal(gamma, 1.0f)) return; detach(); foreach(i, m->imageArray) { m->imageArray[i].toGamma(0, 3, gamma); } } void Texture::transform(const float w0[4], const float w1[4], const float w2[4], const float w3[4], const float offset[4]) { detach(); Matrix xform( Vector4(w0[0], w0[1], w0[2], w0[3]), Vector4(w1[0], w1[1], w1[2], w1[3]), Vector4(w2[0], w2[1], w2[2], w2[3]), Vector4(w3[0], w3[1], w3[2], w3[3])); Vector4 voffset(offset[0], offset[1], offset[2], offset[3]); foreach(i, m->imageArray) { m->imageArray[i].transform(0, xform, voffset); } } void Texture::swizzle(int r, int g, int b, int a) { if (r == 0 && g == 1 && b == 2 && a == 3) return; detach(); foreach(i, m->imageArray) { m->imageArray[i].swizzle(0, r, g, b, a); } } void Texture::scaleBias(int channel, float scale, float bias) { if (equal(scale, 1.0f) && equal(bias, 0.0f)) return; detach(); foreach(i, m->imageArray) { m->imageArray[i].scaleBias(channel, 1, scale, bias); } } void Texture::normalizeNormals() { detach(); foreach(i, m->imageArray) { m->imageArray[i].normalize(0); } } void Texture::blend(float r, float g, float b, float a) { detach(); foreach(i, m->imageArray) { // @@ Not implemented. } } void Texture::premultiplyAlpha() { detach(); // @@ Not implemented. } <|endoftext|>
<commit_before>/* Copyright (c) 2013 Daniele Bartolini, Michele Rossi Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Mutex.h" #include "Assert.h" namespace crown { namespace os { //----------------------------------------------------------------------------- Mutex::Mutex() { bool init = InitializeCriticalSectionAndSpinCount(&m_cs, 0x00000400); CE_ASSERT(init, "Unable to create mutex"); } //----------------------------------------------------------------------------- Mutex::~Mutex() { DeleteCriticalSection(&m_cs); } //----------------------------------------------------------------------------- void Mutex::lock() { EnterCriticalSection(&m_cs); } //----------------------------------------------------------------------------- void Mutex::unlock() { LeaveCriticalSection(&m_cs); } //----------------------------------------------------------------------------- CRITICAL_SECTION Mutex::handle() { return m_cs; } } // namespace os } // namespace crown <commit_msg>Spin count not necessary<commit_after>/* Copyright (c) 2013 Daniele Bartolini, Michele Rossi Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Mutex.h" #include "Assert.h" namespace crown { namespace os { //----------------------------------------------------------------------------- Mutex::Mutex() { InitializeCriticalSection(&m_cs); } //----------------------------------------------------------------------------- Mutex::~Mutex() { DeleteCriticalSection(&m_cs); } //----------------------------------------------------------------------------- void Mutex::lock() { EnterCriticalSection(&m_cs); } //----------------------------------------------------------------------------- void Mutex::unlock() { LeaveCriticalSection(&m_cs); } //----------------------------------------------------------------------------- CRITICAL_SECTION Mutex::handle() { return m_cs; } } // namespace os } // namespace crown <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file rdorss.cpp \authors Барс Александр \authors Урусов Андрей (rdo@rk9.bmstu.ru) \authors Романов Ярослав (robot.xet@gmail.com) \date \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "simulator/compiler/parser/pch.h" // ----------------------------------------------------------------------- INCLUDES #include <boost/bind.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/compiler/parser/rdorss.h" #include "simulator/compiler/parser/rdortp.h" #include "simulator/compiler/parser/rdoparser.h" #include "simulator/compiler/parser/rdoparser_lexer.h" #include "simulator/runtime/calc/resource/calc_resource.h" #include "simulator/runtime/calc/resource/calc_create_resource.h" // -------------------------------------------------------------------------------- OPEN_RDO_PARSER_NAMESPACE // -------------------------------------------------------------------------------- // -------------------- RDORSSResource // -------------------------------------------------------------------------------- const std::string RDORSSResource::GET_RESOURCE = "resource_expression"; RDORSSResource::RDORSSResource(CREF(LPRDOParser) pParser, CREF(RDOParserSrcInfo) src_info, CREF(LPRDORTPResType) pResType, std::size_t id) : RDOParserSrcInfo(src_info ) , m_pResType (pResType ) , m_id (id == UNDEFINED_ID ? pParser->getRSS_id() : id) , trace (false ) , isNested (false ) { ASSERT(m_pResType); pParser->insertRSSResource(LPRDORSSResource(this)); m_currParam = m_pResType->getParams().begin(); RDOParser::s_parser()->contextStack()->push(this); } RDORSSResource::~RDORSSResource() {} void RDORSSResource::end() { RDOParser::s_parser()->contextStack()->pop<RDORSSResource>(); } namespace { LPExpression contextSetTrace(const rdo::runtime::LPRDOCalc& getResource, bool traceValue, const RDOParserSrcInfo& srcInfo) { return rdo::Factory<Expression>::create( rdo::Factory<TypeInfo>::delegate<RDOType__void>(srcInfo), rdo::Factory<rdo::runtime::RDOCalcSetResourceTrace>::create(getResource, traceValue), srcInfo ); } } Context::FindResult RDORSSResource::onFindContext(const std::string& method, const Context::Params& params, const RDOParserSrcInfo& srcInfo) const { if (method == Context::METHOD_GET) { const std::string paramName = params.identifier(); const std::size_t parNumb = getType()->getRTPParamNumber(paramName); if (parNumb == RDORTPResType::UNDEFINED_PARAM) { RDOParser::s_parser()->error().error(srcInfo, rdo::format("Неизвестный параметр ресурса: %s", paramName.c_str())); } Context::Params params_; params_[RDORSSResource::GET_RESOURCE] = createGetResourceExpression(srcInfo); params_[RDOParam::CONTEXT_PARAM_PARAM_ID] = parNumb; LPContext pParam = getType()->findRTPParam(paramName); ASSERT(pParam); return pParam->find(Context::METHOD_GET, params_, srcInfo); } if (method == "trace()") { rdo::runtime::LPRDOCalc getResource = rdo::Factory<rdo::runtime::RDOCalcGetResourceByID>::create(getID()); const bool traceValue = params.get<bool>("traceValue"); return FindResult(CreateExpression(boost::bind(&contextSetTrace, getResource, traceValue, srcInfo))); } return FindResult(); } LPExpression RDORSSResource::createGetResourceExpression(const RDOParserSrcInfo& srcInfo) const { return rdo::Factory<Expression>::create( rdo::Factory<TypeInfo>::create(getType(), getType()->src_info()), rdo::Factory<rdo::runtime::RDOCalcGetResourceByID>::create(getID()), srcInfo ); } void RDORSSResource::writeModelStructure(std::ostream& stream) const { stream << (getID() + 1) << " " << name() << " " << getType()->getNumber() << std::endl; } void RDORSSResource::addParam(CREF(LPRDOValue) pParam) { ASSERT(pParam); LPRDOValue pAddParamValue; LPExpression pAddParam; if (m_currParam == getType()->getParams().end()) { RDOParser::s_parser()->error().push_only(pParam->src_info(), "Слишком много параметров"); RDOParser::s_parser()->error().push_only(getType()->src_info(), "См. тип ресурса"); RDOParser::s_parser()->error().push_done(); } try { if (pParam->value().getAsString() == "*") { if (!(*m_currParam)->getDefault()->defined()) { RDOParser::s_parser()->error().push_only(pParam->src_info(), "Невозможно использовать '*', к.т. отсутствует значение по умолчанию"); /// @todo src_info() без параметра RDOParserSrcInfo() RDOParser::s_parser()->error().push_only((*m_currParam)->getTypeInfo()->src_info(RDOParserSrcInfo()), "См. описание параметра"); RDOParser::s_parser()->error().push_done(); } pAddParamValue = (*m_currParam)->getDefault(); } else if (pParam->value().getAsString() == "#") { pAddParamValue = (*m_currParam)->getDefault()->defined() ? (*m_currParam)->getDefault() : rdo::Factory<rdo::compiler::parser::RDOValue>::create( (*m_currParam)->getTypeInfo()->type()->get_default(), (*m_currParam)->getTypeInfo()->src_info(RDOParserSrcInfo()), (*m_currParam)->getTypeInfo() ); ASSERT(pAddParamValue); pAddParamValue->value().setUndefined(true); } else { pAddParamValue = (*m_currParam)->getTypeInfo()->value_cast(pParam); } } catch(const RDOSyntaxException&) { RDOParser::s_parser()->error().modify(rdo::format("Для параметра '%s': ", (*m_currParam)->name().c_str())); } ASSERT(pAddParamValue); try { if(pAddParamValue->value().type().object_dynamic_cast<rdo::runtime::RDOResourceTypeList>()) { LPRDORSSResource pResourceValue = pAddParamValue->value().getPointerByType<RDORTPResType>(); ASSERT(pResourceValue); std::vector<rdo::runtime::LPRDOCalc> paramList; for (const auto& param : pResourceValue->params()) paramList.push_back(param.param()->calc()); rdo::runtime::LPRDOCalc pCalc = rdo::Factory<rdo::runtime::RDOCalcCreateResource>::create( pResourceValue->getType()->getNumber(), paramList, pResourceValue->getTrace(), pResourceValue->getType()->isPermanent() ); pAddParam = rdo::Factory<Expression>::create( rdo::Factory<TypeInfo>::create(pAddParamValue->typeInfo()), pCalc, pAddParamValue->src_info() ); } else pAddParam = rdo::Factory<Expression>::create( rdo::Factory<TypeInfo>::create(pAddParamValue->typeInfo()), rdo::Factory<rdo::runtime::RDOCalcConst>::create(pAddParamValue->value().clone()), pAddParamValue->src_info() ); } catch (const rdo::runtime::RDOValueException& e) { RDOParser::s_parser()->error().error(pParam->src_info(), rdo::format("Для параметра '%s': %s", (*m_currParam)->name().c_str(), e.message().c_str())); } m_paramList.push_back(Param(pAddParam)); m_currParam++; } bool RDORSSResource::defined() const { return m_currParam == getType()->getParams().end(); } std::vector<rdo::runtime::LPRDOCalc> RDORSSResource::createCalc() const { std::vector<rdo::runtime::LPRDOCalc> calcList; std::vector<rdo::runtime::LPRDOCalc> paramList; for (const auto& param: params()) paramList.push_back(param.param()->calc()); rdo::runtime::LPRDOCalc pCalc = rdo::Factory<rdo::runtime::RDOCalcCreateResource>::create( getType()->getNumber(), paramList, getTrace(), getType()->isPermanent() ); ASSERT(pCalc); rdo::runtime::RDOSrcInfo srcInfo(src_info()); srcInfo.setSrcText("Создание ресурса " + src_text()); pCalc->setSrcInfo(srcInfo); calcList.push_back(pCalc); if (m_traceCalc) calcList.push_back(m_traceCalc); return calcList; } CLOSE_RDO_PARSER_NAMESPACE <commit_msg>пробел после if<commit_after>/*! \copyright (c) RDO-Team, 2011 \file rdorss.cpp \authors Барс Александр \authors Урусов Андрей (rdo@rk9.bmstu.ru) \authors Романов Ярослав (robot.xet@gmail.com) \date \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "simulator/compiler/parser/pch.h" // ----------------------------------------------------------------------- INCLUDES #include <boost/bind.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/compiler/parser/rdorss.h" #include "simulator/compiler/parser/rdortp.h" #include "simulator/compiler/parser/rdoparser.h" #include "simulator/compiler/parser/rdoparser_lexer.h" #include "simulator/runtime/calc/resource/calc_resource.h" #include "simulator/runtime/calc/resource/calc_create_resource.h" // -------------------------------------------------------------------------------- OPEN_RDO_PARSER_NAMESPACE // -------------------------------------------------------------------------------- // -------------------- RDORSSResource // -------------------------------------------------------------------------------- const std::string RDORSSResource::GET_RESOURCE = "resource_expression"; RDORSSResource::RDORSSResource(CREF(LPRDOParser) pParser, CREF(RDOParserSrcInfo) src_info, CREF(LPRDORTPResType) pResType, std::size_t id) : RDOParserSrcInfo(src_info ) , m_pResType (pResType ) , m_id (id == UNDEFINED_ID ? pParser->getRSS_id() : id) , trace (false ) , isNested (false ) { ASSERT(m_pResType); pParser->insertRSSResource(LPRDORSSResource(this)); m_currParam = m_pResType->getParams().begin(); RDOParser::s_parser()->contextStack()->push(this); } RDORSSResource::~RDORSSResource() {} void RDORSSResource::end() { RDOParser::s_parser()->contextStack()->pop<RDORSSResource>(); } namespace { LPExpression contextSetTrace(const rdo::runtime::LPRDOCalc& getResource, bool traceValue, const RDOParserSrcInfo& srcInfo) { return rdo::Factory<Expression>::create( rdo::Factory<TypeInfo>::delegate<RDOType__void>(srcInfo), rdo::Factory<rdo::runtime::RDOCalcSetResourceTrace>::create(getResource, traceValue), srcInfo ); } } Context::FindResult RDORSSResource::onFindContext(const std::string& method, const Context::Params& params, const RDOParserSrcInfo& srcInfo) const { if (method == Context::METHOD_GET) { const std::string paramName = params.identifier(); const std::size_t parNumb = getType()->getRTPParamNumber(paramName); if (parNumb == RDORTPResType::UNDEFINED_PARAM) { RDOParser::s_parser()->error().error(srcInfo, rdo::format("Неизвестный параметр ресурса: %s", paramName.c_str())); } Context::Params params_; params_[RDORSSResource::GET_RESOURCE] = createGetResourceExpression(srcInfo); params_[RDOParam::CONTEXT_PARAM_PARAM_ID] = parNumb; LPContext pParam = getType()->findRTPParam(paramName); ASSERT(pParam); return pParam->find(Context::METHOD_GET, params_, srcInfo); } if (method == "trace()") { rdo::runtime::LPRDOCalc getResource = rdo::Factory<rdo::runtime::RDOCalcGetResourceByID>::create(getID()); const bool traceValue = params.get<bool>("traceValue"); return FindResult(CreateExpression(boost::bind(&contextSetTrace, getResource, traceValue, srcInfo))); } return FindResult(); } LPExpression RDORSSResource::createGetResourceExpression(const RDOParserSrcInfo& srcInfo) const { return rdo::Factory<Expression>::create( rdo::Factory<TypeInfo>::create(getType(), getType()->src_info()), rdo::Factory<rdo::runtime::RDOCalcGetResourceByID>::create(getID()), srcInfo ); } void RDORSSResource::writeModelStructure(std::ostream& stream) const { stream << (getID() + 1) << " " << name() << " " << getType()->getNumber() << std::endl; } void RDORSSResource::addParam(CREF(LPRDOValue) pParam) { ASSERT(pParam); LPRDOValue pAddParamValue; LPExpression pAddParam; if (m_currParam == getType()->getParams().end()) { RDOParser::s_parser()->error().push_only(pParam->src_info(), "Слишком много параметров"); RDOParser::s_parser()->error().push_only(getType()->src_info(), "См. тип ресурса"); RDOParser::s_parser()->error().push_done(); } try { if (pParam->value().getAsString() == "*") { if (!(*m_currParam)->getDefault()->defined()) { RDOParser::s_parser()->error().push_only(pParam->src_info(), "Невозможно использовать '*', к.т. отсутствует значение по умолчанию"); /// @todo src_info() без параметра RDOParserSrcInfo() RDOParser::s_parser()->error().push_only((*m_currParam)->getTypeInfo()->src_info(RDOParserSrcInfo()), "См. описание параметра"); RDOParser::s_parser()->error().push_done(); } pAddParamValue = (*m_currParam)->getDefault(); } else if (pParam->value().getAsString() == "#") { pAddParamValue = (*m_currParam)->getDefault()->defined() ? (*m_currParam)->getDefault() : rdo::Factory<rdo::compiler::parser::RDOValue>::create( (*m_currParam)->getTypeInfo()->type()->get_default(), (*m_currParam)->getTypeInfo()->src_info(RDOParserSrcInfo()), (*m_currParam)->getTypeInfo() ); ASSERT(pAddParamValue); pAddParamValue->value().setUndefined(true); } else { pAddParamValue = (*m_currParam)->getTypeInfo()->value_cast(pParam); } } catch(const RDOSyntaxException&) { RDOParser::s_parser()->error().modify(rdo::format("Для параметра '%s': ", (*m_currParam)->name().c_str())); } ASSERT(pAddParamValue); try { if (pAddParamValue->value().type().object_dynamic_cast<rdo::runtime::RDOResourceTypeList>()) { LPRDORSSResource pResourceValue = pAddParamValue->value().getPointerByType<RDORTPResType>(); ASSERT(pResourceValue); std::vector<rdo::runtime::LPRDOCalc> paramList; for (const auto& param : pResourceValue->params()) paramList.push_back(param.param()->calc()); rdo::runtime::LPRDOCalc pCalc = rdo::Factory<rdo::runtime::RDOCalcCreateResource>::create( pResourceValue->getType()->getNumber(), paramList, pResourceValue->getTrace(), pResourceValue->getType()->isPermanent() ); pAddParam = rdo::Factory<Expression>::create( rdo::Factory<TypeInfo>::create(pAddParamValue->typeInfo()), pCalc, pAddParamValue->src_info() ); } else pAddParam = rdo::Factory<Expression>::create( rdo::Factory<TypeInfo>::create(pAddParamValue->typeInfo()), rdo::Factory<rdo::runtime::RDOCalcConst>::create(pAddParamValue->value().clone()), pAddParamValue->src_info() ); } catch (const rdo::runtime::RDOValueException& e) { RDOParser::s_parser()->error().error(pParam->src_info(), rdo::format("Для параметра '%s': %s", (*m_currParam)->name().c_str(), e.message().c_str())); } m_paramList.push_back(Param(pAddParam)); m_currParam++; } bool RDORSSResource::defined() const { return m_currParam == getType()->getParams().end(); } std::vector<rdo::runtime::LPRDOCalc> RDORSSResource::createCalc() const { std::vector<rdo::runtime::LPRDOCalc> calcList; std::vector<rdo::runtime::LPRDOCalc> paramList; for (const auto& param: params()) paramList.push_back(param.param()->calc()); rdo::runtime::LPRDOCalc pCalc = rdo::Factory<rdo::runtime::RDOCalcCreateResource>::create( getType()->getNumber(), paramList, getTrace(), getType()->isPermanent() ); ASSERT(pCalc); rdo::runtime::RDOSrcInfo srcInfo(src_info()); srcInfo.setSrcText("Создание ресурса " + src_text()); pCalc->setSrcInfo(srcInfo); calcList.push_back(pCalc); if (m_traceCalc) calcList.push_back(m_traceCalc); return calcList; } CLOSE_RDO_PARSER_NAMESPACE <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // This code glues the RLZ library DLL with Chrome. It allows Chrome to work // with or without the DLL being present. If the DLL is not present the // functions do nothing and just return false. #include "chrome/browser/rlz/rlz.h" #include <windows.h> #include <process.h> #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/task.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/profile_manager.h" #include "chrome/browser/search_engines/template_url_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/env_vars.h" #include "chrome/common/notification_service.h" #include "chrome/installer/util/google_update_settings.h" namespace { // The maximum length of an access points RLZ in wide chars. const DWORD kMaxRlzLength = 64; // The RLZ is a DLL that might not be present in the system. We load it // as needed but never unload it. volatile HMODULE rlz_dll = NULL; enum { ACCESS_VALUES_STALE, // Possibly new values available. ACCESS_VALUES_FRESH // The cached values are current. }; // Tracks if we have tried and succeeded sending the ping. This helps us // decide if we need to refresh the some cached strings. volatile int access_values_state = ACCESS_VALUES_STALE; extern "C" { typedef bool (*RecordProductEventFn)(RLZTracker::Product product, RLZTracker::AccessPoint point, RLZTracker::Event event_id, void* reserved); typedef bool (*GetAccessPointRlzFn)(RLZTracker::AccessPoint point, wchar_t* rlz, DWORD rlz_size, void* reserved); typedef bool (*ClearAllProductEventsFn)(RLZTracker::Product product, void* reserved); typedef bool (*SendFinancialPingFn)(RLZTracker::Product product, RLZTracker::AccessPoint* access_points, const WCHAR* product_signature, const WCHAR* product_brand, const WCHAR* product_id, const WCHAR* product_lang, bool exclude_id, void* reserved); } // extern "C". RecordProductEventFn record_event = NULL; GetAccessPointRlzFn get_access_point = NULL; ClearAllProductEventsFn clear_all_events = NULL; SendFinancialPingFn send_ping = NULL; template <typename FuncT> FuncT WireExport(HMODULE module, const char* export_name) { void* entry_point = ::GetProcAddress(module, export_name); return (module)? reinterpret_cast<FuncT>(entry_point) : NULL; } HMODULE LoadRLZLibraryInternal(int directory_key) { std::wstring rlz_path; if (!PathService::Get(directory_key, &rlz_path)) return NULL; file_util::AppendToPath(&rlz_path, L"rlz.dll"); return ::LoadLibraryW(rlz_path.c_str()); } bool LoadRLZLibrary(int directory_key) { rlz_dll = LoadRLZLibraryInternal(directory_key); if (!rlz_dll) { // As a last resort we can try the EXE directory. if (directory_key != base::DIR_EXE) rlz_dll = LoadRLZLibraryInternal(base::DIR_EXE); } if (rlz_dll) { record_event = WireExport<RecordProductEventFn>(rlz_dll, "RecordProductEvent"); get_access_point = WireExport<GetAccessPointRlzFn>(rlz_dll, "GetAccessPointRlz"); clear_all_events = WireExport<ClearAllProductEventsFn>(rlz_dll, "ClearAllProductEvents"); send_ping = WireExport<SendFinancialPingFn>(rlz_dll, "SendFinancialPing"); return (record_event && get_access_point && clear_all_events && send_ping); } return false; } bool SendFinancialPing(const wchar_t* brand, const wchar_t* lang, const wchar_t* referral, bool exclude_id) { RLZTracker::AccessPoint points[] = {RLZTracker::CHROME_OMNIBOX, RLZTracker::CHROME_HOME_PAGE, RLZTracker::NO_ACCESS_POINT}; if (!send_ping) return false; return send_ping(RLZTracker::CHROME, points, L"chrome", brand, referral, lang, exclude_id, NULL); } // This class leverages the AutocompleteEditModel notification to know when // the user first interacted with the omnibox and set a global accordingly. class OmniBoxUsageObserver : public NotificationObserver { public: OmniBoxUsageObserver() { NotificationService::current()->AddObserver(this, NOTIFY_OMNIBOX_OPENED_URL, NotificationService::AllSources()); omnibox_used_ = false; DCHECK(!instance_); instance_ = this; } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { // Try to record event now, else set the flag to try later when we // attempt the ping. if (!RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::FIRST_SEARCH)) omnibox_used_ = true; delete this; } static bool used() { return omnibox_used_; } // Deletes the single instance of OmniBoxUsageObserver. static void DeleteInstance() { delete instance_; } private: // Dtor is private so the object cannot be created on the stack. ~OmniBoxUsageObserver() { NotificationService::current()->RemoveObserver(this, NOTIFY_OMNIBOX_OPENED_URL, NotificationService::AllSources()); instance_ = NULL; } static bool omnibox_used_; // There should only be one instance created at a time, and instance_ points // to that instance. // NOTE: this is only non-null for the amount of time it is needed. Once the // instance_ is no longer needed (or Chrome is exitting), this is null. static OmniBoxUsageObserver* instance_; }; bool OmniBoxUsageObserver::omnibox_used_ = false; OmniBoxUsageObserver* OmniBoxUsageObserver::instance_ = NULL; // This task is run in the file thread, so to not block it for a long time // we use a throwaway thread to do the blocking url request. class DailyPingTask : public Task { public: virtual ~DailyPingTask() { } virtual void Run() { // We use a transient thread because we have no guarantees about // how long the RLZ lib can block us. _beginthread(PingNow, 0, NULL); } private: // Causes a ping to the server using WinInet. There is logic inside RLZ dll // that throttles it to a maximum of one ping per day. static void _cdecl PingNow(void*) { std::wstring lang; GoogleUpdateSettings::GetLanguage(&lang); if (lang.empty()) lang = L"en"; std::wstring brand; GoogleUpdateSettings::GetBrand(&brand); std::wstring referral; GoogleUpdateSettings::GetReferral(&referral); if (SendFinancialPing(brand.c_str(), lang.c_str(), referral.c_str(), is_organic(brand))) { access_values_state = ACCESS_VALUES_STALE; GoogleUpdateSettings::ClearReferral(); } } // Organic brands all start with GG, such as GGCM. static bool is_organic(const std::wstring brand) { return (brand.size() < 2) ? false : (brand.substr(0,2) == L"GG"); } }; // Performs late RLZ initialization and RLZ event recording for chrome. // This task needs to run on the UI thread. class DelayedInitTask : public Task { public: explicit DelayedInitTask(int directory_key, bool first_run) : directory_key_(directory_key), first_run_(first_run) { } virtual ~DelayedInitTask() { } virtual void Run() { // For non-interactive tests we don't do the rest of the initialization // because sometimes the very act of loading the dll causes QEMU to crash. if (::GetEnvironmentVariableW(env_vars::kHeadless, NULL, 0)) return; if (!LoadRLZLibrary(directory_key_)) return; // Do the initial event recording if is the first run or if we have an // empty rlz which means we haven't got a chance to do it. std::wstring omnibox_rlz; RLZTracker::GetAccessPointRlz(RLZTracker::CHROME_OMNIBOX, &omnibox_rlz); if (first_run_ || omnibox_rlz.empty()) { // Record the installation of chrome. RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::INSTALL); RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_HOME_PAGE, RLZTracker::INSTALL); // Record if google is the initial search provider. if (IsGoogleDefaultSearch()) { RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::SET_TO_GOOGLE); } // Record first user interaction with the omnibox. if (OmniBoxUsageObserver::used()) { RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::FIRST_SEARCH); } } // Schedule the daily RLZ ping. base::Thread* thread = g_browser_process->file_thread(); if (thread) thread->message_loop()->PostTask(FROM_HERE, new DailyPingTask()); } private: bool IsGoogleDefaultSearch() { if (!g_browser_process) return false; std::wstring user_data_dir; if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) return false; ProfileManager* profile_manager = g_browser_process->profile_manager(); Profile* profile = profile_manager-> GetDefaultProfile(FilePath::FromWStringHack(user_data_dir)); if (!profile) return false; const TemplateURL* url_template = profile->GetTemplateURLModel()->GetDefaultSearchProvider(); if (!url_template) return false; return url_template->url()->HasGoogleBaseURLs(); } int directory_key_; bool first_run_; DISALLOW_IMPLICIT_CONSTRUCTORS(DelayedInitTask); }; } // namespace bool RLZTracker::InitRlz(int directory_key) { return LoadRLZLibrary(directory_key); } bool RLZTracker::InitRlzDelayed(int directory_key, bool first_run) { if (!OmniBoxUsageObserver::used()) new OmniBoxUsageObserver(); // Schedule the delayed init items. const int kTwentySeconds = 20 * 1000; MessageLoop::current()->PostDelayedTask(FROM_HERE, new DelayedInitTask(directory_key, first_run), kTwentySeconds); return true; } bool RLZTracker::RecordProductEvent(Product product, AccessPoint point, Event event) { return (record_event) ? record_event(product, point, event, NULL) : false; } bool RLZTracker::ClearAllProductEvents(Product product) { return (clear_all_events) ? clear_all_events(product, NULL) : false; } // We implement caching of the answer of get_access_point() if the request // is for CHROME_OMNIBOX. If we had a successful ping, then we update the // cached value. bool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) { static std::wstring cached_ommibox_rlz; if (!get_access_point) return false; if ((CHROME_OMNIBOX == point) && (access_values_state == ACCESS_VALUES_FRESH)) { *rlz = cached_ommibox_rlz; return true; } wchar_t str_rlz[kMaxRlzLength]; if (!get_access_point(point, str_rlz, kMaxRlzLength, NULL)) return false; if (CHROME_OMNIBOX == point) { access_values_state = ACCESS_VALUES_FRESH; cached_ommibox_rlz.assign(str_rlz); } *rlz = str_rlz; return true; } // static void RLZTracker::CleanupRlz() { OmniBoxUsageObserver::DeleteInstance(); } <commit_msg>Move RLZ back to 90 seconds delayed init<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // This code glues the RLZ library DLL with Chrome. It allows Chrome to work // with or without the DLL being present. If the DLL is not present the // functions do nothing and just return false. #include "chrome/browser/rlz/rlz.h" #include <windows.h> #include <process.h> #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/task.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/profile_manager.h" #include "chrome/browser/search_engines/template_url_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/env_vars.h" #include "chrome/common/notification_service.h" #include "chrome/installer/util/google_update_settings.h" namespace { // The maximum length of an access points RLZ in wide chars. const DWORD kMaxRlzLength = 64; // The RLZ is a DLL that might not be present in the system. We load it // as needed but never unload it. volatile HMODULE rlz_dll = NULL; enum { ACCESS_VALUES_STALE, // Possibly new values available. ACCESS_VALUES_FRESH // The cached values are current. }; // Tracks if we have tried and succeeded sending the ping. This helps us // decide if we need to refresh the some cached strings. volatile int access_values_state = ACCESS_VALUES_STALE; extern "C" { typedef bool (*RecordProductEventFn)(RLZTracker::Product product, RLZTracker::AccessPoint point, RLZTracker::Event event_id, void* reserved); typedef bool (*GetAccessPointRlzFn)(RLZTracker::AccessPoint point, wchar_t* rlz, DWORD rlz_size, void* reserved); typedef bool (*ClearAllProductEventsFn)(RLZTracker::Product product, void* reserved); typedef bool (*SendFinancialPingFn)(RLZTracker::Product product, RLZTracker::AccessPoint* access_points, const WCHAR* product_signature, const WCHAR* product_brand, const WCHAR* product_id, const WCHAR* product_lang, bool exclude_id, void* reserved); } // extern "C". RecordProductEventFn record_event = NULL; GetAccessPointRlzFn get_access_point = NULL; ClearAllProductEventsFn clear_all_events = NULL; SendFinancialPingFn send_ping = NULL; template <typename FuncT> FuncT WireExport(HMODULE module, const char* export_name) { void* entry_point = ::GetProcAddress(module, export_name); return (module)? reinterpret_cast<FuncT>(entry_point) : NULL; } HMODULE LoadRLZLibraryInternal(int directory_key) { std::wstring rlz_path; if (!PathService::Get(directory_key, &rlz_path)) return NULL; file_util::AppendToPath(&rlz_path, L"rlz.dll"); return ::LoadLibraryW(rlz_path.c_str()); } bool LoadRLZLibrary(int directory_key) { rlz_dll = LoadRLZLibraryInternal(directory_key); if (!rlz_dll) { // As a last resort we can try the EXE directory. if (directory_key != base::DIR_EXE) rlz_dll = LoadRLZLibraryInternal(base::DIR_EXE); } if (rlz_dll) { record_event = WireExport<RecordProductEventFn>(rlz_dll, "RecordProductEvent"); get_access_point = WireExport<GetAccessPointRlzFn>(rlz_dll, "GetAccessPointRlz"); clear_all_events = WireExport<ClearAllProductEventsFn>(rlz_dll, "ClearAllProductEvents"); send_ping = WireExport<SendFinancialPingFn>(rlz_dll, "SendFinancialPing"); return (record_event && get_access_point && clear_all_events && send_ping); } return false; } bool SendFinancialPing(const wchar_t* brand, const wchar_t* lang, const wchar_t* referral, bool exclude_id) { RLZTracker::AccessPoint points[] = {RLZTracker::CHROME_OMNIBOX, RLZTracker::CHROME_HOME_PAGE, RLZTracker::NO_ACCESS_POINT}; if (!send_ping) return false; return send_ping(RLZTracker::CHROME, points, L"chrome", brand, referral, lang, exclude_id, NULL); } // This class leverages the AutocompleteEditModel notification to know when // the user first interacted with the omnibox and set a global accordingly. class OmniBoxUsageObserver : public NotificationObserver { public: OmniBoxUsageObserver() { NotificationService::current()->AddObserver(this, NOTIFY_OMNIBOX_OPENED_URL, NotificationService::AllSources()); omnibox_used_ = false; DCHECK(!instance_); instance_ = this; } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { // Try to record event now, else set the flag to try later when we // attempt the ping. if (!RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::FIRST_SEARCH)) omnibox_used_ = true; delete this; } static bool used() { return omnibox_used_; } // Deletes the single instance of OmniBoxUsageObserver. static void DeleteInstance() { delete instance_; } private: // Dtor is private so the object cannot be created on the stack. ~OmniBoxUsageObserver() { NotificationService::current()->RemoveObserver(this, NOTIFY_OMNIBOX_OPENED_URL, NotificationService::AllSources()); instance_ = NULL; } static bool omnibox_used_; // There should only be one instance created at a time, and instance_ points // to that instance. // NOTE: this is only non-null for the amount of time it is needed. Once the // instance_ is no longer needed (or Chrome is exitting), this is null. static OmniBoxUsageObserver* instance_; }; bool OmniBoxUsageObserver::omnibox_used_ = false; OmniBoxUsageObserver* OmniBoxUsageObserver::instance_ = NULL; // This task is run in the file thread, so to not block it for a long time // we use a throwaway thread to do the blocking url request. class DailyPingTask : public Task { public: virtual ~DailyPingTask() { } virtual void Run() { // We use a transient thread because we have no guarantees about // how long the RLZ lib can block us. _beginthread(PingNow, 0, NULL); } private: // Causes a ping to the server using WinInet. There is logic inside RLZ dll // that throttles it to a maximum of one ping per day. static void _cdecl PingNow(void*) { std::wstring lang; GoogleUpdateSettings::GetLanguage(&lang); if (lang.empty()) lang = L"en"; std::wstring brand; GoogleUpdateSettings::GetBrand(&brand); std::wstring referral; GoogleUpdateSettings::GetReferral(&referral); if (SendFinancialPing(brand.c_str(), lang.c_str(), referral.c_str(), is_organic(brand))) { access_values_state = ACCESS_VALUES_STALE; GoogleUpdateSettings::ClearReferral(); } } // Organic brands all start with GG, such as GGCM. static bool is_organic(const std::wstring brand) { return (brand.size() < 2) ? false : (brand.substr(0,2) == L"GG"); } }; // Performs late RLZ initialization and RLZ event recording for chrome. // This task needs to run on the UI thread. class DelayedInitTask : public Task { public: explicit DelayedInitTask(int directory_key, bool first_run) : directory_key_(directory_key), first_run_(first_run) { } virtual ~DelayedInitTask() { } virtual void Run() { // For non-interactive tests we don't do the rest of the initialization // because sometimes the very act of loading the dll causes QEMU to crash. if (::GetEnvironmentVariableW(env_vars::kHeadless, NULL, 0)) return; if (!LoadRLZLibrary(directory_key_)) return; // Do the initial event recording if is the first run or if we have an // empty rlz which means we haven't got a chance to do it. std::wstring omnibox_rlz; RLZTracker::GetAccessPointRlz(RLZTracker::CHROME_OMNIBOX, &omnibox_rlz); if (first_run_ || omnibox_rlz.empty()) { // Record the installation of chrome. RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::INSTALL); RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_HOME_PAGE, RLZTracker::INSTALL); // Record if google is the initial search provider. if (IsGoogleDefaultSearch()) { RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::SET_TO_GOOGLE); } // Record first user interaction with the omnibox. if (OmniBoxUsageObserver::used()) { RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::FIRST_SEARCH); } } // Schedule the daily RLZ ping. base::Thread* thread = g_browser_process->file_thread(); if (thread) thread->message_loop()->PostTask(FROM_HERE, new DailyPingTask()); } private: bool IsGoogleDefaultSearch() { if (!g_browser_process) return false; std::wstring user_data_dir; if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) return false; ProfileManager* profile_manager = g_browser_process->profile_manager(); Profile* profile = profile_manager-> GetDefaultProfile(FilePath::FromWStringHack(user_data_dir)); if (!profile) return false; const TemplateURL* url_template = profile->GetTemplateURLModel()->GetDefaultSearchProvider(); if (!url_template) return false; return url_template->url()->HasGoogleBaseURLs(); } int directory_key_; bool first_run_; DISALLOW_IMPLICIT_CONSTRUCTORS(DelayedInitTask); }; } // namespace bool RLZTracker::InitRlz(int directory_key) { return LoadRLZLibrary(directory_key); } bool RLZTracker::InitRlzDelayed(int directory_key, bool first_run) { if (!OmniBoxUsageObserver::used()) new OmniBoxUsageObserver(); // Schedule the delayed init items. const int kNinetySeconds = 90 * 1000; MessageLoop::current()->PostDelayedTask(FROM_HERE, new DelayedInitTask(directory_key, first_run), kNinetySeconds); return true; } bool RLZTracker::RecordProductEvent(Product product, AccessPoint point, Event event) { return (record_event) ? record_event(product, point, event, NULL) : false; } bool RLZTracker::ClearAllProductEvents(Product product) { return (clear_all_events) ? clear_all_events(product, NULL) : false; } // We implement caching of the answer of get_access_point() if the request // is for CHROME_OMNIBOX. If we had a successful ping, then we update the // cached value. bool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) { static std::wstring cached_ommibox_rlz; if (!get_access_point) return false; if ((CHROME_OMNIBOX == point) && (access_values_state == ACCESS_VALUES_FRESH)) { *rlz = cached_ommibox_rlz; return true; } wchar_t str_rlz[kMaxRlzLength]; if (!get_access_point(point, str_rlz, kMaxRlzLength, NULL)) return false; if (CHROME_OMNIBOX == point) { access_values_state = ACCESS_VALUES_FRESH; cached_ommibox_rlz.assign(str_rlz); } *rlz = str_rlz; return true; } // static void RLZTracker::CleanupRlz() { OmniBoxUsageObserver::DeleteInstance(); } <|endoftext|>
<commit_before>// // MCIMAPCheckAccountOperation.cc // mailcore2 // // Created by DINH Viêt Hoà on 1/12/13. // Copyright (c) 2013 MailCore. All rights reserved. // #include "MCIMAPCheckAccountOperation.h" #include "MCIMAPAsyncConnection.h" #include "MCIMAPSession.h" using namespace mailcore; void IMAPCheckAccountOperation::main() { ErrorCode error; session()->session()->login(&error); setError(error); } <commit_msg>Was trying to login before creating a connection in IMAPCheckAccountOperation, which was causing a crash<commit_after>// // MCIMAPCheckAccountOperation.cc // mailcore2 // // Created by DINH Viêt Hoà on 1/12/13. // Copyright (c) 2013 MailCore. All rights reserved. // #include "MCIMAPCheckAccountOperation.h" #include "MCIMAPAsyncConnection.h" #include "MCIMAPSession.h" using namespace mailcore; void IMAPCheckAccountOperation::main() { ErrorCode error; session()->session()->connect(&error); if (error == ErrorNone) session()->session()->login(&error); setError(error); } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Dan Leinir Turthra Jensen <admin@leinir.dk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <QQmlEngine> #include <QQmlContext> #include <QQmlComponent> #include <QStandardPaths> #include <QDir> #include <QDebug> #include <QThread> #include <KLocalizedString> #include <QApplication> #include <QCommandLineParser> #include <QCommandLineOption> #include <iostream> int main(int argc, char** argv) { QApplication app(argc, argv); app.setApplicationDisplayName("Peruse"); QCommandLineParser parser; // TODO file option for opening comics by passing them through on the command line parser.addHelpOption(); parser.process(app); if (parser.positionalArguments().size() > 1) { parser.showHelp(1); } QQmlEngine engine; #ifdef Q_OS_WIN // Because windows is a bit funny with paths and whatnot, just so the thing with the lib paths... QDir appdir(qApp->applicationDirPath()); appdir.cdUp(); engine.addImportPath(appdir.canonicalPath() + "/lib/qml"); #endif QQmlContext* objectContext = engine.rootContext(); QString platformEnv(qgetenv("PLASMA_PLATFORM")); engine.rootContext()->setContextProperty("PLASMA_PLATFORM", platformEnv); // Yes, i realise this is a touch on the ugly side. I have found no better way to allow for // things like the archive book model to create imageproviders for the archives engine.rootContext()->setContextProperty("globalQmlEngine", &engine); QString path; if (platformEnv.startsWith("phone")) { path = QStandardPaths::locate(QStandardPaths::DataLocation, "qml/MobileMain.qml"); } else { path = QStandardPaths::locate(QStandardPaths::DataLocation, "qml/Main.qml"); } int rt = 0; QQmlComponent component(&engine, path); if (component.isError()) { qCritical() << "Failed to load the component from disk. Reported error was:" << component.errorString(); rt = -1; } else { if(component.status() == QQmlComponent::Ready) { QObject* obj = component.create(objectContext); if(obj) { rt = app.exec(); } else { qCritical() << "Failed to create an object from our component"; rt = -2; } } else { qCritical() << "Failed to make the Qt Quick component ready. Status is:" << component.status(); rt = -3; } } return rt; } <commit_msg>Tell kio not to fork on windows<commit_after>/* * Copyright (C) 2015 Dan Leinir Turthra Jensen <admin@leinir.dk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <QQmlEngine> #include <QQmlContext> #include <QQmlComponent> #include <QStandardPaths> #include <QDir> #include <QDebug> #include <QThread> #include <KLocalizedString> #include <QApplication> #include <QCommandLineParser> #include <QCommandLineOption> #include <iostream> int main(int argc, char** argv) { QApplication app(argc, argv); app.setApplicationDisplayName("Peruse"); QCommandLineParser parser; // TODO file option for opening comics by passing them through on the command line parser.addHelpOption(); parser.process(app); if (parser.positionalArguments().size() > 1) { parser.showHelp(1); } QQmlEngine engine; #ifdef Q_OS_WIN // Because windows is a bit funny with paths and whatnot, just so the thing with the lib paths... QDir appdir(qApp->applicationDirPath()); appdir.cdUp(); engine.addImportPath(appdir.canonicalPath() + "/lib/qml"); // Hey, let's try and avoid all those extra stale processes, right? qputenv("KDE_FORK_SLAVES", "true"); #endif QQmlContext* objectContext = engine.rootContext(); QString platformEnv(qgetenv("PLASMA_PLATFORM")); engine.rootContext()->setContextProperty("PLASMA_PLATFORM", platformEnv); // Yes, i realise this is a touch on the ugly side. I have found no better way to allow for // things like the archive book model to create imageproviders for the archives engine.rootContext()->setContextProperty("globalQmlEngine", &engine); QString path; if (platformEnv.startsWith("phone")) { path = QStandardPaths::locate(QStandardPaths::DataLocation, "qml/MobileMain.qml"); } else { path = QStandardPaths::locate(QStandardPaths::DataLocation, "qml/Main.qml"); } int rt = 0; QQmlComponent component(&engine, path); if (component.isError()) { qCritical() << "Failed to load the component from disk. Reported error was:" << component.errorString(); rt = -1; } else { if(component.status() == QQmlComponent::Ready) { QObject* obj = component.create(objectContext); if(obj) { rt = app.exec(); } else { qCritical() << "Failed to create an object from our component"; rt = -2; } } else { qCritical() << "Failed to make the Qt Quick component ready. Status is:" << component.status(); rt = -3; } } return rt; } <|endoftext|>
<commit_before>/* Copyright (c) 2016 Jakob Nixdorf <flocke@shadowice.org> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cstdlib> #include <gtk/gtk.h> #include "sterm/config.hpp" #include "sterm/function_handler.hpp" #include "sterm/misc.hpp" #include "sterm/terminal.hpp" std::string config_file = sterm::misc::xdg_config_file_path("sterm", "sterm.ini"); GtkWidget *main_window = NULL; sterm::config *configuration = NULL; sterm::function_handler *functions = NULL; sterm::terminal *terminal = NULL; gboolean running = false; static gchar *opt_config_file = NULL; static gchar *opt_command = NULL; static GOptionEntry options[] { { "config", 'c', 0, G_OPTION_ARG_FILENAME, &opt_config_file, "Path to an alternative configuration file", NULL }, { "execute", 'e', 0, G_OPTION_ARG_STRING, &opt_command, "Execute a command", NULL }, { NULL } }; static void main_cleanup() { gtk_main_quit(); if ( terminal != NULL ) { delete(terminal); terminal = NULL; } if ( functions != NULL ) { delete(functions); functions = NULL; } if ( configuration != NULL ) { delete(configuration); configuration = NULL; } running = false; } static void main_exit_cb(GtkWidget *i_widget) { main_cleanup(); exit(EXIT_SUCCESS); } static void main_exit_with_status_cb(GtkWidget* i_widget, int status) { main_cleanup(); exit(WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE); } static gboolean parse_commandline(int argc, char* argv[]) { gboolean success = true; GError *error = NULL; GOptionContext *context = g_option_context_new(NULL); g_option_context_set_summary(context, "STerm - a simple terminal emulator based on the VTE library"); g_option_context_add_main_entries(context, options, NULL); g_option_context_add_group(context, gtk_get_option_group(true)); if ( ! g_option_context_parse(context, &argc, &argv, &error) ) { g_warning("failed to parse the commandline options: %s", error->message); g_error_free(error); success = false; } return(success); } int main(int argc, char *argv[]) { gtk_init(&argc, &argv); if ( ! parse_commandline(argc, argv) ) return(EXIT_FAILURE); if ( opt_config_file != NULL ) config_file = opt_config_file; configuration = new sterm::config(config_file); gtk_window_set_default_icon_name("utilities-terminal"); main_window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(main_window), "STerm"); gtk_container_set_border_width(GTK_CONTAINER(main_window), 0); terminal = new sterm::terminal(configuration); std::string child_command; if ( opt_command != NULL ) child_command = opt_command; terminal->attach_to_container(GTK_CONTAINER(main_window)); terminal->spawn_child(child_command); terminal->connect_callback("child-exited", G_CALLBACK(main_exit_with_status_cb), NULL); terminal->connect_callback("destroy", G_CALLBACK(main_exit_cb), NULL); terminal->link_property_to_terminal("window-title", G_OBJECT(main_window), "title"); g_signal_connect(G_OBJECT(main_window), "destroy", G_CALLBACK(main_exit_cb), NULL); functions = new sterm::function_handler(configuration, terminal); gtk_widget_show_all(main_window); running = true; gtk_main(); main_cleanup(); return(EXIT_FAILURE); } <commit_msg>Fix a small memory leak in the main app<commit_after>/* Copyright (c) 2016 Jakob Nixdorf <flocke@shadowice.org> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cstdlib> #include <gtk/gtk.h> #include "sterm/config.hpp" #include "sterm/function_handler.hpp" #include "sterm/misc.hpp" #include "sterm/terminal.hpp" std::string config_file = sterm::misc::xdg_config_file_path("sterm", "sterm.ini"); GtkWidget *main_window = NULL; sterm::config *configuration = NULL; sterm::function_handler *functions = NULL; sterm::terminal *terminal = NULL; gboolean running = false; static gchar *opt_config_file = NULL; static gchar *opt_command = NULL; static GOptionEntry options[] { { "config", 'c', 0, G_OPTION_ARG_FILENAME, &opt_config_file, "Path to an alternative configuration file", NULL }, { "execute", 'e', 0, G_OPTION_ARG_STRING, &opt_command, "Execute a command", NULL }, { NULL } }; static void main_cleanup() { gtk_main_quit(); if ( terminal != NULL ) { delete(terminal); terminal = NULL; } if ( functions != NULL ) { delete(functions); functions = NULL; } if ( configuration != NULL ) { delete(configuration); configuration = NULL; } running = false; } static void main_exit_cb(GtkWidget *i_widget) { main_cleanup(); exit(EXIT_SUCCESS); } static void main_exit_with_status_cb(GtkWidget* i_widget, int status) { main_cleanup(); exit(WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE); } static gboolean parse_commandline(int argc, char* argv[]) { gboolean success = true; GError *error = NULL; GOptionContext *context = g_option_context_new(NULL); g_option_context_set_summary(context, "STerm - a simple terminal emulator based on the VTE library"); g_option_context_add_main_entries(context, options, NULL); g_option_context_add_group(context, gtk_get_option_group(true)); if ( ! g_option_context_parse(context, &argc, &argv, &error) ) { g_warning("failed to parse the commandline options: %s", error->message); g_error_free(error); success = false; } g_option_context_free(context); return(success); } int main(int argc, char *argv[]) { gtk_init(&argc, &argv); if ( ! parse_commandline(argc, argv) ) return(EXIT_FAILURE); if ( opt_config_file != NULL ) config_file = opt_config_file; configuration = new sterm::config(config_file); gtk_window_set_default_icon_name("utilities-terminal"); main_window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(main_window), "STerm"); gtk_container_set_border_width(GTK_CONTAINER(main_window), 0); terminal = new sterm::terminal(configuration); std::string child_command; if ( opt_command != NULL ) child_command = opt_command; terminal->attach_to_container(GTK_CONTAINER(main_window)); terminal->spawn_child(child_command); terminal->connect_callback("child-exited", G_CALLBACK(main_exit_with_status_cb), NULL); terminal->connect_callback("destroy", G_CALLBACK(main_exit_cb), NULL); terminal->link_property_to_terminal("window-title", G_OBJECT(main_window), "title"); g_signal_connect(G_OBJECT(main_window), "destroy", G_CALLBACK(main_exit_cb), NULL); functions = new sterm::function_handler(configuration, terminal); gtk_widget_show_all(main_window); running = true; gtk_main(); main_cleanup(); return(EXIT_FAILURE); } <|endoftext|>
<commit_before><commit_msg>fix typo in ssl patch<commit_after><|endoftext|>
<commit_before><commit_msg>use more reads, even if strand != xs<commit_after><|endoftext|>
<commit_before>#include <stdio.h> #include <cmath> #include <geometry_msgs/PoseStamped.h> #include <jsk_rviz_plugins/OverlayText.h> #include <ros/ros.h> #include <std_msgs/String.h> #include <std_msgs/UInt8.h> #include <autoware_msgs/lane.h> #include <autoware_msgs/traffic_light.h> #include <cross_road_area.hpp> #include <decision_maker_node.hpp> #include <state.hpp> #include <state_context.hpp> namespace decision_maker { void DecisionMakerNode::callbackFromCurrentPose(const geometry_msgs::PoseStamped &msg) { geometry_msgs::PoseStamped _pose = current_pose_ = msg; bool initLocalizationFlag = ctx->isCurrentState(state_machine::INITIAL_LOCATEVEHICLE_STATE); if (initLocalizationFlag && isLocalizationConvergence(_pose.pose.position.x, _pose.pose.position.y, _pose.pose.position.z, _pose.pose.orientation.x, _pose.pose.orientation.y, _pose.pose.orientation.z)) { ROS_INFO("Localization was convergence"); } } bool DecisionMakerNode::handleStateCmd(const uint64_t _state_num) { bool _ret; ctx->setEnableForceSetState(true); if (!ctx->isCurrentState(_state_num)) { _ret = ctx->setCurrentState((state_machine::StateFlags)_state_num); if(_state_num == state_machine::DRIVE_BEHAVIOR_TRAFFICLIGHT_RED_STATE || _state_num == state_machine::DRIVE_BEHAVIOR_TRAFFIC_LIGHT_GREEN_STATE){ isManualLight = true; } } else { _ret = ctx->disableCurrentState((state_machine::StateFlags)_state_num); if(_state_num == state_machine::DRIVE_BEHAVIOR_TRAFFICLIGHT_RED_STATE || _state_num == state_machine::DRIVE_BEHAVIOR_TRAFFIC_LIGHT_GREEN_STATE){ isManualLight = false; } ctx->setEnableForceSetState(false); return _ret; } void DecisionMakerNode::callbackFromSimPose(const geometry_msgs::PoseStamped &msg) { ROS_INFO("Received system is going to simulation mode"); handleStateCmd(state_machine::DRIVE_STATE); Subs["sim_pose"].shutdown(); } void DecisionMakerNode::callbackFromStateCmd(const std_msgs::Int32 &msg) { ROS_INFO("Received forcing state changing request: %llx", 1ULL << (uint64_t)msg.data); handleStateCmd((uint64_t)1ULL << (uint64_t)msg.data); } void DecisionMakerNode::callbackFromLaneChangeFlag(const std_msgs::Int32 &msg) { if (msg.data == enumToInteger<E_ChangeFlags>(E_ChangeFlags::LEFT)) { ctx->disableCurrentState(state_machine::DRIVE_BEHAVIOR_LANECHANGE_RIGHT_STATE); ctx->setCurrentState(state_machine::DRIVE_BEHAVIOR_LANECHANGE_LEFT_STATE); } else if (msg.data == enumToInteger<E_ChangeFlags>(E_ChangeFlags::RIGHT)) { ctx->disableCurrentState(state_machine::DRIVE_BEHAVIOR_LANECHANGE_LEFT_STATE); ctx->setCurrentState(state_machine::DRIVE_BEHAVIOR_LANECHANGE_RIGHT_STATE); } else { ctx->disableCurrentState(state_machine::DRIVE_BEHAVIOR_LANECHANGE_RIGHT_STATE); ctx->disableCurrentState(state_machine::DRIVE_BEHAVIOR_LANECHANGE_LEFT_STATE); } } void DecisionMakerNode::callbackFromConfig(const autoware_msgs::ConfigDecisionMaker &msg) { ROS_INFO("Param setted by Runtime Manager"); enableDisplayMarker = msg.enable_display_marker; ctx->setEnableForceSetState(msg.enable_force_state_change); param_target_waypoint_ = msg.target_waypoint; param_stopline_target_waypoint_ = msg.stopline_target_waypoint; param_shift_width_ = msg.shift_width; } void DecisionMakerNode::callbackFromLightColor(const ros::MessageEvent<autoware_msgs::traffic_light const> &event) { const autoware_msgs::traffic_light *light = event.getMessage().get(); // const ros::M_string &header = event.getConnectionHeader(); // std::string topic = header.at("topic"); if(!isManualLight){// && topic.find("manage") == std::string::npos){ current_traffic_light_ = light->traffic_light; if (current_traffic_light_ == state_machine::E_RED || current_traffic_light_ == state_machine::E_YELLOW) { ctx->setCurrentState(state_machine::DRIVE_BEHAVIOR_TRAFFICLIGHT_RED_STATE); ctx->disableCurrentState(state_machine::DRIVE_BEHAVIOR_TRAFFICLIGHT_GREEN_STATE); } else { ctx->setCurrentState(state_machine::DRIVE_BEHAVIOR_TRAFFICLIGHT_GREEN_STATE); ctx->disableCurrentState(state_machine::DRIVE_BEHAVIOR_TRAFFICLIGHT_RED_STATE); } } } void DecisionMakerNode::callbackFromPointsRaw(const sensor_msgs::PointCloud2::ConstPtr &msg) { if (ctx->setCurrentState(state_machine::INITIAL_LOCATEVEHICLE_STATE)) Subs["points_raw"].shutdown(); } void DecisionMakerNode::insertPointWithinCrossRoad(const std::vector<CrossRoadArea> &_intersects, autoware_msgs::LaneArray &lane_array) { for (auto &lane : lane_array.lanes) { for (auto &wp : lane.waypoints) { geometry_msgs::Point pp; pp.x = wp.pose.pose.position.x; pp.y = wp.pose.pose.position.y; pp.z = wp.pose.pose.position.z; for (auto &area : intersects) { if (CrossRoadArea::isInsideArea(&area, pp)) { // area's if (area.insideLanes.empty() || wp.gid != area.insideLanes.back().waypoints.back().gid + 1) { autoware_msgs::lane nlane; area.insideLanes.push_back(nlane); } area.insideLanes.back().waypoints.push_back(wp); area.insideWaypoint_points.push_back(pp); // geometry_msgs::point // area.insideLanes.Waypoints.push_back(wp);//autoware_msgs::waypoint // lane's wp wp.wpstate.aid = area.area_id; } } } } } geometry_msgs::Point to_geoPoint(const vector_map_msgs::Point &vp) { geometry_msgs::Point gp; gp.x = vp.ly; gp.y = vp.bx; gp.z = vp.h; return gp; } void DecisionMakerNode::setWaypointState(autoware_msgs::LaneArray &lane_array) { insertPointWithinCrossRoad(intersects, lane_array); // STR for (auto &area : intersects) { for (auto &laneinArea : area.insideLanes) { // To straight/left/right recognition by using angle // between first-waypoint and end-waypoint in intersection area. int angle_deg = ((int)std::floor(calcIntersectWayAngle(laneinArea))); // normalized int steering_state; if (angle_deg <= ANGLE_LEFT) steering_state = autoware_msgs::WaypointState::STR_LEFT; else if (angle_deg >= ANGLE_RIGHT) steering_state = autoware_msgs::WaypointState::STR_RIGHT; else steering_state = autoware_msgs::WaypointState::STR_STRAIGHT; for (auto &wp_lane : laneinArea.waypoints) for (auto &lane : lane_array.lanes) for (auto &wp : lane.waypoints) if (wp.gid == wp_lane.gid && wp.wpstate.aid == area.area_id) { wp.wpstate.steering_state = steering_state; } } } // STOP std::vector<StopLine> stoplines = g_vmap.findByFilter([&](const StopLine &stopline) { return (g_vmap.findByKey(Key<RoadSign>(stopline.signid)).type == (int)vector_map_msgs::RoadSign::TYPE_STOP); }); for (auto &lane : lane_array.lanes) { for (size_t wp_idx = 0; wp_idx < lane.waypoints.size() - 1; wp_idx++) { for (auto &stopline : stoplines) { geometry_msgs::Point bp = to_geoPoint(g_vmap.findByKey(Key<Point>(g_vmap.findByKey(Key<Line>(stopline.lid)).bpid))); geometry_msgs::Point fp = to_geoPoint(g_vmap.findByKey(Key<Point>(g_vmap.findByKey(Key<Line>(stopline.lid)).fpid))); if (amathutils::isIntersectLine(lane.waypoints.at(wp_idx).pose.pose.position.x, lane.waypoints.at(wp_idx).pose.pose.position.y, lane.waypoints.at(wp_idx + 1).pose.pose.position.x, lane.waypoints.at(wp_idx + 1).pose.pose.position.y, bp.x, bp.y, fp.x, fp.y)) { geometry_msgs::Point center_point; center_point.x = (bp.x * 2 + fp.x) / 3; center_point.y = (bp.y * 2 + fp.y) / 3; if (amathutils::isPointLeftFromLine( center_point.x, center_point.y, lane.waypoints.at(wp_idx).pose.pose.position.x, lane.waypoints.at(wp_idx).pose.pose.position.y, lane.waypoints.at(wp_idx + 1).pose.pose.position.x, lane.waypoints.at(wp_idx + 1).pose.pose.position.y)) { lane.waypoints.at(wp_idx).wpstate.stopline_state = 1; // lane.waypoints.at(wp_idx + 1).wpstate.stopline_state = 1; } } } } } } // for based waypoint void DecisionMakerNode::callbackFromLaneWaypoint(const autoware_msgs::LaneArray &msg) { ROS_INFO("[%s]:LoadedWaypointLaneArray\n", __func__); current_based_lane_array_ = msg; // cached based path // indexing int gid = 0; for (auto &lane : current_based_lane_array_.lanes) { int lid = 0; for (auto &wp : lane.waypoints) { wp.gid = gid++; wp.lid = lid++; wp.wpstate.aid = 0; wp.wpstate.steering_state = autoware_msgs::WaypointState::NULLSTATE; wp.wpstate.accel_state = autoware_msgs::WaypointState::NULLSTATE; wp.wpstate.stopline_state = autoware_msgs::WaypointState::NULLSTATE; wp.wpstate.lanechange_state = autoware_msgs::WaypointState::NULLSTATE; wp.wpstate.event_state = 0; } } setWaypointState(current_based_lane_array_); current_controlled_lane_array_ = current_shifted_lane_array_ = current_based_lane_array_; // controlled path publishControlledLaneArray(); updateLaneWaypointsArray(); } state_machine::StateFlags getStateFlags(uint8_t msg_state) { if (msg_state == (uint8_t)autoware_msgs::WaypointState::STR_LEFT) return state_machine::DRIVE_STR_LEFT_STATE; else if (msg_state == (uint8_t)autoware_msgs::WaypointState::STR_RIGHT) return state_machine::DRIVE_STR_RIGHT_STATE; else return state_machine::DRIVE_STR_STRAIGHT_STATE; } void DecisionMakerNode::callbackFromFinalWaypoint(const autoware_msgs::lane &msg) { if (!hasvMap()) { std::cerr << "Not found vmap subscribe" << std::endl; return; } if (!ctx->isCurrentState(state_machine::DRIVE_STATE)) { std::cerr << "State is not DRIVE_STATE[" << ctx->getCurrentStateName() << "]" << std::endl; return; } // cached current_finalwaypoints_ = msg; size_t idx = current_finalwaypoints_.waypoints.size() - 1 > param_stopline_target_waypoint_ ? param_stopline_target_waypoint_ : current_finalwaypoints_.waypoints.size() - 1; if (current_finalwaypoints_.waypoints.at(idx).wpstate.stopline_state) ctx->setCurrentState(state_machine::DRIVE_ACC_STOPLINE_STATE); // steering idx = current_finalwaypoints_.waypoints.size() - 1 > param_target_waypoint_ ? param_target_waypoint_ : current_finalwaypoints_.waypoints.size() - 1; if (ctx->isCurrentState(state_machine::DRIVE_BEHAVIOR_LANECHANGE_LEFT_STATE)) { ctx->setCurrentState(state_machine::DRIVE_STR_LEFT_STATE); } if (ctx->isCurrentState(state_machine::DRIVE_BEHAVIOR_LANECHANGE_RIGHT_STATE)) { ctx->setCurrentState(state_machine::DRIVE_STR_RIGHT_STATE); } else { ctx->setCurrentState(getStateFlags(current_finalwaypoints_.waypoints.at(idx).wpstate.steering_state)); } // for publish plan of velocity publishToVelocityArray(); } void DecisionMakerNode::callbackFromTwistCmd(const geometry_msgs::TwistStamped &msg) { static bool Twistflag = false; if (Twistflag) ctx->handleTwistCmd(false); else Twistflag = true; } void DecisionMakerNode::callbackFromClosestWaypoint(const std_msgs::Int32 &msg) { closest_waypoint_ = msg.data; } void DecisionMakerNode::callbackFromVectorMapArea(const vector_map_msgs::AreaArray &msg) { initVectorMap(); } void DecisionMakerNode::callbackFromVectorMapPoint(const vector_map_msgs::PointArray &msg) { initVectorMap(); } void DecisionMakerNode::callbackFromVectorMapLine(const vector_map_msgs::LineArray &msg) { initVectorMap(); } void DecisionMakerNode::callbackFromVectorMapCrossRoad(const vector_map_msgs::CrossRoadArray &msg) { initVectorMap(); } void DecisionMakerNode::callbackFromCurrentVelocity(const geometry_msgs::TwistStamped &msg) { current_velocity_ = amathutils::mps2kmph(msg.twist.linear.x); } } <commit_msg>fix a state num name<commit_after>#include <stdio.h> #include <cmath> #include <geometry_msgs/PoseStamped.h> #include <jsk_rviz_plugins/OverlayText.h> #include <ros/ros.h> #include <std_msgs/String.h> #include <std_msgs/UInt8.h> #include <autoware_msgs/lane.h> #include <autoware_msgs/traffic_light.h> #include <cross_road_area.hpp> #include <decision_maker_node.hpp> #include <state.hpp> #include <state_context.hpp> namespace decision_maker { void DecisionMakerNode::callbackFromCurrentPose(const geometry_msgs::PoseStamped &msg) { geometry_msgs::PoseStamped _pose = current_pose_ = msg; bool initLocalizationFlag = ctx->isCurrentState(state_machine::INITIAL_LOCATEVEHICLE_STATE); if (initLocalizationFlag && isLocalizationConvergence(_pose.pose.position.x, _pose.pose.position.y, _pose.pose.position.z, _pose.pose.orientation.x, _pose.pose.orientation.y, _pose.pose.orientation.z)) { ROS_INFO("Localization was convergence"); } } bool DecisionMakerNode::handleStateCmd(const uint64_t _state_num) { bool _ret; ctx->setEnableForceSetState(true); if (!ctx->isCurrentState(_state_num)) { _ret = ctx->setCurrentState((state_machine::StateFlags)_state_num); if(_state_num == state_machine::DRIVE_BEHAVIOR_TRAFFICLIGHTRED_STATE || _state_num == state_machine::DRIVE_BEHAVIOR_TRAFFICLIGHT_GREEN_STATE){ isManualLight = true; } } else { _ret = ctx->disableCurrentState((state_machine::StateFlags)_state_num); if(_state_num == state_machine::DRIVE_BEHAVIOR_TRAFFICLIGHT_RED_STATE || _state_num == state_machine::DRIVE_BEHAVIOR_TRAFFICLIGHT_GREEN_STATE){ isManualLight = false; } ctx->setEnableForceSetState(false); return _ret; } void DecisionMakerNode::callbackFromSimPose(const geometry_msgs::PoseStamped &msg) { ROS_INFO("Received system is going to simulation mode"); handleStateCmd(state_machine::DRIVE_STATE); Subs["sim_pose"].shutdown(); } void DecisionMakerNode::callbackFromStateCmd(const std_msgs::Int32 &msg) { ROS_INFO("Received forcing state changing request: %llx", 1ULL << (uint64_t)msg.data); handleStateCmd((uint64_t)1ULL << (uint64_t)msg.data); } void DecisionMakerNode::callbackFromLaneChangeFlag(const std_msgs::Int32 &msg) { if (msg.data == enumToInteger<E_ChangeFlags>(E_ChangeFlags::LEFT)) { ctx->disableCurrentState(state_machine::DRIVE_BEHAVIOR_LANECHANGE_RIGHT_STATE); ctx->setCurrentState(state_machine::DRIVE_BEHAVIOR_LANECHANGE_LEFT_STATE); } else if (msg.data == enumToInteger<E_ChangeFlags>(E_ChangeFlags::RIGHT)) { ctx->disableCurrentState(state_machine::DRIVE_BEHAVIOR_LANECHANGE_LEFT_STATE); ctx->setCurrentState(state_machine::DRIVE_BEHAVIOR_LANECHANGE_RIGHT_STATE); } else { ctx->disableCurrentState(state_machine::DRIVE_BEHAVIOR_LANECHANGE_RIGHT_STATE); ctx->disableCurrentState(state_machine::DRIVE_BEHAVIOR_LANECHANGE_LEFT_STATE); } } void DecisionMakerNode::callbackFromConfig(const autoware_msgs::ConfigDecisionMaker &msg) { ROS_INFO("Param setted by Runtime Manager"); enableDisplayMarker = msg.enable_display_marker; ctx->setEnableForceSetState(msg.enable_force_state_change); param_target_waypoint_ = msg.target_waypoint; param_stopline_target_waypoint_ = msg.stopline_target_waypoint; param_shift_width_ = msg.shift_width; } void DecisionMakerNode::callbackFromLightColor(const ros::MessageEvent<autoware_msgs::traffic_light const> &event) { const autoware_msgs::traffic_light *light = event.getMessage().get(); // const ros::M_string &header = event.getConnectionHeader(); // std::string topic = header.at("topic"); if(!isManualLight){// && topic.find("manage") == std::string::npos){ current_traffic_light_ = light->traffic_light; if (current_traffic_light_ == state_machine::E_RED || current_traffic_light_ == state_machine::E_YELLOW) { ctx->setCurrentState(state_machine::DRIVE_BEHAVIOR_TRAFFICLIGHT_RED_STATE); ctx->disableCurrentState(state_machine::DRIVE_BEHAVIOR_TRAFFICLIGHT_GREEN_STATE); } else { ctx->setCurrentState(state_machine::DRIVE_BEHAVIOR_TRAFFICLIGHT_GREEN_STATE); ctx->disableCurrentState(state_machine::DRIVE_BEHAVIOR_TRAFFICLIGHT_RED_STATE); } } } void DecisionMakerNode::callbackFromPointsRaw(const sensor_msgs::PointCloud2::ConstPtr &msg) { if (ctx->setCurrentState(state_machine::INITIAL_LOCATEVEHICLE_STATE)) Subs["points_raw"].shutdown(); } void DecisionMakerNode::insertPointWithinCrossRoad(const std::vector<CrossRoadArea> &_intersects, autoware_msgs::LaneArray &lane_array) { for (auto &lane : lane_array.lanes) { for (auto &wp : lane.waypoints) { geometry_msgs::Point pp; pp.x = wp.pose.pose.position.x; pp.y = wp.pose.pose.position.y; pp.z = wp.pose.pose.position.z; for (auto &area : intersects) { if (CrossRoadArea::isInsideArea(&area, pp)) { // area's if (area.insideLanes.empty() || wp.gid != area.insideLanes.back().waypoints.back().gid + 1) { autoware_msgs::lane nlane; area.insideLanes.push_back(nlane); } area.insideLanes.back().waypoints.push_back(wp); area.insideWaypoint_points.push_back(pp); // geometry_msgs::point // area.insideLanes.Waypoints.push_back(wp);//autoware_msgs::waypoint // lane's wp wp.wpstate.aid = area.area_id; } } } } } geometry_msgs::Point to_geoPoint(const vector_map_msgs::Point &vp) { geometry_msgs::Point gp; gp.x = vp.ly; gp.y = vp.bx; gp.z = vp.h; return gp; } void DecisionMakerNode::setWaypointState(autoware_msgs::LaneArray &lane_array) { insertPointWithinCrossRoad(intersects, lane_array); // STR for (auto &area : intersects) { for (auto &laneinArea : area.insideLanes) { // To straight/left/right recognition by using angle // between first-waypoint and end-waypoint in intersection area. int angle_deg = ((int)std::floor(calcIntersectWayAngle(laneinArea))); // normalized int steering_state; if (angle_deg <= ANGLE_LEFT) steering_state = autoware_msgs::WaypointState::STR_LEFT; else if (angle_deg >= ANGLE_RIGHT) steering_state = autoware_msgs::WaypointState::STR_RIGHT; else steering_state = autoware_msgs::WaypointState::STR_STRAIGHT; for (auto &wp_lane : laneinArea.waypoints) for (auto &lane : lane_array.lanes) for (auto &wp : lane.waypoints) if (wp.gid == wp_lane.gid && wp.wpstate.aid == area.area_id) { wp.wpstate.steering_state = steering_state; } } } // STOP std::vector<StopLine> stoplines = g_vmap.findByFilter([&](const StopLine &stopline) { return (g_vmap.findByKey(Key<RoadSign>(stopline.signid)).type == (int)vector_map_msgs::RoadSign::TYPE_STOP); }); for (auto &lane : lane_array.lanes) { for (size_t wp_idx = 0; wp_idx < lane.waypoints.size() - 1; wp_idx++) { for (auto &stopline : stoplines) { geometry_msgs::Point bp = to_geoPoint(g_vmap.findByKey(Key<Point>(g_vmap.findByKey(Key<Line>(stopline.lid)).bpid))); geometry_msgs::Point fp = to_geoPoint(g_vmap.findByKey(Key<Point>(g_vmap.findByKey(Key<Line>(stopline.lid)).fpid))); if (amathutils::isIntersectLine(lane.waypoints.at(wp_idx).pose.pose.position.x, lane.waypoints.at(wp_idx).pose.pose.position.y, lane.waypoints.at(wp_idx + 1).pose.pose.position.x, lane.waypoints.at(wp_idx + 1).pose.pose.position.y, bp.x, bp.y, fp.x, fp.y)) { geometry_msgs::Point center_point; center_point.x = (bp.x * 2 + fp.x) / 3; center_point.y = (bp.y * 2 + fp.y) / 3; if (amathutils::isPointLeftFromLine( center_point.x, center_point.y, lane.waypoints.at(wp_idx).pose.pose.position.x, lane.waypoints.at(wp_idx).pose.pose.position.y, lane.waypoints.at(wp_idx + 1).pose.pose.position.x, lane.waypoints.at(wp_idx + 1).pose.pose.position.y)) { lane.waypoints.at(wp_idx).wpstate.stopline_state = 1; // lane.waypoints.at(wp_idx + 1).wpstate.stopline_state = 1; } } } } } } // for based waypoint void DecisionMakerNode::callbackFromLaneWaypoint(const autoware_msgs::LaneArray &msg) { ROS_INFO("[%s]:LoadedWaypointLaneArray\n", __func__); current_based_lane_array_ = msg; // cached based path // indexing int gid = 0; for (auto &lane : current_based_lane_array_.lanes) { int lid = 0; for (auto &wp : lane.waypoints) { wp.gid = gid++; wp.lid = lid++; wp.wpstate.aid = 0; wp.wpstate.steering_state = autoware_msgs::WaypointState::NULLSTATE; wp.wpstate.accel_state = autoware_msgs::WaypointState::NULLSTATE; wp.wpstate.stopline_state = autoware_msgs::WaypointState::NULLSTATE; wp.wpstate.lanechange_state = autoware_msgs::WaypointState::NULLSTATE; wp.wpstate.event_state = 0; } } setWaypointState(current_based_lane_array_); current_controlled_lane_array_ = current_shifted_lane_array_ = current_based_lane_array_; // controlled path publishControlledLaneArray(); updateLaneWaypointsArray(); } state_machine::StateFlags getStateFlags(uint8_t msg_state) { if (msg_state == (uint8_t)autoware_msgs::WaypointState::STR_LEFT) return state_machine::DRIVE_STR_LEFT_STATE; else if (msg_state == (uint8_t)autoware_msgs::WaypointState::STR_RIGHT) return state_machine::DRIVE_STR_RIGHT_STATE; else return state_machine::DRIVE_STR_STRAIGHT_STATE; } void DecisionMakerNode::callbackFromFinalWaypoint(const autoware_msgs::lane &msg) { if (!hasvMap()) { std::cerr << "Not found vmap subscribe" << std::endl; return; } if (!ctx->isCurrentState(state_machine::DRIVE_STATE)) { std::cerr << "State is not DRIVE_STATE[" << ctx->getCurrentStateName() << "]" << std::endl; return; } // cached current_finalwaypoints_ = msg; size_t idx = current_finalwaypoints_.waypoints.size() - 1 > param_stopline_target_waypoint_ ? param_stopline_target_waypoint_ : current_finalwaypoints_.waypoints.size() - 1; if (current_finalwaypoints_.waypoints.at(idx).wpstate.stopline_state) ctx->setCurrentState(state_machine::DRIVE_ACC_STOPLINE_STATE); // steering idx = current_finalwaypoints_.waypoints.size() - 1 > param_target_waypoint_ ? param_target_waypoint_ : current_finalwaypoints_.waypoints.size() - 1; if (ctx->isCurrentState(state_machine::DRIVE_BEHAVIOR_LANECHANGE_LEFT_STATE)) { ctx->setCurrentState(state_machine::DRIVE_STR_LEFT_STATE); } if (ctx->isCurrentState(state_machine::DRIVE_BEHAVIOR_LANECHANGE_RIGHT_STATE)) { ctx->setCurrentState(state_machine::DRIVE_STR_RIGHT_STATE); } else { ctx->setCurrentState(getStateFlags(current_finalwaypoints_.waypoints.at(idx).wpstate.steering_state)); } // for publish plan of velocity publishToVelocityArray(); } void DecisionMakerNode::callbackFromTwistCmd(const geometry_msgs::TwistStamped &msg) { static bool Twistflag = false; if (Twistflag) ctx->handleTwistCmd(false); else Twistflag = true; } void DecisionMakerNode::callbackFromClosestWaypoint(const std_msgs::Int32 &msg) { closest_waypoint_ = msg.data; } void DecisionMakerNode::callbackFromVectorMapArea(const vector_map_msgs::AreaArray &msg) { initVectorMap(); } void DecisionMakerNode::callbackFromVectorMapPoint(const vector_map_msgs::PointArray &msg) { initVectorMap(); } void DecisionMakerNode::callbackFromVectorMapLine(const vector_map_msgs::LineArray &msg) { initVectorMap(); } void DecisionMakerNode::callbackFromVectorMapCrossRoad(const vector_map_msgs::CrossRoadArray &msg) { initVectorMap(); } void DecisionMakerNode::callbackFromCurrentVelocity(const geometry_msgs::TwistStamped &msg) { current_velocity_ = amathutils::mps2kmph(msg.twist.linear.x); } } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <humanoid_catching/CalculateTorques.h> #include <Moby/qpOASES.h> #include <Ravelin/VectorNd.h> #include <Ravelin/MatrixNd.h> #include <Ravelin/Quatd.h> #include <Ravelin/Opsd.h> #include <Moby/qpOASES.h> #include <Ravelin/LinAlgd.h> namespace { using namespace std; using namespace humanoid_catching; using namespace Ravelin; static const double GRAVITY = 9.81; class Balancer { private: //! Node handle ros::NodeHandle nh; //! Private nh ros::NodeHandle pnh; //! Balancer Service ros::ServiceServer balancerService; public: Balancer() : pnh("~") { balancerService = nh.advertiseService("/balancer/torques", &Balancer::calculateTorques, this); } private: /** * Convert a geometry_msgs::Vector3 to a Ravelin::Vector3d * @param v3 geometry_msgs::Vector3 * @return Ravelin Vector3d */ static Vector3d toVector(const geometry_msgs::Vector3& v3) { Vector3d v; v[0] = v3.x; v[1] = v3.y; v[2] = v3.z; return v; } /** * Convert a geometry_msgs::Point to a Ravelin::Vector3d * @param p geometry_msgs::Point * @return Ravelin Vector3d */ static Vector3d toVector(const geometry_msgs::Point& p) { Vector3d v; v[0] = p.x; v[1] = p.y; v[2] = p.z; return v; } /** * Calculate balancing torques * @param req Request * @param res Response * @return Success */ bool calculateTorques(humanoid_catching::CalculateTorques::Request& req, humanoid_catching::CalculateTorques::Response& res) { ROS_INFO("Calculating torques frame %s", req.header.frame_id.c_str()); // x // linear velocity of body ROS_INFO("Calculating x vector"); const Vector3d x = toVector(req.body_velocity.linear); ROS_INFO_STREAM("x: " << x); // w // angular velocity of body ROS_INFO("Calculating w vector"); const Vector3d w = toVector(req.body_velocity.angular); ROS_INFO_STREAM("w: " << w); // v(t) // | x | // | w | ROS_INFO("Calculating v vector"); VectorNd v(6); v.set_sub_vec(0, x); v.set_sub_vec(3, w); ROS_INFO_STREAM("v: " << v); // R // Pole rotation matrix ROS_INFO("Calculating R matrix"); const Matrix3d R = MatrixNd(Quatd(req.body_com.orientation.x, req.body_com.orientation.y, req.body_com.orientation.z, req.body_com.orientation.w)); ROS_INFO_STREAM("R: " << R); // J // Pole inertia matrix ROS_INFO("Calculating J matrix"); ROS_INFO_STREAM("BIM: " << req.body_inertia_matrix.size()); const Matrix3d J = Matrix3d(&req.body_inertia_matrix[0]); ROS_INFO_STREAM("J: " << J); // JRobot // Robot end effector jacobian matrix ROS_INFO("Calculating JRobot"); const MatrixNd JRobot = MatrixNd(req.torque_limits.size(), 6, &req.jacobian_matrix[0]); ROS_INFO_STREAM("JRobot: " << JRobot); // RJR_t ROS_INFO("Calculating RJR"); Matrix3d RJR; Matrix3d RTranspose = R.transpose(RTranspose); RJR = R.mult(J, RJR).mult(RTranspose, RJR); ROS_INFO_STREAM("RJR: " << RJR); // M // | Im 0 | // | 0 RJR_t| ROS_INFO("Calculating M"); MatrixNd M(6, 6); M.set_zero(M.rows(), M.columns()); M.set_sub_mat(0, 0, Matrix3d::identity() * req.body_mass); M.set_sub_mat(3, 3, RJR); ROS_INFO_STREAM("M: " << M); // delta t double deltaT = req.time_delta.toSec(); // Working vector Vector3d tempVector; // fext // | g | // | -w x RJR_tw | ROS_INFO("Calculating fExt"); VectorNd fExt(6); fExt[0] = 0; fExt[1] = 0; fExt[2] = GRAVITY; fExt.set_sub_vec(3, Vector3d::cross(-w, RJR.mult(w, tempVector))); ROS_INFO_STREAM("fExt: " << fExt); // n_hat // x component of ground contact position ROS_INFO("Calculating nHat"); Vector3d nHat; nHat[0] = req.ground_contact.x; nHat[1] = 0; nHat[2] = 0; ROS_INFO_STREAM("nHat: " << nHat); // s_hat // s component of contact position ROS_INFO("Calculating sHat"); Vector3d sHat; nHat[0] = 0; nHat[1] = req.ground_contact.y; nHat[2] = 0; ROS_INFO_STREAM("sHat: " << sHat); // t_hat // z component of contact position ROS_INFO("Calculating tHat"); Vector3d tHat; tHat[0] = 0; tHat[1] = 0; tHat[2] = req.ground_contact.z; ROS_INFO_STREAM("tHat: " << tHat); // q_hat // contact normal ROS_INFO("Calculating qHat"); const Vector3d qHat = toVector(req.contact_normal); ROS_INFO_STREAM("qHat: " << qHat); // p // contact point ROS_INFO("Calculating P"); const Vector3d p = toVector(req.ground_contact); ROS_INFO_STREAM("p: " << p); // x_bar // pole COM ROS_INFO("Calculating xBar"); const Vector3d xBar = toVector(req.body_com.position); ROS_INFO_STREAM("xBar: " << xBar); // r ROS_INFO("Calculating r"); const Vector3d r = p - xBar; ROS_INFO_STREAM("r: " << r); // N // | n_hat | // | r x n_hat | ROS_INFO("Calculating N"); VectorNd N(6); N.set_sub_vec(0, nHat); N.set_sub_vec(3, r.cross(nHat, tempVector)); ROS_INFO_STREAM("N: " << N); // S // | s_hat | // | r x s_hat | ROS_INFO("Calculating S"); VectorNd S(6); S.set_sub_vec(0, sHat); S.set_sub_vec(3, r.cross(sHat, tempVector)); ROS_INFO_STREAM("S: " << S); // T // | t_hat | // | r x t_hat | ROS_INFO("Calculating T"); VectorNd T(6); T.set_sub_vec(0, tHat); T.set_sub_vec(3, r.cross(tHat, tempVector)); ROS_INFO_STREAM("T: " << T); // Q ROS_INFO("Calculating Q"); VectorNd Q(6); Q.set_sub_vec(0, qHat); Q.set_sub_vec(3, -r.cross(qHat, tempVector)); ROS_INFO_STREAM("Q: " << Q); // Result vector // Torques, f_n, f_s, f_t, f_robot, v_(t + tdelta) const int torqueIdx = 0; const int fNIdx = req.torque_limits.size(); const int fSIdx = fNIdx + 1; const int fTIdx = fSIdx + 1; const int fRobotIdx = fTIdx + 1; const int vTDeltaIdx = fRobotIdx + 1; VectorNd z(req.torque_limits.size() + 1 + 1 + 1 + 1 + 6); // Set up minimization function ROS_INFO("Calculating H"); MatrixNd H(6, z.size()); H.set_sub_mat(0, vTDeltaIdx, M); ROS_INFO_STREAM("H: " << H); ROS_INFO("Calculating c"); VectorNd c(6); c.set_zero(c.rows()); ROS_INFO_STREAM("c: " << c); // Linear equality constraints ROS_INFO("Calculating A + b"); MatrixNd A(1 * 2 + req.torque_limits.size() + 6, z.size()); VectorNd b(1 * 2 + req.torque_limits.size() + 6); ROS_INFO("Setting Sv constraint"); // Sv(t + t_delta) = 0 (no tangent velocity) unsigned idx = 0; A.set_sub_mat(idx, vTDeltaIdx, S); b.set_sub_vec(idx, VectorNd::zero(1)); idx += 1; ROS_INFO("Setting Tv constraint"); // Tv(t + t_delta) = 0 (no tangent velocity) A.set_sub_mat(idx, vTDeltaIdx, T); b.set_sub_vec(idx, VectorNd::zero(1)); idx += 1; ROS_INFO("Setting torque constraint"); // J_robot(transpose) * Q(transpose) * f_robot = torques // Transformed to: // J_Robot(transpose) * Q(transpose) * f_robot - I * torques = 0 MatrixNd JQ(req.torque_limits.size(), 1); MatrixNd Jt = JRobot; Jt.transpose(); MatrixNd Qt(Q, eTranspose); Jt.mult(Qt, JQ); A.set_sub_mat(idx, fRobotIdx, JQ); A.set_sub_mat(idx, torqueIdx, MatrixNd::identity(req.torque_limits.size()).negate()); b.set_sub_vec(idx, VectorNd::zero(req.torque_limits.size())); idx += req.torque_limits.size(); ROS_INFO("Setting velocity constraint"); // v_(t + t_delta) = v_t + M_inv (N_t * f_n + S_t * f_s + T_t * f_t + delta_t * f_ext + Q_t * delta_t * f_robot) // Manipulated to fit constraint form // -v_t - M_inv * delta_t * f_ext = M_inv * N_t * f_n + M_inv * S_t * f_s + M_inv * T_t * f_t + M_inv * Q_t * delta_t * f_robot + -I * v_(t + t_delta) LinAlgd linAlgd; MatrixNd MInverse = M; linAlgd.pseudo_invert(MInverse); MatrixNd MInverseN(MInverse.rows(), N.columns()); MInverse.mult(N, MInverseN); A.set_sub_mat(idx, fNIdx, MInverseN); MatrixNd MInverseS(MInverse.rows(), S.columns()); MInverse.mult(S, MInverseS); A.set_sub_mat(idx, fSIdx, MInverseS); MatrixNd MInverseT(MInverse.rows(), T.columns()); MInverse.mult(T, MInverseT); A.set_sub_mat(idx, fTIdx, MInverseT); MatrixNd MInverseQ(MInverse.rows(), Q.columns()); MInverse.mult(Q, MInverseQ); MInverseQ *= deltaT; A.set_sub_mat(idx, fRobotIdx, MInverseQ); A.set_sub_mat(idx, vTDeltaIdx, MatrixNd::identity(6).negate()); VectorNd MInverseFExt(6); MInverseFExt.set_zero(); MInverse.mult(fExt, MInverseFExt, deltaT); MInverseFExt.negate() -= v; b.set_sub_vec(idx, MInverseFExt); ROS_INFO_STREAM("A: " << A); ROS_INFO_STREAM("b: " << b); // Linear inequality constraints ROS_INFO("Calculating Mc and q"); MatrixNd Mc(6, z.size()); VectorNd q(6); // Nv(t) >= 0 (non-negative normal velocity) Mc.set_sub_mat(0, vTDeltaIdx, N); q.set_sub_vec(0, VectorNd::zero(6)); ROS_INFO_STREAM("Mc: " << Mc); ROS_INFO_STREAM("q: " << q); // Solution variable constraint ROS_INFO("Calculating lb and ub"); VectorNd lb(z.size()); VectorNd ub(z.size()); // Torque constraints unsigned int bound = 0; for (bound; bound < req.torque_limits.size(); ++bound) { lb[bound] = req.torque_limits[bound].minimum; ub[bound] = req.torque_limits[bound].maximum; } // f_n >= 0 lb[bound] = 0; ub[bound] = INFINITY; ++bound; // f_s (no constraints) lb[bound] = INFINITY; ub[bound] = INFINITY; ++bound; // f_t (no constraints) lb[bound] = INFINITY; ub[bound] = INFINITY; ++bound; // f_robot >= 0 lb[bound] = 0; ub[bound] = INFINITY; ++bound; // v_t (no constraints) for (bound; bound < z.size(); ++bound) { lb[bound] = INFINITY; ub[bound] = INFINITY; } ROS_INFO_STREAM("lb: " << lb); ROS_INFO_STREAM("ub: " << ub); // Call solver ROS_INFO("Calling solver"); Moby::QPOASES qp; if (!qp.qp_activeset(H, p, lb, ub, Mc, q, A, b, z)){ ROS_ERROR("QP failed to find feasible point"); return false; } ROS_INFO_STREAM("QP solved successfully: " << z); // Copy over result res.torques.resize(req.torque_limits.size()); for (unsigned int i = 0; i < z.size(); ++i) { res.torques[i] = z[i]; } return true; } }; } int main(int argc, char** argv) { ros::init(argc, argv, "balancer"); Balancer bal; ros::spin(); } <commit_msg>Small calculation change<commit_after>#include <ros/ros.h> #include <humanoid_catching/CalculateTorques.h> #include <Moby/qpOASES.h> #include <Ravelin/VectorNd.h> #include <Ravelin/MatrixNd.h> #include <Ravelin/Quatd.h> #include <Ravelin/Opsd.h> #include <Moby/qpOASES.h> #include <Ravelin/LinAlgd.h> namespace { using namespace std; using namespace humanoid_catching; using namespace Ravelin; static const double GRAVITY = 9.81; class Balancer { private: //! Node handle ros::NodeHandle nh; //! Private nh ros::NodeHandle pnh; //! Balancer Service ros::ServiceServer balancerService; public: Balancer() : pnh("~") { balancerService = nh.advertiseService("/balancer/torques", &Balancer::calculateTorques, this); } private: /** * Convert a geometry_msgs::Vector3 to a Ravelin::Vector3d * @param v3 geometry_msgs::Vector3 * @return Ravelin Vector3d */ static Vector3d toVector(const geometry_msgs::Vector3& v3) { Vector3d v; v[0] = v3.x; v[1] = v3.y; v[2] = v3.z; return v; } /** * Convert a geometry_msgs::Point to a Ravelin::Vector3d * @param p geometry_msgs::Point * @return Ravelin Vector3d */ static Vector3d toVector(const geometry_msgs::Point& p) { Vector3d v; v[0] = p.x; v[1] = p.y; v[2] = p.z; return v; } /** * Calculate balancing torques * @param req Request * @param res Response * @return Success */ bool calculateTorques(humanoid_catching::CalculateTorques::Request& req, humanoid_catching::CalculateTorques::Response& res) { ROS_INFO("Calculating torques frame %s", req.header.frame_id.c_str()); // x // linear velocity of body ROS_INFO("Calculating x vector"); const Vector3d x = toVector(req.body_velocity.linear); ROS_INFO_STREAM("x: " << x); // w // angular velocity of body ROS_INFO("Calculating w vector"); const Vector3d w = toVector(req.body_velocity.angular); ROS_INFO_STREAM("w: " << w); // v(t) // | x | // | w | ROS_INFO("Calculating v vector"); VectorNd v(6); v.set_sub_vec(0, x); v.set_sub_vec(3, w); ROS_INFO_STREAM("v: " << v); // R // Pole rotation matrix ROS_INFO("Calculating R matrix"); const Matrix3d R = Quatd(req.body_com.orientation.x, req.body_com.orientation.y, req.body_com.orientation.z, req.body_com.orientation.w); ROS_INFO_STREAM("R: " << R); // J // Pole inertia matrix ROS_INFO("Calculating J matrix"); ROS_INFO_STREAM("BIM: " << req.body_inertia_matrix.size()); const Matrix3d J = Matrix3d(&req.body_inertia_matrix[0]); ROS_INFO_STREAM("J: " << J); // JRobot // Robot end effector jacobian matrix ROS_INFO("Calculating JRobot"); const MatrixNd JRobot = MatrixNd(req.torque_limits.size(), 6, &req.jacobian_matrix[0]); ROS_INFO_STREAM("JRobot: " << JRobot); // RJR_t ROS_INFO("Calculating RJR"); Matrix3d RJR; Matrix3d RTranspose = R.transpose(RTranspose); RJR = R.mult(J, RJR).mult(RTranspose, RJR); ROS_INFO_STREAM("RJR: " << RJR); // M // | Im 0 | // | 0 RJR_t| ROS_INFO("Calculating M"); MatrixNd M(6, 6); M.set_zero(M.rows(), M.columns()); M.set_sub_mat(0, 0, Matrix3d::identity() * req.body_mass); M.set_sub_mat(3, 3, RJR); ROS_INFO_STREAM("M: " << M); // delta t double deltaT = req.time_delta.toSec(); // Working vector Vector3d tempVector; // fext // | g | // | -w x RJR_tw | ROS_INFO("Calculating fExt"); VectorNd fExt(6); fExt[0] = 0; fExt[1] = 0; fExt[2] = GRAVITY; fExt.set_sub_vec(3, Vector3d::cross(-w, RJR.mult(w, tempVector))); ROS_INFO_STREAM("fExt: " << fExt); // n_hat // x component of ground contact position ROS_INFO("Calculating nHat"); Vector3d nHat; nHat[0] = req.ground_contact.x; nHat[1] = 0; nHat[2] = 0; ROS_INFO_STREAM("nHat: " << nHat); // s_hat // s component of contact position ROS_INFO("Calculating sHat"); Vector3d sHat; nHat[0] = 0; nHat[1] = req.ground_contact.y; nHat[2] = 0; ROS_INFO_STREAM("sHat: " << sHat); // t_hat // z component of contact position ROS_INFO("Calculating tHat"); Vector3d tHat; tHat[0] = 0; tHat[1] = 0; tHat[2] = req.ground_contact.z; ROS_INFO_STREAM("tHat: " << tHat); // q_hat // contact normal ROS_INFO("Calculating qHat"); const Vector3d qHat = toVector(req.contact_normal); ROS_INFO_STREAM("qHat: " << qHat); // p // contact point ROS_INFO("Calculating P"); const Vector3d p = toVector(req.ground_contact); ROS_INFO_STREAM("p: " << p); // x_bar // pole COM ROS_INFO("Calculating xBar"); const Vector3d xBar = toVector(req.body_com.position); ROS_INFO_STREAM("xBar: " << xBar); // r ROS_INFO("Calculating r"); const Vector3d r = p - xBar; ROS_INFO_STREAM("r: " << r); // N // | n_hat | // | r x n_hat | ROS_INFO("Calculating N"); VectorNd N(6); N.set_sub_vec(0, nHat); N.set_sub_vec(3, r.cross(nHat, tempVector)); ROS_INFO_STREAM("N: " << N); // S // | s_hat | // | r x s_hat | ROS_INFO("Calculating S"); VectorNd S(6); S.set_sub_vec(0, sHat); S.set_sub_vec(3, r.cross(sHat, tempVector)); ROS_INFO_STREAM("S: " << S); // T // | t_hat | // | r x t_hat | ROS_INFO("Calculating T"); VectorNd T(6); T.set_sub_vec(0, tHat); T.set_sub_vec(3, r.cross(tHat, tempVector)); ROS_INFO_STREAM("T: " << T); // Q ROS_INFO("Calculating Q"); VectorNd Q(6); Q.set_sub_vec(0, qHat); Q.set_sub_vec(3, -r.cross(qHat, tempVector)); ROS_INFO_STREAM("Q: " << Q); // Result vector // Torques, f_n, f_s, f_t, f_robot, v_(t + tdelta) const int torqueIdx = 0; const int fNIdx = req.torque_limits.size(); const int fSIdx = fNIdx + 1; const int fTIdx = fSIdx + 1; const int fRobotIdx = fTIdx + 1; const int vTDeltaIdx = fRobotIdx + 1; VectorNd z(req.torque_limits.size() + 1 + 1 + 1 + 1 + 6); // Set up minimization function ROS_INFO("Calculating H"); MatrixNd H(6, z.size()); H.set_sub_mat(0, vTDeltaIdx, M); ROS_INFO_STREAM("H: " << H); ROS_INFO("Calculating c"); VectorNd c(6); c.set_zero(c.rows()); ROS_INFO_STREAM("c: " << c); // Linear equality constraints ROS_INFO("Calculating A + b"); MatrixNd A(1 * 2 + req.torque_limits.size() + 6, z.size()); VectorNd b(1 * 2 + req.torque_limits.size() + 6); ROS_INFO("Setting Sv constraint"); // Sv(t + t_delta) = 0 (no tangent velocity) unsigned idx = 0; A.set_sub_mat(idx, vTDeltaIdx, S); b.set_sub_vec(idx, VectorNd::zero(1)); idx += 1; ROS_INFO("Setting Tv constraint"); // Tv(t + t_delta) = 0 (no tangent velocity) A.set_sub_mat(idx, vTDeltaIdx, T); b.set_sub_vec(idx, VectorNd::zero(1)); idx += 1; ROS_INFO("Setting torque constraint"); // J_robot(transpose) * Q(transpose) * f_robot = torques // Transformed to: // J_Robot(transpose) * Q(transpose) * f_robot - I * torques = 0 MatrixNd JQ(req.torque_limits.size(), 1); MatrixNd Jt = JRobot; Jt.transpose(); MatrixNd Qt(Q, eTranspose); Jt.mult(Qt, JQ); A.set_sub_mat(idx, fRobotIdx, JQ); A.set_sub_mat(idx, torqueIdx, MatrixNd::identity(req.torque_limits.size()).negate()); b.set_sub_vec(idx, VectorNd::zero(req.torque_limits.size())); idx += req.torque_limits.size(); ROS_INFO("Setting velocity constraint"); // v_(t + t_delta) = v_t + M_inv (N_t * f_n + S_t * f_s + T_t * f_t + delta_t * f_ext + Q_t * delta_t * f_robot) // Manipulated to fit constraint form // -v_t - M_inv * delta_t * f_ext = M_inv * N_t * f_n + M_inv * S_t * f_s + M_inv * T_t * f_t + M_inv * Q_t * delta_t * f_robot + -I * v_(t + t_delta) LinAlgd linAlgd; MatrixNd MInverse = M; linAlgd.pseudo_invert(MInverse); MatrixNd MInverseN(MInverse.rows(), N.columns()); MInverse.mult(N, MInverseN); A.set_sub_mat(idx, fNIdx, MInverseN); MatrixNd MInverseS(MInverse.rows(), S.columns()); MInverse.mult(S, MInverseS); A.set_sub_mat(idx, fSIdx, MInverseS); MatrixNd MInverseT(MInverse.rows(), T.columns()); MInverse.mult(T, MInverseT); A.set_sub_mat(idx, fTIdx, MInverseT); MatrixNd MInverseQ(MInverse.rows(), Q.columns()); MInverse.mult(Q, MInverseQ); MInverseQ *= deltaT; A.set_sub_mat(idx, fRobotIdx, MInverseQ); A.set_sub_mat(idx, vTDeltaIdx, MatrixNd::identity(6).negate()); VectorNd MInverseFExt(6); MInverseFExt.set_zero(); MInverse.mult(fExt, MInverseFExt, deltaT); MInverseFExt.negate() -= v; b.set_sub_vec(idx, MInverseFExt); ROS_INFO_STREAM("A: " << A); ROS_INFO_STREAM("b: " << b); // Linear inequality constraints ROS_INFO("Calculating Mc and q"); MatrixNd Mc(6, z.size()); VectorNd q(6); // Nv(t) >= 0 (non-negative normal velocity) Mc.set_sub_mat(0, vTDeltaIdx, N); q.set_sub_vec(0, VectorNd::zero(6)); ROS_INFO_STREAM("Mc: " << Mc); ROS_INFO_STREAM("q: " << q); // Solution variable constraint ROS_INFO("Calculating lb and ub"); VectorNd lb(z.size()); VectorNd ub(z.size()); // Torque constraints unsigned int bound = 0; for (bound; bound < req.torque_limits.size(); ++bound) { lb[bound] = req.torque_limits[bound].minimum; ub[bound] = req.torque_limits[bound].maximum; } // f_n >= 0 lb[bound] = 0; ub[bound] = INFINITY; ++bound; // f_s (no constraints) lb[bound] = INFINITY; ub[bound] = INFINITY; ++bound; // f_t (no constraints) lb[bound] = INFINITY; ub[bound] = INFINITY; ++bound; // f_robot >= 0 lb[bound] = 0; ub[bound] = INFINITY; ++bound; // v_t (no constraints) for (bound; bound < z.size(); ++bound) { lb[bound] = INFINITY; ub[bound] = INFINITY; } ROS_INFO_STREAM("lb: " << lb); ROS_INFO_STREAM("ub: " << ub); // Call solver ROS_INFO("Calling solver"); Moby::QPOASES qp; if (!qp.qp_activeset(H, p, lb, ub, Mc, q, A, b, z)){ ROS_ERROR("QP failed to find feasible point"); return false; } ROS_INFO_STREAM("QP solved successfully: " << z); // Copy over result res.torques.resize(req.torque_limits.size()); for (unsigned int i = 0; i < z.size(); ++i) { res.torques[i] = z[i]; } return true; } }; } int main(int argc, char** argv) { ros::init(argc, argv, "balancer"); Balancer bal; ros::spin(); } <|endoftext|>
<commit_before>#include <yttrium/log.h> #include <yttrium/log_manager.h> #include <yttrium/date_time.h> #include <yttrium/file.h> #include <yttrium/pointer.h> #include "instance_guard.h" namespace Yttrium { class LogManagerImpl; using LogManagerGuard = InstanceGuard<LogManagerImpl>; class LogManagerImpl : public LogManager { public: LogManagerImpl(const StaticString& file_name, Allocator& allocator) : _allocator(allocator) , _std_err(File::StdErr, &_allocator) , _instance_guard(this, "Duplicate LogManager construction") { if (!file_name.is_empty()) _file = File(file_name, File::Write | File::Truncate, &_allocator); } Allocator& allocator() const { return _allocator; } void write(const StaticString& string) { _std_err.write(string.text(), string.size()); _file.write(string.text(), string.size()); _file.flush(); } private: Allocator& _allocator; File _std_err; File _file; LogManagerGuard _instance_guard; }; Pointer<LogManager> LogManager::create(const StaticString& file_name, Allocator& allocator) { return make_pointer<LogManagerImpl>(allocator, file_name, allocator); } Log::Log() : _message(64, LogManagerGuard::instance ? &LogManagerGuard::instance->allocator() : DefaultAllocator) // TODO: Lock mutex. { const auto& now = DateTime::now(); _message << '[' << dec(now.hour, 2) << ':' << dec(now.minute, 2) << ':' << dec(now.second, 2) << "] "_s; } Log::~Log() { _message << "\r\n"_s; std::lock_guard<std::mutex> lock(LogManagerGuard::instance_mutex); if (LogManagerGuard::instance) LogManagerGuard::instance->write(_message); } } <commit_msg>Logging doesn't need flushing.<commit_after>#include <yttrium/log.h> #include <yttrium/log_manager.h> #include <yttrium/date_time.h> #include <yttrium/file.h> #include <yttrium/pointer.h> #include "instance_guard.h" namespace Yttrium { class LogManagerImpl; using LogManagerGuard = InstanceGuard<LogManagerImpl>; class LogManagerImpl : public LogManager { public: LogManagerImpl(const StaticString& file_name, Allocator& allocator) : _allocator(allocator) , _std_err(File::StdErr, &_allocator) , _instance_guard(this, "Duplicate LogManager construction") { if (!file_name.is_empty()) _file = File(file_name, File::Write | File::Truncate, &_allocator); } Allocator& allocator() const { return _allocator; } void write(const StaticString& string) { _std_err.write(string.text(), string.size()); _file.write(string.text(), string.size()); } private: Allocator& _allocator; File _std_err; File _file; LogManagerGuard _instance_guard; }; Pointer<LogManager> LogManager::create(const StaticString& file_name, Allocator& allocator) { return make_pointer<LogManagerImpl>(allocator, file_name, allocator); } Log::Log() : _message(64, LogManagerGuard::instance ? &LogManagerGuard::instance->allocator() : DefaultAllocator) // TODO: Lock mutex. { const auto& now = DateTime::now(); _message << '[' << dec(now.hour, 2) << ':' << dec(now.minute, 2) << ':' << dec(now.second, 2) << "] "_s; } Log::~Log() { _message << "\r\n"_s; std::lock_guard<std::mutex> lock(LogManagerGuard::instance_mutex); if (LogManagerGuard::instance) LogManagerGuard::instance->write(_message); } } <|endoftext|>
<commit_before>/* * $Id$ */ #include <sys/time.h> #include <stdio.h> #include <fstream> #include <map> #include <list> #include <iostream> #include <sstream> #include <cmath> #include <set> #include "crf.h" #include "common.h" using namespace std; multimap<string, string> WNdic; void tokenize(const string &s1, list<string> &lt); string base_form(const string &s, const string &pos); extern int push_stop_watch(); static string normalize(const string &s) { string tmp(s); for (size_t i = 0; i < tmp.size(); i++) { tmp[i] = tolower(tmp[i]); if (isdigit(tmp[i])) tmp[i] = '#'; } return tmp; } static CRF_State crfstate(const vector<Token> &vt, int i) { CRF_State sample; string str = vt[i].str; sample.label = vt[i].pos; sample.add_feature("W0_" + vt[i].str); sample.add_feature("NW0_" + normalize(str)); string prestr = "BOS"; if (i > 0) prestr = vt[i - 1].str; string prestr2 = "BOS"; if (i > 1) prestr2 = vt[i - 2].str; string poststr = "EOS"; if (i < (int)vt.size() - 1) poststr = vt[i + 1].str; string poststr2 = "EOS"; if (i < (int)vt.size() - 2) poststr2 = vt[i + 2].str; sample.add_feature("W-1_" + prestr); sample.add_feature("W+1_" + poststr); sample.add_feature("W-2_" + prestr2); sample.add_feature("W+2_" + poststr2); sample.add_feature("W-10_" + prestr + "_" + str); sample.add_feature("W0+1_" + str + "_" + poststr); sample.add_feature("W-1+1_" + prestr + "_" + poststr); for (size_t j = 1; j <= 10; j++) { char buf[1000]; if (str.size() >= j) { sprintf(buf, "SUF%d_%s", (int)j, str.substr(str.size() - j).c_str()); sample.add_feature(buf); } if (str.size() >= j) { sprintf(buf, "PRE%d_%s", (int)j, str.substr(0, j).c_str()); sample.add_feature(buf); } } for (size_t j = 0; j < str.size(); j++) { if (isdigit(str[j])) { sample.add_feature("CTN_NUM"); break; } } for (size_t j = 0; j < str.size(); j++) { if (isupper(str[j])) { sample.add_feature("CTN_UPP"); break; } } for (size_t j = 0; j < str.size(); j++) { if (str[j] == '-') { sample.add_feature("CTN_HPN"); break; } } bool allupper = true; for (size_t j = 0; j < str.size(); j++) { if (!isupper(str[j])) { allupper = false; break; } } if (allupper) sample.add_feature("ALL_UPP"); if (WNdic.size() > 0) { const string n = normalize(str); for (map<string, string>::const_iterator i = WNdic.lower_bound(n); i != WNdic.upper_bound(n); i++) { sample.add_feature("WN_" + i->second); } } return sample; } int crftrain(const CRF_Model::OptimizationMethod method, CRF_Model &m, const vector<Sentence> &vs, double gaussian, const bool use_l1) { if (method != CRF_Model::BFGS && use_l1) { cerr << "error: L1 regularization is currently not supported in this mode. " "Please use other optimziation methods." << endl; exit(1); } for (vector<Sentence>::const_iterator i = vs.begin(); i != vs.end(); i++) { const Sentence &s = *i; CRF_Sequence cs; for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j)); m.add_training_sample(cs); } if (use_l1) m.train(method, 0, 0, 1.0); else m.train(method, 0, gaussian); return 0; } void crf_decode_lookahead(Sentence &s, CRF_Model &m, vector<map<string, double> > &tagp) { CRF_Sequence cs; for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j)); m.decode_lookahead(cs); tagp.clear(); for (size_t k = 0; k < s.size(); k++) { s[k].prd = cs.vs[k].label; map<string, double> vp; vp[s[k].prd] = 1.0; tagp.push_back(vp); } } void crf_decode_forward_backward(Sentence &s, CRF_Model &m, vector<map<string, double> > &tagp) { CRF_Sequence cs; for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j)); m.decode_forward_backward(cs, tagp); for (size_t k = 0; k < s.size(); k++) s[k].prd = cs.vs[k].label; } void crf_decode_nbest(Sentence &s, CRF_Model &m, vector<pair<double, vector<string> > > &nbest_seqs, int n) { CRF_Sequence cs; for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j)); m.decode_nbest(cs, nbest_seqs, n, 0); for (size_t k = 0; k < s.size(); k++) s[k].prd = cs.vs[k].label; } <commit_msg>pthread/crfpos.cpp: use !empty() instead of 'size() > 0'<commit_after>/* * $Id$ */ #include <sys/time.h> #include <stdio.h> #include <fstream> #include <map> #include <list> #include <iostream> #include <sstream> #include <cmath> #include <set> #include "crf.h" #include "common.h" using namespace std; multimap<string, string> WNdic; void tokenize(const string &s1, list<string> &lt); string base_form(const string &s, const string &pos); extern int push_stop_watch(); static string normalize(const string &s) { string tmp(s); for (size_t i = 0; i < tmp.size(); i++) { tmp[i] = tolower(tmp[i]); if (isdigit(tmp[i])) tmp[i] = '#'; } return tmp; } static CRF_State crfstate(const vector<Token> &vt, int i) { CRF_State sample; string str = vt[i].str; sample.label = vt[i].pos; sample.add_feature("W0_" + vt[i].str); sample.add_feature("NW0_" + normalize(str)); string prestr = "BOS"; if (i > 0) prestr = vt[i - 1].str; string prestr2 = "BOS"; if (i > 1) prestr2 = vt[i - 2].str; string poststr = "EOS"; if (i < (int)vt.size() - 1) poststr = vt[i + 1].str; string poststr2 = "EOS"; if (i < (int)vt.size() - 2) poststr2 = vt[i + 2].str; sample.add_feature("W-1_" + prestr); sample.add_feature("W+1_" + poststr); sample.add_feature("W-2_" + prestr2); sample.add_feature("W+2_" + poststr2); sample.add_feature("W-10_" + prestr + "_" + str); sample.add_feature("W0+1_" + str + "_" + poststr); sample.add_feature("W-1+1_" + prestr + "_" + poststr); for (size_t j = 1; j <= 10; j++) { char buf[1000]; if (str.size() >= j) { sprintf(buf, "SUF%d_%s", (int)j, str.substr(str.size() - j).c_str()); sample.add_feature(buf); } if (str.size() >= j) { sprintf(buf, "PRE%d_%s", (int)j, str.substr(0, j).c_str()); sample.add_feature(buf); } } for (size_t j = 0; j < str.size(); j++) { if (isdigit(str[j])) { sample.add_feature("CTN_NUM"); break; } } for (size_t j = 0; j < str.size(); j++) { if (isupper(str[j])) { sample.add_feature("CTN_UPP"); break; } } for (size_t j = 0; j < str.size(); j++) { if (str[j] == '-') { sample.add_feature("CTN_HPN"); break; } } bool allupper = true; for (size_t j = 0; j < str.size(); j++) { if (!isupper(str[j])) { allupper = false; break; } } if (allupper) sample.add_feature("ALL_UPP"); if (!WNdic.empty()) { const string n = normalize(str); for (map<string, string>::const_iterator i = WNdic.lower_bound(n); i != WNdic.upper_bound(n); i++) { sample.add_feature("WN_" + i->second); } } return sample; } int crftrain(const CRF_Model::OptimizationMethod method, CRF_Model &m, const vector<Sentence> &vs, double gaussian, const bool use_l1) { if (method != CRF_Model::BFGS && use_l1) { cerr << "error: L1 regularization is currently not supported in this mode. " "Please use other optimziation methods." << endl; exit(1); } for (vector<Sentence>::const_iterator i = vs.begin(); i != vs.end(); i++) { const Sentence &s = *i; CRF_Sequence cs; for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j)); m.add_training_sample(cs); } if (use_l1) m.train(method, 0, 0, 1.0); else m.train(method, 0, gaussian); return 0; } void crf_decode_lookahead(Sentence &s, CRF_Model &m, vector<map<string, double> > &tagp) { CRF_Sequence cs; for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j)); m.decode_lookahead(cs); tagp.clear(); for (size_t k = 0; k < s.size(); k++) { s[k].prd = cs.vs[k].label; map<string, double> vp; vp[s[k].prd] = 1.0; tagp.push_back(vp); } } void crf_decode_forward_backward(Sentence &s, CRF_Model &m, vector<map<string, double> > &tagp) { CRF_Sequence cs; for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j)); m.decode_forward_backward(cs, tagp); for (size_t k = 0; k < s.size(); k++) s[k].prd = cs.vs[k].label; } void crf_decode_nbest(Sentence &s, CRF_Model &m, vector<pair<double, vector<string> > > &nbest_seqs, int n) { CRF_Sequence cs; for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j)); m.decode_nbest(cs, nbest_seqs, n, 0); for (size_t k = 0; k < s.size(); k++) s[k].prd = cs.vs[k].label; } <|endoftext|>
<commit_before>/** * @file Dtw.cpp * * An implementation of the Dynamic Time Warping algorithm. * * This file is part of the Aquila DSP library. * Aquila is free software, licensed under the MIT/X11 License. A copy of * the license is provided with the library in the LICENSE file. * * @package Aquila * @version 3.0.0-dev * @author Zbigniew Siciarz * @date 2007-2014 * @license http://www.opensource.org/licenses/mit-license.php MIT * @since 0.5.7 */ #include "Dtw.h" namespace Aquila { /** * Computes the distance between two sets of data. * * @param from first vector of features * @param to second vector of features * @return double DTW distance */ double Dtw::getDistance(const DtwDataType& from, const DtwDataType& to) { m_fromSize = from.size(); m_toSize = to.size(); // fill the local distances array m_points.clear(); m_points.resize(m_fromSize); for (std::size_t i = 0; i < m_fromSize; ++i) { m_points[i].reserve(m_toSize); for (std::size_t j = 0; j < m_toSize; ++j) { // use emplace_back, once all compilers support it correctly m_points[i].push_back( DtwPoint(i, j, m_distanceFunction(from[i], to[j]) )); } } // the actual pathfinding algorithm DtwPoint *top = 0, *center = 0, *bottom = 0, *previous = 0; for (std::size_t i = 1; i < m_fromSize; ++i) { for (std::size_t j = 1; j < m_toSize; ++j) { center = &m_points[i - 1][j - 1]; if (Neighbors == m_passType) { top = &m_points[i - 1][j]; bottom = &m_points[i][j - 1]; } else // Diagonals { if (i > 1 && j > 1) { top = &m_points[i - 2][j - 1]; bottom = &m_points[i - 1][j - 2]; } else { top = &m_points[i - 1][j]; bottom = &m_points[i][j - 1]; } } if (top->dAccumulated < center->dAccumulated) { previous = top; } else { previous = center; } if (bottom->dAccumulated < previous->dAccumulated) { previous = bottom; } m_points[i][j].dAccumulated = m_points[i][j].dLocal + previous->dAccumulated; m_points[i][j].previous = previous; } } return getFinalPoint().dAccumulated; } /** * Returns the lowest-cost path in the DTW array. * * @return path */ DtwPathType Dtw::getPath() const { DtwPathType path; DtwPoint finalPoint = getFinalPoint(); DtwPoint* point = &finalPoint; path.push_back(*point); while(point->previous != 0) { point = point->previous; path.push_back(*point); } return path; } } <commit_msg>Be more explicit about null pointers in DTW.<commit_after>/** * @file Dtw.cpp * * An implementation of the Dynamic Time Warping algorithm. * * This file is part of the Aquila DSP library. * Aquila is free software, licensed under the MIT/X11 License. A copy of * the license is provided with the library in the LICENSE file. * * @package Aquila * @version 3.0.0-dev * @author Zbigniew Siciarz * @date 2007-2014 * @license http://www.opensource.org/licenses/mit-license.php MIT * @since 0.5.7 */ #include "Dtw.h" namespace Aquila { /** * Computes the distance between two sets of data. * * @param from first vector of features * @param to second vector of features * @return double DTW distance */ double Dtw::getDistance(const DtwDataType& from, const DtwDataType& to) { m_fromSize = from.size(); m_toSize = to.size(); // fill the local distances array m_points.clear(); m_points.resize(m_fromSize); for (std::size_t i = 0; i < m_fromSize; ++i) { m_points[i].reserve(m_toSize); for (std::size_t j = 0; j < m_toSize; ++j) { // use emplace_back, once all compilers support it correctly m_points[i].push_back( DtwPoint(i, j, m_distanceFunction(from[i], to[j]) )); } } // the actual pathfinding algorithm DtwPoint *top = nullptr, *center = nullptr, *bottom = nullptr, *previous = nullptr; for (std::size_t i = 1; i < m_fromSize; ++i) { for (std::size_t j = 1; j < m_toSize; ++j) { center = &m_points[i - 1][j - 1]; if (Neighbors == m_passType) { top = &m_points[i - 1][j]; bottom = &m_points[i][j - 1]; } else // Diagonals { if (i > 1 && j > 1) { top = &m_points[i - 2][j - 1]; bottom = &m_points[i - 1][j - 2]; } else { top = &m_points[i - 1][j]; bottom = &m_points[i][j - 1]; } } if (top->dAccumulated < center->dAccumulated) { previous = top; } else { previous = center; } if (bottom->dAccumulated < previous->dAccumulated) { previous = bottom; } m_points[i][j].dAccumulated = m_points[i][j].dLocal + previous->dAccumulated; m_points[i][j].previous = previous; } } return getFinalPoint().dAccumulated; } /** * Returns the lowest-cost path in the DTW array. * * @return path */ DtwPathType Dtw::getPath() const { DtwPathType path; DtwPoint finalPoint = getFinalPoint(); DtwPoint* point = &finalPoint; path.push_back(*point); while(point->previous) { point = point->previous; path.push_back(*point); } return path; } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include "config.h" #include "ep.hh" const double BgFetcher::sleepInterval = 1.0; bool BgFetcherCallback::callback(Dispatcher &, TaskId t) { return bgfetcher->run(t); } void BgFetcher::start() { LockHolder lh(taskMutex); dispatcher->schedule(shared_ptr<BgFetcherCallback>(new BgFetcherCallback(this)), &task, Priority::BgFetcherPriority); assert(task.get()); } void BgFetcher::stop() { LockHolder lh(taskMutex); assert(task.get()); dispatcher->cancel(task); } void BgFetcher::doFetch(uint16_t vbId) { hrtime_t startTime(gethrtime()); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "BgFetcher is fetching data, vBucket = %d numDocs = %d, " "startTime = %lld\n", vbId, items2fetch.size(), startTime/1000000); store->getROUnderlying()->getMulti(vbId, items2fetch); int totalfetches = 0; std::vector<VBucketBGFetchItem *> fetchedItems; vb_bgfetch_queue_t::iterator itr = items2fetch.begin(); for (; itr != items2fetch.end(); itr++) { std::list<VBucketBGFetchItem *> &requestedItems = (*itr).second; std::list<VBucketBGFetchItem *>::iterator itm = requestedItems.begin(); for(; itm != requestedItems.end(); itm++) { fetchedItems.push_back(*itm); ++totalfetches; } } store->completeBGFetchMulti(vbId, fetchedItems, startTime); stats.getMultiHisto.add(startTime-gethrtime()/1000, totalfetches); clearItems(); } void BgFetcher::clearItems(void) { vb_bgfetch_queue_t::iterator itr = items2fetch.begin(); for(; itr != items2fetch.end(); itr++) { // every fetched item belonging to the same seq_id shares // the same buffer, just delete it from the first fetched item std::list<VBucketBGFetchItem *> &doneItems = (*itr).second; VBucketBGFetchItem *firstItem = doneItems.front(); delete firstItem; } } bool BgFetcher::run(TaskId tid) { assert(tid.get()); size_t num_fetched_items = 0; const VBucketMap &vbMap = store->getVBuckets(); size_t numVbuckets = vbMap.getSize(); for (size_t vbid = 0; vbid < numVbuckets; vbid++) { RCPtr<VBucket> vb = vbMap.getBucket(vbid); assert(items2fetch.empty()); if (vb && vb->getBGFetchItems(items2fetch)) { doFetch(vbid); num_fetched_items += items2fetch.size(); items2fetch.clear(); } } size_t remains = stats.numRemainingBgJobs.decr(num_fetched_items); if (!pendingJob()) { stats.numRemainingBgJobs.cas(remains, 0); // Reset the remaining counter // wait a bit until next fetche request arrives double sleep = std::max(store->getBGFetchDelay(), sleepInterval); dispatcher->snooze(tid, sleep); } return true; } bool BgFetcher::pendingJob() { const VBucketMap &vbMap = store->getVBuckets(); size_t numVbuckets = vbMap.getSize(); for (size_t vbid = 0; vbid < numVbuckets; ++vbid) { RCPtr<VBucket> vb = vbMap.getBucket(vbid); if (vb && vb->hasPendingBGFetchItems()) { return true; } } return false; } <commit_msg>Fix BG fetcher histogram computation<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include "config.h" #include "ep.hh" const double BgFetcher::sleepInterval = 1.0; bool BgFetcherCallback::callback(Dispatcher &, TaskId t) { return bgfetcher->run(t); } void BgFetcher::start() { LockHolder lh(taskMutex); dispatcher->schedule(shared_ptr<BgFetcherCallback>(new BgFetcherCallback(this)), &task, Priority::BgFetcherPriority); assert(task.get()); } void BgFetcher::stop() { LockHolder lh(taskMutex); assert(task.get()); dispatcher->cancel(task); } void BgFetcher::doFetch(uint16_t vbId) { hrtime_t startTime(gethrtime()); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "BgFetcher is fetching data, vBucket = %d numDocs = %d, " "startTime = %lld\n", vbId, items2fetch.size(), startTime/1000000); store->getROUnderlying()->getMulti(vbId, items2fetch); int totalfetches = 0; std::vector<VBucketBGFetchItem *> fetchedItems; vb_bgfetch_queue_t::iterator itr = items2fetch.begin(); for (; itr != items2fetch.end(); itr++) { std::list<VBucketBGFetchItem *> &requestedItems = (*itr).second; std::list<VBucketBGFetchItem *>::iterator itm = requestedItems.begin(); for(; itm != requestedItems.end(); itm++) { fetchedItems.push_back(*itm); ++totalfetches; } } store->completeBGFetchMulti(vbId, fetchedItems, startTime); stats.getMultiHisto.add((gethrtime()-startTime)/1000, totalfetches); clearItems(); } void BgFetcher::clearItems(void) { vb_bgfetch_queue_t::iterator itr = items2fetch.begin(); for(; itr != items2fetch.end(); itr++) { // every fetched item belonging to the same seq_id shares // the same buffer, just delete it from the first fetched item std::list<VBucketBGFetchItem *> &doneItems = (*itr).second; VBucketBGFetchItem *firstItem = doneItems.front(); delete firstItem; } } bool BgFetcher::run(TaskId tid) { assert(tid.get()); size_t num_fetched_items = 0; const VBucketMap &vbMap = store->getVBuckets(); size_t numVbuckets = vbMap.getSize(); for (size_t vbid = 0; vbid < numVbuckets; vbid++) { RCPtr<VBucket> vb = vbMap.getBucket(vbid); assert(items2fetch.empty()); if (vb && vb->getBGFetchItems(items2fetch)) { doFetch(vbid); num_fetched_items += items2fetch.size(); items2fetch.clear(); } } size_t remains = stats.numRemainingBgJobs.decr(num_fetched_items); if (!pendingJob()) { stats.numRemainingBgJobs.cas(remains, 0); // Reset the remaining counter // wait a bit until next fetche request arrives double sleep = std::max(store->getBGFetchDelay(), sleepInterval); dispatcher->snooze(tid, sleep); } return true; } bool BgFetcher::pendingJob() { const VBucketMap &vbMap = store->getVBuckets(); size_t numVbuckets = vbMap.getSize(); for (size_t vbid = 0; vbid < numVbuckets; ++vbid) { RCPtr<VBucket> vb = vbMap.getBucket(vbid); if (vb && vb->hasPendingBGFetchItems()) { return true; } } return false; } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "processcontrol.h" #include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtDebug> #ifdef Q_OS_UNIX #include <sys/types.h> #include <signal.h> #endif using namespace Akonadi; ProcessControl::ProcessControl( QObject *parent ) : QObject( parent ), mFailedToStart( false ), mCrashCount( 0 ) { connect( &mProcess, SIGNAL( error( QProcess::ProcessError ) ), this, SLOT( slotError( QProcess::ProcessError ) ) ); connect( &mProcess, SIGNAL( finished( int, QProcess::ExitStatus ) ), this, SLOT( slotFinished( int, QProcess::ExitStatus ) ) ); connect( &mProcess, SIGNAL( readyReadStandardError() ), this, SLOT( slotErrorMessages() ) ); connect( &mProcess, SIGNAL( readyReadStandardOutput() ), this, SLOT( slotStdoutMessages() ) ); } ProcessControl::~ProcessControl() { stop(); } void ProcessControl::start( const QString &application, const QStringList &arguments, CrashPolicy policy ) { mFailedToStart = false; mApplication = application; mArguments = arguments; mPolicy = policy; start(); } void ProcessControl::setCrashPolicy( CrashPolicy policy ) { mPolicy = policy; } void ProcessControl::stop() { if ( mProcess.state() != QProcess::NotRunning ) { mProcess.waitForFinished( 10000 ); mProcess.terminate(); } } void ProcessControl::slotError( QProcess::ProcessError error ) { switch ( error ) { case QProcess::Crashed: // do nothing, we'll respawn in slotFinished break; case QProcess::FailedToStart: default: mFailedToStart = true; break; } qDebug( "ProcessControl: Application '%s' stopped unexpected (%s)", qPrintable( mApplication ), qPrintable( mProcess.errorString() ) ); } void ProcessControl::slotFinished( int exitCode, QProcess::ExitStatus exitStatus ) { if ( exitStatus == QProcess::CrashExit ) { if ( mPolicy == RestartOnCrash ) { if ( !mFailedToStart ) // don't try to start an unstartable application start(); } } else { if ( exitCode != 0 ) { qDebug( "ProcessControl: Application '%s' returned with exit code %d (%s)", qPrintable( mApplication ), exitCode, qPrintable( mProcess.errorString() ) ); if ( mPolicy == RestartOnCrash ) { if ( mCrashCount > 3 ) { qWarning() << mApplication << "crashed too often and will not be restarted!"; mPolicy = StopOnCrash; return; } ++mCrashCount; QTimer::singleShot( 5000, this, SLOT(resetCrashCount()) ); if ( !mFailedToStart ) // don't try to start an unstartable application start(); } } else { qDebug( "Application '%s' exited normally...", qPrintable( mApplication ) ); } } } void ProcessControl::slotErrorMessages() { QString message = QString::fromUtf8( mProcess.readAllStandardError() ); emit processErrorMessages( message ); qDebug( "[%s] %s", qPrintable( mApplication ), qPrintable( message.trimmed() ) ); } void ProcessControl::start() { #ifdef Q_OS_UNIX QString agentValgrind = QString::fromLocal8Bit( qgetenv("AKONADI_VALGRIND") ); if ( !agentValgrind.isEmpty() && mApplication.contains( agentValgrind ) ) { qDebug(); qDebug() << "============================================================"; qDebug() << "ProcessControl: Valgrinding process" << mApplication; qDebug() << "============================================================"; qDebug(); QString valgrindSkin = QString::fromLocal8Bit( qgetenv( "AKONADI_VALGRIND_SKIN" ) ); mArguments.prepend( mApplication ); mApplication = QString::fromLocal8Bit( "valgrind" ); if ( !valgrindSkin.isEmpty() ) mArguments.prepend( QLatin1String( "--tool=" ) + valgrindSkin ); else mArguments.prepend (QLatin1String( "--tool=memcheck") ); } #endif mProcess.start( mApplication, mArguments ); if ( !mProcess.waitForStarted( ) ) { qDebug( "ProcessControl: Unable to start application '%s' (%s)", qPrintable( mApplication ), qPrintable( mProcess.errorString() ) ); return; } #ifdef Q_OS_UNIX else { QString agentDebug = QString::fromLocal8Bit( qgetenv( "AKONADI_DEBUG_WAIT" ) ); pid_t pid = mProcess.pid(); if ( !agentDebug.isEmpty() && mApplication.contains( agentDebug ) ) { qDebug(); qDebug() << "============================================================"; qDebug() << "ProcessControl: Suspending process" << mApplication; qDebug() << "'gdb" << pid << "' to debug"; qDebug() << "'kill -SIGCONT" << pid << "' to continue"; qDebug() << "============================================================"; qDebug(); kill( pid, SIGSTOP ); } } #endif } void Akonadi::ProcessControl::slotStdoutMessages() { QString message = QString::fromUtf8( mProcess.readAllStandardOutput() ); qDebug() << mApplication << "[out]" << message; } void ProcessControl::resetCrashCount() { mCrashCount = 0; } #include "processcontrol.moc" <commit_msg>Up the time for the crash timer reset to one minute. Now it actually seems to work for me.<commit_after>/*************************************************************************** * Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "processcontrol.h" #include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtDebug> #ifdef Q_OS_UNIX #include <sys/types.h> #include <signal.h> #endif using namespace Akonadi; ProcessControl::ProcessControl( QObject *parent ) : QObject( parent ), mFailedToStart( false ), mCrashCount( 0 ) { connect( &mProcess, SIGNAL( error( QProcess::ProcessError ) ), this, SLOT( slotError( QProcess::ProcessError ) ) ); connect( &mProcess, SIGNAL( finished( int, QProcess::ExitStatus ) ), this, SLOT( slotFinished( int, QProcess::ExitStatus ) ) ); connect( &mProcess, SIGNAL( readyReadStandardError() ), this, SLOT( slotErrorMessages() ) ); connect( &mProcess, SIGNAL( readyReadStandardOutput() ), this, SLOT( slotStdoutMessages() ) ); } ProcessControl::~ProcessControl() { stop(); } void ProcessControl::start( const QString &application, const QStringList &arguments, CrashPolicy policy ) { mFailedToStart = false; mApplication = application; mArguments = arguments; mPolicy = policy; start(); } void ProcessControl::setCrashPolicy( CrashPolicy policy ) { mPolicy = policy; } void ProcessControl::stop() { if ( mProcess.state() != QProcess::NotRunning ) { mProcess.waitForFinished( 10000 ); mProcess.terminate(); } } void ProcessControl::slotError( QProcess::ProcessError error ) { switch ( error ) { case QProcess::Crashed: // do nothing, we'll respawn in slotFinished break; case QProcess::FailedToStart: default: mFailedToStart = true; break; } qDebug( "ProcessControl: Application '%s' stopped unexpected (%s)", qPrintable( mApplication ), qPrintable( mProcess.errorString() ) ); } void ProcessControl::slotFinished( int exitCode, QProcess::ExitStatus exitStatus ) { if ( exitStatus == QProcess::CrashExit ) { if ( mPolicy == RestartOnCrash ) { if ( !mFailedToStart ) // don't try to start an unstartable application start(); } } else { if ( exitCode != 0 ) { qDebug( "ProcessControl: Application '%s' returned with exit code %d (%s)", qPrintable( mApplication ), exitCode, qPrintable( mProcess.errorString() ) ); if ( mPolicy == RestartOnCrash ) { if ( mCrashCount > 3 ) { qWarning() << mApplication << "crashed too often and will not be restarted!"; mPolicy = StopOnCrash; return; } ++mCrashCount; QTimer::singleShot( 60000, this, SLOT(resetCrashCount()) ); if ( !mFailedToStart ) // don't try to start an unstartable application start(); } } else { qDebug( "Application '%s' exited normally...", qPrintable( mApplication ) ); } } } void ProcessControl::slotErrorMessages() { QString message = QString::fromUtf8( mProcess.readAllStandardError() ); emit processErrorMessages( message ); qDebug( "[%s] %s", qPrintable( mApplication ), qPrintable( message.trimmed() ) ); } void ProcessControl::start() { #ifdef Q_OS_UNIX QString agentValgrind = QString::fromLocal8Bit( qgetenv("AKONADI_VALGRIND") ); if ( !agentValgrind.isEmpty() && mApplication.contains( agentValgrind ) ) { qDebug(); qDebug() << "============================================================"; qDebug() << "ProcessControl: Valgrinding process" << mApplication; qDebug() << "============================================================"; qDebug(); QString valgrindSkin = QString::fromLocal8Bit( qgetenv( "AKONADI_VALGRIND_SKIN" ) ); mArguments.prepend( mApplication ); mApplication = QString::fromLocal8Bit( "valgrind" ); if ( !valgrindSkin.isEmpty() ) mArguments.prepend( QLatin1String( "--tool=" ) + valgrindSkin ); else mArguments.prepend (QLatin1String( "--tool=memcheck") ); } #endif mProcess.start( mApplication, mArguments ); if ( !mProcess.waitForStarted( ) ) { qDebug( "ProcessControl: Unable to start application '%s' (%s)", qPrintable( mApplication ), qPrintable( mProcess.errorString() ) ); return; } #ifdef Q_OS_UNIX else { QString agentDebug = QString::fromLocal8Bit( qgetenv( "AKONADI_DEBUG_WAIT" ) ); pid_t pid = mProcess.pid(); if ( !agentDebug.isEmpty() && mApplication.contains( agentDebug ) ) { qDebug(); qDebug() << "============================================================"; qDebug() << "ProcessControl: Suspending process" << mApplication; qDebug() << "'gdb" << pid << "' to debug"; qDebug() << "'kill -SIGCONT" << pid << "' to continue"; qDebug() << "============================================================"; qDebug(); kill( pid, SIGSTOP ); } } #endif } void Akonadi::ProcessControl::slotStdoutMessages() { QString message = QString::fromUtf8( mProcess.readAllStandardOutput() ); qDebug() << mApplication << "[out]" << message; } void ProcessControl::resetCrashCount() { mCrashCount = 0; } #include "processcontrol.moc" <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/phy_cntrl.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file phy_cntrl.C /// @brief Subroutines for the PHY PC registers /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <lib/phy/phy_cntrl.H> #include <generic/memory/lib/utils/scom.H> #include <generic/memory/lib/utils/c_str.H> #include <lib/utils/index.H> #include <lib/mss_attribute_accessors.H> using fapi2::TARGET_TYPE_MCA; namespace mss { // Definition of the PHY PC MR shadow registers // indexed by [rank_pair][MR index] const std::vector< std::vector<uint64_t> > pcTraits<TARGET_TYPE_MCA>::PC_MR_SHADOW_REGS = { { MCA_DDRPHY_PC_MR0_PRI_RP0_P0, MCA_DDRPHY_PC_MR1_PRI_RP0_P0, MCA_DDRPHY_PC_MR2_PRI_RP0_P0, MCA_DDRPHY_PC_MR3_PRI_RP0_P0, MCA_DDRPHY_PC_MR0_SEC_RP0_P0, MCA_DDRPHY_PC_MR1_SEC_RP0_P0, MCA_DDRPHY_PC_MR2_SEC_RP0_P0, }, { MCA_DDRPHY_PC_MR0_PRI_RP1_P0, MCA_DDRPHY_PC_MR1_PRI_RP1_P0, MCA_DDRPHY_PC_MR2_PRI_RP1_P0, MCA_DDRPHY_PC_MR3_PRI_RP1_P0, MCA_DDRPHY_PC_MR0_SEC_RP1_P0, MCA_DDRPHY_PC_MR1_SEC_RP1_P0, MCA_DDRPHY_PC_MR2_SEC_RP1_P0, }, { MCA_DDRPHY_PC_MR0_PRI_RP2_P0, MCA_DDRPHY_PC_MR1_PRI_RP2_P0, MCA_DDRPHY_PC_MR2_PRI_RP2_P0, MCA_DDRPHY_PC_MR3_PRI_RP2_P0, MCA_DDRPHY_PC_MR0_SEC_RP2_P0, MCA_DDRPHY_PC_MR1_SEC_RP2_P0, MCA_DDRPHY_PC_MR2_SEC_RP2_P0, }, { MCA_DDRPHY_PC_MR0_PRI_RP3_P0, MCA_DDRPHY_PC_MR1_PRI_RP3_P0, MCA_DDRPHY_PC_MR2_PRI_RP3_P0, MCA_DDRPHY_PC_MR3_PRI_RP3_P0, MCA_DDRPHY_PC_MR0_SEC_RP3_P0, MCA_DDRPHY_PC_MR1_SEC_RP3_P0, MCA_DDRPHY_PC_MR2_SEC_RP3_P0, }, }; namespace pc { /// /// @brief Reset the PC CONFIG0 register /// @param[in] i_target the target (MCA or MBA?) /// @return FAPI2_RC_SUCCESS if and only if ok /// template<> fapi2::ReturnCode reset_config0(const fapi2::Target<TARGET_TYPE_MCA>& i_target) { typedef pcTraits<TARGET_TYPE_MCA> TT; fapi2::buffer<uint64_t> l_data; l_data.setBit<TT::DDR4_CMD_SIG_REDUCTION>(); l_data.setBit<TT::DDR4_VLEVEL_BANK_GROUP>(); FAPI_TRY( write_config0(i_target, l_data) ); fapi_try_exit: return fapi2::current_err; } /// /// @brief Reset the PC CONFIG1 register /// @param[in] i_target <the target (MCA or MBA?) /// @return FAPI2_RC_SUCCESS if and only if ok /// template<> fapi2::ReturnCode reset_config1(const fapi2::Target<TARGET_TYPE_MCA>& i_target) { typedef pcTraits<TARGET_TYPE_MCA> TT; // Static table of PHY config values for MEMORY_TYPE. // [EMPTY, RDIMM, CDIMM, or LRDIMM][EMPTY, DDR3 or DDR4] constexpr uint64_t memory_type[4][3] = { { 0, 0, 0 }, // Empty, never really used. { 0, 0b001, 0b101 }, // RDIMM { 0, 0b000, 0b000 }, // CDIMM bits, UDIMM enum (placeholder, never used on Nimbus) { 0, 0b011, 0b111 }, // LRDIMM }; fapi2::buffer<uint64_t> l_data; uint8_t l_rlo = 0; uint8_t l_wlo = 0; uint8_t l_dram_gen[MAX_DIMM_PER_PORT] = {0}; uint8_t l_dimm_type[MAX_DIMM_PER_PORT] = {0}; uint8_t l_type_index = 0; uint8_t l_gen_index = 0; FAPI_TRY( mss::vpd_mr_dphy_rlo(i_target, l_rlo) ); FAPI_TRY( mss::vpd_mr_dphy_wlo(i_target, l_wlo) ); FAPI_TRY( mss::eff_dram_gen(i_target, &(l_dram_gen[0])) ); FAPI_TRY( mss::eff_dimm_type(i_target, &(l_dimm_type[0])) ); // There's no way to configure the PHY for more than one value. However, we don't know if there's // a DIMM in one slot, the other or double drop. So we do a little gyration here to make sure // we have one of the two values (and assume effective config caught a bad config) l_type_index = l_dimm_type[0] | l_dimm_type[1]; l_gen_index = l_dram_gen[0] | l_dram_gen[1]; // FOR NIMBUS PHY (as the protocol choice above is) BRS FAPI_TRY( mss::getScom(i_target, MCA_DDRPHY_PC_CONFIG1_P0, l_data) ); l_data.insertFromRight<TT::MEMORY_TYPE, TT::MEMORY_TYPE_LEN>(memory_type[l_type_index][l_gen_index]); l_data.insertFromRight<TT::WRITE_LATENCY_OFFSET, TT::WRITE_LATENCY_OFFSET_LEN>(l_wlo); // Always set this bit. It forces the PHY to use A12 when figuring out latency. This makes sense in // all cases as A12 is 0 for non-3DS in MR0. l_data.setBit<TT::DDR4_LATENCY_SW>(); // If we are 2N mode we add one to the RLO (see also Centaur initfile) l_data.insertFromRight<TT::READ_LATENCY_OFFSET, TT::READ_LATENCY_OFFSET_LEN>( mss::two_n_mode_helper(i_target) ? l_rlo + 1 : l_rlo); FAPI_TRY( write_config1(i_target, l_data) ); fapi_try_exit: return fapi2::current_err; } } // close namespace pc } // close namespace mss <commit_msg>Move index API to generic/memory folder<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/phy_cntrl.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file phy_cntrl.C /// @brief Subroutines for the PHY PC registers /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <lib/phy/phy_cntrl.H> #include <generic/memory/lib/utils/scom.H> #include <generic/memory/lib/utils/c_str.H> #include <generic/memory/lib/utils/index.H> #include <lib/mss_attribute_accessors.H> using fapi2::TARGET_TYPE_MCA; namespace mss { // Definition of the PHY PC MR shadow registers // indexed by [rank_pair][MR index] const std::vector< std::vector<uint64_t> > pcTraits<TARGET_TYPE_MCA>::PC_MR_SHADOW_REGS = { { MCA_DDRPHY_PC_MR0_PRI_RP0_P0, MCA_DDRPHY_PC_MR1_PRI_RP0_P0, MCA_DDRPHY_PC_MR2_PRI_RP0_P0, MCA_DDRPHY_PC_MR3_PRI_RP0_P0, MCA_DDRPHY_PC_MR0_SEC_RP0_P0, MCA_DDRPHY_PC_MR1_SEC_RP0_P0, MCA_DDRPHY_PC_MR2_SEC_RP0_P0, }, { MCA_DDRPHY_PC_MR0_PRI_RP1_P0, MCA_DDRPHY_PC_MR1_PRI_RP1_P0, MCA_DDRPHY_PC_MR2_PRI_RP1_P0, MCA_DDRPHY_PC_MR3_PRI_RP1_P0, MCA_DDRPHY_PC_MR0_SEC_RP1_P0, MCA_DDRPHY_PC_MR1_SEC_RP1_P0, MCA_DDRPHY_PC_MR2_SEC_RP1_P0, }, { MCA_DDRPHY_PC_MR0_PRI_RP2_P0, MCA_DDRPHY_PC_MR1_PRI_RP2_P0, MCA_DDRPHY_PC_MR2_PRI_RP2_P0, MCA_DDRPHY_PC_MR3_PRI_RP2_P0, MCA_DDRPHY_PC_MR0_SEC_RP2_P0, MCA_DDRPHY_PC_MR1_SEC_RP2_P0, MCA_DDRPHY_PC_MR2_SEC_RP2_P0, }, { MCA_DDRPHY_PC_MR0_PRI_RP3_P0, MCA_DDRPHY_PC_MR1_PRI_RP3_P0, MCA_DDRPHY_PC_MR2_PRI_RP3_P0, MCA_DDRPHY_PC_MR3_PRI_RP3_P0, MCA_DDRPHY_PC_MR0_SEC_RP3_P0, MCA_DDRPHY_PC_MR1_SEC_RP3_P0, MCA_DDRPHY_PC_MR2_SEC_RP3_P0, }, }; namespace pc { /// /// @brief Reset the PC CONFIG0 register /// @param[in] i_target the target (MCA or MBA?) /// @return FAPI2_RC_SUCCESS if and only if ok /// template<> fapi2::ReturnCode reset_config0(const fapi2::Target<TARGET_TYPE_MCA>& i_target) { typedef pcTraits<TARGET_TYPE_MCA> TT; fapi2::buffer<uint64_t> l_data; l_data.setBit<TT::DDR4_CMD_SIG_REDUCTION>(); l_data.setBit<TT::DDR4_VLEVEL_BANK_GROUP>(); FAPI_TRY( write_config0(i_target, l_data) ); fapi_try_exit: return fapi2::current_err; } /// /// @brief Reset the PC CONFIG1 register /// @param[in] i_target <the target (MCA or MBA?) /// @return FAPI2_RC_SUCCESS if and only if ok /// template<> fapi2::ReturnCode reset_config1(const fapi2::Target<TARGET_TYPE_MCA>& i_target) { typedef pcTraits<TARGET_TYPE_MCA> TT; // Static table of PHY config values for MEMORY_TYPE. // [EMPTY, RDIMM, CDIMM, or LRDIMM][EMPTY, DDR3 or DDR4] constexpr uint64_t memory_type[4][3] = { { 0, 0, 0 }, // Empty, never really used. { 0, 0b001, 0b101 }, // RDIMM { 0, 0b000, 0b000 }, // CDIMM bits, UDIMM enum (placeholder, never used on Nimbus) { 0, 0b011, 0b111 }, // LRDIMM }; fapi2::buffer<uint64_t> l_data; uint8_t l_rlo = 0; uint8_t l_wlo = 0; uint8_t l_dram_gen[MAX_DIMM_PER_PORT] = {0}; uint8_t l_dimm_type[MAX_DIMM_PER_PORT] = {0}; uint8_t l_type_index = 0; uint8_t l_gen_index = 0; FAPI_TRY( mss::vpd_mr_dphy_rlo(i_target, l_rlo) ); FAPI_TRY( mss::vpd_mr_dphy_wlo(i_target, l_wlo) ); FAPI_TRY( mss::eff_dram_gen(i_target, &(l_dram_gen[0])) ); FAPI_TRY( mss::eff_dimm_type(i_target, &(l_dimm_type[0])) ); // There's no way to configure the PHY for more than one value. However, we don't know if there's // a DIMM in one slot, the other or double drop. So we do a little gyration here to make sure // we have one of the two values (and assume effective config caught a bad config) l_type_index = l_dimm_type[0] | l_dimm_type[1]; l_gen_index = l_dram_gen[0] | l_dram_gen[1]; // FOR NIMBUS PHY (as the protocol choice above is) BRS FAPI_TRY( mss::getScom(i_target, MCA_DDRPHY_PC_CONFIG1_P0, l_data) ); l_data.insertFromRight<TT::MEMORY_TYPE, TT::MEMORY_TYPE_LEN>(memory_type[l_type_index][l_gen_index]); l_data.insertFromRight<TT::WRITE_LATENCY_OFFSET, TT::WRITE_LATENCY_OFFSET_LEN>(l_wlo); // Always set this bit. It forces the PHY to use A12 when figuring out latency. This makes sense in // all cases as A12 is 0 for non-3DS in MR0. l_data.setBit<TT::DDR4_LATENCY_SW>(); // If we are 2N mode we add one to the RLO (see also Centaur initfile) l_data.insertFromRight<TT::READ_LATENCY_OFFSET, TT::READ_LATENCY_OFFSET_LEN>( mss::two_n_mode_helper(i_target) ? l_rlo + 1 : l_rlo); FAPI_TRY( write_config1(i_target, l_data) ); fapi_try_exit: return fapi2::current_err; } } // close namespace pc } // close namespace mss <|endoftext|>
<commit_before>#include "config.h" #include <stddef.h> #ifdef _WIN32 #include <io.h> #else #include <fcntl.h> #endif #include "config.pb.h" #include "util.h" #include "google/protobuf/io/zero_copy_stream_impl.h" #include "google/protobuf/text_format.h" namespace grr { ClientConfig::ClientConfig(const std::string& configuration_file) : configuration_filename_(configuration_file) {} bool ClientConfig::ReadConfig() { ClientConfiguration proto; if (!MergeConfigFile(configuration_filename_, &proto)) { GOOGLE_LOG(ERROR) << "Unable to read config:" << configuration_filename_; return false; } std::unique_lock<std::mutex> l(lock_); writeback_filename_ = proto.writeback_filename(); if (!writeback_filename_.empty()) { if (!MergeConfigFile(writeback_filename_, &proto)) { GOOGLE_LOG(ERROR) << "Unable to read writeback:" << writeback_filename_; } } else { GOOGLE_LOG(WARNING) << "No writeback filename. Writeback disabled."; } subprocess_config_ = proto.subprocess_config(); last_server_cert_serial_number_ = proto.last_server_cert_serial_number(); control_urls_ = proto.control_url(); proxy_servers_ = proto.proxy_server(); key_.FromPEM(proto.client_private_key_pem()); ca_cert_.FromPEM(proto.ca_cert_pem()); client_id_ = MakeClientId(); if (control_urls_.empty()) { GOOGLE_LOG(ERROR) << "No control URLs."; return false; } if (ca_cert_.get() == NULL) { GOOGLE_LOG(ERROR) << "Missing or bad ca cert."; return false; } return true; } bool ClientConfig::CheckUpdateServerSerial(int new_serial) { std::unique_lock<std::mutex> l(lock_); if (new_serial < last_server_cert_serial_number_) { return false; } if (new_serial > last_server_cert_serial_number_) { last_server_cert_serial_number_ = new_serial; return WriteBackConfig(); } return true; } bool ClientConfig::ResetKey() { std::unique_lock<std::mutex> l(lock_); if (!key_.Generate()) { return false; } client_id_ = MakeClientId(); return WriteBackConfig(); } std::vector<std::string> ClientConfig::ControlUrls() const { std::unique_lock<std::mutex> l(lock_); return std::vector<std::string>(control_urls_.begin(), control_urls_.end()); } std::vector<std::string> ClientConfig::ProxyServers() const { std::unique_lock<std::mutex> l(lock_); return std::vector<std::string>(proxy_servers_.begin(), proxy_servers_.end()); } ClientConfiguration::SubprocessConfig ClientConfig::SubprocessConfig() const { std::unique_lock<std::mutex> l(lock_); return subprocess_config_; } bool ClientConfig::WriteBackConfig() { if (writeback_filename_.empty()) { return true; } int fd = open(writeback_filename_.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IWUSR | S_IRUSR); if (fd < 0) { GOOGLE_LOG(ERROR) << "Unable to open writeback: " << writeback_filename_; return false; } // Re-read the original configuration file, so we can tell what has changed. ClientConfiguration base_config; if (!MergeConfigFile(configuration_filename_, &base_config)) { GOOGLE_LOG(ERROR) << "Unable to read config: " << configuration_filename_; } // Currently only 2 fields can be changed through the config interface. ClientConfiguration proto; if (base_config.last_server_cert_serial_number() != last_server_cert_serial_number_) { proto.set_last_server_cert_serial_number(last_server_cert_serial_number_); } std::string key_pem = key_.ToStringPEM(); if (base_config.client_private_key_pem() != key_pem) { proto.set_client_private_key_pem(key_pem); } google::protobuf::io::FileOutputStream output(fd); bool result = google::protobuf::TextFormat::Print(proto, &output); output.Close(); return result; } std::string ClientConfig::MakeClientId() { if (!key_.get()) { return ""; } return "C." + BytesToHex(Digest::Sha256(key_.PublicKeyN()).substr(0, 8)); } bool ClientConfig::MergeConfigFile(const std::string& config_file, ClientConfiguration* config) { int fd = open(config_file.c_str(), O_RDONLY); if (fd < 0) { GOOGLE_LOG(ERROR) << "Failed to open:" << config_file; return false; } google::protobuf::io::FileInputStream input(fd); if (!google::protobuf::TextFormat::Merge(&input, config)) { GOOGLE_LOG(ERROR) << "Failed to parse:" << config_file; input.Close(); return false; } input.Close(); return true; } } // namespace grr <commit_msg>Fix compatibility with older versions of proto library.<commit_after>#include "config.h" #include <stddef.h> #ifdef _WIN32 #include <io.h> #else #include <fcntl.h> #endif #include "config.pb.h" #include "util.h" #include "google/protobuf/io/zero_copy_stream_impl.h" #include "google/protobuf/text_format.h" namespace grr { ClientConfig::ClientConfig(const std::string& configuration_file) : configuration_filename_(configuration_file) {} bool ClientConfig::ReadConfig() { ClientConfiguration proto; if (!MergeConfigFile(configuration_filename_, &proto)) { GOOGLE_LOG(ERROR) << "Unable to read config:" << configuration_filename_; return false; } std::unique_lock<std::mutex> l(lock_); writeback_filename_ = proto.writeback_filename(); if (!writeback_filename_.empty()) { if (!MergeConfigFile(writeback_filename_, &proto)) { GOOGLE_LOG(ERROR) << "Unable to read writeback:" << writeback_filename_; } } else { GOOGLE_LOG(WARNING) << "No writeback filename. Writeback disabled."; } subprocess_config_ = proto.subprocess_config(); last_server_cert_serial_number_ = proto.last_server_cert_serial_number(); control_urls_ = proto.control_url(); proxy_servers_ = proto.proxy_server(); key_.FromPEM(proto.client_private_key_pem()); ca_cert_.FromPEM(proto.ca_cert_pem()); client_id_ = MakeClientId(); if (!control_urls_.size()) { GOOGLE_LOG(ERROR) << "No control URLs."; return false; } if (ca_cert_.get() == NULL) { GOOGLE_LOG(ERROR) << "Missing or bad ca cert."; return false; } return true; } bool ClientConfig::CheckUpdateServerSerial(int new_serial) { std::unique_lock<std::mutex> l(lock_); if (new_serial < last_server_cert_serial_number_) { return false; } if (new_serial > last_server_cert_serial_number_) { last_server_cert_serial_number_ = new_serial; return WriteBackConfig(); } return true; } bool ClientConfig::ResetKey() { std::unique_lock<std::mutex> l(lock_); if (!key_.Generate()) { return false; } client_id_ = MakeClientId(); return WriteBackConfig(); } std::vector<std::string> ClientConfig::ControlUrls() const { std::unique_lock<std::mutex> l(lock_); return std::vector<std::string>(control_urls_.begin(), control_urls_.end()); } std::vector<std::string> ClientConfig::ProxyServers() const { std::unique_lock<std::mutex> l(lock_); return std::vector<std::string>(proxy_servers_.begin(), proxy_servers_.end()); } ClientConfiguration::SubprocessConfig ClientConfig::SubprocessConfig() const { std::unique_lock<std::mutex> l(lock_); return subprocess_config_; } bool ClientConfig::WriteBackConfig() { if (writeback_filename_.empty()) { return true; } int fd = open(writeback_filename_.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IWUSR | S_IRUSR); if (fd < 0) { GOOGLE_LOG(ERROR) << "Unable to open writeback: " << writeback_filename_; return false; } // Re-read the original configuration file, so we can tell what has changed. ClientConfiguration base_config; if (!MergeConfigFile(configuration_filename_, &base_config)) { GOOGLE_LOG(ERROR) << "Unable to read config: " << configuration_filename_; } // Currently only 2 fields can be changed through the config interface. ClientConfiguration proto; if (base_config.last_server_cert_serial_number() != last_server_cert_serial_number_) { proto.set_last_server_cert_serial_number(last_server_cert_serial_number_); } std::string key_pem = key_.ToStringPEM(); if (base_config.client_private_key_pem() != key_pem) { proto.set_client_private_key_pem(key_pem); } google::protobuf::io::FileOutputStream output(fd); bool result = google::protobuf::TextFormat::Print(proto, &output); output.Close(); return result; } std::string ClientConfig::MakeClientId() { if (!key_.get()) { return ""; } return "C." + BytesToHex(Digest::Sha256(key_.PublicKeyN()).substr(0, 8)); } bool ClientConfig::MergeConfigFile(const std::string& config_file, ClientConfiguration* config) { int fd = open(config_file.c_str(), O_RDONLY); if (fd < 0) { GOOGLE_LOG(ERROR) << "Failed to open:" << config_file; return false; } google::protobuf::io::FileInputStream input(fd); if (!google::protobuf::TextFormat::Merge(&input, config)) { GOOGLE_LOG(ERROR) << "Failed to parse:" << config_file; input.Close(); return false; } input.Close(); return true; } } // namespace grr <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: soundplayer.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2007-07-17 15:16:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_SLIDESHOW_SOUNDPLAYER_HXX #define INCLUDED_SLIDESHOW_SOUNDPLAYER_HXX #include <rtl/ustring.hxx> #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/media/XManager.hpp> #include <com/sun/star/media/XPlayer.hpp> #include <boost/shared_ptr.hpp> #include "pauseeventhandler.hxx" #include "disposable.hxx" #include "eventmultiplexer.hxx" /* Definition of SoundPlayer class */ namespace slideshow { namespace internal { /** Little class that plays a sound from a URL. TODO: Must be explicitly disposed (as long as enable_shared_ptr_from_this isn't available)! */ class SoundPlayer : public PauseEventHandler, public Disposable { public: /** Create a sound player object. @param rSoundURL URL to a sound file. @param rComponentContext Reference to a component context, used to create the needed services @throws ::com::sun::star::lang::NoSupportException, if the sound file is invalid, or not supported by the player service. */ static ::boost::shared_ptr<SoundPlayer> create( EventMultiplexer & rEventMultiplexer, const ::rtl::OUString& rSoundURL, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext>& rComponentContext ); virtual ~SoundPlayer(); /** Query duration of sound playback. If the sound is already playing, this method returns the remaining playback time. @return the playback duration in seconds. */ double getDuration() const; bool startPlayback(); bool stopPlayback(); void setPlaybackLoop( bool bLoop ); // PauseEventHandler: virtual bool handlePause( bool bPauseShow ); // Disposable virtual void dispose(); private: SoundPlayer( EventMultiplexer & rEventMultiplexer, const ::rtl::OUString& rSoundURL, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext>& rComponentContext ); EventMultiplexer & mrEventMultiplexer; // TODO(Q3): obsolete when boost::enable_shared_ptr_from_this // is available ::boost::shared_ptr<SoundPlayer> mThis; ::com::sun::star::uno::Reference< ::com::sun::star::media::XPlayer > mxPlayer; }; typedef ::boost::shared_ptr< SoundPlayer > SoundPlayerSharedPtr; } } #endif /* INCLUDED_SLIDESHOW_SOUNDPLAYER_HXX */ <commit_msg>INTEGRATION: CWS changefileheader (1.7.46); FILE MERGED 2008/03/31 14:00:31 rt 1.7.46.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: soundplayer.hxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef INCLUDED_SLIDESHOW_SOUNDPLAYER_HXX #define INCLUDED_SLIDESHOW_SOUNDPLAYER_HXX #include <rtl/ustring.hxx> #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/media/XManager.hpp> #include <com/sun/star/media/XPlayer.hpp> #include <boost/shared_ptr.hpp> #include "pauseeventhandler.hxx" #include "disposable.hxx" #include "eventmultiplexer.hxx" /* Definition of SoundPlayer class */ namespace slideshow { namespace internal { /** Little class that plays a sound from a URL. TODO: Must be explicitly disposed (as long as enable_shared_ptr_from_this isn't available)! */ class SoundPlayer : public PauseEventHandler, public Disposable { public: /** Create a sound player object. @param rSoundURL URL to a sound file. @param rComponentContext Reference to a component context, used to create the needed services @throws ::com::sun::star::lang::NoSupportException, if the sound file is invalid, or not supported by the player service. */ static ::boost::shared_ptr<SoundPlayer> create( EventMultiplexer & rEventMultiplexer, const ::rtl::OUString& rSoundURL, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext>& rComponentContext ); virtual ~SoundPlayer(); /** Query duration of sound playback. If the sound is already playing, this method returns the remaining playback time. @return the playback duration in seconds. */ double getDuration() const; bool startPlayback(); bool stopPlayback(); void setPlaybackLoop( bool bLoop ); // PauseEventHandler: virtual bool handlePause( bool bPauseShow ); // Disposable virtual void dispose(); private: SoundPlayer( EventMultiplexer & rEventMultiplexer, const ::rtl::OUString& rSoundURL, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext>& rComponentContext ); EventMultiplexer & mrEventMultiplexer; // TODO(Q3): obsolete when boost::enable_shared_ptr_from_this // is available ::boost::shared_ptr<SoundPlayer> mThis; ::com::sun::star::uno::Reference< ::com::sun::star::media::XPlayer > mxPlayer; }; typedef ::boost::shared_ptr< SoundPlayer > SoundPlayerSharedPtr; } } #endif /* INCLUDED_SLIDESHOW_SOUNDPLAYER_HXX */ <|endoftext|>
<commit_before>/* * Copyright 2015 Cloudius Systems */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE core #include <boost/test/included/unit_test.hpp> #include "types.hh" #include "tuple.hh" BOOST_AUTO_TEST_CASE(test_bytes_type_string_conversions) { BOOST_REQUIRE(bytes_type->equal(bytes_type->from_string("616263646566"), bytes_type->decompose(bytes{"abcdef"}))); } BOOST_AUTO_TEST_CASE(test_int32_type_string_conversions) { BOOST_REQUIRE(int32_type->equal(int32_type->from_string("1234567890"), int32_type->decompose(1234567890))); BOOST_REQUIRE_EQUAL(int32_type->to_string(int32_type->decompose(1234567890)), "1234567890"); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("12"), int32_type->decompose(12))); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("0012"), int32_type->decompose(12))); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("+12"), int32_type->decompose(12))); BOOST_REQUIRE_EQUAL(int32_type->to_string(int32_type->decompose(12)), "12"); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("-12"), int32_type->decompose(-12))); BOOST_REQUIRE_EQUAL(int32_type->to_string(int32_type->decompose(-12)), "-12"); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("0"), int32_type->decompose(0))); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("-0"), int32_type->decompose(0))); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("+0"), int32_type->decompose(0))); BOOST_REQUIRE_EQUAL(int32_type->to_string(int32_type->decompose(0)), "0"); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("-2147483648"), int32_type->decompose((int32_t)-2147483648))); BOOST_REQUIRE_EQUAL(int32_type->to_string(int32_type->decompose((int32_t)-2147483648)), "-2147483648"); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("2147483647"), int32_type->decompose((int32_t)2147483647))); BOOST_REQUIRE_EQUAL(int32_type->to_string(int32_type->decompose((int32_t)-2147483647)), "-2147483647"); auto test_parsing_fails = [] (sstring text) { try { int32_type->from_string(text); BOOST_FAIL(sprint("Parsing of '%s' should have failed", text)); } catch (const marshal_exception& e) { // expected } }; test_parsing_fails("asd"); test_parsing_fails("-2147483649"); test_parsing_fails("2147483648"); test_parsing_fails("2147483648123"); BOOST_REQUIRE_EQUAL(int32_type->to_string(bytes()), ""); } BOOST_AUTO_TEST_CASE(test_tuple_is_prefix_of) { tuple_type<> type({utf8_type, utf8_type, utf8_type}); auto prefix_type = type.as_prefix(); auto val = type.serialize_value({{bytes("a")}, {bytes("b")}, {bytes("c")}}); BOOST_REQUIRE(prefix_type.is_prefix_of(prefix_type.serialize_value({}), val)); BOOST_REQUIRE(prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("a")}}), val)); BOOST_REQUIRE(prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("a")}, {bytes("b")}}), val)); BOOST_REQUIRE(prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("a")}, {bytes("b")}, {bytes("c")}}), val)); BOOST_REQUIRE(!prefix_type.is_prefix_of(prefix_type.serialize_value({{}}), val)); BOOST_REQUIRE(!prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes()}}), val)); BOOST_REQUIRE(!prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("b")}, {bytes("c")}}), val)); BOOST_REQUIRE(!prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("a")}, {bytes("c")}, {bytes("b")}}), val)); BOOST_REQUIRE(!prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("abc")}}), val)); BOOST_REQUIRE(!prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("ab")}}), val)); auto val2 = type.serialize_value({{bytes("a")}, {bytes("b")}, {}}); BOOST_REQUIRE(prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("a")}, {bytes("b")}}), val2)); BOOST_REQUIRE(prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("a")}, {bytes("b")}, {}}), val2)); BOOST_REQUIRE(!prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("a")}, {bytes("b")}, {bytes()}}), val2)); } <commit_msg>tests: Add test for tuple_type::compare()<commit_after>/* * Copyright 2015 Cloudius Systems */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE core #include <boost/test/included/unit_test.hpp> #include "types.hh" #include "tuple.hh" BOOST_AUTO_TEST_CASE(test_bytes_type_string_conversions) { BOOST_REQUIRE(bytes_type->equal(bytes_type->from_string("616263646566"), bytes_type->decompose(bytes{"abcdef"}))); } BOOST_AUTO_TEST_CASE(test_int32_type_string_conversions) { BOOST_REQUIRE(int32_type->equal(int32_type->from_string("1234567890"), int32_type->decompose(1234567890))); BOOST_REQUIRE_EQUAL(int32_type->to_string(int32_type->decompose(1234567890)), "1234567890"); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("12"), int32_type->decompose(12))); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("0012"), int32_type->decompose(12))); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("+12"), int32_type->decompose(12))); BOOST_REQUIRE_EQUAL(int32_type->to_string(int32_type->decompose(12)), "12"); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("-12"), int32_type->decompose(-12))); BOOST_REQUIRE_EQUAL(int32_type->to_string(int32_type->decompose(-12)), "-12"); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("0"), int32_type->decompose(0))); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("-0"), int32_type->decompose(0))); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("+0"), int32_type->decompose(0))); BOOST_REQUIRE_EQUAL(int32_type->to_string(int32_type->decompose(0)), "0"); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("-2147483648"), int32_type->decompose((int32_t)-2147483648))); BOOST_REQUIRE_EQUAL(int32_type->to_string(int32_type->decompose((int32_t)-2147483648)), "-2147483648"); BOOST_REQUIRE(int32_type->equal(int32_type->from_string("2147483647"), int32_type->decompose((int32_t)2147483647))); BOOST_REQUIRE_EQUAL(int32_type->to_string(int32_type->decompose((int32_t)-2147483647)), "-2147483647"); auto test_parsing_fails = [] (sstring text) { try { int32_type->from_string(text); BOOST_FAIL(sprint("Parsing of '%s' should have failed", text)); } catch (const marshal_exception& e) { // expected } }; test_parsing_fails("asd"); test_parsing_fails("-2147483649"); test_parsing_fails("2147483648"); test_parsing_fails("2147483648123"); BOOST_REQUIRE_EQUAL(int32_type->to_string(bytes()), ""); } BOOST_AUTO_TEST_CASE(test_tuple_is_prefix_of) { tuple_type<> type({utf8_type, utf8_type, utf8_type}); auto prefix_type = type.as_prefix(); auto val = type.serialize_value({{bytes("a")}, {bytes("b")}, {bytes("c")}}); BOOST_REQUIRE(prefix_type.is_prefix_of(prefix_type.serialize_value({}), val)); BOOST_REQUIRE(prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("a")}}), val)); BOOST_REQUIRE(prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("a")}, {bytes("b")}}), val)); BOOST_REQUIRE(prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("a")}, {bytes("b")}, {bytes("c")}}), val)); BOOST_REQUIRE(!prefix_type.is_prefix_of(prefix_type.serialize_value({{}}), val)); BOOST_REQUIRE(!prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes()}}), val)); BOOST_REQUIRE(!prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("b")}, {bytes("c")}}), val)); BOOST_REQUIRE(!prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("a")}, {bytes("c")}, {bytes("b")}}), val)); BOOST_REQUIRE(!prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("abc")}}), val)); BOOST_REQUIRE(!prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("ab")}}), val)); auto val2 = type.serialize_value({{bytes("a")}, {bytes("b")}, {}}); BOOST_REQUIRE(prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("a")}, {bytes("b")}}), val2)); BOOST_REQUIRE(prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("a")}, {bytes("b")}, {}}), val2)); BOOST_REQUIRE(!prefix_type.is_prefix_of(prefix_type.serialize_value({{bytes("a")}, {bytes("b")}, {bytes()}}), val2)); } BOOST_AUTO_TEST_CASE(test_tuple_type_compare) { tuple_type<> type({utf8_type, utf8_type, utf8_type}); BOOST_REQUIRE(type.compare( type.serialize_value({{bytes("a")}, {bytes("b")}, {bytes("c")}}), type.serialize_value({{bytes("a")}, {bytes("b")}, {bytes("c")}})) == 0); BOOST_REQUIRE(type.compare( type.serialize_value({{bytes("a")}, {bytes("b")}, {bytes("c")}}), type.serialize_value({{bytes("a")}, {bytes("b")}, {bytes("d")}})) < 0); BOOST_REQUIRE(type.compare( type.serialize_value({{bytes("a")}, {bytes("b")}, {bytes("d")}}), type.serialize_value({{bytes("a")}, {bytes("b")}, {bytes("c")}})) > 0); BOOST_REQUIRE(type.compare( type.serialize_value({{bytes("a")}, {bytes("b")}, {bytes("d")}}), type.serialize_value({{bytes("a")}, {bytes("d")}, {bytes("c")}})) < 0); BOOST_REQUIRE(type.compare( type.serialize_value({{bytes("a")}, {bytes("d")}, {bytes("c")}}), type.serialize_value({{bytes("c")}, {bytes("b")}, {bytes("c")}})) < 0); BOOST_REQUIRE(type.compare( type.serialize_value({{bytes("a")}, {}, {bytes("c")}}), type.serialize_value({{bytes("a")}, {bytes("b")}, {bytes("c")}})) < 0); BOOST_REQUIRE(type.compare( type.serialize_value({{bytes("a")}, {bytes("b")}, {bytes("c")}}), type.serialize_value({{bytes("a")}, {}, {bytes("c")}})) > 0); BOOST_REQUIRE(type.compare( type.serialize_value({{}, {}, {}}), type.serialize_value({{}, {}, {}})) == 0); } <|endoftext|>
<commit_before>#ifndef CHS_HPP #define CHS_HPP // // A class for CHS manipulation // // class CHS { long long cylinder, head, sector; unsigned int spt, // sectors per track tpc; // tracks per cylinder void calc(long long); public: CHS(int c,int h, int s); CHS(long long lba); CHS(); bool SetCylinder(long long); bool SetHead(unsigned int); bool SetSector(unsigned int); unsigned long GetCylinder(); unsigned int GetHead(); unsigned int GetSector(); bool SetGeometry(int spt,int tpc); int GetSPT(); int GetTPC(); void SetSPT(int); void SetTPC(int); long long ToLBA(); CHS &operator =(long long); bool operator ==(CHS &chs); CHS &operator ++(); CHS &operator ++(int); }; #endif <commit_msg>Added MBR_CHS CHS::ToMbrChs() function<commit_after>#ifndef CHS_HPP #define CHS_HPP #include <stdint.h> #pragma pack(1) // Cylinder-head-sector structure for MBR struct MBR_CHS { uint8_t head; // head (<255) uint8_t sector:6; // sector (<64) uint8_t cylinder_bits:2; // 2 bits of cylinder value uint8_t cylinder ; // cylinder (<=1023) }; #pragma pack() // // A class for CHS manipulation // class CHS { long long cylinder, head, sector; unsigned int spt, // sectors per track tpc; // tracks per cylinder void calc(long long); public: CHS(int c,int h, int s); CHS(long long lba); CHS(); bool SetCylinder(long long); bool SetHead(unsigned int); bool SetSector(unsigned int); unsigned long GetCylinder(); unsigned int GetHead(); unsigned int GetSector(); bool SetGeometry(int spt,int tpc); int GetSPT(); int GetTPC(); void SetSPT(int); void SetTPC(int); long long ToLBA(); CHS &operator =(long long); bool operator ==(CHS &chs); CHS &operator ++(); CHS &operator ++(int); MBR_CHS ToMbrChs(); }; #endif <|endoftext|>
<commit_before>//std #include <sstream> //naga #include "model.hpp" #include "model_component.hpp" #include "model_animation.hpp" #include "collision.hpp" #include "resource_manager.hpp" #include "material_instance.hpp" #include "debug_renderer.hpp" #include "game_object.hpp" #include "camera_params.hpp" #include "bisect.hpp" //glm #include <glm\glm.hpp> namespace naga { void ModelComponent::on_tick(f32 dt) { if (animation != nullptr) { t += dt; // TODO: extract this to a function to get the frame index auto frame_count = static_cast<f32>(animation->frame_count); auto seconds_per_frame = 1.0f / animation->frames_per_second; auto frame_0_index = static_cast<size_t>(glm::floor(glm::mod(t / seconds_per_frame, frame_count))); auto frame_1_index = (frame_0_index + 1) % animation->frame_count; auto interpolate_t = glm::mod(t, seconds_per_frame) / seconds_per_frame; auto& frame_skeleton_0 = animation->frame_skeletons[frame_0_index]; auto& frame_skeleton_1 = animation->frame_skeletons[frame_1_index]; skeleton.interpolate(frame_skeleton_0, frame_skeleton_1, interpolate_t); } //TODO: the AABB is not calculated if there is no animation for (size_t i = 0; i < skeleton.bones.size(); ++i) { bone_matrices[i] = skeleton.bone_matrices[i] * model->get_bones()[i].inverse_bind_pose_matrix; } aabb = skeleton.aabb << get_owner()->pose.to_matrix(); sphere.origin = aabb.center(); sphere.radius = glm::length(aabb.extents()); } void ModelComponent::on_render(CameraParameters& camera_parameters) { if (model == nullptr) { throw std::exception(); } // TODO: problem here is that the frustum/sphere/aabb are not if (intersects(camera_parameters.frustum, sphere) == IntersectType::DISJOINT || intersects(camera_parameters.frustum, aabb) == IntersectType::DISJOINT) { //skeleton aabb does not intersect camera frustum return; } // TODO: need to figure out a better way to feed light data into the shaders vec3 light_location; const auto world_matrix = get_owner()->pose.to_matrix(); auto view_projection_matrix = camera_parameters.projection_matrix * camera_parameters.view_matrix; model->render(camera_parameters.location, world_matrix, view_projection_matrix, bone_matrices, light_location, mesh_materials); #if defined (DEBUG) render_aabb(mat4(1.0f), view_projection_matrix, aabb, vec4(1, 0, 0, 1)); render_sphere(mat4(1.0f), view_projection_matrix, sphere, vec4(1)); for (size_t i = 0; i < model->get_bones().size(); ++i) { if (skeleton.bones[i].parent_index != 255) { const auto& a = skeleton.bones[i].pose.location; const auto& b = skeleton.bones[skeleton.bones[i].parent_index].pose.location; render_line_loop(world_matrix, view_projection_matrix, std::vector<vec3>({ a, b }), vec4(0.5f)); } render_axes(skeleton.bones[i].pose.to_matrix() * world_matrix, view_projection_matrix); //render_sphere(, view_projection_matrix, Sphere(vec3(), 0.5f), vec4(1)); } #endif } Pose3 ModelComponent::get_bone_pose(const std::string& bone_name) const { auto bone_index = model->get_bone_index(bone_name); if (!bone_index) { std::ostringstream oss; oss << "model contains no bone " << bone_name; throw std::invalid_argument(oss.str().c_str()); } return get_owner()->pose * skeleton.bones[*bone_index].pose; } void ModelComponent::set_model(const boost::shared_ptr<Model>& model) { this->model = model; skeleton.bones.resize(model->get_bones().size()); skeleton.bone_matrices.resize(model->get_bones().size()); for (size_t i = 0; i < skeleton.bones.size(); ++i) { skeleton.bone_matrices[i] = model->get_bones()[i].bind_pose_matrix; } bone_matrices.resize(skeleton.bones.size()); for (size_t i = 0; i < skeleton.bones.size(); ++i) { bone_matrices[i] = skeleton.bone_matrices[i] * model->get_bones()[i].inverse_bind_pose_matrix; } for (const auto& mesh : model->get_meshes()) { mesh_materials.push_back(boost::make_shared<MaterialInstance>(mesh->material)); } } void ModelComponent::play(const std::string& animation_name) { animation = resources.get<ModelAnimation>(animation_name); } void pause(); } <commit_msg>Fixed a problem where the debug skeleton bone axes would draw in the wrong place.<commit_after>//std #include <sstream> //naga #include "model.hpp" #include "model_component.hpp" #include "model_animation.hpp" #include "collision.hpp" #include "resource_manager.hpp" #include "material_instance.hpp" #include "debug_renderer.hpp" #include "game_object.hpp" #include "camera_params.hpp" #include "bisect.hpp" //glm #include <glm\glm.hpp> namespace naga { void ModelComponent::on_tick(f32 dt) { if (animation != nullptr) { t += dt; // TODO: extract this to a function to get the frame index auto frame_count = static_cast<f32>(animation->frame_count); auto seconds_per_frame = 1.0f / animation->frames_per_second; auto frame_0_index = static_cast<size_t>(glm::floor(glm::mod(t / seconds_per_frame, frame_count))); auto frame_1_index = (frame_0_index + 1) % animation->frame_count; auto interpolate_t = glm::mod(t, seconds_per_frame) / seconds_per_frame; auto& frame_skeleton_0 = animation->frame_skeletons[frame_0_index]; auto& frame_skeleton_1 = animation->frame_skeletons[frame_1_index]; skeleton.interpolate(frame_skeleton_0, frame_skeleton_1, interpolate_t); } //TODO: the AABB is not calculated if there is no animation for (size_t i = 0; i < skeleton.bones.size(); ++i) { bone_matrices[i] = skeleton.bone_matrices[i] * model->get_bones()[i].inverse_bind_pose_matrix; } aabb = skeleton.aabb << get_owner()->pose.to_matrix(); sphere.origin = aabb.center(); sphere.radius = glm::length(aabb.extents()); } void ModelComponent::on_render(CameraParameters& camera_parameters) { if (model == nullptr) { throw std::exception(); } // TODO: problem here is that the frustum/sphere/aabb are not if (intersects(camera_parameters.frustum, sphere) == IntersectType::DISJOINT || intersects(camera_parameters.frustum, aabb) == IntersectType::DISJOINT) { //skeleton aabb does not intersect camera frustum return; } // TODO: need to figure out a better way to feed light data into the shaders vec3 light_location; const auto world_matrix = get_owner()->pose.to_matrix(); auto view_projection_matrix = camera_parameters.projection_matrix * camera_parameters.view_matrix; model->render(camera_parameters.location, world_matrix, view_projection_matrix, bone_matrices, light_location, mesh_materials); #if defined (DEBUG) render_aabb(mat4(1.0f), view_projection_matrix, aabb, vec4(1, 0, 0, 1)); render_sphere(mat4(1.0f), view_projection_matrix, sphere, vec4(1)); for (size_t i = 0; i < model->get_bones().size(); ++i) { if (skeleton.bones[i].parent_index != 255) { const auto& a = skeleton.bones[i].pose.location; const auto& b = skeleton.bones[skeleton.bones[i].parent_index].pose.location; render_line_loop(world_matrix, view_projection_matrix, std::vector<vec3>({ a, b }), vec4(0.5f)); } render_axes(world_matrix * skeleton.bones[i].pose.to_matrix(), view_projection_matrix); } #endif } Pose3 ModelComponent::get_bone_pose(const std::string& bone_name) const { auto bone_index = model->get_bone_index(bone_name); if (!bone_index) { std::ostringstream oss; oss << "model contains no bone " << bone_name; throw std::invalid_argument(oss.str().c_str()); } return get_owner()->pose * skeleton.bones[*bone_index].pose; } void ModelComponent::set_model(const boost::shared_ptr<Model>& model) { this->model = model; skeleton.bones.resize(model->get_bones().size()); skeleton.bone_matrices.resize(model->get_bones().size()); for (size_t i = 0; i < skeleton.bones.size(); ++i) { skeleton.bone_matrices[i] = model->get_bones()[i].bind_pose_matrix; } bone_matrices.resize(skeleton.bones.size()); for (size_t i = 0; i < skeleton.bones.size(); ++i) { bone_matrices[i] = skeleton.bone_matrices[i] * model->get_bones()[i].inverse_bind_pose_matrix; } for (const auto& mesh : model->get_meshes()) { mesh_materials.push_back(boost::make_shared<MaterialInstance>(mesh->material)); } } void ModelComponent::play(const std::string& animation_name) { animation = resources.get<ModelAnimation>(animation_name); } void pause(); } <|endoftext|>
<commit_before>// $Id: rtti.C,v 1.6 2001/06/22 11:06:37 oliver Exp $ #include <BALL/COMMON/rtti.h> #include <typeinfo> #include <ctype.h> #ifdef __GNUC__ extern "C" char* cplus_demangle(const char* s, int options); #endif namespace BALL { string streamClassName(const std::type_info& t) { #ifdef __GNUC__ // s = GNUDemangling::demangle(s); string s("_Z"); s += t.name(); char* name = cplus_demangle(s.c_str(), 1 << 8); if (name != 0) { s = name; } #else string s(t.name()); #endif for (unsigned int i = 0; i < s.size(); i++) { if (s[i] == ' ') { s[i] = '_'; } } if (string(s, 0, 6) == "const_") { s.erase(0, 6); } return s; } #ifdef __GNUC__ namespace GNUDemangling { string decode_mangling(string& s) { string tmp; int i,len; if (s.size() == 0) return ""; if (!isdigit(s[0])) { // decode GNU shortcuts for built-in types char c = s[0]; s.erase(0, 1); switch (c) { case 'Q': // start of class name len = atoi(string(s,1,1).c_str()); s.erase(0, 1); for (i = 0; i < len; i++) { tmp.append(decode_mangling(s)); tmp.append("::"); } tmp.erase(tmp.end() - 2, tmp.end()); break; case 'Z': // template parameter return decode_mangling(s); break; case 'i': return "int"; break; case 'l': return "long"; break; case 's': return "short"; break; case 'c': return "char"; break; case 'x': return "long long"; break; case 'f': return "float"; break; case 'd': return "double"; break; case 'b': return "bool"; break; case 'w': return "wchar_t"; break; case 'U': // unsigned variants tmp = "unsigned "; tmp.append(decode_mangling(s)); break; case 'C': // const tmp = "const "; tmp.append(decode_mangling(s)); break; case 'P': // pointer tmp = decode_mangling(s); tmp.append("*"); break; case 'R': // reference tmp = decode_mangling(s); tmp.append("&"); break; case 't': tmp = decode_mangling(s); tmp.append("<"); len = atoi(string(1, s[0]).c_str()); s.erase(0,1); for (i = 0; i < len; i++) { tmp.append(decode_mangling(s)); tmp.append(","); } // remove last ',' tmp.erase(tmp.end() - 1, tmp.end()); tmp.append(">"); break; default: tmp = "?"; } return tmp; } else { i = s.find_first_not_of("0123456789"); len = atol(string(s, 0, i).c_str()); if (len == 0) { s.erase(0,1); if (s.size() > 0) { return decode_mangling(s); } else { return ""; } } else { string h(s, i, len); s.erase(0, i + len); return h; } } } string demangle(string s) { string tmp = decode_mangling(s); while (tmp[tmp.size() - 1] == ':') { tmp.erase(tmp.end() - 1, tmp.end()); } while (tmp[0] == ':') { tmp.erase(0, 1); } return tmp; } } // namespace GNUDemangling #endif // __GNUC__ } // namespace BALL <commit_msg>fixed: gnu demangling was broken for GCC 2, reintroduced demangloing by hand and use if libiberty.a for GCC3<commit_after>// $Id: rtti.C,v 1.7 2001/06/28 14:13:34 oliver Exp $ #include <BALL/COMMON/rtti.h> #include <typeinfo> #include <ctype.h> #ifdef __GNUC__ extern "C" char* cplus_demangle(const char* s, int options); #endif namespace BALL { string streamClassName(const std::type_info& t) { #ifdef __GNUC__ #if (__GNUC__ < 3) string s(t.name()); s = GNUDemangling::demangle(s); #else string s("_Z"); s += t.name(); char* name = cplus_demangle(s.c_str(), 1 << 8); if (name != 0) { s = name; } #endif #else string s(t.name()); #endif for (unsigned int i = 0; i < s.size(); i++) { if (s[i] == ' ') { s[i] = '_'; } } if (string(s, 0, 6) == "const_") { s.erase(0, 6); } return s; } #ifdef __GNUC__ namespace GNUDemangling { string decode_mangling(string& s) { string tmp; int i,len; if (s.size() == 0) return ""; if (!isdigit(s[0])) { // decode GNU shortcuts for built-in types char c = s[0]; s.erase(0, 1); switch (c) { case 'Q': // start of class name len = atoi(string(s,1,1).c_str()); s.erase(0, 1); for (i = 0; i < len; i++) { tmp.append(decode_mangling(s)); tmp.append("::"); } tmp.erase(tmp.end() - 2, tmp.end()); break; case 'Z': // template parameter return decode_mangling(s); break; case 'i': return "int"; break; case 'l': return "long"; break; case 's': return "short"; break; case 'c': return "char"; break; case 'x': return "long long"; break; case 'f': return "float"; break; case 'd': return "double"; break; case 'b': return "bool"; break; case 'w': return "wchar_t"; break; case 'U': // unsigned variants tmp = "unsigned "; tmp.append(decode_mangling(s)); break; case 'C': // const tmp = "const "; tmp.append(decode_mangling(s)); break; case 'P': // pointer tmp = decode_mangling(s); tmp.append("*"); break; case 'R': // reference tmp = decode_mangling(s); tmp.append("&"); break; case 't': tmp = decode_mangling(s); tmp.append("<"); len = atoi(string(1, s[0]).c_str()); s.erase(0,1); for (i = 0; i < len; i++) { tmp.append(decode_mangling(s)); tmp.append(","); } // remove last ',' tmp.erase(tmp.end() - 1, tmp.end()); tmp.append(">"); break; default: tmp = "?"; } return tmp; } else { i = s.find_first_not_of("0123456789"); len = atol(string(s, 0, i).c_str()); if (len == 0) { s.erase(0,1); if (s.size() > 0) { return decode_mangling(s); } else { return ""; } } else { string h(s, i, len); s.erase(0, i + len); return h; } } } string demangle(string s) { string tmp = decode_mangling(s); while (tmp[tmp.size() - 1] == ':') { tmp.erase(tmp.end() - 1, tmp.end()); } while (tmp[0] == ':') { tmp.erase(0, 1); } return tmp; } } // namespace GNUDemangling #endif // __GNUC__ } // namespace BALL <|endoftext|>
<commit_before>/*****************************************************************************\ * Copyright 2005, 2006, 2007 Niels Lohmann, Christian Gierds * * * * This file is part of GNU BPEL2oWFN. * * * * GNU BPEL2oWFN is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the * * Free Software Foundation; either version 2 of the License, or (at your * * option) any later version. * * * * GNU BPEL2oWFN is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * * Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with GNU BPEL2oWFN; see file COPYING. if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * \*****************************************************************************/ /*! * \file bpel2owfn.cc * * \brief BPEL2oWFN's main * * \author Niels Lohmann <nlohmann@informatik.hu-berlin.de>, * Christian Gierds <gierds@informatik.hu-berlin.de>, * last changes of: \$Author: gierds $ * * \since 2005/10/18 * * \date \$Date: 2007/03/27 12:37:48 $ * * \note This file is part of the tool BPEL2oWFN and was created during the * project "Tools4BPEL" at the Humboldt-Universitt zu Berlin. See * http://www.informatik.hu-berlin.de/top/forschung/projekte/tools4bpel * for details. * * \version \$Revision: 1.152 $ */ /****************************************************************************** * Headers *****************************************************************************/ #include <cstdio> #include <iostream> #include <fstream> #include <string> #include <cassert> #include <map> #include "bpel2owfn.h" // generated configuration file #include "petrinet.h" // Petri Net support #include "cfg.h" // Control Flow Graph #include "debug.h" // debugging help #include "options.h" #include "ast-config.h" #include "ast-details.h" #include "globals.h" using std::cerr; using std::cout; using std::endl; using std::string; using std::map; /****************************************************************************** * External functions *****************************************************************************/ extern int frontend_parse(); // from Bison extern int frontend_debug; // from Bison extern int frontend__flex_debug; // from flex extern FILE *frontend_in; // from flex /****************************************************************************** * Global variables *****************************************************************************/ /// The Petri Net PetriNet PN = PetriNet(); /*! * \brief entry point of BPEL2oWFN * * Controls the behaviour of input and output. * * \param argc number of command line arguments * \param argv array with command line arguments * * \returns 0 if everything went well * \returns 1 if an error occurred * * \todo This function is definitly too long. It should be partitioned! */ int main( int argc, char *argv[]) { globals::program_name = string(argv[0]); // generate the invocation string for (int i = 0; i < argc; i++) { globals::invocation += string(argv[i]); if (i != (argc-1)) globals::invocation += " "; } /* * Reading command line arguments and triggering appropriate behaviour. * In case of false parameters call command line help function and exit. */ parse_command_line(argc, argv); PetriNet PN2 = PetriNet(); set< string >::iterator file = inputfiles.begin(); do { if (inputfiles.size() >= 1) { globals::filename = *file; if (!(frontend_in = fopen(globals::filename.c_str(), "r"))) { cerr << "Could not open file for reading: " << globals::filename.c_str() << endl; exit(1); } } trace(TRACE_INFORMATION, "Parsing " + globals::filename + " ...\n"); // invoke Bison parser int error = frontend_parse(); if (!error) { trace(TRACE_INFORMATION, "Parsing complete.\n"); if ( globals::filename != "<STDIN>" && frontend_in != NULL) { trace(TRACE_INFORMATION," + Closing input file: " + globals::filename + "\n"); fclose(frontend_in); } // apply first set of rewrite rules trace(TRACE_INFORMATION, "Rewriting...\n"); globals::AST = globals::AST->rewrite(kc::invoke); globals::AST = globals::AST->rewrite(kc::implicit); trace(TRACE_INFORMATION, "Rewriting complete...\n"); // postprocess and annotate the AST trace(TRACE_INFORMATION, "Postprocessing...\n"); globals::AST->unparse(kc::printer, kc::postprocessing); trace(TRACE_INFORMATION, "Postprocessing complete...\n"); // apply second set of rewrite rules trace(TRACE_INFORMATION, "Rewriting 2...\n"); globals::AST = globals::AST->rewrite(kc::newNames); trace(TRACE_INFORMATION, "Rewriting 2 complete...\n"); // print information about the process show_process_information(); // an experiment // cout << "digraph G{" << endl; // globals::ASTEmap[1]->output(); // cout << "}" << endl; // print the AST? if (modus == M_AST) { trace(TRACE_INFORMATION, "-> Printing AST ...\n"); if (formats[F_DOT]) { string dot_filename = globals::output_filename + "." + suffixes[F_DOT]; FILE *dotfile = fopen(dot_filename.c_str(), "w+"); globals::AST->fprintdot(dotfile, "", "", "", true, true, true); fclose(dotfile); #ifdef HAVE_DOT string systemcall = "dot -q -Tpng -o" + globals::output_filename + ".png " + globals::output_filename + "." + suffixes[F_DOT]; trace(TRACE_INFORMATION, "Invoking dot with the following options:\n"); trace(TRACE_INFORMATION, systemcall + "\n\n"); system(systemcall.c_str()); #endif } else globals::AST->print(); } if (modus == M_PRETTY) { if (formats[F_XML]) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_XML]); } trace(TRACE_INFORMATION, "-> Printing \"pretty\" XML ...\n"); globals::AST->unparse(kc::printer, kc::xml); if (globals::output_filename != "") { closeOutput(output); output = NULL; } } } // generate and process the control flow graph? if (modus == M_CFG) processCFG(); // generate a Petri net? if (modus == M_PETRINET || modus == M_CONSISTENCY) { trace(TRACE_INFORMATION, "-> Unparsing AST to Petri net ...\n"); // choose Petri net patterns if (globals::parameters[P_COMMUNICATIONONLY] == true) globals::AST->unparse(kc::pseudoPrinter, kc::petrinetsmall); else globals::AST->unparse(kc::pseudoPrinter, kc::petrinetnew); // calculate maximum occurences PN.calculate_max_occurrences(); if (modus == M_CONSISTENCY) { unsigned int pos = file->rfind(".bpel", file->length()); unsigned int pos2 = file->rfind("/", file->length()); string prefix = ""; if (pos == (file->length() - 5)) { prefix = file->substr(pos2 + 1, pos - pos2 - 1) + "_"; } // apply structural reduction rules? if (globals::parameters[P_REDUCE]) { trace(TRACE_INFORMATION, "-> Structurally simplifying Petri Net ...\n"); PN.reduce(); } PN.addPrefix(prefix); PN2.compose(PN); PN = PetriNet(); globals::AST = NULL; } } } else /* parse error */ { cleanup(); return error; } file++; } while (modus == M_CONSISTENCY && file != inputfiles.end()); /* * parsing complete */ if (modus == M_CONSISTENCY) PN = PN2; if (modus == M_PETRINET || modus == M_CONSISTENCY) { // apply structural reduction rules? if ( globals::parameters[P_REDUCE] ) { trace(TRACE_INFORMATION, "-> Structurally simplifying Petri Net ...\n"); PN.reduce(); } // now the net will not change any more, thus the nodes are re-enumerated // and the maximal occurrences of the nodes are calculated. PN.reenumerate(); // PN.calculate_max_occurrences(); cerr << PN.information() << endl; // create oWFN output ? if (formats[F_OWFN]) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_OWFN]); } trace(TRACE_INFORMATION, "-> Printing Petri net for oWFN ...\n"); PN.set_format(FORMAT_OWFN); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; } } // create LoLA output ? if ( formats[F_LOLA] ) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_LOLA]); } if (modus == M_CONSISTENCY) { PN.makeChannelsInternal(); } trace(TRACE_INFORMATION, "-> Printing Petri net for LoLA ...\n"); PN.set_format(FORMAT_LOLA); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; } if (modus == M_CONSISTENCY || modus == M_PETRINET) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + ".task"); } string comment = "{ AG EF ("; string formula = "FORMULA\n ALLPATH ALWAYS EXPATH EVENTUALLY ("; string andStr = ""; set< Place * > finalPlaces = PN.getFinalPlaces(); for (set< Place * >::iterator place = finalPlaces.begin(); place != finalPlaces.end(); place++) { comment += andStr + (*place)->nodeFullName(); formula += andStr + (*place)->nodeShortName() + " > 0"; andStr = " AND "; } comment += ") }"; formula += ")"; (*output) << comment << endl << endl; (*output) << formula << endl << endl; if (globals::output_filename != "") { closeOutput(output); output = NULL; } } } // create PNML output ? if ( formats[F_PNML] ) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_PNML]); } trace(TRACE_INFORMATION, "-> Printing Petri net for PNML ...\n"); PN.set_format(FORMAT_PNML); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; } } // create PEP output ? if ( formats[F_PEP] ) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_PEP]); } trace(TRACE_INFORMATION, "-> Printing Petri net for PEP ...\n"); PN.set_format(FORMAT_PEP); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; } } // create INA output ? if ( formats[F_INA] ) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_INA]); } trace(TRACE_INFORMATION, "-> Printing Petri net for INA ...\n"); PN.set_format(FORMAT_INA); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; } } // create SPIN output ? if ( formats[F_SPIN] ) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_SPIN]); } trace(TRACE_INFORMATION, "-> Printing Petri net for SPIN ...\n"); PN.set_format(FORMAT_SPIN); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; } } // create APNN output ? if ( formats[F_APNN] ) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_APNN]); } trace(TRACE_INFORMATION, "-> Printing Petri net for APNN ...\n"); PN.set_format(FORMAT_APNN); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; } } // create dot output ? if ( formats[F_DOT] ) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_DOT]); } trace(TRACE_INFORMATION, "-> Printing Petri net for dot ...\n"); PN.set_format(FORMAT_DOT); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; #ifdef HAVE_DOT string systemcall = "dot -q -Tpng -o" + globals::output_filename + ".png " + globals::output_filename + "." + suffixes[F_DOT]; trace(TRACE_INFORMATION, "Invoking dot with the following options:\n"); trace(TRACE_INFORMATION, systemcall + "\n\n"); system(systemcall.c_str()); #endif } } // create info file ? if ( formats[F_INFO] ) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_INFO]); } trace(TRACE_INFORMATION, "-> Printing Petri net information ...\n"); PN.set_format(FORMAT_INFO); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; } } } // everything went fine return 0; } /*! * \defgroup frontend Front End * \defgroup patterns Petri Net Patterns */ <commit_msg>+ Partitioned the main function into some program parts<commit_after>/*****************************************************************************\ * Copyright 2005, 2006, 2007 Niels Lohmann, Christian Gierds * * * * This file is part of GNU BPEL2oWFN. * * * * GNU BPEL2oWFN is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the * * Free Software Foundation; either version 2 of the License, or (at your * * option) any later version. * * * * GNU BPEL2oWFN is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * * Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with GNU BPEL2oWFN; see file COPYING. if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * \*****************************************************************************/ /*! * \file bpel2owfn.cc * * \brief BPEL2oWFN's main * * \author Niels Lohmann <nlohmann@informatik.hu-berlin.de>, * Christian Gierds <gierds@informatik.hu-berlin.de>, * last changes of: \$Author: znamirow $ * * \since 2005/10/18 * * \date \$Date: 2007/03/29 15:24:26 $ * * \note This file is part of the tool BPEL2oWFN and was created during the * project "Tools4BPEL" at the Humboldt-Universitt zu Berlin. See * http://www.informatik.hu-berlin.de/top/forschung/projekte/tools4bpel * for details. * * \version \$Revision: 1.153 $ */ /****************************************************************************** * Headers *****************************************************************************/ #include <cstdio> #include <iostream> #include <fstream> #include <string> #include <cassert> #include <map> #include "bpel2owfn.h" // generated configuration file #include "petrinet.h" // Petri Net support #include "cfg.h" // Control Flow Graph #include "debug.h" // debugging help #include "options.h" #include "ast-config.h" #include "ast-details.h" #include "globals.h" using std::cerr; using std::cout; using std::endl; using std::string; using std::map; /****************************************************************************** * External functions *****************************************************************************/ extern int frontend_parse(); // from Bison extern int frontend_debug; // from Bison extern int frontend__flex_debug; // from flex extern FILE *frontend_in; // from flex /****************************************************************************** * Global variables *****************************************************************************/ /// The Petri Net PetriNet PN = PetriNet(); /****************************************************************************** * program parts *****************************************************************************/ // analyzation of the commandline void analyze_cl(int argc, char *argv[]) { // setting globals globals::program_name = string(argv[0]); for (int i = 0; i < argc; i++) { globals::invocation += string(argv[i]); if (i != (argc-1)) globals::invocation += " "; } /* * Reading command line arguments and triggering appropriate behaviour. * In case of false parameters call command line help function and exit. */ parse_command_line(argc, argv); } // opening a file void open_file(set< string >::iterator file) { if (inputfiles.size() >= 1) { globals::filename = *file; if (!(frontend_in = fopen(globals::filename.c_str(), "r"))) { cerr << "Could not open file for reading: " << globals::filename.c_str() << endl; exit(1); } } } // closing a file void close_file(set< string >::iterator file) { if ( globals::filename != "<STDIN>" && frontend_in != NULL) { trace(TRACE_INFORMATION," + Closing input file: " + globals::filename + "\n"); fclose(frontend_in); } } // finishing AST void finish_AST() { // apply first set of rewrite rules trace(TRACE_INFORMATION, "Rewriting...\n"); globals::AST = globals::AST->rewrite(kc::invoke); globals::AST = globals::AST->rewrite(kc::implicit); trace(TRACE_INFORMATION, "Rewriting complete...\n"); // postprocess and annotate the AST trace(TRACE_INFORMATION, "Postprocessing...\n"); globals::AST->unparse(kc::printer, kc::postprocessing); trace(TRACE_INFORMATION, "Postprocessing complete...\n"); // apply second set of rewrite rules trace(TRACE_INFORMATION, "Rewriting 2...\n"); globals::AST = globals::AST->rewrite(kc::newNames); trace(TRACE_INFORMATION, "Rewriting 2 complete...\n"); // print information about the process show_process_information(); // an experiment // cout << "digraph G{" << endl; // globals::ASTEmap[1]->output(); // cout << "}" << endl; } // output of every single processed file void single_output(set< string >::iterator file, PetriNet PN2) { // print the AST? if (modus == M_AST) { trace(TRACE_INFORMATION, "-> Printing AST ...\n"); if (formats[F_DOT]) { string dot_filename = globals::output_filename + "." + suffixes[F_DOT]; FILE *dotfile = fopen(dot_filename.c_str(), "w+"); globals::AST->fprintdot(dotfile, "", "", "", true, true, true); fclose(dotfile); #ifdef HAVE_DOT string systemcall = "dot -q -Tpng -o" + globals::output_filename + ".png " + globals::output_filename + "." + suffixes[F_DOT]; trace(TRACE_INFORMATION, "Invoking dot with the following options:\n"); trace(TRACE_INFORMATION, systemcall + "\n\n"); system(systemcall.c_str()); #endif } else globals::AST->print(); } if (modus == M_PRETTY) { if (formats[F_XML]) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_XML]); } trace(TRACE_INFORMATION, "-> Printing \"pretty\" XML ...\n"); globals::AST->unparse(kc::printer, kc::xml); if (globals::output_filename != "") { closeOutput(output); output = NULL; } } } // generate and process the control flow graph? if (modus == M_CFG) processCFG(); // generate a Petri net? if (modus == M_PETRINET || modus == M_CONSISTENCY) { trace(TRACE_INFORMATION, "-> Unparsing AST to Petri net ...\n"); // choose Petri net patterns if (globals::parameters[P_COMMUNICATIONONLY] == true) globals::AST->unparse(kc::pseudoPrinter, kc::petrinetsmall); else globals::AST->unparse(kc::pseudoPrinter, kc::petrinetnew); // calculate maximum occurences PN.calculate_max_occurrences(); if (modus == M_CONSISTENCY) { unsigned int pos = file->rfind(".bpel", file->length()); unsigned int pos2 = file->rfind("/", file->length()); string prefix = ""; if (pos == (file->length() - 5)) { prefix = file->substr(pos2 + 1, pos - pos2 - 1) + "_"; } // apply structural reduction rules? if (globals::parameters[P_REDUCE]) { trace(TRACE_INFORMATION, "-> Structurally simplifying Petri Net ...\n"); PN.reduce(); } PN.addPrefix(prefix); PN2.compose(PN); PN = PetriNet(); globals::AST = NULL; } } } // Final Output of the result void final_output( PetriNet PN2) { if (modus == M_CONSISTENCY) PN = PN2; if (modus == M_PETRINET || modus == M_CONSISTENCY) { // apply structural reduction rules? if ( globals::parameters[P_REDUCE] ) { trace(TRACE_INFORMATION, "-> Structurally simplifying Petri Net ...\n"); PN.reduce(); } // now the net will not change any more, thus the nodes are re-enumerated // and the maximal occurrences of the nodes are calculated. PN.reenumerate(); // PN.calculate_max_occurrences(); cerr << PN.information() << endl; // create oWFN output ? if (formats[F_OWFN]) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_OWFN]); } trace(TRACE_INFORMATION, "-> Printing Petri net for oWFN ...\n"); PN.set_format(FORMAT_OWFN); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; } } // create LoLA output ? if ( formats[F_LOLA] ) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_LOLA]); } if (modus == M_CONSISTENCY) { PN.makeChannelsInternal(); } trace(TRACE_INFORMATION, "-> Printing Petri net for LoLA ...\n"); PN.set_format(FORMAT_LOLA); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; } if (modus == M_CONSISTENCY || modus == M_PETRINET) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + ".task"); } string comment = "{ AG EF ("; string formula = "FORMULA\n ALLPATH ALWAYS EXPATH EVENTUALLY ("; string andStr = ""; set< Place * > finalPlaces = PN.getFinalPlaces(); for (set< Place * >::iterator place = finalPlaces.begin(); place != finalPlaces.end(); place++) { comment += andStr + (*place)->nodeFullName(); formula += andStr + (*place)->nodeShortName() + " > 0"; andStr = " AND "; } comment += ") }"; formula += ")"; (*output) << comment << endl << endl; (*output) << formula << endl << endl; if (globals::output_filename != "") { closeOutput(output); output = NULL; } } } // create PNML output ? if ( formats[F_PNML] ) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_PNML]); } trace(TRACE_INFORMATION, "-> Printing Petri net for PNML ...\n"); PN.set_format(FORMAT_PNML); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; } } // create PEP output ? if ( formats[F_PEP] ) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_PEP]); } trace(TRACE_INFORMATION, "-> Printing Petri net for PEP ...\n"); PN.set_format(FORMAT_PEP); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; } } // create INA output ? if ( formats[F_INA] ) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_INA]); } trace(TRACE_INFORMATION, "-> Printing Petri net for INA ...\n"); PN.set_format(FORMAT_INA); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; } } // create SPIN output ? if ( formats[F_SPIN] ) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_SPIN]); } trace(TRACE_INFORMATION, "-> Printing Petri net for SPIN ...\n"); PN.set_format(FORMAT_SPIN); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; } } // create APNN output ? if ( formats[F_APNN] ) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_APNN]); } trace(TRACE_INFORMATION, "-> Printing Petri net for APNN ...\n"); PN.set_format(FORMAT_APNN); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; } } // create dot output ? if ( formats[F_DOT] ) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_DOT]); } trace(TRACE_INFORMATION, "-> Printing Petri net for dot ...\n"); PN.set_format(FORMAT_DOT); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; #ifdef HAVE_DOT string systemcall = "dot -q -Tpng -o" + globals::output_filename + ".png " + globals::output_filename + "." + suffixes[F_DOT]; trace(TRACE_INFORMATION, "Invoking dot with the following options:\n"); trace(TRACE_INFORMATION, systemcall + "\n\n"); system(systemcall.c_str()); #endif } } // create info file ? if ( formats[F_INFO] ) { if (globals::output_filename != "") { output = openOutput(globals::output_filename + "." + suffixes[F_INFO]); } trace(TRACE_INFORMATION, "-> Printing Petri net information ...\n"); PN.set_format(FORMAT_INFO); (*output) << PN; if (globals::output_filename != "") { closeOutput(output); output = NULL; } } } } /****************************************************************************** * main() function *****************************************************************************/ /*! * \brief entry point of BPEL2oWFN * * Controls the behaviour of input and output. * * \param argc number of command line arguments * \param argv array with command line arguments * * \returns 0 if everything went well * \returns 1 if an error occurred * * \todo This function is definitly too long. It should be partitioned! */ int main( int argc, char *argv[]) { // initilization of variables PetriNet PN2 = PetriNet(); // analyzation of the commandline analyze_cl(argc,argv); // parsing all inputfiles set< string >::iterator file = inputfiles.begin(); do { open_file(file); // invoke Bison parser trace(TRACE_INFORMATION, "Parsing " + globals::filename + " ...\n"); int error = frontend_parse(); if (!error) { trace(TRACE_INFORMATION, "Parsing of " + globals::filename + " complete.\n"); close_file(file); finish_AST(); // create output for this file single_output(file, PN2); } else /* parse error */ { cleanup(); return error; } file++; } while (modus == M_CONSISTENCY && file != inputfiles.end()); trace(TRACE_INFORMATION, "All files have been parsed.\n"); final_output(PN2); // everything went fine return 0; } /*! * \defgroup frontend Front End * \defgroup patterns Petri Net Patterns */ <|endoftext|>
<commit_before>#ifndef _C4_ERROR_HPP_ #define _C4_ERROR_HPP_ #include "c4/config.hpp" /** @def C4_ERROR_THROWS_EXCEPTION if this is defined and exceptions are * enabled, then calls to C4_ERROR() will throw an exception */ /** @def C4_NOEXCEPT evaluates to noexcept when C4_ERROR might be called * and exceptions are disabled. */ #ifdef C4_ERROR_THROWS_EXCEPTION # define C4_NOEXCEPT #else # define C4_NOEXCEPT noexcept #endif //----------------------------------------------------------------------------- #ifdef __clang__ /* NOTE: using , ## __VA_ARGS__ to deal with zero-args calls to * variadic macros is not portable, but works in clang, gcc, msvc, icc. * clang requires switching off compiler warnings for pedantic mode. * @see http://stackoverflow.com/questions/32047685/variadic-macro-without-arguments */ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" // warning: token pasting of ',' and __VA_ARGS__ is a GNU extension #elif defined(__GNUC__) /* GCC also issues a warning for zero-args calls to variadic macros. * This warning is switched on with -pedantic and apparently there is no * easy way to turn it off as with clang. But marking this as a system * header works. * @see https://gcc.gnu.org/onlinedocs/cpp/System-Headers.html * @see http://stackoverflow.com/questions/35587137/ */ # pragma GCC system_header #endif //----------------------------------------------------------------------------- C4_BEGIN_NAMESPACE(c4) using error_callback_type = void (*)(); void set_error_callback(error_callback_type cb); error_callback_type get_error_callback(); void report_error ( const char *fmt, ...); void report_error_fl (const char *file, int line, const char *fmt, ...); void report_error_flf(const char *file, int line, const char *func, const char *fmt, ...); void report_warning ( const char *fmt, ...); void report_warning_fl (const char *file, int line, const char *fmt, ...); void report_warning_flf(const char *file, int line, const char *func, const char *fmt, ...); /** Raise an error, and report a printf-formatted message. * If an error callback was set, it will be called. * @see set_error_callback() */ #if defined(C4_ERROR_SHOWS_FILELINE) && defined(C4_ERROR_SHOWS_FUNC) # define C4_ERROR(msg, ...) \ c4::report_error_flf(__FILE__, __LINE__, C4_PRETTY_FUNC, msg, ## __VA_ARGS__) #elif defined(C4_ERROR_SHOWS_FILELINE) # define C4_ERROR(msg, ...) \ c4::report_error_fl(__FILE__, __LINE__, msg, ## __VA_ARGS__) #elif ! defined(C4_ERROR_SHOWS_FUNC) # define C4_ERROR(msg, ...) \ c4::report_error(msg, ## __VA_ARGS__) #else # error not implemented #endif /** Report a warning with a printf-formatted message. */ #if defined(C4_ERROR_SHOWS_FILELINE) && defined(C4_ERROR_SHOWS_FUNC) # define C4_WARNING(msg, ...) \ c4::report_warning_flf(__FILE__, __LINE__, C4_PRETTY_FUNC, msg, ## __VA_ARGS__) #elif defined(C4_ERROR_SHOWS_FILELINE) # define C4_WARNING(msg, ...) \ c4::report_warning_fl(__FILE__, __LINE__, msg, ## __VA_ARGS__) #elif ! defined(C4_ERROR_SHOWS_FUNC) # define C4_WARNING(msg, ...) \ c4::report_warning(msg, ## __VA_ARGS__) #else # error not implemented #endif /** Check that a condition is true, or raise an error when not * true. Unlike C4_ASSERT, this check is not omitted in non-debug * builds. * @see C4_ASSERT */ #define C4_CHECK(cond) \ if(C4_UNLIKELY(!(cond))) \ { \ C4_ERROR("check failed: %s", #cond); \ } /** like C4_CHECK(), and additionally log a printf-style message. * @see C4_CHECK */ #define C4_CHECK_MSG(cond, fmt, ...) \ if(C4_UNLIKELY(!(cond))) \ { \ C4_ERROR("check failed: %s\n" fmt, #cond, ## __VA_ARGS__); \ } // assertions - only in debug builds #ifdef NDEBUG // turn off assertions # define C4_ASSERT(cond) # define C4_ASSERT_MSG(cond, fmt, ...) #else # define C4_ASSERT(cond) C4_CHECK(cond) # define C4_ASSERT_MSG(cond, fmt, ...) C4_CHECK_MSG(cond, fmt, ## __VA_ARGS__) #endif // Extreme assertion: can be switched off independently of the regular assertion. // Use eg for bounds checking in hot code. #ifdef C4_USE_XASSERT # define C4_XASSERT(cond) C4_CHECK(cond) # define C4_XASSERT_MSG(cond, fmt, ...) C4_CHECK_MSG(cond, fmt, ## __VA_ARGS__) #else # define C4_XASSERT(cond) # define C4_XASSERT_MSG(cond, fmt, ...) #endif // Common error conditions #define C4_NOT_IMPLEMENTED() C4_ERROR("NOT IMPLEMENTED") #define C4_NOT_IMPLEMENTED_MSG(msg, ...) C4_ERROR("NOT IMPLEMENTED: " msg, ## __VA_ARGS__) #define C4_NEVER_REACH() C4_UNREACHABLE(); C4_ERROR("never reach this point") #define C4_NEVER_REACH_MSG(msg, ...) C4_UNREACHABLE(); C4_ERROR("never reach this point: " msg, ## __VA_ARGS__) C4_END_NAMESPACE(c4) #ifdef __clang__ # pragma clang diagnostic pop #endif #endif /* _C4_ERROR_HPP_ */ <commit_msg>add scoped error callback<commit_after>#ifndef _C4_ERROR_HPP_ #define _C4_ERROR_HPP_ #include "c4/config.hpp" /** @def C4_ERROR_THROWS_EXCEPTION if this is defined and exceptions are * enabled, then calls to C4_ERROR() will throw an exception */ /** @def C4_NOEXCEPT evaluates to noexcept when C4_ERROR might be called * and exceptions are disabled. */ #ifdef C4_ERROR_THROWS_EXCEPTION # define C4_NOEXCEPT #else # define C4_NOEXCEPT noexcept #endif //----------------------------------------------------------------------------- #ifdef __clang__ /* NOTE: using , ## __VA_ARGS__ to deal with zero-args calls to * variadic macros is not portable, but works in clang, gcc, msvc, icc. * clang requires switching off compiler warnings for pedantic mode. * @see http://stackoverflow.com/questions/32047685/variadic-macro-without-arguments */ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" // warning: token pasting of ',' and __VA_ARGS__ is a GNU extension #elif defined(__GNUC__) /* GCC also issues a warning for zero-args calls to variadic macros. * This warning is switched on with -pedantic and apparently there is no * easy way to turn it off as with clang. But marking this as a system * header works. * @see https://gcc.gnu.org/onlinedocs/cpp/System-Headers.html * @see http://stackoverflow.com/questions/35587137/ */ # pragma GCC system_header #endif //----------------------------------------------------------------------------- C4_BEGIN_NAMESPACE(c4) using error_callback_type = void (*)(); void set_error_callback(error_callback_type cb); error_callback_type get_error_callback(); void report_error ( const char *fmt, ...); void report_error_fl (const char *file, int line, const char *fmt, ...); void report_error_flf(const char *file, int line, const char *func, const char *fmt, ...); void report_warning ( const char *fmt, ...); void report_warning_fl (const char *file, int line, const char *fmt, ...); void report_warning_flf(const char *file, int line, const char *func, const char *fmt, ...); //----------------------------------------------------------------------------- struct ScopedErrorCallback { error_callback_type m_original; explicit ScopedErrorCallback(error_callback_type cb) : m_original(get_error_callback()) { set_error_callback(cb); } ~ScopedErrorCallback() { set_error_callback(m_original); } }; //----------------------------------------------------------------------------- /** Raise an error, and report a printf-formatted message. * If an error callback was set, it will be called. * @see set_error_callback() */ #if defined(C4_ERROR_SHOWS_FILELINE) && defined(C4_ERROR_SHOWS_FUNC) # define C4_ERROR(msg, ...) \ c4::report_error_flf(__FILE__, __LINE__, C4_PRETTY_FUNC, msg, ## __VA_ARGS__) #elif defined(C4_ERROR_SHOWS_FILELINE) # define C4_ERROR(msg, ...) \ c4::report_error_fl(__FILE__, __LINE__, msg, ## __VA_ARGS__) #elif ! defined(C4_ERROR_SHOWS_FUNC) # define C4_ERROR(msg, ...) \ c4::report_error(msg, ## __VA_ARGS__) #else # error not implemented #endif /** Report a warning with a printf-formatted message. */ #if defined(C4_ERROR_SHOWS_FILELINE) && defined(C4_ERROR_SHOWS_FUNC) # define C4_WARNING(msg, ...) \ c4::report_warning_flf(__FILE__, __LINE__, C4_PRETTY_FUNC, msg, ## __VA_ARGS__) #elif defined(C4_ERROR_SHOWS_FILELINE) # define C4_WARNING(msg, ...) \ c4::report_warning_fl(__FILE__, __LINE__, msg, ## __VA_ARGS__) #elif ! defined(C4_ERROR_SHOWS_FUNC) # define C4_WARNING(msg, ...) \ c4::report_warning(msg, ## __VA_ARGS__) #else # error not implemented #endif /** Check that a condition is true, or raise an error when not * true. Unlike C4_ASSERT, this check is not omitted in non-debug * builds. * @see C4_ASSERT */ #define C4_CHECK(cond) \ if(C4_UNLIKELY(!(cond))) \ { \ C4_ERROR("check failed: %s", #cond); \ } /** like C4_CHECK(), and additionally log a printf-style message. * @see C4_CHECK */ #define C4_CHECK_MSG(cond, fmt, ...) \ if(C4_UNLIKELY(!(cond))) \ { \ C4_ERROR("check failed: %s\n" fmt, #cond, ## __VA_ARGS__); \ } // assertions - only in debug builds #ifdef NDEBUG // turn off assertions # define C4_ASSERT(cond) # define C4_ASSERT_MSG(cond, fmt, ...) #else # define C4_ASSERT(cond) C4_CHECK(cond) # define C4_ASSERT_MSG(cond, fmt, ...) C4_CHECK_MSG(cond, fmt, ## __VA_ARGS__) #endif // Extreme assertion: can be switched off independently of the regular assertion. // Use eg for bounds checking in hot code. #ifdef C4_USE_XASSERT # define C4_XASSERT(cond) C4_CHECK(cond) # define C4_XASSERT_MSG(cond, fmt, ...) C4_CHECK_MSG(cond, fmt, ## __VA_ARGS__) #else # define C4_XASSERT(cond) # define C4_XASSERT_MSG(cond, fmt, ...) #endif // Common error conditions #define C4_NOT_IMPLEMENTED() C4_ERROR("NOT IMPLEMENTED") #define C4_NOT_IMPLEMENTED_MSG(msg, ...) C4_ERROR("NOT IMPLEMENTED: " msg, ## __VA_ARGS__) #define C4_NOT_IMPLEMENTED_IF(condition) if(C4_UNLIKELY(condition)) { C4_ERROR("NOT IMPLEMENTED"); } #define C4_NOT_IMPLEMENTED_IF_MSG(condition, msg, ...) if(C4_UNLIKELY(condition)) { C4_ERROR("NOT IMPLEMENTED: " msg, ## __VA_ARGS__); } #define C4_NEVER_REACH() C4_UNREACHABLE(); C4_ERROR("never reach this point") #define C4_NEVER_REACH_MSG(msg, ...) C4_UNREACHABLE(); C4_ERROR("never reach this point: " msg, ## __VA_ARGS__) C4_END_NAMESPACE(c4) #ifdef __clang__ # pragma clang diagnostic pop #endif #endif /* _C4_ERROR_HPP_ */ <|endoftext|>
<commit_before>#include "Kick.hpp" #include <stdio.h> #include <algorithm> using namespace std; const float Min_Segment = 1.5 * Ball_Diameter; //Tuning Required (Anthony) Gameplay::Behaviors::Kick::Kick(GameplayModule *gameplay): SingleRobotBehavior(gameplay) { setTargetGoal(); //Whether or not the shot is feasible hasShot = false; //The segment of the best shot _shotSegment = Geometry2d::Segment(Geometry2d::Point(0,0), Geometry2d::Point(0,0)); restart(); } bool Gameplay::Behaviors::Kick::run() { if (!robot || !robot->visible) { return false; } //Only end the behavior is the ball can't be seen and the robot doesn't have it //This prevents the behavior from stopping when the robot blocks the ball if(!ball().valid && !robot->hasBall) { return false; } //If the ball is being blocked set its location to the location of the robot //Accounting for the direction the robot is facing Geometry2d::Point ballPos; if(!ball().valid) { float x = Robot_Radius * sin(robot->angle * DegreesToRadians); float y = Robot_Radius * cos(robot->angle * DegreesToRadians); Geometry2d::Point pt = Geometry2d::Point(x, y); ballPos = robot->pos + pt; } else { ballPos = ball().pos; } //Get the best ublocked area in the target to aim at WindowEvaluator e = WindowEvaluator(state()); e.run(ballPos, _target); Window *w = e.best; //The target to use Geometry2d::Segment target; //Prevents the segfault from using a non existent window if(w != NULL) { if(w->segment.length() < Min_Segment) { hasShot = false; } else { hasShot = true; } target = w->segment; _shotSegment = target; } else { hasShot = false; target = _target; //There is not shot therefore set the best segment to a single point _shotSegment = Geometry2d::Segment(Geometry2d::Point(0,0), Geometry2d::Point(0,0)); } // Some calculations depend on the order of the target endpoints. // Ensure that t0 x t1 > 0. // We have to do this each frame since the ball may move to the other side of the target. //FIXME - Actually, doesn't that mean the kick/pass is done? //FIXME - What about kicking towards a point? cross product is zero... if ((target.pt[0] - ballPos).cross(target.pt[1] - ballPos) < 0) { swap(target.pt[0], target.pt[1]); } // State transitions switch (_state) { case State_Approach1: { Geometry2d::Point targetCenter = target.center(); // Vector from ball to center of target Geometry2d::Point toTarget = targetCenter - ballPos; // Robot position relative to the ball Geometry2d::Point relPos = robot->pos - ballPos; //The Point to compute with Geometry2d::Point point = target.pt[0]; //Behind the ball: move to the nearest line containing the ball and a target endpoint. //the robot is behind the ball, while the target vectors all point in *front* of the ball. if (toTarget.cross(relPos) < 0) { // Above the center line: nearest endpoint-line includes target.pt[1] point = target.pt[1]; } //Change state when the robot is in the right location //facing the right direction Geometry2d::Point b = (point - ballPos + robot->pos).normalized(); float angleError = b.dot(Geometry2d::Point::direction(robot->angle * DegreesToRadians)); bool nearBall = robot->pos.nearPoint(ballPos, Robot_Radius + Ball_Radius + 0.25); //angleError is greater than because cos(0) is 1 which is perfect if (nearBall && angleError > cos(15 * DegreesToRadians)) { _state = State_Approach2; } break; } case State_Approach2: { if (robot->hasBall && robot->charged()) { robot->addText("Aim"); _state = State_Aim; _lastError = INFINITY; } bool nearBall = robot->pos.nearPoint(ballPos, Robot_Radius + Ball_Radius + 0.30); //Go back to state one if needed if(!nearBall) { _state = State_Approach1; } break; } case State_Aim: if (!robot->hasBall) { _state = State_Approach2; } else { state()->drawLine(ballPos, target.pt[0], Qt::red); state()->drawLine(ballPos, target.pt[1], Qt::white); Geometry2d::Point rd = Geometry2d::Point::direction(robot->angle * DegreesToRadians); _kickSegment = Geometry2d::Segment(robot->pos, robot->pos + rd * Field_Length); state()->drawLine(robot->pos, target.center(), Qt::gray); float error = acos(rd.dot((target.center() - robot->pos).normalized())) * RadiansToDegrees; //The distance between the trajectory and the target center float distOff = _kickSegment.distTo(target.center()); //The width of half the target float width = target.pt[0].distTo(target.center()); robot->addText(QString("Aim %1").arg(error)); if (!isinf(_lastError)) { //FIXME - Depends on t0 x t1 > 0 bool inT0 = (target.pt[0] - ballPos).cross(rd) > 0; bool inT1 = rd.cross(target.pt[1] - ballPos) > 0; robot->addText(QString("in %1 %2").arg(inT0).arg(inT1)); //How close to the center line printout robot->addText(QString("Width %1 Distance %2").arg(width).arg(distOff)); //If the tarjectory is within the target bounds if (inT0 && inT1) { //Shoot if the shot is getting worse or the shot is //very good (within half of the width of half the window) (Tuning required) if((error > _lastError) || (distOff < (width * .5))) { // Past the best position _state = State_Kick; } } } _lastError = error; } break; case State_Kick: if (!robot->charged()) { _state = State_Done; } //If the robot loses the ball whilst trying to kick before the kick is done //go back to approach1 to reacquire the ball else if(!robot->hasBall) { _state = State_Approach1; } break; case State_Done: break; } switch (_state) { case State_Approach1: { robot->addText("Approach1"); Geometry2d::Point targetCenter = target.center(); // Vector from ball to center of target Geometry2d::Point toTarget = targetCenter - ballPos; // Robot position relative to the ball Geometry2d::Point relPos = robot->pos - ballPos; //The Point to compute with Geometry2d::Point point = target.pt[0]; //Behind the ball: move to the nearest line containing the ball and a target endpoint. //the robot is behind the ball, while the target vectors all point in *front* of the ball. if (toTarget.cross(relPos) < 0) { // Above the center line: nearest endpoint-line includes target.pt[1] point = target.pt[1]; } //Face that point and move to the appropriate line robot->move(ballPos + (ballPos - point).normalized() * (Robot_Radius + Ball_Radius + .07)); robot->face(point - ballPos + robot->pos); state()->drawLine(ballPos, point, Qt::red); //FIXME - Real robots overshoot and hit the ball in this state. This shouldn't be necessary. //Hopefully moving the target point back and pivoting whilst moving will prevent the ball //from getting hit thus there shouldn't need to be a dribbler robot->dribble(127); robot->avoidBall = true; break; } case State_Approach2: robot->addText("Approach2"); robot->move(ballPos); //Should this face be ballPos or the quanity found in Approach1? robot->face(ballPos); robot->dribble(127); break; case State_Aim: { Geometry2d::Point targetCenter = target.center(); // Vector from ball to center of target Geometry2d::Point toTarget = targetCenter - ballPos; // Robot position relative to the ball Geometry2d::Point relPos = robot->pos - ballPos; // True if the robot is in front of the ball bool inFrontOfBall = toTarget.perpCCW().cross(relPos) > 0; MotionCmd::PivotType dir; if (inFrontOfBall) { // Move behind the ball dir = (toTarget.cross(relPos) > 0) ? MotionCmd::CCW : MotionCmd::CW; } else { // Behind the ball: move to the nearest line containing the ball and a target endpoint. // Note that the robot is behind the ball, while the target vectors all point in *front* of the ball. //FIXME - These assume t0 x t1 > 0. Enforce this here or above. if (toTarget.cross(relPos) > 0) { // Below the center line: nearest endpoint-line includes target.pt[0] dir = (target.pt[0] - ballPos).cross(relPos) > 0 ? MotionCmd::CW : MotionCmd::CCW; } else { // Above the center line: nearest endpoint-line includes target.pt[1] dir = (target.pt[1] - ballPos).cross(relPos) > 0 ? MotionCmd::CCW : MotionCmd::CW; } } robot->dribble(127); robot->pivot(ballPos, dir); state()->drawLine(_kickSegment); break; } case State_Kick: robot->addText("Kick"); if(hasShot) { robot->move(ballPos); robot->face(ballPos); robot->dribble(127); robot->kick(255); } state()->drawLine(_kickSegment); break; case State_Done: robot->addText("Done"); state()->drawLine(_kickSegment); break; } return _state != State_Done; } void Gameplay::Behaviors::Kick::restart() { _state = State_Approach1; } void Gameplay::Behaviors::Kick::setTargetGoal() { //Set the target to be a little inside of the goal posts to prevent noise errors from //causing a post shot setTarget(Geometry2d::Segment( Geometry2d::Point((Field_GoalWidth / 2 - Ball_Diameter), Field_Length), Geometry2d::Point((-Field_GoalWidth / 2 + Ball_Diameter), Field_Length))); } void Gameplay::Behaviors::Kick::setTarget(const Geometry2d::Segment& seg) { _target = seg; } <commit_msg>Fixed a threshold error that was too tight and caused a end zone<commit_after>#include "Kick.hpp" #include <stdio.h> #include <algorithm> using namespace std; const float Min_Segment = 1.5 * Ball_Diameter; //Tuning Required (Anthony) Gameplay::Behaviors::Kick::Kick(GameplayModule *gameplay): SingleRobotBehavior(gameplay) { setTargetGoal(); //Whether or not the shot is feasible hasShot = false; //The segment of the best shot _shotSegment = Geometry2d::Segment(Geometry2d::Point(0,0), Geometry2d::Point(0,0)); restart(); } bool Gameplay::Behaviors::Kick::run() { if (!robot || !robot->visible) { return false; } //Only end the behavior is the ball can't be seen and the robot doesn't have it //This prevents the behavior from stopping when the robot blocks the ball if(!ball().valid && !robot->hasBall) { return false; } //If the ball is being blocked set its location to the location of the robot //Accounting for the direction the robot is facing Geometry2d::Point ballPos; if(!ball().valid) { float x = Robot_Radius * sin(robot->angle * DegreesToRadians); float y = Robot_Radius * cos(robot->angle * DegreesToRadians); Geometry2d::Point pt = Geometry2d::Point(x, y); ballPos = robot->pos + pt; } else { ballPos = ball().pos; } //Get the best ublocked area in the target to aim at WindowEvaluator e = WindowEvaluator(state()); e.run(ballPos, _target); Window *w = e.best; //The target to use Geometry2d::Segment target; //Prevents the segfault from using a non existent window if(w != NULL) { if(w->segment.length() < Min_Segment) { hasShot = false; } else { hasShot = true; } target = w->segment; _shotSegment = target; } else { hasShot = false; target = _target; //There is not shot therefore set the best segment to a single point _shotSegment = Geometry2d::Segment(Geometry2d::Point(0,0), Geometry2d::Point(0,0)); } // Some calculations depend on the order of the target endpoints. // Ensure that t0 x t1 > 0. // We have to do this each frame since the ball may move to the other side of the target. //FIXME - Actually, doesn't that mean the kick/pass is done? //FIXME - What about kicking towards a point? cross product is zero... if ((target.pt[0] - ballPos).cross(target.pt[1] - ballPos) < 0) { swap(target.pt[0], target.pt[1]); } // State transitions switch (_state) { case State_Approach1: { Geometry2d::Point targetCenter = target.center(); // Vector from ball to center of target Geometry2d::Point toTarget = targetCenter - ballPos; // Robot position relative to the ball Geometry2d::Point relPos = robot->pos - ballPos; //The Point to compute with Geometry2d::Point point = target.pt[0]; //Behind the ball: move to the nearest line containing the ball and a target endpoint. //the robot is behind the ball, while the target vectors all point in *front* of the ball. if (toTarget.cross(relPos) < 0) { // Above the center line: nearest endpoint-line includes target.pt[1] point = target.pt[1]; } //Change state when the robot is in the right location //facing the right direction Geometry2d::Point b = (point - ballPos + robot->pos).normalized(); float angleError = b.dot(Geometry2d::Point::direction(robot->angle * DegreesToRadians)); bool nearBall = robot->pos.nearPoint(ballPos, Robot_Radius + Ball_Radius + 0.25); //angleError is greater than because cos(0) is 1 which is perfect if (nearBall && angleError > cos(20 * DegreesToRadians)) { _state = State_Approach2; } break; } case State_Approach2: { if (robot->hasBall && robot->charged()) { robot->addText("Aim"); _state = State_Aim; _lastError = INFINITY; } bool nearBall = robot->pos.nearPoint(ballPos, Robot_Radius + Ball_Radius + 0.30); //Go back to state one if needed if(!nearBall) { _state = State_Approach1; } break; } case State_Aim: if (!robot->hasBall) { _state = State_Approach2; } else { state()->drawLine(ballPos, target.pt[0], Qt::red); state()->drawLine(ballPos, target.pt[1], Qt::white); Geometry2d::Point rd = Geometry2d::Point::direction(robot->angle * DegreesToRadians); _kickSegment = Geometry2d::Segment(robot->pos, robot->pos + rd * Field_Length); state()->drawLine(robot->pos, target.center(), Qt::gray); float error = acos(rd.dot((target.center() - robot->pos).normalized())) * RadiansToDegrees; //The distance between the trajectory and the target center float distOff = _kickSegment.distTo(target.center()); //The width of half the target float width = target.pt[0].distTo(target.center()); robot->addText(QString("Aim %1").arg(error)); if (!isinf(_lastError)) { //FIXME - Depends on t0 x t1 > 0 bool inT0 = (target.pt[0] - ballPos).cross(rd) > 0; bool inT1 = rd.cross(target.pt[1] - ballPos) > 0; robot->addText(QString("in %1 %2").arg(inT0).arg(inT1)); //How close to the center line printout robot->addText(QString("Width %1 Distance %2").arg(width).arg(distOff)); //If the tarjectory is within the target bounds if (inT0 && inT1) { //Shoot if the shot is getting worse or the shot is //very good (within half of the width of half the window) (Tuning required) if((error > _lastError) || (distOff < (width * .5))) { // Past the best position _state = State_Kick; } } } _lastError = error; } break; case State_Kick: if (!robot->charged()) { _state = State_Done; } //If the robot loses the ball whilst trying to kick before the kick is done //go back to approach1 to reacquire the ball else if(!robot->hasBall) { _state = State_Approach1; } break; case State_Done: break; } switch (_state) { case State_Approach1: { robot->addText("Approach1"); Geometry2d::Point targetCenter = target.center(); // Vector from ball to center of target Geometry2d::Point toTarget = targetCenter - ballPos; // Robot position relative to the ball Geometry2d::Point relPos = robot->pos - ballPos; //The Point to compute with Geometry2d::Point point = target.pt[0]; //Behind the ball: move to the nearest line containing the ball and a target endpoint. //the robot is behind the ball, while the target vectors all point in *front* of the ball. if (toTarget.cross(relPos) < 0) { // Above the center line: nearest endpoint-line includes target.pt[1] point = target.pt[1]; } //Face that point and move to the appropriate line robot->move(ballPos + (ballPos - point).normalized() * (Robot_Radius + Ball_Radius + .07)); robot->face(point - ballPos + robot->pos); state()->drawLine(ballPos, point, Qt::red); //FIXME - Real robots overshoot and hit the ball in this state. This shouldn't be necessary. //Hopefully moving the target point back and pivoting whilst moving will prevent the ball //from getting hit thus there shouldn't need to be a dribbler robot->dribble(127); robot->avoidBall = true; break; } case State_Approach2: robot->addText("Approach2"); robot->move(ballPos); //Should this face be ballPos or the quanity found in Approach1? robot->face(ballPos); robot->dribble(127); break; case State_Aim: { Geometry2d::Point targetCenter = target.center(); // Vector from ball to center of target Geometry2d::Point toTarget = targetCenter - ballPos; // Robot position relative to the ball Geometry2d::Point relPos = robot->pos - ballPos; // True if the robot is in front of the ball bool inFrontOfBall = toTarget.perpCCW().cross(relPos) > 0; MotionCmd::PivotType dir; if (inFrontOfBall) { // Move behind the ball dir = (toTarget.cross(relPos) > 0) ? MotionCmd::CCW : MotionCmd::CW; } else { // Behind the ball: move to the nearest line containing the ball and a target endpoint. // Note that the robot is behind the ball, while the target vectors all point in *front* of the ball. //FIXME - These assume t0 x t1 > 0. Enforce this here or above. if (toTarget.cross(relPos) > 0) { // Below the center line: nearest endpoint-line includes target.pt[0] dir = (target.pt[0] - ballPos).cross(relPos) > 0 ? MotionCmd::CW : MotionCmd::CCW; } else { // Above the center line: nearest endpoint-line includes target.pt[1] dir = (target.pt[1] - ballPos).cross(relPos) > 0 ? MotionCmd::CCW : MotionCmd::CW; } } robot->dribble(127); //Robot has trouble handling a moving ball when trying to pivot (I don't know how to fix this) robot->pivot(ballPos, dir); state()->drawLine(_kickSegment); break; } case State_Kick: robot->addText("Kick"); if(hasShot) { robot->move(ballPos); robot->face(ballPos); robot->dribble(127); robot->kick(255); } state()->drawLine(_kickSegment); break; case State_Done: robot->addText("Done"); state()->drawLine(_kickSegment); break; } return _state != State_Done; } void Gameplay::Behaviors::Kick::restart() { _state = State_Approach1; } void Gameplay::Behaviors::Kick::setTargetGoal() { //Set the target to be a little inside of the goal posts to prevent noise errors from //causing a post shot setTarget(Geometry2d::Segment( Geometry2d::Point((Field_GoalWidth / 2 - Ball_Diameter), Field_Length), Geometry2d::Point((-Field_GoalWidth / 2 + Ball_Diameter), Field_Length))); } void Gameplay::Behaviors::Kick::setTarget(const Geometry2d::Segment& seg) { _target = seg; } <|endoftext|>
<commit_before>//===- IVUsers.cpp - Induction Variable Users -------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements bookkeeping for "interesting" users of expressions // computed from induction variables. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "iv-users" #include "llvm/Analysis/IVUsers.h" #include "llvm/Constants.h" #include "llvm/Instructions.h" #include "llvm/Type.h" #include "llvm/DerivedTypes.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/ScalarEvolutionExpressions.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> using namespace llvm; char IVUsers::ID = 0; static RegisterPass<IVUsers> X("iv-users", "Induction Variable Users", false, true); Pass *llvm::createIVUsersPass() { return new IVUsers(); } /// containsAddRecFromDifferentLoop - Determine whether expression S involves a /// subexpression that is an AddRec from a loop other than L. An outer loop /// of L is OK, but not an inner loop nor a disjoint loop. static bool containsAddRecFromDifferentLoop(const SCEV *S, Loop *L) { // This is very common, put it first. if (isa<SCEVConstant>(S)) return false; if (const SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) { for (unsigned int i=0; i< AE->getNumOperands(); i++) if (containsAddRecFromDifferentLoop(AE->getOperand(i), L)) return true; return false; } if (const SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) { if (const Loop *newLoop = AE->getLoop()) { if (newLoop == L) return false; // if newLoop is an outer loop of L, this is OK. if (!LoopInfo::isNotAlreadyContainedIn(L, newLoop)) return false; } return true; } if (const SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S)) return containsAddRecFromDifferentLoop(DE->getLHS(), L) || containsAddRecFromDifferentLoop(DE->getRHS(), L); #if 0 // SCEVSDivExpr has been backed out temporarily, but will be back; we'll // need this when it is. if (const SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S)) return containsAddRecFromDifferentLoop(DE->getLHS(), L) || containsAddRecFromDifferentLoop(DE->getRHS(), L); #endif if (const SCEVCastExpr *CE = dyn_cast<SCEVCastExpr>(S)) return containsAddRecFromDifferentLoop(CE->getOperand(), L); return false; } /// getSCEVStartAndStride - Compute the start and stride of this expression, /// returning false if the expression is not a start/stride pair, or true if it /// is. The stride must be a loop invariant expression, but the start may be /// a mix of loop invariant and loop variant expressions. The start cannot, /// however, contain an AddRec from a different loop, unless that loop is an /// outer loop of the current loop. static bool getSCEVStartAndStride(const SCEV *&SH, Loop *L, Loop *UseLoop, const SCEV *&Start, const SCEV *&Stride, ScalarEvolution *SE, DominatorTree *DT) { const SCEV *TheAddRec = Start; // Initialize to zero. // If the outer level is an AddExpr, the operands are all start values except // for a nested AddRecExpr. if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) { for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i) if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) { if (AddRec->getLoop() == L) TheAddRec = SE->getAddExpr(AddRec, TheAddRec); else return false; // Nested IV of some sort? } else { Start = SE->getAddExpr(Start, AE->getOperand(i)); } } else if (isa<SCEVAddRecExpr>(SH)) { TheAddRec = SH; } else { return false; // not analyzable. } const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec); if (!AddRec || AddRec->getLoop() != L) return false; // Use getSCEVAtScope to attempt to simplify other loops out of // the picture. const SCEV *AddRecStart = AddRec->getStart(); AddRecStart = SE->getSCEVAtScope(AddRecStart, UseLoop); const SCEV *AddRecStride = AddRec->getStepRecurrence(*SE); // FIXME: If Start contains an SCEVAddRecExpr from a different loop, other // than an outer loop of the current loop, reject it. LSR has no concept of // operating on more than one loop at a time so don't confuse it with such // expressions. if (containsAddRecFromDifferentLoop(AddRecStart, L)) return false; Start = SE->getAddExpr(Start, AddRecStart); // If stride is an instruction, make sure it dominates the loop preheader. // Otherwise we could end up with a use before def situation. if (!isa<SCEVConstant>(AddRecStride)) { BasicBlock *Preheader = L->getLoopPreheader(); if (!AddRecStride->dominates(Preheader, DT)) return false; DEBUG(errs() << "[" << L->getHeader()->getName() << "] Variable stride: " << *AddRec << "\n"); } Stride = AddRecStride; return true; } /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression /// and now we need to decide whether the user should use the preinc or post-inc /// value. If this user should use the post-inc version of the IV, return true. /// /// Choosing wrong here can break dominance properties (if we choose to use the /// post-inc value when we cannot) or it can end up adding extra live-ranges to /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we /// should use the post-inc value). static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV, Loop *L, LoopInfo *LI, DominatorTree *DT, Pass *P) { // If the user is in the loop, use the preinc value. if (L->contains(User->getParent())) return false; BasicBlock *LatchBlock = L->getLoopLatch(); // Ok, the user is outside of the loop. If it is dominated by the latch // block, use the post-inc value. if (DT->dominates(LatchBlock, User->getParent())) return true; // There is one case we have to be careful of: PHI nodes. These little guys // can live in blocks that are not dominated by the latch block, but (since // their uses occur in the predecessor block, not the block the PHI lives in) // should still use the post-inc value. Check for this case now. PHINode *PN = dyn_cast<PHINode>(User); if (!PN) return false; // not a phi, not dominated by latch block. // Look at all of the uses of IV by the PHI node. If any use corresponds to // a block that is not dominated by the latch block, give up and use the // preincremented value. unsigned NumUses = 0; for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) if (PN->getIncomingValue(i) == IV) { ++NumUses; if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i))) return false; } // Okay, all uses of IV by PN are in predecessor blocks that really are // dominated by the latch block. Use the post-incremented value. return true; } /// AddUsersIfInteresting - Inspect the specified instruction. If it is a /// reducible SCEV, recursively add its users to the IVUsesByStride set and /// return true. Otherwise, return false. bool IVUsers::AddUsersIfInteresting(Instruction *I) { if (!SE->isSCEVable(I->getType())) return false; // Void and FP expressions cannot be reduced. // LSR is not APInt clean, do not touch integers bigger than 64-bits. if (SE->getTypeSizeInBits(I->getType()) > 64) return false; if (!Processed.insert(I)) return true; // Instruction already handled. // Get the symbolic expression for this instruction. const SCEV *ISE = SE->getSCEV(I); if (isa<SCEVCouldNotCompute>(ISE)) return false; // Get the start and stride for this expression. Loop *UseLoop = LI->getLoopFor(I->getParent()); const SCEV *Start = SE->getIntegerSCEV(0, ISE->getType()); const SCEV *Stride = Start; if (!getSCEVStartAndStride(ISE, L, UseLoop, Start, Stride, SE, DT)) return false; // Non-reducible symbolic expression, bail out. SmallPtrSet<Instruction *, 4> UniqueUsers; for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI) { Instruction *User = cast<Instruction>(*UI); if (!UniqueUsers.insert(User)) continue; // Do not infinitely recurse on PHI nodes. if (isa<PHINode>(User) && Processed.count(User)) continue; // Descend recursively, but not into PHI nodes outside the current loop. // It's important to see the entire expression outside the loop to get // choices that depend on addressing mode use right, although we won't // consider references ouside the loop in all cases. // If User is already in Processed, we don't want to recurse into it again, // but do want to record a second reference in the same instruction. bool AddUserToIVUsers = false; if (LI->getLoopFor(User->getParent()) != L) { if (isa<PHINode>(User) || Processed.count(User) || !AddUsersIfInteresting(User)) { DOUT << "FOUND USER in other loop: " << *User << " OF SCEV: " << *ISE << "\n"; AddUserToIVUsers = true; } } else if (Processed.count(User) || !AddUsersIfInteresting(User)) { DOUT << "FOUND USER: " << *User << " OF SCEV: " << *ISE << "\n"; AddUserToIVUsers = true; } if (AddUserToIVUsers) { IVUsersOfOneStride *StrideUses = IVUsesByStride[Stride]; if (!StrideUses) { // First occurrence of this stride? StrideOrder.push_back(Stride); StrideUses = new IVUsersOfOneStride(Stride); IVUses.push_back(StrideUses); IVUsesByStride[Stride] = StrideUses; } // Okay, we found a user that we cannot reduce. Analyze the instruction // and decide what to do with it. If we are a use inside of the loop, use // the value before incrementation, otherwise use it after incrementation. if (IVUseShouldUsePostIncValue(User, I, L, LI, DT, this)) { // The value used will be incremented by the stride more than we are // expecting, so subtract this off. const SCEV *NewStart = SE->getMinusSCEV(Start, Stride); StrideUses->addUser(NewStart, User, I); StrideUses->Users.back().setIsUseOfPostIncrementedValue(true); DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n"; } else { StrideUses->addUser(Start, User, I); } } } return true; } IVUsers::IVUsers() : LoopPass(&ID) { } void IVUsers::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<LoopInfo>(); AU.addRequired<DominatorTree>(); AU.addRequired<ScalarEvolution>(); AU.setPreservesAll(); } bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) { L = l; LI = &getAnalysis<LoopInfo>(); DT = &getAnalysis<DominatorTree>(); SE = &getAnalysis<ScalarEvolution>(); // Find all uses of induction variables in this loop, and categorize // them by stride. Start by finding all of the PHI nodes in the header for // this loop. If they are induction variables, inspect their uses. for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) AddUsersIfInteresting(I); return false; } /// getReplacementExpr - Return a SCEV expression which computes the /// value of the OperandValToReplace of the given IVStrideUse. const SCEV *IVUsers::getReplacementExpr(const IVStrideUse &U) const { // Start with zero. const SCEV *RetVal = SE->getIntegerSCEV(0, U.getParent()->Stride->getType()); // Create the basic add recurrence. RetVal = SE->getAddRecExpr(RetVal, U.getParent()->Stride, L); // Add the offset in a separate step, because it may be loop-variant. RetVal = SE->getAddExpr(RetVal, U.getOffset()); // For uses of post-incremented values, add an extra stride to compute // the actual replacement value. if (U.isUseOfPostIncrementedValue()) RetVal = SE->getAddExpr(RetVal, U.getParent()->Stride); // Evaluate the expression out of the loop, if possible. if (!L->contains(U.getUser()->getParent())) { const SCEV *ExitVal = SE->getSCEVAtScope(RetVal, L->getParentLoop()); if (ExitVal->isLoopInvariant(L)) RetVal = ExitVal; } return RetVal; } void IVUsers::print(raw_ostream &OS, const Module *M) const { OS << "IV Users for loop "; WriteAsOperand(OS, L->getHeader(), false); if (SE->hasLoopInvariantBackedgeTakenCount(L)) { OS << " with backedge-taken count " << *SE->getBackedgeTakenCount(L); } OS << ":\n"; for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) { std::map<const SCEV *, IVUsersOfOneStride*>::const_iterator SI = IVUsesByStride.find(StrideOrder[Stride]); assert(SI != IVUsesByStride.end() && "Stride doesn't exist!"); OS << " Stride " << *SI->first->getType() << " " << *SI->first << ":\n"; for (ilist<IVStrideUse>::const_iterator UI = SI->second->Users.begin(), E = SI->second->Users.end(); UI != E; ++UI) { OS << " "; WriteAsOperand(OS, UI->getOperandValToReplace(), false); OS << " = "; OS << *getReplacementExpr(*UI); if (UI->isUseOfPostIncrementedValue()) OS << " (post-inc)"; OS << " in "; UI->getUser()->print(OS); OS << '\n'; } } } void IVUsers::print(std::ostream &o, const Module *M) const { raw_os_ostream OS(o); print(OS, M); } void IVUsers::dump() const { print(errs()); } void IVUsers::releaseMemory() { IVUsesByStride.clear(); StrideOrder.clear(); Processed.clear(); } void IVStrideUse::deleted() { // Remove this user from the list. Parent->Users.erase(this); // this now dangles! } <commit_msg>Fix more missing newlines.<commit_after>//===- IVUsers.cpp - Induction Variable Users -------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements bookkeeping for "interesting" users of expressions // computed from induction variables. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "iv-users" #include "llvm/Analysis/IVUsers.h" #include "llvm/Constants.h" #include "llvm/Instructions.h" #include "llvm/Type.h" #include "llvm/DerivedTypes.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/ScalarEvolutionExpressions.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> using namespace llvm; char IVUsers::ID = 0; static RegisterPass<IVUsers> X("iv-users", "Induction Variable Users", false, true); Pass *llvm::createIVUsersPass() { return new IVUsers(); } /// containsAddRecFromDifferentLoop - Determine whether expression S involves a /// subexpression that is an AddRec from a loop other than L. An outer loop /// of L is OK, but not an inner loop nor a disjoint loop. static bool containsAddRecFromDifferentLoop(const SCEV *S, Loop *L) { // This is very common, put it first. if (isa<SCEVConstant>(S)) return false; if (const SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) { for (unsigned int i=0; i< AE->getNumOperands(); i++) if (containsAddRecFromDifferentLoop(AE->getOperand(i), L)) return true; return false; } if (const SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) { if (const Loop *newLoop = AE->getLoop()) { if (newLoop == L) return false; // if newLoop is an outer loop of L, this is OK. if (!LoopInfo::isNotAlreadyContainedIn(L, newLoop)) return false; } return true; } if (const SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S)) return containsAddRecFromDifferentLoop(DE->getLHS(), L) || containsAddRecFromDifferentLoop(DE->getRHS(), L); #if 0 // SCEVSDivExpr has been backed out temporarily, but will be back; we'll // need this when it is. if (const SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S)) return containsAddRecFromDifferentLoop(DE->getLHS(), L) || containsAddRecFromDifferentLoop(DE->getRHS(), L); #endif if (const SCEVCastExpr *CE = dyn_cast<SCEVCastExpr>(S)) return containsAddRecFromDifferentLoop(CE->getOperand(), L); return false; } /// getSCEVStartAndStride - Compute the start and stride of this expression, /// returning false if the expression is not a start/stride pair, or true if it /// is. The stride must be a loop invariant expression, but the start may be /// a mix of loop invariant and loop variant expressions. The start cannot, /// however, contain an AddRec from a different loop, unless that loop is an /// outer loop of the current loop. static bool getSCEVStartAndStride(const SCEV *&SH, Loop *L, Loop *UseLoop, const SCEV *&Start, const SCEV *&Stride, ScalarEvolution *SE, DominatorTree *DT) { const SCEV *TheAddRec = Start; // Initialize to zero. // If the outer level is an AddExpr, the operands are all start values except // for a nested AddRecExpr. if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) { for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i) if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) { if (AddRec->getLoop() == L) TheAddRec = SE->getAddExpr(AddRec, TheAddRec); else return false; // Nested IV of some sort? } else { Start = SE->getAddExpr(Start, AE->getOperand(i)); } } else if (isa<SCEVAddRecExpr>(SH)) { TheAddRec = SH; } else { return false; // not analyzable. } const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec); if (!AddRec || AddRec->getLoop() != L) return false; // Use getSCEVAtScope to attempt to simplify other loops out of // the picture. const SCEV *AddRecStart = AddRec->getStart(); AddRecStart = SE->getSCEVAtScope(AddRecStart, UseLoop); const SCEV *AddRecStride = AddRec->getStepRecurrence(*SE); // FIXME: If Start contains an SCEVAddRecExpr from a different loop, other // than an outer loop of the current loop, reject it. LSR has no concept of // operating on more than one loop at a time so don't confuse it with such // expressions. if (containsAddRecFromDifferentLoop(AddRecStart, L)) return false; Start = SE->getAddExpr(Start, AddRecStart); // If stride is an instruction, make sure it dominates the loop preheader. // Otherwise we could end up with a use before def situation. if (!isa<SCEVConstant>(AddRecStride)) { BasicBlock *Preheader = L->getLoopPreheader(); if (!AddRecStride->dominates(Preheader, DT)) return false; DEBUG(errs() << "[" << L->getHeader()->getName() << "] Variable stride: " << *AddRec << "\n"); } Stride = AddRecStride; return true; } /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression /// and now we need to decide whether the user should use the preinc or post-inc /// value. If this user should use the post-inc version of the IV, return true. /// /// Choosing wrong here can break dominance properties (if we choose to use the /// post-inc value when we cannot) or it can end up adding extra live-ranges to /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we /// should use the post-inc value). static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV, Loop *L, LoopInfo *LI, DominatorTree *DT, Pass *P) { // If the user is in the loop, use the preinc value. if (L->contains(User->getParent())) return false; BasicBlock *LatchBlock = L->getLoopLatch(); // Ok, the user is outside of the loop. If it is dominated by the latch // block, use the post-inc value. if (DT->dominates(LatchBlock, User->getParent())) return true; // There is one case we have to be careful of: PHI nodes. These little guys // can live in blocks that are not dominated by the latch block, but (since // their uses occur in the predecessor block, not the block the PHI lives in) // should still use the post-inc value. Check for this case now. PHINode *PN = dyn_cast<PHINode>(User); if (!PN) return false; // not a phi, not dominated by latch block. // Look at all of the uses of IV by the PHI node. If any use corresponds to // a block that is not dominated by the latch block, give up and use the // preincremented value. unsigned NumUses = 0; for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) if (PN->getIncomingValue(i) == IV) { ++NumUses; if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i))) return false; } // Okay, all uses of IV by PN are in predecessor blocks that really are // dominated by the latch block. Use the post-incremented value. return true; } /// AddUsersIfInteresting - Inspect the specified instruction. If it is a /// reducible SCEV, recursively add its users to the IVUsesByStride set and /// return true. Otherwise, return false. bool IVUsers::AddUsersIfInteresting(Instruction *I) { if (!SE->isSCEVable(I->getType())) return false; // Void and FP expressions cannot be reduced. // LSR is not APInt clean, do not touch integers bigger than 64-bits. if (SE->getTypeSizeInBits(I->getType()) > 64) return false; if (!Processed.insert(I)) return true; // Instruction already handled. // Get the symbolic expression for this instruction. const SCEV *ISE = SE->getSCEV(I); if (isa<SCEVCouldNotCompute>(ISE)) return false; // Get the start and stride for this expression. Loop *UseLoop = LI->getLoopFor(I->getParent()); const SCEV *Start = SE->getIntegerSCEV(0, ISE->getType()); const SCEV *Stride = Start; if (!getSCEVStartAndStride(ISE, L, UseLoop, Start, Stride, SE, DT)) return false; // Non-reducible symbolic expression, bail out. SmallPtrSet<Instruction *, 4> UniqueUsers; for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI) { Instruction *User = cast<Instruction>(*UI); if (!UniqueUsers.insert(User)) continue; // Do not infinitely recurse on PHI nodes. if (isa<PHINode>(User) && Processed.count(User)) continue; // Descend recursively, but not into PHI nodes outside the current loop. // It's important to see the entire expression outside the loop to get // choices that depend on addressing mode use right, although we won't // consider references ouside the loop in all cases. // If User is already in Processed, we don't want to recurse into it again, // but do want to record a second reference in the same instruction. bool AddUserToIVUsers = false; if (LI->getLoopFor(User->getParent()) != L) { if (isa<PHINode>(User) || Processed.count(User) || !AddUsersIfInteresting(User)) { DOUT << "FOUND USER in other loop: " << *User << '\n' << " OF SCEV: " << *ISE << "\n"; AddUserToIVUsers = true; } } else if (Processed.count(User) || !AddUsersIfInteresting(User)) { DOUT << "FOUND USER: " << *User << '\n' << " OF SCEV: " << *ISE << "\n"; AddUserToIVUsers = true; } if (AddUserToIVUsers) { IVUsersOfOneStride *StrideUses = IVUsesByStride[Stride]; if (!StrideUses) { // First occurrence of this stride? StrideOrder.push_back(Stride); StrideUses = new IVUsersOfOneStride(Stride); IVUses.push_back(StrideUses); IVUsesByStride[Stride] = StrideUses; } // Okay, we found a user that we cannot reduce. Analyze the instruction // and decide what to do with it. If we are a use inside of the loop, use // the value before incrementation, otherwise use it after incrementation. if (IVUseShouldUsePostIncValue(User, I, L, LI, DT, this)) { // The value used will be incremented by the stride more than we are // expecting, so subtract this off. const SCEV *NewStart = SE->getMinusSCEV(Start, Stride); StrideUses->addUser(NewStart, User, I); StrideUses->Users.back().setIsUseOfPostIncrementedValue(true); DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n"; } else { StrideUses->addUser(Start, User, I); } } } return true; } IVUsers::IVUsers() : LoopPass(&ID) { } void IVUsers::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<LoopInfo>(); AU.addRequired<DominatorTree>(); AU.addRequired<ScalarEvolution>(); AU.setPreservesAll(); } bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) { L = l; LI = &getAnalysis<LoopInfo>(); DT = &getAnalysis<DominatorTree>(); SE = &getAnalysis<ScalarEvolution>(); // Find all uses of induction variables in this loop, and categorize // them by stride. Start by finding all of the PHI nodes in the header for // this loop. If they are induction variables, inspect their uses. for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) AddUsersIfInteresting(I); return false; } /// getReplacementExpr - Return a SCEV expression which computes the /// value of the OperandValToReplace of the given IVStrideUse. const SCEV *IVUsers::getReplacementExpr(const IVStrideUse &U) const { // Start with zero. const SCEV *RetVal = SE->getIntegerSCEV(0, U.getParent()->Stride->getType()); // Create the basic add recurrence. RetVal = SE->getAddRecExpr(RetVal, U.getParent()->Stride, L); // Add the offset in a separate step, because it may be loop-variant. RetVal = SE->getAddExpr(RetVal, U.getOffset()); // For uses of post-incremented values, add an extra stride to compute // the actual replacement value. if (U.isUseOfPostIncrementedValue()) RetVal = SE->getAddExpr(RetVal, U.getParent()->Stride); // Evaluate the expression out of the loop, if possible. if (!L->contains(U.getUser()->getParent())) { const SCEV *ExitVal = SE->getSCEVAtScope(RetVal, L->getParentLoop()); if (ExitVal->isLoopInvariant(L)) RetVal = ExitVal; } return RetVal; } void IVUsers::print(raw_ostream &OS, const Module *M) const { OS << "IV Users for loop "; WriteAsOperand(OS, L->getHeader(), false); if (SE->hasLoopInvariantBackedgeTakenCount(L)) { OS << " with backedge-taken count " << *SE->getBackedgeTakenCount(L); } OS << ":\n"; for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) { std::map<const SCEV *, IVUsersOfOneStride*>::const_iterator SI = IVUsesByStride.find(StrideOrder[Stride]); assert(SI != IVUsesByStride.end() && "Stride doesn't exist!"); OS << " Stride " << *SI->first->getType() << " " << *SI->first << ":\n"; for (ilist<IVStrideUse>::const_iterator UI = SI->second->Users.begin(), E = SI->second->Users.end(); UI != E; ++UI) { OS << " "; WriteAsOperand(OS, UI->getOperandValToReplace(), false); OS << " = "; OS << *getReplacementExpr(*UI); if (UI->isUseOfPostIncrementedValue()) OS << " (post-inc)"; OS << " in "; UI->getUser()->print(OS); OS << '\n'; } } } void IVUsers::print(std::ostream &o, const Module *M) const { raw_os_ostream OS(o); print(OS, M); } void IVUsers::dump() const { print(errs()); } void IVUsers::releaseMemory() { IVUsesByStride.clear(); StrideOrder.clear(); Processed.clear(); } void IVStrideUse::deleted() { // Remove this user from the list. Parent->Users.erase(this); // this now dangles! } <|endoftext|>
<commit_before>// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/cctz_libc.h" #include <chrono> #include <cstdint> #include <ctime> namespace cctz { TimeZoneLibC::TimeZoneLibC(const std::string& name) { local_ = (name == "localtime"); if (!local_) { // TODO: Support "UTC-05:00", for example. offset_ = 0; abbr_ = "UTC"; } } Breakdown TimeZoneLibC::BreakTime(const time_point<seconds64>& tp) const { Breakdown bd; std::time_t t = ToUnixSeconds(tp); std::tm tm; if (local_) { localtime_r(&t, &tm); bd.abbr = tm.tm_zone; } else { gmtime_r(&t, &tm); tm.tm_gmtoff += offset_; bd.abbr = abbr_; } bd.year = tm.tm_year + 1900; bd.month = tm.tm_mon + 1; bd.day = tm.tm_mday; bd.hour = tm.tm_hour; bd.minute = tm.tm_min; bd.second = tm.tm_sec; bd.weekday = (tm.tm_wday ? tm.tm_wday : 7); bd.yearday = tm.tm_yday + 1; bd.is_dst = tm.tm_isdst; bd.offset = tm.tm_gmtoff; return bd; } namespace { // Normalize *val so that 0 <= *val < base, returning any carry. int NormalizeField(int base, int* val, bool* normalized) { int carry = *val / base; *val %= base; if (*val < 0) { carry -= 1; *val += base; } if (carry != 0) *normalized = true; return carry; } bool IsLeap(int64_t year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } // The month lengths in non-leap and leap years respectively. const int kDaysPerMonth[2][1+12] = { {-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {-1, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, }; // The number of days in non-leap and leap years respectively. const int kDaysPerYear[2] = {365, 366}; // Map a (normalized) Y/M/D to the number of days before/after 1970-01-01. // See http://howardhinnant.github.io/date_algorithms.html#days_from_civil. std::time_t DayOrdinal(int64_t year, int month, int day) { year -= (month <= 2 ? 1 : 0); const std::time_t era = (year >= 0 ? year : year - 399) / 400; const int yoe = year - era * 400; const int doy = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + day - 1; const int doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; return era * 146097 + doe - 719468; // shift epoch to 1970-01-01 } } // namespace TimeInfo TimeZoneLibC::MakeTimeInfo(int64_t year, int mon, int day, int hour, int min, int sec) const { bool normalized = false; std::time_t t; if (local_) { // Does not handle SKIPPED/AMBIGUOUS or huge years. std::tm tm; tm.tm_year = static_cast<int>(year - 1900); tm.tm_mon = mon - 1; tm.tm_mday = day; tm.tm_hour = hour; tm.tm_min = min; tm.tm_sec = sec; tm.tm_isdst = -1; t = std::mktime(&tm); if (tm.tm_year != year - 1900 || tm.tm_mon != mon - 1 || tm.tm_mday != day || tm.tm_hour != hour || tm.tm_min != min || tm.tm_sec != sec) { normalized = true; } } else { min += NormalizeField(60, &sec, &normalized); hour += NormalizeField(60, &min, &normalized); day += NormalizeField(24, &hour, &normalized); mon -= 1; // months are one-based year += NormalizeField(12, &mon, &normalized); mon += 1; // restore [1:12] year += (mon > 2 ? 1 : 0); int year_len = kDaysPerYear[IsLeap(year)]; while (day > year_len) { day -= year_len; year += 1; year_len = kDaysPerYear[IsLeap(year)]; } while (day <= 0) { year -= 1; day += kDaysPerYear[IsLeap(year)]; } year -= (mon > 2 ? 1 : 0); bool leap_year = IsLeap(year); while (day > kDaysPerMonth[leap_year][mon]) { day -= kDaysPerMonth[leap_year][mon]; if (++mon > 12) { mon = 1; year += 1; leap_year = IsLeap(year); } } t = ((((DayOrdinal(year, mon, day) * 24) + hour) * 60) + min) * 60 + sec; } TimeInfo ti; ti.kind = TimeInfo::Kind::UNIQUE; ti.pre = ti.trans = ti.post = FromUnixSeconds(t); ti.normalized = normalized; return ti; } } // namespace cctz <commit_msg>Make TimeZoneLibC portable by adding OFFSET(tm) and ABBR(tm).<commit_after>// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/cctz_libc.h" #include <chrono> #include <cstdint> #include <ctime> // Define OFFSET(tm) and ABBR(tm) for your platform to return the UTC // offset and zone abbreviation after a call to localtime_r(). #if defined(linux) # if defined(__USE_BSD) # define OFFSET(tm) ((tm).tm_gmtoff) # define ABBR(tm) ((tm).tm_zone) # else # define OFFSET(tm) ((tm).__tm_gmtoff) # define ABBR(tm) ((tm).__tm_zone) # endif #elif defined(__APPLE__) # define OFFSET(tm) ((tm).tm_gmtoff) # define ABBR(tm) ((tm).tm_zone) #elif defined(__sun) # define OFFSET(tm) ((tm).tm_isdst > 0 ? altzone : timezone) # define ABBR(tm) (tzname[(tm).tm_isdst > 0]) #else # define OFFSET(tm) (timezone + ((tm).tm_isdst > 0 ? 60 * 60 : 0)) # define ABBR(tm) (tzname[(tm).tm_isdst > 0]) #endif namespace cctz { TimeZoneLibC::TimeZoneLibC(const std::string& name) { local_ = (name == "localtime"); if (!local_) { // TODO: Support "UTC-05:00", for example. offset_ = 0; abbr_ = "UTC"; } } Breakdown TimeZoneLibC::BreakTime(const time_point<seconds64>& tp) const { Breakdown bd; std::time_t t = ToUnixSeconds(tp); std::tm tm; if (local_) { localtime_r(&t, &tm); bd.offset = OFFSET(tm); bd.abbr = ABBR(tm); } else { gmtime_r(&t, &tm); bd.offset = offset_; bd.abbr = abbr_; } bd.year = tm.tm_year + 1900; bd.month = tm.tm_mon + 1; bd.day = tm.tm_mday; bd.hour = tm.tm_hour; bd.minute = tm.tm_min; bd.second = tm.tm_sec; bd.weekday = (tm.tm_wday ? tm.tm_wday : 7); bd.yearday = tm.tm_yday + 1; bd.is_dst = tm.tm_isdst > 0; return bd; } namespace { // Normalize *val so that 0 <= *val < base, returning any carry. int NormalizeField(int base, int* val, bool* normalized) { int carry = *val / base; *val %= base; if (*val < 0) { carry -= 1; *val += base; } if (carry != 0) *normalized = true; return carry; } bool IsLeap(int64_t year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } // The month lengths in non-leap and leap years respectively. const int kDaysPerMonth[2][1+12] = { {-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {-1, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, }; // The number of days in non-leap and leap years respectively. const int kDaysPerYear[2] = {365, 366}; // Map a (normalized) Y/M/D to the number of days before/after 1970-01-01. // See http://howardhinnant.github.io/date_algorithms.html#days_from_civil. std::time_t DayOrdinal(int64_t year, int month, int day) { year -= (month <= 2 ? 1 : 0); const std::time_t era = (year >= 0 ? year : year - 399) / 400; const int yoe = year - era * 400; const int doy = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + day - 1; const int doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; return era * 146097 + doe - 719468; // shift epoch to 1970-01-01 } } // namespace TimeInfo TimeZoneLibC::MakeTimeInfo(int64_t year, int mon, int day, int hour, int min, int sec) const { bool normalized = false; std::time_t t; if (local_) { // Does not handle SKIPPED/AMBIGUOUS or huge years. std::tm tm; tm.tm_year = static_cast<int>(year - 1900); tm.tm_mon = mon - 1; tm.tm_mday = day; tm.tm_hour = hour; tm.tm_min = min; tm.tm_sec = sec; tm.tm_isdst = -1; t = std::mktime(&tm); if (tm.tm_year != year - 1900 || tm.tm_mon != mon - 1 || tm.tm_mday != day || tm.tm_hour != hour || tm.tm_min != min || tm.tm_sec != sec) { normalized = true; } } else { min += NormalizeField(60, &sec, &normalized); hour += NormalizeField(60, &min, &normalized); day += NormalizeField(24, &hour, &normalized); mon -= 1; // months are one-based year += NormalizeField(12, &mon, &normalized); mon += 1; // restore [1:12] year += (mon > 2 ? 1 : 0); int year_len = kDaysPerYear[IsLeap(year)]; while (day > year_len) { day -= year_len; year += 1; year_len = kDaysPerYear[IsLeap(year)]; } while (day <= 0) { year -= 1; day += kDaysPerYear[IsLeap(year)]; } year -= (mon > 2 ? 1 : 0); bool leap_year = IsLeap(year); while (day > kDaysPerMonth[leap_year][mon]) { day -= kDaysPerMonth[leap_year][mon]; if (++mon > 12) { mon = 1; year += 1; leap_year = IsLeap(year); } } t = ((((DayOrdinal(year, mon, day) * 24) + hour) * 60) + min) * 60 + sec; } TimeInfo ti; ti.kind = TimeInfo::Kind::UNIQUE; ti.pre = ti.trans = ti.post = FromUnixSeconds(t); ti.normalized = normalized; return ti; } } // namespace cctz <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: interact.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: sb $ $Date: 2002-12-06 10:48:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "interact.hxx" #include "com/sun/star/java/JavaDisabledException.hpp" #include "com/sun/star/java/JavaVMCreationFailureException.hpp" #include "com/sun/star/task/XInteractionAbort.hpp" #include "com/sun/star/task/XInteractionRetry.hpp" #include "com/sun/star/task/XInteractionContinuation.hpp" #include "cppuhelper/implbase1.hxx" #include "osl/mutex.hxx" namespace css = com::sun::star; using stoc_javavm::InteractionRequest; namespace { class AbortContinuation: public cppu::WeakImplHelper1< css::task::XInteractionAbort > { public: inline AbortContinuation() {} virtual inline void SAL_CALL select() throw (css::uno::RuntimeException) {} private: AbortContinuation(AbortContinuation &); // not implemented void operator =(AbortContinuation); // not implemented virtual inline ~AbortContinuation() {} }; } class InteractionRequest::RetryContinuation: public cppu::WeakImplHelper1< css::task::XInteractionRetry > { public: inline RetryContinuation(): m_bSelected(false) {} virtual void SAL_CALL select() throw (css::uno::RuntimeException); bool isSelected() const; private: RetryContinuation(RetryContinuation &); // not implemented void operator =(RetryContinuation); // not implemented virtual inline ~RetryContinuation() {} mutable osl::Mutex m_aMutex; bool m_bSelected; }; void SAL_CALL InteractionRequest::RetryContinuation::select() throw (css::uno::RuntimeException) { osl::MutexGuard aGuard(m_aMutex); m_bSelected = true; } bool InteractionRequest::RetryContinuation::isSelected() const { osl::MutexGuard aGuard(m_aMutex); return m_bSelected; } InteractionRequest::InteractionRequest(css::uno::Any const & rRequest): m_aRequest(rRequest) { bool bRetry; #if defined LINUX // Only if Java is disabled we allow retry: bRetry = m_aRequest.isExtractableTo( getCppuType(static_cast< css::java::JavaDisabledException * >(0))); #else // LINUX // If the creation of the JVM failed then do not offer retry, because Java // might crash next time: bRetry = !m_aRequest.isExtractableTo( getCppuType( static_cast< css::java::JavaVMCreationFailureException * >(0))); #endif // LINUX m_aContinuations.realloc(bRetry ? 2 : 1); m_aContinuations[0] = new AbortContinuation; if (bRetry) { m_xRetryContinuation = new RetryContinuation; m_aContinuations[1] = m_xRetryContinuation.get(); } } css::uno::Any SAL_CALL InteractionRequest::getRequest() throw (css::uno::RuntimeException) { return m_aRequest; } css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > > SAL_CALL InteractionRequest::getContinuations() throw (css::uno::RuntimeException) { return m_aContinuations; } bool InteractionRequest::retry() const { return m_xRetryContinuation.is() && m_xRetryContinuation->isSelected(); } InteractionRequest::~InteractionRequest() {} <commit_msg>INTEGRATION: CWS mh11rc (1.4.50); FILE MERGED 2003/06/06 08:16:55 mh 1.4.50.1: join: from beta2<commit_after>/************************************************************************* * * $RCSfile: interact.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2003-06-12 11:08:24 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "interact.hxx" #include "com/sun/star/java/JavaDisabledException.hpp" #include "com/sun/star/java/JavaVMCreationFailureException.hpp" #include "com/sun/star/task/XInteractionAbort.hpp" #include "com/sun/star/task/XInteractionRetry.hpp" #include "com/sun/star/task/XInteractionContinuation.hpp" #include "cppuhelper/implbase1.hxx" #include "osl/mutex.hxx" namespace css = com::sun::star; using stoc_javavm::InteractionRequest; namespace { class AbortContinuation: public cppu::WeakImplHelper1< css::task::XInteractionAbort > { public: inline AbortContinuation() {} virtual inline void SAL_CALL select() throw (css::uno::RuntimeException) {} private: AbortContinuation(AbortContinuation &); // not implemented void operator =(AbortContinuation); // not implemented virtual inline ~AbortContinuation() {} }; } class InteractionRequest::RetryContinuation: public cppu::WeakImplHelper1< css::task::XInteractionRetry > { public: inline RetryContinuation(): m_bSelected(false) {} virtual void SAL_CALL select() throw (css::uno::RuntimeException); bool isSelected() const; private: RetryContinuation(RetryContinuation &); // not implemented void operator =(RetryContinuation); // not implemented virtual inline ~RetryContinuation() {} mutable osl::Mutex m_aMutex; bool m_bSelected; }; void SAL_CALL InteractionRequest::RetryContinuation::select() throw (css::uno::RuntimeException) { osl::MutexGuard aGuard(m_aMutex); m_bSelected = true; } bool InteractionRequest::RetryContinuation::isSelected() const { osl::MutexGuard aGuard(m_aMutex); return m_bSelected; } InteractionRequest::InteractionRequest(css::uno::Any const & rRequest): m_aRequest(rRequest) { bool bRetry; #if defined LINUX || defined FREEBSD // Only if Java is disabled we allow retry: bRetry = m_aRequest.isExtractableTo( getCppuType(static_cast< css::java::JavaDisabledException * >(0))); #else // LINUX // If the creation of the JVM failed then do not offer retry, because Java // might crash next time: bRetry = !m_aRequest.isExtractableTo( getCppuType( static_cast< css::java::JavaVMCreationFailureException * >(0))); #endif // LINUX m_aContinuations.realloc(bRetry ? 2 : 1); m_aContinuations[0] = new AbortContinuation; if (bRetry) { m_xRetryContinuation = new RetryContinuation; m_aContinuations[1] = m_xRetryContinuation.get(); } } css::uno::Any SAL_CALL InteractionRequest::getRequest() throw (css::uno::RuntimeException) { return m_aRequest; } css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > > SAL_CALL InteractionRequest::getContinuations() throw (css::uno::RuntimeException) { return m_aContinuations; } bool InteractionRequest::retry() const { return m_xRetryContinuation.is() && m_xRetryContinuation->isSelected(); } InteractionRequest::~InteractionRequest() {} <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: interact.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: sb $ $Date: 2002-12-06 10:48:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #if !defined INCLUDED_STOC_JAVAVM_INTERACT_HXX #define INCLUDED_STOC_JAVAVM_INTERACT_HXX #include "com/sun/star/task/XInteractionRequest.hpp" #include "com/sun/star/uno/Any.hxx" #include "com/sun/star/uno/Reference.hxx" #include "com/sun/star/uno/Sequence.hxx" #include "cppuhelper/implbase1.hxx" #include "rtl/ref.hxx" namespace com { namespace sun { namespace star { namespace task { class XInteractionContinuation; } } } } namespace stoc_javavm { class InteractionRequest: public cppu::WeakImplHelper1< com::sun::star::task::XInteractionRequest > { public: explicit InteractionRequest(com::sun::star::uno::Any const & rRequest); virtual com::sun::star::uno::Any SAL_CALL getRequest() throw (com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< com::sun::star::uno::Reference< com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations() throw (com::sun::star::uno::RuntimeException); bool retry() const; private: class RetryContinuation; InteractionRequest(InteractionRequest &); // not implemented void operator =(InteractionRequest); // not implemented virtual ~InteractionRequest(); com::sun::star::uno::Any m_aRequest; com::sun::star::uno::Sequence< com::sun::star::uno::Reference< com::sun::star::task::XInteractionContinuation > > m_aContinuations; rtl::Reference< RetryContinuation > m_xRetryContinuation; }; } #endif // INCLUDED_STOC_JAVAVM_INTERACT_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.2.188); FILE MERGED 2005/09/05 17:10:55 rt 1.2.188.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: interact.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 07:58:38 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #if !defined INCLUDED_STOC_JAVAVM_INTERACT_HXX #define INCLUDED_STOC_JAVAVM_INTERACT_HXX #include "com/sun/star/task/XInteractionRequest.hpp" #include "com/sun/star/uno/Any.hxx" #include "com/sun/star/uno/Reference.hxx" #include "com/sun/star/uno/Sequence.hxx" #include "cppuhelper/implbase1.hxx" #include "rtl/ref.hxx" namespace com { namespace sun { namespace star { namespace task { class XInteractionContinuation; } } } } namespace stoc_javavm { class InteractionRequest: public cppu::WeakImplHelper1< com::sun::star::task::XInteractionRequest > { public: explicit InteractionRequest(com::sun::star::uno::Any const & rRequest); virtual com::sun::star::uno::Any SAL_CALL getRequest() throw (com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< com::sun::star::uno::Reference< com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations() throw (com::sun::star::uno::RuntimeException); bool retry() const; private: class RetryContinuation; InteractionRequest(InteractionRequest &); // not implemented void operator =(InteractionRequest); // not implemented virtual ~InteractionRequest(); com::sun::star::uno::Any m_aRequest; com::sun::star::uno::Sequence< com::sun::star::uno::Reference< com::sun::star::task::XInteractionContinuation > > m_aContinuations; rtl::Reference< RetryContinuation > m_xRetryContinuation; }; } #endif // INCLUDED_STOC_JAVAVM_INTERACT_HXX <|endoftext|>
<commit_before><commit_msg>Deserialize UMA flag on histograms moving from renderer to browsers<commit_after><|endoftext|>
<commit_before>// $Id: createSpectrumProcessor.C,v 1.11 2001/06/14 11:37:14 oliver Exp $ #include <BALL/NMR/createSpectrumProcessor.h> #include <BALL/NMR/shiftModule.h> #include <BALL/SYSTEM/path.h> #include <BALL/KERNEL/PTE.h> #include <BALL/KERNEL/atom.h> using namespace std; namespace BALL { CreateSpectrumProcessor::CreateSpectrumProcessor() : width_(1.0), use_averaging_(true), use_ignore_table_(true), expression_("element(H)") { } CreateSpectrumProcessor::~CreateSpectrumProcessor () throw() { } bool CreateSpectrumProcessor::start() throw() { // clear the contents of the old peak list peaklist_.clear(); return valid_; } void CreateSpectrumProcessor::init() throw() { valid_ = false; // read the contents of the ignore set // this hash set contains all quickly exchanging protons // -- thos protons are not seen in the spectrum and do // thus not produce a paek in the peak list. ignore_atoms_.clear(); Path path; String filename = path.find("NMR/ignore_atoms.dat"); if (filename == "") { Log.warn() << "CreateSpectrumProcessor::start: could not open atom ignore file NMR/ignore_atoms.dat" << endl; return; } ifstream infile(filename.c_str()); String name; while (infile.good()) { infile >> name; if (name != "") { ignore_atoms_.insert(name); } } infile.close(); infile.clear(); // read the list of equivalent protons filename = path.find("NMR/equivalent_atoms.dat"); if (filename == "") { Log.warn() << "CreateSpectrumProcessor::start: could not open atom equivalency file NMR/equivalent_atoms.dat" << endl; return; } // clear old contents equivalency_residues_.clear(); equivalency_atoms_.clear(); ifstream eqfile(filename.c_str()); while (eqfile.good()) { String residue, atoms; vector<String> equivalencies; eqfile >> residue >> atoms; if ((residue != "") && (atoms != "")) { atoms.split(equivalencies, ","); equivalency_residues_.push_back(residue); equivalency_atoms_.push_back(equivalencies); } } eqfile.close(); // initialization successful valid_ = true; return; } Processor::Result CreateSpectrumProcessor::operator () (Composite& composite) throw() { // Collect all atoms with assigned chemical shifts Atom* atom = dynamic_cast<Atom*>(&composite); if (atom != 0) { if (atom->hasProperty(ShiftModule::PROPERTY__SHIFT)) { float shift = atom->getProperty(ShiftModule::PROPERTY__SHIFT).getFloat(); // if the atom is in the ignore table, skip it if ((!(ignore_atoms_.has(atom->getFullName()) || ignore_atoms_.has("*:" + atom->getName())) || !use_ignore_table_) && (expression_(*atom) == true) && (shift != 0.0)) { Peak1D peak; peak.setAtom(atom); peak.setPosition(shift); peak.setWidth(width_); peak.setIntensity(1.0); peaklist_.push_back(peak); } } } if (use_averaging_ == true) { // average the shifts of chemically equivalent nuclei // in a residue Residue* residue = dynamic_cast<Residue*>(&composite); if (residue != 0) { String residue_name = residue->getName(); for (Position i = 0; i < equivalency_residues_.size(); i++) { if (residue_name == equivalency_residues_[i]) { float shift = 0.0; list<Atom*> atoms; for (AtomIterator it = residue->beginAtom(); +it; ++it) { for (Position j = 0; j < equivalency_atoms_[i].size(); j++) { if (equivalency_atoms_[i][j] == it->getName()) { atoms.push_back(&*it); shift += it->getProperty(ShiftModule::PROPERTY__SHIFT).getFloat(); break; } } } if (atoms.size() != 0) { shift /= (float)atoms.size(); list<Atom*>::const_iterator list_it = atoms.begin(); for (; list_it != atoms.end(); ++list_it) { (*list_it)->setProperty(ShiftModule::PROPERTY__SHIFT, shift); } } } } } } return Processor::CONTINUE; } const list<Peak1D>& CreateSpectrumProcessor::getPeakList() const { return peaklist_; } void CreateSpectrumProcessor::setWidth(float width) throw() { width_ = width; } float CreateSpectrumProcessor::getWidth() const throw() { return width_; } void CreateSpectrumProcessor::enableAveraging(bool flag) throw() { use_averaging_ = flag; } void CreateSpectrumProcessor::enableIgnoreTable(bool flag) throw() { use_ignore_table_ = flag; } void CreateSpectrumProcessor::setExpression(const String& expression) throw() { expression_.setExpression(expression); } } // namespace BALL <commit_msg>adapted: to PeakList type<commit_after>// $Id: createSpectrumProcessor.C,v 1.12 2001/07/14 23:01:30 oliver Exp $ #include <BALL/NMR/createSpectrumProcessor.h> #include <BALL/NMR/shiftModule.h> #include <BALL/SYSTEM/path.h> #include <BALL/KERNEL/PTE.h> #include <BALL/KERNEL/atom.h> using namespace std; namespace BALL { CreateSpectrumProcessor::CreateSpectrumProcessor() : width_(1.0), use_averaging_(true), use_ignore_table_(true), expression_("element(H)") { } CreateSpectrumProcessor::~CreateSpectrumProcessor () throw() { } bool CreateSpectrumProcessor::start() throw() { // clear the contents of the old peak list peaklist_.clear(); return valid_; } void CreateSpectrumProcessor::init() throw() { valid_ = false; // read the contents of the ignore set // this hash set contains all quickly exchanging protons // -- thos protons are not seen in the spectrum and do // thus not produce a paek in the peak list. ignore_atoms_.clear(); Path path; String filename = path.find("NMR/ignore_atoms.dat"); if (filename == "") { Log.warn() << "CreateSpectrumProcessor::start: could not open atom ignore file NMR/ignore_atoms.dat" << endl; return; } ifstream infile(filename.c_str()); String name; while (infile.good()) { infile >> name; if (name != "") { ignore_atoms_.insert(name); } } infile.close(); infile.clear(); // read the list of equivalent protons filename = path.find("NMR/equivalent_atoms.dat"); if (filename == "") { Log.warn() << "CreateSpectrumProcessor::start: could not open atom equivalency file NMR/equivalent_atoms.dat" << endl; return; } // clear old contents equivalency_residues_.clear(); equivalency_atoms_.clear(); ifstream eqfile(filename.c_str()); while (eqfile.good()) { String residue, atoms; vector<String> equivalencies; eqfile >> residue >> atoms; if ((residue != "") && (atoms != "")) { atoms.split(equivalencies, ","); equivalency_residues_.push_back(residue); equivalency_atoms_.push_back(equivalencies); } } eqfile.close(); // initialization successful valid_ = true; return; } Processor::Result CreateSpectrumProcessor::operator () (Composite& composite) throw() { // Collect all atoms with assigned chemical shifts Atom* atom = dynamic_cast<Atom*>(&composite); if (atom != 0) { if (atom->hasProperty(ShiftModule::PROPERTY__SHIFT)) { float shift = atom->getProperty(ShiftModule::PROPERTY__SHIFT).getFloat(); // if the atom is in the ignore table, skip it if ((!(ignore_atoms_.has(atom->getFullName()) || ignore_atoms_.has("*:" + atom->getName())) || !use_ignore_table_) && (expression_(*atom) == true) && (shift != 0.0)) { Peak1D peak; peak.setAtom(atom); peak.setPosition(shift); peak.setWidth(width_); peak.setIntensity(1.0); peaklist_.push_back(peak); } } } if (use_averaging_ == true) { // average the shifts of chemically equivalent nuclei // in a residue Residue* residue = dynamic_cast<Residue*>(&composite); if (residue != 0) { String residue_name = residue->getName(); for (Position i = 0; i < equivalency_residues_.size(); i++) { if (residue_name == equivalency_residues_[i]) { float shift = 0.0; list<Atom*> atoms; for (AtomIterator it = residue->beginAtom(); +it; ++it) { for (Position j = 0; j < equivalency_atoms_[i].size(); j++) { if (equivalency_atoms_[i][j] == it->getName()) { atoms.push_back(&*it); shift += it->getProperty(ShiftModule::PROPERTY__SHIFT).getFloat(); break; } } } if (atoms.size() != 0) { shift /= (float)atoms.size(); list<Atom*>::const_iterator list_it = atoms.begin(); for (; list_it != atoms.end(); ++list_it) { (*list_it)->setProperty(ShiftModule::PROPERTY__SHIFT, shift); } } } } } } return Processor::CONTINUE; } const PeakList1D& CreateSpectrumProcessor::getPeakList() const { return peaklist_; } void CreateSpectrumProcessor::setWidth(float width) throw() { width_ = width; } float CreateSpectrumProcessor::getWidth() const throw() { return width_; } void CreateSpectrumProcessor::enableAveraging(bool flag) throw() { use_averaging_ = flag; } void CreateSpectrumProcessor::enableIgnoreTable(bool flag) throw() { use_ignore_table_ = flag; } void CreateSpectrumProcessor::setExpression(const String& expression) throw() { expression_.setExpression(expression); } } // namespace BALL <|endoftext|>
<commit_before>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: VRMLRenderer.C,v 1.6.20.1 2007-03-25 21:57:01 oliver Exp $ // modified by Annette Treichel (2008.09.12) // #include <BALL/VIEW/RENDERING/VRMLRenderer.h> #include <BALL/VIEW/KERNEL/common.h> #include <BALL/VIEW/KERNEL/stage.h> #include <BALL/VIEW/PRIMITIVES/label.h> #include <BALL/VIEW/PRIMITIVES/line.h> #include <BALL/VIEW/PRIMITIVES/mesh.h> #include <BALL/VIEW/PRIMITIVES/point.h> #include <BALL/VIEW/PRIMITIVES/box.h> #include <BALL/VIEW/PRIMITIVES/simpleBox.h> #include <BALL/VIEW/PRIMITIVES/sphere.h> #include <BALL/VIEW/PRIMITIVES/tube.h> #include <BALL/VIEW/PRIMITIVES/disc.h> #include <BALL/VIEW/PRIMITIVES/twoColoredLine.h> #include <BALL/VIEW/PRIMITIVES/twoColoredTube.h> #include <BALL/VIEW/PRIMITIVES/mesh.h> #include <BALL/MATHS/surface.h> using std::endl; namespace BALL { namespace VIEW { VRMLRenderer::VRMLRenderer() throw() : Renderer(), outfile_(), current_indent_(0) { } VRMLRenderer::VRMLRenderer(const String& name) throw(Exception::FileNotFound) : Renderer(), width(600), height(600), current_indent_(0) { outfile_.open(name, std::ios::out); out_("#VRML V2.0 utf8"); out_(""); } VRMLRenderer::~VRMLRenderer() throw() { #ifdef BALL_VIEW_DEBUG Log.info() << "Destructing object " << (void *)this << " of class " << RTTI::getName<VRMLRenderer>() << std::endl; #endif } void VRMLRenderer::clear() throw() { outfile_.clear(); current_indent_ = 0; } void VRMLRenderer::setFileName(const String& name) throw(Exception::FileNotFound) { outfile_.open(name, std::ios::out); current_indent_ = 0; out_("#VRML V2.0 utf8"); out_(""); } String VRMLRenderer::VRMLColorRGBA(const ColorRGBA& input) throw() { return String((float) input.getRed()) + " " + String((float) input.getGreen()) + " " + String((float) input.getBlue()); } String VRMLRenderer::VRMLVector3(Vector3 input) throw() { // we convert into the new coordinate system: the camera looks // down the negative z axis and sits at (0,0,0) /* input += origin_; input = rotation_ * input; */ String output = ""; output+=String(input.x); output+=" "; output+=String(input.y); output+=" "; output+=String(input.z); return output; } // init must be called right before the rendering starts, since // we need to fix the camera, light sources, etc... bool VRMLRenderer::init(const Stage& stage) throw() { #ifdef BALL_VIEW_DEBUG_PROCESSORS Log.info() << "Start the VRMLRender output..." << std::endl; #endif stage_ = &stage; /* // Find out the position of the camera. const Camera& camera = stage_->getCamera(); view_point = camera.getViewPoint(); Vector3 up_vector = camera.getLookUpVector(); Vector3 right_vector = camera.getRightVector(); Vector3 look_at = camera.getLookAtPosition();// camera.getLookAtPosition(); */ //prepatation for use of sclaing scalingUsed = false; return true; } bool VRMLRenderer::finish() throw() { //before finishing we write the scaling if was used String infos = "# Biggest Values: (" + (String)(bigX) + "|"+ (String)(bigY) + "|"+ (String)(bigZ) + "); Smallest Values: (" + (String)smallX + "|"+ (String)smallY + "|"+ (String)smallZ +")"; String scaling = "# Boxsize: " + (String)(bigX - smallX) + " "+ (String)(bigY - smallY) + " "+ (String)(bigZ - smallZ) + "; Volume (unscaled, [mm^3]): "+ String((bigX - smallX)*(bigY - smallY)*(bigZ - smallZ)); out_(infos); out_(scaling); outfile_.close(); current_indent_ = 0; return true; } void VRMLRenderer::header_(const Vector3& translation, const ColorRGBA& color, const String& rotation) throw() { outheader_("Transform {"); if (rotation != "") { outheader_("rotation " + rotation); } outheader_("translation " + VRMLVector3(translation)); outheader_("children ["); outheader_("Shape {"); VRMLColor(color); } void VRMLRenderer::footer_() throw() { current_indent_ --; outfinish_("}"); outfinish_("}"); outfinish_("]"); out_("}"); } void VRMLRenderer::renderSphere_(const Sphere& sphere) throw() { header_(sphere.getPosition(), sphere.getColor()); outheader_("geometry Sphere {"); out_("radius " + String(sphere.getRadius())); footer_(); } void VRMLRenderer::renderLine_(const Line& miniTube) throw() { static Vector3 default_angle(0,1,0); Vector3 v = miniTube.getVertex2() - miniTube.getVertex1(); float f = v.getAngle(default_angle); Vector3 a = default_angle % v; String r; if (!Maths::isZero(a.getSquareLength())) { a.normalize(); r = String(a.x) + " " + String(a.y) + " " + String(a.z) + " "; r += String(f); } header_(miniTube.getVertex1() + v / 2.0, miniTube.getColor(), r); outheader_("geometry Cylinder {"); out_("height " + String(v.getLength())); out_("radius " + String((v.getLength() / 100.0))); footer_(); } void VRMLRenderer::renderTwoColoredLine_(const TwoColoredLine& miniTube) throw() { static Vector3 default_angle(0,1,0); Vector3 v = miniTube.getVertex2() - miniTube.getVertex1(); float f = v.getAngle(default_angle); Vector3 a = default_angle % v; String r; if (!Maths::isZero(a.getSquareLength())) { a.normalize(); r = String(a.x) + " " + String(a.y) + " " + String(a.z) + " "; r += String(f); } //erste halbe linie: header_(miniTube.getVertex1() + v / 4.0, miniTube.getColor(), r); outheader_("geometry Cylinder {"); out_("height " + String((v.getLength() / 2.0))); out_("radius " + String((v.getLength() / 100.0))); footer_(); //zweite halbe Linie: header_(miniTube.getVertex1() + v / (4.0 / 3.0), miniTube.getColor2(), r); outheader_("geometry Cylinder {"); out_("height " + String((v.getLength() / 2.0))); out_("radius " + String((v.getLength() / 100.0 ))); footer_(); } void VRMLRenderer::renderTube_(const Tube& tube) throw() { static Vector3 default_angle(0,1,0); Vector3 v = tube.getVertex2() - tube.getVertex1(); float f = v.getAngle(default_angle); Vector3 a = default_angle % v; String r; if (!Maths::isZero(a.getSquareLength())) { a.normalize(); r = String(a.x) + " " + String(a.y) + " " + String(a.z) + " "; r += String(f); } header_(tube.getVertex1() + v / 2.0, tube.getColor(), r); outheader_("geometry Cylinder {"); out_("height " + String(v.getLength())); out_("radius " + String(tube.getRadius())); footer_(); } void VRMLRenderer::renderTwoColoredTube_(const TwoColoredTube& tube) throw() { static Vector3 default_angle(0,1,0); Vector3 v = tube.getVertex2() - tube.getVertex1(); float f = v.getAngle(default_angle); Vector3 a = default_angle % v; String r; if (!Maths::isZero(a.getSquareLength())) { a.normalize(); r = String(a.x) + " " + String(a.y) + " " + String(a.z) + " "; r += String(f); } //erstes halbes rohr: header_(tube.getVertex1() + v / 4.0, tube.getColor(), r); outheader_("geometry Cylinder {"); out_("height " + String((v.getLength() / 2.0))); out_("radius " + String(tube.getRadius())); footer_(); //zweites halbes rohr: header_(tube.getVertex1() + v / (4.0 / 3.0), tube.getColor2(), r); outheader_("geometry Cylinder {"); out_("height " + String((v.getLength() / 2.0))); out_("radius " + String(tube.getRadius())); footer_(); } void VRMLRenderer::VRMLColor(const ColorRGBA& color) throw() { outheader_("appearance Appearance {"); outheader_("material Material {"); out_("diffuseColor " + VRMLColorRGBA(color)); out_("shininess 0.5"); current_indent_ --; outfinish_("}"); outfinish_("}"); } void VRMLRenderer::renderMesh_(const Mesh& mesh) throw() { // so we should let VRMLRay know... outheader_("Shape {"); outheader_("geometry IndexedFaceSet {"); out_("normalPerVertex TRUE"); outheader_("coord Coordinate {"); outheader_("point ["); // print vertices vector<Vector3>::const_iterator itv = mesh.vertex.begin(); for (; itv != mesh.vertex.end(); itv++) { String out = VRMLVector3(*itv); if (itv != mesh.vertex.end()) { out += ","; } out_(out); //scaling max and min search if(scalingUsed) { //X value: if (smallX > (*itv).x) { smallX = (*itv).x; } if (bigX < (*itv).x) { bigX = (*itv).x; } //Y value: if (smallY > (*itv).y) { smallY = (*itv).y; } if (bigY < (*itv).y) { bigY = (*itv).y; } //Z value: if (smallZ > (*itv).z) { smallZ = (*itv).z; } if (bigZ < (*itv).z) { bigZ = (*itv).z; } } else { //als initiationswerte werden einfach die ersten Koordinaten genommen smallX = (*itv).x; bigX = (*itv).x; smallY = (*itv).y; bigY = (*itv).y; smallZ = (*itv).z; bigZ = (*itv).z; scalingUsed = true; } } current_indent_ --; outfinish_("]"); out_("}"); // correct // print triangles ===================================== outheader_("coordIndex ["); vector<Surface::Triangle>::const_iterator itt = mesh.triangle.begin(); for (; itt != mesh.triangle.end(); itt++) { String out = (String((*itt).v1) + " " + String((*itt).v2) + " " + String((*itt).v3) + ", -1"); if (itt != mesh.triangle.end()) { out += ","; } out_(out); } outfinish_("]"); // print normals ===================================== //Normals are not needed for printing and increase amount of data therefore I take them away /* outheader_("normal Normal {"); outheader_("vector ["); itv = mesh.normal.begin(); for (; itv != mesh.normal.end(); itv++) { String out = VRMLVector3(*itv); if (itv != mesh.normal.end()) { out += ","; } out_(out); } outfinish_("]"); outfinish_("}"); */ /* outheader_("normalIndex ["); for (Position i = 0; i < mesh.vertex.size(); i++) { String si(i); out_(si + ", " + si + ", " + si); } outfinish_("]"); */ // print colors ======================================== outheader_("color Color {"); outheader_("color ["); if (mesh.colors.size() == 0) { out_(VRMLColorRGBA(ColorRGBA(1.,1,1))); } else { vector<ColorRGBA>::const_iterator itc = mesh.colors.begin(); for (; itc != mesh.colors.end(); itc++) { String out = VRMLColorRGBA(*itc); if (itc != mesh.colors.end()) { out += ","; } out_(out); } } current_indent_ --; outfinish_("]"); out_("}"); if (mesh.colors.size() > 1) { outfinish_("colorPerVertex TRUE"); } else { outfinish_("colorPerVertex FALSE"); } outfinish_("}"); outfinish_("}"); } void VRMLRenderer::out_(const String& data) throw() { if (current_indent_ < 0) { // BALLVIEW_DEBUG } String out; for (Index p=0; p< current_indent_; p++) { out += " "; } out += data; outfile_ << out << std::endl; } } } // namespaces <commit_msg>Fixed VRML export of one colored meshes<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: VRMLRenderer.C,v 1.6.20.1 2007-03-25 21:57:01 oliver Exp $ // modified by Annette Treichel (2008.09.12) // #include <BALL/VIEW/RENDERING/VRMLRenderer.h> #include <BALL/VIEW/KERNEL/common.h> #include <BALL/VIEW/KERNEL/stage.h> #include <BALL/VIEW/PRIMITIVES/label.h> #include <BALL/VIEW/PRIMITIVES/line.h> #include <BALL/VIEW/PRIMITIVES/mesh.h> #include <BALL/VIEW/PRIMITIVES/point.h> #include <BALL/VIEW/PRIMITIVES/box.h> #include <BALL/VIEW/PRIMITIVES/simpleBox.h> #include <BALL/VIEW/PRIMITIVES/sphere.h> #include <BALL/VIEW/PRIMITIVES/tube.h> #include <BALL/VIEW/PRIMITIVES/disc.h> #include <BALL/VIEW/PRIMITIVES/twoColoredLine.h> #include <BALL/VIEW/PRIMITIVES/twoColoredTube.h> #include <BALL/VIEW/PRIMITIVES/mesh.h> #include <BALL/MATHS/surface.h> using std::endl; namespace BALL { namespace VIEW { VRMLRenderer::VRMLRenderer() throw() : Renderer(), outfile_(), current_indent_(0) { } VRMLRenderer::VRMLRenderer(const String& name) throw(Exception::FileNotFound) : Renderer(), width(600), height(600), current_indent_(0) { outfile_.open(name, std::ios::out); out_("#VRML V2.0 utf8"); out_(""); } VRMLRenderer::~VRMLRenderer() throw() { #ifdef BALL_VIEW_DEBUG Log.info() << "Destructing object " << (void *)this << " of class " << RTTI::getName<VRMLRenderer>() << std::endl; #endif } void VRMLRenderer::clear() throw() { outfile_.clear(); current_indent_ = 0; } void VRMLRenderer::setFileName(const String& name) throw(Exception::FileNotFound) { outfile_.open(name, std::ios::out); current_indent_ = 0; out_("#VRML V2.0 utf8"); out_(""); } String VRMLRenderer::VRMLColorRGBA(const ColorRGBA& input) throw() { return String((float) input.getRed()) + " " + String((float) input.getGreen()) + " " + String((float) input.getBlue()); } String VRMLRenderer::VRMLVector3(Vector3 input) throw() { // we convert into the new coordinate system: the camera looks // down the negative z axis and sits at (0,0,0) /* input += origin_; input = rotation_ * input; */ String output = ""; output+=String(input.x); output+=" "; output+=String(input.y); output+=" "; output+=String(input.z); return output; } // init must be called right before the rendering starts, since // we need to fix the camera, light sources, etc... bool VRMLRenderer::init(const Stage& stage) throw() { #ifdef BALL_VIEW_DEBUG_PROCESSORS Log.info() << "Start the VRMLRender output..." << std::endl; #endif stage_ = &stage; /* // Find out the position of the camera. const Camera& camera = stage_->getCamera(); view_point = camera.getViewPoint(); Vector3 up_vector = camera.getLookUpVector(); Vector3 right_vector = camera.getRightVector(); Vector3 look_at = camera.getLookAtPosition();// camera.getLookAtPosition(); */ //prepatation for use of sclaing scalingUsed = false; return true; } bool VRMLRenderer::finish() throw() { //before finishing we write the scaling if was used String infos = "# Biggest Values: (" + (String)(bigX) + "|"+ (String)(bigY) + "|"+ (String)(bigZ) + "); Smallest Values: (" + (String)smallX + "|"+ (String)smallY + "|"+ (String)smallZ +")"; String scaling = "# Boxsize: " + (String)(bigX - smallX) + " "+ (String)(bigY - smallY) + " "+ (String)(bigZ - smallZ) + "; Volume (unscaled, [mm^3]): "+ String((bigX - smallX)*(bigY - smallY)*(bigZ - smallZ)); out_(infos); out_(scaling); outfile_.close(); current_indent_ = 0; return true; } void VRMLRenderer::header_(const Vector3& translation, const ColorRGBA& color, const String& rotation) throw() { outheader_("Transform {"); if (rotation != "") { outheader_("rotation " + rotation); } outheader_("translation " + VRMLVector3(translation)); outheader_("children ["); outheader_("Shape {"); VRMLColor(color); } void VRMLRenderer::footer_() throw() { current_indent_ --; outfinish_("}"); outfinish_("}"); outfinish_("]"); out_("}"); } void VRMLRenderer::renderSphere_(const Sphere& sphere) throw() { header_(sphere.getPosition(), sphere.getColor()); outheader_("geometry Sphere {"); out_("radius " + String(sphere.getRadius())); footer_(); } void VRMLRenderer::renderLine_(const Line& miniTube) throw() { static Vector3 default_angle(0,1,0); Vector3 v = miniTube.getVertex2() - miniTube.getVertex1(); float f = v.getAngle(default_angle); Vector3 a = default_angle % v; String r; if (!Maths::isZero(a.getSquareLength())) { a.normalize(); r = String(a.x) + " " + String(a.y) + " " + String(a.z) + " "; r += String(f); } header_(miniTube.getVertex1() + v / 2.0, miniTube.getColor(), r); outheader_("geometry Cylinder {"); out_("height " + String(v.getLength())); out_("radius " + String((v.getLength() / 100.0))); footer_(); } void VRMLRenderer::renderTwoColoredLine_(const TwoColoredLine& miniTube) throw() { static Vector3 default_angle(0,1,0); Vector3 v = miniTube.getVertex2() - miniTube.getVertex1(); float f = v.getAngle(default_angle); Vector3 a = default_angle % v; String r; if (!Maths::isZero(a.getSquareLength())) { a.normalize(); r = String(a.x) + " " + String(a.y) + " " + String(a.z) + " "; r += String(f); } //erste halbe linie: header_(miniTube.getVertex1() + v / 4.0, miniTube.getColor(), r); outheader_("geometry Cylinder {"); out_("height " + String((v.getLength() / 2.0))); out_("radius " + String((v.getLength() / 100.0))); footer_(); //zweite halbe Linie: header_(miniTube.getVertex1() + v / (4.0 / 3.0), miniTube.getColor2(), r); outheader_("geometry Cylinder {"); out_("height " + String((v.getLength() / 2.0))); out_("radius " + String((v.getLength() / 100.0 ))); footer_(); } void VRMLRenderer::renderTube_(const Tube& tube) throw() { static Vector3 default_angle(0,1,0); Vector3 v = tube.getVertex2() - tube.getVertex1(); float f = v.getAngle(default_angle); Vector3 a = default_angle % v; String r; if (!Maths::isZero(a.getSquareLength())) { a.normalize(); r = String(a.x) + " " + String(a.y) + " " + String(a.z) + " "; r += String(f); } header_(tube.getVertex1() + v / 2.0, tube.getColor(), r); outheader_("geometry Cylinder {"); out_("height " + String(v.getLength())); out_("radius " + String(tube.getRadius())); footer_(); } void VRMLRenderer::renderTwoColoredTube_(const TwoColoredTube& tube) throw() { static Vector3 default_angle(0,1,0); Vector3 v = tube.getVertex2() - tube.getVertex1(); float f = v.getAngle(default_angle); Vector3 a = default_angle % v; String r; if (!Maths::isZero(a.getSquareLength())) { a.normalize(); r = String(a.x) + " " + String(a.y) + " " + String(a.z) + " "; r += String(f); } //erstes halbes rohr: header_(tube.getVertex1() + v / 4.0, tube.getColor(), r); outheader_("geometry Cylinder {"); out_("height " + String((v.getLength() / 2.0))); out_("radius " + String(tube.getRadius())); footer_(); //zweites halbes rohr: header_(tube.getVertex1() + v / (4.0 / 3.0), tube.getColor2(), r); outheader_("geometry Cylinder {"); out_("height " + String((v.getLength() / 2.0))); out_("radius " + String(tube.getRadius())); footer_(); } void VRMLRenderer::VRMLColor(const ColorRGBA& color) throw() { outheader_("appearance Appearance {"); outheader_("material Material {"); out_("diffuseColor " + VRMLColorRGBA(color)); out_("shininess 0.5"); current_indent_ --; outfinish_("}"); outfinish_("}"); } void VRMLRenderer::renderMesh_(const Mesh& mesh) throw() { // so we should let VRMLRay know... outheader_("Shape {"); // if we have no or only a single color, we need an apearance node for the whole mesh if (mesh.colors.size() == 0) { VRMLColor(ColorRGBA(1.,1,1)); } else if (mesh.colors.size() == 1) { VRMLColor(mesh.colors[0]); } outheader_("geometry IndexedFaceSet {"); out_("normalPerVertex TRUE"); outheader_("coord Coordinate {"); outheader_("point ["); // print vertices vector<Vector3>::const_iterator itv = mesh.vertex.begin(); for (; itv != mesh.vertex.end(); itv++) { String out = VRMLVector3(*itv); if (itv != mesh.vertex.end()) { out += ","; } out_(out); //scaling max and min search if(scalingUsed) { //X value: if (smallX > (*itv).x) { smallX = (*itv).x; } if (bigX < (*itv).x) { bigX = (*itv).x; } //Y value: if (smallY > (*itv).y) { smallY = (*itv).y; } if (bigY < (*itv).y) { bigY = (*itv).y; } //Z value: if (smallZ > (*itv).z) { smallZ = (*itv).z; } if (bigZ < (*itv).z) { bigZ = (*itv).z; } } else { //als initiationswerte werden einfach die ersten Koordinaten genommen smallX = (*itv).x; bigX = (*itv).x; smallY = (*itv).y; bigY = (*itv).y; smallZ = (*itv).z; bigZ = (*itv).z; scalingUsed = true; } } current_indent_ --; outfinish_("]"); out_("}"); // correct // print triangles ===================================== outheader_("coordIndex ["); vector<Surface::Triangle>::const_iterator itt = mesh.triangle.begin(); for (; itt != mesh.triangle.end(); itt++) { String out = (String((*itt).v1) + " " + String((*itt).v2) + " " + String((*itt).v3) + ", -1"); if (itt != mesh.triangle.end()) { out += ","; } out_(out); } outfinish_("]"); // print normals ===================================== //Normals are not needed for printing and increase amount of data therefore I take them away /* outheader_("normal Normal {"); outheader_("vector ["); itv = mesh.normal.begin(); for (; itv != mesh.normal.end(); itv++) { String out = VRMLVector3(*itv); if (itv != mesh.normal.end()) { out += ","; } out_(out); } outfinish_("]"); outfinish_("}"); */ /* outheader_("normalIndex ["); for (Position i = 0; i < mesh.vertex.size(); i++) { String si(i); out_(si + ", " + si + ", " + si); } outfinish_("]"); */ // print colors ======================================== outheader_("color Color {"); outheader_("color ["); if (mesh.colors.size() > 1) { vector<ColorRGBA>::const_iterator itc = mesh.colors.begin(); for (; itc != mesh.colors.end(); itc++) { String out = VRMLColorRGBA(*itc); if (itc != mesh.colors.end()) { out += ","; } out_(out); } } current_indent_ --; outfinish_("]"); out_("}"); if (mesh.colors.size() > 1) { outfinish_("colorPerVertex TRUE"); } else { outfinish_("colorPerVertex FALSE"); } outfinish_("}"); outfinish_("}"); } void VRMLRenderer::out_(const String& data) throw() { if (current_indent_ < 0) { // BALLVIEW_DEBUG } String out; for (Index p=0; p< current_indent_; p++) { out += " "; } out += data; outfile_ << out << std::endl; } } } // namespaces <|endoftext|>
<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "autocomplete.h" #include "type/pt_data.h" namespace navitia { namespace autocomplete { void compute_score_poi(type::PT_Data&, georef::GeoRef &georef) { for (auto it = georef.fl_poi.word_quality_list.begin(); it != georef.fl_poi.word_quality_list.end(); ++it){ for (navitia::georef::Admin* admin : georef.pois[it->first]->admin_list){ if(admin->level == 8){ (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score; } } } } void compute_score_way(type::PT_Data&, georef::GeoRef &georef) { for (auto it = georef.fl_way.word_quality_list.begin(); it != georef.fl_way.word_quality_list.end(); ++it){ for (navitia::georef::Admin* admin : georef.ways[it->first]->admin_list){ if (admin->level == 8){ //georef.fl_way.ac_list.at(it->first).score = georef.fl_admin.ac_list.at(admin->idx).score; (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score; } } } } void compute_score_stop_point(type::PT_Data &pt_data, georef::GeoRef &georef) { //Récupérer le score de son admin du niveau 8 dans le autocomplete: georef.fl_admin for (auto it = pt_data.stop_point_autocomplete.word_quality_list.begin(); it != pt_data.stop_point_autocomplete.word_quality_list.end(); ++it){ for(navitia::georef::Admin* admin : pt_data.stop_points[it->first]->admin_list){ if (admin->level == 8){ (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score; } } } } void compute_score_stop_area(type::PT_Data & pt_data){ //Calculate de maximum stop-point count; unsigned int max_score = 0; for (navitia::type::StopArea* sa : pt_data.stop_areas){ max_score = std::max(max_score, sa->stop_point_list.size()); } //Ajust the score of each stop_area from 0 to 100 using maximum score (max_score) if (max_score > 0){ for (auto it = pt_data.stop_area_autocomplete.word_quality_list.begin(); it != pt_data.stop_area_autocomplete.word_quality_list.end(); ++it){ it->second.score = (pt_data.stop_areas[it->first]->stop_point_list.size() * 100)/max_score; } } } void compute_score_admin(type::PT_Data &pt_data, georef::GeoRef &georef) { int max_score = 0; //Pour chaque stop_point incrémenter le score de son admin de niveau 8 par 1. for (navitia::type::StopPoint* sp : pt_data.stop_points){ for (navitia::georef::Admin * admin : sp->admin_list){ if (admin->level == 8){ georef.fl_admin.word_quality_list.at(admin->idx).score++; } } } //Calculer le max_score des admins for (auto it = georef.fl_admin.word_quality_list.begin(); it != georef.fl_admin.word_quality_list.end(); ++it){ max_score = ((it->second).score > max_score)?(it->second).score:max_score; } //Ajuster le score de chaque admin an utilisant le max_score. for (auto it = georef.fl_admin.word_quality_list.begin(); it != georef.fl_admin.word_quality_list.end(); ++it){ (it->second).score = max_score == 0 ? 0 : ((it->second).score * 100)/max_score; } } void compute_score_line(type::PT_Data&, georef::GeoRef&) { } template<> void Autocomplete<type::idx_t>::compute_score(type::PT_Data &pt_data, georef::GeoRef &georef, const type::Type_e type) { switch(type){ case type::Type_e::StopArea: compute_score_stop_area(pt_data); break; case type::Type_e::StopPoint: compute_score_stop_point(pt_data, georef); break; case type::Type_e::Line: compute_score_line(pt_data, georef); break; case type::Type_e::Admin: compute_score_admin(pt_data, georef); break; case type::Type_e::Way: compute_score_way(pt_data, georef); break; case type::Type_e::POI: compute_score_poi(pt_data, georef); break; default: break; } } }} <commit_msg>Autocomplete : Correction after remark.<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "autocomplete.h" #include "type/pt_data.h" namespace navitia { namespace autocomplete { void compute_score_poi(type::PT_Data&, georef::GeoRef &georef) { for (auto it = georef.fl_poi.word_quality_list.begin(); it != georef.fl_poi.word_quality_list.end(); ++it){ for (navitia::georef::Admin* admin : georef.pois[it->first]->admin_list){ if(admin->level == 8){ (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score; } } } } void compute_score_way(type::PT_Data&, georef::GeoRef &georef) { for (auto it = georef.fl_way.word_quality_list.begin(); it != georef.fl_way.word_quality_list.end(); ++it){ for (navitia::georef::Admin* admin : georef.ways[it->first]->admin_list){ if (admin->level == 8){ //georef.fl_way.ac_list.at(it->first).score = georef.fl_admin.ac_list.at(admin->idx).score; (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score; } } } } void compute_score_stop_point(type::PT_Data &pt_data, georef::GeoRef &georef) { //Récupérer le score de son admin du niveau 8 dans le autocomplete: georef.fl_admin for (auto it = pt_data.stop_point_autocomplete.word_quality_list.begin(); it != pt_data.stop_point_autocomplete.word_quality_list.end(); ++it){ for(navitia::georef::Admin* admin : pt_data.stop_points[it->first]->admin_list){ if (admin->level == 8){ (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score; } } } } void compute_score_stop_area(type::PT_Data & pt_data){ //Calculate de maximum stop-point count; size_t max_score = 0; for (navitia::type::StopArea* sa : pt_data.stop_areas){ max_score = std::max(max_score, sa->stop_point_list.size()); } //Ajust the score of each stop_area from 0 to 100 using maximum score (max_score) if (max_score > 0){ for (auto & it : pt_data.stop_area_autocomplete.word_quality_list){ it.second.score = (pt_data.stop_areas[it.first]->stop_point_list.size() * 100)/max_score; } } } void compute_score_admin(type::PT_Data &pt_data, georef::GeoRef &georef) { int max_score = 0; //Pour chaque stop_point incrémenter le score de son admin de niveau 8 par 1. for (navitia::type::StopPoint* sp : pt_data.stop_points){ for (navitia::georef::Admin * admin : sp->admin_list){ if (admin->level == 8){ georef.fl_admin.word_quality_list.at(admin->idx).score++; } } } //Calculer le max_score des admins for (auto it = georef.fl_admin.word_quality_list.begin(); it != georef.fl_admin.word_quality_list.end(); ++it){ max_score = ((it->second).score > max_score)?(it->second).score:max_score; } //Ajuster le score de chaque admin an utilisant le max_score. for (auto it = georef.fl_admin.word_quality_list.begin(); it != georef.fl_admin.word_quality_list.end(); ++it){ (it->second).score = max_score == 0 ? 0 : ((it->second).score * 100)/max_score; } } void compute_score_line(type::PT_Data&, georef::GeoRef&) { } template<> void Autocomplete<type::idx_t>::compute_score(type::PT_Data &pt_data, georef::GeoRef &georef, const type::Type_e type) { switch(type){ case type::Type_e::StopArea: compute_score_stop_area(pt_data); break; case type::Type_e::StopPoint: compute_score_stop_point(pt_data, georef); break; case type::Type_e::Line: compute_score_line(pt_data, georef); break; case type::Type_e::Admin: compute_score_admin(pt_data, georef); break; case type::Type_e::Way: compute_score_way(pt_data, georef); break; case type::Type_e::POI: compute_score_poi(pt_data, georef); break; default: break; } } }} <|endoftext|>
<commit_before>#include <cppassert/details/DebugPrint.hpp> #include <cppassert/details/StackTrace.hpp> #include <stdexcept> #include <memory> #include <mutex> #include <cstdlib> #include <Windows.h> #include <DbgHelp.h> #include <strsafe.h> namespace cppassert { namespace internal { /** * Displays error message related to last occured error * */ void DisplayLastError(LPTSTR lpszFunction) { // Retrieve the system error message for the last-error code LPVOID lpMsgBuf; LPVOID lpDisplayBuf; DWORD dw = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); // Display the error message and exit the process lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR)); StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(TCHAR), TEXT("%s failed with error %d: %s"), lpszFunction, dw, lpMsgBuf); PrintMessageToStdErr((LPCSTR)lpDisplayBuf); LocalFree(lpMsgBuf); LocalFree(lpDisplayBuf); } /** * Provides windows implementation of stack trace collection. */ class StackTraceImpl { StackTraceImpl(const StackTraceImpl &) = delete; StackTraceImpl &operator=(const StackTraceImpl &) = delete; struct BacktraceSymbol : public StackTrace::StackFrame { BacktraceSymbol() = default; BacktraceSymbol(const void *frameAddr, const char *name) { address_ = frameAddr; setSymbol(name); } void setAddress(const void *frameAddress) { address_ = frameAddress; } void setSymbol(const char *name) { if (name && name[0]) { strcpy_s(symbolName_, MaxSymbolNameSize, name); symbolName_[MaxSymbolNameSize - 1] = '\0'; } else { symbolName_[0] = '\0'; } symbol_ = symbolName_; } enum { MaxSymbolNameSize = MAX_SYM_NAME + 1 }; char symbolName_[MaxSymbolNameSize]; }; public: StackTraceImpl() { } ~StackTraceImpl() { } void collect() { HANDLE process; ULONG frame; PSYMBOL_INFO symbol; DWORD64 displacement; PVOID frames[cFramesSize]; enum { MaxNameLen = MAX_SYM_NAME + 1 }; enum { BufferSize = sizeof(SYMBOL_INFO) + MaxNameLen * sizeof(TCHAR) }; char buffer[BufferSize] = { '\0' }; symbol = static_cast<PSYMBOL_INFO>(static_cast<void *>(buffer)); std::memset(symbol, 0, BufferSize); std::memset(frames, 0, sizeof(frames)); symbol->MaxNameLen = MaxNameLen-1; symbol->SizeOfStruct = sizeof(SYMBOL_INFO); process = GetCurrentProcess(); displacement = 0; symInitialize(process); capturedFrames_ = CaptureStackBackTrace(cFramesToSkip , cFramesSize , frames , NULL); if (capturedFrames_ > cFramesSize) { capturedFrames_ = cFramesSize; } for (frame = 0; frame<capturedFrames_; frame++) { DWORD64 frameAddr = (DWORD64)(frames[frame]); frames_[frame].setAddress(frames[frame]); std::unique_lock<std::mutex> lock(mutex_); if (SymFromAddr(process, frameAddr, &displacement, symbol) == TRUE) { frames_[frame].setSymbol(symbol->Name); } else { char buffer[512]; sprintf_s(buffer, sizeof(buffer) , "Error getting symbol from addr: 0x%016llX 0x%016p\n" , frameAddr , frames[frame]); buffer[sizeof(buffer)-1] = '\0'; PrintMessageToStdErr(buffer); DisplayLastError("SymFromAddr"); } } } /** * Call to this function should */ void symInitialize(HANDLE process) { std::unique_lock<std::mutex> lock(mutex_); static bool symbolsInitialized = false; if(symbolsInitialized==false) { //should be only called once if (SymInitialize(process, NULL, TRUE) != TRUE) { DisplayLastError("SymInitialize"); return; } } symbolsInitialized = true; } /** * Returns number of captured frames * @return number of captured frames */ std::size_t size() const { return capturedFrames_; } /** * Returns StackFrame at position \p pos. If pos * is outside range (0, size()) throws std::out_of_range exception. */ const StackTrace::StackFrame &at(std::uint32_t pos) const { if (pos<capturedFrames_) { return frames_[pos]; } throw std::out_of_range("StackTrace::at(pos) out of range"); } private: //all dbhelp library functions are not thread safe //thats why we need a mutext to protect calls to //them static std::mutex mutex_; enum { cFramesToSkip = 2 }; enum { cFramesSize = 1024 }; BacktraceSymbol frames_[cFramesSize]; std::uint32_t capturedFrames_ = 0; }; std::mutex StackTraceImpl::mutex_; } //internal } //asrt <commit_msg>Added pointer size info<commit_after>#include <cppassert/details/DebugPrint.hpp> #include <cppassert/details/StackTrace.hpp> #include <stdexcept> #include <memory> #include <mutex> #include <cstdlib> #include <Windows.h> #include <DbgHelp.h> #include <strsafe.h> namespace cppassert { namespace internal { /** * Displays error message related to last occured error * */ void DisplayLastError(LPTSTR lpszFunction) { // Retrieve the system error message for the last-error code LPVOID lpMsgBuf; LPVOID lpDisplayBuf; DWORD dw = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); // Display the error message and exit the process lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR)); StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(TCHAR), TEXT("%s failed with error %d: %s"), lpszFunction, dw, lpMsgBuf); PrintMessageToStdErr((LPCSTR)lpDisplayBuf); LocalFree(lpMsgBuf); LocalFree(lpDisplayBuf); } /** * Provides windows implementation of stack trace collection. */ class StackTraceImpl { StackTraceImpl(const StackTraceImpl &) = delete; StackTraceImpl &operator=(const StackTraceImpl &) = delete; struct BacktraceSymbol : public StackTrace::StackFrame { BacktraceSymbol() = default; BacktraceSymbol(const void *frameAddr, const char *name) { address_ = frameAddr; setSymbol(name); } void setAddress(const void *frameAddress) { address_ = frameAddress; } void setSymbol(const char *name) { if (name && name[0]) { strcpy_s(symbolName_, MaxSymbolNameSize, name); symbolName_[MaxSymbolNameSize - 1] = '\0'; } else { symbolName_[0] = '\0'; } symbol_ = symbolName_; } enum { MaxSymbolNameSize = MAX_SYM_NAME + 1 }; char symbolName_[MaxSymbolNameSize]; }; public: StackTraceImpl() { } ~StackTraceImpl() { } void collect() { HANDLE process; ULONG frame; PSYMBOL_INFO symbol; DWORD64 displacement; PVOID frames[cFramesSize]; enum { MaxNameLen = MAX_SYM_NAME + 1 }; enum { BufferSize = sizeof(SYMBOL_INFO) + MaxNameLen * sizeof(TCHAR) }; char buffer[BufferSize] = { '\0' }; symbol = static_cast<PSYMBOL_INFO>(static_cast<void *>(buffer)); std::memset(symbol, 0, BufferSize); std::memset(frames, 0, sizeof(frames)); symbol->MaxNameLen = MaxNameLen-1; symbol->SizeOfStruct = sizeof(SYMBOL_INFO); process = GetCurrentProcess(); displacement = 0; symInitialize(process); capturedFrames_ = CaptureStackBackTrace(cFramesToSkip , cFramesSize , frames , NULL); if (capturedFrames_ > cFramesSize) { capturedFrames_ = cFramesSize; } for (frame = 0; frame<capturedFrames_; frame++) { DWORD64 frameAddr = (DWORD64)(frames[frame]); frames_[frame].setAddress(frames[frame]); std::unique_lock<std::mutex> lock(mutex_); if (SymFromAddr(process, frameAddr, &displacement, symbol) == TRUE) { frames_[frame].setSymbol(symbol->Name); } else { char buffer[512]; sprintf_s(buffer, sizeof(buffer) , "Error getting symbol from addr: 0x%016llX 0x%p address size %d\n" , frameAddr , frames[frame] , sizeof(PVOID)); buffer[sizeof(buffer)-1] = '\0'; PrintMessageToStdErr(buffer); DisplayLastError("SymFromAddr"); } } } /** * Call to this function should */ void symInitialize(HANDLE process) { std::unique_lock<std::mutex> lock(mutex_); static bool symbolsInitialized = false; if(symbolsInitialized==false) { //should be only called once if (SymInitialize(process, NULL, TRUE) != TRUE) { DisplayLastError("SymInitialize"); return; } } symbolsInitialized = true; } /** * Returns number of captured frames * @return number of captured frames */ std::size_t size() const { return capturedFrames_; } /** * Returns StackFrame at position \p pos. If pos * is outside range (0, size()) throws std::out_of_range exception. */ const StackTrace::StackFrame &at(std::uint32_t pos) const { if (pos<capturedFrames_) { return frames_[pos]; } throw std::out_of_range("StackTrace::at(pos) out of range"); } private: //all dbhelp library functions are not thread safe //thats why we need a mutext to protect calls to //them static std::mutex mutex_; enum { cFramesToSkip = 2 }; enum { cFramesSize = 1024 }; BacktraceSymbol frames_[cFramesSize]; std::uint32_t capturedFrames_ = 0; }; std::mutex StackTraceImpl::mutex_; } //internal } //asrt <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2013 Heiko Strathmann */ #include <shogun/base/init.h> #include <shogun/statistics/LinearTimeMMD.h> #include <shogun/statistics/MMDKernelSelectionCombMaxL2.h> #include <shogun/features/streaming/StreamingFeatures.h> #include <shogun/features/streaming/StreamingDenseFeatures.h> #include <shogun/features/DenseFeatures.h> #include <shogun/kernel/GaussianKernel.h> #include <shogun/kernel/CombinedKernel.h> #include <shogun/mathematics/Statistics.h> #include <gtest/gtest.h> using namespace shogun; TEST(MMDKernelSelectionCombMaxL2, select_kernel) { index_t m=8; index_t d=3; SGMatrix<float64_t> data(d,2*m); for (index_t i=0; i<2*d*m; ++i) data.matrix[i]=i; /* create data matrix for each features (appended is not supported) */ SGMatrix<float64_t> data_p(d, m); memcpy(&(data_p.matrix[0]), &(data.matrix[0]), sizeof(float64_t)*d*m); SGMatrix<float64_t> data_q(d, m); memcpy(&(data_q.matrix[0]), &(data.matrix[d*m]), sizeof(float64_t)*d*m); /* normalise data to get some reasonable values for Q matrix */ float64_t max_p=data_p.max_single(); float64_t max_q=data_q.max_single(); //SG_SPRINT("%f, %f\n", max_p, max_q); for (index_t i=0; i<d*m; ++i) { data_p.matrix[i]/=max_p; data_q.matrix[i]/=max_q; } //data_p.display_matrix("data_p"); //data_q.display_matrix("data_q"); CDenseFeatures<float64_t>* features_p=new CDenseFeatures<float64_t>(data_p); CDenseFeatures<float64_t>* features_q=new CDenseFeatures<float64_t>(data_q); /* create stremaing features from dense features */ CStreamingFeatures* streaming_p= new CStreamingDenseFeatures<float64_t>(features_p); CStreamingFeatures* streaming_q= new CStreamingDenseFeatures<float64_t>(features_q); /* create kernels with sigmas 2^5 to 2^7 */ CCombinedKernel* combined_kernel=new CCombinedKernel(); for (index_t i=5; i<=7; ++i) { /* shoguns kernel width is different */ float64_t sigma=CMath::pow(2, i); float64_t sq_sigma_twice=sigma*sigma*2; combined_kernel->append_kernel(new CGaussianKernel(10, sq_sigma_twice)); } /* create MMD instance */ CLinearTimeMMD* mmd=new CLinearTimeMMD(combined_kernel, streaming_p, streaming_q, m); /* kernel selection instance with regularisation term */ CMMDKernelSelectionCombMaxL2* selection=new CMMDKernelSelectionCombMaxL2( mmd, 10E-5); /* start streaming features parser */ streaming_p->start_parser(); streaming_q->start_parser(); CKernel* result=selection->select_kernel(); CCombinedKernel* casted=dynamic_cast<CCombinedKernel*>(result); ASSERT(casted); SGVector<float64_t> weights=casted->get_subkernel_weights(); //weights.display_vector("weights"); /* assert weights against matlab */ // w_l2 = // 0.761798188424313 // 0.190556119182660 // 0.047645692393028 EXPECT_LE(CMath::abs(weights[0]-0.761798188424313), 10E-15); EXPECT_LE(CMath::abs(weights[1]-0.190556119182660), 10E-15); EXPECT_LE(CMath::abs(weights[2]-0.047645692393028), 10E-15); /* start streaming features parser */ streaming_p->end_parser(); streaming_q->end_parser(); SG_UNREF(selection); SG_UNREF(result); } <commit_msg>made test compile again<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2013 Heiko Strathmann */ #include <shogun/base/init.h> #include <shogun/statistics/LinearTimeMMD.h> #include <shogun/statistics/MMDKernelSelectionCombMaxL2.h> #include <shogun/features/streaming/StreamingFeatures.h> #include <shogun/features/streaming/StreamingDenseFeatures.h> #include <shogun/features/DenseFeatures.h> #include <shogun/kernel/GaussianKernel.h> #include <shogun/kernel/CombinedKernel.h> #include <shogun/mathematics/Statistics.h> #include <gtest/gtest.h> using namespace shogun; TEST(MMDKernelSelectionCombMaxL2, select_kernel) { index_t m=8; index_t d=3; SGMatrix<float64_t> data(d,2*m); for (index_t i=0; i<2*d*m; ++i) data.matrix[i]=i; /* create data matrix for each features (appended is not supported) */ SGMatrix<float64_t> data_p(d, m); memcpy(&(data_p.matrix[0]), &(data.matrix[0]), sizeof(float64_t)*d*m); SGMatrix<float64_t> data_q(d, m); memcpy(&(data_q.matrix[0]), &(data.matrix[d*m]), sizeof(float64_t)*d*m); /* normalise data to get some reasonable values for Q matrix */ float64_t max_p=data_p.max_single(); float64_t max_q=data_q.max_single(); //SG_SPRINT("%f, %f\n", max_p, max_q); for (index_t i=0; i<d*m; ++i) { data_p.matrix[i]/=max_p; data_q.matrix[i]/=max_q; } //data_p.display_matrix("data_p"); //data_q.display_matrix("data_q"); CDenseFeatures<float64_t>* features_p=new CDenseFeatures<float64_t>(data_p); CDenseFeatures<float64_t>* features_q=new CDenseFeatures<float64_t>(data_q); /* create stremaing features from dense features */ CStreamingFeatures* streaming_p= new CStreamingDenseFeatures<float64_t>(features_p); CStreamingFeatures* streaming_q= new CStreamingDenseFeatures<float64_t>(features_q); /* create kernels with sigmas 2^5 to 2^7 */ CCombinedKernel* combined_kernel=new CCombinedKernel(); for (index_t i=5; i<=7; ++i) { /* shoguns kernel width is different */ float64_t sigma=CMath::pow(2, i); float64_t sq_sigma_twice=sigma*sigma*2; combined_kernel->append_kernel(new CGaussianKernel(10, sq_sigma_twice)); } /* create MMD instance */ CLinearTimeMMD* mmd=new CLinearTimeMMD(combined_kernel, streaming_p, streaming_q, m); /* kernel selection instance */ CMMDKernelSelectionCombMaxL2* selection=new CMMDKernelSelectionCombMaxL2( mmd); /* start streaming features parser */ streaming_p->start_parser(); streaming_q->start_parser(); CKernel* result=selection->select_kernel(); CCombinedKernel* casted=dynamic_cast<CCombinedKernel*>(result); ASSERT(casted); SGVector<float64_t> weights=casted->get_subkernel_weights(); //weights.display_vector("weights"); /* assert weights against matlab */ // w_l2 = // 0.761798188424313 // 0.190556119182660 // 0.047645692393028 EXPECT_LE(CMath::abs(weights[0]-0.761798188424313), 10E-15); EXPECT_LE(CMath::abs(weights[1]-0.190556119182660), 10E-15); EXPECT_LE(CMath::abs(weights[2]-0.047645692393028), 10E-15); /* start streaming features parser */ streaming_p->end_parser(); streaming_q->end_parser(); SG_UNREF(selection); SG_UNREF(result); } <|endoftext|>
<commit_before>#include "LineKickPlanner.hpp" #include <Configuration.hpp> #include <Geometry2d/Util.hpp> #include <motion/TrapezoidalMotion.hpp> #include "EscapeObstaclesPathPlanner.hpp" #include "RRTPlanner.hpp" #include "motion/TrapezoidalMotion.hpp" #include "CompositePath.hpp" #include "MotionInstant.hpp" using namespace std; using namespace Geometry2d; namespace Planning { bool LineKickPlanner::shouldReplan(const PlanRequest& planRequest) const { const MotionConstraints& motionConstraints = planRequest.constraints.mot; const Geometry2d::ShapeSet& obstacles = planRequest.obstacles; const Path* prevPath = planRequest.prevPath.get(); const auto& command = dynamic_cast<const PivotCommand&>(*planRequest.motionCommand); if (!prevPath) { return true; } else { // TODO ashaw37: make this better float radius = command.radius; auto pivotPoint = command.pivotPoint; auto pivotTarget = command.pivotTarget; auto endTarget = pivotPoint + (pivotPoint - pivotTarget).normalized(radius); float targetChange = (prevPath->end().motion.pos - endTarget).mag(); // if (targetChange > SingleRobotPathPlanner::goalChangeThreshold()) { // return true; // } } return false; } std::unique_ptr<Path> LineKickPlanner::run(PlanRequest& planRequest) { const float ApproachSpeed = 1.0; const float ballAvoidDistance = 0.05; auto prevAnglePath = dynamic_cast<AngleFunctionPath*>(planRequest.prevPath.get()); const auto& command = dynamic_cast<const LineKickCommand&>(*planRequest.motionCommand); const MotionInstant& startInstant = planRequest.start; const auto& motionConstraints = planRequest.constraints.mot; const auto& rotationConstraints = planRequest.constraints.rot; auto& obstacles = planRequest.obstacles; auto& systemState = planRequest.systemState; const auto& ball = systemState.ball; const auto& robotConstraints = planRequest.constraints; auto& dynamicObstacles = planRequest.dynamicObstacles; auto ballObstacles = obstacles; const RJ::Time curTime = RJ::now(); ballObstacles.add( make_shared<Circle>(ball.predict(curTime).pos, ballAvoidDistance)); unique_ptr<Path> prevPath; if (prevAnglePath && prevAnglePath->path) { prevPath = std::move(prevAnglePath->path); } if (!prevPath) { finalApproach = false; } if (finalApproach && prevPath && targetKickPos) { RJ::Seconds timeIntoPath = curTime - prevPath->startTime(); MotionInstant target = prevPath->end().motion; RJ::Time time = ball.estimateTimeTo(*targetKickPos); auto timeLeft = prevPath->getSlowedDuration() - timeIntoPath; if (timeLeft < RJ::Seconds(-0.3) || timeLeft > RJ::Seconds(5.0)) { finalApproach = false; prevPath = nullptr; } else if (timeLeft < RJ::Seconds(0)) { prevPath->setDebugText("reuse past done " + QString::number(timeLeft.count())); return make_unique<AngleFunctionPath>( std::move(prevPath), angleFunctionForCommandType(FacePointCommand(command.target))); } else { RJ::Seconds timeForBall = time - curTime; prevPath->slow(timeLeft/timeForBall, timeIntoPath); prevPath->setDebugText("reuse final slow " + QString::number(timeForBall.count()) + " " + QString::number(timeLeft.count())); return make_unique<AngleFunctionPath>( std::move(prevPath), angleFunctionForCommandType(FacePointCommand(command.target))); } } if (ball.vel.mag() < 0.2) { MotionInstant target(ball.pos); target.vel = (command.target - target.pos).normalized(ApproachSpeed); auto ballPath = ball.path(curTime); unique_ptr<Path> path; if (std::abs(target.vel.angleBetween((target.pos - startInstant.pos))) > DegreesToRadians(10)) { target.pos -= target.vel.normalized(ballAvoidDistance*2 + Robot_Radius); if (prevPath && target.pos.distTo(prevPath->end().motion.pos) < SingleRobotPathPlanner::goalPosChangeThreshold() && reusePathCount < 20) { target.vel = prevPath->end().motion.vel; reusePathCount++; } else { reusePathCount = 0; } auto command = std::make_unique<PathTargetCommand>(target); auto request = PlanRequest(systemState, startInstant, std::move(command), robotConstraints, std::move(prevPath), ballObstacles, dynamicObstacles, planRequest.shellID); path = rrtPlanner.run(request); } else { if (prevPath && target.pos.distTo(prevPath->end().motion.pos) < SingleRobotPathPlanner::goalPosChangeThreshold() && reusePathCount < 20) { target.vel = prevPath->end().motion.vel; reusePathCount++; } else { reusePathCount = 0; } target.pos += target.vel.normalized(Robot_Radius/2); auto command = std::make_unique<PathTargetCommand>(target); auto request = PlanRequest(systemState, startInstant, std::move(command), robotConstraints, std::move(prevPath), obstacles, dynamicObstacles, planRequest.shellID); path = rrtPlanner.run(request); } targetKickPos = boost::none; return make_unique<AngleFunctionPath>( std::move(path), angleFunctionForCommandType(FacePointCommand(command.target))); } if (prevPath && targetKickPos) { auto timeInto = RJ::now() - prevPath->startTime(); auto timeLeft = prevPath->getDuration() - timeInto; MotionInstant target; RJ::Time time = ball.estimateTimeTo(*targetKickPos, &target.pos); RJ::Seconds timeToHit = time - curTime; if (timeLeft < RJ::Seconds(1.0)) { target.vel = (command.target - target.pos).normalized(ApproachSpeed); target.pos -= target.vel.normalized(Robot_Radius + Ball_Radius * 2); if (true) { vector<Point> points{startInstant.pos, target.pos}; finalApproach = true; auto path = RRTPlanner::generatePath(points, obstacles, motionConstraints, startInstant.vel, target.vel); if (path) { path->setDebugText( "FinalPath" + QString::number(path->getSlowedDuration().count()) + " " + QString::number(timeToHit.count()) + " " + QString::number(time.time_since_epoch().count())); //path->slow(timeToHit / path->getDuration()); return make_unique<AngleFunctionPath>( std::move(path), angleFunctionForCommandType(FacePointCommand(command.target))); } } } if (!prevPath->hit(obstacles, timeInto) && timeLeft-1000ms < timeToHit && reusePathCount < 10) { reusePathCount++; Point nearPoint; prevPath->setDebugText("Reuse prevPath"); if (ball.estimateTimeTo(prevPath->end().motion.pos, &nearPoint) >= RJ::now() + timeLeft - 1000ms) { return make_unique<AngleFunctionPath>( std::move(prevPath), angleFunctionForCommandType(FacePointCommand(command.target))); } } } std::unique_ptr<Path> partialPath = nullptr; RJ::Seconds partialPathTime = 0ms; auto tmpStartInstant = startInstant; const auto partialReplanLeadTime = RRTPlanner::getPartialReplanLeadTime(); if (prevPath) { auto timeInto = RJ::now() - prevPath->startTime(); if (timeInto < prevPath->getDuration() - partialReplanLeadTime*2) { partialPath = prevPath->subPath(0ms, timeInto + partialReplanLeadTime); partialPathTime = partialReplanLeadTime; tmpStartInstant = partialPath->end().motion; } } QString debug = ""; for (auto t = RJ::Seconds(0.4); t < RJ::Seconds(6); t += RJ::Seconds(0.2)) { auto tempObstacles = obstacles; MotionInstant ballNow = ball.predict(curTime + t); MotionInstant target(ballNow.pos); targetKickPos = target.pos; target.vel = (command.target - target.pos).normalized(ApproachSpeed); target.pos -= target.vel.normalized(Robot_Radius + Ball_Radius * 2); vector<Point> points{tmpStartInstant.pos, target.pos}; if (std::abs(target.vel.angleBetween((target.pos - tmpStartInstant.pos))) > DegreesToRadians(60)) { auto dist = target.pos.distTo(tmpStartInstant.pos); points = {tmpStartInstant.pos, target.pos - target.vel.normalized(Robot_Radius * 2.0 + Ball_Radius * 2.0), target.pos}; //tempObstacles.add( // make_shared<Circle>(ballNow.pos, Robot_Radius + Ball_Radius)); //debug = "additional "; } if (Geometry2d::Segment(ball.pos, target.pos).distTo(tmpStartInstant.pos) < Robot_Radius) { debug = "meh"; // break; } std::unique_ptr<Path> path = RRTPlanner::generatePath( points, tempObstacles, motionConstraints, tmpStartInstant.vel, target.vel); RJ::Seconds hitTime; if (path) { if (path->getDuration() + partialPathTime <= t) { if (path->hit(tempObstacles, RJ::Seconds::zero(), &hitTime)) { continue; } if (partialPath) { path = make_unique<CompositePath>(std::move(partialPath), std::move(path)); path->setStartTime(prevPath->startTime()); } float multiplier = t / path->getDuration(); path->setDebugText( "FoundPath" + debug + QString::number(path->getDuration().count())); // if (path->getDuration() < 0.7) { // path->slow(multiplier); // path->setDebugText(debug + // QString::number(path->getDuration()) + " slow"); //} reusePathCount=0; return make_unique<AngleFunctionPath>( std::move(path), angleFunctionForCommandType( FacePointCommand(command.target))); } } } MotionInstant ballNow = ball.predict(curTime); MotionInstant target(ballNow.pos); target.vel = (command.target - target.pos).normalized(ApproachSpeed); target.pos -= target.vel.normalized(Robot_Radius * 3); // obstacles.add(make_shared<Circle>(target.pos, ballAvoidDistance)); auto ballPath = ball.path(curTime); dynamicObstacles.push_back(DynamicObstacle(ballPath.get(), Ball_Radius)); std::unique_ptr<MotionCommand> rrtCommand = std::make_unique<PathTargetCommand>(target); auto request = PlanRequest(systemState, startInstant, std::move(rrtCommand), robotConstraints, std::move(prevPath), obstacles, dynamicObstacles, planRequest.shellID); auto path = rrtPlanner.run(request); path->setDebugText("Gives ups"); targetKickPos = boost::none; return make_unique<AngleFunctionPath>( std::move(path), angleFunctionForCommandType(FacePointCommand(command.target))); } } <commit_msg>make line kick kick farther<commit_after>#include "LineKickPlanner.hpp" #include <Configuration.hpp> #include <Geometry2d/Util.hpp> #include <motion/TrapezoidalMotion.hpp> #include "EscapeObstaclesPathPlanner.hpp" #include "RRTPlanner.hpp" #include "motion/TrapezoidalMotion.hpp" #include "CompositePath.hpp" #include "MotionInstant.hpp" using namespace std; using namespace Geometry2d; namespace Planning { bool LineKickPlanner::shouldReplan(const PlanRequest& planRequest) const { const MotionConstraints& motionConstraints = planRequest.constraints.mot; const Geometry2d::ShapeSet& obstacles = planRequest.obstacles; const Path* prevPath = planRequest.prevPath.get(); const auto& command = dynamic_cast<const PivotCommand&>(*planRequest.motionCommand); if (!prevPath) { return true; } else { // TODO ashaw37: make this better float radius = command.radius; auto pivotPoint = command.pivotPoint; auto pivotTarget = command.pivotTarget; auto endTarget = pivotPoint + (pivotPoint - pivotTarget).normalized(radius); float targetChange = (prevPath->end().motion.pos - endTarget).mag(); // if (targetChange > SingleRobotPathPlanner::goalChangeThreshold()) { // return true; // } } return false; } std::unique_ptr<Path> LineKickPlanner::run(PlanRequest& planRequest) { const float ApproachSpeed = 1.0; const float ballAvoidDistance = 0.05; auto prevAnglePath = dynamic_cast<AngleFunctionPath*>(planRequest.prevPath.get()); const auto& command = dynamic_cast<const LineKickCommand&>(*planRequest.motionCommand); const MotionInstant& startInstant = planRequest.start; const auto& motionConstraints = planRequest.constraints.mot; const auto& rotationConstraints = planRequest.constraints.rot; auto& obstacles = planRequest.obstacles; auto& systemState = planRequest.systemState; const auto& ball = systemState.ball; const auto& robotConstraints = planRequest.constraints; auto& dynamicObstacles = planRequest.dynamicObstacles; auto ballObstacles = obstacles; const RJ::Time curTime = RJ::now(); ballObstacles.add( make_shared<Circle>(ball.predict(curTime).pos, ballAvoidDistance)); unique_ptr<Path> prevPath; if (prevAnglePath && prevAnglePath->path) { prevPath = std::move(prevAnglePath->path); } if (!prevPath) { finalApproach = false; } if (finalApproach && prevPath && targetKickPos) { RJ::Seconds timeIntoPath = curTime - prevPath->startTime(); MotionInstant target = prevPath->end().motion; RJ::Time time = ball.estimateTimeTo(*targetKickPos); auto timeLeft = prevPath->getSlowedDuration() - timeIntoPath; if (timeLeft < RJ::Seconds(-0.3) || timeLeft > RJ::Seconds(5.0)) { finalApproach = false; prevPath = nullptr; } else if (timeLeft < RJ::Seconds(0)) { prevPath->setDebugText("reuse past done " + QString::number(timeLeft.count())); return make_unique<AngleFunctionPath>( std::move(prevPath), angleFunctionForCommandType(FacePointCommand(command.target))); } else { RJ::Seconds timeForBall = time - curTime; prevPath->slow(timeLeft/timeForBall, timeIntoPath); prevPath->setDebugText("reuse final slow " + QString::number(timeForBall.count()) + " " + QString::number(timeLeft.count())); return make_unique<AngleFunctionPath>( std::move(prevPath), angleFunctionForCommandType(FacePointCommand(command.target))); } } if (ball.vel.mag() < 0.2) { MotionInstant target(ball.pos); target.vel = (command.target - target.pos).normalized(ApproachSpeed); auto ballPath = ball.path(curTime); unique_ptr<Path> path; if (std::abs(target.vel.angleBetween((target.pos - startInstant.pos))) > DegreesToRadians(10)) { target.pos -= target.vel.normalized(ballAvoidDistance*2 + Robot_Radius); if (prevPath && target.pos.distTo(prevPath->end().motion.pos) < SingleRobotPathPlanner::goalPosChangeThreshold() && reusePathCount < 20) { target.vel = prevPath->end().motion.vel; reusePathCount++; } else { reusePathCount = 0; } auto command = std::make_unique<PathTargetCommand>(target); auto request = PlanRequest(systemState, startInstant, std::move(command), robotConstraints, std::move(prevPath), ballObstacles, dynamicObstacles, planRequest.shellID); path = rrtPlanner.run(request); } else { if (prevPath && target.pos.distTo(prevPath->end().motion.pos) < SingleRobotPathPlanner::goalPosChangeThreshold() && reusePathCount < 20) { target.vel = prevPath->end().motion.vel; reusePathCount++; } else { reusePathCount = 0; } target.pos += target.vel.normalized(Robot_Radius); auto command = std::make_unique<PathTargetCommand>(target); auto request = PlanRequest(systemState, startInstant, std::move(command), robotConstraints, std::move(prevPath), obstacles, dynamicObstacles, planRequest.shellID); path = rrtPlanner.run(request); } targetKickPos = boost::none; return make_unique<AngleFunctionPath>( std::move(path), angleFunctionForCommandType(FacePointCommand(command.target))); } if (prevPath && targetKickPos) { auto timeInto = RJ::now() - prevPath->startTime(); auto timeLeft = prevPath->getDuration() - timeInto; MotionInstant target; RJ::Time time = ball.estimateTimeTo(*targetKickPos, &target.pos); RJ::Seconds timeToHit = time - curTime; if (timeLeft < RJ::Seconds(1.0)) { target.vel = (command.target - target.pos).normalized(ApproachSpeed); target.pos -= target.vel.normalized(Robot_Radius + Ball_Radius * 2); if (true) { vector<Point> points{startInstant.pos, target.pos}; finalApproach = true; auto path = RRTPlanner::generatePath(points, obstacles, motionConstraints, startInstant.vel, target.vel); if (path) { path->setDebugText( "FinalPath" + QString::number(path->getSlowedDuration().count()) + " " + QString::number(timeToHit.count()) + " " + QString::number(time.time_since_epoch().count())); //path->slow(timeToHit / path->getDuration()); return make_unique<AngleFunctionPath>( std::move(path), angleFunctionForCommandType(FacePointCommand(command.target))); } } } if (!prevPath->hit(obstacles, timeInto) && timeLeft-1000ms < timeToHit && reusePathCount < 10) { reusePathCount++; Point nearPoint; prevPath->setDebugText("Reuse prevPath"); if (ball.estimateTimeTo(prevPath->end().motion.pos, &nearPoint) >= RJ::now() + timeLeft - 1000ms) { return make_unique<AngleFunctionPath>( std::move(prevPath), angleFunctionForCommandType(FacePointCommand(command.target))); } } } std::unique_ptr<Path> partialPath = nullptr; RJ::Seconds partialPathTime = 0ms; auto tmpStartInstant = startInstant; const auto partialReplanLeadTime = RRTPlanner::getPartialReplanLeadTime(); if (prevPath) { auto timeInto = RJ::now() - prevPath->startTime(); if (timeInto < prevPath->getDuration() - partialReplanLeadTime*2) { partialPath = prevPath->subPath(0ms, timeInto + partialReplanLeadTime); partialPathTime = partialReplanLeadTime; tmpStartInstant = partialPath->end().motion; } } QString debug = ""; for (auto t = RJ::Seconds(0.4); t < RJ::Seconds(6); t += RJ::Seconds(0.2)) { auto tempObstacles = obstacles; MotionInstant ballNow = ball.predict(curTime + t); MotionInstant target(ballNow.pos); targetKickPos = target.pos; target.vel = (command.target - target.pos).normalized(ApproachSpeed); target.pos -= target.vel.normalized(Robot_Radius + Ball_Radius * 2); vector<Point> points{tmpStartInstant.pos, target.pos}; if (std::abs(target.vel.angleBetween((target.pos - tmpStartInstant.pos))) > DegreesToRadians(60)) { auto dist = target.pos.distTo(tmpStartInstant.pos); points = {tmpStartInstant.pos, target.pos - target.vel.normalized(Robot_Radius * 2.0 + Ball_Radius * 2.0), target.pos}; //tempObstacles.add( // make_shared<Circle>(ballNow.pos, Robot_Radius + Ball_Radius)); //debug = "additional "; } if (Geometry2d::Segment(ball.pos, target.pos).distTo(tmpStartInstant.pos) < Robot_Radius) { debug = "meh"; // break; } std::unique_ptr<Path> path = RRTPlanner::generatePath( points, tempObstacles, motionConstraints, tmpStartInstant.vel, target.vel); RJ::Seconds hitTime; if (path) { if (path->getDuration() + partialPathTime <= t) { if (path->hit(tempObstacles, RJ::Seconds::zero(), &hitTime)) { continue; } if (partialPath) { path = make_unique<CompositePath>(std::move(partialPath), std::move(path)); path->setStartTime(prevPath->startTime()); } float multiplier = t / path->getDuration(); path->setDebugText( "FoundPath" + debug + QString::number(path->getDuration().count())); // if (path->getDuration() < 0.7) { // path->slow(multiplier); // path->setDebugText(debug + // QString::number(path->getDuration()) + " slow"); //} reusePathCount=0; return make_unique<AngleFunctionPath>( std::move(path), angleFunctionForCommandType( FacePointCommand(command.target))); } } } MotionInstant ballNow = ball.predict(curTime); MotionInstant target(ballNow.pos); target.vel = (command.target - target.pos).normalized(ApproachSpeed); target.pos -= target.vel.normalized(Robot_Radius * 3); // obstacles.add(make_shared<Circle>(target.pos, ballAvoidDistance)); auto ballPath = ball.path(curTime); dynamicObstacles.push_back(DynamicObstacle(ballPath.get(), Ball_Radius)); std::unique_ptr<MotionCommand> rrtCommand = std::make_unique<PathTargetCommand>(target); auto request = PlanRequest(systemState, startInstant, std::move(rrtCommand), robotConstraints, std::move(prevPath), obstacles, dynamicObstacles, planRequest.shellID); auto path = rrtPlanner.run(request); path->setDebugText("Gives ups"); targetKickPos = boost::none; return make_unique<AngleFunctionPath>( std::move(path), angleFunctionForCommandType(FacePointCommand(command.target))); } } <|endoftext|>
<commit_before>#include "editor/changeset_wrapper.hpp" #include "editor/osm_feature_matcher.hpp" #include "indexer/feature.hpp" #include "geometry/mercator.hpp" #include "base/logging.hpp" #include "base/macros.hpp" #include "std/algorithm.hpp" #include "std/random.hpp" #include "std/sstream.hpp" #include "private.h" using editor::XMLFeature; namespace { m2::RectD GetBoundingRect(vector<m2::PointD> const & geometry) { m2::RectD rect; for (auto const & p : geometry) { auto const latLon = MercatorBounds::ToLatLon(p); rect.Add({latLon.lon, latLon.lat}); } return rect; } bool OsmFeatureHasTags(pugi::xml_node const & osmFt) { return osmFt.child("tag"); } vector<string> const static kMainTags = {"amenity", "shop", "tourism", "historic", "craft", "emergency", "barrier", "highway", "office", "entrance", "building"}; string GetTypeForFeature(XMLFeature const & node) { for (string const & key : kMainTags) { if (node.HasTag(key)) { string const value = node.GetTagValue(key); if (value == "yes") return key; else if (key == "shop" || key == "office" || key == "building" || key == "entrance") return value + " " + key; // "convenience shop" else return value; } } // Did not find any known tags. return node.HasAnyTags() ? "unknown object" : "empty object"; } vector<m2::PointD> NaiveSample(vector<m2::PointD> const & source, size_t count) { count = min(count, source.size()); vector<m2::PointD> result; result.reserve(count); vector<size_t> indexes; indexes.reserve(count); mt19937 engine; uniform_int_distribution<> distrib(0, source.size()); while (count--) { size_t index; do { index = distrib(engine); } while (find(begin(indexes), end(indexes), index) != end(indexes)); result.push_back(source[index]); indexes.push_back(index); } return result; } } // namespace namespace pugi { string DebugPrint(xml_document const & doc) { ostringstream stream; doc.print(stream, " "); return stream.str(); } } // namespace pugi namespace osm { ChangesetWrapper::ChangesetWrapper(TKeySecret const & keySecret, ServerApi06::TKeyValueTags const & comments) noexcept : m_changesetComments(comments), m_api(OsmOAuth::ServerAuth(keySecret)) { } ChangesetWrapper::~ChangesetWrapper() { if (m_changesetId) { try { m_changesetComments["comment"] = GetDescription(); m_api.UpdateChangeSet(m_changesetId, m_changesetComments); m_api.CloseChangeSet(m_changesetId); } catch (std::exception const & ex) { LOG(LWARNING, (ex.what())); } } } void ChangesetWrapper::LoadXmlFromOSM(ms::LatLon const & ll, pugi::xml_document & doc, double radiusInMeters) { auto const response = m_api.GetXmlFeaturesAtLatLon(ll.lat, ll.lon, radiusInMeters); if (response.first != OsmOAuth::HTTP::OK) MYTHROW(HttpErrorException, ("HTTP error", response, "with GetXmlFeaturesAtLatLon", ll)); if (pugi::status_ok != doc.load(response.second.c_str()).status) MYTHROW( OsmXmlParseException, ("Can't parse OSM server response for GetXmlFeaturesAtLatLon request", response.second)); } void ChangesetWrapper::LoadXmlFromOSM(ms::LatLon const & min, ms::LatLon const & max, pugi::xml_document & doc) { auto const response = m_api.GetXmlFeaturesInRect(min.lat, min.lon, max.lat, max.lon); if (response.first != OsmOAuth::HTTP::OK) MYTHROW(HttpErrorException, ("HTTP error", response, "with GetXmlFeaturesInRect", min, max)); if (pugi::status_ok != doc.load(response.second.c_str()).status) MYTHROW(OsmXmlParseException, ("Can't parse OSM server response for GetXmlFeaturesInRect request", response.second)); } XMLFeature ChangesetWrapper::GetMatchingNodeFeatureFromOSM(m2::PointD const & center) { // Match with OSM node. ms::LatLon const ll = MercatorBounds::ToLatLon(center); pugi::xml_document doc; // Throws! LoadXmlFromOSM(ll, doc); pugi::xml_node const bestNode = GetBestOsmNode(doc, ll); if (bestNode.empty()) { MYTHROW(OsmObjectWasDeletedException, ("OSM does not have any nodes at the coordinates", ll, ", server has returned:", doc)); } if (!OsmFeatureHasTags(bestNode)) { stringstream sstr; bestNode.print(sstr); LOG(LDEBUG, ("Node has no tags", sstr.str())); MYTHROW(EmptyFeatureException, ("Node has no tags")); } return XMLFeature(bestNode); } XMLFeature ChangesetWrapper::GetMatchingAreaFeatureFromOSM(vector<m2::PointD> const & geometry) { auto const kSamplePointsCount = 3; bool hasRelation = false; // Try several points in case of poor osm response. for (auto const & pt : NaiveSample(geometry, kSamplePointsCount)) { ms::LatLon const ll = MercatorBounds::ToLatLon(pt); pugi::xml_document doc; // Throws! LoadXmlFromOSM(ll, doc); if (doc.select_node("osm/relation")) { auto const rect = GetBoundingRect(geometry); LoadXmlFromOSM(ms::LatLon(rect.minY(), rect.minX()), ms::LatLon(rect.maxY(), rect.maxX()), doc); hasRelation = true; } pugi::xml_node const bestWayOrRelation = GetBestOsmWayOrRelation(doc, geometry); if (!bestWayOrRelation) { if (hasRelation) break; continue; } if (strcmp(bestWayOrRelation.name(), "relation") == 0) { stringstream sstr; bestWayOrRelation.print(sstr); LOG(LDEBUG, ("Relation is the best match", sstr.str())); MYTHROW(RelationFeatureAreNotSupportedException, ("Got relation as the best matching")); } if (!OsmFeatureHasTags(bestWayOrRelation)) { stringstream sstr; bestWayOrRelation.print(sstr); LOG(LDEBUG, ("Way or relation has no tags", sstr.str())); MYTHROW(EmptyFeatureException, ("Way or relation has no tags")); } // TODO: rename to wayOrRelation when relations are handled. XMLFeature const way(bestWayOrRelation); ASSERT(way.IsArea(), ("Best way must be an area.")); // AlexZ: TODO: Check that this way is really match our feature. // If we had some way to check it, why not to use it in selecting our feature? return way; } MYTHROW(OsmObjectWasDeletedException, ("OSM does not have any matching way for feature")); } void ChangesetWrapper::Create(XMLFeature node) { if (m_changesetId == kInvalidChangesetId) m_changesetId = m_api.CreateChangeSet(m_changesetComments); // Changeset id should be updated for every OSM server commit. node.SetAttribute("changeset", strings::to_string(m_changesetId)); // TODO(AlexZ): Think about storing/logging returned OSM ids. UNUSED_VALUE(m_api.CreateElement(node)); m_created_types[GetTypeForFeature(node)]++; } void ChangesetWrapper::Modify(XMLFeature node) { if (m_changesetId == kInvalidChangesetId) m_changesetId = m_api.CreateChangeSet(m_changesetComments); // Changeset id should be updated for every OSM server commit. node.SetAttribute("changeset", strings::to_string(m_changesetId)); m_api.ModifyElement(node); m_modified_types[GetTypeForFeature(node)]++; } void ChangesetWrapper::Delete(XMLFeature node) { if (m_changesetId == kInvalidChangesetId) m_changesetId = m_api.CreateChangeSet(m_changesetComments); // Changeset id should be updated for every OSM server commit. node.SetAttribute("changeset", strings::to_string(m_changesetId)); m_api.DeleteElement(node); m_deleted_types[GetTypeForFeature(node)]++; } string ChangesetWrapper::TypeCountToString(TTypeCount const & typeCount) { if (typeCount.empty()) return string(); // Convert map to vector and sort pairs by count, descending. vector<pair<string, size_t>> items; for (auto const & tc : typeCount) items.push_back(tc); sort(items.begin(), items.end(), [](pair<string, size_t> const & a, pair<string, size_t> const & b) { return a.second > b.second; }); ostringstream ss; auto const limit = min(size_t(3), items.size()); for (auto i = 0; i < limit; ++i) { if (i > 0) { // Separator: "A and B" for two, "A, B, and C" for three or more. if (limit > 2) ss << ", "; else ss << " "; if (i == limit - 1) ss << "and "; } auto & currentPair = items[i]; // If we have more objects left, make the last one a list of these. if (i == limit - 1 && limit < items.size()) { int count = 0; for (auto j = i; j < items.size(); ++j) count += items[j].second; currentPair = {"other object", count}; } // Format a count: "a shop" for single shop, "4 shops" for multiple. if (currentPair.second == 1) ss << "a "; else ss << currentPair.second << ' '; ss << currentPair.first; if (currentPair.second > 1) ss << 's'; } return ss.str(); } string ChangesetWrapper::GetDescription() const { string result; if (!m_created_types.empty()) result = "Created " + TypeCountToString(m_created_types); if (!m_modified_types.empty()) { if (!result.empty()) result += "; "; result += "Updated " + TypeCountToString(m_modified_types); } if (!m_deleted_types.empty()) { if (!result.empty()) result += "; "; result += "Deleted " + TypeCountToString(m_deleted_types); } return result; } } // namespace osm <commit_msg>Use more ligheweight rand engine.<commit_after>#include "editor/changeset_wrapper.hpp" #include "editor/osm_feature_matcher.hpp" #include "indexer/feature.hpp" #include "geometry/mercator.hpp" #include "base/logging.hpp" #include "base/macros.hpp" #include "std/algorithm.hpp" #include "std/random.hpp" #include "std/sstream.hpp" #include "private.h" using editor::XMLFeature; namespace { m2::RectD GetBoundingRect(vector<m2::PointD> const & geometry) { m2::RectD rect; for (auto const & p : geometry) { auto const latLon = MercatorBounds::ToLatLon(p); rect.Add({latLon.lon, latLon.lat}); } return rect; } bool OsmFeatureHasTags(pugi::xml_node const & osmFt) { return osmFt.child("tag"); } vector<string> const static kMainTags = {"amenity", "shop", "tourism", "historic", "craft", "emergency", "barrier", "highway", "office", "entrance", "building"}; string GetTypeForFeature(XMLFeature const & node) { for (string const & key : kMainTags) { if (node.HasTag(key)) { string const value = node.GetTagValue(key); if (value == "yes") return key; else if (key == "shop" || key == "office" || key == "building" || key == "entrance") return value + " " + key; // "convenience shop" else return value; } } // Did not find any known tags. return node.HasAnyTags() ? "unknown object" : "empty object"; } vector<m2::PointD> NaiveSample(vector<m2::PointD> const & source, size_t count) { count = min(count, source.size()); vector<m2::PointD> result; result.reserve(count); vector<size_t> indexes; indexes.reserve(count); minstd_rand engine; uniform_int_distribution<> distrib(0, source.size()); while (count--) { size_t index; do { index = distrib(engine); } while (find(begin(indexes), end(indexes), index) != end(indexes)); result.push_back(source[index]); indexes.push_back(index); } return result; } } // namespace namespace pugi { string DebugPrint(xml_document const & doc) { ostringstream stream; doc.print(stream, " "); return stream.str(); } } // namespace pugi namespace osm { ChangesetWrapper::ChangesetWrapper(TKeySecret const & keySecret, ServerApi06::TKeyValueTags const & comments) noexcept : m_changesetComments(comments), m_api(OsmOAuth::ServerAuth(keySecret)) { } ChangesetWrapper::~ChangesetWrapper() { if (m_changesetId) { try { m_changesetComments["comment"] = GetDescription(); m_api.UpdateChangeSet(m_changesetId, m_changesetComments); m_api.CloseChangeSet(m_changesetId); } catch (std::exception const & ex) { LOG(LWARNING, (ex.what())); } } } void ChangesetWrapper::LoadXmlFromOSM(ms::LatLon const & ll, pugi::xml_document & doc, double radiusInMeters) { auto const response = m_api.GetXmlFeaturesAtLatLon(ll.lat, ll.lon, radiusInMeters); if (response.first != OsmOAuth::HTTP::OK) MYTHROW(HttpErrorException, ("HTTP error", response, "with GetXmlFeaturesAtLatLon", ll)); if (pugi::status_ok != doc.load(response.second.c_str()).status) MYTHROW( OsmXmlParseException, ("Can't parse OSM server response for GetXmlFeaturesAtLatLon request", response.second)); } void ChangesetWrapper::LoadXmlFromOSM(ms::LatLon const & min, ms::LatLon const & max, pugi::xml_document & doc) { auto const response = m_api.GetXmlFeaturesInRect(min.lat, min.lon, max.lat, max.lon); if (response.first != OsmOAuth::HTTP::OK) MYTHROW(HttpErrorException, ("HTTP error", response, "with GetXmlFeaturesInRect", min, max)); if (pugi::status_ok != doc.load(response.second.c_str()).status) MYTHROW(OsmXmlParseException, ("Can't parse OSM server response for GetXmlFeaturesInRect request", response.second)); } XMLFeature ChangesetWrapper::GetMatchingNodeFeatureFromOSM(m2::PointD const & center) { // Match with OSM node. ms::LatLon const ll = MercatorBounds::ToLatLon(center); pugi::xml_document doc; // Throws! LoadXmlFromOSM(ll, doc); pugi::xml_node const bestNode = GetBestOsmNode(doc, ll); if (bestNode.empty()) { MYTHROW(OsmObjectWasDeletedException, ("OSM does not have any nodes at the coordinates", ll, ", server has returned:", doc)); } if (!OsmFeatureHasTags(bestNode)) { stringstream sstr; bestNode.print(sstr); LOG(LDEBUG, ("Node has no tags", sstr.str())); MYTHROW(EmptyFeatureException, ("Node has no tags")); } return XMLFeature(bestNode); } XMLFeature ChangesetWrapper::GetMatchingAreaFeatureFromOSM(vector<m2::PointD> const & geometry) { auto const kSamplePointsCount = 3; bool hasRelation = false; // Try several points in case of poor osm response. for (auto const & pt : NaiveSample(geometry, kSamplePointsCount)) { ms::LatLon const ll = MercatorBounds::ToLatLon(pt); pugi::xml_document doc; // Throws! LoadXmlFromOSM(ll, doc); if (doc.select_node("osm/relation")) { auto const rect = GetBoundingRect(geometry); LoadXmlFromOSM(ms::LatLon(rect.minY(), rect.minX()), ms::LatLon(rect.maxY(), rect.maxX()), doc); hasRelation = true; } pugi::xml_node const bestWayOrRelation = GetBestOsmWayOrRelation(doc, geometry); if (!bestWayOrRelation) { if (hasRelation) break; continue; } if (strcmp(bestWayOrRelation.name(), "relation") == 0) { stringstream sstr; bestWayOrRelation.print(sstr); LOG(LDEBUG, ("Relation is the best match", sstr.str())); MYTHROW(RelationFeatureAreNotSupportedException, ("Got relation as the best matching")); } if (!OsmFeatureHasTags(bestWayOrRelation)) { stringstream sstr; bestWayOrRelation.print(sstr); LOG(LDEBUG, ("Way or relation has no tags", sstr.str())); MYTHROW(EmptyFeatureException, ("Way or relation has no tags")); } // TODO: rename to wayOrRelation when relations are handled. XMLFeature const way(bestWayOrRelation); ASSERT(way.IsArea(), ("Best way must be an area.")); // AlexZ: TODO: Check that this way is really match our feature. // If we had some way to check it, why not to use it in selecting our feature? return way; } MYTHROW(OsmObjectWasDeletedException, ("OSM does not have any matching way for feature")); } void ChangesetWrapper::Create(XMLFeature node) { if (m_changesetId == kInvalidChangesetId) m_changesetId = m_api.CreateChangeSet(m_changesetComments); // Changeset id should be updated for every OSM server commit. node.SetAttribute("changeset", strings::to_string(m_changesetId)); // TODO(AlexZ): Think about storing/logging returned OSM ids. UNUSED_VALUE(m_api.CreateElement(node)); m_created_types[GetTypeForFeature(node)]++; } void ChangesetWrapper::Modify(XMLFeature node) { if (m_changesetId == kInvalidChangesetId) m_changesetId = m_api.CreateChangeSet(m_changesetComments); // Changeset id should be updated for every OSM server commit. node.SetAttribute("changeset", strings::to_string(m_changesetId)); m_api.ModifyElement(node); m_modified_types[GetTypeForFeature(node)]++; } void ChangesetWrapper::Delete(XMLFeature node) { if (m_changesetId == kInvalidChangesetId) m_changesetId = m_api.CreateChangeSet(m_changesetComments); // Changeset id should be updated for every OSM server commit. node.SetAttribute("changeset", strings::to_string(m_changesetId)); m_api.DeleteElement(node); m_deleted_types[GetTypeForFeature(node)]++; } string ChangesetWrapper::TypeCountToString(TTypeCount const & typeCount) { if (typeCount.empty()) return string(); // Convert map to vector and sort pairs by count, descending. vector<pair<string, size_t>> items; for (auto const & tc : typeCount) items.push_back(tc); sort(items.begin(), items.end(), [](pair<string, size_t> const & a, pair<string, size_t> const & b) { return a.second > b.second; }); ostringstream ss; auto const limit = min(size_t(3), items.size()); for (auto i = 0; i < limit; ++i) { if (i > 0) { // Separator: "A and B" for two, "A, B, and C" for three or more. if (limit > 2) ss << ", "; else ss << " "; if (i == limit - 1) ss << "and "; } auto & currentPair = items[i]; // If we have more objects left, make the last one a list of these. if (i == limit - 1 && limit < items.size()) { int count = 0; for (auto j = i; j < items.size(); ++j) count += items[j].second; currentPair = {"other object", count}; } // Format a count: "a shop" for single shop, "4 shops" for multiple. if (currentPair.second == 1) ss << "a "; else ss << currentPair.second << ' '; ss << currentPair.first; if (currentPair.second > 1) ss << 's'; } return ss.str(); } string ChangesetWrapper::GetDescription() const { string result; if (!m_created_types.empty()) result = "Created " + TypeCountToString(m_created_types); if (!m_modified_types.empty()) { if (!result.empty()) result += "; "; result += "Updated " + TypeCountToString(m_modified_types); } if (!m_deleted_types.empty()) { if (!result.empty()) result += "; "; result += "Deleted " + TypeCountToString(m_deleted_types); } return result; } } // namespace osm <|endoftext|>
<commit_before>#include <string.h> #include <stdlib.h> #include <gtk/gtk.h> #include <getopt.h> #include <iostream> #include <bot_vis/bot_vis.h> #include <lcm/lcm.h> #include <bot_core/bot_core.h> #include <path_util/path_util.h> #include <ConciseArgs> #include <bot_frames/bot_frames_renderers.h> //imported renderers #include <bot_lcmgl_render/lcmgl_bot_renderer.h> #include <laser_utils/renderer_laser.h> #include <image_utils/renderer_cam_thumb.h> #include <visualization/collections_renderer.hpp> #include <octomap_utils/renderer_octomap.h> #include <renderer_maps/MapsRenderer.hpp> #include <renderer_data_control/DataControlRenderer.hpp> #include <multisense/multisense_renderer.h> #include <occ_map/occ_map_renderers.h> // Individual Renderers: #include <renderer_drc/renderer_scrollingplots.h> #include <renderer_drc/renderer_driving.hpp> #include <renderer_drc/renderer_walking.hpp> #include <renderer_drc/renderer_status.hpp> // block of renderers #include <renderer_robot_state/renderer_robot_state.hpp> #include <renderer_robot_plan/renderer_robot_plan.hpp> #include <renderer_affordances/renderer_affordances.hpp> #include <renderer_sticky_feet/renderer_sticky_feet.hpp> #include <renderer_end_effector_goal/renderer_end_effector_goal.hpp> #include "udp_util.h" #include "RendererGroupUtil.hpp" using namespace std; static int logplayer_remote_on_key_press(BotViewer *viewer, BotEventHandler *ehandler, const GdkEventKey *event) { int keyval = event->keyval; switch (keyval) { case 'P': case 'p': udp_send_string("127.0.0.1", 53261, "PLAYPAUSETOGGLE"); break; case 'N': case 'n': udp_send_string("127.0.0.1", 53261, "STEP"); break; case '=': case '+': udp_send_string("127.0.0.1", 53261, "FASTER"); break; case '_': case '-': udp_send_string("127.0.0.1", 53261, "SLOWER"); break; case '[': udp_send_string("127.0.0.1", 53261, "BACK5"); break; case ']': udp_send_string("127.0.0.1", 53261, "FORWARD5"); break; default: return 0; } return 1; } static void on_collapse_all_clicked(GtkToggleToolButton *tb, void *user_data) { BotViewer *viewer = (BotViewer*) user_data; for (unsigned int i = 0; i < viewer->renderers->len; ++i) { BotRenderer* renderer = (BotRenderer*)g_ptr_array_index(viewer->renderers, i); renderer->expanded = FALSE; if (renderer->expander) { gtk_expander_set_expanded (GTK_EXPANDER (renderer->expander), renderer->expanded); } } } // TBD - correct location for this code? static void on_top_view_clicked(GtkToggleToolButton *tb, void *user_data) { BotViewer *self = (BotViewer*) user_data; double eye[3]; double look[3]; double up[3]; self->view_handler->get_eye_look(self->view_handler, eye, look, up); eye[0] = 0; eye[1] = 0; eye[2] = 10; look[0] = 0; look[1] = 0; look[2] = 0; up[0] = 0; up[1] = 10; up[2] = 0; self->view_handler->set_look_at(self->view_handler, eye, look, up); bot_viewer_request_redraw(self); } // TBD - correct location for this? int start_spy_counter=0; static void on_start_spy_clicked(GtkToggleToolButton *tb, void *user_data) { BotViewer *self = (BotViewer*) user_data; if (start_spy_counter >0){ // is there a better way than this counter? int i = system ("bot-spy &> /dev/null &"); } start_spy_counter++; } static void destroy_renderers (BotViewer *viewer) { for (unsigned int ridx = 0; ridx < viewer->renderers->len; ridx++) { BotRenderer *renderer = (BotRenderer*)g_ptr_array_index(viewer->renderers, ridx); if (renderer && renderer->destroy) { std::cout << "Destroying renderer \"" << renderer->name << "\"..." << std::flush; renderer->destroy(renderer); std::cout << "Done" << std::endl; } } g_ptr_array_free(viewer->renderers, TRUE); } int main(int argc, char *argv[]) { setlinebuf(stdout); string config_file = ""; // leave this empty so force viewer to get it from the param server string role = "robot"; ConciseArgs opt(argc, (char**)argv); opt.add(config_file, "c", "config_file","Robot cfg file"); opt.add(role, "r", "role","Role - robot or base"); opt.parse(); std::cout << "config_file: " << config_file << "\n"; std::cout << "role: " << role << "\n"; string viewer_title = "(" + role + ") MIT DRC Viewer"; string vis_config_file = ".bot-plugin-"+ role +"-drc-viewer"; //todo: comment this section gtk_init(&argc, &argv); glutInit(&argc, argv); g_thread_init(NULL); string lcm_url=""; std::string role_upper; for(short i = 0; i < role.size(); ++i) role_upper+= (std::toupper(role[i])); if((role.compare("robot") == 0) || (role.compare("base") == 0) ){ for(short i = 0; i < role_upper.size(); ++i) role_upper[i] = (std::toupper(role_upper[i])); string env_variable_name = string("LCM_URL_DRC_" + role_upper); char* env_variable; env_variable = getenv (env_variable_name.c_str()); if (env_variable!=NULL){ //printf ("The env_variable is: %s\n",env_variable); lcm_url = string(env_variable); }else{ std::cout << env_variable_name << " environment variable has not been set ["<< lcm_url <<"]\n"; exit(-1); } }else{ std::cout << "Role not understood, choose: robot or base\n"; return 1; } lcm_t * lcm; lcm= lcm_create(lcm_url.c_str());// bot_lcm_get_global(lcm_url.c_str()); bot_glib_mainloop_attach_lcm(lcm); BotParam * bot_param; if(config_file.size()) { fprintf(stderr,"Reading config from file\n"); std::string config_path = std::string(getConfigPath()) +'/' + std::string(config_file); bot_param = bot_param_new_from_file(config_path.c_str()); if (bot_param == NULL) { std::cerr << "Couldn't get bot param from file %s\n" << config_path << std::endl; exit(-1); } }else { bot_param = bot_param_new_from_server(lcm, 0); if (bot_param == NULL) { fprintf(stderr, "Couldn't get bot param from server.\n"); return 1; } } BotFrames* bot_frames = bot_frames_new(lcm, bot_param); BotViewer* viewer = bot_viewer_new(viewer_title.c_str()); //die cleanly for control-c etc :-) bot_gtk_quit_on_interrupt(); // logplayer controls BotEventHandler *ehandler = (BotEventHandler*) calloc(1, sizeof(BotEventHandler)); ehandler->name = "LogPlayer Remote"; ehandler->enabled = 1; ehandler->key_press = logplayer_remote_on_key_press; bot_viewer_add_event_handler(viewer, ehandler, 0); // core renderers bot_viewer_add_stock_renderer(viewer, BOT_VIEWER_STOCK_RENDERER_GRID, 1); bot_lcmgl_add_renderer_to_viewer(viewer, lcm, 1); laser_util_add_renderer_to_viewer(viewer, 1, lcm, bot_param, bot_frames); bot_frames_add_renderer_to_viewer(viewer, 1, bot_frames ); collections_add_renderer_to_viewer(viewer, 1, lcm); bot_frames_add_renderer_to_viewer(viewer, 1, bot_frames ); bot_frames_add_renderer_to_viewer(viewer, 1, bot_frames ); // Block of Renderers: setup_renderer_robot_state(viewer, 0, lcm); setup_renderer_robot_plan(viewer, 0, lcm); setup_renderer_affordances(viewer, 0, lcm); setup_renderer_sticky_feet(viewer, 0, lcm,bot_param,bot_frames); setup_renderer_end_effector_goal(viewer, 0, lcm); // Individual Renderers: add_octomap_renderer_to_viewer(viewer, 1, lcm); maps_renderer_setup(viewer, 0, lcm, bot_param, bot_frames); data_control_renderer_setup(viewer, 0, lcm, bot_param, bot_frames); scrollingplots_add_renderer_to_viewer(viewer, 0, lcm); status_add_renderer_to_viewer(viewer, 0, lcm); setup_renderer_driving(viewer, 0, lcm, bot_param, bot_frames); setup_renderer_walking(viewer, 0,lcm,bot_param,bot_frames); occ_map_pixel_map_add_renderer_to_viewer(viewer, 0, "TERRAIN_COST", "PixelMap"); add_cam_thumb_renderer_to_viewer(viewer, 0, lcm, bot_param, bot_frames); multisense_add_renderer_to_viewer(viewer, 0,lcm,bot_frames,"CAMERA", bot_param); // add custom TOP VIEW button GtkWidget *top_view_button; top_view_button = (GtkWidget *) gtk_tool_button_new_from_stock(GTK_STOCK_ZOOM_FIT); gtk_tool_button_set_label(GTK_TOOL_BUTTON(top_view_button), "Top View"); gtk_tool_item_set_tooltip(GTK_TOOL_ITEM(top_view_button), viewer->tips, "Switch to Top View", NULL); gtk_toolbar_insert(GTK_TOOLBAR(viewer->toolbar), GTK_TOOL_ITEM(top_view_button), 4); gtk_widget_show(top_view_button); g_signal_connect(G_OBJECT(top_view_button), "clicked", G_CALLBACK(on_top_view_clicked), viewer); on_top_view_clicked(NULL, (void *) viewer); // add custom TOP VIEW button GtkWidget *start_spy_button; start_spy_button = (GtkWidget *) gtk_tool_button_new_from_stock(GTK_STOCK_FIND); gtk_tool_button_set_label(GTK_TOOL_BUTTON(start_spy_button), "Bot Spy"); gtk_tool_item_set_tooltip(GTK_TOOL_ITEM(start_spy_button), viewer->tips, "Launch Bot Spy", NULL); gtk_toolbar_insert(GTK_TOOLBAR(viewer->toolbar), GTK_TOOL_ITEM(start_spy_button), 4); gtk_widget_show(start_spy_button); g_signal_connect(G_OBJECT(start_spy_button), "clicked", G_CALLBACK(on_start_spy_clicked), viewer); on_start_spy_clicked(NULL, (void *) viewer); // add custom "collapse all" button GtkToolItem *item = gtk_tool_button_new_from_stock (GTK_STOCK_CLEAR); gtk_tool_button_set_label (GTK_TOOL_BUTTON (item), "Collapse All"); gtk_tool_item_set_is_important (GTK_TOOL_ITEM (item), TRUE); gtk_tool_item_set_tooltip (GTK_TOOL_ITEM (item), viewer->tips, "Collapse all visible renderers", NULL); gtk_toolbar_insert (GTK_TOOLBAR (viewer->toolbar), item, -1); gtk_widget_show (GTK_WIDGET (item)); g_signal_connect (G_OBJECT (item), "clicked", G_CALLBACK (on_collapse_all_clicked), viewer); // add custom renderer groups menu RendererGroupUtil groupUtil(viewer, bot_param); groupUtil.setup(); // load the renderer params from the config file. char *fname = g_build_filename(g_get_user_config_dir(), vis_config_file.c_str() , NULL); bot_viewer_load_preferences(viewer, fname); gtk_main(); //save the renderer params to the config file. bot_viewer_save_preferences(viewer, fname); // clean up all renderers destroy_renderers(viewer); // remove reference bot_viewer_unref(viewer); } <commit_msg>added a new interface<commit_after>#include <string.h> #include <stdlib.h> #include <gtk/gtk.h> #include <getopt.h> #include <iostream> #include <bot_vis/bot_vis.h> #include <lcm/lcm.h> #include <bot_core/bot_core.h> #include <path_util/path_util.h> #include <ConciseArgs> #include <bot_frames/bot_frames_renderers.h> //imported renderers #include <bot_lcmgl_render/lcmgl_bot_renderer.h> #include <laser_utils/renderer_laser.h> #include <image_utils/renderer_cam_thumb.h> #include <visualization/collections_renderer.hpp> #include <octomap_utils/renderer_octomap.h> #include <renderer_maps/MapsRenderer.hpp> #include <renderer_data_control/DataControlRenderer.hpp> #include <multisense/multisense_renderer.h> #include <occ_map/occ_map_renderers.h> // Individual Renderers: #include <renderer_drc/renderer_scrollingplots.h> #include <renderer_drc/renderer_driving.hpp> #include <renderer_drc/renderer_walking.hpp> #include <renderer_drc/renderer_status.hpp> // block of renderers #include <renderer_robot_state/renderer_robot_state.hpp> #include <renderer_robot_plan/renderer_robot_plan.hpp> #include <renderer_affordances/renderer_affordances.hpp> #include <renderer_sticky_feet/renderer_sticky_feet.hpp> #include <renderer_end_effector_goal/renderer_end_effector_goal.hpp> #include "udp_util.h" #include "RendererGroupUtil.hpp" using namespace std; static int logplayer_remote_on_key_press(BotViewer *viewer, BotEventHandler *ehandler, const GdkEventKey *event) { int keyval = event->keyval; switch (keyval) { case 'P': case 'p': udp_send_string("127.0.0.1", 53261, "PLAYPAUSETOGGLE"); break; case 'N': case 'n': udp_send_string("127.0.0.1", 53261, "STEP"); break; case '=': case '+': udp_send_string("127.0.0.1", 53261, "FASTER"); break; case '_': case '-': udp_send_string("127.0.0.1", 53261, "SLOWER"); break; case '[': udp_send_string("127.0.0.1", 53261, "BACK5"); break; case ']': udp_send_string("127.0.0.1", 53261, "FORWARD5"); break; default: return 0; } return 1; } static void on_collapse_all_clicked(GtkToggleToolButton *tb, void *user_data) { BotViewer *viewer = (BotViewer*) user_data; for (unsigned int i = 0; i < viewer->renderers->len; ++i) { BotRenderer* renderer = (BotRenderer*)g_ptr_array_index(viewer->renderers, i); renderer->expanded = FALSE; if (renderer->expander) { gtk_expander_set_expanded (GTK_EXPANDER (renderer->expander), renderer->expanded); } } } // TBD - correct location for this code? static void on_top_view_clicked(GtkToggleToolButton *tb, void *user_data) { BotViewer *self = (BotViewer*) user_data; double eye[3]; double look[3]; double up[3]; self->view_handler->get_eye_look(self->view_handler, eye, look, up); eye[0] = 0; eye[1] = 0; eye[2] = 10; look[0] = 0; look[1] = 0; look[2] = 0; up[0] = 0; up[1] = 10; up[2] = 0; self->view_handler->set_look_at(self->view_handler, eye, look, up); bot_viewer_request_redraw(self); } // TBD - correct location for this? int start_spy_counter=0; static void on_start_spy_clicked(GtkToggleToolButton *tb, void *user_data) { BotViewer *self = (BotViewer*) user_data; if (start_spy_counter >0){ // is there a better way than this counter? int i = system ("bot-spy &> /dev/null &"); } start_spy_counter++; } static void destroy_renderers (BotViewer *viewer) { for (unsigned int ridx = 0; ridx < viewer->renderers->len; ridx++) { BotRenderer *renderer = (BotRenderer*)g_ptr_array_index(viewer->renderers, ridx); if (renderer && renderer->destroy) { std::cout << "Destroying renderer \"" << renderer->name << "\"..." << std::flush; renderer->destroy(renderer); std::cout << "Done" << std::endl; } } g_ptr_array_free(viewer->renderers, TRUE); } int main(int argc, char *argv[]) { setlinebuf(stdout); string config_file = ""; // leave this empty so force viewer to get it from the param server string role = "robot"; ConciseArgs opt(argc, (char**)argv); opt.add(config_file, "c", "config_file","Robot cfg file"); opt.add(role, "r", "role","Role - robot or base"); opt.parse(); std::cout << "config_file: " << config_file << "\n"; std::cout << "role: " << role << "\n"; string viewer_title = "(" + role + ") MIT DRC Viewer"; string vis_config_file = ".bot-plugin-"+ role +"-drc-viewer"; //todo: comment this section gtk_init(&argc, &argv); glutInit(&argc, argv); g_thread_init(NULL); string lcm_url=""; std::string role_upper; for(short i = 0; i < role.size(); ++i) role_upper+= (std::toupper(role[i])); if((role.compare("robot") == 0) || (role.compare("base") == 0) ){ for(short i = 0; i < role_upper.size(); ++i) role_upper[i] = (std::toupper(role_upper[i])); string env_variable_name = string("LCM_URL_DRC_" + role_upper); char* env_variable; env_variable = getenv (env_variable_name.c_str()); if (env_variable!=NULL){ //printf ("The env_variable is: %s\n",env_variable); lcm_url = string(env_variable); }else{ std::cout << env_variable_name << " environment variable has not been set ["<< lcm_url <<"]\n"; exit(-1); } }else{ std::cout << "Role not understood, choose: robot or base\n"; return 1; } lcm_t * lcm; lcm= lcm_create(lcm_url.c_str());// bot_lcm_get_global(lcm_url.c_str()); bot_glib_mainloop_attach_lcm(lcm); BotParam * bot_param; if(config_file.size()) { fprintf(stderr,"Reading config from file\n"); std::string config_path = std::string(getConfigPath()) +'/' + std::string(config_file); bot_param = bot_param_new_from_file(config_path.c_str()); if (bot_param == NULL) { std::cerr << "Couldn't get bot param from file %s\n" << config_path << std::endl; exit(-1); } }else { bot_param = bot_param_new_from_server(lcm, 0); if (bot_param == NULL) { fprintf(stderr, "Couldn't get bot param from server.\n"); return 1; } } BotFrames* bot_frames = bot_frames_new(lcm, bot_param); BotViewer* viewer = bot_viewer_new(viewer_title.c_str()); //die cleanly for control-c etc :-) bot_gtk_quit_on_interrupt(); // logplayer controls BotEventHandler *ehandler = (BotEventHandler*) calloc(1, sizeof(BotEventHandler)); ehandler->name = "LogPlayer Remote"; ehandler->enabled = 1; ehandler->key_press = logplayer_remote_on_key_press; bot_viewer_add_event_handler(viewer, ehandler, 0); // core renderers bot_viewer_add_stock_renderer(viewer, BOT_VIEWER_STOCK_RENDERER_GRID, 1); bot_lcmgl_add_renderer_to_viewer(viewer, lcm, 1); laser_util_add_renderer_to_viewer(viewer, 1, lcm, bot_param, bot_frames); bot_frames_add_renderer_to_viewer(viewer, 1, bot_frames ); collections_add_renderer_to_viewer(viewer, 1, lcm); bot_frames_add_renderer_to_viewer(viewer, 1, bot_frames ); bot_frames_add_renderer_to_viewer(viewer, 1, bot_frames ); // Block of Renderers: setup_renderer_robot_state(viewer, 0, lcm); setup_renderer_robot_plan(viewer, 0, lcm); setup_renderer_affordances(viewer, 0, lcm); setup_renderer_sticky_feet(viewer, 0, lcm,bot_param,bot_frames); setup_renderer_end_effector_goal(viewer, 0, lcm); // Individual Renderers: add_octomap_renderer_to_viewer(viewer, 1, lcm); maps_renderer_setup(viewer, 0, lcm, bot_param, bot_frames); data_control_renderer_setup(viewer, 0, lcm, bot_param, bot_frames); scrollingplots_add_renderer_to_viewer(viewer, 0, lcm); status_add_renderer_to_viewer(viewer, 0, lcm); setup_renderer_driving(viewer, 0, lcm, bot_param, bot_frames); setup_renderer_walking(viewer, 0,lcm,bot_param,bot_frames); occ_map_pixel_map_add_renderer_to_viewer_lcm(viewer, 0, lcm, "PIXEL_MAP", "PixelMap"); add_cam_thumb_renderer_to_viewer(viewer, 0, lcm, bot_param, bot_frames); multisense_add_renderer_to_viewer(viewer, 0,lcm,bot_frames,"CAMERA", bot_param); // add custom TOP VIEW button GtkWidget *top_view_button; top_view_button = (GtkWidget *) gtk_tool_button_new_from_stock(GTK_STOCK_ZOOM_FIT); gtk_tool_button_set_label(GTK_TOOL_BUTTON(top_view_button), "Top View"); gtk_tool_item_set_tooltip(GTK_TOOL_ITEM(top_view_button), viewer->tips, "Switch to Top View", NULL); gtk_toolbar_insert(GTK_TOOLBAR(viewer->toolbar), GTK_TOOL_ITEM(top_view_button), 4); gtk_widget_show(top_view_button); g_signal_connect(G_OBJECT(top_view_button), "clicked", G_CALLBACK(on_top_view_clicked), viewer); on_top_view_clicked(NULL, (void *) viewer); // add custom TOP VIEW button GtkWidget *start_spy_button; start_spy_button = (GtkWidget *) gtk_tool_button_new_from_stock(GTK_STOCK_FIND); gtk_tool_button_set_label(GTK_TOOL_BUTTON(start_spy_button), "Bot Spy"); gtk_tool_item_set_tooltip(GTK_TOOL_ITEM(start_spy_button), viewer->tips, "Launch Bot Spy", NULL); gtk_toolbar_insert(GTK_TOOLBAR(viewer->toolbar), GTK_TOOL_ITEM(start_spy_button), 4); gtk_widget_show(start_spy_button); g_signal_connect(G_OBJECT(start_spy_button), "clicked", G_CALLBACK(on_start_spy_clicked), viewer); on_start_spy_clicked(NULL, (void *) viewer); // add custom "collapse all" button GtkToolItem *item = gtk_tool_button_new_from_stock (GTK_STOCK_CLEAR); gtk_tool_button_set_label (GTK_TOOL_BUTTON (item), "Collapse All"); gtk_tool_item_set_is_important (GTK_TOOL_ITEM (item), TRUE); gtk_tool_item_set_tooltip (GTK_TOOL_ITEM (item), viewer->tips, "Collapse all visible renderers", NULL); gtk_toolbar_insert (GTK_TOOLBAR (viewer->toolbar), item, -1); gtk_widget_show (GTK_WIDGET (item)); g_signal_connect (G_OBJECT (item), "clicked", G_CALLBACK (on_collapse_all_clicked), viewer); // add custom renderer groups menu RendererGroupUtil groupUtil(viewer, bot_param); groupUtil.setup(); // load the renderer params from the config file. char *fname = g_build_filename(g_get_user_config_dir(), vis_config_file.c_str() , NULL); bot_viewer_load_preferences(viewer, fname); gtk_main(); //save the renderer params to the config file. bot_viewer_save_preferences(viewer, fname); // clean up all renderers destroy_renderers(viewer); // remove reference bot_viewer_unref(viewer); } <|endoftext|>
<commit_before>#include "core/meta/MetaPopulationApportionment.hpp" #include "core/meta/BlanketResolver.hpp" MetaPopulationApportionment::MetaPopulationApportionment( PopulationNode * metaNode, ApportionmentFunction * apportionment, AggregationFunction * aggregation ) : Apportionment(metaNode, apportionment, aggregation) {} Genome * MetaPopulationApportionment::getOperableGenome(Genome * genome) { Genome resolved = BlanketResolver::resolveBlanket(genome); return new Genome(&resolved); } std::vector<unsigned int> MetaPopulationApportionment::getComponentIndices( Genome * upper, Genome * target ) { unsigned int headIndex = BlanketResolver::findHeadIndex(upper); return upper->getIndex<Genome*>(headIndex) ->getFlattenedIndices(target); } <commit_msg>[MetaPopulationApportionment]: Fixed root node not getting fitness<commit_after>#include "core/meta/MetaPopulationApportionment.hpp" #include "core/meta/BlanketResolver.hpp" MetaPopulationApportionment::MetaPopulationApportionment( PopulationNode * metaNode, ApportionmentFunction * apportionment, AggregationFunction * aggregation ) : Apportionment(metaNode, apportionment, aggregation) {} Genome * MetaPopulationApportionment::getOperableGenome(Genome * genome) { Genome resolved = BlanketResolver::resolveBlanket(genome); return new Genome(&resolved); } std::vector<unsigned int> MetaPopulationApportionment::getComponentIndices( Genome * upper, Genome * target ) { Genome * head = upper->getIndex<Genome*>( BlanketResolver::findHeadIndex(upper) ); return (head == target) ? std::vector<unsigned int>(1, 0) : head->getFlattenedIndices(target); } <|endoftext|>
<commit_before>#include "lcio.h" #include "IO/LCWriter.h" // position of record name for last random access record #define LCSIO_RANDOMACCESS_SIZE 112 #include <iostream> #include <sstream> #include <stdio.h> #include <stdlib.h> using namespace lcio ; static std::vector<std::string> FILEN ; /** Simple program that opens existing LCIO files and appends the records needed for direct access - if they don't exist. */ int main(int argc, char** argv ){ // create sio writer LCWriter* lcWrt = LCFactory::getInstance()->createLCWriter() ; // read file names from command line (only argument) if( argc < 2) { std::cout << " usage: addRandomAccess <input-file1> [[input-file2],...]" << std::endl ; exit(1) ; } int firstFile = 1 ; bool force = false ; std::string firstArg( argv[1] ) ; if( firstArg == "-f" ){ // force: 'undocumented' feature for fixing files with broken TOC (SplitWriter) firstFile++ ; std::cout << " ====== called with -f (force) : will create a TOC for direct access in any case ! " << std::endl ; force = true ; } for(int i=firstFile ; i < argc ; i++){ FILEN.push_back( argv[i] ) ; } int nFiles = argc - firstFile ; for( int i=0 ; i <nFiles ; ++i ) { try{ if( force) { // -------------------------------------------------------------------------------------------- // if called with force we rename the last LCIORandomAcces record so that it is ignored and the // file treated as an old one w/o direct access.... FILE* f = fopen( FILEN[i].c_str() , "r+") ; if( f != 0 ){ fseek( f , -( LCSIO_RANDOMACCESS_SIZE ) , SEEK_END ) ; std::string bla("") ; bla.resize(17) ; int status = fread( &bla[0] , sizeof(char) , 16 , f ) ; // std::cout << " ====== read : [" << bla << "]" << std::endl ; if( !strcmp( bla.c_str() , "LCIORandomAccess") ){ status = fseek( f , -(16) , SEEK_CUR ) ; bla = "LCIORandomIGNORE" ; status = fwrite( &bla[0] , 1 , 16 , f ) ; // std::cout << " --------- wrote " << bla << " to file - bytes written " << status << std::endl; } } fclose( f ) ; } //---------- end if(force) -------------------------------------------------------------------------------- lcWrt->open( FILEN[i] , LCIO::WRITE_APPEND ) ; lcWrt->close() ; }catch(IOException& e){ std::cout << " io error in file " << FILEN[i] << " : " << e.what() << std::endl ; } } return 0 ; } <commit_msg>added <cstring> for compiling with gcc 4.4<commit_after>#include "lcio.h" #include "IO/LCWriter.h" // position of record name for last random access record #define LCSIO_RANDOMACCESS_SIZE 112 #include <iostream> #include <sstream> #include <cstdio> #include <cstdlib> #include <cstring> using namespace lcio ; static std::vector<std::string> FILEN ; /** Simple program that opens existing LCIO files and appends the records needed for direct access - if they don't exist. */ int main(int argc, char** argv ){ // create sio writer LCWriter* lcWrt = LCFactory::getInstance()->createLCWriter() ; // read file names from command line (only argument) if( argc < 2) { std::cout << " usage: addRandomAccess <input-file1> [[input-file2],...]" << std::endl ; exit(1) ; } int firstFile = 1 ; bool force = false ; std::string firstArg( argv[1] ) ; if( firstArg == "-f" ){ // force: 'undocumented' feature for fixing files with broken TOC (SplitWriter) firstFile++ ; std::cout << " ====== called with -f (force) : will create a TOC for direct access in any case ! " << std::endl ; force = true ; } for(int i=firstFile ; i < argc ; i++){ FILEN.push_back( argv[i] ) ; } int nFiles = argc - firstFile ; for( int i=0 ; i <nFiles ; ++i ) { try{ if( force) { // -------------------------------------------------------------------------------------------- // if called with force we rename the last LCIORandomAcces record so that it is ignored and the // file treated as an old one w/o direct access.... FILE* f = fopen( FILEN[i].c_str() , "r+") ; if( f != 0 ){ fseek( f , -( LCSIO_RANDOMACCESS_SIZE ) , SEEK_END ) ; std::string bla("") ; bla.resize(17) ; int status = fread( &bla[0] , sizeof(char) , 16 , f ) ; // std::cout << " ====== read : [" << bla << "]" << std::endl ; if( !strcmp( bla.c_str() , "LCIORandomAccess") ){ status = fseek( f , -(16) , SEEK_CUR ) ; bla = "LCIORandomIGNORE" ; status = fwrite( &bla[0] , 1 , 16 , f ) ; // std::cout << " --------- wrote " << bla << " to file - bytes written " << status << std::endl; } } fclose( f ) ; } //---------- end if(force) -------------------------------------------------------------------------------- lcWrt->open( FILEN[i] , LCIO::WRITE_APPEND ) ; lcWrt->close() ; }catch(IOException& e){ std::cout << " io error in file " << FILEN[i] << " : " << e.what() << std::endl ; } } return 0 ; } <|endoftext|>
<commit_before>/* -*- C++ -*- This file is part of ThreadWeaver. Author: Mirko Boehm Copyright: (C) 2005-2014 Mirko Boehm Contact: mirko@kde.org http://www.kde.org http://creative-destruction.me This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <QtDebug> #include <QFile> #include <QFileInfo> #include <QLocale> #include <ThreadWeaver/ThreadWeaver> #include <ThreadWeaver/Exception> #include "Image.h" #include "Model.h" //const int Image::ThumbHeight = 75; //const int Image::ThumbWidth = 120; const int Image::ThumbHeight = 60; const int Image::ThumbWidth = 80; QReadWriteLock Image::Lock; int Image::ProcessingOrder; Image::Image(const QString inputFileName, const QString outputFileName, Model *model, int id) : m_inputFileName(inputFileName) , m_outputFileName(outputFileName) , m_model(model) , m_id(id) { } Progress Image::progress() const { return qMakePair(m_progress, Step_NumberOfSteps); } QString Image::description() const { QReadLocker l(&Lock); return m_description; } QString Image::details() const { QReadLocker l(&Lock); return m_details; } QString Image::details2() const { QReadLocker l(&Lock); return m_details2; } int Image::processingOrder() const { return m_processingOrder.loadAcquire(); } const QString Image::inputFileName() const { return m_inputFileName; } const QString Image::outputFileName() const { return m_outputFileName; } QImage Image::thumbNail() const { QReadLocker r(&Lock); return m_thumbnail; } void Image::loadFile() { m_processingOrder.storeRelease(ProcessingOrder++); QFile file(m_inputFileName); if (!file.open(QIODevice::ReadOnly)) { error(Step_LoadFile, tr("Unable to load input file!")); } m_imageData = file.readAll(); QFileInfo fi(file); QLocale locale; QString details2 = tr("%1kB").arg(locale.toString(fi.size()/1024)); { QWriteLocker l(&Lock); m_description = fi.fileName(); m_details2 = details2; } announceProgress(Step_LoadFile); } void Image::loadImage() { m_processingOrder.storeRelease(ProcessingOrder++); const bool result = m_image.loadFromData(m_imageData); m_imageData.clear(); if (!result) { error(Step_LoadImage, tr("Unable to parse image data!")); } QString details = tr("%1x%2 pixels") .arg(m_image.width()) .arg(m_image.height()); { QWriteLocker l(&Lock); m_details = details; } announceProgress(Step_LoadImage); } void Image::computeThumbNail() { m_processingOrder.storeRelease(ProcessingOrder++); QImage thumb = m_image.scaled(ThumbWidth, ThumbHeight, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation); if (thumb.isNull()) { error(Step_ComputeThumbNail, tr("Unable to compute thumbnail!")); } { // thumb is implicitly shared, no copy: QWriteLocker l(&Lock); m_thumbnail = thumb; } m_image = QImage(); announceProgress(Step_ComputeThumbNail); } void Image::saveThumbNail() { QImage thumb; { QReadLocker r(&Lock); thumb = m_thumbnail; } if (!thumb.save(m_outputFileName)) { error(Step_SaveThumbNail, tr("Unable to save output file!")); } announceProgress(Step_SaveThumbNail); } void Image::announceProgress(Steps step) { m_progress.storeRelease(step); if (m_model) { m_model->progressChanged(); m_model->elementChanged(m_id); } } void Image::error(Image::Steps step, const QString &message) { m_failedStep.store(step); announceProgress(Step_Complete); throw ThreadWeaver::JobFailed(message); } <commit_msg>Use a QImageReader to be able to detect error causes.<commit_after>/* -*- C++ -*- This file is part of ThreadWeaver. Author: Mirko Boehm Copyright: (C) 2005-2014 Mirko Boehm Contact: mirko@kde.org http://www.kde.org http://creative-destruction.me This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <QtDebug> #include <QFile> #include <QFileInfo> #include <QLocale> #include <QImageReader> #include <QBuffer> #include <ThreadWeaver/ThreadWeaver> #include <ThreadWeaver/Exception> #include "Image.h" #include "Model.h" //const int Image::ThumbHeight = 75; //const int Image::ThumbWidth = 120; const int Image::ThumbHeight = 60; const int Image::ThumbWidth = 80; QReadWriteLock Image::Lock; int Image::ProcessingOrder; Image::Image(const QString inputFileName, const QString outputFileName, Model *model, int id) : m_inputFileName(inputFileName) , m_outputFileName(outputFileName) , m_model(model) , m_id(id) { } Progress Image::progress() const { return qMakePair(m_progress, Step_NumberOfSteps); } QString Image::description() const { QReadLocker l(&Lock); return m_description; } QString Image::details() const { QReadLocker l(&Lock); return m_details; } QString Image::details2() const { QReadLocker l(&Lock); return m_details2; } int Image::processingOrder() const { return m_processingOrder.loadAcquire(); } const QString Image::inputFileName() const { return m_inputFileName; } const QString Image::outputFileName() const { return m_outputFileName; } QImage Image::thumbNail() const { QReadLocker r(&Lock); return m_thumbnail; } void Image::loadFile() { m_processingOrder.storeRelease(ProcessingOrder++); QFile file(m_inputFileName); if (!file.open(QIODevice::ReadOnly)) { error(Step_LoadFile, tr("Unable to load input file!")); } m_imageData = file.readAll(); QFileInfo fi(file); QLocale locale; QString details2 = tr("%1kB").arg(locale.toString(fi.size()/1024)); { QWriteLocker l(&Lock); m_description = fi.fileName(); m_details2 = details2; } announceProgress(Step_LoadFile); } void Image::loadImage() { m_processingOrder.storeRelease(ProcessingOrder++); QBuffer in(&m_imageData); in.open(QIODevice::ReadOnly); QImageReader reader(&in); m_image = reader.read(); m_imageData.clear(); if (m_image.isNull()) { QWriteLocker l(&Lock); m_details = tr("%1!").arg(reader.errorString()); error(Step_LoadImage, m_details); } QString details = tr("%1x%2 pixels") .arg(m_image.width()) .arg(m_image.height()); { QWriteLocker l(&Lock); m_details = details; } announceProgress(Step_LoadImage); } void Image::computeThumbNail() { m_processingOrder.storeRelease(ProcessingOrder++); QImage thumb = m_image.scaled(ThumbWidth, ThumbHeight, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation); if (thumb.isNull()) { error(Step_ComputeThumbNail, tr("Unable to compute thumbnail!")); } { // thumb is implicitly shared, no copy: QWriteLocker l(&Lock); m_thumbnail = thumb; } m_image = QImage(); announceProgress(Step_ComputeThumbNail); } void Image::saveThumbNail() { QImage thumb; { QReadLocker r(&Lock); thumb = m_thumbnail; } if (!thumb.save(m_outputFileName)) { error(Step_SaveThumbNail, tr("Unable to save output file!")); } announceProgress(Step_SaveThumbNail); } void Image::announceProgress(Steps step) { m_progress.storeRelease(step); if (m_model) { m_model->progressChanged(); m_model->elementChanged(m_id); } } void Image::error(Image::Steps step, const QString &message) { m_failedStep.store(step); announceProgress(Step_Complete); throw ThreadWeaver::JobFailed(message); } <|endoftext|>
<commit_before>#include <tabulate/table.hpp> using namespace tabulate; int main() { Table logo; // Add rows logo.add_row({"tabulate for Modern C++"}); // Format the table logo.format() .font_style({FontStyle::bold}) .font_align(FontAlign::center) .font_color(Color::yellow); // Print the table std::cout << logo << std::endl; } <commit_msg>Updated logo sample<commit_after>#include <tabulate/table.hpp> using namespace tabulate; int main() { Table header; header.add_row({"tabulate", "for Modern C++"}); // Format the table header[0][0].format() .font_style({FontStyle::bold, FontStyle::italic}) .font_align(FontAlign::center) .font_color(Color::yellow) .border("") .corner("") .padding_left(17) .column_separator(""); header[0][1].format() .padding(0) .border("") .corner("") .column_separator("") .font_color(Color::green) .font_style({FontStyle::bold}); std::cout << header << std::endl; Table tagline; tagline.format() .border("") .corner("") .column_separator("") .color(Color::red) .font_style({FontStyle::bold}); tagline.add_row({"tabulate", " is a library for printing aligned and formatted tabes"}); tagline[0][0].format() .padding(0) .font_style({FontStyle::italic, FontStyle::underline}); tagline[0][1].format() .padding_left(0); std::cout << tagline << std::endl; Table logo; logo.format() .font_style({FontStyle::bold}); // Add rows logo.add_row({"Header-only Library"}); logo.add_row({"Requires C++17"}); logo.add_row({"MIT License"}); logo[1].format() .font_color(Color::white) .font_background_color(Color::grey) .border_left_background_color(Color::grey) .border_right_background_color(Color::grey); // Print the table std::cout << logo << std::endl; } <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright 2014 Cloudius Systems */ #pragma once #include "future.hh" #include <experimental/optional> #include <exception> namespace seastar { /// \addtogroup fiber-module /// @{ namespace stdx = std::experimental; /// Exception thrown when a \ref gate object has been closed /// by the \ref gate::close() method. class gate_closed_exception : public std::exception { public: virtual const char* what() const noexcept override { return "gate closed"; } }; /// Facility to stop new requests, and to tell when existing requests are done. /// /// When stopping a service that serves asynchronous requests, we are faced with /// two problems: preventing new requests from coming in, and knowing when existing /// requests have completed. The \c gate class provides a solution. class gate { size_t _count = 0; stdx::optional<promise<>> _stopped; public: /// Registers an in-progress request. /// /// If the gate is not closed, the request is registered. Otherwise, /// a \ref gate_closed_exception is thrown. void enter() { if (_stopped) { throw gate_closed_exception(); } ++_count; } /// Unregisters an in-progress request. /// /// If the gate is closed, and there are no more in-progress requests, /// the \ref closed() promise will be fulfilled. void leave() { --_count; if (!_count && _stopped) { _stopped->set_value(); } } /// Potentially stop an in-progress request. /// /// If the gate is already closed, a \ref gate_closed_exception is thrown. /// By using \ref enter() and \ref leave(), the program can ensure that /// no further requests are serviced. However, long-running requests may /// continue to run. The check() method allows such a long operation to /// voluntarily stop itself after the gate is closed, by making calls to /// check() in appropriate places. check() with throw an exception and /// bail out of the long-running code if the gate is closed. void check() { if (_stopped) { throw gate_closed_exception(); } } /// Closes the gate. /// /// Future calls to \ref enter() will fail with an exception, and when /// all current requests call \ref leave(), the returned future will be /// made ready. future<> close() { assert(!_stopped && "seastar::gate::close() cannot be called more than once"); _stopped = stdx::make_optional(promise<>()); if (!_count) { _stopped->set_value(); } return _stopped->get_future(); } }; /// Executes the function \c func making sure the gate \c g is properly entered /// and later on, properly left. /// /// \param func function to be executed /// \param g the gate. Caller must make sure that it outlives this function. /// \returns whatever \c func returns /// /// \relates gate template <typename Func> inline auto with_gate(gate& g, Func&& func) { g.enter(); return func().finally([&g] { g.leave(); }); } /// @} } <commit_msg>core::gate: add a get_count() method<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright 2014 Cloudius Systems */ #pragma once #include "future.hh" #include <experimental/optional> #include <exception> namespace seastar { /// \addtogroup fiber-module /// @{ namespace stdx = std::experimental; /// Exception thrown when a \ref gate object has been closed /// by the \ref gate::close() method. class gate_closed_exception : public std::exception { public: virtual const char* what() const noexcept override { return "gate closed"; } }; /// Facility to stop new requests, and to tell when existing requests are done. /// /// When stopping a service that serves asynchronous requests, we are faced with /// two problems: preventing new requests from coming in, and knowing when existing /// requests have completed. The \c gate class provides a solution. class gate { size_t _count = 0; stdx::optional<promise<>> _stopped; public: /// Registers an in-progress request. /// /// If the gate is not closed, the request is registered. Otherwise, /// a \ref gate_closed_exception is thrown. void enter() { if (_stopped) { throw gate_closed_exception(); } ++_count; } /// Unregisters an in-progress request. /// /// If the gate is closed, and there are no more in-progress requests, /// the \ref closed() promise will be fulfilled. void leave() { --_count; if (!_count && _stopped) { _stopped->set_value(); } } /// Potentially stop an in-progress request. /// /// If the gate is already closed, a \ref gate_closed_exception is thrown. /// By using \ref enter() and \ref leave(), the program can ensure that /// no further requests are serviced. However, long-running requests may /// continue to run. The check() method allows such a long operation to /// voluntarily stop itself after the gate is closed, by making calls to /// check() in appropriate places. check() with throw an exception and /// bail out of the long-running code if the gate is closed. void check() { if (_stopped) { throw gate_closed_exception(); } } /// Closes the gate. /// /// Future calls to \ref enter() will fail with an exception, and when /// all current requests call \ref leave(), the returned future will be /// made ready. future<> close() { assert(!_stopped && "seastar::gate::close() cannot be called more than once"); _stopped = stdx::make_optional(promise<>()); if (!_count) { _stopped->set_value(); } return _stopped->get_future(); } /// Returns a current number of registered in-progress requests. size_t get_count() const { return _count; } }; /// Executes the function \c func making sure the gate \c g is properly entered /// and later on, properly left. /// /// \param func function to be executed /// \param g the gate. Caller must make sure that it outlives this function. /// \returns whatever \c func returns /// /// \relates gate template <typename Func> inline auto with_gate(gate& g, Func&& func) { g.enter(); return func().finally([&g] { g.leave(); }); } /// @} } <|endoftext|>
<commit_before>//===--- ToolChain.cpp - Collections of tools for one platform ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Driver/ToolChain.h" #include "clang/Basic/ObjCRuntime.h" #include "clang/Driver/Action.h" #include "clang/Driver/Arg.h" #include "clang/Driver/ArgList.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Option.h" #include "clang/Driver/Options.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/ErrorHandling.h" using namespace clang::driver; using namespace clang; ToolChain::ToolChain(const Driver &D, const llvm::Triple &T) : D(D), Triple(T) { } ToolChain::~ToolChain() { } const Driver &ToolChain::getDriver() const { return D; } std::string ToolChain::getDefaultUniversalArchName() const { // In universal driver terms, the arch name accepted by -arch isn't exactly // the same as the ones that appear in the triple. Roughly speaking, this is // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the // only interesting special case is powerpc. switch (Triple.getArch()) { case llvm::Triple::ppc: return "ppc"; case llvm::Triple::ppc64: return "ppc64"; default: return Triple.getArchName(); } } bool ToolChain::IsUnwindTablesDefault() const { return false; } std::string ToolChain::GetFilePath(const char *Name) const { return D.GetFilePath(Name, *this); } std::string ToolChain::GetProgramPath(const char *Name) const { return D.GetProgramPath(Name, *this); } types::ID ToolChain::LookupTypeForExtension(const char *Ext) const { return types::lookupTypeForExtension(Ext); } bool ToolChain::HasNativeLLVMSupport() const { return false; } ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const { return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC, VersionTuple()); } /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting. // // FIXME: tblgen this. static const char *getARMTargetCPU(const ArgList &Args, const llvm::Triple &Triple) { // For Darwin targets, the -arch option (which is translated to a // corresponding -march option) should determine the architecture // (and the Mach-O slice) regardless of any -mcpu options. if (!Triple.isOSDarwin()) { // FIXME: Warn on inconsistent use of -mcpu and -march. // If we have -mcpu=, use that. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) return A->getValue(); } StringRef MArch; if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) { // Otherwise, if we have -march= choose the base CPU for that arch. MArch = A->getValue(); } else { // Otherwise, use the Arch from the triple. MArch = Triple.getArchName(); } return llvm::StringSwitch<const char *>(MArch) .Cases("armv2", "armv2a","arm2") .Case("armv3", "arm6") .Case("armv3m", "arm7m") .Cases("armv4", "armv4t", "arm7tdmi") .Cases("armv5", "armv5t", "arm10tdmi") .Cases("armv5e", "armv5te", "arm1026ejs") .Case("armv5tej", "arm926ej-s") .Cases("armv6", "armv6k", "arm1136jf-s") .Case("armv6j", "arm1136j-s") .Cases("armv6z", "armv6zk", "arm1176jzf-s") .Case("armv6t2", "arm1156t2-s") .Cases("armv7", "armv7a", "armv7-a", "cortex-a8") .Cases("armv7f", "armv7-f", "cortex-a9-mp") .Cases("armv7s", "armv7-s", "swift") .Cases("armv7r", "armv7-r", "cortex-r4", "cortex-r5") .Cases("armv7m", "armv7-m", "cortex-m3") .Case("ep9312", "ep9312") .Case("iwmmxt", "iwmmxt") .Case("xscale", "xscale") .Cases("armv6m", "armv6-m", "cortex-m0") // If all else failed, return the most base CPU LLVM supports. .Default("arm7tdmi"); } /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular /// CPU. // // FIXME: This is redundant with -mcpu, why does LLVM use this. // FIXME: tblgen this, or kill it! static const char *getLLVMArchSuffixForARM(StringRef CPU) { return llvm::StringSwitch<const char *>(CPU) .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t") .Cases("arm720t", "arm9", "arm9tdmi", "v4t") .Cases("arm920", "arm920t", "arm922t", "v4t") .Cases("arm940t", "ep9312","v4t") .Cases("arm10tdmi", "arm1020t", "v5") .Cases("arm9e", "arm926ej-s", "arm946e-s", "v5e") .Cases("arm966e-s", "arm968e-s", "arm10e", "v5e") .Cases("arm1020e", "arm1022e", "xscale", "iwmmxt", "v5e") .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "v6") .Cases("arm1176jzf-s", "mpcorenovfp", "mpcore", "v6") .Cases("arm1156t2-s", "arm1156t2f-s", "v6t2") .Cases("cortex-a8", "cortex-a9", "cortex-a15", "v7") .Case("cortex-m3", "v7m") .Case("cortex-m4", "v7m") .Case("cortex-m0", "v6m") .Case("cortex-a9-mp", "v7f") .Case("swift", "v7s") .Default(""); } std::string ToolChain::ComputeLLVMTriple(const ArgList &Args, types::ID InputType) const { switch (getTriple().getArch()) { default: return getTripleString(); case llvm::Triple::arm: case llvm::Triple::thumb: { // FIXME: Factor into subclasses. llvm::Triple Triple = getTriple(); // Thumb2 is the default for V7 on Darwin. // // FIXME: Thumb should just be another -target-feaure, not in the triple. StringRef Suffix = getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple)); bool ThumbDefault = (Suffix.startswith("v7") && getTriple().isOSDarwin()); std::string ArchName = "arm"; // Assembly files should start in ARM mode. if (InputType != types::TY_PP_Asm && Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault)) ArchName = "thumb"; Triple.setArchName(ArchName + Suffix.str()); return Triple.getTriple(); } } } std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args, types::ID InputType) const { // Diagnose use of Darwin OS deployment target arguments on non-Darwin. if (Arg *A = Args.getLastArg(options::OPT_mmacosx_version_min_EQ, options::OPT_miphoneos_version_min_EQ, options::OPT_mios_simulator_version_min_EQ)) getDriver().Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args); return ComputeLLVMTriple(Args, InputType); } void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { // Each toolchain should provide the appropriate include flags. } void ToolChain::addClangTargetOptions(const ArgList &DriverArgs, ArgStringList &CC1Args) const { } ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType( const ArgList &Args) const { if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) { StringRef Value = A->getValue(); if (Value == "compiler-rt") return ToolChain::RLT_CompilerRT; if (Value == "libgcc") return ToolChain::RLT_Libgcc; getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args); } return GetDefaultRuntimeLibType(); } ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{ if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) { StringRef Value = A->getValue(); if (Value == "libc++") return ToolChain::CST_Libcxx; if (Value == "libstdc++") return ToolChain::CST_Libstdcxx; getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args); } return ToolChain::CST_Libstdcxx; } /// \brief Utility function to add a system include directory to CC1 arguments. /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs, ArgStringList &CC1Args, const Twine &Path) { CC1Args.push_back("-internal-isystem"); CC1Args.push_back(DriverArgs.MakeArgString(Path)); } /// \brief Utility function to add a system include directory with extern "C" /// semantics to CC1 arguments. /// /// Note that this should be used rarely, and only for directories that /// historically and for legacy reasons are treated as having implicit extern /// "C" semantics. These semantics are *ignored* by and large today, but its /// important to preserve the preprocessor changes resulting from the /// classification. /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs, ArgStringList &CC1Args, const Twine &Path) { CC1Args.push_back("-internal-externc-isystem"); CC1Args.push_back(DriverArgs.MakeArgString(Path)); } /// \brief Utility function to add a list of system include directories to CC1. /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs, ArgStringList &CC1Args, ArrayRef<StringRef> Paths) { for (ArrayRef<StringRef>::iterator I = Paths.begin(), E = Paths.end(); I != E; ++I) { CC1Args.push_back("-internal-isystem"); CC1Args.push_back(DriverArgs.MakeArgString(*I)); } } void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { // Header search paths should be handled by each of the subclasses. // Historically, they have not been, and instead have been handled inside of // the CC1-layer frontend. As the logic is hoisted out, this generic function // will slowly stop being called. // // While it is being called, replicate a bit of a hack to propagate the // '-stdlib=' flag down to CC1 so that it can in turn customize the C++ // header search paths with it. Once all systems are overriding this // function, the CC1 flag and this line can be removed. DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ); } void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args, ArgStringList &CmdArgs) const { CXXStdlibType Type = GetCXXStdlibType(Args); switch (Type) { case ToolChain::CST_Libcxx: CmdArgs.push_back("-lc++"); break; case ToolChain::CST_Libstdcxx: CmdArgs.push_back("-lstdc++"); break; } } void ToolChain::AddCCKextLibArgs(const ArgList &Args, ArgStringList &CmdArgs) const { CmdArgs.push_back("-lcc_kext"); } bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args, ArgStringList &CmdArgs) const { // Check if -ffast-math or -funsafe-math is enabled. Arg *A = Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations, options::OPT_fno_unsafe_math_optimizations); if (!A || A->getOption().getID() == options::OPT_fno_fast_math || A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations) return false; // If crtfastmath.o exists add it to the arguments. std::string Path = GetFilePath("crtfastmath.o"); if (Path == "crtfastmath.o") // Not found. return false; CmdArgs.push_back(Args.MakeArgString(Path)); return true; } <commit_msg>Adding armv7l default to cortex-a8<commit_after>//===--- ToolChain.cpp - Collections of tools for one platform ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Driver/ToolChain.h" #include "clang/Basic/ObjCRuntime.h" #include "clang/Driver/Action.h" #include "clang/Driver/Arg.h" #include "clang/Driver/ArgList.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Option.h" #include "clang/Driver/Options.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/ErrorHandling.h" using namespace clang::driver; using namespace clang; ToolChain::ToolChain(const Driver &D, const llvm::Triple &T) : D(D), Triple(T) { } ToolChain::~ToolChain() { } const Driver &ToolChain::getDriver() const { return D; } std::string ToolChain::getDefaultUniversalArchName() const { // In universal driver terms, the arch name accepted by -arch isn't exactly // the same as the ones that appear in the triple. Roughly speaking, this is // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the // only interesting special case is powerpc. switch (Triple.getArch()) { case llvm::Triple::ppc: return "ppc"; case llvm::Triple::ppc64: return "ppc64"; default: return Triple.getArchName(); } } bool ToolChain::IsUnwindTablesDefault() const { return false; } std::string ToolChain::GetFilePath(const char *Name) const { return D.GetFilePath(Name, *this); } std::string ToolChain::GetProgramPath(const char *Name) const { return D.GetProgramPath(Name, *this); } types::ID ToolChain::LookupTypeForExtension(const char *Ext) const { return types::lookupTypeForExtension(Ext); } bool ToolChain::HasNativeLLVMSupport() const { return false; } ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const { return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC, VersionTuple()); } /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting. // // FIXME: tblgen this. static const char *getARMTargetCPU(const ArgList &Args, const llvm::Triple &Triple) { // For Darwin targets, the -arch option (which is translated to a // corresponding -march option) should determine the architecture // (and the Mach-O slice) regardless of any -mcpu options. if (!Triple.isOSDarwin()) { // FIXME: Warn on inconsistent use of -mcpu and -march. // If we have -mcpu=, use that. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) return A->getValue(); } StringRef MArch; if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) { // Otherwise, if we have -march= choose the base CPU for that arch. MArch = A->getValue(); } else { // Otherwise, use the Arch from the triple. MArch = Triple.getArchName(); } return llvm::StringSwitch<const char *>(MArch) .Cases("armv2", "armv2a","arm2") .Case("armv3", "arm6") .Case("armv3m", "arm7m") .Cases("armv4", "armv4t", "arm7tdmi") .Cases("armv5", "armv5t", "arm10tdmi") .Cases("armv5e", "armv5te", "arm1026ejs") .Case("armv5tej", "arm926ej-s") .Cases("armv6", "armv6k", "arm1136jf-s") .Case("armv6j", "arm1136j-s") .Cases("armv6z", "armv6zk", "arm1176jzf-s") .Case("armv6t2", "arm1156t2-s") .Cases("armv7", "armv7a", "armv7-a", "cortex-a8") .Cases("armv7l", "armv7-l", "cortex-a8") .Cases("armv7f", "armv7-f", "cortex-a9-mp") .Cases("armv7s", "armv7-s", "swift") .Cases("armv7r", "armv7-r", "cortex-r4", "cortex-r5") .Cases("armv7m", "armv7-m", "cortex-m3") .Case("ep9312", "ep9312") .Case("iwmmxt", "iwmmxt") .Case("xscale", "xscale") .Cases("armv6m", "armv6-m", "cortex-m0") // If all else failed, return the most base CPU LLVM supports. .Default("arm7tdmi"); } /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular /// CPU. // // FIXME: This is redundant with -mcpu, why does LLVM use this. // FIXME: tblgen this, or kill it! static const char *getLLVMArchSuffixForARM(StringRef CPU) { return llvm::StringSwitch<const char *>(CPU) .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t") .Cases("arm720t", "arm9", "arm9tdmi", "v4t") .Cases("arm920", "arm920t", "arm922t", "v4t") .Cases("arm940t", "ep9312","v4t") .Cases("arm10tdmi", "arm1020t", "v5") .Cases("arm9e", "arm926ej-s", "arm946e-s", "v5e") .Cases("arm966e-s", "arm968e-s", "arm10e", "v5e") .Cases("arm1020e", "arm1022e", "xscale", "iwmmxt", "v5e") .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "v6") .Cases("arm1176jzf-s", "mpcorenovfp", "mpcore", "v6") .Cases("arm1156t2-s", "arm1156t2f-s", "v6t2") .Cases("cortex-a8", "cortex-a9", "cortex-a15", "v7") .Case("cortex-m3", "v7m") .Case("cortex-m4", "v7m") .Case("cortex-m0", "v6m") .Case("cortex-a9-mp", "v7f") .Case("swift", "v7s") .Default(""); } std::string ToolChain::ComputeLLVMTriple(const ArgList &Args, types::ID InputType) const { switch (getTriple().getArch()) { default: return getTripleString(); case llvm::Triple::arm: case llvm::Triple::thumb: { // FIXME: Factor into subclasses. llvm::Triple Triple = getTriple(); // Thumb2 is the default for V7 on Darwin. // // FIXME: Thumb should just be another -target-feaure, not in the triple. StringRef Suffix = getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple)); bool ThumbDefault = (Suffix.startswith("v7") && getTriple().isOSDarwin()); std::string ArchName = "arm"; // Assembly files should start in ARM mode. if (InputType != types::TY_PP_Asm && Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault)) ArchName = "thumb"; Triple.setArchName(ArchName + Suffix.str()); return Triple.getTriple(); } } } std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args, types::ID InputType) const { // Diagnose use of Darwin OS deployment target arguments on non-Darwin. if (Arg *A = Args.getLastArg(options::OPT_mmacosx_version_min_EQ, options::OPT_miphoneos_version_min_EQ, options::OPT_mios_simulator_version_min_EQ)) getDriver().Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args); return ComputeLLVMTriple(Args, InputType); } void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { // Each toolchain should provide the appropriate include flags. } void ToolChain::addClangTargetOptions(const ArgList &DriverArgs, ArgStringList &CC1Args) const { } ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType( const ArgList &Args) const { if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) { StringRef Value = A->getValue(); if (Value == "compiler-rt") return ToolChain::RLT_CompilerRT; if (Value == "libgcc") return ToolChain::RLT_Libgcc; getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args); } return GetDefaultRuntimeLibType(); } ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{ if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) { StringRef Value = A->getValue(); if (Value == "libc++") return ToolChain::CST_Libcxx; if (Value == "libstdc++") return ToolChain::CST_Libstdcxx; getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args); } return ToolChain::CST_Libstdcxx; } /// \brief Utility function to add a system include directory to CC1 arguments. /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs, ArgStringList &CC1Args, const Twine &Path) { CC1Args.push_back("-internal-isystem"); CC1Args.push_back(DriverArgs.MakeArgString(Path)); } /// \brief Utility function to add a system include directory with extern "C" /// semantics to CC1 arguments. /// /// Note that this should be used rarely, and only for directories that /// historically and for legacy reasons are treated as having implicit extern /// "C" semantics. These semantics are *ignored* by and large today, but its /// important to preserve the preprocessor changes resulting from the /// classification. /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs, ArgStringList &CC1Args, const Twine &Path) { CC1Args.push_back("-internal-externc-isystem"); CC1Args.push_back(DriverArgs.MakeArgString(Path)); } /// \brief Utility function to add a list of system include directories to CC1. /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs, ArgStringList &CC1Args, ArrayRef<StringRef> Paths) { for (ArrayRef<StringRef>::iterator I = Paths.begin(), E = Paths.end(); I != E; ++I) { CC1Args.push_back("-internal-isystem"); CC1Args.push_back(DriverArgs.MakeArgString(*I)); } } void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { // Header search paths should be handled by each of the subclasses. // Historically, they have not been, and instead have been handled inside of // the CC1-layer frontend. As the logic is hoisted out, this generic function // will slowly stop being called. // // While it is being called, replicate a bit of a hack to propagate the // '-stdlib=' flag down to CC1 so that it can in turn customize the C++ // header search paths with it. Once all systems are overriding this // function, the CC1 flag and this line can be removed. DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ); } void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args, ArgStringList &CmdArgs) const { CXXStdlibType Type = GetCXXStdlibType(Args); switch (Type) { case ToolChain::CST_Libcxx: CmdArgs.push_back("-lc++"); break; case ToolChain::CST_Libstdcxx: CmdArgs.push_back("-lstdc++"); break; } } void ToolChain::AddCCKextLibArgs(const ArgList &Args, ArgStringList &CmdArgs) const { CmdArgs.push_back("-lcc_kext"); } bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args, ArgStringList &CmdArgs) const { // Check if -ffast-math or -funsafe-math is enabled. Arg *A = Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations, options::OPT_fno_unsafe_math_optimizations); if (!A || A->getOption().getID() == options::OPT_fno_fast_math || A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations) return false; // If crtfastmath.o exists add it to the arguments. std::string Path = GetFilePath("crtfastmath.o"); if (Path == "crtfastmath.o") // Not found. return false; CmdArgs.push_back(Args.MakeArgString(Path)); return true; } <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl> * Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "gameobjectprivate.h" using namespace GluonEngine; GameObjectPrivate::GameObjectPrivate() : enabled( true ) , position( QVector3D() ) , scale( QVector3D( 1, 1, 1 ) ) , orientation( QQuaternion( 0, 0, 0, 1 ) ) , transform( QMatrix4x4() ) , transformInvalidated( true ) , parentGameObject( 0 ) { } GameObjectPrivate::GameObjectPrivate( const GameObjectPrivate& other ) : description( other.description ) , enabled( other.enabled ) , position( other.position ) , scale( other.scale ) , orientation( other.orientation ) , transform( QMatrix4x4() ) , transformInvalidated( true ) , parentGameObject( other.parentGameObject ) { } GameObjectPrivate::~GameObjectPrivate() { } <commit_msg>A wrong initialization value of orientation caused a 180 degrees rotation of the scene sometimes.<commit_after>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl> * Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "gameobjectprivate.h" using namespace GluonEngine; GameObjectPrivate::GameObjectPrivate() : enabled( true ) , position( QVector3D() ) , scale( QVector3D( 1, 1, 1 ) ) , orientation( QQuaternion( 1, 0, 0, 0 ) ) , transform( QMatrix4x4() ) , transformInvalidated( true ) , parentGameObject( 0 ) { } GameObjectPrivate::GameObjectPrivate( const GameObjectPrivate& other ) : description( other.description ) , enabled( other.enabled ) , position( other.position ) , scale( other.scale ) , orientation( other.orientation ) , transform( QMatrix4x4() ) , transformInvalidated( true ) , parentGameObject( other.parentGameObject ) { } GameObjectPrivate::~GameObjectPrivate() { } <|endoftext|>
<commit_before>/** * @file state_map.hpp * @brief Purpose: Contain a class to states method's management. * * MIT License * Copyright (c) 2017 MindScape * * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md */ #ifndef STATE_MAP_H #define STATE_MAP_H #include <string> #include <unordered_map> namespace engine { /** * @brief A StateMap class. * * Define a state of the game or of the characters. */ class StateMap { private: std::unordered_map<std::string, std::string> states; public: StateMap(std::unordered_map<std::string, std::string> p_states = {{}} ):states(p_states){ }; ~StateMap(){ }; void set_state (std::string, std::string); std::string get_state (std::string); }; } #endif <commit_msg>[INITIALIZATION] Applies initialization in state_map.hpp variables<commit_after>/** * @file state_map.hpp * @brief Purpose: Contain a class to states method's management. * * MIT License * Copyright (c) 2017 MindScape * * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md */ #ifndef STATE_MAP_H #define STATE_MAP_H #include <string> #include <unordered_map> namespace engine { /** * @brief A StateMap class. * * Define a state of the game or of the characters. */ class StateMap { private: std::unordered_map<std::string, std::string> states = {{}}; public: StateMap(std::unordered_map<std::string, std::string> p_states = {{}} ):states(p_states){ }; ~StateMap(){ }; void set_state (std::string, std::string); std::string get_state (std::string); }; } #endif <|endoftext|>
<commit_before>/* * Block Cipher Lookup * (C) 1999-2007 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/def_eng.h> #include <botan/scan_name.h> #include <botan/algo_factory.h> #if defined(BOTAN_HAS_AES) #include <botan/aes.h> #endif #if defined(BOTAN_HAS_BLOWFISH) #include <botan/blowfish.h> #endif #if defined(BOTAN_HAS_CAST) #include <botan/cast128.h> #include <botan/cast256.h> #endif #if defined(BOTAN_HAS_DES) #include <botan/des.h> #include <botan/desx.h> #endif #if defined(BOTAN_HAS_GOST_28147_89) #include <botan/gost_28147.h> #endif #if defined(BOTAN_HAS_IDEA) #include <botan/idea.h> #endif #if defined(BOTAN_HAS_KASUMI) #include <botan/kasumi.h> #endif #if defined(BOTAN_HAS_LION) #include <botan/lion.h> #endif #if defined(BOTAN_HAS_LUBY_RACKOFF) #include <botan/lubyrack.h> #endif #if defined(BOTAN_HAS_MARS) #include <botan/mars.h> #endif #if defined(BOTAN_HAS_MISTY1) #include <botan/misty1.h> #endif #if defined(BOTAN_HAS_NOEKEON) #include <botan/noekeon.h> #endif #if defined(BOTAN_HAS_RC2) #include <botan/rc2.h> #endif #if defined(BOTAN_HAS_RC5) #include <botan/rc5.h> #endif #if defined(BOTAN_HAS_RC6) #include <botan/rc6.h> #endif #if defined(BOTAN_HAS_SAFER) #include <botan/safer_sk.h> #endif #if defined(BOTAN_HAS_SEED) #include <botan/seed.h> #endif #if defined(BOTAN_HAS_SERPENT) #include <botan/serpent.h> #endif #if defined(BOTAN_HAS_SKIPJACK) #include <botan/skipjack.h> #endif #if defined(BOTAN_HAS_SQUARE) #include <botan/square.h> #endif #if defined(BOTAN_HAS_TEA) #include <botan/tea.h> #endif #if defined(BOTAN_HAS_TWOFISH) #include <botan/twofish.h> #endif #if defined(BOTAN_HAS_XTEA) #include <botan/xtea.h> #endif namespace Botan { /* * Look for an algorithm with this name */ BlockCipher* Default_Engine::find_block_cipher(const SCAN_Name& request, Algorithm_Factory& af) const { #if defined(BOTAN_HAS_AES) if(request.algo_name() == "AES") return new AES; if(request.algo_name() == "AES-128") return new AES_128; if(request.algo_name() == "AES-192") return new AES_192; if(request.algo_name() == "AES-256") return new AES_256; #endif #if defined(BOTAN_HAS_BLOWFISH) if(request.algo_name() == "Blowfish") return new Blowfish; #endif #if defined(BOTAN_HAS_CAST) if(request.algo_name() == "CAST-128") return new CAST_128; if(request.algo_name() == "CAST-256") return new CAST_256; #endif #if defined(BOTAN_HAS_DES) if(request.algo_name() == "DES") return new DES; if(request.algo_name() == "DESX") return new DESX; if(request.algo_name() == "TripleDES") return new TripleDES; #endif #if defined(BOTAN_HAS_GOST_28147_89) if(request.algo_name() == "GOST-28147-89") return new GOST_28147_89; #endif #if defined(BOTAN_HAS_IDEA) if(request.algo_name() == "IDEA") return new IDEA; #endif #if defined(BOTAN_HAS_KASUMI) if(request.algo_name() == "KASUMI") return new KASUMI; #endif #if defined(BOTAN_HAS_MARS) if(request.algo_name() == "MARS") return new MARS; #endif #if defined(BOTAN_HAS_MISTY1) if(request.algo_name() == "MISTY1") return new MISTY1(request.arg_as_u32bit(0, 8)); #endif #if defined(BOTAN_HAS_NOEKEON) if(request.algo_name() == "Noekeon") return new Noekeon; #endif #if defined(BOTAN_HAS_RC2) if(request.algo_name() == "RC2") return new RC2; #endif #if defined(BOTAN_HAS_RC5) if(request.algo_name() == "RC5") return new RC5(request.arg_as_u32bit(0, 12)); #endif #if defined(BOTAN_HAS_RC6) if(request.algo_name() == "RC6") return new RC6; #endif #if defined(BOTAN_HAS_SAFER) if(request.algo_name() == "SAFER-SK") return new SAFER_SK(request.arg_as_u32bit(0, 10)); #endif #if defined(BOTAN_HAS_SEED) if(request.algo_name() == "SEED") return new SEED; #endif #if defined(BOTAN_HAS_SERPENT) if(request.algo_name() == "Serpent") return new Serpent; #endif #if defined(BOTAN_HAS_SKIPJACK) if(request.algo_name() == "Skipjack") return new Skipjack; #endif #if defined(BOTAN_HAS_SQUARE) if(request.algo_name() == "Square") return new Square; #endif #if defined(BOTAN_HAS_TEA) if(request.algo_name() == "TEA") return new TEA; #endif #if defined(BOTAN_HAS_TWOFISH) if(request.algo_name() == "Twofish") return new Twofish; #endif #if defined(BOTAN_HAS_XTEA) if(request.algo_name() == "XTEA") return new XTEA; #endif #if defined(BOTAN_HAS_LUBY_RACKOFF) if(request.algo_name() == "Luby-Rackoff" && request.arg_count() == 1) { const HashFunction* hash = af.prototype_hash_function(request.arg(0)); if(hash) return new LubyRackoff(hash->clone()); } #endif #if defined(BOTAN_HAS_LION) if(request.algo_name() == "Lion" && request.arg_count_between(2, 3)) { const u32bit block_size = request.arg_as_u32bit(2, 1024); const HashFunction* hash = af.prototype_hash_function(request.arg(0)); const StreamCipher* stream_cipher = af.prototype_stream_cipher(request.arg(1)); if(!hash || !stream_cipher) return 0; return new Lion(hash->clone(), stream_cipher->clone(), block_size); } #endif return 0; } } <commit_msg>Support different GOST paramters in the lookup interface.<commit_after>/* * Block Cipher Lookup * (C) 1999-2007 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/def_eng.h> #include <botan/scan_name.h> #include <botan/algo_factory.h> #if defined(BOTAN_HAS_AES) #include <botan/aes.h> #endif #if defined(BOTAN_HAS_BLOWFISH) #include <botan/blowfish.h> #endif #if defined(BOTAN_HAS_CAST) #include <botan/cast128.h> #include <botan/cast256.h> #endif #if defined(BOTAN_HAS_DES) #include <botan/des.h> #include <botan/desx.h> #endif #if defined(BOTAN_HAS_GOST_28147_89) #include <botan/gost_28147.h> #endif #if defined(BOTAN_HAS_IDEA) #include <botan/idea.h> #endif #if defined(BOTAN_HAS_KASUMI) #include <botan/kasumi.h> #endif #if defined(BOTAN_HAS_LION) #include <botan/lion.h> #endif #if defined(BOTAN_HAS_LUBY_RACKOFF) #include <botan/lubyrack.h> #endif #if defined(BOTAN_HAS_MARS) #include <botan/mars.h> #endif #if defined(BOTAN_HAS_MISTY1) #include <botan/misty1.h> #endif #if defined(BOTAN_HAS_NOEKEON) #include <botan/noekeon.h> #endif #if defined(BOTAN_HAS_RC2) #include <botan/rc2.h> #endif #if defined(BOTAN_HAS_RC5) #include <botan/rc5.h> #endif #if defined(BOTAN_HAS_RC6) #include <botan/rc6.h> #endif #if defined(BOTAN_HAS_SAFER) #include <botan/safer_sk.h> #endif #if defined(BOTAN_HAS_SEED) #include <botan/seed.h> #endif #if defined(BOTAN_HAS_SERPENT) #include <botan/serpent.h> #endif #if defined(BOTAN_HAS_SKIPJACK) #include <botan/skipjack.h> #endif #if defined(BOTAN_HAS_SQUARE) #include <botan/square.h> #endif #if defined(BOTAN_HAS_TEA) #include <botan/tea.h> #endif #if defined(BOTAN_HAS_TWOFISH) #include <botan/twofish.h> #endif #if defined(BOTAN_HAS_XTEA) #include <botan/xtea.h> #endif namespace Botan { /* * Look for an algorithm with this name */ BlockCipher* Default_Engine::find_block_cipher(const SCAN_Name& request, Algorithm_Factory& af) const { #if defined(BOTAN_HAS_AES) if(request.algo_name() == "AES") return new AES; if(request.algo_name() == "AES-128") return new AES_128; if(request.algo_name() == "AES-192") return new AES_192; if(request.algo_name() == "AES-256") return new AES_256; #endif #if defined(BOTAN_HAS_BLOWFISH) if(request.algo_name() == "Blowfish") return new Blowfish; #endif #if defined(BOTAN_HAS_CAST) if(request.algo_name() == "CAST-128") return new CAST_128; if(request.algo_name() == "CAST-256") return new CAST_256; #endif #if defined(BOTAN_HAS_DES) if(request.algo_name() == "DES") return new DES; if(request.algo_name() == "DESX") return new DESX; if(request.algo_name() == "TripleDES") return new TripleDES; #endif #if defined(BOTAN_HAS_GOST_28147_89) if(request.algo_name() == "GOST-28147-89") return new GOST_28147_89(request.arg(0, "R3411_94_TestParam")); #endif #if defined(BOTAN_HAS_IDEA) if(request.algo_name() == "IDEA") return new IDEA; #endif #if defined(BOTAN_HAS_KASUMI) if(request.algo_name() == "KASUMI") return new KASUMI; #endif #if defined(BOTAN_HAS_MARS) if(request.algo_name() == "MARS") return new MARS; #endif #if defined(BOTAN_HAS_MISTY1) if(request.algo_name() == "MISTY1") return new MISTY1(request.arg_as_u32bit(0, 8)); #endif #if defined(BOTAN_HAS_NOEKEON) if(request.algo_name() == "Noekeon") return new Noekeon; #endif #if defined(BOTAN_HAS_RC2) if(request.algo_name() == "RC2") return new RC2; #endif #if defined(BOTAN_HAS_RC5) if(request.algo_name() == "RC5") return new RC5(request.arg_as_u32bit(0, 12)); #endif #if defined(BOTAN_HAS_RC6) if(request.algo_name() == "RC6") return new RC6; #endif #if defined(BOTAN_HAS_SAFER) if(request.algo_name() == "SAFER-SK") return new SAFER_SK(request.arg_as_u32bit(0, 10)); #endif #if defined(BOTAN_HAS_SEED) if(request.algo_name() == "SEED") return new SEED; #endif #if defined(BOTAN_HAS_SERPENT) if(request.algo_name() == "Serpent") return new Serpent; #endif #if defined(BOTAN_HAS_SKIPJACK) if(request.algo_name() == "Skipjack") return new Skipjack; #endif #if defined(BOTAN_HAS_SQUARE) if(request.algo_name() == "Square") return new Square; #endif #if defined(BOTAN_HAS_TEA) if(request.algo_name() == "TEA") return new TEA; #endif #if defined(BOTAN_HAS_TWOFISH) if(request.algo_name() == "Twofish") return new Twofish; #endif #if defined(BOTAN_HAS_XTEA) if(request.algo_name() == "XTEA") return new XTEA; #endif #if defined(BOTAN_HAS_LUBY_RACKOFF) if(request.algo_name() == "Luby-Rackoff" && request.arg_count() == 1) { const HashFunction* hash = af.prototype_hash_function(request.arg(0)); if(hash) return new LubyRackoff(hash->clone()); } #endif #if defined(BOTAN_HAS_LION) if(request.algo_name() == "Lion" && request.arg_count_between(2, 3)) { const u32bit block_size = request.arg_as_u32bit(2, 1024); const HashFunction* hash = af.prototype_hash_function(request.arg(0)); const StreamCipher* stream_cipher = af.prototype_stream_cipher(request.arg(1)); if(!hash || !stream_cipher) return 0; return new Lion(hash->clone(), stream_cipher->clone(), block_size); } #endif return 0; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include <iostream> #include <essentia/algorithmfactory.h> #include <essentia/streaming/algorithms/poolstorage.h> #include <essentia/scheduler/network.h> #include "credit_libav.h" using namespace std; using namespace essentia; using namespace essentia::streaming; using namespace essentia::scheduler; int main(int argc, char* argv[]) { if (argc != 3) { cout << "Error: incorrect number of arguments." << endl; cout << "Usage: " << argv[0] << " audio_input json_output" << endl; cout << "Computes spectrogram and mel-band log-energies spectrogram for the input audiofile." << endl; creditLibAV(); exit(1); } string audioFilename = argv[1]; string outputFilename = argv[2]; essentia::init(); Pool pool; // TODO this should be configurable Real sampleRate = 44100.0; int frameSize = 2048; int hopSize = 1024; std::string format ("json"); AlgorithmFactory& factory = streaming::AlgorithmFactory::instance(); Algorithm* audio = factory.create("MonoLoader", "filename", audioFilename, "sampleRate", sampleRate); Algorithm* fc = factory.create("FrameCutter", "frameSize", frameSize, "hopSize", hopSize, "silentFrames", "noise"); Algorithm* w = factory.create("Windowing", "type", "blackmanharris62"); Algorithm* spec = factory.create("Spectrum"); Algorithm* mfcc = factory.create("MFCC", "numberBands", 40, "numberCoefficients", 20); Algorithm* melbands96 = factory.create("MelBands", "numberBands", 96, "log", true); // Audio -> FrameCutter -> Windowing -> Spectrum audio->output("audio") >> fc->input("signal"); fc->output("frame") >> w->input("frame"); w->output("frame") >> spec->input("frame"); // Spectrum -> MFCC -> Pool spec->output("spectrum") >> mfcc->input("spectrum"); spec->output("spectrum") >> melbands96->input("spectrum"); mfcc->output("bands") >> NOWHERE; // only store high-res mel bands mfcc->output("mfcc") >> PC(pool, "lowlevel.mfcc"); melbands96->output("bands") >> PC(pool, "lowlevel.melbands96"); cout << "Analyzing " << audioFilename << endl;; Network n(audio); n.run(); // write results to file cout << "Writing results to file " << outputFilename << endl; standard::Algorithm* output = standard::AlgorithmFactory::create("YamlOutput", "filename", outputFilename, "format", format); output->input("pool").set(pool); output->compute(); n.clear(); delete output; essentia::shutdown(); return 0; } <commit_msg>Output binary spectrogram in spectrogram extractor<commit_after>/* * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include <iostream> #include <essentia/algorithmfactory.h> #include <essentia/streaming/algorithms/poolstorage.h> #include <essentia/streaming/algorithms/fileoutput.h> #include <essentia/scheduler/network.h> #include "credit_libav.h" using namespace std; using namespace essentia; using namespace essentia::streaming; using namespace essentia::scheduler; int main(int argc, char* argv[]) { if (argc != 3) { cout << "Error: incorrect number of arguments." << endl; cout << "Usage: " << argv[0] << " audio_input json_output" << endl; cout << "Computes spectrogram and mel-band log-energies spectrogram for the input audiofile." << endl; creditLibAV(); exit(1); } string audioFile = argv[1]; string outputFile = argv[2]; string outputSpecFile = outputFile + ".spec"; essentia::init(); Pool pool; // TODO this should be configurable Real sampleRate = 44100.0; int frameSize = 2048; int hopSize = 1024; std::string format ("json"); AlgorithmFactory& factory = streaming::AlgorithmFactory::instance(); Algorithm* audio = factory.create("MonoLoader", "filename", audioFile, "sampleRate", sampleRate); Algorithm* fc = factory.create("FrameCutter", "frameSize", frameSize, "hopSize", hopSize, "silentFrames", "noise"); Algorithm* w = factory.create("Windowing", "type", "blackmanharris62"); Algorithm* spec = factory.create("Spectrum"); Algorithm* mfcc = factory.create("MFCC", "numberBands", 40, "numberCoefficients", 20); Algorithm* melbands96 = factory.create("MelBands", "numberBands", 96, "log", true); Algorithm* file = new FileOutput<vector<Real> >(); file->configure("filename", outputSpecFile, "mode", "binary"); // Audio -> FrameCutter -> Windowing -> Spectrum audio->output("audio") >> fc->input("signal"); fc->output("frame") >> w->input("frame"); w->output("frame") >> spec->input("frame"); // Spectrum -> MFCC -> Pool spec->output("spectrum") >> mfcc->input("spectrum"); spec->output("spectrum") >> melbands96->input("spectrum"); spec->output("spectrum") >> file->input("data"); mfcc->output("bands") >> NOWHERE; // only store high-res mel bands mfcc->output("mfcc") >> PC(pool, "lowlevel.mfcc"); melbands96->output("bands") >> PC(pool, "lowlevel.melbands96"); cout << "Analyzing " << audioFile << endl;; Network n(audio); n.run(); // write results to file cout << "Writing results to json file " << outputFile << endl; cout << "Writing spectrogram to binary file " << outputSpecFile << endl; standard::Algorithm* output = standard::AlgorithmFactory::create("YamlOutput", "filename", outputFile, "format", format); output->input("pool").set(pool); output->compute(); n.clear(); delete output; essentia::shutdown(); return 0; } <|endoftext|>
<commit_before>// Copyright 2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/js/mse/media_element.h" #include <cmath> #include "src/core/js_manager_impl.h" #include "src/js/dom/document.h" #include "src/js/js_error.h" #include "src/js/mse/media_source.h" #include "src/js/mse/time_ranges.h" #include "src/media/media_utils.h" #include "src/util/macros.h" #include "src/util/utils.h" namespace shaka { namespace js { namespace mse { #define NOT_ATTACHED_ERROR \ JsError::DOMException(InvalidStateError, \ "The video has been detached from the MediaPlayer") #define CHECK_ATTACHED() \ if (player_) \ ; \ else \ return NOT_ATTACHED_ERROR HTMLMediaElement::HTMLMediaElement(RefPtr<dom::Document> document, const std::string& name, media::MediaPlayer* player) : dom::Element(document, name, nullopt, nullopt), autoplay(false), loop(false), default_muted(false), audio_tracks(new AudioTrackList(player)), video_tracks(new VideoTrackList(player)), text_tracks(new TextTrackList(player)), player_(player), clock_(&util::Clock::Instance) { AddListenerField(EventType::Encrypted, &on_encrypted); AddListenerField(EventType::WaitingForKey, &on_waiting_for_key); player_->AddClient(this); } // \cond Doxygen_Skip HTMLMediaElement::~HTMLMediaElement() { if (player_) Detach(); } // \endcond Doxygen_Skip void HTMLMediaElement::Trace(memory::HeapTracer* tracer) const { dom::Element::Trace(tracer); tracer->Trace(&error); tracer->Trace(&media_source_); tracer->Trace(&audio_tracks); tracer->Trace(&video_tracks); tracer->Trace(&text_tracks); } void HTMLMediaElement::Detach() { player_->RemoveClient(this); player_ = nullptr; audio_tracks->Detach(); video_tracks->Detach(); text_tracks->Detach(); } Promise HTMLMediaElement::SetMediaKeys(RefPtr<eme::MediaKeys> media_keys) { if (!player_) return Promise::Rejected(NOT_ATTACHED_ERROR); if (!media_keys && !media_source_) return Promise::Resolved(); eme::Implementation* cdm = media_keys ? media_keys->GetCdm() : nullptr; std::string key_system = media_keys ? media_keys->key_system : ""; player_->SetEmeImplementation(key_system, cdm); this->media_keys = media_keys; return Promise::Resolved(); } ExceptionOr<void> HTMLMediaElement::Load() { CHECK_ATTACHED(); error = nullptr; if (media_source_) { player_->Detach(); media_source_->CloseMediaSource(); media_source_.reset(); } else if (!src_.empty()) { player_->Detach(); src_ = ""; } SetMuted(default_muted); return {}; } CanPlayTypeEnum HTMLMediaElement::CanPlayType(const std::string& type) { auto info = ConvertMimeToDecodingConfiguration(type, media::MediaDecodingType::File); auto support = player_->DecodingInfo(info); if (!support.supported) return CanPlayTypeEnum::EMPTY; else if (!support.smooth) return CanPlayTypeEnum::MAYBE; return CanPlayTypeEnum::PROBABLY; } media::VideoReadyState HTMLMediaElement::GetReadyState() const { if (!player_) return media::VideoReadyState::HaveNothing; auto ret = player_->ReadyState(); if (ret == media::VideoReadyState::NotAttached) ret = media::VideoReadyState::HaveNothing; return ret; } RefPtr<TimeRanges> HTMLMediaElement::Buffered() const { return new TimeRanges(player_ ? player_->GetBuffered() : std::vector<media::BufferedRange>{}); } RefPtr<TimeRanges> HTMLMediaElement::Seekable() const { const double duration = Duration(); media::BufferedRanges ranges; if (std::isfinite(duration)) ranges.emplace_back(0, duration); return new TimeRanges(ranges); } std::string HTMLMediaElement::Source() const { return media_source_ ? media_source_->url : src_; } ExceptionOr<void> HTMLMediaElement::SetSource(const std::string& src) { // Unload any previous MediaSource objects. RETURN_IF_ERROR(Load()); DCHECK(!media_source_); if (src.empty()) return {}; media_source_ = MediaSource::FindMediaSource(src); if (media_source_) { if (!player_->AttachMse()) { return JsError::DOMException(NotSupportedError, "Error attaching to MediaPlayer"); } media_source_->OpenMediaSource(this, player_); if (autoplay) player_->Play(); } else { if (!player_->AttachSource(src)) { return JsError::DOMException(NotSupportedError, "Given src= URL is unsupported"); } src_ = src; } return {}; } double HTMLMediaElement::CurrentTime() const { return player_ ? player_->CurrentTime() : 0; } ExceptionOr<void> HTMLMediaElement::SetCurrentTime(double time) { CHECK_ATTACHED(); player_->SetCurrentTime(time); return {}; } double HTMLMediaElement::Duration() const { return player_ ? player_->Duration() : 0; } double HTMLMediaElement::PlaybackRate() const { return player_ ? player_->PlaybackRate() : 0; } ExceptionOr<void> HTMLMediaElement::SetPlaybackRate(double rate) { CHECK_ATTACHED(); player_->SetPlaybackRate(rate); return {}; } bool HTMLMediaElement::Muted() const { return player_ && player_->Muted(); } ExceptionOr<void> HTMLMediaElement::SetMuted(bool muted) { CHECK_ATTACHED(); player_->SetMuted(muted); return {}; } double HTMLMediaElement::Volume() const { return player_ ? player_->Volume() : 0; } ExceptionOr<void> HTMLMediaElement::SetVolume(double volume) { CHECK_ATTACHED(); if (volume < 0 || volume > 1) { return JsError::DOMException( IndexSizeError, util::StringPrintf( "The volume provided (%f) is outside the range [0, 1].", volume)); } player_->SetVolume(volume); return {}; } bool HTMLMediaElement::Paused() const { if (!player_) return false; auto state = player_->PlaybackState(); return state == media::VideoPlaybackState::Initializing || state == media::VideoPlaybackState::Paused || state == media::VideoPlaybackState::Ended; } bool HTMLMediaElement::Seeking() const { return player_ && player_->PlaybackState() == media::VideoPlaybackState::Seeking; } bool HTMLMediaElement::Ended() const { return player_ && player_->PlaybackState() == media::VideoPlaybackState::Ended; } ExceptionOr<void> HTMLMediaElement::Play() { CHECK_ATTACHED(); player_->Play(); return {}; } ExceptionOr<void> HTMLMediaElement::Pause() { CHECK_ATTACHED(); player_->Pause(); return {}; } ExceptionOr<RefPtr<TextTrack>> HTMLMediaElement::AddTextTrack( media::TextTrackKind kind, optional<std::string> label, optional<std::string> language) { CHECK_ATTACHED(); auto track = player_->AddTextTrack(kind, label.value_or(""), language.value_or("")); if (!track) { return JsError::DOMException(UnknownError, "Error creating TextTrack"); } // The TextTrackList should already have gotten an event callback for the new // track, so the JS object should be in the list. RefPtr<TextTrack> ret = text_tracks->GetTrack(track); DCHECK(ret); return ret; } void HTMLMediaElement::OnReadyStateChanged(media::VideoReadyState old_state, media::VideoReadyState new_state) { if (old_state < media::VideoReadyState::HaveMetadata && new_state >= media::VideoReadyState::HaveMetadata) { ScheduleEvent<events::Event>(EventType::LoadedMetaData); } if (old_state < media::VideoReadyState::HaveCurrentData && new_state >= media::VideoReadyState::HaveCurrentData) { ScheduleEvent<events::Event>(EventType::LoadedData); } if (old_state < media::VideoReadyState::HaveFutureData && new_state >= media::VideoReadyState::HaveFutureData) { ScheduleEvent<events::Event>(EventType::CanPlay); } if (old_state < media::VideoReadyState::HaveEnoughData && new_state >= media::VideoReadyState::HaveEnoughData) { ScheduleEvent<events::Event>(EventType::CanPlayThrough); } if (old_state >= media::VideoReadyState::HaveFutureData && new_state < media::VideoReadyState::HaveFutureData && new_state > media::VideoReadyState::HaveNothing) { ScheduleEvent<events::Event>(EventType::Waiting); } ScheduleEvent<events::Event>(EventType::ReadyStateChange); } void HTMLMediaElement::OnPlaybackStateChanged( media::VideoPlaybackState old_state, media::VideoPlaybackState new_state) { switch (new_state) { case media::VideoPlaybackState::Detached: ScheduleEvent<events::Event>(EventType::Emptied); break; case media::VideoPlaybackState::Paused: ScheduleEvent<events::Event>(EventType::Pause); break; case media::VideoPlaybackState::Buffering: ScheduleEvent<events::Event>(EventType::Waiting); break; case media::VideoPlaybackState::Playing: ScheduleEvent<events::Event>(EventType::Playing); break; case media::VideoPlaybackState::Ended: ScheduleEvent<events::Event>(EventType::Ended); break; case media::VideoPlaybackState::Initializing: case media::VideoPlaybackState::Errored: break; case media::VideoPlaybackState::Seeking: // We also get an OnSeeking callback, so raise event there. break; case media::VideoPlaybackState::WaitingForKey: // This happens multiple times, raise the event in the OnWaitingForKey. break; } if (old_state == media::VideoPlaybackState::Seeking) ScheduleEvent<events::Event>(EventType::Seeked); } void HTMLMediaElement::OnError(const std::string& error) { if (!this->error) { if (error.empty()) this->error = new MediaError(MEDIA_ERR_DECODE, "Unknown media error"); else this->error = new MediaError(MEDIA_ERR_DECODE, error); } ScheduleEvent<events::Event>(EventType::Error); } void HTMLMediaElement::OnPlay() { ScheduleEvent<events::Event>(EventType::Play); } void HTMLMediaElement::OnSeeking() { ScheduleEvent<events::Event>(EventType::Seeking); } void HTMLMediaElement::OnWaitingForKey() { ScheduleEvent<events::Event>(EventType::WaitingForKey); } HTMLMediaElementFactory::HTMLMediaElementFactory() { AddConstant("HAVE_NOTHING", media::VideoReadyState::HaveNothing); AddConstant("HAVE_METADATA", media::VideoReadyState::HaveMetadata); AddConstant("HAVE_CURRENT_DATA", media::VideoReadyState::HaveCurrentData); AddConstant("HAVE_FUTURE_DATA", media::VideoReadyState::HaveFutureData); AddConstant("HAVE_ENOUGH_DATA", media::VideoReadyState::HaveEnoughData); AddListenerField(EventType::Encrypted, &HTMLMediaElement::on_encrypted); AddListenerField(EventType::WaitingForKey, &HTMLMediaElement::on_waiting_for_key); AddReadWriteProperty("autoplay", &HTMLMediaElement::autoplay); AddReadWriteProperty("loop", &HTMLMediaElement::loop); AddReadWriteProperty("defaultMuted", &HTMLMediaElement::default_muted); AddReadOnlyProperty("mediaKeys", &HTMLMediaElement::media_keys); AddReadOnlyProperty("error", &HTMLMediaElement::error); AddReadOnlyProperty("audioTracks", &HTMLMediaElement::audio_tracks); AddReadOnlyProperty("videoTracks", &HTMLMediaElement::video_tracks); AddReadOnlyProperty("textTracks", &HTMLMediaElement::text_tracks); AddGenericProperty("readyState", &HTMLMediaElement::GetReadyState); AddGenericProperty("paused", &HTMLMediaElement::Paused); AddGenericProperty("seeking", &HTMLMediaElement::Seeking); AddGenericProperty("ended", &HTMLMediaElement::Ended); AddGenericProperty("buffered", &HTMLMediaElement::Buffered); AddGenericProperty("seekable", &HTMLMediaElement::Seekable); AddGenericProperty("src", &HTMLMediaElement::Source, &HTMLMediaElement::SetSource); AddGenericProperty("currentSrc", &HTMLMediaElement::Source); AddGenericProperty("currentTime", &HTMLMediaElement::CurrentTime, &HTMLMediaElement::SetCurrentTime); AddGenericProperty("duration", &HTMLMediaElement::Duration); AddGenericProperty("playbackRate", &HTMLMediaElement::PlaybackRate, &HTMLMediaElement::SetPlaybackRate); AddGenericProperty("volume", &HTMLMediaElement::Volume, &HTMLMediaElement::SetVolume); AddGenericProperty("muted", &HTMLMediaElement::Muted, &HTMLMediaElement::SetMuted); AddMemberFunction("load", &HTMLMediaElement::Load); AddMemberFunction("play", &HTMLMediaElement::Play); AddMemberFunction("pause", &HTMLMediaElement::Pause); AddMemberFunction("setMediaKeys", &HTMLMediaElement::SetMediaKeys); AddMemberFunction("addTextTrack", &HTMLMediaElement::AddTextTrack); AddMemberFunction("canPlayType", &HTMLMediaElement::CanPlayType); NotImplemented("crossOrigin"); NotImplemented("networkState"); NotImplemented("preload"); NotImplemented("getStartDate"); NotImplemented("defaultPlaybackRate"); NotImplemented("playable"); NotImplemented("mediaGroup"); NotImplemented("controller"); NotImplemented("controls"); } } // namespace mse } // namespace js } // namespace shaka <commit_msg>Propagate errors attaching MediaKeys.<commit_after>// Copyright 2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/js/mse/media_element.h" #include <cmath> #include "src/core/js_manager_impl.h" #include "src/js/dom/document.h" #include "src/js/js_error.h" #include "src/js/mse/media_source.h" #include "src/js/mse/time_ranges.h" #include "src/media/media_utils.h" #include "src/util/macros.h" #include "src/util/utils.h" namespace shaka { namespace js { namespace mse { #define NOT_ATTACHED_ERROR \ JsError::DOMException(InvalidStateError, \ "The video has been detached from the MediaPlayer") #define CHECK_ATTACHED() \ if (player_) \ ; \ else \ return NOT_ATTACHED_ERROR HTMLMediaElement::HTMLMediaElement(RefPtr<dom::Document> document, const std::string& name, media::MediaPlayer* player) : dom::Element(document, name, nullopt, nullopt), autoplay(false), loop(false), default_muted(false), audio_tracks(new AudioTrackList(player)), video_tracks(new VideoTrackList(player)), text_tracks(new TextTrackList(player)), player_(player), clock_(&util::Clock::Instance) { AddListenerField(EventType::Encrypted, &on_encrypted); AddListenerField(EventType::WaitingForKey, &on_waiting_for_key); player_->AddClient(this); } // \cond Doxygen_Skip HTMLMediaElement::~HTMLMediaElement() { if (player_) Detach(); } // \endcond Doxygen_Skip void HTMLMediaElement::Trace(memory::HeapTracer* tracer) const { dom::Element::Trace(tracer); tracer->Trace(&error); tracer->Trace(&media_source_); tracer->Trace(&audio_tracks); tracer->Trace(&video_tracks); tracer->Trace(&text_tracks); } void HTMLMediaElement::Detach() { player_->RemoveClient(this); player_ = nullptr; audio_tracks->Detach(); video_tracks->Detach(); text_tracks->Detach(); } Promise HTMLMediaElement::SetMediaKeys(RefPtr<eme::MediaKeys> media_keys) { if (!player_) return Promise::Rejected(NOT_ATTACHED_ERROR); if (!media_keys && !media_source_) return Promise::Resolved(); eme::Implementation* cdm = media_keys ? media_keys->GetCdm() : nullptr; const std::string key_system = media_keys ? media_keys->key_system : ""; if (!player_->SetEmeImplementation(key_system, cdm)) { return Promise::Rejected( JsError::TypeError("Error changing MediaKeys on the MediaPlayer")); } this->media_keys = media_keys; return Promise::Resolved(); } ExceptionOr<void> HTMLMediaElement::Load() { CHECK_ATTACHED(); error = nullptr; if (media_source_) { player_->Detach(); media_source_->CloseMediaSource(); media_source_.reset(); } else if (!src_.empty()) { player_->Detach(); src_ = ""; } SetMuted(default_muted); return {}; } CanPlayTypeEnum HTMLMediaElement::CanPlayType(const std::string& type) { auto info = ConvertMimeToDecodingConfiguration(type, media::MediaDecodingType::File); auto support = player_->DecodingInfo(info); if (!support.supported) return CanPlayTypeEnum::EMPTY; else if (!support.smooth) return CanPlayTypeEnum::MAYBE; return CanPlayTypeEnum::PROBABLY; } media::VideoReadyState HTMLMediaElement::GetReadyState() const { if (!player_) return media::VideoReadyState::HaveNothing; auto ret = player_->ReadyState(); if (ret == media::VideoReadyState::NotAttached) ret = media::VideoReadyState::HaveNothing; return ret; } RefPtr<TimeRanges> HTMLMediaElement::Buffered() const { return new TimeRanges(player_ ? player_->GetBuffered() : std::vector<media::BufferedRange>{}); } RefPtr<TimeRanges> HTMLMediaElement::Seekable() const { const double duration = Duration(); media::BufferedRanges ranges; if (std::isfinite(duration)) ranges.emplace_back(0, duration); return new TimeRanges(ranges); } std::string HTMLMediaElement::Source() const { return media_source_ ? media_source_->url : src_; } ExceptionOr<void> HTMLMediaElement::SetSource(const std::string& src) { // Unload any previous MediaSource objects. RETURN_IF_ERROR(Load()); DCHECK(!media_source_); if (src.empty()) return {}; media_source_ = MediaSource::FindMediaSource(src); if (media_source_) { if (!player_->AttachMse()) { return JsError::DOMException(NotSupportedError, "Error attaching to MediaPlayer"); } media_source_->OpenMediaSource(this, player_); if (autoplay) player_->Play(); } else { if (!player_->AttachSource(src)) { return JsError::DOMException(NotSupportedError, "Given src= URL is unsupported"); } src_ = src; } return {}; } double HTMLMediaElement::CurrentTime() const { return player_ ? player_->CurrentTime() : 0; } ExceptionOr<void> HTMLMediaElement::SetCurrentTime(double time) { CHECK_ATTACHED(); player_->SetCurrentTime(time); return {}; } double HTMLMediaElement::Duration() const { return player_ ? player_->Duration() : 0; } double HTMLMediaElement::PlaybackRate() const { return player_ ? player_->PlaybackRate() : 0; } ExceptionOr<void> HTMLMediaElement::SetPlaybackRate(double rate) { CHECK_ATTACHED(); player_->SetPlaybackRate(rate); return {}; } bool HTMLMediaElement::Muted() const { return player_ && player_->Muted(); } ExceptionOr<void> HTMLMediaElement::SetMuted(bool muted) { CHECK_ATTACHED(); player_->SetMuted(muted); return {}; } double HTMLMediaElement::Volume() const { return player_ ? player_->Volume() : 0; } ExceptionOr<void> HTMLMediaElement::SetVolume(double volume) { CHECK_ATTACHED(); if (volume < 0 || volume > 1) { return JsError::DOMException( IndexSizeError, util::StringPrintf( "The volume provided (%f) is outside the range [0, 1].", volume)); } player_->SetVolume(volume); return {}; } bool HTMLMediaElement::Paused() const { if (!player_) return false; auto state = player_->PlaybackState(); return state == media::VideoPlaybackState::Initializing || state == media::VideoPlaybackState::Paused || state == media::VideoPlaybackState::Ended; } bool HTMLMediaElement::Seeking() const { return player_ && player_->PlaybackState() == media::VideoPlaybackState::Seeking; } bool HTMLMediaElement::Ended() const { return player_ && player_->PlaybackState() == media::VideoPlaybackState::Ended; } ExceptionOr<void> HTMLMediaElement::Play() { CHECK_ATTACHED(); player_->Play(); return {}; } ExceptionOr<void> HTMLMediaElement::Pause() { CHECK_ATTACHED(); player_->Pause(); return {}; } ExceptionOr<RefPtr<TextTrack>> HTMLMediaElement::AddTextTrack( media::TextTrackKind kind, optional<std::string> label, optional<std::string> language) { CHECK_ATTACHED(); auto track = player_->AddTextTrack(kind, label.value_or(""), language.value_or("")); if (!track) { return JsError::DOMException(UnknownError, "Error creating TextTrack"); } // The TextTrackList should already have gotten an event callback for the new // track, so the JS object should be in the list. RefPtr<TextTrack> ret = text_tracks->GetTrack(track); DCHECK(ret); return ret; } void HTMLMediaElement::OnReadyStateChanged(media::VideoReadyState old_state, media::VideoReadyState new_state) { if (old_state < media::VideoReadyState::HaveMetadata && new_state >= media::VideoReadyState::HaveMetadata) { ScheduleEvent<events::Event>(EventType::LoadedMetaData); } if (old_state < media::VideoReadyState::HaveCurrentData && new_state >= media::VideoReadyState::HaveCurrentData) { ScheduleEvent<events::Event>(EventType::LoadedData); } if (old_state < media::VideoReadyState::HaveFutureData && new_state >= media::VideoReadyState::HaveFutureData) { ScheduleEvent<events::Event>(EventType::CanPlay); } if (old_state < media::VideoReadyState::HaveEnoughData && new_state >= media::VideoReadyState::HaveEnoughData) { ScheduleEvent<events::Event>(EventType::CanPlayThrough); } if (old_state >= media::VideoReadyState::HaveFutureData && new_state < media::VideoReadyState::HaveFutureData && new_state > media::VideoReadyState::HaveNothing) { ScheduleEvent<events::Event>(EventType::Waiting); } ScheduleEvent<events::Event>(EventType::ReadyStateChange); } void HTMLMediaElement::OnPlaybackStateChanged( media::VideoPlaybackState old_state, media::VideoPlaybackState new_state) { switch (new_state) { case media::VideoPlaybackState::Detached: ScheduleEvent<events::Event>(EventType::Emptied); break; case media::VideoPlaybackState::Paused: ScheduleEvent<events::Event>(EventType::Pause); break; case media::VideoPlaybackState::Buffering: ScheduleEvent<events::Event>(EventType::Waiting); break; case media::VideoPlaybackState::Playing: ScheduleEvent<events::Event>(EventType::Playing); break; case media::VideoPlaybackState::Ended: ScheduleEvent<events::Event>(EventType::Ended); break; case media::VideoPlaybackState::Initializing: case media::VideoPlaybackState::Errored: break; case media::VideoPlaybackState::Seeking: // We also get an OnSeeking callback, so raise event there. break; case media::VideoPlaybackState::WaitingForKey: // This happens multiple times, raise the event in the OnWaitingForKey. break; } if (old_state == media::VideoPlaybackState::Seeking) ScheduleEvent<events::Event>(EventType::Seeked); } void HTMLMediaElement::OnError(const std::string& error) { if (!this->error) { if (error.empty()) this->error = new MediaError(MEDIA_ERR_DECODE, "Unknown media error"); else this->error = new MediaError(MEDIA_ERR_DECODE, error); } ScheduleEvent<events::Event>(EventType::Error); } void HTMLMediaElement::OnPlay() { ScheduleEvent<events::Event>(EventType::Play); } void HTMLMediaElement::OnSeeking() { ScheduleEvent<events::Event>(EventType::Seeking); } void HTMLMediaElement::OnWaitingForKey() { ScheduleEvent<events::Event>(EventType::WaitingForKey); } HTMLMediaElementFactory::HTMLMediaElementFactory() { AddConstant("HAVE_NOTHING", media::VideoReadyState::HaveNothing); AddConstant("HAVE_METADATA", media::VideoReadyState::HaveMetadata); AddConstant("HAVE_CURRENT_DATA", media::VideoReadyState::HaveCurrentData); AddConstant("HAVE_FUTURE_DATA", media::VideoReadyState::HaveFutureData); AddConstant("HAVE_ENOUGH_DATA", media::VideoReadyState::HaveEnoughData); AddListenerField(EventType::Encrypted, &HTMLMediaElement::on_encrypted); AddListenerField(EventType::WaitingForKey, &HTMLMediaElement::on_waiting_for_key); AddReadWriteProperty("autoplay", &HTMLMediaElement::autoplay); AddReadWriteProperty("loop", &HTMLMediaElement::loop); AddReadWriteProperty("defaultMuted", &HTMLMediaElement::default_muted); AddReadOnlyProperty("mediaKeys", &HTMLMediaElement::media_keys); AddReadOnlyProperty("error", &HTMLMediaElement::error); AddReadOnlyProperty("audioTracks", &HTMLMediaElement::audio_tracks); AddReadOnlyProperty("videoTracks", &HTMLMediaElement::video_tracks); AddReadOnlyProperty("textTracks", &HTMLMediaElement::text_tracks); AddGenericProperty("readyState", &HTMLMediaElement::GetReadyState); AddGenericProperty("paused", &HTMLMediaElement::Paused); AddGenericProperty("seeking", &HTMLMediaElement::Seeking); AddGenericProperty("ended", &HTMLMediaElement::Ended); AddGenericProperty("buffered", &HTMLMediaElement::Buffered); AddGenericProperty("seekable", &HTMLMediaElement::Seekable); AddGenericProperty("src", &HTMLMediaElement::Source, &HTMLMediaElement::SetSource); AddGenericProperty("currentSrc", &HTMLMediaElement::Source); AddGenericProperty("currentTime", &HTMLMediaElement::CurrentTime, &HTMLMediaElement::SetCurrentTime); AddGenericProperty("duration", &HTMLMediaElement::Duration); AddGenericProperty("playbackRate", &HTMLMediaElement::PlaybackRate, &HTMLMediaElement::SetPlaybackRate); AddGenericProperty("volume", &HTMLMediaElement::Volume, &HTMLMediaElement::SetVolume); AddGenericProperty("muted", &HTMLMediaElement::Muted, &HTMLMediaElement::SetMuted); AddMemberFunction("load", &HTMLMediaElement::Load); AddMemberFunction("play", &HTMLMediaElement::Play); AddMemberFunction("pause", &HTMLMediaElement::Pause); AddMemberFunction("setMediaKeys", &HTMLMediaElement::SetMediaKeys); AddMemberFunction("addTextTrack", &HTMLMediaElement::AddTextTrack); AddMemberFunction("canPlayType", &HTMLMediaElement::CanPlayType); NotImplemented("crossOrigin"); NotImplemented("networkState"); NotImplemented("preload"); NotImplemented("getStartDate"); NotImplemented("defaultPlaybackRate"); NotImplemented("playable"); NotImplemented("mediaGroup"); NotImplemented("controller"); NotImplemented("controls"); } } // namespace mse } // namespace js } // namespace shaka <|endoftext|>
<commit_before>//===- TGLexer.cpp - Lexer for TableGen -----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implement the Lexer for TableGen. // //===----------------------------------------------------------------------===// #include "TGLexer.h" #include "llvm/TableGen/Error.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Config/config.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/Twine.h" #include <cctype> #include <cstdio> #include <cstdlib> #include <cstring> #include <cerrno> using namespace llvm; TGLexer::TGLexer(SourceMgr &SM) : SrcMgr(SM) { CurBuffer = 0; CurBuf = SrcMgr.getMemoryBuffer(CurBuffer); CurPtr = CurBuf->getBufferStart(); TokStart = 0; } SMLoc TGLexer::getLoc() const { return SMLoc::getFromPointer(TokStart); } /// ReturnError - Set the error to the specified string at the specified /// location. This is defined to always return tgtok::Error. tgtok::TokKind TGLexer::ReturnError(const char *Loc, const Twine &Msg) { PrintError(Loc, Msg); return tgtok::Error; } int TGLexer::getNextChar() { char CurChar = *CurPtr++; switch (CurChar) { default: return (unsigned char)CurChar; case 0: { // A nul character in the stream is either the end of the current buffer or // a random nul in the file. Disambiguate that here. if (CurPtr-1 != CurBuf->getBufferEnd()) return 0; // Just whitespace. // If this is the end of an included file, pop the parent file off the // include stack. SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer); if (ParentIncludeLoc != SMLoc()) { CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc); CurBuf = SrcMgr.getMemoryBuffer(CurBuffer); CurPtr = ParentIncludeLoc.getPointer(); return getNextChar(); } // Otherwise, return end of file. --CurPtr; // Another call to lex will return EOF again. return EOF; } case '\n': case '\r': // Handle the newline character by ignoring it and incrementing the line // count. However, be careful about 'dos style' files with \n\r in them. // Only treat a \n\r or \r\n as a single line. if ((*CurPtr == '\n' || (*CurPtr == '\r')) && *CurPtr != CurChar) ++CurPtr; // Eat the two char newline sequence. return '\n'; } } tgtok::TokKind TGLexer::LexToken() { TokStart = CurPtr; // This always consumes at least one character. int CurChar = getNextChar(); switch (CurChar) { default: // Handle letters: [a-zA-Z_#] if (isalpha(CurChar) || CurChar == '_' || CurChar == '#') return LexIdentifier(); // Unknown character, emit an error. return ReturnError(TokStart, "Unexpected character"); case EOF: return tgtok::Eof; case ':': return tgtok::colon; case ';': return tgtok::semi; case '.': return tgtok::period; case ',': return tgtok::comma; case '<': return tgtok::less; case '>': return tgtok::greater; case ']': return tgtok::r_square; case '{': return tgtok::l_brace; case '}': return tgtok::r_brace; case '(': return tgtok::l_paren; case ')': return tgtok::r_paren; case '=': return tgtok::equal; case '?': return tgtok::question; case 0: case ' ': case '\t': case '\n': case '\r': // Ignore whitespace. return LexToken(); case '/': // If this is the start of a // comment, skip until the end of the line or // the end of the buffer. if (*CurPtr == '/') SkipBCPLComment(); else if (*CurPtr == '*') { if (SkipCComment()) return tgtok::Error; } else // Otherwise, this is an error. return ReturnError(TokStart, "Unexpected character"); return LexToken(); case '-': case '+': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return LexNumber(); case '"': return LexString(); case '$': return LexVarName(); case '[': return LexBracket(); case '!': return LexExclaim(); } } /// LexString - Lex "[^"]*" tgtok::TokKind TGLexer::LexString() { const char *StrStart = CurPtr; CurStrVal = ""; while (*CurPtr != '"') { // If we hit the end of the buffer, report an error. if (*CurPtr == 0 && CurPtr == CurBuf->getBufferEnd()) return ReturnError(StrStart, "End of file in string literal"); if (*CurPtr == '\n' || *CurPtr == '\r') return ReturnError(StrStart, "End of line in string literal"); if (*CurPtr != '\\') { CurStrVal += *CurPtr++; continue; } ++CurPtr; switch (*CurPtr) { case '\\': case '\'': case '"': // These turn into their literal character. CurStrVal += *CurPtr++; break; case 't': CurStrVal += '\t'; ++CurPtr; break; case 'n': CurStrVal += '\n'; ++CurPtr; break; case '\n': case '\r': return ReturnError(CurPtr, "escaped newlines not supported in tblgen"); // If we hit the end of the buffer, report an error. case '\0': if (CurPtr == CurBuf->getBufferEnd()) return ReturnError(StrStart, "End of file in string literal"); // FALL THROUGH default: return ReturnError(CurPtr, "invalid escape in string literal"); } } ++CurPtr; return tgtok::StrVal; } tgtok::TokKind TGLexer::LexVarName() { if (!isalpha(CurPtr[0]) && CurPtr[0] != '_') return ReturnError(TokStart, "Invalid variable name"); // Otherwise, we're ok, consume the rest of the characters. const char *VarNameStart = CurPtr++; while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_') ++CurPtr; CurStrVal.assign(VarNameStart, CurPtr); return tgtok::VarName; } tgtok::TokKind TGLexer::LexIdentifier() { // The first letter is [a-zA-Z_#]. const char *IdentStart = TokStart; // Match the rest of the identifier regex: [0-9a-zA-Z_#]* while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_' || *CurPtr == '#') ++CurPtr; // Check to see if this identifier is a keyword. unsigned Len = CurPtr-IdentStart; if (Len == 3 && !memcmp(IdentStart, "int", 3)) return tgtok::Int; if (Len == 3 && !memcmp(IdentStart, "bit", 3)) return tgtok::Bit; if (Len == 4 && !memcmp(IdentStart, "bits", 4)) return tgtok::Bits; if (Len == 6 && !memcmp(IdentStart, "string", 6)) return tgtok::String; if (Len == 4 && !memcmp(IdentStart, "list", 4)) return tgtok::List; if (Len == 4 && !memcmp(IdentStart, "code", 4)) return tgtok::Code; if (Len == 3 && !memcmp(IdentStart, "dag", 3)) return tgtok::Dag; if (Len == 5 && !memcmp(IdentStart, "class", 5)) return tgtok::Class; if (Len == 3 && !memcmp(IdentStart, "def", 3)) return tgtok::Def; if (Len == 8 && !memcmp(IdentStart, "multidef", 3)) return tgtok::MultiDef; if (Len == 4 && !memcmp(IdentStart, "defm", 4)) return tgtok::Defm; if (Len == 10 && !memcmp(IdentStart, "multiclass", 10)) return tgtok::MultiClass; if (Len == 5 && !memcmp(IdentStart, "field", 5)) return tgtok::Field; if (Len == 3 && !memcmp(IdentStart, "let", 3)) return tgtok::Let; if (Len == 2 && !memcmp(IdentStart, "in", 2)) return tgtok::In; if (Len == 7 && !memcmp(IdentStart, "include", 7)) { if (LexInclude()) return tgtok::Error; return Lex(); } CurStrVal.assign(IdentStart, CurPtr); return tgtok::Id; } /// LexInclude - We just read the "include" token. Get the string token that /// comes next and enter the include. bool TGLexer::LexInclude() { // The token after the include must be a string. tgtok::TokKind Tok = LexToken(); if (Tok == tgtok::Error) return true; if (Tok != tgtok::StrVal) { PrintError(getLoc(), "Expected filename after include"); return true; } // Get the string. std::string Filename = CurStrVal; std::string IncludedFile; CurBuffer = SrcMgr.AddIncludeFile(Filename, SMLoc::getFromPointer(CurPtr), IncludedFile); if (CurBuffer == -1) { PrintError(getLoc(), "Could not find include file '" + Filename + "'"); return true; } Dependencies.push_back(IncludedFile); // Save the line number and lex buffer of the includer. CurBuf = SrcMgr.getMemoryBuffer(CurBuffer); CurPtr = CurBuf->getBufferStart(); return false; } void TGLexer::SkipBCPLComment() { ++CurPtr; // skip the second slash. while (1) { switch (*CurPtr) { case '\n': case '\r': return; // Newline is end of comment. case 0: // If this is the end of the buffer, end the comment. if (CurPtr == CurBuf->getBufferEnd()) return; break; } // Otherwise, skip the character. ++CurPtr; } } /// SkipCComment - This skips C-style /**/ comments. The only difference from C /// is that we allow nesting. bool TGLexer::SkipCComment() { ++CurPtr; // skip the star. unsigned CommentDepth = 1; while (1) { int CurChar = getNextChar(); switch (CurChar) { case EOF: PrintError(TokStart, "Unterminated comment!"); return true; case '*': // End of the comment? if (CurPtr[0] != '/') break; ++CurPtr; // End the */. if (--CommentDepth == 0) return false; break; case '/': // Start of a nested comment? if (CurPtr[0] != '*') break; ++CurPtr; ++CommentDepth; break; } } } /// LexNumber - Lex: /// [-+]?[0-9]+ /// 0x[0-9a-fA-F]+ /// 0b[01]+ tgtok::TokKind TGLexer::LexNumber() { if (CurPtr[-1] == '0') { if (CurPtr[0] == 'x') { ++CurPtr; const char *NumStart = CurPtr; while (isxdigit(CurPtr[0])) ++CurPtr; // Requires at least one hex digit. if (CurPtr == NumStart) return ReturnError(TokStart, "Invalid hexadecimal number"); errno = 0; CurIntVal = strtoll(NumStart, 0, 16); if (errno == EINVAL) return ReturnError(TokStart, "Invalid hexadecimal number"); if (errno == ERANGE) { errno = 0; CurIntVal = (int64_t)strtoull(NumStart, 0, 16); if (errno == EINVAL) return ReturnError(TokStart, "Invalid hexadecimal number"); if (errno == ERANGE) return ReturnError(TokStart, "Hexadecimal number out of range"); } return tgtok::IntVal; } else if (CurPtr[0] == 'b') { ++CurPtr; const char *NumStart = CurPtr; while (CurPtr[0] == '0' || CurPtr[0] == '1') ++CurPtr; // Requires at least one binary digit. if (CurPtr == NumStart) return ReturnError(CurPtr-2, "Invalid binary number"); CurIntVal = strtoll(NumStart, 0, 2); return tgtok::IntVal; } } // Check for a sign without a digit. if (!isdigit(CurPtr[0])) { if (CurPtr[-1] == '-') return tgtok::minus; else if (CurPtr[-1] == '+') return tgtok::plus; } while (isdigit(CurPtr[0])) ++CurPtr; CurIntVal = strtoll(TokStart, 0, 10); return tgtok::IntVal; } /// LexBracket - We just read '['. If this is a code block, return it, /// otherwise return the bracket. Match: '[' and '[{ ( [^}]+ | }[^]] )* }]' tgtok::TokKind TGLexer::LexBracket() { if (CurPtr[0] != '{') return tgtok::l_square; ++CurPtr; const char *CodeStart = CurPtr; while (1) { int Char = getNextChar(); if (Char == EOF) break; if (Char != '}') continue; Char = getNextChar(); if (Char == EOF) break; if (Char == ']') { CurStrVal.assign(CodeStart, CurPtr-2); return tgtok::CodeFragment; } } return ReturnError(CodeStart-2, "Unterminated Code Block"); } /// LexExclaim - Lex '!' and '![a-zA-Z]+'. tgtok::TokKind TGLexer::LexExclaim() { if (!isalpha(*CurPtr)) return ReturnError(CurPtr - 1, "Invalid \"!operator\""); const char *Start = CurPtr++; while (isalpha(*CurPtr)) ++CurPtr; // Check to see which operator this is. tgtok::TokKind Kind = StringSwitch<tgtok::TokKind>(StringRef(Start, CurPtr - Start)) .Case("eq", tgtok::XEq) .Case("if", tgtok::XIf) .Case("head", tgtok::XHead) .Case("tail", tgtok::XTail) .Case("con", tgtok::XConcat) .Case("shl", tgtok::XSHL) .Case("sra", tgtok::XSRA) .Case("srl", tgtok::XSRL) .Case("cast", tgtok::XCast) .Case("empty", tgtok::XEmpty) .Case("subst", tgtok::XSubst) .Case("foreach", tgtok::XForEach) .Case("strconcat", tgtok::XStrConcat) .Default(tgtok::Error); return Kind != tgtok::Error ? Kind : ReturnError(Start-1, "Unknown operator"); } <commit_msg>Fix Typo<commit_after>//===- TGLexer.cpp - Lexer for TableGen -----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implement the Lexer for TableGen. // //===----------------------------------------------------------------------===// #include "TGLexer.h" #include "llvm/TableGen/Error.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Config/config.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/Twine.h" #include <cctype> #include <cstdio> #include <cstdlib> #include <cstring> #include <cerrno> using namespace llvm; TGLexer::TGLexer(SourceMgr &SM) : SrcMgr(SM) { CurBuffer = 0; CurBuf = SrcMgr.getMemoryBuffer(CurBuffer); CurPtr = CurBuf->getBufferStart(); TokStart = 0; } SMLoc TGLexer::getLoc() const { return SMLoc::getFromPointer(TokStart); } /// ReturnError - Set the error to the specified string at the specified /// location. This is defined to always return tgtok::Error. tgtok::TokKind TGLexer::ReturnError(const char *Loc, const Twine &Msg) { PrintError(Loc, Msg); return tgtok::Error; } int TGLexer::getNextChar() { char CurChar = *CurPtr++; switch (CurChar) { default: return (unsigned char)CurChar; case 0: { // A nul character in the stream is either the end of the current buffer or // a random nul in the file. Disambiguate that here. if (CurPtr-1 != CurBuf->getBufferEnd()) return 0; // Just whitespace. // If this is the end of an included file, pop the parent file off the // include stack. SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer); if (ParentIncludeLoc != SMLoc()) { CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc); CurBuf = SrcMgr.getMemoryBuffer(CurBuffer); CurPtr = ParentIncludeLoc.getPointer(); return getNextChar(); } // Otherwise, return end of file. --CurPtr; // Another call to lex will return EOF again. return EOF; } case '\n': case '\r': // Handle the newline character by ignoring it and incrementing the line // count. However, be careful about 'dos style' files with \n\r in them. // Only treat a \n\r or \r\n as a single line. if ((*CurPtr == '\n' || (*CurPtr == '\r')) && *CurPtr != CurChar) ++CurPtr; // Eat the two char newline sequence. return '\n'; } } tgtok::TokKind TGLexer::LexToken() { TokStart = CurPtr; // This always consumes at least one character. int CurChar = getNextChar(); switch (CurChar) { default: // Handle letters: [a-zA-Z_#] if (isalpha(CurChar) || CurChar == '_' || CurChar == '#') return LexIdentifier(); // Unknown character, emit an error. return ReturnError(TokStart, "Unexpected character"); case EOF: return tgtok::Eof; case ':': return tgtok::colon; case ';': return tgtok::semi; case '.': return tgtok::period; case ',': return tgtok::comma; case '<': return tgtok::less; case '>': return tgtok::greater; case ']': return tgtok::r_square; case '{': return tgtok::l_brace; case '}': return tgtok::r_brace; case '(': return tgtok::l_paren; case ')': return tgtok::r_paren; case '=': return tgtok::equal; case '?': return tgtok::question; case 0: case ' ': case '\t': case '\n': case '\r': // Ignore whitespace. return LexToken(); case '/': // If this is the start of a // comment, skip until the end of the line or // the end of the buffer. if (*CurPtr == '/') SkipBCPLComment(); else if (*CurPtr == '*') { if (SkipCComment()) return tgtok::Error; } else // Otherwise, this is an error. return ReturnError(TokStart, "Unexpected character"); return LexToken(); case '-': case '+': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return LexNumber(); case '"': return LexString(); case '$': return LexVarName(); case '[': return LexBracket(); case '!': return LexExclaim(); } } /// LexString - Lex "[^"]*" tgtok::TokKind TGLexer::LexString() { const char *StrStart = CurPtr; CurStrVal = ""; while (*CurPtr != '"') { // If we hit the end of the buffer, report an error. if (*CurPtr == 0 && CurPtr == CurBuf->getBufferEnd()) return ReturnError(StrStart, "End of file in string literal"); if (*CurPtr == '\n' || *CurPtr == '\r') return ReturnError(StrStart, "End of line in string literal"); if (*CurPtr != '\\') { CurStrVal += *CurPtr++; continue; } ++CurPtr; switch (*CurPtr) { case '\\': case '\'': case '"': // These turn into their literal character. CurStrVal += *CurPtr++; break; case 't': CurStrVal += '\t'; ++CurPtr; break; case 'n': CurStrVal += '\n'; ++CurPtr; break; case '\n': case '\r': return ReturnError(CurPtr, "escaped newlines not supported in tblgen"); // If we hit the end of the buffer, report an error. case '\0': if (CurPtr == CurBuf->getBufferEnd()) return ReturnError(StrStart, "End of file in string literal"); // FALL THROUGH default: return ReturnError(CurPtr, "invalid escape in string literal"); } } ++CurPtr; return tgtok::StrVal; } tgtok::TokKind TGLexer::LexVarName() { if (!isalpha(CurPtr[0]) && CurPtr[0] != '_') return ReturnError(TokStart, "Invalid variable name"); // Otherwise, we're ok, consume the rest of the characters. const char *VarNameStart = CurPtr++; while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_') ++CurPtr; CurStrVal.assign(VarNameStart, CurPtr); return tgtok::VarName; } tgtok::TokKind TGLexer::LexIdentifier() { // The first letter is [a-zA-Z_#]. const char *IdentStart = TokStart; // Match the rest of the identifier regex: [0-9a-zA-Z_#]* while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_' || *CurPtr == '#') ++CurPtr; // Check to see if this identifier is a keyword. unsigned Len = CurPtr-IdentStart; if (Len == 3 && !memcmp(IdentStart, "int", 3)) return tgtok::Int; if (Len == 3 && !memcmp(IdentStart, "bit", 3)) return tgtok::Bit; if (Len == 4 && !memcmp(IdentStart, "bits", 4)) return tgtok::Bits; if (Len == 6 && !memcmp(IdentStart, "string", 6)) return tgtok::String; if (Len == 4 && !memcmp(IdentStart, "list", 4)) return tgtok::List; if (Len == 4 && !memcmp(IdentStart, "code", 4)) return tgtok::Code; if (Len == 3 && !memcmp(IdentStart, "dag", 3)) return tgtok::Dag; if (Len == 5 && !memcmp(IdentStart, "class", 5)) return tgtok::Class; if (Len == 3 && !memcmp(IdentStart, "def", 3)) return tgtok::Def; if (Len == 8 && !memcmp(IdentStart, "multidef", 8)) return tgtok::MultiDef; if (Len == 4 && !memcmp(IdentStart, "defm", 4)) return tgtok::Defm; if (Len == 10 && !memcmp(IdentStart, "multiclass", 10)) return tgtok::MultiClass; if (Len == 5 && !memcmp(IdentStart, "field", 5)) return tgtok::Field; if (Len == 3 && !memcmp(IdentStart, "let", 3)) return tgtok::Let; if (Len == 2 && !memcmp(IdentStart, "in", 2)) return tgtok::In; if (Len == 7 && !memcmp(IdentStart, "include", 7)) { if (LexInclude()) return tgtok::Error; return Lex(); } CurStrVal.assign(IdentStart, CurPtr); return tgtok::Id; } /// LexInclude - We just read the "include" token. Get the string token that /// comes next and enter the include. bool TGLexer::LexInclude() { // The token after the include must be a string. tgtok::TokKind Tok = LexToken(); if (Tok == tgtok::Error) return true; if (Tok != tgtok::StrVal) { PrintError(getLoc(), "Expected filename after include"); return true; } // Get the string. std::string Filename = CurStrVal; std::string IncludedFile; CurBuffer = SrcMgr.AddIncludeFile(Filename, SMLoc::getFromPointer(CurPtr), IncludedFile); if (CurBuffer == -1) { PrintError(getLoc(), "Could not find include file '" + Filename + "'"); return true; } Dependencies.push_back(IncludedFile); // Save the line number and lex buffer of the includer. CurBuf = SrcMgr.getMemoryBuffer(CurBuffer); CurPtr = CurBuf->getBufferStart(); return false; } void TGLexer::SkipBCPLComment() { ++CurPtr; // skip the second slash. while (1) { switch (*CurPtr) { case '\n': case '\r': return; // Newline is end of comment. case 0: // If this is the end of the buffer, end the comment. if (CurPtr == CurBuf->getBufferEnd()) return; break; } // Otherwise, skip the character. ++CurPtr; } } /// SkipCComment - This skips C-style /**/ comments. The only difference from C /// is that we allow nesting. bool TGLexer::SkipCComment() { ++CurPtr; // skip the star. unsigned CommentDepth = 1; while (1) { int CurChar = getNextChar(); switch (CurChar) { case EOF: PrintError(TokStart, "Unterminated comment!"); return true; case '*': // End of the comment? if (CurPtr[0] != '/') break; ++CurPtr; // End the */. if (--CommentDepth == 0) return false; break; case '/': // Start of a nested comment? if (CurPtr[0] != '*') break; ++CurPtr; ++CommentDepth; break; } } } /// LexNumber - Lex: /// [-+]?[0-9]+ /// 0x[0-9a-fA-F]+ /// 0b[01]+ tgtok::TokKind TGLexer::LexNumber() { if (CurPtr[-1] == '0') { if (CurPtr[0] == 'x') { ++CurPtr; const char *NumStart = CurPtr; while (isxdigit(CurPtr[0])) ++CurPtr; // Requires at least one hex digit. if (CurPtr == NumStart) return ReturnError(TokStart, "Invalid hexadecimal number"); errno = 0; CurIntVal = strtoll(NumStart, 0, 16); if (errno == EINVAL) return ReturnError(TokStart, "Invalid hexadecimal number"); if (errno == ERANGE) { errno = 0; CurIntVal = (int64_t)strtoull(NumStart, 0, 16); if (errno == EINVAL) return ReturnError(TokStart, "Invalid hexadecimal number"); if (errno == ERANGE) return ReturnError(TokStart, "Hexadecimal number out of range"); } return tgtok::IntVal; } else if (CurPtr[0] == 'b') { ++CurPtr; const char *NumStart = CurPtr; while (CurPtr[0] == '0' || CurPtr[0] == '1') ++CurPtr; // Requires at least one binary digit. if (CurPtr == NumStart) return ReturnError(CurPtr-2, "Invalid binary number"); CurIntVal = strtoll(NumStart, 0, 2); return tgtok::IntVal; } } // Check for a sign without a digit. if (!isdigit(CurPtr[0])) { if (CurPtr[-1] == '-') return tgtok::minus; else if (CurPtr[-1] == '+') return tgtok::plus; } while (isdigit(CurPtr[0])) ++CurPtr; CurIntVal = strtoll(TokStart, 0, 10); return tgtok::IntVal; } /// LexBracket - We just read '['. If this is a code block, return it, /// otherwise return the bracket. Match: '[' and '[{ ( [^}]+ | }[^]] )* }]' tgtok::TokKind TGLexer::LexBracket() { if (CurPtr[0] != '{') return tgtok::l_square; ++CurPtr; const char *CodeStart = CurPtr; while (1) { int Char = getNextChar(); if (Char == EOF) break; if (Char != '}') continue; Char = getNextChar(); if (Char == EOF) break; if (Char == ']') { CurStrVal.assign(CodeStart, CurPtr-2); return tgtok::CodeFragment; } } return ReturnError(CodeStart-2, "Unterminated Code Block"); } /// LexExclaim - Lex '!' and '![a-zA-Z]+'. tgtok::TokKind TGLexer::LexExclaim() { if (!isalpha(*CurPtr)) return ReturnError(CurPtr - 1, "Invalid \"!operator\""); const char *Start = CurPtr++; while (isalpha(*CurPtr)) ++CurPtr; // Check to see which operator this is. tgtok::TokKind Kind = StringSwitch<tgtok::TokKind>(StringRef(Start, CurPtr - Start)) .Case("eq", tgtok::XEq) .Case("if", tgtok::XIf) .Case("head", tgtok::XHead) .Case("tail", tgtok::XTail) .Case("con", tgtok::XConcat) .Case("shl", tgtok::XSHL) .Case("sra", tgtok::XSRA) .Case("srl", tgtok::XSRL) .Case("cast", tgtok::XCast) .Case("empty", tgtok::XEmpty) .Case("subst", tgtok::XSubst) .Case("foreach", tgtok::XForEach) .Case("strconcat", tgtok::XStrConcat) .Default(tgtok::Error); return Kind != tgtok::Error ? Kind : ReturnError(Start-1, "Unknown operator"); } <|endoftext|>
<commit_before>#include "gvki/UnderlyingCaller.h" #include <iostream> #include <cstdlib> #ifndef MACRO_LIB #include <dlfcn.h> #endif using namespace gvki; #ifdef MACRO_LIB #define SET_FCN_PTR(functionName) functionName ## U = &(::functionName); #else #include <unistd.h> #define _SET_FCN_PTR(functionName, symbol) dlerror(); /* clear any old errors */ \ functionName ## U = reinterpret_cast<functionName ## Ty>(::dlsym(RTLD_NEXT, #symbol)); \ errorMsg = dlerror(); \ if ( errorMsg != NULL) { \ std::cerr << "Failed to dlsym(\"" #symbol "\"): " << errorMsg << std::endl; \ _exit(255); \ } \ if ( functionName ## U == NULL) { \ std::cerr << "Function pointer for \"" #functionName "\" cannot be NULL" << std::endl; \ _exit(255); \ } #ifdef __APPLE__ // Under OSX the OpenCL symbols are prefixed with an underscore [1] claims that // dlsym() is supposed to handle that for us but testing by others seemed to // suggest this wasn't the case. // // [1] https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/dlsym.3.html #define SET_FCN_PTR(functionName) _SET_FCN_PTR(functionName, _ ## functionName) #else #define SET_FCN_PTR(functionName) _SET_FCN_PTR(functionName, functionName) #endif #endif UnderlyingCaller::UnderlyingCaller() { const char* errorMsg = 0; SET_FCN_PTR(clCreateBuffer) SET_FCN_PTR(clCreateSubBuffer) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" // In OpenCL 1.2 these are deprecated. Don't warn about this. SET_FCN_PTR(clCreateImage2D) SET_FCN_PTR(clCreateImage3D) #pragma GCC diagnostic pop SET_FCN_PTR(clCreateSampler) SET_FCN_PTR(clCreateProgramWithSource) SET_FCN_PTR(clBuildProgram) SET_FCN_PTR(clCreateKernel) SET_FCN_PTR(clSetKernelArg) SET_FCN_PTR(clEnqueueNDRangeKernel) }; <commit_msg>Revert "Under OSX add an underscore prefix for the function name being passed"<commit_after>#include "gvki/UnderlyingCaller.h" #include <iostream> #include <cstdlib> #ifndef MACRO_LIB #include <dlfcn.h> #endif using namespace gvki; #ifdef MACRO_LIB #define SET_FCN_PTR(F) F ## U = &(::F); #else #include <unistd.h> #define SET_FCN_PTR(F) dlerror(); /* clear any old errors */ \ F ## U = reinterpret_cast<F ## Ty>(::dlsym(RTLD_NEXT, #F)); \ errorMsg = dlerror(); \ if ( errorMsg != NULL) { \ std::cerr << "Failed to dlsym(\"" #F "\"): " << errorMsg << std::endl; \ _exit(255); \ } \ if ( F ## U == NULL) { \ std::cerr << "Function pointer for \"" #F "\" cannot be NULL" << std::endl; \ _exit(255); \ } #endif UnderlyingCaller::UnderlyingCaller() { const char* errorMsg = 0; SET_FCN_PTR(clCreateBuffer) SET_FCN_PTR(clCreateSubBuffer) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" // In OpenCL 1.2 these are deprecated. Don't warn about this. SET_FCN_PTR(clCreateImage2D) SET_FCN_PTR(clCreateImage3D) #pragma GCC diagnostic pop SET_FCN_PTR(clCreateSampler) SET_FCN_PTR(clCreateProgramWithSource) SET_FCN_PTR(clBuildProgram) SET_FCN_PTR(clCreateKernel) SET_FCN_PTR(clSetKernelArg) SET_FCN_PTR(clEnqueueNDRangeKernel) }; <|endoftext|>
<commit_before>// Copyright (c) 2021 ASMlover. All rights reserved. // // _____ _ _ // |_ _|_ _ __| |_ __ ___ | | ___ // | |/ _` |/ _` | '_ \ / _ \| |/ _ \ // | | (_| | (_| | |_) | (_) | | __/ // |_|\__,_|\__,_| .__/ \___/|_|\___| // |_| // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "lexer.hh" namespace tadpole { Token Lexer::next_token() { skip_whitespace(); begpos_ = curpos_; if (is_tail()) return make_token(TokenKind::TK_EOF); char c = advance(); if (is_alpha(c)) return make_identifier(); if (is_digit(c)) return make_numeric(); // TODO: return make_error(from_fmt("unexpected character `%c`", c)); } void Lexer::skip_whitespace() { // TODO: } Token Lexer::make_token(TokenKind kind) { return Token(kind, gen_literal(begpos_, curpos_), lineno_); } Token Lexer::make_token(TokenKind kind, const str_t& literal) { return Token(kind, literal, lineno_); } Token Lexer::make_error(const str_t& message) { return Token(TokenKind::TK_ERR, message, lineno_); } Token Lexer::make_identifier() { while (is_alnum(peek())) advance(); str_t literal = gen_literal(begpos_, curpos_); return make_token(get_keyword_kind(literal), literal); } Token Lexer::make_numeric() { while (is_digit(peek())) advance(); if (peek() == '.' && is_digit(peek(1))) { advance(); while (is_digit(peek())) advance(); } return make_token(TokenKind::TK_NUMERIC); } Token Lexer::make_string() { #define _MAKE_CHAR(x, y) case x: c = y; advance(); break str_t literal; while (!is_tail() && peek() != '"') { char c = peek(); switch (c) { case '\n': ++lineno_; break; case '\\': switch (peek()) { _MAKE_CHAR('"', '"'); _MAKE_CHAR('\\', '\\'); _MAKE_CHAR('%', '%'); _MAKE_CHAR('0', '\0'); _MAKE_CHAR('a', '\a'); _MAKE_CHAR('b', '\b'); _MAKE_CHAR('f', '\f'); _MAKE_CHAR('n', '\n'); _MAKE_CHAR('r', '\r'); _MAKE_CHAR('t', '\t'); _MAKE_CHAR('v', '\v'); } break; } literal.push_back(c); advance(); } #undef _MAKE_CHAR if (is_tail()) return make_error("unterminated string"); advance(); return make_token(TokenKind::TK_STRING, literal); } } <commit_msg>:construction: chore(whitespace): implementation of skipping whitespace<commit_after>// Copyright (c) 2021 ASMlover. All rights reserved. // // _____ _ _ // |_ _|_ _ __| |_ __ ___ | | ___ // | |/ _` |/ _` | '_ \ / _ \| |/ _ \ // | | (_| | (_| | |_) | (_) | | __/ // |_|\__,_|\__,_| .__/ \___/|_|\___| // |_| // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "lexer.hh" namespace tadpole { Token Lexer::next_token() { skip_whitespace(); begpos_ = curpos_; if (is_tail()) return make_token(TokenKind::TK_EOF); char c = advance(); if (is_alpha(c)) return make_identifier(); if (is_digit(c)) return make_numeric(); // TODO: return make_error(from_fmt("unexpected character `%c`", c)); } void Lexer::skip_whitespace() { for (;;) { char c = peek(); switch (c) { case ' ': case '\r': case '\t': advance(); break; case '\n': ++lineno_; advance(); break; case '/': if (peek(1) == '/') { while (peek() != '\n') advance(); } else { return; } break; default: return; } } } Token Lexer::make_token(TokenKind kind) { return Token(kind, gen_literal(begpos_, curpos_), lineno_); } Token Lexer::make_token(TokenKind kind, const str_t& literal) { return Token(kind, literal, lineno_); } Token Lexer::make_error(const str_t& message) { return Token(TokenKind::TK_ERR, message, lineno_); } Token Lexer::make_identifier() { while (is_alnum(peek())) advance(); str_t literal = gen_literal(begpos_, curpos_); return make_token(get_keyword_kind(literal), literal); } Token Lexer::make_numeric() { while (is_digit(peek())) advance(); if (peek() == '.' && is_digit(peek(1))) { advance(); while (is_digit(peek())) advance(); } return make_token(TokenKind::TK_NUMERIC); } Token Lexer::make_string() { #define _MAKE_CHAR(x, y) case x: c = y; advance(); break str_t literal; while (!is_tail() && peek() != '"') { char c = peek(); switch (c) { case '\n': ++lineno_; break; case '\\': switch (peek()) { _MAKE_CHAR('"', '"'); _MAKE_CHAR('\\', '\\'); _MAKE_CHAR('%', '%'); _MAKE_CHAR('0', '\0'); _MAKE_CHAR('a', '\a'); _MAKE_CHAR('b', '\b'); _MAKE_CHAR('f', '\f'); _MAKE_CHAR('n', '\n'); _MAKE_CHAR('r', '\r'); _MAKE_CHAR('t', '\t'); _MAKE_CHAR('v', '\v'); } break; } literal.push_back(c); advance(); } #undef _MAKE_CHAR if (is_tail()) return make_error("unterminated string"); advance(); return make_token(TokenKind::TK_STRING, literal); } } <|endoftext|>
<commit_before>#include "catch.hpp" #include <SmurffCpp/Types.h> #include <Utils/Error.h> #include <SmurffCpp/Utils/MatrixUtils.h> #include <SmurffCpp/Utils/Distribution.h> namespace smurff { namespace mu = smurff::matrix_utils; TEST_CASE( "mvnormal/covar" ) { init_bmrng(1234); const int num_samples = 1000; Vector mean = mu::make_dense({1, 10} , { 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.}); Matrix covar = Matrix::Identity(10,10); auto randomMatrix = MvNormal(covar, mean, num_samples); // check mean REQUIRE(mu::equals_vector(randomMatrix.rowwise().sum(), num_samples * mean, num_samples/10)); // check variance Matrix centered = (randomMatrix.rowwise() - mean); Matrix squared = centered.array().square(); Vector var = squared.colwise().sum() / num_samples; REQUIRE(mu::equals_vector(var, covar.diagonal(), 0.1)); } TEST_CASE( "mvnormal/prec" ) { init_bmrng(1234); const int num_samples = 1000; Vector mean = mu::make_dense({1, 10} , { 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.}); Matrix covar = Matrix::Identity(10,10); auto randomMatrix = MvNormal_prec(covar, mean, num_samples); // check mean REQUIRE(mu::equals_vector(randomMatrix.rowwise().sum(), num_samples * mean, num_samples/10)); // check variance Matrix centered = (randomMatrix.rowwise() - mean); Matrix squared = centered.array().square(); Vector var = squared.colwise().sum() / num_samples; REQUIRE(mu::equals_vector(var, covar.diagonal(), 0.1)); } TEST_CASE( "CondNormalWishart" ) { init_bmrng(1234); Vector mean = matrix_utils::make_dense({1, 3} , { 1., 2., 3. }); Matrix T = Matrix::Identity(3,3); int kappa = 2; int nu = 4; Matrix U(mu::make_dense({4, 3}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.})); auto N = U.cols(); auto NS = U.transpose() * U; auto NU = U.colwise().sum(); REQUIRE(NS.rows() == NS.cols()); REQUIRE(NS.cols() == 3); REQUIRE(NU.cols() == 3); // should be the same auto p2 = CondNormalWishart(U, mean, kappa, T, nu); auto p1 = CondNormalWishart(N, NS, NU, mean, kappa, T, nu); } }<commit_msg>FIX: N = U.rows()<commit_after>#include "catch.hpp" #include <SmurffCpp/Types.h> #include <Utils/Error.h> #include <SmurffCpp/Utils/MatrixUtils.h> #include <SmurffCpp/Utils/Distribution.h> namespace smurff { namespace mu = smurff::matrix_utils; TEST_CASE( "mvnormal/covar" ) { init_bmrng(1234); const int num_samples = 1000; Vector mean = mu::make_dense({1, 10} , { 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.}); Matrix covar = Matrix::Identity(10,10); auto randomMatrix = MvNormal(covar, mean, num_samples); // check mean REQUIRE(mu::equals_vector(randomMatrix.rowwise().sum(), num_samples * mean, num_samples/10)); // check variance Matrix centered = (randomMatrix.rowwise() - mean); Matrix squared = centered.array().square(); Vector var = squared.colwise().sum() / num_samples; REQUIRE(mu::equals_vector(var, covar.diagonal(), 0.1)); } TEST_CASE( "mvnormal/prec" ) { init_bmrng(1234); const int num_samples = 1000; Vector mean = mu::make_dense({1, 10} , { 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.}); Matrix covar = Matrix::Identity(10,10); auto randomMatrix = MvNormal_prec(covar, mean, num_samples); // check mean REQUIRE(mu::equals_vector(randomMatrix.rowwise().sum(), num_samples * mean, num_samples/10)); // check variance Matrix centered = (randomMatrix.rowwise() - mean); Matrix squared = centered.array().square(); Vector var = squared.colwise().sum() / num_samples; REQUIRE(mu::equals_vector(var, covar.diagonal(), 0.1)); } TEST_CASE( "CondNormalWishart" ) { init_bmrng(1234); Vector mean = matrix_utils::make_dense({1, 3} , { 1., 2., 3. }); Matrix T = Matrix::Identity(3,3); int kappa = 2; int nu = 4; Matrix U(mu::make_dense({4, 3}, {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.})); auto N = U.rows(); auto NS = U.transpose() * U; auto NU = U.colwise().sum(); REQUIRE(NS.rows() == NS.cols()); REQUIRE(NS.cols() == 3); REQUIRE(NU.cols() == 3); // should be the same auto p2 = CondNormalWishart(U, mean, kappa, T, nu); auto p1 = CondNormalWishart(N, NS, NU, mean, kappa, T, nu); } }<|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef SQLITE_STRATEGIES_H #define SQLITE_STRATEGIES_H 1 #include <cstdlib> #include <vector> #include <algorithm> #include "common.hh" #include "queueditem.hh" #include "sqlite-pst.hh" class EventuallyPersistentEngine; typedef enum { select_all, delete_vbucket } vb_statement_type; /** * Base class for all Sqlite strategies. */ class SqliteStrategy { public: SqliteStrategy(const char * const fn, const char * const finit, const char * const pfinit, size_t shards); virtual ~SqliteStrategy(); sqlite3 *open(); void close(); size_t getNumOfDbShards() { return shardCount; } virtual uint16_t getDbShardId(const QueuedItem &qi) { return getDbShardIdForKey(qi.getKey()); } virtual const std::vector<Statements *> &allStatements() = 0; virtual Statements *getStatements(uint16_t vbid, uint16_t vbver, const std::string &key) = 0; PreparedStatement *getInsVBucketStateST() { return ins_vb_stmt; } PreparedStatement *getClearVBucketStateST() { return clear_vb_stmt; } PreparedStatement *getGetVBucketStateST() { return sel_vb_stmt; } PreparedStatement *getClearStatsST() { return clear_stats_stmt; } PreparedStatement *getInsStatST() { return ins_stat_stmt; } virtual bool hasEfficientVBLoad() { return false; } virtual bool hasEfficientVBDeletion() { return false; } virtual std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst) { (void)vb; (void)vbst; std::vector<PreparedStatement*> rv; return rv; } virtual void closeVBStatements(std::vector<PreparedStatement*> &psts) { (void)psts; } virtual void destroyTables() = 0; virtual void optimizeWrites(std::vector<queued_item> &items) { (void)items; } void execute(const char * const query); static void disableSchemaCheck() { shouldCheckSchemaVersion = false; } protected: void doFile(const char * const filename); uint16_t getDbShardIdForKey(const std::string &key) { assert(shardCount > 0); int h=5381; int i=0; const char *str = key.c_str(); for(i=0; str[i] != 0x00; i++) { h = ((h << 5) + h) ^ str[i]; } return std::abs(h) % (int)shardCount; } virtual void initDB() { doFile(initFile); } void checkSchemaVersion(); void initMetaTables(); virtual void initTables() = 0; virtual void initStatements() = 0; virtual void initMetaStatements(); virtual void destroyStatements() {}; void destroyMetaStatements(); static bool shouldCheckSchemaVersion; sqlite3 *db; const char * const filename; const char * const initFile; const char * const postInitFile; size_t shardCount; PreparedStatement *ins_vb_stmt; PreparedStatement *clear_vb_stmt; PreparedStatement *sel_vb_stmt; PreparedStatement *clear_stats_stmt; PreparedStatement *ins_stat_stmt; uint16_t schema_version; private: DISALLOW_COPY_AND_ASSIGN(SqliteStrategy); }; // // ---------------------------------------------------------------------- // Concrete Strategies // ---------------------------------------------------------------------- // /** * Strategy for a single table kv store in a single DB. */ class SingleTableSqliteStrategy : public SqliteStrategy { public: /** * Constructor. * * @param fn the filename of the DB * @param finit an init script to run as soon as the DB opens * @param pfinit an init script to run after initializing all schema * @param shards the number of shards */ SingleTableSqliteStrategy(const char * const fn, const char * const finit, const char * const pfinit, size_t shards = 1) : SqliteStrategy(fn, finit, pfinit, shards), statements() { assert(filename); } virtual ~SingleTableSqliteStrategy() { } const std::vector<Statements *> &allStatements() { return statements; } Statements *getStatements(uint16_t vbid, uint16_t vbver, const std::string &key) { (void)vbid; (void)vbver; return statements.at(getDbShardIdForKey(key)); } void destroyStatements(); virtual void destroyTables(); void optimizeWrites(std::vector<queued_item> &items) { // Sort all the queued items for each db shard by their row ids CompareQueuedItemsByRowId cq; std::sort(items.begin(), items.end(), cq); } protected: std::vector<Statements *> statements; virtual void initTables(); virtual void initStatements(); private: DISALLOW_COPY_AND_ASSIGN(SingleTableSqliteStrategy); }; // // ---------------------------------------------------------------------- // Multi DB strategy // ---------------------------------------------------------------------- // /** * A specialization of SqliteStrategy that allows multiple data * shards with a single kv table each. */ class MultiDBSingleTableSqliteStrategy : public SingleTableSqliteStrategy { public: /** * Constructor. * * @param fn same as SqliteStrategy * @param sp the shard pattern * @param finit same as SqliteStrategy * @param pfinit same as SqliteStrategy * @param n number of DB shards to create */ MultiDBSingleTableSqliteStrategy(const char * const fn, const char * const sp, const char * const finit, const char * const pfinit, int n): SingleTableSqliteStrategy(fn, finit, pfinit, n), shardpattern(sp), numTables(n) { assert(shardpattern); } void initDB(void); void initTables(void); void initStatements(void); void destroyTables(void); private: const char * const shardpattern; int numTables; }; // // ---------------------------------------------------------------------- // Table Per Vbucket // ---------------------------------------------------------------------- // /** * Strategy for a table per vbucket store in a single DB. */ class MultiTableSqliteStrategy : public SqliteStrategy { public: /** * Constructor. * * @param fn the filename of the DB * @param finit an init script to run as soon as the DB opens * @param pfinit an init script to run after initializing all schema * @param nv the maxinum number of vbuckets * @param shards the number of data shards */ MultiTableSqliteStrategy(const char * const fn, const char * const finit, const char * const pfinit, int nv, int shards=1) : SqliteStrategy(fn, finit, pfinit, shards), nvbuckets(nv), statements() { assert(filename); } virtual ~MultiTableSqliteStrategy() { } const std::vector<Statements *> &allStatements() { return statements; } virtual Statements *getStatements(uint16_t vbid, uint16_t vbver, const std::string &key) { (void)vbver; (void)key; assert(static_cast<size_t>(vbid) < statements.size()); return statements.at(vbid); } virtual void destroyStatements(); virtual void destroyTables(); bool hasEfficientVBLoad() { return true; } bool hasEfficientVBDeletion() { return true; } virtual std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst) { std::vector<PreparedStatement*> rv; assert(static_cast<size_t>(vb) < statements.size()); switch (vbst) { case select_all: rv.push_back(statements.at(vb)->all()); break; case delete_vbucket: rv.push_back(statements.at(vb)->del_vb()); break; default: break; } return rv; } void closeVBStatements(std::vector<PreparedStatement*> &psts) { std::for_each(psts.begin(), psts.end(), std::mem_fun(&PreparedStatement::reset)); } void optimizeWrites(std::vector<queued_item> &items) { // Sort all the queued items for each db shard by its vbucket // ID and then its row ids CompareQueuedItemsByVBAndRowId cq; std::sort(items.begin(), items.end(), cq); } protected: size_t nvbuckets; std::vector<Statements *> statements; virtual void initTables(); virtual void initStatements(); private: DISALLOW_COPY_AND_ASSIGN(MultiTableSqliteStrategy); }; // // ---------------------------------------------------------------------- // Multiple Shards, Table Per Vbucket // ---------------------------------------------------------------------- // /** * Strategy for a table per vbucket store in multiple shards. */ class ShardedMultiTableSqliteStrategy : public MultiTableSqliteStrategy { public: /** * Constructor. * * @param fn the filename of the DB * @param sp the shard pattern * @param finit an init script to run as soon as the DB opens * @param pfinit an init script to run after initializing all schema * @param nv the maxinum number of vbuckets * @param n the number of data shards */ ShardedMultiTableSqliteStrategy(const char * const fn, const char * const sp, const char * const finit, const char * const pfinit, int nv, int n) : MultiTableSqliteStrategy(fn, finit, pfinit, nv, n), shardpattern(sp), statementsPerShard() { assert(filename); } virtual ~ShardedMultiTableSqliteStrategy() { } Statements *getStatements(uint16_t vbid, uint16_t vbver, const std::string &key); void destroyStatements(); void destroyTables(); std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst); protected: const char * const shardpattern; // statementsPerShard[vbucket][shard] std::vector<std::vector<Statements*> > statementsPerShard; void initDB(); void initTables(); void initStatements(); private: DISALLOW_COPY_AND_ASSIGN(ShardedMultiTableSqliteStrategy); }; // // ---------------------------------------------------------------------- // Sharded by VBucket // ---------------------------------------------------------------------- // /** * Strategy for a table per vbucket where each vbucket exists in only * one shard. */ class ShardedByVBucketSqliteStrategy : public MultiTableSqliteStrategy { public: /** * Constructor. * * @param fn the filename of the DB * @param sp the shard pattern for generating shard files * @param finit an init script to run as soon as the DB opens * @param pfinit an init script to run after initializing all schema * @param nv the maxinum number of vbuckets * @param n the number of data shards */ ShardedByVBucketSqliteStrategy(const char * const fn, const char * const sp, const char * const finit, const char * const pfinit, int nv, int n) : MultiTableSqliteStrategy(fn, finit, pfinit, nv, n), shardpattern(sp) { assert(filename); } uint16_t getDbShardId(const QueuedItem &qi) { return getShardForVBucket(qi.getVBucketId()); } virtual ~ShardedByVBucketSqliteStrategy() { } void destroyTables(); protected: const char * const shardpattern; size_t getShardForVBucket(uint16_t vb) { size_t rv = (static_cast<size_t>(vb) % shardCount); assert(rv < shardCount); return rv; } void initDB(); void initTables(); void initStatements(); private: DISALLOW_COPY_AND_ASSIGN(ShardedByVBucketSqliteStrategy); }; #endif /* SQLITE_STRATEGIES_H */ <commit_msg>MB-3753 Provide specific SQL stmts even for single table strategy<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef SQLITE_STRATEGIES_H #define SQLITE_STRATEGIES_H 1 #include <cstdlib> #include <vector> #include <algorithm> #include "common.hh" #include "queueditem.hh" #include "sqlite-pst.hh" class EventuallyPersistentEngine; typedef enum { select_all, delete_vbucket } vb_statement_type; /** * Base class for all Sqlite strategies. */ class SqliteStrategy { public: SqliteStrategy(const char * const fn, const char * const finit, const char * const pfinit, size_t shards); virtual ~SqliteStrategy(); sqlite3 *open(); void close(); size_t getNumOfDbShards() { return shardCount; } virtual uint16_t getDbShardId(const QueuedItem &qi) { return getDbShardIdForKey(qi.getKey()); } virtual const std::vector<Statements *> &allStatements() = 0; virtual Statements *getStatements(uint16_t vbid, uint16_t vbver, const std::string &key) = 0; PreparedStatement *getInsVBucketStateST() { return ins_vb_stmt; } PreparedStatement *getClearVBucketStateST() { return clear_vb_stmt; } PreparedStatement *getGetVBucketStateST() { return sel_vb_stmt; } PreparedStatement *getClearStatsST() { return clear_stats_stmt; } PreparedStatement *getInsStatST() { return ins_stat_stmt; } virtual bool hasEfficientVBLoad() { return false; } virtual bool hasEfficientVBDeletion() { return false; } virtual std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst) { (void)vb; (void)vbst; std::vector<PreparedStatement*> rv; return rv; } virtual void closeVBStatements(std::vector<PreparedStatement*> &psts) { (void)psts; } virtual void destroyTables() = 0; virtual void optimizeWrites(std::vector<queued_item> &items) { (void)items; } void execute(const char * const query); static void disableSchemaCheck() { shouldCheckSchemaVersion = false; } protected: void doFile(const char * const filename); uint16_t getDbShardIdForKey(const std::string &key) { assert(shardCount > 0); int h=5381; int i=0; const char *str = key.c_str(); for(i=0; str[i] != 0x00; i++) { h = ((h << 5) + h) ^ str[i]; } return std::abs(h) % (int)shardCount; } virtual void initDB() { doFile(initFile); } void checkSchemaVersion(); void initMetaTables(); virtual void initTables() = 0; virtual void initStatements() = 0; virtual void initMetaStatements(); virtual void destroyStatements() {}; void destroyMetaStatements(); static bool shouldCheckSchemaVersion; sqlite3 *db; const char * const filename; const char * const initFile; const char * const postInitFile; size_t shardCount; PreparedStatement *ins_vb_stmt; PreparedStatement *clear_vb_stmt; PreparedStatement *sel_vb_stmt; PreparedStatement *clear_stats_stmt; PreparedStatement *ins_stat_stmt; uint16_t schema_version; private: DISALLOW_COPY_AND_ASSIGN(SqliteStrategy); }; // // ---------------------------------------------------------------------- // Concrete Strategies // ---------------------------------------------------------------------- // /** * Strategy for a single table kv store in a single DB. */ class SingleTableSqliteStrategy : public SqliteStrategy { public: /** * Constructor. * * @param fn the filename of the DB * @param finit an init script to run as soon as the DB opens * @param pfinit an init script to run after initializing all schema * @param shards the number of shards */ SingleTableSqliteStrategy(const char * const fn, const char * const finit, const char * const pfinit, size_t shards = 1) : SqliteStrategy(fn, finit, pfinit, shards), statements() { assert(filename); } virtual ~SingleTableSqliteStrategy() { } const std::vector<Statements *> &allStatements() { return statements; } Statements *getStatements(uint16_t vbid, uint16_t vbver, const std::string &key) { (void)vbid; (void)vbver; return statements.at(getDbShardIdForKey(key)); } void destroyStatements(); virtual void destroyTables(); void optimizeWrites(std::vector<queued_item> &items) { // Sort all the queued items for each db shard by their row ids CompareQueuedItemsByRowId cq; std::sort(items.begin(), items.end(), cq); } virtual std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst) { (void)vb; std::vector<PreparedStatement*> rv; std::vector<Statements*>::iterator it; for (it = statements.begin(); it != statements.end(); ++it) { switch (vbst) { case select_all: rv.push_back((*it)->all()); break; case delete_vbucket: rv.push_back((*it)->del_vb()); break; default: break; } } return rv; } virtual void closeVBStatements(std::vector<PreparedStatement*> &psts) { std::for_each(psts.begin(), psts.end(), std::mem_fun(&PreparedStatement::reset)); } protected: std::vector<Statements *> statements; virtual void initTables(); virtual void initStatements(); private: DISALLOW_COPY_AND_ASSIGN(SingleTableSqliteStrategy); }; // // ---------------------------------------------------------------------- // Multi DB strategy // ---------------------------------------------------------------------- // /** * A specialization of SqliteStrategy that allows multiple data * shards with a single kv table each. */ class MultiDBSingleTableSqliteStrategy : public SingleTableSqliteStrategy { public: /** * Constructor. * * @param fn same as SqliteStrategy * @param sp the shard pattern * @param finit same as SqliteStrategy * @param pfinit same as SqliteStrategy * @param n number of DB shards to create */ MultiDBSingleTableSqliteStrategy(const char * const fn, const char * const sp, const char * const finit, const char * const pfinit, int n): SingleTableSqliteStrategy(fn, finit, pfinit, n), shardpattern(sp), numTables(n) { assert(shardpattern); } void initDB(void); void initTables(void); void initStatements(void); void destroyTables(void); private: const char * const shardpattern; int numTables; }; // // ---------------------------------------------------------------------- // Table Per Vbucket // ---------------------------------------------------------------------- // /** * Strategy for a table per vbucket store in a single DB. */ class MultiTableSqliteStrategy : public SqliteStrategy { public: /** * Constructor. * * @param fn the filename of the DB * @param finit an init script to run as soon as the DB opens * @param pfinit an init script to run after initializing all schema * @param nv the maxinum number of vbuckets * @param shards the number of data shards */ MultiTableSqliteStrategy(const char * const fn, const char * const finit, const char * const pfinit, int nv, int shards=1) : SqliteStrategy(fn, finit, pfinit, shards), nvbuckets(nv), statements() { assert(filename); } virtual ~MultiTableSqliteStrategy() { } const std::vector<Statements *> &allStatements() { return statements; } virtual Statements *getStatements(uint16_t vbid, uint16_t vbver, const std::string &key) { (void)vbver; (void)key; assert(static_cast<size_t>(vbid) < statements.size()); return statements.at(vbid); } virtual void destroyStatements(); virtual void destroyTables(); bool hasEfficientVBLoad() { return true; } bool hasEfficientVBDeletion() { return true; } virtual std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst) { std::vector<PreparedStatement*> rv; assert(static_cast<size_t>(vb) < statements.size()); switch (vbst) { case select_all: rv.push_back(statements.at(vb)->all()); break; case delete_vbucket: rv.push_back(statements.at(vb)->del_vb()); break; default: break; } return rv; } void closeVBStatements(std::vector<PreparedStatement*> &psts) { std::for_each(psts.begin(), psts.end(), std::mem_fun(&PreparedStatement::reset)); } void optimizeWrites(std::vector<queued_item> &items) { // Sort all the queued items for each db shard by its vbucket // ID and then its row ids CompareQueuedItemsByVBAndRowId cq; std::sort(items.begin(), items.end(), cq); } protected: size_t nvbuckets; std::vector<Statements *> statements; virtual void initTables(); virtual void initStatements(); private: DISALLOW_COPY_AND_ASSIGN(MultiTableSqliteStrategy); }; // // ---------------------------------------------------------------------- // Multiple Shards, Table Per Vbucket // ---------------------------------------------------------------------- // /** * Strategy for a table per vbucket store in multiple shards. */ class ShardedMultiTableSqliteStrategy : public MultiTableSqliteStrategy { public: /** * Constructor. * * @param fn the filename of the DB * @param sp the shard pattern * @param finit an init script to run as soon as the DB opens * @param pfinit an init script to run after initializing all schema * @param nv the maxinum number of vbuckets * @param n the number of data shards */ ShardedMultiTableSqliteStrategy(const char * const fn, const char * const sp, const char * const finit, const char * const pfinit, int nv, int n) : MultiTableSqliteStrategy(fn, finit, pfinit, nv, n), shardpattern(sp), statementsPerShard() { assert(filename); } virtual ~ShardedMultiTableSqliteStrategy() { } Statements *getStatements(uint16_t vbid, uint16_t vbver, const std::string &key); void destroyStatements(); void destroyTables(); std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst); protected: const char * const shardpattern; // statementsPerShard[vbucket][shard] std::vector<std::vector<Statements*> > statementsPerShard; void initDB(); void initTables(); void initStatements(); private: DISALLOW_COPY_AND_ASSIGN(ShardedMultiTableSqliteStrategy); }; // // ---------------------------------------------------------------------- // Sharded by VBucket // ---------------------------------------------------------------------- // /** * Strategy for a table per vbucket where each vbucket exists in only * one shard. */ class ShardedByVBucketSqliteStrategy : public MultiTableSqliteStrategy { public: /** * Constructor. * * @param fn the filename of the DB * @param sp the shard pattern for generating shard files * @param finit an init script to run as soon as the DB opens * @param pfinit an init script to run after initializing all schema * @param nv the maxinum number of vbuckets * @param n the number of data shards */ ShardedByVBucketSqliteStrategy(const char * const fn, const char * const sp, const char * const finit, const char * const pfinit, int nv, int n) : MultiTableSqliteStrategy(fn, finit, pfinit, nv, n), shardpattern(sp) { assert(filename); } uint16_t getDbShardId(const QueuedItem &qi) { return getShardForVBucket(qi.getVBucketId()); } virtual ~ShardedByVBucketSqliteStrategy() { } void destroyTables(); protected: const char * const shardpattern; size_t getShardForVBucket(uint16_t vb) { size_t rv = (static_cast<size_t>(vb) % shardCount); assert(rv < shardCount); return rv; } void initDB(); void initTables(); void initStatements(); private: DISALLOW_COPY_AND_ASSIGN(ShardedByVBucketSqliteStrategy); }; #endif /* SQLITE_STRATEGIES_H */ <|endoftext|>
<commit_before>#include "core/argparse.h" #include <iostream> #include <string> #include <sstream> #include <functional> #include <vector> #include <map> #include <memory> #include "core/assert.h" #include "core/stringutils.h" #include "core/stringmerger.h" namespace argparse { ///////////////////////////////////////////////////////////////////////////////////////// // Name bool Name::IsOptional(const std::string& arg) { if(arg.empty()) { return false; } return arg[0] == '-'; } std::string Name::OptionalName(const std::string& name) { ASSERTX(IsOptional(name), name); ASSERTX(!name.empty(), name); return name.substr(1); } Name::Name() : is_optional(false) { } Name::Name(const char* str) : is_optional(IsOptional(str)) , names( Split(str, ',') ) { if(is_optional) { names[0] = OptionalName(names[0]); } for(auto& n: names) { n = Trim(n); } #ifdef _DEBUG AssertValid(); #endif} } Name Name::Parse(const std::string& n) { return { n.c_str() }; } Name Name::Optional(std::initializer_list<std::string> names) { return { true, names }; } Name Name::Positional(std::string& name) { return {false, {name}}; } Name::Name(bool o, const std::vector<std::string>& n) : is_optional(o) , names(n) { #ifdef _DEBUG AssertValid(); #endif } #ifdef _DEBUG void Name::AssertValid() { if(is_optional) { for(unsigned int i=0; i<names.size(); i+=1) { ASSERTX(IsOptional(names[i])==false, i, names[i]); } } else { ASSERTX(names.size()==1, names.size()); } // todo: assert that name only contains valid characters... } #endif ///////////////////////////////////////////////////////////////////////////////////////// // ConsoleOutput void ConsoleOutput::OnError(const std::string& err) { std::cerr << err << "\n"; } void ConsoleOutput::OnInfo(const std::string& info) { std::cout << info << "\n"; } ///////////////////////////////////////////////////////////////////////////////////////// // Running bool Running::HasMore() const { return next_index < arguments.size(); } std::string Running::Read() { if(next_index < arguments.size()) { const auto ret = arguments[next_index]; next_index += 1; return ret; } else { return ""; } } std::string Running::Peek(size_t advance) const { ASSERTX(advance > 0, advance); const auto suggested_index = next_index + advance - 1; if(suggested_index < arguments.size()) { return arguments[suggested_index]; } else { return ""; } } ///////////////////////////////////////////////////////////////////////////////////////// // Extra Extra& Extra::MetaVar(const std::string& m) { arg->meta_var = m; return *this; } Extra& Extra::Help(const std::string& h) { arg->help = h; return *this; } ///////////////////////////////////////////////////////////////////////////////////////// // SimpleParser template<> ParseResult SimpleParser<std::string>(std::string* target, const std::string&, const std::string& value, Output*) { *target = value; return ParseResult::Ok; } ///////////////////////////////////////////////////////////////////////////////////////// // Parser Parser::Parser(const std::string& n) : display_name(n) { // todo: add help command } Extra Parser::AddArgument(const Name& name, std::shared_ptr<Arg> arg) { arg->name = name; if(name.is_optional) { ASSERT(!name.names.empty()); for(auto n: name.names) { ASSERTX(optional_arguments.find(n)==optional_arguments.end(), n); optional_arguments[n] = arg; } } else { positional_arguments.push_back(arg); } return Extra { arg }; } ParseResult Parser::Parse(int argc, char* argv[]) const { auto args = std::vector<std::string>{}; for (int i = 1; i < argc; i += 1) { args.push_back(argv[i]); } return Parse(argv[0], args); } ParseResult Parser::Parse(const std::string& program_name, const std::vector<std::string>& args) const { auto console = ConsoleOutput {}; auto running = Running { program_name, args, output ? output : &console }; size_t next_positional_index = 0; while(running.HasMore()) { const auto is_optional = Name::IsOptional(running.Peek()); const auto has_more_positionals = next_positional_index < positional_arguments.size(); std::string arg_name; std::shared_ptr<Arg> arg = nullptr; if(has_more_positionals) { // if it is a valid optional, parse it, otherwise send to optional if(is_optional) { auto found = optional_arguments.find(Name::OptionalName(running.Peek())); if(found != optional_arguments.end()) { arg = found->second; } } if(arg == nullptr) { arg = positional_arguments[next_positional_index]; arg_name = arg->name.names[0]; next_positional_index += 1; } } else { // no more positionals, must be a optional const auto optional_name = running.Read(); if(!Name::IsOptional(optional_name)) { running.output->OnError(Str() << "Got " << optional_name << " but all positionals are consumed"); return ParseResult::Failed; } auto found = optional_arguments.find(Name::OptionalName(optional_name)); if(found == optional_arguments.end()) { running.output->OnError(Str() << "Not a valid argument: " << optional_name); return ParseResult::Failed; } arg_name = optional_name; arg = found->second; } auto r = arg->Parse(arg_name, &running); if( r != ParseResult::Ok) { return r; } } const auto has_more_positionals = next_positional_index < positional_arguments.size(); std::vector<std::string> missing_positionals; for(size_t i=next_positional_index; i<positional_arguments.size(); i+=1) { missing_positionals.push_back(positional_arguments[i]->name.names[0]); } if(!missing_positionals.empty()) { running.output->OnError( Str() << "Positionals not consumed: " << StringMerger::EnglishAnd().Generate(missing_positionals)); return ParseResult::Failed; } return ParseResult::Ok; } } <commit_msg>removed warnings<commit_after>#include "core/argparse.h" #include <iostream> #include <string> #include <sstream> #include <functional> #include <vector> #include <map> #include <memory> #include "core/assert.h" #include "core/stringutils.h" #include "core/stringmerger.h" namespace argparse { ///////////////////////////////////////////////////////////////////////////////////////// // Name bool Name::IsOptional(const std::string& arg) { if(arg.empty()) { return false; } return arg[0] == '-'; } std::string Name::OptionalName(const std::string& name) { ASSERTX(IsOptional(name), name); ASSERTX(!name.empty(), name); return name.substr(1); } Name::Name() : is_optional(false) { } Name::Name(const char* str) : is_optional(IsOptional(str)) , names( Split(str, ',') ) { if(is_optional) { names[0] = OptionalName(names[0]); } for(auto& n: names) { n = Trim(n); } #ifdef _DEBUG AssertValid(); #endif } Name Name::Parse(const std::string& n) { return { n.c_str() }; } Name Name::Optional(std::initializer_list<std::string> names) { return { true, names }; } Name Name::Positional(std::string& name) { return {false, {name}}; } Name::Name(bool o, const std::vector<std::string>& n) : is_optional(o) , names(n) { #ifdef _DEBUG AssertValid(); #endif } #ifdef _DEBUG void Name::AssertValid() { if(is_optional) { for(unsigned int i=0; i<names.size(); i+=1) { ASSERTX(IsOptional(names[i])==false, i, names[i]); } } else { ASSERTX(names.size()==1, names.size()); } // todo: assert that name only contains valid characters... } #endif ///////////////////////////////////////////////////////////////////////////////////////// // ConsoleOutput void ConsoleOutput::OnError(const std::string& err) { std::cerr << err << "\n"; } void ConsoleOutput::OnInfo(const std::string& info) { std::cout << info << "\n"; } ///////////////////////////////////////////////////////////////////////////////////////// // Running bool Running::HasMore() const { return next_index < arguments.size(); } std::string Running::Read() { if(next_index < arguments.size()) { const auto ret = arguments[next_index]; next_index += 1; return ret; } else { return ""; } } std::string Running::Peek(size_t advance) const { ASSERTX(advance > 0, advance); const auto suggested_index = next_index + advance - 1; if(suggested_index < arguments.size()) { return arguments[suggested_index]; } else { return ""; } } ///////////////////////////////////////////////////////////////////////////////////////// // Extra Extra& Extra::MetaVar(const std::string& m) { arg->meta_var = m; return *this; } Extra& Extra::Help(const std::string& h) { arg->help = h; return *this; } ///////////////////////////////////////////////////////////////////////////////////////// // SimpleParser template<> ParseResult SimpleParser<std::string>(std::string* target, const std::string&, const std::string& value, Output*) { *target = value; return ParseResult::Ok; } ///////////////////////////////////////////////////////////////////////////////////////// // Parser Parser::Parser(const std::string& n) : display_name(n) { // todo: add help command } Extra Parser::AddArgument(const Name& name, std::shared_ptr<Arg> arg) { arg->name = name; if(name.is_optional) { ASSERT(!name.names.empty()); for(auto n: name.names) { ASSERTX(optional_arguments.find(n)==optional_arguments.end(), n); optional_arguments[n] = arg; } } else { positional_arguments.push_back(arg); } return Extra { arg }; } ParseResult Parser::Parse(int argc, char* argv[]) const { auto args = std::vector<std::string>{}; for (int i = 1; i < argc; i += 1) { args.push_back(argv[i]); } return Parse(argv[0], args); } ParseResult Parser::Parse(const std::string& program_name, const std::vector<std::string>& args) const { auto console = ConsoleOutput {}; auto running = Running { program_name, args, output ? output : &console }; size_t next_positional_index = 0; while(running.HasMore()) { const auto is_optional = Name::IsOptional(running.Peek()); const auto has_more_positionals = next_positional_index < positional_arguments.size(); std::string arg_name; std::shared_ptr<Arg> arg = nullptr; if(has_more_positionals) { // if it is a valid optional, parse it, otherwise send to optional if(is_optional) { auto found = optional_arguments.find(Name::OptionalName(running.Peek())); if(found != optional_arguments.end()) { arg = found->second; } } if(arg == nullptr) { arg = positional_arguments[next_positional_index]; arg_name = arg->name.names[0]; next_positional_index += 1; } } else { // no more positionals, must be a optional const auto optional_name = running.Read(); if(!Name::IsOptional(optional_name)) { running.output->OnError(Str() << "Got " << optional_name << " but all positionals are consumed"); return ParseResult::Failed; } auto found = optional_arguments.find(Name::OptionalName(optional_name)); if(found == optional_arguments.end()) { running.output->OnError(Str() << "Not a valid argument: " << optional_name); return ParseResult::Failed; } arg_name = optional_name; arg = found->second; } auto r = arg->Parse(arg_name, &running); if( r != ParseResult::Ok) { return r; } } std::vector<std::string> missing_positionals; for(size_t i=next_positional_index; i<positional_arguments.size(); i+=1) { missing_positionals.push_back(positional_arguments[i]->name.names[0]); } if(!missing_positionals.empty()) { running.output->OnError( Str() << "Positionals not consumed: " << StringMerger::EnglishAnd().Generate(missing_positionals)); return ParseResult::Failed; } return ParseResult::Ok; } } <|endoftext|>
<commit_before>#include "InputManager.h" #include "InputConfig.h" #include "Settings.h" #include "Window.h" #include "Log.h" #include "pugixml/pugixml.hpp" #include <boost/filesystem.hpp> #include "platform.h" #define KEYBOARD_GUID_STRING "-1" // SO HEY POTENTIAL POOR SAP WHO IS TRYING TO MAKE SENSE OF ALL THIS (by which I mean my future self) // There are like four distinct IDs used for joysticks (crazy, right?) // 1. Device index - this is the "lowest level" identifier, and is just the Nth joystick plugged in to the system (like /dev/js#). // It can change even if the device is the same, and is only used to open joysticks (required to receive SDL events). // 2. SDL_JoystickID - this is an ID for each joystick that is supposed to remain consistent between plugging and unplugging. // ES doesn't care if it does, though. // 3. "Device ID" - this is something I made up and is what InputConfig's getDeviceID() returns. // This is actually just an SDL_JoystickID (also called instance ID), but -1 means "keyboard" instead of "error." // 4. Joystick GUID - this is some squashed version of joystick vendor, version, and a bunch of other device-specific things. // It should remain the same across runs of the program/system restarts/device reordering and is what I use to identify which joystick to load. namespace fs = boost::filesystem; InputManager* InputManager::mInstance = NULL; InputManager::InputManager() : mKeyboardInputConfig(NULL) { } InputManager::~InputManager() { deinit(); } InputManager* InputManager::getInstance() { if(!mInstance) mInstance = new InputManager(); return mInstance; } void InputManager::init() { if(initialized()) deinit(); if (Settings::getInstance()->getBool("BackgroundJoystickInput")){ SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1"); } SDL_InitSubSystem(SDL_INIT_JOYSTICK); SDL_JoystickEventState(SDL_ENABLE); // first, open all currently present joysticks int numJoysticks = SDL_NumJoysticks(); for(int i = 0; i < numJoysticks; i++) { addJoystickByDeviceIndex(i); } mKeyboardInputConfig = new InputConfig(DEVICE_KEYBOARD, "Keyboard", KEYBOARD_GUID_STRING); loadInputConfig(mKeyboardInputConfig); } void InputManager::addJoystickByDeviceIndex(int id) { assert(id >= 0 && id < SDL_NumJoysticks()); // open joystick & add to our list SDL_Joystick* joy = SDL_JoystickOpen(id); assert(joy); // add it to our list so we can close it again later SDL_JoystickID joyId = SDL_JoystickInstanceID(joy); mJoysticks[joyId] = joy; char guid[65]; SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joy), guid, 65); // create the InputConfig mInputConfigs[joyId] = new InputConfig(joyId, SDL_JoystickName(joy), guid); if(!loadInputConfig(mInputConfigs[joyId])) { LOG(LogInfo) << "Added unconfigured joystick " << SDL_JoystickName(joy) << " (GUID: " << guid << ", instance ID: " << joyId << ", device index: " << id << ")."; }else{ LOG(LogInfo) << "Added known joystick " << SDL_JoystickName(joy) << " (instance ID: " << joyId << ", device index: " << id << ")"; } // set up the prevAxisValues int numAxes = SDL_JoystickNumAxes(joy); mPrevAxisValues[joyId] = new int[numAxes]; std::fill(mPrevAxisValues[joyId], mPrevAxisValues[joyId] + numAxes, 0); //initialize array to 0 } void InputManager::removeJoystickByJoystickID(SDL_JoystickID joyId) { assert(joyId != -1); // delete old prevAxisValues auto axisIt = mPrevAxisValues.find(joyId); delete[] axisIt->second; mPrevAxisValues.erase(axisIt); // delete old InputConfig auto it = mInputConfigs.find(joyId); delete it->second; mInputConfigs.erase(it); // close the joystick auto joyIt = mJoysticks.find(joyId); if(joyIt != mJoysticks.end()) { SDL_JoystickClose(joyIt->second); mJoysticks.erase(joyIt); }else{ LOG(LogError) << "Could not find joystick to close (instance ID: " << joyId << ")"; } } void InputManager::deinit() { if(!initialized()) return; for(auto iter = mJoysticks.begin(); iter != mJoysticks.end(); iter++) { SDL_JoystickClose(iter->second); } mJoysticks.clear(); for(auto iter = mInputConfigs.begin(); iter != mInputConfigs.end(); iter++) { delete iter->second; } mInputConfigs.clear(); for(auto iter = mPrevAxisValues.begin(); iter != mPrevAxisValues.end(); iter++) { delete[] iter->second; } mPrevAxisValues.clear(); if(mKeyboardInputConfig != NULL) { delete mKeyboardInputConfig; mKeyboardInputConfig = NULL; } SDL_JoystickEventState(SDL_DISABLE); SDL_QuitSubSystem(SDL_INIT_JOYSTICK); } int InputManager::getNumJoysticks() { return mJoysticks.size(); } int InputManager::getButtonCountByDevice(SDL_JoystickID id) { if(id == DEVICE_KEYBOARD) return 120; //it's a lot, okay. else return SDL_JoystickNumButtons(mJoysticks[id]); } InputConfig* InputManager::getInputConfigByDevice(int device) { if(device == DEVICE_KEYBOARD) return mKeyboardInputConfig; else return mInputConfigs[device]; } bool InputManager::parseEvent(const SDL_Event& ev, Window* window) { bool causedEvent = false; switch(ev.type) { case SDL_JOYAXISMOTION: //if it switched boundaries if((abs(ev.jaxis.value) > DEADZONE) != (abs(mPrevAxisValues[ev.jaxis.which][ev.jaxis.axis]) > DEADZONE)) { int normValue; if(abs(ev.jaxis.value) <= DEADZONE) normValue = 0; else if(ev.jaxis.value > 0) normValue = 1; else normValue = -1; window->input(getInputConfigByDevice(ev.jaxis.which), Input(ev.jaxis.which, TYPE_AXIS, ev.jaxis.axis, normValue, false)); causedEvent = true; } mPrevAxisValues[ev.jaxis.which][ev.jaxis.axis] = ev.jaxis.value; return causedEvent; case SDL_JOYBUTTONDOWN: case SDL_JOYBUTTONUP: window->input(getInputConfigByDevice(ev.jbutton.which), Input(ev.jbutton.which, TYPE_BUTTON, ev.jbutton.button, ev.jbutton.state == SDL_PRESSED, false)); return true; case SDL_JOYHATMOTION: window->input(getInputConfigByDevice(ev.jhat.which), Input(ev.jhat.which, TYPE_HAT, ev.jhat.hat, ev.jhat.value, false)); return true; case SDL_KEYDOWN: if(ev.key.keysym.sym == SDLK_BACKSPACE && SDL_IsTextInputActive()) { window->textInput("\b"); } if(ev.key.repeat) return false; if(ev.key.keysym.sym == SDLK_F4) { SDL_Event* quit = new SDL_Event(); quit->type = SDL_QUIT; SDL_PushEvent(quit); return false; } window->input(getInputConfigByDevice(DEVICE_KEYBOARD), Input(DEVICE_KEYBOARD, TYPE_KEY, ev.key.keysym.sym, 1, false)); return true; case SDL_KEYUP: window->input(getInputConfigByDevice(DEVICE_KEYBOARD), Input(DEVICE_KEYBOARD, TYPE_KEY, ev.key.keysym.sym, 0, false)); return true; case SDL_TEXTINPUT: window->textInput(ev.text.text); break; case SDL_JOYDEVICEADDED: addJoystickByDeviceIndex(ev.jdevice.which); // ev.jdevice.which is a device index return true; case SDL_JOYDEVICEREMOVED: removeJoystickByJoystickID(ev.jdevice.which); // ev.jdevice.which is an SDL_JoystickID (instance ID) return false; } return false; } bool InputManager::loadInputConfig(InputConfig* config) { std::string path = getConfigPath(); if(!fs::exists(path)) return false; pugi::xml_document doc; pugi::xml_parse_result res = doc.load_file(path.c_str()); if(!res) { LOG(LogError) << "Error parsing input config: " << res.description(); return false; } pugi::xml_node root = doc.child("inputList"); if(!root) return false; pugi::xml_node configNode = root.find_child_by_attribute("inputConfig", "deviceGUID", config->getDeviceGUIDString().c_str()); if(!configNode) configNode = root.find_child_by_attribute("inputConfig", "deviceName", config->getDeviceName().c_str()); if(!configNode) return false; config->loadFromXML(configNode); return true; } //used in an "emergency" where no keyboard config could be loaded from the inputmanager config file //allows the user to select to reconfigure in menus if this happens without having to delete es_input.cfg manually void InputManager::loadDefaultKBConfig() { InputConfig* cfg = getInputConfigByDevice(DEVICE_KEYBOARD); cfg->clear(); cfg->mapInput("up", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_UP, 1, true)); cfg->mapInput("down", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_DOWN, 1, true)); cfg->mapInput("left", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_LEFT, 1, true)); cfg->mapInput("right", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_RIGHT, 1, true)); cfg->mapInput("a", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_RETURN, 1, true)); cfg->mapInput("b", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_ESCAPE, 1, true)); cfg->mapInput("start", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_F1, 1, true)); cfg->mapInput("select", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_F2, 1, true)); cfg->mapInput("pageup", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_RIGHTBRACKET, 1, true)); cfg->mapInput("pagedown", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_LEFTBRACKET, 1, true)); } void InputManager::writeDeviceConfig(InputConfig* config) { assert(initialized()); std::string path = getConfigPath(); pugi::xml_document doc; if(fs::exists(path)) { // merge files pugi::xml_parse_result result = doc.load_file(path.c_str()); if(!result) { LOG(LogError) << "Error parsing input config: " << result.description(); }else{ // successfully loaded, delete the old entry if it exists pugi::xml_node root = doc.child("inputList"); if(root) { pugi::xml_node oldEntry = root.find_child_by_attribute("inputConfig", "deviceGUID", config->getDeviceGUIDString().c_str()); if(oldEntry) root.remove_child(oldEntry); oldEntry = root.find_child_by_attribute("inputConfig", "deviceName", config->getDeviceName().c_str()); if(oldEntry) root.remove_child(oldEntry); } } } pugi::xml_node root = doc.child("inputList"); if(!root) root = doc.append_child("inputList"); config->writeToXML(root); doc.save_file(path.c_str()); } std::string InputManager::getConfigPath() { std::string path = getHomePath(); path += "/.emulationstation/es_input.cfg"; return path; } bool InputManager::initialized() const { return mKeyboardInputConfig != NULL; } int InputManager::getNumConfiguredDevices() { int num = 0; for(auto it = mInputConfigs.begin(); it != mInputConfigs.end(); it++) { if(it->second->isConfigured()) num++; } if(mKeyboardInputConfig->isConfigured()) num++; return num; } std::string InputManager::getDeviceGUIDString(int deviceId) { if(deviceId == DEVICE_KEYBOARD) return KEYBOARD_GUID_STRING; auto it = mJoysticks.find(deviceId); if(it == mJoysticks.end()) { LOG(LogError) << "getDeviceGUIDString - deviceId " << deviceId << " not found!"; return "something went horribly wrong"; } char guid[65]; SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(it->second), guid, 65); return std::string(guid); } <commit_msg>Set hint regardless of setting (in case it is changed during run-time).<commit_after>#include "InputManager.h" #include "InputConfig.h" #include "Settings.h" #include "Window.h" #include "Log.h" #include "pugixml/pugixml.hpp" #include <boost/filesystem.hpp> #include "platform.h" #define KEYBOARD_GUID_STRING "-1" // SO HEY POTENTIAL POOR SAP WHO IS TRYING TO MAKE SENSE OF ALL THIS (by which I mean my future self) // There are like four distinct IDs used for joysticks (crazy, right?) // 1. Device index - this is the "lowest level" identifier, and is just the Nth joystick plugged in to the system (like /dev/js#). // It can change even if the device is the same, and is only used to open joysticks (required to receive SDL events). // 2. SDL_JoystickID - this is an ID for each joystick that is supposed to remain consistent between plugging and unplugging. // ES doesn't care if it does, though. // 3. "Device ID" - this is something I made up and is what InputConfig's getDeviceID() returns. // This is actually just an SDL_JoystickID (also called instance ID), but -1 means "keyboard" instead of "error." // 4. Joystick GUID - this is some squashed version of joystick vendor, version, and a bunch of other device-specific things. // It should remain the same across runs of the program/system restarts/device reordering and is what I use to identify which joystick to load. namespace fs = boost::filesystem; InputManager* InputManager::mInstance = NULL; InputManager::InputManager() : mKeyboardInputConfig(NULL) { } InputManager::~InputManager() { deinit(); } InputManager* InputManager::getInstance() { if(!mInstance) mInstance = new InputManager(); return mInstance; } void InputManager::init() { if(initialized()) deinit(); SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, Settings::getInstance()->getBool("BackgroundJoystickInput") ? "1" : "0"); SDL_InitSubSystem(SDL_INIT_JOYSTICK); SDL_JoystickEventState(SDL_ENABLE); // first, open all currently present joysticks int numJoysticks = SDL_NumJoysticks(); for(int i = 0; i < numJoysticks; i++) { addJoystickByDeviceIndex(i); } mKeyboardInputConfig = new InputConfig(DEVICE_KEYBOARD, "Keyboard", KEYBOARD_GUID_STRING); loadInputConfig(mKeyboardInputConfig); } void InputManager::addJoystickByDeviceIndex(int id) { assert(id >= 0 && id < SDL_NumJoysticks()); // open joystick & add to our list SDL_Joystick* joy = SDL_JoystickOpen(id); assert(joy); // add it to our list so we can close it again later SDL_JoystickID joyId = SDL_JoystickInstanceID(joy); mJoysticks[joyId] = joy; char guid[65]; SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joy), guid, 65); // create the InputConfig mInputConfigs[joyId] = new InputConfig(joyId, SDL_JoystickName(joy), guid); if(!loadInputConfig(mInputConfigs[joyId])) { LOG(LogInfo) << "Added unconfigured joystick " << SDL_JoystickName(joy) << " (GUID: " << guid << ", instance ID: " << joyId << ", device index: " << id << ")."; }else{ LOG(LogInfo) << "Added known joystick " << SDL_JoystickName(joy) << " (instance ID: " << joyId << ", device index: " << id << ")"; } // set up the prevAxisValues int numAxes = SDL_JoystickNumAxes(joy); mPrevAxisValues[joyId] = new int[numAxes]; std::fill(mPrevAxisValues[joyId], mPrevAxisValues[joyId] + numAxes, 0); //initialize array to 0 } void InputManager::removeJoystickByJoystickID(SDL_JoystickID joyId) { assert(joyId != -1); // delete old prevAxisValues auto axisIt = mPrevAxisValues.find(joyId); delete[] axisIt->second; mPrevAxisValues.erase(axisIt); // delete old InputConfig auto it = mInputConfigs.find(joyId); delete it->second; mInputConfigs.erase(it); // close the joystick auto joyIt = mJoysticks.find(joyId); if(joyIt != mJoysticks.end()) { SDL_JoystickClose(joyIt->second); mJoysticks.erase(joyIt); }else{ LOG(LogError) << "Could not find joystick to close (instance ID: " << joyId << ")"; } } void InputManager::deinit() { if(!initialized()) return; for(auto iter = mJoysticks.begin(); iter != mJoysticks.end(); iter++) { SDL_JoystickClose(iter->second); } mJoysticks.clear(); for(auto iter = mInputConfigs.begin(); iter != mInputConfigs.end(); iter++) { delete iter->second; } mInputConfigs.clear(); for(auto iter = mPrevAxisValues.begin(); iter != mPrevAxisValues.end(); iter++) { delete[] iter->second; } mPrevAxisValues.clear(); if(mKeyboardInputConfig != NULL) { delete mKeyboardInputConfig; mKeyboardInputConfig = NULL; } SDL_JoystickEventState(SDL_DISABLE); SDL_QuitSubSystem(SDL_INIT_JOYSTICK); } int InputManager::getNumJoysticks() { return mJoysticks.size(); } int InputManager::getButtonCountByDevice(SDL_JoystickID id) { if(id == DEVICE_KEYBOARD) return 120; //it's a lot, okay. else return SDL_JoystickNumButtons(mJoysticks[id]); } InputConfig* InputManager::getInputConfigByDevice(int device) { if(device == DEVICE_KEYBOARD) return mKeyboardInputConfig; else return mInputConfigs[device]; } bool InputManager::parseEvent(const SDL_Event& ev, Window* window) { bool causedEvent = false; switch(ev.type) { case SDL_JOYAXISMOTION: //if it switched boundaries if((abs(ev.jaxis.value) > DEADZONE) != (abs(mPrevAxisValues[ev.jaxis.which][ev.jaxis.axis]) > DEADZONE)) { int normValue; if(abs(ev.jaxis.value) <= DEADZONE) normValue = 0; else if(ev.jaxis.value > 0) normValue = 1; else normValue = -1; window->input(getInputConfigByDevice(ev.jaxis.which), Input(ev.jaxis.which, TYPE_AXIS, ev.jaxis.axis, normValue, false)); causedEvent = true; } mPrevAxisValues[ev.jaxis.which][ev.jaxis.axis] = ev.jaxis.value; return causedEvent; case SDL_JOYBUTTONDOWN: case SDL_JOYBUTTONUP: window->input(getInputConfigByDevice(ev.jbutton.which), Input(ev.jbutton.which, TYPE_BUTTON, ev.jbutton.button, ev.jbutton.state == SDL_PRESSED, false)); return true; case SDL_JOYHATMOTION: window->input(getInputConfigByDevice(ev.jhat.which), Input(ev.jhat.which, TYPE_HAT, ev.jhat.hat, ev.jhat.value, false)); return true; case SDL_KEYDOWN: if(ev.key.keysym.sym == SDLK_BACKSPACE && SDL_IsTextInputActive()) { window->textInput("\b"); } if(ev.key.repeat) return false; if(ev.key.keysym.sym == SDLK_F4) { SDL_Event* quit = new SDL_Event(); quit->type = SDL_QUIT; SDL_PushEvent(quit); return false; } window->input(getInputConfigByDevice(DEVICE_KEYBOARD), Input(DEVICE_KEYBOARD, TYPE_KEY, ev.key.keysym.sym, 1, false)); return true; case SDL_KEYUP: window->input(getInputConfigByDevice(DEVICE_KEYBOARD), Input(DEVICE_KEYBOARD, TYPE_KEY, ev.key.keysym.sym, 0, false)); return true; case SDL_TEXTINPUT: window->textInput(ev.text.text); break; case SDL_JOYDEVICEADDED: addJoystickByDeviceIndex(ev.jdevice.which); // ev.jdevice.which is a device index return true; case SDL_JOYDEVICEREMOVED: removeJoystickByJoystickID(ev.jdevice.which); // ev.jdevice.which is an SDL_JoystickID (instance ID) return false; } return false; } bool InputManager::loadInputConfig(InputConfig* config) { std::string path = getConfigPath(); if(!fs::exists(path)) return false; pugi::xml_document doc; pugi::xml_parse_result res = doc.load_file(path.c_str()); if(!res) { LOG(LogError) << "Error parsing input config: " << res.description(); return false; } pugi::xml_node root = doc.child("inputList"); if(!root) return false; pugi::xml_node configNode = root.find_child_by_attribute("inputConfig", "deviceGUID", config->getDeviceGUIDString().c_str()); if(!configNode) configNode = root.find_child_by_attribute("inputConfig", "deviceName", config->getDeviceName().c_str()); if(!configNode) return false; config->loadFromXML(configNode); return true; } //used in an "emergency" where no keyboard config could be loaded from the inputmanager config file //allows the user to select to reconfigure in menus if this happens without having to delete es_input.cfg manually void InputManager::loadDefaultKBConfig() { InputConfig* cfg = getInputConfigByDevice(DEVICE_KEYBOARD); cfg->clear(); cfg->mapInput("up", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_UP, 1, true)); cfg->mapInput("down", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_DOWN, 1, true)); cfg->mapInput("left", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_LEFT, 1, true)); cfg->mapInput("right", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_RIGHT, 1, true)); cfg->mapInput("a", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_RETURN, 1, true)); cfg->mapInput("b", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_ESCAPE, 1, true)); cfg->mapInput("start", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_F1, 1, true)); cfg->mapInput("select", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_F2, 1, true)); cfg->mapInput("pageup", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_RIGHTBRACKET, 1, true)); cfg->mapInput("pagedown", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_LEFTBRACKET, 1, true)); } void InputManager::writeDeviceConfig(InputConfig* config) { assert(initialized()); std::string path = getConfigPath(); pugi::xml_document doc; if(fs::exists(path)) { // merge files pugi::xml_parse_result result = doc.load_file(path.c_str()); if(!result) { LOG(LogError) << "Error parsing input config: " << result.description(); }else{ // successfully loaded, delete the old entry if it exists pugi::xml_node root = doc.child("inputList"); if(root) { pugi::xml_node oldEntry = root.find_child_by_attribute("inputConfig", "deviceGUID", config->getDeviceGUIDString().c_str()); if(oldEntry) root.remove_child(oldEntry); oldEntry = root.find_child_by_attribute("inputConfig", "deviceName", config->getDeviceName().c_str()); if(oldEntry) root.remove_child(oldEntry); } } } pugi::xml_node root = doc.child("inputList"); if(!root) root = doc.append_child("inputList"); config->writeToXML(root); doc.save_file(path.c_str()); } std::string InputManager::getConfigPath() { std::string path = getHomePath(); path += "/.emulationstation/es_input.cfg"; return path; } bool InputManager::initialized() const { return mKeyboardInputConfig != NULL; } int InputManager::getNumConfiguredDevices() { int num = 0; for(auto it = mInputConfigs.begin(); it != mInputConfigs.end(); it++) { if(it->second->isConfigured()) num++; } if(mKeyboardInputConfig->isConfigured()) num++; return num; } std::string InputManager::getDeviceGUIDString(int deviceId) { if(deviceId == DEVICE_KEYBOARD) return KEYBOARD_GUID_STRING; auto it = mJoysticks.find(deviceId); if(it == mJoysticks.end()) { LOG(LogError) << "getDeviceGUIDString - deviceId " << deviceId << " not found!"; return "something went horribly wrong"; } char guid[65]; SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(it->second), guid, 65); return std::string(guid); } <|endoftext|>
<commit_before>/** * Clever programming language * Copyright (c) Clever Team * * This file is distributed under the MIT license. See LICENSE for details. */ #include "core/cstring.h" #include "core/compiler.h" #include "core/scope.h" #include "core/value.h" #include "core/location.hh" #include "core/astdump.h" #include "core/codegen.h" #include "core/evaluator.h" #include "core/resolver.h" namespace clever { /// Compiler initialization phase void Compiler::init() { m_pkg.init(); } /// Frees all resource used by the compiler void Compiler::shutdown() { delete m_builder; m_pkg.shutdown(); clever_delete_var(g_cstring_tbl); } /// Displays an error message and exits void Compiler::error(const char* msg) { std::cerr << "Compile error: " << msg << std::endl; CLEVER_EXIT_FATAL(); } /// Displays an error message void Compiler::error(const std::string& message, const location& loc) { if (loc.begin.filename) { std::cerr << "Compile error: " << message << " on " << *loc.begin.filename << " line " << loc.begin.line << "\n"; } else { std::cerr << "Compile error: " << message << " on line " << loc.begin.line << "\n"; } CLEVER_EXIT_FATAL(); } /// Displays a formatted error message and abort the compilation void Compiler::errorf(const location& loc, const char* format, ...) { std::ostringstream out; va_list args; va_start(args, format); vsprintf(out, format, args); va_end(args); error(out.str(), loc); } void Compiler::emitAST(ast::Node* tree) { if (!tree) { return; } if (m_flags & USE_OPTIMIZER) { ast::Evaluator evaluator; tree = tree->accept(evaluator); } if (m_flags & DUMP_AST) { ast::Dumper astdump; tree->accept(astdump); } ast::Resolver resolver(m_pkg); tree->accept(resolver); if (!(m_flags & PARSER_ONLY)) { m_global_env = resolver.getGlobalEnv(); m_builder = new IRBuilder(m_global_env); ast::Codegen codegen(this, m_builder); tree->accept(codegen); } clever_delete_var(tree); } } // clever <commit_msg>- Added missing OP_HALT instruction<commit_after>/** * Clever programming language * Copyright (c) Clever Team * * This file is distributed under the MIT license. See LICENSE for details. */ #include "core/cstring.h" #include "core/compiler.h" #include "core/scope.h" #include "core/value.h" #include "core/location.hh" #include "core/astdump.h" #include "core/codegen.h" #include "core/evaluator.h" #include "core/resolver.h" namespace clever { /// Compiler initialization phase void Compiler::init() { m_pkg.init(); } /// Frees all resource used by the compiler void Compiler::shutdown() { delete m_builder; m_pkg.shutdown(); clever_delete_var(g_cstring_tbl); } /// Displays an error message and exits void Compiler::error(const char* msg) { std::cerr << "Compile error: " << msg << std::endl; CLEVER_EXIT_FATAL(); } /// Displays an error message void Compiler::error(const std::string& message, const location& loc) { if (loc.begin.filename) { std::cerr << "Compile error: " << message << " on " << *loc.begin.filename << " line " << loc.begin.line << "\n"; } else { std::cerr << "Compile error: " << message << " on line " << loc.begin.line << "\n"; } CLEVER_EXIT_FATAL(); } /// Displays a formatted error message and abort the compilation void Compiler::errorf(const location& loc, const char* format, ...) { std::ostringstream out; va_list args; va_start(args, format); vsprintf(out, format, args); va_end(args); error(out.str(), loc); } void Compiler::emitAST(ast::Node* tree) { if (!tree) { return; } if (m_flags & USE_OPTIMIZER) { ast::Evaluator evaluator; tree = tree->accept(evaluator); } if (m_flags & DUMP_AST) { ast::Dumper astdump; tree->accept(astdump); } ast::Resolver resolver(m_pkg); tree->accept(resolver); if (!(m_flags & PARSER_ONLY)) { m_global_env = resolver.getGlobalEnv(); m_builder = new IRBuilder(m_global_env); ast::Codegen codegen(this, m_builder); tree->accept(codegen); m_builder->push(OP_HALT); } clever_delete_var(tree); } } // clever <|endoftext|>
<commit_before>#include <cassert> #include "CodeGen_Bash.h" using namespace Bish; void CodeGen_Bash::indent() { for (unsigned i = 0; i < indent_level; i++) { stream << " "; } } void CodeGen_Bash::visit(Module *n) { for (std::vector<Function *>::const_iterator I = n->functions.begin(), E = n->functions.end(); I != E; ++I) { (*I)->accept(this); } // Insert a call to bish_main(). assert(n->main); FunctionCall *call_main = new FunctionCall(n->main); visit(call_main); stream << ";\n"; delete call_main; } void CodeGen_Bash::visit(Block *n) { if (should_print_block_braces()) stream << "{\n"; indent_level++; for (std::vector<IRNode *>::const_iterator I = n->nodes.begin(), E = n->nodes.end(); I != E; ++I) { indent(); (*I)->accept(this); stream << ";\n"; } indent_level--; if (should_print_block_braces()) stream << "}\n\n"; } void CodeGen_Bash::visit(Variable *n) { if (should_quote_variable()) stream << "\""; stream << "$" << lookup_name(n); if (should_quote_variable()) stream << "\""; } void CodeGen_Bash::visit(ReturnStatement *n) { stream << "echo "; enable_functioncall_wrap(); n->value->accept(this); disable_functioncall_wrap(); stream << "; exit"; } void CodeGen_Bash::visit(IfStatement *n) { stream << "if [[ "; enable_functioncall_wrap(); n->pblock->condition->accept(this); disable_functioncall_wrap(); stream << " ]]; then\n"; disable_block_braces(); n->pblock->body->accept(this); for (std::vector<PredicatedBlock *>::const_iterator I = n->elses.begin(), E = n->elses.end(); I != E; ++I) { indent(); stream << "elif [[ "; enable_functioncall_wrap(); (*I)->condition->accept(this); disable_functioncall_wrap(); stream << " ]]; then\n"; (*I)->body->accept(this); } if (n->elseblock) { indent(); stream << "else\n"; n->elseblock->accept(this); } enable_block_braces(); indent(); stream << "fi"; } void CodeGen_Bash::visit(ForLoop *n) { stream << "for " << lookup_name(n->variable) << " in "; if (n->upper) { stream << "$(seq "; n->lower->accept(this); stream << " "; n->upper->accept(this); stream << ")"; } else { disable_quote_variable(); n->lower->accept(this); enable_quote_variable(); } stream << "; do\n"; disable_block_braces(); n->body->accept(this); enable_block_braces(); indent(); stream << "done"; } void CodeGen_Bash::visit(Function *n) { stream << "function bish_" << n->name << " "; stream << "() "; LetScope *s = new LetScope(); push_let_scope(s); // Bash doesn't allow named arguments to functions. // We have to translate to positional arguments. unsigned i = 1; for (std::vector<Variable *>::const_iterator I = n->args.begin(), E = n->args.end(); I != E; ++I, ++i) { s->add(*I, convert_string(i)); } if (n->body) n->body->accept(this); pop_let_scope(); } void CodeGen_Bash::visit(FunctionCall *n) { const int nargs = n->args.size(); if (should_functioncall_wrap()) stream << "$("; stream << "bish_" << n->function->name; for (int i = 0; i < nargs; i++) { stream << " "; bool old = enable_functioncall_wrap(); if (const FunctionCall *FC = dynamic_cast<const FunctionCall*>(n->args[i])) { if (should_quote_variable()) stream << "\""; n->args[i]->accept(this); if (should_quote_variable()) stream << "\""; } else { n->args[i]->accept(this); } set_functioncall_wrap(old); } if (should_functioncall_wrap()) stream << ")"; } void CodeGen_Bash::visit(ExternCall *n) { if (should_functioncall_wrap()) stream << "$("; disable_quote_variable(); for (InterpolatedString::const_iterator I = n->body->begin(), E = n->body->end(); I != E; ++I) { if ((*I).is_str()) { stream << (*I).str(); } else { assert((*I).is_var()); visit((*I).var()); } } enable_quote_variable(); if (should_functioncall_wrap()) stream << ")"; } void CodeGen_Bash::visit(Assignment *n) { stream << lookup_name(n->variable) << "="; enable_functioncall_wrap(); n->value->accept(this); disable_functioncall_wrap(); } void CodeGen_Bash::visit(BinOp *n) { std::string bash_op; bool comparison = false; switch (n->op) { case BinOp::Eq: bash_op = n->type() == StringTy ? "==" : "-eq"; comparison = true; break; case BinOp::NotEq: bash_op = n->type() == StringTy ? "!=" : "-ne"; comparison = true; break; case BinOp::LT: bash_op = "<"; comparison = true; break; case BinOp::LTE: bash_op = "<="; comparison = true; break; case BinOp::GT: bash_op = ">"; comparison = true; break; case BinOp::GTE: bash_op = ">="; comparison = true; break; case BinOp::Add: bash_op = "+"; break; case BinOp::Sub: bash_op = "-"; break; case BinOp::Mul: bash_op = "*"; break; case BinOp::Div: bash_op = "/"; break; case BinOp::Mod: bash_op = "%"; break; } if (!comparison) stream << "$(("; disable_quote_variable(); n->a->accept(this); stream << " " << bash_op << " "; n->b->accept(this); if (!comparison) stream << "))"; enable_quote_variable(); } void CodeGen_Bash::visit(UnaryOp *n) { switch (n->op) { case UnaryOp::Negate: stream << "-"; break; } n->a->accept(this); } void CodeGen_Bash::visit(Integer *n) { stream << n->value; } void CodeGen_Bash::visit(Fractional *n) { stream << n->value; } void CodeGen_Bash::visit(String *n) { stream << "\"" << n->value << "\""; } void CodeGen_Bash::visit(Boolean *n) { stream << n->value; } <commit_msg>Fix non-binary operators in conditionals.<commit_after>#include <cassert> #include "CodeGen_Bash.h" using namespace Bish; void CodeGen_Bash::indent() { for (unsigned i = 0; i < indent_level; i++) { stream << " "; } } void CodeGen_Bash::visit(Module *n) { for (std::vector<Function *>::const_iterator I = n->functions.begin(), E = n->functions.end(); I != E; ++I) { (*I)->accept(this); } // Insert a call to bish_main(). assert(n->main); FunctionCall *call_main = new FunctionCall(n->main); visit(call_main); stream << ";\n"; delete call_main; } void CodeGen_Bash::visit(Block *n) { if (should_print_block_braces()) stream << "{\n"; indent_level++; for (std::vector<IRNode *>::const_iterator I = n->nodes.begin(), E = n->nodes.end(); I != E; ++I) { indent(); (*I)->accept(this); stream << ";\n"; } indent_level--; if (should_print_block_braces()) stream << "}\n\n"; } void CodeGen_Bash::visit(Variable *n) { if (should_quote_variable()) stream << "\""; stream << "$" << lookup_name(n); if (should_quote_variable()) stream << "\""; } void CodeGen_Bash::visit(ReturnStatement *n) { stream << "echo "; enable_functioncall_wrap(); n->value->accept(this); disable_functioncall_wrap(); stream << "; exit"; } void CodeGen_Bash::visit(IfStatement *n) { stream << "if [[ "; enable_functioncall_wrap(); n->pblock->condition->accept(this); if (dynamic_cast<BinOp*>(n->pblock->condition) == NULL) { stream << " -eq 1"; } disable_functioncall_wrap(); stream << " ]]; then\n"; disable_block_braces(); n->pblock->body->accept(this); for (std::vector<PredicatedBlock *>::const_iterator I = n->elses.begin(), E = n->elses.end(); I != E; ++I) { indent(); stream << "elif [[ "; enable_functioncall_wrap(); (*I)->condition->accept(this); disable_functioncall_wrap(); stream << " ]]; then\n"; (*I)->body->accept(this); } if (n->elseblock) { indent(); stream << "else\n"; n->elseblock->accept(this); } enable_block_braces(); indent(); stream << "fi"; } void CodeGen_Bash::visit(ForLoop *n) { stream << "for " << lookup_name(n->variable) << " in "; if (n->upper) { stream << "$(seq "; n->lower->accept(this); stream << " "; n->upper->accept(this); stream << ")"; } else { disable_quote_variable(); n->lower->accept(this); enable_quote_variable(); } stream << "; do\n"; disable_block_braces(); n->body->accept(this); enable_block_braces(); indent(); stream << "done"; } void CodeGen_Bash::visit(Function *n) { stream << "function bish_" << n->name << " "; stream << "() "; LetScope *s = new LetScope(); push_let_scope(s); // Bash doesn't allow named arguments to functions. // We have to translate to positional arguments. unsigned i = 1; for (std::vector<Variable *>::const_iterator I = n->args.begin(), E = n->args.end(); I != E; ++I, ++i) { s->add(*I, convert_string(i)); } if (n->body) n->body->accept(this); pop_let_scope(); } void CodeGen_Bash::visit(FunctionCall *n) { const int nargs = n->args.size(); if (should_functioncall_wrap()) stream << "$("; stream << "bish_" << n->function->name; for (int i = 0; i < nargs; i++) { stream << " "; bool old = enable_functioncall_wrap(); if (const FunctionCall *FC = dynamic_cast<const FunctionCall*>(n->args[i])) { if (should_quote_variable()) stream << "\""; n->args[i]->accept(this); if (should_quote_variable()) stream << "\""; } else { n->args[i]->accept(this); } set_functioncall_wrap(old); } if (should_functioncall_wrap()) stream << ")"; } void CodeGen_Bash::visit(ExternCall *n) { if (should_functioncall_wrap()) stream << "$("; disable_quote_variable(); for (InterpolatedString::const_iterator I = n->body->begin(), E = n->body->end(); I != E; ++I) { if ((*I).is_str()) { stream << (*I).str(); } else { assert((*I).is_var()); visit((*I).var()); } } enable_quote_variable(); if (should_functioncall_wrap()) stream << ")"; } void CodeGen_Bash::visit(Assignment *n) { stream << lookup_name(n->variable) << "="; enable_functioncall_wrap(); n->value->accept(this); disable_functioncall_wrap(); } void CodeGen_Bash::visit(BinOp *n) { std::string bash_op; bool comparison = false; switch (n->op) { case BinOp::Eq: bash_op = n->type() == StringTy ? "==" : "-eq"; comparison = true; break; case BinOp::NotEq: bash_op = n->type() == StringTy ? "!=" : "-ne"; comparison = true; break; case BinOp::LT: bash_op = "<"; comparison = true; break; case BinOp::LTE: bash_op = "<="; comparison = true; break; case BinOp::GT: bash_op = ">"; comparison = true; break; case BinOp::GTE: bash_op = ">="; comparison = true; break; case BinOp::Add: bash_op = "+"; break; case BinOp::Sub: bash_op = "-"; break; case BinOp::Mul: bash_op = "*"; break; case BinOp::Div: bash_op = "/"; break; case BinOp::Mod: bash_op = "%"; break; } if (!comparison) stream << "$(("; disable_quote_variable(); n->a->accept(this); stream << " " << bash_op << " "; n->b->accept(this); if (!comparison) stream << "))"; enable_quote_variable(); } void CodeGen_Bash::visit(UnaryOp *n) { switch (n->op) { case UnaryOp::Negate: stream << "-"; break; } n->a->accept(this); } void CodeGen_Bash::visit(Integer *n) { stream << n->value; } void CodeGen_Bash::visit(Fractional *n) { stream << n->value; } void CodeGen_Bash::visit(String *n) { stream << "\"" << n->value << "\""; } void CodeGen_Bash::visit(Boolean *n) { stream << n->value; } <|endoftext|>
<commit_before>#include "CodeGenerator.hpp" #include "AST.hpp" GenericValue CodeGenerator::runCode() { std::cout<<"Now.. Running Code"<<std::endl; ExistingModuleProvider *EMP = new ExistingModuleProvider(module); ExectionEngine *EE = ExectuionEngine::create(EMP, false); std::vector <GenericValue> gv_vec; GenericValue gv = EE->runFunction(mainFunc, gv_vec); return gv; } CodeBlock* CodeGenerator::popStack() { CodeBlock* value = null; if(!this.block_stack.empty()) { value = this.block_stack.pop(); } return value; } void CodeGenerator::pushStack(CodeBlock *block) { this.block_stack.push(block); } void CodeGenerator::GenerateCode() { std::cout<<"Now Generatring Code...."<<std::endl; FunctionType *ftype = FuntionType::get(Type::getInt32Ty this._mainFunc = llvm::Function::Create(this._globalContext, "main", this._module); BasicBlock *BB = BasicBlock::Create(this._globalContext, "EntryBlock", this._mainFunc); } <commit_msg>2014-10-18<commit_after>#include "CodeGenerator.hpp" #include "AST.hpp" GenericValue CodeGenerator::runCode() { std::cout<<"Now.. Running Code"<<std::endl; ExistingModuleProvider *EMP = new ExistingModuleProvider(module); ExectionEngine *EE = ExectuionEngine::create(EMP, false); std::vector <GenericValue> gv_vec; GenericValue gv = EE->runFunction(this._mainFunc, gv_vec); return gv; } CodeBlock* CodeGenerator::popStack() { CodeBlock* value = null; if(!this.block_stack.empty()) { value = this.block_stack.pop(); } return value; } void CodeGenerator::pushStack(CodeBlock *block) { this.block_stack.push(block); } void CodeGenerator::GenerateCode() { std::cout<<"Now Generatring Code...."<<std::endl; FunctionType *ftype = FuntionType::get(Type::getInt32Ty this._mainFunc = llvm::Function::Create(this._globalContext, "main", this._module); BasicBlock *BB = BasicBlock::Create(this._globalContext, "EntryBlock", this._mainFunc); } <|endoftext|>
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/vespalib/util/exception.h> #include <vespa/vespalib/util/slaveproc.h> using namespace vespalib; TEST("that uncaught exception causes negative exitcode.") { SlaveProc proc("ulimit -c 0 && exec ./vespalib_caught_uncaught_app uncaught"); proc.wait(); EXPECT_LESS(proc.getExitCode(), 0); } TEST("that uncaught silenced exception causes exitcode 66") { SlaveProc proc("ulimit -c 0 && exec ./vespalib_caught_uncaught_app silenced_and_uncaught"); proc.wait(); EXPECT_EQUAL(proc.getExitCode(), 66); } TEST("that caught silenced exception followed by an uncaught causes negative exitcode.") { SlaveProc proc("ulimit -c 0 && exec ./vespalib_caught_uncaught_app uncaught_after_silenced_and_caught"); proc.wait(); EXPECT_LESS(proc.getExitCode(), 0); } TEST("that caught silenced exception causes exitcode 0") { SlaveProc proc("ulimit -c 0 && exec ./vespalib_caught_uncaught_app silenced_and_caught"); proc.wait(); EXPECT_EQUAL(proc.getExitCode(), 0); } TEST("that mmap within limits are fine cause exitcode 0") { SlaveProc proc("ulimit -c 0 && exec ./vespalib_mmap_app 100000000 10485760 1"); proc.wait(); EXPECT_EQUAL(proc.getExitCode(), 0); } TEST("that mmap beyond limits cause negative exitcode.") { SlaveProc proc("ulimit -c 0 && exec ./vespalib_mmap_app 100000000 10485760 10"); proc.wait(); EXPECT_LESS(proc.getExitCode(), 0); } TEST("that mmap beyond limits with set VESPA_SILENCE_CORE_ON_OOM cause exitcode 66.") { SlaveProc proc("ulimit -c 0 && VESPA_SILENCE_CORE_ON_OOM=1 exec ./vespalib_mmap_app 100000000 10485760 10"); proc.wait(); EXPECT_EQUAL(proc.getExitCode(), 66); } TEST_MAIN_WITH_PROCESS_PROXY() { TEST_RUN_ALL(); } <commit_msg>ulimit -c 0 only when needed<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/vespalib/util/exception.h> #include <vespa/vespalib/util/slaveproc.h> using namespace vespalib; TEST("that uncaught exception causes negative exitcode.") { SlaveProc proc("ulimit -c 0 && exec ./vespalib_caught_uncaught_app uncaught"); proc.wait(); EXPECT_LESS(proc.getExitCode(), 0); } TEST("that uncaught silenced exception causes exitcode 66") { SlaveProc proc("exec ./vespalib_caught_uncaught_app silenced_and_uncaught"); proc.wait(); EXPECT_EQUAL(proc.getExitCode(), 66); } TEST("that caught silenced exception followed by an uncaught causes negative exitcode.") { SlaveProc proc("ulimit -c 0 && exec ./vespalib_caught_uncaught_app uncaught_after_silenced_and_caught"); proc.wait(); EXPECT_LESS(proc.getExitCode(), 0); } TEST("that caught silenced exception causes exitcode 0") { SlaveProc proc("exec ./vespalib_caught_uncaught_app silenced_and_caught"); proc.wait(); EXPECT_EQUAL(proc.getExitCode(), 0); } TEST("that mmap within limits are fine cause exitcode 0") { SlaveProc proc("exec ./vespalib_mmap_app 100000000 10485760 1"); proc.wait(); EXPECT_EQUAL(proc.getExitCode(), 0); } TEST("that mmap beyond limits cause negative exitcode.") { SlaveProc proc("ulimit -c 0 && exec ./vespalib_mmap_app 100000000 10485760 10"); proc.wait(); EXPECT_LESS(proc.getExitCode(), 0); } TEST("that mmap beyond limits with set VESPA_SILENCE_CORE_ON_OOM cause exitcode 66.") { SlaveProc proc("VESPA_SILENCE_CORE_ON_OOM=1 exec ./vespalib_mmap_app 100000000 10485760 10"); proc.wait(); EXPECT_EQUAL(proc.getExitCode(), 66); } TEST_MAIN_WITH_PROCESS_PROXY() { TEST_RUN_ALL(); } <|endoftext|>
<commit_before>/*! * \file Utils.cpp * \brief Utility functions - implementation * \author mstefanc * \date Jun 9, 2010 */ #include "Utils.hpp" #include <string> #include <vector> #define BOOST_FILESYSTEM_VERSION 2 #include <boost/filesystem.hpp> using namespace boost::filesystem; #include <boost/regex.hpp> #include <boost/foreach.hpp> using namespace std; namespace Utils { std::vector<std::string> searchFiles(const std::string & root, const std::string & regexp, bool with_path) { boost::regex e(regexp); std::vector<std::string> ret; path dir_path(root); if ( !exists( dir_path ) ) return ret; directory_iterator end_itr; // default construction yields past-the-end for ( directory_iterator itr( dir_path ); itr != end_itr; ++itr ) { std::string fname = itr->path().filename(); if (regex_match(fname, e)) { if (with_path) ret.push_back(itr->path().file_string()); else ret.push_back(fname); } } return ret; } std::vector<std::string> getSubdirs(const std::string & root, bool with_path) { std::vector<std::string> ret; path dir_path(root); if ( !exists( dir_path ) ) return ret; directory_iterator end_itr; // default construction yields past-the-end for ( directory_iterator itr( dir_path ); itr != end_itr; ++itr ) { std::string fname = itr->path().filename(); if (is_directory(itr->status())) { if (with_path) ret.push_back(itr->path().file_string()); else ret.push_back(fname); } } return ret; } std::string findSubdir(const std::string & name, const std::vector<std::string> & roots, bool with_path) { std::string root; BOOST_FOREACH(root, roots) { path dir_path(root); if ( !exists( dir_path ) ) continue; directory_iterator end_itr; // default construction yields past-the-end for ( directory_iterator itr( dir_path ); itr != end_itr; ++itr ) { std::string fname = itr->path().filename(); if (is_directory(itr->status()) && fname == name) { if (with_path) return itr->path().file_string(); else return fname; } } } return ""; } } //: namespace Utils <commit_msg>Last Filesystem V3 fix<commit_after>/*! * \file Utils.cpp * \brief Utility functions - implementation * \author mstefanc * \date Jun 9, 2010 */ #include "Utils.hpp" #include <string> #include <vector> #include <boost/filesystem.hpp> using namespace boost::filesystem; #include <boost/regex.hpp> #include <boost/foreach.hpp> using namespace std; namespace Utils { std::vector<std::string> searchFiles(const std::string & root, const std::string & regexp, bool with_path) { boost::regex e(regexp); std::vector<std::string> ret; path dir_path(root); if ( !exists( dir_path ) ) return ret; directory_iterator end_itr; // default construction yields past-the-end for ( directory_iterator itr( dir_path ); itr != end_itr; ++itr ) { std::string fname = itr->path().filename().string(); if (regex_match(fname, e)) { if (with_path) ret.push_back(itr->path().string()); else ret.push_back(fname); } } return ret; } std::vector<std::string> getSubdirs(const std::string & root, bool with_path) { std::vector<std::string> ret; path dir_path(root); if ( !exists( dir_path ) ) return ret; directory_iterator end_itr; // default construction yields past-the-end for ( directory_iterator itr( dir_path ); itr != end_itr; ++itr ) { std::string fname = itr->path().filename().string(); if (is_directory(itr->status())) { if (with_path) ret.push_back(itr->path().string()); else ret.push_back(fname); } } return ret; } std::string findSubdir(const std::string & name, const std::vector<std::string> & roots, bool with_path) { std::string root; BOOST_FOREACH(root, roots) { path dir_path(root); if ( !exists( dir_path ) ) continue; directory_iterator end_itr; // default construction yields past-the-end for ( directory_iterator itr( dir_path ); itr != end_itr; ++itr ) { std::string fname = itr->path().filename().string(); if (is_directory(itr->status()) && fname == name) { if (with_path) return itr->path().string(); else return fname; } } } return ""; } } //: namespace Utils <|endoftext|>
<commit_before> #include "queued_cpu_tracker.h" #ifdef WIN32 #include <Windows.h> #undef AddJob #endif static int PDT_BytesPerPixel(QTRK_PixelDataType pdt) { const int pdtBytes[] = {1, 2, 4}; return pdtBytes[(int)pdt]; } void QueuedCPUTracker::JobFinished(QueuedCPUTracker::Job* j) { pthread_mutex_lock(&jobs_buffer_mutex); jobs_buffer.push_back(j); pthread_mutex_unlock(&jobs_buffer_mutex); } QueuedCPUTracker::Job* QueuedCPUTracker::GetNextJob() { QueuedCPUTracker::Job *j = 0; pthread_mutex_lock(&jobs_mutex); if (!jobs.empty()) { j = jobs.front(); jobs.pop_front(); } pthread_mutex_unlock(&jobs_mutex); return j; } QueuedCPUTracker::Job* QueuedCPUTracker::AllocateJob() { QueuedCPUTracker::Job *j; pthread_mutex_lock(&jobs_buffer_mutex); if (!jobs_buffer.empty()) { j = jobs_buffer.back(); jobs_buffer.pop_back(); } else j = new Job; pthread_mutex_unlock(&jobs_buffer_mutex); return j; } void QueuedCPUTracker::AddJob(Job* j) { pthread_mutex_lock(&jobs_mutex); jobs.push_back(j); pthread_mutex_unlock(&jobs_mutex); } QueuedCPUTracker::QueuedCPUTracker(int w, int h, int xcorw, int numThreads) { quitWork = false; threads.resize(numThreads); for (int k=0;k<numThreads;k++) { threads[k].tracker = new CPUTracker(w, h, xcorw); threads[k].manager = this; } pthread_attr_init(&joinable_attr); pthread_attr_setdetachstate(&joinable_attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&jobs_mutex,0); pthread_mutex_init(&results_mutex,0); pthread_mutex_init(&jobs_buffer_mutex,0); } QueuedCPUTracker::~QueuedCPUTracker() { // wait for threads to finish quitWork = true; for (int k=0;k<threads.size();k++) { pthread_join(threads[k].thread, 0); delete threads[k].tracker; } pthread_attr_destroy(&joinable_attr); pthread_mutex_destroy(&jobs_mutex); pthread_mutex_destroy(&jobs_buffer_mutex); pthread_mutex_destroy(&results_mutex); // free job memory DeleteAllElems(jobs); DeleteAllElems(jobs_buffer); } void QueuedCPUTracker::Start() { quitWork = false; for (int k=0;k<threads.size();k++) { pthread_create(&threads[k].thread, &joinable_attr, WorkerThreadMain, (void*)&threads[k]); } } void* QueuedCPUTracker::WorkerThreadMain(void* arg) { Thread* th = (Thread*)arg; QueuedCPUTracker* this_ = th->manager; while (!this_->quitWork) { Job* j = this_->GetNextJob(); if (j) { this_->ProcessJob(th, j); } else { #ifdef WIN32 Sleep(1); #endif } } return 0; } void QueuedCPUTracker::ProcessJob(Thread* th, Job* j) { if (j->dataType == QTrkU8) { th->tracker->SetImage8Bit(j->data, width); } else if (j->dataType == QTrkU16) { th->tracker->SetImage16Bit((ushort*)j->data, width*2); } else { th->tracker->SetImageFloat((float*)j->data); } LocalizationResult result={}; result.id = j->id; result.locType = j->locType; result.zlutIndex = j->zlut; vector2f com = th->tracker->ComputeBgCorrectedCOM(); if (j->locType == LocalizeXCor1D) { result.firstGuess = com; result.pos = th->tracker->ComputeXCorInterpolated(com, cfg.xcor1D_iterations, cfg.profileWidth); } else if(j->locType == LocalizeOnlyCOM) { result.firstGuess = result.pos = com; } else if(j->locType == LocalizeQI) { result.firstGuess = com; result.pos = th->tracker->ComputeQI(com, cfg.qi_iterations, cfg.qi_radialsteps, cfg.qi_angularsteps, cfg.qi_maxr); } pthread_mutex_lock(&results_mutex); results.push_back(result); pthread_mutex_unlock(&results_mutex); } void QueuedCPUTracker::SetZLUT(float* data, int planes, int res, int num_zluts, float prof_radius, int angularSteps) { } void QueuedCPUTracker::ComputeRadialProfile(float* dst, int radialSteps, int angularSteps, float radius, vector2f center) { } void QueuedCPUTracker::ScheduleLocalization(uchar* data, int pitch, QTRK_PixelDataType pdt, Localize2DType locType, bool computeZ, uint id, uint zlutIndex) { Job* j = AllocateJob(); int dstPitch = PDT_BytesPerPixel(pdt) * width; if(!j->data || j->dataType != pdt) { if (j->data) delete[] j->data; j->data = new uchar[dstPitch * height]; } for (int y=0;y<height;y++) memcpy(&j->data[dstPitch*y], &data[pitch*y], dstPitch); j->dataType = pdt; j->id = id; j->locType = locType; j->zlut = zlutIndex; AddJob(j); } int QueuedCPUTracker::PollFinished(LocalizationResult* dstResults, int maxResults) { int numResults = 0; pthread_mutex_lock(&results_mutex); while (numResults < maxResults && !results.empty()) { dstResults[numResults++] = results.front(); results.pop_front(); } pthread_mutex_unlock(&results_mutex); return numResults; } <commit_msg>call JobFinished()<commit_after> #include "queued_cpu_tracker.h" #ifdef WIN32 #include <Windows.h> #undef AddJob #endif static int PDT_BytesPerPixel(QTRK_PixelDataType pdt) { const int pdtBytes[] = {1, 2, 4}; return pdtBytes[(int)pdt]; } void QueuedCPUTracker::JobFinished(QueuedCPUTracker::Job* j) { pthread_mutex_lock(&jobs_buffer_mutex); jobs_buffer.push_back(j); pthread_mutex_unlock(&jobs_buffer_mutex); } QueuedCPUTracker::Job* QueuedCPUTracker::GetNextJob() { QueuedCPUTracker::Job *j = 0; pthread_mutex_lock(&jobs_mutex); if (!jobs.empty()) { j = jobs.front(); jobs.pop_front(); } pthread_mutex_unlock(&jobs_mutex); return j; } QueuedCPUTracker::Job* QueuedCPUTracker::AllocateJob() { QueuedCPUTracker::Job *j; pthread_mutex_lock(&jobs_buffer_mutex); if (!jobs_buffer.empty()) { j = jobs_buffer.back(); jobs_buffer.pop_back(); } else j = new Job; pthread_mutex_unlock(&jobs_buffer_mutex); return j; } void QueuedCPUTracker::AddJob(Job* j) { pthread_mutex_lock(&jobs_mutex); jobs.push_back(j); pthread_mutex_unlock(&jobs_mutex); } QueuedCPUTracker::QueuedCPUTracker(int w, int h, int xcorw, int numThreads) { quitWork = false; threads.resize(numThreads); for (int k=0;k<numThreads;k++) { threads[k].tracker = new CPUTracker(w, h, xcorw); threads[k].manager = this; } pthread_attr_init(&joinable_attr); pthread_attr_setdetachstate(&joinable_attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&jobs_mutex,0); pthread_mutex_init(&results_mutex,0); pthread_mutex_init(&jobs_buffer_mutex,0); } QueuedCPUTracker::~QueuedCPUTracker() { // wait for threads to finish quitWork = true; for (int k=0;k<threads.size();k++) { pthread_join(threads[k].thread, 0); delete threads[k].tracker; } pthread_attr_destroy(&joinable_attr); pthread_mutex_destroy(&jobs_mutex); pthread_mutex_destroy(&jobs_buffer_mutex); pthread_mutex_destroy(&results_mutex); // free job memory DeleteAllElems(jobs); DeleteAllElems(jobs_buffer); } void QueuedCPUTracker::Start() { quitWork = false; for (int k=0;k<threads.size();k++) { pthread_create(&threads[k].thread, &joinable_attr, WorkerThreadMain, (void*)&threads[k]); } } void* QueuedCPUTracker::WorkerThreadMain(void* arg) { Thread* th = (Thread*)arg; QueuedCPUTracker* this_ = th->manager; while (!this_->quitWork) { Job* j = this_->GetNextJob(); if (j) { this_->ProcessJob(th, j); this_->JobFinished(j); } else { #ifdef WIN32 Sleep(1); #endif } } return 0; } void QueuedCPUTracker::ProcessJob(Thread* th, Job* j) { if (j->dataType == QTrkU8) { th->tracker->SetImage8Bit(j->data, width); } else if (j->dataType == QTrkU16) { th->tracker->SetImage16Bit((ushort*)j->data, width*2); } else { th->tracker->SetImageFloat((float*)j->data); } LocalizationResult result={}; result.id = j->id; result.locType = j->locType; result.zlutIndex = j->zlut; vector2f com = th->tracker->ComputeBgCorrectedCOM(); if (j->locType == LocalizeXCor1D) { result.firstGuess = com; result.pos = th->tracker->ComputeXCorInterpolated(com, cfg.xcor1D_iterations, cfg.profileWidth); } else if(j->locType == LocalizeOnlyCOM) { result.firstGuess = result.pos = com; } else if(j->locType == LocalizeQI) { result.firstGuess = com; result.pos = th->tracker->ComputeQI(com, cfg.qi_iterations, cfg.qi_radialsteps, cfg.qi_angularsteps, cfg.qi_maxr); } pthread_mutex_lock(&results_mutex); results.push_back(result); pthread_mutex_unlock(&results_mutex); } void QueuedCPUTracker::SetZLUT(float* data, int planes, int res, int num_zluts, float prof_radius, int angularSteps) { } void QueuedCPUTracker::ComputeRadialProfile(float* dst, int radialSteps, int angularSteps, float radius, vector2f center) { } void QueuedCPUTracker::ScheduleLocalization(uchar* data, int pitch, QTRK_PixelDataType pdt, Localize2DType locType, bool computeZ, uint id, uint zlutIndex) { Job* j = AllocateJob(); int dstPitch = PDT_BytesPerPixel(pdt) * width; if(!j->data || j->dataType != pdt) { if (j->data) delete[] j->data; j->data = new uchar[dstPitch * height]; } for (int y=0;y<height;y++) memcpy(&j->data[dstPitch*y], &data[pitch*y], dstPitch); j->dataType = pdt; j->id = id; j->locType = locType; j->zlut = zlutIndex; AddJob(j); } int QueuedCPUTracker::PollFinished(LocalizationResult* dstResults, int maxResults) { int numResults = 0; pthread_mutex_lock(&results_mutex); while (numResults < maxResults && !results.empty()) { dstResults[numResults++] = results.front(); results.pop_front(); } pthread_mutex_unlock(&results_mutex); return numResults; } <|endoftext|>
<commit_before>/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2014-2016 Kim Kulling Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -----------------------------------------------------------------------------------------------*/ #include <cppcore/Random/RandomGenerator.h> #include <stdlib.h> #include <time.h> #include <cassert> namespace CPPCore { static const unsigned int N = 624; static const unsigned int M = 397; static void mersenne_twister_vector_init( unsigned int *seedPoints, size_t len ) { assert( nullptr != seedPoints ); const unsigned int mult = 1812433253ul; unsigned int seed = 5489ul; for (unsigned int i = 0; i < len; ++i) { seedPoints[ i ] = seed; seed = mult * (seed ^ (seed >> 30)) + (i + 1); } } static void mersenne_twister_vector_update(unsigned int* const p) { static const unsigned int A[ 2 ] = { 0, 0x9908B0DF }; unsigned int i=0; for (; i < N - M; i++) p[i] = p[i + (M)] ^ (((p[i] & 0x80000000) | (p[i + 1] & 0x7FFFFFFF)) >> 1) ^ A[p[i + 1] & 1]; for (; i < N - 1; i++) p[i] = p[i + (M - N)] ^ (((p[i] & 0x80000000) | (p[i + 1] & 0x7FFFFFFF)) >> 1) ^ A[p[i + 1] & 1]; p[N - 1] = p[M - 1] ^ (((p[N - 1] & 0x80000000) | (p[0] & 0x7FFFFFFF)) >> 1) ^ A[p[0] & 1]; } unsigned int mersenne_twister() { // State-vector static unsigned int vector[ N ]; // readout index static int idx = N + 1; if (static_cast<unsigned int>(idx) >= N) { if (static_cast<unsigned int>(idx) > N) { mersenne_twister_vector_init(vector, N); } mersenne_twister_vector_update(vector); idx = 0; } unsigned int e = vector[ idx++ ]; // Tempering e ^= (e >> 11); e ^= (e << 7) & 0x9D2C5680; e ^= (e << 15) & 0xEFC60000; e ^= (e >> 18); return e; } RandomGenerator::RandomGenerator( GeneratorType type ) noexcept : m_type( type ) { ::srand( static_cast< unsigned int >( time( NULL ) ) ); } RandomGenerator::~RandomGenerator() { // empty } int RandomGenerator::get( int lower, int upper ) { int ret( 0 ); if ( GeneratorType::Standard == m_type ) { ret = ::rand() % upper + lower; } else if (GeneratorType::MersenneTwister == m_type) { ret = mersenne_twister() % upper + lower; } return ret; } } // Namespace CPPCore <commit_msg>Update RandomGenerator.cpp<commit_after>/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2014-2016 Kim Kulling Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -----------------------------------------------------------------------------------------------*/ #include <cppcore/Random/RandomGenerator.h> #include <stdlib.h> #include <time.h> #include <cassert> namespace CPPCore { static const unsigned int N = 624; static const unsigned int M = 397; static void mersenne_twister_vector_init( unsigned int *seedPoints, size_t len ) { assert( nullptr != seedPoints ); const unsigned int mult = 1812433253ul; unsigned int seed = 5489ul; for (size_t i = 0; i < len; ++i) { seedPoints[ i ] = seed; seed = mult * (seed ^ (seed >> 30)) + (i + 1); } } static void mersenne_twister_vector_update(unsigned int* const p) { static const unsigned int A[ 2 ] = { 0, 0x9908B0DF }; unsigned int i=0; for (; i < N - M; i++) { p[i] = p[i + (M)] ^ (((p[i] & 0x80000000) | (p[i + 1] & 0x7FFFFFFF)) >> 1) ^ A[p[i + 1] & 1]; } for (; i < N - 1; i++) { p[i] = p[i + (M - N)] ^ (((p[i] & 0x80000000) | (p[i + 1] & 0x7FFFFFFF)) >> 1) ^ A[p[i + 1] & 1]; } p[N - 1] = p[M - 1] ^ (((p[N - 1] & 0x80000000) | (p[0] & 0x7FFFFFFF)) >> 1) ^ A[p[0] & 1]; } unsigned int mersenne_twister() { // State-vector static unsigned int vector[ N ]; // readout index static int idx = N + 1; if (static_cast<unsigned int>(idx) >= N) { if (static_cast<unsigned int>(idx) > N) { mersenne_twister_vector_init(vector, N); } mersenne_twister_vector_update(vector); idx = 0; } unsigned int e = vector[ idx++ ]; // Tempering e ^= (e >> 11); e ^= (e << 7) & 0x9D2C5680; e ^= (e << 15) & 0xEFC60000; e ^= (e >> 18); return e; } RandomGenerator::RandomGenerator( GeneratorType type ) noexcept : m_type( type ) { ::srand( static_cast<unsigned int>(time(nullptr))); } RandomGenerator::~RandomGenerator() { // empty } int RandomGenerator::get( int lower, int upper ) { int ret( 0 ); if ( GeneratorType::Standard == m_type ) { ret = ::rand() % upper + lower; } else if (GeneratorType::MersenneTwister == m_type) { ret = mersenne_twister() % upper + lower; } return ret; } } // Namespace CPPCore <|endoftext|>
<commit_before>/****************************************************************************************************** July 10, 2017 Ian A. Cosden Princeton University icosden@princeton.edu Sample Matrix-Matrix multiplication code for CoDaS-HEP Summer School Purpose: To use as a example to profile with performance tuning tools such as VTune. The code does not do anything useful and is for illustrative/educational use only. It is not meant to be exhaustive or demostrating optimal matrix-matrix multiplication techniques. Description: Code generates two matrices with random numbers. They are stored in 2D arrays (named A and B) as well as 1D arrays (a and b). There are 4 functions that multiply A and B and store the result in matrix C (or c in the 1D case). It is possible to set the percentage of time each function is called via the command line. Command line arguments: N <threshold 1> <threshold 2> <threshold 3> N: size of NxN matrix **optional**: thresholds: 4 functions are distributed between 0 and 1. mm1 is called between 0 and <threshold 1> mm2 is called between <threshold 1> and <threshold 2> mm3 is called between <threshold 2> and <threshold 3> mm4 is called between <threshold 3> and 1. Example: to call only mm1 use 1.0 0 0 to call only mm2 use 0 1.0 1.0 to call only mm3 use 0 0 1.0 to call only mm4 use 0 0 0 *******************************************************************************************************/ #include "mm.h" int main(int argc, char *argv[]) { int matrix_size; //N*N matrix double thresh_1, thresh_2, thresh_3; //read command line input //set various paramaters if(argc<2) { cout<<"ERROR: expecting integer matrix size, i.e., N for NxN matrix"<<endl; exit(1); } else { matrix_size=atoi(argv[1]); } if(argc<5) { thresh_1=0.1; thresh_2=0.3; thresh_3=0.6; cout<<"Using default thresholds: "; } else { thresh_1=atof(argv[2]); thresh_2=atof(argv[3]); thresh_3=atof(argv[4]); cout<<"Using user supplied thresholds: "; } cout<<thresh_1<<" "<<thresh_2<<" "<<thresh_3<<endl; cout<<"using matrix size:"<<matrix_size<<endl; mkl_set_num_threads(1); //needed to prevent mkl (mm4) from grabbing all available cores double **A, **B, **C; //2D arrays double *a, *b, *c; //equivalent 1D arrays A = new double*[matrix_size]; B = new double*[matrix_size]; C = new double*[matrix_size]; a = new double[matrix_size*matrix_size]; b = new double[matrix_size*matrix_size]; c = new double[matrix_size*matrix_size]; for (int i = 0 ; i < matrix_size; i++) { A[i] = new double[matrix_size]; B[i] = new double[matrix_size]; C[i] = new double[matrix_size]; } int idx; //initialize values crudely between 0 and 1 //(we don't really care what they are) for (int i=0; i<matrix_size; i++) { idx=i*matrix_size; for (int j = 0 ; j < matrix_size; j++) { A[i][j]=((double) rand() / (RAND_MAX)); B[i][j]=((double) rand() / (RAND_MAX)); C[i][j]=0.0; a[idx+j]=A[i][j]; b[idx+j]=B[i][j]; c[idx+j]=0.0; } } int max_iters=50; //number of times to call a matrix-matrix (mm) function double random_choice; //random number from rng //Depending on random number and earlier set thresholds call a matrix-multiplication //function mm1,mm2,mm3,mm4. This is done to purposely obfuscate the "hotspots" for (int r=0; r < max_iters; r++) { random_choice = ((double) rand() / (RAND_MAX)); if (random_choice<thresh_1) { zero_result(C,matrix_size); mm1(A,B,C,matrix_size); } else if (random_choice>=thresh_1 && random_choice<thresh_2) { zero_result(C,matrix_size); mm2(A,B,C,matrix_size); } else if (random_choice>=thresh_2 && random_choice<thresh_3) { zero_result_1D(c,matrix_size); mm3(a,b,c,matrix_size); } else { zero_result_1D(c,matrix_size); mm4(a,b,c,matrix_size); } } for (int i = 0 ; i < matrix_size; i++) { delete A[i]; delete B[i]; delete C[i]; } delete A; delete B; delete C; return 0; } <commit_msg>added rng seed<commit_after>/****************************************************************************************************** July 10, 2017 Ian A. Cosden Princeton University icosden@princeton.edu Sample Matrix-Matrix multiplication code for CoDaS-HEP Summer School Purpose: To use as a example to profile with performance tuning tools such as VTune. The code does not do anything useful and is for illustrative/educational use only. It is not meant to be exhaustive or demostrating optimal matrix-matrix multiplication techniques. Description: Code generates two matrices with random numbers. They are stored in 2D arrays (named A and B) as well as 1D arrays (a and b). There are 4 functions that multiply A and B and store the result in matrix C (or c in the 1D case). It is possible to set the percentage of time each function is called via the command line. Command line arguments: N <threshold 1> <threshold 2> <threshold 3> N: size of NxN matrix **optional**: thresholds: 4 functions are distributed between 0 and 1. mm1 is called between 0 and <threshold 1> mm2 is called between <threshold 1> and <threshold 2> mm3 is called between <threshold 2> and <threshold 3> mm4 is called between <threshold 3> and 1. Example: to call only mm1 use 1.0 0 0 to call only mm2 use 0 1.0 1.0 to call only mm3 use 0 0 1.0 to call only mm4 use 0 0 0 *******************************************************************************************************/ #include "mm.h" int main(int argc, char *argv[]) { int matrix_size; //N*N matrix double thresh_1, thresh_2, thresh_3; //read command line input //set various paramaters if(argc<2) { cout<<"ERROR: expecting integer matrix size, i.e., N for NxN matrix"<<endl; exit(1); } else { matrix_size=atoi(argv[1]); } if(argc<5) { thresh_1=0.1; thresh_2=0.3; thresh_3=0.6; cout<<"Using default thresholds: "; } else { thresh_1=atof(argv[2]); thresh_2=atof(argv[3]); thresh_3=atof(argv[4]); cout<<"Using user supplied thresholds: "; } cout<<thresh_1<<" "<<thresh_2<<" "<<thresh_3<<endl; cout<<"using matrix size:"<<matrix_size<<endl; mkl_set_num_threads(1); //needed to prevent mkl (mm4) from grabbing all available cores double **A, **B, **C; //2D arrays double *a, *b, *c; //equivalent 1D arrays A = new double*[matrix_size]; B = new double*[matrix_size]; C = new double*[matrix_size]; a = new double[matrix_size*matrix_size]; b = new double[matrix_size*matrix_size]; c = new double[matrix_size*matrix_size]; for (int i = 0 ; i < matrix_size; i++) { A[i] = new double[matrix_size]; B[i] = new double[matrix_size]; C[i] = new double[matrix_size]; } int idx; //initialize values crudely between 0 and 1 //(we don't really care what they are) for (int i=0; i<matrix_size; i++) { idx=i*matrix_size; for (int j = 0 ; j < matrix_size; j++) { A[i][j]=((double) rand() / (RAND_MAX)); B[i][j]=((double) rand() / (RAND_MAX)); C[i][j]=0.0; a[idx+j]=A[i][j]; b[idx+j]=B[i][j]; c[idx+j]=0.0; } } int max_iters=50; //number of times to call a matrix-matrix (mm) function double random_choice; //random number from rng srand (time(NULL)); //Depending on random number and earlier set thresholds call a matrix-multiplication //function mm1,mm2,mm3,mm4. This is done to purposely obfuscate the "hotspots" for (int r=0; r < max_iters; r++) { random_choice = ((double) rand() / (RAND_MAX)); if (random_choice<thresh_1) { zero_result(C,matrix_size); mm1(A,B,C,matrix_size); } else if (random_choice>=thresh_1 && random_choice<thresh_2) { zero_result(C,matrix_size); mm2(A,B,C,matrix_size); } else if (random_choice>=thresh_2 && random_choice<thresh_3) { zero_result_1D(c,matrix_size); mm3(a,b,c,matrix_size); } else { zero_result_1D(c,matrix_size); mm4(a,b,c,matrix_size); } } for (int i = 0 ; i < matrix_size; i++) { delete A[i]; delete B[i]; delete C[i]; } delete A; delete B; delete C; return 0; } <|endoftext|>
<commit_before>#include "../include/ex_utilities.hpp" int main() { Vector v; Vector v2(4); v.Print("empty vect"); v2.Print("size 4 vect"); int dim = 6; Vector zeros(dim, 0.0); Vector ones(dim, 1.0); Vector twos(dim, 2.0); std::cout << "Ones size: " << ones.size() << "\n"; ones.Print("ones"); zeros[0] = 2.0; zeros[1] *= 8.0; std::cout << "Modified 0th element: " << zeros[0] << " "; std::cout << "1st element: " << zeros[1] << "\n"; Vector vect_from_file(linalgcpp::ReadText("vect.text")); vect_from_file.Print("From file"); double ip = twos.Mult(ones); std::cout << "Inner product: " << ip << "\n"; double norm = twos.L2Norm(); std::cout << "Norm: " << norm << "\n"; Vector twos_normalized = twos; twos_normalized /= norm; twos_normalized.Print("twos normalized"); double two_ip = twos.Mult(twos); std::cout << "Twos Inner product: " << two_ip << "\n"; Vector threes = twos; threes += ones; threes.Print("1 + 2"); Vector fours = twos + twos; fours.Print("2 + 2"); } <commit_msg>Fix vector example when parsing from file<commit_after>#include "../include/ex_utilities.hpp" int main() { Vector v; Vector v2(4); v.Print("empty vect"); v2.Print("size 4 vect"); int dim = 6; Vector zeros(dim, 0.0); Vector ones(dim, 1.0); Vector twos(dim, 2.0); std::cout << "Ones size: " << ones.size() << "\n"; ones.Print("ones"); zeros[0] = 2.0; zeros[1] *= 8.0; std::cout << "Modified 0th element: " << zeros[0] << " "; std::cout << "1st element: " << zeros[1] << "\n"; Vector vect_from_file(linalgcpp::ReadText("data/vect4.txt")); vect_from_file.Print("From file"); double ip = twos.Mult(ones); std::cout << "Inner product: " << ip << "\n"; double norm = twos.L2Norm(); std::cout << "Norm: " << norm << "\n"; Vector twos_normalized = twos; twos_normalized /= norm; twos_normalized.Print("twos normalized"); double two_ip = twos.Mult(twos); std::cout << "Twos Inner product: " << two_ip << "\n"; Vector threes = twos; threes += ones; threes.Print("1 + 2"); Vector fours = twos + twos; fours.Print("2 + 2"); } <|endoftext|>
<commit_before>#pragma once #include <memory> #include <string> #include <unordered_map> #include "human_interface_device.hpp" class event_grabber final { public: event_grabber(void) { manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); if (!manager_) { return; } auto device_matching_dictionaries = create_device_matching_dictionaries(); if (device_matching_dictionaries) { IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries); CFRelease(device_matching_dictionaries); IOHIDManagerRegisterDeviceMatchingCallback(manager_, device_matching_callback, this); IOHIDManagerRegisterDeviceRemovalCallback(manager_, device_removal_callback, this); IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); } } ~event_grabber(void) { if (manager_) { IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); CFRelease(manager_); manager_ = nullptr; } } private: CFDictionaryRef _Nonnull create_device_matching_dictionary(uint32_t usage_page, uint32_t usage) { auto device_matching_dictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (!device_matching_dictionary) { goto finish; } // usage_page if (!usage_page) { goto finish; } else { auto number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage_page); if (!number) { goto finish; } CFDictionarySetValue(device_matching_dictionary, CFSTR(kIOHIDDeviceUsagePageKey), number); CFRelease(number); } // usage (The usage is only valid if the usage page is also defined) if (!usage) { goto finish; } else { auto number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage); if (!number) { goto finish; } CFDictionarySetValue(device_matching_dictionary, CFSTR(kIOHIDDeviceUsageKey), number); CFRelease(number); } finish: return device_matching_dictionary; } CFArrayRef _Nullable create_device_matching_dictionaries(void) { auto device_matching_dictionaries = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); if (!device_matching_dictionaries) { return nullptr; } // kHIDUsage_GD_Keyboard { auto device_matching_dictionary = create_device_matching_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard); if (device_matching_dictionary) { CFArrayAppendValue(device_matching_dictionaries, device_matching_dictionary); CFRelease(device_matching_dictionary); } } #if 0 // kHIDUsage_GD_Mouse { auto device_matching_dictionary = create_device_matching_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse); if (device_matching_dictionary) { CFArrayAppendValue(device_matching_dictionaries, device_matching_dictionary); CFRelease(device_matching_dictionary); } } #endif return device_matching_dictionaries; } static void device_matching_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) { if (result != kIOReturnSuccess) { return; } auto self = static_cast<event_grabber*>(context); if (!self) { return; } if (!device) { return; } auto dev = std::make_shared<human_interface_device>(device); if (!dev) { return; } std::cout << "matching: " << std::endl << " vendor_id:0x" << std::hex << dev->get_vendor_id() << std::endl << " product_id:0x" << std::hex << dev->get_product_id() << std::endl << " location_id:0x" << std::hex << dev->get_location_id() << std::endl << " serial_number:" << dev->get_serial_number_string() << std::endl << " " << dev->get_manufacturer() << std::endl << " " << dev->get_product() << std::endl; if (dev->get_serial_number_string() == "org.pqrs.driver.VirtualHIDKeyboard") { dev->open(); self->virtual_keyboard_ = dev; } else { //if (dev->get_manufacturer() != "pqrs.org") { if (dev->get_manufacturer() == "Apple Inc.") { dev->grab(queue_value_available_callback, self); } } (self->hids_)[device] = dev; } static void device_removal_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) { if (result != kIOReturnSuccess) { return; } auto self = static_cast<event_grabber*>(context); if (!self) { return; } if (!device) { return; } auto it = (self->hids_).find(device); if (it == (self->hids_).end()) { std::cout << "unknown device has been removed" << std::endl; } else { auto dev = it->second; if (dev) { std::cout << "removal vendor_id:0x" << std::hex << dev->get_vendor_id() << " product_id:0x" << std::hex << dev->get_product_id() << std::endl; (self->hids_).erase(it); } } } static void queue_value_available_callback(void* _Nullable context, IOReturn result, void* _Nullable sender) { std::cout << "queue_value_available_callback" << std::endl; auto queue = static_cast<IOHIDQueueRef>(sender); while (true) { auto value = IOHIDQueueCopyNextValueWithTimeout(queue, 0.); if (!value) { break; } std::cout << "value arrived" << std::endl; CFRelease(value); } } IOHIDManagerRef _Nullable manager_; std::unordered_map<IOHIDDeviceRef, std::shared_ptr<human_interface_device>> hids_; std::weak_ptr<human_interface_device> virtual_keyboard_; }; <commit_msg>dump element information<commit_after>#pragma once #include <memory> #include <string> #include <unordered_map> #include "human_interface_device.hpp" class event_grabber final { public: event_grabber(void) { manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); if (!manager_) { return; } auto device_matching_dictionaries = create_device_matching_dictionaries(); if (device_matching_dictionaries) { IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries); CFRelease(device_matching_dictionaries); IOHIDManagerRegisterDeviceMatchingCallback(manager_, device_matching_callback, this); IOHIDManagerRegisterDeviceRemovalCallback(manager_, device_removal_callback, this); IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); } } ~event_grabber(void) { if (manager_) { IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); CFRelease(manager_); manager_ = nullptr; } } private: CFDictionaryRef _Nonnull create_device_matching_dictionary(uint32_t usage_page, uint32_t usage) { auto device_matching_dictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (!device_matching_dictionary) { goto finish; } // usage_page if (!usage_page) { goto finish; } else { auto number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage_page); if (!number) { goto finish; } CFDictionarySetValue(device_matching_dictionary, CFSTR(kIOHIDDeviceUsagePageKey), number); CFRelease(number); } // usage (The usage is only valid if the usage page is also defined) if (!usage) { goto finish; } else { auto number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage); if (!number) { goto finish; } CFDictionarySetValue(device_matching_dictionary, CFSTR(kIOHIDDeviceUsageKey), number); CFRelease(number); } finish: return device_matching_dictionary; } CFArrayRef _Nullable create_device_matching_dictionaries(void) { auto device_matching_dictionaries = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); if (!device_matching_dictionaries) { return nullptr; } // kHIDUsage_GD_Keyboard { auto device_matching_dictionary = create_device_matching_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard); if (device_matching_dictionary) { CFArrayAppendValue(device_matching_dictionaries, device_matching_dictionary); CFRelease(device_matching_dictionary); } } #if 0 // kHIDUsage_GD_Mouse { auto device_matching_dictionary = create_device_matching_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse); if (device_matching_dictionary) { CFArrayAppendValue(device_matching_dictionaries, device_matching_dictionary); CFRelease(device_matching_dictionary); } } #endif return device_matching_dictionaries; } static void device_matching_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) { if (result != kIOReturnSuccess) { return; } auto self = static_cast<event_grabber*>(context); if (!self) { return; } if (!device) { return; } auto dev = std::make_shared<human_interface_device>(device); if (!dev) { return; } std::cout << "matching: " << std::endl << " vendor_id:0x" << std::hex << dev->get_vendor_id() << std::endl << " product_id:0x" << std::hex << dev->get_product_id() << std::endl << " location_id:0x" << std::hex << dev->get_location_id() << std::endl << " serial_number:" << dev->get_serial_number_string() << std::endl << " " << dev->get_manufacturer() << std::endl << " " << dev->get_product() << std::endl; if (dev->get_serial_number_string() == "org.pqrs.driver.VirtualHIDKeyboard") { dev->open(); self->virtual_keyboard_ = dev; } else { //if (dev->get_manufacturer() != "pqrs.org") { if (dev->get_manufacturer() == "Apple Inc.") { dev->grab(queue_value_available_callback, self); } } (self->hids_)[device] = dev; } static void device_removal_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) { if (result != kIOReturnSuccess) { return; } auto self = static_cast<event_grabber*>(context); if (!self) { return; } if (!device) { return; } auto it = (self->hids_).find(device); if (it == (self->hids_).end()) { std::cout << "unknown device has been removed" << std::endl; } else { auto dev = it->second; if (dev) { std::cout << "removal vendor_id:0x" << std::hex << dev->get_vendor_id() << " product_id:0x" << std::hex << dev->get_product_id() << std::endl; (self->hids_).erase(it); } } } static void queue_value_available_callback(void* _Nullable context, IOReturn result, void* _Nullable sender) { auto queue = static_cast<IOHIDQueueRef>(sender); while (true) { auto value = IOHIDQueueCopyNextValueWithTimeout(queue, 0.); if (!value) { break; } auto element = IOHIDValueGetElement(value); auto integerValue = IOHIDValueGetIntegerValue(value); if (element) { auto usagePage = IOHIDElementGetUsagePage(element); auto usage = IOHIDElementGetUsage(element); std::cout << "element" << std::endl << " usagePage:0x" << std::hex << usagePage << std::endl << " usage:0x" << std::hex << usage << std::endl << " type:" << IOHIDElementGetType(element) << std::endl << " integerValue:" << integerValue << std::endl ; } std::cout << "value arrived" << std::endl; CFRelease(value); } } IOHIDManagerRef _Nullable manager_; std::unordered_map<IOHIDDeviceRef, std::shared_ptr<human_interface_device>> hids_; std::weak_ptr<human_interface_device> virtual_keyboard_; }; <|endoftext|>
<commit_before><commit_msg>flattening custom types ranges<commit_after><|endoftext|>
<commit_before>#include <initializer_list> #include <map> #include <sstream> #include <string> #include <gtk/gtk.h> /// List of unit types we handle. enum class ConversionUnit { Inch, Point, Twip, M, Cm, Mm, Mm100, Emu }; /// Hold references to all data needed to perform a conversion. class Conversion { public: GtkEntry* _amount; GtkComboBox* _from; GtkComboBox* _to; GtkLabel* _result; Conversion(); }; Conversion::Conversion() : _amount(nullptr), _from(nullptr), _to(nullptr), _result(nullptr) { } namespace { void initAmount(GtkWidget* grid, Conversion& conversion) { GtkWidget* amount = gtk_entry_new(); conversion._amount = GTK_ENTRY(amount); gtk_grid_attach(GTK_GRID(grid), amount, 0, 0, 1, 1); } GtkComboBox* initUnit(GtkWidget* grid, int active, int top) { GtkWidget* unitCombo = gtk_combo_box_text_new(); std::initializer_list<std::string> units = {"inch", "point", "twip", "m", "cm", "mm", "mm100", "emu"}; for (const auto& unit : units) gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(unitCombo), nullptr, unit.c_str()); gtk_combo_box_set_active(GTK_COMBO_BOX(unitCombo), active); gtk_grid_attach(GTK_GRID(grid), unitCombo, 1, top, 1, 1); return GTK_COMBO_BOX(unitCombo); } void initResult(GtkWidget* grid, Conversion& conversion) { GtkWidget* result = gtk_label_new(""); conversion._result = GTK_LABEL(result); gtk_label_set_selectable(conversion._result, TRUE); gtk_grid_attach(GTK_GRID(grid), result, 0, 1, 1, 1); } void convert(GtkWidget* /*widget*/, gpointer userData) { Conversion* conversion = static_cast<Conversion*>(userData); static std::map<ConversionUnit, double> units; if (units.empty()) { units[ConversionUnit::Inch] = 914400.0; units[ConversionUnit::Point] = 914400.0 / 72; units[ConversionUnit::Twip] = 914400.0 / 72 / 20; units[ConversionUnit::M] = 360 * 100000; units[ConversionUnit::Cm] = 360 * 1000; units[ConversionUnit::Mm] = 360 * 100; units[ConversionUnit::Mm100] = 360; units[ConversionUnit::Emu] = 1; } std::string text; // Convert to EMU. try { double amount = std::stod(gtk_entry_get_text(conversion->_amount)); auto from = static_cast<ConversionUnit>( gtk_combo_box_get_active(conversion->_from)); double emu = amount * units[from]; auto to = static_cast<ConversionUnit>( gtk_combo_box_get_active(conversion->_to)); double ret = emu / units[to]; text = std::to_string(ret); } catch (const std::invalid_argument& exception) { std::stringstream ss; ss << "invalid argument: " << exception.what(); text = ss.str(); } gtk_label_set_text(conversion->_result, text.c_str()); } void initConvert(GtkWidget* grid, Conversion& conversion) { GtkWidget* convertButton = gtk_button_new_with_label("Convert"); gtk_grid_attach(GTK_GRID(grid), convertButton, 0, 2, 1, 1); g_signal_connect(convertButton, "clicked", G_CALLBACK(convert), &conversion); } void initQuit(GtkWidget* grid) { GtkWidget* quit = gtk_button_new_with_label("Quit"); g_signal_connect(quit, "clicked", G_CALLBACK(gtk_main_quit), nullptr); gtk_grid_attach(GTK_GRID(grid), quit, 1, 2, 1, 1); } void initControls(GtkWidget* window, Conversion& conversion) { GtkWidget* grid = gtk_grid_new(); initAmount(grid, conversion); conversion._from = initUnit(grid, 0, 0); conversion._to = initUnit(grid, 1, 1); initResult(grid, conversion); initConvert(grid, conversion); initQuit(grid); gtk_container_add(GTK_CONTAINER(window), grid); } } // anonymous namespace int main(int argc, char** argv) { gtk_init(&argc, &argv); GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window), "gtktpconv"); g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), nullptr); Conversion conversion; initControls(window, conversion); gtk_widget_show_all(window); gtk_main(); return 0; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>gtktpconv: separate UI and logic pieces<commit_after>#include <initializer_list> #include <map> #include <sstream> #include <string> #include <gtk/gtk.h> namespace tpconv { /// List of unit types we handle. enum class ConversionUnit { Inch, Point, Twip, M, Cm, Mm, Mm100, Emu }; /// List of string representation of ConversionUnit elements. std::initializer_list<std::string> getUnitNames() { static std::initializer_list<std::string> units = {"inch", "point", "twip", "m", "cm", "mm", "mm100", "emu"}; return units; } double convert(double amount, ConversionUnit from, ConversionUnit to) { static std::map<ConversionUnit, double> units; if (units.empty()) { units[ConversionUnit::Inch] = 914400.0; units[ConversionUnit::Point] = 914400.0 / 72; units[ConversionUnit::Twip] = 914400.0 / 72 / 20; units[ConversionUnit::M] = 360 * 100000; units[ConversionUnit::Cm] = 360 * 1000; units[ConversionUnit::Mm] = 360 * 100; units[ConversionUnit::Mm100] = 360; units[ConversionUnit::Emu] = 1; } // Convert to EMU. double emu = amount * units[from]; return emu / units[to]; } } // namespace tpconv /// Hold Gtk references to all data needed to perform a conversion. class Conversion { GtkEntry* _amount; GtkComboBox* _from; GtkComboBox* _to; GtkLabel* _result; void initAmount(GtkWidget* grid); static GtkComboBox* initUnit(GtkWidget* grid, int active, int top); void initResult(GtkWidget* grid); void initConvert(GtkWidget* grid); static void convert(GtkWidget* widget, gpointer userData); void convertImpl(); static void initQuit(GtkWidget* grid); public: Conversion(); void initControls(GtkWidget* window); }; Conversion::Conversion() : _amount(nullptr), _from(nullptr), _to(nullptr), _result(nullptr) { } void Conversion::initAmount(GtkWidget* grid) { GtkWidget* amount = gtk_entry_new(); _amount = GTK_ENTRY(amount); gtk_grid_attach(GTK_GRID(grid), amount, 0, 0, 1, 1); } GtkComboBox* Conversion::initUnit(GtkWidget* grid, int active, int top) { GtkWidget* unitCombo = gtk_combo_box_text_new(); for (const auto& unit : tpconv::getUnitNames()) gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(unitCombo), nullptr, unit.c_str()); gtk_combo_box_set_active(GTK_COMBO_BOX(unitCombo), active); gtk_grid_attach(GTK_GRID(grid), unitCombo, 1, top, 1, 1); return GTK_COMBO_BOX(unitCombo); } void Conversion::initResult(GtkWidget* grid) { GtkWidget* result = gtk_label_new(""); _result = GTK_LABEL(result); gtk_label_set_selectable(_result, TRUE); gtk_grid_attach(GTK_GRID(grid), result, 0, 1, 1, 1); } void Conversion::initConvert(GtkWidget* grid) { GtkWidget* convertButton = gtk_button_new_with_label("Convert"); gtk_grid_attach(GTK_GRID(grid), convertButton, 0, 2, 1, 1); g_signal_connect(convertButton, "clicked", G_CALLBACK(Conversion::convert), this); } void Conversion::initControls(GtkWidget* window) { GtkWidget* grid = gtk_grid_new(); initAmount(grid); _from = Conversion::initUnit(grid, 0, 0); _to = Conversion::initUnit(grid, 1, 1); initResult(grid); initConvert(grid); initQuit(grid); gtk_container_add(GTK_CONTAINER(window), grid); } void Conversion::convert(GtkWidget* /*widget*/, gpointer userData) { Conversion* conversion = static_cast<Conversion*>(userData); conversion->convertImpl(); } void Conversion::convertImpl() { std::string text; try { double amount = std::stod(gtk_entry_get_text(_amount)); auto from = static_cast<tpconv::ConversionUnit>( gtk_combo_box_get_active(_from)); auto to = static_cast<tpconv::ConversionUnit>(gtk_combo_box_get_active(_to)); double ret = tpconv::convert(amount, from, to); text = std::to_string(ret); } catch (const std::invalid_argument& exception) { std::stringstream ss; ss << "invalid argument: " << exception.what(); text = ss.str(); } gtk_label_set_text(_result, text.c_str()); } void Conversion::initQuit(GtkWidget* grid) { GtkWidget* quit = gtk_button_new_with_label("Quit"); g_signal_connect(quit, "clicked", G_CALLBACK(gtk_main_quit), nullptr); gtk_grid_attach(GTK_GRID(grid), quit, 1, 2, 1, 1); } int main(int argc, char** argv) { gtk_init(&argc, &argv); GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window), "gtktpconv"); g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), nullptr); Conversion conversion; conversion.initControls(window); gtk_widget_show_all(window); gtk_main(); return 0; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> #include <sstream> #include <iomanip> #include "orc_proto.pb.h" using namespace org::apache::hadoop::hive::ql::io::orc; long getTotalPaddingSize(Footer footer); StripeFooter readStripeFooter(StripeInformation stripe); std::ifstream input; int main(int argc, char* argv[]) { GOOGLE_PROTOBUF_VERIFY_VERSION; // Read the input arguments const char ROWINDEX_PREFIX[] = "--rowindex="; const int ROWINDEX_PREFIX_LENGTH = strlen(ROWINDEX_PREFIX); std::vector<char*> files; std::vector<int> rowIndexCols; char* pChar ; for (int i=1; i<argc; i++) { if (argv[i][0]=='-' & argv[i][1]=='-') { pChar = strstr(argv[i], ROWINDEX_PREFIX); if (pChar == argv[i]) { // the argument string starts with ROWINDEX_PREFIX pChar = strtok(argv[i]+ROWINDEX_PREFIX_LENGTH,","); while (pChar != NULL) { rowIndexCols.push_back(atoi(pChar)); pChar = strtok(NULL,","); }; } else { std::cout << "Unknown argument " << argv[i] << std::endl ; std::cout << "Usage: localfiledump <filename1> [... <filenameN>] [--rowindex=i1,i2,...,iN]" << std::endl ; }; } else { files.push_back(argv[i]); }; }; for(int fileIx=0; fileIx<files.size(); fileIx++) { std::cout << "Structure for " << files[fileIx] << std::endl; // FIXIT: Instead of allocating memory for each part of the ORC file (postscript, footer, etc), // find a way to provide the stream + initial position + length to the ParseFromXXX() functions // Java implementation of protobuf has it, but C++ seems to lack. char* buffer ; // Determine the file size // FIXIT: Should be done using filesystem info input.open(files[fileIx], std::ios::in | std::ios::binary); input.seekg(0,input.end); unsigned int fileSize = input.tellg(); // Read the postscript size input.seekg(fileSize-1); unsigned int postscriptSize = (int)input.get() ; // Read the postscript input.seekg(fileSize - postscriptSize-1); buffer = new char[postscriptSize]; input.read(buffer, postscriptSize); PostScript postscript ; postscript.ParseFromArray(buffer, postscriptSize); delete[] buffer; // Everything but the postscript is compressed //CompressionCodec codec ; switch (postscript.compression()) { case NONE: //codec = NULL; break; case ZLIB: //codec = ZlibCodec(); break; case SNAPPY: //codec = SnappyCodec(); break; case LZO: //codec = LzoCodec(); break; default: std::cout << "Unsupported compression!" << std::endl ; input.close(); return -1; }; int footerSize = postscript.footerlength(); int metadataSize = postscript.metadatalength(); // Read the metadata input.seekg(fileSize - 1 - postscriptSize - footerSize - metadataSize); buffer = new char[metadataSize]; input.read(buffer, metadataSize); Metadata metadata ; metadata.ParseFromArray(buffer, metadataSize); delete[] buffer; // Read the footer //input.seekg(fileSize -1 - postscriptSize-footerSize); buffer = new char[footerSize]; input.read(buffer, footerSize); Footer footer ; footer.ParseFromArray(buffer, footerSize); delete[] buffer; std::cout << "Rows: " << footer.numberofrows() << std::endl; std::cout << "Compression: " << postscript.compression() << std::endl; if (postscript.compression() != NONE) std::cout << "Compression size: " << postscript.compressionblocksize() << std::endl; std::cout << "Type: " ; for (int typeIx=0; typeIx < footer.types_size(); typeIx++) { Type type = footer.types(typeIx); type.PrintDebugString(); }; std::cout << "\nStripe Statistics:" << std::endl; StripeInformation stripe ; Stream section; ColumnEncoding encoding; for (int stripeIx=0; stripeIx<footer.stripes_size(); stripeIx++) { std::cout << " Stripe " << stripeIx+1 <<": " << std::endl ; stripe = footer.stripes(stripeIx); stripe.PrintDebugString(); long offset = stripe.offset() + stripe.indexlength() + stripe.datalength(); int tailLength = stripe.footerlength(); // read the stripe footer input.seekg(offset); buffer = new char[tailLength]; input.read(buffer, tailLength); StripeFooter stripeFooter; stripeFooter.ParseFromArray(buffer, tailLength); //stripeFooter.PrintDebugString(); long stripeStart = stripe.offset(); long sectionStart = stripeStart; for (int streamIx=0; streamIx<stripeFooter.streams_size(); streamIx++) { section = stripeFooter.streams(streamIx); std::cout << " Stream: column " << section.column() << " section " << section.kind() << " start: " << sectionStart << " length " << section.length() << std::endl; sectionStart += section.length(); }; for (int columnIx=0; columnIx<stripeFooter.columns_size(); columnIx++) { encoding = stripeFooter.columns(columnIx); std::cout << " Encoding column " << columnIx << ": " << encoding.kind() ; if (encoding.kind() == ColumnEncoding_Kind_DICTIONARY || encoding.kind() == ColumnEncoding_Kind_DICTIONARY_V2) std::cout << "[" << encoding.dictionarysize() << "]"; std::cout << std::endl; }; /* if (!rowIndexCols.empty()) { std::vector<RowIndex> indices; long offset = stripeStart; stripeFooter = readStripeFooter(stripe); for(int streamIx=0; streamIx< stripeFooter.streams_size();streamIx++) { section = stripeFooter.streams(streamIx); if (section.kind() == Stream_Kind_ROW_INDEX) { int col = section.column(); int streamLength = section.length(); char* bufferRowIndex = new char[streamLength]; input.seekg(offset); input.read(bufferRowIndex, streamLength); RowIndex rowIndex; rowIndex.ParseFromArray(bufferRowIndex, streamLength); delete[] bufferRowIndex ; indices.push_back(rowIndex); }; offset += section.length(); }; for (int rowIx = 0; rowIx < rowIndexCols.size(); rowIx++) { int col = rowIndexCols[rowIx]; std::cout << " Row group index column " << col << ":" ; if (col >= indices.size()) { std::cout << " not found" << std::endl ; continue; }; RowIndex index = indices[col]; for (int entryIx = 0; entryIx < index.entry_size(); ++entryIx) { std::cout << "\n Entry " << entryIx << ":"; RowIndexEntry entry = index.entry(entryIx); ColumnStatistics colStats = entry.statistics(); std::cout << " number of values: " << colStats.numberofvalues() ; for (int posIx = 0; posIx < entry.positions_size(); ++posIx) { if (posIx != 0) std::cout << ","; std::cout << entry.positions(posIx); }; }; std::cout <<std::endl ; }; };*/ }; long paddedBytes = getTotalPaddingSize(footer); // empty ORC file is ~45 bytes. Assumption here is file length always >0 double percentPadding = ((double) paddedBytes / (double) fileSize) * 100; std::cout << "File length: " << fileSize << " bytes" << std::endl; std::cout <<"Padding length: " << paddedBytes << " bytes" << std::endl; std::cout <<"Padding ratio: " << std::fixed << std::setprecision(2) << percentPadding << " %" << std::endl; input.close(); }; google::protobuf::ShutdownProtobufLibrary(); return 0; } StripeFooter readStripeFooter(StripeInformation stripe) { long offset = stripe.offset() + stripe.indexlength() + stripe.datalength(); int tailLength = (int) stripe.footerlength(); char* buffer = new char[tailLength]; input.seekg(offset); input.read(buffer, tailLength); StripeFooter stripeFooter ; stripeFooter.ParseFromArray(buffer, tailLength); delete[] buffer; return stripeFooter; } long getTotalPaddingSize(Footer footer) { long paddedBytes = 0; StripeInformation stripe; for (int stripeIx=1; stripeIx<footer.stripes_size(); stripeIx++) { stripe = footer.stripes(stripeIx-1); long prevStripeOffset = stripe.offset(); long prevStripeLen = stripe.datalength() + stripe.indexlength() + stripe.footerlength(); paddedBytes += footer.stripes(stripeIx).offset() - (prevStripeOffset + prevStripeLen); }; return paddedBytes; } <commit_msg>Modified LocalFileDump.cc to print more detailed metadata information.<commit_after>#include <iostream> #include <fstream> #include <string> #include <sstream> #include <iomanip> #include "orc_proto.pb.h" using namespace org::apache::hadoop::hive::ql::io::orc; long getTotalPaddingSize(Footer footer); StripeFooter readStripeFooter(StripeInformation stripe); std::ifstream input; int main(int argc, char* argv[]) { GOOGLE_PROTOBUF_VERIFY_VERSION; // Read the input arguments const char ROWINDEX_PREFIX[] = "--rowindex="; const int ROWINDEX_PREFIX_LENGTH = strlen(ROWINDEX_PREFIX); std::vector<char*> files; std::vector<int> rowIndexCols; char* pChar ; for (int i=1; i<argc; i++) { if (argv[i][0]=='-' & argv[i][1]=='-') { pChar = strstr(argv[i], ROWINDEX_PREFIX); if (pChar == argv[i]) { // the argument string starts with ROWINDEX_PREFIX pChar = strtok(argv[i]+ROWINDEX_PREFIX_LENGTH,","); while (pChar != NULL) { rowIndexCols.push_back(atoi(pChar)); pChar = strtok(NULL,","); }; } else { std::cout << "Unknown argument " << argv[i] << std::endl ; std::cout << "Usage: localfiledump <filename1> [... <filenameN>] [--rowindex=i1,i2,...,iN]" << std::endl ; }; } else { files.push_back(argv[i]); }; }; for(int fileIx=0; fileIx<files.size(); fileIx++) { std::cout << "Structure for " << files[fileIx] << std::endl; // FIXIT: Instead of allocating memory for each part of the ORC file (postscript, footer, etc), // find a way to provide the stream + initial position + length to the ParseFromXXX() functions // Java implementation of protobuf has it, but C++ seems to lack. char* buffer ; // Determine the file size // FIXIT: Should be done using filesystem info input.open(files[fileIx], std::ios::in | std::ios::binary); input.seekg(0,input.end); unsigned int fileSize = input.tellg(); // Read the postscript size input.seekg(fileSize-1); unsigned int postscriptSize = (int)input.get() ; // Read the postscript input.seekg(fileSize - postscriptSize-1); buffer = new char[postscriptSize]; input.read(buffer, postscriptSize); PostScript postscript ; postscript.ParseFromArray(buffer, postscriptSize); delete[] buffer; std::cout << std::endl << "Postscript: " << std::endl ; postscript.PrintDebugString(); // Everything but the postscript is compressed //CompressionCodec codec ; switch (postscript.compression()) { case NONE: //codec = NULL; break; case ZLIB: //codec = ZlibCodec(); break; case SNAPPY: //codec = SnappyCodec(); break; case LZO: //codec = LzoCodec(); break; default: std::cout << "Unsupported compression!" << std::endl ; input.close(); return -1; }; int footerSize = postscript.footerlength(); int metadataSize = postscript.metadatalength(); // Read the metadata input.seekg(fileSize - 1 - postscriptSize - footerSize - metadataSize); buffer = new char[metadataSize]; input.read(buffer, metadataSize); Metadata metadata ; metadata.ParseFromArray(buffer, metadataSize); delete[] buffer; std::cout << std::endl << "Metadata: " << std::endl ; postscript.PrintDebugString(); // Read the footer //input.seekg(fileSize -1 - postscriptSize-footerSize); buffer = new char[footerSize]; input.read(buffer, footerSize); Footer footer ; footer.ParseFromArray(buffer, footerSize); delete[] buffer; std::cout << std::endl << "Footer: " << std::endl ; postscript.PrintDebugString(); std::cout << std::endl << "Rows: " << footer.numberofrows() << std::endl; std::cout << "Compression: " << postscript.compression() << std::endl; if (postscript.compression() != NONE) std::cout << "Compression size: " << postscript.compressionblocksize() << std::endl; std::cout << "Type: " ; for (int typeIx=0; typeIx < footer.types_size(); typeIx++) { Type type = footer.types(typeIx); type.PrintDebugString(); }; std::cout << "\nStripe Statistics:" << std::endl; StripeInformation stripe ; Stream section; ColumnEncoding encoding; for (int stripeIx=0; stripeIx<footer.stripes_size(); stripeIx++) { std::cout << " Stripe " << stripeIx+1 <<": " << std::endl ; stripe = footer.stripes(stripeIx); stripe.PrintDebugString(); long offset = stripe.offset() + stripe.indexlength() + stripe.datalength(); int tailLength = stripe.footerlength(); // read the stripe footer input.seekg(offset); buffer = new char[tailLength]; input.read(buffer, tailLength); StripeFooter stripeFooter; stripeFooter.ParseFromArray(buffer, tailLength); //stripeFooter.PrintDebugString(); long stripeStart = stripe.offset(); long sectionStart = stripeStart; for (int streamIx=0; streamIx<stripeFooter.streams_size(); streamIx++) { section = stripeFooter.streams(streamIx); std::cout << " Stream: column " << section.column() << " section " << section.kind() << " start: " << sectionStart << " length " << section.length() << std::endl; sectionStart += section.length(); }; for (int columnIx=0; columnIx<stripeFooter.columns_size(); columnIx++) { encoding = stripeFooter.columns(columnIx); std::cout << " Encoding column " << columnIx << ": " << encoding.kind() ; if (encoding.kind() == ColumnEncoding_Kind_DICTIONARY || encoding.kind() == ColumnEncoding_Kind_DICTIONARY_V2) std::cout << "[" << encoding.dictionarysize() << "]"; std::cout << std::endl; }; /* if (!rowIndexCols.empty()) { std::vector<RowIndex> indices; long offset = stripeStart; stripeFooter = readStripeFooter(stripe); for(int streamIx=0; streamIx< stripeFooter.streams_size();streamIx++) { section = stripeFooter.streams(streamIx); if (section.kind() == Stream_Kind_ROW_INDEX) { int col = section.column(); int streamLength = section.length(); char* bufferRowIndex = new char[streamLength]; input.seekg(offset); input.read(bufferRowIndex, streamLength); RowIndex rowIndex; rowIndex.ParseFromArray(bufferRowIndex, streamLength); delete[] bufferRowIndex ; indices.push_back(rowIndex); }; offset += section.length(); }; for (int rowIx = 0; rowIx < rowIndexCols.size(); rowIx++) { int col = rowIndexCols[rowIx]; std::cout << " Row group index column " << col << ":" ; if (col >= indices.size()) { std::cout << " not found" << std::endl ; continue; }; RowIndex index = indices[col]; for (int entryIx = 0; entryIx < index.entry_size(); ++entryIx) { std::cout << "\n Entry " << entryIx << ":"; RowIndexEntry entry = index.entry(entryIx); ColumnStatistics colStats = entry.statistics(); std::cout << " number of values: " << colStats.numberofvalues() ; for (int posIx = 0; posIx < entry.positions_size(); ++posIx) { if (posIx != 0) std::cout << ","; std::cout << entry.positions(posIx); }; }; std::cout <<std::endl ; }; };*/ }; long paddedBytes = getTotalPaddingSize(footer); // empty ORC file is ~45 bytes. Assumption here is file length always >0 double percentPadding = ((double) paddedBytes / (double) fileSize) * 100; std::cout << "File length: " << fileSize << " bytes" << std::endl; std::cout <<"Padding length: " << paddedBytes << " bytes" << std::endl; std::cout <<"Padding ratio: " << std::fixed << std::setprecision(2) << percentPadding << " %" << std::endl; input.close(); }; google::protobuf::ShutdownProtobufLibrary(); return 0; } StripeFooter readStripeFooter(StripeInformation stripe) { long offset = stripe.offset() + stripe.indexlength() + stripe.datalength(); int tailLength = (int) stripe.footerlength(); char* buffer = new char[tailLength]; input.seekg(offset); input.read(buffer, tailLength); StripeFooter stripeFooter ; stripeFooter.ParseFromArray(buffer, tailLength); delete[] buffer; return stripeFooter; } long getTotalPaddingSize(Footer footer) { long paddedBytes = 0; StripeInformation stripe; for (int stripeIx=1; stripeIx<footer.stripes_size(); stripeIx++) { stripe = footer.stripes(stripeIx-1); long prevStripeOffset = stripe.offset(); long prevStripeLen = stripe.datalength() + stripe.indexlength() + stripe.footerlength(); paddedBytes += footer.stripes(stripeIx).offset() - (prevStripeOffset + prevStripeLen); }; return paddedBytes; } <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include <mesos/secret/resolver.hpp> #include <process/future.hpp> #include <process/gtest.hpp> #include <stout/gtest.hpp> #include "tests/mesos.hpp" using process::Future; using process::Owned; using mesos::internal::slave::Fetcher; using mesos::internal::slave::MesosContainerizer; using mesos::master::detector::MasterDetector; using std::string; namespace mesos { namespace internal { namespace tests { const char SECRET_VALUE[] = "password"; const char SECRET_ENV_NAME[] = "My_SeCrEt"; class EnvironmentSecretIsolatorTest : public MesosTest {}; // This test verifies that the environment secrets are resolved when launching a // task. TEST_F(EnvironmentSecretIsolatorTest, ResolveSecret) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); mesos::internal::slave::Flags flags = CreateSlaveFlags(); Fetcher fetcher(flags); Try<SecretResolver*> secretResolver = SecretResolver::create(); EXPECT_SOME(secretResolver); Try<MesosContainerizer*> containerizer = MesosContainerizer::create(flags, false, &fetcher, secretResolver.get()); EXPECT_SOME(containerizer); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), containerizer.get()); ASSERT_SOME(slave); MockScheduler sched; MesosSchedulerDriver driver( &sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL); EXPECT_CALL(sched, registered(&driver, _, _)); Future<std::vector<Offer>> offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(offers); EXPECT_FALSE(offers->empty()); const string commandString = strings::format( "env; test \"$%s\" = \"%s\"", SECRET_ENV_NAME, SECRET_VALUE).get(); CommandInfo command; command.set_value(commandString); // Request a secret. // TODO(kapil): Update createEnvironment() to support secrets. mesos::Environment::Variable *env = command.mutable_environment()->add_variables(); env->set_name(SECRET_ENV_NAME); env->set_type(mesos::Environment::Variable::SECRET); mesos::Secret* secret = env->mutable_secret(); secret->set_type(Secret::VALUE); secret->mutable_value()->set_data(SECRET_VALUE); TaskInfo task = createTask( offers.get()[0].slave_id(), Resources::parse("cpus:0.1;mem:32").get(), command); // NOTE: Successful tasks will output two status updates. Future<TaskStatus> statusRunning; Future<TaskStatus> statusFinished; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusRunning)) .WillOnce(FutureArg<1>(&statusFinished)); driver.launchTasks(offers.get()[0].id(), {task}); AWAIT_READY(statusRunning); EXPECT_EQ(TASK_RUNNING, statusRunning.get().state()); AWAIT_READY(statusFinished); EXPECT_EQ(TASK_FINISHED, statusFinished.get().state()); driver.stop(); driver.join(); } } // namespace tests { } // namespace internal { } // namespace mesos { <commit_msg>Added a test that uses environment secrets and the DefaultExecutor.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include <mesos/secret/resolver.hpp> #include <process/future.hpp> #include <process/gtest.hpp> #include <stout/gtest.hpp> #include "tests/mesos.hpp" using process::Future; using process::Owned; using mesos::internal::slave::Fetcher; using mesos::internal::slave::MesosContainerizer; using mesos::master::detector::MasterDetector; using std::string; namespace mesos { namespace internal { namespace tests { const char SECRET_VALUE[] = "password"; const char SECRET_ENV_NAME[] = "My_SeCrEt"; class EnvironmentSecretIsolatorTest : public MesosTest {}; // This test verifies that the environment secrets are resolved when launching a // task. TEST_F(EnvironmentSecretIsolatorTest, ResolveSecret) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); mesos::internal::slave::Flags flags = CreateSlaveFlags(); Fetcher fetcher(flags); Try<SecretResolver*> secretResolver = SecretResolver::create(); EXPECT_SOME(secretResolver); Try<MesosContainerizer*> containerizer = MesosContainerizer::create(flags, false, &fetcher, secretResolver.get()); EXPECT_SOME(containerizer); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), containerizer.get()); ASSERT_SOME(slave); MockScheduler sched; MesosSchedulerDriver driver( &sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL); EXPECT_CALL(sched, registered(&driver, _, _)); Future<std::vector<Offer>> offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(offers); EXPECT_FALSE(offers->empty()); const string commandString = strings::format( "env; test \"$%s\" = \"%s\"", SECRET_ENV_NAME, SECRET_VALUE).get(); CommandInfo command; command.set_value(commandString); // Request a secret. // TODO(kapil): Update createEnvironment() to support secrets. mesos::Environment::Variable *env = command.mutable_environment()->add_variables(); env->set_name(SECRET_ENV_NAME); env->set_type(mesos::Environment::Variable::SECRET); mesos::Secret* secret = env->mutable_secret(); secret->set_type(Secret::VALUE); secret->mutable_value()->set_data(SECRET_VALUE); TaskInfo task = createTask( offers.get()[0].slave_id(), Resources::parse("cpus:0.1;mem:32").get(), command); // NOTE: Successful tasks will output two status updates. Future<TaskStatus> statusRunning; Future<TaskStatus> statusFinished; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusRunning)) .WillOnce(FutureArg<1>(&statusFinished)); driver.launchTasks(offers.get()[0].id(), {task}); AWAIT_READY(statusRunning); EXPECT_EQ(TASK_RUNNING, statusRunning.get().state()); AWAIT_READY(statusFinished); EXPECT_EQ(TASK_FINISHED, statusFinished.get().state()); driver.stop(); driver.join(); } // This test verifies that the environment secrets are resolved when launching // a task using the DefaultExecutor. TEST_F(EnvironmentSecretIsolatorTest, ResolveSecretDefaultExecutor) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); mesos::internal::slave::Flags flags = CreateSlaveFlags(); #ifndef USE_SSL_SOCKET // Disable operator API authentication for the default executor. Executor // authentication currently has SSL as a dependency, so we cannot require // executors to authenticate with the agent operator API if Mesos was not // built with SSL support. flags.authenticate_http_readwrite = false; #endif // USE_SSL_SOCKET Fetcher fetcher(flags); Try<SecretResolver*> secretResolver = SecretResolver::create(); EXPECT_SOME(secretResolver); Try<MesosContainerizer*> containerizer = MesosContainerizer::create(flags, true, &fetcher, secretResolver.get()); EXPECT_SOME(containerizer); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), containerizer.get(), flags); ASSERT_SOME(slave); MockScheduler sched; MesosSchedulerDriver driver( &sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL); Future<FrameworkID> frameworkId; EXPECT_CALL(sched, registered(&driver, _, _)) .WillOnce(FutureArg<1>(&frameworkId)); Future<std::vector<Offer>> offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(frameworkId); AWAIT_READY(offers); ASSERT_FALSE(offers->empty()); Resources resources = Resources::parse("cpus:0.1;mem:32;disk:32").get(); ExecutorInfo executorInfo; executorInfo.set_type(ExecutorInfo::DEFAULT); executorInfo.mutable_executor_id()->CopyFrom(DEFAULT_EXECUTOR_ID); executorInfo.mutable_framework_id()->CopyFrom(frameworkId.get()); executorInfo.mutable_resources()->CopyFrom(resources); const string commandString = strings::format( "env; test \"$%s\" = \"%s\"", SECRET_ENV_NAME, SECRET_VALUE).get(); CommandInfo command; command.set_value(commandString); // Request a secret. // TODO(kapil): Update createEnvironment() to support secrets. mesos::Environment::Variable *env = command.mutable_environment()->add_variables(); env->set_name(SECRET_ENV_NAME); env->set_type(mesos::Environment::Variable::SECRET); mesos::Secret* secret = env->mutable_secret(); secret->set_type(Secret::VALUE); secret->mutable_value()->set_data(SECRET_VALUE); const Offer& offer = offers->front(); const SlaveID& slaveId = offer.slave_id(); TaskInfo task = createTask( slaveId, Resources::parse("cpus:0.1;mem:32").get(), command); // NOTE: Successful tasks will output two status updates. Future<TaskStatus> statusRunning; Future<TaskStatus> statusFinished; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusRunning)) .WillOnce(FutureArg<1>(&statusFinished)); TaskGroupInfo taskGroup = createTaskGroupInfo({task}); driver.acceptOffers({offer.id()}, {LAUNCH_GROUP(executorInfo, taskGroup)}); AWAIT_READY(statusRunning); EXPECT_EQ(TASK_RUNNING, statusRunning->state()); AWAIT_READY(statusFinished); EXPECT_EQ(TASK_FINISHED, statusFinished->state()); driver.stop(); driver.join(); } } // namespace tests { } // namespace internal { } // namespace mesos { <|endoftext|>
<commit_before>/* This file is part of the Grantlee template system. Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the Licence, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "util.h" #include "metaenumvariable_p.h" #include <QStringList> QString Grantlee::unescapeStringLiteral( const QString &input ) { return input.mid( 1, input.size() - 2 ) .replace( "\\\'", QChar( '\'' ) ) .replace( "\\\"", QChar( '"' ) ) .replace( "\\\\", QChar( '\\' ) ); } bool Grantlee::variantIsTrue( const QVariant &variant ) { if ( !variant.isValid() ) return false; switch ( variant.userType() ) { case QVariant::Bool: { return variant.toBool(); } case QVariant::Int: { return ( variant.toInt() > 0 ); } case QVariant::Double: { return ( variant.toDouble() > 0 ); } case QMetaType::QObjectStar: { QObject *obj = variant.value<QObject *>(); if ( !obj ) return false; if ( obj->property( "__true__" ).isValid() ) { return obj->property( "__true__" ).toBool(); } return true; } case QVariant::List: { return ( variant.toList().size() > 0 ); } case QVariant::Hash: { return ( variant.toHash().size() > 0 ); } } return !getSafeString( variant ).get().isEmpty(); } QVariantList Grantlee::variantToList( const QVariant &var ) { if ( !var.isValid() ) return QVariantList(); if ( var.type() == QVariant::List ) { return var.toList(); } if ( var.type() == QVariant::StringList ) { QVariantList list; foreach(const QString &_string, var.toStringList()) list << _string; return list; } if ( var.type() == QVariant::Hash ) { const QVariantHash varHash = var.toHash(); QVariantList list; QVariantHash::const_iterator it = varHash.constBegin(); for ( ; it != varHash.constEnd(); ++it ) list << it.key(); return list; } if ( var.userType() == qMetaTypeId<MetaEnumVariable>() ) { const MetaEnumVariable mev = var.value<MetaEnumVariable>(); if (mev.value != -1) return QVariantList(); QVariantList list; for (int row = 0; row < mev.enumerator.keyCount(); ++row) { list << QVariant::fromValue( MetaEnumVariable( mev.enumerator, row ) ); } return list; } if ( var.userType() == QMetaType::QObjectStar ) { QObject *obj = var.value<QObject*>(); if ( obj->property( "__list__" ).isValid() ) { return obj->property( "__list__" ).toList(); } } else { return QVariantList() << var; } return QVariantList(); } Grantlee::SafeString Grantlee::markSafe( const Grantlee::SafeString &input ) { Grantlee::SafeString sret = input; sret.setSafety( Grantlee::SafeString::IsSafe ); return sret; } Grantlee::SafeString Grantlee::markForEscaping( const Grantlee::SafeString &input ) { Grantlee::SafeString temp = input; if ( input.isSafe() || input.needsEscape() ) return input; temp.setNeedsEscape( true ); return temp; } Grantlee::SafeString Grantlee::getSafeString( const QVariant &input ) { if ( input.userType() == qMetaTypeId<Grantlee::SafeString>() ) { return input.value<Grantlee::SafeString>(); } else { return input.toString(); } } bool Grantlee::isSafeString( const QVariant &input ) { const int type = input.userType(); return (( type == qMetaTypeId<Grantlee::SafeString>() ) || type == QVariant::String ); } static QList<int> getPrimitives() { QList<int> primitives; primitives << qMetaTypeId<Grantlee::SafeString>() << QVariant::Bool << QVariant::Int << QVariant::Double << QVariant::DateTime; return primitives; } bool Grantlee::supportedOutputType( const QVariant &input ) { static const QList<int> primitives = getPrimitives(); return primitives.contains( input.userType() ); } bool Grantlee::equals( const QVariant &lhs, const QVariant &rhs ) { // TODO: Redesign... // QVariant doesn't use operator== to compare its held data, so we do it manually instead for SafeString. bool equal = false; if ( lhs.userType() == qMetaTypeId<Grantlee::SafeString>() ) { if ( rhs.userType() == qMetaTypeId<Grantlee::SafeString>() ) { equal = ( lhs.value<Grantlee::SafeString>() == rhs.value<Grantlee::SafeString>() ); } else if ( rhs.userType() == QVariant::String ) { equal = ( lhs.value<Grantlee::SafeString>() == rhs.toString() ); } } else if ( rhs.userType() == qMetaTypeId<Grantlee::SafeString>() && lhs.userType() == QVariant::String ) { equal = ( rhs.value<Grantlee::SafeString>() == lhs.toString() ); } else if ( rhs.userType() == qMetaTypeId<MetaEnumVariable>() ) { if (lhs.userType() == qMetaTypeId<MetaEnumVariable>() ) { equal = ( rhs.value<MetaEnumVariable>() == lhs.value<MetaEnumVariable>() ); } else if ( lhs.type() == QVariant::Int ) { equal = ( rhs.value<MetaEnumVariable>() == lhs.toInt() ); } } else if ( lhs.userType() == qMetaTypeId<MetaEnumVariable>() ) { if ( rhs.type() == QVariant::Int ) { equal = ( lhs.value<MetaEnumVariable>() == rhs.toInt() ); } } else { equal = (( lhs == rhs ) && ( lhs.userType() == rhs.userType() ) ); } return equal; } Grantlee::SafeString Grantlee::toString( const QVariantList &list ) { QString output( '[' ); QVariantList::const_iterator it = list.constBegin(); const QVariantList::const_iterator end = list.constEnd(); while ( it != end ) { const QVariant item = *it; if ( isSafeString( item ) ) { output.append( "u\'" ); output.append( getSafeString( item ) ); output.append( '\'' ); if (( it + 1 ) != end ) output.append( ", " ); } if ( item.type() == QVariant::List ) { output.append( toString( item.toList() ) ); output.append( ", " ); } ++it; } return output.append( ']' ); } <commit_msg>More explict latin1.<commit_after>/* This file is part of the Grantlee template system. Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the Licence, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "util.h" #include "metaenumvariable_p.h" #include "grantlee_latin1literal_p.h" #include <QStringList> QString Grantlee::unescapeStringLiteral( const QString &input ) { return input.mid( 1, input.size() - 2 ) .replace( QLatin1String( "\\\'" ), QChar::fromLatin1( '\'' ) ) .replace( QLatin1String( "\\\"" ), QChar::fromLatin1( '"' ) ) .replace( QLatin1String( "\\\\" ), QChar::fromLatin1( '\\' ) ); } bool Grantlee::variantIsTrue( const QVariant &variant ) { if ( !variant.isValid() ) return false; switch ( variant.userType() ) { case QVariant::Bool: { return variant.toBool(); } case QVariant::Int: { return ( variant.toInt() > 0 ); } case QVariant::Double: { return ( variant.toDouble() > 0 ); } case QMetaType::QObjectStar: { QObject *obj = variant.value<QObject *>(); if ( !obj ) return false; if ( obj->property( "__true__" ).isValid() ) { return obj->property( "__true__" ).toBool(); } return true; } case QVariant::List: { return ( variant.toList().size() > 0 ); } case QVariant::Hash: { return ( variant.toHash().size() > 0 ); } } return !getSafeString( variant ).get().isEmpty(); } QVariantList Grantlee::variantToList( const QVariant &var ) { if ( !var.isValid() ) return QVariantList(); if ( var.type() == QVariant::List ) { return var.toList(); } if ( var.type() == QVariant::StringList ) { QVariantList list; foreach(const QString &_string, var.toStringList()) list << _string; return list; } if ( var.type() == QVariant::Hash ) { const QVariantHash varHash = var.toHash(); QVariantList list; QVariantHash::const_iterator it = varHash.constBegin(); for ( ; it != varHash.constEnd(); ++it ) list << it.key(); return list; } if ( var.userType() == qMetaTypeId<MetaEnumVariable>() ) { const MetaEnumVariable mev = var.value<MetaEnumVariable>(); if (mev.value != -1) return QVariantList(); QVariantList list; for (int row = 0; row < mev.enumerator.keyCount(); ++row) { list << QVariant::fromValue( MetaEnumVariable( mev.enumerator, row ) ); } return list; } if ( var.userType() == QMetaType::QObjectStar ) { QObject *obj = var.value<QObject*>(); if ( obj->property( "__list__" ).isValid() ) { return obj->property( "__list__" ).toList(); } } else { return QVariantList() << var; } return QVariantList(); } Grantlee::SafeString Grantlee::markSafe( const Grantlee::SafeString &input ) { Grantlee::SafeString sret = input; sret.setSafety( Grantlee::SafeString::IsSafe ); return sret; } Grantlee::SafeString Grantlee::markForEscaping( const Grantlee::SafeString &input ) { Grantlee::SafeString temp = input; if ( input.isSafe() || input.needsEscape() ) return input; temp.setNeedsEscape( true ); return temp; } Grantlee::SafeString Grantlee::getSafeString( const QVariant &input ) { if ( input.userType() == qMetaTypeId<Grantlee::SafeString>() ) { return input.value<Grantlee::SafeString>(); } else { return input.toString(); } } bool Grantlee::isSafeString( const QVariant &input ) { const int type = input.userType(); return (( type == qMetaTypeId<Grantlee::SafeString>() ) || type == QVariant::String ); } static QList<int> getPrimitives() { QList<int> primitives; primitives << qMetaTypeId<Grantlee::SafeString>() << QVariant::Bool << QVariant::Int << QVariant::Double << QVariant::DateTime; return primitives; } bool Grantlee::supportedOutputType( const QVariant &input ) { static const QList<int> primitives = getPrimitives(); return primitives.contains( input.userType() ); } bool Grantlee::equals( const QVariant &lhs, const QVariant &rhs ) { // TODO: Redesign... // QVariant doesn't use operator== to compare its held data, so we do it manually instead for SafeString. bool equal = false; if ( lhs.userType() == qMetaTypeId<Grantlee::SafeString>() ) { if ( rhs.userType() == qMetaTypeId<Grantlee::SafeString>() ) { equal = ( lhs.value<Grantlee::SafeString>() == rhs.value<Grantlee::SafeString>() ); } else if ( rhs.userType() == QVariant::String ) { equal = ( lhs.value<Grantlee::SafeString>() == rhs.toString() ); } } else if ( rhs.userType() == qMetaTypeId<Grantlee::SafeString>() && lhs.userType() == QVariant::String ) { equal = ( rhs.value<Grantlee::SafeString>() == lhs.toString() ); } else if ( rhs.userType() == qMetaTypeId<MetaEnumVariable>() ) { if (lhs.userType() == qMetaTypeId<MetaEnumVariable>() ) { equal = ( rhs.value<MetaEnumVariable>() == lhs.value<MetaEnumVariable>() ); } else if ( lhs.type() == QVariant::Int ) { equal = ( rhs.value<MetaEnumVariable>() == lhs.toInt() ); } } else if ( lhs.userType() == qMetaTypeId<MetaEnumVariable>() ) { if ( rhs.type() == QVariant::Int ) { equal = ( lhs.value<MetaEnumVariable>() == rhs.toInt() ); } } else { equal = (( lhs == rhs ) && ( lhs.userType() == rhs.userType() ) ); } return equal; } Grantlee::SafeString Grantlee::toString( const QVariantList &list ) { QString output( QLatin1Char( '[' ) ); QVariantList::const_iterator it = list.constBegin(); const QVariantList::const_iterator end = list.constEnd(); while ( it != end ) { const QVariant item = *it; if ( isSafeString( item ) ) { output += QLatin1Literal( "u\'" ) + static_cast<QString>( getSafeString( item ).get() ) + QLatin1Char( '\'' ) + ( ( it + 1 ) != end ? QLatin1Literal( ", " ) : QLatin1Literal( "" ) ); } if ( item.type() == QVariant::List ) { output += static_cast<QString>( toString( item.toList() ).get() ) + QLatin1Literal( ", " ); } ++it; } return output.append( QLatin1Char( ']' ) ); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> #include <random> #include <sstream> #include "slitherlink/sl_dictionary.h" #include "slitherlink/sl_generator.h" #include "slitherlink/sl_generator_option.h" #include "slitherlink/sl_clue_placement.h" #include "slitherlink/sl_problem.h" namespace { void ShowUsage(int argc, char** argv) { std::cerr << "Usage: " << argv[0] << " [options] [file]" << std::endl; std::cerr << "Options:\n\ -o <file> Place the output into <file>\n\ -a Generate the clue placement automatically\n\ -h <height> Set the height of the problem <height>\n\ -w <width> Set the width of the problem <width>\n\ -c <num> Set the minimum number of the clues <num>\n\ -C <num> Set the maximum number of the clues <num>\n\ \n\ Options -h, -w, -c and -C are valid only if -a is specified.\n\ If -a is not specified, the input file should be specified for the clue placement." << std::endl; } bool GenerateWithCluePlacement( penciloid::slitherlink::CluePlacement &placement, penciloid::slitherlink::GeneratorOption &opt, std::mt19937 *rnd, penciloid::slitherlink::Problem *problem, int n_trial = -1) { if (n_trial < 0) { while (!penciloid::slitherlink::GenerateByLocalSearch(placement, opt, rnd, problem)); return true; } while (n_trial) { if (penciloid::slitherlink::GenerateByLocalSearch(placement, opt, rnd, problem)) { return true; } --n_trial; } return false; } void GenerateAuto( int height, int width, int n_clue_lo, int n_clue_hi, int symmetry, penciloid::slitherlink::GeneratorOption &opt, std::mt19937 *rnd, penciloid::slitherlink::Problem *problem) { using namespace penciloid; using namespace slitherlink; for (;;) { int n_clues = std::uniform_int_distribution<int>(n_clue_lo, n_clue_hi)(*rnd); CluePlacement placement = GenerateCluePlacement(Y(height), X(width), n_clues, symmetry, rnd); if (GenerateWithCluePlacement(placement, opt, rnd, problem, 3)) { break; } } } } int main(int argc, char** argv) { if (argc < 2) { ShowUsage(argc, argv); return 0; } std::string in_filename = "", out_filename = ""; int height = -1, width = -1, n_clue_lo = -1, n_clue_hi = -1; bool gen_clue_auto = false; // parse options int arg_idx = 1; for (; arg_idx < argc; ++arg_idx) { if (argv[arg_idx][0] != '-') { // option ended break; } bool is_next_int = false; int val_next_int; if (arg_idx + 1 < argc) { std::istringstream iss(argv[arg_idx + 1]); iss >> val_next_int; if (!iss.fail()) is_next_int = true; } char opt = argv[arg_idx][1]; switch (opt) { case 'o': // specify the output file if (arg_idx + 1 >= argc) { std::cerr << "error: missing value after -o" << std::endl; return 0; } out_filename = argv[arg_idx + 1]; ++arg_idx; break; case 'a': // generate clue placement automatically gen_clue_auto = true; break; case 'h': // specify the height of the generated problem (enabled only if '-a' is specified) if (!is_next_int) { std::cerr << "error: missing integer value after -h" << std::endl; return 0; } height = val_next_int; ++arg_idx; break; case 'w': // specify the width of the generated problem (enabled only if '-a' is specified) if (!is_next_int) { std::cerr << "error: missing integer value after -w" << std::endl; return 0; } width = val_next_int; ++arg_idx; break; case 'c': // specify the minimum number of the clues if (!is_next_int) { std::cerr << "error: missing integer value after -c" << std::endl; return 0; } n_clue_lo = val_next_int; ++arg_idx; break; case 'C': // specify the maximum number of the clues if (!is_next_int) { std::cerr << "error: missing integer value after -C" << std::endl; return 0; } n_clue_hi = val_next_int; ++arg_idx; break; default: std::cerr << "error: unrecognized option '" << argv[arg_idx] << "'" << std::endl; return 0; } } if (gen_clue_auto) { if (out_filename.empty()) { std::cerr << "error: -o must be specified if -a is specified." << std::endl; return 0; } } if (!gen_clue_auto) { in_filename = argv[arg_idx]; } using namespace penciloid; using namespace slitherlink; GeneratorOption opt; Dictionary dic; dic.CreateDefault(); opt.field_dictionary = &dic; Problem problem; std::random_device dev; std::mt19937 rnd(dev()); if (!gen_clue_auto) { std::ifstream ifs(in_filename); if (ifs.fail()) { std::cerr << "error: couldn't open file '" << in_filename << "'" << std::endl; return 0; } ifs >> height >> width; if (ifs.fail() || height <= 0 || width <= 0) { std::cerr << "error: invalid input format" << std::endl; return 0; } CluePlacement clue_placement{ Y(height), X(width) }; for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { std::string token; ifs >> token; if (ifs.fail()) { std::cerr << "error: invalid input format" << std::endl; return 0; } if (token[0] >= '0' && token[0] <= '3') { clue_placement.SetClue(CellPosition(y, x), Clue(static_cast<int>(token[0] - '0'))); } else if (token[0] == '5') { clue_placement.SetClue(CellPosition(y, x), kSomeClue); } else { std::cerr << "error: invalid input format" << std::endl; return 0; } } } GenerateWithCluePlacement(clue_placement, opt, &rnd, &problem); } else { if (n_clue_lo == -1 || n_clue_hi == -1) { n_clue_lo = static_cast<int>(height * width * 0.3); n_clue_hi = static_cast<int>(height * width * 0.4); } GenerateAuto(height, width, n_clue_lo, n_clue_hi, penciloid::slitherlink::kSymmetryDyad, opt, &rnd, &problem); } if (out_filename.empty()) { out_filename = in_filename + ".generated.txt"; } std::ofstream ofs(out_filename); if (!ofs.good()) { std::cerr << "error: couldn't open file '" << in_filename << "'" << std::endl; return 0; } ofs << height << std::endl; ofs << width << std::endl; for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { Clue c = problem.GetClue(CellPosition(y, x)); if (c == kNoClue) ofs << ". "; else ofs << static_cast<int>(c) << " "; } ofs << std::endl; } return 0; } <commit_msg>frontend_slitherlink_generator: switch -> if<commit_after>#include <iostream> #include <fstream> #include <string> #include <random> #include <sstream> #include "slitherlink/sl_dictionary.h" #include "slitherlink/sl_generator.h" #include "slitherlink/sl_generator_option.h" #include "slitherlink/sl_clue_placement.h" #include "slitherlink/sl_problem.h" namespace { void ShowUsage(int argc, char** argv) { std::cerr << "Usage: " << argv[0] << " [options] [file]" << std::endl; std::cerr << "Options:\n\ --help Display this information\n\ -o <file> Place the output into <file>\n\ -a Generate the clue placement automatically\n\ -h <height> Set the height of the problem <height>\n\ -w <width> Set the width of the problem <width>\n\ -c <num> Set the minimum number of the clues <num>\n\ -C <num> Set the maximum number of the clues <num>\n\ \n\ Options -h, -w, -c and -C are valid only if -a is specified.\n\ If -a is not specified, the input file should be specified for the clue placement." << std::endl; } bool GenerateWithCluePlacement( penciloid::slitherlink::CluePlacement &placement, penciloid::slitherlink::GeneratorOption &opt, std::mt19937 *rnd, penciloid::slitherlink::Problem *problem, int n_trial = -1) { if (n_trial < 0) { while (!penciloid::slitherlink::GenerateByLocalSearch(placement, opt, rnd, problem)); return true; } while (n_trial) { if (penciloid::slitherlink::GenerateByLocalSearch(placement, opt, rnd, problem)) { return true; } --n_trial; } return false; } void GenerateAuto( int height, int width, int n_clue_lo, int n_clue_hi, int symmetry, penciloid::slitherlink::GeneratorOption &opt, std::mt19937 *rnd, penciloid::slitherlink::Problem *problem) { using namespace penciloid; using namespace slitherlink; for (;;) { int n_clues = std::uniform_int_distribution<int>(n_clue_lo, n_clue_hi)(*rnd); CluePlacement placement = GenerateCluePlacement(Y(height), X(width), n_clues, symmetry, rnd); if (GenerateWithCluePlacement(placement, opt, rnd, problem, 3)) { break; } } } } int main(int argc, char** argv) { if (argc < 2) { ShowUsage(argc, argv); return 0; } std::string in_filename = "", out_filename = ""; int height = -1, width = -1, n_clue_lo = -1, n_clue_hi = -1; bool gen_clue_auto = false; // parse options int arg_idx = 1; for (; arg_idx < argc; ++arg_idx) { if (argv[arg_idx][0] != '-') { // option ended break; } bool is_next_int = false; int val_next_int; if (arg_idx + 1 < argc) { std::istringstream iss(argv[arg_idx + 1]); iss >> val_next_int; if (!iss.fail()) is_next_int = true; } std::string opt = argv[arg_idx]; if (opt == "-o") { if (arg_idx + 1 >= argc) { std::cerr << "error: missing value after -o" << std::endl; return 0; } out_filename = argv[arg_idx + 1]; ++arg_idx; } else if (opt == "-a") { gen_clue_auto = true; } else if (opt == "-h") { if (!is_next_int) { std::cerr << "error: missing integer value after -h" << std::endl; return 0; } height = val_next_int; ++arg_idx; } else if (opt == "-w") { if (!is_next_int) { std::cerr << "error: missing integer value after -w" << std::endl; return 0; } width = val_next_int; ++arg_idx; } else if (opt == "-c") { if (!is_next_int) { std::cerr << "error: missing integer value after -c" << std::endl; return 0; } n_clue_lo = val_next_int; ++arg_idx; } else if (opt == "-C") { if (!is_next_int) { std::cerr << "error: missing integer value after -C" << std::endl; return 0; } n_clue_hi = val_next_int; ++arg_idx; } else if (opt == "--help") { ShowUsage(argc, argv); return 0; } else { std::cerr << "error: unrecognized option '" << argv[arg_idx] << "'" << std::endl; return 0; } } if (gen_clue_auto) { if (out_filename.empty()) { std::cerr << "error: -o must be specified if -a is specified." << std::endl; return 0; } } if (!gen_clue_auto) { if (arg_idx < argc) { in_filename = argv[arg_idx]; } else { std::cerr << "error: no input file" << std::endl; return 0; } } using namespace penciloid; using namespace slitherlink; GeneratorOption opt; Dictionary dic; dic.CreateDefault(); opt.field_dictionary = &dic; Problem problem; std::random_device dev; std::mt19937 rnd(dev()); if (!gen_clue_auto) { std::ifstream ifs(in_filename); if (ifs.fail()) { std::cerr << "error: couldn't open file '" << in_filename << "'" << std::endl; return 0; } ifs >> height >> width; if (ifs.fail() || height <= 0 || width <= 0) { std::cerr << "error: invalid input format" << std::endl; return 0; } CluePlacement clue_placement{ Y(height), X(width) }; for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { std::string token; ifs >> token; if (ifs.fail()) { std::cerr << "error: invalid input format" << std::endl; return 0; } if (token[0] >= '0' && token[0] <= '3') { clue_placement.SetClue(CellPosition(y, x), Clue(static_cast<int>(token[0] - '0'))); } else if (token[0] == '5') { clue_placement.SetClue(CellPosition(y, x), kSomeClue); } else { std::cerr << "error: invalid input format" << std::endl; return 0; } } } GenerateWithCluePlacement(clue_placement, opt, &rnd, &problem); } else { if (n_clue_lo == -1 || n_clue_hi == -1) { n_clue_lo = static_cast<int>(height * width * 0.3); n_clue_hi = static_cast<int>(height * width * 0.4); } GenerateAuto(height, width, n_clue_lo, n_clue_hi, penciloid::slitherlink::kSymmetryDyad, opt, &rnd, &problem); } if (out_filename.empty()) { out_filename = in_filename + ".generated.txt"; } std::ofstream ofs(out_filename); if (!ofs.good()) { std::cerr << "error: couldn't open file '" << in_filename << "'" << std::endl; return 0; } ofs << height << std::endl; ofs << width << std::endl; for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { Clue c = problem.GetClue(CellPosition(y, x)); if (c == kNoClue) ofs << ". "; else ofs << static_cast<int>(c) << " "; } ofs << std::endl; } return 0; } <|endoftext|>
<commit_before><commit_msg>Cover NaN case for reference and sensors data<commit_after><|endoftext|>
<commit_before>#include "chrono_parallel/solver/ChSolverParallel.h" using namespace chrono; ChSolverParallel::ChSolverParallel() { max_iteration = 100; current_iteration = 0; rigid_rigid = NULL; bilateral = NULL; } ChSolverParallel::~ChSolverParallel() {} void ChSolverParallel::Setup(ChParallelDataManager* data_container_) { data_container = data_container_; Initialize(); } void ChSolverParallel::Project(real* gamma) { data_container->system_timer.start("ChSolverParallel_Project"); rigid_rigid->Project(gamma); data_container->system_timer.stop("ChSolverParallel_Project"); } void ChSolverParallel::Project_Single(int index, real* gamma) { data_container->system_timer.start("ChSolverParallel_Project"); rigid_rigid->Project_Single(index, gamma); data_container->system_timer.stop("ChSolverParallel_Project"); } //================================================================================================================================= void ChSolverParallel::shurA(blaze::DynamicVector<real>& x, blaze::DynamicVector<real>& out) { out = data_container->host_data.M_invD * x; } void ChSolverParallel::ComputeSRhs(custom_vector<real>& gamma, const custom_vector<real>& rhs, custom_vector<real3>& vel_data, custom_vector<real3>& omg_data, custom_vector<real>& b) { // TODO change SHRS to use blaze // ComputeImpulses(gamma, vel_data, omg_data); // rigid_rigid->ComputeS(rhs, vel_data, omg_data, b); } void ChSolverParallel::ShurProduct(const blaze::DynamicVector<real>& x, blaze::DynamicVector<real>& output) { data_container->system_timer.start("ShurProduct"); output = data_container->host_data.D_T * data_container->host_data.M_invD * x + data_container->host_data.E * x; data_container->system_timer.stop("ShurProduct"); } void ChSolverParallel::ShurBilaterals(const blaze::DynamicVector<real>& x, blaze::DynamicVector<real>& output) { CompressedMatrix<real>& D_T = data_container->host_data.D_T; CompressedMatrix<real>& M_invD = data_container->host_data.M_invD; uint& num_bodies = data_container->num_bodies; uint& num_unilaterals = data_container->num_unilaterals; uint& num_bilaterals = data_container->num_bilaterals; blaze::SparseSubmatrix<CompressedMatrix<real> > D_T_sub = blaze::submatrix(D_T, num_unilaterals, 0, num_bilaterals, num_bodies * 6); blaze::SparseSubmatrix<CompressedMatrix<real> > M_invD_sub = blaze::submatrix(M_invD, 0, num_unilaterals, num_bodies * 6, num_bilaterals); output = D_T_sub * M_invD_sub * x; } //================================================================================================================================= void ChSolverParallel::UpdatePosition(custom_vector<real>& x) { // // if (rigid_rigid->solve_sliding == true || rigid_rigid->solve_spinning == // true) { // return; // } // shurA(x.data()); // // data_container->host_data.vel_new_data = // data_container->host_data.vel_data + data_container->host_data.QXYZ_data; // data_container->host_data.omg_new_data + // data_container->host_data.omg_data + data_container->host_data.QUVW_data; // //#pragma omp parallel for // for (int i = 0; i < data_container->num_bodies; i++) { // // data_container->host_data.pos_new_data[i] = // data_container->host_data.pos_data[i] + // data_container->host_data.vel_new_data[i] * step_size; // //real3 dp = // data_container->host_data.pos_new_data[i]-data_container->host_data.pos_data[i]; // //cout<<dp<<endl; // real4 moldrot = data_container->host_data.rot_data[i]; // real3 newwel = data_container->host_data.omg_new_data[i]; // // M33 A = AMat(moldrot); // real3 newwel_abs = MatMult(A, newwel); // real mangle = length(newwel_abs) * step_size; // newwel_abs = normalize(newwel_abs); // real4 mdeltarot = Q_from_AngAxis(mangle, newwel_abs); // real4 mnewrot = mdeltarot % moldrot; // data_container->host_data.rot_new_data[i] = mnewrot; // } } void ChSolverParallel::UpdateContacts() { ////TODO: Re-implement this using new dispatch // if (rigid_rigid->solve_sliding == true || rigid_rigid->solve_spinning == // true) { // return; // } // // //// TODO: This ASSUMES that we are using an MPR narrowphase!! // //// Instead of constructing a narrowphaseMPR object here, // //// modify so that we can use the CHCNarrowphase object // //// from the CollisionSystemParallel. // collision::ChCNarrowphaseMPR narrowphase; // narrowphase.SetCollisionEnvelope(data_container->settings.collision.collision_envelope); // narrowphase.Update(data_container); // // rigid_rigid->UpdateJacobians(); // rigid_rigid->UpdateRHS(); } uint ChSolverParallel::SolveStab(const uint max_iter, const uint size, const blaze::DenseSubvector<DynamicVector<real> >& mb, blaze::DenseSubvector<DynamicVector<real> >& x) { real& residual = data_container->measures.solver.residual; custom_vector<real>& iter_hist = data_container->measures.solver.iter_hist; uint N = mb.size(); blaze::DynamicVector<real> v(N, 0), v_hat(x.size()), w(N, 0), w_old, xMR, v_old, Av(x.size()), w_oold; real beta, c = 1, eta, norm_rMR, norm_r0, c_old = 1, s_old = 0, s = 0, alpha, beta_old, c_oold, s_oold, r1_hat, r1, r2, r3; ShurBilaterals(x, v_hat); v_hat = mb - v_hat; beta = sqrt((v_hat, v_hat)); w_old = w; eta = beta; xMR = x; norm_rMR = beta; norm_r0 = beta; if (beta == 0 || norm_rMR / norm_r0 < data_container->settings.solver.tolerance) { return 0; } for (current_iteration = 0; current_iteration < max_iter; current_iteration++) { //// Lanczos v_old = v; v = 1.0 / beta * v_hat; ShurBilaterals(v, Av); alpha = (v, Av); v_hat = Av - alpha * v - beta * v_old; beta_old = beta; beta = sqrt((v_hat, v_hat)); //// QR factorization c_oold = c_old; c_old = c; s_oold = s_old; s_old = s; r1_hat = c_old * alpha - c_oold * s_old * beta_old; r1 = 1 / sqrt(r1_hat * r1_hat + beta * beta); r2 = s_old * alpha + c_oold * c_old * beta_old; r3 = s_oold * beta_old; //// Givens Rotation c = r1_hat * r1; s = beta * r1; //// update w_oold = w_old; w_old = w; w = r1 * (v - r3 * w_oold - r2 * w_old); x = x + c * eta * w; norm_rMR = norm_rMR * std::abs(s); eta = -s * eta; residual = norm_rMR / norm_r0; real maxdeltalambda = 0; // CompRes(mb, num_contacts); //NormInf(ms); AtIterationEnd(residual, maxdeltalambda, iter_hist.size() + current_iteration); if (residual < data_container->settings.solver.tolerance) { break; } } return current_iteration; } <commit_msg>Fix for Visual Studio 12: must explicitly group matrix * matrix * vector operations<commit_after>#include "chrono_parallel/solver/ChSolverParallel.h" using namespace chrono; ChSolverParallel::ChSolverParallel() { max_iteration = 100; current_iteration = 0; rigid_rigid = NULL; bilateral = NULL; } ChSolverParallel::~ChSolverParallel() {} void ChSolverParallel::Setup(ChParallelDataManager* data_container_) { data_container = data_container_; Initialize(); } void ChSolverParallel::Project(real* gamma) { data_container->system_timer.start("ChSolverParallel_Project"); rigid_rigid->Project(gamma); data_container->system_timer.stop("ChSolverParallel_Project"); } void ChSolverParallel::Project_Single(int index, real* gamma) { data_container->system_timer.start("ChSolverParallel_Project"); rigid_rigid->Project_Single(index, gamma); data_container->system_timer.stop("ChSolverParallel_Project"); } //================================================================================================================================= void ChSolverParallel::shurA(blaze::DynamicVector<real>& x, blaze::DynamicVector<real>& out) { out = data_container->host_data.M_invD * x; } void ChSolverParallel::ComputeSRhs(custom_vector<real>& gamma, const custom_vector<real>& rhs, custom_vector<real3>& vel_data, custom_vector<real3>& omg_data, custom_vector<real>& b) { // TODO change SHRS to use blaze // ComputeImpulses(gamma, vel_data, omg_data); // rigid_rigid->ComputeS(rhs, vel_data, omg_data, b); } void ChSolverParallel::ShurProduct(const blaze::DynamicVector<real>& x, blaze::DynamicVector<real>& output) { data_container->system_timer.start("ShurProduct"); output = data_container->host_data.D_T * ( data_container->host_data.M_invD * x ) + data_container->host_data.E * x; data_container->system_timer.stop("ShurProduct"); } void ChSolverParallel::ShurBilaterals(const blaze::DynamicVector<real>& x, blaze::DynamicVector<real>& output) { CompressedMatrix<real>& D_T = data_container->host_data.D_T; CompressedMatrix<real>& M_invD = data_container->host_data.M_invD; uint& num_bodies = data_container->num_bodies; uint& num_unilaterals = data_container->num_unilaterals; uint& num_bilaterals = data_container->num_bilaterals; blaze::SparseSubmatrix<CompressedMatrix<real> > D_T_sub = blaze::submatrix(D_T, num_unilaterals, 0, num_bilaterals, num_bodies * 6); blaze::SparseSubmatrix<CompressedMatrix<real> > M_invD_sub = blaze::submatrix(M_invD, 0, num_unilaterals, num_bodies * 6, num_bilaterals); output = D_T_sub * ( M_invD_sub * x ); } //================================================================================================================================= void ChSolverParallel::UpdatePosition(custom_vector<real>& x) { // // if (rigid_rigid->solve_sliding == true || rigid_rigid->solve_spinning == // true) { // return; // } // shurA(x.data()); // // data_container->host_data.vel_new_data = // data_container->host_data.vel_data + data_container->host_data.QXYZ_data; // data_container->host_data.omg_new_data + // data_container->host_data.omg_data + data_container->host_data.QUVW_data; // //#pragma omp parallel for // for (int i = 0; i < data_container->num_bodies; i++) { // // data_container->host_data.pos_new_data[i] = // data_container->host_data.pos_data[i] + // data_container->host_data.vel_new_data[i] * step_size; // //real3 dp = // data_container->host_data.pos_new_data[i]-data_container->host_data.pos_data[i]; // //cout<<dp<<endl; // real4 moldrot = data_container->host_data.rot_data[i]; // real3 newwel = data_container->host_data.omg_new_data[i]; // // M33 A = AMat(moldrot); // real3 newwel_abs = MatMult(A, newwel); // real mangle = length(newwel_abs) * step_size; // newwel_abs = normalize(newwel_abs); // real4 mdeltarot = Q_from_AngAxis(mangle, newwel_abs); // real4 mnewrot = mdeltarot % moldrot; // data_container->host_data.rot_new_data[i] = mnewrot; // } } void ChSolverParallel::UpdateContacts() { ////TODO: Re-implement this using new dispatch // if (rigid_rigid->solve_sliding == true || rigid_rigid->solve_spinning == // true) { // return; // } // // //// TODO: This ASSUMES that we are using an MPR narrowphase!! // //// Instead of constructing a narrowphaseMPR object here, // //// modify so that we can use the CHCNarrowphase object // //// from the CollisionSystemParallel. // collision::ChCNarrowphaseMPR narrowphase; // narrowphase.SetCollisionEnvelope(data_container->settings.collision.collision_envelope); // narrowphase.Update(data_container); // // rigid_rigid->UpdateJacobians(); // rigid_rigid->UpdateRHS(); } uint ChSolverParallel::SolveStab(const uint max_iter, const uint size, const blaze::DenseSubvector<DynamicVector<real> >& mb, blaze::DenseSubvector<DynamicVector<real> >& x) { real& residual = data_container->measures.solver.residual; custom_vector<real>& iter_hist = data_container->measures.solver.iter_hist; uint N = mb.size(); blaze::DynamicVector<real> v(N, 0), v_hat(x.size()), w(N, 0), w_old, xMR, v_old, Av(x.size()), w_oold; real beta, c = 1, eta, norm_rMR, norm_r0, c_old = 1, s_old = 0, s = 0, alpha, beta_old, c_oold, s_oold, r1_hat, r1, r2, r3; ShurBilaterals(x, v_hat); v_hat = mb - v_hat; beta = sqrt((v_hat, v_hat)); w_old = w; eta = beta; xMR = x; norm_rMR = beta; norm_r0 = beta; if (beta == 0 || norm_rMR / norm_r0 < data_container->settings.solver.tolerance) { return 0; } for (current_iteration = 0; current_iteration < max_iter; current_iteration++) { //// Lanczos v_old = v; v = 1.0 / beta * v_hat; ShurBilaterals(v, Av); alpha = (v, Av); v_hat = Av - alpha * v - beta * v_old; beta_old = beta; beta = sqrt((v_hat, v_hat)); //// QR factorization c_oold = c_old; c_old = c; s_oold = s_old; s_old = s; r1_hat = c_old * alpha - c_oold * s_old * beta_old; r1 = 1 / sqrt(r1_hat * r1_hat + beta * beta); r2 = s_old * alpha + c_oold * c_old * beta_old; r3 = s_oold * beta_old; //// Givens Rotation c = r1_hat * r1; s = beta * r1; //// update w_oold = w_old; w_old = w; w = r1 * (v - r3 * w_oold - r2 * w_old); x = x + c * eta * w; norm_rMR = norm_rMR * std::abs(s); eta = -s * eta; residual = norm_rMR / norm_r0; real maxdeltalambda = 0; // CompRes(mb, num_contacts); //NormInf(ms); AtIterationEnd(residual, maxdeltalambda, iter_hist.size() + current_iteration); if (residual < data_container->settings.solver.tolerance) { break; } } return current_iteration; } <|endoftext|>
<commit_before>/* * Copyright 2009-2013 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <iostream> #include <fstream> #include <boost/algorithm/string.hpp> #ifndef HAVE_NO_CONFIG #include <votca_config.h> #endif #include "dlpolytopologyreader.h" #ifdef DLPOLY #include "dlpoly/dlp_io_layer.h" #endif namespace votca { namespace csg { bool DLPOLYTopologyReader::ReadTopology(string file, Topology &top) { #ifdef DLPOLY struct FieldSpecsT FieldBase; struct FrameSpecsT FrameBase; struct MolecSpecsT *MolecBase; struct FieldSiteT *FieldSite; struct FrameSiteT *FrameSite; int idnode,matms,natms,nmols,nmolt; int istateF; int inode=matms=natms=nmols=nmolt=0; // TODO: istateF must be an enum! istateF=1; // TODO: we need to fix the file naming! field_scan_(&istateF,&matms,&natms,&nmolt); MolecBase = new MolecSpecsT[nmolt]; FieldSite = new FieldSiteT[natms]; FieldBase.nmols = nmolt; FieldBase.natms = natms; field_read_(&istateF,&FieldBase,MolecBase,FieldSite); // AB: if on return istateF < 0 => in the next F-call the relevant F-arrays will be deallocated (at the end) // AB: NOT TO RE-/DE-ALLOCATE F-arrays in the next F-call, reset istateF = 0 istateF = 0; // TODO: fix residue naming / assignment Residue *res = top.CreateResidue("no"); // read the atoms int is=0; for(int im=0; im<nmolt; im++){ for(int imr=0; imr<MolecBase[im].nrept; ++imr) { Molecule *mi = top.CreateMolecule(MolecBase[im].name); for(int ims=0; ims<MolecBase[im].nsites; ims++) { BeadType *type = top.GetOrCreateBeadType(FieldSite[is].name); // what is Bead *bead = top.CreateBead(1, FieldSite[is].type, type, res->getId(), FieldSite[is].m, FieldSite[is].q); stringstream nm; nm << bead->getResnr() + 1 << ":" << top.getResidue(bead->getResnr())->getName() << ":" << bead->getName(); mi->AddBead(bead, nm.str()); } } } delete [] MolecBase; delete [] FieldSite; #else // TODO: fix residue naming / assignment Residue *res = top.CreateResidue("no"); std::ifstream fl; fl.open("FIELD"); if (!fl.is_open()){ throw std::runtime_error("could open dlpoly file FIELD"); } else { string line; getline(fl, line); //title getline(fl, line); //unit line fl >> line; if (line != "MOLECULES") throw std::runtime_error("unexpected line in dlpoly file FIELD, expected 'MOLECULES' got" + line); int nmol_types; fl >> nmol_types; getline(fl, line); //rest of MOLECULES line int id=0; for (int nmol_type=0;nmol_type<nmol_types; nmol_type++){ string mol_name; getline(fl, mol_name); //molecule name might incl. spaces boost::erase_all(mol_name, " "); Molecule *mi = top.CreateMolecule(mol_name); fl >> line; if (line != "NUMMOLS") throw std::runtime_error("unexpected line in dlpoly file FIELD, expected 'NUMMOLS' got" + line); int nreplica; fl >> nreplica; fl >> line; if (line != "ATOMS") throw std::runtime_error("unexpected line in dlpoly file FIELD, expected 'ATOMS' got" + line); int natoms; fl >> natoms; //read molecule for (int i=0;i<natoms;){//i is altered in reapeater loop string beadtype; fl >> beadtype; BeadType *type = top.GetOrCreateBeadType(beadtype); double mass; fl >> mass; double charge; fl >> charge; getline(fl,line); //rest of the atom line Tokenizer tok(line, " "); vector<int> fields; tok.ConvertToVector<int>(fields); int repeater=1; if (fields.size() > 1) repeater=fields[0]; for(int j=0;j<repeater;j++){ string beadname = beadtype + boost::lexical_cast<string>(j+1); Bead *bead = top.CreateBead(1, beadname , type, res->getId(), mass, charge); stringstream nm; nm << bead->getResnr() + 1 << ":" << top.getResidue(bead->getResnr())->getName() << ":" << bead->getName(); mi->AddBead(bead, nm.str()); i++; } } while (line != "FINISH"){ fl >> line; if (fl.eof()) throw std::runtime_error("unexpected end of dlpoly file FIELD while scanning for 'FINISH'"); } //replicate molecule for (int replica=1;replica<nreplica;replica++){ Molecule *mi_replica = top.CreateMolecule(mol_name); for(int i=0;i<mi->BeadCount();i++){ Bead *bead=mi->getBead(i); BeadType *type = top.GetOrCreateBeadType(bead->Type()->getName()); string beadname=mi->getBeadName(i); Bead *bead_replica = top.CreateBead(1, bead->getName(), type, res->getId(), bead->getM(), bead->getQ()); mi_replica->AddBead(bead_replica,beadname); } } } } //we don't need the rest. fl.close(); #endif fl.open("CONFIG"); if(fl.is_open()) { string line; getline(fl, line); //title getline(fl, line); // 2nd header line vec box_vectors[3]; for (int i=0;i<3;i++){ // read 3 box lines getline(fl, line); if(fl.eof()) throw std::runtime_error("unexpected end of file in dlpoly file CONFIG, when reading box vector" + boost::lexical_cast<string>(i)); Tokenizer tok(line, " "); vector<double> fields; tok.ConvertToVector<double>(fields); box_vectors[i]=vec(fields[0],fields[1],fields[2]); } matrix box(box_vectors[0],box_vectors[1],box_vectors[2]); top.setBox(box); } else { cout << "NOTE: Could open dlploy file CONFIG, so no boundary conditions, where set in the topology" << endl; } fl.close(); return true; } }} <commit_msg>dlpolytopologyreader: fixes multiple molecule reading<commit_after>/* * Copyright 2009-2013 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <iostream> #include <fstream> #include <boost/algorithm/string.hpp> #ifndef HAVE_NO_CONFIG #include <votca_config.h> #endif #include "dlpolytopologyreader.h" #ifdef DLPOLY #include "dlpoly/dlp_io_layer.h" #endif namespace votca { namespace csg { bool DLPOLYTopologyReader::ReadTopology(string file, Topology &top) { std::ifstream fl; #ifdef DLPOLY struct FieldSpecsT FieldBase; struct FrameSpecsT FrameBase; struct MolecSpecsT *MolecBase; struct FieldSiteT *FieldSite; struct FrameSiteT *FrameSite; int idnode,matms,natms,nmols,nmolt; int istateF; int inode=matms=natms=nmols=nmolt=0; // TODO: istateF must be an enum! istateF=1; // TODO: we need to fix the file naming! field_scan_(&istateF,&matms,&natms,&nmolt); MolecBase = new MolecSpecsT[nmolt]; FieldSite = new FieldSiteT[natms]; FieldBase.nmols = nmolt; FieldBase.natms = natms; field_read_(&istateF,&FieldBase,MolecBase,FieldSite); // AB: if on return istateF < 0 => in the next F-call the relevant F-arrays will be deallocated (at the end) // AB: NOT TO RE-/DE-ALLOCATE F-arrays in the next F-call, reset istateF = 0 istateF = 0; // TODO: fix residue naming / assignment Residue *res = top.CreateResidue("no"); // read the atoms int is=0; for(int im=0; im<nmolt; im++){ for(int imr=0; imr<MolecBase[im].nrept; ++imr) { Molecule *mi = top.CreateMolecule(MolecBase[im].name); for(int ims=0; ims<MolecBase[im].nsites; ims++) { BeadType *type = top.GetOrCreateBeadType(FieldSite[is].name); // what is Bead *bead = top.CreateBead(1, FieldSite[is].type, type, res->getId(), FieldSite[is].m, FieldSite[is].q); stringstream nm; nm << bead->getResnr() + 1 << ":" << top.getResidue(bead->getResnr())->getName() << ":" << bead->getName(); mi->AddBead(bead, nm.str()); } } } delete [] MolecBase; delete [] FieldSite; #else // TODO: fix residue naming / assignment Residue *res = top.CreateResidue("no"); fl.open("FIELD"); if (!fl.is_open()){ throw std::runtime_error("could open dlpoly file FIELD"); } else { string line; getline(fl, line); //title getline(fl, line); //unit line fl >> line; if (line != "MOLECULES") throw std::runtime_error("unexpected line in dlpoly file FIELD, expected 'MOLECULES' got" + line); int nmol_types; fl >> nmol_types; getline(fl, line); //rest of MOLECULES line int id=0; for (int nmol_type=0;nmol_type<nmol_types; nmol_type++){ string mol_name; getline(fl, mol_name); //molecule name might incl. spaces boost::erase_all(mol_name, " "); Molecule *mi = top.CreateMolecule(mol_name); fl >> line; if (line != "NUMMOLS") throw std::runtime_error("unexpected line in dlpoly file FIELD, expected 'NUMMOLS' got" + line); int nreplica; fl >> nreplica; fl >> line; if (line != "ATOMS") throw std::runtime_error("unexpected line in dlpoly file FIELD, expected 'ATOMS' got" + line); int natoms; fl >> natoms; //read molecule for (int i=0;i<natoms;){//i is altered in reapeater loop string beadtype; fl >> beadtype; BeadType *type = top.GetOrCreateBeadType(beadtype); double mass; fl >> mass; double charge; fl >> charge; getline(fl,line); //rest of the atom line Tokenizer tok(line, " "); vector<int> fields; tok.ConvertToVector<int>(fields); int repeater=1; if (fields.size() > 1) repeater=fields[0]; for(int j=0;j<repeater;j++){ string beadname = beadtype + boost::lexical_cast<string>(j+1); Bead *bead = top.CreateBead(1, beadname , type, res->getId(), mass, charge); stringstream nm; nm << bead->getResnr() + 1 << ":" << top.getResidue(bead->getResnr())->getName() << ":" << bead->getName(); mi->AddBead(bead, nm.str()); i++; } } while (line != "FINISH"){ fl >> line; if (fl.eof()) throw std::runtime_error("unexpected end of dlpoly file FIELD while scanning for 'FINISH'"); } getline(fl, line); //rest of the FINISH line //replicate molecule for (int replica=1;replica<nreplica;replica++){ Molecule *mi_replica = top.CreateMolecule(mol_name); for(int i=0;i<mi->BeadCount();i++){ Bead *bead=mi->getBead(i); BeadType *type = top.GetOrCreateBeadType(bead->Type()->getName()); string beadname=mi->getBeadName(i); Bead *bead_replica = top.CreateBead(1, bead->getName(), type, res->getId(), bead->getM(), bead->getQ()); mi_replica->AddBead(bead_replica,beadname); } } } } //we don't need the rest. fl.close(); #endif fl.open("CONFIG"); if(fl.is_open()) { string line; getline(fl, line); //title getline(fl, line); // 2nd header line vec box_vectors[3]; for (int i=0;i<3;i++){ // read 3 box lines getline(fl, line); if(fl.eof()) throw std::runtime_error("unexpected end of file in dlpoly file CONFIG, when reading box vector" + boost::lexical_cast<string>(i)); Tokenizer tok(line, " "); vector<double> fields; tok.ConvertToVector<double>(fields); box_vectors[i]=vec(fields[0],fields[1],fields[2]); } matrix box(box_vectors[0],box_vectors[1],box_vectors[2]); top.setBox(box); } else { cout << "NOTE: Could open dlploy file CONFIG, so no boundary conditions, where set in the topology" << endl; } fl.close(); return true; } }} <|endoftext|>
<commit_before>/** * Copyright 2016 Colin Doig. Distributed under the MIT license. */ #include <iomanip> #include <sstream> #include "MatchedOrder.h" #include "Util.h" #include "entity/Config.h" namespace greenthumb { MatchedOrder::MatchedOrder(wxWindow* parent, const wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : CurrentOrder(parent, id, pos, size, style, name) { wxFlexGridSizer* sizer = new wxFlexGridSizer(6, 5, 5); sizer->AddGrowableCol(0, 1); SetSizer(sizer); runnerName = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize); runnerName->SetMinSize(wxSize(150, -1)); sizer->Add(runnerName, 0, wxALIGN_CENTRE_VERTICAL); price = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize); sizer->Add(price, 0, wxALIGN_CENTRE_VERTICAL); wxStaticText* stakeLabel = new wxStaticText(this, wxID_ANY, "Stake: "); sizer->Add(stakeLabel, 0, wxALIGN_CENTRE_VERTICAL); stake = new wxStaticText(this, wxID_ANY, wxEmptyString); sizer->Add(stake, 0, wxALIGN_CENTRE_VERTICAL); profitOrLiabilityLabel = new wxStaticText(this, wxID_ANY, wxEmptyString); profitOrLiabilityLabel->SetMinSize(wxSize(75, -1)); sizer->Add(profitOrLiabilityLabel, 0, wxALIGN_CENTRE_VERTICAL); profitOrLiability = new wxStaticText(this, wxID_ANY, wxEmptyString); sizer->Add(profitOrLiability, 0, wxALIGN_CENTRE_VERTICAL); } void MatchedOrder::SetCurrentOrderSummary(const greentop::CurrentOrderSummary& cos) { currentOrderSummary = cos; if (market.HasRunner(currentOrderSummary.getSelectionId())) { greentop::RunnerCatalog runner = market.GetRunner(currentOrderSummary.getSelectionId()); wxString label(runner.getRunnerName().c_str(), wxConvUTF8); runnerName->SetLabel(currentOrderSummary.getSide().getValue() + " " + label); std::ostringstream priceLabelStream; priceLabelStream << std::fixed << std::setprecision(2) << currentOrderSummary.getPriceSize().getPrice(); wxString priceLabel(priceLabelStream.str().c_str(), wxConvUTF8); price->SetLabel(priceLabel); std::string currencySymbol = GetCurrencySymbol(entity::Config::GetConfigValue<std::string>("accountCurrency", "?")); std::ostringstream stakeLabelStream; double sizeMatched = 0; greentop::Optional<double> optionalSizeMatched = currentOrderSummary.getSizeMatched(); if (optionalSizeMatched.isValid()) { sizeMatched = optionalSizeMatched.getValue(); } stakeLabelStream << currencySymbol << std::fixed << std::setprecision(2) << sizeMatched; wxString stakeLabel(stakeLabelStream.str().c_str(), wxConvUTF8); stake->SetLabel(stakeLabel); if (currentOrderSummary.getSide() == greentop::Side::BACK) { profitOrLiabilityLabel->SetLabel(_("Profit: ")); SetBackgroundColour(wxColour(227, 235, 255)); } else if (currentOrderSummary.getSide() == greentop::Side::LAY) { profitOrLiabilityLabel->SetLabel(_("Liability: ")); SetBackgroundColour(wxColour(255, 224, 255)); } UpdateProfitOrLiability(); } } void MatchedOrder::UpdateProfitOrLiability() { std::string currencySymbol = GetCurrencySymbol(entity::Config::GetConfigValue<std::string>("accountCurrency", "?")); std::ostringstream profitOrLiabilityStream; double profit; double sizeMatched = 0; greentop::Optional<double> optionalSizeMatched = currentOrderSummary.getSizeMatched(); if (optionalSizeMatched.isValid()) { sizeMatched = optionalSizeMatched.getValue(); } if (currentOrderSummary.getSide() == greentop::Side::BACK) { profit = sizeMatched * (currentOrderSummary.getPriceSize().getPrice() - 1); } else if (currentOrderSummary.getSide() == greentop::Side::LAY) { profit = sizeMatched * (currentOrderSummary.getPriceSize().getPrice() - 1); } profitOrLiabilityStream << currencySymbol << std::fixed << std::setprecision(2) << profit; wxString label(profitOrLiabilityStream.str().c_str(), wxConvUTF8); profitOrLiability->SetLabel(label); } } <commit_msg>show price matched instead of price requested in matched orders<commit_after>/** * Copyright 2016 Colin Doig. Distributed under the MIT license. */ #include <iomanip> #include <sstream> #include "MatchedOrder.h" #include "Util.h" #include "entity/Config.h" namespace greenthumb { MatchedOrder::MatchedOrder(wxWindow* parent, const wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : CurrentOrder(parent, id, pos, size, style, name) { wxFlexGridSizer* sizer = new wxFlexGridSizer(6, 5, 5); sizer->AddGrowableCol(0, 1); SetSizer(sizer); runnerName = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize); runnerName->SetMinSize(wxSize(150, -1)); sizer->Add(runnerName, 0, wxALIGN_CENTRE_VERTICAL); price = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize); sizer->Add(price, 0, wxALIGN_CENTRE_VERTICAL); wxStaticText* stakeLabel = new wxStaticText(this, wxID_ANY, "Stake: "); sizer->Add(stakeLabel, 0, wxALIGN_CENTRE_VERTICAL); stake = new wxStaticText(this, wxID_ANY, wxEmptyString); sizer->Add(stake, 0, wxALIGN_CENTRE_VERTICAL); profitOrLiabilityLabel = new wxStaticText(this, wxID_ANY, wxEmptyString); profitOrLiabilityLabel->SetMinSize(wxSize(75, -1)); sizer->Add(profitOrLiabilityLabel, 0, wxALIGN_CENTRE_VERTICAL); profitOrLiability = new wxStaticText(this, wxID_ANY, wxEmptyString); sizer->Add(profitOrLiability, 0, wxALIGN_CENTRE_VERTICAL); } void MatchedOrder::SetCurrentOrderSummary(const greentop::CurrentOrderSummary& cos) { currentOrderSummary = cos; if (market.HasRunner(currentOrderSummary.getSelectionId())) { greentop::RunnerCatalog runner = market.GetRunner(currentOrderSummary.getSelectionId()); wxString label(runner.getRunnerName().c_str(), wxConvUTF8); runnerName->SetLabel(currentOrderSummary.getSide().getValue() + " " + label); std::ostringstream priceLabelStream; priceLabelStream << std::fixed << std::setprecision(2) << currentOrderSummary.getAveragePriceMatched(); wxString priceLabel(priceLabelStream.str().c_str(), wxConvUTF8); price->SetLabel(priceLabel); std::string currencySymbol = GetCurrencySymbol(entity::Config::GetConfigValue<std::string>("accountCurrency", "?")); std::ostringstream stakeLabelStream; double sizeMatched = 0; greentop::Optional<double> optionalSizeMatched = currentOrderSummary.getSizeMatched(); if (optionalSizeMatched.isValid()) { sizeMatched = optionalSizeMatched.getValue(); } stakeLabelStream << currencySymbol << std::fixed << std::setprecision(2) << sizeMatched; wxString stakeLabel(stakeLabelStream.str().c_str(), wxConvUTF8); stake->SetLabel(stakeLabel); if (currentOrderSummary.getSide() == greentop::Side::BACK) { profitOrLiabilityLabel->SetLabel(_("Profit: ")); SetBackgroundColour(wxColour(227, 235, 255)); } else if (currentOrderSummary.getSide() == greentop::Side::LAY) { profitOrLiabilityLabel->SetLabel(_("Liability: ")); SetBackgroundColour(wxColour(255, 224, 255)); } UpdateProfitOrLiability(); } } void MatchedOrder::UpdateProfitOrLiability() { std::string currencySymbol = GetCurrencySymbol(entity::Config::GetConfigValue<std::string>("accountCurrency", "?")); std::ostringstream profitOrLiabilityStream; double profit; double sizeMatched = 0; greentop::Optional<double> optionalSizeMatched = currentOrderSummary.getSizeMatched(); if (optionalSizeMatched.isValid()) { sizeMatched = optionalSizeMatched.getValue(); } if (currentOrderSummary.getSide() == greentop::Side::BACK) { profit = sizeMatched * (currentOrderSummary.getPriceSize().getPrice() - 1); } else if (currentOrderSummary.getSide() == greentop::Side::LAY) { profit = sizeMatched * (currentOrderSummary.getPriceSize().getPrice() - 1); } profitOrLiabilityStream << currencySymbol << std::fixed << std::setprecision(2) << profit; wxString label(profitOrLiabilityStream.str().c_str(), wxConvUTF8); profitOrLiability->SetLabel(label); } } <|endoftext|>
<commit_before>#include "CodeGen_C.h" #include "StmtToHtml.h" #include "Output.h" #include "LLVM_Headers.h" #include "LLVM_Output.h" #include <fstream> using namespace llvm; namespace Halide { namespace { // Define the mex wrapper API call for the given func with name pipeline_name. llvm::Function *define_mex_wrapper(const std::string &pipeline_name, llvm::Module *module) { LLVMContext &ctx = module->getContext(); llvm::Function *pipeline = module->getFunction(pipeline_name + "_argv"); internal_assert(pipeline) << "Did not find function '" << pipeline_name << "_argv' in module.\n"; llvm::Function *mex_call_pipeline = module->getFunction("halide_mex_call_pipeline"); internal_assert(mex_call_pipeline) << "Did not find function 'halide_mex_call_pipeline' in module.\n"; llvm::Value *metadata = module->getGlobalVariable(pipeline_name + "_metadata"); internal_assert(metadata) << "Did not find global variable '" << pipeline_name << "_metadata' in module.\n"; llvm::Type *void_ty = llvm::Type::getVoidTy(ctx); llvm::Type *i8_ty = llvm::Type::getInt8Ty(ctx); llvm::Type *i32_ty = llvm::Type::getInt32Ty(ctx); Value *user_context = ConstantPointerNull::get(i8_ty->getPointerTo()); llvm::Type *mxArray_ty = module->getTypeByName("struct.mxArray"); internal_assert(mxArray_ty) << "Did not find mxArray in initial module"; llvm::Type *mxArray_ptr_ty = mxArray_ty->getPointerTo(); llvm::Type *mxArray_ptr_ptr_ty = mxArray_ptr_ty->getPointerTo(); // Create the mexFunction function. llvm::Type *mex_arg_types[] = { i32_ty, mxArray_ptr_ptr_ty, i32_ty, mxArray_ptr_ptr_ty, }; FunctionType *mex_ty = FunctionType::get(void_ty, mex_arg_types, false); llvm::Function *mex = llvm::Function::Create(mex_ty, llvm::GlobalValue::ExternalLinkage, "mexFunction", module); BasicBlock *entry = BasicBlock::Create(ctx, "entry", mex); // Extract the argument values. llvm::Function::arg_iterator mex_args = mex->arg_begin(); Value *nlhs = mex_args++; Value *plhs = mex_args++; Value *nrhs = mex_args++; Value *prhs = mex_args++; IRBuilder<> ir(ctx); ir.SetInsertPoint(entry); Value *call_pipeline_args[] = { user_context, pipeline, metadata, nlhs, plhs, nrhs, prhs, }; ir.CreateCall(mex_call_pipeline, call_pipeline_args); ir.CreateRetVoid(); return mex; } } // namespace void compile_module_to_matlab_object(const Module &module, const std::string &pipeline_name, const std::string &filename) { llvm::LLVMContext context; llvm::Module *llvm_module = compile_module_to_llvm_module(module, context); define_mex_wrapper(pipeline_name, llvm_module); compile_llvm_module_to_object(llvm_module, filename); delete llvm_module; } } // namespace Halide <commit_msg>Removed unused headers.<commit_after>#include "Output.h" #include "LLVM_Headers.h" #include "LLVM_Output.h" using namespace llvm; namespace Halide { namespace { // Define the mex wrapper API call for the given func with name pipeline_name. llvm::Function *define_mex_wrapper(const std::string &pipeline_name, llvm::Module *module) { LLVMContext &ctx = module->getContext(); llvm::Function *pipeline = module->getFunction(pipeline_name + "_argv"); internal_assert(pipeline) << "Did not find function '" << pipeline_name << "_argv' in module.\n"; llvm::Function *mex_call_pipeline = module->getFunction("halide_mex_call_pipeline"); internal_assert(mex_call_pipeline) << "Did not find function 'halide_mex_call_pipeline' in module.\n"; llvm::Value *metadata = module->getGlobalVariable(pipeline_name + "_metadata"); internal_assert(metadata) << "Did not find global variable '" << pipeline_name << "_metadata' in module.\n"; llvm::Type *void_ty = llvm::Type::getVoidTy(ctx); llvm::Type *i8_ty = llvm::Type::getInt8Ty(ctx); llvm::Type *i32_ty = llvm::Type::getInt32Ty(ctx); Value *user_context = ConstantPointerNull::get(i8_ty->getPointerTo()); llvm::Type *mxArray_ty = module->getTypeByName("struct.mxArray"); internal_assert(mxArray_ty) << "Did not find mxArray in initial module"; llvm::Type *mxArray_ptr_ty = mxArray_ty->getPointerTo(); llvm::Type *mxArray_ptr_ptr_ty = mxArray_ptr_ty->getPointerTo(); // Create the mexFunction function. llvm::Type *mex_arg_types[] = { i32_ty, mxArray_ptr_ptr_ty, i32_ty, mxArray_ptr_ptr_ty, }; FunctionType *mex_ty = FunctionType::get(void_ty, mex_arg_types, false); llvm::Function *mex = llvm::Function::Create(mex_ty, llvm::GlobalValue::ExternalLinkage, "mexFunction", module); BasicBlock *entry = BasicBlock::Create(ctx, "entry", mex); // Extract the argument values. llvm::Function::arg_iterator mex_args = mex->arg_begin(); Value *nlhs = mex_args++; Value *plhs = mex_args++; Value *nrhs = mex_args++; Value *prhs = mex_args++; IRBuilder<> ir(ctx); ir.SetInsertPoint(entry); Value *call_pipeline_args[] = { user_context, pipeline, metadata, nlhs, plhs, nrhs, prhs, }; ir.CreateCall(mex_call_pipeline, call_pipeline_args); ir.CreateRetVoid(); return mex; } } // namespace void compile_module_to_matlab_object(const Module &module, const std::string &pipeline_name, const std::string &filename) { llvm::LLVMContext context; llvm::Module *llvm_module = compile_module_to_llvm_module(module, context); define_mex_wrapper(pipeline_name, llvm_module); compile_llvm_module_to_object(llvm_module, filename); delete llvm_module; } } // namespace Halide <|endoftext|>
<commit_before> #include "llvm/ADT/Triple.h" #include "llvm/ADT/SmallString.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/AsmParser/Parser.h" #include "llvm/Bitcode/BitcodeWriter.h" #include "llvm/CodeGen/CommandFlags.h" #include "llvm/CodeGen/LinkAllAsmWriterComponents.h" #include "llvm/CodeGen/LinkAllCodegenComponents.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/IRPrintingPasses.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/Verifier.h" #include "llvm/IRReader/IRReader.h" #include "llvm/Linker/Linker.h" #include "llvm/MC/SubtargetFeature.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Pass.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileUtilities.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/Host.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Path.h" #include "llvm/Support/Program.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetSubtargetInfo.h" #include "llvm/Transforms/Scalar.h" #include <memory> #include <string> #include "DynamicCallCounter.h" #include "StaticCallCounter.h" #include "config.h" using namespace llvm; using std::string; using std::unique_ptr; using std::vector; using llvm::sys::ExecuteAndWait; using llvm::sys::findProgramByName; using llvm::legacy::PassManager; enum class AnalysisType { STATIC, DYNAMIC, }; static cl::OptionCategory callCounterCategory{"call counter options"}; static cl::opt<string> inPath{cl::Positional, cl::desc{"<Module to analyze>"}, cl::value_desc{"bitcode filename"}, cl::init(""), cl::Required, cl::cat{callCounterCategory}}; static cl::opt<AnalysisType> analysisType{ cl::desc{"Select analyis type:"}, cl::values(clEnumValN(AnalysisType::STATIC, "static", "Count static direct calls."), clEnumValN(AnalysisType::DYNAMIC, "dynamic", "Count dynamic direct calls.") ), cl::Required, cl::cat{callCounterCategory}}; static cl::opt<string> outFile{"o", cl::desc{"Filename of the instrumented program"}, cl::value_desc{"filename"}, cl::init(""), cl::cat{callCounterCategory}}; static cl::opt<char> optLevel{ "O", cl::desc{"Optimization level. [-O0, -O1, -O2, or -O3] (default = '-O2')"}, cl::Prefix, cl::ZeroOrMore, cl::init('2'), cl::cat{callCounterCategory}}; static cl::list<string> libPaths{"L", cl::Prefix, cl::desc{"Specify a library search path"}, cl::value_desc{"directory"}, cl::cat{callCounterCategory}}; static cl::list<string> libraries{"l", cl::Prefix, cl::desc{"Specify libraries to link against"}, cl::value_desc{"library prefix"}, cl::cat{callCounterCategory}}; static void compile(Module& m, StringRef outputPath) { string err; Triple triple = Triple(m.getTargetTriple()); Target const* target = TargetRegistry::lookupTarget(MArch, triple, err); if (!target) { report_fatal_error("Unable to find target:\n " + err); } CodeGenOpt::Level level = CodeGenOpt::Default; switch (optLevel) { default: report_fatal_error("Invalid optimization level.\n"); // No fall through case '0': level = CodeGenOpt::None; break; case '1': level = CodeGenOpt::Less; break; case '2': level = CodeGenOpt::Default; break; case '3': level = CodeGenOpt::Aggressive; break; } string FeaturesStr; TargetOptions options = InitTargetOptionsFromCodeGenFlags(); unique_ptr<TargetMachine> machine( target->createTargetMachine(triple.getTriple(), MCPU, FeaturesStr, options, getRelocModel(), CMModel, level)); assert(machine.get() && "Could not allocate target machine!"); if (FloatABIForCalls != FloatABI::Default) { options.FloatABIType = FloatABIForCalls; } std::error_code errc; auto out = std::make_unique<tool_output_file>(outputPath, errc, sys::fs::F_None); if (!out) { report_fatal_error("Unable to create file:\n " + errc.message()); } // Build up all of the passes that we want to do to the module. legacy::PassManager pm; // Add target specific info and transforms TargetLibraryInfoImpl tlii(triple); pm.add(new TargetLibraryInfoWrapperPass(tlii)); m.setDataLayout(machine->createDataLayout()); { // Bound this scope raw_pwrite_stream* os(&out->os()); FileType = TargetMachine::CGFT_ObjectFile; std::unique_ptr<buffer_ostream> bos; if (!out->os().supportsSeeking()) { bos = std::make_unique<buffer_ostream>(*os); os = bos.get(); } // Ask the target to add backend passes as necessary. if (machine->addPassesToEmitFile(pm, *os, FileType)) { report_fatal_error("target does not support generation " "of this file type!\n"); } // Before executing passes, print the final values of the LLVM options. cl::PrintOptionValues(); pm.run(m); } // Keep the output binary if we've been successful to this point. out->keep(); } static void link(StringRef objectFile, StringRef outputFile) { auto clang = findProgramByName("clang++"); string opt("-O"); opt += optLevel; if (!clang) { report_fatal_error("Unable to find clang."); } vector<string> args{clang.get(), opt, "-o", outputFile, objectFile}; for (auto& libPath : libPaths) { args.push_back("-L" + libPath); } for (auto& library : libraries) { args.push_back("-l" + library); } vector<char const*> charArgs; for (auto& arg : args) { charArgs.push_back(arg.c_str()); } charArgs.push_back(nullptr); for (auto& arg : args) { outs() << arg.c_str() << " "; } outs() << "\n"; string err; if (-1 == ExecuteAndWait( clang.get(), &charArgs[0], nullptr, nullptr, 0, 0, &err)) { report_fatal_error("Unable to link output file."); } } static void generateBinary(Module& m, StringRef outputFilename) { // Compiling to native should allow things to keep working even when the // version of clang on the system and the version of LLVM used to compile // the tool don't quite match up. string objectFile = outputFilename.str() + ".o"; compile(m, objectFile); link(objectFile, outputFilename); } static void saveModule(Module const& m, StringRef filename) { std::error_code errc; raw_fd_ostream out(filename.data(), errc, sys::fs::F_None); if (errc) { report_fatal_error("error saving llvm module to '" + filename + "': \n" + errc.message()); } WriteBitcodeToFile(&m, out); } static void prepareLinkingPaths(SmallString<32> invocationPath) { // First search the directory of the binary for the library, in case it is // all bundled together. sys::path::remove_filename(invocationPath); if (!invocationPath.empty()) { libPaths.push_back(invocationPath.str()); } // If the builder doesn't plan on installing it, we still need to get to the // runtime library somehow, so just build in the path to the temporary one. #ifdef CMAKE_INSTALL_PREFIX libPaths.push_back(CMAKE_INSTALL_PREFIX "/lib"); #elif defined(CMAKE_TEMP_LIBRARY_PATH) libPaths.push_back(CMAKE_TEMP_LIBRARY_PATH); #elif defined(TEMP_LIBRARY_PATH) // This is a bit of a hack libPaths.push_back(TEMP_LIBRARY_PATH "/Debug+Asserts/lib/"); libPaths.push_back(TEMP_LIBRARY_PATH "/Release+Asserts/lib/"); libPaths.push_back(TEMP_LIBRARY_PATH "/Debug/lib/"); libPaths.push_back(TEMP_LIBRARY_PATH "/Release/lib/"); #endif libraries.push_back(RUNTIME_LIB); libraries.push_back("rt"); } static void instrumentForDynamicCount(Module& m) { InitializeAllTargets(); InitializeAllTargetMCs(); InitializeAllAsmPrinters(); InitializeAllAsmParsers(); cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); if (outFile.getValue() == "") { errs() << "-o command line option must be specified.\n"; exit(-1); } // Build up all of the passes that we want to run on the module. legacy::PassManager pm; pm.add(new callcounter::DynamicCallCounter()); pm.add(createVerifierPass()); pm.run(m); generateBinary(m, outFile); saveModule(m, outFile + ".callcounter.bc"); } struct StaticCountPrinter : public ModulePass { static char ID; raw_ostream& out; explicit StaticCountPrinter(raw_ostream& out) : ModulePass(ID), out(out) {} bool runOnModule(Module& m) override { getAnalysis<callcounter::StaticCallCounter>().print(out, &m); return false; } void getAnalysisUsage(AnalysisUsage& au) const override { au.addRequired<callcounter::StaticCallCounter>(); au.setPreservesAll(); } }; char StaticCountPrinter::ID = 0; static void countStaticCalls(Module& m) { // Build up all of the passes that we want to run on the module. legacy::PassManager pm; pm.add(new callcounter::StaticCallCounter()); pm.add(new StaticCountPrinter(outs())); pm.run(m); } int main(int argc, char** argv) { // This boilerplate provides convenient stack traces and clean LLVM exit // handling. It also initializes the built in support for convenient // command line option handling. sys::PrintStackTraceOnErrorSignal(argv[0]); llvm::PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj shutdown; cl::HideUnrelatedOptions(callCounterCategory); cl::ParseCommandLineOptions(argc, argv); // Construct an IR file from the filename passed on the command line. SMDiagnostic err; LLVMContext context; unique_ptr<Module> module = parseIRFile(inPath.getValue(), err, context); if (!module.get()) { errs() << "Error reading bitcode file: " << inPath << "\n"; err.print(argv[0], errs()); return -1; } if (AnalysisType::DYNAMIC == analysisType) { prepareLinkingPaths(StringRef(argv[0])); instrumentForDynamicCount(*module); } else { countStaticCalls(*module); } return 0; } <commit_msg>Update to llvm 6.0<commit_after> #include "llvm/ADT/Triple.h" #include "llvm/ADT/SmallString.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/AsmParser/Parser.h" #include "llvm/Bitcode/BitcodeWriter.h" #include "llvm/CodeGen/CommandFlags.def" #include "llvm/CodeGen/LinkAllAsmWriterComponents.h" #include "llvm/CodeGen/LinkAllCodegenComponents.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/IRPrintingPasses.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/Verifier.h" #include "llvm/IRReader/IRReader.h" #include "llvm/Linker/Linker.h" #include "llvm/MC/SubtargetFeature.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Pass.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileUtilities.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/Host.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Path.h" #include "llvm/Support/Program.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/Scalar.h" #include <memory> #include <string> #include "DynamicCallCounter.h" #include "StaticCallCounter.h" #include "config.h" using namespace llvm; using std::string; using std::unique_ptr; using std::vector; using llvm::sys::ExecuteAndWait; using llvm::sys::findProgramByName; using llvm::legacy::PassManager; enum class AnalysisType { STATIC, DYNAMIC, }; static cl::OptionCategory callCounterCategory{"call counter options"}; static cl::opt<string> inPath{cl::Positional, cl::desc{"<Module to analyze>"}, cl::value_desc{"bitcode filename"}, cl::init(""), cl::Required, cl::cat{callCounterCategory}}; static cl::opt<AnalysisType> analysisType{ cl::desc{"Select analyis type:"}, cl::values(clEnumValN(AnalysisType::STATIC, "static", "Count static direct calls."), clEnumValN(AnalysisType::DYNAMIC, "dynamic", "Count dynamic direct calls.") ), cl::Required, cl::cat{callCounterCategory}}; static cl::opt<string> outFile{"o", cl::desc{"Filename of the instrumented program"}, cl::value_desc{"filename"}, cl::init(""), cl::cat{callCounterCategory}}; static cl::opt<char> optLevel{ "O", cl::desc{"Optimization level. [-O0, -O1, -O2, or -O3] (default = '-O2')"}, cl::Prefix, cl::ZeroOrMore, cl::init('2'), cl::cat{callCounterCategory}}; static cl::list<string> libPaths{"L", cl::Prefix, cl::desc{"Specify a library search path"}, cl::value_desc{"directory"}, cl::cat{callCounterCategory}}; static cl::list<string> libraries{"l", cl::Prefix, cl::desc{"Specify libraries to link against"}, cl::value_desc{"library prefix"}, cl::cat{callCounterCategory}}; static void compile(Module& m, StringRef outputPath) { string err; Triple triple = Triple(m.getTargetTriple()); Target const* target = TargetRegistry::lookupTarget(MArch, triple, err); if (!target) { report_fatal_error("Unable to find target:\n " + err); } CodeGenOpt::Level level = CodeGenOpt::Default; switch (optLevel) { default: report_fatal_error("Invalid optimization level.\n"); // No fall through case '0': level = CodeGenOpt::None; break; case '1': level = CodeGenOpt::Less; break; case '2': level = CodeGenOpt::Default; break; case '3': level = CodeGenOpt::Aggressive; break; } string FeaturesStr; TargetOptions options = InitTargetOptionsFromCodeGenFlags(); unique_ptr<TargetMachine> machine( target->createTargetMachine(triple.getTriple(), MCPU, FeaturesStr, options, getRelocModel(), CMModel.getValue(), level)); assert(machine.get() && "Could not allocate target machine!"); if (FloatABIForCalls != FloatABI::Default) { options.FloatABIType = FloatABIForCalls; } std::error_code errc; auto out = std::make_unique<ToolOutputFile>(outputPath, errc, sys::fs::F_None); if (!out) { report_fatal_error("Unable to create file:\n " + errc.message()); } // Build up all of the passes that we want to do to the module. legacy::PassManager pm; // Add target specific info and transforms TargetLibraryInfoImpl tlii(triple); pm.add(new TargetLibraryInfoWrapperPass(tlii)); m.setDataLayout(machine->createDataLayout()); { // Bound this scope raw_pwrite_stream* os(&out->os()); FileType = TargetMachine::CGFT_ObjectFile; std::unique_ptr<buffer_ostream> bos; if (!out->os().supportsSeeking()) { bos = std::make_unique<buffer_ostream>(*os); os = bos.get(); } // Ask the target to add backend passes as necessary. if (machine->addPassesToEmitFile(pm, *os, FileType)) { report_fatal_error("target does not support generation " "of this file type!\n"); } // Before executing passes, print the final values of the LLVM options. cl::PrintOptionValues(); pm.run(m); } // Keep the output binary if we've been successful to this point. out->keep(); } static void link(StringRef objectFile, StringRef outputFile) { auto clang = findProgramByName("clang++"); string opt("-O"); opt += optLevel; if (!clang) { report_fatal_error("Unable to find clang."); } vector<string> args{clang.get(), opt, "-o", outputFile, objectFile}; for (auto& libPath : libPaths) { args.push_back("-L" + libPath); } for (auto& library : libraries) { args.push_back("-l" + library); } vector<char const*> charArgs; for (auto& arg : args) { charArgs.push_back(arg.c_str()); } charArgs.push_back(nullptr); for (auto& arg : args) { outs() << arg.c_str() << " "; } outs() << "\n"; string err; if (-1 == ExecuteAndWait( clang.get(), &charArgs[0], nullptr, {}, 0, 0, &err)) { report_fatal_error("Unable to link output file."); } } static void generateBinary(Module& m, StringRef outputFilename) { // Compiling to native should allow things to keep working even when the // version of clang on the system and the version of LLVM used to compile // the tool don't quite match up. string objectFile = outputFilename.str() + ".o"; compile(m, objectFile); link(objectFile, outputFilename); } static void saveModule(Module const& m, StringRef filename) { std::error_code errc; raw_fd_ostream out(filename.data(), errc, sys::fs::F_None); if (errc) { report_fatal_error("error saving llvm module to '" + filename + "': \n" + errc.message()); } WriteBitcodeToFile(&m, out); } static void prepareLinkingPaths(SmallString<32> invocationPath) { // First search the directory of the binary for the library, in case it is // all bundled together. sys::path::remove_filename(invocationPath); if (!invocationPath.empty()) { libPaths.push_back(invocationPath.str()); } // If the builder doesn't plan on installing it, we still need to get to the // runtime library somehow, so just build in the path to the temporary one. #ifdef CMAKE_INSTALL_PREFIX libPaths.push_back(CMAKE_INSTALL_PREFIX "/lib"); #elif defined(CMAKE_TEMP_LIBRARY_PATH) libPaths.push_back(CMAKE_TEMP_LIBRARY_PATH); #elif defined(TEMP_LIBRARY_PATH) // This is a bit of a hack libPaths.push_back(TEMP_LIBRARY_PATH "/Debug+Asserts/lib/"); libPaths.push_back(TEMP_LIBRARY_PATH "/Release+Asserts/lib/"); libPaths.push_back(TEMP_LIBRARY_PATH "/Debug/lib/"); libPaths.push_back(TEMP_LIBRARY_PATH "/Release/lib/"); #endif libraries.push_back(RUNTIME_LIB); libraries.push_back("rt"); } static void instrumentForDynamicCount(Module& m) { InitializeAllTargets(); InitializeAllTargetMCs(); InitializeAllAsmPrinters(); InitializeAllAsmParsers(); cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); if (outFile.getValue() == "") { errs() << "-o command line option must be specified.\n"; exit(-1); } // Build up all of the passes that we want to run on the module. legacy::PassManager pm; pm.add(new callcounter::DynamicCallCounter()); pm.add(createVerifierPass()); pm.run(m); generateBinary(m, outFile); saveModule(m, outFile + ".callcounter.bc"); } struct StaticCountPrinter : public ModulePass { static char ID; raw_ostream& out; explicit StaticCountPrinter(raw_ostream& out) : ModulePass(ID), out(out) {} bool runOnModule(Module& m) override { getAnalysis<callcounter::StaticCallCounter>().print(out, &m); return false; } void getAnalysisUsage(AnalysisUsage& au) const override { au.addRequired<callcounter::StaticCallCounter>(); au.setPreservesAll(); } }; char StaticCountPrinter::ID = 0; static void countStaticCalls(Module& m) { // Build up all of the passes that we want to run on the module. legacy::PassManager pm; pm.add(new callcounter::StaticCallCounter()); pm.add(new StaticCountPrinter(outs())); pm.run(m); } int main(int argc, char** argv) { // This boilerplate provides convenient stack traces and clean LLVM exit // handling. It also initializes the built in support for convenient // command line option handling. sys::PrintStackTraceOnErrorSignal(argv[0]); llvm::PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj shutdown; cl::HideUnrelatedOptions(callCounterCategory); cl::ParseCommandLineOptions(argc, argv); // Construct an IR file from the filename passed on the command line. SMDiagnostic err; LLVMContext context; unique_ptr<Module> module = parseIRFile(inPath.getValue(), err, context); if (!module.get()) { errs() << "Error reading bitcode file: " << inPath << "\n"; err.print(argv[0], errs()); return -1; } if (AnalysisType::DYNAMIC == analysisType) { prepareLinkingPaths(StringRef(argv[0])); instrumentForDynamicCount(*module); } else { countStaticCalls(*module); } return 0; } <|endoftext|>
<commit_before>/************************************************************************************* garlic-player: SMIL Player for Digital Signage Copyright (C) 2016 Nikolaos Saghiadinos <ns@smil-control.com> This file is part of the garlic-player source code This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. *************************************************************************************/ #include "configuration.h" #include <QXmlStreamReader> #include <QString> #include <memory> #include <mutex> /** * @brief TConfiguration::TConfiguration * @param UserConfig */ TConfiguration::TConfiguration(QSettings *UserConfig, QObject *parent) : QObject(parent) { setUserConfig(UserConfig); determineUuid(); determinePlayerName(); determineOS(); setTimeZone(QTimeZone::systemTimeZoneId()); // ugly workaround from https://stackoverflow.com/questions/21976264/qt-isodate-formatted-date-time-including-timezone // cause otherwise we get no time zone in date string setStartTime(QDateTime::currentDateTime().toOffsetFromUtc(QDateTime::currentDateTime().offsetFromUtc()).toString(Qt::ISODate)); determineUserAgent(); } QString TConfiguration::getLastPlayedIndexPath() { return getUserConfigByKey("last_played_index_path"); } void TConfiguration::setLastPlayedIndexPath(const QString &value) { setUserConfigByKey("last_played_index_path", value); } QSettings *TConfiguration::getUserConfig() const { return UserConfig; } void TConfiguration::setUserConfig(QSettings *value) { UserConfig = value; } QString TConfiguration::getUserConfigByKey(QString key) { return UserConfig->value(key, "").toString(); } void TConfiguration::setUserConfigByKey(QString key, QString value) { UserConfig->setValue(key, value); } QString TConfiguration::getPlayerName() const { return player_name; } void TConfiguration::setPlayerName(const QString &value) { player_name = value; setUserConfigByKey("player_name", value); } QString TConfiguration::getUuid() const { return uuid; } void TConfiguration::setUuid(const QString &value) { uuid = value; setUserConfigByKey("uuid", value); } QString TConfiguration::getUserAgent() const { return user_agent; } void TConfiguration::setUserAgent(const QString &value) { user_agent = value; } QString TConfiguration::getIndexUri() { return index_uri; } void TConfiguration::setIndexUri(const QString &value) { index_uri = value; } void TConfiguration::determineIndexUri(QString path) { if (path != "") { setUserConfigByKey("index_uri", path); setIndexUri(path); } else if (getUserConfigByKey("index_uri") != "") // get from intern config { setIndexUri(getUserConfigByKey("index_uri")); } else { checkConfigXML(); } if (index_uri != "" && index_uri.mid(0, 4) != "http" && index_uri.mid(0, 3) != "ftp" && index_uri.mid(0, 1) != "/") // https is includered in http! { setUserConfigByKey("index_uri", base_path+index_uri); setIndexUri( base_path+index_uri); } determineIndexPath(); } void TConfiguration::setIndexPath(const QString &value) { index_path = value; } void TConfiguration::determineIndexPath() { if (index_uri.mid(0, 4) == "http" || index_uri.mid(0, 3) == "ftp") { QUrl url(index_uri); setIndexPath(url.adjusted(QUrl::RemoveFilename | QUrl::RemoveQuery | QUrl::RemoveFragment | QUrl::RemovePort).toString()); if (index_path.mid(index_path.length()-1, 1) != "/") setIndexPath(index_path+"/"); } else { QFileInfo fi(index_uri); setIndexPath(fi.path()+"/"); } } QString TConfiguration::getIndexPath() { return index_path; } QString TConfiguration::getOS() const { return os; } void TConfiguration::setOS(const QString &value) { os = value; } QString TConfiguration::getBasePath() const { return base_path; } void TConfiguration::setBasePath(const QString &value) { base_path = value; } void TConfiguration::determineBasePath(QString absolute_path_to_bin) { if (absolute_path_to_bin.contains("/bin")) setBasePath(absolute_path_to_bin.mid(0, absolute_path_to_bin.length()-3)); // "/" is set when xyz/bin else setBasePath(absolute_path_to_bin); if (base_path.mid(base_path.length()-1, 1) != "/") setBasePath(base_path+"/"); } /** * @brief TConfiguration::getPaths returns paths. * Values can be config, var, media or base * @param path_name * @return */ QString TConfiguration::getPaths(QString path_name) { QString ret = base_path; if (path_name == "cache") ret = cache_dir; else if (path_name == "logs") ret = log_dir; return ret; } void TConfiguration::createDirectories() { #if defined Q_OS_WIN32 // QStandardPaths::CacheLocation in windows 7 is set to appdir (bin), which should not be writable after installation in Program Files cache_dir = QStandardPaths::locate(QStandardPaths::AppLocalDataLocation, QString(), QStandardPaths::LocateDirectory) + getAppName() + "/cache/"; log_dir = QStandardPaths::locate(QStandardPaths::AppLocalDataLocation, QString(), QStandardPaths::LocateDirectory) + getAppName() + "/logs/"; #else cache_dir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation); log_dir = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/logs/"; #endif createDirectoryIfNotExist(cache_dir); createDirectoryIfNotExist(log_dir); } void TConfiguration::determineUserAgent() { setUserAgent("GAPI/1.0 (UUID:"+getUuid()+"; NAME:"+getPlayerName()+") garlic-"+getOS()+"/"+getVersion()+" (MODEL:Garlic)"); } void TConfiguration::checkConfigXML() { QFile file(base_path+"config.xml"); if (file.exists() && file.open(QIODevice::ReadOnly)) { QXmlStreamReader reader(&file); while (!reader.atEnd()) { reader.readNext(); if (reader.isStartElement()) { if (reader.name() == "prop" && reader.attributes().value("name") == "content.serverUrl") { setUserConfigByKey("index_uri", reader.attributes().value("value").toString()); setIndexUri(reader.attributes().value("value").toString()); } } } file.rename(base_path+"config.xml", base_path+"config_readed.xml"); } } QString TConfiguration::getStartTime() const { return start_time; } void TConfiguration::setStartTime(const QString &value) { start_time = value; } QString TConfiguration::getTimeZone() const { return time_zone; } void TConfiguration::setTimeZone(const QString &value) { time_zone = value; } void TConfiguration::createDirectoryIfNotExist(QString path) { QDir dir; dir.setPath(path); if (!dir.exists() && !dir.mkpath(".")) qCritical(SmilParser) << "Failed to create " << dir.path() << "\r"; return; } void TConfiguration::determineUuid() { setUuid(getUserConfigByKey("uuid")); if (getUuid() == "") { setUuid(QUuid::createUuid().toString().mid(1, 36)); UserConfig->setValue("uuid", getUuid()); } } void TConfiguration::determinePlayerName() { setPlayerName(getUserConfigByKey("player_name")); if (getPlayerName() == "") { setPlayerName(getUuid().mid(24,12)); UserConfig->setValue("player_name", getPlayerName()); } } void TConfiguration::determineOS() { #if defined Q_OS_ANDROID setOS("android"); #elif defined Q_OS_BSD4 setOS("bsd4"); #elif defined Q_OS_DARWIN setOS("darwin"); #elif defined Q_OS_FREEBSD setOS("freebsd"); #elif defined Q_OS_HURD setOS("hurd"); #elif defined Q_OS_IOS setOS("ios"); #elif defined Q_OS_LINUX setOS("linux"); #elif defined Q_OS_NETBSD setOS("netbsd"); #elif defined Q_OS_OPENBSD setOS("openbsd"); #elif defined Q_OS_OSX setOS("osx"); #elif defined Q_OS_WIN32 setOS("windows"); #elif defined Q_OS_WINPHONE setOS("winphone"); #elif defined Q_OS_WINRT setOS("winrt"); #else setOS("unknown"); #endif } <commit_msg>bugfixes<commit_after>/************************************************************************************* garlic-player: SMIL Player for Digital Signage Copyright (C) 2016 Nikolaos Saghiadinos <ns@smil-control.com> This file is part of the garlic-player source code This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. *************************************************************************************/ #include "configuration.h" #include <QXmlStreamReader> #include <QString> #include <memory> #include <mutex> /** * @brief TConfiguration::TConfiguration * @param UserConfig */ TConfiguration::TConfiguration(QSettings *UserConfig, QObject *parent) : QObject(parent) { setUserConfig(UserConfig); determineUuid(); determinePlayerName(); determineOS(); setTimeZone(QTimeZone::systemTimeZoneId()); // ugly workaround from https://stackoverflow.com/questions/21976264/qt-isodate-formatted-date-time-including-timezone // cause otherwise we get no time zone in date string setStartTime(QDateTime::currentDateTime().toOffsetFromUtc(QDateTime::currentDateTime().offsetFromUtc()).toString(Qt::ISODate)); determineUserAgent(); } QString TConfiguration::getLastPlayedIndexPath() { return getUserConfigByKey("last_played_index_path"); } void TConfiguration::setLastPlayedIndexPath(const QString &value) { setUserConfigByKey("last_played_index_path", value); } QSettings *TConfiguration::getUserConfig() const { return UserConfig; } void TConfiguration::setUserConfig(QSettings *value) { UserConfig = value; } QString TConfiguration::getUserConfigByKey(QString key) { return UserConfig->value(key, "").toString(); } void TConfiguration::setUserConfigByKey(QString key, QString value) { UserConfig->setValue(key, value); } QString TConfiguration::getPlayerName() const { return player_name; } void TConfiguration::setPlayerName(const QString &value) { player_name = value; setUserConfigByKey("player_name", value); } QString TConfiguration::getUuid() const { return uuid; } void TConfiguration::setUuid(const QString &value) { uuid = value; setUserConfigByKey("uuid", value); } QString TConfiguration::getUserAgent() const { return user_agent; } void TConfiguration::setUserAgent(const QString &value) { user_agent = value; } QString TConfiguration::getIndexUri() { return index_uri; } void TConfiguration::setIndexUri(const QString &value) { index_uri = value; } void TConfiguration::determineIndexUri(QString path) { if (path != "") { setUserConfigByKey("index_uri", path); setIndexUri(path); } else if (getUserConfigByKey("index_uri") != "") // get from intern config { setIndexUri(getUserConfigByKey("index_uri")); } else { checkConfigXML(); } if (index_uri != "" && index_uri.mid(0, 4) != "http" && index_uri.mid(0, 3) != "ftp" && index_uri.mid(0, 1) != "/") // https is includered in http! { setUserConfigByKey("index_uri", base_path+index_uri); setIndexUri( base_path+index_uri); } determineIndexPath(); } void TConfiguration::setIndexPath(const QString &value) { index_path = value; } void TConfiguration::determineIndexPath() { if (index_uri.mid(0, 4) == "http" || index_uri.mid(0, 3) == "ftp") { QUrl url(index_uri); setIndexPath(url.adjusted(QUrl::RemoveFilename | QUrl::RemoveQuery | QUrl::RemoveFragment | QUrl::RemovePort).toString()); if (index_path.mid(index_path.length()-1, 1) != "/") setIndexPath(index_path+"/"); } else { QFileInfo fi(index_uri); setIndexPath(fi.path()+"/"); } } QString TConfiguration::getIndexPath() { return index_path; } QString TConfiguration::getOS() const { return os; } void TConfiguration::setOS(const QString &value) { os = value; } QString TConfiguration::getBasePath() const { return base_path; } void TConfiguration::setBasePath(const QString &value) { base_path = value; } void TConfiguration::determineBasePath(QString absolute_path_to_bin) { if (absolute_path_to_bin.contains("/bin")) setBasePath(absolute_path_to_bin.mid(0, absolute_path_to_bin.length()-3)); // "/" is set when xyz/bin else setBasePath(absolute_path_to_bin); if (base_path.mid(base_path.length()-1, 1) != "/") setBasePath(base_path+"/"); } /** * @brief TConfiguration::getPaths returns paths. * Values can be config, var, media or base * @param path_name * @return */ QString TConfiguration::getPaths(QString path_name) { QString ret = base_path; if (path_name == "cache") ret = cache_dir; else if (path_name == "logs") ret = log_dir; return ret; } void TConfiguration::createDirectories() { #if defined Q_OS_WIN32 // QStandardPaths::CacheLocation in windows 7 is set to appdir (bin), which should not be writable after installation in Program Files cache_dir = QStandardPaths::locate(QStandardPaths::AppLocalDataLocation, QString(), QStandardPaths::LocateDirectory) + getAppName() + "/cache/"; log_dir = QStandardPaths::locate(QStandardPaths::AppLocalDataLocation, QString(), QStandardPaths::LocateDirectory) + getAppName() + "/logs/"; #else cache_dir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation)+ "/"; log_dir = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/logs/"; #endif createDirectoryIfNotExist(cache_dir); createDirectoryIfNotExist(log_dir); } void TConfiguration::determineUserAgent() { setUserAgent("GAPI/1.0 (UUID:"+getUuid()+"; NAME:"+getPlayerName()+") garlic-"+getOS()+"/"+getVersion()+" (MODEL:Garlic)"); } void TConfiguration::checkConfigXML() { QFile file(base_path+"config.xml"); if (file.exists() && file.open(QIODevice::ReadOnly)) { QXmlStreamReader reader(&file); while (!reader.atEnd()) { reader.readNext(); if (reader.isStartElement()) { if (reader.name() == "prop" && reader.attributes().value("name") == "content.serverUrl") { setUserConfigByKey("index_uri", reader.attributes().value("value").toString()); setIndexUri(reader.attributes().value("value").toString()); } } } file.rename(base_path+"config.xml", base_path+"config_readed.xml"); } } QString TConfiguration::getStartTime() const { return start_time; } void TConfiguration::setStartTime(const QString &value) { start_time = value; } QString TConfiguration::getTimeZone() const { return time_zone; } void TConfiguration::setTimeZone(const QString &value) { time_zone = value; } void TConfiguration::createDirectoryIfNotExist(QString path) { QDir dir; dir.setPath(path); if (!dir.exists() && !dir.mkpath(".")) qCritical(SmilParser) << "Failed to create " << dir.path() << "\r"; return; } void TConfiguration::determineUuid() { setUuid(getUserConfigByKey("uuid")); if (getUuid() == "") { setUuid(QUuid::createUuid().toString().mid(1, 36)); UserConfig->setValue("uuid", getUuid()); } } void TConfiguration::determinePlayerName() { setPlayerName(getUserConfigByKey("player_name")); if (getPlayerName() == "") { setPlayerName(getUuid().mid(24,12)); UserConfig->setValue("player_name", getPlayerName()); } } void TConfiguration::determineOS() { #if defined Q_OS_ANDROID setOS("android"); #elif defined Q_OS_BSD4 setOS("bsd4"); #elif defined Q_OS_DARWIN setOS("darwin"); #elif defined Q_OS_FREEBSD setOS("freebsd"); #elif defined Q_OS_HURD setOS("hurd"); #elif defined Q_OS_IOS setOS("ios"); #elif defined Q_OS_LINUX setOS("linux"); #elif defined Q_OS_NETBSD setOS("netbsd"); #elif defined Q_OS_OPENBSD setOS("openbsd"); #elif defined Q_OS_OSX setOS("osx"); #elif defined Q_OS_WIN32 setOS("windows"); #elif defined Q_OS_WINPHONE setOS("winphone"); #elif defined Q_OS_WINRT setOS("winrt"); #else setOS("unknown"); #endif } <|endoftext|>
<commit_before><commit_msg>coverity#705269 Missing break in switch<commit_after><|endoftext|>
<commit_before>#ifndef AP_MOVING_OBJECT #define AP_MOVING_OBJECT #include <Ogre.h> #include "net/NetObject.h" #include "net/Serializable.h" #include "RectBoundaries.hpp" namespace ap { class MovableState : public net::Serializable { public: Ogre::Vector3 location; Ogre::Quaternion orientation; Ogre::Vector3 velocity; MovableState(Ogre::Vector3 startingVelocity); ~MovableState() { /* Do nothing */ } int serialize(uint8 *buffer, int start, int buflength) const; int unserialize(uint8 *buffer, int start); }; class MovableControl : public net::Serializable { public: float accelerationFwd; float velocityCWiseTurning; MovableControl(); ~MovableControl() { /* Do nothing */ } int serialize(uint8 *buffer, int start, int buflength) const; int unserialize(uint8 *buffer, int start); }; class MovingObject : public net::NetObject { public: MovingObject(float nFriction = 0.05f, Ogre::Vector3 startingSpeed = Ogre::Vector3::ZERO); virtual ~MovingObject(); void setWorldBoundaries(float top, float bottom, float left, float right); void setMaxSpeed(float speed); void setVelocity(Ogre::Vector3 velocity); Ogre::Vector3 getVelocity() const { return state.velocity; }; void setPosition(Ogre::Vector3 pos) { state.location = pos; }; void addForwardAcceleration(float amount); void addClockwiseTurningSpeed(float amountRad); void setForwardAcceleration(float amount) { control.accelerationFwd = amount; } void setClockwiseTurningSpeed(float amount) { control.velocityCWiseTurning = amount; } Ogre::Vector3 getFacing() const; Ogre::SceneNode* getOwnerNode() const { return pOwnerNode; } void setOwnerNode(Ogre::SceneNode *node) { pOwnerNode = node; } bool hasOwnerNode() const { return (!pOwnerNode); } void update(unsigned long msSinceLast); //NetObject serialization int serialize(uint8 *buffer, int start, int buflength) const; int unserialize(uint8 *buffer, int start); NetObject *create(int id); private: Ogre::Vector3 initialFacing; MovableState state; MovableControl control; float friction; RectBoundaries worldBoundaries; float maxSpeedSquared; Ogre::SceneNode *pOwnerNode; void updateVelocity(unsigned long msSinceLast); void updateFacing(unsigned long msSinceLast); void updatePosition(unsigned long msSinceLast); }; } // namespace ap #endif <commit_msg>Fixed hasOwnerNode()-method, used to be negated for some reason.<commit_after>#ifndef AP_MOVING_OBJECT #define AP_MOVING_OBJECT #include <Ogre.h> #include "net/NetObject.h" #include "net/Serializable.h" #include "RectBoundaries.hpp" namespace ap { class MovableState : public net::Serializable { public: Ogre::Vector3 location; Ogre::Quaternion orientation; Ogre::Vector3 velocity; MovableState(Ogre::Vector3 startingVelocity); ~MovableState() { /* Do nothing */ } int serialize(uint8 *buffer, int start, int buflength) const; int unserialize(uint8 *buffer, int start); }; class MovableControl : public net::Serializable { public: float accelerationFwd; float velocityCWiseTurning; MovableControl(); ~MovableControl() { /* Do nothing */ } int serialize(uint8 *buffer, int start, int buflength) const; int unserialize(uint8 *buffer, int start); }; class MovingObject : public net::NetObject { public: MovingObject(float nFriction = 0.05f, Ogre::Vector3 startingSpeed = Ogre::Vector3::ZERO); virtual ~MovingObject(); void setWorldBoundaries(float top, float bottom, float left, float right); void setMaxSpeed(float speed); void setVelocity(Ogre::Vector3 velocity); Ogre::Vector3 getVelocity() const { return state.velocity; }; void setPosition(Ogre::Vector3 pos) { state.location = pos; }; void addForwardAcceleration(float amount); void addClockwiseTurningSpeed(float amountRad); void setForwardAcceleration(float amount) { control.accelerationFwd = amount; } void setClockwiseTurningSpeed(float amount) { control.velocityCWiseTurning = amount; } Ogre::Vector3 getFacing() const; Ogre::SceneNode* getOwnerNode() const { return pOwnerNode; } void setOwnerNode(Ogre::SceneNode *node) { pOwnerNode = node; } bool hasOwnerNode() const { return pOwnerNode; } void update(unsigned long msSinceLast); //NetObject serialization int serialize(uint8 *buffer, int start, int buflength) const; int unserialize(uint8 *buffer, int start); NetObject *create(int id); private: Ogre::Vector3 initialFacing; MovableState state; MovableControl control; float friction; RectBoundaries worldBoundaries; float maxSpeedSquared; Ogre::SceneNode *pOwnerNode; void updateVelocity(unsigned long msSinceLast); void updateFacing(unsigned long msSinceLast); void updatePosition(unsigned long msSinceLast); }; } // namespace ap #endif <|endoftext|>
<commit_before>/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #include <iostream> #include <fstream> #include <list> #include <vector> #include "itkSpatialObjectReader.h" #include "itkImageFileReader.h" #include "itkVesselTubeSpatialObject.h" #include "tubeMessage.h" #include "tubeCLIFilterWatcher.h" #include "tubeCLIProgressReporter.h" #include "itkTimeProbesCollectorBase.h" #include "ComputeTubeProbabilityCLP.h" template< unsigned int VDimension > int DoIt( int argc, char **argv ); // This needs to be declared for tubeCLIHelperFunctions. template< class TPixel, unsigned int VDimension > int DoIt( int argc, char **argv ){ return 0; } #include "tubeCLIHelperFunctions.h" int main(int argc, char **argv) { PARSE_ARGS; itk::ImageIOBase::IOComponentType componentType; unsigned int dimension; try { tube::GetImageInformation( inMeanImageFile, componentType, dimension ); switch( dimension ) { case 2: return DoIt< 2 >( argc, argv ); case 3: return DoIt< 3 >( argc, argv ); default: return EXIT_FAILURE; } } catch( const std::exception & exception ) { tube::ErrorMessage( exception.what() ); return EXIT_FAILURE; } return EXIT_FAILURE; } template< unsigned int VDimension > int DoIt(int argc, char **argv) { PARSE_ARGS; const unsigned int Dimension = VDimension; typedef itk::Image< short, Dimension > ImageType; typedef itk::GroupSpatialObject< Dimension > GroupType; typedef itk::ImageFileReader< ImageType > ImageReaderType; typedef itk::SpatialObjectReader< Dimension > SOReaderType; typedef itk::VesselTubeSpatialObject< Dimension > TubeType; typedef typename TubeType::TubePointType TubePointType; typedef typename TubeType::TransformType TubeTransformType; tube::CLIProgressReporter progressReporter( "tubeDensityProbability", CLPProcessInformation ); progressReporter.Start(); /* * Read in spatial object file (tubes) */ typename SOReaderType::Pointer soReader = SOReaderType::New(); soReader->SetFileName( inTubeFile.c_str() ); soReader->Update(); typename GroupType::Pointer group = soReader->GetGroup(); progressReporter.Report(0.1); /* * Read in ATLAS EMD image */ typename ImageReaderType::Pointer imReader = ImageReaderType::New(); imReader->SetFileName( inMeanImageFile.c_str() ); imReader->Update(); typename ImageType::Pointer meanImage = imReader->GetOutput(); progressReporter.Report(0.2); char childName[] = "Tube"; typename TubeType::ChildrenListType * tubeList = group->GetChildren(99999, childName); typename TubeType::ChildrenListType::const_iterator tubeIt = tubeList->begin(); TubePointType tubePoint; typename TubeTransformType::Pointer tubeTransform; std::ofstream writeStream; writeStream.open(outFile.c_str(), std::ios::binary | std::ios::out); while(tubeIt != tubeList->end()) // Iterate over tubes { typename TubeType::Pointer tube = dynamic_cast<TubeType *>((*tubeIt).GetPointer()); tube->RemoveDuplicatePoints(); tube->ComputeTangentAndNormals(); itk::Point<double, Dimension> pnt; itk::Index< Dimension > indx; tube->ComputeObjectToWorldTransform(); tubeTransform = tube->GetIndexToWorldTransform(); for( unsigned int i=0; i<tube->GetNumberOfPoints() ; i++) { tubePoint = static_cast<TubePointType>(tube->GetPoints()[i]); // Get point pnt = tubePoint.GetPosition(); // Get point's position pnt = tubeTransform->TransformPoint(pnt); // Point coords to physical coords meanImage->TransformPhysicalPointToIndex(pnt, indx); // Get closest voxel writeStream << meanImage->GetPixel(indx) << std::endl; // Write value of ATLAS EMD file at voxel } ++tubeIt; } writeStream.close(); progressReporter.Report(1.0); progressReporter.End(); return 1; } <commit_msg>COMP: ComputeTubeProbability: unused parameter warnings.<commit_after>/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #include <iostream> #include <fstream> #include <list> #include <vector> #include "itkSpatialObjectReader.h" #include "itkImageFileReader.h" #include "itkVesselTubeSpatialObject.h" #include "tubeMessage.h" #include "tubeCLIFilterWatcher.h" #include "tubeCLIProgressReporter.h" #include "itkTimeProbesCollectorBase.h" #include "ComputeTubeProbabilityCLP.h" template< unsigned int VDimension > int DoIt( int argc, char **argv ); // This needs to be declared for tubeCLIHelperFunctions. template< class TPixel, unsigned int VDimension > int DoIt( int itkNotUsed(argc), char **itkNotUsed(argv) ){ return 0; } #include "tubeCLIHelperFunctions.h" int main(int argc, char **argv) { PARSE_ARGS; itk::ImageIOBase::IOComponentType componentType; unsigned int dimension; try { tube::GetImageInformation( inMeanImageFile, componentType, dimension ); switch( dimension ) { case 2: return DoIt< 2 >( argc, argv ); case 3: return DoIt< 3 >( argc, argv ); default: return EXIT_FAILURE; } } catch( const std::exception & exception ) { tube::ErrorMessage( exception.what() ); return EXIT_FAILURE; } return EXIT_FAILURE; } template< unsigned int VDimension > int DoIt(int argc, char **argv) { PARSE_ARGS; const unsigned int Dimension = VDimension; typedef itk::Image< short, Dimension > ImageType; typedef itk::GroupSpatialObject< Dimension > GroupType; typedef itk::ImageFileReader< ImageType > ImageReaderType; typedef itk::SpatialObjectReader< Dimension > SOReaderType; typedef itk::VesselTubeSpatialObject< Dimension > TubeType; typedef typename TubeType::TubePointType TubePointType; typedef typename TubeType::TransformType TubeTransformType; tube::CLIProgressReporter progressReporter( "tubeDensityProbability", CLPProcessInformation ); progressReporter.Start(); /* * Read in spatial object file (tubes) */ typename SOReaderType::Pointer soReader = SOReaderType::New(); soReader->SetFileName( inTubeFile.c_str() ); soReader->Update(); typename GroupType::Pointer group = soReader->GetGroup(); progressReporter.Report(0.1); /* * Read in ATLAS EMD image */ typename ImageReaderType::Pointer imReader = ImageReaderType::New(); imReader->SetFileName( inMeanImageFile.c_str() ); imReader->Update(); typename ImageType::Pointer meanImage = imReader->GetOutput(); progressReporter.Report(0.2); char childName[] = "Tube"; typename TubeType::ChildrenListType * tubeList = group->GetChildren(99999, childName); typename TubeType::ChildrenListType::const_iterator tubeIt = tubeList->begin(); TubePointType tubePoint; typename TubeTransformType::Pointer tubeTransform; std::ofstream writeStream; writeStream.open(outFile.c_str(), std::ios::binary | std::ios::out); while(tubeIt != tubeList->end()) // Iterate over tubes { typename TubeType::Pointer tube = dynamic_cast<TubeType *>((*tubeIt).GetPointer()); tube->RemoveDuplicatePoints(); tube->ComputeTangentAndNormals(); itk::Point<double, Dimension> pnt; itk::Index< Dimension > indx; tube->ComputeObjectToWorldTransform(); tubeTransform = tube->GetIndexToWorldTransform(); for( unsigned int i=0; i<tube->GetNumberOfPoints() ; i++) { tubePoint = static_cast<TubePointType>(tube->GetPoints()[i]); // Get point pnt = tubePoint.GetPosition(); // Get point's position pnt = tubeTransform->TransformPoint(pnt); // Point coords to physical coords meanImage->TransformPhysicalPointToIndex(pnt, indx); // Get closest voxel writeStream << meanImage->GetPixel(indx) << std::endl; // Write value of ATLAS EMD file at voxel } ++tubeIt; } writeStream.close(); progressReporter.Report(1.0); progressReporter.End(); return 1; } <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System */ #include "cvmfs_config.h" #include "encrypt.h" #include <fcntl.h> #include <openssl/evp.h> #include <openssl/rand.h> #include <cassert> #include <cstdlib> #include <cstring> #include <ctime> #include "hash.h" #include "platform.h" #include "smalloc.h" #include "util.h" #include "util_concurrency.h" using namespace std; // NOLINT namespace cipher { Key *Key::CreateRandomly(const unsigned size) { Key *result = new Key(); result->size_ = size; result->data_ = reinterpret_cast<unsigned char *>(smalloc(size)); // TODO(jblomer): pin memory in RAM int retval = RAND_bytes(result->data_, result->size_); if (retval != 1) { // Not enough entropy delete result; result = NULL; } return result; } Key *Key::CreateFromFile(const string &path) { int fd = open(path.c_str(), O_RDONLY); if (fd < 0) return NULL; platform_disable_kcache(fd); platform_stat64 info; int retval = platform_fstat(fd, &info); if (retval != 0) { close(fd); return NULL; } if ((info.st_size == 0) || (info.st_size > kMaxSize)) { close(fd); return false; } Key *result = new Key(); result->size_ = info.st_size; result->data_ = reinterpret_cast<unsigned char *>(smalloc(result->size_)); int nbytes = read(fd, result->data_, result->size_); close(fd); if ((nbytes < 0) || (static_cast<unsigned>(nbytes) != result->size_)) { delete result; result = NULL; } return result; } Key *Key::CreateFromString(const string &key) { unsigned size = key.size(); if ((size == 0) || (size > kMaxSize)) return NULL; UniquePtr<Key> result(new Key()); result->size_ = size; result->data_ = reinterpret_cast<unsigned char *>(smalloc(size)); memcpy(result->data_, key.data(), size); return result.Release(); } Key::~Key() { if (data_) { memset(data_, 0, size_); free(data_); } } bool Key::SaveToFile(const std::string &path) { int fd = open(path.c_str(), O_WRONLY); if (fd < 0) return false; platform_disable_kcache(fd); int nbytes = write(fd, data_, size_); close(fd); return (nbytes >= 0) && (static_cast<unsigned>(nbytes) == size_); } string Key::ToBase64() const { return Base64(string(reinterpret_cast<const char *>(data_), size_)); } //------------------------------------------------------------------------------ MemoryKeyDatabase::MemoryKeyDatabase() { lock_ = reinterpret_cast<pthread_mutex_t *>(smalloc(sizeof(pthread_mutex_t))); int retval = pthread_mutex_init(lock_, NULL); assert(retval == 0); } MemoryKeyDatabase::~MemoryKeyDatabase() { pthread_mutex_destroy(lock_); free(lock_); } bool MemoryKeyDatabase::StoreNew(const Key *key, string *id) { MutexLockGuard mutex_guard(lock_); // TODO(jblomer): is this good enough for random keys? Salting? KDF2? shash::Any hash(shash::kShake128); HashMem(key->data(), key->size(), &hash); *id = "H" + hash.ToString(); map<string, const Key *>::const_iterator i = database_.find(*id); if (i != database_.end()) return false; database_[*id] = key; return true; } const Key *MemoryKeyDatabase::Find(const string &id) { MutexLockGuard mutex_guard(lock_); map<string, const Key *>::const_iterator i = database_.find(id); if (i != database_.end()) return i->second; return NULL; } //------------------------------------------------------------------------------ Cipher *Cipher::Create(const Algorithms a) { switch (a) { case kAes256Cbc: return new CipherAes256Cbc(); case kNone: return new CipherNone(); default: abort(); } // Never here } bool Cipher::Encrypt( const string &plaintext, const Key &key, string *ciphertext) { ciphertext->clear(); if (key.size() != key_size()) return false; unsigned char envelope = 0 & 0x0F; envelope |= (algorithm() << 4) & 0xF0; ciphertext->push_back(envelope); *ciphertext += DoEncrypt(plaintext, key); return true; } bool Cipher::Decrypt( const string &ciphertext, const Key &key, string *plaintext) { plaintext->clear(); if (ciphertext.size() < 1) return false; unsigned char envelope = ciphertext[0]; unsigned char version = envelope & 0x0F; if (version != 0) return false; unsigned char algorithm = (envelope & 0xF0) >> 4; if (algorithm > kNone) return false; UniquePtr<Cipher> cipher(Create(static_cast<Algorithms>(algorithm))); if (key.size() != cipher->key_size()) return false; *plaintext += cipher->DoDecrypt(ciphertext.substr(1), key); return true; } //------------------------------------------------------------------------------ atomic_int64 CipherAes256Cbc::sequence_ = 0; string CipherAes256Cbc::DoDecrypt(const string &ciphertext, const Key &key) { assert(key.size() == kKeySize); int retval, retval_2; if (ciphertext.size() < kIvSize) return ""; const unsigned char *iv = reinterpret_cast<const unsigned char *>( ciphertext.data()); // See OpenSSL documentation for the size unsigned char *plaintext = reinterpret_cast<unsigned char *>( smalloc(kBlockSize + ciphertext.size() - kIvSize)); int plaintext_len; int tail_len; EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); retval = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, key.data(), iv); assert(retval == 1); retval = EVP_DecryptUpdate(&ctx, plaintext, &plaintext_len, reinterpret_cast<const unsigned char *>( ciphertext.data() + kIvSize), ciphertext.length() - kIvSize); if (retval != 1) { free(plaintext); retval = EVP_CIPHER_CTX_cleanup(&ctx); assert(retval == 1); return ""; } retval = EVP_DecryptFinal_ex(&ctx, plaintext + plaintext_len, &tail_len); retval_2 = EVP_CIPHER_CTX_cleanup(&ctx); assert(retval_2 == 1); if (retval != 1) { free(plaintext); return ""; } plaintext_len += tail_len; if (plaintext_len == 0) { free(plaintext); return ""; } string result(reinterpret_cast<char *>(plaintext), plaintext_len); free(plaintext); return result; } string CipherAes256Cbc::DoEncrypt(const string &plaintext, const Key &key) { assert(key.size() == kKeySize); int retval; shash::Md5 md5(GenerateIv(key)); // iv size happens to be md5 digest size unsigned char *iv = md5.digest; // See OpenSSL documentation as for the size. Additionally, we prepend the // initialization vector. unsigned char *ciphertext = reinterpret_cast<unsigned char *>( smalloc(kIvSize + 2 * kBlockSize + plaintext.size())); memcpy(ciphertext, iv, kIvSize); int cipher_len; int tail_len; EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); retval = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, key.data(), iv); assert(retval == 1); retval = EVP_EncryptUpdate(&ctx, ciphertext + kIvSize, &cipher_len, reinterpret_cast<const unsigned char *>(plaintext.data()), plaintext.length()); assert(retval == 1); retval = EVP_EncryptFinal_ex(&ctx, ciphertext + kIvSize + cipher_len, &tail_len); assert(retval == 1); retval = EVP_CIPHER_CTX_cleanup(&ctx); assert(retval == 1); cipher_len += tail_len; assert(cipher_len > 0); string result(reinterpret_cast<char *>(ciphertext), kIvSize + cipher_len); free(ciphertext); return result; } /** * The block size of AES-256-CBC happens to be the same of the MD5 digest * (128 bits). Use the HMAC of the key and time + seqno to make it random and * unpredictable. */ shash::Md5 CipherAes256Cbc::GenerateIv(const Key &key) { uint64_t timestamp = time(NULL); uint64_t nonce = timestamp + atomic_xadd64(&sequence_, 1); shash::Any hmac(shash::kMd5); shash::Hmac(string(reinterpret_cast<const char *>(key.data()), key.size()), reinterpret_cast<const unsigned char *>(&nonce), sizeof(nonce), &hmac); return hmac.CastToMd5(); } //------------------------------------------------------------------------------ string CipherNone::DoDecrypt(const string &ciphertext, const Key &key) { return ciphertext; } string CipherNone::DoEncrypt(const string &plaintext, const Key &key) { return plaintext; } } // namespace cipher <commit_msg>another fix for the initialization vector<commit_after>/** * This file is part of the CernVM File System */ #include "cvmfs_config.h" #include "encrypt.h" #include <fcntl.h> #include <openssl/evp.h> #include <openssl/rand.h> #include <cassert> #include <cstdlib> #include <cstring> #include <ctime> #include "hash.h" #include "platform.h" #include "smalloc.h" #include "util.h" #include "util_concurrency.h" using namespace std; // NOLINT namespace cipher { Key *Key::CreateRandomly(const unsigned size) { Key *result = new Key(); result->size_ = size; result->data_ = reinterpret_cast<unsigned char *>(smalloc(size)); // TODO(jblomer): pin memory in RAM int retval = RAND_bytes(result->data_, result->size_); if (retval != 1) { // Not enough entropy delete result; result = NULL; } return result; } Key *Key::CreateFromFile(const string &path) { int fd = open(path.c_str(), O_RDONLY); if (fd < 0) return NULL; platform_disable_kcache(fd); platform_stat64 info; int retval = platform_fstat(fd, &info); if (retval != 0) { close(fd); return NULL; } if ((info.st_size == 0) || (info.st_size > kMaxSize)) { close(fd); return false; } Key *result = new Key(); result->size_ = info.st_size; result->data_ = reinterpret_cast<unsigned char *>(smalloc(result->size_)); int nbytes = read(fd, result->data_, result->size_); close(fd); if ((nbytes < 0) || (static_cast<unsigned>(nbytes) != result->size_)) { delete result; result = NULL; } return result; } Key *Key::CreateFromString(const string &key) { unsigned size = key.size(); if ((size == 0) || (size > kMaxSize)) return NULL; UniquePtr<Key> result(new Key()); result->size_ = size; result->data_ = reinterpret_cast<unsigned char *>(smalloc(size)); memcpy(result->data_, key.data(), size); return result.Release(); } Key::~Key() { if (data_) { memset(data_, 0, size_); free(data_); } } bool Key::SaveToFile(const std::string &path) { int fd = open(path.c_str(), O_WRONLY); if (fd < 0) return false; platform_disable_kcache(fd); int nbytes = write(fd, data_, size_); close(fd); return (nbytes >= 0) && (static_cast<unsigned>(nbytes) == size_); } string Key::ToBase64() const { return Base64(string(reinterpret_cast<const char *>(data_), size_)); } //------------------------------------------------------------------------------ MemoryKeyDatabase::MemoryKeyDatabase() { lock_ = reinterpret_cast<pthread_mutex_t *>(smalloc(sizeof(pthread_mutex_t))); int retval = pthread_mutex_init(lock_, NULL); assert(retval == 0); } MemoryKeyDatabase::~MemoryKeyDatabase() { pthread_mutex_destroy(lock_); free(lock_); } bool MemoryKeyDatabase::StoreNew(const Key *key, string *id) { MutexLockGuard mutex_guard(lock_); // TODO(jblomer): is this good enough for random keys? Salting? KDF2? shash::Any hash(shash::kShake128); HashMem(key->data(), key->size(), &hash); *id = "H" + hash.ToString(); map<string, const Key *>::const_iterator i = database_.find(*id); if (i != database_.end()) return false; database_[*id] = key; return true; } const Key *MemoryKeyDatabase::Find(const string &id) { MutexLockGuard mutex_guard(lock_); map<string, const Key *>::const_iterator i = database_.find(id); if (i != database_.end()) return i->second; return NULL; } //------------------------------------------------------------------------------ Cipher *Cipher::Create(const Algorithms a) { switch (a) { case kAes256Cbc: return new CipherAes256Cbc(); case kNone: return new CipherNone(); default: abort(); } // Never here } bool Cipher::Encrypt( const string &plaintext, const Key &key, string *ciphertext) { ciphertext->clear(); if (key.size() != key_size()) return false; unsigned char envelope = 0 & 0x0F; envelope |= (algorithm() << 4) & 0xF0; ciphertext->push_back(envelope); *ciphertext += DoEncrypt(plaintext, key); return true; } bool Cipher::Decrypt( const string &ciphertext, const Key &key, string *plaintext) { plaintext->clear(); if (ciphertext.size() < 1) return false; unsigned char envelope = ciphertext[0]; unsigned char version = envelope & 0x0F; if (version != 0) return false; unsigned char algorithm = (envelope & 0xF0) >> 4; if (algorithm > kNone) return false; UniquePtr<Cipher> cipher(Create(static_cast<Algorithms>(algorithm))); if (key.size() != cipher->key_size()) return false; *plaintext += cipher->DoDecrypt(ciphertext.substr(1), key); return true; } //------------------------------------------------------------------------------ atomic_int64 CipherAes256Cbc::sequence_ = 0; string CipherAes256Cbc::DoDecrypt(const string &ciphertext, const Key &key) { assert(key.size() == kKeySize); int retval, retval_2; if (ciphertext.size() < kIvSize) return ""; const unsigned char *iv = reinterpret_cast<const unsigned char *>( ciphertext.data()); // See OpenSSL documentation for the size unsigned char *plaintext = reinterpret_cast<unsigned char *>( smalloc(kBlockSize + ciphertext.size() - kIvSize)); int plaintext_len; int tail_len; EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); retval = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, key.data(), iv); assert(retval == 1); retval = EVP_DecryptUpdate(&ctx, plaintext, &plaintext_len, reinterpret_cast<const unsigned char *>( ciphertext.data() + kIvSize), ciphertext.length() - kIvSize); if (retval != 1) { free(plaintext); retval = EVP_CIPHER_CTX_cleanup(&ctx); assert(retval == 1); return ""; } retval = EVP_DecryptFinal_ex(&ctx, plaintext + plaintext_len, &tail_len); retval_2 = EVP_CIPHER_CTX_cleanup(&ctx); assert(retval_2 == 1); if (retval != 1) { free(plaintext); return ""; } plaintext_len += tail_len; if (plaintext_len == 0) { free(plaintext); return ""; } string result(reinterpret_cast<char *>(plaintext), plaintext_len); free(plaintext); return result; } string CipherAes256Cbc::DoEncrypt(const string &plaintext, const Key &key) { assert(key.size() == kKeySize); int retval; shash::Md5 md5(GenerateIv(key)); // iv size happens to be md5 digest size unsigned char *iv = md5.digest; // See OpenSSL documentation as for the size. Additionally, we prepend the // initialization vector. unsigned char *ciphertext = reinterpret_cast<unsigned char *>( smalloc(kIvSize + 2 * kBlockSize + plaintext.size())); memcpy(ciphertext, iv, kIvSize); int cipher_len; int tail_len; EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); retval = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, key.data(), iv); assert(retval == 1); retval = EVP_EncryptUpdate(&ctx, ciphertext + kIvSize, &cipher_len, reinterpret_cast<const unsigned char *>(plaintext.data()), plaintext.length()); assert(retval == 1); retval = EVP_EncryptFinal_ex(&ctx, ciphertext + kIvSize + cipher_len, &tail_len); assert(retval == 1); retval = EVP_CIPHER_CTX_cleanup(&ctx); assert(retval == 1); cipher_len += tail_len; assert(cipher_len > 0); string result(reinterpret_cast<char *>(ciphertext), kIvSize + cipher_len); free(ciphertext); return result; } /** * The block size of AES-256-CBC happens to be the same of the MD5 digest * (128 bits). Use the HMAC of the key and time + seqno to make it random and * unpredictable. */ shash::Md5 CipherAes256Cbc::GenerateIv(const Key &key) { uint64_t now = time(NULL); struct { uint64_t timestamp; uint64_t seq; } nonce; nonce.timestamp = now; nonce.seq = atomic_xadd64(&sequence_, 1); shash::Any hmac(shash::kMd5); shash::Hmac(string(reinterpret_cast<const char *>(key.data()), key.size()), reinterpret_cast<const unsigned char *>(&nonce), sizeof(nonce), &hmac); return hmac.CastToMd5(); } //------------------------------------------------------------------------------ string CipherNone::DoDecrypt(const string &ciphertext, const Key &key) { return ciphertext; } string CipherNone::DoEncrypt(const string &plaintext, const Key &key) { return plaintext; } } // namespace cipher <|endoftext|>
<commit_before><commit_msg>Use offapi constants instead of hardcoded magic constant<commit_after><|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2009 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ #endif #include "Application.h" #include "Document.h" #include "DocumentObject.h" #include "DocumentObserverPython.h" #include <Base/Interpreter.h> #include <Base/Console.h> using namespace App; std::vector<DocumentObserverPython*> DocumentObserverPython::_instances; void DocumentObserverPython::addObserver(const Py::Object& obj) { _instances.push_back(new DocumentObserverPython(obj)); } void DocumentObserverPython::removeObserver(const Py::Object& obj) { DocumentObserverPython* obs=0; for (std::vector<DocumentObserverPython*>::iterator it = _instances.begin(); it != _instances.end(); ++it) { if ((*it)->inst == obj) { obs = *it; _instances.erase(it); break; } } delete obs; } DocumentObserverPython::DocumentObserverPython(const Py::Object& obj) : inst(obj) { this->connectApplicationCreatedDocument = App::GetApplication().signalNewDocument.connect(boost::bind (&DocumentObserverPython::slotCreatedDocument, this, _1)); this->connectApplicationDeletedDocument = App::GetApplication().signalDeleteDocument.connect(boost::bind (&DocumentObserverPython::slotDeletedDocument, this, _1)); this->connectApplicationRelabelDocument = App::GetApplication().signalRelabelDocument.connect(boost::bind (&DocumentObserverPython::slotRelabelDocument, this, _1)); this->connectApplicationActivateDocument = App::GetApplication().signalActiveDocument.connect(boost::bind (&DocumentObserverPython::slotActivateDocument, this, _1)); this->connectApplicationUndoDocument = App::GetApplication().signalUndoDocument.connect(boost::bind (&DocumentObserverPython::slotUndoDocument, this, _1)); this->connectApplicationRedoDocument = App::GetApplication().signalRedoDocument.connect(boost::bind (&DocumentObserverPython::slotRedoDocument, this, _1)); this->connectDocumentCreatedObject = App::GetApplication().signalNewObject.connect(boost::bind (&DocumentObserverPython::slotCreatedObject, this, _1)); this->connectDocumentDeletedObject = App::GetApplication().signalDeletedObject.connect(boost::bind (&DocumentObserverPython::slotDeletedObject, this, _1)); this->connectDocumentChangedObject = App::GetApplication().signalChangedObject.connect(boost::bind (&DocumentObserverPython::slotChangedObject, this, _1, _2)); } DocumentObserverPython::~DocumentObserverPython() { this->connectApplicationCreatedDocument.disconnect(); this->connectApplicationDeletedDocument.disconnect(); this->connectApplicationRelabelDocument.disconnect(); this->connectApplicationActivateDocument.disconnect(); this->connectApplicationUndoDocument.disconnect(); this->connectApplicationRedoDocument.disconnect(); this->connectDocumentCreatedObject.disconnect(); this->connectDocumentDeletedObject.disconnect(); this->connectDocumentChangedObject.disconnect(); } void DocumentObserverPython::slotCreatedDocument(const App::Document& Doc) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotCreatedDocument"))) { Py::Callable method(this->inst.getAttr(std::string("slotCreatedDocument"))); Py::Tuple args(1); args.setItem(0, Py::Object(const_cast<App::Document&>(Doc).getPyObject(), true)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } void DocumentObserverPython::slotDeletedDocument(const App::Document& Doc) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotDeletedDocument"))) { Py::Callable method(this->inst.getAttr(std::string("slotDeletedDocument"))); Py::Tuple args(1); args.setItem(0, Py::Object(const_cast<App::Document&>(Doc).getPyObject(), true)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } void DocumentObserverPython::slotRelabelDocument(const App::Document& Doc) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotRelabelDocument"))) { Py::Callable method(this->inst.getAttr(std::string("slotRelabelDocument"))); Py::Tuple args(1); args.setItem(0, Py::Object(const_cast<App::Document&>(Doc).getPyObject(), true)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } void DocumentObserverPython::slotActivateDocument(const App::Document& Doc) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotActivateDocument"))) { Py::Callable method(this->inst.getAttr(std::string("slotActivateDocument"))); Py::Tuple args(1); args.setItem(0, Py::Object(const_cast<App::Document&>(Doc).getPyObject(), true)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } void DocumentObserverPython::slotUndoDocument(const App::Document& Doc) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotUndoDocument"))) { Py::Callable method(this->inst.getAttr(std::string("slotUndoDocument"))); Py::Tuple args(1); args.setItem(0, Py::Object(const_cast<App::Document&>(Doc).getPyObject(), true)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } void DocumentObserverPython::slotRedoDocument(const App::Document& Doc) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotRedoDocument"))) { Py::Callable method(this->inst.getAttr(std::string("slotRedoDocument"))); Py::Tuple args(1); args.setItem(0, Py::Object(const_cast<App::Document&>(Doc).getPyObject(), true)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } void DocumentObserverPython::slotCreatedObject(const App::DocumentObject& Obj) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotCreatedObject"))) { Py::Callable method(this->inst.getAttr(std::string("slotCreatedObject"))); Py::Tuple args(1); args.setItem(0, Py::Object(const_cast<App::DocumentObject&>(Obj).getPyObject(), true)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } void DocumentObserverPython::slotDeletedObject(const App::DocumentObject& Obj) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotDeletedObject"))) { Py::Callable method(this->inst.getAttr(std::string("slotDeletedObject"))); Py::Tuple args(1); args.setItem(0, Py::Object(const_cast<App::DocumentObject&>(Obj).getPyObject(), true)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } void DocumentObserverPython::slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotChangedObject"))) { Py::Callable method(this->inst.getAttr(std::string("slotChangedObject"))); Py::Tuple args(2); args.setItem(0, Py::Object(const_cast<App::DocumentObject&>(Obj).getPyObject(), true)); std::string prop_name = Obj.getPropertyName(&Prop); args.setItem(1, Py::String(prop_name)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } <commit_msg>+ fix crash in DocumentObserverPython if a property has no name (because it's not part of an object)<commit_after>/*************************************************************************** * Copyright (c) 2009 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ #endif #include "Application.h" #include "Document.h" #include "DocumentObject.h" #include "DocumentObserverPython.h" #include <Base/Interpreter.h> #include <Base/Console.h> using namespace App; std::vector<DocumentObserverPython*> DocumentObserverPython::_instances; void DocumentObserverPython::addObserver(const Py::Object& obj) { _instances.push_back(new DocumentObserverPython(obj)); } void DocumentObserverPython::removeObserver(const Py::Object& obj) { DocumentObserverPython* obs=0; for (std::vector<DocumentObserverPython*>::iterator it = _instances.begin(); it != _instances.end(); ++it) { if ((*it)->inst == obj) { obs = *it; _instances.erase(it); break; } } delete obs; } DocumentObserverPython::DocumentObserverPython(const Py::Object& obj) : inst(obj) { this->connectApplicationCreatedDocument = App::GetApplication().signalNewDocument.connect(boost::bind (&DocumentObserverPython::slotCreatedDocument, this, _1)); this->connectApplicationDeletedDocument = App::GetApplication().signalDeleteDocument.connect(boost::bind (&DocumentObserverPython::slotDeletedDocument, this, _1)); this->connectApplicationRelabelDocument = App::GetApplication().signalRelabelDocument.connect(boost::bind (&DocumentObserverPython::slotRelabelDocument, this, _1)); this->connectApplicationActivateDocument = App::GetApplication().signalActiveDocument.connect(boost::bind (&DocumentObserverPython::slotActivateDocument, this, _1)); this->connectApplicationUndoDocument = App::GetApplication().signalUndoDocument.connect(boost::bind (&DocumentObserverPython::slotUndoDocument, this, _1)); this->connectApplicationRedoDocument = App::GetApplication().signalRedoDocument.connect(boost::bind (&DocumentObserverPython::slotRedoDocument, this, _1)); this->connectDocumentCreatedObject = App::GetApplication().signalNewObject.connect(boost::bind (&DocumentObserverPython::slotCreatedObject, this, _1)); this->connectDocumentDeletedObject = App::GetApplication().signalDeletedObject.connect(boost::bind (&DocumentObserverPython::slotDeletedObject, this, _1)); this->connectDocumentChangedObject = App::GetApplication().signalChangedObject.connect(boost::bind (&DocumentObserverPython::slotChangedObject, this, _1, _2)); } DocumentObserverPython::~DocumentObserverPython() { this->connectApplicationCreatedDocument.disconnect(); this->connectApplicationDeletedDocument.disconnect(); this->connectApplicationRelabelDocument.disconnect(); this->connectApplicationActivateDocument.disconnect(); this->connectApplicationUndoDocument.disconnect(); this->connectApplicationRedoDocument.disconnect(); this->connectDocumentCreatedObject.disconnect(); this->connectDocumentDeletedObject.disconnect(); this->connectDocumentChangedObject.disconnect(); } void DocumentObserverPython::slotCreatedDocument(const App::Document& Doc) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotCreatedDocument"))) { Py::Callable method(this->inst.getAttr(std::string("slotCreatedDocument"))); Py::Tuple args(1); args.setItem(0, Py::Object(const_cast<App::Document&>(Doc).getPyObject(), true)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } void DocumentObserverPython::slotDeletedDocument(const App::Document& Doc) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotDeletedDocument"))) { Py::Callable method(this->inst.getAttr(std::string("slotDeletedDocument"))); Py::Tuple args(1); args.setItem(0, Py::Object(const_cast<App::Document&>(Doc).getPyObject(), true)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } void DocumentObserverPython::slotRelabelDocument(const App::Document& Doc) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotRelabelDocument"))) { Py::Callable method(this->inst.getAttr(std::string("slotRelabelDocument"))); Py::Tuple args(1); args.setItem(0, Py::Object(const_cast<App::Document&>(Doc).getPyObject(), true)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } void DocumentObserverPython::slotActivateDocument(const App::Document& Doc) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotActivateDocument"))) { Py::Callable method(this->inst.getAttr(std::string("slotActivateDocument"))); Py::Tuple args(1); args.setItem(0, Py::Object(const_cast<App::Document&>(Doc).getPyObject(), true)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } void DocumentObserverPython::slotUndoDocument(const App::Document& Doc) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotUndoDocument"))) { Py::Callable method(this->inst.getAttr(std::string("slotUndoDocument"))); Py::Tuple args(1); args.setItem(0, Py::Object(const_cast<App::Document&>(Doc).getPyObject(), true)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } void DocumentObserverPython::slotRedoDocument(const App::Document& Doc) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotRedoDocument"))) { Py::Callable method(this->inst.getAttr(std::string("slotRedoDocument"))); Py::Tuple args(1); args.setItem(0, Py::Object(const_cast<App::Document&>(Doc).getPyObject(), true)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } void DocumentObserverPython::slotCreatedObject(const App::DocumentObject& Obj) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotCreatedObject"))) { Py::Callable method(this->inst.getAttr(std::string("slotCreatedObject"))); Py::Tuple args(1); args.setItem(0, Py::Object(const_cast<App::DocumentObject&>(Obj).getPyObject(), true)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } void DocumentObserverPython::slotDeletedObject(const App::DocumentObject& Obj) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotDeletedObject"))) { Py::Callable method(this->inst.getAttr(std::string("slotDeletedObject"))); Py::Tuple args(1); args.setItem(0, Py::Object(const_cast<App::DocumentObject&>(Obj).getPyObject(), true)); method.apply(args); } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } void DocumentObserverPython::slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop) { Base::PyGILStateLocker lock; try { if (this->inst.hasAttr(std::string("slotChangedObject"))) { Py::Callable method(this->inst.getAttr(std::string("slotChangedObject"))); Py::Tuple args(2); args.setItem(0, Py::Object(const_cast<App::DocumentObject&>(Obj).getPyObject(), true)); // If a property is touched but not part of a document object then its name is null. // In this case the slot function must not be called. const char* prop_name = Obj.getPropertyName(&Prop); if (prop_name) { args.setItem(1, Py::String(prop_name)); method.apply(args); } } } catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); } } <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include "Myexception.h" #include "chain.h" using namespace std; void chain :: readAndStoreFromFile(char* fileName) { //This function reads integers from the file given by fileName then store them in the chain std::ifstream data(filename); std::string line; while(std::getline(data,line)) td::stringstream str(line); td::string text; td::getline(str,text,'='); double value; tr >> value; } } void chain :: eraseModuloValue(int theInt) { //This function erases all the entries from the list which are multiple of theInt } void chain :: oddAndEvenOrdering() { //This function reorders the list such a way that all odd numbers precede all even numbers. //Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering. } void chain :: reverse() { //Reverses the list } chain :: chain(int initialCapacity) { //Constructor if(initialCapacity < 1) { ostringstream s; s << "Initial capacity = " << initialCapacity << " Must be > 0"; throw illegalParameterValue(s.str()); } firstNode = NULL; listSize = 0; } chain :: ~chain() { //Destructor. Delete all nodes in chain while(firstNode != NULL) { //delete firstNode chainNode* nextNode = firstNode->next; delete firstNode; firstNode = nextNode; } } int* chain :: get(int theIndex) const { //Return element whose index is theIndex. //Throw illegalIndex exception if no such element. try{ checkIndex(theIndex); } catch(illegalIndex &e){ e.outputMessage(); return NULL; } chainNode* currentNode = firstNode; for(int i=0;i<theIndex;i++) currentNode = currentNode->next; return &currentNode->element; } int chain :: indexOf(const int& theElement) const { //Return index of first occurrence of theElement. //Return -1 of theElement not in list. chainNode* currentNode = firstNode; int index = 0; while(currentNode != NULL && currentNode->element != theElement) { //move to the next node currentNode = currentNode->next; index++; } //make sure we found matching element if(currentNode == NULL) return -1; else return index; } void chain :: erase(int theIndex) { //Delete the element whose index is theIndex. //Throw illegalIndex exception if no such element. try{ checkIndex(theIndex); } catch(illegalIndex &e){ e.outputMessage(); return; } chainNode* deleteNode; if(theIndex == 0) { //remove first node from chain deleteNode = firstNode; firstNode = firstNode->next; } else { //use p to get to predecessor of desired node chainNode* p = firstNode; for(int i=0;i<theIndex-1;i++) p = p->next; deleteNode = p->next; p->next = p->next->next; //remove deleteNode from chain } listSize--; delete deleteNode; } void chain :: insert(int theIndex, const int& theElement) { //Insert theElement so that its index is theIndex. try{ if (theIndex < 0 || theIndex > listSize) {// invalid index ostringstream s; s << "index = " << theIndex << " size = " << listSize; throw illegalIndex(s.str()); } } catch(illegalIndex &e){ e.outputMessage(); return; } if(theIndex == 0) //insert at front firstNode = new chainNode(theElement, firstNode); else { chainNode *p = firstNode; for(int i=0;i<theIndex-1;i++) p = p->next; //insert after p p->next = new chainNode(theElement, p->next); } listSize++; } void chain :: output() const { //Put the list into the output. for(int i=0;i<listSize;i++) cout << *this->get(i) << " "; cout<<endl; } void chain::checkIndex(int theIndex) const { // Verify that theIndex is between 0 and // listSize - 1. if (theIndex < 0 || theIndex >= listSize){ ostringstream s; s << "index = " << theIndex << " size = " << listSize<<", the input index is invalid"; throw illegalIndex(s.str()); } } <commit_msg>Update chain.cpp<commit_after>#include <iostream> #include <sstream> #include "Myexception.h" #include "chain.h" using namespace std; void chain :: readAndStoreFromFile(char* fileName) { //This function reads integers from the file given by fileName then store them in the chain ifstream in; in.open(filename.c_str()); if (!in) return; // file doesn't exist int line; while(getline(in, line)) { insert(1, line); } /*int line; while(std::getline(data, line)) std::stringstream str(line); std::string text; std::getline(str,text,'='); double value; str >> value; }*/ } void chain :: eraseModuloValue(int theInt) { //This function erases all the entries from the list which are multiple of theInt } void chain :: oddAndEvenOrdering() { //This function reorders the list such a way that all odd numbers precede all even numbers. //Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering. } void chain :: reverse() { //Reverses the list } chain :: chain(int initialCapacity) { //Constructor if(initialCapacity < 1) { ostringstream s; s << "Initial capacity = " << initialCapacity << " Must be > 0"; throw illegalParameterValue(s.str()); } firstNode = NULL; listSize = 0; } chain :: ~chain() { //Destructor. Delete all nodes in chain while(firstNode != NULL) { //delete firstNode chainNode* nextNode = firstNode->next; delete firstNode; firstNode = nextNode; } } int* chain :: get(int theIndex) const { //Return element whose index is theIndex. //Throw illegalIndex exception if no such element. try{ checkIndex(theIndex); } catch(illegalIndex &e){ e.outputMessage(); return NULL; } chainNode* currentNode = firstNode; for(int i=0;i<theIndex;i++) currentNode = currentNode->next; return &currentNode->element; } int chain :: indexOf(const int& theElement) const { //Return index of first occurrence of theElement. //Return -1 of theElement not in list. chainNode* currentNode = firstNode; int index = 0; while(currentNode != NULL && currentNode->element != theElement) { //move to the next node currentNode = currentNode->next; index++; } //make sure we found matching element if(currentNode == NULL) return -1; else return index; } void chain :: erase(int theIndex) { //Delete the element whose index is theIndex. //Throw illegalIndex exception if no such element. try{ checkIndex(theIndex); } catch(illegalIndex &e){ e.outputMessage(); return; } chainNode* deleteNode; if(theIndex == 0) { //remove first node from chain deleteNode = firstNode; firstNode = firstNode->next; } else { //use p to get to predecessor of desired node chainNode* p = firstNode; for(int i=0;i<theIndex-1;i++) p = p->next; deleteNode = p->next; p->next = p->next->next; //remove deleteNode from chain } listSize--; delete deleteNode; } void chain :: insert(int theIndex, const int& theElement) { //Insert theElement so that its index is theIndex. try{ if (theIndex < 0 || theIndex > listSize) {// invalid index ostringstream s; s << "index = " << theIndex << " size = " << listSize; throw illegalIndex(s.str()); } } catch(illegalIndex &e){ e.outputMessage(); return; } if(theIndex == 0) //insert at front firstNode = new chainNode(theElement, firstNode); else { chainNode *p = firstNode; for(int i=0;i<theIndex-1;i++) p = p->next; //insert after p p->next = new chainNode(theElement, p->next); } listSize++; } void chain :: output() const { //Put the list into the output. for(int i=0;i<listSize;i++) cout << *this->get(i) << " "; cout<<endl; } void chain::checkIndex(int theIndex) const { // Verify that theIndex is between 0 and // listSize - 1. if (theIndex < 0 || theIndex >= listSize){ ostringstream s; s << "index = " << theIndex << " size = " << listSize<<", the input index is invalid"; throw illegalIndex(s.str()); } } <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #include "cvmfs_config.h" #include <stdio.h> #include <sys/stat.h> #include <unistd.h> #include <string> #include "download.h" #include "logging.h" #include "signature.h" #include "statistics.h" #include "swissknife.h" #include "swissknife_pull.h" #include "util.h" using namespace std; // NOLINT namespace swissknife { download::DownloadManager *g_download_manager; signature::SignatureManager *g_signature_manager; perf::Statistics *g_statistics; void Usage() { LogCvmfs(kLogCvmfs, kLogStderr, "Usage:\n" "cvmfs_preload -u <Stratum 0 URL>\n" " -r <alien cache directory>\n" " -k <public key>\n" " -m <fully qualified repository name>\n" " -x <directory for temporary files>\n" " -d <path to dirtab file>\n\n"); } } // namespace swissknife const char CERN_PUBLIC_KEY[] = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAukBusmYyFW8KJxVMmeCj\n" "N7vcU1mERMpDhPTa5PgFROSViiwbUsbtpP9CvfxB/KU1gggdbtWOTZVTQqA3b+p8\n" "g5Vve3/rdnN5ZEquxeEfIG6iEZta9Zei5mZMeuK+DPdyjtvN1wP0982ppbZzKRBu\n" "BbzR4YdrwwWXXNZH65zZuUISDJB4my4XRoVclrN5aGVz4PjmIZFlOJ+ytKsMlegW\n" "SNDwZO9z/YtBFil/Ca8FJhRPFMKdvxK+ezgq+OQWAerVNX7fArMC+4Ya5pF3ASr6\n" "3mlvIsBpejCUBygV4N2pxIcPJu/ZDaikmVvdPTNOTZlIFMf4zIP/YHegQSJmOyVp\n" "HQIDAQAB\n" "-----END PUBLIC KEY-----\n"; const char CERN_IT1_PUBLIC_KEY[] = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo8uKvscgW7FNxzb65Uhm\n" "yr8jPJiyrl2kVzb/hhgdfN14C0tCbfFoE6ciuZFg+9ytLeiL9pzM96gSC+atIFl4\n" "7wTgtAFO1W4PtDQBwA/IG2bnwvNrzk19ob0JYhjZlS9tYKeh7TKCub55+vMwcEbP\n" "urzo3WSNCzJngiGMh1vM5iSlGLpCdSGzdwxLGwc1VjRM7q3KAd7M7TJCynKqXZPX\n" "R2xiD6I/p4xv39AnwphCFSmDh0MWE1WeeNHIiiveikvvN+l8d/ZNASIDhKNCsz6o\n" "aFDsGXvjGy7dg43YzjSSYSFGUnONtl5Fe6y4bQZj1LEPbeInW334MAbMwYF4LKma\n" "yQIDAQAB\n" "-----END PUBLIC KEY-----\n"; const char CERN_IT2_PUBLIC_KEY[] = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkX6+mj6/X5yLV9uHt56l\n" "ZK1uLMueEULUhSCRrLj+9qz3EBMsANCjzfdabllKqWX/6qIfqppKVBwScF38aRnC\n" "vhlVGYtDgiqM1tfa1tA6BF7HUZQ1R1lU01tP0iYGhNTlTfY+fMAZDeerGDckT8cl\n" "NAQuICFUKy6w6aar8Sf3mpUC/hXVD2QUESmFgQ0SZhhW3eIB1xEoRxW0ieO6AidF\n" "qxmAxrB4H4+7i9O+B7Wf0VJQLSzP5bvIzx7xoqs3aUlnuzGFOaI8zypMvSvycSUb\n" "xhLsYbTgnlqSI/SPehMeQeEirhhKPaA+TsVSvxuqCJNoQ/wPBEG0HR+XkTsO9/sH\n" "FQIDAQAB\n" "-----END PUBLIC KEY-----\n"; const char CERN_IT3_PUBLIC_KEY[] = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAosLXrVkA4p6IjQj6rUNM\n" "odr9oWB1nL3tWPKyPhS7mqAg+J4EW9m4ka/98PXi6jS/b1i/QLP9oGXlxJpugT1E\n" "jaKh/I0tY7Cvf19mX3uoyS4omWRqZqopQdeLOvuqiCip23YyO3lK4Yzkq1E58JGi\n" "WLGe5UJ8kY8Bko79dGNsHsU01pAaI0QN/fSmwhHQqfpMv62cAkqB9GSilRalxf3+\n" "mDtJhYBdaDKbB5+QDqh40HcH838H+GcQLXxdT5ogdchjeldZJzsTwEhRq3yDcYr3\n" "ie6ocWVLchQx9CKpxPufRTEpuo3BPMqdTxhZJZWPG27I/FSWnUmd0auirFY51Rw6\n" "9wIDAQAB\n" "-----END PUBLIC KEY-----\n"; static char check_parameters(const string &params, swissknife::ArgumentList *args) { for (unsigned i = 0; i < params.length(); ++i) { char param = params[i]; if (args->find(param) == args->end()) { return param; } } return '\0'; } static void create_pk_file(const string &path, const char content[], int content_size) { int retval; FILE *pk_file = fopen(path.c_str(), "w"); assert(pk_file); retval = fwrite(content, sizeof(char), content_size, pk_file); assert(retval); retval = fclose(pk_file); assert(retval == 0); retval = chmod(path.c_str(), 0644); assert(retval == 0); } int main(int argc, char *argv[]) { if (argc < 7) { printf("Not enough arguments: %d\n\n", argc); swissknife::Usage(); return 1; } int retval; // load some default arguments swissknife::ArgumentList args; string default_num_threads = "4"; args['n'] = &default_num_threads; string option_string = "u:r:k:m:x:d:n:"; int c; while ((c = getopt(argc, argv, option_string.c_str())) != -1) { args[c] = new string(optarg); } // check all mandatory parameters are included string necessary_params = "urm"; char result; if ((result = check_parameters(necessary_params, &args)) != '\0') { printf("Argument not included but necessary: -%c\n\n", result); swissknife::Usage(); return 2; } if (args.find('x') == args.end()) args['x'] = new string(*args['r'] + "/txn"); // first create the alien cache string *alien_cache_dir = args['r']; retval = MkdirDeep(*alien_cache_dir, 0770); if (!retval) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to create %s", alien_cache_dir->c_str()); return 1; } retval = MakeCacheDirectories(*alien_cache_dir, 0770); if (!retval) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to create cache skeleton"); return 1; } // if there is no specified public key file we dump the cern.ch public key in // the temporary directory if (args.find('k') == args.end()) { string cern_pk_base_path = *args['x']; string cern_pk_path = cern_pk_base_path + "/cern.ch.pub"; string cern_pk_it1_path = cern_pk_base_path + "/cern-it1.cern.ch.pub"; string cern_pk_it2_path = cern_pk_base_path + "/cern-it2.cern.ch.pub"; string cern_pk_it3_path = cern_pk_base_path + "/cern-it3.cern.ch.pub"; create_pk_file(cern_pk_path, CERN_PUBLIC_KEY, sizeof(CERN_PUBLIC_KEY)); create_pk_file(cern_pk_it1_path, CERN_IT1_PUBLIC_KEY, sizeof(CERN_IT1_PUBLIC_KEY)); create_pk_file(cern_pk_it2_path, CERN_IT2_PUBLIC_KEY, sizeof(CERN_IT2_PUBLIC_KEY)); create_pk_file(cern_pk_it3_path, CERN_IT3_PUBLIC_KEY, sizeof(CERN_IT3_PUBLIC_KEY)); char path_separator = ':'; args['k'] = new string(cern_pk_path + path_separator + cern_pk_it1_path + path_separator + cern_pk_it2_path + path_separator + cern_pk_it3_path); } // now launch swissknife_pull swissknife::g_download_manager = new download::DownloadManager(); swissknife::g_signature_manager = new signature::SignatureManager(); swissknife::g_statistics = new perf::Statistics(); // load the command args['c'] = NULL; return swissknife::CommandPull().Main(args); } <commit_msg>FIX: renamed constants and removed key files in preload.cc<commit_after>/** * This file is part of the CernVM File System. */ #include "cvmfs_config.h" #include <stdio.h> #include <sys/stat.h> #include <unistd.h> #include <string> #include "compression.h" #include "download.h" #include "logging.h" #include "signature.h" #include "statistics.h" #include "swissknife.h" #include "swissknife_pull.h" #include "util.h" using namespace std; // NOLINT namespace swissknife { download::DownloadManager *g_download_manager; signature::SignatureManager *g_signature_manager; perf::Statistics *g_statistics; void Usage() { LogCvmfs(kLogCvmfs, kLogStderr, "Usage:\n" "cvmfs_preload -u <Stratum 0 URL>\n" " -r <alien cache directory>\n" " -k <public key>\n" " -m <fully qualified repository name>\n" " -x <directory for temporary files>\n" " -d <path to dirtab file>\n\n"); } } // namespace swissknife const char gCernPublicKey[] = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAukBusmYyFW8KJxVMmeCj\n" "N7vcU1mERMpDhPTa5PgFROSViiwbUsbtpP9CvfxB/KU1gggdbtWOTZVTQqA3b+p8\n" "g5Vve3/rdnN5ZEquxeEfIG6iEZta9Zei5mZMeuK+DPdyjtvN1wP0982ppbZzKRBu\n" "BbzR4YdrwwWXXNZH65zZuUISDJB4my4XRoVclrN5aGVz4PjmIZFlOJ+ytKsMlegW\n" "SNDwZO9z/YtBFil/Ca8FJhRPFMKdvxK+ezgq+OQWAerVNX7fArMC+4Ya5pF3ASr6\n" "3mlvIsBpejCUBygV4N2pxIcPJu/ZDaikmVvdPTNOTZlIFMf4zIP/YHegQSJmOyVp\n" "HQIDAQAB\n" "-----END PUBLIC KEY-----\n"; const char gCernIt1PublicKey[] = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo8uKvscgW7FNxzb65Uhm\n" "yr8jPJiyrl2kVzb/hhgdfN14C0tCbfFoE6ciuZFg+9ytLeiL9pzM96gSC+atIFl4\n" "7wTgtAFO1W4PtDQBwA/IG2bnwvNrzk19ob0JYhjZlS9tYKeh7TKCub55+vMwcEbP\n" "urzo3WSNCzJngiGMh1vM5iSlGLpCdSGzdwxLGwc1VjRM7q3KAd7M7TJCynKqXZPX\n" "R2xiD6I/p4xv39AnwphCFSmDh0MWE1WeeNHIiiveikvvN+l8d/ZNASIDhKNCsz6o\n" "aFDsGXvjGy7dg43YzjSSYSFGUnONtl5Fe6y4bQZj1LEPbeInW334MAbMwYF4LKma\n" "yQIDAQAB\n" "-----END PUBLIC KEY-----\n"; const char gCernIt2PublicKey[] = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkX6+mj6/X5yLV9uHt56l\n" "ZK1uLMueEULUhSCRrLj+9qz3EBMsANCjzfdabllKqWX/6qIfqppKVBwScF38aRnC\n" "vhlVGYtDgiqM1tfa1tA6BF7HUZQ1R1lU01tP0iYGhNTlTfY+fMAZDeerGDckT8cl\n" "NAQuICFUKy6w6aar8Sf3mpUC/hXVD2QUESmFgQ0SZhhW3eIB1xEoRxW0ieO6AidF\n" "qxmAxrB4H4+7i9O+B7Wf0VJQLSzP5bvIzx7xoqs3aUlnuzGFOaI8zypMvSvycSUb\n" "xhLsYbTgnlqSI/SPehMeQeEirhhKPaA+TsVSvxuqCJNoQ/wPBEG0HR+XkTsO9/sH\n" "FQIDAQAB\n" "-----END PUBLIC KEY-----\n"; const char gCernIt3PublicKey[] = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAosLXrVkA4p6IjQj6rUNM\n" "odr9oWB1nL3tWPKyPhS7mqAg+J4EW9m4ka/98PXi6jS/b1i/QLP9oGXlxJpugT1E\n" "jaKh/I0tY7Cvf19mX3uoyS4omWRqZqopQdeLOvuqiCip23YyO3lK4Yzkq1E58JGi\n" "WLGe5UJ8kY8Bko79dGNsHsU01pAaI0QN/fSmwhHQqfpMv62cAkqB9GSilRalxf3+\n" "mDtJhYBdaDKbB5+QDqh40HcH838H+GcQLXxdT5ogdchjeldZJzsTwEhRq3yDcYr3\n" "ie6ocWVLchQx9CKpxPufRTEpuo3BPMqdTxhZJZWPG27I/FSWnUmd0auirFY51Rw6\n" "9wIDAQAB\n" "-----END PUBLIC KEY-----\n"; static char CheckParameters(const string &params, swissknife::ArgumentList *args) { for (unsigned i = 0; i < params.length(); ++i) { char param = params[i]; if (args->find(param) == args->end()) { return param; } } return '\0'; } int main(int argc, char *argv[]) { if (argc < 7) { printf("Not enough arguments: %d\n\n", argc); swissknife::Usage(); return 1; } int retval; // load some default arguments swissknife::ArgumentList args; string default_num_threads = "4"; args['n'] = &default_num_threads; string option_string = "u:r:k:m:x:d:n:"; int c; while ((c = getopt(argc, argv, option_string.c_str())) != -1) { args[c] = new string(optarg); } // check all mandatory parameters are included string necessary_params = "urm"; char result; if ((result = CheckParameters(necessary_params, &args)) != '\0') { printf("Argument not included but necessary: -%c\n\n", result); swissknife::Usage(); return 2; } if (args.find('x') == args.end()) args['x'] = new string(*args['r'] + "/txn"); // first create the alien cache string *alien_cache_dir = args['r']; retval = MkdirDeep(*alien_cache_dir, 0770); if (!retval) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to create %s", alien_cache_dir->c_str()); return 1; } retval = MakeCacheDirectories(*alien_cache_dir, 0770); if (!retval) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to create cache skeleton"); return 1; } // if there is no specified public key file we dump the cern.ch public key in // the temporary directory string cern_pk_base_path = *args['x']; string cern_pk_path = cern_pk_base_path + "/cern.ch.pub"; string cern_pk_it1_path = cern_pk_base_path + "/cern-it1.cern.ch.pub"; string cern_pk_it2_path = cern_pk_base_path + "/cern-it2.cern.ch.pub"; string cern_pk_it3_path = cern_pk_base_path + "/cern-it3.cern.ch.pub"; bool keys_created = false; if (args.find('k') == args.end()) { keys_created = true; assert(CopyMem2Path(reinterpret_cast<const unsigned char*>(gCernPublicKey), sizeof(gCernPublicKey), cern_pk_path)); assert(CopyMem2Path( reinterpret_cast<const unsigned char*>(gCernIt1PublicKey), sizeof(gCernIt1PublicKey), cern_pk_it1_path)); assert(CopyMem2Path( reinterpret_cast<const unsigned char*>(gCernIt2PublicKey), sizeof(gCernIt2PublicKey), cern_pk_it2_path)); assert(CopyMem2Path( reinterpret_cast<const unsigned char*>(gCernIt3PublicKey), sizeof(gCernIt3PublicKey), cern_pk_it3_path)); char path_separator = ':'; args['k'] = new string(cern_pk_path + path_separator + cern_pk_it1_path + path_separator + cern_pk_it2_path + path_separator + cern_pk_it3_path); } // now launch swissknife_pull swissknife::g_download_manager = new download::DownloadManager(); swissknife::g_signature_manager = new signature::SignatureManager(); swissknife::g_statistics = new perf::Statistics(); // load the command args['c'] = NULL; retval = swissknife::CommandPull().Main(args); if (keys_created) { unlink(cern_pk_path.c_str()); unlink(cern_pk_it1_path.c_str()); unlink(cern_pk_it2_path.c_str()); unlink(cern_pk_it3_path.c_str()); } return retval; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: conpoly.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: os $ $Date: 2002-12-05 12:47:05 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PRECOMPILED #include "ui_pch.hxx" #endif #pragma hdrstop #ifndef _SVDMARK_HXX //autogen #include <svx/svdmark.hxx> #endif #ifndef _SVDVIEW_HXX //autogen #include <svx/svdview.hxx> #endif #ifndef _SVDOPATH_HXX //autogen #include <svx/svdopath.hxx> #endif #include "view.hxx" #include "edtwin.hxx" #include "wrtsh.hxx" #include "drawbase.hxx" #include "conpoly.hxx" /************************************************************************/ #define CLOSE_PIXDIST 5 // Pixelabstand, ab dem geschlossen wird /************************************************************************* |* |* Konstruktor |* \************************************************************************/ ConstPolygon::ConstPolygon(SwWrtShell* pWrtShell, SwEditWin* pEditWin, SwView* pSwView) : SwDrawBase(pWrtShell, pEditWin, pSwView) { } /************************************************************************* |* |* MouseButtonDown-event |* \************************************************************************/ BOOL ConstPolygon::MouseButtonDown(const MouseEvent& rMEvt) { BOOL bReturn; if ((bReturn = SwDrawBase::MouseButtonDown(rMEvt)) == TRUE) aLastPos = rMEvt.GetPosPixel(); return (bReturn); } /************************************************************************* |* |* MouseMove-event |* \************************************************************************/ BOOL ConstPolygon::MouseMove(const MouseEvent& rMEvt) { BOOL bReturn = FALSE; bReturn = SwDrawBase::MouseMove(rMEvt); return bReturn; } /************************************************************************* |* |* MouseButtonUp-event |* \************************************************************************/ BOOL ConstPolygon::MouseButtonUp(const MouseEvent& rMEvt) { BOOL bReturn = FALSE; if (pSh->IsDrawCreate()) { if (rMEvt.IsLeft() && rMEvt.GetClicks() == 1 && pWin->GetDrawMode() != OBJ_FREELINE) { if (!pSh->EndCreate(SDRCREATE_NEXTPOINT)) { pSh->BreakCreate(); EnterSelectMode(rMEvt); return TRUE; } } else { Point aPnt(pWin->PixelToLogic(rMEvt.GetPosPixel())); bReturn = SwDrawBase::MouseButtonUp(rMEvt); if (!(bReturn && (aPnt == aStartPos || rMEvt.IsRight()))) { SdrView *pSdrView = pSh->GetDrawView(); long nCloseDist = pWin->PixelToLogic(Size(CLOSE_PIXDIST, 0)).Width(); const SdrMarkList& rMarkList = pSdrView->GetMarkList(); if (rMarkList.GetMark(0)) { SdrPathObj* pPathObj = (SdrPathObj *)rMarkList.GetMark(0)->GetObj(); const XPolyPolygon& rXPP = pPathObj->GetPathPoly(); if (rXPP.Count() == 1) { USHORT nPntMax = rXPP[0].GetPointCount() - 1; Point aDiff = rXPP[0][nPntMax] - rXPP[0][0]; long nSqDist = aDiff.X() * aDiff.X() + aDiff.Y() * aDiff.Y(); nCloseDist *= nCloseDist; if (nSqDist <= nCloseDist && !pPathObj->IsClosed()) pPathObj->ToggleClosed(0); } } } } } else bReturn = SwDrawBase::MouseButtonUp(rMEvt); return (bReturn); } /************************************************************************* |* |* Function aktivieren |* \************************************************************************/ void ConstPolygon::Activate(const USHORT nSlotId) { switch (nSlotId) { case SID_DRAW_POLYGON_NOFILL: pWin->SetDrawMode(OBJ_PLIN); break; case SID_DRAW_BEZIER_NOFILL: pWin->SetDrawMode(OBJ_PATHLINE); break; case SID_DRAW_FREELINE_NOFILL: pWin->SetDrawMode(OBJ_FREELINE); break; default: break; } SwDrawBase::Activate(nSlotId); } <commit_msg>INTEGRATION: CWS os8 (1.2.138); FILE MERGED 2003/04/03 07:14:53 os 1.2.138.1: #108583# precompiled headers removed<commit_after>/************************************************************************* * * $RCSfile: conpoly.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2003-04-17 15:38:46 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _SVDMARK_HXX //autogen #include <svx/svdmark.hxx> #endif #ifndef _SVDVIEW_HXX //autogen #include <svx/svdview.hxx> #endif #ifndef _SVDOPATH_HXX //autogen #include <svx/svdopath.hxx> #endif #include "view.hxx" #include "edtwin.hxx" #include "wrtsh.hxx" #include "drawbase.hxx" #include "conpoly.hxx" /************************************************************************/ #define CLOSE_PIXDIST 5 // Pixelabstand, ab dem geschlossen wird /************************************************************************* |* |* Konstruktor |* \************************************************************************/ ConstPolygon::ConstPolygon(SwWrtShell* pWrtShell, SwEditWin* pEditWin, SwView* pSwView) : SwDrawBase(pWrtShell, pEditWin, pSwView) { } /************************************************************************* |* |* MouseButtonDown-event |* \************************************************************************/ BOOL ConstPolygon::MouseButtonDown(const MouseEvent& rMEvt) { BOOL bReturn; if ((bReturn = SwDrawBase::MouseButtonDown(rMEvt)) == TRUE) aLastPos = rMEvt.GetPosPixel(); return (bReturn); } /************************************************************************* |* |* MouseMove-event |* \************************************************************************/ BOOL ConstPolygon::MouseMove(const MouseEvent& rMEvt) { BOOL bReturn = FALSE; bReturn = SwDrawBase::MouseMove(rMEvt); return bReturn; } /************************************************************************* |* |* MouseButtonUp-event |* \************************************************************************/ BOOL ConstPolygon::MouseButtonUp(const MouseEvent& rMEvt) { BOOL bReturn = FALSE; if (pSh->IsDrawCreate()) { if (rMEvt.IsLeft() && rMEvt.GetClicks() == 1 && pWin->GetDrawMode() != OBJ_FREELINE) { if (!pSh->EndCreate(SDRCREATE_NEXTPOINT)) { pSh->BreakCreate(); EnterSelectMode(rMEvt); return TRUE; } } else { Point aPnt(pWin->PixelToLogic(rMEvt.GetPosPixel())); bReturn = SwDrawBase::MouseButtonUp(rMEvt); if (!(bReturn && (aPnt == aStartPos || rMEvt.IsRight()))) { SdrView *pSdrView = pSh->GetDrawView(); long nCloseDist = pWin->PixelToLogic(Size(CLOSE_PIXDIST, 0)).Width(); const SdrMarkList& rMarkList = pSdrView->GetMarkList(); if (rMarkList.GetMark(0)) { SdrPathObj* pPathObj = (SdrPathObj *)rMarkList.GetMark(0)->GetObj(); const XPolyPolygon& rXPP = pPathObj->GetPathPoly(); if (rXPP.Count() == 1) { USHORT nPntMax = rXPP[0].GetPointCount() - 1; Point aDiff = rXPP[0][nPntMax] - rXPP[0][0]; long nSqDist = aDiff.X() * aDiff.X() + aDiff.Y() * aDiff.Y(); nCloseDist *= nCloseDist; if (nSqDist <= nCloseDist && !pPathObj->IsClosed()) pPathObj->ToggleClosed(0); } } } } } else bReturn = SwDrawBase::MouseButtonUp(rMEvt); return (bReturn); } /************************************************************************* |* |* Function aktivieren |* \************************************************************************/ void ConstPolygon::Activate(const USHORT nSlotId) { switch (nSlotId) { case SID_DRAW_POLYGON_NOFILL: pWin->SetDrawMode(OBJ_PLIN); break; case SID_DRAW_BEZIER_NOFILL: pWin->SetDrawMode(OBJ_PATHLINE); break; case SID_DRAW_FREELINE_NOFILL: pWin->SetDrawMode(OBJ_FREELINE); break; default: break; } SwDrawBase::Activate(nSlotId); } <|endoftext|>
<commit_before> #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "BeaconEntity.h" #include "../BlockArea.h" cBeaconEntity::cBeaconEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World) : super(E_BLOCK_BEACON, a_BlockX, a_BlockY, a_BlockZ, a_World) { } int cBeaconEntity::GetPyramidLevel() { cBlockArea Area; Area.Read( m_World, GetPosX() - 4, GetPosX() + 4, GetPosY() - 5, GetPosY() - 1, GetPosZ() - 4, GetPosZ() + 4 ); int Layer = 1; int MiddleXZ = 4; for (int Y = Area.GetSizeY() - 1; Y > 0; Y--) { bool FullLayer = true; for (int X = MiddleXZ - Layer; X <= (MiddleXZ + Layer); X++) { for (int Z = MiddleXZ - Layer; Z <= (MiddleXZ + Layer); Z++) { if (!IsMineralBlock(Area.GetRelBlockType(X, Y, Z))) { FullLayer = false; } } } if (!FullLayer) { break; } else { Layer++; } } return Layer; } bool cBeaconEntity::IsMineralBlock(BLOCKTYPE a_BlockType) { switch(a_BlockType) { case E_BLOCK_DIAMOND_BLOCK: case E_BLOCK_GOLD_BLOCK: case E_BLOCK_IRON_BLOCK: case E_BLOCK_EMERALD_BLOCK: { return true; } } return false; } bool cBeaconEntity::Tick(float a_Dt, cChunk & a_Chunk) { return false; } void cBeaconEntity::SaveToJson(Json::Value& a_Value) { } void cBeaconEntity::SendTo(cClientHandle & a_Client) { } void cBeaconEntity::UsedBy(cPlayer * a_Player) { }<commit_msg>Simplefied GetPyramidLevel<commit_after> #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "BeaconEntity.h" #include "../BlockArea.h" cBeaconEntity::cBeaconEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World) : super(E_BLOCK_BEACON, a_BlockX, a_BlockY, a_BlockZ, a_World) { } int cBeaconEntity::GetPyramidLevel() { cBlockArea Area; Area.Read( m_World, GetPosX() - 4, GetPosX() + 4, GetPosY() - 5, GetPosY() - 1, GetPosZ() - 4, GetPosZ() + 4 ); int Layer = 1; int MiddleXZ = 4; for (int Y = Area.GetSizeY() - 1; Y > 0; Y--) { for (int X = MiddleXZ - Layer; X <= (MiddleXZ + Layer); X++) { for (int Z = MiddleXZ - Layer; Z <= (MiddleXZ + Layer); Z++) { if (!IsMineralBlock(Area.GetRelBlockType(X, Y, Z))) { return Layer; } } } Layer++; } return Layer; } bool cBeaconEntity::IsMineralBlock(BLOCKTYPE a_BlockType) { switch(a_BlockType) { case E_BLOCK_DIAMOND_BLOCK: case E_BLOCK_GOLD_BLOCK: case E_BLOCK_IRON_BLOCK: case E_BLOCK_EMERALD_BLOCK: { return true; } } return false; } bool cBeaconEntity::Tick(float a_Dt, cChunk & a_Chunk) { std::cout << GetPyramidLevel() << "\n"; return false; } void cBeaconEntity::SaveToJson(Json::Value& a_Value) { } void cBeaconEntity::SendTo(cClientHandle & a_Client) { } void cBeaconEntity::UsedBy(cPlayer * a_Player) { }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: grfshex.cxx,v $ * * $Revision: 1.16 $ * * last change: $Author: hr $ $Date: 2006-08-14 17:54:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #pragma hdrstop #ifndef _DOCARY_HXX #include <docary.hxx> #endif #ifndef _GRFSH_HXX #include <grfsh.hxx> #endif #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _VIEW_HXX #include <view.hxx> #endif #ifndef _DOCARY_HXX #include <docary.hxx> #endif #ifndef _TEXTSH_HXX #include <textsh.hxx> #endif #ifndef _VIEWOPT_HXX #include <viewopt.hxx> #endif #ifndef _SWUNDO_HXX #include <swundo.hxx> #endif #ifndef _SHELLS_HRC #include <shells.hrc> #endif #ifndef _CAPTION_HXX #include <caption.hxx> #endif #define _SVSTDARR_STRINGSSORTDTOR #include <svtools/svstdarr.hxx> #ifndef _FILTER_HXX #include <svtools/filter.hxx> #endif #ifndef _SVX_IMPGRF_HXX #include <svx/impgrf.hxx> #endif #ifndef _SVX_HTMLMODE_HXX //autogen #include <svx/htmlmode.hxx> #endif #ifndef _DOCSH_HXX #include <docsh.hxx> #endif #ifndef _FRMFMT_HXX #include <frmfmt.hxx> #endif #ifndef _FRMMGR_HXX #include <frmmgr.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _SVX_SVDOMEDIA_HXX #include <svx/svdomedia.hxx> #endif #ifndef _SVX_SVDVIEW_HXX #include <svx/svdview.hxx> #endif #ifndef _SVX_SVDPAGV_HXX #include <svx/svdpagv.hxx> #endif #ifndef _SWSTYLENAMEMAPPER_HXX #include <SwStyleNameMapper.hxx> #endif #ifndef _FILEDLGHELPER_HXX #include <sfx2/filedlghelper.hxx> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_ #include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_ #include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_ #include <com/sun/star/ui/dialogs/ListboxControlActions.hpp> #endif #ifndef _POOLFMT_HRC #include <poolfmt.hrc> #endif #include <sfx2/request.hxx> #include <sfx2/viewfrm.hxx> #include <svtools/stritem.hxx> #include <avmedia/mediawindow.hxx> // -> #111827# #include <SwRewriter.hxx> #include <undobj.hxx> #include <comcore.hrc> // <- #111827# using namespace ::com::sun::star::uno; using namespace ::com::sun::star::ui::dialogs; using namespace ::sfx2; using namespace ::rtl; bool SwTextShell::InsertMediaDlg( SfxRequest& rReq ) { ::rtl::OUString aURL; const SfxItemSet* pReqArgs = rReq.GetArgs(); Window* pWindow = &GetView().GetViewFrame()->GetWindow(); bool bAPI = false, bRet = false; if( pReqArgs ) { const SfxStringItem* pStringItem = PTR_CAST( SfxStringItem, &pReqArgs->Get( rReq.GetSlot() ) ); if( pStringItem ) { aURL = pStringItem->GetValue(); bAPI = aURL.getLength(); } } if( bAPI || ::avmedia::MediaWindow::executeMediaURLDialog( pWindow, aURL ) ) { Size aPrefSize; if( pWindow ) pWindow->EnterWait(); if( !::avmedia::MediaWindow::isMediaURL( aURL, true, &aPrefSize ) ) { if( pWindow ) pWindow->LeaveWait(); if( !bAPI ) ::avmedia::MediaWindow::executeFormatErrorBox( pWindow ); } else { SwWrtShell& rSh = GetShell(); if( !rSh.HasDrawView() ) rSh.MakeDrawView(); Size aDocSz( rSh.GetDocSize() ); const SwRect& rVisArea = rSh.VisArea(); Point aPos( rVisArea.Center() ); Size aSize; if( rVisArea.Width() > aDocSz.Width()) aPos.X() = aDocSz.Width() / 2 + rVisArea.Left(); if(rVisArea.Height() > aDocSz.Height()) aPos.Y() = aDocSz.Height() / 2 + rVisArea.Top(); if( aPrefSize.Width() && aPrefSize.Height() ) { if( pWindow ) aSize = pWindow->PixelToLogic( aPrefSize, MAP_TWIP ); else aSize = Application::GetDefaultDevice()->PixelToLogic( aPrefSize, MAP_TWIP ); } else aSize = Size( 2835, 2835 ); SdrMediaObj* pObj = new SdrMediaObj( Rectangle( aPos, aSize ) ); pObj->setURL( aURL ); rSh.EnterStdMode(); rSh.SwFEShell::Insert( *pObj, 0, 0, &aPos ); bRet = true; if( pWindow ) pWindow->LeaveWait(); } } return bRet; } <commit_msg>INTEGRATION: CWS pchfix02 (1.16.2); FILE MERGED 2006/09/01 17:53:19 kaib 1.16.2.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: grfshex.cxx,v $ * * $Revision: 1.17 $ * * last change: $Author: obo $ $Date: 2006-09-16 23:15:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _DOCARY_HXX #include <docary.hxx> #endif #ifndef _GRFSH_HXX #include <grfsh.hxx> #endif #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _VIEW_HXX #include <view.hxx> #endif #ifndef _DOCARY_HXX #include <docary.hxx> #endif #ifndef _TEXTSH_HXX #include <textsh.hxx> #endif #ifndef _VIEWOPT_HXX #include <viewopt.hxx> #endif #ifndef _SWUNDO_HXX #include <swundo.hxx> #endif #ifndef _SHELLS_HRC #include <shells.hrc> #endif #ifndef _CAPTION_HXX #include <caption.hxx> #endif #define _SVSTDARR_STRINGSSORTDTOR #include <svtools/svstdarr.hxx> #ifndef _FILTER_HXX #include <svtools/filter.hxx> #endif #ifndef _SVX_IMPGRF_HXX #include <svx/impgrf.hxx> #endif #ifndef _SVX_HTMLMODE_HXX //autogen #include <svx/htmlmode.hxx> #endif #ifndef _DOCSH_HXX #include <docsh.hxx> #endif #ifndef _FRMFMT_HXX #include <frmfmt.hxx> #endif #ifndef _FRMMGR_HXX #include <frmmgr.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _SVX_SVDOMEDIA_HXX #include <svx/svdomedia.hxx> #endif #ifndef _SVX_SVDVIEW_HXX #include <svx/svdview.hxx> #endif #ifndef _SVX_SVDPAGV_HXX #include <svx/svdpagv.hxx> #endif #ifndef _SWSTYLENAMEMAPPER_HXX #include <SwStyleNameMapper.hxx> #endif #ifndef _FILEDLGHELPER_HXX #include <sfx2/filedlghelper.hxx> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_ #include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_ #include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_ #include <com/sun/star/ui/dialogs/ListboxControlActions.hpp> #endif #ifndef _POOLFMT_HRC #include <poolfmt.hrc> #endif #include <sfx2/request.hxx> #include <sfx2/viewfrm.hxx> #include <svtools/stritem.hxx> #include <avmedia/mediawindow.hxx> // -> #111827# #include <SwRewriter.hxx> #include <undobj.hxx> #include <comcore.hrc> // <- #111827# using namespace ::com::sun::star::uno; using namespace ::com::sun::star::ui::dialogs; using namespace ::sfx2; using namespace ::rtl; bool SwTextShell::InsertMediaDlg( SfxRequest& rReq ) { ::rtl::OUString aURL; const SfxItemSet* pReqArgs = rReq.GetArgs(); Window* pWindow = &GetView().GetViewFrame()->GetWindow(); bool bAPI = false, bRet = false; if( pReqArgs ) { const SfxStringItem* pStringItem = PTR_CAST( SfxStringItem, &pReqArgs->Get( rReq.GetSlot() ) ); if( pStringItem ) { aURL = pStringItem->GetValue(); bAPI = aURL.getLength(); } } if( bAPI || ::avmedia::MediaWindow::executeMediaURLDialog( pWindow, aURL ) ) { Size aPrefSize; if( pWindow ) pWindow->EnterWait(); if( !::avmedia::MediaWindow::isMediaURL( aURL, true, &aPrefSize ) ) { if( pWindow ) pWindow->LeaveWait(); if( !bAPI ) ::avmedia::MediaWindow::executeFormatErrorBox( pWindow ); } else { SwWrtShell& rSh = GetShell(); if( !rSh.HasDrawView() ) rSh.MakeDrawView(); Size aDocSz( rSh.GetDocSize() ); const SwRect& rVisArea = rSh.VisArea(); Point aPos( rVisArea.Center() ); Size aSize; if( rVisArea.Width() > aDocSz.Width()) aPos.X() = aDocSz.Width() / 2 + rVisArea.Left(); if(rVisArea.Height() > aDocSz.Height()) aPos.Y() = aDocSz.Height() / 2 + rVisArea.Top(); if( aPrefSize.Width() && aPrefSize.Height() ) { if( pWindow ) aSize = pWindow->PixelToLogic( aPrefSize, MAP_TWIP ); else aSize = Application::GetDefaultDevice()->PixelToLogic( aPrefSize, MAP_TWIP ); } else aSize = Size( 2835, 2835 ); SdrMediaObj* pObj = new SdrMediaObj( Rectangle( aPos, aSize ) ); pObj->setURL( aURL ); rSh.EnterStdMode(); rSh.SwFEShell::Insert( *pObj, 0, 0, &aPos ); bRet = true; if( pWindow ) pWindow->LeaveWait(); } } return bRet; } <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // Copyright (c) 2014 Michael G. Brehm // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //----------------------------------------------------------------------------- #include "stdafx.h" #include "resource.h" #include "VmService.h" #pragma warning(push, 4) //--------------------------------------------------------------------------- // _tWinMain // // Main application entry point // // Arguments : // // instance - Application instance handle // previnstance - Unused in Win32, always set to NULL // cmdline - Pointer to application command line string // show - Application initial display flags int APIENTRY _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int) { #ifdef _DEBUG int nDbgFlags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); // Get current flags nDbgFlags |= _CRTDBG_LEAK_CHECK_DF; // Enable leak-check _CrtSetDbgFlag(nDbgFlags); // Set the new flags #endif // _DEBUG //////// RPC_STATUS rpcresult = RpcServerUseAllProtseqsIf(RPC_C_PROTSEQ_MAX_REQS_DEFAULT, SystemCalls_v1_0_s_ifspec, nullptr); if(rpcresult != RPC_S_OK) { } /////// // Use manual dispatching for now; haven't implemented a new ServiceModule<> class yet ServiceTable services = { ServiceTableEntry<VmService>(L"Instance Service") }; services.Dispatch(); return 0; } //--------------------------------------------------------------------------- #pragma warning(pop) <commit_msg>Updated service template library to allow resource IDs as service name strings<commit_after>//----------------------------------------------------------------------------- // Copyright (c) 2014 Michael G. Brehm // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //----------------------------------------------------------------------------- #include "stdafx.h" #include "resource.h" #include "VmService.h" #pragma warning(push, 4) //--------------------------------------------------------------------------- // _tWinMain // // Main application entry point // // Arguments : // // instance - Application instance handle // previnstance - Unused in Win32, always set to NULL // cmdline - Pointer to application command line string // show - Application initial display flags int APIENTRY _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int) { #ifdef _DEBUG int nDbgFlags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); // Get current flags nDbgFlags |= _CRTDBG_LEAK_CHECK_DF; // Enable leak-check _CrtSetDbgFlag(nDbgFlags); // Set the new flags #endif // _DEBUG //////// RPC_STATUS rpcresult = RpcServerUseAllProtseqsIf(RPC_C_PROTSEQ_MAX_REQS_DEFAULT, SystemCalls_v1_0_s_ifspec, nullptr); if(rpcresult != RPC_S_OK) { } /////// // Use manual dispatching for now; haven't implemented a new ServiceModule<> class yet ServiceTable services = { ServiceTableEntry<VmService>(IDS_VMSERVICE_NAME) }; services.Dispatch(); return 0; } //--------------------------------------------------------------------------- #pragma warning(pop) <|endoftext|>
<commit_before>#pragma once #include <map> #include <type_traits> // conditionals #include <unordered_map> /// \file This file contains utilities and wrapper to iterate over Map and OrderedMap values/keys /// Source: https://gist.github.com/eruffaldi/93d09ed6644ae3fa279f namespace Ra { namespace Core { namespace Utils { /// \brief Generate a range to iterate over the keys of a map /// /// \tparam Mapclass Specialized Map or OrderedMap /// /// Usage: /// \snippet tests/unittest/Core/mapiterators.cpp Iterating over keys template <class Mapclass> struct map_keys { using map_t = Mapclass; struct iterator { using realiterator_t = typename std::conditional<std::is_const<map_t>::value, typename map_t::const_iterator, typename map_t::iterator>::type; using value_t = typename std::add_const<typename map_t::key_type>::type; realiterator_t under; iterator( realiterator_t x ) : under( x ) {} auto operator*() -> typename std::add_lvalue_reference<value_t>::type { return under->first; } auto operator-> () -> typename std::add_pointer<value_t>::type { return &under->first; } bool operator!=( const iterator& o ) const { return under != o.under; } iterator& operator++() { ++under; return *this; } iterator operator++( int ) { iterator x( *this ); ++under; return x; } }; map_keys( map_t& x ) : x_( x ) {} iterator begin() { return iterator( x_.begin() ); } iterator end() { return iterator( x_.end() ); } unsigned int size() const { return x_.size(); } map_t& x_; }; /// \brief Generate a range to iterate over the values of a map /// /// \tparam Mapclass Specialized Map or OrderedMap /// /// Usage: /// \snippet tests/unittest/Core/mapiterators.cpp Iterating over values template <class Mapclass> struct map_values { using map_t = Mapclass; struct iterator { using realiterator_t = typename std::conditional<std::is_const<map_t>::value, typename map_t::const_iterator, typename map_t::iterator>::type; using value_t = typename std::conditional<std::is_const<map_t>::value, typename std::add_const<typename map_t::mapped_type>::type, typename map_t::mapped_type>::type; realiterator_t under; iterator( realiterator_t x ) : under( x ) {} auto operator*() -> typename std::add_lvalue_reference<value_t>::type { return under->second; } auto operator-> () -> typename std::add_pointer<value_t>::type { return &under->second; } bool operator!=( const iterator& o ) const { return under != o.under; } iterator& operator++() { ++under; return *this; } iterator operator++( int ) { iterator x( *this ); ++under; return x; } }; map_values( map_t& x ) : x_( x ) {} iterator begin() { return iterator( x_.begin() ); } iterator end() { return iterator( x_.end() ); } unsigned int size() const { return x_.size(); } map_t& x_; }; } // namespace Utils } // namespace Core } // namespace Ra <commit_msg>[Core] StdMapIterator: add virtual destructor<commit_after>#pragma once #include <map> #include <type_traits> // conditionals #include <unordered_map> /// \file This file contains utilities and wrapper to iterate over Map and OrderedMap values/keys /// Source: https://gist.github.com/eruffaldi/93d09ed6644ae3fa279f namespace Ra { namespace Core { namespace Utils { /// \brief Generate a range to iterate over the keys of a map /// /// \tparam Mapclass Specialized Map or OrderedMap /// /// Usage: /// \snippet tests/unittest/Core/mapiterators.cpp Iterating over keys template <class Mapclass> struct map_keys { using map_t = Mapclass; struct iterator { using realiterator_t = typename std::conditional<std::is_const<map_t>::value, typename map_t::const_iterator, typename map_t::iterator>::type; using value_t = typename std::add_const<typename map_t::key_type>::type; realiterator_t under; iterator( realiterator_t x ) : under( x ) {} auto operator*() -> typename std::add_lvalue_reference<value_t>::type { return under->first; } auto operator-> () -> typename std::add_pointer<value_t>::type { return &under->first; } bool operator!=( const iterator& o ) const { return under != o.under; } iterator& operator++() { ++under; return *this; } iterator operator++( int ) { iterator x( *this ); ++under; return x; } }; map_keys( map_t& x ) : x_( x ) {} virtual inline ~map_keys() = default; iterator begin() { return iterator( x_.begin() ); } iterator end() { return iterator( x_.end() ); } unsigned int size() const { return x_.size(); } map_t& x_; }; /// \brief Generate a range to iterate over the values of a map /// /// \tparam Mapclass Specialized Map or OrderedMap /// /// Usage: /// \snippet tests/unittest/Core/mapiterators.cpp Iterating over values template <class Mapclass> struct map_values { using map_t = Mapclass; struct iterator { using realiterator_t = typename std::conditional<std::is_const<map_t>::value, typename map_t::const_iterator, typename map_t::iterator>::type; using value_t = typename std::conditional<std::is_const<map_t>::value, typename std::add_const<typename map_t::mapped_type>::type, typename map_t::mapped_type>::type; realiterator_t under; iterator( realiterator_t x ) : under( x ) {} auto operator*() -> typename std::add_lvalue_reference<value_t>::type { return under->second; } auto operator-> () -> typename std::add_pointer<value_t>::type { return &under->second; } bool operator!=( const iterator& o ) const { return under != o.under; } iterator& operator++() { ++under; return *this; } iterator operator++( int ) { iterator x( *this ); ++under; return x; } }; map_values( map_t& x ) : x_( x ) {} iterator begin() { return iterator( x_.begin() ); } iterator end() { return iterator( x_.end() ); } unsigned int size() const { return x_.size(); } map_t& x_; }; } // namespace Utils } // namespace Core } // namespace Ra <|endoftext|>
<commit_before> #include "otbWrapperOutputProcessXMLParameter.h" #include "otbWrapperChoiceParameter.h" #include "otbWrapperListViewParameter.h" #include "otbWrapperDirectoryParameter.h" #include "otbWrapperEmptyParameter.h" #include "otbWrapperInputFilenameParameter.h" #include "otbWrapperInputFilenameListParameter.h" #include "otbWrapperOutputFilenameParameter.h" #include "otbWrapperInputVectorDataParameter.h" #include "otbWrapperInputVectorDataListParameter.h" #include "otbWrapperNumericalParameter.h" #include "otbWrapperOutputVectorDataParameter.h" #include "otbWrapperRadiusParameter.h" #include "otbWrapperStringParameter.h" #include "otbWrapperStringListParameter.h" #include "otbWrapperInputImageParameter.h" #include "otbWrapperInputImageListParameter.h" #include "otbWrapperComplexInputImageParameter.h" #include "otbWrapperOutputImageParameter.h" #include "otbWrapperComplexOutputImageParameter.h" #include "otbWrapperRAMParameter.h" #include "itksys/SystemTools.hxx" namespace otb { namespace Wrapper { OutputProcessXMLParameter::OutputProcessXMLParameter() { this->SetKey("outxml"); this->SetName("Save otb application to xml file"); this->SetDescription("Save otb application to xml file"); this->SetMandatory(false); this->SetActive(false); this->SetRole(Role_Output); } OutputProcessXMLParameter::~OutputProcessXMLParameter() { } std::string OutputProcessXMLParameter::pixelTypeToString(ImagePixelType pixType) { std::string type; switch( pixType ) { case ImagePixelType_uint8: { type = "uint8"; break; } case ImagePixelType_int16: { type = "int16"; break; } case ImagePixelType_uint16: { type = "uint16"; break; } case ImagePixelType_int32: { type = "int32"; break; } case ImagePixelType_uint32: { type = "uint32"; break; } case ImagePixelType_float: { type = "float"; break; } case ImagePixelType_double: { type = "double"; break; } } return type; } TiXmlElement* OutputProcessXMLParameter::AddChildNodeTo(TiXmlElement *parent, std::string name, std::string value) { TiXmlElement * n_Node = new TiXmlElement( name.c_str() ); parent->LinkEndChild( n_Node ); if(!value.empty()) { TiXmlText * nv_NodeValue = new TiXmlText( value.c_str() ); n_Node->LinkEndChild( nv_NodeValue ); } return n_Node; } void OutputProcessXMLParameter::Write(Application::Pointer app) { // Check if the filename is not empty if(m_FileName.empty()) itkExceptionMacro("The XML output FileName is empty, please set the filename via the method SetFileName"); // Check that the right extension is given : expected .xml */ if (itksys::SystemTools::GetFilenameLastExtension(m_FileName) != ".xml") { itkExceptionMacro(<<itksys::SystemTools::GetFilenameLastExtension(m_FileName) <<" is a wrong Extension FileName : Expected .xml"); } // start creating XML file TiXmlDocument doc; TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" ); doc.LinkEndChild( decl ); TiXmlElement * n_OTB = new TiXmlElement( "OTB"); doc.LinkEndChild( n_OTB ); std::string version = "3.18"; std::string platform = "Linux"; std::string build = "18-05-2013"; AddChildNodeTo(n_OTB, "version", version); AddChildNodeTo(n_OTB, "build", build); AddChildNodeTo(n_OTB, "platform", platform); TiXmlElement *n_App; n_App = AddChildNodeTo(n_OTB, "application"); AddChildNodeTo(n_App, "name", app->GetName()); AddChildNodeTo(n_App, "descr", app->GetDescription()); TiXmlElement *n_AppDoc; n_AppDoc = AddChildNodeTo(n_App, "doc"); AddChildNodeTo(n_AppDoc, "name", app->GetDocName()); AddChildNodeTo(n_AppDoc, "longdescr", app->GetDocLongDescription()); AddChildNodeTo(n_AppDoc, "authors", app->GetDocAuthors()); AddChildNodeTo(n_AppDoc, "limitations", app->GetDocLimitations()); AddChildNodeTo(n_AppDoc, "seealso", app->GetDocSeeAlso()); TiXmlElement *n_DocTags; n_DocTags = AddChildNodeTo(n_AppDoc, "tags"); std::vector<std::string> docTagList = app->GetDocTags(); std::vector<std::string>::iterator tagIt; for(tagIt = docTagList.begin(); tagIt!= docTagList.end(); ++tagIt) { std::string tag = *tagIt; AddChildNodeTo(n_DocTags, "tag", tag); } ParameterGroup::Pointer paramGroup = app->GetParameterList(); std::vector<std::string> paramList = paramGroup->GetParametersKeys(true); // Iterate through parameters for (std::vector<std::string>::const_iterator it = paramList.begin(); it!= paramList.end(); ++it) { std::string key = *it; Parameter *param = paramGroup->GetParameterByKey(key); std::string paramName = param->GetName(); ParameterType type = app->GetParameterType(key); std::string typeAsString = paramGroup->GetParameterTypeAsString(type); // if param is a Group, dont do anything, ParamGroup dont have values if (type != ParameterType_Group) { bool paramExists = app->HasValue(key) && app->IsParameterEnabled(key); if ( key == "outxml" ) { paramExists = false; } if (type == ParameterType_Empty) { paramExists = true; } // if parameter doesn't have any value then skip it if (paramExists) { std::vector<std::string> values; std::string value; bool hasValueList = false; if (type == ParameterType_OutputImage) { OutputImageParameter *imgParam = dynamic_cast<OutputImageParameter *>(param); value = imgParam->GetFileName(); ImagePixelType pixType = imgParam->GetPixelType(); std::string ptype = pixelTypeToString(pixType); //FIXME save this } else if( type == ParameterType_InputImageList || type == ParameterType_InputFilenameList || type == ParameterType_InputVectorDataList || type == ParameterType_StringList ) { values = app->GetParameterStringList(key); hasValueList = true; } else if (type == ParameterType_Float || type == ParameterType_Int || type == ParameterType_Radius || type == ParameterType_RAM ) { value = app->GetParameterAsString(key); } else if ( type == ParameterType_String || type == ParameterType_InputFilename || type == ParameterType_Directory || type == ParameterType_InputImage || type == ParameterType_ComplexInputImage || type == ParameterType_InputVectorData || type == ParameterType_Choice || type == ParameterType_ListView || type == ParameterType_OutputVectorData || type == ParameterType_OutputFilename) { value = app->GetParameterString(key); } else if(key == "rand") { std::ostringstream strm; strm << app->GetParameterInt("rand"); value = strm.str(); } else if (typeAsString == "Empty") { EmptyParameter* eParam = dynamic_cast<EmptyParameter *> (param); value = "false"; if( eParam->GetActive() ) { value = "true"; } } //get only file name /* if(type == ParameterType_InputFilename || type == ParameterType_InputImage || type == ParameterType_ComplexInputImage || type == ParameterType_InputVectorData || type == ParameterType_OutputVectorData || type == ParameterType_OutputFilename) { unsigned found = value.find_last_of("/\\"); //std::cerr << " path: " << value.substr(0,found) << '\n'; value = value.substr(found+1); } else if(type == ParameterType_InputImageList || type == ParameterType_InputFilenameList || type == ParameterType_InputVectorDataList) { std::vector<std::string>::iterator strIt; for(strIt = values.begin(); strIt != values.end(); ++strIt) { std::string val = *strIt; unsigned found = val.find_last_of("/\\"); *strIt = val.substr(found+1); } } */ //parameter node in xml TiXmlElement * n_Parameter = new TiXmlElement("parameter"); const char * mandatory = "false"; if( param->GetMandatory() ) mandatory = "true"; n_Parameter->SetAttribute("mandatory", mandatory); //setting parameter key as child node in parameter AddChildNodeTo(n_Parameter, "key", key); AddChildNodeTo(n_Parameter, "type", typeAsString); AddChildNodeTo(n_Parameter, "name", paramName); if(!hasValueList) { AddChildNodeTo(n_Parameter, "value", value); } else { TiXmlElement *n_Values = AddChildNodeTo(n_Parameter, "values"); std::vector<std::string>::iterator strIt; for(strIt = values.begin(); strIt != values.end(); ++strIt) { AddChildNodeTo(n_Values, "value",*strIt); } } n_App->LinkEndChild(n_Parameter); } } } // Finally, write xml contents to file doc.SaveFile( m_FileName.c_str() ); } } //end namespace wrapper } //end namespace otb <commit_msg>BUG: setting precision for float parameter for writing as string to xml<commit_after> #include "otbWrapperOutputProcessXMLParameter.h" #include "otbWrapperChoiceParameter.h" #include "otbWrapperListViewParameter.h" #include "otbWrapperDirectoryParameter.h" #include "otbWrapperEmptyParameter.h" #include "otbWrapperInputFilenameParameter.h" #include "otbWrapperInputFilenameListParameter.h" #include "otbWrapperOutputFilenameParameter.h" #include "otbWrapperInputVectorDataParameter.h" #include "otbWrapperInputVectorDataListParameter.h" #include "otbWrapperNumericalParameter.h" #include "otbWrapperOutputVectorDataParameter.h" #include "otbWrapperRadiusParameter.h" #include "otbWrapperStringParameter.h" #include "otbWrapperStringListParameter.h" #include "otbWrapperInputImageParameter.h" #include "otbWrapperInputImageListParameter.h" #include "otbWrapperComplexInputImageParameter.h" #include "otbWrapperOutputImageParameter.h" #include "otbWrapperComplexOutputImageParameter.h" #include "otbWrapperRAMParameter.h" #include "itksys/SystemTools.hxx" namespace otb { namespace Wrapper { OutputProcessXMLParameter::OutputProcessXMLParameter() { this->SetKey("outxml"); this->SetName("Save otb application to xml file"); this->SetDescription("Save otb application to xml file"); this->SetMandatory(false); this->SetActive(false); this->SetRole(Role_Output); } OutputProcessXMLParameter::~OutputProcessXMLParameter() { } std::string OutputProcessXMLParameter::pixelTypeToString(ImagePixelType pixType) { std::string type; switch( pixType ) { case ImagePixelType_uint8: { type = "uint8"; break; } case ImagePixelType_int16: { type = "int16"; break; } case ImagePixelType_uint16: { type = "uint16"; break; } case ImagePixelType_int32: { type = "int32"; break; } case ImagePixelType_uint32: { type = "uint32"; break; } case ImagePixelType_float: { type = "float"; break; } case ImagePixelType_double: { type = "double"; break; } } return type; } TiXmlElement* OutputProcessXMLParameter::AddChildNodeTo(TiXmlElement *parent, std::string name, std::string value) { TiXmlElement * n_Node = new TiXmlElement( name.c_str() ); parent->LinkEndChild( n_Node ); if(!value.empty()) { TiXmlText * nv_NodeValue = new TiXmlText( value.c_str() ); n_Node->LinkEndChild( nv_NodeValue ); } return n_Node; } void OutputProcessXMLParameter::Write(Application::Pointer app) { // Check if the filename is not empty if(m_FileName.empty()) itkExceptionMacro("The XML output FileName is empty, please set the filename via the method SetFileName"); // Check that the right extension is given : expected .xml */ if (itksys::SystemTools::GetFilenameLastExtension(m_FileName) != ".xml") { itkExceptionMacro(<<itksys::SystemTools::GetFilenameLastExtension(m_FileName) <<" is a wrong Extension FileName : Expected .xml"); } // start creating XML file TiXmlDocument doc; TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" ); doc.LinkEndChild( decl ); TiXmlElement * n_OTB = new TiXmlElement( "OTB"); doc.LinkEndChild( n_OTB ); std::string version = "3.18"; std::string platform = "Linux"; std::string build = "18-05-2013"; AddChildNodeTo(n_OTB, "version", version); AddChildNodeTo(n_OTB, "build", build); AddChildNodeTo(n_OTB, "platform", platform); TiXmlElement *n_App; n_App = AddChildNodeTo(n_OTB, "application"); AddChildNodeTo(n_App, "name", app->GetName()); AddChildNodeTo(n_App, "descr", app->GetDescription()); TiXmlElement *n_AppDoc; n_AppDoc = AddChildNodeTo(n_App, "doc"); AddChildNodeTo(n_AppDoc, "name", app->GetDocName()); AddChildNodeTo(n_AppDoc, "longdescr", app->GetDocLongDescription()); AddChildNodeTo(n_AppDoc, "authors", app->GetDocAuthors()); AddChildNodeTo(n_AppDoc, "limitations", app->GetDocLimitations()); AddChildNodeTo(n_AppDoc, "seealso", app->GetDocSeeAlso()); TiXmlElement *n_DocTags; n_DocTags = AddChildNodeTo(n_AppDoc, "tags"); std::vector<std::string> docTagList = app->GetDocTags(); std::vector<std::string>::iterator tagIt; for(tagIt = docTagList.begin(); tagIt!= docTagList.end(); ++tagIt) { std::string tag = *tagIt; AddChildNodeTo(n_DocTags, "tag", tag); } ParameterGroup::Pointer paramGroup = app->GetParameterList(); std::vector<std::string> paramList = paramGroup->GetParametersKeys(true); // Iterate through parameters for (std::vector<std::string>::const_iterator it = paramList.begin(); it!= paramList.end(); ++it) { std::string key = *it; Parameter *param = paramGroup->GetParameterByKey(key); std::string paramName = param->GetName(); ParameterType type = app->GetParameterType(key); std::string typeAsString = paramGroup->GetParameterTypeAsString(type); // if param is a Group, dont do anything, ParamGroup dont have values if (type != ParameterType_Group) { bool paramExists = app->HasValue(key) && app->IsParameterEnabled(key); if ( key == "outxml" ) { paramExists = false; } if (type == ParameterType_Empty) { paramExists = true; } // if parameter doesn't have any value then skip it if (paramExists) { std::vector<std::string> values; std::string value; bool hasValueList = false; if (type == ParameterType_OutputImage) { OutputImageParameter *imgParam = dynamic_cast<OutputImageParameter *>(param); value = imgParam->GetFileName(); ImagePixelType pixType = imgParam->GetPixelType(); std::string ptype = pixelTypeToString(pixType); //FIXME save this } else if( type == ParameterType_InputImageList || type == ParameterType_InputFilenameList || type == ParameterType_InputVectorDataList || type == ParameterType_StringList ) { values = app->GetParameterStringList(key); hasValueList = true; } else if (type == ParameterType_Int || type == ParameterType_Radius || type == ParameterType_RAM ) { value = app->GetParameterAsString(key); } else if(type == ParameterType_Float) { std::ostringstream oss; oss << std::setprecision(10); oss << app->GetParameterFloat( key ); value = oss.str(); } else if ( type == ParameterType_String || type == ParameterType_InputFilename || type == ParameterType_Directory || type == ParameterType_InputImage || type == ParameterType_ComplexInputImage || type == ParameterType_InputVectorData || type == ParameterType_Choice || type == ParameterType_ListView || type == ParameterType_OutputVectorData || type == ParameterType_OutputFilename) { value = app->GetParameterString(key); } else if(key == "rand") { std::ostringstream strm; strm << app->GetParameterInt("rand"); value = strm.str(); } else if (typeAsString == "Empty") { EmptyParameter* eParam = dynamic_cast<EmptyParameter *> (param); value = "false"; if( eParam->GetActive() ) { value = "true"; } } //get only file name /* if(type == ParameterType_InputFilename || type == ParameterType_InputImage || type == ParameterType_ComplexInputImage || type == ParameterType_InputVectorData || type == ParameterType_OutputVectorData || type == ParameterType_OutputFilename) { unsigned found = value.find_last_of("/\\"); //std::cerr << " path: " << value.substr(0,found) << '\n'; value = value.substr(found+1); } else if(type == ParameterType_InputImageList || type == ParameterType_InputFilenameList || type == ParameterType_InputVectorDataList) { std::vector<std::string>::iterator strIt; for(strIt = values.begin(); strIt != values.end(); ++strIt) { std::string val = *strIt; unsigned found = val.find_last_of("/\\"); *strIt = val.substr(found+1); } } */ //parameter node in xml TiXmlElement * n_Parameter = new TiXmlElement("parameter"); const char * mandatory = "false"; if( param->GetMandatory() ) mandatory = "true"; n_Parameter->SetAttribute("mandatory", mandatory); //setting parameter key as child node in parameter AddChildNodeTo(n_Parameter, "key", key); AddChildNodeTo(n_Parameter, "type", typeAsString); AddChildNodeTo(n_Parameter, "name", paramName); if(!hasValueList) { AddChildNodeTo(n_Parameter, "value", value); } else { TiXmlElement *n_Values = AddChildNodeTo(n_Parameter, "values"); std::vector<std::string>::iterator strIt; for(strIt = values.begin(); strIt != values.end(); ++strIt) { AddChildNodeTo(n_Values, "value",*strIt); } } n_App->LinkEndChild(n_Parameter); } } } // Finally, write xml contents to file doc.SaveFile( m_FileName.c_str() ); } } //end namespace wrapper } //end namespace otb <|endoftext|>
<commit_before>// $Id: mesh_data_unv_support.C,v 1.3 2003-05-22 09:39:58 spetersen Exp $ // The Next Great Finite Element Library. // Copyright (C) 2002 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <fstream> #include <stdio.h> // Local includes #include "mesh_data.h" #include "mesh_base.h" //------------------------------------------------------ // MeshData UNV support functions void MeshData::read_unv(const std::string& name) { /* * When reading data, make sure the id maps are ok */ assert (_node_id_map_closed); assert (_elem_id_map_closed); /** * clear the data, but keep the id maps */ this->clear(); std::ifstream in_file (name.c_str()); if ( !in_file.good() ) { std::cerr << "ERROR: Input file not good." << std::endl; error(); } const std::string _label_dataset_mesh_data = "2414"; /** * locate the beginning of data set * and read it. */ { std::string olds, news; while (true) { in_file >> olds >> news; /* * a "-1" followed by a number means the beginning of a dataset * stop combing at the end of the file */ while( ((olds != "-1") || (news == "-1") ) && !in_file.eof() ) { olds = news; in_file >> news; } if(in_file.eof()) break; /* * if beginning of dataset, buffer it in * temp_buffer, if desired */ if (news == _label_dataset_mesh_data) { /** * Now read the data of interest. */ /** * Ignore the first lines that stand for * analysis dataset label and name. */ for(unsigned int i=0; i<3; i++) in_file.ignore(256,'\n'); unsigned int Dataset_location; unsigned int Model_type, Analysis_type, Data_characteristic, Result_type, Data_type, NVALDC; Real dummy_Real; /** * Read the dataset location, where * 1: Data at nodes * 2: Data on elements * other sets are currently not supported. */ in_file >> Dataset_location; if (Dataset_location != 1) { std::cerr << "ERROR: Currently only Data at nodes is supported." << std::endl; error(); } /** * Ignore five ID lines. */ for(unsigned int i=0; i<6; i++) in_file.ignore(256,'\n'); /** * Read record 9. */ in_file >> Model_type // not supported yet >> Analysis_type // not supported yet >> Data_characteristic // not supported yet >> Result_type // not supported yet >> Data_type >> NVALDC; /** * Ignore record 10 and 11 * (Integer analysis type specific data). */ for (unsigned int i=0; i<3; i++) in_file.ignore(256,'\n'); /** * Ignore record 12 and record 13. */ for (unsigned int i=0; i<12; i++) in_file >> dummy_Real; /** * Now get the foreign node id number and the respective nodal data. */ int f_n_id; std::vector<Number> values; while(true) { in_file >> f_n_id; /** * if node_nr = -1 then we have reached the end of the dataset. */ if (f_n_id==-1) break; /** * Resize the values vector (usually data in three * principal directions, i.e. NVALDC = 3). */ values.resize(NVALDC); /** * Read the meshdata for the respective node. */ for (unsigned int data_cnt=0; data_cnt<NVALDC; data_cnt++) { /** * Check what data type we are reading. * 2,4: Real * 5,6: Complex * other data types are not supported yet. */ if (Data_type == 2 || Data_type == 4) in_file >> values[data_cnt]; else if(Data_type == 5 || Data_type == 6) { Real re_val, im_val; in_file >> re_val >> im_val; values[data_cnt] = Complex(re_val,im_val); } else { std::cerr << "ERROR: Data type not supported." << std::endl; error(); } } // end loop data_cnt /** * Add the values vector to the MechData data structure. */ const Node* node = foreign_id_to_node(f_n_id); _node_data.insert (std::make_pair(node, values)); } // while(true) } else { /** * all other datasets are ignored */ } } } /* * finished reading. Ready for use */ this->_node_data_closed = true; this->_elem_data_closed = true; } void MeshData::write_unv (const std::string& name) { /* * make sure the id maps are ready * and that we have data to write */ assert (_node_id_map_closed); assert (_elem_id_map_closed); assert (_node_data_closed); assert (_elem_data_closed); std::ofstream out_file (name.c_str()); const std::string _label_dataset_mesh_data = "2414"; /** * Currently this function handles only nodal data. */ assert (!_node_data.empty()); /** * Write the beginning of the dataset. */ out_file << " -1\n" << " " << _label_dataset_mesh_data << "\n"; /** * Record 1 (analysis dataset label, currently just a dummy). */ char buf[78]; sprintf(buf, "%10i\n",1); out_file << buf; /** * Record 2 (analysis dataset name, currently just a dummy). */ std::string _dummy_string = "libMesh\n"; out_file << _dummy_string; /** * Record 3 (dataset location). */ sprintf(buf, "%10i\n",1); out_file << buf; /** * Record 4 trough 8 (ID lines). */ for (unsigned int i=0; i<5;i++) out_file << _dummy_string; /** * Record 9 trough 11. */ sprintf(buf, "%10i%10i%10i%10i%10i%10i\n", 0, 0, 0, 0, 0, 0); out_file << buf; sprintf(buf, "%10i%10i%10i%10i%10i%10i%10i%10i\n", 0, 0, 0, 0, 0, 0, 0, 0); out_file << buf; sprintf(buf, "%10i%10i\n", 0, 0); out_file << buf; /** * Record 12 and 13. */ sprintf(buf, "%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n", 0., 0., 0., 0., 0., 0.); out_file << buf; sprintf(buf, "%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n", 0., 0., 0., 0., 0., 0.); out_file << buf; /** * Write the foreign node number and the respective data. */ std::map<const Node*, std::vector<Number> >::const_iterator nit = _node_data.begin(); for (; nit != _node_data.end(); ++nit) { const Node* node = (*nit).first; unsigned int f_n_id = node_to_foreign_id (node); sprintf(buf, "%10i\n", f_n_id); out_file << buf; std::vector<Number> values; this->operator()(node, values); for (unsigned int v_cnt=0; v_cnt<values.size(); v_cnt++) { #ifdef USE_COMPLEX_NUMBERS sprintf(buf, "%13.5E%13.5E", values[v_cnt].real(), values[v_cnt].imag()); out_file << buf; #else sprintf(buf, "%13.5E%13.5E", values[v_cnt]); out_file << buf; #endif } out_file << "\n"; } /** * Write end of the dataset. */ out_file << " -1\n"; } <commit_msg>fixed for Real data<commit_after>// $Id: mesh_data_unv_support.C,v 1.4 2003-05-22 16:20:52 benkirk Exp $ // The Next Great Finite Element Library. // Copyright (C) 2002 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <fstream> #include <stdio.h> // Local includes #include "mesh_data.h" #include "mesh_base.h" //------------------------------------------------------ // MeshData UNV support functions void MeshData::read_unv(const std::string& name) { /* * When reading data, make sure the id maps are ok */ assert (_node_id_map_closed); assert (_elem_id_map_closed); /** * clear the data, but keep the id maps */ this->clear(); std::ifstream in_file (name.c_str()); if ( !in_file.good() ) { std::cerr << "ERROR: Input file not good." << std::endl; error(); } const std::string _label_dataset_mesh_data = "2414"; /** * locate the beginning of data set * and read it. */ { std::string olds, news; while (true) { in_file >> olds >> news; /* * a "-1" followed by a number means the beginning of a dataset * stop combing at the end of the file */ while( ((olds != "-1") || (news == "-1") ) && !in_file.eof() ) { olds = news; in_file >> news; } if(in_file.eof()) break; /* * if beginning of dataset, buffer it in * temp_buffer, if desired */ if (news == _label_dataset_mesh_data) { /** * Now read the data of interest. */ /** * Ignore the first lines that stand for * analysis dataset label and name. */ for(unsigned int i=0; i<3; i++) in_file.ignore(256,'\n'); unsigned int Dataset_location; unsigned int Model_type, Analysis_type, Data_characteristic, Result_type, Data_type, NVALDC; Real dummy_Real; /** * Read the dataset location, where * 1: Data at nodes * 2: Data on elements * other sets are currently not supported. */ in_file >> Dataset_location; if (Dataset_location != 1) { std::cerr << "ERROR: Currently only Data at nodes is supported." << std::endl; error(); } /** * Ignore five ID lines. */ for(unsigned int i=0; i<6; i++) in_file.ignore(256,'\n'); /** * Read record 9. */ in_file >> Model_type // not supported yet >> Analysis_type // not supported yet >> Data_characteristic // not supported yet >> Result_type // not supported yet >> Data_type >> NVALDC; /** * Ignore record 10 and 11 * (Integer analysis type specific data). */ for (unsigned int i=0; i<3; i++) in_file.ignore(256,'\n'); /** * Ignore record 12 and record 13. */ for (unsigned int i=0; i<12; i++) in_file >> dummy_Real; /** * Now get the foreign node id number and the respective nodal data. */ int f_n_id; std::vector<Number> values; while(true) { in_file >> f_n_id; /** * if node_nr = -1 then we have reached the end of the dataset. */ if (f_n_id==-1) break; /** * Resize the values vector (usually data in three * principal directions, i.e. NVALDC = 3). */ values.resize(NVALDC); /** * Read the meshdata for the respective node. */ for (unsigned int data_cnt=0; data_cnt<NVALDC; data_cnt++) { /** * Check what data type we are reading. * 2,4: Real * 5,6: Complex * other data types are not supported yet. */ if (Data_type == 2 || Data_type == 4) in_file >> values[data_cnt]; else if(Data_type == 5 || Data_type == 6) { #ifdef USE_COMPLEX_NUMBERS Real re_val, im_val; in_file >> re_val >> im_val; values[data_cnt] = Complex(re_val,im_val); #else std::cerr << "ERROR: Complex data only supported" << std::endl << "when libMesh is configured with --enable-complex!" << std::endl; error(); #endif } else { std::cerr << "ERROR: Data type not supported." << std::endl; error(); } } // end loop data_cnt /** * Add the values vector to the MechData data structure. */ const Node* node = foreign_id_to_node(f_n_id); _node_data.insert (std::make_pair(node, values)); } // while(true) } else { /** * all other datasets are ignored */ } } } /* * finished reading. Ready for use */ this->_node_data_closed = true; this->_elem_data_closed = true; } void MeshData::write_unv (const std::string& name) { /* * make sure the id maps are ready * and that we have data to write */ assert (_node_id_map_closed); assert (_elem_id_map_closed); assert (_node_data_closed); assert (_elem_data_closed); std::ofstream out_file (name.c_str()); const std::string _label_dataset_mesh_data = "2414"; /** * Currently this function handles only nodal data. */ assert (!_node_data.empty()); /** * Write the beginning of the dataset. */ out_file << " -1\n" << " " << _label_dataset_mesh_data << "\n"; /** * Record 1 (analysis dataset label, currently just a dummy). */ char buf[78]; sprintf(buf, "%10i\n",1); out_file << buf; /** * Record 2 (analysis dataset name, currently just a dummy). */ std::string _dummy_string = "libMesh\n"; out_file << _dummy_string; /** * Record 3 (dataset location). */ sprintf(buf, "%10i\n",1); out_file << buf; /** * Record 4 trough 8 (ID lines). */ for (unsigned int i=0; i<5;i++) out_file << _dummy_string; /** * Record 9 trough 11. */ sprintf(buf, "%10i%10i%10i%10i%10i%10i\n", 0, 0, 0, 0, 0, 0); out_file << buf; sprintf(buf, "%10i%10i%10i%10i%10i%10i%10i%10i\n", 0, 0, 0, 0, 0, 0, 0, 0); out_file << buf; sprintf(buf, "%10i%10i\n", 0, 0); out_file << buf; /** * Record 12 and 13. */ sprintf(buf, "%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n", 0., 0., 0., 0., 0., 0.); out_file << buf; sprintf(buf, "%13.5E%13.5E%13.5E%13.5E%13.5E%13.5E\n", 0., 0., 0., 0., 0., 0.); out_file << buf; /** * Write the foreign node number and the respective data. */ std::map<const Node*, std::vector<Number> >::const_iterator nit = _node_data.begin(); for (; nit != _node_data.end(); ++nit) { const Node* node = (*nit).first; unsigned int f_n_id = node_to_foreign_id (node); sprintf(buf, "%10i\n", f_n_id); out_file << buf; std::vector<Number> values; this->operator()(node, values); for (unsigned int v_cnt=0; v_cnt<values.size(); v_cnt++) { #ifdef USE_COMPLEX_NUMBERS sprintf(buf, "%13.5E%13.5E", values[v_cnt].real(), values[v_cnt].imag()); out_file << buf; #else sprintf(buf, "%13.5E", values[v_cnt]); out_file << buf; #endif } out_file << "\n"; } /** * Write end of the dataset. */ out_file << " -1\n"; } <|endoftext|>
<commit_before>/*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include <usModuleContext.h> #include <usGetModuleContext.h> #include <usModuleRegistry.h> #include <usModule.h> #include <usModuleResource.h> #include <usModuleResourceStream.h> #include <usTestingConfig.h> #include "usTestUtilSharedLibrary.h" #include "usTestingMacros.h" #include <assert.h> #include <set> US_USE_NAMESPACE namespace { std::string GetResourceContent(const ModuleResource& resource) { std::string line; ModuleResourceStream rs(resource); std::getline(rs, line); return line; } struct ResourceComparator { bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const { return mr1 < mr2; } }; void testResourceOperators(Module* module) { std::vector<ModuleResource> resources = module->FindResources("", "res.txt", false); US_TEST_CONDITION_REQUIRED(resources.size() == 2, "Check resource count") US_TEST_CONDITION(resources[0] != resources[1], "Check non-equality for equally named resources") } void testResourcesWithStaticImport(Module* module) { ModuleResource resource = module->GetResource("res.txt"); US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid res.txt resource") std::string line = GetResourceContent(resource); US_TEST_CONDITION(line == "dynamic resource", "Check dynamic resource content") resource = module->GetResource("dynamic.txt"); US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid dynamic.txt resource") line = GetResourceContent(resource); US_TEST_CONDITION(line == "dynamic", "Check dynamic resource content") resource = module->GetResource("static.txt"); US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource") line = GetResourceContent(resource); US_TEST_CONDITION(line == "static", "Check dynamic resource content") std::vector<ModuleResource> resources = module->FindResources("", "*.txt", false); std::stable_sort(resources.begin(), resources.end(), ResourceComparator()); #ifdef US_BUILD_SHARED_LIBS US_TEST_CONDITION(resources.size() == 4, "Check imported resource count") line = GetResourceContent(resources[0]); US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content") line = GetResourceContent(resources[1]); US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content") line = GetResourceContent(resources[2]); US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content") line = GetResourceContent(resources[3]); US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content") #else US_TEST_CONDITION(resources.size() == 6, "Check imported resource count") line = GetResourceContent(resources[0]); US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content") // skip foo.txt line = GetResourceContent(resources[2]); US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content") line = GetResourceContent(resources[3]); US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content") // skip special_chars.dummy.txt line = GetResourceContent(resources[5]); US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content") #endif } } // end unnamed namespace int usStaticModuleResourceTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("StaticModuleResourceTest"); ModuleContext* mc = GetModuleContext(); assert(mc); #ifdef US_BUILD_SHARED_LIBS SharedLibraryHandle libB("TestModuleB"); try { libB.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) } Module* module = ModuleRegistry::GetModule("TestModuleB Module"); US_TEST_CONDITION_REQUIRED(module != NULL, "Test for existing module TestModuleB") US_TEST_CONDITION(module->GetName() == "TestModuleB Module", "Test module name") #else Module* module = mc->GetModule(); #endif testResourceOperators(module); testResourcesWithStaticImport(module); #ifdef US_BUILD_SHARED_LIBS ModuleResource resource = module->GetResource("static.txt"); US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource") libB.Unload(); US_TEST_CONDITION_REQUIRED(resource.IsValid() == false, "Check invalid static.txt resource") #endif US_TEST_END() } <commit_msg>Fix unused variable error in release builds.<commit_after>/*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include <usModuleContext.h> #include <usGetModuleContext.h> #include <usModuleRegistry.h> #include <usModule.h> #include <usModuleResource.h> #include <usModuleResourceStream.h> #include <usTestingConfig.h> #include "usTestUtilSharedLibrary.h" #include "usTestingMacros.h" #include <assert.h> #include <set> US_USE_NAMESPACE namespace { std::string GetResourceContent(const ModuleResource& resource) { std::string line; ModuleResourceStream rs(resource); std::getline(rs, line); return line; } struct ResourceComparator { bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const { return mr1 < mr2; } }; void testResourceOperators(Module* module) { std::vector<ModuleResource> resources = module->FindResources("", "res.txt", false); US_TEST_CONDITION_REQUIRED(resources.size() == 2, "Check resource count") US_TEST_CONDITION(resources[0] != resources[1], "Check non-equality for equally named resources") } void testResourcesWithStaticImport(Module* module) { ModuleResource resource = module->GetResource("res.txt"); US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid res.txt resource") std::string line = GetResourceContent(resource); US_TEST_CONDITION(line == "dynamic resource", "Check dynamic resource content") resource = module->GetResource("dynamic.txt"); US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid dynamic.txt resource") line = GetResourceContent(resource); US_TEST_CONDITION(line == "dynamic", "Check dynamic resource content") resource = module->GetResource("static.txt"); US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource") line = GetResourceContent(resource); US_TEST_CONDITION(line == "static", "Check dynamic resource content") std::vector<ModuleResource> resources = module->FindResources("", "*.txt", false); std::stable_sort(resources.begin(), resources.end(), ResourceComparator()); #ifdef US_BUILD_SHARED_LIBS US_TEST_CONDITION(resources.size() == 4, "Check imported resource count") line = GetResourceContent(resources[0]); US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content") line = GetResourceContent(resources[1]); US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content") line = GetResourceContent(resources[2]); US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content") line = GetResourceContent(resources[3]); US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content") #else US_TEST_CONDITION(resources.size() == 6, "Check imported resource count") line = GetResourceContent(resources[0]); US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content") // skip foo.txt line = GetResourceContent(resources[2]); US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content") line = GetResourceContent(resources[3]); US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content") // skip special_chars.dummy.txt line = GetResourceContent(resources[5]); US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content") #endif } } // end unnamed namespace int usStaticModuleResourceTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("StaticModuleResourceTest"); assert(GetModuleContext()); #ifdef US_BUILD_SHARED_LIBS SharedLibraryHandle libB("TestModuleB"); try { libB.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) } Module* module = ModuleRegistry::GetModule("TestModuleB Module"); US_TEST_CONDITION_REQUIRED(module != NULL, "Test for existing module TestModuleB") US_TEST_CONDITION(module->GetName() == "TestModuleB Module", "Test module name") #else Module* module = mc->GetModule(); #endif testResourceOperators(module); testResourcesWithStaticImport(module); #ifdef US_BUILD_SHARED_LIBS ModuleResource resource = module->GetResource("static.txt"); US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource") libB.Unload(); US_TEST_CONDITION_REQUIRED(resource.IsValid() == false, "Check invalid static.txt resource") #endif US_TEST_END() } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <osl/file.h> #include <tools/vcompat.hxx> #include <tools/debug.hxx> #include <unotools/ucbstreamhelper.hxx> #include <unotools/tempfile.hxx> #include <ucbhelper/content.hxx> #include <vcl/graph.hxx> #include <vcl/gfxlink.hxx> #include <vcl/cvtgrf.hxx> #include <com/sun/star/ucb/CommandAbortedException.hpp> GfxLink::GfxLink() : meType ( GFX_LINK_TYPE_NONE ), mpBuf ( NULL ), mpSwap ( NULL ), mnBufSize ( 0 ), mnUserId ( 0UL ), mpImpData ( new ImpGfxLink ) { } GfxLink::GfxLink( const GfxLink& rGfxLink ) : mpImpData( new ImpGfxLink ) { ImplCopy( rGfxLink ); } GfxLink::GfxLink( sal_uInt8* pBuf, sal_uInt32 nSize, GfxLinkType nType, sal_Bool bOwns ) : mpImpData( new ImpGfxLink ) { DBG_ASSERT( (pBuf != NULL && nSize) || (!bOwns && nSize == 0), "GfxLink::GfxLink(): empty/NULL buffer given" ); meType = nType; mnBufSize = nSize; mpSwap = NULL; mnUserId = 0UL; if( bOwns ) mpBuf = new ImpBuffer( pBuf ); else if( nSize ) { mpBuf = new ImpBuffer( nSize ); memcpy( mpBuf->mpBuffer, pBuf, nSize ); } else mpBuf = NULL; } GfxLink::~GfxLink() { if( mpBuf && !( --mpBuf->mnRefCount ) ) delete mpBuf; if( mpSwap && !( --mpSwap->mnRefCount ) ) delete mpSwap; delete mpImpData; } GfxLink& GfxLink::operator=( const GfxLink& rGfxLink ) { if( &rGfxLink != this ) { if ( mpBuf && !( --mpBuf->mnRefCount ) ) delete mpBuf; if( mpSwap && !( --mpSwap->mnRefCount ) ) delete mpSwap; ImplCopy( rGfxLink ); } return *this; } sal_Bool GfxLink::IsEqual( const GfxLink& rGfxLink ) const { sal_Bool bIsEqual = sal_False; if ( ( mnBufSize == rGfxLink.mnBufSize ) && ( meType == rGfxLink.meType ) ) { const sal_uInt8* pSource = GetData(); const sal_uInt8* pDest = rGfxLink.GetData(); sal_uInt32 nSourceSize = GetDataSize(); sal_uInt32 nDestSize = rGfxLink.GetDataSize(); if ( pSource && pDest && ( nSourceSize == nDestSize ) ) { bIsEqual = memcmp( pSource, pDest, nSourceSize ) == 0; } else if ( ( pSource == 0 ) && ( pDest == 0 ) ) bIsEqual = sal_True; } return bIsEqual; } void GfxLink::ImplCopy( const GfxLink& rGfxLink ) { mnBufSize = rGfxLink.mnBufSize; meType = rGfxLink.meType; mpBuf = rGfxLink.mpBuf; mpSwap = rGfxLink.mpSwap; mnUserId = rGfxLink.mnUserId; *mpImpData = *rGfxLink.mpImpData; if( mpBuf ) mpBuf->mnRefCount++; if( mpSwap ) mpSwap->mnRefCount++; } GfxLinkType GfxLink::GetType() const { return meType; } sal_Bool GfxLink::IsNative() const { return( meType >= GFX_LINK_FIRST_NATIVE_ID && meType <= GFX_LINK_LAST_NATIVE_ID ); } sal_uInt32 GfxLink::GetDataSize() const { return mnBufSize; } const sal_uInt8* GfxLink::GetData() const { if( IsSwappedOut() ) ( (GfxLink*) this )->SwapIn(); return( mpBuf ? mpBuf->mpBuffer : NULL ); } const Size& GfxLink::GetPrefSize() const { return mpImpData->maPrefSize; } void GfxLink::SetPrefSize( const Size& rPrefSize ) { mpImpData->maPrefSize = rPrefSize; mpImpData->mbPrefSizeValid = true; } bool GfxLink::IsPrefSizeValid() { return mpImpData->mbPrefSizeValid; } const MapMode& GfxLink::GetPrefMapMode() const { return mpImpData->maPrefMapMode; } void GfxLink::SetPrefMapMode( const MapMode& rPrefMapMode ) { mpImpData->maPrefMapMode = rPrefMapMode; mpImpData->mbPrefMapModeValid = true; } bool GfxLink::IsPrefMapModeValid() { return mpImpData->mbPrefMapModeValid; } sal_Bool GfxLink::LoadNative( Graphic& rGraphic ) { sal_Bool bRet = sal_False; if( IsNative() && mnBufSize ) { const sal_uInt8* pData = GetData(); if( pData ) { SvMemoryStream aMemStm; sal_uLong nCvtType; aMemStm.SetBuffer( (char*) pData, mnBufSize, sal_False, mnBufSize ); switch( meType ) { case( GFX_LINK_TYPE_NATIVE_GIF ): nCvtType = CVT_GIF; break; case( GFX_LINK_TYPE_NATIVE_JPG ): nCvtType = CVT_JPG; break; case( GFX_LINK_TYPE_NATIVE_PNG ): nCvtType = CVT_PNG; break; case( GFX_LINK_TYPE_NATIVE_TIF ): nCvtType = CVT_TIF; break; case( GFX_LINK_TYPE_NATIVE_WMF ): nCvtType = CVT_WMF; break; case( GFX_LINK_TYPE_NATIVE_MET ): nCvtType = CVT_MET; break; case( GFX_LINK_TYPE_NATIVE_PCT ): nCvtType = CVT_PCT; break; case( GFX_LINK_TYPE_NATIVE_SVG ): nCvtType = CVT_SVG; break; default: nCvtType = CVT_UNKNOWN; break; } if( nCvtType && ( GraphicConverter::Import( aMemStm, rGraphic, nCvtType ) == ERRCODE_NONE ) ) bRet = sal_True; } } return bRet; } void GfxLink::SwapOut() { if( !IsSwappedOut() && mpBuf ) { mpSwap = new ImpSwap( mpBuf->mpBuffer, mnBufSize ); if( !mpSwap->IsSwapped() ) { delete mpSwap; mpSwap = NULL; } else { if( !( --mpBuf->mnRefCount ) ) delete mpBuf; mpBuf = NULL; } } } void GfxLink::SwapIn() { if( IsSwappedOut() ) { mpBuf = new ImpBuffer( mpSwap->GetData() ); if( !( --mpSwap->mnRefCount ) ) delete mpSwap; mpSwap = NULL; } } sal_Bool GfxLink::ExportNative( SvStream& rOStream ) const { if( GetDataSize() ) { if( IsSwappedOut() ) mpSwap->WriteTo( rOStream ); else if( GetData() ) rOStream.Write( GetData(), GetDataSize() ); } return ( rOStream.GetError() == ERRCODE_NONE ); } SvStream& operator<<( SvStream& rOStream, const GfxLink& rGfxLink ) { VersionCompat* pCompat = new VersionCompat( rOStream, STREAM_WRITE, 2 ); // Version 1 rOStream << (sal_uInt16) rGfxLink.GetType() << rGfxLink.GetDataSize() << rGfxLink.GetUserId(); // Version 2 rOStream << rGfxLink.GetPrefSize() << rGfxLink.GetPrefMapMode(); delete pCompat; if( rGfxLink.GetDataSize() ) { if( rGfxLink.IsSwappedOut() ) rGfxLink.mpSwap->WriteTo( rOStream ); else if( rGfxLink.GetData() ) rOStream.Write( rGfxLink.GetData(), rGfxLink.GetDataSize() ); } return rOStream; } SvStream& operator>>( SvStream& rIStream, GfxLink& rGfxLink) { Size aSize; MapMode aMapMode; sal_uInt32 nSize; sal_uInt32 nUserId; sal_uInt16 nType; sal_uInt8* pBuf; bool bMapAndSizeValid( false ); VersionCompat* pCompat = new VersionCompat( rIStream, STREAM_READ ); // Version 1 rIStream >> nType >> nSize >> nUserId; if( pCompat->GetVersion() >= 2 ) { rIStream >> aSize >> aMapMode; bMapAndSizeValid = true; } delete pCompat; pBuf = new sal_uInt8[ nSize ]; rIStream.Read( pBuf, nSize ); rGfxLink = GfxLink( pBuf, nSize, (GfxLinkType) nType, sal_True ); rGfxLink.SetUserId( nUserId ); if( bMapAndSizeValid ) { rGfxLink.SetPrefSize( aSize ); rGfxLink.SetPrefMapMode( aMapMode ); } return rIStream; } ImpSwap::ImpSwap( sal_uInt8* pData, sal_uLong nDataSize ) : mnDataSize( nDataSize ), mnRefCount( 1UL ) { if( pData && mnDataSize ) { ::utl::TempFile aTempFile; maURL = aTempFile.GetURL(); if( !maURL.isEmpty() ) { SvStream* pOStm = ::utl::UcbStreamHelper::CreateStream( maURL, STREAM_READWRITE | STREAM_SHARE_DENYWRITE ); if( pOStm ) { pOStm->Write( pData, mnDataSize ); sal_Bool bError = ( ERRCODE_NONE != pOStm->GetError() ); delete pOStm; if( bError ) { osl_removeFile( maURL.pData ); maURL = String(); } } } } } ImpSwap::~ImpSwap() { if( IsSwapped() ) osl_removeFile( maURL.pData ); } sal_uInt8* ImpSwap::GetData() const { sal_uInt8* pData; if( IsSwapped() ) { SvStream* pIStm = ::utl::UcbStreamHelper::CreateStream( maURL, STREAM_READWRITE ); if( pIStm ) { pData = new sal_uInt8[ mnDataSize ]; pIStm->Read( pData, mnDataSize ); sal_Bool bError = ( ERRCODE_NONE != pIStm->GetError() ); delete pIStm; if( bError ) delete[] pData, pData = NULL; } else pData = NULL; } else pData = NULL; return pData; } void ImpSwap::WriteTo( SvStream& rOStm ) const { sal_uInt8* pData = GetData(); if( pData ) { rOStm.Write( pData, mnDataSize ); delete[] pData; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Resolves: #i119965# Fixed saving slides where temporary files...<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <osl/file.h> #include <tools/vcompat.hxx> #include <tools/debug.hxx> #include <unotools/ucbstreamhelper.hxx> #include <unotools/tempfile.hxx> #include <ucbhelper/content.hxx> #include <vcl/graph.hxx> #include <vcl/gfxlink.hxx> #include <vcl/cvtgrf.hxx> #include <com/sun/star/ucb/CommandAbortedException.hpp> GfxLink::GfxLink() : meType ( GFX_LINK_TYPE_NONE ), mpBuf ( NULL ), mpSwap ( NULL ), mnBufSize ( 0 ), mnUserId ( 0UL ), mpImpData ( new ImpGfxLink ) { } GfxLink::GfxLink( const GfxLink& rGfxLink ) : mpImpData( new ImpGfxLink ) { ImplCopy( rGfxLink ); } GfxLink::GfxLink( sal_uInt8* pBuf, sal_uInt32 nSize, GfxLinkType nType, sal_Bool bOwns ) : mpImpData( new ImpGfxLink ) { DBG_ASSERT( (pBuf != NULL && nSize) || (!bOwns && nSize == 0), "GfxLink::GfxLink(): empty/NULL buffer given" ); meType = nType; mnBufSize = nSize; mpSwap = NULL; mnUserId = 0UL; if( bOwns ) mpBuf = new ImpBuffer( pBuf ); else if( nSize ) { mpBuf = new ImpBuffer( nSize ); memcpy( mpBuf->mpBuffer, pBuf, nSize ); } else mpBuf = NULL; } GfxLink::~GfxLink() { if( mpBuf && !( --mpBuf->mnRefCount ) ) delete mpBuf; if( mpSwap && !( --mpSwap->mnRefCount ) ) delete mpSwap; delete mpImpData; } GfxLink& GfxLink::operator=( const GfxLink& rGfxLink ) { if( &rGfxLink != this ) { if ( mpBuf && !( --mpBuf->mnRefCount ) ) delete mpBuf; if( mpSwap && !( --mpSwap->mnRefCount ) ) delete mpSwap; ImplCopy( rGfxLink ); } return *this; } sal_Bool GfxLink::IsEqual( const GfxLink& rGfxLink ) const { sal_Bool bIsEqual = sal_False; if ( ( mnBufSize == rGfxLink.mnBufSize ) && ( meType == rGfxLink.meType ) ) { const sal_uInt8* pSource = GetData(); const sal_uInt8* pDest = rGfxLink.GetData(); sal_uInt32 nSourceSize = GetDataSize(); sal_uInt32 nDestSize = rGfxLink.GetDataSize(); if ( pSource && pDest && ( nSourceSize == nDestSize ) ) { bIsEqual = memcmp( pSource, pDest, nSourceSize ) == 0; } else if ( ( pSource == 0 ) && ( pDest == 0 ) ) bIsEqual = sal_True; } return bIsEqual; } void GfxLink::ImplCopy( const GfxLink& rGfxLink ) { mnBufSize = rGfxLink.mnBufSize; meType = rGfxLink.meType; mpBuf = rGfxLink.mpBuf; mpSwap = rGfxLink.mpSwap; mnUserId = rGfxLink.mnUserId; *mpImpData = *rGfxLink.mpImpData; if( mpBuf ) mpBuf->mnRefCount++; if( mpSwap ) mpSwap->mnRefCount++; } GfxLinkType GfxLink::GetType() const { return meType; } sal_Bool GfxLink::IsNative() const { return( meType >= GFX_LINK_FIRST_NATIVE_ID && meType <= GFX_LINK_LAST_NATIVE_ID ); } sal_uInt32 GfxLink::GetDataSize() const { return mnBufSize; } const sal_uInt8* GfxLink::GetData() const { if( IsSwappedOut() ) ( (GfxLink*) this )->SwapIn(); return( mpBuf ? mpBuf->mpBuffer : NULL ); } const Size& GfxLink::GetPrefSize() const { return mpImpData->maPrefSize; } void GfxLink::SetPrefSize( const Size& rPrefSize ) { mpImpData->maPrefSize = rPrefSize; mpImpData->mbPrefSizeValid = true; } bool GfxLink::IsPrefSizeValid() { return mpImpData->mbPrefSizeValid; } const MapMode& GfxLink::GetPrefMapMode() const { return mpImpData->maPrefMapMode; } void GfxLink::SetPrefMapMode( const MapMode& rPrefMapMode ) { mpImpData->maPrefMapMode = rPrefMapMode; mpImpData->mbPrefMapModeValid = true; } bool GfxLink::IsPrefMapModeValid() { return mpImpData->mbPrefMapModeValid; } sal_Bool GfxLink::LoadNative( Graphic& rGraphic ) { sal_Bool bRet = sal_False; if( IsNative() && mnBufSize ) { const sal_uInt8* pData = GetData(); if( pData ) { SvMemoryStream aMemStm; sal_uLong nCvtType; aMemStm.SetBuffer( (char*) pData, mnBufSize, sal_False, mnBufSize ); switch( meType ) { case( GFX_LINK_TYPE_NATIVE_GIF ): nCvtType = CVT_GIF; break; case( GFX_LINK_TYPE_NATIVE_JPG ): nCvtType = CVT_JPG; break; case( GFX_LINK_TYPE_NATIVE_PNG ): nCvtType = CVT_PNG; break; case( GFX_LINK_TYPE_NATIVE_TIF ): nCvtType = CVT_TIF; break; case( GFX_LINK_TYPE_NATIVE_WMF ): nCvtType = CVT_WMF; break; case( GFX_LINK_TYPE_NATIVE_MET ): nCvtType = CVT_MET; break; case( GFX_LINK_TYPE_NATIVE_PCT ): nCvtType = CVT_PCT; break; case( GFX_LINK_TYPE_NATIVE_SVG ): nCvtType = CVT_SVG; break; default: nCvtType = CVT_UNKNOWN; break; } if( nCvtType && ( GraphicConverter::Import( aMemStm, rGraphic, nCvtType ) == ERRCODE_NONE ) ) bRet = sal_True; } } return bRet; } void GfxLink::SwapOut() { if( !IsSwappedOut() && mpBuf ) { mpSwap = new ImpSwap( mpBuf->mpBuffer, mnBufSize ); if( !mpSwap->IsSwapped() ) { delete mpSwap; mpSwap = NULL; } else { if( !( --mpBuf->mnRefCount ) ) delete mpBuf; mpBuf = NULL; } } } void GfxLink::SwapIn() { if( IsSwappedOut() ) { mpBuf = new ImpBuffer( mpSwap->GetData() ); if( !( --mpSwap->mnRefCount ) ) delete mpSwap; mpSwap = NULL; } } sal_Bool GfxLink::ExportNative( SvStream& rOStream ) const { if( GetDataSize() ) { if( IsSwappedOut() ) mpSwap->WriteTo( rOStream ); else if( GetData() ) rOStream.Write( GetData(), GetDataSize() ); } return ( rOStream.GetError() == ERRCODE_NONE ); } SvStream& operator<<( SvStream& rOStream, const GfxLink& rGfxLink ) { VersionCompat* pCompat = new VersionCompat( rOStream, STREAM_WRITE, 2 ); // Version 1 rOStream << (sal_uInt16) rGfxLink.GetType() << rGfxLink.GetDataSize() << rGfxLink.GetUserId(); // Version 2 rOStream << rGfxLink.GetPrefSize() << rGfxLink.GetPrefMapMode(); delete pCompat; if( rGfxLink.GetDataSize() ) { if( rGfxLink.IsSwappedOut() ) rGfxLink.mpSwap->WriteTo( rOStream ); else if( rGfxLink.GetData() ) rOStream.Write( rGfxLink.GetData(), rGfxLink.GetDataSize() ); } return rOStream; } SvStream& operator>>( SvStream& rIStream, GfxLink& rGfxLink) { Size aSize; MapMode aMapMode; sal_uInt32 nSize; sal_uInt32 nUserId; sal_uInt16 nType; sal_uInt8* pBuf; bool bMapAndSizeValid( false ); VersionCompat* pCompat = new VersionCompat( rIStream, STREAM_READ ); // Version 1 rIStream >> nType >> nSize >> nUserId; if( pCompat->GetVersion() >= 2 ) { rIStream >> aSize >> aMapMode; bMapAndSizeValid = true; } delete pCompat; pBuf = new sal_uInt8[ nSize ]; rIStream.Read( pBuf, nSize ); rGfxLink = GfxLink( pBuf, nSize, (GfxLinkType) nType, sal_True ); rGfxLink.SetUserId( nUserId ); if( bMapAndSizeValid ) { rGfxLink.SetPrefSize( aSize ); rGfxLink.SetPrefMapMode( aMapMode ); } return rIStream; } ImpSwap::ImpSwap( sal_uInt8* pData, sal_uLong nDataSize ) : mnDataSize( nDataSize ), mnRefCount( 1UL ) { if( pData && mnDataSize ) { ::utl::TempFile aTempFile; maURL = aTempFile.GetURL(); if( !maURL.isEmpty() ) { SvStream* pOStm = ::utl::UcbStreamHelper::CreateStream( maURL, STREAM_READWRITE | STREAM_SHARE_DENYWRITE ); if( pOStm ) { pOStm->Write( pData, mnDataSize ); sal_Bool bError = ( ERRCODE_NONE != pOStm->GetError() ); delete pOStm; if( bError ) { osl_removeFile( maURL.pData ); maURL = String(); } } } } } ImpSwap::~ImpSwap() { if( IsSwapped() ) osl_removeFile( maURL.pData ); } sal_uInt8* ImpSwap::GetData() const { sal_uInt8* pData; if( IsSwapped() ) { SvStream* pIStm = ::utl::UcbStreamHelper::CreateStream( maURL, STREAM_READWRITE ); if( pIStm ) { pData = new sal_uInt8[ mnDataSize ]; pIStm->Read( pData, mnDataSize ); sal_Bool bError = ( ERRCODE_NONE != pIStm->GetError() ); sal_Size nActReadSize = pIStm->Tell(); if (nActReadSize != mnDataSize) { bError = sal_True; } delete pIStm; if( bError ) delete[] pData, pData = NULL; } else pData = NULL; } else pData = NULL; return pData; } void ImpSwap::WriteTo( SvStream& rOStm ) const { sal_uInt8* pData = GetData(); if( pData ) { rOStm.Write( pData, mnDataSize ); delete[] pData; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// The following two definitions are required by llvm/Support/DataTypes.h #define __STDC_LIMIT_MACROS 1 #define __STDC_CONSTANT_MACROS 1 #include "llvm/Support/CommandLine.h" #include "ofpx.h" #include "ofp/yaml/decoder.h" #include "ofp/yaml/encoder.h" #include <iostream> #include <fstream> //-------------------------------------// // d e c o d e _ o n e _ m e s s a g e // //-------------------------------------// static int decode_one_message(const ofp::Message *message) { ofp::yaml::Decoder decoder{message}; if (!decoder.error().empty()) { std::cerr << "Error: Decode failed: " << decoder.error() << '\n'; return 128; } std::cout << decoder.result(); // Now double-check the result by re-encoding the message. We should obtain // the original message contents. ofp::yaml::Encoder encoder{decoder.result()}; if (!encoder.error().empty()) { std::cerr << "Error: Decode succeeded but encode failed: " << encoder.error() << '\n'; return 129; } if (encoder.size() != message->size()) { std::cerr << "Error: Encode yielded different size data: " << encoder.size() << " vs. " << message->size() << '\n' << ofp::RawDataToHex(encoder.data(), encoder.size()) << '\n'; return 130; } if (std::memcmp(message->data(), encoder.data(), encoder.size()) != 0) { std::cerr << "Error: Encode yielded different data:\n" << ofp::RawDataToHex(encoder.data(), encoder.size()) << '\n' << ofp::RawDataToHex(message->data(), message->size()) << '\n'; //return 131; } return 0; } //-------------------------------// // d e c o d e _ m e s s a g e s // //-------------------------------// static int decode_messages(std::ifstream &input) { ofp::Message message{nullptr}; while (input) { char *msg = (char *)message.mutableData(sizeof(ofp::Header)); input.read(msg, sizeof(ofp::Header)); if (input) { // Read the rest of the message. size_t msgLen = message.header()->length(); if (msgLen < sizeof(ofp::Header)) { std::cerr << "Error: Message length " << msgLen << " bytes is too short." << '\n'; return 2; } msg = (char *)message.mutableData(msgLen); input.read(msg + sizeof(ofp::Header), ofp::Signed_cast(msgLen - sizeof(ofp::Header))); if (input) { message.transmogrify(); int result = decode_one_message(&message); if (result) { return result; } } else if (!input.eof()) { // There was an error reading the message body. std::cerr << "Error: Only " << input.gcount() << " bytes read of body." << '\n' << input.rdstate(); return 1; } } else if (!input.eof()) { // There was an error reading the message header. std::cerr << "Error: Only " << input.gcount() << " bytes read of header." << '\n' << input.rdstate(); return 1; } } return 0; } //-----------------------// // d e c o d e _ f i l e // //-----------------------// static int decode_file(const std::string &filename) { std::ifstream input{filename, std::ifstream::binary}; int result = -1; if (input) { result = decode_messages(input); input.close(); } else { std::cerr << "Error: opening file " << filename << '\n'; } return result; } //-------------------------// // d e c o d e _ f i l e s // //-------------------------// static int decode_files(const std::vector<std::string> &files) { for (const std::string &filename : files) { int result = decode_file(filename); if (result) { return result; } } return 0; } //-------------------// // o f p x _ p i n g // //-------------------// int ofpx_decode(int argc, char **argv) { using namespace llvm; cl::list<std::string> inputFiles(cl::Positional, cl::desc("<Input files>"), cl::OneOrMore); cl::ParseCommandLineOptions(argc, argv); return decode_files(inputFiles); } <commit_msg>Changes to error reporting in ofpx_decode.<commit_after>// The following two definitions are required by llvm/Support/DataTypes.h #define __STDC_LIMIT_MACROS 1 #define __STDC_CONSTANT_MACROS 1 #include "llvm/Support/CommandLine.h" #include "ofpx.h" #include "ofp/yaml/decoder.h" #include "ofp/yaml/encoder.h" #include <iostream> #include <fstream> //-------------------------------------// // d e c o d e _ o n e _ m e s s a g e // //-------------------------------------// static int decode_one_message(const ofp::Message *message) { ofp::yaml::Decoder decoder{message}; if (!decoder.error().empty()) { std::cerr << "Error: Decode failed: " << decoder.error() << '\n'; return 128; } std::cout << decoder.result(); // Now double-check the result by re-encoding the message. We should obtain // the original message contents. ofp::yaml::Encoder encoder{decoder.result()}; if (!encoder.error().empty()) { std::cerr << "Error: Decode succeeded but encode failed: " << encoder.error() << '\n'; //return 129; } if (encoder.size() != message->size()) { std::cerr << "Error: Encode yielded different size data: " << encoder.size() << " vs. " << message->size() << '\n' << ofp::RawDataToHex(encoder.data(), encoder.size()) << '\n' << ofp::RawDataToHex(message->data(), message->size()) << '\n'; //return 130; } else if (std::memcmp(message->data(), encoder.data(), encoder.size()) != 0) { std::cerr << "Error: Encode yielded different data:\n" << ofp::RawDataToHex(encoder.data(), encoder.size()) << '\n' << ofp::RawDataToHex(message->data(), message->size()) << '\n'; //return 131; } return 0; } //-------------------------------// // d e c o d e _ m e s s a g e s // //-------------------------------// static int decode_messages(std::ifstream &input) { ofp::Message message{nullptr}; while (input) { char *msg = (char *)message.mutableData(sizeof(ofp::Header)); input.read(msg, sizeof(ofp::Header)); if (input) { // Read the rest of the message. size_t msgLen = message.header()->length(); if (msgLen < sizeof(ofp::Header)) { std::cerr << "Error: Message length " << msgLen << " bytes is too short." << '\n'; return 2; } msg = (char *)message.mutableData(msgLen); input.read(msg + sizeof(ofp::Header), ofp::Signed_cast(msgLen - sizeof(ofp::Header))); if (input) { message.transmogrify(); int result = decode_one_message(&message); if (result) { return result; } } else if (!input.eof()) { // There was an error reading the message body. std::cerr << "Error: Only " << input.gcount() << " bytes read of body." << '\n' << input.rdstate(); return 1; } } else if (!input.eof()) { // There was an error reading the message header. std::cerr << "Error: Only " << input.gcount() << " bytes read of header." << '\n' << input.rdstate(); return 1; } } return 0; } //-----------------------// // d e c o d e _ f i l e // //-----------------------// static int decode_file(const std::string &filename) { std::ifstream input{filename, std::ifstream::binary}; int result = -1; if (input) { result = decode_messages(input); input.close(); } else { std::cerr << "Error: opening file " << filename << '\n'; } return result; } //-------------------------// // d e c o d e _ f i l e s // //-------------------------// static int decode_files(const std::vector<std::string> &files) { for (const std::string &filename : files) { int result = decode_file(filename); if (result) { return result; } } return 0; } //-------------------// // o f p x _ p i n g // //-------------------// int ofpx_decode(int argc, char **argv) { using namespace llvm; cl::list<std::string> inputFiles(cl::Positional, cl::desc("<Input files>"), cl::OneOrMore); cl::ParseCommandLineOptions(argc, argv); return decode_files(inputFiles); } <|endoftext|>
<commit_before>/* * katch/examples/run_tch_ea_query.cpp * * * This file is part of * * KaTCH -- Karlsruhe Time-Dependent Contraction Hierarchies * * Copyright (C) 2015 * * Institut fuer Theroretische Informatik, * Karlsruher Institut fuer Technology (KIT), * 76131 Karlsruhe, Germany * * Author: Gernot Veit Batz * * * * KaTCH is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * KaTCH is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public * License along with Contraction Hierarchies; see the file COPYING; * if not, see <http://www.gnu.org/licenses/>. * */ #include <iostream> #include <stdlib.h> #include <string> #include "util/misc.h" #include "io/btch_format.h" #include "io/demands_format.h" #include "io/edge_info.h" #include "io/tch_format.h" #include "query/tch_ea_query.h" int main(int argc, char** argv) { using Graph = katch::TchEaQuery::Graph; using EdgeInfo = katch::EdgeInfo<Graph::TTF>; const char* binary_name = argv[0]; if ( argc != 3 ) { std::cerr << std::endl << "USAGE: " << binary_name << " <.btch input file> <.demands input file>" << std::endl << std::endl; return EXIT_FAILURE; } const std::string btch_input_file_name(argv[1]); const std::string demands_input_file_name(argv[2]); std::vector<EdgeInfo> edge_list = katch::btch_format::read_edges<EdgeInfo>(btch_input_file_name); Graph graph(std::move(edge_list)); KATCH_STATUS("Graph has " << graph.get_n_nodes() << " nodes, " << graph.get_n_edges() << " edges.\n"); std::vector<katch::demands_format::Demand> demands = katch::demands_format::read(demands_input_file_name); katch::TchEaQuery query(std::move(graph)); KATCH_STATUS("Running " << demands.size() << " queries..."); double max_abs_error = 0.0; double max_rel_error = 0.0; double total_abs_error = 0.0; double total_rel_error = 0.0; double max_abs_error_expand = 0.0; double max_rel_error_expand = 0.0; double total_abs_error_expand = 0.0; double total_rel_error_expand = 0.0; double total_route_extraction_and_expansion_time = 0.0; auto t1 = katch::util::time_stamp(); for ( const auto& demand : demands ) { // obtain travel time from start to destination const double t_arr = query.one_to_one(demand._start, demand._destination, demand._t_dep); // compute absolute and relative errors of obtained travel time const double abs_error = fabs(t_arr - demand._t_arr); max_abs_error = std::max(max_abs_error, abs_error); total_abs_error += abs_error; const double rel_error = abs_error / demand._t_arr; max_rel_error = std::max(max_rel_error, rel_error); total_rel_error += rel_error; auto t_expand_begin = katch::util::time_stamp(); // obtain up-down-path from start to destination (requires katch::TchEaQuery::one_to_one called first) const katch::TchEaQuery::Path up_down_path = query.get_up_down_path(demand._destination); // expand up-down-path to obtain path in the original road network const katch::TchEaQuery::Path original_path = query.expand_path(up_down_path); auto t_expand_end = katch::util::time_stamp(); total_route_extraction_and_expansion_time += katch::util::get_duration_in_seconds(t_expand_begin, t_expand_end); // compute absolute and relative errors of the travel time of the expanded path const double t_arr_expand = original_path.get_t_arr(original_path.get_n_edges()); const double abs_error_expand = fabs(t_arr_expand - demand._t_arr); max_abs_error_expand = std::max(max_abs_error_expand, abs_error_expand); total_abs_error_expand += abs_error_expand; const double rel_error_expand = abs_error_expand / demand._t_arr; max_rel_error_expand = std::max(max_rel_error_expand, rel_error_expand); total_rel_error_expand += rel_error_expand; } auto t2 = katch::util::time_stamp(); KATCH_CONTINUE_STATUS(" OK\n"); KATCH_STATUS("avg. running time (including route extraction) = " << ((katch::util::get_duration_in_seconds(t1, t2) / double(demands.size())) *1000.0) << " msec\n"); KATCH_STATUS("avg. running time (without route extraction) = " << (((katch::util::get_duration_in_seconds(t1, t2) - total_route_extraction_and_expansion_time) / double(demands.size())) *1000.0) << " msec\n"); KATCH_STATUS("\n"); KATCH_STATUS("Error of computed arrival time\n"); KATCH_STATUS("------------------------------\n"); KATCH_STATUS("max. rel. error = " << (max_rel_error * 100.0) << " %\n"); KATCH_STATUS("avg. rel. error = " << ((total_rel_error / double(demands.size())) * 100.0) << " %\n"); KATCH_STATUS("\n"); KATCH_STATUS("Error of arrival time of expanded route\n"); KATCH_STATUS("---------------------------------------\n"); KATCH_STATUS("max. rel. error = " << (max_rel_error_expand * 100.0) << " %\n"); KATCH_STATUS("avg. rel. error = " << ((total_rel_error_expand / double(demands.size())) * 100.0) << " %\n"); // KATCH_STATUS("avg. running time = " << ((katch::util::get_duration_in_seconds(t1, t2) / double(demands.size())) *1000.0) << " msec\n"); return EXIT_SUCCESS; } <commit_msg>removed blind include<commit_after>/* * katch/examples/run_tch_ea_query.cpp * * * This file is part of * * KaTCH -- Karlsruhe Time-Dependent Contraction Hierarchies * * Copyright (C) 2015 * * Institut fuer Theroretische Informatik, * Karlsruher Institut fuer Technology (KIT), * 76131 Karlsruhe, Germany * * Author: Gernot Veit Batz * * * * KaTCH is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * KaTCH is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public * License along with Contraction Hierarchies; see the file COPYING; * if not, see <http://www.gnu.org/licenses/>. * */ #include <iostream> #include <stdlib.h> #include <string> #include "util/misc.h" #include "io/btch_format.h" #include "io/demands_format.h" #include "io/edge_info.h" #include "query/tch_ea_query.h" int main(int argc, char** argv) { using Graph = katch::TchEaQuery::Graph; using EdgeInfo = katch::EdgeInfo<Graph::TTF>; const char* binary_name = argv[0]; if ( argc != 3 ) { std::cerr << std::endl << "USAGE: " << binary_name << " <.btch input file> <.demands input file>" << std::endl << std::endl; return EXIT_FAILURE; } const std::string btch_input_file_name(argv[1]); const std::string demands_input_file_name(argv[2]); std::vector<EdgeInfo> edge_list = katch::btch_format::read_edges<EdgeInfo>(btch_input_file_name); Graph graph(std::move(edge_list)); KATCH_STATUS("Graph has " << graph.get_n_nodes() << " nodes, " << graph.get_n_edges() << " edges.\n"); std::vector<katch::demands_format::Demand> demands = katch::demands_format::read(demands_input_file_name); katch::TchEaQuery query(std::move(graph)); KATCH_STATUS("Running " << demands.size() << " queries..."); double max_abs_error = 0.0; double max_rel_error = 0.0; double total_abs_error = 0.0; double total_rel_error = 0.0; double max_abs_error_expand = 0.0; double max_rel_error_expand = 0.0; double total_abs_error_expand = 0.0; double total_rel_error_expand = 0.0; double total_route_extraction_and_expansion_time = 0.0; auto t1 = katch::util::time_stamp(); for ( const auto& demand : demands ) { // obtain travel time from start to destination const double t_arr = query.one_to_one(demand._start, demand._destination, demand._t_dep); // compute absolute and relative errors of obtained travel time const double abs_error = fabs(t_arr - demand._t_arr); max_abs_error = std::max(max_abs_error, abs_error); total_abs_error += abs_error; const double rel_error = abs_error / demand._t_arr; max_rel_error = std::max(max_rel_error, rel_error); total_rel_error += rel_error; auto t_expand_begin = katch::util::time_stamp(); // obtain up-down-path from start to destination (requires katch::TchEaQuery::one_to_one called first) const katch::TchEaQuery::Path up_down_path = query.get_up_down_path(demand._destination); // expand up-down-path to obtain path in the original road network const katch::TchEaQuery::Path original_path = query.expand_path(up_down_path); auto t_expand_end = katch::util::time_stamp(); total_route_extraction_and_expansion_time += katch::util::get_duration_in_seconds(t_expand_begin, t_expand_end); // compute absolute and relative errors of the travel time of the expanded path const double t_arr_expand = original_path.get_t_arr(original_path.get_n_edges()); const double abs_error_expand = fabs(t_arr_expand - demand._t_arr); max_abs_error_expand = std::max(max_abs_error_expand, abs_error_expand); total_abs_error_expand += abs_error_expand; const double rel_error_expand = abs_error_expand / demand._t_arr; max_rel_error_expand = std::max(max_rel_error_expand, rel_error_expand); total_rel_error_expand += rel_error_expand; } auto t2 = katch::util::time_stamp(); KATCH_CONTINUE_STATUS(" OK\n"); KATCH_STATUS("avg. running time (including route extraction) = " << ((katch::util::get_duration_in_seconds(t1, t2) / double(demands.size())) *1000.0) << " msec\n"); KATCH_STATUS("avg. running time (without route extraction) = " << (((katch::util::get_duration_in_seconds(t1, t2) - total_route_extraction_and_expansion_time) / double(demands.size())) *1000.0) << " msec\n"); KATCH_STATUS("\n"); KATCH_STATUS("Error of computed arrival time\n"); KATCH_STATUS("------------------------------\n"); KATCH_STATUS("max. rel. error = " << (max_rel_error * 100.0) << " %\n"); KATCH_STATUS("avg. rel. error = " << ((total_rel_error / double(demands.size())) * 100.0) << " %\n"); KATCH_STATUS("\n"); KATCH_STATUS("Error of arrival time of expanded route\n"); KATCH_STATUS("---------------------------------------\n"); KATCH_STATUS("max. rel. error = " << (max_rel_error_expand * 100.0) << " %\n"); KATCH_STATUS("avg. rel. error = " << ((total_rel_error_expand / double(demands.size())) * 100.0) << " %\n"); // KATCH_STATUS("avg. running time = " << ((katch::util::get_duration_in_seconds(t1, t2) / double(demands.size())) *1000.0) << " msec\n"); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <algorithm> #include <set> #include <list> #include <iterator> #include "otc/otcli.h" #include "otc/tree_operations.h" #include "otc/tree_iter.h" using namespace otc; using std::vector; using std::unique_ptr; using std::set; using std::list; using std::map; using std::string; using namespace otc; typedef TreeMappedWithSplits Tree_t; template <typename T> std::ostream& operator<<(std::ostream& o, const std::set<T>& s) { auto it = s.begin(); o<<*it++; for(; it != s.end(); it++) o<<" "<<*it; return o; } template <typename T> std::ostream& operator<<(std::ostream& o, const std::list<T>& s) { auto it = s.begin(); o<<*it++; for(; it != s.end(); it++) o<<" "<<*it; return o; } struct RSplit { set<long> in; set<long> out; set<long> all; RSplit() = default; RSplit(const set<long>& i, const set<long>& a) :in(i),all(a) { out = set_difference_as_set(all,in); assert(in.size() + out.size() == all.size()); } }; std::ostream& operator<<(std::ostream& o, const RSplit& s) { o<<s.in<<" | "<<s.out; return o; } /// Merge components c1 and c2 and return the component name that survived long merge_components(long c1, long c2, map<long,long>& component, map<long,list<long>>& elements) { if (elements[c2].size() > elements[c1].size()) std::swap(c1,c2); for(long i:elements[c2]) component[i] = c1; elements[c1].splice(elements[c1].begin(), elements[c2]); return c1; } bool empty_intersection(const set<long>& x, const set<long>& y) { std::set<long>::const_iterator i = x.begin(); std::set<long>::const_iterator j = y.begin(); while (i != x.end() && j != y.end()) { if (*i == *j) return false; else if (*i < *j) ++i; else ++j; } return true; } /// Construct a tree with all the splits mentioned, and return a null pointer if this is not possible unique_ptr<Tree_t> BUILD(const std::set<long>& tips, const vector<RSplit>& splits) { std::unique_ptr<Tree_t> tree(new Tree_t()); tree->createRoot(); // 1. First handle trees of size 1 and 2 if (tips.size() == 1) { tree->getRoot()->setOttId(*tips.begin()); return tree; } else if (tips.size() == 2) { auto Node1a = tree->createChild(tree->getRoot()); auto Node1b = tree->createChild(tree->getRoot()); auto it = tips.begin(); Node1a->setOttId(*it++); Node1b->setOttId(*it++); return tree; } // 2. Initialize the mapping from elements to components map<long,long> component; // element -> component map<long,list<long>> elements; // component -> elements for(long i: tips) { component[i] = i; elements[i].push_back(i); } // 3. For each split, all the leaves in the include group must be in the same component for(const auto& split: splits) { long c1 = -1; for(long i: split.in) { long c2 = component[i]; if (c1 != -1 and c1 != c2) merge_components(c1,c2,component,elements); c1 = component[i]; } } // 4. If we can't subdivide the leaves in any way, then the splits are not consistent, so return failure long first = *tips.begin(); if (elements[component[first]].size() == tips.size()) return {}; // 5. Create the set of tips in each connected component map<long,set<long>> subtips; for(long c: tips) { if (c != component[c]) continue; set<long>& s = subtips[c]; for(long l: elements[c]) s.insert(l); } // 6. Determine the splits that are not satisfied yet and go into each component map<long,vector<RSplit>> subsplits; for(const auto& split: splits) { long first = *split.in.begin(); long c = component[first]; // if none of the exclude group are in the component, then the split is satisfied by the top-level partition. if (empty_intersection(split.out, subtips[c])) continue; subsplits[c].push_back(split); } // 7. Recursively solve the sub-problems of the partition components for(const auto& x: subtips) { auto subtree = BUILD(x.second, subsplits[x.first]); if (not subtree) return {}; tree->addSubtree(tree->getRoot(), *subtree); } return tree; } /// Run the BUILD algorithm on the first n splits unique_ptr<Tree_t> BUILD(const std::set<long>& tips, const vector<RSplit>& splits, int n) { vector<RSplit> splits2; for(int i=0;i<n;i++) splits2.push_back(splits[i]); return BUILD(tips,splits2); } /// Copy node names from taxonomy to tree based on ott ids, and copy the root name also void add_names(unique_ptr<Tree_t>& tree, const unique_ptr<Tree_t>& taxonomy) { clearAndfillDesIdSets(*tree); for(auto n1: iter_post(*tree)) for(auto n2: iter_post(*taxonomy)) if (n1->getData().desIds == n2->getData().desIds) n1->setName( n2->getName()); } /// Get the list of splits, and add them one at a time if they are consistent with previous splits unique_ptr<Tree_t> combine(const vector<unique_ptr<Tree_t>>& trees) { // Standardize names to 0..n-1 for this subproblem const auto& taxonomy = trees.back(); auto all_leaves = taxonomy->getRoot()->getData().desIds; // 1. Find splits in order of input trees vector<RSplit> splits; for(const auto& tree: trees) { auto root = tree->getRoot(); const auto leafTaxa = root->getData().desIds; for(const auto& leaf: set_difference_as_set(leafTaxa, all_leaves)) throw OTCError()<<"OTT Id "<<leaf<<" not in taxonomy!"; for(auto nd: iter_post_const(*tree)) { const auto& descendants = nd->getData().desIds; RSplit split{descendants, leafTaxa}; if (split.in.size()>1 and split.out.size()) splits.push_back(split); } } // 2. Add splits sequentially if they are consistent with previous splits. vector<RSplit> consistent; for(const auto& split: splits) { consistent.push_back(split); auto result = BUILD(all_leaves, consistent); if (not result) { consistent.pop_back(); LOG(DEBUG)<<"Reject: "<<split<<"\n"; } else LOG(DEBUG)<<"Keep: "<<split<<"\n"; } // 3. Construct final tree and add names auto tree = BUILD(all_leaves, consistent); add_names(tree, taxonomy); return tree; } bool handleRequireOttIds(OTCLI & otCLI, const std::string & arg) { if (arg == "true" or arg == "yes" or arg == "True" or arg == "Yes") otCLI.getParsingRules().requireOttIds = true; else if (arg == "false" or arg == "no" or arg == "False" or arg == "no") otCLI.getParsingRules().requireOttIds = false; else return false; return true; } bool handlePruneUnrecognizedTips(OTCLI & otCLI, const std::string & arg) { if (arg == "true" or arg == "yes" or arg == "True" or arg == "Yes") otCLI.getParsingRules().pruneUnrecognizedInputTips = true; else if (arg == "false" or arg == "no" or arg == "False" or arg == "no") otCLI.getParsingRules().pruneUnrecognizedInputTips = false; else return false; return true; } bool synthesize_taxonomy = false; bool handleSynthesizeTaxonomy(OTCLI &, const std::string & arg) { if (arg == "true" or "yes" or "True" or "Yes") synthesize_taxonomy = true; else if (arg == "false" or "no" or "False" or "no") synthesize_taxonomy = false; else return false; return true; } unique_ptr<Tree_t> make_unresolved_tree(const vector<unique_ptr<Tree_t>>& trees, bool use_ids) { std::unique_ptr<Tree_t> tree(new Tree_t()); tree->createRoot(); if (use_ids) { map<long,string> names; for(const auto& tree: trees) for(auto nd: iter_pre_const(*tree)) if (nd->isTip()) { long id = nd->getOttId(); auto it = names.find(id); if (it == names.end()) names[id] = nd->getName(); } for(const auto& n: names) { auto node = tree->createChild(tree->getRoot()); node->setOttId(n.first); node->setName(n.second); } clearAndfillDesIdSets(*tree); } else { set<string> names; for(const auto& tree: trees) for(auto nd: iter_pre_const(*tree)) if (nd->isTip()) names.insert(nd->getName()); for(const auto& n: names) { auto node = tree->createChild(tree->getRoot()); node->setName(n); } } return tree; } string newick(const Tree_t &t) { std::ostringstream s; writeTreeAsNewick(s, t); return s.str(); } int main(int argc, char *argv[]) { OTCLI otCLI("otc-solve-subproblem", "takes at series of tree files. Each is treated as a subproblem.\n", "subproblem.tre"); otCLI.addFlag('o', "Require OTT ids. Defaults to true", handleRequireOttIds, true); otCLI.addFlag('p', "Prune unrecognized tips. Defaults to false", handlePruneUnrecognizedTips, true); otCLI.addFlag('T', "Synthesize unresolved taxonomy from all mentioned taxa. Defaults to false", handleSynthesizeTaxonomy, false); vector<unique_ptr<Tree_t>> trees; auto get = [&trees](OTCLI &, unique_ptr<Tree_t> nt) {trees.push_back(std::move(nt)); return true;}; if (argc < 2) throw OTCError("No subproblem provided!"); // I think multiple subproblem files are essentially concatenated. // Is it possible to read a single subproblem from cin? if (treeProcessingMain<Tree_t>(otCLI, argc, argv, get, nullptr, 1)) std::exit(1); bool requireOttIds = otCLI.getParsingRules().requireOttIds; if (synthesize_taxonomy) { trees.push_back(make_unresolved_tree(trees,requireOttIds)); LOG(DEBUG)<<"taxonomy = "<<newick(*trees.back())<<"\n"; } // Add fake Ott Ids to tips and compute desIds if (not requireOttIds) { auto& taxonomy = trees.back(); // 1. Compute mapping from name -> id long id = 1; map<string,long> name_to_id; for(auto nd: iter_pre(*taxonomy)) if (nd->isTip()) { string name = nd->getName(); if (not name.size()) throw OTCError()<<"Taxonomy tip has no label or OTT id!"; auto it = name_to_id.find(name); if (it != name_to_id.end()) throw OTCError()<<"Tip label '"<<name<<"' occurs twice in taxonomy!"; name_to_id[name] = id++; } // 2. Set ids for(auto& tree: trees) for(auto nd: iter_post(*tree)) if (nd->isTip()) { string name = nd->getName(); if (not name.size()) throw OTCError()<<"Tip has no label or OTT id!"; auto it = name_to_id.find(name); if (it == name_to_id.end()) throw OTCError()<<"Can't find label '"<<name<<"' in taxonomy!"; auto id = it->second; nd->setOttId(id); } // 3. Compute DesIds. for(auto& tree: trees) clearAndfillDesIdSets(*tree); } auto tree = combine(trees); writeTreeAsNewick(std::cout, *tree); std::cout<<"\n"; } <commit_msg>Remove dead code.<commit_after>#include <algorithm> #include <set> #include <list> #include <iterator> #include "otc/otcli.h" #include "otc/tree_operations.h" #include "otc/tree_iter.h" using namespace otc; using std::vector; using std::unique_ptr; using std::set; using std::list; using std::map; using std::string; using namespace otc; typedef TreeMappedWithSplits Tree_t; template <typename T> std::ostream& operator<<(std::ostream& o, const std::set<T>& s) { auto it = s.begin(); o<<*it++; for(; it != s.end(); it++) o<<" "<<*it; return o; } template <typename T> std::ostream& operator<<(std::ostream& o, const std::list<T>& s) { auto it = s.begin(); o<<*it++; for(; it != s.end(); it++) o<<" "<<*it; return o; } struct RSplit { set<long> in; set<long> out; set<long> all; RSplit() = default; RSplit(const set<long>& i, const set<long>& a) :in(i),all(a) { out = set_difference_as_set(all,in); assert(in.size() + out.size() == all.size()); } }; std::ostream& operator<<(std::ostream& o, const RSplit& s) { o<<s.in<<" | "<<s.out; return o; } /// Merge components c1 and c2 and return the component name that survived long merge_components(long c1, long c2, map<long,long>& component, map<long,list<long>>& elements) { if (elements[c2].size() > elements[c1].size()) std::swap(c1,c2); for(long i:elements[c2]) component[i] = c1; elements[c1].splice(elements[c1].begin(), elements[c2]); return c1; } bool empty_intersection(const set<long>& x, const set<long>& y) { std::set<long>::const_iterator i = x.begin(); std::set<long>::const_iterator j = y.begin(); while (i != x.end() && j != y.end()) { if (*i == *j) return false; else if (*i < *j) ++i; else ++j; } return true; } /// Construct a tree with all the splits mentioned, and return a null pointer if this is not possible unique_ptr<Tree_t> BUILD(const std::set<long>& tips, const vector<RSplit>& splits) { std::unique_ptr<Tree_t> tree(new Tree_t()); tree->createRoot(); // 1. First handle trees of size 1 and 2 if (tips.size() == 1) { tree->getRoot()->setOttId(*tips.begin()); return tree; } else if (tips.size() == 2) { auto Node1a = tree->createChild(tree->getRoot()); auto Node1b = tree->createChild(tree->getRoot()); auto it = tips.begin(); Node1a->setOttId(*it++); Node1b->setOttId(*it++); return tree; } // 2. Initialize the mapping from elements to components map<long,long> component; // element -> component map<long,list<long>> elements; // component -> elements for(long i: tips) { component[i] = i; elements[i].push_back(i); } // 3. For each split, all the leaves in the include group must be in the same component for(const auto& split: splits) { long c1 = -1; for(long i: split.in) { long c2 = component[i]; if (c1 != -1 and c1 != c2) merge_components(c1,c2,component,elements); c1 = component[i]; } } // 4. If we can't subdivide the leaves in any way, then the splits are not consistent, so return failure long first = *tips.begin(); if (elements[component[first]].size() == tips.size()) return {}; // 5. Create the set of tips in each connected component map<long,set<long>> subtips; for(long c: tips) { if (c != component[c]) continue; set<long>& s = subtips[c]; for(long l: elements[c]) s.insert(l); } // 6. Determine the splits that are not satisfied yet and go into each component map<long,vector<RSplit>> subsplits; for(const auto& split: splits) { long first = *split.in.begin(); long c = component[first]; // if none of the exclude group are in the component, then the split is satisfied by the top-level partition. if (empty_intersection(split.out, subtips[c])) continue; subsplits[c].push_back(split); } // 7. Recursively solve the sub-problems of the partition components for(const auto& x: subtips) { auto subtree = BUILD(x.second, subsplits[x.first]); if (not subtree) return {}; tree->addSubtree(tree->getRoot(), *subtree); } return tree; } /// Copy node names from taxonomy to tree based on ott ids, and copy the root name also void add_names(unique_ptr<Tree_t>& tree, const unique_ptr<Tree_t>& taxonomy) { clearAndfillDesIdSets(*tree); for(auto n1: iter_post(*tree)) for(auto n2: iter_post(*taxonomy)) if (n1->getData().desIds == n2->getData().desIds) n1->setName( n2->getName()); } /// Get the list of splits, and add them one at a time if they are consistent with previous splits unique_ptr<Tree_t> combine(const vector<unique_ptr<Tree_t>>& trees) { // Standardize names to 0..n-1 for this subproblem const auto& taxonomy = trees.back(); auto all_leaves = taxonomy->getRoot()->getData().desIds; // 1. Find splits in order of input trees vector<RSplit> splits; for(const auto& tree: trees) { auto root = tree->getRoot(); const auto leafTaxa = root->getData().desIds; for(const auto& leaf: set_difference_as_set(leafTaxa, all_leaves)) throw OTCError()<<"OTT Id "<<leaf<<" not in taxonomy!"; for(auto nd: iter_post_const(*tree)) { const auto& descendants = nd->getData().desIds; RSplit split{descendants, leafTaxa}; if (split.in.size()>1 and split.out.size()) splits.push_back(split); } } // 2. Add splits sequentially if they are consistent with previous splits. vector<RSplit> consistent; for(const auto& split: splits) { consistent.push_back(split); auto result = BUILD(all_leaves, consistent); if (not result) { consistent.pop_back(); LOG(DEBUG)<<"Reject: "<<split<<"\n"; } else LOG(DEBUG)<<"Keep: "<<split<<"\n"; } // 3. Construct final tree and add names auto tree = BUILD(all_leaves, consistent); add_names(tree, taxonomy); return tree; } bool handleRequireOttIds(OTCLI & otCLI, const std::string & arg) { if (arg == "true" or arg == "yes" or arg == "True" or arg == "Yes") otCLI.getParsingRules().requireOttIds = true; else if (arg == "false" or arg == "no" or arg == "False" or arg == "no") otCLI.getParsingRules().requireOttIds = false; else return false; return true; } bool handlePruneUnrecognizedTips(OTCLI & otCLI, const std::string & arg) { if (arg == "true" or arg == "yes" or arg == "True" or arg == "Yes") otCLI.getParsingRules().pruneUnrecognizedInputTips = true; else if (arg == "false" or arg == "no" or arg == "False" or arg == "no") otCLI.getParsingRules().pruneUnrecognizedInputTips = false; else return false; return true; } bool synthesize_taxonomy = false; bool handleSynthesizeTaxonomy(OTCLI &, const std::string & arg) { if (arg == "true" or "yes" or "True" or "Yes") synthesize_taxonomy = true; else if (arg == "false" or "no" or "False" or "no") synthesize_taxonomy = false; else return false; return true; } unique_ptr<Tree_t> make_unresolved_tree(const vector<unique_ptr<Tree_t>>& trees, bool use_ids) { std::unique_ptr<Tree_t> tree(new Tree_t()); tree->createRoot(); if (use_ids) { map<long,string> names; for(const auto& tree: trees) for(auto nd: iter_pre_const(*tree)) if (nd->isTip()) { long id = nd->getOttId(); auto it = names.find(id); if (it == names.end()) names[id] = nd->getName(); } for(const auto& n: names) { auto node = tree->createChild(tree->getRoot()); node->setOttId(n.first); node->setName(n.second); } clearAndfillDesIdSets(*tree); } else { set<string> names; for(const auto& tree: trees) for(auto nd: iter_pre_const(*tree)) if (nd->isTip()) names.insert(nd->getName()); for(const auto& n: names) { auto node = tree->createChild(tree->getRoot()); node->setName(n); } } return tree; } string newick(const Tree_t &t) { std::ostringstream s; writeTreeAsNewick(s, t); return s.str(); } int main(int argc, char *argv[]) { OTCLI otCLI("otc-solve-subproblem", "takes at series of tree files. Each is treated as a subproblem.\n", "subproblem.tre"); otCLI.addFlag('o', "Require OTT ids. Defaults to true", handleRequireOttIds, true); otCLI.addFlag('p', "Prune unrecognized tips. Defaults to false", handlePruneUnrecognizedTips, true); otCLI.addFlag('T', "Synthesize unresolved taxonomy from all mentioned taxa. Defaults to false", handleSynthesizeTaxonomy, false); vector<unique_ptr<Tree_t>> trees; auto get = [&trees](OTCLI &, unique_ptr<Tree_t> nt) {trees.push_back(std::move(nt)); return true;}; if (argc < 2) throw OTCError("No subproblem provided!"); // I think multiple subproblem files are essentially concatenated. // Is it possible to read a single subproblem from cin? if (treeProcessingMain<Tree_t>(otCLI, argc, argv, get, nullptr, 1)) std::exit(1); bool requireOttIds = otCLI.getParsingRules().requireOttIds; if (synthesize_taxonomy) { trees.push_back(make_unresolved_tree(trees,requireOttIds)); LOG(DEBUG)<<"taxonomy = "<<newick(*trees.back())<<"\n"; } // Add fake Ott Ids to tips and compute desIds if (not requireOttIds) { auto& taxonomy = trees.back(); // 1. Compute mapping from name -> id long id = 1; map<string,long> name_to_id; for(auto nd: iter_pre(*taxonomy)) if (nd->isTip()) { string name = nd->getName(); if (not name.size()) throw OTCError()<<"Taxonomy tip has no label or OTT id!"; auto it = name_to_id.find(name); if (it != name_to_id.end()) throw OTCError()<<"Tip label '"<<name<<"' occurs twice in taxonomy!"; name_to_id[name] = id++; } // 2. Set ids for(auto& tree: trees) for(auto nd: iter_post(*tree)) if (nd->isTip()) { string name = nd->getName(); if (not name.size()) throw OTCError()<<"Tip has no label or OTT id!"; auto it = name_to_id.find(name); if (it == name_to_id.end()) throw OTCError()<<"Can't find label '"<<name<<"' in taxonomy!"; auto id = it->second; nd->setOttId(id); } // 3. Compute DesIds. for(auto& tree: trees) clearAndfillDesIdSets(*tree); } auto tree = combine(trees); writeTreeAsNewick(std::cout, *tree); std::cout<<"\n"; } <|endoftext|>