text:
/* Copyright © 2019 Apple Inc. All rights reserved.
 *
 * Use of this source code is governed by a BSD-3-clause license that can
 * be found in the LICENSE.txt file or at
 * https://opensource.org/licenses/BSD-3-Clause
 */

#define BOOST_TEST_MODULE test_drawing_classifier

#include <toolkits/drawing_classifier/drawing_classifier.hpp>

#include <algorithm>

#include <boost/test/unit_test.hpp>
#include <core/util/test_macros.hpp>
#include <model_server/lib/image_util.hpp>

#include "../neural_net/neural_net_mocks.hpp"
#include "dc_data_utils.hpp"
#include "dc_mock_interface.hpp"

namespace turi {
namespace drawing_classifier {

namespace {

using turi::neural_net::compute_context;
using turi::neural_net::float_array_map;
using turi::neural_net::mock_compute_context;
using turi::neural_net::mock_model_backend;
using turi::neural_net::model_backend;
using turi::neural_net::model_spec;
using turi::neural_net::shared_float_array;

void test_init_training(bool with_bitmap_based_data) {
  test_drawing_classifier model;

  // Allocate the mock dependencies. We'll transfer ownership when the toolkit
  // code attempts to instantiate these dependencies.
  std::unique_ptr<mock_data_iterator> mock_iterator(new mock_data_iterator);
  std::unique_ptr<mock_model_backend> mock_nn_model(new mock_model_backend);
  std::unique_ptr<mock_compute_context> mock_context(new mock_compute_context);

  // We'll request 4 training iterations, since the learning rate schedule
  // kicks in at the 50% and 75% points.
  static constexpr size_t test_max_iterations = 4;
  static constexpr size_t test_batch_size = 2;
  const flex_list test_class_labels = {"label1", "label2"};
  static constexpr size_t test_num_rows = 100;

  mock_iterator->class_labels_ = test_class_labels;

  const std::string test_target_name = "test_target";
  const std::string test_feature_name = "test_feature";

  // The following callbacks capture by reference so that they can transfer
  // ownership of the mocks created above.

  auto create_iterator_impl = [&](data_iterator::parameters iterator_params) {
    // Should infer class labels from data.
    TS_ASSERT(iterator_params.class_labels.empty());
    TS_ASSERT(iterator_params.repeat);
    TS_ASSERT_EQUALS(iterator_params.feature_column_name, test_feature_name);

    gl_sframe data = iterator_params.data;
    TS_ASSERT(data.contains_column(iterator_params.feature_column_name));
    TS_ASSERT_EQUALS(data[iterator_params.feature_column_name].dtype(),
                     flex_type_enum::IMAGE);

    return std::move(mock_iterator);
  };

  model.create_iterator_calls_.push_back(create_iterator_impl);

  model.init_model_calls_.emplace_back([=]() {
    std::unique_ptr<model_spec> nn_spec(new model_spec);
    auto weight_init_fn = [](float* w, float* w_end) {
      for (int i = 0; i < w_end - w; ++i) {
        w[i] = static_cast<float>(i);
      }
    };
    nn_spec->add_convolution("test_layer", "test_input", 16, 16, 3, 3, 1, 1,
                             model_spec::padding_type::SAME, weight_init_fn);
    return nn_spec;
  });

  auto create_drawing_classifier_impl = [&](const float_array_map& weights,
                                            size_t batch_size,
                                            size_t num_classes) {
    TS_ASSERT_EQUALS(batch_size, test_batch_size);
    TS_ASSERT_EQUALS(num_classes, test_class_labels.size());

    // weights should be what we returned from init_model, as copied by
    // neural_net::wrap_network_params
    TS_ASSERT_EQUALS(weights.size(), 1);
    auto it = weights.find("test_layer_weight");
    TS_ASSERT(it != weights.end());
    for (size_t i = 0; i < it->second.size(); ++i) {
      TS_ASSERT_EQUALS(it->second.data()[i], static_cast<float>(i));
    }

    // TODO: Assert the config values?

    return std::move(mock_nn_model);
  };

  mock_context->create_drawing_classifier_calls_.push_back(
      create_drawing_classifier_impl);

  auto create_compute_context_impl = [&] { return std::move(mock_context); };
  model.create_compute_context_calls_.push_back(create_compute_context_impl);

  // Create an arbitrary SFrame with test_num_rows rows.
  drawing_data_generator data_generator(
    /* is_bitmap_based     */ with_bitmap_based_data,
    /* num_rows            */ test_num_rows,
    /* class_labels        */ test_class_labels,
    /* target_column_name  */ test_target_name,
    /* feature_column_name */ test_feature_name);

  gl_sframe data = data_generator.get_data();
  TS_ASSERT_EQUALS(data.size(), test_num_rows);

  std::string feature_column_name = data_generator.get_feature_column_name();
  std::string target_column_name = data_generator.get_target_column_name();
  TS_ASSERT_EQUALS(feature_column_name, test_feature_name);
  TS_ASSERT_EQUALS(target_column_name, test_target_name);

  if (!with_bitmap_based_data) {
    TS_ASSERT_EQUALS(data[feature_column_name].dtype(), flex_type_enum::LIST);
  }

  // Now, actually invoke drawing_classifier::init_training. This will trigger
  // all the assertions registered above.
  model.init_training(data, test_target_name, test_feature_name, gl_sframe(),
                      {
                          {"batch_size", test_batch_size},
                          {"max_iterations", test_max_iterations},
                      });

  // Verify model fields.
  TS_ASSERT_EQUALS(model.get_field<flex_int>("batch_size"), test_batch_size);
  TS_ASSERT_EQUALS(model.get_field<flex_int>("max_iterations"),
                   test_max_iterations);
  TS_ASSERT_EQUALS(model.get_field<flex_string>("target"), test_target_name);
  TS_ASSERT_EQUALS(model.get_field<flex_string>("feature"), test_feature_name);
  TS_ASSERT_EQUALS(model.get_field<flex_int>("num_classes"),
                   test_class_labels.size());
  TS_ASSERT_EQUALS(model.get_field<flex_int>("training_iterations"), 0);

  // Deconstructing `model` here will assert that every expected call to a
  // mocked-out method has been called.
}

/**
 * Most of this test body will be spent setting up the mock objects that we'll
 * inject into the drawing_classifier implementation. These mock objects will
 * make assertions about their inputs along the way and provide the outputs
 * that we manually pre-program. At the end will be a single call to
 * drawing_classifier::init_training that will trigger all the actual testing.
 */
BOOST_AUTO_TEST_CASE(test_drawing_classifier_init_training) {
  test_init_training(/* with_bitmap_based_data */ true);
}

BOOST_AUTO_TEST_CASE(test_init_training_with_stroke_based_conversion) {
  test_init_training(/* with_bitmap_based_data */ false);
}

/**
 * Most of this test body will be spent setting up the mock objects that we'll
 * inject into the drawing_classifier implementation. These mock objects will
 * make assertions about their inputs along the way and provide the outputs
 * that we manually pre-program. At the end will be a single call to
 * drawing_classifier::init_training that will trigger all the actual testing.
 */
BOOST_AUTO_TEST_CASE(test_drawing_classifier_iterate_training) {
  // Allocate the mock dependencies. We'll transfer ownership when the toolkit
  // code attempts to instantiate these dependencies.
  std::unique_ptr<mock_data_iterator> mock_iterator(new mock_data_iterator);
  std::unique_ptr<mock_model_backend> mock_nn_model(new mock_model_backend);
  std::unique_ptr<mock_compute_context> mock_context(new mock_compute_context);

  // We'll request 4 training iterations, since the learning rate schedule
  // kicks in at the 50% and 75% points.
  static constexpr size_t test_max_iterations = 4;
  static constexpr size_t test_batch_size = 2;
  const flex_list test_class_labels = {"label1", "label2"};
  // static constexpr size_t test_num_rows = 100;
  static constexpr float test_loss = 5.f;

  mock_iterator->class_labels_ = test_class_labels;

  auto num_iterations_submitted = std::make_shared<size_t>(0);
  for (size_t i = 0; i < test_max_iterations; ++i) {
    // Program the mock_iterator to return nothing.
    auto next_batch_impl = [=](size_t batch_size) {
      TS_ASSERT_EQUALS(batch_size, test_batch_size);

      data_iterator::batch result;
      result.num_samples = batch_size;

      return result;
    };
    mock_iterator->next_batch_calls_.push_back(next_batch_impl);

    // Since has_next_batch is the loop guard in iterate_training,
    // it will be called twice, and we need to push two implementations,
    // one that returns true, and one that returns false.
    auto has_next_batch_true_impl = [=]() { return true; };

    auto has_next_batch_false_impl = [=]() { return false; };

    mock_iterator->has_next_batch_calls_.push_back(has_next_batch_true_impl);
    mock_iterator->has_next_batch_calls_.push_back(has_next_batch_false_impl);

    auto reset_impl = [=]() { return; };
    mock_iterator->reset_calls_.push_back(reset_impl);

    // The mock_model_backend should expect calls to set_learning_rate just at
    // the 50% and 75% marks.
    if (i == test_max_iterations / 2 || i == test_max_iterations * 3 / 4) {
      auto set_learning_rate_impl = [=](float lr) {
        TS_ASSERT_EQUALS(*num_iterations_submitted, i);
      };
      mock_nn_model->set_learning_rate_calls_.push_back(set_learning_rate_impl);
    }

    // The mock_model_backend should expect `train` calls on every iteration.
    auto train_impl = [=](const float_array_map& inputs) {
      // shared_float_array input_batch = inputs.at("input");
      // TS_ASSERT_EQUALS(input_batch.data(), test_image_batch->data());

      // Track how many calls we've had.
      *num_iterations_submitted += 1;

      // Multiply loss by 8 to offset the "mps_loss_mult" factor currently
      // hardwired in to avoid fp16 underflow in MPS.
      neural_net::float_array_map result;

      result["loss"] = shared_float_array::wrap(8 * test_loss);
      result["accuracy"] = shared_float_array::wrap(.5);

      return result;
    };

    mock_nn_model->train_calls_.push_back(train_impl);
  }

  test_drawing_classifier model({{"batch_size", test_batch_size},
                                 {"max_iterations", test_max_iterations},
                                 {"num_classes", test_class_labels.size()},
                                 {"training_iterations", 0}},
                                nullptr, std::move(mock_context),
                                std::move(mock_iterator),
                                std::move(mock_nn_model));

  // Now, actually invoke drawing_classifier::iterate_training.
  // This will trigger all the assertions registered above.
  for (size_t i = 0; i < test_max_iterations; ++i) {
    model.iterate_training();
  }

  TS_ASSERT_EQUALS(model.get_field<flex_int>("training_iterations"),
                   test_max_iterations);

  // Deconstructing `model` here will assert that every expected call to a
  // mocked-out method has been called.
}

}  // namespace
}  // namespace drawing_classifier
}  // namespace turi

ext: cxx

max_stars_repo_name: pappasG/turicreate

max_issues_repo_name: pappasG/turicreate

max_forks_repo_name: pappasG/turicreate


text:
#include <string>
#include <algorithm>

std::string between_str(const std::string& input, char starts, char ends) {
    std::string::const_iterator pos_beg
        = std::find(input.begin(), input.end(), starts);
    if (pos_beg == input.end()) {
        return std::string();
    }
    ++ pos_beg;

    std::string::const_iterator pos_end
        = std::find(pos_beg, input.end(), ends);

    return std::string(pos_beg, pos_end);
}

#include <boost/utility/string_view.hpp>
boost::string_view between(
    boost::string_view input,
    char starts,
    char ends)
{
    boost::string_view::const_iterator pos_beg
        = std::find(input.cbegin(), input.cend(), starts);
    if (pos_beg == input.cend()) {
        return boost::string_view();
    }
    ++ pos_beg;

    boost::string_view::const_iterator pos_end
        = std::find(pos_beg, input.cend(), ends);
    // ...
    if (pos_end == input.cend()) {
        return boost::string_view(pos_beg, input.end() - pos_beg);
    }

    return boost::string_view(pos_beg, pos_end - pos_beg);
}

#include <vector>
void string_view_init_examples() {
    boost::string_view r0("^_^");

    std::string O_O("O__O");
    boost::string_view r1 = O_O;

    std::vector<char> chars_vec(10, '#');
    boost::string_view r2(&chars_vec.front(), chars_vec.size());

    (void)r0;
    (void)r1;
    (void)r2;
}

#include <boost/algorithm/string/case_conv.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/lexical_cast.hpp>
#include <iterator>
#include <iostream>

void string_view_algorithms_examples() {
    boost::string_view r("O_O");
    // Finding single symbol.
    std::find(r.cbegin(), r.cend(), '_');

    // Will print 'o_o'.
    boost::to_lower_copy(std::ostream_iterator<char>(std::cout), r);
    std::cout << '\n';

    // Will print 'O_O'.
    std::cout << r << '\n';

    // Will print '^_^'.
    boost::replace_all_copy(
        std::ostream_iterator<char>(std::cout), r, "O", "^"
    );
    std::cout << '\n';

    r = "100";
    assert(boost::lexical_cast<int>(r) == 100);
}

int main() {
    std::cout << between("Getting expression (between brackets)", '(', ')') << '\n';

    std::string s("(expression)");
    std::cout << between(s, '(', ')') << '\n';

    string_view_init_examples();
    string_view_algorithms_examples();

    assert(between_str(s, '(', ')') == between(s, '(', ')'));
    assert(between_str("(expr", '(', ')') == between("(expr", '(', ')'));
    assert(between_str("expr)", '(', ')') == between("expr)", '(', ')'));
}

ext: cpp

max_stars_repo_name: apolukhin/boost-cookbook

max_issues_repo_name: apolukhin/boost-cookbook

max_forks_repo_name: apolukhin/boost-cookbook


text:
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef NETKET_SGD_HPP
#define NETKET_SGD_HPP

#include "abstract_optimizer.hpp"
#include <Eigen/Core>
#include <Eigen/Dense>
#include <cassert>
#include <cmath>
#include <iostream>

namespace netket {

class Sgd : public AbstractOptimizer {
  // decay constant
  double eta_;

  int npar_;

  double l2reg_;

  double decay_factor_;

public:
  // Json constructor
  explicit Sgd(const json &pars) {
    npar_ = -1;

    from_json(pars);
    PrintParameters();
  }

  void PrintParameters() {
    InfoMessage() << "Sgd optimizer initialized with these parameters :"
                  << std::endl;
    InfoMessage() << "Learning Rate = " << eta_ << std::endl;
    InfoMessage() << "L2 Regularization = " << l2reg_ << std::endl;
    InfoMessage() << "Decay Factor = " << decay_factor_ << std::endl;
  }

  void Init(const Eigen::VectorXd &pars) override { npar_ = pars.size(); }

  void Init(const Eigen::VectorXcd &pars) override { npar_ = 2 * pars.size(); }

  void Update(const Eigen::VectorXd &grad, Eigen::VectorXd &pars) override {
    assert(npar_ > 0);

    eta_ *= decay_factor_;

    for (int i = 0; i < npar_; i++) {
      pars(i) = pars(i) - (grad(i) + l2reg_ * pars(i)) * eta_;
    }
  }

  void Update(const Eigen::VectorXcd &grad, Eigen::VectorXd &pars) override {
    Update(Eigen::VectorXd(grad.real()), pars);
  }

  void Update(const Eigen::VectorXcd &grad, Eigen::VectorXcd &pars) override {
    eta_ *= decay_factor_;

    for (int i = 0; i < pars.size(); i++) {
      pars(i) = pars(i) - (grad(i) + l2reg_ * pars(i)) * eta_;
    }
  }

  void SetDecayFactor(double decay_factor) {
    assert(decay_factor <= 1.00001);
    decay_factor_ = decay_factor;
  }

  void Reset() override {}

  void from_json(const json &pars) {
    // DEPRECATED (to remove for v2.0.0)
    std::string section = "Optimizer";
    if (!FieldExists(pars, section)) {
      section = "Learning";
    }

    eta_ = FieldVal(pars[section], "LearningRate");
    l2reg_ = FieldOrDefaultVal(pars[section], "L2Reg", 0.0);
    SetDecayFactor(FieldOrDefaultVal(pars[section], "DecayFactor", 1.0));
  }
};

} // namespace netket

#endif

ext: hpp


text:
//
//  Created by huanghaifeng on 16-3-1.
//  Copyright (c) 2016 wonghoifung. All rights reserved.
//
#include "conn_manager.h"
#include "config.h"
#include "shared/utils/common_globals.h"
#include "shared/utils/logger.h"
#include <boost/bind.hpp>

conn_info::conn_info() :type(CONN_TYPE_UNVERIFIED), id(-1), idle_timer(NULL), last_op_count(0), current_op_count(0)
{
	start_idle_timer();
}

conn_info::~conn_info()
{
	stop_idle_timer();
}

void conn_info::start_idle_timer()
{
	if (!idle_timer)
	{
		idle_timer = new boost::asio::deadline_timer(global_io_service::ref().get());
	}
	boost::system::error_code e;
	idle_timer->expires_from_now(boost::posix_time::seconds(config::ref().pingpong_timeout()), e);
	idle_timer->async_wait(boost::bind(&conn_info::on_idle_timeout, this, boost::asio::placeholders::error));
}

void conn_info::stop_idle_timer()
{
	if (idle_timer)
	{
		boost::system::error_code e;
		idle_timer->cancel(e);
		delete idle_timer;
		idle_timer = NULL;
	}
}

void conn_info::update_current_op_count()
{
	current_op_count += 1;
}

void conn_info::on_idle_timeout(const boost::system::error_code& error)
{
	if (error)
	{
		return;
	}

	if (current_op_count == last_op_count)
	{
		logstr("%s %d timeout, close %s", conn_type_str(type), id, conn->remoteaddr().c_str());
		conn->stop();
	}
	else
	{
		last_op_count = current_op_count;
		start_idle_timer();
	}
}

conn_manager& conn_manager::ref()
{
	static conn_manager bm;
	return bm;
}

int conn_manager::insert_producer(int id, tcpconn_ptr conn)
{
	//delete_producer(id);
	conn_info* info = new conn_info();
	info->conn = conn;
	info->type = CONN_TYPE_PRODUCER;
	info->id = id;
	conn->set_id(id);
	conn->set_ud(info);
	return producers_.insert(std::make_pair(id, info)).second ? 0 : 1;
}

int conn_manager::delete_producer(int id)
{
	connmap_t::iterator it = producers_.find(id);
	if (it != producers_.end())
	{
		it->second->conn->set_id(0);
		it->second->conn->set_ud(NULL);
		it->second->stop_idle_timer();
		delete it->second;
		producers_.erase(it);
	}
	return 0;
}

tcpconn_ptr conn_manager::producer_conn(int id)
{
	conn_info* info = producer_info(id);
	if (info) {
		return info->conn;
	}
	else {
		return tcpconn_ptr(); // null
	}
}

conn_info* conn_manager::producer_info(int id)
{
	connmap_t::iterator it = producers_.find(id);
	if (it == producers_.end())
	{
		return NULL;
	}
	return it->second;
}

int conn_manager::insert_consumer(int id, tcpconn_ptr conn)
{
	//delete_consumer(id);
	conn_info* info = new conn_info();
	info->conn = conn;
	info->type = CONN_TYPE_CONSUMER;
	info->id = id;
	conn->set_id(id);
	conn->set_ud(info);
	add_consumer_cap(id, config::ref().consumer_cap());
	return consumers_.insert(std::make_pair(id, info)).second ? 0 : 1;
}

int conn_manager::delete_consumer(int id)
{
	connmap_t::iterator it = consumers_.find(id);
	if (it != consumers_.end())
	{
		it->second->conn->set_id(0);
		it->second->conn->set_ud(NULL);
		it->second->stop_idle_timer();
		delete it->second;
		consumer_cap_.erase(id);
		consumers_.erase(it);
	}
	return 0;
}

tcpconn_ptr conn_manager::consumer_conn(int id)
{
	conn_info* info = consumer_info(id);
	if (info) {
		return info->conn;
	}
	else {
		return tcpconn_ptr(); // null
	}
}

conn_info* conn_manager::consumer_info(int id)
{
	connmap_t::iterator it = consumers_.find(id);
	if (it == consumers_.end())
	{
		return NULL;
	}
	return it->second;
}

bool conn_manager::add_consumer_cap(int id, int addcap)
{
	int& cap = consumer_cap_[id];
	if (cap + addcap > config::ref().consumer_cap()) return false;
	cap += addcap;
	return true;
}

bool conn_manager::sub_consumer_cap(int id, int subcap)
{
	int& cap = consumer_cap_[id];
	if (cap < subcap) return false;
	cap -= subcap;
	return true;
}

int conn_manager::consumer_cap(int id)
{
	return consumer_cap_[id];
}

max_stars_repo_name: wonghoifung/learning-python

max_issues_repo_name: wonghoifung/learning-python

max_forks_repo_name: wonghoifung/learning-python


text:
/* Copyright (C) 2012-2017 IBM Corp.
 * This program is Licensed under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *   http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. See accompanying LICENSE file.
 */
namespace std {} using namespace std;
namespace NTL {} using namespace NTL;

#include <NTL/BasicThreadPool.h>

#include "EvalMap.h"
#include "hypercube.h"
#include "powerful.h"

NTL_CLIENT

static bool dry = false; // a dry-run flag
static bool noPrint = true;

void  TestIt(long p, long r, long c, long _k,
             long L, Vec<long>& mvec,
             Vec<long>& gens, Vec<long>& ords, long useCache)
{
  if (lsize(mvec)<1) { // use default values
    mvec.SetLength(3); gens.SetLength(3); ords.SetLength(3);
    mvec[0] = 7;    mvec[1] = 3;    mvec[2] = 221;
    gens[0] = 3979; gens[1] = 3095; gens[2] = 3760;
    ords[0] = 6;    ords[1] = 2;    ords[2] = -8;
  }
  if (!noPrint)
    cout << "*** TestIt"
       << (dry? " (dry run):" : ":")
       << " p=" << p
       << ", r=" << r
       << ", c=" << c
       << ", k=" << _k
       << ", L=" << L
       << ", mvec=" << mvec << ", "
       << ", useCache = " << useCache
       << endl;

  setTimersOn();
  setDryRun(false); // Need to get a "real context" to test EvalMap

  // mvec is supposed to include the prime-power factorization of m
  long nfactors = mvec.length();
  for (long i = 0; i < nfactors; i++)
    for (long j = i+1; j < nfactors; j++)
      assert(GCD(mvec[i], mvec[j]) == 1);

  // multiply all the prime powers to get m itself
  long m = computeProd(mvec);
  assert(GCD(p, m) == 1);

  // build a context with these generators and orders
  vector<long> gens1, ords1;
  convert(gens1, gens);
  convert(ords1, ords);
  FHEcontext context(m, p, r, gens1, ords1);
  buildModChain(context, L, c);

  if (!noPrint) {
    context.zMStar.printout(); // print structure of Zm* /(p) to cout
    cout << endl;
  }
  long d = context.zMStar.getOrdP();
  long phim = context.zMStar.getPhiM();
  long nslots = phim/d;

  setDryRun(dry); // Now we can set the dry-run flag if desired

  FHESecKey secretKey(context);
  const FHEPubKey& publicKey = secretKey;
  secretKey.GenSecKey(); // A Hamming-weight-w secret key
  addSome1DMatrices(secretKey); // compute key-switching matrices that we need
  addFrbMatrices(secretKey); // compute key-switching matrices that we need

  // GG defines the plaintext space Z_p[X]/GG(X)
  ZZX GG;
  GG = context.alMod.getFactorsOverZZ()[0];
  EncryptedArray ea(context, GG);

  zz_p::init(context.alMod.getPPowR());
  zz_pX F;
  random(F, phim); // a random polynomial of degree phi(m)-1 modulo p

  // convert F to powerful representation: cube represents a multi-variate
  // polynomial with as many variables Xi as factors mi in mvec. cube has
  // degree phi(mi) in the variable Xi, and the coefficients are given
  // in lexicographic order.

  // compute tables for converting between powerful and zz_pX
  PowerfulTranslationIndexes ind(mvec); // indpendent of p
  PowerfulConversion pConv(ind);        // depends on p

  HyperCube<zz_p> cube(pConv.getShortSig());
  pConv.polyToPowerful(cube, F);

  // Sanity check: convert back and compare
  zz_pX F2;
  pConv.powerfulToPoly(F2, cube);
  if (F != F2) {
    cout << "BAD\n";
    if (!noPrint) cout << " @@@ conversion error ):\n";
  }
  // pack the coefficients from cube in the plaintext slots: the j'th
  // slot contains the polynomial pj(X) = \sum_{t=0}^{d-1} cube[jd+t] X^t
  vector<ZZX> val1;
  val1.resize(nslots);
  for (long i = 0; i < phim; i++) {
    val1[i/d] += conv<ZZX>(conv<ZZ>(cube[i])) << (i % d);
  }
  PlaintextArray pa1(ea);
  encode(ea, pa1, val1);

  Ctxt ctxt(publicKey);
  ea.encrypt(ctxt, publicKey, pa1);

  resetAllTimers();
  FHE_NTIMER_START(ALL);

  // Compute homomorphically the transformation that takes the
  // coefficients packed in the slots and produces the polynomial
  // corresponding to cube

  if (!noPrint) CheckCtxt(ctxt, "init");

  if (!noPrint) cout << "build EvalMap\n";
  EvalMap map(ea, /*minimal=*/false, mvec,
    /*invert=*/false, /*build_cache=*/false, /*normal_basis=*/false);
  // compute the transformation to apply

  if (!noPrint) cout << "apply EvalMap\n";
  if (useCache) map.upgrade();
  map.apply(ctxt); // apply the transformation to ctxt
  if (!noPrint) CheckCtxt(ctxt, "EvalMap");
  if (!noPrint) cout << "check results\n";

  ZZX FF1;
  secretKey.Decrypt(FF1, ctxt);
  zz_pX F1 = conv<zz_pX>(FF1);

  if (F1 == F)
    cout << "GOOD\n";
  else
    cout << "BAD\n";

  publicKey.Encrypt(ctxt, FF1);
  if (!noPrint) CheckCtxt(ctxt, "init");

  // Compute homomorphically the inverse transformation that takes the
  // polynomial corresponding to cube and produces the coefficients
  // packed in the slots

  if (!noPrint) cout << "build EvalMap\n";
  EvalMap imap(ea, /*minimal=*/false, mvec,
    /*invert=*/true, /*build_cache=*/false, /*normal_basis=*/false);
  // compute the transformation to apply
  if (!noPrint) cout << "apply EvalMap\n";
  if (useCache) imap.upgrade();
  imap.apply(ctxt); // apply the transformation to ctxt
  if (!noPrint) {
    CheckCtxt(ctxt, "EvalMap");
    cout << "check results\n";
  }
  PlaintextArray pa2(ea);
  ea.decrypt(ctxt, secretKey, pa2);

  if (equals(ea, pa1, pa2))
    cout << "GOOD\n";
  else
    cout << "BAD\n";
  FHE_NTIMER_STOP(ALL);

  if (!noPrint) {
    cout << "\n*********\n";
    printAllTimers();
    cout << endl;
  }
}

/* Usage: Test_EvalMap_x.exe [ name=value ]...
 *  p       plaintext base  [ default=2 ]
 *  r       lifting  [ default=1 ]
 *  c       number of columns in the key-switching matrices  [ default=2 ]
 *  k       security parameter  [ default=80 ]
 *  L       # of bits in the modulus chain
 *  s       minimum number of slots  [ default=0 ]
 *  seed    PRG seed  [ default=0 ]
 *  mvec    use specified factorization of m
 *             e.g., mvec='[5 3 187]'
 *  gens    use specified vector of generators
 *             e.g., gens='[562 1871 751]'
 *  ords    use specified vector of orders
 *             e.g., ords='[4 2 -4]', negative means 'bad'
 */
int main(int argc, char *argv[])
{
  ArgMapping amap;

  long p=2;
  amap.arg("p", p, "plaintext base");

  long r=1;
  amap.arg("r", r,  "lifting");

  long c=2;
  amap.arg("c", c, "number of columns in the key-switching matrices");

  long k=80;
  amap.arg("k", k, "security parameter");

  long L=300;
  amap.arg("L", L, "# of bits in the modulus chain");

  long s=0;
  amap.arg("s", s, "minimum number of slots");

  long seed=0;
  amap.arg("seed", seed, "PRG seed");

  Vec<long> mvec;
  amap.arg("mvec", mvec, "use specified factorization of m", NULL);
  amap.note("e.g., mvec='[7 3 221]'");

  Vec<long> gens;
  amap.arg("gens", gens, "use specified vector of generators", NULL);
  amap.note("e.g., gens='[3979 3095 3760]'");

  Vec<long> ords;
  amap.arg("ords", ords, "use specified vector of orders", NULL);
  amap.note("e.g., ords='[6 2 -8]', negative means 'bad'");

  amap.arg("dry", dry, "a dry-run flag to check the noise");

  long nthreads=1;
  amap.arg("nthreads", nthreads, "number of threads");

  amap.arg("noPrint", noPrint, "suppress printouts");

  long useCache=0;
  amap.arg("useCache", useCache, "0: zzX cache, 2: DCRT cache");

  amap.parse(argc, argv);

  SetNumThreads(nthreads);

  SetSeed(conv<ZZ>(seed));
  TestIt(p, r, c, k, L, mvec, gens, ords, useCache);
}

// ./Test_EvalMap_x mvec="[73 433]" gens="[18620 12995]" ords="[72 -6]"

max_stars_repo_name: usafchn/DiPSI

max_issues_repo_name: usafchn/DiPSI

max_forks_repo_name: usafchn/DiPSI


text:
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
// Copyright (c) 2016 Klemens D. Morgenstern
//
// 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)

/**
 * \file boost/process/execute.hpp
 *
 * Defines a function to execute a program.
 */

#ifndef BOOST_PROCESS_EXECUTE_HPP
#define BOOST_PROCESS_EXECUTE_HPP

#include <process/detail/config.hpp>
#include <process/detail/traits.hpp>

#if defined(BOOST_POSIX_API)
#include <boost/process/detail/posix/executor.hpp>
#elif defined(BOOST_WINDOWS_API)
#include <process/detail/windows/executor.hpp>
#endif

#include <process/detail/basic_cmd.hpp>
#include <process/detail/handler.hpp>

#include <boost/fusion/view.hpp>
#include <boost/fusion/container.hpp>
#include <boost/fusion/sequence.hpp>
#include <boost/fusion/tuple.hpp>
#include <boost/fusion/algorithm/transformation/filter_if.hpp>
//#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/fusion/container/vector/convert.hpp>

#include <fusion/container/set/append.hpp>
#include <boost/fusion/algorithm/transformation/transform.hpp>

#include <type_traits>
#include <utility>

namespace ets { namespace process {

class child;

namespace detail {

/*
template<typename ...Args>
struct has_wchar;
*/

template<typename Iterator, typename End>
struct has_wchar
{
    typedef has_wchar<typename boost::fusion::result_of::next<Iterator>::type, End> next;
    typedef typename std::remove_cv<
        typename std::remove_reference<
            typename boost::fusion::result_of::deref<Iterator>::type
        >::type>::type res_type;

    BOOST_CONSTEXPR_OR_CONST static bool my_value = is_wchar_t<res_type>::value;
    BOOST_CONSTEXPR_OR_CONST static bool value = my_value || next::value;

    typedef std::integral_constant<bool, value> type;
};

template<typename Iterator>
struct has_wchar<Iterator, Iterator>
{
    /*
    typedef typename std::remove_cv<
        typename std::remove_reference<First>::type>::type res_type;

    BOOST_CONSTEXPR_OR_CONST static bool value = is_wchar_t<res_type>::value;

    typedef std::integral_constant<bool, value> type;
    */
    BOOST_CONSTEXPR_OR_CONST static bool value = false;
    typedef std::false_type type;
};

#if defined(BOOST_WINDOWS_API)
//everything needs to be wchar_t
#if defined(BOOST_NO_ANSI_APIS)
template<bool has_wchar>
struct required_char_type
{
    typedef wchar_t type;
};
#else
template<bool has_wchar> struct required_char_type;
template<> struct required_char_type<true>
{
    typedef wchar_t type;
};
template<> struct required_char_type<false>
{
    typedef char type;
};
#endif

#elif defined(BOOST_POSIX_API)
template<bool has_wchar>
struct required_char_type
{
    typedef char type;
};
#endif

/*
template<typename ... Args>
using required_char_type_t = typename required_char_type<
    has_wchar<Args...>::value>::type;
*/

template<typename Iterator, typename End, typename Set = boost::fusion::set<>>
struct make_builders_from_view
{
    //typedef boost::fusion::set<Args...> set;
    typedef typename boost::fusion::result_of::deref<Iterator>::type ref_type;
    typedef typename std::remove_reference<ref_type>::type res_type;
    typedef typename initializer_tag<res_type>::type tag;
    typedef typename initializer_builder<tag>::type builder_type;
    /*
    typedef typename boost::fusion::result_of::has_key<Set, builder_type> has_key;

    typedef typename boost::fusion::result_of::next<Iterator>::type next_itr;
    typedef typename make_builders_from_view<next_itr, End>::type next;

    typedef typename
            std::conditional<has_key::value,
                typename make_builders_from_view<next_itr, End, Set>::type,
                typename make_builders_from_view<next_itr, End, my_make_set<Set, builder_type>::type>::type
            >::type type;
    */
    typedef typename make_builders_from_view<
        typename boost::fusion::result_of::next<Iterator>::type,
        End,
        typename ets::fusion::result_of::append_set<Set, builder_type>::type
    >::type type;
};

template<typename Iterator, typename Set>
struct make_builders_from_view<Iterator, Iterator, Set>
{
    //typedef boost::fusion::set<Args...> type;
    typedef Set type;
};

template<typename Builders>
struct builder_ref
{
    Builders &builders;
    builder_ref(Builders & builders) : builders(builders) {};

    template<typename T>
    void operator()(T && value) const
    {
        typedef typename initializer_tag<typename std::remove_reference<T>::type>::type tag;
        typedef typename initializer_builder<tag>::type builder_type;
        boost::fusion::at_key<builder_type>(builders)(std::forward<T>(value));
    }
};

template<typename T>
struct get_initializers_result
{
    typedef typename T::result_type type;
};

template<>
struct get_initializers_result<boost::fusion::void_>
{
    typedef boost::fusion::void_ type;
};

/*
template<typename ...Args>
struct helper_vector
{

};

template<typename T, typename ...Stack>
struct invoke_get_initializer_collect_keys;

template<typename ...Stack>
struct invoke_get_initializer_collect_keys<boost::fusion::vector<>, Stack...>
{
    typedef helper_vector<Stack...> type;
};

template<typename First, typename ...Args, typename ...Stack>
struct invoke_get_initializer_collect_keys<boost::fusion::vector<First, Args...>, Stack...>
{
    typedef typename invoke_get_initializer_collect_keys<boost::fusion::vector<Args...>, Stack..., First>::type next;
    typedef helper_vector<Stack...> stack_t;

    typedef typename std::conditional<std::is_same<boost::fusion::void_, First>::value,
            stack_t, next>::type type;

};

template<typename Keys>
struct invoke_get_initializer;

template<typename ...Args>
struct invoke_get_initializer<helper_vector<Args...>>

{
    typedef boost::fusion::tuple<typename get_initializers_result<Args>::type...> result_type;

    template<typename Sequence>
    static result_type call(Sequence & seq)
    {
        return result_type(boost::fusion::at_key<Args>(seq).get_initializer()...);;
    }
};

template<typename ...Args>
inline boost::fusion::tuple<typename get_initializers_result<Args>::type...>
        get_initializers(boost::fusion::set<Args...> & builders)
{
    //typedef boost::fusion::tuple<typename get_initializers_result<Args>::type...> return_type;
    typedef typename invoke_get_initializer_collect_keys<boost::fusion::vector<Args...>>::type keys;
    return invoke_get_initializer<keys>::call(builders);
}
*/

struct get_initializers
{
    template<typename F>
    struct result;

    template <typename Element>
    struct result<get_initializers(Element)>
    {
        typedef typename get_initializers_result<Element>::type type;
    };

    template <typename Element>
    struct result<get_initializers(Element &)>
    {
        typedef typename get_initializers_result<Element>::type type;
    };

    template<typename Element>
    typename result<get_initializers(Element)>::type
    operator ()(Element &e) const
    {
        return e.get_initializer();
    }
};

template<typename Char, typename Sequence>
inline child basic_execute_impl(Sequence &tup)
{
    //create a tuple from the argument list
    //boost::fusion::tuple<typename std::remove_reference<Args>::type&...> tup(args...);

    //auto inits = boost::fusion::filter_if<
    auto inits = boost::fusion::filter_view<Sequence,
                is_initializer<
                    typename std::remove_reference<
                        boost::mpl::_
                        >::type
                    >
                >(tup);

    //auto others = boost::fusion::filter_if<
    auto others = boost::fusion::filter_view<Sequence,
                boost::mpl::not_<
                    is_initializer<
                     typename std::remove_reference<
                            boost::mpl::_
                            >::type
                        >
                    >
                >(tup);

   // typename detail::make_builders_from_view<decltype(others)>::type builders;

    //typedef typename boost::fusion::result_of::as_vector<decltype(inits)>::type  inits_t;
    typedef typename boost::fusion::result_of::as_vector<decltype(others)>::type others_t;
    //  typedef decltype(others) others_t;
    typedef typename ::ets::process::detail::make_builders_from_view<
            typename boost::fusion::result_of::begin<others_t>::type,
            typename boost::fusion::result_of::end  <others_t>::type>::type builder_t;

    builder_t builders;
    ::ets::process::detail::builder_ref<builder_t> builder_ref(builders);

    boost::fusion::for_each(others, builder_ref);
    //auto other_inits = ::ets::process::detail::get_initializers(builders);
    auto other_inits = boost::fusion::as_vector(
        boost::fusion::transform_view<builder_t, get_initializers>(builders, get_initializers()));

    boost::fusion::joint_view<decltype(other_inits), decltype(inits)> complete_inits(other_inits, inits);
    auto exec = ets::process::detail::api::make_executor<Char>(complete_inits);
    return exec();
}

template<typename Char>
struct call_char_converter
{
    template<typename F>
    struct result;

    template <typename Element>
    struct result<call_char_converter(Element &)>
    {
        typedef typename ets::process::detail::char_converter<Char, Element> res_char_converter;
        typedef typename boost::detail::tr1_result_of_impl<
            res_char_converter,
            Element,
            boost::detail::has_result_type<res_char_converter>::value
        >::type type;
    };

    template<typename Element>
    typename result<call_char_converter(Element &)>::type
        operator ()(Element &e) const
    {
        return ets::process::detail::char_converter<Char, Element>::conv(e);
    }
};

template<typename Sequence>
inline child execute_impl(Sequence &tup)
{
    typedef typename required_char_type<has_wchar<
        typename boost::fusion::result_of::begin<Sequence>::type,
        typename boost::fusion::result_of::end<Sequence>::type>::value>::type req_char_type;

    return basic_execute_impl<req_char_type>(
        boost::fusion::transform_view<Sequence, call_char_converter<req_char_type>>(
            tup, call_char_converter<req_char_type>()));
}

}}}

#endif

max_stars_repo_name: ets-ddui/ets

max_issues_repo_name: ets-ddui/ets

max_forks_repo_name: ets-ddui/ets


text:
/*
ConvGpsToLL

※　カノニカル入力処理　＆　同期　通信方式

カノニカル：１行単位でread関数が動く
同期：データが来るまでread関数が待機

Author Nuk1 kondo copy right suzuki motor corp.
2017.10.12

*/

#include <ros/ros.h>
#include <algorithm>
#include <sensor_msgs/NavSatFix.h>
#include <gnss_suzuki/StringWithStamped.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <fcntl.h>

#include <vector>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

#include <termios.h>
#define BAUDRATE B38400  //ボーレート

typedef struct {
   int    latitude_degree;  //緯度(度)
   double latitude_minute;  //緯度(分)
   double latitude;         //緯度

   int    longitude_degree; //経度(度)
   double longitude_minute; //経度(分)
   double longitude;        //経度
} GPGGA_FORMAT;

class ConvGpsToLL{
   public:
     ConvGpsToLL();   //breief: constructor

     bool inital_port(); //@breief: open port, store current port settings and set port setting
     bool read_serial_port();  //@breief: read serial port and input data to buf
     bool convert_data();  //@breief: convert serial data to longitude latitude topic
     bool publish_topic(int ret);  //@breief: publish longitude latitude topic
     bool close_port();  //@breief: close port and restorre port settings

   private:
     ros::Publisher ll_pub, gpgga_pub;

     GPGGA_FORMAT gpgga_data_;

     int fd; //ファイルディスクリプタ
     std::string data_str; //生データ保管
     struct termios newtio, oldtio;  // シリアル通信設定の構造体
     std::vector<std::string> elements;  //bunkatu-data

     std::string GPS_PORT_NUM; //port_namae

};

ConvGpsToLL::ConvGpsToLL()
{
   ros::NodeHandle private_nh("~");
   ll_pub = private_nh.advertise<sensor_msgs::NavSatFix>("/NavSatFix_msg", 1);
   gpgga_pub = private_nh.advertise<gnss_suzuki::StringWithStamped>("/GPGGA_msg", 1);

   private_nh.param("GPS_PORT", GPS_PORT_NUM, std::string("/dev/ttyUSB0"));
   ROS_INFO("port:%s, baudrate:%d", GPS_PORT_NUM.c_str(), BAUDRATE);
}

bool ConvGpsToLL::inital_port(){

  const char* GPS_PORT = GPS_PORT_NUM.c_str();
  fd = open(GPS_PORT, O_RDONLY);     // デバイスをオープンする
  if (fd < 0) {
      printf("open error\n");
      return -1;
  }

  tcgetattr(fd, &oldtio);     //現在のシリアルポートの設定を待避させる

  bzero(&newtio, sizeof(newtio));  //数値ゼロで埋める（初期化）
  /*
    BAUDRATE: ボーレートの設定
    CRTSCTS : 出力のハードウェアフロー制御
    CS8     : 8n1 (8 ビット，ノンパリティ，ストップビット 1)
    CLOCAL  : ローカル接続，モデム制御なし
    CREAD   : 受信文字(receiving characters)を有効にする．
 */
  newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;

  /*
    IGNPAR  : パリティエラーのデータは無視する
    ICRNL   : CR を NL に対応させる(これを行わないと，他のコンピュータで
              CR を入力しても，入力が終りにならない)
    それ以外の設定では，デバイスは raw モードである(他の入力処理は行わない)
  */

  newtio.c_iflag = IGNPAR;
  newtio.c_oflag = 0; // Raw モードでの出力

  /*
    ICANON  : カノニカル入力を有効にする
    全てのエコーを無効にし，プログラムに対してシグナルは送らせない
  */
  newtio.c_lflag = ICANON;

  //モデムラインをクリアし，ポートの設定を有効にする
  tcflush(fd, TCIFLUSH);
  tcsetattr(fd,TCSANOW,&newtio);

  return(0);

}

bool ConvGpsToLL::read_serial_port(){

  char buf[1000]="";
  if(read(fd,buf,500) == -1){  //1行(改行まで）read
    printf("read error\n");
    return -1;
  }

  data_str = std::string(buf);

  //受信チェックGPGGA文字受信してたらOK
   if(strncmp(buf, "$GPGGA", 6)!=0){
     ROS_INFO("no sentence GPGGA: %s", buf);
     return 1;
   }

  //NULL check
   elements.clear();
   boost::split(elements, data_str, boost::is_any_of(","));  // split sentence the word ","
   for(int i=0; i<13; i++){
     if(elements[i].empty()){
        ROS_INFO("sum elements is empty: %s", buf);
        return 1;
     }
     i++;
   }

   ROS_INFO("Correct GPS data accepted: %s", buf);
   return 0;

}

bool ConvGpsToLL::convert_data(){

   //elements[2]が緯度情報ddmm.mmmm
   gpgga_data_.latitude_degree = boost::lexical_cast<int>(elements[2].substr(0, 2));
   gpgga_data_.latitude_minute = boost::lexical_cast<double>(elements[2].substr(2, 7));
   gpgga_data_.latitude = (double) gpgga_data_.latitude_degree + gpgga_data_.latitude_minute / 60.0;
   //elements[4]が経度情報dddmm.mmmm
   gpgga_data_.longitude_degree = boost::lexical_cast<int>(elements[4].substr(0, 3));
   gpgga_data_.longitude_minute = boost::lexical_cast<double>(elements[4].substr(3, 7));
   gpgga_data_.longitude = (double) gpgga_data_.longitude_degree + gpgga_data_.longitude_minute / 60.0;

   return 0;
}

bool ConvGpsToLL::publish_topic(int ret){

   if(ret == 0){
     sensor_msgs::NavSatFix ll_topic;
     ll_topic.header.seq++;
     ll_topic.header.stamp = ros::Time::now();
     ll_topic.header.frame_id = "GPS_Frame";
     ll_topic.latitude = gpgga_data_.latitude;
     ll_topic.longitude = gpgga_data_.longitude;
     ll_pub.publish(ll_topic);
   }

   gnss_suzuki::StringWithStamped gpgga_topic;
   gpgga_topic.header.stamp = ros::Time::now();
   gpgga_topic.header.frame_id = "GPS_Frame";
   gpgga_topic.data = data_str;
   gpgga_pub.publish(gpgga_topic);

   return 0;
}

bool ConvGpsToLL::close_port(){

  tcsetattr(fd, TCSANOW, &oldtio);  /* 退避させた設定に戻す */
  close(fd);

}

int main(int argc, char *argv[]){
   ros::init(argc, argv, "ConvGpsToLL");
   int ret;
   ConvGpsToLL convgpstoll;
   int i=0;

   if( convgpstoll.inital_port() ){
      ROS_ERROR("at inital_port, sumthing error occurs");
      convgpstoll.close_port();  //initial　異常終了
      return -1;
   }

   ros::Rate pub_rate(200);
   while(ros::ok()){
     i++;
     ret = convgpstoll.read_serial_port();
     if(ret == -1){
       ROS_ERROR("at read_serial_port, sumthing error occurs");
     }else if(ret == 1){   //can read but incorrect data
       convgpstoll.publish_topic(ret);
     }else if(ret == 0){
       convgpstoll.convert_data();
       convgpstoll.publish_topic(ret);
     }
     pub_rate.sleep();    //ちょっと待つ
   }

   convgpstoll.close_port(); //正常終了
   return 0;
}


text:
//  (C) Copyright Eric Niebler 2005.
//  Use, modification and distribution are subject to 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 <boost/test/unit_test.hpp>
#include <boost/time_series/dense_series.hpp>
#include <boost/time_series/ordered_inserter.hpp>
#include <boost/time_series/numeric/numeric.hpp>

using namespace boost::unit_test;
using namespace boost::time_series;

namespace seq = boost::sequence;
namespace rrs = boost::range_run_storage;

///////////////////////////////////////////////////////////////////////////////
// test_dense_series
//
void test_dense_series()
{
    // sanity checks, shifted series.
    dense_series<int> ts(start = -1, stop = 3);

    make_ordered_inserter(ts)(42, -1).commit();

    BOOST_CHECK_EQUAL(-1, rrs::offset(rrs::runs(ts)(*seq::begin(ts))));
    BOOST_CHECK_EQUAL(42, seq::elements(ts)(*seq::begin(ts)));

    // check addition of two dense time series yields a dense time series
    dense_series<int> ss1;
    dense_series<int> ss2;

    make_ordered_inserter(ss1)(3, 1)(4, 2).commit();
    make_ordered_inserter(ss2)(4, 2)(5, 3).commit();

    dense_series<int> ss3 = ss1 + ss2;
    BOOST_CHECK_EQUAL(3, std::distance(seq::begin(ss3), seq::end(ss3)));
    BOOST_CHECK_EQUAL(3, seq::elements(ss3)(*seq::begin(ss3)));
    BOOST_CHECK_EQUAL(1, rrs::offset(rrs::runs(ss3)(*seq::begin(ss3))));
    BOOST_CHECK_EQUAL(8, seq::elements(ss3)(*++seq::begin(ss3)));
    BOOST_CHECK_EQUAL(2, rrs::offset(rrs::runs(ss3)(*++seq::begin(ss3))));
    BOOST_CHECK_EQUAL(5, seq::elements(ss3)(*++++seq::begin(ss3)));
    BOOST_CHECK_EQUAL(3, rrs::offset(rrs::runs(ss3)(*++++seq::begin(ss3))));
}

///////////////////////////////////////////////////////////////////////////////
// test_random_access
//
void test_random_access()
{
    dense_series<int> s(start = -1, stop = 3);
    dense_series<int> const &cs = s;

    typedef rrs::unit_run<std::ptrdiff_t> run_type;
    rrs::set_at(s, run_type(-1), 1);

    BOOST_CHECK_EQUAL(4, std::distance(seq::begin(s), seq::end(s)));
    BOOST_CHECK_EQUAL(1, cs[-1]);
    BOOST_CHECK_EQUAL(0, cs[0]);
}

///////////////////////////////////////////////////////////////////////////////
// test_get_raw_buffer
//
void test_get_raw_buffer()
{
    dense_series<int> d(0, 20, 5);
    std::pair<int *, std::size_t> buff = get_raw_buffer(d);
    BOOST_CHECK_EQUAL(20u, buff.second);

    dense_series<int> const &cd = d;
    std::pair<int const *, std::size_t> cbuff = get_raw_buffer(cd);
    BOOST_CHECK_EQUAL(20u, cbuff.second);
}

///////////////////////////////////////////////////////////////////////////////
// init_unit_test_suite
//
test_suite* init_unit_test_suite( int argc, char* argv[] )
{
    test_suite *test = BOOST_TEST_SUITE("dense series test");

    test->add(BOOST_TEST_CASE(&test_dense_series));
    test->add(BOOST_TEST_CASE(&test_random_access));
    test->add(BOOST_TEST_CASE(&test_get_raw_buffer));

    return test;
}


text:
//
// Copyright yutopp 2015 - .
//
// 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)
//
#pragma once

#include <random>
#include <string>
#include <cstdlib>
#include <vector>
#include <memory>
#include <tuple>

#include <boost/regex.hpp>
#include <boost/range/adaptor/indexed.hpp>
#include <boost/algorithm/string/case_conv.hpp>

#include <unistd.h>
#include <sys/types.h>

namespace awaho
{
    namespace adap = boost::adaptors;

    auto make_random_name()
        -> std::string
    {
        static char const BaseChars[] = "abcdefghijklmnopqrstuvwxyz1234567890";

        auto gen = std::mt19937( std::random_device{}() );
        auto dist = std::uniform_int_distribution<int>{
            0,
            sizeof(BaseChars) / sizeof(char) - 1 /*term*/ -1 /*closed-interval*/
        };

        constexpr auto MaxNameLength = 10;    //28;
        char random_chars[MaxNameLength+1] = {};
        for( int i=0; i<MaxNameLength; ++i ) {
            auto const index = dist(gen);
            random_chars[i] = BaseChars[index];
        }

        return std::string("_") + random_chars;
    }

    void expect_cap()
    {
        if ( ::geteuid() != 0 ) {
            throw std::runtime_error( "you must run this program as root" );
        }
    }

    template<typename V>
    auto make_buffer_for_execve(
        V const& data_set
        )
        -> std::tuple<std::vector<char*>, std::shared_ptr<char>>
    {
        std::vector<char*> ptr_list(
            data_set.size() + 1,
            nullptr
            ); // +1 is for termination

        auto const cont_buf_len =
            std::accumulate( data_set.cbegin(), data_set.cend(),
                             std::size_t(0),
                             []( std::size_t const& len, std::string const& r ) {
                                 return len + ( r.size() + 1 );     // length + EOF
                             });

        // 0 filled continuous buffer
        std::shared_ptr<char> argv_buf(
            new char[cont_buf_len]{},
            std::default_delete<char[]>()
            );

        std::size_t argv_cur_len = 0;
        for( auto&& im : data_set | adap::indexed( 0 ) ) {
            // current ptr in continuous buffer
            char* const cur_ptr = argv_buf.get() + argv_cur_len;

            std::copy( im.value().cbegin(), im.value().cend(), cur_ptr );

            ptr_list[im.index()] = cur_ptr;

            argv_cur_len += im.value().size() + 1;  // +1 is EOF
        }
        assert( argv_cur_len == cont_buf_len );
        assert( ptr_list[data_set.size()] == nullptr );

        return std::make_tuple( std::move( ptr_list ), argv_buf );
    }

    template<typename Envs>
    auto overwrite_path( Envs const& envs )
        -> void
    {
        // First reset PATH
        if ( ::unsetenv( "PATH" ) == -1 ) {
            throw std::runtime_error( "Failed to unset PATH" );
        }
        if ( ::setenv( "PATH", "", 1 ) == -1 ) {
            throw std::runtime_error( "Failed to reset PATH" );
        }

        boost::regex const re("^(.*?)=(.*)$");
        for( auto const& env : envs ) {
            boost::smatch sm;
            boost::regex_search( env, sm, re );

            // If 'PATH' is specified, set this as new PATH variable
            if ( sm.size() == 3 ) {
                if ( boost::to_upper_copy<std::string>( sm[1] ) == "PATH" ) {
                    std::string const value = sm[2];

                    if ( ::setenv( "PATH", value.c_str(), 1 ) == -1 ) {
                        throw std::runtime_error( "Failed to set PATH" );
                    }
                }
            }
        }
    }

} // namespace awaho

max_stars_repo_name: yutopp/awaho

max_issues_repo_name: yutopp/awaho

max_forks_repo_name: yutopp/awaho


text:
/*
**  Copyright (C) 2017 SoftBank Robotics
**  See COPYING for the license
*/

#include <qi/detail/print.hpp>
#include <qi/iocolor.hpp>
#include <qi/numeric.hpp>
#include <qi/type/metaobject.hpp>
#include <qi/type/metamethod.hpp>
#include <qi/type/detail/structtypeinterface.hxx>
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/range/algorithm/max_element.hpp>
#include <iomanip>
#include <limits>

namespace
{
  /// (MetaMethod || MetaSignal || MetaProperty) M
  template <typename M>
  struct MustDisplay
  {
    bool operator()(const std::pair<unsigned int, M>& m) const
    {
      return displayHidden || !qi::MetaObject::isPrivateMember(m.second.name(), m.second.uid());
    }

    bool displayHidden;
  };

  /// std::pair<_, MetaMethod || MetaSignal || MetaProperty> MP
  template <typename MP>
  int memberNameSize(const MP& member)
  {
    return qi::numericConvertBound<int>(member.second.name().size());
  }
}

namespace qi
{
namespace detail
{
  using boost::optional;

  const boost::string_ref PrettyPrintStream::infoLabel = "Info";
  const boost::string_ref PrettyPrintStream::methodsLabel = "Methods";
  const boost::string_ref PrettyPrintStream::signalsLabel = "Signals";
  const boost::string_ref PrettyPrintStream::propertiesLabel = "Properties";
  const boost::string_ref PrettyPrintStream::membersLabel = "members";
  const boost::string_ref PrettyPrintStream::returnTypeLabel = "return type";
  const boost::string_ref PrettyPrintStream::returnDescrLabel = "returns";
  const boost::string_ref PrettyPrintStream::elementTypeLabel = "element type";
  const boost::string_ref PrettyPrintStream::keyTypeLabel = "key type";
  const boost::string_ref PrettyPrintStream::parametersLabel = "parameters";
  const boost::string_ref PrettyPrintStream::signalTypesLabel = "signal type(s)";
  const int PrettyPrintStream::indentFactor(2);
  const int PrettyPrintStream::maxOffset(30);
  const int PrettyPrintStream::idColumnWidth(3);

  PrettyPrintStream::PrettyPrintStream(std::ostream& stream,
                                       DisplayHiddenMembers displayHidden,
                                       Options flags,
                                       int indentLevel)
    : _stream(&stream)
    , _displayHidden(displayHidden)
    , _options(flags)
    , _indentLevel(indentLevel)
  {}

  PrettyPrintStream::IndentLevelPtr PrettyPrintStream::makeIndentLevel()
  {
    return IndentLevelPtr(new IndentLevel(*this));
  }

  void PrettyPrintStream::print(const Line& line)
  {
    auto& stream = *_stream;

    if (line.opts.test(Line::Option::Indent))
    {
      stream << std::string(static_cast<std::string::size_type>(indentWidth()), ' ');
    }

    if (!line.columns.empty())
    {
      auto it = begin(line.columns);
      print(*it++);

      for (; it != end(line.columns); ++it)
      {
        const auto& column = *it;
        if (column.opts.test(Column::Option::DelimitWithSpace))
        {
          stream << ' ';
        }
        print(column);
      }
    }

    if (line.opts.test(Line::Option::NewLine))
    {
      stream << '\n';
    }
    else
    {
      stream << ' '; // print a blank instead
    }
  }

  PrettyPrintStream::Line PrettyPrintStream::makeSectionHeader(const Line& line)
  {
    Line header {{}, line.opts};
    if (line.columns.empty())
    {
      return header;
    }

    header.columns.reserve(line.columns.size() + 2);

    auto columnsIt = begin(line.columns);
    const auto count = [&] {
      const auto n = line.columns.size();
      return n > 0u ? n - 1u : 0u;
    }();

    std::copy_n(columnsIt, count, std::back_inserter(header.columns));
    std::advance(columnsIt, count);

    auto lastColumn = *columnsIt;
    lastColumn.opts.reset(Column::Option::DelimitWithSpace);
    header.columns.push_back(Column("["));
    header.columns.push_back(lastColumn);
    header.columns.push_back(Column("]", StreamColor_None, Column::Alignment::Left, Column::Options{/* no space */}));
    return header;
  }

  PrettyPrintStream::Line PrettyPrintStream::makeSubSectionHeader(const Line& line)
  {
    Line header {{}, line.opts};
    header.columns.reserve(line.columns.size() + 1);
    header.columns.push_back(Column( "*", StreamColor_Green ));
    header.columns.insert(header.columns.end(), begin(line.columns), end(line.columns));
    return header;
  }

  /// Linearizable<std::pair<_, MetaMethod || MetaSignal || MetaProperty>> L
  template <typename L>
  void PrettyPrintStream::printMetaObjectMembers(const L& members, string_ref headerLabel)
  {
    using V = typename L::value_type;
    using boost::range::max_element;
    using boost::algorithm::join;

    if (!boost::empty(members))
    {
      print(makeSubSectionHeader(Line{ Column(headerLabel.to_string(), StreamColor_Fuchsia) }));
      IndentLevelPtr membersIndentLevel = makeIndentLevel();

      const auto cmpMemberNameSize = [](const V& lhs, const V& rhs) {
        return memberNameSize(lhs) < memberNameSize(rhs);
      };
      const auto maxMemberIt = max_element(members, cmpMemberNameSize);
      const auto offset = std::min(memberNameSize(*maxMemberIt), maxOffset);

      for (const auto& member: members)
      {
        print(member.second, offset, RecurseOption::DoNotRecurse);
      }
    }
  }

  void PrettyPrintStream::print(const MetaObject& mobj)
  {
    const bool displayHidden = (_displayHidden == DisplayHiddenMembers::Display);

    using boost::adaptors::filtered;

    {
      const auto unfilteredMethods = mobj.methodMap();
      const auto methods = unfilteredMethods | filtered(MustDisplay<MetaMethod>{displayHidden});
      printMetaObjectMembers(methods, methodsLabel);
    }

    {
      const auto unfilteredSignals = mobj.signalMap();
      const auto signals = unfilteredSignals | filtered(MustDisplay<MetaSignal>{displayHidden});
      printMetaObjectMembers(signals, signalsLabel);
    }

    {
      const auto unfilteredProps = mobj.propertyMap();
      const auto props = unfilteredProps | filtered(MustDisplay<MetaProperty>{displayHidden});
      printMetaObjectMembers(props, propertiesLabel);
    }
  }

  void PrettyPrintStream::print(const MetaMethod& method, int offsetLabel, RecurseOption recurse)
  {
    const bool showDoc = _options.test(Option::Documentation);

    // method info
    print(Line{ Column(method.uid(), StreamColor_Blue, Column::Alignment::Right, {}, idColumnWidth, '0'),
                Column(method.name(), StreamColor_None, Column::Alignment::Left,
                       Column::Options{ Column::Option::DelimitWithSpace }, offsetLabel),
                Column(stringify(method.returnSignature()), StreamColor_Blue),
                Column(stringify(method.parametersSignature()), StreamColor_Yellow) });
    if (showDoc && !method.description().empty())
    {
      print(Line { Column(method.description(), StreamColor_DarkGreen) });
    }

    // return type
    if (showDoc && !method.returnDescription().empty())
    {
      print(Line{ Column(returnDescrLabel.to_string(), StreamColor_Brown),
                  Column(method.returnDescription(), StreamColor_DarkGreen) });
    }
    if (recurse == RecurseOption::Recurse)
    {
      const auto typeInterface = TypeInterface::fromSignature(method.returnSignature());
      print(typeInterface, [](const std::string& typeName) -> optional<Line> {
        return Line({ Column(returnTypeLabel.to_string(), StreamColor_Teal),
                      Column(typeName, StreamColor_Yellow) });
      });
    }

    // parameters
    const auto parameters = method.parameters();
    printParameters(method.parametersSignature().children(), parametersLabel.to_string(), recurse,
                    [&](int index) -> optional<Line> {
                      if (!showDoc || index >= static_cast<int>(parameters.size()))
                      {
                        return {};
                      }
                      const auto& param = parameters[static_cast<std::size_t>(index)];
                      return Line{ { Column(param.name(), StreamColor_Brown),
                                     Column(param.description(), StreamColor_DarkGreen) } };
                    });
  }

  void PrettyPrintStream::print(const MetaSignal& signal, int offsetLabel, RecurseOption recurse)
  {
    print(Line{ Column(signal.uid(), StreamColor_Blue, Column::Alignment::Right, {}, idColumnWidth, '0'),
                Column(signal.name(), StreamColor_None, Column::Alignment::Left,
                       Column::Options{ Column::Option::DelimitWithSpace }, offsetLabel),
                Column(stringify(signal.parametersSignature()), StreamColor_Yellow) });

    printParameters(signal.parametersSignature().children(), signalTypesLabel.to_string(), recurse);
  }

  void PrettyPrintStream::print(const MetaProperty& property, int offsetLabel, RecurseOption recurse)
  {
    print(Line{ Column(property.uid(), StreamColor_Blue, Column::Alignment::Right, {}, idColumnWidth, '0'),
                Column(property.name(), StreamColor_None, Column::Alignment::Left,
                       Column::Options{ Column::Option::DelimitWithSpace }, offsetLabel),
                Column(stringify(property.signature()), StreamColor_Yellow) });

    if (recurse == RecurseOption::Recurse)
    {
      const auto type = TypeInterface::fromSignature(property.signature());
      print(type, [](const std::string&) -> optional<Line> { return {}; }); // no header
    }
  }

  void PrettyPrintStream::print(TypeInterface* type)
  {
    print(type, [](const std::string& name) -> optional<Line> {
      return Line { Column(name, StreamColor_Yellow) };
    });
  }

  /// Procedure<optional<Line> (std::string)> Proc
  template <typename Proc>
  void PrettyPrintStream::print(TypeInterface* type, Proc makeHeaderLine)
  {
    const std::string typeName = type ? stringify(type->signature()) : "unknown";
    const auto line = makeHeaderLine(typeName);
    if (line)
    {
      print(*line);
    }

    if (type)
    {
      auto typeIndentLevel = makeIndentLevel();
      printDetails(*type);
    }
  }

  void PrettyPrintStream::printDetails(TypeInterface& type)
  {
    switch (type.kind())
    {
      case TypeKind_Tuple:
        print(static_cast<StructTypeInterface&>(type));
        break;
      case TypeKind_List:
        print(static_cast<ListTypeInterface&>(type));
        break;
      case TypeKind_Map:
        print(static_cast<MapTypeInterface&>(type));
        break;
      default:
        // no details to print for all other types
        break;
    }
  }

  void PrettyPrintStream::print(StructTypeInterface& structType)
  {
    using boost::range::max_element;

    const auto memberTypes = structType.memberTypes();
    const auto elementNames = structType.elementsName();
    const auto cmpStringSize = [](const std::string& lhs, const std::string& rhs) {
        return lhs.size() < rhs.size();
    };

    const auto offset = [&] {
      if (elementNames.empty())
        return 0;
      const auto maxElemIt = max_element(elementNames, cmpStringSize);
      return std::min(numericConvertBound<int>(maxElemIt->size()), maxOffset);
    }();

    if (!memberTypes.empty())
    {
      print(Line{ { Column(membersLabel.to_string(), StreamColor_Teal) } });
    }

    IndentLevelPtr membersLevelIndent = makeIndentLevel();
    for (std::size_t memberIndex = 0; memberIndex < memberTypes.size(); ++memberIndex)
    {
      const auto elementName = (memberIndex < elementNames.size() ?
                                    elementNames[memberIndex] :
                                    os::to_string(memberIndex));
      const auto memberType = memberTypes.at(memberIndex);
      print(Line{ { Column(elementName, StreamColor_None, Column::Alignment::Left, {}, offset),
                    Column(stringify(memberType->signature()), StreamColor_Yellow) } });
    }
  }

  void PrettyPrintStream::print(ListTypeInterface& listType)
  {
    TypeInterface* const elementType = listType.elementType();
    print(elementType, [](const std::string& typeName) -> optional<Line> {
      return Line{ { Column(elementTypeLabel.to_string(), StreamColor_Teal), Column(typeName, StreamColor_Yellow) } };
    });
  }

  void PrettyPrintStream::print(MapTypeInterface& mapType)
  {
    using boost::range::max_element;

    const auto cmpStringSize = [](string_ref lhs, string_ref rhs) {
        return lhs.size() < rhs.size();
    };

    const std::vector<string_ref> labels {keyTypeLabel, elementTypeLabel};
    const auto maxLabelIt = max_element(labels, cmpStringSize);
    const auto offset = std::min(numericConvertBound<int>(maxLabelIt->size()), maxOffset);

    TypeInterface* const keyType = mapType.keyType();
    print(keyType, [&](const std::string& typeName) -> optional<Line> {
      return Line{ Column(labels.at(0).to_string(), StreamColor_Teal, Column::Alignment::Left, {}, offset),
                   Column(typeName, StreamColor_Yellow) };
    });

    TypeInterface* const elementType = mapType.elementType();
    print(elementType, [&](const std::string& typeName) -> optional<Line> {
      return Line{ Column(labels.at(1).to_string(), StreamColor_Teal, Column::Alignment::Left, {}, offset),
                   Column(typeName, StreamColor_Yellow) };
    });
  }

  void PrettyPrintStream::increaseIndent()
  {
    const auto maxIndentLevel = std::numeric_limits<decltype(_indentLevel)>::max();
    if (_indentLevel == maxIndentLevel) {
      return;
    }
    ++_indentLevel;
  }

  void PrettyPrintStream::decreaseIndent()
  {
    if (_indentLevel == 0) {
      return;
    }
    --_indentLevel;
  }

  StreamColor PrettyPrintStream::colorIfEnabled(StreamColor color) const
  {
    return qi::enabledColor(color, _options.test(Option::Colorized));
  }

  std::string PrettyPrintStream::stringify(const Signature& signature) const
  {
    return _options.test(Option::RawSignatures) ? signature.toString() : signature.toPrettySignature();
  }

  void PrettyPrintStream::print(const Column& column) const
  {
    auto& stream = *_stream;

    stream << colorIfEnabled(column.color);
    switch (column.alignment)
    {
      case Column::Alignment::Left:
        stream << std::left;
        break;
      case Column::Alignment::Right:
        stream << std::right;
        break;
      case Column::Alignment::Internal:
        stream << std::internal;
        break;
      default:
        throw std::runtime_error("unknown column alignement value");
    }
    stream << std::setfill(column.fillChar) << std::setw(column.width) << column.value;

    // reset default config
    stream << std::left << std::setfill(' ') << std::setw(0) << colorIfEnabled(StreamColor_Reset);
  }

  void PrettyPrintStream::printParameters(const std::vector<Signature>& signatures,
                                            const std::string& label,
                                            RecurseOption recurse)
  {
    printParameters(signatures, label, recurse, [](int) -> boost::optional<Line> { return {}; });
  }

  /// Procedure<optional<Line> (int)> Proc
  template <typename Proc>
  void PrettyPrintStream::printParameters(const std::vector<Signature>& signatures,
                                            const std::string& label,
                                            RecurseOption recurse,
                                            Proc makeExtraLine)
  {
    if (signatures.empty())
    {
      return;
    }

    IndentLevelPtr paramsIndentLevel;
    if (recurse == RecurseOption::Recurse)
    {
      print(Line{ Column(std::move(label), StreamColor_Teal) });
      paramsIndentLevel = makeIndentLevel();
    }

    for (std::size_t index = 0; index < signatures.size(); ++index)
    {
      const auto& param = signatures[index];
      const auto type = TypeInterface::fromSignature(param);

      if (recurse == RecurseOption::Recurse)
      {
        print(type, [&](const std::string& typeName) -> optional<Line> {
          return Line{ { Column(os::to_string(index + 1) + ":", StreamColor_Red),
                         Column(typeName, StreamColor_Yellow) } };
        });
      }

      const auto line = makeExtraLine(numericConvertBound<int>(index));
      if (line)
      {
        print(*line);
      }
    }
  }

  PrettyPrintStream::IndentLevel::IndentLevel(PrettyPrintStream& printer)
    : _printer(printer)
  {
    _printer.increaseIndent();
  }

  PrettyPrintStream::IndentLevel::~IndentLevel()
  {
    _printer.decreaseIndent();
  }

  PrettyPrintStream::Column::Column(PrettyPrintStream::Column::ValueType value,
                                      StreamColor color,
                                      Alignment alignment, Options opts,
                                      int width,
                                      char fillChar)
    : value(value)
    , color(color)
    , alignment(alignment)
    , opts(opts)
    , width(width)
    , fillChar(fillChar)
  {}

  PrettyPrintStream::Line::Line(const std::initializer_list<PrettyPrintStream::Column>& columns)
    : columns(columns)
    , opts({Option::NewLine, Option::Indent})
  {}

  PrettyPrintStream::Line::Line(const Columns& columns, Options opts)
    : columns(columns)
    , opts(opts)
  {}

  ParseablePrintStream::ParseablePrintStream(std::ostream& stream, DisplayHiddenMembers displayHidden)
    : _stream(&stream)
    , _displayHidden(displayHidden)
  {
  }

  void ParseablePrintStream::print(const MetaObject& mobj)
  {
    const auto displayHidden = (_displayHidden == DisplayHiddenMembers::Display);

    using boost::adaptors::filtered;

    {
      const auto unfilteredMethods = mobj.methodMap();
      const auto methods = unfilteredMethods | filtered(MustDisplay<MetaMethod>{ displayHidden });
      printMetaObjectMembers(methods);
    }

    {
      const auto unfilteredSignals = mobj.signalMap();
      const auto signals = unfilteredSignals | filtered(MustDisplay<MetaSignal>{ displayHidden });
      printMetaObjectMembers(signals);
    }

    {
      const auto unfilteredProps = mobj.propertyMap();
      const auto props = unfilteredProps | filtered(MustDisplay<MetaProperty>{ displayHidden });
      printMetaObjectMembers(props);
    }
  }

  /// Linearizable<std::pair<_, MetaMethod || MetaSignal || MetaProperty>> L
  template <typename L>
  void ParseablePrintStream::printMetaObjectMembers(const L& members)
  {
    using V = typename L::value_type;
    using boost::adaptors::transformed;
    using boost::algorithm::join;

    *_stream << ":" << join(members | transformed([](const V& v) { return v.second.name(); }), ",");
  }
}
}

max_stars_repo_name: Maelic/libqi

max_issues_repo_name: Maelic/libqi

max_forks_repo_name: Maelic/libqi


text:
// Boost.Range library
//
//  Copyright Neil Groves 2010. Use, modification and
//  distribution is subject to 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 http://www.boost.org/libs/range/
//
#include <boost/range/algorithm_ext/copy_n.hpp>

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

#include <boost/range/iterator.hpp>
#include <algorithm>
#include <list>
#include <vector>

namespace
{
    template< class Container >
    void test_copy_n_impl()
    {
        std::vector<std::size_t> source;
        for (std::size_t i = 0; i < 10; ++i)
            source.push_back(i);

        for (std::size_t k = 0; k < 10; ++k)
        {
            std::vector<std::size_t> reference;
            for (std::size_t j = 0; j < k; ++j)
                reference.push_back(j);

            Container test;
            boost::copy_n(source, k, std::back_inserter(test));

            BOOST_CHECK_EQUAL_COLLECTIONS( reference.begin(), reference.end(),
                test.begin(), test.end() );
        }
    }

    void test_copy_n()
    {
        test_copy_n_impl< std::vector<std::size_t> >();
        test_copy_n_impl< std::list<std::size_t> >();
    }
}

boost::unit_test::test_suite*
init_unit_test_suite(int argc, char* argv[])
{
    boost::unit_test::test_suite* test
        = BOOST_TEST_SUITE( "RangeTestSuite.algorithm_ext.copy_n" );

    test->add( BOOST_TEST_CASE( &test_copy_n ) );

    return test;
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text: #include <boost/numeric/odeint/stepper/symplectic_rkn_sb3a_m4_mclachlan.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#define BOOST_TEST_MODULE
#include <boost/test/unit_test.hpp>
#include <random/random.hpp>
#include <random/alias.hpp>
#include <parallel/thread_pool.hpp>
#include <cmath>
#include <iostream>
#include <vector>

typedef double vertex_data_type;
typedef double edge_data_type;

template<typename NumType>
void uniform_speed(const size_t max_iter) {
  NumType sum(0);
  turi::timer ti;
  ti.start();
  for(size_t i = 0; i < max_iter; ++i) {
    sum += (NumType)(turi::random::uniform<NumType>(0, 10));
  }
  double slow_time = ti.current_time();
  ti.start();
  for(size_t i = 0; i < max_iter; ++i) {
    sum += (NumType)(turi::random::fast_uniform<NumType>(0, 10));
  }
  double fast_time = ti.current_time();
  std::cout << slow_time << ", " << fast_time << std::endl;
}

class thread_worker {
public:
  std::vector<int> values;
  void run() {
    namespace random = turi::random;
    for(size_t i = 0; i < values.size(); ++i) {
      values[i] = random::uniform<int>(0,3);
    }
  }
};

template<typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& values) {
  out << "{";
  for(size_t i = 0; i < values.size(); ++i) {
    out << values[i];
    if(i + 1 < values.size()) out << ", ";
  }
  return out << "}";
}

std::vector<int> operator+(const std::vector<int>& v1,
                           const std::vector<int>& v2) {
  assert(v1.size() == v2.size());
  std::vector<int> result(v1.size());
  for(size_t i = 0; i < result.size(); ++i) {
    result[i] = v1[i] + v2[i];
  }
  return result;
}

struct RandomTestSuite {
  size_t iterations;
  RandomTestSuite() : iterations(1E8) { }

  void test_nondet_generator() {
    turi::random::nondet_seed();
    turi::random::nondet_seed();
    turi::random::nondet_seed();
  }

  void test_random_number_generators() {
    std::cout << std::endl;
    std::cout << "beginning seed" << std::endl;
    namespace random = turi::random;
    turi::random::seed();
    turi::random::time_seed();
    turi::random::nondet_seed();
    turi::random::seed(12345);
    std::cout << "finished" << std::endl;

    const size_t num_iterations(20);
    std::vector<thread_worker> workers(10);
    for(size_t i = 0; i < workers.size(); ++i)
      workers[i].values.resize(num_iterations);
    turi::thread_group threads;
    for(size_t i = 0; i < workers.size(); ++i) {
      threads.launch(boost::bind(&thread_worker::run, &(workers[i])));
    }
    threads.join();
    for(size_t i = 0; i < workers.size(); ++i) {
      std::cout << workers[i].values << std::endl;
    }
    std::vector<int> sum(workers[0].values.size());
    for(size_t i = 0; i < workers.size(); ++i) {
      sum = sum + workers[i].values;
    }
    std::cout << "Result: " << sum << std::endl;
  }

  void shuffle() {
    namespace random = turi::random;
    random::nondet_seed();
    std::vector<int> numbers(100);
    for(size_t i = 0; i < numbers.size(); ++i) numbers[i] = (int)i + 1;
    for(size_t j = 0; j < 10; ++j) {
      // shuffle the numbers
      random::shuffle(numbers);
      std::cout << numbers << std::endl;
    }
  }

};

BOOST_FIXTURE_TEST_SUITE(_RandomTestSuite, RandomTestSuite)
  BOOST_AUTO_TEST_CASE(test_nondet_generator) {
    RandomTestSuite::test_nondet_generator();
  }
  BOOST_AUTO_TEST_CASE(test_random_number_generators) {
    RandomTestSuite::test_random_number_generators();
  }
BOOST_AUTO_TEST_SUITE_END()

  // void speed() {
  //   namespace random = turi::random;
  //   std::cout << "speed test run: " << std::endl;
  //   const size_t MAX_ITER(10000);
  //   std::cout << "size_t:   ";
  //   uniform_speed<size_t>(MAX_ITER);
  //   std::cout << "int:      ";
  //   uniform_speed<int>(MAX_ITER);
  //   std::cout << "uint32_t: ";
  //   uniform_speed<uint32_t>(MAX_ITER);
  //   std::cout << "uint16_t: ";
  //   uniform_speed<uint16_t>(MAX_ITER);
  //   std::cout << "char:     ";
  //   uniform_speed<char>(MAX_ITER);
  //   std::cout << "float:    ";
  //   uniform_speed<float>(MAX_ITER);
  //   std::cout << "double:   ";
  //   uniform_speed<double>(MAX_ITER);

  //   std::cout << "gaussian: ";
  //   double sum = 0;
  //   turi::timer time;
  //   time.start();
  //   for(size_t i = 0; i < MAX_ITER; ++i)
  //     sum += random::gaussian();
  //   std::cout << time.current_time() << std::endl;

  //   std::cout << "shuffle:  ";
  //   std::vector<int> numbers(6);
  //   for(size_t i = 0; i < numbers.size(); ++i) numbers[i] = (int)i + 1;
  //   time.start();
  //   for(size_t j = 0; j < MAX_ITER/numbers.size(); ++j) {
  //     // shuffle the numbers
  //     random::shuffle(numbers);
  //   }
  //   std::cout << time.current_time() << ", ";
  //   time.start();
  //   for(size_t j = 0; j < MAX_ITER/numbers.size(); ++j) {
  //     // shuffle the numbers
  //     std::random_shuffle(numbers.begin(), numbers.end());
  //   }
  //   std::cout << time.current_time() << std::endl;
  // }

max_forks_repo_name: ZeroInfinite/turicreate


text:
/*
 * MysqlPersistence.cpp
 *
 *  Created on: 2013-9-11
 *      Author: chenfeng
 */

#include "NetdPersistenceServiceMysql.h"
#include "common/src/my_log.h"
#include <string>
#include <boost/lexical_cast.hpp>

NetdPersistenceServiceMysql::NetdPersistenceServiceMysql(const std::string& db_name) :
		PersistenceServiceMysql(db_name)
{
}

NetdPersistenceServiceMysql::~NetdPersistenceServiceMysql() {
    // TODO Auto-generated destructor stub
}

void NetdPersistenceServiceMysql::clean_db() {
    // TODO Auto-generated destructor stub
}
std::string NetdPersistenceServiceMysql::getKey(const std::string& uid)
{
	return "62c6e8ee0c06df7d";
}

max_stars_repo_name: caiqingfeng/libmrock

max_issues_repo_name: caiqingfeng/libmrock

max_forks_repo_name: caiqingfeng/libmrock


text:
/** @file
 *
 * @brief Common base class for yaml_oarchive and yaml_woarchive.
 *
 * @author    Raoul Wols
 *
 * @date      2017
 *
 * @copyright See LICENSE.md
 *
 */

#ifndef BOOST_ARCHIVE_BASIC_YAML_OARCHIVE_HPP
#define BOOST_ARCHIVE_BASIC_YAML_OARCHIVE_HPP

// MS compatible compilers support #pragma once
#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/archive/detail/common_oarchive.hpp>
#include <boost/archive/detail/yaml_decl.hpp>
#include <boost/config.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/serialization/collection_size_type.hpp>
#include <boost/serialization/item_version_type.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/string.hpp>

#include <boost/archive/detail/abi_prefix.hpp> // must be the last header

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

namespace boost {
namespace archive {

namespace detail {
template <class Archive> class interface_oarchive;
} // namespace detail

/**
 * @brief      Write serialized objects to a YAML output stream.
 *
 * @warning    **Everything** that you want to stream to the archive must be
 *             wrapped inside boost::serialization::make_nvp or the
 *             BOOST_SERIALIZATION_NVP macro. Include the file
 *             boost/serialization/nvp.hpp for that.
 *
 * @tparam     Archive  The derived archive class
 */
template <class Archive>
class BOOST_SYMBOL_VISIBLE basic_yaml_oarchive
    : public detail::common_oarchive<Archive>
{
    // special stuff for yaml output
    unsigned int depth;
    const char*  m_pending_class_name = nullptr;
#ifdef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
  public:
#else
  protected:
    friend class detail::interface_oarchive<Archive>;
#endif
    YAML_AWARCHIVE_API void indent();
    YAML_AWARCHIVE_API void init();
    YAML_AWARCHIVE_API void windup();
    // helpers used below
    YAML_AWARCHIVE_API void save_start(const char* name);
    YAML_AWARCHIVE_API void save_end(const char* name);
    YAML_AWARCHIVE_API void end_preamble();

#if BOOST_VERSION > 105800

    // Anything not an attribute and not a name-value pair is an
    // error and should be trapped here.
    template <class T> void save_override(T& t)
    {
        // If your program fails to compile here, its most likely due to
        // not specifying an nvp wrapper around the variable to
        // be serialized.
        BOOST_MPL_ASSERT((serialization::is_wrapper<T>));
        this->detail_common_oarchive::save_override(t);
    }

    // special treatment for name-value pairs.
    typedef detail::common_oarchive<Archive> detail_common_oarchive;
    template <class T> void save_override(const serialization::nvp<T>& t)
    {
        this->This()->save_start(t.name());
        this->detail_common_oarchive::save_override(t.const_value());
        this->This()->save_end(t.name());
    }

    // specific overrides for attributes - not name value pairs so we
    // want to trap them before the above "fall through"
    YAML_AWARCHIVE_API void save_override(const class_id_type& t);
    YAML_AWARCHIVE_API void save_override(const class_id_optional_type& t);
    YAML_AWARCHIVE_API void save_override(const class_id_reference_type& t);
    YAML_AWARCHIVE_API void save_override(const object_id_type& t);
    YAML_AWARCHIVE_API void save_override(const object_reference_type& t);
    YAML_AWARCHIVE_API void save_override(const version_type& t);
    YAML_AWARCHIVE_API void save_override(const class_name_type& t);
    YAML_AWARCHIVE_API void save_override(const tracking_type& t);

#else // BOOST_VERSION <= 105800

#ifdef _MSC_VER
#pragma message("Boost version is " BOOST_LIB_VERSION ". Consider upgrading!")
#endif

    // These overloads are required for versions of boost <= 1.58.

    template <class T> void save_override(T& t, BOOST_PFTO int)
    {
        // If your program fails to compile here, its most likely due to
        // not specifying an nvp wrapper around the variable to
        // be serialized.
        BOOST_MPL_ASSERT((serialization::is_wrapper<T>));
        this->detail_common_oarchive::save_override(t, 0);
    }

    typedef detail::common_oarchive<Archive> detail_common_oarchive;
    template <class T> void save_override(const serialization::nvp<T>& t, int)
    {
        this->This()->save_start(t.name());
        this->detail_common_oarchive::save_override(t.const_value(), 0);
        this->This()->save_end(t.name());
    }

    YAML_AWARCHIVE_API
    void save_override(const class_id_type& t, int);

    YAML_AWARCHIVE_API
    void save_override(const class_id_optional_type& t, int);

    YAML_AWARCHIVE_API
    void save_override(const class_id_reference_type& t, int);

    YAML_AWARCHIVE_API
    void save_override(const object_id_type& t, int);

    YAML_AWARCHIVE_API
    void save_override(const object_reference_type& t, int);

    YAML_AWARCHIVE_API
    void save_override(const version_type& t, int);

    YAML_AWARCHIVE_API
    void save_override(const class_name_type& t, int);

    YAML_AWARCHIVE_API
    void save_override(const tracking_type& t, int);

#endif // BOOST_VERSION

    YAML_AWARCHIVE_API basic_yaml_oarchive(unsigned int flags);
    YAML_AWARCHIVE_API ~basic_yaml_oarchive();
};

} // namespace archive
} // namespace boost

#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

#include <boost/archive/detail/abi_suffix.hpp> // pops abi_suffix.hpp pragmas

#endif // BOOST_ARCHIVE_BASIC_YAML_OARCHIVE_HPP

max_stars_repo_name: rwols/yaml-archive

max_issues_repo_name: rwols/yaml-archive

max_forks_repo_name: rwols/yaml-archive


text:
#if 0
#include <algorithm>
#include <cassert>
#include <climits>
#include <functional>
#include <iomanip>
#include <memory>
#include <random>
#include <sstream>
#include <string>
#include <utility>
#include <vector>

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/strong_components.hpp>
#include <boost/graph/random_spanning_tree.hpp>

#include "dbg.hpp"
#include "dump.hpp"
#include "eemp.hpp"
#include "partial_perm.hpp"
#include "perm_group.hpp"
#include "perm_set.hpp"
#include "util.hpp"

namespace mpsym
{

namespace internal
{

namespace eemp
{

std::vector<std::vector<unsigned>> action_component(
  std::vector<unsigned> const &alpha,
  std::vector<PartialPerm> const &generators, unsigned dom_max,
  SchreierTree &schreier_tree, OrbitGraph &orbit_graph)
{
#ifndef NDEBUG
  DBG(DEBUG) << "Computing component of action of generators:";
  for (PartialPerm const &gen : generators)
    DBG(TRACE) << gen;

  DBG(TRACE) << "on:";
  DBG(TRACE) << alpha;
#endif

  // compute domain range over all generators
  unsigned dom_min = UINT_MAX;
  for (PartialPerm const &gen : generators)
    dom_min = std::min(dom_min, gen.dom_min());

  // data structures for efficient component membership testing
  std::vector<int> elem_size_present(dom_max + 1u, 0);
  elem_size_present[alpha.size()] = true;

  struct ComponentElemId {
    ComponentElemId(unsigned id, std::size_t hash) : id(id), hash(hash) {}

    unsigned id;
    std::size_t hash;
  };

  std::vector<std::vector<ComponentElemId>> elem_ids(dom_max + 1u);

  std::size_t hash = util::container_hash(alpha.begin(), alpha.end());
  elem_ids[alpha.size()].push_back(ComponentElemId(0u, hash));

  // if beta is a component element, set 'id' to it's component index,
  // otherwise add add it to the component
  auto in_component = [&](std::vector<unsigned> const &beta, unsigned &id) {
    bool contained = true;

    std::size_t beta_hash = util::container_hash(beta.begin(), beta.end());

    auto const size_idx = beta.size();
    if (!elem_size_present[size_idx]) {
      contained = false;

    } else {
      auto it = std::find_if(
        elem_ids[size_idx].begin(), elem_ids[size_idx].end(),
        [&](ComponentElemId const &cei) { return cei.hash == beta_hash; });

      if (it == elem_ids[size_idx].end())
        contained = false;
      else
        id = it->id;
    }

    if (contained)
      return true;

    DBG(TRACE) << "Adjoining " << beta;
    elem_size_present[size_idx] = true;
    elem_ids[size_idx].push_back(ComponentElemId(id, beta_hash));

    return false;
  };

  // main loop
  std::vector<std::vector<unsigned>> component {alpha};
  decltype(schreier_tree.data) schreier_tree_data;
  decltype(orbit_graph.data) orbit_graph_data(generators.size());

  unsigned i = 0u, n = 0u;
  while (i < component.size()) {
    std::vector<unsigned> beta = component[i];
    DBG(TRACE) << "Looking at Component element " << beta
               << " (i = " << i  << ')';

    for (auto j = 0u; j < generators.size(); ++j) {
      DBG(TRACE) << "Considering generator " << generators[j];

      auto beta_prime(generators[j].image<std::vector>(beta.begin(),
                                                       beta.end()));

      unsigned id = static_cast<unsigned>(component.size());

      if (!in_component(beta_prime, id)) {
        component.push_back(beta_prime);

        ++n;

        schreier_tree_data.push_back(std::make_pair(i, j));
        DBG(TRACE) << "v_" << n + 1u << " = " << i + 1u;
        DBG(TRACE) << "w_" << n  + 1u<< " = " << j + 1u;

        orbit_graph_data[j].push_back(n);
        DBG(TRACE) << "g_" << i + 1u << "," << j + 1u << " = " << n + 1u;

      } else {
        DBG(TRACE) << beta_prime << " already processed";

        orbit_graph_data[j].push_back(id);
        DBG(TRACE) << "g_" << i + 1u << "," << j + 1u << " = " << id + 1u;
      }
    }

    ++i;
  }

  schreier_tree.data = schreier_tree_data;

#ifndef NDEBUG
  DBG(TRACE) << "Resulting action component";
  for (auto i = 0u; i < component.size(); ++i)
    DBG(TRACE) << i + 1u << ": " << component[i];
#endif

  DBG(TRACE) << "Resulting schreier tree:\n" << schreier_tree;

  orbit_graph.data = orbit_graph_data;

  DBG(TRACE) << "Resulting orbit graph:\n" << orbit_graph;

  return component;
}

std::pair<unsigned, std::vector<unsigned>> strongly_connected_components(
  OrbitGraph const &orbit_graph)
{
  boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS> g;

  for (auto i = 0u; i < orbit_graph.data[0].size(); ++i)
    boost::add_vertex(g);

  for (auto i = 0u; i < orbit_graph.data[0].size(); ++i) {
    for (auto const &row : orbit_graph.data) {
      auto j = row[i];
      if (j != i)
        boost::add_edge(i, j, g);
    }
  }

  std::vector<unsigned> component(boost::num_vertices(g));
  unsigned num = boost::strong_components(g, &component[0]);

  return std::make_pair(num, component);
}

SchreierTree scc_spanning_tree(
  unsigned i, OrbitGraph const &orbit_graph, std::vector<unsigned> const &scc)
{
  static auto re(util::random_engine());

  DBG(TRACE) << "Finding spanning tree for s.c.c rooted at node " << i + 1u
             << " in orbit graph:\n" << orbit_graph;

  // construct s.c.c. subgraph
  struct VertexProperty { unsigned i; };
  struct EdgeProperty { unsigned gen; };

  boost::adjacency_list<
    boost::vecS, boost::vecS, boost::directedS, VertexProperty, EdgeProperty> g;

  std::vector<unsigned> scc_i;
  std::vector<unsigned> vertex_map(scc.size(), 0u);

  DBG(TRACE) << "Constructing temporary subgraph";

  for (unsigned j = 0u; j < scc.size(); ++j) {
    if (scc[j] == scc[i]) {
      scc_i.push_back(j);

      unsigned v = boost::add_vertex({j}, g);
      vertex_map[j] = v + 1u;

      DBG(TRACE) << "Added vertex " << v << " (" << j + 1u << ')';
    }
  }

  assert(scc_i[0] == i && "provided representative is first node in s.c.c");

  for (unsigned source : scc_i) {
    for (unsigned row = 0; row < orbit_graph.data.size(); ++row) {
      unsigned dest = orbit_graph.data[row][source];

      unsigned source_vertex = vertex_map[source];
      unsigned dest_vertex = vertex_map[dest];

      if (dest_vertex > 0u && dest_vertex != source_vertex) {
        boost::add_edge(dest_vertex - 1u, source_vertex - 1u, {row}, g);

        DBG(TRACE) << "Added edge "
                   << source_vertex - 1u << " => " << dest_vertex - 1u
                   << " (" << source + 1u << " => " << dest + 1u
                   << " (" << row + 1u << "))";
      }
    }
  }

  // find random spanning tree
  SchreierTree spanning_tree;

  std::vector<unsigned> pred(boost::num_vertices(g));

  DBG(TRACE) << "Finding random spanning tree...";

  boost::random_spanning_tree(
    g, re, boost::root_vertex(vertex_map[i] - 1u).predecessor_map(&pred[0]));

  DBG(TRACE) << "Found spanning tree with predecessor relationships: "
             << std::vector<unsigned>(pred.begin() + 1, pred.end());

  // convert into Schreier tree format
  spanning_tree.data =
    std::vector<std::pair<unsigned, unsigned>>(scc.size() - 1u);

  for (auto j = 1u; j < pred.size(); ++j) {
    auto child(boost::vertex(j, g));
    auto parent(boost::vertex(pred[j], g));
    auto edge(boost::edge(child, parent, g));

    assert(edge.second && "edge exists");

    spanning_tree.data[g[child].i - 1u] =
      std::make_pair(g[parent].i, g[edge.first].gen);
  }

  DBG(TRACE) << "Resulting spanning Schreier tree is:\n" << spanning_tree;

  return spanning_tree;
}

PartialPerm schreier_trace(
  unsigned x, SchreierTree const &schreier_tree,
  std::vector<PartialPerm> const &generators, unsigned dom_max, unsigned target)
{
  PartialPerm res(dom_max);

  while (x != target) {
    unsigned v = std::get<0>(schreier_tree.data[x - 1u]);
    unsigned w = std::get<1>(schreier_tree.data[x - 1u]);

    res = generators[w] * res;
    x = v;
  }

  return res;
}

PermGroup schreier_generators(unsigned i,
  std::vector<PartialPerm> const &generators, unsigned dom_max,
  std::vector<std::vector<unsigned>> const &action_component,
  SchreierTree const &schreier_tree, OrbitGraph const &orbit_graph,
  std::vector<unsigned> const &sccs)
{
  auto im(action_component[i]);

  DBG(TRACE) << "Finding schreier generators for Sx for: " << im;

  if (im.empty()) {
    DBG(TRACE) << "=> Returning empty permutation group";
    return PermGroup();
  }

  unsigned im_max = im.back();

  std::vector<unsigned> scc;
  for (unsigned j = 0u; j < sccs.size(); ++j) {
    if (sccs[j] == sccs[i])
      scc.push_back(j);
  }

#ifndef NDEBUG
  std::vector<std::vector<unsigned>> _scc(scc.size());
  for (auto j = 0u; j < scc.size(); ++j)
    _scc[j] = action_component[scc[j]];

  DBG(TRACE) << "Strongly connected component of x is: " << _scc;
#endif

  PermSet sg_gens;

  for (auto j = 0u; j < scc.size(); ++j) {
    for (auto k = 0u; k < generators.size(); ++k) {

      unsigned l = orbit_graph.data[k][scc[j]];
      if (sccs[l] != sccs[i])
        continue;

      DBG(TRACE) << "Found generator for j/i(j)/k/l = "
                 << j + 1u << '/'
                 << scc[j] + 1u << '/'
                 << k + 1u << '/'
                 << l + 1u;

      PartialPerm ui(schreier_trace(
        scc[j], schreier_tree, generators, dom_max, i));
      PartialPerm ul(schreier_trace(
        l, schreier_tree, generators, dom_max, i));

      DBG(TRACE) << "where:";
      DBG(TRACE) << "u_i(j) = " << "u_" << scc[j] + 1u << " = " << ui;
      DBG(TRACE) << "x_k = " << "x_" << k + 1u << " = " << generators[k];
      DBG(TRACE) << "~u_l = " << "u_" << l + 1u << " = " << ~ul;

      PartialPerm sg(ui * generators[k] * ~ul);
      sg = sg.restricted(im.begin(), im.end());

      DBG(TRACE) << "Schreier generator is: " << sg;

      if (!sg.id())
        sg_gens.emplace(sg.to_perm(im_max));
    }
  }

  PermGroup res(im_max, sg_gens);

  DBG(TRACE) << "=> Returning:";
  DBG(TRACE) << res;

  return res;
}

std::vector<PartialPerm> r_class_representatives(
  SchreierTree const &schreier_tree, std::vector<PartialPerm> const &generators)
{
  std::vector<std::vector<unsigned>> st_adj(schreier_tree.data.size() + 1u);
  for (auto i = 0u; i < schreier_tree.data.size(); ++i)
    st_adj[std::get<0>(schreier_tree.data[i])].push_back(i + 1u);

  std::vector<PartialPerm> res;

  std::function<void(unsigned, PartialPerm const &)>
  backtrack = [&](unsigned node, PartialPerm const &pperm) {
    res.push_back(pperm);

    for (unsigned child : st_adj[node]) {
      unsigned gen_idx = schreier_tree.data[child - 1u].second;
      PartialPerm next_pperm(pperm * generators[gen_idx]);

      backtrack(child, next_pperm);
    }
  };

  backtrack(0, generators[0]);

  return res;
}

std::vector<std::vector<unsigned>> expand_partition(
  std::vector<unsigned> partition)
{
  auto mm = std::minmax_element(partition.begin(), partition.end());

  auto first = *mm.first;
  auto last = *mm.second;

  std::vector<std::vector<unsigned>> res(last - first + 1);
  for (unsigned x = 0u; x < partition.size(); ++x)
    res[partition[x] - first].push_back(x);

  std::sort(res.begin(), res.end(),
           [](std::vector<unsigned> const &a,
              std::vector<unsigned> const &b){ return a[0] < b[0]; });

  return res;
}

std::ostream& operator<<(
  std::ostream& stream, eemp::SchreierTree const &schreier_tree)
{
  if (schreier_tree.data.empty()) {
    stream << "empty schreier tree";
    return stream;
  }

  auto size = schreier_tree.data.size();
  auto cellwidth = std::to_string(size).length();

  stream << "i   |";
  stream << std::setw(cellwidth) << 2u;
  for (auto i = 1u; i < size; ++i)
    stream << ' ' << std::setw(cellwidth) << i + 2u;
  stream << '\n';

  stream << std::string(4u, '-');
  for (auto i = 0u; i < size; ++i)
    stream << std::string(cellwidth + 1u, '-');
  stream << '\n';

  stream << "v_i |";
  stream << std::setw(cellwidth) << std::get<0>(schreier_tree.data[0]) + 1u;
  for (auto i = 1u; i < size; ++i) {
    stream << ' ' << std::setw(cellwidth)
           << std::get<0>(schreier_tree.data[i]) + 1u;
  }
  stream << '\n';

  stream << "w_i |";
  stream << std::setw(cellwidth) << std::get<1>(schreier_tree.data[0]) + 1u;
  for (auto i = 1u; i < size; ++i) {
    stream << ' ' << std::setw(cellwidth)
           << std::get<1>(schreier_tree.data[i]) + 1u;
  }

  return stream;
}

std::ostream &operator<<(std::ostream &os, eemp::OrbitGraph const &orbit_graph)
{
  if (orbit_graph.data.empty()) {
    os << "empty orbit graph";
    return os;
  }

  auto size = orbit_graph.data[0].size();

  auto cellwidth = std::to_string(size).length();
  auto pad = std::to_string(orbit_graph.data.size()).length();

  os << "i   " << std::string(pad, ' ') << "  |";
  os << std::setw(cellwidth) << 1u;
  for (auto i = 1u; i < size; ++i)
    os << ' ' << std::setw(cellwidth) << i + 1u;
  os << '\n';

  os << std::string(6u + pad, '-');
  for (auto i = 0u; i < size; ++i)
    os << std::string(cellwidth + 1, '-');
  os << '\n';

  for (auto j = 0u; j < orbit_graph.data.size(); ++j) {
    os << "g_i," << std::setw(pad) << j + 1u << "  |";

    os << std::setw(cellwidth) << orbit_graph.data[j][0] + 1u;
    for (auto k = 1u; k < size; ++k)
      os << ' ' << std::setw(cellwidth) << orbit_graph.data[j][k] + 1u;
    os << '\n';
  }

  auto tmp(strongly_connected_components(orbit_graph));
  auto scc(expand_partition(tmp.second));

  os << "s.c.c." << std::string(pad - 1u, ' ') << " | "
     << DUMP_CUSTOM(scc, "{}", "{}");

  return os;
}

} // namespace eemp

} // namespace internal

} // namespace mpsym
#endif