text:
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <chrono>
#include <iostream>
#include <thread>

#include <boost/thread/latch.hpp>

#include <gtest/gtest.h>

#include <geode/AuthInitialize.hpp>
#include <geode/Cache.hpp>
#include <geode/CqAttributesFactory.hpp>
#include <geode/CqEvent.hpp>
#include <geode/PoolManager.hpp>
#include <geode/QueryService.hpp>
#include <geode/RegionFactory.hpp>
#include <geode/RegionShortcut.hpp>

#include "CacheRegionHelper.hpp"
#include "SimpleAuthInitialize.hpp"
#include "SimpleCqListener.hpp"
#include "framework/Cluster.h"

namespace {

using apache::geode::client::AuthInitialize;
using apache::geode::client::Cache;
using apache::geode::client::Cacheable;
using apache::geode::client::CacheableKey;
using apache::geode::client::CacheableString;
using apache::geode::client::CacheFactory;
using apache::geode::client::CqAttributes;
using apache::geode::client::CqAttributesFactory;
using apache::geode::client::CqEvent;
using apache::geode::client::CqListener;
using apache::geode::client::CqOperation;
using apache::geode::client::Exception;
using apache::geode::client::HashMapOfCacheable;
using apache::geode::client::Pool;
using apache::geode::client::Properties;
using apache::geode::client::QueryService;
using apache::geode::client::Region;
using apache::geode::client::RegionShortcut;

using std::chrono::minutes;

const int32_t CQ_PLUS_AUTH_TEST_REGION_ENTRY_COUNT = 50000;
const int32_t CQ_REAUTH_TEST_REGION_ENTRY_COUNT = 5000;

Cache createCache(std::shared_ptr<SimpleAuthInitialize> auth) {
  auto cache = CacheFactory()
                   .set("log-level", "none")
                   .set("statistic-sampling-enabled", "false")
                   .setAuthInitialize(auth)
                   .create();

  return cache;
}

Cache createDurableCache(std::shared_ptr<SimpleAuthInitialize> auth) {
  auto pp = Properties::create();
  pp->insert("durable-client-id", "DurableClient-1111");
  pp->insert("durable-timeout", std::chrono::seconds(600));
  auto cache = CacheFactory(pp)
                   .set("log-level", "none")
                   .set("statistic-sampling-enabled", "false")
                   .setAuthInitialize(auth)
                   .create();

  return cache;
}

std::shared_ptr<Pool> createPool(Cluster& cluster, Cache& cache,
                                 bool subscriptionEnabled) {
  auto poolFactory = cache.getPoolManager().createFactory().setIdleTimeout(
      std::chrono::milliseconds(0));

  cluster.applyLocators(poolFactory);
  poolFactory.setPRSingleHopEnabled(true).setSubscriptionEnabled(
      subscriptionEnabled);

  return poolFactory.create("default");
}

std::shared_ptr<Region> setupRegion(Cache& cache,
                                    const std::shared_ptr<Pool>& pool) {
  auto region = cache.createRegionFactory(RegionShortcut::PROXY)
                    .setPoolName(pool->getName())
                    .create("region");

  return region;
}

TEST(CqPlusAuthInitializeTest, putInALoopWhileSubscribedAndAuthenticated) {
  Cluster cluster(
      Name(std::string(::testing::UnitTest::GetInstance()
                           ->current_test_info()
                           ->test_suite_name()) +
           "/" +
           ::testing::UnitTest::GetInstance()->current_test_info()->name()),
      Classpath{getFrameworkString(FrameworkVariable::JavaObjectJarPath)},
      SecurityManager{"javaobject.SimpleSecurityManager"}, User{"root"},
      Password{"root-password"}, LocatorCount{1}, ServerCount{1});

  cluster.start();

  cluster.getGfsh()
      .create()
      .region()
      .withName("region")
      .withType("PARTITION")
      .execute();

  auto authInitialize = std::make_shared<SimpleAuthInitialize>();
  auto cache = createCache(authInitialize);
  auto pool = createPool(cluster, cache, true);
  auto region = setupRegion(cache, pool);

  try {
    region->put("foo", "bar");
  } catch (const Exception& ex) {
    std::cerr << "Caught exception: " << ex.what() << std::endl;
    std::cerr << "In initial region put" << std::endl;
    std::cerr << "Callstack" << ex.getStackTrace() << std::endl;
    FAIL();
  }

  auto queryService = cache.getQueryService();

  auto createLatch =
      std::make_shared<boost::latch>(CQ_PLUS_AUTH_TEST_REGION_ENTRY_COUNT);
  auto updateLatch =
      std::make_shared<boost::latch>(CQ_PLUS_AUTH_TEST_REGION_ENTRY_COUNT);
  auto destroyLatch =
      std::make_shared<boost::latch>(CQ_PLUS_AUTH_TEST_REGION_ENTRY_COUNT);
  auto testListener = std::make_shared<SimpleCqListener>(
      createLatch, updateLatch, destroyLatch);

  CqAttributesFactory attributesFactory;
  attributesFactory.addCqListener(testListener);
  auto cqAttributes = attributesFactory.create();

  auto query =
      queryService->newCq("SimpleCQ", "SELECT * FROM /region", cqAttributes);

  try {
    query->execute();
  } catch (const Exception& ex) {
    std::cerr << "Caught exception: " << ex.what() << std::endl;
    std::cerr << "While executing Cq" << std::endl;
    std::cerr << "Callstack" << ex.getStackTrace() << std::endl;
    FAIL();
  }

  int32_t i = 0;

  try {
    for (i = 0; i < CQ_PLUS_AUTH_TEST_REGION_ENTRY_COUNT; i++) {
      region->put("key" + std::to_string(i), "value" + std::to_string(i));
      std::this_thread::yield();
    }
  } catch (const Exception& ex) {
    std::cerr << "Caught exception: " << ex.what() << std::endl;
    std::cerr << "In value create loop, i=" << i << std::endl;
    std::cerr << "Callstack" << ex.getStackTrace() << std::endl;
    FAIL();
  }

  try {
    for (i = 0; i < CQ_PLUS_AUTH_TEST_REGION_ENTRY_COUNT; i++) {
      region->put("key" + std::to_string(i), "value" + std::to_string(i + 1));
      std::this_thread::yield();
    }
  } catch (const Exception& ex) {
    std::cerr << "Caught exception: " << ex.what() << std::endl;
    std::cerr << "In value update loop, i=" << i << std::endl;
    std::cerr << "Callstack" << ex.getStackTrace() << std::endl;
    FAIL();
  }

  try {
    for (i = 0; i < CQ_PLUS_AUTH_TEST_REGION_ENTRY_COUNT; i++) {
      region->destroy("key" + std::to_string(i));
      std::this_thread::yield();
    }
  } catch (const Exception& ex) {
    std::cerr << "Caught exception: " << ex.what() << std::endl;
    std::cerr << "In value destroy loop, i=" << i << std::endl;
    std::cerr << "Callstack" << ex.getStackTrace() << std::endl;
    FAIL();
  }

  EXPECT_EQ(boost::cv_status::no_timeout,
            createLatch->wait_for(boost::chrono::seconds(30)));
  EXPECT_EQ(boost::cv_status::no_timeout,
            updateLatch->wait_for(boost::chrono::seconds(30)));
  EXPECT_EQ(boost::cv_status::no_timeout,
            destroyLatch->wait_for(boost::chrono::seconds(30)));

  EXPECT_GT(authInitialize->getGetCredentialsCallCount(), 0);
}

TEST(CqPlusAuthInitializeTest, reAuthenticateWithDurable) {
  // Start a cluster with user expiration support

  Cluster cluster(
      Name(std::string(::testing::UnitTest::GetInstance()
                           ->current_test_info()
                           ->test_suite_name()) +
           "/" +
           ::testing::UnitTest::GetInstance()->current_test_info()->name()),
      Classpath{getFrameworkString(FrameworkVariable::JavaObjectJarPath)},
      SecurityManager{"javaobject.SimulatedExpirationSecurityManager"},
      User{"root"}, Password{"root-password"}, LocatorCount{1}, ServerCount{1});

  cluster.start();

  cluster.getGfsh()
      .create()
      .region()
      .withName("region")
      .withType("PARTITION")
      .execute();

  // Use a non-root user for reAuthentication testing.

  auto authInitialize =
      std::make_shared<SimpleAuthInitialize>("user", "user-password");
  auto cache = createDurableCache(authInitialize);
  auto pool = createPool(cluster, cache, true);
  auto region = setupRegion(cache, pool);

  try {
    region->put("foo", "bar");
  } catch (const Exception& ex) {
    std::cerr << "Caught exception: " << ex.what() << std::endl;
    std::cerr << "In initial region put" << std::endl;
    std::cerr << "Callstack" << ex.getStackTrace() << std::endl;
    FAIL();
  }

  auto queryService = cache.getQueryService();

  auto createLatch =
      std::make_shared<boost::latch>(CQ_REAUTH_TEST_REGION_ENTRY_COUNT);
  auto updateLatch =
      std::make_shared<boost::latch>(CQ_REAUTH_TEST_REGION_ENTRY_COUNT);
  auto destroyLatch =
      std::make_shared<boost::latch>(CQ_REAUTH_TEST_REGION_ENTRY_COUNT);
  auto testListener = std::make_shared<SimpleCqListener>(
      createLatch, updateLatch, destroyLatch);

  CqAttributesFactory attributesFactory;
  attributesFactory.addCqListener(testListener);
  auto cqAttributes = attributesFactory.create();

  auto query = queryService->newCq("SimpleCQ", "SELECT * FROM /region",
                                   cqAttributes, true);

  try {
    query->execute();
  } catch (const Exception& ex) {
    std::cerr << "Caught exception: " << ex.what() << std::endl;
    std::cerr << "While executing Cq" << std::endl;
    std::cerr << "Callstack" << ex.getStackTrace() << std::endl;
    FAIL();
  }

  int32_t i = 0;

  cache.readyForEvents();

  try {
    for (i = 0; i < CQ_REAUTH_TEST_REGION_ENTRY_COUNT; i++) {
      region->put("key" + std::to_string(i), "value" + std::to_string(i));
      std::this_thread::yield();
    }
  } catch (const Exception& ex) {
    std::cerr << "Caught exception: " << ex.what() << std::endl;
    std::cerr << "In value create loop, i=" << i << std::endl;
    std::cerr << "Callstack" << ex.getStackTrace() << std::endl;
    FAIL();
  }

  try {
    for (i = 0; i < CQ_REAUTH_TEST_REGION_ENTRY_COUNT; i++) {
      region->put("key" + std::to_string(i), "value" + std::to_string(i + 1));
      std::this_thread::yield();
    }
  } catch (const Exception& ex) {
    std::cerr << "Caught exception: " << ex.what() << std::endl;
    std::cerr << "In value update loop, i=" << i << std::endl;
    std::cerr << "Callstack" << ex.getStackTrace() << std::endl;
    FAIL();
  }

  try {
    for (i = 0; i < CQ_REAUTH_TEST_REGION_ENTRY_COUNT; i++) {
      region->destroy("key" + std::to_string(i));
      std::this_thread::yield();
    }
  } catch (const Exception& ex) {
    std::cerr << "Caught exception: " << ex.what() << std::endl;
    std::cerr << "In value destroy loop, i=" << i << std::endl;
    std::cerr << "Callstack" << ex.getStackTrace() << std::endl;
    FAIL();
  }

  EXPECT_EQ(boost::cv_status::no_timeout,
            createLatch->wait_for(boost::chrono::seconds(90)));
  EXPECT_EQ(boost::cv_status::no_timeout,
            updateLatch->wait_for(boost::chrono::seconds(90)));
  EXPECT_EQ(boost::cv_status::no_timeout,
            destroyLatch->wait_for(boost::chrono::seconds(90)));

  // SimulatedExpirationSecurityManager is set to throw
  // AuthenticationExpiredException for 1% of operations.
  // If the random number generator were perfect we'd expect reauth
  // to happen for 1% of the operations. Back it off to .5% since
  // it's not perfect.
  //
  // Number of operations is 3 * CQ_REAUTH_TEST_REGION_ENTRY_COUNT
  // since doing put, update, and destory.

  EXPECT_GT(authInitialize->getGetCredentialsCallCount(),
            3 * CQ_REAUTH_TEST_REGION_ENTRY_COUNT * .005);

  // Keep the durable messages so we can test getting them back
  // on reconnect.

  cache.close(true);

  // Create a new durable cache with the same durable-client-id and
  // ensure we get all the events that were created.

  auto cacheRecovery = createDurableCache(authInitialize);
  auto poolRecovery = createPool(cluster, cacheRecovery, true);
  auto regionRecovery = setupRegion(cacheRecovery, poolRecovery);

  auto queryServiceRecovery = cacheRecovery.getQueryService();

  auto createLatchRecovery =
      std::make_shared<boost::latch>(CQ_REAUTH_TEST_REGION_ENTRY_COUNT);
  auto updateLatchRecovery =
      std::make_shared<boost::latch>(CQ_REAUTH_TEST_REGION_ENTRY_COUNT);
  auto destroyLatchRecovery =
      std::make_shared<boost::latch>(CQ_REAUTH_TEST_REGION_ENTRY_COUNT);
  auto testListenerRecovery = std::make_shared<SimpleCqListener>(
      createLatchRecovery, updateLatchRecovery, destroyLatchRecovery);

  CqAttributesFactory attributesFactoryRecovery;
  attributesFactoryRecovery.addCqListener(testListenerRecovery);
  auto cqAttributesRecovery = attributesFactoryRecovery.create();

  auto queryRecovery = queryServiceRecovery->newCq(
      "SimpleCQ", "SELECT * FROM /region", cqAttributesRecovery, true);

  try {
    queryRecovery->execute();
  } catch (const Exception& ex) {
    std::cerr << "Caught exception: " << ex.what() << std::endl;
    std::cerr << "While executing Cq" << std::endl;
    std::cerr << "Callstack" << ex.getStackTrace() << std::endl;
    FAIL();
  }

  cacheRecovery.readyForEvents();

  EXPECT_EQ(boost::cv_status::no_timeout,
            createLatchRecovery->wait_for(boost::chrono::seconds(90)));
  EXPECT_EQ(boost::cv_status::no_timeout,
            updateLatchRecovery->wait_for(boost::chrono::seconds(90)));
  EXPECT_EQ(boost::cv_status::no_timeout,
            destroyLatchRecovery->wait_for(boost::chrono::seconds(90)));
}

}  // namespace

max_stars_repo_name: onichols-pivotal/geode-native

max_issues_repo_name: onichols-pivotal/geode-native

max_forks_repo_name: onichols-pivotal/geode-native


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2012-2013. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#ifndef BOOST_CONTAINER_THROW_EXCEPTION_HPP
#define BOOST_CONTAINER_THROW_EXCEPTION_HPP

#ifndef BOOST_CONFIG_HPP
#  include <boost/config.hpp>
#endif

#if defined(BOOST_HAS_PRAGMA_ONCE)
#  pragma once
#endif

#include <boost/container/detail/config_begin.hpp>
#include <boost/container/detail/workaround.hpp>

#ifndef BOOST_NO_EXCEPTIONS
   #include <stdexcept> //for std exception types
   #include <string>    //for implicit std::string conversion
   #include <new>       //for std::bad_alloc
#else
   #include <boost/assert.hpp>
   #include <cstdlib>   //for std::abort
#endif

namespace boost {
namespace container {

#if defined(BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS)
   //The user must provide definitions for the following functions

   void throw_bad_alloc();

   void throw_out_of_range(const char* str);

   void throw_length_error(const char* str);

   void throw_logic_error(const char* str);

   void throw_runtime_error(const char* str);

#elif defined(BOOST_NO_EXCEPTIONS)

   inline void throw_bad_alloc()
   {
      BOOST_ASSERT(!"boost::container bad_alloc thrown");
      std::abort();
   }

   inline void throw_out_of_range(const char* str)
   {
      BOOST_ASSERT_MSG(!"boost::container out_of_range thrown", str);
      std::abort();
   }

   inline void throw_length_error(const char* str)
   {
      BOOST_ASSERT_MSG(!"boost::container length_error thrown", str);
      std::abort();
   }

   inline void throw_logic_error(const char* str)
   {
      BOOST_ASSERT_MSG(!"boost::container logic_error thrown", str);
      std::abort();
   }

   inline void throw_runtime_error(const char* str)
   {
      BOOST_ASSERT_MSG(!"boost::container runtime_error thrown", str);
      std::abort();
   }

#else //defined(BOOST_NO_EXCEPTIONS)

   //! Exception callback called by Boost.Container when fails to allocate the requested storage space.
   //!

   //!
If BOOST_NO_EXCEPTIONS is NOT defined std::bad_alloc() is thrown.

   //!
   //!
If BOOST_NO_EXCEPTIONS is defined and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS
   //!   is NOT defined BOOST_ASSERT(!"boost::container bad_alloc thrown") is called
   //!   and std::abort() if the former returns.

   //!
   //!
If BOOST_NO_EXCEPTIONS and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS are defined
   //!   the user must provide an implementation and the function should not return.

   //!

   inline void throw_bad_alloc()
   {
      throw std::bad_alloc();
   }

   //! Exception callback called by Boost.Container to signal arguments out of range.
   //!

   //!
If BOOST_NO_EXCEPTIONS is NOT defined std::out_of_range(str) is thrown.

   //!
   //!
If BOOST_NO_EXCEPTIONS is defined and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS
   //!   is NOT defined BOOST_ASSERT_MSG(!"boost::container out_of_range thrown", str) is called
   //!   and std::abort() if the former returns.

   //!
   //!
If BOOST_NO_EXCEPTIONS and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS are defined
   //!   the user must provide an implementation and the function should not return.

   //!

   inline void throw_out_of_range(const char* str)
   {
      throw std::out_of_range(str);
   }

   //! Exception callback called by Boost.Container to signal errors resizing.
   //!

   //!
If BOOST_NO_EXCEPTIONS is NOT defined std::length_error(str) is thrown.

   //!
   //!
If BOOST_NO_EXCEPTIONS is defined and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS
   //!   is NOT defined BOOST_ASSERT_MSG(!"boost::container length_error thrown", str) is called
   //!   and std::abort() if the former returns.

   //!
   //!
If BOOST_NO_EXCEPTIONS and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS are defined
   //!   the user must provide an implementation and the function should not return.

   //!

   inline void throw_length_error(const char* str)
   {
      throw std::length_error(str);
   }

   //! Exception callback called by Boost.Container  to report errors in the internal logical
   //! of the program, such as violation of logical preconditions or class invariants.
   //!

   //!
If BOOST_NO_EXCEPTIONS is NOT defined std::logic_error(str) is thrown.

   //!
   //!
If BOOST_NO_EXCEPTIONS is defined and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS
   //!   is NOT defined BOOST_ASSERT_MSG(!"boost::container logic_error thrown", str) is called
   //!   and std::abort() if the former returns.

   //!
   //!
If BOOST_NO_EXCEPTIONS and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS are defined
   //!   the user must provide an implementation and the function should not return.

   //!

   inline void throw_logic_error(const char* str)
   {
      throw std::logic_error(str);
   }

   //! Exception callback called by Boost.Container  to report errors that can only be detected during runtime.
   //!

   //!
If BOOST_NO_EXCEPTIONS is NOT defined std::runtime_error(str) is thrown.

   //!
   //!
If BOOST_NO_EXCEPTIONS is defined and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS
   //!   is NOT defined BOOST_ASSERT_MSG(!"boost::container runtime_error thrown", str) is called
   //!   and std::abort() if the former returns.

   //!
   //!
If BOOST_NO_EXCEPTIONS and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS are defined
   //!   the user must provide an implementation and the function should not return.

   //!

   inline void throw_runtime_error(const char* str)
   {
      throw std::runtime_error(str);
   }

#endif

}}  //namespace boost { namespace container {

#include <boost/container/detail/config_end.hpp>

#endif //#ifndef BOOST_CONTAINER_THROW_EXCEPTION_HPP

ext: hpp

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
#include <boost/test/unit_test.hpp>
#include <assimp/types.h>
#include <assimp/Importer.hpp>
#include <assimp/IOStream.hpp>
#include <assimp/IOSystem.hpp>
#include <assimp/DefaultIOSystem.h>

#include <X4ConverterTools/ani/AnimFile.h>
#include <boost/filesystem.hpp>
#include "../testUtil.h"

namespace fs = boost::filesystem;
using namespace boost;
using namespace Assimp;
using namespace ani;
BOOST_AUTO_TEST_SUITE(UnitTests) // NOLINT(cert-err58-cpp)

    BOOST_AUTO_TEST_SUITE(AnimUnitTests) // NOLINT(cert-err58-cpp)

        BOOST_AUTO_TEST_CASE(ani_read_basic) { // NOLINT(cert-err58-cpp)
            // TODO mock reading & writing to memory - would be faster & good form
            // See https://github.com/assimp/assimp/blob/master/include/assimp/MemoryIOWrapper.h
            const std::string aniFile =
                    test::TestUtil::GetBasePath() + "/assets/units/size_s/SHIP_GEN_S_FIGHTER_01_DATA.ANI";
            IOSystem *io = new DefaultIOSystem();
            IOStream *sourceStream = io->Open(aniFile, "rb");
            BOOST_TEST_REQUIRE(sourceStream != nullptr);
            AnimFile file(sourceStream);
            std::cout << file.validate();

            delete io;
        }

        BOOST_AUTO_TEST_CASE(ani_out) { // NOLINT(cert-err58-cpp)
            // TODO fixme
            const std::string aniFile =
                    test::TestUtil::GetBasePath() + "/assets/units/size_s/SHIP_GEN_S_FIGHTER_01_DATA.ANI";
            const std::string xmlFile =
                    test::TestUtil::GetBasePath() + "/assets/units/size_s/ship_gen_s_fighter_01.xml";
            const std::string aniOutFile =
                    test::TestUtil::GetBasePath() + "/assets/units/size_s/ship_gen_s_fighter_01.out.anixml";
//const std::string aniFile = "test::TestUtil::GetBasePath()/test_files/struct_bt_ut_omicron_superyard_data.ani";
//        const std::string aniFile =current_path().string()+"/assets/fx/lensflares/LENSFLARES_DATA.ANI";
            IOSystem *io = new DefaultIOSystem();
            IOStream *sourceStream = io->Open(aniFile, "rb");
            BOOST_TEST_REQUIRE(sourceStream != nullptr);
            AnimFile file(sourceStream);
            std::cout << file.validate();

            // TODO fixme

            pugi::xml_document doc;
            file.WriteIntermediateRepr(xmlFile, doc.root());
            doc.save_file(aniOutFile.c_str());//TODO get rid of this once we validate

            // TODO validate
            delete io;
        }

//        BOOST_AUTO_TEST_CASE(ani_both) { // NOLINT(cert-err58-cpp)
//            // TODO fixme
//            const std::string aniFile =
//                    test::TestUtil::GetBasePath() + "/assets/units/size_s/SHIP_GEN_S_FIGHTER_01_DATA.ANI";
//            const std::string xmlFile =
//                    test::TestUtil::GetBasePath() + "/assets/units/size_s/ship_gen_s_fighter_01.xml";
//            IOSystem *io = new DefaultIOSystem();
//            IOStream *sourceStream = io->Open(aniFile, "rb");
//            BOOST_TEST_REQUIRE(sourceStream != nullptr);
//            AnimFile file(sourceStream);
//            std::string expected = file.validate();
//            std::cout << "Expected:\n" << expected;
//
//            // TODO fixme
//
//            pugi::xml_document doc;
//            file.WriteIntermediateRepr(xmlFile, doc.root());
//            AnimFile reverse = AnimFile(doc.root());
//            std::string actual = reverse.validate();
//            std::cout << "Actual:\n" << actual;
//            BOOST_TEST(expected == actual);
//            // TODO validate better
//            delete io;
//        }

    BOOST_AUTO_TEST_SUITE_END() // NOLINT(cert-err58-cpp)
BOOST_AUTO_TEST_SUITE_END() // NOLINT(cert-err58-cpp)

BOOST_AUTO_TEST_SUITE(ValidateData)

    BOOST_AUTO_TEST_CASE(ani_struct_correctness) { // NOLINT(cert-err58-cpp)
        // TODO mock reading & writing to memory - would be faster & good form
        // See https://github.com/assimp/assimp/blob/master/include/assimp/MemoryIOWrapper.h
        const fs::path basePath = fs::path(std::getenv("X4_UNPACKED_ROOT"));
        fs::recursive_directory_iterator iter(basePath);
        IOSystem *io = new DefaultIOSystem();
        for (const auto &x : iter) {
            const fs::path &filePath = x.path();
            if (filePath.has_extension() && iequals(filePath.extension().generic_string(), ".ANI")) {
//                std::cout << filePath << std::endl;

                auto sourceStream = io->Open(filePath.generic_string(), "rb");
                try {
                    AnimFile file(sourceStream);
                    std::cout << filePath.c_str() << std::endl;
                    file.validate();
                } catch (std::runtime_error &e) {
                    std::string error = str(format("Filepath: %1% Exception:\n %2%\n") % filePath.c_str() % e.what());
                    // Change to BOOST_CHECK_MESSAGE if you want all the files violating the structure
                    BOOST_REQUIRE_MESSAGE(false, error);
                }
            }
        }
        // To make a confusing warning go away
        BOOST_REQUIRE_MESSAGE(true, "No files should have errors");
        delete io;
    }

BOOST_AUTO_TEST_SUITE_END() // NOLINT(cert-err58-cpp)

ext: cpp


text:
/*
 * Copyright (c) 2018 Ryan Berryhill, University of Toronto
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include "sat/sat.h"

#define BOOST_TEST_MODULE SATTest

#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>

#include <algorithm>

using namespace SAT;

typedef std::unique_ptr<SAT::Solver> SolverPointer;

struct SATFixture
{
    SATFixture()
    {
        SolverPointer minisat(new MinisatSolver);
        SolverPointer minisat_simp(new MinisatSimplifyingSolver);
        SolverPointer glucose(new GlucoseSolver);
        solvers.push_back(std::move(minisat));
        solvers.push_back(std::move(minisat_simp));
        solvers.push_back(std::move(glucose));
    }

    std::vector<SolverPointer> solvers;
};

void sortClauseVec(std::vector<Clause> & vec)
{
    for (Clause & cls : vec)
    {
        std::sort(cls.begin(), cls.end());
    }
    std::sort(vec.begin(), vec.end());
}

BOOST_AUTO_TEST_CASE(one_var)
{
    SATFixture f;

    for (auto & slv : f.solvers)
    {
        BOOST_CHECK(!slv->isSAT());
        Variable v = slv->newVariable();

        // (v)
        slv->addClause({v});
        BOOST_CHECK(slv->solve({}));
        BOOST_CHECK(slv->isSAT());

        // (v) & (-v)[assumption]
        BOOST_CHECK(!slv->solve({negate(v)}));
        BOOST_CHECK(!slv->isSAT());

        // (v) & (-v)
        slv->addClause({negate(v)});
        BOOST_CHECK(!slv->isSAT());
        BOOST_CHECK(!slv->solve({}));
    }
}

BOOST_AUTO_TEST_CASE(three_var)
{
    SATFixture f;

    for (auto & slv : f.solvers)
    {
        Variable a = slv->newVariable();
        Variable b = slv->newVariable();
        Variable c = slv->newVariable();

        // (a) & (b V c) & (-c)
        Cube empty_assumps;
        slv->addClause({a});
        slv->addClause({b, c});
        slv->addClause({negate(c)});
        BOOST_CHECK(slv->solve({}));

        BOOST_CHECK(!slv->solve({c}));

        BOOST_CHECK(slv->solve({b}));

        slv->addClause({b});
        BOOST_CHECK(slv->solve(empty_assumps));
        BOOST_CHECK(!slv->solve({negate(b)}));
    }
}

BOOST_AUTO_TEST_CASE(get_assignment)
{
    SATFixture f;

    for (auto & slv : f.solvers)
    {
        Variable a = slv->newVariable();
        Variable b = slv->newVariable();

        // (-a V -b)
        slv->addClause({negate(a), negate(b)});
        BOOST_CHECK(slv->solve({a}));
        BOOST_CHECK_EQUAL(slv->getAssignment(a), TRUE);
        BOOST_CHECK_EQUAL(slv->getAssignment(b), FALSE);

        BOOST_CHECK(slv->solve({b}));
        BOOST_CHECK_EQUAL(slv->getAssignment(a), FALSE);
        BOOST_CHECK_EQUAL(slv->getAssignment(b), TRUE);
    }
}

BOOST_AUTO_TEST_CASE(critical_assumptions)
{
    SATFixture f;
    for (auto & slv : f.solvers)
    {
        Variable a = slv->newVariable();
        Variable b = slv->newVariable();
        Variable c = slv->newVariable();
        Variable d = slv->newVariable();

        slv->addClause({a, b, c, d});
        slv->addClause({negate(a), negate(b), negate(c), negate(d)});
        slv->addClause({negate(c), d});

        Cube assumps = { a, b, c, d };
        Cube crits;
        BOOST_REQUIRE(!slv->solve(assumps, &crits));

        // Criticals are sufficient to prove UNSAT
        BOOST_CHECK(!crits.empty());
        BOOST_CHECK(!slv->solve(crits));

        // Each critical should be from the assumptions
        for (Literal l : crits)
        {
            BOOST_CHECK(std::find(assumps.begin(), assumps.end(), l) != assumps.end());
        }
    }
}

BOOST_AUTO_TEST_CASE(clause_iterators)
{
    SATFixture f;
    Cube empty;

    for (auto & slv : f.solvers)
    {
        std::vector<Clause> clauses(slv->begin_clauses(), slv->end_clauses());
        BOOST_CHECK_EQUAL(clauses.size(), 0);

        Variable a = slv->newVariable();
        Variable b = slv->newVariable();

        // (-a V -b)
        Clause c0 = {negate(a), negate(b)};
        slv->addClause(c0);

        std::vector<Clause> expected = {c0};
        clauses = std::vector<Clause>(slv->begin_clauses(), slv->end_clauses());
        sortClauseVec(expected);
        sortClauseVec(clauses);

        BOOST_CHECK_EQUAL(clauses.size(), 1);
        BOOST_CHECK(clauses == expected);

        BOOST_CHECK(slv->solve(empty));

        // Calling solve didn't change anything
        clauses = std::vector<Clause>(slv->begin_clauses(), slv->end_clauses());
        sortClauseVec(clauses);

        BOOST_CHECK_EQUAL(clauses.size(), 1);
        BOOST_CHECK(clauses == expected);

        // (-a V -b) & (a V b)
        Clause c1 = {a, b};
        slv->addClause(c1);

        expected = {c0, c1};
        clauses = std::vector<Clause>(slv->begin_clauses(), slv->end_clauses());
        sortClauseVec(expected);
        sortClauseVec(clauses);

        BOOST_CHECK_EQUAL(clauses.size(), 2);
        BOOST_CHECK(clauses == expected);

        BOOST_CHECK(slv->solve(empty));
        BOOST_CHECK(slv->solve({a}));
        BOOST_CHECK(slv->solve({b}));
        BOOST_CHECK(slv->solve({negate(a)}));
        BOOST_CHECK(slv->solve({negate(b)}));
        BOOST_CHECK(!slv->solve({a, b}));
        BOOST_CHECK(!slv->solve({negate(a), negate(b)}));

        clauses = std::vector<Clause>(slv->begin_clauses(), slv->end_clauses());
        sortClauseVec(clauses);
        BOOST_CHECK_EQUAL(clauses.size(), 2);
        BOOST_CHECK(clauses == expected);
    }
}

BOOST_AUTO_TEST_CASE(simplifying_trivial)
{
    MinisatSimplifyingSolver slv;

    Variable a = slv.newVariable();
    Variable b = slv.newVariable();
    Variable c = slv.newVariable();

    slv.addClause({a, c});
    slv.addClause({negate(a), b, negate(c)});

    slv.freeze(a);
    slv.freeze(b);

    slv.eliminate();

    // Everything should be eliminated
    std::vector<Clause> clauses(slv.begin_clauses(), slv.end_clauses());
    BOOST_CHECK_EQUAL(clauses.size(), 0);

    BOOST_CHECK(slv.solve({a, b}));
    BOOST_CHECK_EQUAL(slv.getAssignment(a), SAT::TRUE);
    BOOST_CHECK_EQUAL(slv.getAssignment(b), SAT::TRUE);

    BOOST_CHECK(slv.solve({negate(a), negate(b)}));
    BOOST_CHECK_EQUAL(slv.getAssignment(a), SAT::FALSE);
    BOOST_CHECK_EQUAL(slv.getAssignment(b), SAT::FALSE);
}

BOOST_AUTO_TEST_CASE(simplifying_simple)
{
    MinisatSimplifyingSolver slv;

    Variable a = slv.newVariable();
    Variable b = slv.newVariable();
    Variable c = slv.newVariable();

    slv.addClause({a, b});
    slv.addClause({negate(a), c});
    slv.addClause({negate(b), negate(c)});

    slv.freeze(b);
    slv.freeze(c);

    slv.eliminate();

    std::vector<Clause> clauses(slv.begin_clauses(), slv.end_clauses());
    BOOST_CHECK_EQUAL(clauses.size(), 2);
    std::vector<Clause> expected;
    expected.push_back({b, c});
    expected.push_back({negate(b), negate(c)});

    sortClauseVec(clauses);
    sortClauseVec(expected);

    BOOST_CHECK(clauses == expected);

    BOOST_CHECK(slv.solve({b, negate(c)}));
    BOOST_CHECK_EQUAL(slv.getAssignment(b), SAT::TRUE);
    BOOST_CHECK_EQUAL(slv.getAssignment(c), SAT::FALSE);

    BOOST_CHECK(slv.solve({b}));
    BOOST_CHECK_EQUAL(slv.getAssignment(b), SAT::TRUE);
    BOOST_CHECK_EQUAL(slv.getAssignment(c), SAT::FALSE);

    BOOST_CHECK(slv.solve({c}));
    BOOST_CHECK_EQUAL(slv.getAssignment(b), SAT::FALSE);
    BOOST_CHECK_EQUAL(slv.getAssignment(c), SAT::TRUE);

    BOOST_CHECK(!slv.solve({negate(b), negate(c)}));
}

BOOST_AUTO_TEST_CASE(simplifying_trail)
{
    MinisatSimplifyingSolver slv;

    Variable a = slv.newVariable();
    Variable b = slv.newVariable();
    Variable c = slv.newVariable();
    Variable d = slv.newVariable();

    slv.freeze(a);
    slv.freeze(d);

    slv.addClause({a});
    slv.addClause({a, b});
    slv.addClause({negate(b), c});
    slv.addClause({negate(a), d});

    slv.eliminate();

    // This check mostly checks that the test does something - we
    // don't really want to test how the SAT solver works internally
    std::vector<Literal> trail(slv.begin_trail(), slv.end_trail());
    BOOST_CHECK(!trail.empty());

    BOOST_CHECK(slv.solve({d}));
    BOOST_CHECK(!slv.solve({negate(d)}));

    // Adding the literals on the trail should not change satisfiability
    for (Literal lit : trail)
    {
        Clause cls { lit };
        slv.addClause(cls);
    }

    BOOST_CHECK(slv.solve({d}));
    BOOST_CHECK(!slv.solve({negate(d)}));
}

BOOST_AUTO_TEST_CASE(trail)
{
    SATFixture f;
    Cube empty;

    for (auto & slv : f.solvers)
    {
        Variable a = slv->newVariable();
        Variable b = slv->newVariable();
        Variable c = slv->newVariable();
        Variable d = slv->newVariable();

        slv->addClause({a});
        slv->addClause({a, b});
        slv->addClause({negate(b), c});
        slv->addClause({negate(a), d});

        BOOST_CHECK(slv->solve(empty));

        // We can't check if the trail is empty here - for solvers like Glucose
        // that don't implement an interface to access the trail SAT::Solver
        // should leave it empty
        std::vector<Literal> trail(slv->begin_trail(), slv->end_trail());

        BOOST_CHECK(slv->solve({d}));
        BOOST_CHECK(!slv->solve({negate(d)}));

        // Adding the literals on the trail should not change satisfiability
        for (Literal lit : trail)
        {
            Clause cls { lit };
            slv->addClause(cls);
        }

        BOOST_CHECK(slv->solve({d}));
        BOOST_CHECK(!slv->solve({negate(d)}));
    }
}

max_stars_repo_name: ryanberryhill/pme

max_issues_repo_name: ryanberryhill/pme

max_forks_repo_name: ryanberryhill/pme


text:
#include <boost/bind.hpp>
#include <boost/make_shared.hpp>
#include <vector>
#include "caffe/internode/tree_cluster.hpp"
#include "caffe/MultiSolver.hpp"

namespace caffe {

template <typename Dtype>
MultiSolver<Dtype>::MultiSolver(shared_ptr<Solver<Dtype> > root_solver)
  : root_solver_(root_solver)
  , iter_size(root_solver->param().iter_size()) {
  root_solver->set_forward_backward(
    boost::bind(&MultiSolver<Dtype>::ForwardBackward, this));
}

template <typename Dtype>
Dtype MultiSolver<Dtype>::ForwardBackwardImpl(bool first, bool last) {
  Dtype loss = 0;
  Net<Dtype>& net = *root_solver_->net();
  for (int i = 0; i < net.layers().size(); ++i) {
    if (first) {
      for (int j = 0; j < callbacks_.size(); ++j) {
        callbacks_[j]->on_start(i);
      }
    }
    vector<int> param_ids = net.get_layer_learnable_param_ids(i);
    loss += root_solver_->net()->ForwardFromTo(i, i);
    if (last) {
      for (int j = 0; j < callbacks_.size(); ++j) {
        callbacks_[j]->on_forward_finished(i);
      }
    }
  }

  for (int i = net.layers().size() - 1; i >= 0; --i) {
    if (first) {
      for (int j = 0; j < callbacks_.size(); ++j) {
        callbacks_[j]->on_backward_start(i);
      }
    }
    root_solver_->net()->BackwardFromTo(i, i);
    if (last) {
      for (int j = 0; j < callbacks_.size(); ++j) {
        callbacks_[j]->on_gradients_ready(i);
      }
    }
  }
  return loss;
}

template <typename Dtype>
Dtype MultiSolver<Dtype>::ForwardBackward() {
  Dtype loss = 0;
  for (int i = 0; i < iter_size; ++i) {
    loss += ForwardBackwardImpl(
      (i == 0), (i + 1 == iter_size));
  }
  return loss / iter_size;
}

template <typename Dtype>
void MultiSolver<Dtype>::Solve() {
  root_solver_->Solve();
}

INSTANTIATE_CLASS(MultiSolver);

}  // namespace caffe


text:
#include <iostream>
#include <vector>

#include <Eigen/Core>
#include <stan/math.hpp>

#include "celerite/solver/cholesky.h"

#define DO_TEST(NAME, VAR1, VAR2)                            \
{                                                            \
  double base, comp, delta;                                  \
  base = VAR1;                                               \
  comp = VAR2;                                               \
  delta = std::abs(base - comp);                             \
  if (delta > 1e-10) {                                       \
    std::cerr << "Test failed: '" << #NAME << "' - error: " << delta << " " << base << " " << comp << std::endl; \
    return 1;                                                \
  } else                                                     \
    std::cerr << "Test passed: '" << #NAME << "' - error: " << delta << std::endl; \
}

int main (int argc, char* argv[])
{
  typedef stan::math::var g_t;
  typedef Eigen::Matrix<g_t, Eigen::Dynamic, 1> v_t;
  typedef Eigen::Matrix<g_t, Eigen::Dynamic, Eigen::Dynamic> m_t;

  srand(42);

  size_t N = 1024;
  if (argc >= 2) N = atoi(argv[1]);
  size_t niter = 10;
  if (argc >= 3) niter = atoi(argv[2]);

  // Set up the coefficients.
  size_t p_real = 2, p_complex = 1;
  g_t jitter = g_t(0.01);
  v_t a_real(p_real), c_real(p_real),
      a_comp(p_complex), b_comp(p_complex), c_comp(p_complex), d_comp(p_complex);

  a_real << 1.3, 1.5;
  c_real << 0.5, 0.2;
  a_comp << 1.0;
  b_comp << 0.1;
  c_comp << 1.0;
  d_comp << 1.0;

  // Generate some fake data.
  Eigen::VectorXd x = Eigen::VectorXd::Random(N),
                  yerr2 = Eigen::VectorXd::Random(N),
                  y;

  // Set the scale of the uncertainties.
  yerr2.array() *= 0.1;
  yerr2.array() += 0.3;

  // The times need to be sorted.
  std::sort(x.data(), x.data() + x.size());

  // Compute the y values.
  y = sin(x.array());

  celerite::solver::CholeskySolver<g_t> cholesky;
  cholesky.compute(jitter, a_real, c_real, a_comp, b_comp, c_comp, d_comp, x, yerr2);

  std::vector<g_t> params;
  for (int i = 0; i < p_real; ++i) {
    params.push_back(a_real(i));
    params.push_back(c_real(i));
  }
  for (int i = 0; i < p_complex; ++i) {
    params.push_back(a_comp(i));
    params.push_back(b_comp(i));
    params.push_back(c_comp(i));
    params.push_back(d_comp(i));
  }
  std::vector<double> g;

  g_t ll = -0.5 * (cholesky.dot_solve(y) + cholesky.log_determinant());
  ll.grad(params, g);
  for (int i = 0; i < g.size(); ++i) std::cout << g[i] << std::endl;

  return 0;
}

ext: cc

max_stars_repo_name: dfm/ess

max_issues_repo_name: dfm/ess

max_forks_repo_name: dfm/ess