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

#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
#include <boost/utility/string_view.hpp>
#include <cstdlib>
#include <iostream>
#include <unordered_map>
#include <string>
#include <vector>

#include <daw/daw_bounded_stack.h>

#include "data_types.h"

std::pair<std::string, std::string> parse_kv_string( boost::string_view line ) {
	daw::bounded_stack_t<char, 2> ch_stack;
	bool in_quote = false;
	for( size_t pos=0; pos<line.size( ); ++pos ) {
		switch( line[pos] ) {
			case '\\':
				ch_stack.push_back( '\\' );
			break;
			case '\"': {
				ch_stack.push_back( '\"' );
				break;
			}
			case '=':
				if( !in_quote ) {
					auto sep = std::next( line.begin( ), static_cast<std::iterator_traits<decltype(line.begin( ))>::difference_type>(pos) );
					return { boost::trim_copy( std::string{ line.begin( ), sep } ), boost::trim_copy( std::string{ std::next( sep ), line.end( ) } ) };
				}
				break;
		}
		if( !ch_stack.empty( ) ) {
			if( ch_stack.front( ) == '\\' ) {
				if( ch_stack.used( ) == 2 ) {
					ch_stack.clear( );
				}
			} else if( ch_stack.front( ) == '\"' ) {
				in_quote = !in_quote;
				ch_stack.clear( );
			}
		}
	}
	return { boost::trim_copy( std::string{ line.begin( ), line.end( ) } ), "" };
}

struct parameters {
	std::vector<std::string> ordered_parameters;
	std::unordered_map<std::string, std::string> optional_parameters;

	template<typename T>
	T ordered_as( size_t n ) const {
		return boost::lexical_cast<T>( ordered_parameters.at( n ) );
	}

	boost::optional<std::string> kv_get( boost::string_view key ) const {
		auto it = optional_parameters.find( key.to_string( ) );
		if( it != optional_parameters.end( ) ) {
			return { it->second };
		}
		return { };
	}

	size_t ordered_count( ) const {
		return ordered_parameters.size( );
	}
};

parameters parse_cmd_line( int const argc, char const * const * argv ) {
	parameters result;
	for( int n=1; n<argc; ++n ) {
		if( boost::starts_with( argv[n], "--" ) ) {
			result.optional_parameters.insert( parse_kv_string( argv[n] + 2 ) );
		} else {
			result.ordered_parameters.emplace_back( argv[n] );
		}
	}
	return result;
}

struct unnamed_parameters {
	std::vector<std::string> required;
	std::vector<std::string> optional;

	unnamed_parameters( std::vector<std::string> Required, std::vector<std::string> Optional ):
			required{ std::move( Required ) },
			optional{ std::move( Optional ) } { }

	boost::optional<std::string> find( parameters const & param, std::string const & key ) const {
		{
			auto const pos = std::find( required.begin( ), required.end( ), key );
			if( pos != required.end( ) ) {
				auto const dist = static_cast<size_t>(std::distance( required.begin( ), pos ));
				return { param.ordered_parameters[dist] };
			}
		}
		auto const pos = std::find( optional.begin( ), optional.end( ), key );
		if( pos == optional.end( ) ) {
			return { };
		}
		auto const dist = static_cast<size_t>(std::distance( optional.begin( ), pos )) + required.size( );
		return { param.ordered_parameters[dist] };
	}
};

void show_help( char const * name, unnamed_parameters const & unnamed ) {
	std::cout << name;
	for( auto const & param: unnamed.required ) {
		std::cout << " <" << param << ".json>";
	}
	for( auto const & param: unnamed.optional ) {
		std::cout << " [" << param << ".json]";
	}
	std::cout << "\nOptional Parameters\n--------------------\n";
	std::cout << "--help - Display this help message\n";
	std::cout << "--model=<pump model> - Model of pump\n";
	std::cout << "--exportDefaults\n";
	std::cout << "--updatePreferences=<true|false>" << std::endl;
}

int main( int argc, char** argv ) {
	auto const params = parse_cmd_line( argc, argv );
	unnamed_parameters const unnamed{ { "pump_settings", "bg_targets", "insulin_sensitivities", "basal_profile" }, { "preferencces", "carb_ratios", "temp_targets" } };

	if( params.kv_get( "help" ) ) {
		show_help( argv[0], unnamed );
		return EXIT_SUCCESS;
	}
	auto const model = params.kv_get( "model" );

	if( params.kv_get( "exportDefaults" ) ) {
		std::cout << (ns::profile_t{ }).to_string( ) << std::endl;
		return EXIT_SUCCESS;
	} else if( params.kv_get( "updatePreferences" ) ) {
		auto const prefs_file_name = params.kv_get( "updatePreferences" );
		if( prefs_file_name && !prefs_file_name->empty( ) ) {
			boost::filesystem::path const pref_file{ *prefs_file_name };
			if( exists( pref_file ) && is_regular_file( pref_file ) ) {
				try {
					auto prefs = daw::json::from_file<ns::profile_t>( pref_file.native( ) );
					std::cout << prefs.to_string( ) << std::endl;
					return EXIT_SUCCESS;
				} catch( std::exception const & ex ) {
					std::cerr << "Error importing prefernces\n" << ex.what( ) << std::endl;
					exit( EXIT_FAILURE );
				}
			}
		}
		std::cout << (ns::profile_t{ }).to_string( ) << std::endl;
		return EXIT_SUCCESS;
	}

	if( params.ordered_count( ) < unnamed.required.size( ) || params.ordered_count( ) > (unnamed.required.size( ) + unnamed.optional.size( )) ) {
		show_help( argv[0], unnamed );
		return EXIT_SUCCESS;
	}
	return EXIT_SUCCESS;
}


text:
/* Copyright (C) 2014 InfiniDB, Inc.

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; version 2 of
   the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
   MA 02110-1301, USA. */

/*
 * A tool that can take a csv file of extent map entires and produce a BRM_saves_em-compatible file.
 * If you re-compile extentmap.cpp to dump the extent map as it loads, you'll get a csv file on stdout.
 * Save this to a file and edit it as needed (remove the cruft at the top & bottom for sure). Then use
 * this tool to create a binary BRM_saves_em file.
 *
 * compile with
 * g++ -g -Wall -o load_brm_from_file -I$HOME/genii/export/include -I/usr/include/libxml2 load_brm_from_file.cpp
 *
*/
#include <iostream>
#include <stdint.h>
#include <fstream>
#include <cerrno>
#include <string>
#include <cstdlib>
//#define NDEBUG
#include <cassert>
#include <limits>
using namespace std;

#include <boost/tokenizer.hpp>
using namespace boost;

#include "extentmap.h"
using namespace BRM;

#define EM_MAGIC_V4 0x76f78b1f

namespace BRM
{
EMEntry::EMEntry()
{
    fileID = 0;
    blockOffset = 0;
    HWM = 0;
    partitionNum = 0;
    segmentNum   = 0;
    dbRoot       = 0;
    colWid       = 0;
    status		= 0;
}
EMCasualPartition_struct::EMCasualPartition_struct()
{
    lo_val = numeric_limits<int64_t>::min();
    hi_val = numeric_limits<int64_t>::max();
    sequenceNum = 0;
    isValid = CP_INVALID;
}
}

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

    int loadSize[3];

    if (argc < 2)
    {
        cerr << "filename arg needed" << endl;
        return 1;
    }

    ifstream in(argv[1]);
    e = errno;

    if (!in)
    {
        cerr << "file read error: " << strerror(e) << endl;
        return 1;
    }

    //Brute force count the number of lines
    int numEMEntries = 0;

    string line;

    getline(in, line);

    while (!in.eof())
    {
        numEMEntries++;
        getline(in, line);
    }

    //start at the beginning again...
    in.clear();
    in.seekg(0, ios_base::beg);

    idbassert(in.good());
    idbassert(in.tellg() == static_cast<streampos>(0));

    string outname(argv[1]);
    outname += ".out";

    ofstream out(outname.c_str());
    e = errno;

    if (!out)
    {
        cerr << "file write error: " << strerror(e) << endl;
        return 1;
    }

    loadSize[0] = EM_MAGIC_V4;
    loadSize[1] = numEMEntries;
    loadSize[2] = 1; //one free list entry
    out.write((char*)&loadSize, (3 * sizeof(int)));

    InlineLBIDRange fl;
    fl.start = 0;
    //the max lbid is 2^54-1, the size is in units of 1k
    fl.size = numeric_limits<uint32_t>::max();

    InlineLBIDRange maxLBIDinUse;
    maxLBIDinUse.start = 0;
    maxLBIDinUse.size = 0;

    getline(in, line);

    while (!in.eof())
    {
        EMEntry em;
        int64_t v;
        tokenizer<> tok(line);
        tokenizer<>::iterator beg = tok.begin();
#if 0
        emSrc[i].range.start
                << '\t' << emSrc[i].range.size
                << '\t' << emSrc[i].fileID
                << '\t' << emSrc[i].blockOffset
                << '\t' << emSrc[i].HWM
                << '\t' << emSrc[i].partitionNum
                << '\t' << emSrc[i].segmentNum
                << '\t' << emSrc[i].dbRoot
                << '\t' << emSrc[i].colWid
                << '\t' << emSrc[i].status
                << '\t' << emSrc[i].partition.cprange.hi_val
                << '\t' << emSrc[i].partition.cprange.lo_val
                << '\t' << emSrc[i].partition.cprange.sequenceNum
                << '\t' << (int)(emSrc[i].partition.cprange.isValid)
#endif
                v = strtoll(beg->c_str(), 0, 0);
        ++beg;
        em.range.start = v;

        v = strtoll(beg->c_str(), 0, 0);
        ++beg;
        em.range.size = v;

        if (em.range.start > maxLBIDinUse.start)
        {
            maxLBIDinUse.start = em.range.start;
            maxLBIDinUse.size = em.range.size;
        }

        v = strtoll(beg->c_str(), 0, 0);
        ++beg;
        em.fileID = v;

        v = strtoll(beg->c_str(), 0, 0);
        ++beg;
        em.blockOffset = v;

        v = strtoll(beg->c_str(), 0, 0);
        ++beg;
        em.HWM = v;

        v = strtoll(beg->c_str(), 0, 0);
        ++beg;
        em.partitionNum = v;

        v = strtoll(beg->c_str(), 0, 0);
        ++beg;
        em.segmentNum = v;

        v = strtoll(beg->c_str(), 0, 0);
        ++beg;
        em.dbRoot = v;

        v = strtoll(beg->c_str(), 0, 0);
        ++beg;
        em.colWid = v;

        v = strtoll(beg->c_str(), 0, 0);
        ++beg;
        em.status = v;

        v = strtoll(beg->c_str(), 0, 0);
        ++beg;
        em.partition.cprange.hi_val = v;

        v = strtoll(beg->c_str(), 0, 0);
        ++beg;
        em.partition.cprange.lo_val = v;

        v = strtoll(beg->c_str(), 0, 0);
        ++beg;
        em.partition.cprange.sequenceNum = v;

        v = strtoll(beg->c_str(), 0, 0);
        ++beg;
        em.partition.cprange.isValid = v;

        out.write((char*)&em, sizeof(em));

        getline(in, line);
    }

    fl.start = maxLBIDinUse.start + maxLBIDinUse.size * 1024;
    fl.size -= fl.start / 1024;

    out.write((char*)&fl, sizeof(fl));

    out.close();
    in.close();

    return 0;
}

ext: cpp

max_stars_repo_name: zettadb/zettalib

max_issues_repo_name: zettadb/zettalib

max_forks_repo_name: zettadb/zettalib


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2007 François du Vignaud

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#ifndef quantlib_tap_correlations_hpp
#define quantlib_tap_correlations_hpp

#include <ql/types.hpp>
#include <ql/utilities/disposable.hpp>
#include <ql/math/matrix.hpp>
#include <ql/math/optimization/costfunction.hpp>
#include <boost/function.hpp>
#include <vector>

namespace QuantLib {

    //! Returns the Triangular Angles Parametrized correlation matrix
    /*! The matrix \f$ m \f$ is filled with values corresponding to angles
        given in the \f$ angles \f$ vector. See equation (24) in
        "Parameterizing correlations: a geometric interpretation"
        by Francesco Rapisarda, Damiano Brigo, Fabio Mercurio

        \test
        - the correctness of the results is tested by reproducing
          known good data.
        - the correctness of the results is tested by checking
          returned values against numerical calculations.
    */
    Disposable<Matrix>
    triangularAnglesParametrization(const Array& angles,
                                    Size matrixSize,
                                    Size rank);

    Disposable<Matrix>
    lmmTriangularAnglesParametrization(const Array& angles,
                                       Size matrixSize,
                                       Size rank);

    // the same function using the angles parameterized by the following
    // transformation \f[ \teta_i = \frac{\Pi}{2} - arctan(x_i)\f]
    Disposable<Matrix>
    triangularAnglesParametrizationUnconstrained(const Array& x,
                                                 Size matrixSize,
                                                 Size rank);

    Disposable<Matrix>
    lmmTriangularAnglesParametrizationUnconstrained(const Array& x,
                                                    Size matrixSize,
                                                    Size rank);

    //! Returns the rank reduced Triangular Angles Parametrized correlation matrix
    /*! The matrix \f$ m \f$ is filled with values corresponding to angles
        corresponding  to the 3D spherical spiral paramterized by
        \f$ alpha \f$, \f$ t0 \f$, \f$ epsilon \f$ values. See equation (32) in
        "Parameterizing correlations: a geometric interpretation"
        by Francesco Rapisarda, Damiano Brigo, Fabio Mercurio

        \test
        - the correctness of the results is tested by reproducing
          known good data.
        - the correctness of the results is tested by checking
          returned values against numerical calculations.
    */
    Disposable<Matrix>
    triangularAnglesParametrizationRankThree(Real alpha,
                                             Real t0,
                                             Real epsilon,
                                             Size nbRows);

    // the same function with parameters packed in an Array
    Disposable<Matrix>
    triangularAnglesParametrizationRankThreeVectorial(const Array& paramters,
                                                      Size nbRows);

    // Cost function associated with Frobenius norm.
    // <http://en.wikipedia.org/wiki/Matrix_norm>
    class FrobeniusCostFunction : public CostFunction{
      public:
        FrobeniusCostFunction(
            const Matrix& target,
            const boost::function<Disposable<Matrix>(const Array&,
                                                     Size,
                                                     Size)>& f,
                                                     Size matrixSize,
                                                     Size rank)
        : target_(target), f_(f), matrixSize_(matrixSize), rank_(rank) {}
        Real value (const Array &x) const;
        Disposable<Array> values (const Array &x) const;
      private:
        Matrix target_;
        boost::function<Disposable<Matrix>(const Array&, Size, Size)> f_;
        Size matrixSize_;
        Size rank_;
    };
}

/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2007 François du Vignaud

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#include <cmath>

namespace QuantLib {

    inline Disposable<Matrix> triangularAnglesParametrization(const Array& angles,
                                                       Size matrixSize,
                                                       Size rank) {

        // what if rank == 1?
        QL_REQUIRE((rank-1) * (2*matrixSize - rank) == 2*angles.size(),
                    "rank-1) * (matrixSize - rank/2) == angles.size()");
        Matrix m(matrixSize, matrixSize);

        // first row filling
        m[0][0] = 1.0;
        for (Size j=1; j<matrixSize; ++j)
            m[0][j] = 0.0;

        // next ones...
        Size k = 0; //angles index
        for (Size i=1; i<m.rows(); ++i) {
            Real sinProduct = 1.0;
            Size bound = std::min(i,rank-1);
            for (Size j=0; j<bound; ++j) {
                m[i][j] = std::cos(angles[k]);
                m[i][j] *= sinProduct;
                sinProduct *= std::sin(angles[k]);
                ++k;
            }
            m[i][bound] = sinProduct;
            for (Size j=bound+1; j<m.rows(); ++j)
                m[i][j] = 0;
        }
        return m;
    }

    inline Disposable<Matrix> lmmTriangularAnglesParametrization(const Array& angles,
                                                          Size matrixSize,
                                                          Size) {
        Matrix m(matrixSize, matrixSize);
        for (Size i=0; i<m.rows(); ++i) {
            Real cosPhi, sinPhi;
            if (i>0) {
                cosPhi = std::cos(angles[i-1]);
                sinPhi = std::sin(angles[i-1]);
            } else {
                cosPhi = 1.0;
                sinPhi = 0.0;
            }

            for (Size j=0; j<i; ++j)
                m[i][j] = sinPhi * m[i-1][j];

            m[i][i] = cosPhi;

            for (Size j=i+1; j<m.rows(); ++j)
                m[i][j] = 0.0;
        }
        return m;
    }

    inline Disposable<Matrix> triangularAnglesParametrizationUnconstrained(
                                                            const Array& x,
                                                            Size matrixSize,
                                                            Size rank) {
        Array angles(x.size());
        //we convert the unconstrained parameters in angles
        for (Size i = 0; i < x.size(); ++i)
            angles[i] = M_PI*.5 - std::atan(x[i]);
        return triangularAnglesParametrization(angles, matrixSize, rank);
    }

    inline Disposable<Matrix> lmmTriangularAnglesParametrizationUnconstrained(
                                                            const Array& x,
                                                            Size matrixSize,
                                                            Size rank) {
        Array angles(x.size());
        //we convert the unconstrained parameters in angles
        for (Size i = 0; i < x.size(); ++i)
            angles[i] = M_PI*.5 - std::atan(x[i]);
        return lmmTriangularAnglesParametrization(angles, matrixSize, rank);
    }

    inline Disposable<Matrix> triangularAnglesParametrizationRankThree(
                                            Real alpha, Real t0,
                                            Real epsilon, Size matrixSize) {
        Matrix m(matrixSize, 3);
        for (Size i=0; i<m.rows(); ++i) {
            Real t = t0 * (1 - std::exp(epsilon*Real(i)));
            Real phi = std::atan(alpha * t);
            m[i][0] = std::cos(t)*std::cos(phi);
            m[i][1] = std::sin(t)*std::cos(phi);
            m[i][2] = -std::sin(phi);
        }
        return m;
    }

    inline Disposable<Matrix> triangularAnglesParametrizationRankThreeVectorial(
                                                    const Array& parameters,
                                                    Size nbRows) {
        QL_REQUIRE(parameters.size() == 3,
                   "the parameter array must contain exactly 3 values" );
        return triangularAnglesParametrizationRankThree(parameters[0],
                                                        parameters[1],
                                                        parameters[2],
                                                        nbRows);

    }

  inline Real FrobeniusCostFunction::value(const Array& x) const {
        Array temp = values(x);
        return DotProduct(temp, temp);
    }

  inline Disposable<Array> FrobeniusCostFunction::values(const Array& x) const {
        Array result((target_.rows()*(target_.columns()-1))/2);
        Matrix pseudoRoot = f_(x, matrixSize_, rank_);
        Matrix differences = pseudoRoot * transpose(pseudoRoot) - target_;
        Size k = 0;
        // then we store the elementwise differences in a vector.
        for (Size i=0; i<target_.rows(); ++i) {
            for (Size j=0; j<i; ++j){
                result[k] = differences[i][j];
                ++k;
            }
        }
        return result;
    }
}

#endif

ext: hpp

max_stars_repo_name: markxio/Quantuccia

max_issues_repo_name: markxio/Quantuccia

max_forks_repo_name: markxio/Quantuccia


text:
/*
    Copyright (c) 2002-2010 Tampere University.

    This file is part of TTA-Based Codesign Environment (TCE).

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
 */
/**
 * @file BasicBlockScheduler.hh
 *
 * Declaration of BasicBlockScheduler class.
 *
 * @author Pekka J��skel�inen 2006,2010 (pjaaskel-no.spam-cs.tut.fi)
 * @author Fabio Garzia 2010 (fabio.garzia-no.spam-tut.fi)
 * @note rating: red
 */

#ifndef TTA_BB_SCHEDULER_HH
#define TTA_BB_SCHEDULER_HH

#include <boost/timer.hpp>
#include <boost/progress.hpp>

#include "MoveNodeSelector.hh"
#include "DDGPass.hh"
#include "BasicBlockPass.hh"
#include "DataDependenceGraph.hh"

class SimpleResourceManager;
class SoftwareBypasser;
class LLVMTCECmdLineOptions;
class RegisterRenamer;
class MoveNode;
class MoveNodeGroup;
class LLVMTCECmdLineOptions;

namespace TTAMachine {
    class Unit;
    class Port;
    class RegisterFile;
}

/**
 * A class that implements the functionality of a basic block scheduler.
 *
 * Schedules the program one basic block at a time. Does not fill delay slots
 * if they couldn't be filled with the basic block's contents itself (no
 * instruction importing).
 */
class BasicBlockScheduler :
    public DDGPass, public BasicBlockPass {
public:
    BasicBlockScheduler(
        InterPassData& data, SoftwareBypasser* bypasser=NULL,
        RegisterRenamer* renamer=NULL);

    virtual ~BasicBlockScheduler();

    virtual int handleDDG(
        DataDependenceGraph& ddg, SimpleResourceManager& rm,
        const TTAMachine::Machine& targetMachine, int minCycle = 0,
        bool testOnly = false) override;

    virtual int handleLoopDDG(
        DataDependenceGraph& ddg, SimpleResourceManager& rm,
        const TTAMachine::Machine& targetMachine, int tripCount,
        SimpleResourceManager* prologRM, bool testOnly = false) override;

    virtual std::string shortDescription() const;
    virtual std::string longDescription() const;

    virtual void printStats() const;

    using BasicBlockPass::ddgBuilder;

    static MoveNode* findTrigger(
        const ProgramOperation& po,
        const TTAMachine::Machine& mach);

protected:
    void scheduleRRMove(MoveNode& moveNode);

    void scheduleOperation(MoveNodeGroup& moves);

    int scheduleOperandWrites(int& cycle, MoveNodeGroup& moves);

    bool scheduleResultReads(MoveNodeGroup& moves);

    void scheduleMove(
        MoveNode& move, int earliestCycle, bool allowPredicationAndRenaming);

    void scheduleRRTempMoves(
        MoveNode& regToRegMove, MoveNode& firstMove, int lastUse);

    void scheduleInputOperandTempMoves(
        MoveNode& operandMove, MoveNode& operandWrite);

    void unschedule(MoveNode& moveNode);

    void unscheduleAllNodes();

    void unscheduleInputOperandTempMoves(MoveNode& operandMove);

    void scheduleResultReadTempMoves(
        MoveNode& resultMove, MoveNode& resultRead, int lastUse);

    void unscheduleResultReadTempMoves(MoveNode& resultMove);

    void notifyScheduled(MoveNodeGroup& moves, MoveNodeSelector& selector);

    void ddgSnapshot(
        DataDependenceGraph& ddg, const std::string& name,
        DataDependenceGraph::DumpFileFormat format, bool final,
        bool resetCounter = false) const;

    MoveNode* succeedingTempMove(MoveNode& current);

    static MoveNode* findTriggerFromUnit(
        const ProgramOperation& po, const TTAMachine::Unit& unit);

    int getTriggerOperand(
        const Operation& operation, const TTAMachine::Machine& machine);

    bool tryToSwitchInputs(ProgramOperation& op);

    void handleRemovedResultMoves(
        std::set<std::pair<TTAProgram::Move*, int> > removedMoves);

    bool tryToOptimizeWaw(const MoveNode& moveNode);

    void tryToDelayOperands(MoveNodeGroup& moves);

    /// The target machine we are scheduling the program against.
    const TTAMachine::Machine* targetMachine_;
    /// DDG of the currently scheduled BB.
    DataDependenceGraph* ddg_;
    /// Resource Manager of the currently scheduled BB.
    SimpleResourceManager* rm_;
    /// Stores the MoveNodes that were scheduled as temp moves during
    /// scheduling of the operand move.
    std::map<const MoveNode*, DataDependenceGraph::NodeSet> scheduledTempMoves_;
    /// The software bypasser to use to bypass registers when possible.
    SoftwareBypasser* softwareBypasser_;

    RegisterRenamer* renamer_;

    /// The earliest cycle to schedule moves in. Used to leave room for
    /// sched_yield() by the sched_yield() emitter.
    int minCycle_;

    MoveNodeSelector* selector_;
    /// Time for getting the scheduling time for current basic block.
    boost::timer schedulingTime_;
    int bypassedCount_;
    int deadResults_;

    LLVMTCECmdLineOptions* options_;

    MoveNode* jumpNode_;

    int tripCount_;
};

#endif

ext: hh

max_stars_repo_name: kanishkan/tce

max_issues_repo_name: kanishkan/tce

max_forks_repo_name: kanishkan/tce


text:
#ifndef HERMIT_UTF8_HPP
#define HERMIT_UTF8_HPP

#include <string>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/qi.hpp>

namespace hermit {
  namespace grammar {
    template <typename InputIterator>
    class  :
      public boost::spirit::qi::grammar< InputIterator, char32_t() > {
      public:
      parser_rule() : paeser_rule::base_type( root ) {
        using namespace boost::spirit;
        continous = byte_[
          qi::_pass = ( qi::_1 & 0xC0 ) == 0x80,
          qi::_val = qi::_1 & 0x3F
            ];
        block1_head = byte_[
          qi::_pass = ( qi::_1 & 0xE0 ) == 0xC0,
          qi::_val = qi::_1 & 0x1F
            ];
        block2_head = byte_[
          qi::_pass = ( qi::_1 & 0xF0 ) == 0xE0,
          qi::_val = qi::_1 & 0x0F
            ];
        block3_head = byte_[
          qi::_pass = ( qi::_1 & 0xF8 ) == 0xF0,
          qi::_val = qi::_1 & 0x07
            ];
        block4_head = byte_[
          qi::_pass = ( qi::_1 & 0xFC ) == 0xF8,
          qi::_val = qi::_1 & 0x03
            ];
        block5_head = byte_[
          qi::_pass = ( qi::_1 & 0xFE ) == 0xFC,
          qi::_val = qi::_1 & 0x01
            ];
        root =
          byte_[ qi::_pass = qi::_1 < 0x80, qi::_val = qi::_1 ]|
          ( block1_head >> continous )[
          qi::_val = boost::phoenix::static_cast_<char32_t>( qi::_1 ) << 6|
          boost::phoenix::static_cast_<char32_t>( qi::_2 )
          ]|
          ( block2_head >> continous >> continous )[
          qi::_val = boost::phoenix::static_cast_<char32_t>( qi::_1 ) << 12|
          boost::phoenix::static_cast_<char32_t>( qi::_2 ) << 6|
          boost::phoenix::static_cast_<char32_t>( qi::_3 )
          ]|
          ( block3_head >> continous >> continous >> continous )[
          qi::_val = boost::phoenix::static_cast_<char32_t>( qi::_1 ) << 18|
          boost::phoenix::static_cast_<char32_t>( qi::_2 ) << 12|
          boost::phoenix::static_cast_<char32_t>( qi::_3 ) << 6|
          boost::phoenix::static_cast_<char32_t>( qi::_4 )
          ]|
          ( block4_head >> continous >> continous >> continous >> continous )[
          qi::_val = boost::phoenix::static_cast_<char32_t>( qi::_1 ) << 24|
          boost::phoenix::static_cast_<char32_t>( qi::_2 ) << 18|
          boost::phoenix::static_cast_<char32_t>( qi::_3 ) << 12|
          boost::phoenix::static_cast_<char32_t>( qi::_4 ) << 6|
          boost::phoenix::static_cast_<char32_t>( qi::_5 )
          ]|
          ( block5_head >> continous >> continous >> continous >> continous >> continous )[
          qi::_val = boost::phoenix::static_cast_<char32_t>( qi::_1 ) << 30|
          boost::phoenix::static_cast_<char32_t>( qi::_2 ) << 24|
          boost::phoenix::static_cast_<char32_t>( qi::_3 ) << 18|
          boost::phoenix::static_cast_<char32_t>( qi::_4 ) << 12|
          boost::phoenix::static_cast_<char32_t>( qi::_5 ) << 6|
          boost::phoenix::static_cast_<char32_t>( qi::_6 )
          ];
      }
    private:
      boost::spirit::qi::rule< InputIterator, uint8_t() > continous;
      boost::spirit::qi::rule< InputIterator, uint8_t() > block1_head;
      boost::spirit::qi::rule< InputIterator, uint8_t() > block2_head;
      boost::spirit::qi::rule< InputIterator, uint8_t() > block3_head;
      boost::spirit::qi::rule< InputIterator, uint8_t() > block4_head;
      boost::spirit::qi::rule< InputIterator, uint8_t() > block5_head;
      boost::spirit::qi::rule< InputIterator, char32_t() > root;
  };

template <typename InputIterator>
class utf8string_to_u32string :
  public boost::spirit::qi::grammar< InputIterator, std::u32string() > {
    public:
      utf8string_to_u32string() : utf8string_to_u32string::base_type( root ) {
        using namespace boost::spirit;
        root = *char32_;
      }
    private:
      utf8_to_ucs4< InputIterator > char32_;
      boost::spirit::qi::rule< InputIterator, std::u32string() > root;
};
template< typename OutputIterator >
class ucs4_to_utf8 :
  public boost::spirit::karma::grammar< OutputIterator, char32_t() > {
    public:
      ucs4_to_utf8() : ucs4_to_utf8::base_type( root ) {
        using namespace boost::spirit;
        ascii_ = byte_[ karma::_1 = karma::_val ];
        block1 = ( byte_ << byte_ )[
          karma::_1 = 0xC0|( karma::_val >> 6 ),
          karma::_2 = 0x80|( karma::_val & 0x3F )
        ];
        block2 = ( byte_ << byte_ << byte_ )[
          karma::_1 = 0xE0|( karma::_val >> 12 ),
          karma::_2 = 0x80|( ( karma::_val >> 6 ) & 0x3F ),
          karma::_3 = 0x80|( karma::_val & 0x3F )
        ];
        block3 = ( byte_ << byte_ << byte_ << byte_ )[
          karma::_1 = 0xF0|( karma::_val >> 18 ),
          karma::_2 = 0x80|( ( karma::_val >> 12 ) & 0x3F ),
          karma::_3 = 0x80|( ( karma::_val >> 6 ) & 0x3F ),
          karma::_4 = 0x80|( ( karma::_val ) & 0x3F )
        ];
        block4 = ( byte_ << byte_ << byte_ << byte_ << byte_ )[
          karma::_1 = 0xF8|( karma::_val >> 24 ),
          karma::_2 = 0x80|( ( karma::_val >> 18 ) & 0x3F ),
          karma::_3 = 0x80|( ( karma::_val >> 12 ) & 0x3F ),
          karma::_4 = 0x80|( ( karma::_val >> 6 ) & 0x3F ),
          karma::_5 = 0x80|( ( karma::_val ) & 0x3F )
        ];
        block5 = ( byte_ << byte_ << byte_ << byte_ << byte_ << byte_ )[
          karma::_1 = 0xFC|( karma::_val >> 30 ),
          karma::_2 = 0x80|( ( karma::_val >> 24 ) & 0x3F ),
          karma::_3 = 0x80|( ( karma::_val >> 18 ) & 0x3F ),
          karma::_4 = 0x80|( ( karma::_val >> 12 ) & 0x3F ),
          karma::_5 = 0x80|( ( karma::_val >> 6 ) & 0x3F ),
          karma::_6 = 0x80|( ( karma::_val ) & 0x3F )
        ];
        root = ascii_[
          karma::_pass = karma::_val <= 0x7F,
          karma::_1 = karma::_val
        ]|
        block1[
          karma::_pass = karma::_val <= 0x7FF,
          karma::_1 = karma::_val
        ]|
        block2[
          karma::_pass = karma::_val <= 0xFFFF,
          karma::_1 = karma::_val
        ]|
        block3[
          karma::_pass = karma::_val <= 0x1FFFFF,
          karma::_1 = karma::_val
        ]|
        block4[
          karma::_pass = karma::_val <= 0x3FFFFFF,
          karma::_1 = karma::_val
        ]|
        block5[
          karma::_pass = karma::_val <= 0x7FFFFFFF,
          karma::_1 = karma::_val
        ];
      }
    private:
      boost::spirit::karma::rule< OutputIterator, uint32_t() > ascii_;
      boost::spirit::karma::rule< OutputIterator, uint32_t() > block1;
      boost::spirit::karma::rule< OutputIterator, uint32_t() > block2;
      boost::spirit::karma::rule< OutputIterator, uint32_t() > block3;
      boost::spirit::karma::rule< OutputIterator, uint32_t() > block4;
      boost::spirit::karma::rule< OutputIterator, uint32_t() > block5;
      boost::spirit::karma::rule< OutputIterator, char32_t() > root;
  };

template< typename OutputIterator >
class u32string_to_utf8string :
  public boost::spirit::karma::grammar< OutputIterator, std::u32string() > {
    public:
      u32string_to_utf8string() : u32string_to_utf8string::base_type( root ) {
        using namespace boost::spirit;
        root = *char32_;
      }
    private:
      ucs4_to_utf8< OutputIterator > char32_;
      boost::spirit::karma::rule< OutputIterator, std::u32string() > root;
};

int main() {
  std::string source( "UTF8で表現された\n何か" );
  utf8string_to_u32string< std::string::iterator > rule;
  auto iter = source.begin();
  std::u32string result;
  boost::spirit::qi::parse( iter, source.end(), rule, result );
  for( auto &elem: result )
    std::cout << static_cast< uint32_t >( elem ) << ',';
  std::cout << std::endl;
  typedef std::back_insert_iterator<std::string> sink_type;
  u32string_to_utf8string< sink_type > rrule;
  std::string result2;
  boost::spirit::karma::generate( sink_type( result2 ), rrule, result );
  std::cout << result2 << std::endl;
}

max_stars_repo_name: Fadis/hermit

max_issues_repo_name: Fadis/hermit

max_forks_repo_name: Fadis/hermit


text:
// Copyright 2013 Daniel Parker
// Distributed under Boost license

#include <boost/test/unit_test.hpp>
#include <boost/numeric/ublas/io.hpp>
#include "jsoncons/json.hpp"
#include "jsoncons/json_serializer.hpp"
#include <sstream>
#include <vector>
#include <utility>
#include <ctime>

using jsoncons::json_serializer;
using jsoncons::output_format;
using jsoncons::json;
using jsoncons::pretty_print;
using jsoncons::wjson;
using jsoncons::json_reader;
using jsoncons::json_exception;
using std::string;

BOOST_AUTO_TEST_CASE(test_construction_from_string)
{
    std::string input = "{\"first_name\":\"Jane\",\"last_name\":\"Roe\",\"events_attended\":10}";

    json val = json::parse_string(input);

    std::cout << val << std::endl;
}

BOOST_AUTO_TEST_CASE(test_construction_from_file)
{
    json val = json::parse_file("input/members.json");

    std::cout << pretty_print(val) << std::endl;
}

BOOST_AUTO_TEST_CASE(test_construction_in_code)
{
    // A null value
    json null_val;

    // A boolean value
    json flag(true);

    // A numeric value
    json number(10.5);

    // An object value with four members
    json obj;
    obj["first_name"] = "Jane";
    obj["last_name"] = "Roe";
    obj["events_attended"] = 10;
    obj["accept_waiver_of_liability"] = true;

    // An array value with four elements
    json arr(json::an_array);
    arr.add(null_val);
    arr.add(flag);
    arr.add(number);
    arr.add(obj);

    output_format format;
    arr.to_stream(std::cout,format,true);
    std::cout << std::endl;
}

BOOST_AUTO_TEST_CASE(test_from_container)
{
    std::vector<int> vec;
    vec.push_back(10);
    vec.push_back(20);
    vec.push_back(30);

    json val1(vec.begin(), vec.end());
    std::cout << val1 << std::endl;

    std::list<double> list;
    list.push_back(10.5);
    list.push_back(20.5);
    list.push_back(30.5);

    json val2(list.begin(), list.end());
    std::cout << val2 << std::endl;
}

BOOST_AUTO_TEST_CASE(test_accessing)
{
    json obj;
    obj["first_name"] = "Jane";
    obj["last_name"] = "Roe";
    obj["events_attended"] = 10;
    obj["accept_waiver_of_liability"] = true;

    std::string first_name = obj["first_name"].as<std::string>();
    std::string last_name = obj.at("last_name").as<std::string>();
    int events_attended = obj["events_attended"].as<int>();
    bool accept_waiver_of_liability = obj["accept_waiver_of_liability"].as<bool>();

    std::cout << first_name << " " << last_name << ", " << events_attended << ", " << accept_waiver_of_liability << std::endl;

}

BOOST_AUTO_TEST_CASE(test_value_not_found_and_defaults)
{
    json obj;
    obj["first_name"] = "Jane";
    obj["last_name"] = "Roe";

    try
    {
        std::string experience = obj["outdoor_experience"].as<std::string>();
    }
    catch (const json_exception& e)
    {
        std::cout << e.what() << std::endl;
    }

    std::string experience = obj.has_member("outdoor_experience") ? obj["outdoor_experience"].as<std::string>() : "";

    bool first_aid_certification = obj.get("first_aid_certification",false).as<bool>();

    std::cout << "experience=" << experience << ", first_aid_certification=" << first_aid_certification << std::endl;
}

BOOST_AUTO_TEST_CASE(test_another_object_iterator)
{
    json obj;
    obj["first_name"] = "Jane";
    obj["last_name"] = "Roe";
    obj["events_attended"] = 10;
    obj["accept_waiver_of_liability"] = true;

    for (auto it = obj.begin_members(); it != obj.end_members(); ++it)
    {
        std::cout << "name=" << it->name() << ", value=" << it->value().as<std::string>() << std::endl;
    }
}

BOOST_AUTO_TEST_CASE(test_another_array_iterator)
{
    json arr(json::an_array);
    arr.add("Montreal");
    arr.add("Toronto");
    arr.add("Ottawa");
    arr.add("Vancouver");

    for (auto it = arr.begin_elements(); it != arr.end_elements(); ++it)
    {
        std::cout << it->as<std::string>() << std::endl;
    }
}

BOOST_AUTO_TEST_CASE(test_integer_limits)
{
    const long long max_value = std::numeric_limits<long long>::max();

    const unsigned long long max_uvalue = std::numeric_limits<unsigned long long>::max();
    {
        std::ostringstream os;

        //os << max_value;

        os << "{\"max_longlong\":-" << max_value << "}";
        json val = json::parse_string(os.str());
        std::cout << val << std::endl;
        BOOST_CHECK(val["max_longlong"].is_longlong());
    }
    {
        std::ostringstream os;

        //os << max_value;

        std::cout << "TEST LIMITS" << std::endl;
        os << "{\"max_longlong_overflow\":-" << max_value << "0}";
        std::cout << os.str() << std::endl;

        json val = json::parse_string(os.str());
        std::cout << val << std::endl;
        BOOST_CHECK(val["max_longlong_overflow"].is_double());
    }
    {
        std::ostringstream os;

        os << "{\"max_ulonglong\":" << max_uvalue << "}";
        json val = json::parse_string(os.str());
        std::cout << val << std::endl;
        BOOST_CHECK(val["max_ulonglong"].is_ulonglong());
    }
    {
        std::ostringstream os;

        os << "{\"max_ulonglong_overflow\":" << max_uvalue << "0}";
        json val = json::parse_string(os.str());
        std::cout << val << std::endl;
        BOOST_CHECK(val["max_ulonglong_overflow"].is_double());
    }

    std::cout << "size json=" << sizeof(json) << std::endl;
    std::cout << "size string=" << sizeof(string) << std::endl;
    std::cout << "size array=" << sizeof(std::vector<json>) << std::endl;
    std::cout << "size map=" << sizeof(std::vector<json::member_type>) << std::endl;
}

BOOST_AUTO_TEST_CASE(test_multiple)
{
    std::string in="{\"a\":1,\"b\":2,\"c\":3}{\"a\":4,\"b\":5,\"c\":6}";
    std::cout << in << std::endl;

    std::istringstream is(in);

    jsoncons::json_deserializer handler;
    json_reader reader(is,handler);

    while (!reader.eof())
    {
        reader.read();
        if (!reader.eof())
        {
            json val = std::move(handler.root());
            std::cout << val << std::endl;
        }
    }
}

max_stars_repo_name: avacore/jsoncons

max_issues_repo_name: avacore/jsoncons

max_forks_repo_name: avacore/jsoncons


text:
#include "DebuggerHelper.h"

#include "LeanWindowsInclude.h"

#include "VectoredExceptionDisplayMode.h"

#include "UniversalString.h"
#include "VisualStudioOutputCompliantParser.h"

#include "StormMacro.h"

#include <boost/stacktrace.hpp>

namespace
{
	boost::stacktrace::stacktrace obtainStackTraceImpl(std::size_t toSkip = 1)
	{
		// The 2 more to skip are to skip the internal trace needed to get the stack trace (stacktrace will add 2 methods to the stack when it computes it, which we don't want).
		return boost::stacktrace::stacktrace{ toSkip + static_cast<std::size_t>(2), std::numeric_limits<std::size_t>::max() };
	}

	static bool g_shouldLogAllVectoredExceptions = true;

	static constexpr std::string_view unknownSeDescription()
	{
		return "UNKNOWN EXCEPTION OR CUSTOM NON SE EXCEPTION";
	}

	static std::string_view seDescription(const unsigned int code)
	{
#define STORM_TRADUCE_SEH_CODE_DESCRIPTION(code) case code: return #code
		switch (code)
		{
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_ACCESS_VIOLATION);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_ARRAY_BOUNDS_EXCEEDED);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_BREAKPOINT);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_DATATYPE_MISALIGNMENT);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_FLT_DENORMAL_OPERAND);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_FLT_DIVIDE_BY_ZERO);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_FLT_INEXACT_RESULT);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_FLT_INVALID_OPERATION);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_FLT_OVERFLOW);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_FLT_STACK_CHECK);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_FLT_UNDERFLOW);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_ILLEGAL_INSTRUCTION);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_GUARD_PAGE);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_IN_PAGE_ERROR);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_INT_DIVIDE_BY_ZERO);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_INT_OVERFLOW);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_INVALID_DISPOSITION);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_NONCONTINUABLE_EXCEPTION);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_PRIV_INSTRUCTION);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_SINGLE_STEP);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION(EXCEPTION_STACK_OVERFLOW);
		default: return unknownSeDescription();
		}
	}
#undef STORM_TRADUCE_SEH_CODE_DESCRIPTION

	enum class GravityAction
	{
		Ignore,
		Low,
		Normal,
		Irreversible,
	};

	GravityAction getDescritpionGravity(const unsigned int code)
	{
#define STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(code, irreversibility) case code: return GravityAction::irreversibility
		switch (code)
		{
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_ACCESS_VIOLATION, Irreversible);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_ARRAY_BOUNDS_EXCEEDED, Normal);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_BREAKPOINT, Ignore);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_DATATYPE_MISALIGNMENT, Ignore); // On Windows, it is not so important, will induce performance issue at best.
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_FLT_DENORMAL_OPERAND, Low);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_FLT_DIVIDE_BY_ZERO, Low);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_FLT_INEXACT_RESULT, Low);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_FLT_INVALID_OPERATION, Low);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_FLT_OVERFLOW, Low);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_FLT_STACK_CHECK, Low);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_FLT_UNDERFLOW, Low);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_ILLEGAL_INSTRUCTION, Irreversible);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_GUARD_PAGE, Normal); // I don't really understand it, but it seems heavy stuff. In the doubt I set it as normal.
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_IN_PAGE_ERROR, Normal);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_INT_DIVIDE_BY_ZERO, Low);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_INT_OVERFLOW, Low);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_INVALID_DISPOSITION, Normal); // I don't really understand it (and the doc is not helpful). In the doubt I set it as normal.
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_INVALID_HANDLE, Irreversible); // It is like a sigsegv, but with OS handle...
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_NONCONTINUABLE_EXCEPTION, Irreversible);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_PRIV_INSTRUCTION, Irreversible);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_SINGLE_STEP, Ignore);
		STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY(EXCEPTION_STACK_OVERFLOW, Irreversible);
		default: return GravityAction::Normal;
		}
#undef STORM_TRADUCE_SEH_CODE_DESCRIPTION_GRAVITY
	}

	LONG stormVectoredExceptionHandler(_EXCEPTION_POINTERS* exceptionInfo)
	{
		bool isNonContinuable;
		bool isIrreversibleException;
		bool ignore = false;
		std::string_view seDescriptionStr;
		if (exceptionInfo && exceptionInfo->ExceptionRecord)
		{
			seDescriptionStr = seDescription(exceptionInfo->ExceptionRecord->ExceptionCode);
			const GravityAction gravity = getDescritpionGravity(exceptionInfo->ExceptionRecord->ExceptionCode);
			ignore = gravity == GravityAction::Ignore;
			isIrreversibleException = gravity == GravityAction::Irreversible;
			isNonContinuable = exceptionInfo->ExceptionRecord->ExceptionFlags == EXCEPTION_NONCONTINUABLE;
		}
		else
		{
			seDescriptionStr = unknownSeDescription();
			isIrreversibleException = false;
			isNonContinuable = false;
		}

		if (!ignore)
		{
			const boost::stacktrace::stacktrace currentStacktrace = obtainStackTraceImpl();

			if (isIrreversibleException)
			{
				// I know this isn't good (we shouldn't allocate or acquire OS resources in a vectored exception handler), but until issues happens, I'll keep it like this.
				// Yuck. After all, even std::cout would acquire something because it is synchronized stdio (even if I think they would be safer, but anyway, I want to see my log so cout won't do for me).
				LOG_FATAL <<
					"Irreversible exception signal (fatal) received: " << seDescriptionStr << ".\n"
					"The stacktrace :\n" << currentStacktrace << "\n";

				// Wait a little before terminating.
				std::this_thread::sleep_for(std::chrono::milliseconds{ 1000 });
			}
			else if (g_shouldLogAllVectoredExceptions)
			{
				if (isNonContinuable)
				{
					LOG_ERROR <<
						"Non Continuable exception received: " << seDescriptionStr << ".\n"
						"The stacktrace :\n" << currentStacktrace << "\n";
				}
				else
				{
					LOG_ERROR <<
						"Continuable exception received: " << seDescriptionStr << ".\n"
						"The stacktrace :\n" << currentStacktrace << "\n";
				}
			}
		}

		// stormVectoredExceptionHandler is just a hook before the real hook to retrieve and print more info about the exception that happened,
		// it doesn't intend to replace other hooks, therefore we forward to real hooks.
		return EXCEPTION_CONTINUE_SEARCH;
	}

	class VectoredExceptionHandlerHooker
	{
	public:
		constexpr VectoredExceptionHandlerHooker() = default;

		void doHooking()
		{
			if (!_active)
			{
				_handler = ::AddVectoredExceptionHandler(TRUE, stormVectoredExceptionHandler);
				if (_handler != NULL)
				{
					_active = true;
					LOG_DEBUG << "Vectored exception handler hooked successfully.";
				}
				else
				{
					_active = false;
					LOG_DEBUG_ERROR << "Vectored exception handler hooking failed. Exception debugging won't be able to print exceptions infos!";
				}
			}
		}

		bool doUnhooking() noexcept
		{
			if (_active)
			{
				// if the return is 0, then we failed to unhook. If we were active then we did hook. Therefore the hook is still there.
				_active = ::RemoveVectoredExceptionHandler(_handler) == 0;
				if (!_active)
				{
					_handler = nullptr;
				}
			}

			return !_active;
		}

		~VectoredExceptionHandlerHooker() noexcept
		{
			this->doUnhooking();
		}

	private:
		bool _active = false;
		PVOID _handler = nullptr;
	} g_raiiHooker;
}

void Storm::waitForDebuggerToAttach(bool breakAfter /*= false*/)
{
	while (!Storm::isDebuggerAttached())
	{
		std::this_thread::sleep_for(std::chrono::milliseconds{ 1 });
	}

	if (breakAfter)
	{
		__debugbreak();
	}
}

void Storm::setupFullAssertionBox()
{
	// assert is useless in release.

#if defined(DEBUG) || defined(_DEBUG)
	::_set_error_mode(_OUT_TO_MSGBOX);
#endif
}

void Storm::unhookVectoredExceptionsDebugging()
{
	g_raiiHooker.doUnhooking();
}

void Storm::setLogVectoredExceptionsDisplayMode(Storm::VectoredExceptionDisplayMode displayMode)
{
	switch (displayMode)
	{
	case Storm::VectoredExceptionDisplayMode::DisplayAll:
		g_shouldLogAllVectoredExceptions = true;
		g_raiiHooker.doHooking();
		break;

	case Storm::VectoredExceptionDisplayMode::DisplayFatal:
		g_shouldLogAllVectoredExceptions = false;
		g_raiiHooker.doHooking();
		break;

	case Storm::VectoredExceptionDisplayMode::None:
		if (!g_raiiHooker.doUnhooking())
		{
			LOG_DEBUG_ERROR << "Failed to unhook vectored exception handler!";
		}
		break;

	default:
		break;
	}
}

std::string Storm::obtainStackTrace(bool minimalString)
{
	const boost::stacktrace::stacktrace currentStacktrace = obtainStackTraceImpl(2);

	if (minimalString)
	{
		return Storm::toStdString(currentStacktrace);
	}
	else
	{
		struct StackTracePolicyParser
		{
		public:
			static std::string parsePolicyAgnostic(const boost::stacktrace::stacktrace &stacktraceObject)
			{
				std::string result;

#if true
				if (stacktraceObject) STORM_LIKELY
				{
					boost::stacktrace::detail::debugging_symbols idebug;
					if (idebug.is_inited()) STORM_LIKELY
					{
						enum : std::size_t
						{
							k_expectedFirstReserveMsgSize = 128,
							k_frameFirstReserveSize = 128,
							k_decoratorMsgSize = 6,
							k_incrementReserveSize = 5,
							k_firstReserveSizeSum = k_expectedFirstReserveMsgSize + k_frameFirstReserveSize + k_decoratorMsgSize + k_incrementReserveSize
						};

						constexpr std::string_view k_header = "Stack trace:\n";

						const std::size_t frameCount = stacktraceObject.size();
						result.reserve(k_header.size() + frameCount * k_firstReserveSizeSum);

						result += k_header;

						std::string moduleTmp;

						for (std::size_t iter = 0; iter < frameCount; ++iter)
						{
							const auto &frame = stacktraceObject[iter];
							if (!frame.empty())
							{
								const auto address = frame.address();
								const auto [sourceFilePath, fileLine] = idebug.get_source_file_line_impl(address);

								result += ' ';
								if (Storm::VisualStudioOutputCompliantParser::produceVSOutputCompliantLine(result, iter, sourceFilePath, fileLine))
								{
									result += ':';
								}

								const std::string nameImpl = idebug.get_name_impl(address, &moduleTmp);
								if (!nameImpl.empty())
								{
									result += " at ";
									result += nameImpl;
								}
								if (!moduleTmp.empty())
								{
									result += " in ";
									result += moduleTmp;
								}

								result += '\n';
							}
						}

						result.pop_back();
					}
				}
#else
				result = boost::stacktrace::to_string(stacktraceObject);
#endif

				return result;
			}
		};

		return Storm::toStdString<StackTracePolicyParser>(currentStacktrace);
	}
}

bool Storm::isDebuggerAttached()
{
	return ::IsDebuggerPresent() == TRUE;
}

// Good to know: we can also traduce SE exception to normal C++ exception using _set_se_translator.
// Maybe I'll do it another day. For now I don't need it and I don't want to have throwing for any C signals happening like 0 division or numbers overflows...

max_stars_repo_name: SunlayGGX/Storm

max_issues_repo_name: SunlayGGX/Storm

max_forks_repo_name: SunlayGGX/Storm


text:
#include <monsoon/time_point.h>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <locale>
#include <sstream>
#include <ostream>

namespace monsoon {

using namespace boost::posix_time;
using namespace boost::gregorian;

inline namespace time_point_internals {

monsoon_intf_local_ auto unix_epoch() -> ptime;
monsoon_intf_local_ std::locale imbue_tp_out_format(std::basic_ios<char>& out);
monsoon_intf_local_ std::locale imbue_tp_in_format(std::basic_ios<char>& out);
monsoon_intf_local_ auto parse_as_msec_since_posix_epoch(const std::string&)
    -> std::int64_t;

} /* namespace monsoon::(inline)time_point_internals */

time_point::time_point(const std::string& s)
: time_point(parse_as_msec_since_posix_epoch(s))
{}

time_point time_point::now() {
  const auto time_since_unix_epoch =
      second_clock::universal_time() - unix_epoch();
  return time_point(time_since_unix_epoch.total_milliseconds());
}

std::string to_string(time_point tp) {
  std::ostringstream oss;
  imbue_tp_out_format(oss);
  oss << (unix_epoch() + millisec(tp.millis_since_posix_epoch()));
  return oss.str();
}

auto operator<<(std::ostream& out, time_point tp) -> std::ostream& {
  auto loc = imbue_tp_out_format(out);
  out << (unix_epoch() + millisec(tp.millis_since_posix_epoch()));
  out.imbue(loc);
  return out;
}

int time_point::year() const noexcept {
  return (unix_epoch() + millisec(millis_since_posix_epoch())).date().year();
}

int time_point::month() const noexcept {
  return (unix_epoch() + millisec(millis_since_posix_epoch())).date().month();
}

int time_point::day_of_month() const noexcept {
  return (unix_epoch() + millisec(millis_since_posix_epoch())).date().day();
}

int time_point::hour() const noexcept {
  return (unix_epoch() + millisec(millis_since_posix_epoch())).time_of_day().hours();
}

int time_point::minute() const noexcept {
  return (unix_epoch() + millisec(millis_since_posix_epoch())).time_of_day().minutes();
}

int time_point::second() const noexcept {
  return (unix_epoch() + millisec(millis_since_posix_epoch())).time_of_day().seconds();
}

std::string to_string(time_point::duration d) {
  return (std::ostringstream() << d).str();
}

auto operator<<(std::ostream& out, time_point::duration d) -> std::ostream& {
  auto millis = d.millis();
  if (millis < 0) {
    out << "-";
    millis = -millis;
  }

  auto seconds = millis / 1000;
  auto minutes = seconds / 60;
  auto hours = minutes / 60;
  auto days = hours = 24;
  millis %= 1000;
  seconds %= 60;
  minutes %= 60;
  hours %= 24;

  bool need_space = false;

  if (days != 0) {
    if (std::exchange(need_space, true)) out << " ";
    out << days << "d";
  }
  if (hours != 0) {
    if (std::exchange(need_space, true)) out << " ";
    out << hours << "h";
  }
  if (minutes != 0) {
    if (std::exchange(need_space, true)) out << " ";
    out << minutes << "m";
  }
  if (seconds != 0) {
    if (std::exchange(need_space, true)) out << " ";
    out << seconds << "s";
  }
  if (millis != 0) {
    if (std::exchange(need_space, true)) out << " ";
    out << millis << "ms";
  }
  return out;
}

inline namespace time_point_internals {

const auto FORMAT = "%Y-%m-%dT%H:%M:%S%FZ";

std::locale imbue_tp_out_format(std::basic_ios<char>& out) {
  auto fmt = std::make_unique<time_facet>();
  fmt->format(FORMAT);
  return out.imbue(std::locale(std::locale::classic(), fmt.release()));
}

std::locale imbue_tp_in_format(std::basic_ios<char>& out) {
  auto fmt = std::make_unique<time_input_facet>();
  fmt->format(FORMAT);
  return out.imbue(std::locale(std::locale::classic(), fmt.release()));
}

auto unix_epoch() -> ptime {
  return ptime(date(1970, 1, 1), time_duration(0, 0, 0));
}

auto parse_as_msec_since_posix_epoch(const std::string& s) -> std::int64_t {
  std::istringstream iss = std::istringstream(s);
  imbue_tp_in_format(iss);

  ptime pval;
  iss >> pval;
  return (pval - unix_epoch()).total_milliseconds();
}

} /* namespace monsoon::time_point_internals */
} /* namespace monsoon */

ext: cc


text:
#if !defined(REST_CONTROLLER_HPP)
#define REST_CONTROLLER_HPP

#include <boost/lexical_cast.hpp>

#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <tuple>
#include <typeinfo>
#include <vector>

#include "../../util/Utility.hpp"
#include "BasicController.hpp"
#include "HandlerResult.hpp"
#include "HttpException.hpp"

using std::string;
using std::vector;

namespace controller {

// controller cope with request parameter only
template <typename... Args> struct ParamController : public BasicController {
    using ParamsType = std::tuple<std::optional<Args>...>;
    using HandlerType =
        std::function<HandlerResult(const std::tuple<std::optional<Args>...> &, const Headers &)>;

    ParamsType mParamValues;
    HandlerType mHandler;

    ParamController() {}
    ParamController(const string &path, const vector<string> &paramNames,
                    const vector<string> &headerNames, const ParamsType &paramDefaultValues,
                    const HandlerType &handler)
        : BasicController(path, paramNames, headerNames), mParamValues(paramDefaultValues),
          mHandler(handler) {}
    virtual ~ParamController() = default;

    virtual HandlerResult invoke() override { return mHandler(mParamValues, mHeaders); }

    // set the value of the parameter, support int32_t, int64_t, string or
    // is_convertible_v<string, decltype(v)>
    virtual void setParamValue(int32_t which, const string &val) {
        auto modifier = [&val](std::optional<auto> &v) {
            using VType = typename std::remove_reference<decltype(v)>::type::value_type;
            using std::is_same_v;
            try {
                if constexpr (is_same_v<VType, int32_t>) {
                    v.emplace(boost::lexical_cast<int>(val));
                } else if constexpr (is_same_v<VType, int64_t>) {
                    v.emplace(boost::lexical_cast<long>(val));
                } else if constexpr (is_same_v<VType, string>) {
                    v = val;
                } else if constexpr (std::is_convertible_v<string, VType>) {
                    v.emplace(static_cast<VType>(val));
                } else {
                    throw std::runtime_error("unsupported type");
                }
            } catch (std::bad_cast &e) {
                throw HttpException(HttpException::CODE_BAD_REQUEST,
                                    "failed to set string parameter");
            }
        };
        visit_at(mParamValues, which, modifier);
    }

    // set the value of a request body parameter
    virtual void setParamValue(int32_t which, const nlohmann::json &val) override {
        auto modifier = [&val](std::optional<auto> &v) {
            using VType = typename std::remove_reference<decltype(v)>::type::value_type;
            constexpr bool REQUIRED_CONDITION = std::is_convertible<nlohmann::json, VType>::value;
            static_assert(REQUIRED_CONDITION, "unsupported type");
            try {
                if constexpr (std::is_convertible_v<nlohmann::json, VType>) {
                    v.emplace(static_cast<VType>(val));
                }
            } catch (nlohmann::json::exception &e) {
                throw HttpException(HttpException::CODE_BAD_REQUEST,
                                    "failed to set json parameter");
            }
        };
        visit_at(mParamValues, which, modifier);
    }

    virtual std::unique_ptr<BasicController> clone() override {
        return std::unique_ptr<BasicController>{dynamic_cast<BasicController *>(new ParamController(
            mPath, mRequiredParamNames, mRequiredHeaderNames, mParamValues, mHandler))};
    }
};

// Create a shared_ptr<BasicController> pointing to a ParamController with specified Parameter
// types. The object is created using new expression. Make it static so that it can be used by
// static-member-function.
template <typename... ParamTypes>
static std::shared_ptr<BasicController>
makeParamController(const string &path, const vector<string> &paramNames,
                    const vector<string> &headerNames,
                    typename ParamController<ParamTypes...>::HandlerType handler) {

    auto *pointer = new ParamController<ParamTypes...>(
        path, paramNames, headerNames, std::make_tuple(std::optional<ParamTypes>{}...), handler);
    return std::shared_ptr<BasicController>(dynamic_cast<BasicController *>(pointer));
}
}; // namespace controller

#endif // REST_CONTROLLER_HPP

max_stars_repo_name: EricJeffrey/TheCheatSheet

max_issues_repo_name: EricJeffrey/TheCheatSheet

max_forks_repo_name: EricJeffrey/TheCheatSheet


text:
//////////////////////////////////////////////////////////////////////////////////////////////
/// \file BlockMatrix.hpp
///
/// \author Sean Anderson, ASRL
//////////////////////////////////////////////////////////////////////////////////////////////

#ifndef STEAM_BLOCK_MATRIX_HPP
#define STEAM_BLOCK_MATRIX_HPP

#include <vector>
#include <map>

#include <Eigen/Core>
#include <Eigen/Sparse>

#include <steam/blockmat/BlockMatrixBase.hpp>

namespace steam {

/////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Class to store a block matrix
/////////////////////////////////////////////////////////////////////////////////////////////
class BlockMatrix : public BlockMatrixBase
{
 public:

  //////////////////////////////////////////////////////////////////////////////////////////////
  /// \brief Default constructor, matrix size must still be set before using
  //////////////////////////////////////////////////////////////////////////////////////////////
  BlockMatrix();

  //////////////////////////////////////////////////////////////////////////////////////////////
  /// \brief Rectangular matrix constructor
  //////////////////////////////////////////////////////////////////////////////////////////////
  BlockMatrix(const std::vector<unsigned int>& blkRowSizes,
              const std::vector<unsigned int>& blkColSizes);

  //////////////////////////////////////////////////////////////////////////////////////////////
  /// \brief Block-size-symmetric matrix constructor, pure scalar symmetry is still optional
  //////////////////////////////////////////////////////////////////////////////////////////////
  BlockMatrix(const std::vector<unsigned int>& blkSizes, bool symmetric = false);

  //////////////////////////////////////////////////////////////////////////////////////////////
  /// \brief Set entries to zero
  //////////////////////////////////////////////////////////////////////////////////////////////
  virtual void zero();

  //////////////////////////////////////////////////////////////////////////////////////////////
  /// \brief Adds the matrix to the block entry at index (r,c), block dim must match
  //////////////////////////////////////////////////////////////////////////////////////////////
  virtual void add(unsigned int r, unsigned int c, const Eigen::MatrixXd& m);

  //////////////////////////////////////////////////////////////////////////////////////////////
  /// \brief Returns a reference to the value at (r,c), if it exists
  ///        *Note this throws an exception if matrix is symmetric and you request a lower
  ///         triangular entry. For read operations, use copyAt(r,c).
  //////////////////////////////////////////////////////////////////////////////////////////////
  virtual Eigen::MatrixXd& at(unsigned int r, unsigned int c);

  //////////////////////////////////////////////////////////////////////////////////////////////
  /// \brief Returns a copy of the entry at index (r,c)
  //////////////////////////////////////////////////////////////////////////////////////////////
  virtual Eigen::MatrixXd copyAt(unsigned int r, unsigned int c) const;

 private:

  //////////////////////////////////////////////////////////////////////////////////////////////
  /// \brief Matrix of block matrices (row, column)
  //////////////////////////////////////////////////////////////////////////////////////////////
  std::vector<std::vector<Eigen::MatrixXd> > data_;

};

} // steam

#endif // STEAM_BLOCK_MATRIX_HPP

max_stars_repo_name: neophack/steam

max_issues_repo_name: neophack/steam

max_forks_repo_name: neophack/steam


text:
#ifndef CRISPR_SEARCH_LOCATION_CSLOCATION_HPP
#define CRISPR_SEARCH_LOCATION_CSLOCATION_HPP

#include <string>
#include <memory>
#include <utility>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <fstream>
#include <exception>
#include <sstream>
#include <vector>
#include <cctype>

#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/string_generator.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/filesystem.hpp>
#include <boost/process.hpp>

#include "rapidjson/document.h"

#include <sqlite3.h>

#include "csl_constants.hpp"

using std::string;
using std::unique_ptr;
using std::shared_ptr;
using std::ifstream;
using std::ofstream;
using std::ios_base;
using std::stringstream;
using std::make_unique;
using std::make_shared;
using std::exception;
using std::vector;
using std::cout;
using std::endl;
using std::istreambuf_iterator;
using std::move;
using std::isalnum;
using std::remove_if;

using boost::iostreams::input;
using boost::iostreams::filtering_streambuf;
using boost::iostreams::gzip_decompressor;
using boost::uuids::uuid;
using boost::uuids::basic_random_generator;

using namespace rapidjson;

extern string CRISPR_CAS_FINDER_PATH;

namespace crisprsearch::location {
    struct InvalidJSONException : public exception {
        const char *what() const throw() {
            return "Setup JSON was invalid or missing required parameters.";
        }
    };

    struct FileNotGoodException : public exception {
        const char *what() const throw() {
            return "Could not load file";
        }
    };
}

#endif


text:
//
// Created by arehal on 1/18/19.
//

#include <iostream>
#include <boost/filesystem.hpp>

#include "WorldHandler.h"
#include "DataManager.h"
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/case_conv.hpp>

using handler::WorldHandler;
using Json = nlohmann::json;

constexpr auto DATA_JSON_PATH = "lib/data/mirkwood.json";
constexpr auto LOAD_FILE_PATH = "lib/data/saveFile.json";

namespace handler {

    WorldHandler::WorldHandler() {
        this->world = World();

        // load save file if it exists, otherwise load a default area file
        if (boost::filesystem::exists( LOAD_FILE_PATH )) {
            std::cout << "Loaded save file" << std::endl;
            auto savedAreas = DataManager::ParseWorldFile(LOAD_FILE_PATH);
            for(Area& area: savedAreas) {
                resetHandler.loadSavedResets(area);
            }
            this->world.setAreas(savedAreas);

        } else {
            std::cout << "Loaded default area file" << std::endl;
            this->world.addArea(DataManager::ParseDataFile(DATA_JSON_PATH));
            reset();
        }
    }

    World WorldHandler::getWorld() const {
        return world;
    }

    void WorldHandler::setWorld(const World &world) {
        this->world = world;
    }

    bool WorldHandler::roomExists(const model::ID &roomId) {
        bool found = false;
        for (Area &area : this->world.getAreas()) {
            std::vector<Room>& rooms = area.getRooms();
            auto it = std::find_if(rooms.begin(), rooms.end(), [&roomId](const Room &room) {return room.getId() == roomId;});
            if (it != rooms.end()) {
                found = true;
                break;
            }
        }
        return found;
    }

    Room& WorldHandler::findRoom(const model::ID &roomId) {
        for (Area &area : this->world.getAreas()) {
            std::vector<Room>& rooms = area.getRooms();
            auto it = std::find_if(rooms.begin(), rooms.end(), [&roomId](const Room &room) {return room.getId() == roomId;});
            if (it != rooms.end()) {
                return *it;
            }
        }
        throw std::runtime_error("Error: tried to find room that does not exist");
    }

    Area& WorldHandler::findArea(const model::ID &roomId) {
        for (Area &area : this->world.getAreas()) {
            std::vector<Room>& rooms = area.getRooms();
            auto it = std::find_if(rooms.begin(), rooms.end(), [&roomId](const Room &room) {return room.getId() == roomId;});
            if (it != rooms.end()) {
                return area;
            }
        }
        throw std::runtime_error("Error: tried to find area that does not exist");
    }

    bool WorldHandler::isValidDirection(const model::ID &roomId, const std::string &dir) {
        Room& room = findRoom(roomId);
        return room.isValidDirection(dir);
    }

    model::ID WorldHandler::getDestination(const model::ID &roomId, const std::string &dir) {
        Room& room = findRoom(roomId);
        return room.getDestination(dir);
    }

    void WorldHandler::addPlayer(const model::ID &roomId, const model::ID &playerId) {
        Room& room = findRoom(roomId);
        room.addPlayerToRoom(playerId);
    }

    void WorldHandler::removePlayer(const model::ID &roomId, const model::ID &playerId) {
        Room& room = findRoom(roomId);
        room.removePlayerFromRoom(playerId);
    }

    void WorldHandler::movePlayer(const model::ID &playerId, const model::ID &sourceId, const model::ID &destinationId) {
        removePlayer(sourceId, playerId);
        addPlayer(destinationId, playerId);
    }

    void WorldHandler::addItem(const model::ID &roomId, const Object &item) {
        Room& room = findRoom(roomId);
        room.addObject(item);
    }

    void WorldHandler::removeItem(const model::ID &roomId, const model::ID &objectId) {
        Room& room = findRoom(roomId);
        room.removeObject(objectId);
    }

    bool WorldHandler::canGive(const model::ID &roomId, const model::ID &playerId) {
        Room& room = findRoom(roomId);
        auto players = room.getPlayersInRoom();
        auto it = std::find(players.begin(), players.end(), playerId);
        return (it != players.end());
    }

    std::vector<model::ID> WorldHandler::getNearbyPlayerIds(const model::ID &roomId) {
        Room room = findRoom(roomId);
        std::vector<model::ID> playerIds = room.getPlayersInRoom();
        auto nearbyRoomIds = room.getNearbyRoomIds();
        for (const auto &nearbyRoomId : nearbyRoomIds) {
            Room nearbyRoom = findRoom(nearbyRoomId);
            auto playersInNearbyRoom = nearbyRoom.getPlayersInRoom();
            playerIds.insert(playerIds.end(), playersInNearbyRoom.begin(), playersInNearbyRoom.end());
        }
        return playerIds;
    }

    bool WorldHandler::createArea(const std::string &name) {
        //acreate [name]
        if (!name.empty()) {
            auto area = Area(name);
            this->world.addArea(area);
        }
        return !name.empty();
    }

    bool WorldHandler::createRoom(const std::vector<std::string> &arguments) {
        //rcreate [anum] [id] [name]
        bool canCreate = false;
        if (arguments.size() > 2 && isNum(arguments.at(0)) && isNum(arguments.at(1)) && isValidIdString(arguments.at(1))) {
            unsigned int index = std::stoi(arguments.at(0)) - 1;
            unsigned int roomId = std::stoi(arguments.at(1));
            canCreate = (index < this->world.getAreas().size() && !roomExists(roomId));
            if (canCreate) {
                std::string name = boost::algorithm::join(std::vector<std::string>(arguments.begin()+2, arguments.end()), " ");
                auto room = Room(roomId, name);
                this->world.getAreas().at(index).addRoom(room);
            }
        }
        return canCreate;
    }

    bool WorldHandler::createObject(const model::ID &roomId, const std::vector<std::string> &arguments) {
        //ocreate [id] [short description]
        bool canCreate = false;
        if (arguments.size() > 1 && isNum(arguments.at(0)) && isValidIdString(arguments.at(0))) {
            unsigned int id = std::stoi(arguments.at(0));
            auto &area = findArea(roomId);
            canCreate = !area.objectExists(id);
            if (canCreate) {
                std::string shortDesc = boost::algorithm::join(std::vector<std::string>(arguments.begin()+1, arguments.end()), " ");
                auto object = Object(id, shortDesc);
                area.addObject(object);
            }
        }
        return canCreate;
    }

    bool WorldHandler::createNpc(const model::ID &roomId, const std::vector<std::string> &arguments) {
        //ncreate [id] [short description]
        bool canCreate = false;
        if (arguments.size() > 1 && isNum(arguments.at(0)) && isValidIdString(arguments.at(0))) {
            unsigned int id = std::stoi(arguments.at(0));
            auto &area = findArea(roomId);
            canCreate = !area.npcExists(id);
            if (canCreate) {
                std::string shortDesc = boost::algorithm::join(std::vector<std::string>(arguments.begin()+1, arguments.end()), " ");
                auto npc = NPC(id, shortDesc);
                area.addNpc(npc);
            }
        }
        return canCreate;
    }

    bool WorldHandler::createObjectReset(const model::ID &roomId, const std::vector<std::string> &arguments) {
        //oreset [id]
        bool canCreate = false;
        if (arguments.size() == 1 && isNum(arguments.at(0)) && isValidIdString(arguments.at(0))) {
            unsigned int id = std::stoi(arguments.at(0));
            auto &area = findArea(roomId);
            canCreate = area.objectExists(id);
            if (canCreate) {
                Reset reset = Reset();
                reset.setAction("object");
                reset.setId(id);
                reset.setRoom(roomId);
                area.addReset(reset);
            }
        }
        return canCreate;
    }

    bool WorldHandler::createNpcReset(const model::ID &roomId, const std::vector<std::string> &arguments) {
        //nreset [id] [amount]
        bool canCreate = false;
        if (arguments.size() == 2 && isNum(arguments.at(0)) && isValidIdString(arguments.at(0)) &&
                isNum(arguments.at(1)) && arguments.at(1).size() <= MAX_NPC_OF_TYPE_COUNT) {
            unsigned int id = std::stoi(arguments.at(0));
            unsigned int amount = std::stoi(arguments.at(1));
            auto &area = findArea(roomId);
            canCreate = area.npcExists(id);
            if (canCreate) {
                Reset reset = Reset();
                reset.setAction("npc");
                reset.setId(id);
                reset.setRoom(roomId);
                reset.setLimit(amount);
                area.addReset(reset);
            }
        }
        return canCreate;
    }

    bool WorldHandler::editArea(const model::ID &roomId, const std::vector<std::string> &arguments) {
        //aedit [field] [values]
        bool success = false;
        if (arguments.size() > 1) {
            std::string field = arguments.at(0);
            std::string value = boost::algorithm::join(std::vector<std::string>(arguments.begin()+1, arguments.end()), " ");
            if (field == "name") {
                auto &area = findArea(roomId);
                area.setName(value);
                success = true;
            }
        }
        return success;
    }

    bool WorldHandler::editRoom(const model::ID &roomId, const std::vector<std::string> &arguments) {
        //redit [field] [values]
        bool success = false;
        if (arguments.size() > 1) {
            std::string field = arguments.at(0);
            std::string value = boost::algorithm::join(std::vector<std::string>(arguments.begin()+1, arguments.end()), " ");
            auto &room = findRoom(roomId);
            if (field == "name") {
                room.setName(value);
                success = true;
            } else if (field == "desc") {
                room.setDesc({value});
                success = true;
            } else if (field == "extra" && arguments.size() >= 3) {
                //redit extra [keyword] [description]
                std::string keyword = boost::algorithm::to_lower_copy(arguments.at(1));
                std::string desc = boost::algorithm::join(std::vector<std::string>(arguments.begin()+2, arguments.end()), " ");
                room.addExtra({{keyword},{desc}});
                success = true;
            } else if (field == "door") {
                //redit door [direction] [roomId] [description]
                std::string dir = boost::algorithm::to_lower_copy(arguments.at(1));
                if (!room.isValidDirection(dir) && arguments.size() >= 3 && isNum(arguments.at(2))) {
                    int leadsTo = std::stoi(arguments.at(2));
                    model::Door door = model::Door{dir, leadsTo};
                    if (arguments.size() > 3) {
                        std::string desc = boost::algorithm::join(std::vector<std::string>(arguments.begin()+3, arguments.end()), " ");
                        door.desc = {desc};
                    }
                    room.addDoor(door);
                    success = true;
                }
            }
        }
        return success;
    }

    bool WorldHandler::editObject(const model::ID &roomId, const std::vector<std::string> &arguments) {
        //oedit [id] [field] [values]
        bool success = false;
        if (arguments.size() > 2 && isNum(arguments.at(0)) && isValidIdString(arguments.at(0))) {
            unsigned int id = std::stoi(arguments.at(0));
            std::string field = arguments.at(1);
            std::string value = boost::algorithm::join(std::vector<std::string>(arguments.begin()+2, arguments.end()), " ");
            auto &area = findArea(roomId);
            if (area.objectExists(id)) {
                auto object = area.findObjectById(id);
                if (field == "short") {
                    object->setShortDescription(value);
                    success = true;
                } else if (field == "long") {
                    object->setLongDescription({value});
                    success = true;
                } else if (field == "keywords") {
                    std::vector<std::string> keywords = std::vector<std::string>(arguments.begin()+2, arguments.end());
                    for (auto &keyword : keywords) {
                        keyword = boost::algorithm::to_lower_copy(keyword);
                    }
                    object->setKeywords(keywords);
                    success = true;
                } else if (field == "slot") {
                    auto slot = model::getSlotFromString(value);
                    if (slot != model::Slot::Misc) {
                        object->setSlot(slot);
                        success = true;
                    }
                }
            }
        }
        return success;
    }

    bool WorldHandler::editNpc(const model::ID &roomId, const std::vector<std::string> &arguments) {
        //nedit [id] [field] [values]
        bool success = false;
        if (arguments.size() > 2 && isNum(arguments.at(0)) && isValidIdString(arguments.at(0))) {
            unsigned int id = std::stoi(arguments.at(0));
            std::string field = arguments.at(1);
            std::string value = boost::algorithm::join(std::vector<std::string>(arguments.begin()+2, arguments.end()), " ");
            auto &area = findArea(roomId);
            if (area.npcExists(id)) {
                auto npc = area.findNpcById(id);
                if (field == "short") {
                    npc->setShortDescription(value);
                    success = true;
                } else if (field == "long") {
                    npc->setLongDescription({value});
                    success = true;
                } else if (field == "desc") {
                    npc->setDescription({value});
                    success = true;
                } else if (field == "keywords") {
                    std::vector<std::string> keywords = std::vector<std::string>(arguments.begin()+2, arguments.end());
                    for (auto &keyword : keywords) {
                        keyword = boost::algorithm::to_lower_copy(keyword);
                    }
                    npc->setKeywords(keywords);
                    success = true;
                }
            }
        }
        return success;
    }

    void WorldHandler::clear(const model::ID &roomId) {
        auto &area = findArea(roomId);
        area.removeResets(roomId);
        auto &room = findRoom(roomId);
        room.setDesc({});
        room.setDoors({});
        room.setExtras({});
        room.setObjects({});
        room.setNpcs({});
    }

    void WorldHandler::resetArea(const model::ID &roomId) {
        auto &area = findArea(roomId);
        for (auto &room : area.getRooms()) {
            room.setObjects({});
            room.setNpcs({});
        }

        this->resetHandler.resetArea(area);
    }

    void WorldHandler::reset() {
        for (Area& area : this->world.getAreas()) {
            this->resetHandler.resetArea(area);
        }
    }

    void WorldHandler::processResets() {
        if (resetHandler.isTimeToReset()) {
            this->reset();
            this->resetHandler.resetTimer();

        } else {
            this->resetHandler.decrementTimer();
        }
    }

    bool WorldHandler::isNum(const std::string &str) const {
        return !str.empty() && std::all_of(str.begin(), str.end(), ::isdigit);
    }

    bool WorldHandler::isValidIdString(const std::string &str) const {
        return str.size() <= MAX_ID_DIGITS;
    }
}


text:
//
// any_io_executor.hpp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff 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)
//

#ifndef BOOST_ASIO_ANY_IO_EXECUTOR_HPP
#define BOOST_ASIO_ANY_IO_EXECUTOR_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/detail/config.hpp>
#if defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT)
# include <boost/asio/executor.hpp>
#else // defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT)
# include <boost/asio/execution.hpp>
# include <boost/asio/execution_context.hpp>
#endif // defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT)

#include <boost/asio/detail/push_options.hpp>

namespace boost {
namespace asio {

#if defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT)

typedef executor any_io_executor;

#else // defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT)

/// Polymorphic executor type for use with I/O objects.
/**
 * The @c any_io_executor type is a polymorphic executor that supports the set
 * of properties required by I/O objects. It is defined as the
 * execution::any_executor class template parameterised as follows:
 * @code execution::any_executor<
 *   execution::context_as_t<execution_context&>,
 *   execution::blocking_t::never_t,
 *   execution::prefer_only<execution::blocking_t::possibly_t>,
 *   execution::prefer_only<execution::outstanding_work_t::tracked_t>,
 *   execution::prefer_only<execution::outstanding_work_t::untracked_t>,
 *   execution::prefer_only<execution::relationship_t::fork_t>,
 *   execution::prefer_only<execution::relationship_t::continuation_t>
 * > @endcode
 */
#if defined(GENERATING_DOCUMENTATION)
typedef execution::any_executor<...> any_io_executor;
#else // defined(GENERATING_DOCUMENTATION)
typedef execution::any_executor<
    execution::context_as_t<execution_context&>,
    execution::blocking_t::never_t,
    execution::prefer_only<execution::blocking_t::possibly_t>,
    execution::prefer_only<execution::outstanding_work_t::tracked_t>,
    execution::prefer_only<execution::outstanding_work_t::untracked_t>,
    execution::prefer_only<execution::relationship_t::fork_t>,
    execution::prefer_only<execution::relationship_t::continuation_t>
  > any_io_executor;
#endif // defined(GENERATING_DOCUMENTATION)

#endif // defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT)

} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_ANY_IO_EXECUTOR_HPP

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
//          Copyright Oliver Kowalke 2009.
//          Copyright Edvard Severin Pettersen 2017.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE.md or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#pragma once

#include <chrono>
#include <tuple>
#include <utility>

#include <proxc/config.hpp>

#include <proxc/detail/delegate.hpp>
#include <proxc/detail/hook.hpp>
#include <proxc/detail/queue.hpp>
#include <proxc/detail/spinlock.hpp>
#include <proxc/detail/traits.hpp>

#include <boost/assert.hpp>
#include <boost/intrusive_ptr.hpp>
#include <boost/context/execution_context_v1.hpp>

PROXC_NAMESPACE_BEGIN

namespace hook = detail::hook;

// forward declaration
class Alt;

namespace runtime {

// forward declaration
class Scheduler;

namespace context {

struct MainType {};
const MainType main_type{};

struct SchedulerType {};
const SchedulerType scheduler_type{};

struct WorkType {};
const WorkType work_type{};

} // namespace context

class Context
{
public:
    friend class Scheduler;

    enum class Type {
        None      = 1 << 0,
        Main      = 1 << 1,
        Scheduler = 1 << 2,
        Work      = 1 << 3,
        Static    = Main | Scheduler, // cannot migrate from a scheduler
        Dynamic   = Work,             // can migrate between schedulers
        Process   = Main | Dynamic    // contexts which are not a scheduler
    };

    class Id
    {
    private:
        Context *    ptr_{ nullptr };

    public:
        Id( Context * ctx ) noexcept : ptr_{ ctx } {}

        bool operator == ( Id const & other ) const noexcept { return ptr_ == other.ptr_; }
        bool operator != ( Id const & other ) const noexcept { return ptr_ != other.ptr_; }
        bool operator <= ( Id const & other ) const noexcept { return ptr_ <= other.ptr_; }
        bool operator >= ( Id const & other ) const noexcept { return ptr_ >= other.ptr_; }
        bool operator <  ( Id const & other ) const noexcept { return ptr_ < other.ptr_; }
        bool operator >  ( Id const & other ) const noexcept { return ptr_ > other.ptr_; }

        explicit operator bool() const noexcept { return ptr_ != nullptr; }
        bool operator ! () const noexcept { return ptr_ == nullptr; }

        template<typename CharT, typename TraitsT>
        friend std::basic_ostream< CharT, TraitsT > &
        operator << ( std::basic_ostream< CharT, TraitsT > & os, Id const & id )
        {
            if ( id ) { return os << id.ptr_; }
            else      { return os << "invalid id"; }
        }
    };

    using ContextT = boost::context::execution_context;
    using TimePointT = std::chrono::steady_clock::time_point;

    using EntryFn     = detail::delegate< void( void * ) >;

private:
    Type    type_;

    std::atomic< bool >    terminated_flag_{ false };

    EntryFn     entry_fn_{ nullptr };
    ContextT    ctx_;

    Scheduler *    scheduler_{ nullptr };

    // intrusive_ptr friend methods and counter
    friend void intrusive_ptr_add_ref( Context * ctx ) noexcept;
    friend void intrusive_ptr_release( Context * ctx ) noexcept;
    std::atomic< std::size_t >    use_count_{ 0 };

public:
    TimePointT     time_point_{ TimePointT::max() };
    Alt *          alt_{ nullptr };

    detail::Spinlock    splk_;

    // Intrusive hooks
    hook::Ready         ready_{};
    hook::Work          work_{};
    hook::Sleep         sleep_{};
    hook::Terminated    terminated_{};

    // Wait queue must be context specific, as this differs from
    // from context to context
    hook::Wait    wait_{};
    using WaitQueue = detail::queue::ListQueue<
        Context, detail::hook::Wait, & Context::wait_
    >;
    WaitQueue     wait_queue_{};

    // Mpsc queue intrusive link
    std::atomic< Context * > mpsc_next_{ nullptr };

public:
    // constructors and destructor
    explicit Context( context::MainType );
    explicit Context( context::SchedulerType, EntryFn && );
    explicit Context( context::WorkType, EntryFn && );

    ~Context() noexcept;

    // make non copy-able
    Context( Context const & )             = delete;
    Context & operator=( Context const & ) = delete;

    // general methods
    Id get_id() const noexcept;
    void * resume( void * = nullptr ) noexcept;

    bool is_type( Type ) const noexcept;

    void terminate() noexcept;
    bool has_terminated() const noexcept;

    void print_debug() noexcept;

private:
    [[noreturn]]
    void trampoline_( void * );

    // Intrusive hook methods
private:
    template<typename Hook>
    Hook & get_hook_() noexcept;

public:
    template<typename Hook>
    bool is_linked() noexcept;
    template<typename ... Ts>
    void link( boost::intrusive::list< Ts ... > & list ) noexcept;
    template<typename ... Ts>
    void link( boost::intrusive::multiset< Ts ... > & set ) noexcept;
    template<typename Hook>
    void unlink() noexcept;
    template<typename Hook>
    bool try_unlink() noexcept;

    void wait_for( Context * ) noexcept;
};

// Intrusive list methods.
template<typename Hook>
bool Context::is_linked() noexcept
{
    return get_hook_< Hook >().is_linked();
}

template<typename ... Ts>
void Context::link( boost::intrusive::list< Ts ... > & list ) noexcept
{
    BOOST_ASSERT( ! is_linked< typename boost::intrusive::list< Ts ... >::value_traits::hook_type >() );
    list.push_back( *this);
}

template<typename ... Ts>
void Context::link( boost::intrusive::multiset< Ts ... > & list ) noexcept
{
    BOOST_ASSERT( ! is_linked< typename boost::intrusive::multiset< Ts ... >::value_traits::hook_type >() );
    list.insert( *this);
}

template<typename Hook>
void Context::unlink() noexcept
{
    BOOST_ASSERT( is_linked< Hook >() );
    get_hook_< Hook >().unlink();
}

template<typename Hook>
bool Context::try_unlink() noexcept
{
    bool link = is_linked< Hook >();
    if ( link ) { unlink< Hook >(); }
    return link;
}

} // namespace runtime
PROXC_NAMESPACE_END

max_stars_repo_name: edvardsp/libproxc-

max_issues_repo_name: edvardsp/libproxc-

max_forks_repo_name: edvardsp/libproxc-


text:
#ifndef DRAM_HPP
#define DRAM_HPP

#include <queue>

#include "tiles.hpp"
#include "bank.hpp"

#include <boost/serialization/deque.hpp>
#include <boost/serialization/queue.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

using namespace std;

class Dram{
    public:
        int prefetch_limit;

        float bandwidth;

        float x_tiles_bw_usage;
        float w_tiles_bw_usage;
        float p_tiles_bw_usage;

        list<pair<int, Tile*>>* load_queue;

        Dram(){};
        Dram(float bandwidth, int prefetch_limit);
        ~Dram(){};

        void update(list<Bank*>* p_banks, int r);

        friend class boost::serialization::access;

        template<class Archive>
        void serialize(Archive & ar, const unsigned int version){
            ar & this->bandwidth;
            ar & this->load_queue;
        }

    private:

};

#endif

max_stars_repo_name: yuezuegu/sosa-compiler

max_issues_repo_name: yuezuegu/sosa-compiler

max_forks_repo_name: yuezuegu/sosa-compiler


text:
#define BOOST_TEST_MODULE InstructionTest

#include "instruction.h"
#include "addressMode.h"
#include "cpu6502.h"
#include "registers.h"

#include <cinttypes>
#include <string>
#include <vector>
#include <boost/test/unit_test.hpp>

/*
 * These tests test the actual instructions with the associated permutations
 * of addressing modes. Notably, the translation of op code to instruction/mode
 * is skipped.
 */

class CpuTester {
public:

  CpuTester() : cpu(nullptr, nullptr) {}

  std::string print(const std::string& op_name, uint8_t op) {
    return '\n' + op_name + '\n' + cpu.print_registers(op);
  }

  void run() {
    cpu.power(true);
  }
  void queue(Instruction6502 *instruction) {
    // Push an instruction onto the instruction queue and power on the CPU.
    cpu.q->push(instruction);
  }

  registers& data() {
    return cpu.reg;
  }

  Cpu6502 cpu;
};

class Immediate : public AddressMode {
public:
  Immediate(uint8_t o) :
    operand(o) {}
  uint8_t fetch(registers&) { return operand; }

private:
  uint8_t operand;
};

// Verification funtions.

static void
verify_acc(CpuTester& c, uint8_t expected, const std::string& op_name="")
{
  BOOST_CHECK_MESSAGE(c.data().acc == expected, c.print(op_name, expected));
}

static void
verify_status_all(CpuTester& c, uint8_t expected, const std::string& op_name="")
{
  BOOST_CHECK_MESSAGE(c.data().p == expected, c.print(op_name, expected));
}

static void
verify_status_one(CpuTester& c, uint8_t expected,const std::string& op_name="")
{
  BOOST_CHECK_MESSAGE((c.data().p & expected) > 0, c.print(op_name, expected));
}

/*
 * Declares an instruction and subsequently executes it.  It then prints the output.
 * We assume that the addressing mode has been determined and so feed it directly to
 * the instructions.
 *
 * INST        = The Instruction name.
 * ADDRESSMODE = The addressing mode.
 * OP          = The Operand on which the instruction operates.
 */

template<typename INSTRUCTION>
static void run(CpuTester& c, uint8_t operand)
{
  Immediate mode(operand);
  INSTRUCTION instruction(c.cpu, c.data(), &mode);
  c.queue(&instruction);
  c.run();
}

template<typename INSTRUCTION>
static void run(CpuTester& c, std::vector<uint8_t> operands)
{
  std::vector<Immediate *> storage;
  std::vector<INSTRUCTION *> storage2;
  for (uint8_t operand : operands) {
    Immediate *mode = new Immediate(operand);
    storage.push_back(mode);
    INSTRUCTION *instruction = new INSTRUCTION(c.cpu, c.data(), mode);
    storage2.push_back(instruction);
    c.queue(instruction);
  }
  c.run();
}

BOOST_AUTO_TEST_CASE(_adc_)
{
  // Test customs.
  // Simple case.

  {
    CpuTester c;
    run<ADC>(c, 0);
    verify_acc(c, 0, "0");
  }
  {
    CpuTester c;
    run<ADC>(c, 69);
    verify_acc(c, 69, "General");
  }

  {
    CpuTester c;
    std::vector<uint8_t> operands = { 1, 127 };
    run<ADC>(c, operands);
    verify_acc(c, 128, "1 + 127 = 128");
  }

  {
    CpuTester c;
    std::vector<uint8_t> operands = { 1, 255 };
    run<ADC>(c, operands);
    verify_acc(c, 0, "1 + 255 = 0");
    verify_status_one(c, Registers::CARRY_FLAG, "Carry FLAG");
  }
  {
    CpuTester c;
    std::vector<uint8_t> operands = { 255, 255 };
    run<ADC>(c, operands);
    verify_acc(c, 254, "255 + 255 = 254");
    verify_status_one(c, Registers::CARRY_FLAG, "Carry FLAG");
    verify_status_one(c, Registers::OVERFLOW_FLAG, "Overflow FLAG");
  }
  {
    CpuTester c;
    std::vector<uint8_t> operands = { 255, 255, 0 };
    run<ADC>(c, operands);
    verify_acc(c, 255, "255 + 255 = 254 + carry = 255");
  }
}

BOOST_AUTO_TEST_CASE(_sbc_)
{
  CpuTester c;
  // run<SBC>(c, 0);
}

max_stars_repo_name: brakthehack/NESEMU

max_issues_repo_name: brakthehack/NESEMU

max_forks_repo_name: brakthehack/NESEMU