<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "AutowiringDebug.h"
#include "Autowired.h"
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <sstream>

using namespace autowiring;
using namespace autowiring::dbg;

#ifdef _MSC_VER
// On Windows, lambda functions start with the key string "class <"
bool autowiring::dbg::IsLambda(const std::type_info& ti) {
  return demangle(ti)[0] == '<';
}
#else
// On other platforms, try to find lambda functions by the presence of forbidden characters
bool autowiring::dbg::IsLambda(const std::type_info& ti) {
  auto name = demangle(ti);
  for (auto cur : name)
    if (
      !('a' <= cur && cur <= 'z') &&
      !('A' <= cur && cur <= 'Z') &&
      !('0' <= cur && cur <= '9') &&
      cur != '_' &&
      cur != ':' &&
      cur != '<' &&
      cur != '>' &&
      cur != ',' &&
      cur != ' '
    )
      return true;
  return false;
}
#endif

static std::string DemangleWithAutoID(const std::type_info& ti) {
  auto retVal = demangle(ti);

  // prefix is at the beginning of the string, skip over it
  static const char prefix [] = "auto_id<";

  if (retVal.compare(0, sizeof(prefix) - 1, prefix) == 0) {
    size_t off = sizeof(prefix) - 1;
    size_t end = retVal.find_last_not_of(' ', retVal.find_last_of('>') - 1);
    retVal = retVal.substr(off, end - off + 1);
  }
  return retVal;
}

std::string autowiring::dbg::ContextName(void) {
  AutoCurrentContext ctxt;
  return autowiring::demangle(ctxt->GetSigilType());
}

void PrintContextTreeRecursive(std::ostream& os, std::shared_ptr<CoreContext> ctxt) {
  // Initialize this only once
  AutoCurrentContext curCtxt;

  for (; ctxt; ctxt = ctxt->NextSibling()) {

    // Create of vector of contexts from child of global to 'ctxt'
    std::deque<std::shared_ptr<CoreContext>> path;
    for (auto c = ctxt; !c->IsGlobalContext(); c = c->GetParentContext()) {
      path.push_front(c);
    }

    // Print indentation the shows 'ctxt's path in the tree
    for (auto it = path.begin(); it != path.end(); ++it)
      if (std::next(it) == path.end()) // Check if last element
        if ((*it)->NextSibling())
          os << "├── ";
        else
          os << "└── ";
      else if ((*it)->NextSibling()) // If not the last child
        os << "│   ";
      else
        os << "    ";

    // Print context name
    os << autowiring::demangle(ctxt->GetSigilType());
    if (ctxt == curCtxt) {
      os << "(Current Context)";
    }
    os << std::endl;
    PrintContextTreeRecursive(os, ctxt->FirstChild());
  }
}

void autowiring::dbg::PrintContextTree(std::ostream& os) {
  PrintContextTreeRecursive(os, AutoGlobalContext());
}

void autowiring::dbg::PrintContextTree(void) {
  PrintContextTreeRecursive(std::cout, AutoGlobalContext());
}

AutoPacket* autowiring::dbg::CurrentPacket(void) {
  Autowired<AutoPacketFactory> factory;
  if (!factory)
    return nullptr;
  return factory->CurrentPacket().get();
}

static const AutoFilterDescriptor* DescriptorByName(const char* name, const std::vector<AutoFilterDescriptor>& filters) {
  for (const auto& filter : filters) {
    auto type = filter.GetType();
    if (!type)
      continue;

    auto curName = demangle(type);
    if (!curName.compare(name))
      return &filter;
  }
  return nullptr;
}

const AutoFilterDescriptor* autowiring::dbg::DescriptorByName(const char* name) {
  Autowired<AutoPacketFactory> factory;
  if (!factory)
    return nullptr;

  return DescriptorByName(name, factory->GetAutoFilters());
}

std::string autowiring::dbg::AutoFilterInfo(const char* name) {
  Autowired<AutoPacketFactory> factory;
  if (!factory)
    return "No factory detected in this context";

  // Obtain all descriptors:
  const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters();

  // Need the root descriptor first
  const AutoFilterDescriptor* desc = DescriptorByName(name, descs);
  if (!desc)
    return "Filter not found";

  std::ostringstream os;
  std::function<void(const AutoFilterDescriptor&, int)> fnCall = [&](const AutoFilterDescriptor& desc, size_t nLevels) {
    auto args = desc.GetAutoFilterArguments();

    for (size_t i = 0; i < desc.GetArity(); i++) {
      // Argument must be an input to the filter we want to know more about
      if (!args[i].is_input)
        continue;

      // Who provides this input?
      for (const auto& providerDesc : descs) {
        auto providerArg = providerDesc.GetArgumentType(args[i].ti);
        if (providerArg && providerArg->is_output) {
          // Need to print information about this provider:
          os << demangle(*args[i].ti) << ' ' << std::string(' ', nLevels) << demangle(*providerDesc.GetType()) << std::endl;

          // The current descriptor provides an input to the parent, recurse
          fnCall(providerDesc, nLevels + 1);
        }
      }
    }
  };

  // Root typename print first:
  os << demangle(desc->GetType()) << std::endl;
  fnCall(*desc, 1);

  auto retVal = os.str();
  return retVal;
}

std::vector<std::string> autowiring::dbg::ListRootDecorations(void) {
  Autowired<AutoPacketFactory> factory;
  if (!factory)
    return std::vector<std::string>{};

  // Obtain all descriptors:
  const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters();

  // Get all baseline descriptor types, figure out what isn't satisfied:
  std::unordered_map<std::type_index, const std::type_info*> outputs;
  std::unordered_map<std::type_index, const std::type_info*> inputs;

  for (const auto& desc : descs) {
    auto args = desc.GetAutoFilterArguments();
    for (size_t i = 0; i < desc.GetArity(); i++)
      (args[i].is_output ? outputs : inputs)[*args[i].ti] = args[i].ti;
  }

  // Remove all inputs that exist in the outputs set:
  for (auto& output : outputs)
    inputs.erase(*output.second);

  // Any remaining inputs are unsatisfied
  std::vector<std::string> retVal;
  for (auto& input : inputs)
    if (input.second)
      retVal.push_back(DemangleWithAutoID(*input.second));
  return retVal;
}

void autowiring::dbg::WriteAutoFilterGraph(std::ostream& os) {
  WriteAutoFilterGraph(os, AutoCurrentContext());
}

std::string WriteAutoFilterGraph(void) {
  std::stringstream ss;
  WriteAutoFilterGraph(ss);
  return ss.str();
}

void autowiring::dbg::WriteAutoFilterGraph(std::ostream& os, std::shared_ptr<CoreContext> ctxt) {
  CurrentContextPusher pshr(ctxt);
  Autowired<AutoPacketFactory> factory;

  // Write opening and closing parts of file. Now, we only need to write edges
  os << "digraph " << autowiring::demangle(ctxt->GetSigilType()) << " {" << std::endl;
  auto exit = MakeAtExit([&os]{
    os << "}" << std::endl;
  });

  // If no factory, this is an empty network
  if (!factory) {
    return;
  }

  // Obtain all descriptors:
  const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters();

  std::unordered_map<std::string, int> decorations; // demangled name to ID
  std::unordered_map<std::string, int> filters; // demangled name to ID

  // give each node a unique id
  int idCounter = 0;

  for (const auto& desc : descs) {
    std::string filter = autowiring::demangle(desc.GetType());

    // Assign each filter an ID
    if (filters.find(filter) == filters.end()) {
      filters[filter] = idCounter++;
    }

    auto args = desc.GetAutoFilterArguments();
    for (size_t i = 0; i < desc.GetArity(); i++) {
      const AutoFilterArgument& arg = args[i];

      std::string decoration = DemangleWithAutoID(*arg.ti);

      // Assign each decoration and ID
      if (decorations.find(decoration) == decorations.end()) {
        decorations[decoration] = idCounter++;
      }

      // Add edge
      if (arg.is_input) {
        os << decorations[decoration] << " -> " << filters[filter];
      } else {
        os << filters[filter] << " -> " << decorations[decoration];
      }

      // Label time shifted edges
      if (arg.tshift) {
        os << " [style=dotted label=\"prev=" << arg.tshift << "\"]";
      }

      os << std::endl;
    }
  }

  // Label each filter with its demangled name
  for (const auto& filter : filters) {
    const std::string& name = filter.first;
    int id = filter.second;

    os << id << " [shape=box label=\""<< name << "\"];" << std::endl;
  }

  // Label each decoration with its demangled name
  for (const auto& decoration : decorations) {
    const std::string& name = decoration.first;
    int id = decoration.second;

    os << id << " [shape=oval label=\""<< name << "\"];" << std::endl;
  }
}

void autowiring::dbg::DebugInit(void) {

}<commit_msg>Fix conversion warnings<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "AutowiringDebug.h"
#include "Autowired.h"
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <sstream>

using namespace autowiring;
using namespace autowiring::dbg;

#ifdef _MSC_VER
// On Windows, lambda functions start with the key string "class <"
bool autowiring::dbg::IsLambda(const std::type_info& ti) {
  return demangle(ti)[0] == '<';
}
#else
// On other platforms, try to find lambda functions by the presence of forbidden characters
bool autowiring::dbg::IsLambda(const std::type_info& ti) {
  auto name = demangle(ti);
  for (auto cur : name)
    if (
      !('a' <= cur && cur <= 'z') &&
      !('A' <= cur && cur <= 'Z') &&
      !('0' <= cur && cur <= '9') &&
      cur != '_' &&
      cur != ':' &&
      cur != '<' &&
      cur != '>' &&
      cur != ',' &&
      cur != ' '
    )
      return true;
  return false;
}
#endif

static std::string DemangleWithAutoID(const std::type_info& ti) {
  auto retVal = demangle(ti);

  // prefix is at the beginning of the string, skip over it
  static const char prefix [] = "auto_id<";

  if (retVal.compare(0, sizeof(prefix) - 1, prefix) == 0) {
    size_t off = sizeof(prefix) - 1;
    size_t end = retVal.find_last_not_of(' ', retVal.find_last_of('>') - 1);
    retVal = retVal.substr(off, end - off + 1);
  }
  return retVal;
}

std::string autowiring::dbg::ContextName(void) {
  AutoCurrentContext ctxt;
  return autowiring::demangle(ctxt->GetSigilType());
}

void PrintContextTreeRecursive(std::ostream& os, std::shared_ptr<CoreContext> ctxt) {
  // Initialize this only once
  AutoCurrentContext curCtxt;

  for (; ctxt; ctxt = ctxt->NextSibling()) {

    // Create of vector of contexts from child of global to 'ctxt'
    std::deque<std::shared_ptr<CoreContext>> path;
    for (auto c = ctxt; !c->IsGlobalContext(); c = c->GetParentContext()) {
      path.push_front(c);
    }

    // Print indentation the shows 'ctxt's path in the tree
    for (auto it = path.begin(); it != path.end(); ++it)
      if (std::next(it) == path.end()) // Check if last element
        if ((*it)->NextSibling())
          os << "├── ";
        else
          os << "└── ";
      else if ((*it)->NextSibling()) // If not the last child
        os << "│   ";
      else
        os << "    ";

    // Print context name
    os << autowiring::demangle(ctxt->GetSigilType());
    if (ctxt == curCtxt) {
      os << "(Current Context)";
    }
    os << std::endl;
    PrintContextTreeRecursive(os, ctxt->FirstChild());
  }
}

void autowiring::dbg::PrintContextTree(std::ostream& os) {
  PrintContextTreeRecursive(os, AutoGlobalContext());
}

void autowiring::dbg::PrintContextTree(void) {
  PrintContextTreeRecursive(std::cout, AutoGlobalContext());
}

AutoPacket* autowiring::dbg::CurrentPacket(void) {
  Autowired<AutoPacketFactory> factory;
  if (!factory)
    return nullptr;
  return factory->CurrentPacket().get();
}

static const AutoFilterDescriptor* DescriptorByName(const char* name, const std::vector<AutoFilterDescriptor>& filters) {
  for (const auto& filter : filters) {
    auto type = filter.GetType();
    if (!type)
      continue;

    auto curName = demangle(type);
    if (!curName.compare(name))
      return &filter;
  }
  return nullptr;
}

const AutoFilterDescriptor* autowiring::dbg::DescriptorByName(const char* name) {
  Autowired<AutoPacketFactory> factory;
  if (!factory)
    return nullptr;

  return DescriptorByName(name, factory->GetAutoFilters());
}

std::string autowiring::dbg::AutoFilterInfo(const char* name) {
  Autowired<AutoPacketFactory> factory;
  if (!factory)
    return "No factory detected in this context";

  // Obtain all descriptors:
  const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters();

  // Need the root descriptor first
  const AutoFilterDescriptor* desc = DescriptorByName(name, descs);
  if (!desc)
    return "Filter not found";

  std::ostringstream os;
  std::function<void(const AutoFilterDescriptor&, size_t)> fnCall = [&](const AutoFilterDescriptor& desc, size_t nLevels) {
    auto args = desc.GetAutoFilterArguments();

    for (size_t i = 0; i < desc.GetArity(); i++) {
      // Argument must be an input to the filter we want to know more about
      if (!args[i].is_input)
        continue;

      // Who provides this input?
      for (const auto& providerDesc : descs) {
        auto providerArg = providerDesc.GetArgumentType(args[i].ti);
        if (providerArg && providerArg->is_output) {
          // Need to print information about this provider:
          os << demangle(*args[i].ti) << ' ' << std::string(nLevels, ' ') << demangle(*providerDesc.GetType()) << std::endl;

          // The current descriptor provides an input to the parent, recurse
          fnCall(providerDesc, nLevels + 1);
        }
      }
    }
  };

  // Root typename print first:
  os << demangle(desc->GetType()) << std::endl;
  fnCall(*desc, 1);

  auto retVal = os.str();
  return retVal;
}

std::vector<std::string> autowiring::dbg::ListRootDecorations(void) {
  Autowired<AutoPacketFactory> factory;
  if (!factory)
    return std::vector<std::string>{};

  // Obtain all descriptors:
  const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters();

  // Get all baseline descriptor types, figure out what isn't satisfied:
  std::unordered_map<std::type_index, const std::type_info*> outputs;
  std::unordered_map<std::type_index, const std::type_info*> inputs;

  for (const auto& desc : descs) {
    auto args = desc.GetAutoFilterArguments();
    for (size_t i = 0; i < desc.GetArity(); i++)
      (args[i].is_output ? outputs : inputs)[*args[i].ti] = args[i].ti;
  }

  // Remove all inputs that exist in the outputs set:
  for (auto& output : outputs)
    inputs.erase(*output.second);

  // Any remaining inputs are unsatisfied
  std::vector<std::string> retVal;
  for (auto& input : inputs)
    if (input.second)
      retVal.push_back(DemangleWithAutoID(*input.second));
  return retVal;
}

void autowiring::dbg::WriteAutoFilterGraph(std::ostream& os) {
  WriteAutoFilterGraph(os, AutoCurrentContext());
}

std::string WriteAutoFilterGraph(void) {
  std::stringstream ss;
  WriteAutoFilterGraph(ss);
  return ss.str();
}

void autowiring::dbg::WriteAutoFilterGraph(std::ostream& os, std::shared_ptr<CoreContext> ctxt) {
  CurrentContextPusher pshr(ctxt);
  Autowired<AutoPacketFactory> factory;

  // Write opening and closing parts of file. Now, we only need to write edges
  os << "digraph " << autowiring::demangle(ctxt->GetSigilType()) << " {" << std::endl;
  auto exit = MakeAtExit([&os]{
    os << "}" << std::endl;
  });

  // If no factory, this is an empty network
  if (!factory) {
    return;
  }

  // Obtain all descriptors:
  const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters();

  std::unordered_map<std::string, int> decorations; // demangled name to ID
  std::unordered_map<std::string, int> filters; // demangled name to ID

  // give each node a unique id
  int idCounter = 0;

  for (const auto& desc : descs) {
    std::string filter = autowiring::demangle(desc.GetType());

    // Assign each filter an ID
    if (filters.find(filter) == filters.end()) {
      filters[filter] = idCounter++;
    }

    auto args = desc.GetAutoFilterArguments();
    for (size_t i = 0; i < desc.GetArity(); i++) {
      const AutoFilterArgument& arg = args[i];

      std::string decoration = DemangleWithAutoID(*arg.ti);

      // Assign each decoration and ID
      if (decorations.find(decoration) == decorations.end()) {
        decorations[decoration] = idCounter++;
      }

      // Add edge
      if (arg.is_input) {
        os << decorations[decoration] << " -> " << filters[filter];
      } else {
        os << filters[filter] << " -> " << decorations[decoration];
      }

      // Label time shifted edges
      if (arg.tshift) {
        os << " [style=dotted label=\"prev=" << arg.tshift << "\"]";
      }

      os << std::endl;
    }
  }

  // Label each filter with its demangled name
  for (const auto& filter : filters) {
    const std::string& name = filter.first;
    int id = filter.second;

    os << id << " [shape=box label=\""<< name << "\"];" << std::endl;
  }

  // Label each decoration with its demangled name
  for (const auto& decoration : decorations) {
    const std::string& name = decoration.first;
    int id = decoration.second;

    os << id << " [shape=oval label=\""<< name << "\"];" << std::endl;
  }
}

void autowiring::dbg::DebugInit(void) {

}<|endoftext|>


<commit_before>#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){
    ofSetVerticalSync(true);

    //  Load STUFF
    //
    calibration.setup();
    imageQueue.setup();

    shoeModel.loadModel("models/LOCKED_SHOE_ROTATION.obj");
    terrainModel.loadModel("models/LOCKED_TERRAFORM.obj");

    //  Initialize the Render
    //
    renderEngine = new RenderRadar();

    imageQueue.renderEngine = renderEngine;

    renderEngine->shoeMesh = shoeModel.getMesh(0);
    renderEngine->terrainMesh = terrainModel.getMesh(0);

    ofLoadImage(renderEngine->terrainDepthMap, "models/terrainDepthMap.png");
    ofLoadImage(renderEngine->terrainNormalMap, "models/terrainNormalMap.png");
    renderEngine->terrainResolution = renderEngine->terrainDepthMap.getWidth();

	renderEngine->setup();
    renderEngine->setImageQueue(&imageQueue);
    renderEngine->setCalibration(&calibration);

    //  Ready to go
    //
	renderEngine->play();
    imageQueue.transitionToNextItem();

    normalMap.allocate(renderEngine->terrainResolution,renderEngine->terrainResolution);
}

//--------------------------------------------------------------
void ofApp::update(){
    imageQueue.update();
}

//--------------------------------------------------------------
void ofApp::draw(){

}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}
<commit_msg>new obj file<commit_after>#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){
    ofSetVerticalSync(true);

    //  Load STUFF
    //
    calibration.setup();
    imageQueue.setup();

    shoeModel.loadModel("models/LOCKED_SHOE_ROTATION.obj");
    terrainModel.loadModel("models/LOCKED_TERRAFORM_002.obj");

    //  Initialize the Render
    //
    renderEngine = new RenderRadar();

    imageQueue.renderEngine = renderEngine;

    renderEngine->shoeMesh = shoeModel.getMesh(0);
    renderEngine->terrainMesh = terrainModel.getMesh(0);

    ofLoadImage(renderEngine->terrainDepthMap, "models/terrainDepthMap.png");
    ofLoadImage(renderEngine->terrainNormalMap, "models/terrainNormalMap.png");
    renderEngine->terrainResolution = renderEngine->terrainDepthMap.getWidth();

	renderEngine->setup();
    renderEngine->setImageQueue(&imageQueue);
    renderEngine->setCalibration(&calibration);

    //  Ready to go
    //
	renderEngine->play();
    imageQueue.transitionToNextItem();

    normalMap.allocate(renderEngine->terrainResolution,renderEngine->terrainResolution);
}

//--------------------------------------------------------------
void ofApp::update(){
    imageQueue.update();
}

//--------------------------------------------------------------
void ofApp::draw(){

}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}
<|endoftext|>


<commit_before>// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>

#include <libmesh/vector_value.h>

#include "type_vector_test.h"

using namespace libMesh;

#define VECTORVALUETEST                         \
  TYPEVECTORTEST                                \
  CPPUNIT_TEST( testScalarInit );               \

class RealVectorValueTest : public TypeVectorTestBase<VectorValue<Real> > {
public:
  CPPUNIT_TEST_SUITE( RealVectorValueTest );

  VECTORVALUETEST

  CPPUNIT_TEST_SUITE_END();
};

class NumberVectorValueTest : public TypeVectorTestBase<VectorValue<Number> > {
public:
  CPPUNIT_TEST_SUITE( NumberVectorValueTest );

  VECTORVALUETEST

  CPPUNIT_TEST_SUITE_END();
};

CPPUNIT_TEST_SUITE_REGISTRATION( RealVectorValueTest );
CPPUNIT_TEST_SUITE_REGISTRATION( NumberVectorValueTest );
<commit_msg>Always test VectorValue<Complex><commit_after>// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>

#include <libmesh/vector_value.h>

#include "type_vector_test.h"

using namespace libMesh;

#define VECTORVALUETEST                         \
  TYPEVECTORTEST                                \
  CPPUNIT_TEST( testScalarInit );               \

class RealVectorValueTest : public TypeVectorTestBase<VectorValue<Real> > {
public:
  CPPUNIT_TEST_SUITE( RealVectorValueTest );

  VECTORVALUETEST

  CPPUNIT_TEST_SUITE_END();
};

class NumberVectorValueTest : public TypeVectorTestBase<VectorValue<Number> > {
public:
  CPPUNIT_TEST_SUITE( NumberVectorValueTest );

  VECTORVALUETEST

  CPPUNIT_TEST_SUITE_END();
};

class ComplexVectorValueTest : public TypeVectorTestBase<VectorValue<Complex> > {
public:
  CPPUNIT_TEST_SUITE( NumberVectorValueTest );

  VECTORVALUETEST

  CPPUNIT_TEST_SUITE_END();
};

CPPUNIT_TEST_SUITE_REGISTRATION( RealVectorValueTest );
CPPUNIT_TEST_SUITE_REGISTRATION( NumberVectorValueTest );
CPPUNIT_TEST_SUITE_REGISTRATION( ComplexVectorValueTest );
<|endoftext|>


<commit_before>#include "test_comm.h"

// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>

#include <libmesh/parallel.h>
#include <libmesh/null_output_iterator.h>

#include <vector>

namespace libMesh {
namespace Parallel {
template <typename T>
class Packing<std::basic_string<T> > {
public:

  static const unsigned int size_bytes = 4;

  typedef T buffer_type;

static unsigned int get_string_len
  (typename std::vector<T>::const_iterator in)
{
  unsigned int string_len = in[size_bytes-1];
  for (signed int i=size_bytes-2; i >= 0; --i)
    {
      string_len *= 256;
      string_len += in[i];
    }
  return string_len;
}

static unsigned int packed_size
  (typename std::vector<T>::const_iterator in)
{
  return get_string_len(in) + size_bytes;
}

static unsigned int packable_size
  (const std::basic_string<T> & s,
   const void *)
{
  return s.size() + size_bytes;
}

template <typename Iter>
static void pack (const std::basic_string<T> & b, Iter data_out,
                  const void * f)
{
  unsigned int string_len = b.size();
  for (unsigned int i=0; i != size_bytes; ++i)
    {
      *data_out++ = (string_len % 256);
      string_len /= 256;
    }
  std::copy(b.begin(), b.end(), data_out);
}

static std::basic_string<T> unpack
  (typename std::vector<T>::const_iterator in, void * f)
{
  unsigned int string_len = get_string_len(in);

  std::ostringstream oss;
  for (unsigned int i = 0; i < string_len; ++i)
    oss << static_cast<char>(in[i+size_bytes]);

  in += size_bytes + string_len;

//  std::cout << oss.str() << std::endl;
  return std::string(oss.str());
}

};

} // namespace Parallel

} // namespace libMesh

using namespace libMesh;

class PackedRangeTest : public CppUnit::TestCase {
public:
  CPPUNIT_TEST_SUITE( PackedRangeTest );

  CPPUNIT_TEST( testNullAllGather );
//  CPPUNIT_TEST( testNullSendReceive );
//  CPPUNIT_TEST( testAdapterSendReceive );
//  CPPUNIT_TEST( testPointerAdapterSendReceive );

  CPPUNIT_TEST_SUITE_END();

private:

public:
  void setUp()
  {}

  void tearDown()
  {}

  void testNullAllGather()
  {
    std::vector<processor_id_type> vals;

    std::vector<std::string> send(1);
    if (TestCommWorld->rank() == 0)
      send[0].assign("Hello");
    else
      send[0].assign("Goodbye");

    TestCommWorld->allgather_packed_range
      ((void *)(NULL), send.begin(), send.end(),
       libMesh::null_output_iterator<std::string>());
  }

};

CPPUNIT_TEST_SUITE_REGISTRATION( PackedRangeTest );
<commit_msg>Fix unused variable warnings<commit_after>#include "test_comm.h"

// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>

#include <libmesh/parallel.h>
#include <libmesh/null_output_iterator.h>

#include <vector>

namespace libMesh {
namespace Parallel {
template <typename T>
class Packing<std::basic_string<T> > {
public:

  static const unsigned int size_bytes = 4;

  typedef T buffer_type;

static unsigned int get_string_len
  (typename std::vector<T>::const_iterator in)
{
  unsigned int string_len = in[size_bytes-1];
  for (signed int i=size_bytes-2; i >= 0; --i)
    {
      string_len *= 256;
      string_len += in[i];
    }
  return string_len;
}

static unsigned int packed_size
  (typename std::vector<T>::const_iterator in)
{
  return get_string_len(in) + size_bytes;
}

static unsigned int packable_size
  (const std::basic_string<T> & s,
   const void *)
{
  return s.size() + size_bytes;
}

template <typename Iter>
static void pack (const std::basic_string<T> & b, Iter data_out,
                  const void *)
{
  unsigned int string_len = b.size();
  for (unsigned int i=0; i != size_bytes; ++i)
    {
      *data_out++ = (string_len % 256);
      string_len /= 256;
    }
  std::copy(b.begin(), b.end(), data_out);
}

static std::basic_string<T> unpack
  (typename std::vector<T>::const_iterator in, void *)
{
  unsigned int string_len = get_string_len(in);

  std::ostringstream oss;
  for (unsigned int i = 0; i < string_len; ++i)
    oss << static_cast<char>(in[i+size_bytes]);

  in += size_bytes + string_len;

//  std::cout << oss.str() << std::endl;
  return std::string(oss.str());
}

};

} // namespace Parallel

} // namespace libMesh

using namespace libMesh;

class PackedRangeTest : public CppUnit::TestCase {
public:
  CPPUNIT_TEST_SUITE( PackedRangeTest );

  CPPUNIT_TEST( testNullAllGather );
//  CPPUNIT_TEST( testNullSendReceive );
//  CPPUNIT_TEST( testAdapterSendReceive );
//  CPPUNIT_TEST( testPointerAdapterSendReceive );

  CPPUNIT_TEST_SUITE_END();

private:

public:
  void setUp()
  {}

  void tearDown()
  {}

  void testNullAllGather()
  {
    std::vector<processor_id_type> vals;

    std::vector<std::string> send(1);
    if (TestCommWorld->rank() == 0)
      send[0].assign("Hello");
    else
      send[0].assign("Goodbye");

    TestCommWorld->allgather_packed_range
      ((void *)(NULL), send.begin(), send.end(),
       libMesh::null_output_iterator<std::string>());
  }

};

CPPUNIT_TEST_SUITE_REGISTRATION( PackedRangeTest );
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// Unit tests for hashtable.

#include <vespa/vespalib/stllike/hashtable.hpp>
#include <vespa/vespalib/stllike/hash_fun.h>
#include <vespa/vespalib/stllike/identity.h>
#include <vespa/vespalib/testkit/testapp.h>
#include <memory>
#include <vector>

using vespalib::hashtable;
using std::vector;

using namespace vespalib;

namespace {

template<typename T>
struct Dereference : std::unary_function<T, std::unique_ptr<T>> {
    T &operator()(std::unique_ptr<T>& p) const { return *p; }
    const T& operator()(const std::unique_ptr<T>& p) const { return *p; }
};

template<typename K> using up_hashtable =
    hashtable<K, std::unique_ptr<K>,
              vespalib::hash<K>, std::equal_to<K>, Dereference<K>>;

TEST("require that hashtable can store unique_ptrs") {
    up_hashtable<int> table(100);
    typedef std::unique_ptr<int> UP;
    table.insert(UP(new int(42)));
    auto it = table.find(42);
    EXPECT_EQUAL(42, **it);

    UP u = std::move(*it);  // This changes the key. Don't do this.
    EXPECT_EQUAL(42, *u);

    // it = table.find(42);  // This will crash, since the key is removed.
}

template<typename To, typename Entry>
struct First : std::unary_function<To, Entry> {
    To &operator()(Entry& p) const { return p.first; }
    const To& operator()(const Entry& p) const { return p.first; }
};

template <typename K, typename V> using Entry =
    std::pair<K, std::unique_ptr<V>>;
typedef hashtable<int, Entry<int, int>,
                  vespalib::hash<int>, std::equal_to<int>,
                  First<int, Entry<int, int>>> PairHashtable;

TEST("require that hashtable can store pairs of <key, unique_ptr to value>") {
    PairHashtable table(100);
    table.insert(make_pair(42, std::unique_ptr<int>(new int(84))));
    PairHashtable::iterator it = table.find(42);
    EXPECT_EQUAL(84, *it->second);
    auto it2 = table.find(42);
    EXPECT_EQUAL(84, *it2->second);  // find is not destructive.

    std::unique_ptr<int> up = std::move(it->second);
    it2 = table.find(42);
    EXPECT_FALSE(it2->second.get());  // value has been moved out.
}

template<typename K> using set_hashtable =
    hashtable<K, K, vespalib::hash<K>, std::equal_to<K>, Identity>;

TEST("require that hashtable<int> can be copied") {
    set_hashtable<int> table(100);
    table.insert(42);
    set_hashtable<int> table2(table);
    EXPECT_EQUAL(42, *table2.find(42));
}

TEST("require that you can insert duplicates") {
    using Pair = std::pair<int, vespalib::string>;
    using Map = hashtable<int, Pair, vespalib::hash<int>, std::equal_to<int>, First<int, Pair>>;

    Map m(1);
    EXPECT_EQUAL(0u, m.size());
    EXPECT_EQUAL(8u, m.capacity());
    auto res = m.insert(Pair(1, "1"));
    EXPECT_TRUE(res.second);
    EXPECT_EQUAL(1u, m.size());
    EXPECT_EQUAL(8u, m.capacity());
    res = m.insert(Pair(1, "1.2"));
    EXPECT_FALSE(res.second);
    auto found = m.find(1);
    ASSERT_TRUE(found != m.end());
    EXPECT_EQUAL(found->second, "1");

    m.force_insert(Pair(1, "1.2"));
    EXPECT_EQUAL(2u, m.size());
    EXPECT_EQUAL(8u, m.capacity());
    m.force_insert(Pair(1, "1.3"));
    EXPECT_EQUAL(3u, m.size());
    EXPECT_EQUAL(16u, m.capacity()); // Resize has been conducted
    Pair expected[3] = {{1,"1"},{1,"1.2"},{1,"1.3"}};
    size_t index(0);
    for (const auto & e : m) {
        EXPECT_EQUAL(expected[index].first, e.first);
        EXPECT_EQUAL(expected[index].second, e.second);
        index++;
    }
    found = m.find(1);
    ASSERT_TRUE(found != m.end());
    EXPECT_EQUAL(found->second, "1");

    m.erase(1);
    EXPECT_EQUAL(2u, m.size());
    EXPECT_EQUAL(16u, m.capacity());
    found = m.find(1);
    ASSERT_TRUE(found != m.end());
    EXPECT_EQUAL(found->second, "1.3");

    m.erase(1);
    EXPECT_EQUAL(1u, m.size());
    EXPECT_EQUAL(16u, m.capacity());
    found = m.find(1);
    ASSERT_TRUE(found != m.end());
    EXPECT_EQUAL(found->second, "1.2");
}

template<typename To, typename Vector>
struct FirstInVector : std::unary_function<To, Vector> {
    To &operator()(Vector& v) const { return v[0]; }
    const To& operator()(const Vector& v) const { return v[0]; }
};

TEST("require that hashtable<vector<int>> can be copied") {
    typedef hashtable<int, vector<int>, vespalib::hash<int>,
        std::equal_to<int>, FirstInVector<int, vector<int>>> VectorHashtable;
    VectorHashtable table(100);
    table.insert(std::vector<int>{2, 4, 6});
    VectorHashtable table2(table);
    EXPECT_EQUAL(6, (*table2.find(2))[2]);
    EXPECT_EQUAL(6, (*table.find(2))[2]);
}

}  // namespace

TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>Use Select1st<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// Unit tests for hashtable.

#include <vespa/vespalib/stllike/hashtable.hpp>
#include <vespa/vespalib/stllike/hash_fun.h>
#include <vespa/vespalib/stllike/identity.h>
#include <vespa/vespalib/testkit/testapp.h>
#include <memory>
#include <vector>
#include <vespa/vespalib/stllike/hash_map.h>

using vespalib::hashtable;
using std::vector;

using namespace vespalib;

namespace {

template<typename T>
struct Dereference : std::unary_function<T, std::unique_ptr<T>> {
    T &operator()(std::unique_ptr<T>& p) const { return *p; }
    const T& operator()(const std::unique_ptr<T>& p) const { return *p; }
};

template<typename K> using up_hashtable =
    hashtable<K, std::unique_ptr<K>,
              vespalib::hash<K>, std::equal_to<K>, Dereference<K>>;

TEST("require that hashtable can store unique_ptrs") {
    up_hashtable<int> table(100);
    typedef std::unique_ptr<int> UP;
    table.insert(UP(new int(42)));
    auto it = table.find(42);
    EXPECT_EQUAL(42, **it);

    UP u = std::move(*it);  // This changes the key. Don't do this.
    EXPECT_EQUAL(42, *u);

    // it = table.find(42);  // This will crash, since the key is removed.
}

template <typename K, typename V> using Entry =
    std::pair<K, std::unique_ptr<V>>;
typedef hashtable<int, Entry<int, int>,
                  vespalib::hash<int>, std::equal_to<int>,
                  Select1st<Entry<int, int>>> PairHashtable;

TEST("require that hashtable can store pairs of <key, unique_ptr to value>") {
    PairHashtable table(100);
    table.insert(make_pair(42, std::unique_ptr<int>(new int(84))));
    PairHashtable::iterator it = table.find(42);
    EXPECT_EQUAL(84, *it->second);
    auto it2 = table.find(42);
    EXPECT_EQUAL(84, *it2->second);  // find is not destructive.

    std::unique_ptr<int> up = std::move(it->second);
    it2 = table.find(42);
    EXPECT_FALSE(it2->second.get());  // value has been moved out.
}

template<typename K> using set_hashtable =
    hashtable<K, K, vespalib::hash<K>, std::equal_to<K>, Identity>;

TEST("require that hashtable<int> can be copied") {
    set_hashtable<int> table(100);
    table.insert(42);
    set_hashtable<int> table2(table);
    EXPECT_EQUAL(42, *table2.find(42));
}

TEST("require that you can insert duplicates") {
    using Pair = std::pair<int, vespalib::string>;
    using Map = hashtable<int, Pair, vespalib::hash<int>, std::equal_to<int>, Select1st<Pair>>;

    Map m(1);
    EXPECT_EQUAL(0u, m.size());
    EXPECT_EQUAL(8u, m.capacity());
    auto res = m.insert(Pair(1, "1"));
    EXPECT_TRUE(res.second);
    EXPECT_EQUAL(1u, m.size());
    EXPECT_EQUAL(8u, m.capacity());
    res = m.insert(Pair(1, "1.2"));
    EXPECT_FALSE(res.second);
    auto found = m.find(1);
    ASSERT_TRUE(found != m.end());
    EXPECT_EQUAL(found->second, "1");

    m.force_insert(Pair(1, "1.2"));
    EXPECT_EQUAL(2u, m.size());
    EXPECT_EQUAL(8u, m.capacity());
    m.force_insert(Pair(1, "1.3"));
    EXPECT_EQUAL(3u, m.size());
    EXPECT_EQUAL(16u, m.capacity()); // Resize has been conducted
    Pair expected[3] = {{1,"1"},{1,"1.2"},{1,"1.3"}};
    size_t index(0);
    for (const auto & e : m) {
        EXPECT_EQUAL(expected[index].first, e.first);
        EXPECT_EQUAL(expected[index].second, e.second);
        index++;
    }
    found = m.find(1);
    ASSERT_TRUE(found != m.end());
    EXPECT_EQUAL(found->second, "1");

    m.erase(1);
    EXPECT_EQUAL(2u, m.size());
    EXPECT_EQUAL(16u, m.capacity());
    found = m.find(1);
    ASSERT_TRUE(found != m.end());
    EXPECT_EQUAL(found->second, "1.3");

    m.erase(1);
    EXPECT_EQUAL(1u, m.size());
    EXPECT_EQUAL(16u, m.capacity());
    found = m.find(1);
    ASSERT_TRUE(found != m.end());
    EXPECT_EQUAL(found->second, "1.2");
}

template<typename To, typename Vector>
struct FirstInVector : std::unary_function<To, Vector> {
    To &operator()(Vector& v) const { return v[0]; }
    const To& operator()(const Vector& v) const { return v[0]; }
};

TEST("require that hashtable<vector<int>> can be copied") {
    typedef hashtable<int, vector<int>, vespalib::hash<int>,
        std::equal_to<int>, FirstInVector<int, vector<int>>> VectorHashtable;
    VectorHashtable table(100);
    table.insert(std::vector<int>{2, 4, 6});
    VectorHashtable table2(table);
    EXPECT_EQUAL(6, (*table2.find(2))[2]);
    EXPECT_EQUAL(6, (*table.find(2))[2]);
}

}  // namespace

TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|>


<commit_before>#ifndef _ctoolhu_typesafe_id_included_
#define _ctoolhu_typesafe_id_included_

#include <ostream>

namespace Ctoolhu {

	namespace TypeSafe {

		//stores a value (id) and exposes some typical operations usually performed on ids
		template <typename IdType>
		class Storage {

			typedef Storage<IdType> self_type;

		  public:

			bool operator ==(const self_type &comp) const
			{
				return _id == comp._id;
			}

			bool operator !=(const self_type &comp) const
			{
				return _id != comp._id;
			}

			bool operator <(const self_type &comp) const
			{
				return _id < comp._id;
			}

			bool operator >(const self_type &comp) const
			{
				return _id > comp._id;
			}

			bool operator <=(const self_type &comp) const
			{
				return _id <= comp._id;
			}

			bool operator >=(const self_type &comp) const
			{
				return _id >= comp._id;
			}

			template <typename T>
			friend std::ostream &operator <<(std::ostream &, const Storage<T> &);

		  protected:

			Storage() = default;

			IdType _id;
		};

		template <typename T>
		std::ostream &operator <<(std::ostream &out, const Storage<T> &storage)
		{
			out << storage._id;
			return out;
		}

		//conversion to stored id type is implicit
		template <typename IdType>
		class ImplicitConversion : public Storage<IdType> {

		  public:

			operator IdType() const
			{
				return _id;
			}

		  protected:

			ImplicitConversion() = default;
		};

		//conversion to stored id type is explicit, via the operator ()
		template <typename IdType>
		class ExplicitConversion : public Storage<IdType> {

		  public:

			explicit operator IdType() const
			{
				return _id;
			}

		  protected:

			ExplicitConversion() = default;
		};

		//Tool for preventing mix-up of ids of different objects by means of
		//distinguishing their id types and disallowing conversion between them.
		//The conversions to the underlying type are based on the chosen policy.
		//
		//e.g. for lesson ID use (inside class Lesson)
		//
		//	Id<Lesson> _id;
		//
		//instead of
		//
		//	unsigned int _id;
		//
		template <
			class RequestingObject,				//type of the object which will have this id
			typename IdType = unsigned int,		//type of the id that would normally be used
			template <typename> class ConversionPolicy = ImplicitConversion
		>
		class Id : public ConversionPolicy<IdType> {

		  public:

			typedef RequestingObject object_type;
			typedef IdType id_type;

			explicit Id(IdType id)
			{
				_id = id;
			}
		};

	}; //ns TypeSafe

}; //ns Ctoolhu

#endif //file guard
<commit_msg>improved the typesafe id class<commit_after>#ifndef _ctoolhu_typesafe_id_included_
#define _ctoolhu_typesafe_id_included_

#include <iosfwd>

namespace Ctoolhu {

	namespace TypeSafe {

		//stores a value (id) and exposes some typical operations usually performed on ids
		template <typename IdType>
		class Storage {

			typedef Storage<IdType> self_type;

		  public:

			bool operator ==(const self_type &comp) const
			{
				return _id == comp._id;
			}

			bool operator !=(const self_type &comp) const
			{
				return _id != comp._id;
			}

			bool operator <(const self_type &comp) const
			{
				return _id < comp._id;
			}

			bool operator >(const self_type &comp) const
			{
				return _id > comp._id;
			}

			bool operator <=(const self_type &comp) const
			{
				return _id <= comp._id;
			}

			bool operator >=(const self_type &comp) const
			{
				return _id >= comp._id;
			}

			friend std::ostream &operator <<(std::ostream &out, const self_type &storage)
			{
				out << storage._id;
				return out;
			}

		  protected:

			Storage() = default;

			IdType _id;
		};

		//policy defining that the conversion to stored id type is implicit
		template <typename IdType>
		class ImplicitConversion : public Storage<IdType> {

		  public:

			operator IdType() const
			{
				return _id;
			}

		  protected:

			ImplicitConversion() = default;
		};

		//policy defining that the conversion to stored id type is explicit so that it cannot be mistakenly juxtaposed for the underlying type
		template <typename IdType>
		class ExplicitConversion : public Storage<IdType> {

		  public:

			explicit operator IdType() const
			{
				return _id;
			}

		  protected:

			ExplicitConversion() = default;
		};

		//Tool for preventing mix-up of ids of different objects by means of
		//distinguishing their id types and disallowing conversion between them.
		//The conversions to the underlying type are based on the chosen policy.
		//
		//e.g. for lesson ID use (inside class Lesson)
		//
		//	Id<Lesson> _id;
		//
		//instead of
		//
		//	int _id;
		//
		template <
			class RequestingObject,		//type of the object which will have this id
			typename IdType = int,		//type of the id that would normally be used
			template <typename> class ConversionPolicy = ImplicitConversion
		>
		class Id : public ConversionPolicy<IdType> {

		  public:

			typedef RequestingObject object_type;
			typedef IdType id_type;

			explicit Id(IdType id)
#ifdef _DEBUG
				: _val(_id)
#endif
			{
				_id = id;
			}

#ifdef _DEBUG
			Id &operator =(const Id &src)
			{
				_id = src._id;
				return *this;
			}

		  private:

			const IdType &_val; //so that we can see the value readily in watch window of the debugger
#endif
		};

	}; //ns TypeSafe

}; //ns Ctoolhu

#endif //file guard
<|endoftext|>


<commit_before>// $Id$

/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh

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 <algorithm>
#include "TargetPhraseCollection.h"

using namespace std;

namespace Moses
{
// helper for sort
struct CompareTargetPhrase {
  bool operator() (const TargetPhrase *a, const TargetPhrase *b) {
    return a->GetFutureScore() > b->GetFutureScore();
  }
};

void TargetPhraseCollection::NthElement(size_t tableLimit)
{
  vector<TargetPhrase*>::iterator
  iterMiddle = (tableLimit == 0 || m_collection.size() < tableLimit) ?m_collection.end() : m_collection.begin() + tableLimit;

  //std::sort(m_collection.begin(), m_collection.end(), CompareTargetPhrase());
  std::nth_element(m_collection.begin(), iterMiddle, m_collection.end(), CompareTargetPhrase());
}

void TargetPhraseCollection::Prune(bool adhereTableLimit, size_t tableLimit)
{
  NthElement(tableLimit);

  if (adhereTableLimit && m_collection.size() > tableLimit) {
    for (size_t ind = tableLimit; ind < m_collection.size(); ++ind) {
      TargetPhrase *targetPhrase = m_collection[ind];
      delete targetPhrase;
    }
    m_collection.erase(m_collection.begin() + tableLimit, m_collection.end());
  }
}

void TargetPhraseCollection::Sort(bool adhereTableLimit, size_t tableLimit)
{
  std::vector<TargetPhrase*>::iterator iterMiddle;
  iterMiddle = (tableLimit == 0 || m_collection.size() < tableLimit)
             ? m_collection.end()
             : m_collection.begin()+tableLimit;

  std::partial_sort(m_collection.begin(), iterMiddle, m_collection.end(),
                    CompareTargetPhrase());

  if (adhereTableLimit && m_collection.size() > tableLimit) {
    for (size_t i = tableLimit; i < m_collection.size(); ++i) {
      TargetPhrase *targetPhrase = m_collection[i];
      delete targetPhrase;
    }
    m_collection.erase(m_collection.begin()+tableLimit, m_collection.end());
  }
}

std::ostream& operator<<(std::ostream &out, const TargetPhraseCollection &obj)
{
  TargetPhraseCollection::const_iterator iter;
  for (iter = obj.begin(); iter != obj.end(); ++iter) {
    const TargetPhrase &tp = **iter;
    out << tp << endl;
  }
  return out;
}

} // namespace

<commit_msg>Minor reformatting.<commit_after>// $Id$

/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh

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 <algorithm>
#include "TargetPhraseCollection.h"

using namespace std;

namespace Moses
{
// helper for sort
struct CompareTargetPhrase {
  bool operator() (const TargetPhrase *a, const TargetPhrase *b) {
    return a->GetFutureScore() > b->GetFutureScore();
  }
};

void TargetPhraseCollection::NthElement(size_t tableLimit)
{
  vector<TargetPhrase*>::iterator nth;
  nth = (tableLimit && tableLimit <= m_collection.size()
	 ? m_collection.begin() + tableLimit
	 : m_collection.end());
  std::nth_element(m_collection.begin(), nth, m_collection.end(), CompareTargetPhrase());
}

void TargetPhraseCollection::Prune(bool adhereTableLimit, size_t tableLimit)
{
  NthElement(tableLimit);

  if (adhereTableLimit && m_collection.size() > tableLimit) {
    for (size_t ind = tableLimit; ind < m_collection.size(); ++ind) {
      TargetPhrase *targetPhrase = m_collection[ind];
      delete targetPhrase;
    }
    m_collection.erase(m_collection.begin() + tableLimit, m_collection.end());
  }
}

void TargetPhraseCollection::Sort(bool adhereTableLimit, size_t tableLimit)
{
  std::vector<TargetPhrase*>::iterator iterMiddle;
  iterMiddle = (tableLimit == 0 || m_collection.size() < tableLimit)
             ? m_collection.end()
             : m_collection.begin()+tableLimit;

  std::partial_sort(m_collection.begin(), iterMiddle, m_collection.end(),
                    CompareTargetPhrase());

  if (adhereTableLimit && m_collection.size() > tableLimit) {
    for (size_t i = tableLimit; i < m_collection.size(); ++i) {
      TargetPhrase *targetPhrase = m_collection[i];
      delete targetPhrase;
    }
    m_collection.erase(m_collection.begin()+tableLimit, m_collection.end());
  }
}

std::ostream& operator<<(std::ostream &out, const TargetPhraseCollection &obj)
{
  TargetPhraseCollection::const_iterator iter;
  for (iter = obj.begin(); iter != obj.end(); ++iter) {
    const TargetPhrase &tp = **iter;
    out << tp << endl;
  }
  return out;
}

} // namespace

<|endoftext|>


<commit_before>#include <string>

#include <ros/ros.h>
#include <geometry_msgs/Quaternion.h>
#include <rviz_visual_tools/rviz_visual_tools.h>
#include <tf2_eigen/tf2_eigen.h>
#include <tf2_ros/transform_listener.h>

#include <Eigen/Geometry>
#include <Eigen/SVD>

namespace
{

constexpr auto pi {3.141592653589793};

}

int main(int argc, char** argv)
{
  ros::init(argc, argv, "body_angle_visualizer");
  ros::NodeHandle n {};

  int target_number {1};
  std::string root_name {"openni_coordinater"};
  std::string to_name {"head"};
  std::string from_name {"torso"};
  {
    ros::NodeHandle pn {"~"};
    pn.getParam("target_number", target_number);
    pn.getParam("root", root_name);
    pn.getParam("to", to_name);
    pn.getParam("from", from_name);
  }

  const auto to_frame_name {to_name + '_' + std::to_string(target_number)};
  const auto from_frame_name {from_name + '_' + std::to_string(target_number)};

  ros::Publisher pub {n.advertise<geometry_msgs::Quaternion>("body_direction", 1)};
  ros::Rate r {5};
  tf2_ros::Buffer tfBuffer {};
  tf2_ros::TransformListener tfListener {tfBuffer};
  rviz_visual_tools::RvizVisualTools rvt {root_name, "rviz_visual_markers"};

  while (ros::ok()) {
    try {
      const auto to_pos {tf2::transformToEigen(tfBuffer.lookupTransform(root_name, to_frame_name, ros::Time{0}))};
      const auto from_pos {tf2::transformToEigen(tfBuffer.lookupTransform(root_name, from_frame_name, ros::Time{0}))};
      const auto from_ypr {from_pos.rotation().eulerAngles(1, 0, 2)};
      const auto trim_half_rotation {[](double angle) {
        if (angle < -pi / 2)
          return angle + pi;
        if (angle > pi / 2)
          return angle - pi;
        return angle;
      }};
      const auto roll_angle {trim_half_rotation(from_ypr(2))};
      const auto invert_half_rotation {[](double angle) {
        if (angle < -pi / 2)
          return -angle - pi;
        if (angle > pi / 2)
          return -angle + pi;
        return angle;
      }};
      const auto pitch_angle {invert_half_rotation(from_ypr(1))};
      const auto stand_vec {to_pos.translation() - from_pos.translation()};
      const auto stand_quaternion {Eigen::Quaterniond::FromTwoVectors(Eigen::Vector3d::UnitX(), stand_vec)};

      pub.publish(tf2::toMsg(Eigen::Quaterniond{from_pos.rotation()}));

      rvt.deleteAllMarkers();
      rvt.publishArrow(Eigen::Affine3d{stand_quaternion}, rviz_visual_tools::BLUE, rviz_visual_tools::LARGE);

      Eigen::Affine3d text_pos {};
      text_pos.translation() = stand_vec.normalized() * .5;
      rvt.publishText(text_pos, std::to_string(roll_angle * 180 / pi), rviz_visual_tools::WHITE, rviz_visual_tools::XLARGE, false);
      text_pos.translation() *= 1.1;
      rvt.publishText(text_pos, std::to_string(pitch_angle * 180 / pi), rviz_visual_tools::WHITE, rviz_visual_tools::XLARGE, false);

      rvt.trigger();
    } catch (tf2::TransformException &e) {
      ROS_WARN("%s", e.what());
    }

    r.sleep();
  }
}
<commit_msg>Refactor lamda function with constexpr for runtime<commit_after>#include <string>

#include <ros/ros.h>
#include <geometry_msgs/Quaternion.h>
#include <rviz_visual_tools/rviz_visual_tools.h>
#include <tf2_eigen/tf2_eigen.h>
#include <tf2_ros/transform_listener.h>

#include <Eigen/Geometry>
#include <Eigen/SVD>

namespace
{

constexpr auto pi {3.141592653589793};

}

int main(int argc, char** argv)
{
  ros::init(argc, argv, "body_angle_visualizer");
  ros::NodeHandle n {};

  int target_number {1};
  std::string root_name {"openni_coordinater"};
  std::string to_name {"head"};
  std::string from_name {"torso"};
  {
    ros::NodeHandle pn {"~"};
    pn.getParam("target_number", target_number);
    pn.getParam("root", root_name);
    pn.getParam("to", to_name);
    pn.getParam("from", from_name);
  }

  const auto to_frame_name {to_name + '_' + std::to_string(target_number)};
  const auto from_frame_name {from_name + '_' + std::to_string(target_number)};

  ros::Publisher pub {n.advertise<geometry_msgs::Quaternion>("body_direction", 1)};
  ros::Rate r {5};
  tf2_ros::Buffer tfBuffer {};
  tf2_ros::TransformListener tfListener {tfBuffer};
  rviz_visual_tools::RvizVisualTools rvt {root_name, "rviz_visual_markers"};

  while (ros::ok()) {
    try {
      const auto to_pos {tf2::transformToEigen(tfBuffer.lookupTransform(root_name, to_frame_name, ros::Time{0}))};
      const auto from_pos {tf2::transformToEigen(tfBuffer.lookupTransform(root_name, from_frame_name, ros::Time{0}))};
      const auto from_ypr {from_pos.rotation().eulerAngles(1, 0, 2)};
      constexpr auto trim_half_rotation {[](double angle) {
        if (angle < -pi / 2)
          return angle + pi;
        if (angle > pi / 2)
          return angle - pi;
        return angle;
      }};
      const auto roll_angle {trim_half_rotation(from_ypr(2))};
      constexpr auto invert_half_rotation {[](double angle) {
        if (angle < -pi / 2)
          return -angle - pi;
        if (angle > pi / 2)
          return -angle + pi;
        return angle;
      }};
      const auto pitch_angle {invert_half_rotation(from_ypr(1))};
      const auto stand_vec {to_pos.translation() - from_pos.translation()};
      const auto stand_quaternion {Eigen::Quaterniond::FromTwoVectors(Eigen::Vector3d::UnitX(), stand_vec)};

      pub.publish(tf2::toMsg(Eigen::Quaterniond{from_pos.rotation()}));

      rvt.deleteAllMarkers();
      rvt.publishArrow(Eigen::Affine3d{stand_quaternion}, rviz_visual_tools::BLUE, rviz_visual_tools::LARGE);

      Eigen::Affine3d text_pos {};
      text_pos.translation() = stand_vec.normalized() * .5;
      rvt.publishText(text_pos, std::to_string(roll_angle * 180 / pi), rviz_visual_tools::WHITE, rviz_visual_tools::XLARGE, false);
      text_pos.translation() *= 1.1;
      rvt.publishText(text_pos, std::to_string(pitch_angle * 180 / pi), rviz_visual_tools::WHITE, rviz_visual_tools::XLARGE, false);

      rvt.trigger();
    } catch (tf2::TransformException &e) {
      ROS_WARN("%s", e.what());
    }

    r.sleep();
  }
}
<|endoftext|>


<commit_before>#include <silicium/process.hpp>
#include <silicium/build_result.hpp>
#include <silicium/directory_allocator.hpp>
#include <silicium/to_unique.hpp>
#include <silicium/git/repository.hpp>
#include <silicium/read_file.hpp>
#include <boost/asio.hpp>
#include <fstream>

namespace
{
	struct tcp_trigger
	{
		explicit tcp_trigger(boost::asio::io_service &io, boost::asio::ip::tcp::endpoint address)
			: m_acceptor(io, address, true)
		{
		}

		template <class Handler>
		void async_wait(Handler handler)
		{
			if (m_accepting)
			{
				m_accepting->close();
			}
			m_accepting.reset(new boost::asio::ip::tcp::socket(m_acceptor.get_io_service()));
			m_acceptor.async_accept(*m_accepting, [this, handler](boost::system::error_code error)
			{
				if (error)
				{
					//TODO
				}
				else
				{
					m_accepting->shutdown(boost::asio::ip::tcp::socket::shutdown_both);
					handler();
				}
			});
		}

		void cancel()
		{
			m_acceptor.cancel();
		}

	private:

		boost::asio::ip::tcp::acceptor m_acceptor;
		std::unique_ptr<boost::asio::ip::tcp::socket> m_accepting;
	};

	boost::filesystem::path make_last_built_file_name(
			boost::filesystem::path const &output_location,
			std::string const &branch)
	{
		return output_location / (branch + ".lastbuild.txt");
	}

	boost::optional<git_oid> get_last_built(boost::filesystem::path const &last_build_file_name)
	{
		if (!boost::filesystem::exists(last_build_file_name))
		{
			return boost::none;
		}
		auto str = Si::read_file(last_build_file_name);
		git_oid id;
		Si::git::throw_if_libgit2_error(git_oid_fromstrn(&id, str.data(), str.size()));
		return id;
	}

	void write_file(boost::filesystem::path const &name, char const *data, std::size_t size)
	{
		std::ofstream file(name.string(), std::ios::binary);
		if (!file)
		{
			throw std::runtime_error("Could not open file " + name.string() + " for writing");
		}
		file.write(data, size);
		if (!file)
		{
			throw std::runtime_error("Could not write to file " + name.string());
		}
	}

	std::string format_oid(git_oid const &id)
	{
		std::array<char, 41> str;
		git_oid_fmt(str.data(), &id);
		str[40] = 0;
		return str.data();
	}

	void set_last_built(
			git_repository &repository,
			boost::filesystem::path const &last_build_file_name,
			git_reference const &built)
	{
		char const * const name = git_reference_name(&built);
		git_oid commit_id;
		Si::git::throw_if_libgit2_error(git_reference_name_to_id(&commit_id, &repository, name));
		auto const id_str = format_oid(commit_id);
		write_file(last_build_file_name, id_str.data(), id_str.size());
	}

	struct directory_builder
	{
		virtual ~directory_builder()
		{
		}

		virtual std::unique_ptr<Si::sink<char>> begin_artifact(std::string const &name) = 0;
		virtual std::unique_ptr<directory_builder> create_subdirectory(std::string const &name) = 0;
	};

	Si::build_result make(
			boost::filesystem::path const &source,
			boost::filesystem::path const &build_dir,
			directory_builder &artifacts)
	{
		{
			Si::process_parameters parameters;
			parameters.executable = "/usr/bin/cmake";
			parameters.arguments = {source.string()};
			parameters.current_path = build_dir;
			parameters.stdout = artifacts.begin_artifact("cmake.log");
			int const exit_code = Si::run_process(parameters);
			if (exit_code != 0)
			{
				return Si::build_failure{"CMake failed"};
			}
		}
		{
			Si::process_parameters parameters;
			parameters.executable = "/usr/bin/make";
			parameters.arguments = {"-j4"};
			parameters.current_path = build_dir;
			parameters.stdout = artifacts.begin_artifact("make.log");
			int const exit_code = Si::run_process(parameters);
			if (exit_code != 0)
			{
				return Si::build_failure{"make failed"};
			}
		}
		{
			Si::process_parameters parameters;
			parameters.executable = build_dir / "test/test";
			parameters.current_path = build_dir / "test";
			parameters.stdout = artifacts.begin_artifact("test.log");
			int const exit_code = Si::run_process(parameters);
			if (exit_code != 0)
			{
				return Si::build_failure{"tests failed"};
			}
		}
		return Si::build_success{};
	}

	struct filesystem_directory_builder : directory_builder
	{
		explicit filesystem_directory_builder(boost::filesystem::path destination)
			: m_destination(std::move(destination))
		{
		}

		virtual std::unique_ptr<Si::sink<char>> begin_artifact(std::string const &name) override
		{
			auto const file_name = m_destination / name;
			std::unique_ptr<std::ostream> file(new std::ofstream(file_name.string(), std::ios::binary));
			if (!*file)
			{
				throw std::runtime_error("Cannot open file for writing: " + file_name.string());
			}
			return std::unique_ptr<Si::sink<char>>(new Si::ostream_sink(std::move(file)));
		}

		virtual std::unique_ptr<directory_builder> create_subdirectory(std::string const &name) override
		{
			auto sub = m_destination / name;
			boost::filesystem::create_directories(sub);
			return std::unique_ptr<directory_builder>(new filesystem_directory_builder(sub));
		}

	private:

		boost::filesystem::path m_destination;
	};

	void clone(
			std::string const &branch,
			boost::filesystem::path const &source_location,
			boost::filesystem::path const &cloned_dir)
	{
		git_clone_options options = GIT_CLONE_OPTIONS_INIT;
		options.checkout_branch = branch.c_str(); //TODO: clone the reference directly without repeating the branch name
		Si::git::clone(source_location.string(), cloned_dir, &options);
	}

	Si::build_result build_commit(
			std::string const &branch,
			boost::filesystem::path const &source_location,
			boost::filesystem::path const &commit_dir,
			boost::filesystem::path const &report_location)
	{
		auto const cloned_dir = commit_dir / "source";
		clone(branch, source_location, cloned_dir);

		auto const build_dir = commit_dir / "build";
		boost::filesystem::create_directories(build_dir);
		filesystem_directory_builder artifacts(report_location);
		return make(cloned_dir, build_dir, artifacts);
	}

	void check_build(
			boost::filesystem::path const &source_location,
			boost::filesystem::path const &workspace)
	{
		std::string const branch = "master";
		auto const source = Si::git::open_repository(source_location);
		auto const full_branch_name = ("refs/heads/" + branch);
		auto const ref_to_build = Si::git::lookup(*source, full_branch_name.c_str());
		if (!ref_to_build)
		{
			throw std::runtime_error(branch + " branch does not exist");
		}
		git_oid oid_to_build;
		Si::git::throw_if_libgit2_error(git_reference_name_to_id(&oid_to_build, source.get(), full_branch_name.c_str()));
		auto const results_repository = workspace / "results.git";
		auto const last_built_file_name = make_last_built_file_name(results_repository, branch);
		auto const ref_last_built = get_last_built(last_built_file_name);
		if (ref_last_built &&
			git_oid_equal(&*ref_last_built, &oid_to_build))
		{
			//nothing to do
			return;
		}

		auto const temporary_location = workspace / format_oid(oid_to_build);
		boost::filesystem::create_directories(temporary_location);

		auto const report_location = results_repository / format_oid(oid_to_build);
		boost::filesystem::create_directories(report_location);

		build_commit(branch, source_location, temporary_location, report_location);
		set_last_built(*source, last_built_file_name, *ref_to_build);
	}
}

int main(int argc, char **argv)
{
	if (argc < 3)
	{
		return 1;
	}
	boost::filesystem::path const source_location = argv[1];
	boost::filesystem::path const workspace = argv[2];

	auto const build = [&]
	{
		try
		{
			check_build(source_location, workspace);
		}
		catch (std::exception const &ex)
		{
			//continue to run
			std::cerr << ex.what() << '\n';
		}
	};

	boost::asio::io_service io;
	tcp_trigger external_build_trigger(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), 12345));
	std::function<void ()> wait_for_trigger;
	wait_for_trigger = [&wait_for_trigger, &external_build_trigger, &build]
	{
		external_build_trigger.async_wait([&wait_for_trigger, &build]
		{
			build();
			wait_for_trigger();
		});
	};
	wait_for_trigger();

	build();
	io.run();
}
<commit_msg>use directory_builder for creating the report directory<commit_after>#include <silicium/process.hpp>
#include <silicium/build_result.hpp>
#include <silicium/directory_allocator.hpp>
#include <silicium/to_unique.hpp>
#include <silicium/git/repository.hpp>
#include <silicium/read_file.hpp>
#include <boost/asio.hpp>
#include <fstream>

namespace
{
	struct tcp_trigger
	{
		explicit tcp_trigger(boost::asio::io_service &io, boost::asio::ip::tcp::endpoint address)
			: m_acceptor(io, address, true)
		{
		}

		template <class Handler>
		void async_wait(Handler handler)
		{
			if (m_accepting)
			{
				m_accepting->close();
			}
			m_accepting.reset(new boost::asio::ip::tcp::socket(m_acceptor.get_io_service()));
			m_acceptor.async_accept(*m_accepting, [this, handler](boost::system::error_code error)
			{
				if (error)
				{
					//TODO
				}
				else
				{
					m_accepting->shutdown(boost::asio::ip::tcp::socket::shutdown_both);
					handler();
				}
			});
		}

		void cancel()
		{
			m_acceptor.cancel();
		}

	private:

		boost::asio::ip::tcp::acceptor m_acceptor;
		std::unique_ptr<boost::asio::ip::tcp::socket> m_accepting;
	};

	boost::filesystem::path make_last_built_file_name(
			boost::filesystem::path const &output_location,
			std::string const &branch)
	{
		return output_location / (branch + ".lastbuild.txt");
	}

	boost::optional<git_oid> get_last_built(boost::filesystem::path const &last_build_file_name)
	{
		if (!boost::filesystem::exists(last_build_file_name))
		{
			return boost::none;
		}
		auto str = Si::read_file(last_build_file_name);
		git_oid id;
		Si::git::throw_if_libgit2_error(git_oid_fromstrn(&id, str.data(), str.size()));
		return id;
	}

	void write_file(boost::filesystem::path const &name, char const *data, std::size_t size)
	{
		std::ofstream file(name.string(), std::ios::binary);
		if (!file)
		{
			throw std::runtime_error("Could not open file " + name.string() + " for writing");
		}
		file.write(data, size);
		if (!file)
		{
			throw std::runtime_error("Could not write to file " + name.string());
		}
	}

	std::string format_oid(git_oid const &id)
	{
		std::array<char, 41> str;
		git_oid_fmt(str.data(), &id);
		str[40] = 0;
		return str.data();
	}

	void set_last_built(
			git_repository &repository,
			boost::filesystem::path const &last_build_file_name,
			git_reference const &built)
	{
		char const * const name = git_reference_name(&built);
		git_oid commit_id;
		Si::git::throw_if_libgit2_error(git_reference_name_to_id(&commit_id, &repository, name));
		auto const id_str = format_oid(commit_id);
		write_file(last_build_file_name, id_str.data(), id_str.size());
	}

	struct directory_builder
	{
		virtual ~directory_builder()
		{
		}

		virtual std::unique_ptr<Si::sink<char>> begin_artifact(std::string const &name) = 0;
		virtual std::unique_ptr<directory_builder> create_subdirectory(std::string const &name) = 0;
	};

	Si::build_result make(
			boost::filesystem::path const &source,
			boost::filesystem::path const &build_dir,
			directory_builder &artifacts)
	{
		{
			Si::process_parameters parameters;
			parameters.executable = "/usr/bin/cmake";
			parameters.arguments = {source.string()};
			parameters.current_path = build_dir;
			parameters.stdout = artifacts.begin_artifact("cmake.log");
			int const exit_code = Si::run_process(parameters);
			if (exit_code != 0)
			{
				return Si::build_failure{"CMake failed"};
			}
		}
		{
			Si::process_parameters parameters;
			parameters.executable = "/usr/bin/make";
			parameters.arguments = {"-j4"};
			parameters.current_path = build_dir;
			parameters.stdout = artifacts.begin_artifact("make.log");
			int const exit_code = Si::run_process(parameters);
			if (exit_code != 0)
			{
				return Si::build_failure{"make failed"};
			}
		}
		{
			Si::process_parameters parameters;
			parameters.executable = build_dir / "test/test";
			parameters.current_path = build_dir / "test";
			parameters.stdout = artifacts.begin_artifact("test.log");
			int const exit_code = Si::run_process(parameters);
			if (exit_code != 0)
			{
				return Si::build_failure{"tests failed"};
			}
		}
		return Si::build_success{};
	}

	struct filesystem_directory_builder : directory_builder
	{
		explicit filesystem_directory_builder(boost::filesystem::path destination)
			: m_destination(std::move(destination))
		{
		}

		virtual std::unique_ptr<Si::sink<char>> begin_artifact(std::string const &name) override
		{
			auto const file_name = m_destination / name;
			std::unique_ptr<std::ostream> file(new std::ofstream(file_name.string(), std::ios::binary));
			if (!*file)
			{
				throw std::runtime_error("Cannot open file for writing: " + file_name.string());
			}
			return std::unique_ptr<Si::sink<char>>(new Si::ostream_sink(std::move(file)));
		}

		virtual std::unique_ptr<directory_builder> create_subdirectory(std::string const &name) override
		{
			auto sub = m_destination / name;
			boost::filesystem::create_directories(sub);
			return std::unique_ptr<directory_builder>(new filesystem_directory_builder(sub));
		}

	private:

		boost::filesystem::path m_destination;
	};

	void clone(
			std::string const &branch,
			boost::filesystem::path const &source_location,
			boost::filesystem::path const &cloned_dir)
	{
		git_clone_options options = GIT_CLONE_OPTIONS_INIT;
		options.checkout_branch = branch.c_str(); //TODO: clone the reference directly without repeating the branch name
		Si::git::clone(source_location.string(), cloned_dir, &options);
	}

	Si::build_result build_commit(
			std::string const &branch,
			boost::filesystem::path const &source_location,
			boost::filesystem::path const &commit_dir,
			directory_builder &reports)
	{
		auto const cloned_dir = commit_dir / "source";
		clone(branch, source_location, cloned_dir);

		auto const build_dir = commit_dir / "build";
		boost::filesystem::create_directories(build_dir);
		return make(cloned_dir, build_dir, reports);
	}

	void check_build(
			boost::filesystem::path const &source_location,
			boost::filesystem::path const &workspace)
	{
		std::string const branch = "master";
		auto const source = Si::git::open_repository(source_location);
		auto const full_branch_name = ("refs/heads/" + branch);
		auto const ref_to_build = Si::git::lookup(*source, full_branch_name.c_str());
		if (!ref_to_build)
		{
			throw std::runtime_error(branch + " branch does not exist");
		}
		git_oid oid_to_build;
		Si::git::throw_if_libgit2_error(git_reference_name_to_id(&oid_to_build, source.get(), full_branch_name.c_str()));
		auto const results_repository = workspace / "results.git";
		auto const last_built_file_name = make_last_built_file_name(results_repository, branch);
		auto const ref_last_built = get_last_built(last_built_file_name);
		if (ref_last_built &&
			git_oid_equal(&*ref_last_built, &oid_to_build))
		{
			//nothing to do
			return;
		}

		auto const temporary_location = workspace / format_oid(oid_to_build);
		boost::filesystem::create_directories(temporary_location);

		filesystem_directory_builder results(results_repository);
		auto const reports = results.create_subdirectory(format_oid(oid_to_build));
		build_commit(branch, source_location, temporary_location, *reports);
		set_last_built(*source, last_built_file_name, *ref_to_build);
	}
}

int main(int argc, char **argv)
{
	if (argc < 3)
	{
		return 1;
	}
	boost::filesystem::path const source_location = argv[1];
	boost::filesystem::path const workspace = argv[2];

	auto const build = [&]
	{
		try
		{
			check_build(source_location, workspace);
		}
		catch (std::exception const &ex)
		{
			//continue to run
			std::cerr << ex.what() << '\n';
		}
	};

	boost::asio::io_service io;
	tcp_trigger external_build_trigger(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), 12345));
	std::function<void ()> wait_for_trigger;
	wait_for_trigger = [&wait_for_trigger, &external_build_trigger, &build]
	{
		external_build_trigger.async_wait([&wait_for_trigger, &build]
		{
			build();
			wait_for_trigger();
		});
	};
	wait_for_trigger();

	build();
	io.run();
}
<|endoftext|>


<commit_before>#include "SearchNormalBatch.h"
#include "LM/Base.h"
#include "Manager.h"
#include "Hypothesis.h"

//#include <google/profiler.h>

using namespace std;

namespace Moses
{
SearchNormalBatch::SearchNormalBatch(Manager& manager, const InputType &source, const TranslationOptionCollection &transOptColl)
  :SearchNormal(manager, source, transOptColl)
  ,m_batch_size(10000)
{
  m_max_stack_size = StaticData::Instance().GetMaxHypoStackSize();

  // Split the feature functions into sets of stateless, stateful
  // distributed lm, and stateful non-distributed.
  const vector<const StatefulFeatureFunction*>& ffs =
    StatefulFeatureFunction::GetStatefulFeatureFunctions();
  for (unsigned i = 0; i < ffs.size(); ++i) {
    if (ffs[i]->GetScoreProducerDescription() == "DLM_5gram") { // TODO WFT
      m_dlm_ffs[i] = const_cast<LanguageModel*>(static_cast<const LanguageModel* const>(ffs[i]));
      m_dlm_ffs[i]->SetFFStateIdx(i);
    } else {
      m_stateful_ffs[i] = const_cast<StatefulFeatureFunction*>(ffs[i]);
    }
  }
  m_stateless_ffs = StatelessFeatureFunction::GetStatelessFeatureFunctions();

}

SearchNormalBatch::~SearchNormalBatch()
{
}

/**
 * Main decoder loop that translates a sentence by expanding
 * hypotheses stack by stack, until the end of the sentence.
 */
void SearchNormalBatch::ProcessSentence()
{
  const StaticData &staticData = StaticData::Instance();
  SentenceStats &stats = m_manager.GetSentenceStats();
  clock_t t=0; // used to track time for steps

  // initial seed hypothesis: nothing translated, no words produced
  Hypothesis *hypo = Hypothesis::Create(m_manager,m_source, m_initialTransOpt);
  m_hypoStackColl[0]->AddPrune(hypo);

  // go through each stack
  std::vector < HypothesisStack* >::iterator iterStack;
  for (iterStack = m_hypoStackColl.begin() ; iterStack != m_hypoStackColl.end() ; ++iterStack) {
    // check if decoding ran out of time
    double _elapsed_time = GetUserTime();
    if (_elapsed_time > staticData.GetTimeoutThreshold()) {
      VERBOSE(1,"Decoding is out of time (" << _elapsed_time << "," << staticData.GetTimeoutThreshold() << ")" << std::endl);
      interrupted_flag = 1;
      return;
    }
    HypothesisStackNormal &sourceHypoColl = *static_cast<HypothesisStackNormal*>(*iterStack);

    // the stack is pruned before processing (lazy pruning):
    VERBOSE(3,"processing hypothesis from next stack");
    IFVERBOSE(2) {
      t = clock();
    }
    sourceHypoColl.PruneToSize(staticData.GetMaxHypoStackSize());
    VERBOSE(3,std::endl);
    sourceHypoColl.CleanupArcList();
    IFVERBOSE(2) {
      stats.AddTimeStack( clock()-t );
    }

    // go through each hypothesis on the stack and try to expand it
    HypothesisStackNormal::const_iterator iterHypo;
    for (iterHypo = sourceHypoColl.begin() ; iterHypo != sourceHypoColl.end() ; ++iterHypo) {
      Hypothesis &hypothesis = **iterHypo;
      ProcessOneHypothesis(hypothesis); // expand the hypothesis
    }
    EvalAndMergePartialHypos();

    // some logging
    IFVERBOSE(2) {
      OutputHypoStackSize();
    }

    // this stack is fully expanded;
    actual_hypoStack = &sourceHypoColl;
  }

  EvalAndMergePartialHypos();

  // some more logging
  IFVERBOSE(2) {
    m_manager.GetSentenceStats().SetTimeTotal( clock()-m_start );
  }
  VERBOSE(2, m_manager.GetSentenceStats());
}

/**
 * Expand one hypothesis with a translation option.
 * this involves initial creation, scoring and adding it to the proper stack
 * \param hypothesis hypothesis to be expanded upon
 * \param transOpt translation option (phrase translation)
 *        that is applied to create the new hypothesis
 * \param expectedScore base score for early discarding
 *        (base hypothesis score plus future score estimation)
 */
void SearchNormalBatch::ExpandHypothesis(const Hypothesis &hypothesis, const TranslationOption &transOpt, float expectedScore)
{
  // Check if the number of partial hypotheses exceeds the batch size.
  if (m_partial_hypos.size() >= m_batch_size) {
    EvalAndMergePartialHypos();
  }

  const StaticData &staticData = StaticData::Instance();
  SentenceStats &stats = m_manager.GetSentenceStats();
  clock_t t=0; // used to track time for steps

  Hypothesis *newHypo;
  if (! staticData.UseEarlyDiscarding()) {
    // simple build, no questions asked
    IFVERBOSE(2) {
      t = clock();
    }
    newHypo = hypothesis.CreateNext(transOpt);
    IFVERBOSE(2) {
      stats.AddTimeBuildHyp( clock()-t );
    }
    if (newHypo==NULL) return;
    //newHypo->Evaluate(m_transOptColl.GetFutureScore());

    // Issue DLM requests for new hypothesis and put into the list of
    // partial hypotheses.
    std::map<int, LanguageModel*>::iterator dlm_iter;
    for (dlm_iter = m_dlm_ffs.begin();
         dlm_iter != m_dlm_ffs.end();
         ++dlm_iter) {
      const FFState* input_state = newHypo->GetPrevHypo() ? newHypo->GetPrevHypo()->GetFFState((*dlm_iter).first) : NULL;
      (*dlm_iter).second->IssueRequestsFor(*newHypo, input_state);
    }
    m_partial_hypos.push_back(newHypo);
  } else {
    std::cerr << "can't use early discarding with batch decoding!" << std::endl;
    abort();
  }
}

void SearchNormalBatch::EvalAndMergePartialHypos()
{
  std::vector<Hypothesis*>::iterator partial_hypo_iter;
  for (partial_hypo_iter = m_partial_hypos.begin();
       partial_hypo_iter != m_partial_hypos.end();
       ++partial_hypo_iter) {
    Hypothesis* hypo = *partial_hypo_iter;

    // Evaluate with other ffs.
    std::map<int, StatefulFeatureFunction*>::iterator sfff_iter;
    for (sfff_iter = m_stateful_ffs.begin();
         sfff_iter != m_stateful_ffs.end();
         ++sfff_iter) {
      const StatefulFeatureFunction &ff = *(sfff_iter->second);
      int state_idx = sfff_iter->first;
      hypo->EvaluateWith(ff, state_idx);
    }
    std::vector<const StatelessFeatureFunction*>::iterator slff_iter;
    for (slff_iter = m_stateless_ffs.begin();
         slff_iter != m_stateless_ffs.end();
         ++slff_iter) {
      hypo->EvaluateWith(**slff_iter);
    }
  }

  // Wait for all requests from the distributed LM to come back.
  std::map<int, LanguageModel*>::iterator dlm_iter;
  for (dlm_iter = m_dlm_ffs.begin();
       dlm_iter != m_dlm_ffs.end();
       ++dlm_iter) {
    (*dlm_iter).second->sync();
  }

  // Incorporate the DLM scores into all hypotheses and put into their
  // stacks.
  for (partial_hypo_iter = m_partial_hypos.begin();
       partial_hypo_iter != m_partial_hypos.end();
       ++partial_hypo_iter) {
    Hypothesis* hypo = *partial_hypo_iter;

    // Calculate DLM scores.
    std::map<int, LanguageModel*>::iterator dlm_iter;
    for (dlm_iter = m_dlm_ffs.begin();
         dlm_iter != m_dlm_ffs.end();
         ++dlm_iter) {
      LanguageModel &lm = *(dlm_iter->second);
      hypo->EvaluateWith(lm, (*dlm_iter).first);
    }

    // Put completed hypothesis onto its stack.
    size_t wordsTranslated = hypo->GetWordsBitmap().GetNumWordsCovered();
    m_hypoStackColl[wordsTranslated]->AddPrune(hypo);
  }
  m_partial_hypos.clear();

  std::vector < HypothesisStack* >::iterator stack_iter;
  HypothesisStackNormal* stack;
  for (stack_iter = m_hypoStackColl.begin();
       stack_iter != m_hypoStackColl.end();
       ++stack_iter) {
    stack = static_cast<HypothesisStackNormal*>(*stack_iter);
    stack->PruneToSize(m_max_stack_size);
  }
}

}
<commit_msg>Formatting.<commit_after>#include "SearchNormalBatch.h"
#include "LM/Base.h"
#include "Manager.h"
#include "Hypothesis.h"

//#include <google/profiler.h>

using namespace std;

namespace Moses
{
SearchNormalBatch::SearchNormalBatch(Manager& manager, const InputType &source, const TranslationOptionCollection &transOptColl)
  :SearchNormal(manager, source, transOptColl)
  ,m_batch_size(10000)
{
  m_max_stack_size = StaticData::Instance().GetMaxHypoStackSize();

  // Split the feature functions into sets of stateless, stateful
  // distributed lm, and stateful non-distributed.
  const vector<const StatefulFeatureFunction*>& ffs =
    StatefulFeatureFunction::GetStatefulFeatureFunctions();
  for (unsigned i = 0; i < ffs.size(); ++i) {
    if (ffs[i]->GetScoreProducerDescription() == "DLM_5gram") { // TODO WFT
      m_dlm_ffs[i] = const_cast<LanguageModel*>(static_cast<const LanguageModel* const>(ffs[i]));
      m_dlm_ffs[i]->SetFFStateIdx(i);
    } else {
      m_stateful_ffs[i] = const_cast<StatefulFeatureFunction*>(ffs[i]);
    }
  }
  m_stateless_ffs = StatelessFeatureFunction::GetStatelessFeatureFunctions();

}

SearchNormalBatch::~SearchNormalBatch()
{
}

/**
 * Main decoder loop that translates a sentence by expanding
 * hypotheses stack by stack, until the end of the sentence.
 */
void SearchNormalBatch::ProcessSentence()
{
  const StaticData &staticData = StaticData::Instance();
  SentenceStats &stats = m_manager.GetSentenceStats();
  clock_t t=0; // used to track time for steps

  // initial seed hypothesis: nothing translated, no words produced
  Hypothesis *hypo = Hypothesis::Create(m_manager,m_source, m_initialTransOpt);
  m_hypoStackColl[0]->AddPrune(hypo);

  // go through each stack
  std::vector < HypothesisStack* >::iterator iterStack;
  for (iterStack = m_hypoStackColl.begin() ; iterStack != m_hypoStackColl.end() ; ++iterStack) {
    // check if decoding ran out of time
    double _elapsed_time = GetUserTime();
    if (_elapsed_time > staticData.GetTimeoutThreshold()) {
      VERBOSE(1,"Decoding is out of time (" << _elapsed_time << "," << staticData.GetTimeoutThreshold() << ")" << std::endl);
      interrupted_flag = 1;
      return;
    }
    HypothesisStackNormal &sourceHypoColl = *static_cast<HypothesisStackNormal*>(*iterStack);

    // the stack is pruned before processing (lazy pruning):
    VERBOSE(3,"processing hypothesis from next stack");
    IFVERBOSE(2) {
      t = clock();
    }
    sourceHypoColl.PruneToSize(staticData.GetMaxHypoStackSize());
    VERBOSE(3,std::endl);
    sourceHypoColl.CleanupArcList();
    IFVERBOSE(2) {
      stats.AddTimeStack( clock()-t );
    }

    // go through each hypothesis on the stack and try to expand it
    HypothesisStackNormal::const_iterator iterHypo;
    for (iterHypo = sourceHypoColl.begin() ; iterHypo != sourceHypoColl.end() ; ++iterHypo) {
      Hypothesis &hypothesis = **iterHypo;
      ProcessOneHypothesis(hypothesis); // expand the hypothesis
    }
    EvalAndMergePartialHypos();

    // some logging
    IFVERBOSE(2) {
      OutputHypoStackSize();
    }

    // this stack is fully expanded;
    actual_hypoStack = &sourceHypoColl;
  }

  EvalAndMergePartialHypos();

  // some more logging
  IFVERBOSE(2) {
    m_manager.GetSentenceStats().SetTimeTotal( clock()-m_start );
  }
  VERBOSE(2, m_manager.GetSentenceStats());
}

/**
 * Expand one hypothesis with a translation option.
 * this involves initial creation, scoring and adding it to the proper stack
 * \param hypothesis hypothesis to be expanded upon
 * \param transOpt translation option (phrase translation)
 *        that is applied to create the new hypothesis
 * \param expectedScore base score for early discarding
 *        (base hypothesis score plus future score estimation)
 */

void
SearchNormalBatch::
ExpandHypothesis(const Hypothesis &hypothesis,
		 const TranslationOption &transOpt, float expectedScore)
{
  // Check if the number of partial hypotheses exceeds the batch size.
  if (m_partial_hypos.size() >= m_batch_size) {
    EvalAndMergePartialHypos();
  }

  const StaticData &staticData = StaticData::Instance();
  SentenceStats &stats = m_manager.GetSentenceStats();
  clock_t t=0; // used to track time for steps

  Hypothesis *newHypo;
  if (! staticData.UseEarlyDiscarding()) {
    // simple build, no questions asked
    IFVERBOSE(2) {
      t = clock();
    }
    newHypo = hypothesis.CreateNext(transOpt);
    IFVERBOSE(2) {
      stats.AddTimeBuildHyp( clock()-t );
    }
    if (newHypo==NULL) return;
    //newHypo->Evaluate(m_transOptColl.GetFutureScore());

    // Issue DLM requests for new hypothesis and put into the list of
    // partial hypotheses.
    std::map<int, LanguageModel*>::iterator dlm_iter;
    for (dlm_iter = m_dlm_ffs.begin();
         dlm_iter != m_dlm_ffs.end();
         ++dlm_iter) {
      const FFState* input_state = newHypo->GetPrevHypo() ? newHypo->GetPrevHypo()->GetFFState((*dlm_iter).first) : NULL;
      (*dlm_iter).second->IssueRequestsFor(*newHypo, input_state);
    }
    m_partial_hypos.push_back(newHypo);
  } else {
    std::cerr << "can't use early discarding with batch decoding!" << std::endl;
    abort();
  }
}

void SearchNormalBatch::EvalAndMergePartialHypos()
{
  std::vector<Hypothesis*>::iterator partial_hypo_iter;
  for (partial_hypo_iter = m_partial_hypos.begin();
       partial_hypo_iter != m_partial_hypos.end();
       ++partial_hypo_iter) {
    Hypothesis* hypo = *partial_hypo_iter;

    // Evaluate with other ffs.
    std::map<int, StatefulFeatureFunction*>::iterator sfff_iter;
    for (sfff_iter = m_stateful_ffs.begin();
         sfff_iter != m_stateful_ffs.end();
         ++sfff_iter) {
      const StatefulFeatureFunction &ff = *(sfff_iter->second);
      int state_idx = sfff_iter->first;
      hypo->EvaluateWith(ff, state_idx);
    }
    std::vector<const StatelessFeatureFunction*>::iterator slff_iter;
    for (slff_iter = m_stateless_ffs.begin();
         slff_iter != m_stateless_ffs.end();
         ++slff_iter) {
      hypo->EvaluateWith(**slff_iter);
    }
  }

  // Wait for all requests from the distributed LM to come back.
  std::map<int, LanguageModel*>::iterator dlm_iter;
  for (dlm_iter = m_dlm_ffs.begin();
       dlm_iter != m_dlm_ffs.end();
       ++dlm_iter) {
    (*dlm_iter).second->sync();
  }

  // Incorporate the DLM scores into all hypotheses and put into their
  // stacks.
  for (partial_hypo_iter = m_partial_hypos.begin();
       partial_hypo_iter != m_partial_hypos.end();
       ++partial_hypo_iter) {
    Hypothesis* hypo = *partial_hypo_iter;

    // Calculate DLM scores.
    std::map<int, LanguageModel*>::iterator dlm_iter;
    for (dlm_iter = m_dlm_ffs.begin();
         dlm_iter != m_dlm_ffs.end();
         ++dlm_iter) {
      LanguageModel &lm = *(dlm_iter->second);
      hypo->EvaluateWith(lm, (*dlm_iter).first);
    }

    // Put completed hypothesis onto its stack.
    size_t wordsTranslated = hypo->GetWordsBitmap().GetNumWordsCovered();
    m_hypoStackColl[wordsTranslated]->AddPrune(hypo);
  }
  m_partial_hypos.clear();

  std::vector < HypothesisStack* >::iterator stack_iter;
  HypothesisStackNormal* stack;
  for (stack_iter = m_hypoStackColl.begin();
       stack_iter != m_hypoStackColl.end();
       ++stack_iter) {
    stack = static_cast<HypothesisStackNormal*>(*stack_iter);
    stack->PruneToSize(m_max_stack_size);
  }
}

}
<|endoftext|>


<commit_before>// -*- mode: c++; indent-tabs-mode: nil; tab-width:2  -*-

#include "Translator.h"
#include "TranslationRequest.h"
#include "Server.h"

namespace MosesServer
{

using namespace std;
using namespace Moses;

Translator::
Translator(Server& server)
  : m_threadPool(server.options().numThreads),
    m_server(server)
{
  // signature and help strings are documentation -- the client
  // can query this information with a system.methodSignature and
  // system.methodHelp RPC.
  this->_signature = "S:S";
  this->_help = "Does translation";
}

void
Translator::
execute(xmlrpc_c::paramList const& paramList,
        xmlrpc_c::value *   const  retvalP)
{
  boost::condition_variable cond;
  boost::mutex mut;
  boost::shared_ptr<TranslationRequest> task;
  task = TranslationRequest::create(this, paramList,cond,mut);
  m_threadPool.Submit(task);
  boost::unique_lock<boost::mutex> lock(mut);
  while (!task->IsDone())
    cond.wait(lock);
  *retvalP = xmlrpc_c::value_struct(task->GetRetData());
}

Session const&
Translator::
get_session(uint64_t const id)
{
  return m_server.get_session(id);
}

}
<commit_msg>Initialization order of members.<commit_after>// -*- mode: c++; indent-tabs-mode: nil; tab-width:2  -*-

#include "Translator.h"
#include "TranslationRequest.h"
#include "Server.h"

namespace MosesServer
{

using namespace std;
using namespace Moses;

Translator::
Translator(Server& server)
  : m_server(server),
    m_threadPool(server.options().numThreads)
{
  // signature and help strings are documentation -- the client
  // can query this information with a system.methodSignature and
  // system.methodHelp RPC.
  this->_signature = "S:S";
  this->_help = "Does translation";
}

void
Translator::
execute(xmlrpc_c::paramList const& paramList,
        xmlrpc_c::value *   const  retvalP)
{
  boost::condition_variable cond;
  boost::mutex mut;
  boost::shared_ptr<TranslationRequest> task;
  task = TranslationRequest::create(this, paramList,cond,mut);
  m_threadPool.Submit(task);
  boost::unique_lock<boost::mutex> lock(mut);
  while (!task->IsDone())
    cond.wait(lock);
  *retvalP = xmlrpc_c::value_struct(task->GetRetData());
}

Session const&
Translator::
get_session(uint64_t const id)
{
  return m_server.get_session(id);
}

}
<|endoftext|>


<commit_before>#ifndef CMDSTAN_ARGUMENTS_ARG_SEED_HPP
#define CMDSTAN_ARGUMENTS_ARG_SEED_HPP

#include <cmdstan/arguments/singleton_argument.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>

namespace cmdstan {

class arg_seed : public long_long_int_argument {
 public:
  unsigned int _random_value;
  arg_seed() : long_long_int_argument() {
    _name = "seed";
    _description = "Random number generator seed";
    _validity = "non-negative integer < 4294967296  or -1 to generate seed from system time";
    _default = "-1";
    _default_value = -1;
    _constrained = true;
    _good_value = 18383;
    _bad_value = -2;
    _value = _default_value;
    _random_value
        = (boost::posix_time::microsec_clock::universal_time()
           - boost::posix_time::ptime(boost::posix_time::min_date_time))
              .total_milliseconds();
  }

  bool is_valid(long long int value) { return (value <= UINT_MAX && value >= 0) || value == _default_value; }

  unsigned int random_value() {
    if (_value == _default_value) {
      return _random_value;
    } else {
      return _value;
    }
  }

  std::string print_value() {
    if (_value == _default_value) {
      return boost::lexical_cast<std::string>(_random_value);
    } else {
      return boost::lexical_cast<std::string>(_value);
    }
  }
};

}  // namespace cmdstan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef CMDSTAN_ARGUMENTS_ARG_SEED_HPP
#define CMDSTAN_ARGUMENTS_ARG_SEED_HPP

#include <cmdstan/arguments/singleton_argument.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>

namespace cmdstan {

class arg_seed : public long_long_int_argument {
 public:
  unsigned int _random_value;
  arg_seed() : long_long_int_argument() {
    _name = "seed";
    _description = "Random number generator seed";
    _validity
        = "non-negative integer < 4294967296  or -1 to generate seed from "
          "system time";
    _default = "-1";
    _default_value = -1;
    _constrained = true;
    _good_value = 18383;
    _bad_value = -2;
    _value = _default_value;
    _random_value
        = (boost::posix_time::microsec_clock::universal_time()
           - boost::posix_time::ptime(boost::posix_time::min_date_time))
              .total_milliseconds();
  }

  bool is_valid(long long int value) {
    return (value <= UINT_MAX && value >= 0) || value == _default_value;
  }

  unsigned int random_value() {
    if (_value == _default_value) {
      return _random_value;
    } else {
      return _value;
    }
  }

  std::string print_value() {
    if (_value == _default_value) {
      return boost::lexical_cast<std::string>(_random_value);
    } else {
      return boost::lexical_cast<std::string>(_value);
    }
  }
};

}  // namespace cmdstan
#endif
<|endoftext|>


<commit_before>#ifndef UNIVERSE_HPP
#define UNIVERSE_HPP

#include <SFML/Graphics.hpp>
#include <iostream>
#include <random>
#include <cmath>
#include "Body.hpp"

#ifndef M_PI
	#define M_PI 3.14
#endif

class Universe
{
public:
	void addPlanet(sf::Vector2f position, uint64_t m, sf::Vector2f dir);
	void addPlanet(Body p);
	void createProtodisk(const int number, const int radius, const int mass, const sf::Vector2f& position);

	void move(float delta_t);
	void draw(sf::RenderWindow& window);
	void eraseAt(const sf::Vector2f& pos);

private:
	std::vector<Body> planets;

	// Protodisk stuff
	std::mt19937 rng;
	std::uniform_real_distribution<float> distribution;
};

Body combinedPlanets(const Body& a, const Body& b);

#endif // UNIVERSE_HPP<commit_msg>Delete Universe.hpp<commit_after><|endoftext|>


<commit_before>//----------------------------  tensor_base.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2010 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  tensor_base.cc  ---------------------------

// check serialization for Tensor<1,dim>

#include "../tests.h"
#include <base/tensor.h>
#include <base/logstream.h>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <sstream>
#include <fstream>
#include <iomanip>

template <typename T>
void verify (const T &t1,
	     const T &t2)
{
				   // save data to archive
  std::ostringstream oss;
  {
    boost::archive::text_oarchive oa(oss);
    oa << t1;
				     // archive and stream closed when
				     // destructors are called
  }
  deallog << oss.str() << std::endl;

				   // verify correctness of the
				   // serialization
  {
    std::istringstream  iss(oss.str());
    boost::archive::text_iarchive ia(iss);

    ia >> t2;

    Assert (t1 == t2, ExcInternalError());
  }
}

void test ()
{
  const unsigned int dim=3;

  double a1[3] = {1, 2, 3};
  Tensor<1,dim> t1(a1);

  double a2[3] = {3, 6, 9};
  Tensor<1,dim> t2 (a2);

  verify (t1, t2);
}

int main ()
{
  std::ofstream logfile("tensor_base/output");
  deallog << std::setprecision(3);
  deallog.attach(logfile);
  deallog.depth_console(0);
  deallog.threshold_double(1.e-10);

  test ();

  deallog << "OK" << std::endl;
}
<commit_msg>Make objects non-const so that we can load into them.<commit_after>//----------------------------  tensor_base.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2010 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  tensor_base.cc  ---------------------------

// check serialization for Tensor<1,dim>

#include "../tests.h"
#include <base/tensor.h>
#include <base/logstream.h>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <sstream>
#include <fstream>
#include <iomanip>

template <typename T>
void verify (T &t1,
	     T &t2)
{
				   // save data to archive
  std::ostringstream oss;
  {
    boost::archive::text_oarchive oa(oss);
    oa << t1;
				     // archive and stream closed when
				     // destructors are called
  }
  deallog << oss.str() << std::endl;

				   // verify correctness of the
				   // serialization
  {
    std::istringstream  iss(oss.str());
    boost::archive::text_iarchive ia(iss);

    ia >> t2;

    Assert (t1 == t2, ExcInternalError());
  }
}

void test ()
{
  const unsigned int dim=3;

  double a1[3] = {1, 2, 3};
  Tensor<1,dim> t1(a1);

  double a2[3] = {3, 6, 9};
  Tensor<1,dim> t2 (a2);

  verify (t1, t2);
}

int main ()
{
  std::ofstream logfile("tensor_base/output");
  deallog << std::setprecision(3);
  deallog.attach(logfile);
  deallog.depth_console(0);
  deallog.threshold_double(1.e-10);

  test ();

  deallog << "OK" << std::endl;
}
<|endoftext|>