text:
#include "variant/variant_builder_multi_sample_vector.h"
#include "variant/variant.h"

#include <boost/test/unit_test.hpp>
#include <stdexcept>

using namespace std;
using namespace gamgee;

// Input and expected output for both test_integer_multi_sample_vector_multiple_samples and test_integer_multi_sample_vector_multiple_samples_bulk_setting
const static auto multi_sample_tests_input_values = vector<vector<int32_t>>{ {1, 2, 3}, {1, 2}, {1}, {} };
const static auto multi_sample_tests_expected_output = vector<int32_t>{1, 2, 3, 1, 2, bcf_int32_vector_end, 1, bcf_int32_vector_end, bcf_int32_vector_end, bcf_int32_missing, bcf_int32_vector_end, bcf_int32_vector_end};

BOOST_AUTO_TEST_CASE( test_integer_multi_sample_vector_multiple_samples ) {
  // 4 samples, max of 3 values per sample
  const auto num_samples = 4u;
  const auto max_values_per_sample = 3u;
  auto vec = VariantBuilderMultiSampleVector<int32_t>{num_samples, max_values_per_sample, bcf_int32_missing, bcf_int32_vector_end};

  for ( auto sample_index = 0u; sample_index < multi_sample_tests_input_values.size(); ++sample_index ) {
    // Set each value for each sample individually
    for ( auto value_index = 0u; value_index < multi_sample_tests_input_values[sample_index].size(); ++value_index ) {
      vec.set_sample_value(sample_index, value_index, multi_sample_tests_input_values[sample_index][value_index]);
    }
  }

  BOOST_CHECK_EQUAL(vec.num_samples(), num_samples);
  BOOST_CHECK_EQUAL(vec.max_values_per_sample(), max_values_per_sample);
  BOOST_CHECK_EQUAL(multi_sample_tests_expected_output.size(), vec.get_vector().size());
  auto output_vector = vec.get_vector();
  for ( auto i = 0u; i < multi_sample_tests_expected_output.size(); ++i ) {
    BOOST_CHECK_EQUAL(multi_sample_tests_expected_output[i], output_vector[i]);
  }
}

BOOST_AUTO_TEST_CASE( test_integer_multi_sample_vector_multiple_samples_bulk_setting ) {
  // 4 samples, max of 3 values per sample
  const auto num_samples = 4u;
  const auto max_values_per_sample = 3u;
  auto vec = VariantBuilderMultiSampleVector<int32_t>{num_samples, max_values_per_sample, bcf_int32_missing, bcf_int32_vector_end};

  for ( auto sample_index = 0u; sample_index < multi_sample_tests_input_values.size(); ++sample_index ) {
    // Set all values for each sample at once
    vec.set_sample_values(sample_index, multi_sample_tests_input_values[sample_index]);
  }

  BOOST_CHECK_EQUAL(vec.num_samples(), num_samples);
  BOOST_CHECK_EQUAL(vec.max_values_per_sample(), max_values_per_sample);
  BOOST_CHECK_EQUAL(multi_sample_tests_expected_output.size(), vec.get_vector().size());
  auto output_vector = vec.get_vector();
  for ( auto i = 0u; i < multi_sample_tests_expected_output.size(); ++i ) {
    BOOST_CHECK_EQUAL(multi_sample_tests_expected_output[i], output_vector[i]);
  }
}

BOOST_AUTO_TEST_CASE( test_integer_multi_sample_vector_one_sample ) {
  // 1 sample, max of 3 values per sample
  const auto num_samples = 1u;
  const auto max_values_per_sample = 3u;
  auto vec = VariantBuilderMultiSampleVector<int32_t>{num_samples, max_values_per_sample, bcf_int32_missing, bcf_int32_vector_end};
  auto input_values = vector<int32_t>{1, 2};
  auto expected_output = vector<int32_t>{1, 2, bcf_int32_vector_end};

  vec.set_sample_values(0, input_values);

  BOOST_CHECK_EQUAL(vec.num_samples(), num_samples);
  BOOST_CHECK_EQUAL(vec.max_values_per_sample(), max_values_per_sample);
  BOOST_CHECK_EQUAL(expected_output.size(), vec.get_vector().size());
  auto output_vector = vec.get_vector();
  for ( auto i = 0u; i < expected_output.size(); ++i ) {
    BOOST_CHECK_EQUAL(expected_output[i], output_vector[i]);
  }
}

BOOST_AUTO_TEST_CASE( test_integer_multi_sample_vector_single_valued_field ) {
  // 4 samples, max of 1 value per sample
  const auto num_samples = 4u;
  const auto max_values_per_sample = 1u;
  auto vec = VariantBuilderMultiSampleVector<int32_t>{num_samples, max_values_per_sample, bcf_int32_missing, bcf_int32_vector_end};
  auto input_values = vector<vector<int32_t>>{ {1}, {2}, {}, {3} };
  auto expected_output = vector<int32_t>{1, 2, bcf_int32_missing, 3};

  for ( auto sample_index = 0u; sample_index < input_values.size(); ++sample_index ) {
    // Set all values for each sample at once
    vec.set_sample_values(sample_index, input_values[sample_index]);
  }

  BOOST_CHECK_EQUAL(vec.num_samples(), num_samples);
  BOOST_CHECK_EQUAL(vec.max_values_per_sample(), max_values_per_sample);
  BOOST_CHECK_EQUAL(expected_output.size(), vec.get_vector().size());
  auto output_vector = vec.get_vector();
  for ( auto i = 0u; i < expected_output.size(); ++i ) {
    BOOST_CHECK_EQUAL(expected_output[i], output_vector[i]);
  }
}

BOOST_AUTO_TEST_CASE( test_float_multi_sample_vector_multiple_samples ) {
  auto float_missing = 0.0f; bcf_float_set_missing(float_missing);
  auto float_vector_end = 0.0f; bcf_float_set_vector_end(float_vector_end);

  // 4 samples, max of 3 values per sample
  const auto num_samples = 4u;
  const auto max_values_per_sample = 3u;
  auto vec = VariantBuilderMultiSampleVector<float>{num_samples, max_values_per_sample, float_missing, float_vector_end};
  auto input_values = vector<vector<float>>{ {1.5, 2.5, 3.5}, {1.5, 2.5}, {1.5}, {} };
  auto expected_output = vector<float>{1.5, 2.5, 3.5, 1.5, 2.5, float_vector_end, 1.5, float_vector_end, float_vector_end, float_missing, float_vector_end, float_vector_end};

  for ( auto sample_index = 0u; sample_index < input_values.size(); ++sample_index ) {
    // Set each value for each sample individually
    for ( auto value_index = 0u; value_index < input_values[sample_index].size(); ++value_index ) {
      vec.set_sample_value(sample_index, value_index, input_values[sample_index][value_index]);
    }
  }

  BOOST_CHECK_EQUAL(vec.num_samples(), num_samples);
  BOOST_CHECK_EQUAL(vec.max_values_per_sample(), max_values_per_sample);
  BOOST_CHECK_EQUAL(expected_output.size(), vec.get_vector().size());
  auto output_vector = vec.get_vector();
  for ( auto i = 0u; i < expected_output.size(); ++i ) {
    if ( bcf_float_is_missing(expected_output[i]) ) {
      BOOST_CHECK(bcf_float_is_missing(output_vector[i]));
    }
    else if ( bcf_float_is_vector_end(expected_output[i]) ) {
      BOOST_CHECK(bcf_float_is_vector_end(output_vector[i]));
    }
    else {
      BOOST_CHECK_EQUAL(expected_output[i], output_vector[i]);
    }
  }
}

BOOST_AUTO_TEST_CASE( test_multi_sample_vector_zero_samples_and_values ) {
  // Ensure that we don't crash when creating empty vectors with num_samples or max_values_per_sample equal to 0

  // 0 samples, max of 0 values per sample
  auto vec = VariantBuilderMultiSampleVector<int32_t>{0u, 0u, bcf_int32_missing, bcf_int32_vector_end};
  BOOST_CHECK_EQUAL(vec.num_samples(), 0u);
  BOOST_CHECK_EQUAL(vec.max_values_per_sample(), 0u);

  // 4 samples, max of 0 values per sample
  vec = VariantBuilderMultiSampleVector<int32_t>{4u, 0u, bcf_int32_missing, bcf_int32_vector_end};
  BOOST_CHECK_EQUAL(vec.num_samples(), 4u);
  BOOST_CHECK_EQUAL(vec.max_values_per_sample(), 0u);

  // 0 samples, max of 4 values per sample
  vec = VariantBuilderMultiSampleVector<int32_t>{0u, 4u, bcf_int32_missing, bcf_int32_vector_end};
  BOOST_CHECK_EQUAL(vec.num_samples(), 0u);
  BOOST_CHECK_EQUAL(vec.max_values_per_sample(), 4u);
}

max_stars_repo_name: audiohacked/gamgee

max_issues_repo_name: audiohacked/gamgee

max_forks_repo_name: audiohacked/gamgee


text:
//  constructor_tests.cpp  -- The Boost Lambda Library ------------------
//
// Copyright (C) 2000-2003 Jaakko Jarvi (jaakko.jarvi@cs.utu.fi)
// Copyright (C) 2000-2003 Gary Powell (powellg@amazon.com)
//
// 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)
//
// For more information, see www.boost.org

// -----------------------------------------------------------------------

#include <boost/core/lightweight_test.hpp>

#include "boost/lambda/lambda.hpp"
#include "boost/lambda/bind.hpp"

#include "boost/lambda/construct.hpp"

#include <iostream>
#include <algorithm>
#include <vector>

#ifdef BOOST_MSVC
#pragma warning(disable:4512)
#endif

using namespace boost::lambda;
namespace bl = boost::lambda;

template<class T>
bool check_tuple(int n, const T& t)
{
  return (t.get_head() == n) && check_tuple(n+1, t.get_tail());
}

template<class T>
bool check_tuple(int n, T * t)
{
  bool ok = check_tuple(n, *t);
  delete t;
  return ok;
}

template <>
bool check_tuple(int /*n*/, const null_type& ) { return true; }

void constructor_all_lengths()
{
  bool ok;
  ok = check_tuple(
    1,
    bind(constructor<tuple<int> >(),
       1)()
  );
  BOOST_TEST(ok);

  ok = check_tuple(
    1,
    bind(constructor<tuple<int, int> >(),
       1, 2)()
  );
  BOOST_TEST(ok);

  ok = check_tuple(
    1,
    bind(constructor<tuple<int, int, int> >(),
       1, 2, 3)()
  );
  BOOST_TEST(ok);

  ok = check_tuple(
    1,
    bind(constructor<tuple<int, int, int, int> >(),
       1, 2, 3, 4)()
  );
  BOOST_TEST(ok);

  ok = check_tuple(
    1,
    bind(constructor<tuple<int, int, int, int, int> >(),
       1, 2, 3, 4, 5)()
  );
  BOOST_TEST(ok);

  ok = check_tuple(
    1,
    bind(constructor<tuple<int, int, int, int, int, int> >(),
       1, 2, 3, 4, 5, 6)()
  );
  BOOST_TEST(ok);

  ok = check_tuple(
    1,
    bind(constructor<tuple<int, int, int, int, int, int, int> >(),
       1, 2, 3, 4, 5, 6, 7)()
  );
  BOOST_TEST(ok);

  ok = check_tuple(
    1,
    bind(constructor<tuple<int, int, int, int, int, int, int, int> >(),
       1, 2, 3, 4, 5, 6, 7, 8)()
  );
  BOOST_TEST(ok);

  ok = check_tuple(
    1,
    bind(constructor<tuple<int, int, int, int, int, int, int, int, int> >(),
       1, 2, 3, 4, 5, 6, 7, 8, 9)()
  );
  BOOST_TEST(ok);

}

void new_ptr_all_lengths()
{
  bool ok;
  ok = check_tuple(
    1,
    (bind(new_ptr<tuple<int> >(),
       1))()
  );
  BOOST_TEST(ok);

  ok = check_tuple(
    1,
    (bind(new_ptr<tuple<int, int> >(),
       1, 2))()
  );
  BOOST_TEST(ok);

  ok = check_tuple(
    1,
    (bind(new_ptr<tuple<int, int, int> >(),
       1, 2, 3))()
  );
  BOOST_TEST(ok);

  ok = check_tuple(
    1,
    (bind(new_ptr<tuple<int, int, int, int> >(),
       1, 2, 3, 4))()
  );
  BOOST_TEST(ok);

  ok = check_tuple(
    1,
    (bind(new_ptr<tuple<int, int, int, int, int> >(),
       1, 2, 3, 4, 5))()
  );
  BOOST_TEST(ok);

  ok = check_tuple(
    1,
    (bind(new_ptr<tuple<int, int, int, int, int, int> >(),
       1, 2, 3, 4, 5, 6))()
  );
  BOOST_TEST(ok);

  ok = check_tuple(
    1,
    (bind(new_ptr<tuple<int, int, int, int, int, int, int> >(),
       1, 2, 3, 4, 5, 6, 7))()
  );
  BOOST_TEST(ok);

  ok = check_tuple(
    1,
    (bind(new_ptr<tuple<int, int, int, int, int, int, int, int> >(),
       1, 2, 3, 4, 5, 6, 7, 8))()
  );
  BOOST_TEST(ok);

  ok = check_tuple(
    1,
    (bind(new_ptr<tuple<int, int, int, int, int, int, int, int, int> >(),
       1, 2, 3, 4, 5, 6, 7, 8, 9))()
  );
  BOOST_TEST(ok);

}

class is_destructor_called {
  bool& b;
public:
  is_destructor_called(bool& bb) : b(bb) { b = false; }
  ~is_destructor_called() { b = true; }
};

void test_destructor ()
{
  char space[sizeof(is_destructor_called)];
  bool flag = false;

  is_destructor_called* idc = new(space) is_destructor_called(flag);
  BOOST_TEST_EQ(flag, false);
  bind(destructor(), _1)(idc);
  BOOST_TEST_EQ(flag, true);

  idc = new(space) is_destructor_called(flag);
  BOOST_TEST_EQ(flag, false);
  bind(destructor(), _1)(*idc);
  BOOST_TEST_EQ(flag, true);
}

class count_deletes {
public:
  static int count;
  ~count_deletes() { ++count; }
};

int count_deletes::count = 0;

void test_news_and_deletes ()
{
  int* i[10];
  std::for_each(i, i+10, _1 = bind(new_ptr<int>(), 2));
  int count_errors = 0;

  std::for_each(i, i+10, (*_1 == 2) || ++var(count_errors));
  BOOST_TEST_EQ(count_errors, 0);
  std::for_each(i, i+10, bind(delete_ptr(), _1));

  count_deletes* ct[10];
  std::for_each(ct, ct+10, _1 = bind(new_ptr<count_deletes>()));
  count_deletes::count = 0;
  std::for_each(ct, ct+10, bind(delete_ptr(), _1));
  BOOST_TEST_EQ(count_deletes::count, 10);

}

void test_array_new_and_delete()
{
  count_deletes* c;
  (_1 = bind(new_array<count_deletes>(), 5))(c);
  count_deletes::count = 0;

  bind(delete_array(), _1)(c);
  BOOST_TEST_EQ(count_deletes::count, 5);
}

void delayed_construction()
{
  std::vector<int> x(3);
  std::vector<int> y(3);

  std::fill(x.begin(), x.end(), 0);
  std::fill(y.begin(), y.end(), 1);

  std::vector<std::pair<int, int> > v;

  std::transform(x.begin(), x.end(), y.begin(), std::back_inserter(v),
            bl::bind(constructor<std::pair<int, int> >(), _1, _2) );
}

int main()
{
  constructor_all_lengths();
  new_ptr_all_lengths();
  delayed_construction();
  test_destructor();
  test_news_and_deletes();
  test_array_new_and_delete();

  return boost::report_errors();
}

ext: cpp

max_issues_repo_name: qingkouwei/mediaones


text:
//  Copyright (c) 2005-2011 Hartmut Kaiser
//
//  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)

#include <map>
#include <vector>

#include <boost/tokenizer.hpp>
#include <boost/filesystem/path.hpp>

#include <saga/saga/util.hpp>
#include <saga/saga/path_leaf.hpp>
#include <saga/saga/exception.hpp>
#include <saga/saga/url.hpp>
#include <saga/saga/adaptors/task.hpp>

#include <saga/impl/config.hpp>
#include <saga/impl/exception_list.hpp>

#include "config.hpp"
#include "advertdirectory.hpp"
#include "common_helpers.hpp"

///////////////////////////////////////////////////////////////////////////////
// wrap database calls and catch all exceptions
#define SAGA_ADVERTDIR_DBACTION(name, f)                                      \
    try {                                                                     \
        (f);                                                                  \
    }                                                                         \
    catch (saga::adaptors::exception const& e) {                              \
    /* just rethrow using this cpi instance */                                \
        saga::impl::exception_list exceptions;                                \
        exceptions.add(e);                                                    \
        SAGA_ADAPTOR_THROW_PLAIN_LIST(this, exceptions);                      \
    }                                                                         \
    catch (std::exception const& e) {                                         \
    /* wrap this error in a SAGA adaptor exception */                         \
        SAGA_OSSTREAM strm;                                                   \
        strm << "advert::advertdirectory_cpi_impl::" #name ": "               \
             << e.what();                                                     \
        SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::NoSuccess);   \
    }                                                                         \
    /**/

///////////////////////////////////////////////////////////////////////////////
namespace advert
{

///////////////////////////////////////////////////////////////////////////////
//  constructor
advertdirectory_cpi_impl::advertdirectory_cpi_impl (
        proxy* p, cpi_info const& info,
        saga::ini::ini const& glob_ini, saga::ini::ini const& adap_ini,
        TR1::shared_ptr<saga::adaptor> adaptor)
  : base_cpi (p, info, adaptor, cpi::Noflags),
//     monitor_handle_(0),
    db_(detail::get_db_type<instance_data>(adap_ini, p),
        detail::get_db_connectstring<instance_data>(adap_ini, p->get_session(), p))
{

    // first usage of this adaptor
    instance_data data (this);
    saga::url advert_url(data->location_);
    std::string url(saga::url::unescape(advert_url.get_path()));
    if (url.empty())
        url = "/";      // root only

    SAGA_LOG(SAGA_VERBOSE_LEVEL_DEBUG)
        << "Trying to create advert directory instance for: "
        << clean_url (advert_url);

    // we understand absolute paths only
    if ('/' != url[0])
    {
        SAGA_OSSTREAM strm;
        strm << "advert::advertdirectory_cpi_impl::init: "
                "cannot handle relative advert directory name: "
             << advert_url.get_string();
        SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::IncorrectURL);
    }

    // we understand adname's only for localhost (if sqlite3)
    std::string host(advert_url.get_host());
    if (!host.empty() && !detail::host_is_valid(db_.get_dbtype(), host))
    {
        SAGA_OSSTREAM strm;
        strm << "advert::advertdirectory_cpi_impl::init: "
                "cannot handle advert directory host: "
             << advert_url.get_string();
        SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::adaptors::AdaptorDeclined);
    }

    // we understand only 'any' and 'advert' url schemes
    std::string scheme(advert_url.get_scheme());

    if ( !scheme.empty ()   &&
         scheme != "advert" &&
         scheme != "any"    )
    {
        SAGA_OSSTREAM strm;
        strm << "advert::advertdirectory_cpi_impl::init: "
                "cannot handle advert directory scheme: " << advert_url.get_string();
        SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::adaptors::AdaptorDeclined);
    }

    database_scope db_scope(this, db_);

    saga::advert::flags mode = (saga::advert::flags)data->mode_;
    if (((mode & saga::advert::Create) ||
         (mode & saga::advert::CreateParents)) &&
        (mode & saga::advert::Exclusive))
    {
        if (db_.exists_directory(url))
        {
            SAGA_OSSTREAM strm;
            strm << "advert::advertdirectory_cpi_impl::init: "
                    "advert already exists: " << advert_url.get_string();
            SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::AlreadyExists);
        }
    }

    // Create advert if saga::advert::directory::create flag is given
    if ((mode & saga::advert::Create) ||
        (mode & saga::advert::CreateParents))
    {
        SAGA_ADVERTDIR_DBACTION(advertdirectory_cpi_impl,
            (db_.create_directory(url, (mode & saga::advert::CreateParents) ? true : false)));

        // no need to create this entry twice
        data->mode_ &= ~(saga::advert::Create |
                         saga::advert::CreateParents);
    }

    if (!db_.exists_directory(url))
    {
        SAGA_OSSTREAM strm;
        strm << "advert::advertdirectory_cpi_impl::init: "
                "advert does not exist: " << advert_url.get_string();
        SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::DoesNotExist);
    }

    opened_ = true;

//     setup_monitoring();

    SAGA_LOG(SAGA_VERBOSE_LEVEL_DEBUG)
        << "Created advert directory instance for: "
        << clean_url (advert_url);
}

///////////////////////////////////////////////////////////////////////////////
// void advertdirectory_cpi_impl::setup_monitoring()
// {
//     // register a new work item to be called 100ms from now
//     monitor_handle_ = saga::adaptors::register_workitem(
//         TR1::bind(&advertdirectory_cpi_impl::monitor_entry, this, _1),
//         saga::adaptors::duration_type(boost::posix_time::milliseconds(100)),
//         get_session());
// }

///////////////////////////////////////////////////////////////////////////////
// void advertdirectory_cpi_impl::monitor_entry(boost::system::error_code const& e)
// {
//     monitor_handle_ = 0;    // no need to delete anymore
//
//     if (!e) return;         // some error occurred
//
//     try {
//         std::string key("utime");
//         std::string adname;
//         {
//             instance_data data (this);
//             adname = detail::get_filepath(data->location_);
//         }
//
//         bool exists = false;
//
//     // fetch modification time
//         std::string utime;
//         mutex_type::scoped_lock l(mtx_);
//
//         {
//         // read entry
//             database_scope db_scope(this, db_);
//             exists = false;
//             SAGA_ADVERTDIR_DBACTION(attribute_exists,
//                 (db_.attribute_exists(adname, key, exists)));
//
//             if (!exists) {
//                 saga::monitorable monitor (this->proxy_);
//                 saga::adaptors::metric m (
//                     monitor.get_metric(saga::advert::metrics::directory_deleted_entry));
//                 m.set_attribute(saga::attributes::metric_value, adname);
//                 m.fire();
//             }
//             else {
//                 bool is_vector = false;
//                 SAGA_ADVERTDIR_DBACTION(get_attribute,
//                     (db_.get_attribute(adname, key, utime, is_vector)));
//             }
//         }
//
//     // if the modification time has been changed, fire metric
//         if (exists && !last_modification_time_.empty() &&
//             utime != last_modification_time_)
//         {
//             saga::monitorable monitor (this->proxy_);
//             saga::adaptors::metric m (
//                 monitor.get_metric(saga::advert::metrics::directory_modified_entry));
//             m.set_attribute(saga::attributes::metric_value, adname);
//             m.fire();
//             last_modification_time_ = utime;
//         }
//
//     // reschedule this work item, the current work item will be unregistered
//     // automatically
//         if (exists)
//             setup_monitoring();
//     }
//     catch (...) {
//         // just ignore any error in the monitoring thread
//     }
// }

///////////////////////////////////////////////////////////////////////////////
//  destructor
advertdirectory_cpi_impl::~advertdirectory_cpi_impl (void)
{
//     BOOST_ASSERT(0 == monitor_handle_);    // close should have been called

    opened_ = false;
    try {
        mutex_type::scoped_lock lock(mtx_);
        database_scope db_scope(this, db_);
        SAGA_ADVERTDIR_DBACTION(~advertdirectory_cpi_impl, db_.close(false));
    }
    catch (...) {
        // ignore any errors here, we can't report errors from the destructor
    }
}

///////////////////////////////////////////////////////////////////////////////
//  SAGA CPI functions
void advertdirectory_cpi_impl::check_if_open (std::string const& functionname,
        saga::url const& location)
{
    if (!opened_)
    {
        SAGA_OSSTREAM strm;
        strm << functionname << ": advert directory is not in open state: "
             << location.get_string();
        SAGA_ADAPTOR_THROW (SAGA_OSSTREAM_GETSTRING (strm), saga::IncorrectState);
    }
}

///////////////////////////////////////////////////////////////////////////////
// attribute functions
void
advertdirectory_cpi_impl::sync_attribute_exists(bool& ret, std::string key)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_attribute_exists", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    SAGA_ADVERTDIR_DBACTION(attribute_exists,
        (db_.attribute_exists(adname, key, ret)));
}

void
advertdirectory_cpi_impl::sync_attribute_is_readonly(bool& ret, std::string key)
{
    instance_data data (this);
    check_if_open("advertdirectory_cpi_impl::sync_attribute_is_readonly", data->location_);
    ret = !(data->mode_ & saga::advert::Read);
}

void
advertdirectory_cpi_impl::sync_attribute_is_writable(bool& ret, std::string key)
{
    instance_data data (this);
    check_if_open("advertdirectory_cpi_impl::sync_attribute_is_writable", data->location_);
    ret = (data->mode_ & saga::advert::Write) ? true : false;
}

///////////////////////////////////////////////////////////////////////////////
void
advertdirectory_cpi_impl::check_permissions(saga::advert::flags flags,
    char const* name, std::string const& adname)
{
    instance_data data (this);
    if (!(data->mode_ & flags)) {
        SAGA_OSSTREAM strm;
        strm << "advert::advertdirectory_cpi_impl::" << name << ": "
                "could not access("
             << ((flags & saga::advert::Read) ? "read" : "write")
             << ") attribute for advert: "
             << adname;
        SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm),
            saga::PermissionDenied);
    }
}

void
advertdirectory_cpi_impl::sync_attribute_is_vector(bool& ret, std::string key)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_attribute_is_vector", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Read, "attribute_is_vector", adname);

    // read attribute from db
    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    std::string val;
    SAGA_ADVERTDIR_DBACTION(attribute_is_vector,
        (db_.get_attribute(adname, key, val, ret)));
}

void
advertdirectory_cpi_impl::sync_attribute_is_extended(bool& ret, std::string key)
{
    instance_data data (this);
    check_if_open("advertdirectory_cpi_impl::sync_attribute_is_extended", data->location_);
    ret = (data->mode_ & saga::advert::Write) ? true : false;
}

///////////////////////////////////////////////////////////////////////////////
void
advertdirectory_cpi_impl::sync_get_attribute(std::string& ret, std::string key)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_get_attribute", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Read, "get_attribute", adname);

    // read attribute from db
    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    bool is_vector = false;
    std::string val;
    SAGA_ADVERTDIR_DBACTION(get_attribute,
        (db_.get_attribute(adname, key, val, is_vector)));

    if (!is_vector) {
        ret = val;
    }
    else {
        SAGA_OSSTREAM strm;
        strm << "advert::advertdirectory_cpi_impl::sync_get_attribute: "
                "attribute '" << key << "' is a vector attribute for: " << adname;
        SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm),
            saga::IncorrectState);
    }
}

///////////////////////////////////////////////////////////////////////////////
void
advertdirectory_cpi_impl::sync_get_vector_attribute(std::vector<std::string>& ret,
    std::string key)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_get_vector_attribute", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Read, "get_vector_attribute", adname);

    // read attribute from db
    std::string val;

    bool is_vector = false;
    bool result    = false;

    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    SAGA_ADVERTDIR_DBACTION(get_vector_attribute,
        (result = db_.get_attribute(adname, key, val, is_vector)));

    if (result) {
        if (is_vector) {
            detail::tokenize_values(val, ret);
        }
        else {
            SAGA_OSSTREAM strm;
            strm << "advert::advertdirectory_cpi_impl::sync_get_vector_attribute: "
                    "attribute '" << key << "' is not a vector attribute for: "
                 << adname;
            SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm),
                saga::IncorrectState);
        }
    }
}

///////////////////////////////////////////////////////////////////////////////
void
advertdirectory_cpi_impl::sync_set_attribute(saga::impl::void_t&, std::string key,
    std::string val)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_set_attribute", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Write, "set_attribute", adname);

    // write attribute to db
    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    SAGA_ADVERTDIR_DBACTION(set_attribute,
        (db_.set_attribute(adname, key, val, false)));
}

///////////////////////////////////////////////////////////////////////////////
void
advertdirectory_cpi_impl::sync_set_vector_attribute(saga::impl::void_t&, std::string key,
    std::vector<std::string> val)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_set_vector_attribute", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Write, "get_vector_attribute", adname);

    // write attribute to db
    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    SAGA_ADVERTDIR_DBACTION(set_vector_attribute,
        (db_.set_attribute(adname, key, detail::concat_values(val), true)));
}

///////////////////////////////////////////////////////////////////////////////
void
advertdirectory_cpi_impl::sync_remove_attribute(saga::impl::void_t&, std::string key)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_remove_attribute", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Write, "remove_attribute", adname);

    // remove attribute from db
    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    SAGA_ADVERTDIR_DBACTION(remove_attribute,
        (db_.remove_attribute(adname, key)));
}

///////////////////////////////////////////////////////////////////////////////
void
advertdirectory_cpi_impl::sync_list_attributes(std::vector<std::string>& keys)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_list_attributes", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Read, "list_attributes", adname);

    // get attributes from db
    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    SAGA_ADVERTDIR_DBACTION(list_attributes, (db_.list_attributes(adname, keys)));
}

///////////////////////////////////////////////////////////////////////////////
void
advertdirectory_cpi_impl::sync_find_attributes(std::vector<std::string>& keys,
    std::string pattern)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_find_attributes", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Read, "find_attributes", adname);

    // extract patterns from 'key=value' expression
    std::string kpat, vpat;
    detail::parse_pattern(this, pattern, kpat, vpat);

    // look for matching keys in the database
    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    SAGA_ADVERTDIR_DBACTION(find_attributes,
        (db_.find_attributes(adname, detail::regex_from_pattern(kpat),
            detail::regex_from_pattern(vpat), &keys)));
}

///////////////////////////////////////////////////////////////////////////////
// namespace_entry functions
void
advertdirectory_cpi_impl::sync_get_url(saga::url& url)
{
    instance_data data (this);
    check_if_open("advertdirectory_cpi_impl::sync_get_url", data->location_);

    {
        mutex_type::scoped_lock lock(mtx_);
        database_scope db_scope(this, db_);

        SAGA_ADVERTDIR_DBACTION(get_url, db_.verify_status()); // throws when db has been closed
    }

    url = data->location_;
}

void
advertdirectory_cpi_impl::sync_get_cwd(saga::url& url)
{
    saga::url result;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_get_cwd", data->location_);
        result = data->location_;
    }

    {
        mutex_type::scoped_lock lock(mtx_);
        database_scope db_scope(this, db_);

        SAGA_ADVERTDIR_DBACTION(get_cwd, db_.verify_status()); // throws when db has been closed
    }

    std::string dirpath(detail::get_filepath(result));
    std::string::size_type pos = dirpath.find_last_of('/');
    if (pos != std::string::npos)
        dirpath = dirpath.substr(0, pos);

    boost::filesystem::path p(dirpath);
    url = result;
    url.set_path(saga::detail::parent(p));
}

void
advertdirectory_cpi_impl::sync_get_name(saga::url& url)
{
    saga::url result;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_get_name", data->location_);
        result = data->location_;
    }

    {
        mutex_type::scoped_lock lock(mtx_);
        database_scope db_scope(this, db_);

        SAGA_ADVERTDIR_DBACTION(get_name, db_.verify_status()); // throws when db has been closed
    }

    std::string dirpath(detail::get_filepath(result));
    std::string::size_type pos = dirpath.find_last_of('/');
    if (pos != std::string::npos)
        dirpath = dirpath.substr(0, pos);

    boost::filesystem::path p(dirpath);
    url.set_path(saga::detail::leaf(p));
}

void
advertdirectory_cpi_impl::sync_is_dir(bool& ret)
{
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_is_dir", data->location_);
    }

    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    SAGA_ADVERTDIR_DBACTION(is_dir, db_.verify_status()); // throws when db has been closed
    ret = true;
}

void
advertdirectory_cpi_impl::sync_is_entry(bool& ret)
{
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_is_entry", data->location_);
    }

    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    SAGA_ADVERTDIR_DBACTION(is_entry, db_.verify_status()); // throws when db has been closed
    ret = false;
}

void
advertdirectory_cpi_impl::sync_is_link(bool& ret)
{
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_is_link", data->location_);
    }

    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    SAGA_ADVERTDIR_DBACTION(is_link, db_.verify_status()); // throws when db has been closed
    ret = false;                // we don't support links
}

void
advertdirectory_cpi_impl::sync_remove(saga::impl::void_t&, int flags)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_remove", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    if (!(flags & saga::advert::Recursive)) {
        SAGA_ADAPTOR_THROW(
            "advert::advertdirectory_cpi_impl::sync_remove: "
            "Recursive flag was not specified while attempting to delete a "
            "directory", saga::BadParameter);
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Write, "remove", adname);

    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    SAGA_ADVERTDIR_DBACTION(remove, (db_.remove_directory(adname), db_.close()));
    opened_ = false;
}

void advertdirectory_cpi_impl::sync_close(saga::impl::void_t&, double)
{
//     if (0 != monitor_handle_) {
//         try {
//             saga::adaptors::unregister_workitem(monitor_handle_, get_session());
//         }
//         catch (...) {
//             // ignore any errors here, the item might have been unregistered
//             // already
//         }
//     }

    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    opened_ = false;
    SAGA_ADVERTDIR_DBACTION(close, db_.close());
}

///////////////////////////////////////////////////////////////////////////////
//  namespace_dir functions
///////////////////////////////////////////////////////////////////////////////
namespace
{
    // find all matching entries recursively
    void
    find_recursive(database& db, std::string const& adname,
        std::string const& pattern, std::string const& cwd,
        std::vector<std::string>& ret)
    {
        std::vector<std::string> entries;
        db.list(adname, pattern, entries, !cwd.empty());

        std::vector<std::string>::iterator end = entries.end();
        for (std::vector<std::string>::iterator it = entries.begin();
             it != end; ++it)
        {
            std::string entry(adname.empty() ? "/" : adname);
            if (entry.find_last_of('/') != entry.size()-1)
                entry += '/';
            entry += *it;

            bool is_dir = false;
            if (0 == db.find(entry, is_dir, true)) {
            // this should not happen!
                SAGA_OSSTREAM strm;
                strm << "advert::advertdirectory_cpi_impl::find_recursive: "
                        "Database inconsistency detected: " << entry;
                SAGA_ADAPTOR_THROW_NO_CONTEXT(SAGA_OSSTREAM_GETSTRING(strm),
                    saga::NoSuccess);
            }

            std::string rel_entry(cwd.empty() ? *it : cwd + '/' + *it);
            if (is_dir)     // analyze this directory
                find_recursive(db, entry, pattern, rel_entry, ret);

        // found a matching entry
            ret.push_back(rel_entry);
        }
    }

    // the difference between list_recursive and find_recursve is, that list
    // applies the pattern in the top level directory only
    void
    list_recursive(database& db, std::string const& adname,
        std::string const& pattern, std::string const& cwd,
        std::vector<std::string>& ret)
    {
        std::vector<std::string> entries;
        db.list(adname, pattern, entries);

        std::vector<std::string>::iterator end = entries.end();
        for (std::vector<std::string>::iterator it = entries.begin();
             it != end; ++it)
        {
            std::string entry(adname.empty() ? "/" : adname);
            if (entry.find_last_of('/') != entry.size()-1)
                entry += '/';
            entry += *it;

            bool is_dir = false;
            if (0 == db.find(entry, is_dir, true)) {
            // this should not happen!
                SAGA_OSSTREAM strm;
                strm << "advert::advertdirectory_cpi_impl::list_recursive: "
                        "Database inconsistency detected: " << entry;
                SAGA_ADAPTOR_THROW_NO_CONTEXT(SAGA_OSSTREAM_GETSTRING(strm),
                    saga::NoSuccess);
            }

            std::string rel_entry(cwd.empty() ? *it : cwd + '/' + *it);
            if (is_dir)     // analyze this directory
                find_recursive(db, entry, ".*", rel_entry, ret);

        // found a matching entry
            ret.push_back(rel_entry);
        }
    }
}

void
advertdirectory_cpi_impl::sync_list(std::vector<saga::url>& ret,
    std::string pattern, int flags)
{
    std::string adname;
    std::string basename;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_list", data->location_);
        adname = detail::get_filepath(data->location_);
        basename = data->location_.get_string();
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Read, "list", adname);

    if (flags & saga::advert::Dereference) {
        SAGA_OSSTREAM strm;
        strm << "advert::advertdirectory_cpi_impl::sync_list: "
                "Dereferencing links is not supported.";
        SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm),
            saga::NotImplemented);
    }

//     std::string entry(basename.empty() ? "/" : basename);
//     if (entry.find_last_of('/') != entry.size()-1)
//         entry += '/';

    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    std::vector<std::string> entries;
    if (flags & saga::advert::Recursive) {
    // invoke list recursively
        SAGA_ADVERTDIR_DBACTION(list,
            (list_recursive(db_, adname, detail::regex_from_pattern(pattern),
                "", entries)));
    }
    else {
        // return the matching entries
        SAGA_ADVERTDIR_DBACTION(list,
            (db_.list(adname, detail::regex_from_pattern(pattern), entries)));
    }

    // create result vector
    std::vector<std::string>::iterator end = entries.end();
    for (std::vector<std::string>::iterator it = entries.begin();
         it != end; ++it)
    {
        ret.push_back(saga::url(/*entry + */*it));
    }
}

void
advertdirectory_cpi_impl::sync_find(std::vector<saga::url>& ret,
    std::string pattern, int flags)
{
    std::string adname;
    std::string basename;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_find", data->location_);
        adname = detail::get_filepath(data->location_);
        basename = data->location_.get_string();
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Read, "find", adname);

    if (flags & saga::advert::Dereference) {
        SAGA_OSSTREAM strm;
        strm << "advert::advertdirectory_cpi_impl::sync_find: "
                "Dereferencing links is not supported.";
        SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm),
            saga::NotImplemented);
    }

    std::string entry(basename.empty() ? "/" : basename);
    if (entry.find_last_of('/') != entry.size()-1)
        entry += '/';

    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    std::vector<std::string> entries;
    if (flags & saga::advert::Recursive) {
    // invoke list recursively
        SAGA_ADVERTDIR_DBACTION(find,
            (find_recursive(db_, adname, detail::regex_from_pattern(pattern),
                "", entries)));
    }
    else {
    // same as list
        SAGA_ADVERTDIR_DBACTION(find,
            (db_.list(adname, detail::regex_from_pattern(pattern), entries)));
    }

    // create result vector
    std::vector<std::string>::iterator end = entries.end();
    for (std::vector<std::string>::iterator it = entries.begin();
         it != end; ++it)
    {
        ret.push_back(saga::url(entry + *it));
    }
}

void
advertdirectory_cpi_impl::sync_exists(bool& ret, saga::url entry)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_exists", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Read, "exists", adname);

    std::string entry_path (detail::get_filepath(entry));
    if ('/' != entry_path[0])
        entry_path = adname + "/" + entry_path;   // relative path given

    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    SAGA_ADVERTDIR_DBACTION(exists, (ret = db_.exists_other(entry_path)));
}

void
advertdirectory_cpi_impl::sync_is_dir(bool& ret, saga::url entry)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_is_dir", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Read, "is_dir", adname);

    std::string entry_path (detail::get_filepath(entry));
    if ('/' != entry_path[0])
        entry_path = adname + "/" + entry_path;   // relative path given

    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    SAGA_ADVERTDIR_DBACTION(is_dir,
        (ret = db_.exists_directory_other(entry_path, false)));
}

void
advertdirectory_cpi_impl::sync_is_entry(bool& ret, saga::url entry)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_is_entry", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Read, "is_entry", adname);

    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    std::string entry_path (detail::get_filepath(entry));
    if ('/' == entry_path[0]) {
    // absolute path given
        SAGA_ADVERTDIR_DBACTION(is_entry,
            (ret = db_.exists_entry_other(entry_path, false)));
    }
    else {
    // relative path given
        SAGA_ADVERTDIR_DBACTION(is_entry,
            (ret = db_.exists_entry_other(adname + "/" + entry_path, false)));
    }
}

void
advertdirectory_cpi_impl::sync_is_link(bool& ret, saga::url)
{
    instance_data data (this);
    check_if_open("advertdirectory_cpi_impl::sync_is_link", data->location_);

    ret = false;    // we don't support links
}

void
advertdirectory_cpi_impl::sync_get_num_entries(std::size_t& num_entries)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_get_num_entries", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Read, "get_num_entries", adname);

    // return the matching entries
    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    std::vector<std::string> entries;
    SAGA_ADVERTDIR_DBACTION(get_num_entries,
        (db_.list(adname, detail::regex_from_pattern("*"), entries)));
    num_entries = (unsigned int)entries.size();
}

void
advertdirectory_cpi_impl::sync_get_entry(saga::url& entry, std::size_t num)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_get_entry", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Read, "get_num_entries", adname);

    // return the matching entries
    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    std::vector<std::string> entries;
    SAGA_ADVERTDIR_DBACTION(get_entry,
        (db_.list(adname, detail::regex_from_pattern("*"), entries)));
    if (num < 0 || num >= entries.size()) {
        SAGA_OSSTREAM strm;
        strm << "advert::advertdirectory_cpi_impl::sync_get_entry: "
                "bad entry number for: " << adname;
        SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm),
            saga::BadParameter);
    }
    entry = entries[num];
}

void
advertdirectory_cpi_impl::sync_remove(saga::impl::void_t&, saga::url entry,
    int flags)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_remove", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Write, "remove", adname);

    // now (recursively) remove the entry
    std::string entry_path (detail::get_filepath(entry));
    if ('/' != entry_path[0])
        entry_path = adname + "/" + entry_path;     // relative path given

    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    bool exists_entry = false;
    SAGA_ADVERTDIR_DBACTION(get_entry,
        (exists_entry = db_.exists_entry_other(entry_path, false)));

    bool exists_dir = false;
    SAGA_ADVERTDIR_DBACTION(get_entry,
        (exists_dir = db_.exists_directory_other(entry_path, false)));

    if (exists_entry) {
        if (flags & saga::advert::Recursive) {
            SAGA_ADAPTOR_THROW(
                "advert::advertdirectory_cpi_impl::sync_remove: "
                "Recursive flag was specified while attempting to delete a "
                "file", saga::BadParameter);
        }
        SAGA_ADVERTDIR_DBACTION(remove, db_.remove_other(entry_path));
    }
    else if (exists_dir) {
        if (!(flags & saga::advert::Recursive)) {
            SAGA_ADAPTOR_THROW(
                "advert::advertdirectory_cpi_impl::sync_remove: "
                "Recursive flag was not specified while attempting to delete a "
                "directory", saga::BadParameter);
        }
        SAGA_ADVERTDIR_DBACTION(remove, db_.remove_directory_other(entry_path));
    }
    else {
        SAGA_ADAPTOR_THROW(
            "advert::advertdirectory_cpi_impl::sync_remove: "
            "Attempting to delete a non-existing directory: " + entry_path,
            saga::BadParameter);
    }
}

void
advertdirectory_cpi_impl::sync_open(saga::name_space::entry& ret,
    saga::url entry, int flags)
{
    saga::url adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_open", data->location_);
        adname = data->location_.clone();
    }

    // now open the entry
    std::string entry_path (detail::get_filepath(entry));
    if ('/' != entry_path[0])
        adname.set_path(saga::url::unescape(adname.get_path()) + "/" + entry_path);     // relative path given
    else
        adname.set_path(entry_path);

    ret = saga::advert::entry(this->get_proxy()->get_session(), adname.get_url(),
        flags);
}

void
advertdirectory_cpi_impl::sync_open_dir(saga::name_space::directory& ret,
    saga::url entry, int flags)
{
    saga::url adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_open_dir", data->location_);
        adname = data->location_.clone();
    }

    // now open the directory
    std::string entry_path (detail::get_filepath(entry));
    if ('/' != entry_path[0])
        adname.set_path(saga::url::unescape(adname.get_path()) + "/" + entry_path);     // relative path given
    else
        adname.set_path(entry_path);

    ret = saga::advert::directory(this->get_proxy()->get_session(),
        adname.get_url(), flags);
}

void
advertdirectory_cpi_impl::sync_change_dir(saga::impl::void_t&, saga::url dir)
{
    saga::url adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_change_dir", data->location_);
        adname = data->location_.clone();
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Write, "change_dir", adname.get_string());

    std::string dir_path (detail::get_filepath(dir));
    if ('/' != dir_path[0])
        adname.set_path(saga::url::unescape(adname.get_path()) + "/" + dir_path);     // relative path given
    else
        adname.set_path(dir_path);

    // verify the directory existence
    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    SAGA_ADVERTDIR_DBACTION(change_dir,
        db_.change_directory(saga::url::unescape(adname.get_path())));

    // change directory
    {
        instance_data data (this);
        data->location_ = adname.get_url();
    }
}

void
advertdirectory_cpi_impl::sync_make_dir(saga::impl::void_t&, saga::url dir,
    int flags)
{
    std::string adname;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_make_dir", data->location_);
        adname = detail::get_filepath(data->location_);
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Write, "make_dir", adname);

    std::string dir_path (detail::get_filepath(dir));
    if ('/' != dir_path[0])
        dir_path = adname + "/" + dir_path;     // relative path given

    bool result = false;

    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    SAGA_ADVERTDIR_DBACTION(make_dir,
        (result = db_.exists_directory_other(dir_path)));

    if (result) {
        // make sure directory does not exist if Exclusive is given
        if (flags & saga::advert::Exclusive) {
            SAGA_ADAPTOR_THROW(
                "advert::advertdirectory_cpi_impl::sync_make_dir: "
                "Exclusive flag was specified while the directory already exists",
                saga::AlreadyExists);
        }
    }
    else {
        // create the new directory
        SAGA_ADVERTDIR_DBACTION(make_dir,
            (db_.create_new_directory(dir_path,
                (flags & saga::advert::CreateParents) ? true : false)));
    }
}

///////////////////////////////////////////////////////////////////////////////
//  directory functions
void
advertdirectory_cpi_impl::sync_open(saga::advert::entry& ret, saga::url entry,
    int flags)
{
    sync_open((saga::name_space::entry&)ret, entry, flags);
}

void
advertdirectory_cpi_impl::sync_open_dir(saga::advert::directory& ret,
    saga::url entry, int flags)
{
    sync_open_dir((saga::name_space::directory&)ret, entry, flags);
}

void
advertdirectory_cpi_impl::sync_find(std::vector<saga::url>& ret,
    std::string pattern, std::vector<std::string> patterns, int flags)
{
    std::string adname;
    std::string basename;
    {
        instance_data data (this);
        check_if_open("advertdirectory_cpi_impl::sync_find", data->location_);
        adname = detail::get_filepath(data->location_);
        basename = data->location_.get_string();
    }

    // check permissions (throws on mismatch)
    check_permissions(saga::advert::Read, "find", adname);

    if (flags & saga::advert::Dereference) {
        SAGA_OSSTREAM strm;
        strm << "advert::advertdirectory_cpi_impl::sync_find: "
                "Dereferencing links is not supported.";
        SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm),
            saga::NotImplemented);
    }

    mutex_type::scoped_lock lock(mtx_);
    database_scope db_scope(this, db_);

    std::vector<std::string> paths;
    if (flags & saga::advert::Recursive) {
    // invoke list recursively
        SAGA_ADVERTDIR_DBACTION(find,
            (find_recursive(db_, adname, detail::regex_from_pattern(pattern),
                "", paths)));
    }
    else {
    // same as list
        SAGA_ADVERTDIR_DBACTION(find,
            (db_.list(adname, detail::regex_from_pattern(pattern), paths)));
    }

// look for matching keys in the database, iterating for all found paths
    std::string entry(basename.empty() ? "/" : basename);
    if (entry.find_last_of('/') != entry.size()-1)
        entry += '/';

    if (!patterns.empty()) {
    // generate regex patterns for given key and value patterns
        std::vector<std::string> kpat, vpat;
        detail::parse_patterns(this, patterns, kpat, vpat);

        std::vector<std::string> kpatrx, vpatrx;
        detail::regex_from_patterns(kpat, kpatrx);
        detail::regex_from_patterns(vpat, vpatrx);

    // look for matching keys in the database, iterating for all found paths
        std::string entry(basename.empty() ? "/" : basename);
        if (entry.find_last_of('/') != entry.size()-1)
            entry += '/';

        std::vector<std::string>::iterator end = paths.end();
        for (std::vector<std::string>::iterator it = paths.begin(); it != end; ++it)
        {
            std::string e(adname + *it);
            bool keys_exist = false;
            SAGA_ADVERTDIR_DBACTION(find,
                (keys_exist = db_.find_attributes(e, kpatrx, vpatrx, NULL, true, true)));
            if (keys_exist)
                ret.push_back(entry + *it);
        }
    }
    else {
    // no additional attribute based criteria given, return all existing
        std::vector<std::string>::iterator end = paths.end();
        for (std::vector<std::string>::iterator it = paths.begin(); it != end; ++it)
        {
            ret.push_back(entry + *it);
        }
    }
}

std::string
advertdirectory_cpi_impl::clean_url (const saga::url & u)
{
  saga::url tmp = u;
  if ( ! tmp.get_password ().empty () )
  {
    tmp.set_password ("************");
  }

  return tmp.get_string ();
}

///////////////////////////////////////////////////////////////////////////////
}   // namespace advert

max_stars_repo_name: saga-project/saga-cpp

max_issues_repo_name: saga-project/saga-cpp

max_forks_repo_name: saga-project/saga-cpp


text:
//Copyright (c) 2013 Singapore-MIT Alliance for Research and Technology
//Licensed under the terms of the MIT License, as described in the file:
//   license.txt   (http://opensource.org/licenses/MIT)

#include "PopulationSqlDao.hpp"

#include <boost/lexical_cast.hpp>
#include "conf/ConfigManager.hpp"
#include <behavioral/params/ZoneCostParams.hpp>
#include <conf/ConfigParams.hpp>
#include "DatabaseHelper.hpp"
#include "logging/Log.hpp"
//#include "medium/config/MT_Config.hpp"

using namespace sim_mob;
using namespace sim_mob::db;

namespace
{
typedef long long BigInt;
}

PopulationSqlDao::PopulationSqlDao(DB_Connection& connection) :
		SqlAbstractDao<PersonParams>(connection, "", "", "", "", "", "SELECT * FROM " +
		APPLY_SCHEMA(ConfigManager::GetInstanceRW().FullConfig().schemas.main_schema,
				ConfigManager::GetInstanceRW().FullConfig().dbStoredProcMap["individual_by_id"]))
{
}

PopulationSqlDao::~PopulationSqlDao()
{
}

void PopulationSqlDao::fromRow(Row& result, PersonParams& outObj)
{
	outObj.setPersonId(boost::lexical_cast<std::string>(result.get<BigInt>(DB_FIELD_ID)));
	outObj.setPersonTypeId(result.get<BigInt>(DB_FIELD_PERSON_TYPE_ID));
	outObj.setGenderId(result.get<BigInt>(DB_FIELD_GENDER_ID));
	outObj.setStudentTypeId(result.get<BigInt>(DB_FIELD_STUDENT_TYPE_ID));
	outObj.setVehicleOwnershipCategory(result.get<int>(DB_FIELD_VEHICLE_CATEGORY_ID));

	outObj.setAgeId(result.get<BigInt>(DB_FIELD_AGE_CATEGORY_ID));
	outObj.setIncomeIdFromIncome(result.get<double>(DB_FIELD_INCOME));
	outObj.setWorksAtHome(result.get<int>(DB_FIELD_WORK_AT_HOME));
	outObj.setCarLicense(result.get<int>(DB_FIELD_CAR_LICENSE));
	outObj.setMotorLicense(result.get<int>(DB_FIELD_MOTOR_LICENSE));
	outObj.setVanbusLicense(result.get<int>(DB_FIELD_VANBUS_LICENSE));
	outObj.setHasFixedWorkTiming(result.get<int>(DB_FIELD_WORK_TIME_FLEX));
	outObj.setHasWorkplace(result.get<int>(DB_FIELD_HAS_FIXED_WORK_PLACE));
	outObj.setIsStudent(result.get<int>(DB_FIELD_IS_STUDENT));
	outObj.setActivityAddressId(result.get<BigInt>(DB_FIELD_ACTIVITY_ADDRESS_ID));

	//household related
	outObj.setHhId(boost::lexical_cast<std::string>(result.get<BigInt>(DB_FIELD_HOUSEHOLD_ID)));
	outObj.setHomeAddressId(result.get<BigInt>(DB_FIELD_HOME_ADDRESS_ID));
	outObj.setHH_Size(result.get<int>(DB_FIELD_HH_SIZE));
	outObj.setHH_NumUnder4(result.get<int>(DB_FIELD_HH_CHILDREN_UNDER_4));
	outObj.setHH_NumUnder15(result.get<int>(DB_FIELD_HH_CHILDREN_UNDER_15));
	outObj.setHH_NumAdults(result.get<int>(DB_FIELD_HH_ADULTS));
	outObj.setHH_NumWorkers(result.get<int>(DB_FIELD_HH_WORKERS));

	VehicleParams vp;
	//vehicle related
		vp.setVehicleId(result.get<int>(DB_FIELD_V_ID));
		vp.setDrivetrain(result.get<std::string>(DB_FIELD_V_DRIVETRAIN));
		vp.setMake(result.get<std::string>(DB_FIELD_V_MAKE));
		vp.setModel(result.get<std::string>(DB_FIELD_V_MODEL));
	outObj.setVehicleParams(vp);
	//infer params
	outObj.fixUpParamsForLtPerson();
}

void PopulationSqlDao::toRow(PersonParams& data, Parameters& outParams, bool update)
{
}

void PopulationSqlDao::getOneById(long long id, PersonParams& outParam)
{
	db::Parameters params;
	db::Parameter idParam(id);
	params.push_back(idParam);
	getById(params, outParam);
}

void PopulationSqlDao::getAllIds(std::vector<long>& outList)
{
	if (isConnected())
    {
		ConfigParams& fullConfig = ConfigManager::GetInstanceRW().FullConfig();
		Statement query(connection.getSession<soci::session>());
		const std::string MAIN_SCHEMA = fullConfig.schemas.main_schema;
		const std::string TABLE_NAME = fullConfig.dbStoredProcMap["get_individual_id_list"];
		const std::string DB_SP_GET_INDIVIDUAL_IDS = APPLY_SCHEMA(MAIN_SCHEMA,TABLE_NAME);
		const std::string DB_GET_ALL_PERSON_IDS = "SELECT * FROM " + DB_SP_GET_INDIVIDUAL_IDS;
		prepareStatement(DB_GET_ALL_PERSON_IDS, db::EMPTY_PARAMS, query);
		ResultSet rs(query);
		for (ResultSet::const_iterator it = rs.begin(); it != rs.end(); ++it)
		{
			outList.push_back((*it).get<BigInt>(DB_FIELD_ID));
		}
		Print() << "Person Ids loaded from LT database: " << outList.size() << std::endl;
	}
}

void PopulationSqlDao::getAddresses()
{
	if (isConnected())
	{
		PersonParams::clearAddressLookup();
		PersonParams::clearZoneAddresses();
		Statement query(connection.getSession<soci::session>());
		ConfigParams& fullConfig = ConfigManager::GetInstanceRW().FullConfig();
		const std::string MAIN_SCHEMA = fullConfig.schemas.main_schema;
		const std::string TABLE_NAME = fullConfig.dbStoredProcMap["addresses"];
		const std::string DB_SP_GET_ADDRESSES = APPLY_SCHEMA(MAIN_SCHEMA, TABLE_NAME);
		const std::string DB_GET_ADDRESSES = "SELECT * FROM " + DB_SP_GET_ADDRESSES;
		prepareStatement(DB_GET_ADDRESSES, db::EMPTY_PARAMS, query);
		ResultSet rs(query);
		for (ResultSet::const_iterator it = rs.begin(); it != rs.end(); ++it)
		{
			long addressId = (*it).get<BigInt>(DB_FIELD_ADDRESS_ID);
			sim_mob::Address address;
			address.setAddressId(addressId);
			address.setPostcode((*it).get<int>(DB_FIELD_POSTCODE));
			address.setTazCode((*it).get<int>(DB_FIELD_TAZ_CODE));
			address.setDistanceMrt((*it).get<double>(DB_FIELD_DISTANCE_MRT));
			address.setDistanceBus((*it).get<double>(DB_FIELD_DISTANCE_BUS));
			PersonParams::setAddressLookup(address);
			PersonParams::setZoneNodeAddressesMap(address);
		}
	}
	else
	{
		std::cout << "Zone lookup Not connected!! " << std::endl;
	}
}

void PopulationSqlDao::getIncomeCategories(double incomeLowerLimits[])
{
	if (isConnected())
	{
		Statement query(connection.getSession<soci::session>());
		ConfigParams& fullConfig = ConfigManager::GetInstanceRW().FullConfig();
		const std::string MAIN_SCHEMA = fullConfig.schemas.main_schema;
		const std::string TABLE_NAME = fullConfig.dbTableNamesMap["income_cat"];
		const std::string DB_TABLE_INCOME_CATEGORIES = APPLY_SCHEMA(MAIN_SCHEMA,TABLE_NAME );
		const std::string DB_GET_INCOME_CATEGORIES = "SELECT * FROM " + DB_TABLE_INCOME_CATEGORIES;
		prepareStatement(DB_GET_INCOME_CATEGORIES, db::EMPTY_PARAMS, query);
		ResultSet rs(query);

		double lowLimit = 0;
		incomeLowerLimits[0] = 0;
		for (ResultSet::const_iterator it = rs.begin(); it != rs.end(); ++it)
		{
			lowLimit = (*it).get<double>(DB_FIELD_INCOME_CATEGORY_LOWER_LIMIT);
			if (lowLimit > 0)
			{
				incomeLowerLimits[(*it).get<BigInt>(DB_FIELD_ID)] = lowLimit;
			}
		}
	}
}

void PopulationSqlDao::getVehicleCategories(std::map<int, std::bitset<6> >& vehicleCategories)
{
	if (isConnected())
	{
		vehicleCategories.clear();
		Statement query(connection.getSession<soci::session>());
		ConfigParams& fullConfig = ConfigManager::GetInstanceRW().FullConfig();
		const std::string MAIN_SCHEMA = fullConfig.schemas.main_schema;
		const std::string TABLE_NAME = fullConfig.dbTableNamesMap["vehicle_ownership_status"];
		const std::string DB_TABLE_VEHICLE_OWNERSHIP_STATUS = APPLY_SCHEMA(MAIN_SCHEMA, TABLE_NAME);
		const std::string DB_GET_VEHICLE_OWNERSHIP_STATUS = "SELECT * FROM " + DB_TABLE_VEHICLE_OWNERSHIP_STATUS;
		prepareStatement(DB_GET_VEHICLE_OWNERSHIP_STATUS, db::EMPTY_PARAMS, query);
		ResultSet rs(query);
		for (ResultSet::const_iterator it = rs.begin(); it != rs.end(); ++it)
		{
			std::bitset<6> vehOwnershipBits;
			std::string categoryDescription = (*it).get<std::string>(DB_FIELD_VEHICLE_CATEGORY_NAME);
			if (categoryDescription.find(SEARCH_STRING_NO_VEHICLE) != std::string::npos)
			{
				vehOwnershipBits[0] = 1;
			}
			if (categoryDescription.find(SEARCH_STRING_MULT_MOTORCYCLE_ONLY) != std::string::npos)
			{
				vehOwnershipBits[1] = 1;
			}
			if (categoryDescription.find(SEARCH_STRING_ONE_CAR_OFF_PEAK_W_WO_MC) != std::string::npos)
			{
				vehOwnershipBits[2] = 1;
			}
			if (categoryDescription.find(SEARCH_STRING_ONE_NORMAL_CAR) != std::string::npos)
			{
				vehOwnershipBits[3] = 1;
			}
			if(categoryDescription.find(SEARCH_STRING_ONE_CAR_PLUS_MULT_MC) != std::string::npos)
			{
				vehOwnershipBits[4] = 1;
			}
			if(categoryDescription.find(SEARCH_STRING_MULT_CAR_W_WO_MC) != std::string::npos)
			{
				vehOwnershipBits[5] = 1;
			}

			vehicleCategories[(*it).get<BigInt>(DB_FIELD_ID)] = vehOwnershipBits;
		}
	}
}
std::string var_value()
{

    const std::unordered_map<StopType, ActivityTypeConfig>& activityTypeConfig = ConfigManager::GetInstance().FullConfig().getActivityTypeConfigMap();
    int num_activity= activityTypeConfig.size();
    std::string column_name =" VALUES ( :v1, ";  // for first column person_id
    for(int i=1;i<=num_activity;i++)
    {
        column_name += ":v" + std::to_string(i+1) + ", ";
    }
    column_name += ":v" + std::to_string( num_activity + 2 ) + ", :v" + std::to_string( num_activity + 3 ) + ", :v" + std::to_string( num_activity + 4 ) + ") ";

    return column_name;
}
SimmobSqlDao::SimmobSqlDao(db::DB_Connection& connection, const std::string& tableName, const std::vector<std::string>& activityLogsumColumns) :
		SqlAbstractDao<PersonParams>(
				connection,
				tableName,
				("INSERT INTO " + tableName + var_value()), //" VALUES (:v1, :v2, :v3, :v4, :v5, :v6, :v7, :v8)"), //insert
				"", //update
				("TRUNCATE " + tableName), //delete
				"", //get all
				"SELECT "
                    + getLogsumColumnsStr(activityLogsumColumns)
					+ " FROM " + tableName + " where person_id = :_id" //get by id
                ), activityLogsumColumns(activityLogsumColumns)
{
}

SimmobSqlDao::~SimmobSqlDao()
{
}

void SimmobSqlDao::fromRow(db::Row& result, PersonParams& outObj)
{
    StopType activityType = 1;
    for (const auto& column : activityLogsumColumns)
    {
        outObj.setActivityLogsum(activityType, result.get<double>(column));
        ++activityType;
    }
    outObj.setDptLogsum(result.get<double>(DB_FIELD_DPT_LOGSUM));
	outObj.setDpsLogsum(result.get<double>(DB_FIELD_DPS_LOGSUM));
	outObj.setDpbLogsum(result.get<double>(DB_FIELD_DPB_LOGSUM));
}

void SimmobSqlDao::toRow(PersonParams& data, db::Parameters& outParams, bool update)
{
    outParams.push_back(data.getPersonId());
    for (int activityType = 1; activityType <= activityLogsumColumns.size(); ++activityType)
    {
        outParams.push_back(data.getActivityLogsum(activityType));
    }
	outParams.push_back(data.getDptLogsum());
    outParams.push_back(data.getDpsLogsum());
    outParams.push_back(data.getDpbLogsum());
}

std::string SimmobSqlDao::getLogsumColumnsStr(const std::vector<std::string>& actvtylogsumClmns)
{
    std::string columnStr = "";
    for (const auto& column : actvtylogsumClmns)
    {
        columnStr += (column + ",");
    }
    columnStr += DB_FIELD_DPT_LOGSUM + "," + DB_FIELD_DPS_LOGSUM +  "," + DB_FIELD_DPB_LOGSUM;

    return columnStr;
}

void SimmobSqlDao::getLogsumById(long long id, PersonParams& outObj)
{
	db::Parameters params;
	params.push_back(id);
	getById(params, outObj);
}

void SimmobSqlDao::getPostcodeNodeMap()
{
	if (isConnected())
	{
		PersonParams::clearPostCodeNodeMap();
		ConfigParams& fullConfig = ConfigManager::GetInstanceRW().FullConfig();
		const std::string PUBLIC_SCHEMA = fullConfig.schemas.public_schema;
		const std::string TABLE_NAME = fullConfig.dbStoredProcMap["postcode_node_map"];
		const std::string DB_SP_GET_POSTCODE_NODE_MAP = APPLY_SCHEMA(PUBLIC_SCHEMA, TABLE_NAME);
		const std::string DB_GET_POSTCODE_NODE_MAP = "SELECT * FROM " + DB_SP_GET_POSTCODE_NODE_MAP;
		Statement query(connection.getSession<soci::session>());
		prepareStatement(DB_GET_POSTCODE_NODE_MAP, db::EMPTY_PARAMS, query);
		ResultSet rs(query);
		for (ResultSet::const_iterator it = rs.begin(); it != rs.end(); ++it)
		{
			sim_mob::Address address;
			address.setPostcode((*it).get<int>(DB_FIELD_POSTCODE));
			ZoneNodeParams nodeId;
			nodeId.setNodeId((*it).get<BigInt>(DB_FIELD_NODE_ID));
			PersonParams::setPostCodeNodeMap(address,nodeId);
		}
	}
}


text:
//
#pragma once

#include <array>
#include <boost/uuid/detail/md5.hpp>
#include <cstdio>
#include <fstream>
#include <string>

namespace MD5
{
using Hash = boost::uuids::detail::md5;

// 1ファイル分のMD5を計算
std::string
calc(std::string path)
{
  std::ifstream infile(path, std::ios::binary);
  Hash          hash;
  while (infile.eof() == false)
  {
    std::array<char, 8192> buff;
    infile.read(buff.data(), buff.size());
    auto nb = infile.gcount();
    hash.process_bytes(buff.data(), nb);
  }
  Hash::digest_type digest;
  hash.get_digest(digest);
  char md5string[64];
  std::snprintf(md5string,
                sizeof(md5string),
                "%08x%08x%08x%08x",
                digest[0],
                digest[1],
                digest[2],
                digest[3]);
  return md5string;
}
} // namespace MD5

ext: hpp

max_stars_repo_name: zsuzuki/filesync

max_issues_repo_name: zsuzuki/filesync

max_forks_repo_name: zsuzuki/filesync


text:
// *****************************************************************************
//
// © Copyright 2020, Septentrio NV/SA.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//    1. Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//    2. Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//    3. Neither the name of the copyright holder nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// *****************************************************************************

// *****************************************************************************
//
// Boost Software License - Version 1.0 - August 17th, 2003
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:

// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// *****************************************************************************

#ifndef COMMUNICATION_CORE_HPP // This block is called a conditional group. The
                               // controlled text will get included in the
                               // preprocessor output iff the macroname is not
                               // defined.
#define COMMUNICATION_CORE_HPP // Include guards help to avoid the double inclusion
                               // of header files, by defining a token = macro.

// Boost includes
#include <boost/asio.hpp>
#include <boost/asio/serial_port.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/exception/diagnostic_information.hpp> // dealing with bad file descriptor error
#include <boost/function.hpp>
// C++ library includes
#include <fstream>
#include <memory>
#include <sstream>
#include <unistd.h> // for usleep()
// ROSaic includes
#include <septentrio_gnss_driver/communication/async_manager.hpp>
#include <septentrio_gnss_driver/communication/callback_handlers.hpp>

/**
 * @file communication_core.hpp
 * @date 22/08/20
 * @brief Highest-Level view on communication services
 */

/**
 * @namespace io_comm_rx
 * This namespace is for the communication interface, handling all aspects related to
 * serial and TCP/IP communication..
 */
namespace io_comm_rx {

    //! Possible baudrates for the Rx
    const static uint32_t BAUDRATES[] = {
        1200,    2400,    4800,    9600,    19200,   38400,   57600,
        115200,  230400,  460800,  500000,  576000,  921600,  1000000,
        1152000, 1500000, 2000000, 2500000, 3000000, 3500000, 4000000};

    /**
     * @class Comm_IO
     * @brief Handles communication with and configuration of the mosaic (and beyond)
     * receiver(s)
     */
    class Comm_IO
    {
    public:
        /**
         * @brief Constructor of the class Comm_IO
         * @param[in] node Pointer to node
         */
        Comm_IO(ROSaicNodeBase* node, Settings* settings);
        /**
         * @brief Default destructor of the class Comm_IO
         */
        ~Comm_IO()
        {
            send("logout \x0D");
            stopping_ = true;
            connectionThread_->join();
        }

        /**
         * @brief Initializes the I/O handling
         */
        void initializeIO();

        /**
         * @brief Configures Rx: Which SBF/NMEA messages it should output and later
         * correction settings
         * @param[in] settings The device's settings
         * */
        void configureRx();

        /**
         * @brief Defines which Rx messages to read and which ROS messages to publish
         * @param[in] settings The device's settings
         * */
        void defineMessages();

    private:
        /**
         * @brief Sets up the stage for SBF file reading
         * @param[in] file_name The name of (or path to) the SBF file, e.g. "xyz.sbf"
         */
        void prepareSBFFileReading(std::string file_name);

        /**
         * @brief Sets up the stage for PCAP file reading
         * @param[in] file_name The path to PCAP file, e.g. "/tmp/capture.sbf"
         */
        void preparePCAPFileReading(std::string file_name);

        /**
         * @brief Attempts to (re)connect every reconnect_delay_s_ seconds
         */
        void reconnect();

        /**
         * @brief Calls the reconnect() method
         */
        void connect();

        /**
         * @brief Initializes the serial port
         * @param[in] port The device's port address
         * @param[in] baudrate The chosen baud rate of the port
         * @param[in] flowcontrol Default is "None", set variable (not yet checked)
         * to "RTS|CTS" to activate hardware flow control (only for serial ports
         * COM1, COM2 and COM3 (for mosaic))
         * @return True if connection could be established, false otherwise
         */
        bool initializeSerial(std::string port, uint32_t baudrate = 115200,
                              std::string flowcontrol = "None");

        /**
         * @brief Initializes the TCP I/O
         * @param[in] host The TCP host
         * @param[in] port The TCP port
         * @return True if connection could be established, false otherwise
         */
        bool initializeTCP(std::string host, std::string port);

        /**
         * @brief Initializes SBF file reading and reads SBF file by repeatedly
         * calling read_callback_()
         * @param[in] file_name The name of (or path to) the SBF file, e.g. "xyz.sbf"
         */
        void initializeSBFFileReading(std::string file_name);

        /**
         * @brief Initializes PCAP file reading and reads PCAP file by repeatedly
         * calling read_callback_()
         * @param[in] file_name The name of (or path to) the PCAP file, e.g. "/tmp/capture.pcap"
         */
        void initializePCAPFileReading(std::string file_name);

        /**
         * @brief Set the I/O manager
         * @param[in] manager An I/O handler
         */
        void setManager(const boost::shared_ptr<Manager>& manager);

        /**
         * @brief Reset the Serial I/O port, e.g. after a Rx reset
         * @param[in] port The device's port address
         */
        void resetSerial(std::string port);

        /**
         * @brief Hands over to the send() method of manager_
         * @param cmd The command to hand over
         */
        void send(std::string cmd);

        //! Pointer to Node
        ROSaicNodeBase* node_;
        //! Callback handlers for the inwards streaming messages
        CallbackHandlers handlers_;
        //! Settings
        Settings* settings_;
        //! Whether connecting to Rx was successful
        bool connected_ = false;
        //! Since the configureRx() method should only be called once the connection
        //! was established, we need the threads to communicate this to each other.
        //! Associated mutex..
        boost::mutex connection_mutex_;
        //! Since the configureRx() method should only be called once the connection
        //! was established, we need the threads to communicate this to each other.
        //! Associated condition variable..
        boost::condition_variable connection_condition_;
        //! Host name of TCP server
        std::string tcp_host_;
        //! TCP port number
        std::string tcp_port_;
        //! Whether yet-to-be-established connection to Rx will be serial or TCP
        bool serial_;
        //! Saves the port description
        std::string serial_port_;
        //! Processes I/O stream data
        //! This declaration is deliberately stream-independent (Serial or TCP).
        boost::shared_ptr<Manager> manager_;
        //! Baudrate at the moment, unless InitializeSerial or ResetSerial fail
        uint32_t baudrate_;

        //! Connection or reading thread
        std::unique_ptr<boost::thread> connectionThread_;
        //! Indicator for threads to exit
        std::atomic<bool> stopping_;

        friend class CallbackHandlers;
        friend class RxMessage;

        //! Host currently connected to
        std::string host_;
        //! Port over which TCP/IP connection is currently established
        std::string port_;
        //! Sleep time in microseconds (there is no Unix command for milliseconds)
        //! after setting the baudrate to certain value (important between
        //! increments)
        const static unsigned int SET_BAUDRATE_SLEEP_ = 500000;
    };
} // namespace io_comm_rx

#endif // for COMMUNICATION_CORE_HPP


text:
#include <algorithm>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <iostream>
#include <list>
#include <map>
#include <set>
#include <tbb/blocked_range.h>
#include <tbb/parallel_for.h>
#include <vector>

struct Layer
{
    int range = 0;
    std::vector<int> positions;

    Layer(int r)
        : range(r)
    {
        for (int i = 0; i < r; ++i) {
            positions.push_back(i);
        }
        for (int i = range - 2; i > 0; --i) {
            positions.push_back(i);
        }
    }

    int scanner_pos(int tick) const
    {
        return positions[tick % positions.size()];
    }
};

using Map = std::map<int, Layer>;

int main()
{
    Map map;

    std::string line;
    int max_k = 0;
    while (std::getline(std::cin, line)) {
        std::vector<std::string> words;
        boost::algorithm::split(
                words, line, boost::is_any_of(": "), boost::algorithm::token_compress_on);

        int k = std::stoi(&words[0][0]);
        int r = std::stoi(&words[1][0]);
        map.insert({k, Layer{r}});
        max_k = std::max(max_k, k);
    }

    int delay = 0;
    for (;;++delay) {
        bool hit = false;
        for (int pos = 0; pos <= max_k; ++pos) {
            int tick = delay + pos;
            auto it = map.find(pos);
            if (it != map.end()) {
                if (it->second.scanner_pos(tick) == 0) {
                    hit = true;
                    break;
                }
            }
        }
        if (!hit) {
            break;
        }
    }

    std::cout << "delay: " << delay << "\n";

    return 0;
}

ext: cc


text:
#if !defined(BOOST_PROTO_DONT_USE_PREPROCESSED_FILES)

    #include <boost/proto/context/detail/preprocessed/default_eval.hpp>

#elif !defined(BOOST_PP_IS_ITERATING)

    #define BOOST_PROTO_DEFAULT_EVAL_SHIFTED(Z, M, DATA)                                            \
        BOOST_PROTO_DEFAULT_EVAL(Z, BOOST_PP_ADD(M, 2), DATA)                                       \
        /**/

    #if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES)
        #pragma wave option(preserve: 2, line: 0, output: "preprocessed/default_eval.hpp")
    #endif

    ///////////////////////////////////////////////////////////////////////////////
    /// \file default_eval.hpp
    /// Contains specializations of the default_eval\<\> class template.
    //
    //  Copyright 2008 Eric Niebler. 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)

    #if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES)
        #pragma wave option(preserve: 1)
    #endif

    #define BOOST_PP_ITERATION_PARAMS_1                                                             \
        (3, (3, BOOST_PROTO_MAX_ARITY, <boost/proto/context/detail/default_eval.hpp>))
    #include BOOST_PP_ITERATE()

    #if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES)
        #pragma wave option(output: null)
    #endif

    #undef BOOST_PROTO_DEFAULT_EVAL_SHIFTED

#else

    #define N BOOST_PP_ITERATION()

    template<typename Expr, typename Context>
    struct default_eval<Expr, Context, proto::tag::function, N>
    {
        typedef
            typename proto::detail::result_of_fixup<
                BOOST_PROTO_DEFAULT_EVAL_TYPE(~, 0, Expr)
            >::type
        function_type;

        typedef
            typename BOOST_PROTO_RESULT_OF<
                function_type(BOOST_PP_ENUM_SHIFTED(N, BOOST_PROTO_DEFAULT_EVAL_TYPE, Expr))
            >::type
        result_type;

        result_type operator ()(Expr &expr, Context &context) const
        {
            return this->invoke(expr, context, is_member_function_pointer<function_type>());
        }

    private:
        result_type invoke(Expr &expr, Context &context, mpl::false_) const
        {
            return BOOST_PROTO_DEFAULT_EVAL(~, 0, expr)(
                BOOST_PP_ENUM_SHIFTED(N, BOOST_PROTO_DEFAULT_EVAL, expr)
            );
        }

        result_type invoke(Expr &expr, Context &context, mpl::true_) const
        {
            BOOST_PROTO_USE_GET_POINTER();
            typedef typename detail::classtypeof<function_type>::type class_type;
            return (
                BOOST_PROTO_GET_POINTER(class_type, (BOOST_PROTO_DEFAULT_EVAL(~, 1, expr))) ->*
                BOOST_PROTO_DEFAULT_EVAL(~, 0, expr)
            )(BOOST_PP_ENUM(BOOST_PP_SUB(N, 2), BOOST_PROTO_DEFAULT_EVAL_SHIFTED, expr));
        }
    };

    #undef N

#endif


text:
#ifndef __C_AUTOM8_PREFERENCES_HPP__
#define __C_AUTOM8_PREFERENCES_HPP__

#include <string>
#include <sqlite3.h>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>

namespace autom8 {
    class preferences {
    public:
        preferences(const std::string& name);
        ~preferences();

        template <typename KT, typename VT>
        VT& get(const KT& key, VT& value);

        template <typename KT, typename VT>
        bool set(const KT& key, const VT& value);

    private:
        sqlite3* connection_;
        std::string name_;
    };

    template <typename KT, typename VT>
    VT& preferences::get(const KT& key, VT& value) {
        std::string query = std::string(" SELECT value FROM ") + name_ + std::string(" WHERE key LIKE ?;");

        std::string key_str = boost::lexical_cast<std::string>(key);

        sqlite3_stmt* stmt = NULL;

        int result = sqlite3_prepare(
            connection_,
            query.c_str(),
            (int) query.size(),
            &stmt,
            NULL
        );

        if (result == SQLITE_OK) {
            sqlite3_bind_text(stmt, 1, key_str.c_str(), -1, SQLITE_STATIC);
            result = sqlite3_step(stmt);

            if (result == SQLITE_ROW) {
                std::string result_str((const char *) sqlite3_column_text(stmt, 0));

                try {
                    value = boost::lexical_cast<VT>(result_str);
                }
                catch (boost::bad_lexical_cast) {
                    // swallow it
                }
            }
        }

        sqlite3_finalize(stmt);

        return value;
    }

    template <typename KT, typename VT>
    bool preferences::set(const KT& key, const VT& value) {
        std::string key_str, value_str;
        try {
            key_str = boost::lexical_cast<std::string>(key);
            value_str = boost::lexical_cast<std::string>(value);
        }
        catch (boost::bad_lexical_cast) {
            return false;
        }

        std::string query = std::string(" REPLACE INTO ") + name_ + std::string(" (key, value) VALUES(?, ?);");

        sqlite3_stmt* stmt = NULL;

        int result = sqlite3_prepare(
            connection_,
            query.c_str(),
            (int) query.size(),
            &stmt,
            NULL);

        if (result == SQLITE_OK) {
            sqlite3_bind_text(stmt, 1, key_str.c_str(), -1, SQLITE_STATIC);
            sqlite3_bind_text(stmt, 2, value_str.c_str(), -1, SQLITE_STATIC);
            result = sqlite3_step(stmt);
        }

        sqlite3_finalize(stmt);

        return (result == SQLITE_DONE);
    }
}

#endif