<commit_before>/*
 * examples/solve.C
 *
 * Copyright (C) 2005, 2010 J-G Dumas, D. Saunders, P. Giorgi
 * ========LICENCE========
 * This file is part of the library LinBox.
 *
 * LinBox is free software: you can redistribute it and/or modify
 * it under the terms of the  GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * ========LICENCE========
 */

/** @file examples/solve.C
 * @ingroup examples
 * @brief Blackbox solvers.
 * @warning some are commented out...
 * @example  examples/solve.C
 */

#include <linbox/linbox-config.h>

#include <iostream>

#include <givaro/modular.h>
#include <givaro/zring.h>
#include <linbox/matrix/sparse-matrix.h>
#include <linbox/solutions/solve.h>
#include <linbox/util/matrix-stream.h>
#include <linbox/solutions/methods.h>

using namespace LinBox;
using namespace std;

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

	commentator().setMaxDetailLevel (-1);
	commentator().setMaxDepth (-1);
	commentator().setReportStream (std::cerr);

	if (argc < 2 || argc > 4) {
		cerr << "Usage: solve <matrix-file-in-supported-format> [<dense-vector-file>] [<p>]" << endl;
		return 0;
	}
	srand48( BaseTimer::seed() );

	std::ifstream input (argv[1]);
	if (!input) { cerr << "Error opening matrix file " << argv[1] << endl; return -1; }
	std::ifstream invect;

	bool createB = false;
	int ModComp = 0;
	if (argc == 2) {
		createB = true;
		ModComp = 0;
	}

	if (argc == 3) {
		invect.open (argv[2], std::ifstream::in);
		if (!invect) {
			createB = true;
			ModComp = 2;
		}
		else {
			createB = false;
			ModComp = 0;
		}
	}

	if (argc == 4) {
		ModComp = 3;
		invect.open (argv[2], std::ifstream::in);
		if (!invect) {
			createB = true;
		}
		else
			createB = false;
	}

	if (ModComp) {
                cout<<"Computation is done over Z/("<<atoi(argv[ModComp])<<")"<<endl;
		typedef Givaro::Modular<double> Field;
		double q = atof(argv[ModComp]);
		typedef DenseVector<Field> DenseVector ;
		Field F(q);
		MatrixStream< Field > ms ( F, input );
		SparseMatrix<Field> A (ms);  // A.write(std::cout);
		cout << "A is " << A.rowdim() << " by " << A.coldim() << endl;
                if (A.rowdim() <= 20 && A.coldim() <= 20) A.write(std::cerr << "A:=",Tag::FileFormat::Maple) << ';' << std::endl;
		DenseVector X(F, A.coldim()),B(F, A.rowdim());
		if (createB) {
			cerr << "Creating a random {-1,1} vector U, B is AU (to have a consistent system)" << endl;
			DenseVector U(F, A.coldim() );
			for(DenseVector::iterator it=U.begin();
			    it != U.end(); ++it)
				if (drand48() <0.5)
					F.assign(*it,F.mOne);
				else
					F.assign(*it,F.one);
			A.apply(B,U);
		}
		else {
			for(DenseVector::iterator it=B.begin();
			    it != B.end(); ++it)
				F.read(invect,*it);
		}

		//         A.write(std::cout << "A: ") << std::endl;

		std::cout << "B is " << B << std::endl;

		Timer chrono;

		// Sparse Elimination
		std::cout << "Sparse Elimination" << std::endl;
		chrono.clear();
		chrono.start();
		Method::SparseElimination M;
		solve (X, A, B, M);
		chrono.stop();

		std::cout << "(Sparse Gauss) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			F.write(cout, *it) << " ";
		std::cout << "]" << std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl<<std::endl;;

		// BlasElimination
		std::cout << "BlasElimination" << std::endl;
		chrono.start();
		solve (X, A, B, Method::BlasElimination());
		chrono.stop();

		std::cout << "(BlasElimination) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			F.write(cout, *it) << " ";
		std::cout << "]" << std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl<< std::endl;

		// Wiedemann
		std::cout << "Blackbox" << std::endl;
		chrono.clear();
		chrono.start();
		solve (X, A, B, Method::Blackbox());
		chrono.stop();

		std::cout << "(Wiedemann) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			F.write(cout, *it) << " ";
		std::cout << "]" << std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl<<std::endl;;
#if 0
		// Lanczos
		std::cout << "Lanczos" << std::endl;
		chrono.clear();
		chrono.start();
		solve (X, A, B, Method::Lanczos());
		chrono.stop();

		std::cout << "(Lanczos) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			F.write(cout, *it) << " ";
		std::cout << "]" << std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl<< std::endl;

		// Block Lanczos
		std::cout << "Block Lanczos" << std::endl;
		Method::BlockLanczos MBL;
		MBL.preconditioner(Specifier::FULL_DIAGONAL);
		chrono.clear();
		chrono.start();
		solve (X, A, B, MBL);
		chrono.stop();

		std::cout << "(Block Lanczos) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			F.write(cout, *it) << " ";
		std::cout << "]" << std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl<< std::endl;
#endif

	}
	else {
                cout<<"Computation is done over Q"<<endl;
		Givaro::ZRing<Integer> ZZ;
		typedef DenseVector<Givaro::ZRing<Integer> > DenseVector ;
		MatrixStream< Givaro::ZRing<Integer> > ms( ZZ, input );
		SparseMatrix<Givaro::ZRing<Integer> > A (ms);
		Givaro::ZRing<Integer>::Element d;
		std::cout << "A is " << A.rowdim() << " by " << A.coldim() << std::endl;
                if (A.rowdim() <= 20 && A.coldim() <= 20) A.write(std::cerr << "A:=",Tag::FileFormat::Maple) << ';' << std::endl;
		DenseVector X(ZZ, A.coldim()),B(ZZ, A.rowdim());

		if (createB) {
			cerr << "Creating a random {-1,1} vector U, B is AU" << endl;
			DenseVector U(ZZ, A.coldim() );
			for(DenseVector::iterator it=U.begin();
			    it != U.end(); ++it)
				if (drand48() <0.5)
					*it = -1;
				else
					*it = 1;
			A.apply(B,U);
		}
		else {
			for(DenseVector::iterator it=B.begin();
			    it != B.end(); ++it)
				invect >> *it;
		}

		std::cout << "B is " << B << std::endl;

		Timer chrono;
/*
		// BlasElimination
                std::cout << "BlasElimination" << std::endl;
                chrono.start();
                solve (X, d, A, B, Method::BlasElimination());
                chrono.stop();

 		std::cout << "(BlasElimination) Solution is [";
                for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
 			ZZ.write(cout, *it) << " ";
                std::cout << "] / ";
                ZZ.write(std::cout, d)<< std::endl;
                std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl;
                */

		// Sparse Elimination
		std::cout << "Sparse Elimination" << std::endl;
		chrono.start();
		solve (X, d, A, B, Method::SparseElimination());
		chrono.stop();

		std::cout << "(SparseElimination) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			ZZ.write(cout, *it) << " ";
		std::cout << "] / ";
		ZZ.write(std::cout, d)<< std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl;

                		// Wiedemann
		std::cout << "Wiedemann" << std::endl;
		chrono.start();
		solve (X, d, A, B, Method::Wiedemann());
		chrono.stop();

		std::cout << "(Wiedemann) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			ZZ.write(cout, *it) << " ";
		std::cout << "] / ";
		ZZ.write(std::cout, d) << std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl;

#if 0
		// Lanczos
		std::cout << "Lanczos" << std::endl;
		chrono.start();
		solve (X, d, A, B, Method::Lanczos());
		chrono.stop();

		std::cout << "(Lanczos) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			ZZ.write(cout, *it) << " ";
		std::cout << "] / ";
		ZZ.write(std::cout, d) << std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl;

		// Block Lanczos
		std::cout << "Block Lanczos" << std::endl;
		chrono.clear();
		chrono.start();
		solve (X, d, A, B, Method::BlockLanczos());
		chrono.stop();

		std::cout << "(Block Lanczos) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			ZZ.write(cout, *it) << " ";
		std::cout << "] / ";
		ZZ.write(std::cout, d) << std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl;
#endif
	}

	return 0;
}

// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<commit_msg>iput back blas<commit_after>/*
 * examples/solve.C
 *
 * Copyright (C) 2005, 2010 J-G Dumas, D. Saunders, P. Giorgi
 * ========LICENCE========
 * This file is part of the library LinBox.
 *
 * LinBox is free software: you can redistribute it and/or modify
 * it under the terms of the  GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * ========LICENCE========
 */

/** @file examples/solve.C
 * @ingroup examples
 * @brief Blackbox solvers.
 * @warning some are commented out...
 * @example  examples/solve.C
 */

#include <linbox/linbox-config.h>

#include <iostream>

#include <givaro/modular.h>
#include <givaro/zring.h>
#include <linbox/matrix/sparse-matrix.h>
#include <linbox/solutions/solve.h>
#include <linbox/util/matrix-stream.h>
#include <linbox/solutions/methods.h>

using namespace LinBox;
using namespace std;

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

	commentator().setMaxDetailLevel (-1);
	commentator().setMaxDepth (-1);
	commentator().setReportStream (std::cerr);

	if (argc < 2 || argc > 4) {
		cerr << "Usage: solve <matrix-file-in-supported-format> [<dense-vector-file>] [<p>]" << endl;
		return 0;
	}
	srand48( BaseTimer::seed() );

	std::ifstream input (argv[1]);
	if (!input) { cerr << "Error opening matrix file " << argv[1] << endl; return -1; }
	std::ifstream invect;

	bool createB = false;
	int ModComp = 0;
	if (argc == 2) {
		createB = true;
		ModComp = 0;
	}

	if (argc == 3) {
		invect.open (argv[2], std::ifstream::in);
		if (!invect) {
			createB = true;
			ModComp = 2;
		}
		else {
			createB = false;
			ModComp = 0;
		}
	}

	if (argc == 4) {
		ModComp = 3;
		invect.open (argv[2], std::ifstream::in);
		if (!invect) {
			createB = true;
		}
		else
			createB = false;
	}

	if (ModComp) {
                cout<<"Computation is done over Z/("<<atoi(argv[ModComp])<<")"<<endl;
		typedef Givaro::Modular<double> Field;
		double q = atof(argv[ModComp]);
		typedef DenseVector<Field> DenseVector ;
		Field F(q);
		MatrixStream< Field > ms ( F, input );
		SparseMatrix<Field> A (ms);  // A.write(std::cout);
		cout << "A is " << A.rowdim() << " by " << A.coldim() << endl;
                if (A.rowdim() <= 20 && A.coldim() <= 20) A.write(std::cerr << "A:=",Tag::FileFormat::Maple) << ';' << std::endl;
		DenseVector X(F, A.coldim()),B(F, A.rowdim());
		if (createB) {
			cerr << "Creating a random {-1,1} vector U, B is AU (to have a consistent system)" << endl;
			DenseVector U(F, A.coldim() );
			for(DenseVector::iterator it=U.begin();
			    it != U.end(); ++it)
				if (drand48() <0.5)
					F.assign(*it,F.mOne);
				else
					F.assign(*it,F.one);
			A.apply(B,U);
		}
		else {
			for(DenseVector::iterator it=B.begin();
			    it != B.end(); ++it)
				F.read(invect,*it);
		}

		//         A.write(std::cout << "A: ") << std::endl;

		std::cout << "B is " << B << std::endl;

		Timer chrono;

		// Sparse Elimination
		std::cout << "Sparse Elimination" << std::endl;
		chrono.clear();
		chrono.start();
		Method::SparseElimination M;
		solve (X, A, B, M);
		chrono.stop();

		std::cout << "(Sparse Gauss) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			F.write(cout, *it) << " ";
		std::cout << "]" << std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl<<std::endl;;

		// BlasElimination
		std::cout << "BlasElimination" << std::endl;
		chrono.start();
		solve (X, A, B, Method::BlasElimination());
		chrono.stop();

		std::cout << "(BlasElimination) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			F.write(cout, *it) << " ";
		std::cout << "]" << std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl<< std::endl;

		// Wiedemann
		std::cout << "Blackbox" << std::endl;
		chrono.clear();
		chrono.start();
		solve (X, A, B, Method::Blackbox());
		chrono.stop();

		std::cout << "(Wiedemann) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			F.write(cout, *it) << " ";
		std::cout << "]" << std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl<<std::endl;;
#if 0
		// Lanczos
		std::cout << "Lanczos" << std::endl;
		chrono.clear();
		chrono.start();
		solve (X, A, B, Method::Lanczos());
		chrono.stop();

		std::cout << "(Lanczos) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			F.write(cout, *it) << " ";
		std::cout << "]" << std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl<< std::endl;

		// Block Lanczos
		std::cout << "Block Lanczos" << std::endl;
		Method::BlockLanczos MBL;
		MBL.preconditioner(Specifier::FULL_DIAGONAL);
		chrono.clear();
		chrono.start();
		solve (X, A, B, MBL);
		chrono.stop();

		std::cout << "(Block Lanczos) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			F.write(cout, *it) << " ";
		std::cout << "]" << std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl<< std::endl;
#endif

	}
	else {
                cout<<"Computation is done over Q"<<endl;
		Givaro::ZRing<Integer> ZZ;
		typedef DenseVector<Givaro::ZRing<Integer> > DenseVector ;
		MatrixStream< Givaro::ZRing<Integer> > ms( ZZ, input );
		SparseMatrix<Givaro::ZRing<Integer> > A (ms);
		Givaro::ZRing<Integer>::Element d;
		std::cout << "A is " << A.rowdim() << " by " << A.coldim() << std::endl;
                if (A.rowdim() <= 20 && A.coldim() <= 20) A.write(std::cerr << "A:=",Tag::FileFormat::Maple) << ';' << std::endl;
		DenseVector X(ZZ, A.coldim()),B(ZZ, A.rowdim());

		if (createB) {
			cerr << "Creating a random {-1,1} vector U, B is AU" << endl;
			DenseVector U(ZZ, A.coldim() );
			for(DenseVector::iterator it=U.begin();
			    it != U.end(); ++it)
				if (drand48() <0.5)
					*it = -1;
				else
					*it = 1;
			A.apply(B,U);
		}
		else {
			for(DenseVector::iterator it=B.begin();
			    it != B.end(); ++it)
				invect >> *it;
		}

		std::cout << "B is " << B << std::endl;

		Timer chrono;
		// BlasElimination
        std::cout << "BlasElimination" << std::endl;
        chrono.start();
        solve (X, d, A, B, Method::BlasElimination());
        chrono.stop();

 		std::cout << "(BlasElimination) Solution is [";
        for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
 		ZZ.write(cout, *it) << " ";
        std::cout << "] / ";
        ZZ.write(std::cout, d)<< std::endl;
        std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl;

		// Sparse Elimination
		std::cout << "Sparse Elimination" << std::endl;
		chrono.start();
		solve (X, d, A, B, Method::SparseElimination());
		chrono.stop();

		std::cout << "(SparseElimination) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			ZZ.write(cout, *it) << " ";
		std::cout << "] / ";
		ZZ.write(std::cout, d)<< std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl;

                		// Wiedemann
		std::cout << "Wiedemann" << std::endl;
		chrono.start();
		solve (X, d, A, B, Method::Wiedemann());
		chrono.stop();

		std::cout << "(Wiedemann) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			ZZ.write(cout, *it) << " ";
		std::cout << "] / ";
		ZZ.write(std::cout, d) << std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl;

#if 0
		// Lanczos
		std::cout << "Lanczos" << std::endl;
		chrono.start();
		solve (X, d, A, B, Method::Lanczos());
		chrono.stop();

		std::cout << "(Lanczos) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			ZZ.write(cout, *it) << " ";
		std::cout << "] / ";
		ZZ.write(std::cout, d) << std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl;

		// Block Lanczos
		std::cout << "Block Lanczos" << std::endl;
		chrono.clear();
		chrono.start();
		solve (X, d, A, B, Method::BlockLanczos());
		chrono.stop();

		std::cout << "(Block Lanczos) Solution is [";
		for(DenseVector::const_iterator it=X.begin();it != X.end(); ++it)
			ZZ.write(cout, *it) << " ";
		std::cout << "] / ";
		ZZ.write(std::cout, d) << std::endl;
		std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl;
#endif
	}

	return 0;
}

// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<|endoftext|>


<commit_before>/*
 *
 * copyright (c) 2010 ZAO Inventos (inventos.ru)
 * copyright (c) 2010 jk@inventos.ru
 * copyright (c) 2010 kuzalex@inventos.ru
 * copyright (c) 2010 artint@inventos.ru
 *
 * This file is part of mp4frag.
 *
 * mp4grag is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * mp4frag 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
 * Lesser General Public License for more details.
 */

#include "mp4frag.hh"
#include <boost/program_options.hpp>
#include <boost/system/system_error.hpp>
#include <boost/system/error_code.hpp>
#include <boost/foreach.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include <stdexcept>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>

using namespace boost::system;
namespace bfs = boost::filesystem;
using boost::lexical_cast;

namespace {
    bfs::path manifest_name = "manifest.f4m";
    std::string video_id("some_video");
    std::vector<bfs::path> srcfiles;
    bool produce_template = false;
    int fragment_duration;
}

void parse_options(int argc, char **argv) {
    namespace po = boost::program_options;

    po::options_description desc("Allowed options");
    desc.add_options()
      ("help", "produce help message")
      ("src", po::value< std::vector<bfs::path> >(&srcfiles), "source mp4 file name")
      ("video_id", po::value<std::string>(&video_id)->default_value("some_video"), "video id for manifest file")
      ("manifest", po::value<bfs::path>(&manifest_name)->default_value("manifest.f4m"), "manifest file name")
      ("fragmentduration", po::value<int>(&fragment_duration)->default_value(3000), "single fragment duration, ms")
      ("template", "make template files instead of full fragments")
    ;

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

    if (vm.count("help") || argc == 1 || srcfiles.size() == 0) {
        std::cerr << desc << "\n";
        exit(1);
    }

    produce_template = vm.count("template") != 0;

}

boost::shared_ptr<Mapping> create_mapping(const std::string& filename) {
    return boost::shared_ptr<Mapping>(new Mapping(filename.c_str()));
}

#include <sys/time.h>

int main(int argc, char **argv) try {
    parse_options(argc, argv);

    std::vector<boost::shared_ptr<Media> > fileinfo_list;

    struct timeval then, now;
    gettimeofday(&then, 0);
    BOOST_FOREACH(bfs::path& srcfile, srcfiles) {
        boost::shared_ptr<Media> pmedia = make_fragments(srcfile.string(), fragment_duration);
        fileinfo_list.push_back(pmedia);
        pmedia->medianame = bfs::complete(srcfile).string();
    }
    gettimeofday(&now, 0);
    double diff = now.tv_sec - then.tv_sec + 1e-6*(now.tv_usec - then.tv_usec);
    gettimeofday(&then, 0);
    gettimeofday(&now, 0);
    diff -= now.tv_sec - then.tv_sec + 1e-6*(now.tv_usec - then.tv_usec);

    std::cerr << "Parsed in " << diff << " seconds\n";

    if ( produce_template ) {
        std::filebuf out;
        std::string indexname = (manifest_name.parent_path() / "index").string();
        if ( out.open(indexname.c_str(), std::ios::out | std::ios::binary | std::ios::trunc) ) {
            serialize(&out, fileinfo_list);
            if ( !out.close() ) {
                throw std::runtime_error("Error closing " + indexname);
            }
        }
        else {
                throw std::runtime_error("Error opening " + indexname);
        }
#if TESTING
        Mapping index(indexname.c_str());
        for ( unsigned ix = 0; ix < fileinfo_list.size(); ++ix ) {
            boost::shared_ptr<Media>& pmedia = fileinfo_list[ix];
            bfs::path mediadir = manifest_name.parent_path() / lexical_cast<std::string>(ix);
            if ( mkdir(mediadir.string().c_str(), 0755) == -1 && errno != EEXIST ) {
                throw system_error(errno, get_system_category(), "mkdir " + mediadir.string());
            }
            for ( unsigned fragment = 1; fragment <= pmedia->fragments.size(); ++fragment ) {
                std::filebuf out;
                std::string fragment_basename = std::string("Seg1-Frag") + boost::lexical_cast<std::string>(fragment);
                bfs::path fragment_file = mediadir / fragment_basename;
                if ( out.open(fragment_file.string().c_str(), std::ios::out | std::ios::binary | std::ios::trunc) ) {
                    get_fragment(&out, ix, fragment - 1, index.data(), index.size(), create_mapping);
                    if ( !out.close() ) {
                        throw std::runtime_error("Error closing " + fragment_file.string());
                    }
                }
                else {
                    throw std::runtime_error("Error opening " + fragment_file.string());
                }
            }
        }
#endif
    }
    else {
        for ( unsigned ix = 0; ix < fileinfo_list.size(); ++ix ) {
            boost::shared_ptr<Media>& pmedia = fileinfo_list[ix];
            bfs::path mediadir = manifest_name.parent_path() / lexical_cast<std::string>(ix);
            if ( mkdir(mediadir.string().c_str(), 0755) == -1 && errno != EEXIST ) {
                throw system_error(errno, get_system_category(), "mkdir " + mediadir.string());
            }
            for ( unsigned fragment = 1; fragment <= pmedia->fragments.size(); ++fragment ) {
                std::filebuf out;
                std::string fragment_basename = std::string("Seg1-Frag") + boost::lexical_cast<std::string>(fragment);
                bfs::path fragment_file = mediadir / fragment_basename;
                if ( out.open(fragment_file.string().c_str(), std::ios::out | std::ios::binary | std::ios::trunc) ) {
                    serialize_fragment(&out, pmedia, fragment - 1);
                    if ( !out.close() ) {
                        throw std::runtime_error("Error closing " + fragment_file.string());
                    }
                }
                else {
                    throw std::runtime_error("Error opening " + fragment_file.string());
                }
            }
        }
    }

    std::filebuf manifest_filebuf;
    if ( manifest_filebuf.open(manifest_name.string().c_str(),
                               std::ios::out | std::ios::binary | std::ios::trunc) ) {
        get_manifest(&manifest_filebuf, fileinfo_list, video_id);
        if ( !manifest_filebuf.close() ) {
            std::stringstream errmsg;
            errmsg << "Error closing " << manifest_name;
            throw std::runtime_error(errmsg.str());
        }
    }
    else {
        throw std::runtime_error("Error opening " + manifest_name.string());
    }
}
catch ( std::exception& e ) {
    std::cerr << e.what() << "\n";
}
<commit_msg>Manifest only generation mode added.<commit_after>/*
 *
 * copyright (c) 2010 ZAO Inventos (inventos.ru)
 * copyright (c) 2010 jk@inventos.ru
 * copyright (c) 2010 kuzalex@inventos.ru
 * copyright (c) 2010 artint@inventos.ru
 *
 * This file is part of mp4frag.
 *
 * mp4grag is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * mp4frag 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
 * Lesser General Public License for more details.
 */

#include "mp4frag.hh"
#include <boost/program_options.hpp>
#include <boost/system/system_error.hpp>
#include <boost/system/error_code.hpp>
#include <boost/foreach.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include <stdexcept>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>

using namespace boost::system;
namespace bfs = boost::filesystem;
using boost::lexical_cast;

namespace {
    bfs::path manifest_name = "manifest.f4m";
    std::string video_id("some_video");
    std::vector<bfs::path> srcfiles;
    bool produce_template = false;
    bool manifest_only = false;
    int fragment_duration;
}

void parse_options(int argc, char **argv) {
    namespace po = boost::program_options;

    po::options_description desc("Allowed options");
    desc.add_options()
      ("help", "produce help message")
      ("src", po::value< std::vector<bfs::path> >(&srcfiles), "source mp4 file name")
      ("video_id", po::value<std::string>(&video_id)->default_value("some_video"), "video id for manifest file")
      ("manifest", po::value<bfs::path>(&manifest_name)->default_value("manifest.f4m"), "manifest file name")
      ("fragmentduration", po::value<int>(&fragment_duration)->default_value(3000), "single fragment duration, ms")
      ("template", "make template files instead of full fragments")
      ("manifest-only", "make manifest only")
    ;

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

    if (vm.count("help") || argc == 1 || srcfiles.size() == 0) {
        std::cerr << desc << "\n";
        exit(1);
    }

    produce_template = vm.count("template") != 0;
    manifest_only = vm.count("manifest-only") != 0;

}

boost::shared_ptr<Mapping> create_mapping(const std::string& filename) {
    return boost::shared_ptr<Mapping>(new Mapping(filename.c_str()));
}

#include <sys/time.h>

int main(int argc, char **argv) try {
    parse_options(argc, argv);

    std::vector<boost::shared_ptr<Media> > fileinfo_list;

    struct timeval then, now;
    gettimeofday(&then, 0);
    BOOST_FOREACH(bfs::path& srcfile, srcfiles) {
        boost::shared_ptr<Media> pmedia = make_fragments(srcfile.string(), fragment_duration);
        fileinfo_list.push_back(pmedia);
        pmedia->medianame = bfs::complete(srcfile).string();
    }
    gettimeofday(&now, 0);
    double diff = now.tv_sec - then.tv_sec + 1e-6*(now.tv_usec - then.tv_usec);
    gettimeofday(&then, 0);
    gettimeofday(&now, 0);
    diff -= now.tv_sec - then.tv_sec + 1e-6*(now.tv_usec - then.tv_usec);

    std::cerr << "Parsed in " << diff << " seconds\n";

    if ( !manifest_only ) {
    if ( produce_template ) {
        std::filebuf out;
        std::string indexname = (manifest_name.parent_path() / "index").string();
        if ( out.open(indexname.c_str(), std::ios::out | std::ios::binary | std::ios::trunc) ) {
            serialize(&out, fileinfo_list);
            if ( !out.close() ) {
                throw std::runtime_error("Error closing " + indexname);
            }
        }
        else {
                throw std::runtime_error("Error opening " + indexname);
        }
#if TESTING
        Mapping index(indexname.c_str());
        for ( unsigned ix = 0; ix < fileinfo_list.size(); ++ix ) {
            boost::shared_ptr<Media>& pmedia = fileinfo_list[ix];
            bfs::path mediadir = manifest_name.parent_path() / lexical_cast<std::string>(ix);
            if ( mkdir(mediadir.string().c_str(), 0755) == -1 && errno != EEXIST ) {
                throw system_error(errno, get_system_category(), "mkdir " + mediadir.string());
            }
            for ( unsigned fragment = 1; fragment <= pmedia->fragments.size(); ++fragment ) {
                std::filebuf out;
                std::string fragment_basename = std::string("Seg1-Frag") + boost::lexical_cast<std::string>(fragment);
                bfs::path fragment_file = mediadir / fragment_basename;
                if ( out.open(fragment_file.string().c_str(), std::ios::out | std::ios::binary | std::ios::trunc) ) {
                    get_fragment(&out, ix, fragment - 1, index.data(), index.size(), create_mapping);
                    if ( !out.close() ) {
                        throw std::runtime_error("Error closing " + fragment_file.string());
                    }
                }
                else {
                    throw std::runtime_error("Error opening " + fragment_file.string());
                }
            }
        }
#endif
    }
    else {
        for ( unsigned ix = 0; ix < fileinfo_list.size(); ++ix ) {
            boost::shared_ptr<Media>& pmedia = fileinfo_list[ix];
            bfs::path mediadir = manifest_name.parent_path() / lexical_cast<std::string>(ix);
            if ( mkdir(mediadir.string().c_str(), 0755) == -1 && errno != EEXIST ) {
                throw system_error(errno, get_system_category(), "mkdir " + mediadir.string());
            }
            for ( unsigned fragment = 1; fragment <= pmedia->fragments.size(); ++fragment ) {
                std::filebuf out;
                std::string fragment_basename = std::string("Seg1-Frag") + boost::lexical_cast<std::string>(fragment);
                bfs::path fragment_file = mediadir / fragment_basename;
                if ( out.open(fragment_file.string().c_str(), std::ios::out | std::ios::binary | std::ios::trunc) ) {
                    serialize_fragment(&out, pmedia, fragment - 1);
                    if ( !out.close() ) {
                        throw std::runtime_error("Error closing " + fragment_file.string());
                    }
                }
                else {
                    throw std::runtime_error("Error opening " + fragment_file.string());
                }
            }
        }
    }
    }

    std::filebuf manifest_filebuf;
    if ( manifest_filebuf.open(manifest_name.string().c_str(),
                               std::ios::out | std::ios::binary | std::ios::trunc) ) {
        get_manifest(&manifest_filebuf, fileinfo_list, video_id);
        if ( !manifest_filebuf.close() ) {
            std::stringstream errmsg;
            errmsg << "Error closing " << manifest_name;
            throw std::runtime_error(errmsg.str());
        }
    }
    else {
        throw std::runtime_error("Error opening " + manifest_name.string());
    }
}
catch ( std::exception& e ) {
    std::cerr << e.what() << "\n";
}
<|endoftext|>


<commit_before>// AMX profiler for SA-MP server: http://sa-mp.com
//
// Copyright (C) 2011-2012 Sergey Zolotarev
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef AMX_PROFILER_CALL_GRAPH_WRITER_H
#define AMX_PROFILER_CALL_GRAPH_WRITER_H

#include <algorithm>
#include <iostream>
#include <tuple>
#include "call_graph.h"
#include "call_graph_writer_gv.h"
#include "function.h"
#include "function_info.h"
#include "time_interval.h"

namespace amx_profiler {

CallGraphWriterGV::CallGraphWriterGV(std::ostream *stream, const std::string &name)
	: stream_(stream)
	, name_(name)
{
}

void CallGraphWriterGV::Write(const CallGraph &graph) {
	*stream_ <<
	"digraph Profile {\n"
	"	size=\"6,4\"; ratio = fill;\n"
	"	node [style=filled];\n"
	;

	// Write basic graph (nodes + arrows).
	graph.Traverse([this](const std::shared_ptr<const CallGraphNode> &node) {
		if (!node->callees().empty()) {
			std::string caller_name;
			if (node->info()) {
				caller_name = node->info()->function()->name();
			} else {
				caller_name = "<host>";
			}
			std::for_each(node->callees().begin(), node->callees().end(), [&](const std::shared_ptr<CallGraphNode> &c) {
				std::string color;
				if (c->info()->function()->type() == "public") {
					color = "#001EE0";
				} else if (c->info()->function()->type() == "native") {
					color = "#9900E0";
				} else {
					color = "#000000";
				}
				*stream_ << "\t\"" << caller_name << "\" -> \"" << c->info()->function()->name()
					<< "\" [color=\"" << color << "\"];" << std::endl;
			});
		}
	});

	// Get maximum execution time.
	TimeInterval max_time = 0;
	graph.Traverse([&max_time, &graph](const std::shared_ptr<const CallGraphNode> &node) {
		if (node != graph.sentinel()) {
			auto time = node->info()->GetSelfTime();
			if (time > max_time) {
				max_time = time;
			}
		}
	});

	// Color nodes depending to draw attention to hot spots.
	graph.Traverse([&max_time, this, &graph](const std::shared_ptr<const CallGraphNode> &node) {
		if (node != graph.sentinel()) {
			auto time = node->info()->GetSelfTime();
			auto ratio = static_cast<double>(time) / static_cast<double>(max_time);
			// We encode color in hue-saturation-brightness.
			auto hsb = std::make_tuple((1.0 - ratio) * 0.65, (ratio * 0.8) + 0.2, 1.0);
			*stream_ << "\t\"" << node->info()->function()->name() << "\" [color=\""
				<< std::get<0>(hsb) << ", "
				<< std::get<1>(hsb) << ", "
				<< std::get<2>(hsb)
			<< "\"];" << std::endl;
		}
	});

	*stream_ <<
	"}\n";
}

} // namespace amx_profiler

#endif // !AMX_PROFILER_CALL_GRAPH_WRITER_H

<commit_msg>Learn CallGraphWriterGV respect the name parameter<commit_after>// AMX profiler for SA-MP server: http://sa-mp.com
//
// Copyright (C) 2011-2012 Sergey Zolotarev
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef AMX_PROFILER_CALL_GRAPH_WRITER_H
#define AMX_PROFILER_CALL_GRAPH_WRITER_H

#include <algorithm>
#include <iostream>
#include <tuple>
#include "call_graph.h"
#include "call_graph_writer_gv.h"
#include "function.h"
#include "function_info.h"
#include "time_interval.h"

namespace amx_profiler {

CallGraphWriterGV::CallGraphWriterGV(std::ostream *stream, const std::string &name)
	: stream_(stream)
	, name_(name)
{
}

void CallGraphWriterGV::Write(const CallGraph &graph) {
	*stream_ <<
	"digraph \"Call graph of " << name_ << "\" {\n"
	"	size=\"6,4\"; ratio = fill;\n"
	"	node [style=filled];\n"
	;

	// Write basic graph (nodes + arrows).
	graph.Traverse([this](const std::shared_ptr<const CallGraphNode> &node) {
		if (!node->callees().empty()) {
			std::string caller_name;
			if (node->info()) {
				caller_name = node->info()->function()->name();
			} else {
				caller_name = "<host>";
			}
			std::for_each(node->callees().begin(), node->callees().end(), [&](const std::shared_ptr<CallGraphNode> &c) {
				std::string color;
				if (c->info()->function()->type() == "public") {
					color = "#001EE0";
				} else if (c->info()->function()->type() == "native") {
					color = "#9900E0";
				} else {
					color = "#000000";
				}
				*stream_ << "\t\"" << caller_name << "\" -> \"" << c->info()->function()->name()
					<< "\" [color=\"" << color << "\"];" << std::endl;
			});
		}
	});

	// Get maximum execution time.
	TimeInterval max_time = 0;
	graph.Traverse([&max_time, &graph](const std::shared_ptr<const CallGraphNode> &node) {
		if (node != graph.sentinel()) {
			auto time = node->info()->GetSelfTime();
			if (time > max_time) {
				max_time = time;
			}
		}
	});

	// Color nodes depending to draw attention to hot spots.
	graph.Traverse([&max_time, this, &graph](const std::shared_ptr<const CallGraphNode> &node) {
		if (node != graph.sentinel()) {
			auto time = node->info()->GetSelfTime();
			auto ratio = static_cast<double>(time) / static_cast<double>(max_time);
			// We encode color in hue-saturation-brightness.
			auto hsb = std::make_tuple((1.0 - ratio) * 0.65, (ratio * 0.8) + 0.2, 1.0);
			*stream_ << "\t\"" << node->info()->function()->name() << "\" [color=\""
				<< std::get<0>(hsb) << ", "
				<< std::get<1>(hsb) << ", "
				<< std::get<2>(hsb)
			<< "\"];" << std::endl;
		}
	});

	*stream_ <<
	"}\n";
}

} // namespace amx_profiler

#endif // !AMX_PROFILER_CALL_GRAPH_WRITER_H

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: bitmapbackbuffer.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 23:16:25 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _VCLCANVAS_BITMAPBACKBUFFER_HXX_
#define _VCLCANVAS_BITMAPBACKBUFFER_HXX_

#ifndef _SV_VIRDEV_HXX
#include <vcl/virdev.hxx>
#endif

#include <canvas/vclwrapper.hxx>
#include "outdevprovider.hxx"

namespace vclcanvas
{
    /** OutDevProvider implementation for canvas bitmap.

        This class implements the OutDevProvider interface for the
        bitmap canvas. The actual VirtualDevice is only created when
        necessary, which makes read-only bitmaps a lot smaller.
    */
    class BitmapBackBuffer : public OutDevProvider
    {
    public:
        /** Create a backbuffer for given reference device
         */
        BitmapBackBuffer( const BitmapEx&       rBitmap,
                          const OutputDevice&   rRefDevice );

        ~BitmapBackBuffer();

        virtual OutputDevice&           getOutDev();
        virtual const OutputDevice&     getOutDev() const;

        VirtualDevice&                  getVirDev();
        const VirtualDevice&            getVirDev() const;

        /** Exposing our internal bitmap. Only to be used from
            CanvasBitmapHelper

            @internal
        */
        BitmapEx&                       getBitmapReference();

    private:
        void createVDev() const;
        void updateVDev() const;

        ::canvas::vcltools::VCLObject<BitmapEx> maBitmap;
        mutable VirtualDevice*                  mpVDev; // created only on demand

        const OutputDevice&                     mrRefDevice;

        /** When true, the bitmap contains the last valid
            content. When false, and mbVDevContentIsCurrent is true,
            the VDev contains the last valid content (which must be
            copied back to the bitmap, when getBitmapReference() is
            called). When both are false, this object is just
            initialized.
         */
        mutable bool                            mbBitmapContentIsCurrent;

        /** When true, and mpVDev is non-NULL, the VDev contains the
            last valid content. When false, and
            mbBitmapContentIsCurrent is true, the bitmap contains the
            last valid content. When both are false, this object is
            just initialized.
         */
        mutable bool                            mbVDevContentIsCurrent;
    };

    typedef ::boost::shared_ptr< BitmapBackBuffer > BitmapBackBufferSharedPtr;

}

#endif /* #ifndef _VCLCANVAS_BITMAPBACKBUFFER_HXX_ */
<commit_msg>INTEGRATION: CWS canvas02 (1.3.10); FILE MERGED 2005/10/08 12:52:04 thb 1.3.10.2: RESYNC: (1.3-1.4); FILE MERGED 2005/06/17 23:49:48 thb 1.3.10.1: #i48939# Huge refactoring of canvas; as much functionality as possible is now common in a bunch of shared base classes (input checking, locking, sprite redraw, etc.); added scroll update optimization, transparently to all canvas implementations<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: bitmapbackbuffer.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2005-11-02 12:57:35 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _VCLCANVAS_BITMAPBACKBUFFER_HXX_
#define _VCLCANVAS_BITMAPBACKBUFFER_HXX_

#include <vcl/virdev.hxx>
#include <vcl/bitmapex.hxx>

#include <canvas/vclwrapper.hxx>
#include "outdevprovider.hxx"

#include <boost/shared_ptr.hpp>

namespace vclcanvas
{
    /** Backbuffer implementation for canvas bitmap.

        This class abstracts away the renderable bitmap for the bitmap
        canvas. The actual VirtualDevice is only created when
        necessary, which makes read-only bitmaps a lot smaller.
    */
    class BitmapBackBuffer : public OutDevProvider
    {
    public:
        /** Create a backbuffer for given reference device
         */
        BitmapBackBuffer( const BitmapEx&       rBitmap,
                          const OutputDevice&   rRefDevice );

        ~BitmapBackBuffer();

        virtual OutputDevice&       getOutDev();
        virtual const OutputDevice& getOutDev() const;

        VirtualDevice&              getVirDev();
        const VirtualDevice&        getVirDev() const;

        /** Exposing our internal bitmap. Only to be used from
            CanvasBitmapHelper

            @internal
        */
        BitmapEx&                   getBitmapReference();

    private:
        void createVDev() const;
        void updateVDev() const;

        ::canvas::vcltools::VCLObject<BitmapEx> maBitmap;
        mutable VirtualDevice*                  mpVDev; // created only on demand

        const OutputDevice&                     mrRefDevice;

        /** When true, the bitmap contains the last valid
            content. When false, and mbVDevContentIsCurrent is true,
            the VDev contains the last valid content (which must be
            copied back to the bitmap, when getBitmapReference() is
            called). When both are false, this object is just
            initialized.
         */
        mutable bool                            mbBitmapContentIsCurrent;

        /** When true, and mpVDev is non-NULL, the VDev contains the
            last valid content. When false, and
            mbBitmapContentIsCurrent is true, the bitmap contains the
            last valid content. When both are false, this object is
            just initialized.
         */
        mutable bool                            mbVDevContentIsCurrent;
    };

    typedef ::boost::shared_ptr< BitmapBackBuffer > BitmapBackBufferSharedPtr;

}

#endif /* #ifndef _VCLCANVAS_BITMAPBACKBUFFER_HXX_ */
<|endoftext|>


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

#include "bt.hpp"
#include "io.hpp"
#include "lpc.hpp"
#include "p2a.hpp"
#include "pci.hpp"
#include "tool_errors.hpp"
#include "updater.hpp"

/* Use CLI11 argument parser once in openbmc/meta-oe or whatever. */
#include <getopt.h>

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <ipmiblob/blob_handler.hpp>
#include <ipmiblob/ipmi_handler.hpp>
#include <iterator>
#include <memory>
#include <string>
#include <vector>

#define IPMILPC "ipmilpc"
#define IPMIPCI "ipmipci"
#define IPMIBT "ipmibt"

namespace
{
const std::vector<std::string> interfaceList = {IPMIBT, IPMILPC, IPMIPCI};
}

void usage(const char* program)
{
    std::fprintf(
        stderr,
        "Usage: %s --command <command> --interface <interface> --image "
        "<image file> --sig <signature file>\n",
        program);

    std::fprintf(stderr, "interfaces: ");
    std::copy(interfaceList.begin(), interfaceList.end(),
              std::ostream_iterator<std::string>(std::cerr, ", "));
    std::fprintf(stderr, "\n");
}

bool checkCommand(const std::string& command)
{
    return (command == "update");
}

bool checkInterface(const std::string& interface)
{
    auto intf =
        std::find(interfaceList.begin(), interfaceList.end(), interface);
    return (intf != interfaceList.end());
}

int main(int argc, char* argv[])
{
    std::string command, interface, imagePath, signaturePath;

    while (1)
    {
        // clang-format off
        static struct option long_options[] = {
            {"command", required_argument, 0, 'c'},
            {"interface", required_argument, 0, 'i'},
            {"image", required_argument, 0, 'm'},
            {"sig", required_argument, 0, 's'},
            {0, 0, 0, 0}
        };
        // clang-format on

        int option_index = 0;
        int c =
            getopt_long(argc, argv, "c:i:m:s:", long_options, &option_index);
        if (c == -1)
        {
            break;
        }

        switch (c)
        {
            case 'c':
                command = std::string{optarg};
                if (!checkCommand(command))
                {
                    usage(argv[0]);
                    exit(EXIT_FAILURE);
                }

                break;
            case 'i':
                interface = std::string{optarg};
                if (!checkInterface(interface))
                {
                    usage(argv[0]);
                    exit(EXIT_FAILURE);
                }
                break;
            case 'm':
                imagePath = std::string{optarg};
                break;
            case 's':
                signaturePath = std::string{optarg};
                break;
            default:
                usage(argv[0]);
                exit(EXIT_FAILURE);
        }
    }

    if (command.empty())
    {
        usage(argv[0]);
        exit(EXIT_FAILURE);
    }

    /* They want to update the firmware. */
    if (command == "update")
    {
        if (interface.empty() || imagePath.empty() || signaturePath.empty())
        {
            usage(argv[0]);
            exit(EXIT_FAILURE);
        }

        ipmiblob::IpmiHandler ipmi;
        ipmiblob::BlobHandler blob(&ipmi);
        host_tool::DevMemDevice devmem;
        host_tool::PciUtilImpl pci;

        std::unique_ptr<host_tool::DataInterface> handler;

        /* Input has already been validated in this case. */
        if (interface == IPMIBT)
        {
            handler = std::make_unique<host_tool::BtDataHandler>(&blob);
        }
        else if (interface == IPMILPC)
        {
            handler =
                std::make_unique<host_tool::LpcDataHandler>(&blob, &devmem);
        }
        else if (interface == IPMIPCI)
        {
            handler = std::make_unique<host_tool::P2aDataHandler>(
                &blob, &devmem, &pci);
        }

        if (!handler)
        {
            /* TODO(venture): use a custom exception. */
            std::fprintf(stderr, "Interface %s is unavailable\n",
                         interface.c_str());
            exit(EXIT_FAILURE);
        }

        /* The parameters are all filled out. */
        try
        {
            host_tool::updaterMain(&blob, handler.get(), imagePath,
                                   signaturePath);
        }
        catch (const host_tool::ToolException& e)
        {
            std::fprintf(stderr, "Exception received: %s\n", e.what());
            return -1;
        }
    }

    return 0;
}
<commit_msg>tools: main: update ipmi-blob-tool constructors<commit_after>/*
 * Copyright 2018 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "bt.hpp"
#include "io.hpp"
#include "lpc.hpp"
#include "p2a.hpp"
#include "pci.hpp"
#include "tool_errors.hpp"
#include "updater.hpp"

/* Use CLI11 argument parser once in openbmc/meta-oe or whatever. */
#include <getopt.h>

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <ipmiblob/blob_handler.hpp>
#include <ipmiblob/ipmi_handler.hpp>
#include <iterator>
#include <memory>
#include <string>
#include <vector>

#define IPMILPC "ipmilpc"
#define IPMIPCI "ipmipci"
#define IPMIBT "ipmibt"

namespace
{
const std::vector<std::string> interfaceList = {IPMIBT, IPMILPC, IPMIPCI};
}

void usage(const char* program)
{
    std::fprintf(
        stderr,
        "Usage: %s --command <command> --interface <interface> --image "
        "<image file> --sig <signature file>\n",
        program);

    std::fprintf(stderr, "interfaces: ");
    std::copy(interfaceList.begin(), interfaceList.end(),
              std::ostream_iterator<std::string>(std::cerr, ", "));
    std::fprintf(stderr, "\n");
}

bool checkCommand(const std::string& command)
{
    return (command == "update");
}

bool checkInterface(const std::string& interface)
{
    auto intf =
        std::find(interfaceList.begin(), interfaceList.end(), interface);
    return (intf != interfaceList.end());
}

int main(int argc, char* argv[])
{
    std::string command, interface, imagePath, signaturePath;

    while (1)
    {
        // clang-format off
        static struct option long_options[] = {
            {"command", required_argument, 0, 'c'},
            {"interface", required_argument, 0, 'i'},
            {"image", required_argument, 0, 'm'},
            {"sig", required_argument, 0, 's'},
            {0, 0, 0, 0}
        };
        // clang-format on

        int option_index = 0;
        int c =
            getopt_long(argc, argv, "c:i:m:s:", long_options, &option_index);
        if (c == -1)
        {
            break;
        }

        switch (c)
        {
            case 'c':
                command = std::string{optarg};
                if (!checkCommand(command))
                {
                    usage(argv[0]);
                    exit(EXIT_FAILURE);
                }

                break;
            case 'i':
                interface = std::string{optarg};
                if (!checkInterface(interface))
                {
                    usage(argv[0]);
                    exit(EXIT_FAILURE);
                }
                break;
            case 'm':
                imagePath = std::string{optarg};
                break;
            case 's':
                signaturePath = std::string{optarg};
                break;
            default:
                usage(argv[0]);
                exit(EXIT_FAILURE);
        }
    }

    if (command.empty())
    {
        usage(argv[0]);
        exit(EXIT_FAILURE);
    }

    /* They want to update the firmware. */
    if (command == "update")
    {
        if (interface.empty() || imagePath.empty() || signaturePath.empty())
        {
            usage(argv[0]);
            exit(EXIT_FAILURE);
        }

        auto ipmi = ipmiblob::IpmiHandler::CreateIpmiHandler();
        ipmiblob::BlobHandler blob(std::move(ipmi));
        host_tool::DevMemDevice devmem;
        host_tool::PciUtilImpl pci;

        std::unique_ptr<host_tool::DataInterface> handler;

        /* Input has already been validated in this case. */
        if (interface == IPMIBT)
        {
            handler = std::make_unique<host_tool::BtDataHandler>(&blob);
        }
        else if (interface == IPMILPC)
        {
            handler =
                std::make_unique<host_tool::LpcDataHandler>(&blob, &devmem);
        }
        else if (interface == IPMIPCI)
        {
            handler = std::make_unique<host_tool::P2aDataHandler>(
                &blob, &devmem, &pci);
        }

        if (!handler)
        {
            /* TODO(venture): use a custom exception. */
            std::fprintf(stderr, "Interface %s is unavailable\n",
                         interface.c_str());
            exit(EXIT_FAILURE);
        }

        /* The parameters are all filled out. */
        try
        {
            host_tool::updaterMain(&blob, handler.get(), imagePath,
                                   signaturePath);
        }
        catch (const host_tool::ToolException& e)
        {
            std::fprintf(stderr, "Exception received: %s\n", e.what());
            return -1;
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id$
/////////////////////////////////////////////////////////////////////////
//
//   Copyright (c) 2003 Stanislav Shwartsman
//          Written by Stanislav Shwartsman [sshwarts at sourceforge net]
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library 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
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
//
/////////////////////////////////////////////////////////////////////////

#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu/cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR

#if BX_SUPPORT_FPU

#include "softfloat-specialize.h"

void BX_CPU_C::FPU_stack_overflow(void)
{
  /* The masked response */
  if (BX_CPU_THIS_PTR the_i387.is_IA_masked())
  {
    BX_CPU_THIS_PTR the_i387.FPU_push();
    BX_WRITE_FPU_REG(floatx80_default_nan, 0);
  }
  FPU_exception(FPU_EX_Stack_Overflow);
}

void BX_CPU_C::FPU_stack_underflow(int stnr, int pop_stack)
{
  /* The masked response */
  if (BX_CPU_THIS_PTR the_i387.is_IA_masked())
  {
    BX_WRITE_FPU_REG(floatx80_default_nan, stnr);
    if (pop_stack)
        BX_CPU_THIS_PTR the_i387.FPU_pop();
  }
  FPU_exception(FPU_EX_Stack_Underflow);
}

/* Returns 1 if unmasked exception occured */
bx_bool BX_CPU_C::FPU_exception(int exception)
{
  int unmasked = 0;

  /* Extract only the bits which we use to set the status word */
  exception &= (FPU_SW_Exceptions_Mask);

  /* Set the corresponding exception bits */
  FPU_PARTIAL_STATUS |= exception;

  /* Set summary bits iff exception isn't masked */
  if (FPU_PARTIAL_STATUS & ~FPU_CONTROL_WORD & FPU_CW_Exceptions_Mask)
  {
    FPU_PARTIAL_STATUS |= (FPU_SW_Summary | FPU_SW_Backward);
    unmasked = 1;
  }

  if (exception & (FPU_SW_Stack_Fault | FPU_EX_Precision))
  {
    if (! (exception & FPU_SW_C1)) {
      /* This bit distinguishes over- from underflow for a stack fault,
           and roundup from round-down for precision loss. */
      FPU_PARTIAL_STATUS &= ~FPU_SW_C1;
    }
  }

  return unmasked;
}

#endif
<commit_msg>- Fixed x87 Inexact Result (#P) unmasked responce<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id$
/////////////////////////////////////////////////////////////////////////
//
//   Copyright (c) 2003 Stanislav Shwartsman
//          Written by Stanislav Shwartsman [sshwarts at sourceforge net]
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library 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
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
//
/////////////////////////////////////////////////////////////////////////

#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu/cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR

#if BX_SUPPORT_FPU

#include "softfloat-specialize.h"

void BX_CPU_C::FPU_stack_overflow(void)
{
  /* The masked response */
  if (BX_CPU_THIS_PTR the_i387.is_IA_masked())
  {
    BX_CPU_THIS_PTR the_i387.FPU_push();
    BX_WRITE_FPU_REG(floatx80_default_nan, 0);
  }
  FPU_exception(FPU_EX_Stack_Overflow);
}

void BX_CPU_C::FPU_stack_underflow(int stnr, int pop_stack)
{
  /* The masked response */
  if (BX_CPU_THIS_PTR the_i387.is_IA_masked())
  {
    BX_WRITE_FPU_REG(floatx80_default_nan, stnr);
    if (pop_stack)
        BX_CPU_THIS_PTR the_i387.FPU_pop();
  }
  FPU_exception(FPU_EX_Stack_Underflow);
}

/* Returns unmasked exceptions if occured */
unsigned BX_CPU_C::FPU_exception(int exception)
{
  /* Extract only the bits which we use to set the status word */
  exception &= (FPU_SW_Exceptions_Mask);

  /* Set the corresponding exception bits */
  FPU_PARTIAL_STATUS |= exception;

  unsigned unmasked = FPU_PARTIAL_STATUS & ~FPU_CONTROL_WORD & FPU_CW_Exceptions_Mask;

  /* Set summary bits iff exception isn't masked */
  if (unmasked)
    FPU_PARTIAL_STATUS |= (FPU_SW_Summary | FPU_SW_Backward);

  if (exception & (FPU_SW_Stack_Fault | FPU_EX_Precision))
  {
    if (! (exception & FPU_SW_C1)) {
      /* This bit distinguishes over- from underflow for a stack fault,
           and roundup from round-down for precision loss. */
      FPU_PARTIAL_STATUS &= ~FPU_SW_C1;
    }
  }

  // if #P unmasked exception occured the result still has to be
  // written to the destination.
  unmasked &= ~FPU_CW_Precision;

  return unmasked;
}

#endif
<|endoftext|>


<commit_before>/*
You have the word FREEBEE. How many words can you form by moving the letters around?
How many words can you form that start and end in E? How many words can you have that
contain the sequence "EEEE"?
E = 0
F = 1
R = 2
B = 30
*/

#include <iostream>
#define length 7

using namespace std;

int values[5040][length], valuesCount;
int word[length] = { 1, 2, 0, 0, 3, 0, 0 };
int answers[3];

void question1(int word[])
{
    ++answers[0];
}

void question2(int word[])
{
    if (word[0] == 0 && word[length - 1] == 0)
    {
        ++answers[1];
    }
}

void question3(int word[])
{
    int count = 0;

    for (int i = 0; i < length; ++i)
    {
        if (word[i] == 0)
        {
            ++count;

            if (count == 4)
            {
                ++answers[2];

                return;
            }
        }
        else
        {
            count = 0;
        }
    }
}

void answerQuestions()
{
    for (int i = 0; i < valuesCount; ++i)
    {
        question1(values[i]);
        question2(values[i]);
        question3(values[i]);
    }
}

void showAnswers()
{
    for (int i = 0; i < 3; ++i)
    {
        cout << "Answer to Q" << i + 1 << ": " << answers[i] << endl;
    }
}

bool equals(int word1[], int word2[])
{
    for (int i = 0; i < length; ++i)
    {
        if (word1[i] != word2[i])
        {
            return false;
        }
    }

    return true;
}

bool isUnique(int word[])
{
    for (int i = 0; i < valuesCount; ++i)
    {
        if (equals(word, values[i]))
        {
            return false;
        }
    }

    return true;
}

void store(int word[])
{
    if (isUnique(word))
    {
     	for (int i = 0; i < length; ++i)
        {
            values[valuesCount][i] = word[i];
        }

	    ++valuesCount;
    }
}

void swap(int word[], int i, int j)
{
    int temp = word[i];
    word[i] = word[j];
    word[j] = temp;
}

void generatePermutations(int word[], int start)
{
    if (start == length)
    {
        store(word);
    }
    else
    {
        for (int i = start; i < length; ++i)
        {
            swap(word, start, i);
            generatePermutations(word, start + 1);
            swap(word, start, i);
        }
    }
}

int main()
{
    generatePermutations(word, 0);
    answerQuestions();
    showAnswers();

    return 0;
}
<commit_msg>Update<commit_after>/*
You have the word FREEBEE. How many words can you form by moving the letters around?
How many words can you form that start and end in E? How many words can you have that
contain the sequence "EEEE"?
E = 0
F = 1
R = 2
B = 30
*/

#include <iostream>
#define length 7

using namespace std;

int values[5040][length], valuesCount;
int word[length] = { 1, 2, 0, 0, 3, 0, 0 };
int answers[3];

void question1(int word[])
{
    ++answers[0];
}

void question2(int word[])
{
    if (word[0] == 0 && word[length - 1] == 0)
    {
        ++answers[1];
    }
}

void question3(int word[])
{
    int count = 0;

    for (int i = 0; i < length; ++i)
    {
        if (word[i] == 0)
        {
            ++count;

            if (count == 4)
            {
                ++answers[2];

                return;
            }
        }
        else
        {
            count = 0;
        }
    }
}

void answerQuestions()
{
    for (int i = 0; i < valuesCount; ++i)
    {
        question1(values[i]);
        question2(values[i]);
        question3(values[i]);
    }
}

void showAnswers()
{
    for (int i = 0; i < 3; ++i)
    {
        cout << "Answer to Q" << i + 1 << ": " << answers[i] << endl;
    }
}

bool equals(int word1[], int word2[])
{
    for (int i = 0; i < length; ++i)
    {
        if (word1[i] != word2[i])
        {
            return false;
        }
    }

    return true;
}

bool isUnique(int word[])
{
    for (int i = 0; i < valuesCount; ++i)
    {
        if (equals(word, values[i]))
        {
            return false;
        }
    }

    return true;
}

void store(int word[])
{
    if (isUnique(word))
    {
     	for (int i = 0; i < length; ++i)
        {
            values[valuesCount][i] = word[i];
        }

        ++valuesCount;
    }
}

void swap(int word[], int i, int j)
{
    int temp = word[i];
    word[i] = word[j];
    word[j] = temp;
}

void generatePermutations(int word[], int start)
{
    if (start == length)
    {
        store(word);
    }
    else
    {
        for (int i = start; i < length; ++i)
        {
            swap(word, start, i);
            generatePermutations(word, start + 1);
            swap(word, start, i);
        }
    }
}

int main()
{
    generatePermutations(word, 0);
    answerQuestions();
    showAnswers();

    return 0;
}
<|endoftext|>


<commit_before><commit_msg>chart2: fix duplicate entries at index 0<commit_after><|endoftext|>


<commit_before>// Copyright (C) 2018 Egor Pugin <egor.pugin@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <primitives/exceptions.h>
#include <boost/stacktrace.hpp>

#include <primitives/debug.h>

#include <chrono>
#include <iostream>
#include <sstream>
#include <string>
#include <thread>

bool gUseStackTrace;
bool gDebugOnException;
std::string gSymbolPath;

#ifdef _WIN32
#include "exceptions_msvc.h"
#endif

using namespace std::chrono_literals;

namespace sw
{

namespace detail
{

BaseException::BaseException(const char *file, const char *function, int line, const std::string &msg, bool stacktrace)
    : file(file), function(function), line(line), message(msg)
{
    if (stacktrace && gUseStackTrace)
    {
        // skip 3 frames
        // -1 means till the end
        boost::stacktrace::stacktrace t(3, -1);
        message += "\nStacktrace:\n";
#ifdef _WIN32
        message += ::to_string(t);
#else
        std::ostringstream ss;
        ss << t;
        message += ss.str();
#endif
    }
}

const char *BaseException::getMessage() const
{
    if (what_.empty())
        what_ = format();
    return what_.c_str();
}

std::string BaseException::format() const
{
    std::string s;
    //s += ex_type;
    //s += "Exception: " + message; // disabled for now, too poor :(
    if (file.empty() && function.empty() && line == 0)
        s += "Exception: " + message;
    else
        s += "Exception in file " + file + ":" + std::to_string(line) + ", function " + function + ": " + message;
    return s;
}

}

Exception::Exception(const char *file, const char *function, int line, const std::string &msg, bool stacktrace)
    : BaseException(file, function, line, msg, stacktrace), std::exception(
#ifdef _MSC_VER
        getMessage()
#endif
    )
{
}

static void doe(const std::string &msg)
{
    if (!gDebugOnException)
        return;
    if (primitives::isDebuggerAttached())
        return;

    std::cerr << msg << "\n";
    std::cerr << "Waiting for debugger..." << "\n";
    while (!primitives::isDebuggerAttached())
        std::this_thread::sleep_for(100ms);
}

RuntimeError::RuntimeError(const char *file, const char *function, int line, const std::string &msg, bool stacktrace)
    : BaseException
    //Exception
    (file, function, line, msg, stacktrace), std::runtime_error(getMessage())
{
    doe(getMessage());
}

LogicError::LogicError(const char *file, const char *function, int line, const std::string &msg, bool stacktrace)
    : BaseException
    //Exception
    (file, function, line, msg, stacktrace), std::logic_error(getMessage())
{
    doe(getMessage());
}

} // namespace sw
<commit_msg>Fix clang build.<commit_after>// Copyright (C) 2018 Egor Pugin <egor.pugin@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <primitives/exceptions.h>
#include <boost/stacktrace.hpp>

#include <primitives/debug.h>

#include <chrono>
#include <iostream>
#include <sstream>
#include <string>
#include <thread>

bool gUseStackTrace;
bool gDebugOnException;
std::string gSymbolPath;

#ifdef BOOST_MSVC
#include "exceptions_msvc.h"
#endif

using namespace std::chrono_literals;

namespace sw
{

namespace detail
{

BaseException::BaseException(const char *file, const char *function, int line, const std::string &msg, bool stacktrace)
    : file(file), function(function), line(line), message(msg)
{
    if (stacktrace && gUseStackTrace)
    {
        // skip 3 frames
        // -1 means till the end
        boost::stacktrace::stacktrace t(3, -1);
        message += "\nStacktrace:\n";
#ifdef BOOST_MSVC
        message += ::to_string(t);
#else
        std::ostringstream ss;
        ss << t;
        message += ss.str();
#endif
    }
}

const char *BaseException::getMessage() const
{
    if (what_.empty())
        what_ = format();
    return what_.c_str();
}

std::string BaseException::format() const
{
    std::string s;
    //s += ex_type;
    //s += "Exception: " + message; // disabled for now, too poor :(
    if (file.empty() && function.empty() && line == 0)
        s += "Exception: " + message;
    else
        s += "Exception in file " + file + ":" + std::to_string(line) + ", function " + function + ": " + message;
    return s;
}

}

Exception::Exception(const char *file, const char *function, int line, const std::string &msg, bool stacktrace)
    : BaseException(file, function, line, msg, stacktrace), std::exception(
#ifdef _MSC_VER
        getMessage()
#endif
    )
{
}

static void doe(const std::string &msg)
{
    if (!gDebugOnException)
        return;
    if (primitives::isDebuggerAttached())
        return;

    std::cerr << msg << "\n";
    std::cerr << "Waiting for debugger..." << "\n";
    while (!primitives::isDebuggerAttached())
        std::this_thread::sleep_for(100ms);
}

RuntimeError::RuntimeError(const char *file, const char *function, int line, const std::string &msg, bool stacktrace)
    : BaseException
    //Exception
    (file, function, line, msg, stacktrace), std::runtime_error(getMessage())
{
    doe(getMessage());
}

LogicError::LogicError(const char *file, const char *function, int line, const std::string &msg, bool stacktrace)
    : BaseException
    //Exception
    (file, function, line, msg, stacktrace), std::logic_error(getMessage())
{
    doe(getMessage());
}

} // namespace sw
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Mathematics (glm.g-truc.net)
///
/// Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)
/// 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.
///
/// @ref core
/// @file glm/glm.hpp
/// @date 2005-01-14 / 2011-05-16
/// @author Christophe Riccio
///
///	@defgroup core GLM Core
///
///	@brief The core of GLM, which implements exactly and only the GLSL specification to the degree possible.
///
/// The GLM core consists of @ref core_types "C++ types that mirror GLSL types",
/// @ref core_funcs "C++ functions that mirror the GLSL functions". It also includes
/// @ref core_precision "a set of precision-based types" that can be used in the appropriate
/// functions. The C++ types are all based on a basic set of @ref core_template "template types".
///
/// The best documentation for GLM Core is the current GLSL specification,
/// version 4.1
/// (pdf file).
/// There are a few @ref pg_differences "differences" between GLM core and GLSL.
///
/// GLM core functionnalities requires <glm/glm.hpp> to be included to be used.
///
/// @defgroup core_types Types
///
/// @brief The standard types defined by the specification.
///
/// These types are all typedefs of more generalized, template types. To see the definiton
/// of these template types, go to @ref core_template.
///
/// @ingroup core
///
/// @defgroup core_precision Precision types
///
/// @brief Non-GLSL types that are used to define precision-based types.
///
/// The GLSL language allows the user to define the precision of a particular variable.
/// In OpenGL's GLSL, these precision qualifiers have no effect; they are there for compatibility
/// with OpenGL ES's precision qualifiers, where they @em do have an effect.
///
/// C++ has no language equivalent to precision qualifiers. So GLM provides the next-best thing:
/// a number of typedefs of the @ref core_template that use a particular precision.
///
/// None of these types make any guarantees about the actual precision used.
///
/// @ingroup core
///
/// @defgroup core_template Template types
///
/// @brief The generic template types used as the basis for the core types.
///
/// These types are all templates used to define the actual @ref core_types.
/// These templetes are implementation details of GLM types and should not be used explicitly.
///
/// @ingroup core
///////////////////////////////////////////////////////////////////////////////////

#include "core/_fixes.hpp"

#ifndef glm_glm
#define glm_glm

#include <cmath>
#include <climits>
#include <cfloat>
#include <limits>
//#include <type_traits>
#include "core/setup.hpp"

#if(defined(GLM_MESSAGES) && !defined(GLM_MESSAGE_CORE_INCLUDED_DISPLAYED))
#	define GLM_MESSAGE_CORE_INCLUDED_DISPLAYED
#	pragma message("GLM: Core library included")
#endif//GLM_MESSAGE

#include "./core/_detail.hpp"
#include "./core/type.hpp"

#include "./core/func_trigonometric.hpp"
#include "./core/func_exponential.hpp"
#include "./core/func_common.hpp"
#include "./core/func_packing.hpp"
#include "./core/func_geometric.hpp"
#include "./core/func_matrix.hpp"
#include "./core/func_vector_relational.hpp"
#include "./core/func_integer.hpp"
#include "./core/func_noise.hpp"
#include "./core/_swizzle.hpp"

////////////////////
// check type sizes
#ifndef GLM_STATIC_ASSERT_NULL
	GLM_STATIC_ASSERT(sizeof(glm::detail::int8) == 1, "int8 size isn't 1 byte on this platform");
	GLM_STATIC_ASSERT(sizeof(glm::detail::int16) == 2, "int16 size isn't 2 bytes on this platform");
	GLM_STATIC_ASSERT(sizeof(glm::detail::int32) == 4, "int32 size isn't 4 bytes on this platform");
	GLM_STATIC_ASSERT(sizeof(glm::detail::int64) == 8, "int64 size isn't 8 bytes on this platform");

	GLM_STATIC_ASSERT(sizeof(glm::detail::uint8) == 1, "uint8 size isn't 1 byte on this platform");
	GLM_STATIC_ASSERT(sizeof(glm::detail::uint16) == 2, "uint16 size isn't 2 bytes on this platform");
	GLM_STATIC_ASSERT(sizeof(glm::detail::uint32) == 4, "uint32 size isn't 4 bytes on this platform");
	GLM_STATIC_ASSERT(sizeof(glm::detail::uint64) == 8, "uint64 size isn't 8 bytes on this platform");

	GLM_STATIC_ASSERT(sizeof(glm::detail::float16) == 2, "float16 size isn't 2 bytes on this platform");
	GLM_STATIC_ASSERT(sizeof(glm::detail::float32) == 4, "float32 size isn't 4 bytes on this platform");
	GLM_STATIC_ASSERT(sizeof(glm::detail::float64) == 8, "float64 size isn't 8 bytes on this platform");
#endif//GLM_STATIC_ASSERT_NULL

#endif//glm_glm
<commit_msg>Fixed doxygen error<commit_after>///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Mathematics (glm.g-truc.net)
///
/// Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)
/// 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.
///
/// @ref core
/// @file glm/glm.hpp
/// @date 2005-01-14 / 2011-10-24
/// @author Christophe Riccio
///
///	@defgroup core GLM Core
///
///	@brief The core of GLM, which implements exactly and only the GLSL specification to the degree possible.
///
/// The GLM core consists of @ref core_types "C++ types that mirror GLSL types" and
/// C++ functions that mirror the GLSL functions. It also includes
/// @ref core_precision "a set of precision-based types" that can be used in the appropriate
/// functions. The C++ types are all based on a basic set of @ref core_template "template types".
///
/// The best documentation for GLM Core is the current GLSL specification,
/// version 4.2
/// (pdf file).
/// There are a few @ref pg_differences "differences" between GLM core and GLSL.
///
/// GLM core functionnalities require <glm/glm.hpp> to be included to be used.
///
/// @defgroup core_types Types
///
/// @brief The standard types defined by the specification.
///
/// These types are all typedefs of more generalized, template types. To see the definiton
/// of these template types, go to @ref core_template.
///
/// @ingroup core
///
/// @defgroup core_precision Precision types
///
/// @brief Non-GLSL types that are used to define precision-based types.
///
/// The GLSL language allows the user to define the precision of a particular variable.
/// In OpenGL's GLSL, these precision qualifiers have no effect; they are there for compatibility
/// with OpenGL ES's precision qualifiers, where they @em do have an effect.
///
/// C++ has no language equivalent to precision qualifiers. So GLM provides the next-best thing:
/// a number of typedefs of the @ref core_template that use a particular precision.
///
/// None of these types make any guarantees about the actual precision used.
///
/// @ingroup core
///
/// @defgroup core_template Template types
///
/// @brief The generic template types used as the basis for the core types.
///
/// These types are all templates used to define the actual @ref core_types.
/// These templetes are implementation details of GLM types and should not be used explicitly.
///
/// @ingroup core
///////////////////////////////////////////////////////////////////////////////////

#include "core/_fixes.hpp"

#ifndef glm_glm
#define glm_glm

#include <cmath>
#include <climits>
#include <cfloat>
#include <limits>
//#include <type_traits>
#include "core/setup.hpp"

#if(defined(GLM_MESSAGES) && !defined(GLM_MESSAGE_CORE_INCLUDED_DISPLAYED))
#	define GLM_MESSAGE_CORE_INCLUDED_DISPLAYED
#	pragma message("GLM: Core library included")
#endif//GLM_MESSAGE

#include "./core/_detail.hpp"
#include "./core/type.hpp"

#include "./core/func_trigonometric.hpp"
#include "./core/func_exponential.hpp"
#include "./core/func_common.hpp"
#include "./core/func_packing.hpp"
#include "./core/func_geometric.hpp"
#include "./core/func_matrix.hpp"
#include "./core/func_vector_relational.hpp"
#include "./core/func_integer.hpp"
#include "./core/func_noise.hpp"
#include "./core/_swizzle.hpp"

////////////////////
// check type sizes
#ifndef GLM_STATIC_ASSERT_NULL
	GLM_STATIC_ASSERT(sizeof(glm::detail::int8) == 1, "int8 size isn't 1 byte on this platform");
	GLM_STATIC_ASSERT(sizeof(glm::detail::int16) == 2, "int16 size isn't 2 bytes on this platform");
	GLM_STATIC_ASSERT(sizeof(glm::detail::int32) == 4, "int32 size isn't 4 bytes on this platform");
	GLM_STATIC_ASSERT(sizeof(glm::detail::int64) == 8, "int64 size isn't 8 bytes on this platform");

	GLM_STATIC_ASSERT(sizeof(glm::detail::uint8) == 1, "uint8 size isn't 1 byte on this platform");
	GLM_STATIC_ASSERT(sizeof(glm::detail::uint16) == 2, "uint16 size isn't 2 bytes on this platform");
	GLM_STATIC_ASSERT(sizeof(glm::detail::uint32) == 4, "uint32 size isn't 4 bytes on this platform");
	GLM_STATIC_ASSERT(sizeof(glm::detail::uint64) == 8, "uint64 size isn't 8 bytes on this platform");

	GLM_STATIC_ASSERT(sizeof(glm::detail::float16) == 2, "float16 size isn't 2 bytes on this platform");
	GLM_STATIC_ASSERT(sizeof(glm::detail::float32) == 4, "float32 size isn't 4 bytes on this platform");
	GLM_STATIC_ASSERT(sizeof(glm::detail::float64) == 8, "float64 size isn't 8 bytes on this platform");
#endif//GLM_STATIC_ASSERT_NULL

#endif//glm_glm
<|endoftext|>


<commit_before>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/iterator_ops.h"

#include <cstdint>
#include <utility>
#include <vector>

#include "tensorflow/core/common_runtime/device_mgr.h"
#include "tensorflow/core/common_runtime/process_function_library_runtime.h"
#include "tensorflow/core/data/dataset_test_base.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/function_testlib.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/monitoring/cell_reader.h"
#include "tensorflow/core/lib/monitoring/test_utils.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/refcount.h"
#include "tensorflow/core/platform/statusor.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace data {
namespace {

using ::tensorflow::monitoring::testing::CellReader;
using ::tensorflow::monitoring::testing::Histogram;

class IteratorOpsTest : public DatasetOpsTestBase {
 public:
  StatusOr<core::RefCountPtr<IteratorResource>> GetIteratorResource() {
    FunctionLibraryRuntime* flr = nullptr;
    std::unique_ptr<DeviceMgr> device_mgr;
    std::unique_ptr<FunctionLibraryDefinition> flib_def;
    std::unique_ptr<ProcessFunctionLibraryRuntime> plfr;
    TF_RETURN_IF_ERROR(dataset_ctx_->function_library()->Clone(
        &flib_def, &plfr, &flr, /*skip_flib_def=*/true));

    core::RefCountPtr<IteratorResource> iter_resource(
        new IteratorResource(dataset_ctx_->env(), dataset_->output_dtypes(),
                             dataset_->output_shapes(), std::move(device_mgr),
                             std::move(flib_def), std::move(plfr), flr));
    TF_RETURN_IF_ERROR(
        iter_resource->SetIteratorFromDataset(dataset_ctx_.get(), dataset_));
    return iter_resource;
  }

  StatusOr<std::vector<std::vector<Tensor>>> GetIteratorOutput(
      IteratorResource& iterator) {
    std::vector<std::vector<Tensor>> output;
    for (bool end_of_sequence = false; !end_of_sequence;) {
      std::vector<Tensor> tensors;
      TF_RETURN_IF_ERROR(
          iterator.GetNext(dataset_ctx_.get(), &tensors, &end_of_sequence));
      if (end_of_sequence) {
        break;
      }
      output.push_back(std::move(tensors));
    }
    return output;
  }
};

TEST_F(IteratorOpsTest, RecordMetrics) {
  CellReader<Histogram> latency_metric("/tensorflow/data/getnext_duration");
  CellReader<int64_t> throughput_metric("/tensorflow/data/bytes_fetched");
  EXPECT_FLOAT_EQ(latency_metric.Delta().num(), 0.0);
  EXPECT_EQ(throughput_metric.Delta(), 0.0);

  RangeDatasetParams dataset_params = RangeDatasetParams(0, 10, 3);
  TF_ASSERT_OK(Initialize(dataset_params));
  TF_ASSERT_OK_AND_ASSIGN(core::RefCountPtr<IteratorResource> iter_resource,
                          GetIteratorResource());
  TF_ASSERT_OK_AND_ASSIGN(std::vector<std::vector<Tensor>> output,
                          GetIteratorOutput(*iter_resource));
  EXPECT_EQ(output.size(), 4);

  Histogram histogram = latency_metric.Delta();
  EXPECT_FLOAT_EQ(histogram.num(), 5.0);
  EXPECT_GT(histogram.sum(), 0.0);
  EXPECT_GT(throughput_metric.Delta(), 0);
}

}  // namespace
}  // namespace data
}  // namespace tensorflow
<commit_msg>#tf-data [1/3] Improve test coverage for tf.data metrics.<commit_after>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/iterator_ops.h"

#include <cstdint>
#include <utility>
#include <vector>

#include "tensorflow/core/common_runtime/device_mgr.h"
#include "tensorflow/core/common_runtime/process_function_library_runtime.h"
#include "tensorflow/core/data/dataset_test_base.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/function_testlib.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/monitoring/cell_reader.h"
#include "tensorflow/core/lib/monitoring/test_utils.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/refcount.h"
#include "tensorflow/core/platform/statusor.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace data {
namespace {

using ::tensorflow::monitoring::testing::CellReader;
using ::tensorflow::monitoring::testing::Histogram;

class IteratorOpsTest : public DatasetOpsTestBase {
 public:
  StatusOr<core::RefCountPtr<IteratorResource>> GetIteratorResource() {
    FunctionLibraryRuntime* flr = nullptr;
    std::unique_ptr<DeviceMgr> device_mgr;
    std::unique_ptr<FunctionLibraryDefinition> flib_def;
    std::unique_ptr<ProcessFunctionLibraryRuntime> plfr;
    TF_RETURN_IF_ERROR(dataset_ctx_->function_library()->Clone(
        &flib_def, &plfr, &flr, /*skip_flib_def=*/true));

    core::RefCountPtr<IteratorResource> iter_resource(
        new IteratorResource(dataset_ctx_->env(), dataset_->output_dtypes(),
                             dataset_->output_shapes(), std::move(device_mgr),
                             std::move(flib_def), std::move(plfr), flr));
    TF_RETURN_IF_ERROR(
        iter_resource->SetIteratorFromDataset(dataset_ctx_.get(), dataset_));
    return iter_resource;
  }

  StatusOr<std::vector<std::vector<Tensor>>> GetIteratorOutput(
      IteratorResource& iterator) {
    std::vector<std::vector<Tensor>> output;
    for (bool end_of_sequence = false; !end_of_sequence;) {
      std::vector<Tensor> tensors;
      TF_RETURN_IF_ERROR(
          iterator.GetNext(dataset_ctx_.get(), &tensors, &end_of_sequence));
      if (end_of_sequence) {
        break;
      }
      output.push_back(std::move(tensors));
    }
    return output;
  }
};

TEST_F(IteratorOpsTest, CollectMetrics) {
  CellReader<Histogram> latency("/tensorflow/data/getnext_duration");
  CellReader<Histogram> iterator_gap("/tensorflow/data/iterator_gap");
  CellReader<int64_t> throughput("/tensorflow/data/bytes_fetched");
  EXPECT_FLOAT_EQ(latency.Delta().num(), 0.0);
  EXPECT_FLOAT_EQ(iterator_gap.Delta().num(), 0.0);
  EXPECT_EQ(throughput.Delta(), 0.0);

  RangeDatasetParams dataset_params = RangeDatasetParams(0, 10, 3);
  TF_ASSERT_OK(Initialize(dataset_params));
  TF_ASSERT_OK_AND_ASSIGN(core::RefCountPtr<IteratorResource> iter_resource,
                          GetIteratorResource());
  TF_ASSERT_OK_AND_ASSIGN(std::vector<std::vector<Tensor>> output,
                          GetIteratorOutput(*iter_resource));
  EXPECT_EQ(output.size(), 4);

  Histogram latency_histogram = latency.Delta();
  EXPECT_FLOAT_EQ(latency_histogram.num(), 5.0);
  EXPECT_GT(latency_histogram.sum(), 0.0);
  Histogram iterator_gap_histogram = iterator_gap.Delta();
  EXPECT_FLOAT_EQ(iterator_gap_histogram.num(), 5.0);
  EXPECT_GT(iterator_gap_histogram.sum(), 0.0);
  EXPECT_GT(throughput.Delta(), 0);
}

}  // namespace
}  // namespace data
}  // namespace tensorflow
<|endoftext|>