<commit_before>//===- lib/MC/MCSymbol.cpp - MCSymbol implementation ----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;

// Sentinel value for the absolute pseudo section.
MCSection *MCSymbol::AbsolutePseudoSection = reinterpret_cast<MCSection *>(1);

void *MCSymbol::operator new(size_t s, const StringMapEntry<bool> *Name,
                             MCContext &Ctx) {
  // We may need more space for a Name to account for alignment.  So allocate
  // space for the storage type and not the name pointer.
  size_t Size = s + (Name ? sizeof(NameEntryStorageTy) : 0);

  // For safety, ensure that the alignment of a pointer is enough for an
  // MCSymbol.  This also ensures we don't need padding between the name and
  // symbol.
  // FIXME: Use static_assert when constexpr is supported.
  assert(alignOf<MCSymbol>() <= alignOf<NameEntryStorageTy>() &&
         "Bad alignment of MCSymbol");
  void *Storage = Ctx.allocate(Size, alignOf<NameEntryStorageTy>());
  NameEntryStorageTy *Start = static_cast<NameEntryStorageTy*>(Storage);
  NameEntryStorageTy *End = Start + (Name ? 1 : 0);
  return End;
}

void MCSymbol::setVariableValue(const MCExpr *Value) {
  assert(!IsUsed && "Cannot set a variable that has already been used.");
  assert(Value && "Invalid variable value!");
  this->Value = Value;
  SectionOrFragment = nullptr;
}

void MCSymbol::print(raw_ostream &OS, const MCAsmInfo *MAI) const {
  // The name for this MCSymbol is required to be a valid target name.  However,
  // some targets support quoting names with funny characters.  If the name
  // contains a funny character, then print it quoted.
  StringRef Name = getName();
  if (!MAI || MAI->isValidUnquotedName(Name)) {
    OS << Name;
    return;
  }

  if (MAI && !MAI->supportsNameQuoting())
    report_fatal_error("Symbol name with unsupported characters");

  OS << '"';
  for (char C : Name) {
    if (C == '\n')
      OS << "\\n";
    else if (C == '"')
      OS << "\\\"";
    else
      OS << C;
  }
  OS << '"';
}

#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
void MCSymbol::dump() const { dbgs() << *this; }
#endif
<commit_msg>Use AlignOf traits to enable static_assert.<commit_after>//===- lib/MC/MCSymbol.cpp - MCSymbol implementation ----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;

// Sentinel value for the absolute pseudo section.
MCSection *MCSymbol::AbsolutePseudoSection = reinterpret_cast<MCSection *>(1);

void *MCSymbol::operator new(size_t s, const StringMapEntry<bool> *Name,
                             MCContext &Ctx) {
  // We may need more space for a Name to account for alignment.  So allocate
  // space for the storage type and not the name pointer.
  size_t Size = s + (Name ? sizeof(NameEntryStorageTy) : 0);

  // For safety, ensure that the alignment of a pointer is enough for an
  // MCSymbol.  This also ensures we don't need padding between the name and
  // symbol.
  static_assert(AlignOf<MCSymbol>::Alignment <=
                AlignOf<NameEntryStorageTy>::Alignment,
                "Bad alignment of MCSymbol");
  void *Storage = Ctx.allocate(Size, alignOf<NameEntryStorageTy>());
  NameEntryStorageTy *Start = static_cast<NameEntryStorageTy*>(Storage);
  NameEntryStorageTy *End = Start + (Name ? 1 : 0);
  return End;
}

void MCSymbol::setVariableValue(const MCExpr *Value) {
  assert(!IsUsed && "Cannot set a variable that has already been used.");
  assert(Value && "Invalid variable value!");
  this->Value = Value;
  SectionOrFragment = nullptr;
}

void MCSymbol::print(raw_ostream &OS, const MCAsmInfo *MAI) const {
  // The name for this MCSymbol is required to be a valid target name.  However,
  // some targets support quoting names with funny characters.  If the name
  // contains a funny character, then print it quoted.
  StringRef Name = getName();
  if (!MAI || MAI->isValidUnquotedName(Name)) {
    OS << Name;
    return;
  }

  if (MAI && !MAI->supportsNameQuoting())
    report_fatal_error("Symbol name with unsupported characters");

  OS << '"';
  for (char C : Name) {
    if (C == '\n')
      OS << "\\n";
    else if (C == '"')
      OS << "\\\"";
    else
      OS << C;
  }
  OS << '"';
}

#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
void MCSymbol::dump() const { dbgs() << *this; }
#endif
<|endoftext|>


<commit_before>//===-- Path.cpp - Implement OS Path Concept --------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This header file implements the operating system Path concept.
//
//===----------------------------------------------------------------------===//

#include "llvm/System/Path.h"
#include "llvm/Config/config.h"
#include <cassert>

namespace llvm {
using namespace sys;

//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only TRULY operating system
//===          independent code.
//===----------------------------------------------------------------------===//

Path
Path::GetLLVMConfigDir() {
  Path result;
#ifdef LLVM_ETCDIR
  if (result.set(LLVM_ETCDIR))
    return result;
#endif
  return GetLLVMDefaultConfigDir();
}

LLVMFileType
sys::IdentifyFileType(const char*magic, unsigned length) {
  assert(magic && "Invalid magic number string");
  assert(length >=4 && "Invalid magic number length");
  switch (magic[0]) {
    case 'l':
      if (magic[1] == 'l' && magic[2] == 'v') {
        if (magic[3] == 'c')
          return CompressedBytecodeFileType;
        else if (magic[3] == 'm')
          return BytecodeFileType;
      }
      break;

    case '!':
      if (length >= 8) {
        if (memcmp(magic,"!<arch>\n",8) == 0)
          return ArchiveFileType;
      }
      break;

    default:
      break;
  }
  return UnknownFileType;
}

bool
Path::isArchive() const {
  if (canRead())
    return hasMagicNumber("!<arch>\012");
  return false;
}

bool
Path::isDynamicLibrary() const {
  if (canRead())
    return hasMagicNumber("\177ELF");
  return false;
}

Path
Path::FindLibrary(std::string& name) {
  std::vector<sys::Path> LibPaths;
  GetSystemLibraryPaths(LibPaths);
  for (unsigned i = 0; i < LibPaths.size(); ++i) {
    sys::Path FullPath(LibPaths[i]);
    FullPath.appendComponent("lib" + name + LTDL_SHLIB_EXT);
    if (FullPath.isDynamicLibrary())
      return FullPath;
    FullPath.eraseSuffix();
    FullPath.appendSuffix("a");
    if (FullPath.isArchive())
      return FullPath;
  }
  return sys::Path();
}

std::string
Path::GetDLLSuffix() {
  return LTDL_SHLIB_EXT;
}

}

// Include the truly platform-specific parts of this class.

#if defined(LLVM_ON_UNIX)
#include "Unix/Path.inc"
#endif
#if defined(LLVM_ON_WIN32)
#include "Win32/Path.inc"
#endif

<commit_msg>Move << method out of line.<commit_after>//===-- Path.cpp - Implement OS Path Concept --------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This header file implements the operating system Path concept.
//
//===----------------------------------------------------------------------===//

#include "llvm/System/Path.h"
#include "llvm/Config/config.h"
#include <cassert>
#include <ostream>
using namespace llvm;
using namespace sys;

//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only TRULY operating system
//===          independent code.
//===----------------------------------------------------------------------===//

std::ostream& llvm::operator<<(std::ostream &strm, const sys::Path &aPath) {
  strm << aPath.toString();
  return strm;
}

Path
Path::GetLLVMConfigDir() {
  Path result;
#ifdef LLVM_ETCDIR
  if (result.set(LLVM_ETCDIR))
    return result;
#endif
  return GetLLVMDefaultConfigDir();
}

LLVMFileType
sys::IdentifyFileType(const char*magic, unsigned length) {
  assert(magic && "Invalid magic number string");
  assert(length >=4 && "Invalid magic number length");
  switch (magic[0]) {
    case 'l':
      if (magic[1] == 'l' && magic[2] == 'v') {
        if (magic[3] == 'c')
          return CompressedBytecodeFileType;
        else if (magic[3] == 'm')
          return BytecodeFileType;
      }
      break;

    case '!':
      if (length >= 8) {
        if (memcmp(magic,"!<arch>\n",8) == 0)
          return ArchiveFileType;
      }
      break;

    default:
      break;
  }
  return UnknownFileType;
}

bool
Path::isArchive() const {
  if (canRead())
    return hasMagicNumber("!<arch>\012");
  return false;
}

bool
Path::isDynamicLibrary() const {
  if (canRead())
    return hasMagicNumber("\177ELF");
  return false;
}

Path
Path::FindLibrary(std::string& name) {
  std::vector<sys::Path> LibPaths;
  GetSystemLibraryPaths(LibPaths);
  for (unsigned i = 0; i < LibPaths.size(); ++i) {
    sys::Path FullPath(LibPaths[i]);
    FullPath.appendComponent("lib" + name + LTDL_SHLIB_EXT);
    if (FullPath.isDynamicLibrary())
      return FullPath;
    FullPath.eraseSuffix();
    FullPath.appendSuffix("a");
    if (FullPath.isArchive())
      return FullPath;
  }
  return sys::Path();
}

std::string Path::GetDLLSuffix() {
  return LTDL_SHLIB_EXT;
}

// Include the truly platform-specific parts of this class.
#if defined(LLVM_ON_UNIX)
#include "Unix/Path.inc"
#endif
#if defined(LLVM_ON_WIN32)
#include "Win32/Path.inc"
#endif
<|endoftext|>


<commit_before>// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "TextRenderer.hpp"
#include "core/Engine.hpp"
#include "graphics/Renderer.hpp"
#include "scene/Camera.hpp"
#include "assets/Cache.hpp"
#include "utils/Utils.hpp"

namespace ouzel
{
    namespace scene
    {
        TextRenderer::TextRenderer(const std::string& fontFile,
                                   bool initMipmaps,
                                   float initFontSize,
                                   const std::string& initText,
                                   Color initColor,
                                   const Vector2& initTextAnchor):
            Component(TYPE),
            text(initText),
            fontSize(initFontSize),
            textAnchor(initTextAnchor),
            color(initColor),
            mipmaps(initMipmaps)
        {
            shader = engine->getCache()->getShader(graphics::SHADER_TEXTURE);
            blendState = engine->getCache()->getBlendState(graphics::BLEND_ALPHA);
            whitePixelTexture = engine->getCache()->getTexture(graphics::TEXTURE_WHITE_PIXEL);

            indexBuffer = std::make_shared<graphics::Buffer>();
            indexBuffer->init(graphics::Buffer::Usage::INDEX, graphics::Buffer::DYNAMIC);

            vertexBuffer = std::make_shared<graphics::Buffer>();
            vertexBuffer->init(graphics::Buffer::Usage::VERTEX, graphics::Buffer::DYNAMIC);

            meshBuffer = std::make_shared<graphics::MeshBuffer>();
            meshBuffer->init(sizeof(uint16_t), indexBuffer, vertexBuffer);

            font = engine->getCache()->getFont(fontFile, mipmaps);

            updateText();
        }

        void TextRenderer::setFont(const std::string& fontFile)
        {
            font = engine->getCache()->getFont(fontFile);

            updateText();
        }

        void TextRenderer::setTextAnchor(const Vector2& newTextAnchor)
        {
            textAnchor = newTextAnchor;

            updateText();
        }

        void TextRenderer::setFontSize(float newFontSize)
        {
            fontSize = newFontSize;

            updateText();
        }

        void TextRenderer::draw(const Matrix4& transformMatrix,
                                float opacity,
                                const Matrix4& renderViewProjection,
                                const std::shared_ptr<graphics::Texture>& renderTarget,
                                const Rect& renderViewport,
                                bool depthWrite,
                                bool depthTest,
                                bool wireframe,
                                bool scissorTest,
                                const Rect& scissorRectangle)
        {
            Component::draw(transformMatrix,
                            opacity,
                            renderViewProjection,
                            renderTarget,
                            renderViewport,
                            depthWrite,
                            depthTest,
                            wireframe,
                            scissorTest,
                            scissorRectangle);

            if (needsMeshUpdate)
            {
                indexBuffer->setData(indices.data(), static_cast<uint32_t>(getVectorSize(indices)));
                vertexBuffer->setData(vertices.data(), static_cast<uint32_t>(getVectorSize(vertices)));

                needsMeshUpdate = false;
            }

            Matrix4 modelViewProj = renderViewProjection * transformMatrix;
            float colorVector[] = {color.normR(), color.normG(), color.normB(), color.normA() * opacity};

            std::vector<std::vector<float>> pixelShaderConstants(1);
            pixelShaderConstants[0] = {std::begin(colorVector), std::end(colorVector)};

            std::vector<std::vector<float>> vertexShaderConstants(1);
            vertexShaderConstants[0] = {std::begin(modelViewProj.m), std::end(modelViewProj.m)};

            engine->getRenderer()->addDrawCommand({wireframe ? whitePixelTexture : texture},
                                                        shader,
                                                        pixelShaderConstants,
                                                        vertexShaderConstants,
                                                        blendState,
                                                        meshBuffer,
                                                        static_cast<uint32_t>(indices.size()),
                                                        graphics::Renderer::DrawMode::TRIANGLE_LIST,
                                                        0,
                                                        renderTarget,
                                                        renderViewport,
                                                        depthWrite,
                                                        depthTest,
                                                        wireframe,
                                                        scissorTest,
                                                        scissorRectangle,
                                                        graphics::Renderer::CullMode::NONE);
        }

        void TextRenderer::setText(const std::string& newText)
        {
            text = newText;

            updateText();
        }

        void TextRenderer::setColor(const Color& newColor)
        {
            color = newColor;
        }

        void TextRenderer::updateText()
        {
            font->getVertices(text, Color::WHITE, fontSize, textAnchor, indices, vertices, texture);
            needsMeshUpdate = true;

            boundingBox.reset();

            for (const graphics::Vertex& vertex : vertices)
            {
                boundingBox.insertPoint(Vector2(vertex.position.x, vertex.position.y));
            }

        }
    } // namespace scene
} // namespace ouzel
<commit_msg>Don't render text if font was not loaded<commit_after>// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "TextRenderer.hpp"
#include "core/Engine.hpp"
#include "graphics/Renderer.hpp"
#include "scene/Camera.hpp"
#include "assets/Cache.hpp"
#include "utils/Utils.hpp"

namespace ouzel
{
    namespace scene
    {
        TextRenderer::TextRenderer(const std::string& fontFile,
                                   bool initMipmaps,
                                   float initFontSize,
                                   const std::string& initText,
                                   Color initColor,
                                   const Vector2& initTextAnchor):
            Component(TYPE),
            text(initText),
            fontSize(initFontSize),
            textAnchor(initTextAnchor),
            color(initColor),
            mipmaps(initMipmaps)
        {
            shader = engine->getCache()->getShader(graphics::SHADER_TEXTURE);
            blendState = engine->getCache()->getBlendState(graphics::BLEND_ALPHA);
            whitePixelTexture = engine->getCache()->getTexture(graphics::TEXTURE_WHITE_PIXEL);

            indexBuffer = std::make_shared<graphics::Buffer>();
            indexBuffer->init(graphics::Buffer::Usage::INDEX, graphics::Buffer::DYNAMIC);

            vertexBuffer = std::make_shared<graphics::Buffer>();
            vertexBuffer->init(graphics::Buffer::Usage::VERTEX, graphics::Buffer::DYNAMIC);

            meshBuffer = std::make_shared<graphics::MeshBuffer>();
            meshBuffer->init(sizeof(uint16_t), indexBuffer, vertexBuffer);

            font = engine->getCache()->getFont(fontFile, mipmaps);

            updateText();
        }

        void TextRenderer::setFont(const std::string& fontFile)
        {
            font = engine->getCache()->getFont(fontFile);

            updateText();
        }

        void TextRenderer::setTextAnchor(const Vector2& newTextAnchor)
        {
            textAnchor = newTextAnchor;

            updateText();
        }

        void TextRenderer::setFontSize(float newFontSize)
        {
            fontSize = newFontSize;

            updateText();
        }

        void TextRenderer::draw(const Matrix4& transformMatrix,
                                float opacity,
                                const Matrix4& renderViewProjection,
                                const std::shared_ptr<graphics::Texture>& renderTarget,
                                const Rect& renderViewport,
                                bool depthWrite,
                                bool depthTest,
                                bool wireframe,
                                bool scissorTest,
                                const Rect& scissorRectangle)
        {
            Component::draw(transformMatrix,
                            opacity,
                            renderViewProjection,
                            renderTarget,
                            renderViewport,
                            depthWrite,
                            depthTest,
                            wireframe,
                            scissorTest,
                            scissorRectangle);

            if (needsMeshUpdate)
            {
                indexBuffer->setData(indices.data(), static_cast<uint32_t>(getVectorSize(indices)));
                vertexBuffer->setData(vertices.data(), static_cast<uint32_t>(getVectorSize(vertices)));

                needsMeshUpdate = false;
            }

            Matrix4 modelViewProj = renderViewProjection * transformMatrix;
            float colorVector[] = {color.normR(), color.normG(), color.normB(), color.normA() * opacity};

            std::vector<std::vector<float>> pixelShaderConstants(1);
            pixelShaderConstants[0] = {std::begin(colorVector), std::end(colorVector)};

            std::vector<std::vector<float>> vertexShaderConstants(1);
            vertexShaderConstants[0] = {std::begin(modelViewProj.m), std::end(modelViewProj.m)};

            engine->getRenderer()->addDrawCommand({wireframe ? whitePixelTexture : texture},
                                                        shader,
                                                        pixelShaderConstants,
                                                        vertexShaderConstants,
                                                        blendState,
                                                        meshBuffer,
                                                        static_cast<uint32_t>(indices.size()),
                                                        graphics::Renderer::DrawMode::TRIANGLE_LIST,
                                                        0,
                                                        renderTarget,
                                                        renderViewport,
                                                        depthWrite,
                                                        depthTest,
                                                        wireframe,
                                                        scissorTest,
                                                        scissorRectangle,
                                                        graphics::Renderer::CullMode::NONE);
        }

        void TextRenderer::setText(const std::string& newText)
        {
            text = newText;

            updateText();
        }

        void TextRenderer::setColor(const Color& newColor)
        {
            color = newColor;
        }

        void TextRenderer::updateText()
        {
            boundingBox.reset();

            if (font)
            {
                font->getVertices(text, Color::WHITE, fontSize, textAnchor, indices, vertices, texture);
                needsMeshUpdate = true;

                for (const graphics::Vertex& vertex : vertices)
                {
                    boundingBox.insertPoint(Vector2(vertex.position.x, vertex.position.y));
                }
            }
            else
            {
                indices.clear();
                vertices.clear();
                texture.reset();
            }
        }
    } // namespace scene
} // namespace ouzel
<|endoftext|>


<commit_before>#include "stdafx.h"

#include "../../You-DataStore/datastore.h"
#include "../../You-DataStore/task_typedefs.h"
#include "controller/task_graph_controller.h"

#include "state.h"

namespace You {
namespace QueryEngine {
namespace Internal {

namespace {
	using DataStore = You::DataStore::DataStore;
	using Transaction = You::DataStore::Transaction;
	using KeyValuePairs = You::DataStore::KeyValuePairs;
}

const std::wstring State::MAX_ID_FIELD = L"max-id";

std::int64_t State::getMaxIDFromDataStore() {
	auto resources = DataStore::get().getAllResources();
	bool resourceFound = false;
	for (const auto& resource : resources) {
		auto it = resource.find(MAX_ID_FIELD);
		if (it != resource.end()) {
			resourceFound = true;
			auto newMaxID = boost::lexical_cast<Task::ID>(it->second);
			return newMaxID;
		}
	}
	return -1;
}

State::State()
: innerGraph(TaskGraph(TaskGraph::GraphType::DEPENDENCY)),
  innerSubtaskGraph(TaskGraph(TaskGraph::GraphType::SUBTASK)) {
	maxID = TaskGraphController::loadFromFile(innerGraph);
	TaskGraphController::loadFromFile(innerSubtaskGraph);
	commitMaxIDToDataStore();
}

State& State::get() {
	static State instance;
	return instance;
}

void State::clear() {
	get().innerGraph = TaskGraph(TaskGraph::GraphType::DEPENDENCY);
	get().innerSubtaskGraph = TaskGraph(TaskGraph::GraphType::SUBTASK);
	while (!get().undoStack().empty()) {
		get().undoStack().pop();
	}
	get().maxID = 0;
}

void State::setActiveFilter(const Filter& filter) {
	this->activeFilter = filter;
}

void State::setActiveComparator(const Comparator& comparator) {
	this->activeComparator = comparator;
}

Task::ID State::inquireNewID() {
	++maxID;
	return maxID;
}

void State::commitMaxIDToDataStore() {
	Transaction t(DataStore::get().begin());
	auto previousMaxID = getMaxIDFromDataStore();
	maxID = std::max(previousMaxID, maxID);
	auto sMaxID = boost::lexical_cast<std::wstring>(maxID);
	if (previousMaxID == -1) {
		DataStore::get().post(MAX_ID_FIELD, {{ MAX_ID_FIELD, sMaxID }});
	} else {
		DataStore::get().put(MAX_ID_FIELD, {{ MAX_ID_FIELD, sMaxID }});
	}
	t.commit();
}

}  // namespace Internal
}  // namespace QueryEngine
}  // namespace You
<commit_msg>Remove one more anon namespace<commit_after>#include "stdafx.h"

#include "../../You-DataStore/datastore.h"
#include "../../You-DataStore/task_typedefs.h"
#include "controller/task_graph_controller.h"

#include "state.h"

namespace You {
namespace QueryEngine {
namespace Internal {

using You::DataStore::DataStore;
using You::DataStore::Transaction;
using You::DataStore::KeyValuePairs;

const std::wstring State::MAX_ID_FIELD = L"max-id";

std::int64_t State::getMaxIDFromDataStore() {
	auto resources = DataStore::get().getAllResources();
	bool resourceFound = false;
	for (const auto& resource : resources) {
		auto it = resource.find(MAX_ID_FIELD);
		if (it != resource.end()) {
			resourceFound = true;
			auto newMaxID = boost::lexical_cast<Task::ID>(it->second);
			return newMaxID;
		}
	}
	return -1;
}

State::State()
: innerGraph(TaskGraph(TaskGraph::GraphType::DEPENDENCY)),
  innerSubtaskGraph(TaskGraph(TaskGraph::GraphType::SUBTASK)) {
	maxID = TaskGraphController::loadFromFile(innerGraph);
	TaskGraphController::loadFromFile(innerSubtaskGraph);
	commitMaxIDToDataStore();
}

State& State::get() {
	static State instance;
	return instance;
}

void State::clear() {
	get().innerGraph = TaskGraph(TaskGraph::GraphType::DEPENDENCY);
	get().innerSubtaskGraph = TaskGraph(TaskGraph::GraphType::SUBTASK);
	while (!get().undoStack().empty()) {
		get().undoStack().pop();
	}
	get().maxID = 0;
}

void State::setActiveFilter(const Filter& filter) {
	this->activeFilter = filter;
}

void State::setActiveComparator(const Comparator& comparator) {
	this->activeComparator = comparator;
}

Task::ID State::inquireNewID() {
	++maxID;
	return maxID;
}

void State::commitMaxIDToDataStore() {
	Transaction t(DataStore::get().begin());
	auto previousMaxID = getMaxIDFromDataStore();
	maxID = std::max(previousMaxID, maxID);
	auto sMaxID = boost::lexical_cast<std::wstring>(maxID);
	if (previousMaxID == -1) {
		DataStore::get().post(MAX_ID_FIELD, {{ MAX_ID_FIELD, sMaxID }});
	} else {
		DataStore::get().put(MAX_ID_FIELD, {{ MAX_ID_FIELD, sMaxID }});
	}
	t.commit();
}

}  // namespace Internal
}  // namespace QueryEngine
}  // namespace You
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: scopeguard.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-10 14:00:09 $
 *
 *  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 "comphelper/scopeguard.hxx"
#include "osl/diagnose.h"
#include "com/sun/star/uno/Exception.hpp"

namespace comphelper {

ScopeGuard::~ScopeGuard()
{
    if (m_func)
    {
        if (m_bIgnoreExceptions)
        {
            try {
                m_func();
            }
            catch (com::sun::star::uno::Exception & exc) {
                OSL_ENSURE(
                    false, rtl::OUStringToOString(
                        rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                                           "UNO exception occured: ") ) +
                        exc.Message, RTL_TEXTENCODING_UTF8 ).getStr() );
            }
            catch (...) {
                OSL_ENSURE( false, "unknown exception occured!" );
            }
        }
        else
        {
            m_func();
        }
    }
}

void ScopeGuard::dismiss()
{
    m_func.clear();
}

} // namespace comphelper

<commit_msg>INTEGRATION: CWS presfixes02 (1.2.2); FILE MERGED 2005/03/17 09:32:21 dbo 1.2.2.1: #i39513# modified sception handling switch<commit_after>/*************************************************************************
 *
 *  $RCSfile: scopeguard.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-03-30 08:18:13 $
 *
 *  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 "comphelper/scopeguard.hxx"
#include "osl/diagnose.h"
#include "com/sun/star/uno/Exception.hpp"

namespace comphelper {

ScopeGuard::~ScopeGuard()
{
    if (m_func)
    {
        if (m_excHandling == IGNORE_EXCEPTIONS)
        {
            try {
                m_func();
            }
            catch (com::sun::star::uno::Exception & exc) {
                OSL_ENSURE(
                    false, rtl::OUStringToOString(
                        rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                                           "UNO exception occured: ") ) +
                        exc.Message, RTL_TEXTENCODING_UTF8 ).getStr() );
            }
            catch (...) {
                OSL_ENSURE( false, "unknown exception occured!" );
            }
        }
        else
        {
            m_func();
        }
    }
}

void ScopeGuard::dismiss()
{
    m_func.clear();
}

} // namespace comphelper

<|endoftext|>


<commit_before>#include "mbed.h"
#include "me135.h"
#define VERBOSE
#define KEY(x,y) #x ":" #y

BusOut leds(LED1, LED2, LED3, LED4);
me135::BeagleBone bone(p9, p10);
QEI left_enc(p11, p12);
QEI right_enc(p13, p14);
me135::IRSensor front_ir(p15);
me135::IRSensor left_ir(p16);
me135::IRSensor right_ir(p17);
me135::DriveTrain right_drive(p21, p22);
me135::DriveTrain left_drive(p24, p23);
me135::Shooter shooter(p28, p25, p26);
me135::Claw claw(p29);

volatile int g_left_target_speed = 0;
volatile int g_right_target_speed = 0;
// Temporary hack
volatile int left_speed = 0;
volatile int right_speed = 0;
volatile int left_power = 0;
volatile int right_power = 0;

const char *dir_to_str[] = {"fwd", "left", "back", "right", "stop"};

// We send the data back so we can have pretty graphs
void send_ir(void) {
  char buffer[256];
  int len = sprintf(buffer, "{" KEY("id","ir")
                            "," KEY("front", %f)
                            "," KEY("left",%f)
                            "," KEY("right",%f) "}\n",
                        front_ir.read(), left_ir.read(), right_ir.read());
  bone.write(buffer, len);
}

void send_encoder(void) {
  char buffer[256];
  int len = sprintf(buffer, "{" KEY("id", "encoder")
                            "," KEY("left", %d)
                            "," KEY("right", %d) "}\n",
                            left_enc.getPulses(2), right_enc.getPulses(2));
//  printf("%d,%d,%d,%d,%d,%d\r\n",g_left_target_speed, g_right_target_speed, left_speed, right_speed, left_power, right_power);
  left_enc.reset(2);
  right_enc.reset(2);
  bone.write(buffer, len);
}

void send_encoder_count(void) {
  char buffer[256];
  int len = sprintf(buffer, "{" KEY("id", "encoder_count")
                            "," KEY("left", %d)
                            "," KEY("right", %d) "}\n",
                            left_enc.getPulses(1), right_enc.getPulses(1));
  bone.write(buffer, len);
}

void send_walls(Directions dir) {
  char buffer[256];
  char len = sprintf(buffer, "{" KEY("id","maze_walls")
                             "," KEY("left",%d)
                             "," KEY("right",%d)
                             "," KEY("center",%d)
                             "," KEY("action","%s") "}\n",
                              left_ir < kWallDist,
                              right_ir < kWallDist,
                              front_ir < kWallDist,
                              dir_to_str[dir]);
  bone.write(buffer, len);
}

void send_claw_pos(const float claw_pos) {
  int pos = (int)(claw_pos * 99);
  char buffer[128];
  char len = sprintf(buffer, "{" KEY("id","claw")
                             "," KEY("pos",%d) "}\n", pos);
  bone.write(buffer, len);
}

bool dist_control(const int final, const Directions dir) {
//  static int i_term = 0;
  int dist;
  if (dir == FWD) {
    dist = min(left_enc.getPulses(0), right_enc.getPulses(0));
  } else if (dir == LEFT) {
    dist = min(-left_enc.getPulses(0), right_enc.getPulses(0));
  } else if (dir == RIGHT) {
    dist = min(left_enc.getPulses(0), -right_enc.getPulses(0));
  } else {
    dist = 0;
  }
  // TODO: Use walls to go straight
  int error = final - dist;
  int target = kDistP * error;
//  printf("d:%d,f:%d,t:%d\r\n", dist, final, target);
  if (dist < final) {
    if (dir == LEFT) {
      g_left_target_speed = -target;
    } else {
      g_left_target_speed = target;
    }
    if (dir == RIGHT) {
      g_right_target_speed = -target;
    } else {
      g_right_target_speed = target;
    }
    return false;
  } else {
    g_left_target_speed = 0;
    g_right_target_speed = 0;
    return true;
  }
}

// PI Control
// Uses the global g_target_speed
void speed_control(void) {
  static int i_term_l = 0;
  static int i_term_r = 0;

  /*int*/ left_speed = kSpeedScaling * left_enc.getPulses(3);
  /*int*/ right_speed = kSpeedScaling * right_enc.getPulses(3);
  left_enc.reset(3);
  right_enc.reset(3);

  // DUMB BANG BANG
//  left_speed > g_left_target_speed ? left_drive = 0 : left_drive = 1;
//  right_speed > g_right_target_speed ? right_drive = 0 : right_drive = 1;

  // Actual code?
   int l_error = g_left_target_speed - left_speed;
   i_term_l += kSpeedI * l_error;
   i_term_l = constrain(i_term_l, kMinITerm, kMaxITerm);
   /*int*/ left_power = kSpeedOL * g_left_target_speed + kSpeedP * l_error + i_term_l;
   left_drive = constrain(left_power / kMaxPrescaledSpeed, -1.0f, 1.0f);

   int r_error = g_right_target_speed - right_speed;
   i_term_r += kSpeedI * r_error;
   i_term_r = constrain(i_term_r, kMinITerm, kMaxITerm);
   /*int*/ right_power = kSpeedOL * g_right_target_speed + kSpeedP * r_error + i_term_r;
   right_drive = constrain(right_power / kMaxPrescaledSpeed, -1.0f, 1.0f);
}

void runMotors(const int speed, const Directions dir) {
//  float spd = speed / kMaxSpeed;
  int spd = speed / 2;
  switch (dir) {
    case FWD:  // Forwards
      g_right_target_speed = spd;
      g_left_target_speed = spd;
      break;
    case BACK:  // Backwards
      g_right_target_speed = -spd;
      g_left_target_speed = -spd;
      break;
    case RIGHT:  // Right
      g_right_target_speed = -spd;
      g_left_target_speed = spd;
      break;
    case LEFT:  // Left
      g_right_target_speed = spd;
      g_left_target_speed = -spd;
      break;
    case STOP:  // Stop
      g_right_target_speed = 0;
      g_left_target_speed = 0;
      break;
  }
}

void coast(void) {
  right_drive = 0;
  left_drive = 0;
}

int main() {
  Ticker speed_loop_ticker;
  speed_loop_ticker.attach_us(speed_control, kSpeedControlLoopTime);

  Timeout motor_safety;

  Timer send_data_timer;
  send_data_timer.start();

  Timer dist_control_loop_timer;
  dist_control_loop_timer.start();

  int target_dist = 0; // Used in distance mode;
  Directions target_dir = STOP; // Used in distance mode;
  Modes mode = IDLE;

  char msg[kMaxMsgSize];
  for (;;) {
    switch (mode) {
      case MOVING:
        if (dist_control_loop_timer.read_us() > kDistControlLoopTime) {
          dist_control_loop_timer.reset();
          bool done = dist_control(target_dist, target_dir);
          if (done) {
            send_walls(target_dir);
            mode = IDLE;
          }
        }
        break;
      case IDLE:
      default:
       // Do nothing, for now
       break;
    }
    if (shooter.hasFired()) {
      char buffer[128];
      int len = sprintf(buffer, "{" KEY("id","shooter")
                                "," KEY("shot", 1) "}\n");
      bone.write(buffer, len);
    }
    if (bone.readable()) {
      bone.read(msg, kMaxMsgSize);
      switch (msg[0]) {
        // Get walls
        case 'w': {
          send_walls(STOP);
        }
        // gfXX - go direction for XX spaces
        case 'g': {
          if (mode == IDLE) {
            char dir = msg[1];
            switch(dir) {
              case 'f':
                // Prevent us from running into a wall!
                if (front_ir < kWallDist) {
                  target_dist = 0;
                  target_dir = STOP;
                } else {
                  target_dist = kSquareSize * kClicksPerInch;
                  target_dir = FWD;
                }
                break;
              case 'r':
                target_dist = kQuarterCircle;
                target_dir = RIGHT;
                break;
              case 'l':
                target_dist = kQuarterCircle;
                target_dir = LEFT;
                break;
              default:
                // Not recognized, do nothing
                break;
            }
            // We have to reset the encoders so we have the right distance
            left_enc.reset(0);
            right_enc.reset(0);
            mode = MOVING;
          }
          break;
        }
        // mfXX - go direction at speed, with safety after .5s
        case 'm': {
          mode = IDLE;
          Directions dir = charToDirection(msg[1]);
          int spd = (msg[2] - '0') * 10 + (msg[3] - '0');
          runMotors(spd, dir);
          if (dir != STOP) {
            motor_safety.attach(coast, 0.5);
          } else {
            motor_safety.detach();
          }
          break;
        }
        // Claw
        case 'c': {
          int pos = (msg[1] - '0') * 10 + (msg[2] - '0');
          claw = pos / kMaxClawPos;
          send_claw_pos(claw.read());
          break;
        }
        // Shooter
        case 's': {
          shooter.fire();
          break;
        }
        case 'l': { // LEDs
          leds = leds ^ (1 << (msg[1] - '1'));
          break;
        }
      }
    }

    if (send_data_timer.read_us() > kSendDataTime) {
      send_data_timer.reset();
      send_ir();
      send_encoder();
      send_encoder_count();
    }
  }
  return -1; // End of program, should never be reached
}
<commit_msg>Switching shooter motor pins<commit_after>#include "mbed.h"
#include "me135.h"
#define VERBOSE
#define KEY(x,y) #x ":" #y

BusOut leds(LED1, LED2, LED3, LED4);
me135::BeagleBone bone(p9, p10);
QEI left_enc(p11, p12);
QEI right_enc(p13, p14);
me135::IRSensor front_ir(p15);
me135::IRSensor left_ir(p16);
me135::IRSensor right_ir(p17);
me135::DriveTrain right_drive(p21, p22);
me135::DriveTrain left_drive(p24, p23);
me135::Shooter shooter(p28, p26, p25);
me135::Claw claw(p29);

volatile int g_left_target_speed = 0;
volatile int g_right_target_speed = 0;
// Temporary hack
volatile int left_speed = 0;
volatile int right_speed = 0;
volatile int left_power = 0;
volatile int right_power = 0;

const char *dir_to_str[] = {"fwd", "left", "back", "right", "stop"};

// We send the data back so we can have pretty graphs
void send_ir(void) {
  char buffer[256];
  int len = sprintf(buffer, "{" KEY("id","ir")
                            "," KEY("front", %f)
                            "," KEY("left",%f)
                            "," KEY("right",%f) "}\n",
                        front_ir.read(), left_ir.read(), right_ir.read());
  bone.write(buffer, len);
}

void send_encoder(void) {
  char buffer[256];
  int len = sprintf(buffer, "{" KEY("id", "encoder")
                            "," KEY("left", %d)
                            "," KEY("right", %d) "}\n",
                            left_enc.getPulses(2), right_enc.getPulses(2));
//  printf("%d,%d,%d,%d,%d,%d\r\n",g_left_target_speed, g_right_target_speed, left_speed, right_speed, left_power, right_power);
  left_enc.reset(2);
  right_enc.reset(2);
  bone.write(buffer, len);
}

void send_encoder_count(void) {
  char buffer[256];
  int len = sprintf(buffer, "{" KEY("id", "encoder_count")
                            "," KEY("left", %d)
                            "," KEY("right", %d) "}\n",
                            left_enc.getPulses(1), right_enc.getPulses(1));
  bone.write(buffer, len);
}

void send_walls(Directions dir) {
  char buffer[256];
  char len = sprintf(buffer, "{" KEY("id","maze_walls")
                             "," KEY("left",%d)
                             "," KEY("right",%d)
                             "," KEY("center",%d)
                             "," KEY("action","%s") "}\n",
                              left_ir < kWallDist,
                              right_ir < kWallDist,
                              front_ir < kWallDist,
                              dir_to_str[dir]);
  bone.write(buffer, len);
}

void send_claw_pos(const float claw_pos) {
  int pos = (int)(claw_pos * 99);
  char buffer[128];
  char len = sprintf(buffer, "{" KEY("id","claw")
                             "," KEY("pos",%d) "}\n", pos);
  bone.write(buffer, len);
}

bool dist_control(const int final, const Directions dir) {
//  static int i_term = 0;
  int dist;
  if (dir == FWD) {
    dist = min(left_enc.getPulses(0), right_enc.getPulses(0));
  } else if (dir == LEFT) {
    dist = min(-left_enc.getPulses(0), right_enc.getPulses(0));
  } else if (dir == RIGHT) {
    dist = min(left_enc.getPulses(0), -right_enc.getPulses(0));
  } else {
    dist = 0;
  }
  // TODO: Use walls to go straight
  int error = final - dist;
  int target = kDistP * error;
//  printf("d:%d,f:%d,t:%d\r\n", dist, final, target);
  if (dist < final) {
    if (dir == LEFT) {
      g_left_target_speed = -target;
    } else {
      g_left_target_speed = target;
    }
    if (dir == RIGHT) {
      g_right_target_speed = -target;
    } else {
      g_right_target_speed = target;
    }
    return false;
  } else {
    g_left_target_speed = 0;
    g_right_target_speed = 0;
    return true;
  }
}

// PI Control
// Uses the global g_target_speed
void speed_control(void) {
  static int i_term_l = 0;
  static int i_term_r = 0;

  /*int*/ left_speed = kSpeedScaling * left_enc.getPulses(3);
  /*int*/ right_speed = kSpeedScaling * right_enc.getPulses(3);
  left_enc.reset(3);
  right_enc.reset(3);

  // DUMB BANG BANG
//  left_speed > g_left_target_speed ? left_drive = 0 : left_drive = 1;
//  right_speed > g_right_target_speed ? right_drive = 0 : right_drive = 1;

  // Actual code?
   int l_error = g_left_target_speed - left_speed;
   i_term_l += kSpeedI * l_error;
   i_term_l = constrain(i_term_l, kMinITerm, kMaxITerm);
   /*int*/ left_power = kSpeedOL * g_left_target_speed + kSpeedP * l_error + i_term_l;
   left_drive = constrain(left_power / kMaxPrescaledSpeed, -1.0f, 1.0f);

   int r_error = g_right_target_speed - right_speed;
   i_term_r += kSpeedI * r_error;
   i_term_r = constrain(i_term_r, kMinITerm, kMaxITerm);
   /*int*/ right_power = kSpeedOL * g_right_target_speed + kSpeedP * r_error + i_term_r;
   right_drive = constrain(right_power / kMaxPrescaledSpeed, -1.0f, 1.0f);
}

void runMotors(const int speed, const Directions dir) {
//  float spd = speed / kMaxSpeed;
  int spd = speed / 2;
  switch (dir) {
    case FWD:  // Forwards
      g_right_target_speed = spd;
      g_left_target_speed = spd;
      break;
    case BACK:  // Backwards
      g_right_target_speed = -spd;
      g_left_target_speed = -spd;
      break;
    case RIGHT:  // Right
      g_right_target_speed = -spd;
      g_left_target_speed = spd;
      break;
    case LEFT:  // Left
      g_right_target_speed = spd;
      g_left_target_speed = -spd;
      break;
    case STOP:  // Stop
      g_right_target_speed = 0;
      g_left_target_speed = 0;
      break;
  }
}

void coast(void) {
  right_drive = 0;
  left_drive = 0;
}

int main() {
  Ticker speed_loop_ticker;
  speed_loop_ticker.attach_us(speed_control, kSpeedControlLoopTime);

  Timeout motor_safety;

  Timer send_data_timer;
  send_data_timer.start();

  Timer dist_control_loop_timer;
  dist_control_loop_timer.start();

  int target_dist = 0; // Used in distance mode;
  Directions target_dir = STOP; // Used in distance mode;
  Modes mode = IDLE;

  char msg[kMaxMsgSize];
  for (;;) {
    switch (mode) {
      case MOVING:
        if (dist_control_loop_timer.read_us() > kDistControlLoopTime) {
          dist_control_loop_timer.reset();
          bool done = dist_control(target_dist, target_dir);
          if (done) {
            send_walls(target_dir);
            mode = IDLE;
          }
        }
        break;
      case IDLE:
      default:
       // Do nothing, for now
       break;
    }
    if (shooter.hasFired()) {
      char buffer[128];
      int len = sprintf(buffer, "{" KEY("id","shooter")
                                "," KEY("shot", 1) "}\n");
      bone.write(buffer, len);
    }
    if (bone.readable()) {
      bone.read(msg, kMaxMsgSize);
      switch (msg[0]) {
        // Get walls
        case 'w': {
          send_walls(STOP);
        }
        // gfXX - go direction for XX spaces
        case 'g': {
          if (mode == IDLE) {
            char dir = msg[1];
            switch(dir) {
              case 'f':
                // Prevent us from running into a wall!
                if (front_ir < kWallDist) {
                  target_dist = 0;
                  target_dir = STOP;
                } else {
                  target_dist = kSquareSize * kClicksPerInch;
                  target_dir = FWD;
                }
                break;
              case 'r':
                target_dist = kQuarterCircle;
                target_dir = RIGHT;
                break;
              case 'l':
                target_dist = kQuarterCircle;
                target_dir = LEFT;
                break;
              default:
                // Not recognized, do nothing
                break;
            }
            // We have to reset the encoders so we have the right distance
            left_enc.reset(0);
            right_enc.reset(0);
            mode = MOVING;
          }
          break;
        }
        // mfXX - go direction at speed, with safety after .5s
        case 'm': {
          mode = IDLE;
          Directions dir = charToDirection(msg[1]);
          int spd = (msg[2] - '0') * 10 + (msg[3] - '0');
          runMotors(spd, dir);
          if (dir != STOP) {
            motor_safety.attach(coast, 0.5);
          } else {
            motor_safety.detach();
          }
          break;
        }
        // Claw
        case 'c': {
          int pos = (msg[1] - '0') * 10 + (msg[2] - '0');
          claw = pos / kMaxClawPos;
          send_claw_pos(claw.read());
          break;
        }
        // Shooter
        case 's': {
          shooter.fire();
          break;
        }
        case 'l': { // LEDs
          leds = leds ^ (1 << (msg[1] - '1'));
          break;
        }
      }
    }

    if (send_data_timer.read_us() > kSendDataTime) {
      send_data_timer.reset();
      send_ir();
      send_encoder();
      send_encoder_count();
    }
  }
  return -1; // End of program, should never be reached
}
<|endoftext|>


<commit_before>
#ifndef _COLLECTIVE_HPP
#define _COLLECTIVE_HPP

#include "SoftXMT.hpp"
#include "ForkJoin.hpp"
#include "common.hpp"

int64_t collective_max(int64_t a, int64_t b);
int64_t collective_min(int64_t a, int64_t b);
int64_t collective_add(int64_t a, int64_t b);
int64_t collective_mult(int64_t a, int64_t b);

#define COLL_MAX &collective_max
#define COLL_MIN &collective_min
#define COLL_ADD &collective_add
#define COLL_MULT &collective_mult

int64_t SoftXMT_collective_reduce( int64_t (*commutative_func)(int64_t, int64_t), Node home_node, int64_t myValue, int64_t initialValue );

template< typename T >
inline T coll_add(const T& a, const T& b) {
  return a+b;
}

#define HOME_NODE 0
extern Thread * reducing_thread;
extern int64_t reduction_result;
extern int64_t final_reduction_result;
extern Node reduction_reported_in;

template< typename T >
static void am_reduce_wake(T * val, size_t sz, void * payload, size_t psz) {
  final_reduction_result = *val;
  SoftXMT_wake(reducing_thread);
}

template< typename T, T (*Reducer)(const T&, const T&), T BaseVal>
static void am_reduce(T * val, size_t sz, void* payload, size_t psz) {
  CHECK(SoftXMT_mynode() == HOME_NODE);
  if (reduction_reported_in == 0) reduction_result = BaseVal;
  reduction_result = (int64_t)Reducer((T)reduction_result, *val);
  reduction_reported_in++;
  VLOG(5) << "reported_in = " << reduction_reported_in;
  if (reduction_reported_in == SoftXMT_nodes()) {
    reduction_reported_in = 0;
    for (Node n = 0; n < SoftXMT_nodes(); n++) {
      VLOG(5) << "waking " << n;
      SoftXMT_call_on(n, &am_reduce_wake, (T*)(&reduction_result));
    }
  }
}

/// Global reduction across all nodes, returning the completely reduced value to everyone.
/// Notes:
///  - this suffices as a global barrier across *all nodes*
///  - as such, only one instance of this can be running at a given time
///  - and it must be called by every node or deadlock will occur
template< typename T, T (*Reducer)(const T&, const T&), T BaseVal>
T SoftXMT_allreduce(T myval) {
  BOOST_STATIC_ASSERT( sizeof(T) <= 8 );
  // TODO: do tree reduction to reduce amount of serialization at Node 0
  reducing_thread = CURRENT_THREAD;

  SoftXMT_call_on(0, &am_reduce<T,Reducer,BaseVal>, &myval);

  SoftXMT_suspend();

  return final_reduction_result;
}

#endif // _COLLECTIVE_HPP

<commit_msg>Collective reduce supports any size of reduce object that can be copied. Added a no-initial-value reduce<commit_after>
#ifndef _COLLECTIVE_HPP
#define _COLLECTIVE_HPP

#include "SoftXMT.hpp"
#include "ForkJoin.hpp"
#include "common.hpp"

int64_t collective_max(int64_t a, int64_t b);
int64_t collective_min(int64_t a, int64_t b);
int64_t collective_add(int64_t a, int64_t b);
int64_t collective_mult(int64_t a, int64_t b);

#define COLL_MAX &collective_max
#define COLL_MIN &collective_min
#define COLL_ADD &collective_add
#define COLL_MULT &collective_mult

int64_t SoftXMT_collective_reduce( int64_t (*commutative_func)(int64_t, int64_t), Node home_node, int64_t myValue, int64_t initialValue );

template< typename T >
inline T coll_add(const T& a, const T& b) {
  return a+b;
}

#define HOME_NODE 0
extern Thread * reducing_thread;
extern Node reduction_reported_in;

// This class is just for holding the reduction
// value in a type-safe manner
template < typename T >
class Reductions {
  private:
    Reductions() {}
  public:
    static T reduction_result;
    static T final_reduction_result;
};

template <typename T>
T Reductions<T>::reduction_result;

template <typename T>
T Reductions<T>::final_reduction_result;

template< typename T >
static void am_reduce_wake(T * val, size_t sz, void * payload, size_t psz) {
  Reductions<T>::final_reduction_result = *val;
  SoftXMT_wake(reducing_thread);
}

template< typename T, T (*Reducer)(const T&, const T&), T BaseVal>
static void am_reduce(T * val, size_t sz, void* payload, size_t psz) {
  CHECK(SoftXMT_mynode() == HOME_NODE);

  if (reduction_reported_in == 0) Reductions<T>::reduction_result = BaseVal;
  Reductions<T>::reduction_result = Reducer(Reductions<T>::reduction_result, *val);

  reduction_reported_in++;
  VLOG(5) << "reported_in = " << reduction_reported_in;
  if (reduction_reported_in == SoftXMT_nodes()) {
    reduction_reported_in = 0;
    for (Node n = 0; n < SoftXMT_nodes(); n++) {
      VLOG(5) << "waking " << n;
      T data = Reductions<T>::reduction_result;
      SoftXMT_call_on(n, &am_reduce_wake, &data);
    }
  }
}

template< typename T, T (*Reducer)(const T&, const T&) >
static void am_reduce_noinit(T * val, size_t sz, void* payload, size_t psz) {
  CHECK(SoftXMT_mynode() == HOME_NODE);

  if (reduction_reported_in == 0) Reductions<T>::reduction_result = *val; // no base val
  else Reductions<T>::reduction_result = Reducer(Reductions<T>::reduction_result, *val);

  reduction_reported_in++;
  VLOG(5) << "reported_in = " << reduction_reported_in;
  if (reduction_reported_in == SoftXMT_nodes()) {
    reduction_reported_in = 0;
    for (Node n = 0; n < SoftXMT_nodes(); n++) {
      VLOG(5) << "waking " << n;
      T data = Reductions<T>::reduction_result;
      SoftXMT_call_on(n, &am_reduce_wake, &data);
    }
  }
}

/// Global reduction across all nodes, returning the completely reduced value to everyone.
/// Notes:
///  - this suffices as a global barrier across *all nodes*
///  - as such, only one instance of this can be running at a given time
///  - and it must be called by every node or deadlock will occur
template< typename T, T (*Reducer)(const T&, const T&), T BaseVal>
T SoftXMT_allreduce(T myval) {
  // TODO: do tree reduction to reduce amount of serialization at Node 0
  reducing_thread = CURRENT_THREAD;

  SoftXMT_call_on(0, &am_reduce<T,Reducer,BaseVal>, &myval);

  SoftXMT_suspend();

  return Reductions<T>::final_reduction_result;
}

template< typename T, T (*Reducer)(const T&, const T&) >
T SoftXMT_allreduce_noinit(T myval) {
  // TODO: do tree reduction to reduce amount of serialization at Node 0
  reducing_thread = CURRENT_THREAD;

  SoftXMT_call_on(0, &am_reduce_noinit<T,Reducer>, &myval);

  SoftXMT_suspend();

  return Reductions<T>::final_reduction_result;
}

#endif // _COLLECTIVE_HPP

<|endoftext|>


<commit_before>
#ifndef _COLLECTIVE_HPP
#define _COLLECTIVE_HPP

#include "SoftXMT.hpp"
#include "ForkJoin.hpp"
#include "common.hpp"

int64_t collective_max(int64_t a, int64_t b);
int64_t collective_min(int64_t a, int64_t b);
int64_t collective_add(int64_t a, int64_t b);
int64_t collective_mult(int64_t a, int64_t b);

#define COLL_MAX &collective_max
#define COLL_MIN &collective_min
#define COLL_ADD &collective_add
#define COLL_MULT &collective_mult

int64_t SoftXMT_collective_reduce( int64_t (*commutative_func)(int64_t, int64_t), Node home_node, int64_t myValue, int64_t initialValue );

template< typename T >
inline T coll_add(const T& a, const T& b) {
  return a+b;
}

#define HOME_NODE 0
extern Thread * reducing_thread;
extern Node reduction_reported_in;

// This class is just for holding the reduction
// value in a type-safe manner
template < typename T >
class Reductions {
  private:
    Reductions() {}
  public:
    static T reduction_result;
    static T final_reduction_result;
};

template <typename T>
T Reductions<T>::reduction_result;

template <typename T>
T Reductions<T>::final_reduction_result;

template< typename T >
static void am_reduce_wake(T * val, size_t sz, void * payload, size_t psz) {
  Reductions<T>::final_reduction_result = *val;
  SoftXMT_wake(reducing_thread);
}

template< typename T >
static void am_reduce_array_wake(T * val, size_t sz, void * payload, size_t psz) {
  memcpy(Reductions<T*>::final_reduction_result, val, sz);
  SoftXMT_wake(reducing_thread);
}

template< typename T, T (*Reducer)(const T&, const T&), T BaseVal>
static void am_reduce(T * val, size_t sz, void* payload, size_t psz) {
  CHECK(SoftXMT_mynode() == HOME_NODE);

  if (reduction_reported_in == 0) Reductions<T>::reduction_result = BaseVal;
  Reductions<T>::reduction_result = Reducer(Reductions<T>::reduction_result, *val);

  reduction_reported_in++;
  VLOG(5) << "reported_in = " << reduction_reported_in;
  if (reduction_reported_in == SoftXMT_nodes()) {
    reduction_reported_in = 0;
    for (Node n = 0; n < SoftXMT_nodes(); n++) {
      VLOG(5) << "waking " << n;
      T data = Reductions<T>::reduction_result;
      SoftXMT_call_on(n, &am_reduce_wake, &data);
    }
  }
}

template< typename T, T (*Reducer)(const T&, const T&), T BaseVal>
static void am_reduce_array(T * val, size_t sz, void* payload, size_t psz) {
  CHECK(SoftXMT_mynode() == HOME_NODE);

  size_t nelem = sz / sizeof(T);

  if (reduction_reported_in == 0) {
    // allocate space for result
    Reductions<T*>::reduction_result = new T[nelem];
    for (size_t i=0; i<nelem; i++) Reductions<T*>::reduction_result[i] = BaseVal;
  }

  T * rarray = Reductions<T*>::reduction_result;
  for (size_t i=0; i<nelem; i++) {
    rarray[i] = Reducer(rarray[i], val[i]);
  }

  reduction_reported_in++;
  VLOG(5) << "reported_in = " << reduction_reported_in;
  if (reduction_reported_in == SoftXMT_nodes()) {
    reduction_reported_in = 0;
    for (Node n = 0; n < SoftXMT_nodes(); n++) {
      VLOG(5) << "waking " << n;
      SoftXMT_call_on(n, &am_reduce_array_wake, rarray, sizeof(T)*nelem);
    }
    delete [] Reductions<T*>::reduction_result;
  }
}

template< typename T, T (*Reducer)(const T&, const T&) >
static void am_reduce_noinit(T * val, size_t sz, void* payload, size_t psz) {
  CHECK(SoftXMT_mynode() == HOME_NODE);

  if (reduction_reported_in == 0) Reductions<T>::reduction_result = *val; // no base val
  else Reductions<T>::reduction_result = Reducer(Reductions<T>::reduction_result, *val);

  reduction_reported_in++;
  VLOG(5) << "reported_in = " << reduction_reported_in;
  if (reduction_reported_in == SoftXMT_nodes()) {
    reduction_reported_in = 0;
    for (Node n = 0; n < SoftXMT_nodes(); n++) {
      VLOG(5) << "waking " << n;
      T data = Reductions<T>::reduction_result;
      SoftXMT_call_on(n, &am_reduce_wake, &data);
    }
  }
}

/// Global reduction across all nodes, returning the completely reduced value to everyone.
/// Notes:
///  - this suffices as a global barrier across *all nodes*
///  - as such, only one instance of this can be running at a given time
///  - and it must be called by every node or deadlock will occur
template< typename T, T (*Reducer)(const T&, const T&), T BaseVal>
T SoftXMT_allreduce(T myval) {
  // TODO: do tree reduction to reduce amount of serialization at Node 0
  reducing_thread = CURRENT_THREAD;

  SoftXMT_call_on(0, &am_reduce<T,Reducer,BaseVal>, &myval);

  SoftXMT_suspend();

  return Reductions<T>::final_reduction_result;
}

template< typename T, T (*Reducer)(const T&, const T&), T BaseVal>
void SoftXMT_allreduce(T * array, size_t nelem, T * result = NULL) {
  // default is to overwrite original array
  if (!result) result = array;
  Reductions<T*>::final_reduction_result = result;

  // TODO: do tree reduction to reduce amount of serialization at Node 0
  reducing_thread = CURRENT_THREAD;

  SoftXMT_call_on(0, &am_reduce_array<T,Reducer,BaseVal>, array, sizeof(T)*nelem);

  SoftXMT_suspend();
}

template< typename T, T (*Reducer)(const T&, const T&) >
T SoftXMT_allreduce_noinit(T myval) {
  // TODO: do tree reduction to reduce amount of serialization at Node 0
  reducing_thread = CURRENT_THREAD;

  SoftXMT_call_on(0, &am_reduce_noinit<T,Reducer>, &myval);

  SoftXMT_suspend();

  return Reductions<T>::final_reduction_result;
}

#endif // _COLLECTIVE_HPP

<commit_msg>Quick solution to larger allreduce's: serial max-size allreduce calls.<commit_after>
#ifndef _COLLECTIVE_HPP
#define _COLLECTIVE_HPP

#include "SoftXMT.hpp"
#include "ForkJoin.hpp"
#include "common.hpp"

int64_t collective_max(int64_t a, int64_t b);
int64_t collective_min(int64_t a, int64_t b);
int64_t collective_add(int64_t a, int64_t b);
int64_t collective_mult(int64_t a, int64_t b);

#define COLL_MAX &collective_max
#define COLL_MIN &collective_min
#define COLL_ADD &collective_add
#define COLL_MULT &collective_mult

int64_t SoftXMT_collective_reduce( int64_t (*commutative_func)(int64_t, int64_t), Node home_node, int64_t myValue, int64_t initialValue );

template< typename T >
inline T coll_add(const T& a, const T& b) {
  return a+b;
}

#define HOME_NODE 0
extern Thread * reducing_thread;
extern Node reduction_reported_in;

// This class is just for holding the reduction
// value in a type-safe manner
template < typename T >
class Reductions {
  private:
    Reductions() {}
  public:
    static T reduction_result;
    static T final_reduction_result;
};

template <typename T>
T Reductions<T>::reduction_result;

template <typename T>
T Reductions<T>::final_reduction_result;

template< typename T >
static void am_reduce_wake(T * val, size_t sz, void * payload, size_t psz) {
  Reductions<T>::final_reduction_result = *val;
  SoftXMT_wake(reducing_thread);
}

template< typename T >
static void am_reduce_array_wake(T * val, size_t sz, void * payload, size_t psz) {
  memcpy(Reductions<T*>::final_reduction_result, val, sz);
  SoftXMT_wake(reducing_thread);
}

template< typename T, T (*Reducer)(const T&, const T&), T BaseVal>
static void am_reduce(T * val, size_t sz, void* payload, size_t psz) {
  CHECK(SoftXMT_mynode() == HOME_NODE);

  if (reduction_reported_in == 0) Reductions<T>::reduction_result = BaseVal;
  Reductions<T>::reduction_result = Reducer(Reductions<T>::reduction_result, *val);

  reduction_reported_in++;
  VLOG(5) << "reported_in = " << reduction_reported_in;
  if (reduction_reported_in == SoftXMT_nodes()) {
    reduction_reported_in = 0;
    for (Node n = 0; n < SoftXMT_nodes(); n++) {
      VLOG(5) << "waking " << n;
      T data = Reductions<T>::reduction_result;
      SoftXMT_call_on(n, &am_reduce_wake, &data);
    }
  }
}

template< typename T, T (*Reducer)(const T&, const T&), T BaseVal>
static void am_reduce_array(T * val, size_t sz, void* payload, size_t psz) {
  CHECK(SoftXMT_mynode() == HOME_NODE);

  size_t nelem = sz / sizeof(T);

  if (reduction_reported_in == 0) {
    // allocate space for result
    Reductions<T*>::reduction_result = new T[nelem];
    for (size_t i=0; i<nelem; i++) Reductions<T*>::reduction_result[i] = BaseVal;
  }

  T * rarray = Reductions<T*>::reduction_result;
  for (size_t i=0; i<nelem; i++) {
    rarray[i] = Reducer(rarray[i], val[i]);
  }

  reduction_reported_in++;
  VLOG(5) << "reported_in = " << reduction_reported_in;
  if (reduction_reported_in == SoftXMT_nodes()) {
    reduction_reported_in = 0;
    for (Node n = 0; n < SoftXMT_nodes(); n++) {
      VLOG(5) << "waking " << n;
      SoftXMT_call_on(n, &am_reduce_array_wake, rarray, sizeof(T)*nelem);
    }
    delete [] Reductions<T*>::reduction_result;
  }
}

template< typename T, T (*Reducer)(const T&, const T&) >
static void am_reduce_noinit(T * val, size_t sz, void* payload, size_t psz) {
  CHECK(SoftXMT_mynode() == HOME_NODE);

  if (reduction_reported_in == 0) Reductions<T>::reduction_result = *val; // no base val
  else Reductions<T>::reduction_result = Reducer(Reductions<T>::reduction_result, *val);

  reduction_reported_in++;
  VLOG(5) << "reported_in = " << reduction_reported_in;
  if (reduction_reported_in == SoftXMT_nodes()) {
    reduction_reported_in = 0;
    for (Node n = 0; n < SoftXMT_nodes(); n++) {
      VLOG(5) << "waking " << n;
      T data = Reductions<T>::reduction_result;
      SoftXMT_call_on(n, &am_reduce_wake, &data);
    }
  }
}

/// Global reduction across all nodes, returning the completely reduced value to everyone.
/// Notes:
///  - this suffices as a global barrier across *all nodes*
///  - as such, only one instance of this can be running at a given time
///  - and it must be called by every node or deadlock will occur
template< typename T, T (*Reducer)(const T&, const T&), T BaseVal>
T SoftXMT_allreduce(T myval) {
  // TODO: do tree reduction to reduce amount of serialization at Node 0
  reducing_thread = CURRENT_THREAD;

  SoftXMT_call_on(0, &am_reduce<T,Reducer,BaseVal>, &myval);

  SoftXMT_suspend();

  return Reductions<T>::final_reduction_result;
}

template< typename T, T (*Reducer)(const T&, const T&), T BaseVal>
void allreduce_one_message(T * array, size_t nelem, T * result = NULL) {
  const size_t maxn = 2048 / sizeof(T);
  CHECK( nelem <= maxn );
  // default is to overwrite original array
  if (!result) result = array;
  Reductions<T*>::final_reduction_result = result;

  // TODO: do tree reduction to reduce amount of serialization at Node 0
  reducing_thread = CURRENT_THREAD;

  SoftXMT_call_on(0, &am_reduce_array<T,Reducer,BaseVal>, array, sizeof(T)*nelem);
  SoftXMT_suspend();
}

template< typename T, T (*Reducer)(const T&, const T&), T BaseVal>
void SoftXMT_allreduce(T * array, size_t nelem, T * result = NULL) {
  const size_t maxn = 2048 / sizeof(T);

  for (size_t i=0; i<nelem; i+=maxn) {
    size_t n = MIN(maxn, nelem-i);
    allreduce_one_message<T,Reducer,BaseVal>(array+i, n, result);
  }
}

template< typename T, T (*Reducer)(const T&, const T&) >
T SoftXMT_allreduce_noinit(T myval) {
  // TODO: do tree reduction to reduce amount of serialization at Node 0
  reducing_thread = CURRENT_THREAD;

  SoftXMT_call_on(0, &am_reduce_noinit<T,Reducer>, &myval);

  SoftXMT_suspend();

  return Reductions<T>::final_reduction_result;
}

#endif // _COLLECTIVE_HPP

<|endoftext|>


<commit_before>#ifndef FMO_STATS_HPP
#define FMO_STATS_HPP

#include <cstdint>
#include <vector>

namespace fmo {
    /**
     * Provides current time in the form of the number of nanoseconds relative to a specific a point
     * in time (the origin). The origin does not change during the execution of the program, which
     * makes this function viable for execution time measurements. A system clock with the best
     * precision is used. Monotonicity of the returned times is not guaranteed.
     */
    int64_t nanoTime();

    /**
     * Statistic measurements of a random variable, consisting of the 50% quantile (the median),
     * the 95% quantile, and the 99% quantile.
     */
    template <typename T>
    struct Quantiles {
        Quantiles(T in50, T in95, T in99) : q50(in50), q95(in95), q99(in99) {}
        T q50, q95, q99;
    };

    /**
     * Provides robust statistic measurements of fuzzy quantities, such as execution time. The data
     * type of the measurements is fixed to 64-bit signed integer. Use the add() method to add new
     * samples. The add() method may trigger calculation of quantiles, which are afterwards
     * retrievable using the quantiles() method.
     */
    struct Stats {
        Stats(const Stats&) = delete;

        Stats& operator=(const Stats&) = delete;

        /**
         * @param storageSize The maximum number of samples that will be retained over time. Once
         * the maximum is reached, some of the samples are removed to make space for the new ones.
         * @param sortPeriod The calculation of quantiles is triggered periodically, after the
         * specified number of samples is added.
         * @param warmUpFrames The number of initial samples that will be ignored.
         */
        Stats(size_t storageSize, int sortPeriod, int warmUpFrames);

        /**
         * Restores the object to the initial state. All samples will be removed.
         *
         * @param defVal The value to set all quantiles to.
         */
        void reset(int64_t defVal);

        /**
         * Inserts a sample to an internal vector. Each time sortPeriod (see constructor) samples
         * are added, new quantiles are calculated. This can be detected using the return value of
         * this method.
         *
         * @return True if the quantiles have just been updated. Use the quantiles() method to
         * retrieve them.
         */
        bool add(int64_t val);

        /**
         * @return The statistic measurements (quantiles) as previously calculated by the add()
         * method, or specified using the reset() method, whichever happened last.
         */
        const Quantiles<int64_t>& quantiles() const { return mQuantiles; }

    private:
        /**
         * Discard half of the elements in the underlying sorted or partially sorted vector so that
         * the statistics are not affected.
         */
        void decimate();

        const size_t mStorageSize;
        const int mSortPeriod;
        const int mWarmUpFrames;
        std::vector<int64_t> mVec;
        int mWarmUpCounter;
        Quantiles<int64_t> mQuantiles;
    };

    /**
     * A class that measures frame time and robustly estimates the frame rate in Hertz. Use the
     * tick() method to perform the measurements.
     */
    struct FrameStats {
        FrameStats();

        /**
         * Removes all previously measured values and resets all the quantiles to a given value.
         */
        void reset(float defaultHz);

        /**
         * Performs the frame time measurement. Call this method once per frame. Check the return
         * value to detect whether the quantiles have been updated during the call to this method.
         *
         * @return True if the quantiles have just been updated. Retrieve the quantiles using the
         * quantilesHz() method.
         */
        bool tick();

        /**
         * @return Quantiles, calculated previously by the tick() method, or specified by the
         * reset() method, whichever happened last.
         */
        const Quantiles<float>& quantilesHz() const { return mQuantilesHz; }

    private:
        void updateMyQuantiles();

        Stats mStats;
        int64_t mLastTimeNs;
        Quantiles<float> mQuantilesHz;
    };

    /**
     * A class that robustly estimates execution time of a repeatedly performed code section. Use
     * the start() and stop() methods to mark the beginning and the end of the evaluated code.
     */
    struct SectionStats {
        SectionStats();

        /**
         * Removes all previously measured values and resets all the quantiles to zero.
         */
        void reset();

        /**
         * To be called just before the measured section of code starts.
         */
        void start();

        /**
         * To be called as soon as the measured section of code ends. Check the return value to
         * detect whether the quantiles have been updated during the call to this method.
         *
         * @return True if the quantiles have just been updated. Retrieve the quantiles using the
         * quantilesMs() method.
         */
        bool stop();

        /**
         * @return Quantiles, calculated previously by the stop() method, or specified by the
         * reset() method, whichever happened last.
         */
        const Quantiles<float>& quantilesMs() const { return mQuantilesMs; }

    private:
        void updateMyQuantiles();

        Stats mStats;
        int64_t mStartTimeNs;
        Quantiles<float> mQuantilesMs;
    };
}

#endif // FMO_STATS_HPP
<commit_msg>Implement NanoCast, Timer<commit_after>#ifndef FMO_STATS_HPP
#define FMO_STATS_HPP

#include <cstdint>
#include <vector>

namespace fmo {
    /**
     * Provides current time in the form of the number of nanoseconds relative to a specific a point
     * in time (the origin). The origin does not change during the execution of the program, which
     * makes this function viable for execution time measurements. A system clock with the best
     * precision is used. Monotonicity of the returned times is not guaranteed.
     */
    int64_t nanoTime();

    /**
     * Lists all supported units for display.
     */
    enum class TimeUnit { NS, MS, SEC, HZ };

    /**
     * Allows to convert nanoseconds to another time unit. The conversion involves a double
     * division, therefore beware of a performance hit if used too often.
     */
    template <TimeUnit TU, typename T>
    struct NanoCast;
    template <typename T>
    struct NanoCast<TimeUnit::NS, T> {
        T operator()(int64_t ns) { return static_cast<T>(ns); }
    };
    template <typename T>
    struct NanoCast<TimeUnit::MS, T> {
        T operator()(int64_t ns) { return static_cast<T>(ns / 1e6); }
    };
    template <typename T>
    struct NanoCast<TimeUnit::SEC, T> {
        T operator()(int64_t ns) { return static_cast<T>(ns / 1e9); }
    };
    template <typename T>
    struct NanoCast<TimeUnit::HZ, T> {
        T operator()(int64_t ns) { return static_cast<T>(1e9 / ns); }
    };

    /**
     * Allows to measure time in seconds.
     */
    struct Timer {
        Timer() : mTicNs(nanoTime()) {}

        /**
         * Call at the start of the measured segment.
         */
        void tic() { mTicNs = nanoTime(); }

        /**
         * Call at the end of the measured segment. Returns measured time since the last call to
         * tic() or the construction, whichever happened most recently.
         */
        template <TimeUnit TU, typename T>
        T toc() {
            int64_t delta = nanoTime() - mTicNs;
            mTocSec = NanoCast<TU, T>{}(delta);
            return mTocSec;
        }

    private:
        int64_t mTicNs;
    };

    /**
     * Statistic measurements of a random variable, consisting of the 50% quantile (the median),
     * the 95% quantile, and the 99% quantile.
     */
    template <typename T>
    struct Quantiles {
        Quantiles(T in50, T in95, T in99) : q50(in50), q95(in95), q99(in99) {}
        T q50, q95, q99;
    };

    /**
     * Provides robust statistic measurements of fuzzy quantities, such as execution time. The data
     * type of the measurements is fixed to 64-bit signed integer. Use the add() method to add new
     * samples. The add() method may trigger calculation of quantiles, which are afterwards
     * retrievable using the quantiles() method.
     */
    struct Stats {
        Stats(const Stats&) = delete;

        Stats& operator=(const Stats&) = delete;

        /**
         * @param storageSize The maximum number of samples that will be retained over time. Once
         * the maximum is reached, some of the samples are removed to make space for the new ones.
         * @param sortPeriod The calculation of quantiles is triggered periodically, after the
         * specified number of samples is added.
         * @param warmUpFrames The number of initial samples that will be ignored.
         */
        Stats(size_t storageSize, int sortPeriod, int warmUpFrames);

        /**
         * Restores the object to the initial state. All samples will be removed.
         *
         * @param defVal The value to set all quantiles to.
         */
        void reset(int64_t defVal);

        /**
         * Inserts a sample to an internal vector. Each time sortPeriod (see constructor) samples
         * are added, new quantiles are calculated. This can be detected using the return value of
         * this method.
         *
         * @return True if the quantiles have just been updated. Use the quantiles() method to
         * retrieve them.
         */
        bool add(int64_t val);

        /**
         * @return The statistic measurements (quantiles) as previously calculated by the add()
         * method, or specified using the reset() method, whichever happened last.
         */
        const Quantiles<int64_t>& quantiles() const { return mQuantiles; }

    private:
        /**
         * Discard half of the elements in the underlying sorted or partially sorted vector so that
         * the statistics are not affected.
         */
        void decimate();

        const size_t mStorageSize;
        const int mSortPeriod;
        const int mWarmUpFrames;
        std::vector<int64_t> mVec;
        int mWarmUpCounter;
        Quantiles<int64_t> mQuantiles;
    };

    /**
     * A class that measures frame time and robustly estimates the frame rate in Hertz. Use the
     * tick() method to perform the measurements.
     */
    struct FrameStats {
        FrameStats();

        /**
         * Removes all previously measured values and resets all the quantiles to a given value.
         */
        void reset(float defaultHz);

        /**
         * Performs the frame time measurement. Call this method once per frame. Check the return
         * value to detect whether the quantiles have been updated during the call to this method.
         *
         * @return True if the quantiles have just been updated. Retrieve the quantiles using the
         * quantilesHz() method.
         */
        bool tick();

        /**
         * @return Quantiles, calculated previously by the tick() method, or specified by the
         * reset() method, whichever happened last.
         */
        const Quantiles<float>& quantilesHz() const { return mQuantilesHz; }

    private:
        void updateMyQuantiles();

        Stats mStats;
        int64_t mLastTimeNs;
        Quantiles<float> mQuantilesHz;
    };

    /**
     * A class that robustly estimates execution time of a repeatedly performed code section. Use
     * the start() and stop() methods to mark the beginning and the end of the evaluated code.
     */
    struct SectionStats {
        SectionStats();

        /**
         * Removes all previously measured values and resets all the quantiles to zero.
         */
        void reset();

        /**
         * To be called just before the measured section of code starts.
         */
        void start();

        /**
         * To be called as soon as the measured section of code ends. Check the return value to
         * detect whether the quantiles have been updated during the call to this method.
         *
         * @return True if the quantiles have just been updated. Retrieve the quantiles using the
         * quantilesMs() method.
         */
        bool stop();

        /**
         * @return Quantiles, calculated previously by the stop() method, or specified by the
         * reset() method, whichever happened last.
         */
        const Quantiles<float>& quantilesMs() const { return mQuantilesMs; }

    private:
        void updateMyQuantiles();

        Stats mStats;
        int64_t mStartTimeNs;
        Quantiles<float> mQuantilesMs;
    };
}

#endif // FMO_STATS_HPP
<|endoftext|>


<commit_before>#include <nonius/main.h++>

#include <string>
#include <vector>

NONIUS_BENCHMARK("construct small", [](nonius::chronometer meter)
{
    std::vector<nonius::storage_for<std::string>> storage(meter.runs());
    meter.measure([&](int i) { storage[i].construct("small"); });
})

NONIUS_BENCHMARK("construct large", [](nonius::chronometer meter)
{
    std::vector<nonius::storage_for<std::string>> storage(meter.runs());
    meter.measure([&](int i) { storage[i].construct("It was big. Really, really big. No, bigger than that. Even bigger. Keep going. More. No, more. Look, we're talking krakens and dreadnoughts for jewelry. It was big!"); });
})

NONIUS_BENCHMARK("destroy small", [](nonius::chronometer meter)
{
    std::vector<nonius::destructable_object<std::string>> storage(meter.runs());
    std::for_each(storage.begin(), storage.end(), [](nonius::destructable_object<std::string>& object) { object.construct("small"); });
    meter.measure([&](int i) { storage[i].destruct(); });
})

NONIUS_BENCHMARK("destroy large", [](nonius::chronometer meter)
{
    std::vector<nonius::destructable_object<std::string>> storage(meter.runs());
    std::for_each(storage.begin(), storage.end(), [](nonius::destructable_object<std::string>& object) { object.construct("It was big. Really, really big. No, bigger than that. Even bigger. Keep going. More. No, more. Look, we're talking krakens and dreadnoughts for jewelry. It was big!"); });
    meter.measure([&](int i) { storage[i].destruct(); });
})
<commit_msg>Range-based for > std::foreach<commit_after>#include <nonius/main.h++>

#include <string>
#include <vector>

NONIUS_BENCHMARK("construct small", [](nonius::chronometer meter)
{
    std::vector<nonius::storage_for<std::string>> storage(meter.runs());
    meter.measure([&](int i) { storage[i].construct("small"); });
})

NONIUS_BENCHMARK("construct large", [](nonius::chronometer meter)
{
    std::vector<nonius::storage_for<std::string>> storage(meter.runs());
    meter.measure([&](int i) { storage[i].construct("It was big. Really, really big. No, bigger than that. Even bigger. Keep going. More. No, more. Look, we're talking krakens and dreadnoughts for jewelry. It was big!"); });
})

NONIUS_BENCHMARK("destroy small", [](nonius::chronometer meter)
{
    std::vector<nonius::destructable_object<std::string>> storage(meter.runs());
    for(auto&& o : storage)
        o.construct("small");
    meter.measure([&](int i) { storage[i].destruct(); });
})

NONIUS_BENCHMARK("destroy large", [](nonius::chronometer meter)
{
    std::vector<nonius::destructable_object<std::string>> storage(meter.runs());
    for(auto&& o : storage)
        o.construct("It was big. Really, really big. No, bigger than that. Even bigger. Keep going. More. No, more. Look, we're talking krakens and dreadnoughts for jewelry. It was big!");
    meter.measure([&](int i) { storage[i].destruct(); });
})
<|endoftext|>


<commit_before>#include <iostream>
#include <ctime>
#include <QCPP.h>

int main() {

	// make it more non-deterministic
	srand(time(NULL));

	// initialize Quantum state with 5 qubits
	Quantum qubits(5);

	// turns all qubits into every state with same probabilities
	qubits.Hadamard(0, 1, 2, 3, 4);
	// or
	// for(int i = 0;i < qubits.size();i++) qubits.Hadamard(i);
	// or
	// qubits.Hadamard({0, 1, 2, 3, 4});
	// would result the same

	// the possibility should be the same
	for(int i = 0;i < (1 << qubits.size());i++) {
		std::cout << "Probabilities of being " << i << " : " << qubits.getProbability(i) << std::endl;
	}

	// try to observe
	for(int i = 0;i < 10;i++) {
		std::cout << "State of qubits : " << qubits.getState() << std::endl;
	}

	return 0;
}<commit_msg>Fix functions' names according to last change<commit_after>#include <iostream>
#include <ctime>
#include <QCPP.h>

int main() {

	// make it more non-deterministic
	srand(time(NULL));

	// initialize Quantum state with 5 qubits
	Quantum qubits(5);

	// turns all qubits into every state with same probabilities
	qubits.hadamard(0, 1, 2, 3, 4);
	// or
	// for(int i = 0;i < qubits.size();i++) qubits.Hadamard(i);
	// or
	// qubits.hadamard({0, 1, 2, 3, 4});
	// would result the same

	// the possibility should be the same
	for(int i = 0;i < (1 << qubits.size());i++) {
		std::cout << "Probabilities of being " << i << " : " << qubits.getProbability(i) << std::endl;
	}

	// try to observe
	for(int i = 0;i < 10;i++) {
		std::cout << "State of qubits : " << qubits.getState() << std::endl;
	}

	return 0;
}<|endoftext|>