text:
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//  Quantum Monte Carlo Simulation for Kitaev Models
//  written by: Tim Eschmann, June 2016
//  Modified version: February 2019
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
//  The code skeleton of this file was derived from "ising_skeleton.cpp"
//  which is part of the ALPS libraries:
//
/*****************************************************************************
 *
 * ALPS Project: Algorithms and Libraries for Physics Simulations
 *
 * ALPS Libraries
 *
 * Copyright (C) 2003 by Brigitte Surer
 *                       and Jan Gukelberger
 *
 * This software is part of the ALPS libraries, published under the ALPS
 * Library License; you can use, redistribute it and/or modify it under
 * the terms of the license, either version 1 or (at your option) any later
 * version.
 *
 * You should have received a copy of the ALPS Library License along with
 * the ALPS Libraries; see the file LICENSE.txt. If not, the license is also
 * available from http://alps.comp-phys.org/.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
 * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
 * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
/*****************************************************************************/
//  This software incorporates the Armadillo C++ Library
//  Armadillo C++ Linear Algebra Library
//  Copyright 2008-2020 Conrad Sanderson (http://conradsanderson.id.au)
//  Copyright 2008-2016 National ICT Australia (NICTA)
//  Copyright 2017-2020 Arroyo Consortium
//  Copyright 2017-2020 Data61, CSIRO

//  This product includes software developed by Conrad Sanderson (http://conradsanderson.id.au)
//  This product includes software developed at National ICT Australia (NICTA)
//  This product includes software developed at Arroyo Consortium
//  This product includes software developed at Data61, CSIRO

//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <sstream>
#include <vector>
#include <complex>
#include <cmath>
#include <armadillo>
#include <mpi.h>

#include <alps/scheduler/montecarlo.h>
#include <alps/alea.h>
#include <boost/random.hpp>
#include <boost/multi_array.hpp>
#include <boost/filesystem.hpp>

// Include functions package
#include "functions.hpp"

// Include the desired lattice (read in header file from .hpp folder)
#include "Lattices/honeycomb_8_sites.hpp"

#ifndef _temp_hpp_
#define _temp_hpp_
double calc_temp(double T_min, double T_max, int me, int np, std::string dist);
#endif

using namespace arma;

class Simulation
{
public:
    Simulation(int np, int me, double T_min, double T_max, double T, std::string dist, std::string output_file)
    // Define interaction matrix A, parameters and measurable observables:
    :   eng_(3*me) // Random generator engine (different seed for each replica)
    ,   rng_(eng_, dist_) // Random generator
    ,   np_(np) // # of processes
    ,   me_(me) // process number / parallelization rank
    ,   T_min(T_min) // minimal temperature
    ,   T_max(T_max) // maximal temperature
    ,   dist(dist) // Temperature distribution
    ,   temp_(T)  // Replica Temperature
    ,   beta_(1/T) // Inverse replica Temperature
    ,   ham() // Interaction matrix / Z2 configuration
    ,   N_() // # system sites (IMPORTANT: THIS HAS CHANGED W.R.T. FORMER VERSIONS !!!)
    ,   v_() // Vector with coordinates of nonzero matrix entries
    ,   length_() // Length of this vector
    ,   eigval() // Eigenvalues of interaction matrix
    ,   F() // Free energy
    ,   plaquettes() // matrix with elementary plaquettes
    ,   energy_("E") // Measurement data: energy
    ,   e2_("E2") // Measurement data: squared energy
    //,   e4_("E4") // Measurement data: energy^4
    ,   dE_db("dE_db") // Measurement data: dE / d(beta) = fermionic part of specific heat
    //,   p_("p") // Disorder
    ,   flux_real("Flreal") // Measurement data: average plaquet flux (real part)
    ,   flux_imag("Flimag") // "" (imaginary part)
    ,   flux_real_squared("Flreal2") // Measurement data: average plaquet flux (real part)
    ,   flux_imag_squared("Flimag2") // "" (imaginary part)
    ,   spin_corr("Spin_corr")
    ,   flip_rate() // Single flip acceptance rate
    ,   filename_(output_file) // Filename for data saving

    {

    // Locate nonzero entries of interaction matrix (.hpp file):
    v_ = non_zeros();
    length_ = v_.size();

    // Fill interaction matrix A with coefficients due to lattice symmetry (.hpp file)
    ham = randomize(def_matrix());

    N_ = size(ham)[0];

    // Vector of eigenvalues of A
    eigval = eig_sym(ham);

    F = free_en(eigval, beta_);

    plaquettes = create_plaquettes();

    // Initialize single flip acceptance to 0:
    flip_rate = 0;

    }

    // Replica Monte Carlo iteration
    void run(int n, int ntherm, int sweeps_per_swap, int sweeps_per_save)
    {
        engine_type loaded, saved; // needed to load and save random engine status
        sweeps_ = n;
        thermalization_ = ntherm; // thermalization steps

        double fr;
        int n_tot = n + ntherm;
        double tau_en, tau_fl; // autocorrelation times

        std::stringstream matrix_output; // needed for saving configurations
        matrix_output << "matrix_temp_" << 1/beta_ << ".saved";

        std::stringstream rng_save; // needed for saving random generator status
        rng_save << "rng_" << me_ << ".saved";

        //Load so-far-obtained measurement data (ALPS)
        if (boost::filesystem::exists(filename_))
        {
            load(filename_);
        }

        // Load random generator status:
        std::ifstream rngfile(rng_save.str().c_str(), std::ifstream::in);
        if(rngfile.good())
        {
            rngfile >> loaded;
            rngfile.close();
            eng_ = loaded;
        }

        // Load last Z2 configuration from file (-> skip thermalization)
        std::ifstream matfile(matrix_output.str().c_str(), std::ifstream::in);
        if(matfile.good())
            ham.load(matrix_output.str().c_str());

        // Thermalize for ntherm steps
        if (me_ == 1)
            std::cout << "Thermalizing ..." << std::endl;

        while(ntherm--)
        {
            step();

            if (ntherm % sweeps_per_swap == 0)
            {
                swap();

                if (((ntherm + n) / sweeps_per_swap) % sweeps_per_save == 0)
                {
                    // Calculate single flip acceptance rate and send it to Master process:
                    fr = double(flip_rate)/(double(n_tot - n - ntherm)*N_);
                    MPI_Send(&fr, 1, MPI_DOUBLE, 0, 5, MPI_COMM_WORLD);
                }
            }

            if (ntherm % sweeps_per_save == 0)
            {
                // Save Z2 configuration:
                ham.save(matrix_output.str().c_str());

                // Save random generator status:
                saved = eng_;
                std::ofstream file(rng_save.str().c_str(), std::ofstream::trunc);
                file << saved;

                // Tell that everything is saved ...
                if (me_ == 1)
                    std::cout << "SAVE " << ntherm << std::endl;

            }
        }

        if (me_ == 1)
        {
            std::cout << "###############################" << std::endl;
            std::cout << "Sweeping ..." << std::endl;
        }

        // Run n steps
        while(n--)
        {
            step();

            // Output eigenvalue and flux configurations:
            //outputZ2gauge();
            //output_eigenvalues();
            //output_flux_confs();

            // Measure observables:
            measure();

            // Swap:
            if (n % sweeps_per_swap == 0)
            {
                swap();

                if (((n) / sweeps_per_swap) % sweeps_per_save == 0)
                {
                    // Calculate single flip acceptance rate and send it to Master process:
                    fr = double(flip_rate)/(double(n_tot - n - ntherm)*N_);
                    MPI_Send(&fr, 1, MPI_DOUBLE, 0, 5, MPI_COMM_WORLD);
                }
            }

            // Save all simulation data:
            if (n % sweeps_per_save == 0)
            {
                // Save results:
                save(filename_);

                // Save Z2 configuration:
                ham.save(matrix_output.str().c_str());

                // Save random generator status:
                saved = eng_;
                std::ofstream file(rng_save.str().c_str(), std::ofstream::trunc);
                file << saved;

                // Tell that everything is saved ...
                if (me_ == 1)
                    std::cout << "SAVE " << n << std::endl;
            }
        }

        //Save the observables to file
        save(filename_);

        tau_en = energy_.tau();
        tau_fl = flux_real.tau();
        MPI_Send(&tau_en, 1, MPI_DOUBLE, 0, 6, MPI_COMM_WORLD);
        MPI_Send(&tau_fl, 1, MPI_DOUBLE, 0, 7, MPI_COMM_WORLD);

        // Print observables
	    /*
        std::cout << temp_ << std::endl;
	    std::cout.precision(17);
       	std::cout << energy_.name() << ":\t" << energy_.mean()
            << " +- " << energy_.error() << ";\ttau = " << energy_.tau()
            << ";\tconverged: " << alps::convergence_to_text(energy_.converged_errors())
            << std::endl;

	    std::cout << flux_real.name() << ":\t" << flux_real.mean()
            << " +- " << flux_real.error() << ";\ttau = " << flux_real.tau()
            << ";\tconverged: " << alps::convergence_to_te        //std::cout << double(counter)/double(tries) << std::endl;xt(flux_real.converged_errors())
            << std::endl;
        std::cout << flux_imag.name() << ":\t" << flux_imag.mean()
            << " +- " << flux_imag.error() << ";\ttau = " << flux_imag.tau()
            << ";\tconverged: " << alps::convergence_to_text(flux_imag.converged_errors())
            << std::endl;*/

    }

    // Iteration step (= "Metropolis sweep"):
    void step()
    {
        int kk, i, j; // Running indices
        cx_mat ham_new(N_,N_);
        vec eigval_new(N_); // Vector for eigenvalues of new matrix (= update proposal)

        double F_new; // New free energy

        int coord1, coord2; // Random bond coordinate
        double alpha, gamma; // Monte Carlo variables

        int count = 0;

        // One sweep = N tries (# lattice sites)
        for (kk = 0; kk < N_; kk++)
        {
            // Alternative matrix for sampling:
            ham_new = ham;

            // Switch sign of random matrix entry:
            int die = roll_die(length_);
            coord1 = v_[die]/(N_);
            coord2 = v_[die]%(N_);
            ham_new(coord1, coord2) *= -1;
            ham_new(coord2, coord1) *= -1;

            // Measure free energy of changed Hamiltonian:
            eigval_new = eig_sym(ham_new);
            F_new = free_en(eigval_new, beta_);

            // Accept change with probability according to Boltzmann distribution:
            //alpha = exp(- beta_ * (F_new - F));
            // Use Gibbs weights instead of Metropolis weights:
            alpha = 1./ (1. + exp(beta_ * (F_new - F)));
            gamma = rng_();

            // Accepted?
            if (gamma <= alpha) // accept
            {
                ham = ham_new;
                eigval = eigval_new;
                F = F_new;

                // Single flip acceptance rate + 1
                flip_rate += 1;
            }

            count += 1;
        }
    }

    // Does what it says ...
    void measure()
    {
        std::complex <double> fl;
        double E_, dE_, s;
        //double p;
        double fl_real;
        double fl_imag;
        double corr;

        // Measure energy etc.:
        E_ = en(eigval, beta_);
        dE_ = diffE(eigval, beta_);

        // Measure average flux per plaquet / disorder:
        fl = flux(ham, plaquettes);
        fl_real = std::real(fl);
        fl_imag = std::imag(fl);
        //p = get_p(ham, plaquettes);

        // Measure spin-spin correlation:
        corr = correlation(ham, v_, beta_);

        // Add sample to observables:
        energy_ << E_/double(N_); // Energy per site
        e2_ << E_/double(N_)*E_/double(N_); // Squared energy per site
        //e4_ << E_/double(N_)*E_/double(N_)*E_/double(N_)*E_/double(N_);
        dE_db << dE_ / double(N_); // dE/d(beta)
        //p_ << p;
        flux_real << fl_real;
        flux_imag << fl_imag;
        flux_real_squared << fl_real*fl_real;
        flux_imag_squared << fl_imag*fl_imag;
        spin_corr << corr;
    }

    ///////////////////////////////////////////////////////////////
    // Output Z2 gauge field configuration:
    ///////////////////////////////////////////////////////////////

    void outputZ2gauge()
    {
        int coord1, coord2;
        std::stringstream gauge_output; // needed for saving configurations
        gauge_output << "gauge_configuration_temp_" << 1/beta_ << ".saved";

        std::ofstream gauge(gauge_output.str().c_str(), std::ofstream::app);
        for (int j = 0; j < v_.size(); j++)
        {
            coord1 = v_[j]/N_;
            coord2 = v_[j]%N_;

            gauge << std::setprecision(17) << std::imag(ham(coord1, coord2) / std::abs(ham(coord1, coord2))) << "   ";
        }
        gauge << std::endl;
    }

    // Output flux configurations:
    void output_flux_confs()
    {
        cx_vec fl_confs = flux_confs(ham, plaquettes);

        std::stringstream flux_output; // needed for saving configurations
        flux_output << "flux_configuration_temp_" << 1/beta_ << ".saved";

        std::ofstream flux(flux_output.str().c_str(), std::ofstream::app);
        for(int iii = 0; iii < size(plaquettes)[0]; iii++)
        {
            // Switch between real and imaginary fluxes:
            flux << std::setprecision(17) << std::real(fl_confs[iii]) << "   ";
            //flux << std::setprecision(17) << std::imag(fl_confs[iii]) << std::endl;
        }
        flux << std::endl;
    }

    // Output eigenvalue configurations:
    void output_eigenvalues()
    {
        std::stringstream output; // needed for saving energies
        output << "eigenvalues_temp_" << 1/beta_ << ".saved";

        std::ofstream eig(output.str().c_str(), std::ofstream::app);
        for(int iii = 0; iii < size(eigval)[0]/2; iii++)
        {
            eig << std::setprecision(17) << eigval[iii] << "   ";
        }
        eig << std::endl;
    }

    // Swap replica with left neighbour ...
    void swapleft()
    {
        MPI_Status status;
        int control = 0;
        int jj,kk;
        double beta_alt = 1/calc_temp(T_min, T_max, me_ - 1, np_, dist);
        cx_mat H_a(N_,N_); // receive
        cx_mat H_b = ham; // send

        double f2 = -beta_alt * free_en(eigval, beta_alt);
        double f3 = beta_ * F;

        MPI_Send(&f2, 1, MPI_DOUBLE, 0, 2, MPI_COMM_WORLD);
        MPI_Send(&f3, 1, MPI_DOUBLE, 0, 2, MPI_COMM_WORLD);

        MPI_Recv(&control, 1, MPI_INT, 0, 2, MPI_COMM_WORLD, &status);

        if (control == 1)
        {
            // Receive replica from left neighbour
            for (jj = 0; jj < N_; jj++)
            {
                for (kk = 0; kk < N_; kk++)
                {
                    MPI_Recv(&H_a(jj,kk), 1, MPI_DOUBLE_COMPLEX, me_- 1, 3, MPI_COMM_WORLD, &status);
                }
            }

            // Send own replica to left neighbour
            for (jj = 0; jj < N_; jj++)
            {
                for (kk = 0; kk < N_; kk++)
                {
                    MPI_Send(&H_b(jj,kk), 1, MPI_DOUBLE_COMPLEX, me_- 1, 4, MPI_COMM_WORLD);
                }
            }

            ham = H_a;
            eigval = eig_sym(ham);
            F = free_en(eigval, beta_);
        }
    }

    // Swap replica with right neighbour ...
    void swapright()
    {
        MPI_Status status;
        int control = 0;
        int jj, kk;
        double beta_alt = 1/calc_temp(T_min, T_max, me_ + 1, np_, dist);
        cx_mat H_b(N_,N_); // receive (here it's the other way round!!!)
        cx_mat H_a = ham; // send

        double f1 = -beta_alt * free_en(eigval, beta_alt);
        double f4 = beta_ * F;

        MPI_Send(&f1, 1, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD);
        MPI_Send(&f4, 1, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD);

        MPI_Recv(&control, 1, MPI_INT, 0, 1, MPI_COMM_WORLD, &status);

        if (control == 1)
        {
            // Send own replica to right neighbour
            for (jj = 0; jj < N_; jj++)
            {
                for (kk = 0; kk < N_; kk++)
                {
                    MPI_Send(&H_a(jj,kk), 1, MPI_DOUBLE_COMPLEX, me_+ 1, 3, MPI_COMM_WORLD);
                }
            }

            // Receive replica from right neighbour
            for (jj = 0; jj < N_; jj++)
            {
                for (kk = 0; kk < N_; kk++)
                {
                    MPI_Recv(&H_b(jj,kk), 1, MPI_DOUBLE_COMPLEX, me_+ 1, 4, MPI_COMM_WORLD, &status);
                }
            }

            ham = H_b;
            eigval = eig_sym(ham);
            F = free_en(eigval, beta_);
        }

    }

    // Parallel Tempering for each temperature point (= "Swap"")
    void swap()
    {
        if (me_ != 1)
            swapleft();
        if (me_ != np_ - 1)
            swapright();
    }

    // Master process for managing swaps:
    void master(int therm, int sweeps, int sweeps_per_save, int sweeps_per_swap)
    {
        MPI_Status status;
        engine_type loaded, saved; // needed to load and save random engine status
        int counts = (therm + sweeps)/sweeps_per_swap; // How many swaps in total?
        int control = 0;  // Signal for accepting / rejecting swap
        int sign_[np_];   // needed for ensemble optimization
        int nplus_[np_];  // n+ histogram
        int nminus_[np_]; // n- histogram
        double counter[np_]; // How many accepted swaps?
        double den = 0;
        int s_i, s_i_plus_1; // sign for each replica (was it at T_min or T_max latest?)
        double f1, f2, f3, f4; // free energy variables
        double alpha_pt, gamma_pt; // Monte Carlo variables

        double fr; // Single flip acceptance rate

        // Autocorrelation times:
        double tau_en;
        double tau_fl;

        std::stringstream rng_save; // needed for saving random generator status
        rng_save << "rng_" << me_ << ".saved";

        std::stringstream sfar; // needed for saving single flip acceptance rates
        sfar << "single_flip_rate.saved";

        std::stringstream nplus_ratio; // needed for saving ratio function f = n_plus / n_tot
        nplus_ratio << "n_plus_ratio.saved";

        std::stringstream swap_ratio; // needed for saving replica exchange ratio
        swap_ratio << "swap_ratio.saved";

        std::stringstream tau_energy; // needed for saving energy autocorrelation time
        tau_energy << "tau_energy.saved";

        std::stringstream tau_flux; // needed for saving flux autocorrelation time
        tau_flux << "tau_flux.saved";

        // Load random generator status:
        std::ifstream rngfile(rng_save.str().c_str(), std::ifstream::in);
        if(rngfile.good())
        {
            rngfile >> loaded;
            rngfile.close();
            eng_ = loaded;
        }

        // Initialize sign array and histograms
        for (int k = 0; k < np_; k++)
        {
            sign_[k] = 0;
            nplus_[k] = 0;
            nminus_[k] = 0;
            counter[k] = 0;
        }

        sign_[1] = 1;
        sign_[np_ - 1] = -1;

        // PT iteration
        while(counts--)
        {
            den += 2;

            // Regard temperature points from T_min to T_max
            for (int i = 1; i < np_ - 1; i++)
            {
                // Receive free energies from replicas
                MPI_Recv(&f1, 1, MPI_DOUBLE, i, 1, MPI_COMM_WORLD, &status);
                MPI_Recv(&f4, 1, MPI_DOUBLE, i, 1, MPI_COMM_WORLD, &status);
                MPI_Recv(&f2, 1, MPI_DOUBLE, i+1, 2, MPI_COMM_WORLD, &status);
                MPI_Recv(&f3, 1, MPI_DOUBLE, i+1, 2, MPI_COMM_WORLD, &status);

                // Decide if replicas are swapped
                alpha_pt = exp(f1 + f2 + f3 + f4);
		        gamma_pt = rng_();

                if (gamma_pt <= alpha_pt) // accept
                {
                    control = 1;

                    MPI_Send(&control, 1, MPI_INT, i, 1, MPI_COMM_WORLD);
                    MPI_Send(&control, 1, MPI_INT, i+1, 2, MPI_COMM_WORLD);

                    // Record histogram for ensemble optimization:
                    s_i = check_sign_i(i, np_,  sign_[i], sign_[i+1]);
                    s_i_plus_1 = check_sign_i_plus_1(i, np_,  sign_[i], sign_[i+1]);
                    sign_[i] = s_i;
                    sign_[i+1] = s_i_plus_1;
                    if (counts < sweeps + therm - 100) // Start recording after a couple of steps ...
                    {
                        if (s_i == 1)
                            nplus_[i] += 1;
                        else if (s_i = -1)
                            nminus_[i] += 1;
                        if (s_i_plus_1 == 1)
                            nplus_[i+1] += 1;
                        else if (s_i_plus_1 == -1)
                            nminus_[i+1] += 1;
                    }

                    // Record replica exchange rate:
                    counter[i] += 1;
                    counter[i+1] += 1;

                }
                else // refuse
                {
                    //std::cout << "NO SWAP " << i << " " << i + 1 << std::endl;
                    control = 0;
                    MPI_Send(&control, 1, MPI_INT, i, 1, MPI_COMM_WORLD);
                    MPI_Send(&control, 1, MPI_INT, i+1, 2, MPI_COMM_WORLD);
                }
            }

            if (counts % sweeps_per_save == 0)
            {
                // Give single flip acceptance rates as output ...
                std::ofstream sf__(sfar.str().c_str(), std::ofstream::trunc);
                for (int jj = 1; jj < np_; jj++)
                {
                    MPI_Recv(&fr, 1, MPI_DOUBLE, jj, 5, MPI_COMM_WORLD, &status);
                    sf__ << std::setprecision(17) << calc_temp(T_min, T_max, jj, np_, dist) << " " << fr << std::endl;
                }

                // Give histogram as output ...
                std::ofstream nplus__(nplus_ratio.str().c_str(), std::ofstream::trunc);
                for (int kk = 1; kk < np_ ; kk++)
                {
                    nplus__ << std::setprecision(17) << calc_temp(T_min, T_max, kk, np_, dist) << " " << nplus_[kk] / double(nplus_[kk] + nminus_[kk]) << std::endl;
                }

                // Give swap ratio as output ...
                std::ofstream swap_ratio__(swap_ratio.str().c_str(), std::ofstream::trunc);
                for (int ll = 1; ll < np_ ; ll++)
                {
                    swap_ratio__ << std::setprecision(17) << calc_temp(T_min, T_max, ll, np_, dist) << " " << counter[ll] / den << std::endl;
                }

                // Save random generator status:
                saved = eng_;
                std::ofstream file(rng_save.str().c_str(), std::ofstream::trunc);
                file << saved;
            }
        }

        // Give autocorrelation times as output ...
        std::ofstream tau1(tau_energy.str().c_str(), std::ofstream::trunc);
        std::ofstream tau2(tau_flux.str().c_str(), std::ofstream::trunc);
        for (int ll = 1; ll < np_; ll++)
        {
            MPI_Recv(&tau_en, 1, MPI_DOUBLE, ll, 6, MPI_COMM_WORLD, &status);
            tau1 << std::setprecision(17) << calc_temp(T_min, T_max, ll, np_, dist) << " " << tau_en << std::endl;

            MPI_Recv(&tau_fl, 1, MPI_DOUBLE, ll, 7, MPI_COMM_WORLD, &status);
            tau2 << std::setprecision(17) << calc_temp(T_min, T_max, ll, np_, dist) << " " << tau_fl << std::endl;
        }
    }

    void load(std::string const & filename)
    {
        alps::hdf5::archive ar(filename, "a");
        ar["/simulation/results/"+energy_.representation()] >> energy_;
        ar["/simulation/results/"+e2_.representation()] >> e2_;
        //ar["/simulation/results/"+e4_.representation()] >> e4_;
        ar["/simulation/results/"+dE_db.representation()] >> dE_db;
        //ar["/simulation/results/"+p_.representation()] >> p_;
        ar["/simulation/results/"+flux_real.representation()] >> flux_real;
        ar["/simulation/results/"+flux_imag.representation()] >> flux_imag;
        ar["/simulation/results/"+flux_real_squared.representation()] >> flux_real_squared;
        ar["/simulation/results/"+flux_imag_squared.representation()] >> flux_imag_squared;
        ar["/simulation/results/"+spin_corr.representation()] >> spin_corr;
        ar["/parameters/T"] >> temp_;
        ar["/parameters/BETA"] >> beta_;
        ar["/parameters/SWEEPS"] >> sweeps_;
        ar["/parameters/THERMALIZATION"] >> thermalization_;
    }

    void save(std::string const & filename)
    {
        alps::hdf5::archive ar(filename, "a");
        ar["/simulation/results/"+energy_.representation()] << energy_;
        ar["/simulation/results/"+e2_.representation()] << e2_;
        //ar["/simulation/results/"+e4_.representation()] << e4_;
        ar["/simulation/results/"+dE_db.representation()] << dE_db;
        //ar["/simulation/results/"+p_.representation()] << p_;
        ar["/simulation/results/"+flux_real.representation()] << flux_real;
        ar["/simulation/results/"+flux_imag.representation()] << flux_imag;
        ar["/simulation/results/"+flux_real_squared.representation()] << flux_real_squared;
        ar["/simulation/results/"+flux_imag_squared.representation()] << flux_imag_squared;
        ar["/simulation/results/"+spin_corr.representation()] << spin_corr;
        ar["/parameters/T"] << temp_;
        ar["/parameters/BETA"] << beta_;
        ar["/parameters/SWEEPS"] << sweeps_;
        ar["/parameters/THERMALIZATION"] << thermalization_;
    }

    /////////////////////////////////////////////////////////////////////
    // Randomize zz-entries of matrix (likewise: all nonzero entries): //
    /////////////////////////////////////////////////////////////////////

    cx_mat randomize(cx_mat ham)
    {
        int N_ = size(ham)[0];
        int die, coord1, coord2;

        for (int j = 0 ; j < 3*N_/2; j++)
        {
            die = roll_die(length_);
            coord1 = v_[die]/N_;
            coord2 = v_[die]%N_;

            // Flip a coin:
            if (rng_() < 0.5)
            {
                ham(coord1, coord2) *= -1;
                ham(coord2, coord1) *= -1;
            }
        }

        return ham;
    }

    /*cx_mat bond_randomize(cx_mat ham)
    {
        int N_ = size(ham)[0];
        int die, coord1, coord2;
        double dJ = 0.8;

        for (int j = 0 ; j < N_/4; j++)
        {
            die = roll_die(length_);
            coord1 = v_[die]/N_;
            coord2 = v_[die]%N_;

            // Flip a coin:
            if (rng_() < 0.5)
            {
                ham(coord1, coord2) -= dJ;
                ham(coord2, coord1) = -ham(coord1, coord2);
            }
            else
            {
                ham(coord1, coord2) += dJ;
                ham(coord2, coord1) = -ham(coord1, coord2);
            }
        }

        return ham;
    }*/

    ////////////////////////////////////////////////////////////////

    protected:

    // Random int from the interval [0,max)
    int roll_die(int max) const
    {
        return static_cast<int>(max * rng_());
    }

private:
    typedef boost::mt19937 engine_type; // Mersenne twister
    typedef boost::uniform_real<> distribution_type;
    typedef boost::variate_generator<engine_type&, distribution_type> rng_type;
    engine_type eng_;
    distribution_type dist_;
    mutable rng_type rng_;

    size_t sweeps_;
    size_t thermalization_;

    // Everything here is described above:
    int np_;
    int me_;
    double T_min;
    double T_max;
    double temp_;
    double beta_;

    cx_mat ham;
    size_t N_;

    std::vector<int> v_;
    int length_;

    vec eigval;

    double F;

    Mat<int> plaquettes;

    // ALPS Observables:

    alps::RealObservable energy_;
    alps::RealObservable e2_;
    //alps::RealObservable e4_;
    alps::RealObservable dE_db;
    //alps::RealObservable p_;
    alps::RealObservable flux_real;
    alps::RealObservable flux_imag;
    alps::RealObservable flux_real_squared;
    alps::RealObservable flux_imag_squared;
    alps::RealObservable spin_corr;

    int flip_rate;

    signed int sign;

    std::string dist;
    std::string filename_;
};


text:
/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */

#include "base/os.h"
#include <sys/socket.h>

#include <net/if.h>

#ifdef __linux__
#include <linux/netlink.h>
#include <linux/if_tun.h>
#include <linux/if_packet.h>
#endif

#ifdef __FreeBSD__
#include <sys/sockio.h>
#include <ifaddrs.h>
#endif

#include "testing/gunit.h"

#include <base/logging.h>
#include <io/event_manager.h>
#include <tbb/task.h>
#include <base/task.h>

#include <cmn/agent_cmn.h>

#include "oper/operdb_init.h"
#include "controller/controller_init.h"
#include "pkt/pkt_init.h"
#include "services/services_init.h"
#include "vrouter/ksync/ksync_init.h"
#include "oper/interface_common.h"
#include "test_cmn_util.h"
#include "vr_types.h"
#include <controller/controller_export.h>
#include <ksync/ksync_sock_user.h>
#include <boost/assign/list_of.hpp>
#include "oper/qos_config.h"

using namespace boost::assign;

void RouterIdDepInit(Agent *agent) {
}

class FwdClassTest : public ::testing::Test {

    virtual void SetUp() {
        agent = Agent::GetInstance();
    }

    virtual void TearDown() {

    }

protected:
    Agent *agent;
};

TEST_F(FwdClassTest, Test1) {
    AddGlobalConfig(NULL, 0);
    client->WaitForIdle();
    EXPECT_TRUE(agent->forwarding_class_table()->Size() == 0);
}

TEST_F(FwdClassTest, Test2) {
    TestForwardingClassData data[] = {
        {1, 1, 1, 1, 1},
        {2, 2, 2, 2, 2}
    };

    AddGlobalConfig(data, 2);
    client->WaitForIdle();
    EXPECT_TRUE(agent->forwarding_class_table()->Size() == 2);
    VerifyForwardingClass(agent, data, 2);

    DelGlobalConfig(data, 2);
    client->WaitForIdle();
    EXPECT_TRUE(agent->forwarding_class_table()->Size() == 0);
}

TEST_F(FwdClassTest, Test3) {
    TestForwardingClassData data[] = {
        {1, 1, 1, 1, 1},
        {2, 2, 2, 2, 2}
    };

    AddGlobalConfig(data, 2);
    client->WaitForIdle();
    EXPECT_TRUE(agent->forwarding_class_table()->Size() == 2);
    VerifyForwardingClass(agent, data, 2);

    TestForwardingClassData data2[] = {
        {1, 2, 3, 4, 5},
        {2, 3, 4, 5, 6}
    };

    AddGlobalConfig(data2, 2);
    DelLink("forwarding-class", "fc1", "qos-queue", "qosqueue1");
    DelLink("forwarding-class", "fc2", "qos-queue", "qosqueue2");
    DelNode("qos-queue", "qosqueue1");
    DelNode("qos-queue", "qosqueue2");
    client->WaitForIdle();
    EXPECT_TRUE(agent->forwarding_class_table()->Size() == 2);
    VerifyForwardingClass(agent, data2, 2);

    DelGlobalConfig(data2, 2);
    client->WaitForIdle();
    EXPECT_TRUE(agent->forwarding_class_table()->Size() == 0);
}

int main(int argc, char **argv) {
    GETUSERARGS();

    client = TestInit(init_file, ksync_init, false, false, false);

    int ret = RUN_ALL_TESTS();

    usleep(10000);
    client->WaitForIdle();
    usleep(10000);
    TestShutdown();
    delete client;

    return ret;
}

ext: cc

max_stars_repo_name: UbuntuEvangelist/contrail-controller

max_issues_repo_name: UbuntuEvangelist/contrail-controller

max_forks_repo_name: UbuntuEvangelist/contrail-controller


text:
/*
    Copyright 2005-2013 Adobe Systems Incorporated
    Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
    or a copy at http://stlab.adobe.com/licenses.html)
*/

/**************************************************************************************************/

// stdc++
#include <iostream>
#include <vector>

#define BOOST_TEST_MAIN

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

// asl
#include <adobe/algorithm/for_each.hpp>
#include <adobe/algorithm/lower_bound.hpp>
#include <adobe/algorithm/sort.hpp>
#include <adobe/json.hpp>

/**************************************************************************************************/

using namespace std;
using namespace boost;
using namespace adobe;

/**************************************************************************************************/

struct any_json_helper_t {
    typedef any value_type;
    typedef string key_type;
    typedef string string_type;
    typedef unordered_map<key_type, value_type> object_type;
    typedef vector<value_type> array_type;
    typedef object_type::value_type pair_type;

    static json_type type(const value_type& x) {
        // REVISIT (make this thread safe) - nuke json_type and add functions to table directly.
        bool inited = false;

        static struct type_table_t {
            const std::type_info* type_info_;
            json_type type_;
        } table[] = {
            {&typeid(object_type), json_type::object}, {&typeid(array_type), json_type::array},
            {&typeid(string_type), json_type::string}, {&typeid(double), json_type::number},
            {&typeid(bool), json_type::boolean},       {&typeid(void), json_type::null}};
        static const auto projection = [](const type_table_t& x) -> const std::type_info& {
            return *x.type_info_;
        };

        if (!inited) {
            adobe::sort(table, adobe::less(), projection);
            inited = true;
        }

        auto p = adobe::lower_bound(table, x.type(), adobe::less(), projection);
        assert(p != end(table) && "invalid type for serialization");

        return p->type_;
    }

    template <typename T>
    static const T& as(const value_type& x) {
        return any_cast<const T&>(x);
    }

    static void move_append(object_type& obj, key_type& key, value_type& value) {
        obj.emplace(std::move(key), std::move(value));
    }
    static void append(string_type& str, const char* f, const char* l) { str.append(f, l); }
    static void move_append(array_type& array, value_type& value) {
        array.push_back(std::move(value));
    }
};

/**************************************************************************************************/

BOOST_AUTO_TEST_CASE(any_json_helper_smoke) {
    std::cout << "-=-=- any_json_helper_smoke -=-=-\n";
    any x = json_parser<any_json_helper_t>(u8R"raw(
        [
            42,
            12.536,
            -20.5,
            -1.375e+112,
            3.1415926535897932384626433832795028841971693993751058209,
            null,
            {
                "Country": "US",
                "State": "CA",
                "Address": "",
                "Longitude": -122.3959,
                "Zip": "94107",
                "City": "SAN FRANCISCO",
                "Latitude": 37.7668,
                "precision": "zip"
            },
            {
                "precision": "zip",
                "Latitude": 37.371991,
                "City": "SUNNYVALE",
                "Zip": "94085",
                "Longitude": -122.02602,
                "Address": "",
                "State": "CA",
                "Country": "US"
            }
        ]
    )raw")
                .parse();

    json_generator<any_json_helper_t, ostream_iterator<char>>(ostream_iterator<char>(cout))
        .generate(x);

    cout << endl;
}

/******************************************************************************/

ext: cpp


text:
// Copyright 2012 Daniel James.
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include "./config.hpp"

#ifdef TEST_EXTENSIONS
#  ifdef TEST_STD_INCLUDES
#    include <functional>
#  else
#    include <boost/functional/hash.hpp>
#  endif
#endif

#include <boost/config.hpp>
#include <boost/detail/lightweight_test.hpp>

#if defined(TEST_EXTENSIONS) && !defined(BOOST_NO_CXX11_HDR_TUPLE)
#define TEST_TUPLE
#include <tuple>
#include <vector>
#endif

#ifdef TEST_TUPLE

template <typename T>
void tuple_tests(T const& v) {
    boost::hash<typename T::value_type> hf;
    for(typename T::const_iterator i = v.begin(); i != v.end(); ++i) {
        for(typename T::const_iterator j = v.begin(); j != v.end(); ++j) {
            if (i != j)
                BOOST_TEST(hf(*i) != hf(*j));
            else
                BOOST_TEST(hf(*i) == hf(*j));
        }
    }
}

void empty_tuple_test() {
    boost::hash<std::tuple<> > empty_tuple_hash;
    std::tuple<> empty_tuple;
    BOOST_TEST(empty_tuple_hash(empty_tuple) == boost::hash_value(empty_tuple));
}

void int_tuple_test() {
    std::vector<std::tuple<int> > int_tuples;
    int_tuples.push_back(std::make_tuple(0));
    int_tuples.push_back(std::make_tuple(1));
    int_tuples.push_back(std::make_tuple(2));
    tuple_tests(int_tuples);
}

void int_string_tuple_test() {
    std::vector<std::tuple<int, std::string> > int_string_tuples;
    int_string_tuples.push_back(std::make_tuple(0, std::string("zero")));
    int_string_tuples.push_back(std::make_tuple(1, std::string("one")));
    int_string_tuples.push_back(std::make_tuple(2, std::string("two")));
    int_string_tuples.push_back(std::make_tuple(0, std::string("one")));
    int_string_tuples.push_back(std::make_tuple(1, std::string("zero")));
    int_string_tuples.push_back(std::make_tuple(0, std::string("")));
    int_string_tuples.push_back(std::make_tuple(1, std::string("")));
    tuple_tests(int_string_tuples);
}

#endif // TEST_TUPLE

int main()
{
#ifdef TEST_TUPLE
    empty_tuple_test();
    int_tuple_test();
    int_string_tuple_test();
#endif

    return boost::report_errors();
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
#ifndef STAN_MATH_PRIM_MAT_PROB_LKJ_CORR_CHOLESKY_LOG_HPP
#define STAN_MATH_PRIM_MAT_PROB_LKJ_CORR_CHOLESKY_LOG_HPP

#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/prob/lkj_corr_cholesky_lpdf.hpp>
#include <boost/math/tools/promotion.hpp>

namespace stan {
namespace math {

/**
 * @deprecated use lkj_corr_cholesky_lpdf
 */
template <bool propto, typename T_covar, typename T_shape>
typename boost::math::tools::promote_args<T_covar, T_shape>::type
lkj_corr_cholesky_log(
    const Eigen::Matrix<T_covar, Eigen::Dynamic, Eigen::Dynamic>& L,
    const T_shape& eta) {
  return lkj_corr_cholesky_lpdf<propto, T_covar, T_shape>(L, eta);
}

/**
 * @deprecated use lkj_corr_cholesky_lpdf
 */
template <typename T_covar, typename T_shape>
inline typename boost::math::tools::promote_args<T_covar, T_shape>::type
lkj_corr_cholesky_log(
    const Eigen::Matrix<T_covar, Eigen::Dynamic, Eigen::Dynamic>& L,
    const T_shape& eta) {
  return lkj_corr_cholesky_lpdf<T_covar, T_shape>(L, eta);
}

}  // namespace math
}  // namespace stan
#endif

ext: hpp

max_stars_repo_name: jrmie/math

max_issues_repo_name: jrmie/math

max_forks_repo_name: jrmie/math


text:
//
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_HTTP_STRING_BODY_HPP
#define BOOST_BEAST_HTTP_STRING_BODY_HPP

#include <boost/beast/core/detail/config.hpp>
#include <boost/beast/core/buffer_size.hpp>
#include <boost/beast/http/error.hpp>
#include <boost/beast/http/message.hpp>
#include <boost/beast/core/buffers_range.hpp>
#include <boost/beast/core/detail/type_traits.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/optional.hpp>
#include <cstdint>
#include <limits>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>

namespace boost {
namespace beast {
namespace http {

/** A @b Body using `std::basic_string`

    This body uses `std::basic_string` as a memory-based container
    for holding message payloads. Messages using this body type
    may be serialized and parsed.
*/
template<
    class CharT,
    class Traits = std::char_traits<CharT>,
    class Allocator = std::allocator<CharT>>
struct basic_string_body
{
private:
    static_assert(
        std::is_integral<CharT>::value &&
            sizeof(CharT) == 1,
        "CharT requirements not met");

public:
    /** The type of container used for the body

        This determines the type of @ref message::body
        when this body type is used with a message container.
    */
    using value_type =
        std::basic_string<CharT, Traits, Allocator>;

    /** Returns the payload size of the body

        When this body is used with @ref message::prepare_payload,
        the Content-Length will be set to the payload size, and
        any chunked Transfer-Encoding will be removed.
    */
    static
    std::uint64_t
    size(value_type const& body)
    {
        return body.size();
    }

    /** The algorithm for parsing the body

        Meets the requirements of @b BodyReader.
    */
#if BOOST_BEAST_DOXYGEN
    using reader = __implementation_defined__;
#else
    class reader
    {
        value_type& body_;

    public:
        template<bool isRequest, class Fields>
        explicit
        reader(header<isRequest, Fields>&, value_type& b)
            : body_(b)
        {
        }

        void
        init(boost::optional<
            std::uint64_t> const& length, error_code& ec)
        {
            if(length)
            {
                if(static_cast<std::size_t>(*length) != *length)
                {
                    ec = error::buffer_overflow;
                    return;
                }
                try
                {
                    body_.reserve(
                        static_cast<std::size_t>(*length));
                }
                catch(std::exception const&)
                {
                    ec = error::buffer_overflow;
                    return;
                }
            }
            ec = {};
        }

        template<class ConstBufferSequence>
        std::size_t
        put(ConstBufferSequence const& buffers,
            error_code& ec)
        {
            auto const extra = buffer_size(buffers);
            auto const size = body_.size();
            try
            {
                body_.resize(size + extra);
            }
            catch(std::exception const&)
            {
                ec = error::buffer_overflow;
                return 0;
            }
            ec = {};
            CharT* dest = &body_[size];
            for(auto b : beast::buffers_range_ref(buffers))
            {
                Traits::copy(dest, static_cast<
                    CharT const*>(b.data()), b.size());
                dest += b.size();
            }
            return extra;
        }

        void
        finish(error_code& ec)
        {
            ec = {};
        }
    };
#endif

    /** The algorithm for serializing the body

        Meets the requirements of @b BodyWriter.
    */
#if BOOST_BEAST_DOXYGEN
    using writer = __implementation_defined__;
#else
    class writer
    {
        value_type const& body_;

    public:
        using const_buffers_type =
            net::const_buffer;

        template<bool isRequest, class Fields>
        explicit
        writer(header<isRequest, Fields> const&, value_type const& b)
            : body_(b)
        {
        }

        void
        init(error_code& ec)
        {
            ec = {};
        }

        boost::optional<std::pair<const_buffers_type, bool>>
        get(error_code& ec)
        {
            ec = {};
            return {{const_buffers_type{
                body_.data(), body_.size()}, false}};
        }
    };
#endif
};

/// A @b Body using `std::string`
using string_body = basic_string_body<char>;

} // http
} // beast
} // boost

#endif

max_stars_repo_name: bebuch/beast

max_issues_repo_name: bebuch/beast

max_forks_repo_name: bebuch/beast


text:
//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id: sortertest_main.cc $
//
// Created 2011/09/21
//
// Copyright 2011 Yahoo Corporation.  All rights reserved.
// This file is part of the Sailfish project.
//
// 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.
//
// \brief Uses the sorter code for testing: if compression is involved,
// that code path is tested too.
//----------------------------------------------------------------------------

#include "common/log.h"
#include "chunksorter.h"

#include <unistd.h>
#include <fcntl.h>

#include <cerrno>
#include <arpa/inet.h>
#include <iostream>
#include <sstream>
#include <boost/program_options.hpp>
#include <boost/scoped_array.hpp>
#include <algorithm>
#include <string>
#include <vector>
namespace po = boost::program_options;

using namespace KFS;
using std::string;

int main(int argc, char **argv)
{
    SortFileOp sfo(0);
    KFS::SortWorker worker(0, 0, 0);

    // Declare the supported options.
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help,h", "produce help message")
        ("input,i", po::value<string>(&sfo.inputFn)->default_value(""), "Input file to be sorted")
        ("output,o", po::value<string>(&sfo.outputFn)->default_value(""), "Output file")
        ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }

    MsgLogger::Init(NULL, MsgLogger::kLogLevelINFO);

    worker.sortFile(&sfo);

    MsgLogger::Stop();
}

max_stars_repo_name: sriramsrao/kfs

max_issues_repo_name: sriramsrao/kfs

max_forks_repo_name: sriramsrao/kfs


text:
#include <boost/foreach.hpp>
#include "InMemoryPerSentenceOnDemandLM.h"
#include "moses/FactorCollection.h"
#include "moses/Util.h"
#include "moses/StaticData.h"
#include "moses/TranslationTask.h"
#include "moses/ContextScope.h"
#include "moses/LM/Ken.h"
#include "lm/model.hh"
#include "util/mmap.hh"

#include <cstdio>
#include <iostream>
#include <fstream>

using namespace std;

namespace Moses
{
InMemoryPerSentenceOnDemandLM::InMemoryPerSentenceOnDemandLM(const std::string &line) : LanguageModel(line)
{
  ReadParameters();
}

InMemoryPerSentenceOnDemandLM::~InMemoryPerSentenceOnDemandLM()
{
}

void InMemoryPerSentenceOnDemandLM::InitializeForInput(ttasksptr const& ttask)
{

  // The context scope object for this translation task
  //     contains a map of translation task-specific data
  boost::shared_ptr<Moses::ContextScope> contextScope = ttask->GetScope();

  // The key to the map is this object
  void const* key = static_cast<void const*>(this);

  // The value stored in the map is a string representing a phrase table
  boost::shared_ptr<string> value = contextScope->get<string>(key);

  // Create a stream to read the phrase table data
  stringstream strme(*(value.get()));

  char * nullpointer = (char *) 0;
  const char * filename = std::tmpnam(nullpointer);
  ofstream tmp;
  tmp.open(filename);

  // Read the phrase table data, one line at a time
  string line;
  while (getline(strme, line)) {

    tmp << line << "\n";

  }

  tmp.close();

  //  m_tmpFilename.reset(new std::string("/home/lanes/mosesdecoder/tiny.with_per_sentence/europarl.en.srilm"));
  m_tmpFilename.reset(new std::string(filename));

  //LanguageModelKen<lm::ngram::ProbingModel> & lm =
  GetPerThreadLM();

  //  std::remove(filename);

}

LanguageModelKen<lm::ngram::ProbingModel>& InMemoryPerSentenceOnDemandLM::GetPerThreadLM() const
{

  LanguageModelKen<lm::ngram::ProbingModel> *lm;
  lm = m_perThreadLM.get();
  if (lm == NULL) {
    lm = new LanguageModelKen<lm::ngram::ProbingModel>();

    string* filename = m_tmpFilename.get();
    if (filename == NULL) {
      UTIL_THROW(util::Exception, "Can't get a thread-specific LM because no temporary filename has been set for this thread\n");
    } else {
      lm->LoadModel(*filename, util::POPULATE_OR_READ);
    }

    VERBOSE(1, filename);
    VERBOSE(1, "\tLM initialized\n");

    m_perThreadLM.reset(lm);
  }
  assert(lm);

  return *lm;

}

}


text:
/*
 *          Copyright Andrey Semashev 2007 - 2014.
 * 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   value_extraction_fwd.hpp
 * \author Andrey Semashev
 * \date   01.03.2008
 *
 * The header contains forward declaration of tools for extracting attribute values
 * from the view.
 */

#ifndef BOOST_LOG_ATTRIBUTES_VALUE_EXTRACTION_FWD_HPP_INCLUDED_
#define BOOST_LOG_ATTRIBUTES_VALUE_EXTRACTION_FWD_HPP_INCLUDED_

#include <boost/log/detail/config.hpp>
#include <boost/log/attributes/fallback_policy_fwd.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

namespace result_of {

/*!
 * \brief A metafunction that allows to acquire the result of the value extraction
 */
template< typename T, typename DefaultT = T, typename TagT = void >
struct extract_or_default;

/*!
 * \brief A metafunction that allows to acquire the result of the value extraction
 */
template< typename T, typename TagT = void >
struct extract_or_throw;

/*!
 * \brief A metafunction that allows to acquire the result of the value extraction
 */
template< typename T, typename TagT = void >
struct extract;

} // namespace result_of

/*!
 * \brief Generic attribute value extractor
 */
template< typename T, typename FallbackPolicyT = fallback_to_none, typename TagT = void >
class value_extractor;

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#endif // BOOST_LOG_ATTRIBUTES_VALUE_EXTRACTION_FWD_HPP_INCLUDED_


text:
#include <cstdlib>
#include <deque>
#include <iostream>
#include <list>
#include <memory>
#include <set>
#include <utility>
#include <boost/asio.hpp>
#include "ChatMessage.hpp"

using boost::asio::ip::tcp;

typedef std::deque<ChatMessage> ChatMessageQueue;

class ChatMember
{
public:
  virtual ~ChatMember() {}
  virtual void deliver(const ChatMessage& msg) = 0;
};

typedef std::shared_ptr<ChatMember> ChatMemberPtr;

class ChatRoom
{
public:
  void join(ChatMemberPtr member)
  {
    members_.insert(member);
    for (auto msg: recent_msgs_)
      member->deliver(msg);
  }

  void leave(ChatMemberPtr member)
  {
    members_.erase(member);
  }

  void deliver(const ChatMessage& msg)
  {
    recent_msgs_.push_back(msg);
    while (recent_msgs_.size() > max_recent_msgs)
      recent_msgs_.pop_front();

    for (auto member: members_)
      member->deliver(msg);
  }

private:
  std::set<ChatMemberPtr> members_;
  enum { max_recent_msgs = 100 };
  ChatMessageQueue recent_msgs_;
};

class ChatSession
  : public ChatMember,
    public std::enable_shared_from_this<ChatSession>
{
public:
  ChatSession(tcp::socket socket, ChatRoom& room)
    : socket_(std::move(socket)),
      room_(room)
  {
  }

  void start()
  {
    room_.join(shared_from_this());
    read_header();
  }

  void deliver(const ChatMessage& msg)
  {
    bool write_in_progress = !write_msgs_.empty();
    write_msgs_.push_back(msg);
    if (!write_in_progress)
      write();
  }

private:
  void read_header()
  {
    auto self(shared_from_this());
    boost::asio::async_read(socket_,
        boost::asio::buffer(read_msg_.data(), ChatMessage::HEADER_SIZE),
        [this, self](boost::system::error_code ec, std::size_t /*length*/) {
          if (!ec && read_msg_.decode_header())
            read_body();
          else
            room_.leave(shared_from_this());
        });
  }

  void read_body()
  {
    auto self(shared_from_this());
    boost::asio::async_read(socket_,
        boost::asio::buffer(read_msg_.body(), read_msg_.body_length()),
        [this, self](boost::system::error_code ec, std::size_t /*length*/) {
          if (!ec) {
            room_.deliver(read_msg_);
            read_header();
          } else {
            room_.leave(shared_from_this());
          }
        });
  }

  void write()
  {
    auto self(shared_from_this());
    boost::asio::async_write(socket_,
        boost::asio::buffer(write_msgs_.front().data(),
          write_msgs_.front().length()),
        [this, self](boost::system::error_code ec, std::size_t /*length*/) {
          if (!ec) {
            write_msgs_.pop_front();
            if (!write_msgs_.empty())
              write();
          } else {
            room_.leave(shared_from_this());
          }
        });
  }

private:
  tcp::socket socket_;
  ChatRoom& room_;
  ChatMessage read_msg_;
  ChatMessageQueue write_msgs_;
};

class ChatServer
{
public:
  ChatServer(boost::asio::io_service& io_service,
      const tcp::endpoint& endpoint)
    : acceptor_(io_service, endpoint),
      socket_(io_service)
  {
    do_accept();
  }

private:
  void do_accept()
  {
    acceptor_.async_accept(socket_,
        [this](boost::system::error_code ec) {
          if (!ec)
            std::make_shared<ChatSession>(std::move(socket_), room_)->start();
          do_accept();
        });
  }

  tcp::acceptor acceptor_;
  tcp::socket socket_;
  ChatRoom room_;
};

int main_impl(int argc, const char *argv[])
{
    if (argc != 2)
        throw std::invalid_argument("Incorrect number of arguments \n"
                                    "Usage: chat_server <port>");

    boost::asio::io_service io_service;
    tcp::endpoint endpoint(tcp::v4(), std::atoi(argv[1]));
    ChatServer server(io_service, endpoint);
    io_service.run();
    return EXIT_SUCCESS;
}

int main(int argc, const char *argv[])
{
    try {
        return main_impl(argc, argv);
    } catch (const std::exception &ex) {
        std::cout << "[" << __FUNCTION__ << "]::" << __LINE__ << " Unhandled exception -> " << ex.what() << std::endl;
    } catch (...) {
        std::cout << "[" << __FUNCTION__ << "]::" << __LINE__ << " Unrecognized unhandled exception" << std::endl;
    }

    return EXIT_FAILURE;
}


text:
/*
 [auto_generated]
 libs/numeric/odeint/test/runge_kutta_concepts.cpp

 [begin_description]
 This file tests the Stepper concepts of odeint with all Runge-Kutta steppers. It's one of the main tests
 of odeint.
 [end_description]

 Copyright 2009-2012 Karsten Ahnert
 Copyright 2009-2012 Mario Mulansky

 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)
 */

// disable checked iterator warning for msvc
#include <boost/config.hpp>
#ifdef BOOST_MSVC
    #pragma warning(disable:4996)
#endif

#define BOOST_TEST_MODULE odeint_runge_kutta_concepts

#include <vector>
#include <cmath>
#include <iostream>

#include <boost/numeric/odeint/config.hpp>

#include <boost/array.hpp>

#include <boost/test/unit_test.hpp>

#include <boost/ref.hpp>
#include <boost/bind.hpp>
#include <boost/utility.hpp>
#include <boost/type_traits/add_reference.hpp>

#include <boost/mpl/vector.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/insert_range.hpp>
#include <boost/mpl/end.hpp>
#include <boost/mpl/copy.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/inserter.hpp>

#include <boost/numeric/odeint/stepper/euler.hpp>
#include <boost/numeric/odeint/stepper/modified_midpoint.hpp>
#include <boost/numeric/odeint/stepper/runge_kutta4_classic.hpp>
#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>
#include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54_classic.hpp>
#include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54.hpp>
#include <boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp>
#include <boost/numeric/odeint/stepper/runge_kutta_fehlberg78.hpp>

#include "prepare_stepper_testing.hpp"
#include "dummy_odes.hpp"

using std::vector;

using namespace boost::unit_test;
using namespace boost::numeric::odeint;
namespace mpl = boost::mpl;

const double result = 2.2;

const double eps = 1.0e-14;

template< class Stepper , class System >
void check_stepper_concept( Stepper &stepper , System system , typename Stepper::deriv_type &x )
{
    typedef Stepper stepper_type;
    typedef typename stepper_type::deriv_type container_type;
    typedef typename stepper_type::order_type order_type;
    typedef typename stepper_type::time_type time_type;

    stepper.do_step( system , x , 0.0 , 0.1 );
}

template< class Stepper , class State > struct perform_stepper_test;

template< class Stepper >
struct perform_stepper_test< Stepper , vector_type >
{
    void operator()( void )
    {
        vector_type x( 1 , 2.0 );
        Stepper stepper;
        check_stepper_concept( stepper , constant_system_standard< vector_type , vector_type , double > , x );
        check_stepper_concept( stepper , boost::cref( constant_system_functor_standard() ) , x );
        std::cout << x[0] << " ?= " << result << std::endl;
        BOOST_CHECK_SMALL( fabs( x[0] - result ) , eps );
    }
};

template< class Stepper >
struct perform_stepper_test< Stepper , vector_space_type >
{
    void operator()( void ) const
    {
        vector_space_type x;
        x.m_x = 2.0;
        Stepper stepper;
        check_stepper_concept( stepper , constant_system_vector_space< vector_space_type , vector_space_type , double > , x );
        check_stepper_concept( stepper , boost::cref( constant_system_functor_vector_space() ) , x );
        std::cout << x.m_x << " ?= " << result << std::endl;
        BOOST_CHECK_SMALL( fabs( x.m_x - result ) , eps );
    }
};

template< class Stepper >
struct perform_stepper_test< Stepper , array_type >
{
    void operator()( void )
    {
        array_type x;
        x[0] = 2.0;
        Stepper stepper;
        check_stepper_concept( stepper , constant_system_standard< array_type , array_type , double> , x );
        check_stepper_concept( stepper , boost::cref( constant_system_functor_standard() ) , x );
        std::cout << x[0] << " ?= " << result << std::endl;
        BOOST_CHECK_SMALL( fabs( x[0] - result ) , eps );
    }
};

template< class State > class stepper_methods : public mpl::vector<
    euler< State , double , State , double , typename algebra_dispatcher< State >::type > ,
    modified_midpoint< State , double , State , double , typename algebra_dispatcher< State >::type > ,
    runge_kutta4< State , double , State , double , typename algebra_dispatcher< State >::type > ,
    runge_kutta4_classic< State , double , State , double , typename algebra_dispatcher< State >::type > ,
    runge_kutta_cash_karp54_classic< State , double , State , double , typename algebra_dispatcher< State >::type > ,
    runge_kutta_cash_karp54< State , double , State , double , typename algebra_dispatcher< State >::type > ,
    runge_kutta_dopri5< State , double , State , double , typename algebra_dispatcher< State >::type > ,
    runge_kutta_fehlberg78< State , double , State , double , typename algebra_dispatcher< State >::type >
    > { };

typedef mpl::copy
<
  container_types ,
  mpl::inserter
  <
    mpl::vector0<> ,
    mpl::insert_range
    <
      mpl::_1 ,
      mpl::end< mpl::_1 > ,
      stepper_methods< mpl::_2 >
    >
  >
>::type all_stepper_methods;

BOOST_AUTO_TEST_SUITE( runge_kutta_concept_test )

BOOST_AUTO_TEST_CASE_TEMPLATE( stepper_test , Stepper, all_stepper_methods )
{
    perform_stepper_test< Stepper , typename Stepper::deriv_type > tester;
    tester();
}

BOOST_AUTO_TEST_SUITE_END()


text:
#include <GL/gl3w.h>
#include <GLFW/glfw3.h>

#include <iostream>
#include <atomic>
#include <chrono>

#include <unistd.h>

#include "quori_face/Window.hpp"
#include "quori_face/WindowManager.hpp"
#include "quori_face/Shader.hpp"
#include "quori_face/Program.hpp"
#include "quori_face/Texture.hpp"
#include "quori_face/PixelBufferObject.hpp"
#include "quori_face/transform.hpp"
#include "quori_face/gl.hpp"

#include "geometry.hpp"
#include "shader/frag.hpp"
#include "shader/vertex.hpp"

#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/photo.hpp>

#include <image_transport/image_transport.h>
#include <sensor_msgs/image_encodings.h>
#include <cv_bridge/cv_bridge.h>

#include <unordered_map>
#include <ros/ros.h>
#include <ros/package.h>

#include <boost/optional.hpp>
#include <fstream>

#include <dynamic_reconfigure/server.h>
#include <quori_face/CalibrationConfig.h>

#include <yaml-cpp/yaml.h>

#include "trace.hpp"
#include "param.hpp"

using namespace quori_face;
using namespace quori_face_node;

namespace
{
  sensor_msgs::ImageConstPtr latest_image;

  void imageCallback(const sensor_msgs::ImageConstPtr &msg)
  {
    latest_image = msg;
  }

  std::atomic<bool> static_params_updated(false);
  TransformStaticParameters static_params(TransformStaticParameters::DEFAULT);

  SphericalCoordinate center(SphericalCoordinate::CENTER);

  SphericalCoordinate min_coord = {
    .theta = -M_PI * 0.45,
    .psi = -M_PI * 0.5
  };

  SphericalCoordinate max_coord = {
    .theta = M_PI * 0.45,
    .psi = M_PI * 0.5
  };

  void reconfigureCallback(CalibrationConfig &calibration, uint32_t level)
  {
    static bool debounce = true;
    if (debounce)
    {
      debounce = false;
      return;
    }

    static_params.delta.x = calibration.dx;
    static_params.delta.y = calibration.dy;

    center.theta = calibration.center_theta;
    center.psi = calibration.center_psi;

    min_coord.theta = center.theta + calibration.min_theta;
    min_coord.psi = center.psi + calibration.min_psi;

    max_coord.theta = center.theta + calibration.max_theta;
    max_coord.psi = center.psi + calibration.max_psi;

    static_params_updated = true;
  }

  const Vector2<std::uint32_t> LOOKUP_TABLE_RESOLUTION = {
    // Theta resolution
    .x = 2048,
    // Psi resolution
    .y = 2048
  };

  const Vector2<std::uint32_t> IMAGE_RESOLUTION = {
    .x = 1280,
    .y = 720
  };

  const std::unordered_map<std::string, std::uint32_t> ENCODING_GL_MAPPINGS {
    { sensor_msgs::image_encodings::RGB8, GL_RGB },
    { sensor_msgs::image_encodings::BGR8, GL_BGR },
  };

  const std::unordered_map<std::string, std::uint32_t> ENCODING_CV_MAPPINGS {
    { sensor_msgs::image_encodings::RGB8, CV_8UC3 },
    { sensor_msgs::image_encodings::BGR8, CV_8UC3 }
  };

  const std::unordered_map<std::string, boost::optional<cv::ColorConversionCodes>> ENCODING_CV_CVT_MAPPINGS {
    { sensor_msgs::image_encodings::RGB8, cv::COLOR_RGB2BGR },
    { sensor_msgs::image_encodings::BGR8, boost::none }
  };

  std::size_t encodingSize(const std::string &encoding)
  {
    const std::size_t bitDepth = sensor_msgs::image_encodings::bitDepth(latest_image->encoding);
    const std::size_t numChannels = sensor_msgs::image_encodings::numChannels(latest_image->encoding);
    return bitDepth / 8 * numChannels;
  }

  void mapImage(std::uint8_t *const data, const cv::Mat &image)
  {
    const std::size_t elementSize = image.elemSize();
    for (std::size_t row = 0; row < image.rows; ++row)
    {
      memcpy(data + image.cols * row * elementSize, image.ptr(row), image.cols * elementSize);
    }
  }
}

int main(int argc, char *argv[])
{
  using namespace std;
  using namespace cv;

  ros::init(argc, argv, "quori_face");

  ros::NodeHandle nh;
  ros::NodeHandle pnh("~");

  boost::recursive_mutex reconfigure_mutex;
  dynamic_reconfigure::Server<quori_face::CalibrationConfig> reconfigure_server(reconfigure_mutex);
  reconfigure_server.setCallback(boost::bind(&reconfigureCallback, _1, _2));

  const auto lookup_table_resolution = param(pnh, "lookup_table_resolution", LOOKUP_TABLE_RESOLUTION);
  const auto image_resolution = param(pnh, "image_resolution", IMAGE_RESOLUTION);
  center = param(pnh, "center", center);

  min_coord = center + param(pnh, "min", min_coord);
  max_coord = center + param(pnh, "max", max_coord);

  const bool update_params = param(pnh, "update_params", false);

  const std::string override_image_encoding = param(pnh, "override_image_encoding", std::string());

  static_params = param(pnh, "transform", static_params);

  CalibrationConfig config;
  config.dx = static_params.delta.x;
  config.dy = static_params.delta.y;
  config.center_theta = center.theta;
  config.center_psi = center.psi;
  config.min_theta = min_coord.theta - center.theta;
  config.min_psi = min_coord.psi - center.psi;
  config.max_theta = max_coord.theta - center.theta;
  config.max_psi = max_coord.psi - center.psi;
  reconfigure_server.updateConfig(config);

  const auto generate_lookup_table = [&]() {
    const auto start_time = std::chrono::system_clock::now();
    cout << "Updating lookup table (this may take several seconds)...";
    cout.flush();

    GLfloat *const ret = generateLookupTable(static_params, min_coord, max_coord, lookup_table_resolution);
    const auto end_time = std::chrono::system_clock::now();
    cout << " done (took " << std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count() << "ms)" << endl;
    return ret;
  };
  GLfloat *lookup_table = generate_lookup_table();

  image_transport::ImageTransport it(pnh);
  const auto image_sub = it.subscribe("image", 1, &imageCallback);
  const auto window = Window::open(static_params.screen_size.x, static_params.screen_size.y, "Quori Face", Monitor::getPrimaryMonitor());
  QUORI_FACE_NODE_TRACE(glEnable(GL_TEXTURE_2D));

  window->bind();

  WindowManager::ref().attach(window);
  const auto program = Program::link({
    Shader::compile(Shader::Type::Vertex, shader::VERTEX),
    Shader::compile(Shader::Type::Fragment, shader::FRAGMENT)
  });

  // Generate geometry for displaying the transformed image

  GLuint vao;
  QUORI_FACE_NODE_TRACE(glGenVertexArrays(1, &vao));

  GLuint vbo;
  QUORI_FACE_NODE_TRACE(glGenBuffers(1, &vbo));

  GLuint ebo;
  QUORI_FACE_NODE_TRACE(glGenBuffers(1, &ebo));

  QUORI_FACE_NODE_TRACE(glBindVertexArray(vao));

  QUORI_FACE_NODE_TRACE(glBindBuffer(GL_ARRAY_BUFFER, vbo));
  QUORI_FACE_NODE_TRACE(glBufferData(GL_ARRAY_BUFFER, GEOMETRY_VERTICES.size() * sizeof(float), GEOMETRY_VERTICES.data(), GL_STATIC_DRAW));

  QUORI_FACE_NODE_TRACE(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo));
  QUORI_FACE_NODE_TRACE(glBufferData(GL_ELEMENT_ARRAY_BUFFER, GEOMETRY_INDICES.size() * sizeof(std::uint32_t), GEOMETRY_INDICES.data(), GL_STATIC_DRAW));

  QUORI_FACE_NODE_TRACE(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), nullptr));
  QUORI_FACE_NODE_TRACE(glEnableVertexAttribArray(0));

  QUORI_FACE_NODE_TRACE(glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (void *)(3 * sizeof(GLfloat))));
  QUORI_FACE_NODE_TRACE(glEnableVertexAttribArray(1));

  // Create textures

  size_t image_size = image_resolution.x * image_resolution.y * 3;
  uint8_t *const image_texture_data = new uint8_t[image_size];
  memset(image_texture_data, 0, image_size);
  Texture::Ptr image_texture = Texture::create(image_resolution.y, image_resolution.x, GL_BGR, image_texture_data);
  delete[] image_texture_data;
  const auto lookup_table_texture = Texture::create(static_params.screen_size.y, static_params.screen_size.x, lookup_table);

  program->use();
  QUORI_FACE_NODE_TRACE(glUniform1i(program->getUniformLocation("lookup_table"), 0));
  QUORI_FACE_NODE_TRACE(glUniform1i(program->getUniformLocation("image"), 1));
  GLint i_resolution[] = {
    static_cast<GLint>(static_params.screen_size.x),
    static_cast<GLint>(static_params.screen_size.y),
    0
  };

  QUORI_FACE_NODE_TRACE(glUniform3iv(program->getUniformLocation("i_resolution"), 3, i_resolution));
  QUORI_FACE_NODE_TRACE(glActiveTexture(GL_TEXTURE0));
  QUORI_FACE_NODE_TRACE(glBindBuffer(GL_ARRAY_BUFFER, 0));
  QUORI_FACE_NODE_TRACE(glBindVertexArray(0));

  std::size_t image_pbo_index = 0;
  std::size_t lookup_table_pbo_index = 0;
  PixelBufferObject image_pbo(image_resolution.x * image_resolution.y * sizeof(uint8_t) * 3);
  PixelBufferObject lookup_table_pbo(lookup_table_resolution.x * lookup_table_resolution.y * sizeof(float) * 3);

  const auto copy_current_image_pbo = [&]()
  {
    image_texture->bind();
    image_pbo.bind(image_pbo_index);
    QUORI_FACE_NODE_TRACE(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, image_resolution.x, image_resolution.y, GL_BGR, GL_UNSIGNED_BYTE, 0));
    checkGlError();
    image_pbo.unbind();
  };

  const auto write_next_image_pbo = [&](const cv::Mat &image)
  {
    image_pbo.bind(image_pbo_index + 1);
    uint8_t *const data = reinterpret_cast<uint8_t *>(QUORI_FACE_NODE_TRACE(glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_READ_WRITE)));
    checkGlError();
    if (data)
    {
      mapImage(data, image);
      QUORI_FACE_NODE_TRACE(glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER));
      checkGlError();
    }

    image_pbo.unbind();
  };

  sensor_msgs::ImageConstPtr prev_image;

  while (!window->isClosed() && ros::ok())
  {
    ros::spinOnce();

    if (!latest_image) continue;
    if (latest_image == prev_image) continue;

    const auto &encoding = override_image_encoding.empty() ? latest_image->encoding : override_image_encoding;

    const auto cv_it = ENCODING_CV_MAPPINGS.find(encoding);
    if (cv_it == ENCODING_CV_MAPPINGS.cend())
    {
      cerr << "Unsupported image encoding (no CV encoding) \"" << encoding << "\"" << endl;
      continue;
    }

    const cv::Mat image(
      cv::Size(latest_image->width, latest_image->height),
      cv_it->second,
      // We pinky promise not to modify the constant image data
      const_cast<uint8_t *>(latest_image->data.data()),
      latest_image->step
    );

    const auto cvt_it = ENCODING_CV_CVT_MAPPINGS.find(encoding);
    if (cvt_it == ENCODING_CV_CVT_MAPPINGS.cend())
    {
      cerr << "Unsupported image encoding (no conversion) \"" << encoding << "\"" << endl;
      continue;
    }

    cv::Mat final_image;
    if (!cvt_it->second)
    {
      final_image = image;
    }
    else
    {
      cv::cvtColor(image, final_image, cvt_it->second.get());
    }

    if (final_image.rows != image_resolution.y || final_image.cols != image_resolution.x)
    {
      cv::Mat resized;
      cv::resize(final_image, resized, cv::Size(image_resolution.x, image_resolution.y));
      final_image = resized;
    }

    prev_image = latest_image;

    if (static_params_updated)
    {
      static_params_updated = false;
      GLfloat *const next_lookup_table = generate_lookup_table();

      QUORI_FACE_NODE_TRACE(glActiveTexture(GL_TEXTURE0));
      checkGlError();

      lookup_table_texture->bind();
      QUORI_FACE_NODE_TRACE(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, static_params.screen_size.x, static_params.screen_size.y, GL_RGB, GL_FLOAT, next_lookup_table));
      delete[] lookup_table;
      lookup_table = next_lookup_table;
      checkGlError();

      glBindTexture(GL_TEXTURE_2D, 0);
      checkGlError();
    }

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    QUORI_FACE_NODE_TRACE(glActiveTexture(GL_TEXTURE1));

    copy_current_image_pbo();
    write_next_image_pbo(final_image);

    program->use();

    QUORI_FACE_NODE_TRACE(glActiveTexture(GL_TEXTURE0));
    lookup_table_texture->bind();

    QUORI_FACE_NODE_TRACE(glActiveTexture(GL_TEXTURE1));
    image_texture->bind();

    QUORI_FACE_NODE_TRACE(glBindVertexArray(vao));
    QUORI_FACE_NODE_TRACE(glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0));
    QUORI_FACE_NODE_TRACE(glBindVertexArray(0));

    window->swapBuffers();
    ++image_pbo_index;

    Window::pollEvents();
  }

  QUORI_FACE_NODE_TRACE(glDeleteVertexArrays(1, &vao));
  QUORI_FACE_NODE_TRACE(glDeleteBuffers(1, &vbo));
  QUORI_FACE_NODE_TRACE(glDeleteBuffers(1, &ebo));

  delete[] lookup_table;

  // Update params

  if (update_params)
  {
    const std::string path = ros::package::getPath("quori_face");
    if (path.empty())
    {
      ROS_ERROR("Failed to update parameter file. quori_face package not found.");
      return EXIT_FAILURE;
    }

    std::ofstream out(path + "/config/params.yaml");

    if (!out.is_open())
    {
      ROS_ERROR("Failed to update parameter file. Couldn't open parameter file for writing.");
      return EXIT_FAILURE;
    }

    YAML::Node delta;
    delta["x"] = static_params.delta.x;
    delta["y"] = static_params.delta.y;

    YAML::Node screen_size;
    screen_size["x"] = static_params.screen_size.x;
    screen_size["y"] = static_params.screen_size.y;

    YAML::Node transform;
    transform["R"] = static_params.R;
    transform["r_m"] = static_params.r_m;
    transform["r_o"] = static_params.r_o;
    transform["h"] = static_params.h;
    transform["L"] = static_params.L;
    transform["epsilon"] = static_params.epsilon;
    transform["delta"] = delta;
    transform["screen_size"] = screen_size;

    YAML::Node lookup_table_resolution_node;
    lookup_table_resolution_node["x"] = lookup_table_resolution.x;
    lookup_table_resolution_node["y"] = lookup_table_resolution.y;

    YAML::Node image_resolution_node;
    image_resolution_node["x"] = image_resolution.x;
    image_resolution_node["y"] = image_resolution.y;

    YAML::Node min_node;
    min_node["theta"] = (min_coord.theta - center.theta);
    min_node["psi"] = (min_coord.psi - center.psi);

    YAML::Node max_node;
    max_node["theta"] = (max_coord.theta - center.theta);
    max_node["psi"] = (max_coord.psi - center.psi);

    YAML::Node center_node;
    center_node["theta"] = center.theta;
    center_node["psi"] = center.psi;

    YAML::Node root;
    root["transform"] = transform;
    root["lookup_table_resolution"] = lookup_table_resolution_node;
    root["image_resolution"] = image_resolution_node;
    root["max"] = max_node;
    root["min"] = min_node;
    root["center"] = center_node;

    YAML::Emitter emitter;
    emitter << root;

    out << emitter.c_str();
    out.close();
  }

  return EXIT_SUCCESS;
}


text:
#include <boost/python.hpp>

#include "OpenPGP/Subpackets/Tag2Sub23.h"

void Tag2Sub23_init()
{
boost::python::class_<Tag2Sub23, boost::python::bases<Tag2Subpacket>>("Tag2Sub23")
    .def(boost::python::init<std::string &>())
    .def("read", &Tag2Sub23::read)
    .def("get_flags", &Tag2Sub23::get_flags)
    .def("show", &Tag2Sub23::show)
    .def("raw", &Tag2Sub23::raw)
    .def("clone", &Tag2Sub23::clone)
    .def("set_flags", &Tag2Sub23::set_flags)
    ;
}

max_stars_repo_name: mugwort-rc/pyOpenPGP

max_issues_repo_name: mugwort-rc/pyOpenPGP

max_forks_repo_name: mugwort-rc/pyOpenPGP


text:
// Copyright Daniel Wallin 2006.
// Copyright Cromwell D. Enage 2017.
// 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)

#ifndef BOOST_PARAMETER_TEMPLATE_KEYWORD_HPP
#define BOOST_PARAMETER_TEMPLATE_KEYWORD_HPP

#include <boost/parameter/aux_/template_keyword.hpp>
#include <boost/parameter/config.hpp>

#if defined(BOOST_PARAMETER_CAN_USE_MP11)
#include <boost/mp11/integral.hpp>
#include <boost/mp11/utility.hpp>
#include <type_traits>
#else
#include <boost/mpl/bool.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/type_traits/add_lvalue_reference.hpp>
#include <boost/type_traits/is_function.hpp>
#include <boost/type_traits/is_array.hpp>
#endif

namespace boost { namespace parameter {

    template <typename Tag, typename T>
    struct template_keyword : ::boost::parameter::aux::template_keyword_base
    {
        typedef Tag key_type;
        typedef T value_type;

        // reference is needed for two reasons:
        //
        // 1. It is used in the body of arg_list<...>
        //
        // 2. It is the result of binding<...>, which we mistakenly told
        //    people to use instead of value_type<...> to access named
        //    template parameters
        //
        // It used to be that reference == value_type, but that broke when
        // the argument was a function or array type, because various
        // arg_list functions return reference.
        //
        // Simply making reference == value_type& would break all the
        // legacy code that uses binding<...> to access named template
        // parameters. -- David Abrahams
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
        using reference = typename ::boost::mp11::mp_eval_if<
            ::boost::mp11::mp_if<
                ::std::is_function<value_type>
              , ::boost::mp11::mp_true
              , ::std::is_array<value_type>
            >
          , ::std::add_lvalue_reference<value_type>
          , ::boost::mp11::mp_identity
          , value_type
        >::type;
#else
        typedef typename ::boost::mpl::eval_if<
            typename ::boost::mpl::if_<
                ::boost::is_function<value_type>
              , ::boost::mpl::true_
              , ::boost::is_array<value_type>
            >::type
          , ::boost::add_lvalue_reference<value_type>
          , ::boost::mpl::identity<value_type>
        >::type reference;
#endif  // BOOST_PARAMETER_CAN_USE_MP11
    };
}} // namespace boost::parameter

#define BOOST_PARAMETER_TEMPLATE_KEYWORD(name)                               \
    namespace tag                                                            \
    {                                                                        \
        struct name;                                                         \
    }                                                                        \
    template <typename T>                                                    \
    struct name : ::boost::parameter::template_keyword<tag::name,T>          \
    {                                                                        \
    };
/**/

#endif  // include guard


text:
#include <assert.h>
#include <unistd.h>

#include <sstream>
//#include <boost/algorithm/string.hpp>
#include <algorithm> // for is_permutation
#include <tuple>
#include <functional>
#include <iterator>

#include "./permutation.h"

#include "./dm_english.h"
#include "./dm_perm.h"
#include "./sagemath_alter.h"

Permutation::Permutation(){}

Permutation::Permutation(const int n)
{
	if(n==-1) non_perm();
	else identify(n);
}

Permutation::Permutation(const std::vector<int> vec)
{
	std::vector<int>::const_iterator it;
	for(it = vec.begin() ; it != vec.end() ; ++it){
		perm.push_back(*it);
	}
	label.resize( length() );
	computeInverse();
// 	canonization();
}

// construct a canonical permutation for G (induced by modules)
// for parallel, series, prime modules.
Permutation::Permutation(const int n, const ModuleType type)
{
	switch(type){
	case FEUILLE:
		identify(1);
		break;
		      /*
		    case PREMIER:
			// This case will not be reached
		      prime(G);
		      break;
		      */
	case PARALLELE:
		identify(n);
		break;
	case SERIE:
		reverse(n);
		break;
	default:
		std::cerr << "Error! Strange the module type.\n\n";
	}
}

  // For a prime module.
  // ここで sagemath を使っている．
  // sagemath を使わなければ，1000倍は早くなるはず．
void Permutation::prime(const graphe G)
{
	std::vector< std::vector< int > > adj_matrix( G.n, std::vector< int >( G.n ) );
	for ( int i = 0; i < G.n; ++i )
	{
		for ( adj* adj_list = G.G[i]; adj_list != NULL; adj_list = adj_list->suiv )
		{
			const int j = adj_list->s;
			adj_matrix[i][j] = adj_matrix[j][i] = 1;
		}
	}

	std::vector< int > vec1, vec2;
	std::tie( vec1, vec2 ) = is_permutation_certificate( adj_matrix );
	if ( vec1.empty() )
	{
		non_perm();
		return;
	}

// #define D_PRIME

	label = vec1;
	// 正規化（一方の permutation を(1, 2, 3, ..., n)に変換）し，perm に格納
	std::vector<int> v1(vec1.size());
	for(int i=0 ; i<vec1.size() ; i++){
		v1[vec1[i]-1] = i+1;
	}
	for(int i=0 ; i<vec2.size() ; i++){
		perm.push_back(v1[vec2[i]-1]);
	}
	// -----（ここまで）出力データから二つの permutation を読み込んで正規化 -----

	canonization(); // 標準形に変換

}

void Permutation::identify(const int n)
{
	for(int i=0 ; i<n ; i++){
		perm.push_back(i+1);
	}
	computeInverse();
}

void Permutation::reverse(const int n)
{
	for(int i=n ; i>0 ; i--){
		perm.push_back(i);
	}
	computeInverse();
}

void Permutation::non_perm(){
	std::vector<int>().swap(perm);
	perm.push_back(-1);
}

  /******************************************/

void Permutation::canonization()
{
	std::vector<int> vecH = computeHorizontalFlip();
	std::vector<int> vecV = computeVerticalFlip();
	std::vector<int> vecR = computeRotation();

	computeInverse();

	if(is_SmallerEqual(vecH) && is_SmallerEqual(vecV) && is_SmallerEqual(vecR)){
		return;
	}

	if(is_small(vecH, vecV)){ // checked vecH < vecV
		if(is_small(vecH, vecR)){ // vecH < vecR
			perm = vecH;
			computeHorizontalFlip_label();
		}
		else{ // vecR < vecH
			perm = vecR;
			computeRotation_label();
		}
	}
	else{ // vecV < vecH
		if(is_small(vecV, vecR)){ // vecV < vecR
			perm = vecV;
			computeVerticalFlip_label();
		}
		else{ // vecR < vecV
			perm = vecR;
			computeRotation_label();
		}
	}

	computeInverse();
}

void Permutation::computeInverse()
{
	inverse.resize( length() );
	for ( int i = 0; i < length(); ++i )
	{
		inverse[ perm[i] - 1 ] = i + 1;
	}
	return;
}

void Permutation::computeHorizontalFlip_label()
{
// 	cerr << "H-flip" << endl;
	std::vector<int> vec(length());
	for(int i=0 ; i<length() ; i++){
		vec[pi(i)-1] = label[i];
// 		cerr << i << " -> " << perm[i] << endl;
	}
	label = vec;
}

std::vector<int> Permutation::computeHorizontalFlip() const
{
	std::vector<int> vec(length());
	for(int i=0 ; i<length() ; i++){
		vec[pi(i)-1] = i+1;
	}
	//perm = vec;
	return vec;
}

void Permutation::computeVerticalFlip_label()
{
	std::vector<int> vec(length());
	for(int i=0 ; i<length() ; i++){
		vec[length()-i-1] = label[i];
	}
	label = vec;
}

std::vector<int> Permutation::computeVerticalFlip() const
{
	std::vector<int> vec(length());
	for(int i=0 ; i<length() ; i++){
		vec[length()-i-1] = length() - pi(i) + 1;
	}
	//perm = vec;
	return vec;
}

std::vector<int> Permutation::computeVerticalFlip(std::vector<int> p) const
{
	assert(p.size()==length());
	std::vector<int> vec(length());
	for(int i=0 ; i<length() ; i++){
		vec[length()-i-1] = length() - p[i] + 1;
	}
	//perm = vec;
	return vec;
}

void Permutation::computeRotation_label()
{
	vector< int > vec( length() );
	for ( int i = 0; i < length(); ++i )
	{
		vec[ length() - inverse[i] ] = label[i];
	}
	label = vec;

// 	computeHorizontalFlip_label();
// 	computeVerticalFlip_label();
}

std::vector<int> Permutation::computeRotation() const
{
	std::vector<int> vecH = computeHorizontalFlip();
	std::vector<int> vec = computeVerticalFlip(vecH);
	return vec;
}

bool Permutation::is_canonical()
{
	Permutation p(perm);
	p.canonization();
	if(is_Smaller(p.perm)) return true;
	else return false;
}

bool Permutation::is_v_symmetry() const
{
	for(int i=0 ; i<length()/2 ; i++){
		if (perm[i] != length() - perm[length()-i-1] + 1){
// 			cerr << "i : " << i << endl;
// 			cerr << "perm[i] : " << perm[i] << endl;
// 			cerr << "length() - perm[length()-i-1] + 1) : " << length() - perm[length()-i-1] + 1 << endl;
			return false;
		}
	}
	return true;
}

bool Permutation::is_h_symmetry() const
{
	for ( int i = 0; i < length(); ++i )
	{
		if ( i != perm[ perm[i] - 1 ] - 1 )
		{
			return false;
		}
	}
	return true;
}

bool Permutation::is_rotational_symmetry() const
{
	std::vector<int> vecR = computeRotation();
	return is_equal(vecR);
}

bool Permutation::is_permutation()
{
	//std::cout << perm[0] << std::endl;
	if(perm[0] == -1) return false;
	else return true;
}

int Permutation::length() const
{
	return perm.size();
}

int Permutation::pi(int k) const
{
	return perm[k];
}

bool Permutation::operator==(const Permutation& p) const
{
	if(length() != p.length()) return false;

	for(int i=0 ; i<length() ; i++){
		if(perm[i] != p.pi(i)) return false;
	}
	return true;
}

bool Permutation::operator==(const std::vector<int>& vec) const
{
	if(length() != vec.size()) return false;

	for(int i=0 ; i<length() ; i++){
		if(perm[i] != vec[i]) return false;
	}
	return true;
}

bool Permutation::is_equal(const std::vector<int>& vec) const
{
	if(length() != vec.size()) return false;

	for(int i=0 ; i<length() ; i++){
		if(perm[i] != vec[i]) return false;
	}
	return true;
}

bool Permutation::operator<(const Permutation& p) const {

	if(length() < p.length()) return true;
	if(length() > p.length()) return false;

	for(int i=0 ; i<length() ; i++){
		if(perm[i] < p.pi(i)) return true;
		if(perm[i] > p.pi(i)) return false;
	}
	return false;
}

bool Permutation::is_Smaller(const std::vector<int>& vec) const
{
	if(length() < vec.size()) return true;
	if(length() > vec.size()) return false;

	for(int i=0 ; i<length() ; i++){
		if(perm[i] < vec[i]) return true;
		if(perm[i] > vec[i]) return false;
	}
	return false;
}

bool Permutation::is_SmallerEqual(const std::vector<int>& vec) const
{
	if(length() < vec.size()) return true;
	if(length() > vec.size()) return false;

	for(int i=0 ; i<length() ; i++){
		if(perm[i] < vec[i]) return true;
		if(perm[i] > vec[i]) return false;
	}
	return true;
}

bool Permutation::is_Smaller(const Permutation& p) const
{
	if(length() < p.length()) return true;
	if(length() > p.length()) return false;

	for(int i=0 ; i<length() ; i++){
		if(perm[i] < p.pi(i)) return true;
		if(perm[i] > p.pi(i)) return false;
	}
	return false;
}

bool Permutation::is_small(const std::vector<int> v1, const std::vector<int> v2) const
{
	if(v1.size() < v2.size()) return true;
	if(v1.size() > v2.size()) return false;

	for(int i=0 ; i<v1.size() ; i++){
		if(v1[i] < v2[i]) return true;
		if(v1[i] > v2[i]) return false;
	}
	return false;
}

bool Permutation::is_smallequal(const std::vector<int> v1, const std::vector<int> v2) const
{
	if(v1.size() < v2.size()) return true;
	if(v1.size() > v2.size()) return false;

	for(int i=0 ; i<v1.size() ; i++){
		if(v1[i] < v2[i]) return true;
		if(v1[i] > v2[i]) return false;
	}
	return true;
}

// for Prime module
void Permutation::merge(const std::vector<Permutation> p)
{

	vector< vector< int > > perms;
	for ( int i = 0; i < p.size(); ++i )
	{
		perms.push_back( p[i].perm );
	}

	vector< int > psum( length() + 1 );
	for ( int i = 0; i < length(); ++i )
	{
		psum[ i + 1 ] = perms[i].size();
	}
	//partial_sum( begin( psum ), end( psum ), begin( psum ) );

	for ( int i = 0, s = 0; i < length(); s += perms[ inverse[ i++ ] - 1 ].size() )
	{
		// 		cerr << "perms[ " << inverse[i] - 1 << " ]" << endl;
		// 		cerr << s << endl;
		transform( begin( perms[ inverse[i] - 1 ] ), end( perms[ inverse[i] - 1 ] ), begin( perms[ inverse[i] - 1 ] ), bind( plus< int >(), placeholders::_1, s ) );
	}

	vector< int > vec;
	for ( const auto &pp : perms )
	{

		copy( begin( pp ), end( pp ), back_inserter( vec ) );
// 				copy( begin( pp ), end( pp ), ostream_iterator< int >( cerr, " " ) );
// 				cerr << endl;
	}

	perm = vec;
	label.resize( perm.size() );
}

Permutation Permutation::parentPermutation() const
{
	std::vector< int > vec( perm );
	for ( int i = 0; i + 1 < length(); ++i )
	{
		if ( vec[i] < vec[ i + 1 ] )
		{
			std::swap( vec[i], vec[ i + 1 ] );
			break;
		}
	}

	Permutation p(vec);
// 	cerr << "parent permutation from : ";
// 	p.print();
	graphe G = p.makeGraphe();
	noeud *root = decomposition_modulaire( G );
	Permutation pp = createPermutation( root, G );
	return pp;
}

graphe Permutation::makeGraphe() const
{
	graphe G;
	G.n = length();
	G.G=(adj **)malloc(G.n*sizeof(adj *));
	for(int i=0 ; i<G.n ; i++) G.G[i] = NULL;

	for(int i=0 ; i<length() ; i++){
		for(int j=i+1 ; j<length() ; j++){
			if(perm[i] > perm[j]){
				// add an edge perm[i] to perm[j] (and its reversal).
				adj *a = (adj *)malloc(sizeof(adj));
				a->s = perm[j]-1;
				a->suiv = G.G[perm[i]-1];
				G.G[perm[i]-1] = a;

				a = (adj *)malloc(sizeof(adj)); a->s = perm[i]-1;
				a->suiv = G.G[perm[j]-1];
				G.G[perm[j]-1] = a;

			}
		}
	}
	return G;
}

void Permutation::print() const
{
	if(length()<1){
		std::cout << "length 0" << std::endl;
		return;
	}

	std::vector<int>::const_iterator it;
	for(it = perm.begin() ; it != perm.end() ; ++it){
		std::cout << *it << ( it + 1 != perm.end() ? ' ' : '\n' );
	}
	std::cout << std::flush;
}

void Permutation::print(std::ofstream &ofs) const
{
	if(length()<1){
		ofs << "length 0" << std::endl;
		return;
	}

	std::vector<int>::const_iterator it;
	for(it = perm.begin() ; it != perm.end() ; ++it){
		ofs << *it << ( it + 1 != perm.end() ? ' ' : '\n' );
	}
	ofs << std::flush;
}

void Permutation::print(std::ofstream &ofs, std::vector<int> vec) const
{
	if(vec.size()<1){
		ofs << "length 0" << std::endl;
		return;
	}

	std::vector<int>::const_iterator it;
	for(it = vec.begin() ; it != vec.end() ; ++it){
		ofs << *it << ( it + 1 != vec.end() ? ' ' : '\n' );
	}
	ofs << std::flush;
}

void Permutation::print(std::vector<int> vec)
{
	for(int i=0 ; i<vec.size() ; i++){
		std::cout << vec[i] << ( i + 1 < vec.size() ? ' ' : '\n' );
	}
	std::cout << std::endl;
}

max_stars_repo_name: toshikisaitoh/EnumPermGraphs

max_issues_repo_name: toshikisaitoh/EnumPermGraphs

max_forks_repo_name: toshikisaitoh/EnumPermGraphs


text:
#include "Exporter.hpp"
#ifdef WIN32
#include <direct.h>
#else
#include <unistd.h>
#endif //WIN32
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <algorithm>
#include <fstream>
using namespace std;

RHStandardExporter::RHStandardExporter(){
	hashGenerator = 0;
}

RHStandardExporter::~RHStandardExporter(){

}

void RHStandardExporter::SetHashGenerator(HashGenerator* generator){
	hashGenerator = generator;
}

void appendFilesToList(const path& p, vector<string>& actualFilesList, int level){
	directory_iterator end_itr;
	directory_iterator itr(p);
	while(itr!=end_itr){
		auto fnstring = itr->path().generic_string();
		if(  is_directory(itr->status())  ){
			appendFilesToList(itr->path(), actualFilesList, level+1);
		}else{
			actualFilesList.push_back(fnstring);
		}
		itr++;
	}
}

void RHStandardExporter::removeOmittedFromList(
	const ExportOptions& opts,
	std::vector<std::string>& list
)const{
	vector<mypair> pairs;
	vector<string> ignoredFileList;
	path rootPath(opts.exportRoothPath);
	rootPath = absolute(rootPath);
	auto exportRoothPath = rootPath.generic_string();
	if(exportRoothPath.back()!='/'){
		exportRoothPath+='/';
	}

	for(auto omittedFile:opts.omitFiles ){
		path omitFilePath(exportRoothPath+omittedFile);
		//path absolutePath = rootPath+omitFilePath;
		if(exists(omitFilePath)){
			mypair element;
			element.path = omitFilePath.generic_string();
			element.isDir = is_directory(omitFilePath);
			if(element.isDir){element.path+=('/');}
			pairs.push_back(element);
		}
	}
	//Ya se tiene la lista de elementos que eliminar de la lista
	//Ahora comparar la lista de archivos y quitarle los elementos a emitir
	for(auto omitFile:pairs){

		if(omitFile.isDir){
			bool continuar = true;
			while(continuar){
				continuar = false;
				bool deleteThisEntry = false;
				for(auto itr = list.begin();itr!=list.end();itr++){
					const auto& file = *itr;
					if(	(file.find(omitFile.path)==0) ){
						cout<<"Omitting dir: "<<file<<endl;
						list.erase(itr);
						continuar = true;
						break;
					}
				}
			};
		}else{
			auto itr = list.end();
			auto found = find(list.begin(), list.end(), omitFile.path);
			if(found!=itr){
				cout<<"Omitting: "<<omitFile.path<<endl;
				list.erase(found);
			}
		}
	}
}

int RHStandardExporter::Export(ExportOptions& opts, ExportResultStats& stats, ResultPackage& result){
	srand(static_cast<unsigned int>(time(0)));
	if(hashGenerator==0){
		cout<<"No se ha indicado un generador de Hash"<<endl;
		return Error_ExporterNotSet;
	}

	//Primer paso, pasar el directorio de trabajo a la ruta que se indico como rootPath
	//asi sera mas sencillo trabajar

	path exportPath(opts.exportRoothPath);
	if( !(exists(exportPath)&&is_directory(exportPath)) ){
		cout<<"No existe el directorio de origen: "<<opts.exportRoothPath<<endl;
		return Error_RootDirDoesntExist;
	}

	vector<string> fileNamesList;

	appendFilesToList(exportPath, fileNamesList, 0);
	stats.filesInRootDir = fileNamesList.size();
	//Eliminar archivos que no se van a esportar
	removeOmittedFromList(opts, fileNamesList);
	stats.filesExported = fileNamesList.size();

	vector<string> filenames_relativesToRoot;
	std::vector<ExportTupple> tupples;

	int pETRes = prepareExportTuples(opts, fileNamesList, filenames_relativesToRoot, tupples, stats);
	if(pETRes<0){
		return pETRes;
	}

	//Generar los hashes de los nombres completos de los paths
	bool generateHashes = true;
	HashType32 seed = rand();
	const HashType32 originalSeed = seed;
	while(generateHashes){

		for(auto& element:tupples){
			element.hash = hashGenerator->GenerateHash32(
				(void*)element.url.c_str(),
				element.url.length(),
				seed
			);
		}
		//hashes generados, ahora segurarnos de que no hayan colisiones
		if(doesListHasDuplicatedHashesQ(tupples)){
			seed++;
			if(seed == originalSeed){
				cout<<"ERROR: no se puede generar una tabalhash sin colisiones con el algoritmo actual"<<endl;
				return Error_TableGenerationImpossible;
			}
		}else{
			generateHashes = false;
			stats.exportSeed = seed;
		}

	}
	//Hasta ahora ya se han generado la lista de URLs a responder
	//Hay que ordenar la lista con respecto a los hashes generados
	std::stable_sort(
		begin(tupples),
		end(tupples),
		[] (const ExportTupple& a, const ExportTupple& b) {return a.hash < b.hash;}
	);

	generateFinalResult(
		opts,
		fileNamesList,
		tupples,
		stats,
		result
	);

	//Creamos el archivo donde almacenar el resultado
	bool ioerror = false;
	ofstream file;
	file.open(opts.output, ios::out|ios::binary|ios::trunc);
	bool isOpendQ = file.is_open();
	ioerror = file.good();
	//Almacenamos el size de los datos
	int resultSize = result.Size();
	file.write((char*)&resultSize, 4);
	ioerror = file.bad();
	//Almacenamos el numero de tuplas
	int tupplesN = tupples.size();
	file.write((char*)&tupplesN, 4);
	//Almacenamos la semilla usada
	HashType32 exportSeed = stats.exportSeed;
	file.write((char*)&exportSeed, 4);
	ioerror = file.bad();

	file.write((char*)&stats.exportHomeFileIndex, 4);
	file.write((char*)&stats.exportErrorFileIndex, 4);

	ioerror = file.bad();
	//Y almacenamso finalmente la tabla
	file.write(result.GetData(), result.Size());
	ioerror = file.bad();
	file.close();

	return 0;
}

bool RHStandardExporter::doesListHasDuplicatedHashesQ(const std::vector<ExportTupple>& list)const{
	bool ret = false;
	for(size_t e = 0; e<list.size(); e++){
		const auto& element = list[e];
		for(size_t p = 0; p<list.size(); p++){
			const auto& listEntry = list[p];
			if(p==e){
				continue;
			}
			if(listEntry.hash==element.hash){
				ret = true;
				break;
			}
		}
	}
	return ret;;
}

int RHStandardExporter::prepareExportTuples(
	const ExportOptions& opts,
	std::vector<std::string>& list,
	std::vector<std::string>& filenames_relativesToRoot,
	std::vector<ExportTupple>& tupples,
	ExportResultStats& stats
)const{
	path rootPath(opts.exportRoothPath);
	rootPath = absolute(rootPath);
	auto exportRoothPath = rootPath.generic_string();
	if(exportRoothPath.back()!='/'){
		exportRoothPath+='/';
	}
	//vector<string> filenames_relativesToRoot;
	filenames_relativesToRoot.clear();
	filenames_relativesToRoot.reserve(list.size());
	for(auto file:list){
		path filePath(file);
		filePath = absolute(filePath);
		auto filePathName = filePath.generic_string();
		filenames_relativesToRoot.push_back(
			filePathName.substr(exportRoothPath.length())
		);
	}

	//buscar archivos especiales en la lista de archivos
	for( size_t e = 0; e<filenames_relativesToRoot.size(); e++){
		const auto& fileName = filenames_relativesToRoot[e];
		if(fileName==opts.homeFile){
			stats.exportHomeFileIndex = e;
			break;
		}
	}
	if(stats.exportHomeFileIndex<0){
		cout<<"No se pudo encontrar el archivo HOME: "<<opts.homeFile<<endl;
		return Error_FileNotFound;
	}
	//buscar archivos especiales en la lista de archivos
	for( size_t e = 0; e<filenames_relativesToRoot.size(); e++){
		const auto& fileName = filenames_relativesToRoot[e];
		if(fileName==opts.error404File){
			stats.exportErrorFileIndex = e;
			break;
		}
	}
	if(stats.exportHomeFileIndex<0){
		cout<<"No se pudo encontrar el archivo ERROR404: "<<opts.error404File<<endl;
		return Error_FileNotFound;
	}

	//Generar las tuplas
	tupples.clear();
	tupples.reserve(filenames_relativesToRoot.size()*2+2);

	for( size_t e = 0; e<filenames_relativesToRoot.size(); e++){
		const auto& fileName = filenames_relativesToRoot[e];
		ExportTupple tupple1;
		ExportTupple tupple2;
		tupple1.url = fileName;
		tupple2.url = "/"+fileName;
		tupple1.listIndex = tupple2.listIndex = e;
		tupples.push_back(tupple1);
		tupples.push_back(tupple2);
	}
	//buscar archivos especiales en la lista de archivos
	for( size_t e = 0; e<filenames_relativesToRoot.size(); e++){
		const auto& fileName = filenames_relativesToRoot[e];
		if(fileName==opts.homeFile){
			stats.exportHomeFileIndex = e;
		}
	}

	ExportTupple homeTupple1;
	//ExportTupple homeTupple2;
	homeTupple1.url = "/";
	//homeTupple2.url = "/"+opts.homeFile;
	//homeTupple1.listIndex = homeTupple2.listIndex = stats.exportHomeFileIndex;
	homeTupple1.listIndex = stats.exportHomeFileIndex;

	/*ExportTupple errorTupple;
	errorTupple.url = opts.error404File;
	errorTupple.listIndex = stats.exportErrorFileIndex;*/

	tupples.push_back(homeTupple1);
	//tupples.push_back(errorTupple);

	return 0;
}

max_stars_repo_name: RaulHuertas/rhpackageexporter

max_issues_repo_name: RaulHuertas/rhpackageexporter

max_forks_repo_name: RaulHuertas/rhpackageexporter