text:
#include <build_properties.h>
#include <private-key.h>
#include "license-generator.h"
#include "../base_lib/CryptoHelper.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <boost/date_time.hpp>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/unordered_map.hpp>
#include <boost/assign.hpp>
#include <fstream>
#include <regex>
#include <boost/filesystem.hpp>
#include "../LicenseComm.hpp"

namespace fs = boost::filesystem;
namespace bt = boost::posix_time;
namespace po = boost::program_options;

using namespace std;

namespace license {

LicenseGenerator::LicenseGenerator() {

}

void LicenseGenerator::printHelp(const char* prog_name,
		const po::options_description& options) {
	cout << endl;
	cout << prog_name << " Version " << PROJECT_VERSION << endl << ". Usage:"
			<< endl;
	cout << prog_name << " [options] product_name1 product_name2 ... " << endl
			<< endl;
	cout
			<< " product_name1 ... = Product name. This string must match the one passed by the software."
			<< endl;
	cout << options << endl;
}

po::options_description LicenseGenerator::configureProgramOptions() {
	po::options_description common("General options");
	common.add_options()("help,h", "print help message and exit.") //
	("verbose,v", "print more information.") //
	("output,o", po::value<string>(), "Output file name. If not specified the "
		"license will be printed in standard output"); //
	po::options_description licenseGeneration("License Generation");
	licenseGeneration.add_options()("private_key,p", po::value<string>(),
			"Specify an alternate file for the primary key to be used. "
				"If not specified the internal primary key will be used.") //
	("begin_date,b", po::value<string>(),
			"Specify the start of the validity for this license. "
				" Format YYYYMMDD. If not specified defaults to today") //
	("expire_date,e", po::value<string>(),
			"Specify the expire date for this license. "
				" Format YYYYMMDD. If not specified the license won't expire") //
	("client_signature,s", po::value<string>(),
			"The signature of the pc that requires the license. "
				"It should be in the format XXXX-XXXX-XXXX-XXXX."
				" If not specified the license "
				"won't be linked to a specific pc.") //
	("start_version,t", po::value<unsigned int>()->default_value(0
	/*FullLicenseInfo.UNUSED_SOFTWARE_VERSION*/, "All Versions"),
			"Specify the first version of the software this license apply to.") //
	("end_version,n", po::value<unsigned int>()->default_value(0
	/*FullLicenseInfo.UNUSED_SOFTWARE_VERSION*/, "All Versions"),
			"Specify the last version of the software this license apply to."); //
	po::options_description visibleOptions;
	visibleOptions.add(common).add(licenseGeneration);
	return visibleOptions;
}

vector<FullLicenseInfo> LicenseGenerator::parseLicenseInfo(po::variables_map vm) {
	string begin_date = FullLicenseInfo::UNUSED_TIME;
	string end_date = FullLicenseInfo::UNUSED_TIME;
	if (vm.count("expire_date")) {
		const std::string dt_end = vm["expire_date"].as<string> ();
		try {
			end_date = normalize_date(dt_end.c_str());
			char curdate[20];
			time_t curtime = time(NULL);
			strftime(curdate, 20, "%Y-%m-%d", localtime(&curtime));
			begin_date.assign(curdate);
		} catch (const invalid_argument &e) {
			cerr << endl << "End date not recognized: " << dt_end
					<< " Please enter a valid date in format YYYYMMDD" << endl;
			exit(2);
		}
	}
	if (vm.count("begin_date")) {
		const std::string begin_date_str = vm["begin_date"].as<string> ();
		try {
			begin_date = normalize_date(begin_date_str.c_str());
		} catch (invalid_argument &e) {
			cerr << endl << "Begin date not recognized: " << begin_date_str
					<< " Please enter a valid date in format YYYYMMDD" << endl;
			//print_usage(vm);
			exit(2);
		}
	}
	string client_signature = "";
	if (vm.count("client_signature")) {
		client_signature = vm["client_signature"].as<string> ();
		//fixme match + and /
		/*regex e("(A-Za-z0-9){4}-(A-Za-z0-9){4}-(A-Za-z0-9){4}-(A-Za-z0-9){4}");
		 if (!regex_match(client_signature, e)) {
		 cerr << endl << "Client signature not recognized: "
		 << client_signature
		 << " Please enter a valid signature in format XXXX-XXXX-XXXX-XXXX"
		 << endl;
		 exit(2);
		 }*/
	}
	string extra_data = "";
	if (vm.count("extra_data")) {
		extra_data = vm["extra_data"].as<string> ();
	}
	unsigned int from_sw_version = vm["start_version"].as<unsigned int> ();
	unsigned int to_sw_version = vm["end_version"].as<unsigned int> ();
	if (vm.count("product") == 0) {
		cerr << endl << "Parameter [product] not found. " << endl;
		exit(2);
	}
	vector < string > products = vm["product"].as<vector<string>> ();
	vector<FullLicenseInfo> licInfo;
	licInfo.reserve(products.size());
	for (auto it = products.begin(); it != products.end(); it++) {
		if (boost::algorithm::trim_copy(*it).length() > 0) {
			licInfo.push_back(
					FullLicenseInfo("", *it, "", PROJECT_INT_VERSION,
							begin_date, end_date, client_signature,"",
							from_sw_version, to_sw_version, extra_data, false,
							0, 0));

		}
	}
	return licInfo;
}
#if 0
vector<FullLicenseInfo> LicenseGenerator::parseLicenseInfo(LicenseComm & lc) {

	vector<FullLicenseInfo> licInfo;
	LicenseLocation licenseLocation;
	licenseLocation.openFileNearModule = false;
	licenseLocation.licenseFileLocation = lc.client_signature.c_str();
	licenseLocation.environmentVariableName = "";

	//if (lc.CammnadType == EVENT_TYPE::LICENSE_OK || lc.CammnadType == EVENT_TYPE::LICENSE_FILE_NOT_FOUND) {
		vector<FullLicenseInfo> licenseInfo;
		LicenseReader licreader(licenseLocation);

		for (auto it = lc.products.begin(); it != lc.products.end(); ++it) {
			licreader.readLicenses(*it, licenseInfo);

			cout <<__LINE__<<"Here license size "<<licenseInfo.size();
				for (int i=0; i<licenseInfo.size(); i++){

				if(!lc.server_signature.empty())
					licenseInfo[i].server_signature=lc.server_signature;
	           std::cout <<__LINE__ << "  days_left: " << licenseInfo[i].source << "\n";
	           //std::cout << "  license_type: " << it->prod << "\n";
	           //std::cout << "  proprietary_data: " << licenseInfo[i].proprietary_data << "\n";
	           std::cout <<__LINE__ << "  license_version: " << licenseInfo[i].license_version << "\n";
	           std::cout <<__LINE__ << "  client_signature: " << licenseInfo[i].client_signature << "\n";
	           std::cout <<__LINE__ << "  products: " << licenseInfo[i].product << "\n";
	           std::cout <<__LINE__ << "  license_signature: " << licenseInfo[i].license_signature << "\n";
	           std::cout <<__LINE__ << "  server_signature: " << licenseInfo[i].server_signature << "\n";
	           std::cout <<__LINE__ << "  from_date: " << licenseInfo[i].from_date << "\n";
	           std::cout <<__LINE__ << "  to_date: " << licenseInfo[i].to_date << "\n";
	           std::cout <<__LINE__ << "  has_expiry: " << licenseInfo[i].has_expiry << "\n";
	           std::cout <<__LINE__ << "  from_sw_version: " << licenseInfo[i].from_sw_version << "\n";
	           std::cout <<__LINE__ << "  to_sw_version: " << licenseInfo[i].to_sw_version << "\n";
	           std::cout <<__LINE__ << "  has_versions: " << licenseInfo[i].has_versions << "\n";
	           std::cout <<__LINE__ << "  has_client_sig: " << licenseInfo[i].has_client_sig << "\n";
	           std::cout <<__LINE__ << "  extra_data: " << licenseInfo[i].extra_data << "\n";
	           std::cout <<__LINE__ << "  has_use_limit: " << licenseInfo[i].has_use_limit << "\n";
	           std::cout <<__LINE__ << "  use_limit: " << licenseInfo[i].use_limit << "\n";
	           std::cout <<__LINE__ << "   has_used_num: " << licenseInfo[i].has_used_num << "\n";
				}
			licInfo.insert(licInfo.end(), licenseInfo.begin(),
					licenseInfo.end());

		}
		if(licInfo.size()>0)
			return licInfo;

		string begin_date = FullLicenseInfo::UNUSED_TIME;
		string end_date = FullLicenseInfo::UNUSED_TIME;
		bool has_use_limit;
		double use_limit;
		double has_used_num;

		char curdate[20];
		if (lc.products.size() == 0) {//vm.count("product") == 0) {
			cerr << endl << "Parameter [product] not found. " << endl;
			exit(2);
		}
		vector < string > products = lc.products;//vm["product"].as<vector<string>>();
		licInfo.reserve(products.size());
		for (auto it = products.begin(); it != products.end(); it++) {
			if (boost::algorithm::trim_copy(*it).length() > 0) {

				if (!lc.to_date.empty()) {///vm.count("expire_date")) {
					const std::string dt_end = lc.to_date;//vm["expire_date"].as<string>();
					try {
						end_date = normalize_date(dt_end.c_str());

						time_t curtime = time(NULL);
						strftime(curdate, 20, "%Y-%m-%d", localtime(&curtime));
						begin_date.assign(curdate);
					} catch (const invalid_argument &e) {
						cerr << endl << "End date not recognized: " << dt_end
								<< " Please enter a valid date in format YYYYMMDD"
								<< endl;
						exit(2);
					}
				}
				if (!lc.from_date.empty()) {//vm.count("begin_date")) {
					const std::string begin_date_str = lc.from_date;//vm["begin_date"].as<string>();
					try {
						begin_date = normalize_date(begin_date_str.c_str());
					} catch (invalid_argument &e) {
						cerr << endl << "Begin date not recognized: "
								<< begin_date_str
								<< " Please enter a valid date in format YYYYMMDD"
								<< endl;
						//print_usage(vm);
						exit(2);
					}
				}
				string client_signature = "";
				if (!lc.client_signature.empty()) {//vm.count("client_signature")) {
					client_signature = lc.client_signature;//vm["client_signature"].as<string>();
					//fixme match + and /
					/*regex e("(A-Za-z0-9){4}-(A-Za-z0-9){4}-(A-Za-z0-9){4}-(A-Za-z0-9){4}");
					 if (!regex_match(client_signature, e)) {
					 cerr << endl << "Client signature not recognized: "
					 << client_signature
					 << " Please enter a valid signature in format XXXX-XXXX-XXXX-XXXX"
					 << endl;
					 exit(2);
					 }*/
				}
				string server_signature = "";
								if (!lc.server_signature.empty()) {//vm.count("client_signature")) {
									server_signature = lc.server_signature;//vm["client_signature"].as<string>();
									//fixme match + and /
									/*regex e("(A-Za-z0-9){4}-(A-Za-z0-9){4}-(A-Za-z0-9){4}-(A-Za-z0-9){4}");
									 if (!regex_match(client_signature, e)) {
									 cerr << endl << "Client signature not recognized: "
									 << client_signature
									 << " Please enter a valid signature in format XXXX-XXXX-XXXX-XXXX"
									 << endl;
									 exit(2);
									 }*/
								}
				string extra_data = "";
				if (!lc.extra_data.empty()) {//vm.count("extra_data")) {
					extra_data = lc.extra_data;//vm["extra_data"].as<string>();
				}
				unsigned int from_sw_version = lc.from_sw_version;//vm["start_version"].as<unsigned int>();
				unsigned int to_sw_version = lc.to_sw_version;//vm["end_version"].as<unsigned int>();
				if (*it == "smart-eye") { //product profile....
					time_t t1 = time(0); // get time now
					struct tm * now = localtime(&t1);
					snprintf(curdate, 20,"%4d-%02d-%02d", now->tm_year+1900, now->tm_mon,
							now->tm_mday);
					begin_date.assign(curdate);
					snprintf(curdate,20, "%4d-%02d-%02d", now->tm_year+1900 + 1,
							now->tm_mon, now->tm_mday);
					end_date.assign(curdate);
					has_use_limit=false;
					use_limit=10;
					has_used_num=0;
				}
				else{
					time_t t1 = time(0); // get time now
										struct tm * now = localtime(&t1);
										snprintf(curdate, 20,"%4d-%02d-%02d", now->tm_year+1900, now->tm_mon,
												now->tm_mday);
										begin_date.assign(curdate);
										snprintf(curdate,20, "%4d-%02d-%02d", now->tm_year+1900,
												now->tm_mon+6, now->tm_mday);
										end_date.assign(curdate);
										has_use_limit=false;
										use_limit=10;
										has_used_num=0;

				}
				licInfo.push_back(
						FullLicenseInfo("", *it, "", PROJECT_INT_VERSION,
								begin_date, end_date, client_signature,server_signature,
								from_sw_version, to_sw_version, extra_data,
								has_use_limit, use_limit, has_used_num));
			}
		}

	return licInfo;
}

vector<FullLicenseInfo> LicenseGenerator::generateAndOutputLicenses(
		LicenseComm &lc) {
	vector<FullLicenseInfo> licenseInfo = parseLicenseInfo(lc);

	unique_ptr < CryptoHelper > helper = CryptoHelper::getInstance();
	const char pkey[] = PRIVATE_KEY;
	size_t len = sizeof(pkey);
	const string fname = lc.client_signature;

	fstream ofstream(fname, std::ios::out | std::ios::trunc);
	if (!ofstream.is_open()) {
		cerr << "can't open file [" << fname << "] for Lincese." << endl
				<< " error: " << strerror(errno);
		//exit(3);
	}

	for (auto it = licenseInfo.begin(); it != licenseInfo.end(); ++it) {
		if(it->has_use_limit){
			it->has_used_num++;
			//it->param_to_update=it->param_to_update+"has_used_num";
		}
		const string license = it->printForSign();
		cout << "lincense_generate " << license << endl;

		string signature =	helper->signString((const void *) pkey, len, license);
		it->license_signature = signature;
		//license =	it->printForSignServer();
		signature = helper->signString((const void *) pkey, len, it->printForSignServer());

		cout<<"license server gen:- "<<signature<<endl;

		//it->server_signature = signature;

		//it->printAsIni(outputFile);
		it->printAsIni(ofstream);
		//#ifdef DEBUG
		it->printAsIni(cout);
		//#endif
	}
	return licenseInfo;
}

vector<licsenceCommPack> LicenseGenerator::parseLincenseToCom(
		vector<FullLicenseInfo> genresponse, EVENT_TYPE response_event,Crypto * crypto,char * remote_pub_key) {
	vector<licsenceCommPack> genresponsecom;
	//Crypto crypto;
	unique_ptr < CryptoHelper > helper = CryptoHelper::getInstance();
		const char pkey[] = PRIVATE_KEY;
		size_t len = sizeof(pkey);

		licsenceCommPack lcp;

	for (auto it = genresponse.begin(); it != genresponse.end(); ++it) {
		vector < string > products;
		products.push_back(it->product);
		//genresponsecom.push_back(LicenseComm(response_event,0,LICENSE_TYPE::REMOTE,"",it->license_version,it->client_signature,products,it->license_signature,it->from_date,it->to_date,false,it->from_sw_version,it->to_sw_version,it->has_versions,it->has_client_sig,it->extra_data,it->has_use_limit,it->use_limit,it->has_used_num));

		LicenseComm lc;
		if(it->server_signature.empty())
			lc.CammnadType = EVENT_TYPE::PRODUCT_NOT_LICENSED;
		else{
			//const string license = it->printForSignServer();

			//string signature = helper->signString((const void *) pkey, len, license+"CompanyName:softonnet.com");

			//cout << "lincense_generate " << license << endl;
			//cout<<"          server_sig: "<<it->server_signature.c_str()<<"\n print sign server:"<<it->printForSignServer().c_str();
			FUNCTION_RETURN sigVer = verifySignature(it->printForSignServer().c_str(),it->server_signature.c_str());
			bool sigVerified = sigVer == FUNC_RET_OK;
			if (sigVerified) {
				//lc.param_to_update.assign(":param_to_update");
				lc.CammnadType=LICENSE_VERIFIED;
			} else {
				//lc.param_to_update.assign(":param_to_update");
				lc.CammnadType=LICENSE_CORRUPTED;
			}

		}
		//lc.param_to_update.assign(":has_used_num");
		//cout<<" param to update: "<<lc.param_to_update<<endl;
		lc.days_left = 0;
		lc.license_type = LICENSE_TYPE::REMOTE; // Local or Remote

		lc.proprietary_data = "";
		lc.license_version = it->license_version; //license file version
		lc.client_signature = it->client_signature;

		lc.products = products;
		lc.license_signature = it->license_signature;

		//cout << endl << "lc.from_date= " << lc.from_date;
		lc.from_date = it->from_date;//it->from_date;
		lc.to_date = it->to_date;//it->to_date;
		//cout << endl << "lc.from_date= " << lc.from_date.c_str() << __LINE__

		lc.has_expiry = it->has_expiry;
		lc.from_sw_version = it->from_sw_version;
		lc.to_sw_version = it->to_sw_version;
		lc.has_versions = it->has_versions;

		lc.has_client_sig = it->has_client_sig;
		lc.extra_data = it->extra_data;
		lc.has_use_limit = it->has_use_limit;
		lc.use_limit = it->use_limit;
		lc.has_used_num = it->has_used_num;
		lc.server_signature = it->server_signature;

		//lcp.data.assign(packet_manager::objToString(lc));
//		packet_manager::encryptRsaData(crypto,&(lcp.data),&(lcp.encryptedData), &(lcp.encryptedKey),  &(lcp.iv));
		lcp.decrypted_length=packet_manager::objToCharArray((unsigned char*)&(lcp.decrypted),lc);
		lcp.encrypted_length= crypto->public_encrypt(lcp.decrypted,lcp.decrypted_length,remote_pub_key,lcp.encrypted);
		genresponsecom.push_back(lcp);

	}
	return genresponsecom;

}
#endif
void LicenseGenerator::generateAndOutputLicenses(const po::variables_map& vm,
		ostream& outputFile) {
	vector<FullLicenseInfo> licenseInfo = parseLicenseInfo(vm);
	unique_ptr < CryptoHelper > helper = CryptoHelper::getInstance();
	const char pkey[] = PRIVATE_KEY;
	size_t len = sizeof(pkey);
	for (auto it = licenseInfo.begin(); it != licenseInfo.end(); ++it) {
		const string license = it->printForSign();
		string signature =	helper->signString((const void *) pkey, len, license);
		it->license_signature = signature;
		it->printAsIni(outputFile);
	}
}

int LicenseGenerator::generateLicense(int argc, const char **argv) {

	po::options_description visibleOptions = configureProgramOptions();
	//positional options must be addedd to standard options
	po::options_description allOptions;
	allOptions.add(visibleOptions).add_options()("product",
			po::value<vector<string>>(), "product names");

	po::positional_options_description p;
	p.add("product", -1);

	po::variables_map vm;
	po::store(
			po::command_line_parser(argc, argv).options(allOptions).positional(
					p).run(), vm);
	po::notify(vm);
	if (vm.count("help") || argc == 1) {
		printHelp(argv[0], visibleOptions);
		return 0;
	}

	if (vm.count("output")) {
		const std::string fname = vm["output"].as<string> ();

		fstream ofstream(fname, std::ios::out | std::ios::trunc);
		if (!ofstream.is_open()) {
			cerr << "can't open file [" << fname << "] for output." << endl
					<< " error: " << strerror(errno);
			exit(3);
		}
		generateAndOutputLicenses(vm, ofstream);
		ofstream.close();
	} else {
		generateAndOutputLicenses(vm, cout);
	}
	return 0;
}

const std::string formats[] = { "%4u-%2u-%2u", "%4u/%2u/%2u", "%4u%2u%2u" };
const size_t formats_n = 3;

string LicenseGenerator::normalize_date(const char * s) {
	unsigned int year, month, day;
	int chread;
	bool found = false;
	for (size_t i = 0; i < formats_n && !found; ++i) {
		chread = sscanf(s, formats[i].c_str(), &year, &month, &day);
		if (chread == 3) {
			found = true;
		}
	}
	if (!found) {
		throw invalid_argument("Date not recognized.");
	}
	ostringstream oss;
	oss << year << "-" << setfill('0') << std::setw(2) << month << "-" << day;
	//delete (facet);
	return oss.str();
}
}

max_stars_repo_name: YAS-CODE/License-Manager

max_issues_repo_name: YAS-CODE/Open-source-dev

max_forks_repo_name: YAS-CODE/Open-source-dev


text:
#define BOOST_TEST_MODULE "test_vector"

#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif

#include <mill/math/Vector.hpp>

#include <random>
constexpr static unsigned int seed = 32479327;
constexpr static std::size_t N = 10000;

BOOST_AUTO_TEST_CASE(add_vector_3d)
{
    std::mt19937 mt(seed);
    std::uniform_real_distribution<double> uni(-1.0, 1.0);
    for(std::size_t test_times=0; test_times<N; ++test_times)
    {
        const mill::Vector<double, 3> lhs(uni(mt), uni(mt), uni(mt));
        const mill::Vector<double, 3> rhs(uni(mt), uni(mt), uni(mt));

        mill::Vector<double, 3> vec = lhs + rhs;
        BOOST_CHECK_EQUAL(vec[0], lhs[0] + rhs[0]);
        BOOST_CHECK_EQUAL(vec[1], lhs[1] + rhs[1]);
        BOOST_CHECK_EQUAL(vec[2], lhs[2] + rhs[2]);
    }
}

BOOST_AUTO_TEST_CASE(sub_vector_3d)
{
    std::mt19937 mt(seed);
    std::uniform_real_distribution<double> uni(-1.0, 1.0);
    for(std::size_t test_times=0; test_times<N; ++test_times)
    {
        const mill::Vector<double, 3> lhs(uni(mt), uni(mt), uni(mt));
        const mill::Vector<double, 3> rhs(uni(mt), uni(mt), uni(mt));

        mill::Vector<double, 3> vec = lhs - rhs;
        BOOST_CHECK_EQUAL(vec[0], lhs[0] - rhs[0]);
        BOOST_CHECK_EQUAL(vec[1], lhs[1] - rhs[1]);
        BOOST_CHECK_EQUAL(vec[2], lhs[2] - rhs[2]);
    }
}

BOOST_AUTO_TEST_CASE(mul_vector_3d)
{
    std::mt19937 mt(seed);
    std::uniform_real_distribution<double> uni(-1.0, 1.0);
    for(std::size_t test_times=0; test_times<N; ++test_times)
    {
        const mill::Vector<double, 3> lhs(uni(mt), uni(mt), uni(mt));
        const double scl = uni(mt);

        mill::Vector<double, 3> vec = lhs * scl;
        BOOST_CHECK_EQUAL(vec[0], lhs[0] * scl);
        BOOST_CHECK_EQUAL(vec[1], lhs[1] * scl);
        BOOST_CHECK_EQUAL(vec[2], lhs[2] * scl);
    }
}

ext: cpp

max_stars_repo_name: ToruNiina/Coffee-mill

max_issues_repo_name: ToruNiina/Coffee-mill

max_forks_repo_name: ToruNiina/Coffee-mill


text:
/*
 *  Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd 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
 */
/*
 * @file       test_descriptor-set.cpp
 * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
 * @version    1.0
 */

#include <unistd.h>
#include <errno.h>
#include <string.h>

#include <thread>
#include <memory>

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

#include <test_common.h>
#include <test_watched-thread.h>

#include <descriptor-set.h>

using namespace CKM;

namespace {

const int POLL_TIMEOUT = 8000;
const int POLL_TIMEOUT_SHORT = 1000;

typedef std::unique_ptr<int[], std::function<void(int *)>> PipePtr;

const short POLLALL = std::numeric_limits<short>::max();

void closePipe(int* fd) {
    close(fd[0]);
    close(fd[1]);
}

/*
 * Declares pipe descriptor array
 * Creates pipe and checks for error
 * Wraps pipe in unique_ptr
 */
#define PIPE(fd) \
    int (fd)[2]; \
    BOOST_REQUIRE_MESSAGE(0 == pipe((fd)),"Pipe creation failed: " << strerror(errno)); \
    PipePtr fd##Ptr((fd), closePipe);

void unexpectedCallback(int, short) {
    BOOST_FAIL("Unexpected callback");
}

void readFd(int fd, int expectedFd, short revents) {
    char buf[1];
    BOOST_REQUIRE_MESSAGE(fd == expectedFd, "Unexpected descriptor");
    BOOST_REQUIRE_MESSAGE(revents & POLLIN, "Unexpected event");
    BOOST_REQUIRE_MESSAGE(1 == TEMP_FAILURE_RETRY(read(fd,buf,1)),
                          "Pipe read failed" << strerror(errno));
}

void writeFd(int fd, int expectedFd, short revents) {
    BOOST_REQUIRE_MESSAGE(fd == expectedFd, "Unexpected descriptor");
    BOOST_REQUIRE_MESSAGE(revents & POLLOUT, "Unexpected event");
    BOOST_REQUIRE_MESSAGE(1 == TEMP_FAILURE_RETRY(write(fd,"j",1)),
                          "Pipe writing failed" << strerror(errno));
}

} // anonymous namespace

BOOST_AUTO_TEST_SUITE(DESCRIPTOR_SET_TEST)

/*
 * Wait on empty descriptor set. Function should return immediately.
 */
BOOST_AUTO_TEST_CASE(T010_Empty) {
    DescriptorSet descriptors;

    BOOST_REQUIRE_NO_THROW(descriptors.wait(POLL_TIMEOUT));
}

/*
 * Add and remove (twice) descriptor. Wait on empty set. No callback should be called. wait() should
 * return immediately.
 */
BOOST_AUTO_TEST_CASE(T020_AddRemove) {
    DescriptorSet descriptors;
    descriptors.add(10, POLLALL, unexpectedCallback);
    descriptors.remove(10);
    descriptors.remove(10);

    BOOST_REQUIRE_NO_THROW(descriptors.wait(POLL_TIMEOUT));
}

/*
 * Add 2 descriptors and purge all. Wait on empty set. No callback should be called. wait() should
 * return immediately.
 */
BOOST_AUTO_TEST_CASE(T030_AddPurge) {
    DescriptorSet descriptors;
    descriptors.add(10, POLLALL, unexpectedCallback);
    descriptors.add(20, POLLALL, unexpectedCallback);
    descriptors.purge();

    BOOST_REQUIRE_NO_THROW(descriptors.wait(POLL_TIMEOUT));
}

/*
 * Add pipe[1] descriptor and wait for write possibility. Provided callback should be called
 * immediately.
 */
BOOST_AUTO_TEST_CASE(T040_Callback) {
    DescriptorSet descriptors;
    bool callback = false;

    PIPE(fd);

    descriptors.add(fd[1],POLLALL, [&callback](int, short revents)
    {
        callback = true;
        BOOST_REQUIRE_MESSAGE(revents & POLLOUT, "Not able to write");
    });

    BOOST_REQUIRE_NO_THROW(descriptors.wait(POLL_TIMEOUT));
    BOOST_REQUIRE_MESSAGE(callback, "Callback was not called");
}

/*
 * Add pipe[1] descriptor twice with different callbacks. The first one should be overwritten and
 * shouldn't be called. The second one should be called instead.
 */
BOOST_AUTO_TEST_CASE(T050_DoubleAdd) {
    DescriptorSet descriptors;
    bool callback = false;

    PIPE(fd);

    descriptors.add(fd[1], POLLALL, unexpectedCallback);
    descriptors.add(fd[1], POLLALL, [&callback](int, short revents)
    {
        callback = true;
        BOOST_REQUIRE_MESSAGE(revents & POLLOUT, "Not able to write");
    });

    BOOST_REQUIRE_NO_THROW(descriptors.wait(POLL_TIMEOUT));
    BOOST_REQUIRE_MESSAGE(callback, "Callback was not called");
}

/*
 * Add pipe[0] descriptor and wait. Callback should not be called. Instead the 8s timeout should
 * occur and a proper exception should be thrown.
 */
BOOST_AUTO_TEST_CASE(T060_Timeout) {
    DescriptorSet descriptors;

    PIPE(fd);

    descriptors.add(fd[0],POLLALL, unexpectedCallback);

    BOOST_REQUIRE_THROW(descriptors.wait(POLL_TIMEOUT_SHORT), CKM::DescriptorSet::Timeout);
}

/*
 * Create pipe and try to write it. Start thread that will read it.
 */
BOOST_AUTO_TEST_CASE(T070_Write) {
    DescriptorSet descriptors;
    bool callback = false;

    PIPE(fd);

    descriptors.add(fd[1],POLLOUT, [&fd, &callback](int desc, short revents)
    {
        callback = true;
        writeFd(desc, fd[1], revents);
    } );

    {
        auto thread = CreateWatchedThread([fd]
        {
            char buf[1];
            ssize_t tmp = TEMP_FAILURE_RETRY(read(fd[0], buf, 1));
            THREAD_REQUIRE_MESSAGE(tmp == 1, "Pipe reading failed " << strerror(errno));
        });

        BOOST_REQUIRE_NO_THROW(descriptors.wait(POLL_TIMEOUT));
    }

    BOOST_REQUIRE_MESSAGE(callback, "Callback not called");
}

/*
 * Create pipe and try to read it. Start thread that will write it.
 */
BOOST_AUTO_TEST_CASE(T080_Read) {
    DescriptorSet descriptors;
    bool callback = false;

    PIPE(fd);

    descriptors.add(fd[0],POLLIN, [&](int desc, short revents)
    {
        callback = true;
        readFd(desc, fd[0], revents);
    } );

    {
        auto thread = CreateWatchedThread([fd]
        {
            ssize_t tmp = TEMP_FAILURE_RETRY(write(fd[1], "j", 1));
            THREAD_REQUIRE_MESSAGE(tmp == 1, "Pipe writing failed " << strerror(errno));
        });

        BOOST_REQUIRE_NO_THROW(descriptors.wait(POLL_TIMEOUT));
    }

    BOOST_REQUIRE_MESSAGE(callback, "Callback not called");
}

/*
 * Create two pipes. Try to read first one. Start the thread that writes it. In the callback read
 * the pipe, remove it from the descriptor set and try to write the second pipe. The thread will
 * read it. In second pipe callback remove the second pipe descriptor from the set.
 */
BOOST_AUTO_TEST_CASE(T090_WriteAfterRead) {
    DescriptorSet descriptors;
    bool callback1 = false;
    bool callback2 = false;

    PIPE(fd);
    PIPE(fd2);

    descriptors.add(fd[0],POLLIN, [&](int desc, short revents)
    {
        callback1 = true;
        readFd(desc, fd[0], revents);

        descriptors.remove(desc);
        descriptors.add(fd2[1],POLLOUT, [&](int desc, short revents) {
            callback2 = true;
            writeFd(desc, fd2[1], revents);
            descriptors.remove(desc);
        } );
    } );

    {
        auto thread = CreateWatchedThread([fd,fd2]
        {
            ssize_t tmp = TEMP_FAILURE_RETRY(write(fd[1], "j", 1));
            BOOST_REQUIRE_MESSAGE(tmp == 1, "Pipe writing failed " << strerror(errno));

            char buf[1];
            tmp = TEMP_FAILURE_RETRY(read(fd2[0], buf, 1));
            THREAD_REQUIRE_MESSAGE(tmp == 1, "Pipe reading failed " << strerror(errno));
        });

        BOOST_REQUIRE_NO_THROW(descriptors.wait(POLL_TIMEOUT));
        BOOST_REQUIRE_NO_THROW(descriptors.wait(POLL_TIMEOUT));
    }

    BOOST_REQUIRE_MESSAGE(callback1, "First callback not called");
    BOOST_REQUIRE_MESSAGE(callback2, "Second callback not called");
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: Samsung/ckm

max_issues_repo_name: Samsung/ckm

max_forks_repo_name: Samsung/ckm


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_DIV_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_DIV_HPP_INCLUDED

#include <boost/simd/function/divides.hpp>
#include <boost/simd/detail/dispatch/function/overload.hpp>
#include <boost/simd/detail/dispatch/meta/as_integer.hpp>
#include <boost/simd/detail/dispatch/hierarchy.hpp>
#include <boost/config.hpp>

namespace boost { namespace simd { namespace ext
{
  namespace bd = boost::dispatch;
  namespace bs = boost::simd;
  BOOST_DISPATCH_OVERLOAD_IF ( div_
                          , (typename T, typename X)
                          , (detail::is_native<X>)
                          , bd::cpu_
                          , bs::pack_<bd::arithmetic_<T>, X>
                          , bs::pack_<bd::arithmetic_<T>, X>
                          )
  {
    BOOST_MAYBEINLINE T operator()(T const& a, T const& b ) const BOOST_NOEXCEPT
    {
      return divides(a, b);
    }
  };

} } }

#endif

ext: hpp


text:
#pragma once

#include <boost/thread/future.hpp>

#include <memory>

#include "gmock/gmock.h"

#include "storage/prepared_plan.hpp"
#include "tasks/server/bind_server_prepared_statement_task.hpp"
#include "tasks/server/create_pipeline_task.hpp"
#include "tasks/server/execute_server_prepared_statement_task.hpp"
#include "tasks/server/execute_server_query_task.hpp"
#include "tasks/server/load_server_file_task.hpp"
#include "tasks/server/parse_server_prepared_statement_task.hpp"

namespace opossum {

class MockTaskRunner {
 public:
  MOCK_METHOD1(dispatch_server_task,
               boost::future<std::unique_ptr<PreparedPlan>>(std::shared_ptr<ParseServerPreparedStatementTask>));
  MOCK_METHOD1(dispatch_server_task,
               boost::future<std::shared_ptr<AbstractOperator>>(std::shared_ptr<BindServerPreparedStatementTask>));
  MOCK_METHOD1(dispatch_server_task,
               boost::future<std::unique_ptr<CreatePipelineResult>>(std::shared_ptr<CreatePipelineTask>));
  MOCK_METHOD1(dispatch_server_task,
               boost::future<std::shared_ptr<const Table>>(std::shared_ptr<ExecuteServerPreparedStatementTask>));
  MOCK_METHOD1(dispatch_server_task, boost::future<void>(std::shared_ptr<ExecuteServerQueryTask>));
  MOCK_METHOD1(dispatch_server_task, boost::future<void>(std::shared_ptr<LoadServerFileTask>));
};

}  // namespace opossum

max_stars_repo_name: nilsthamm/hyrise

max_issues_repo_name: nilsthamm/hyrise

max_forks_repo_name: nilsthamm/hyrise


text:
#include <iostream>
#include <fstream>
#include <Eigen/Eigen>
//include the bie header files
#include "material.hh"
#include "precomputed_kernel.hh"
#include "bimat_interface.hh"
#include "infinite_boundary.hh"
//include the fem header files
#include "mesh_Abaqus_multi_faults.hpp"
#include "bcdof.hpp"
#include "bcdof_ptr.hpp"
#include "cal_ke.hpp"
#include "cal_fe_global_const_ke.hpp"
#include "mapglobal.hpp"
#include "maplocal.hpp"
#include "Slip_Weakening_lumpM.hpp"
#include "cal_slip_sliprate_angle.hpp"
#include "time_advance.hpp"
#include "BIE_correct.hpp"
#include "igl/list_to_matrix.h"
#include <math.h>
using namespace Eigen;
using namespace std;

typedef Eigen::Matrix<int, -1, -1,RowMajor> MatrixXi_rm;

void read_matrix(std::string fileName, Eigen::MatrixXd &outputMat);

double time_fem=0;
double time_bie;
int main() {
    std::string filename = "abaqus_cpp_5degree_100m_10km_4km.inp";
    std::cout<<filename<<std::endl;
    double fault_angle  = 5/180.0*M_PI;
    int dim = 2.0;
    double x_max = 5.0e3;
    double x_min = -5.0e3;
    double dx = 100.0;
    double dy = 100.0;
    std::vector<int> BIE_top, BIE_bot;
    MatrixXd Node;
    MatrixXi_rm Element;
    int num_faults = 1;
    std::vector<std::vector<int>> fault_nodes(2*num_faults);
    mesh_Abaqus_multi_faults(filename, Node, Element, BIE_top, BIE_bot,fault_nodes);
    std::cout<<Node<<std::endl;
    std::cout<<"Node size=" << Node.rows()<<std::endl;
    std::cout<<Element<<std::endl;
    std::cout<<"Element size="<<Element.rows()<<std::endl;
    int nx_BIE = BIE_top.size();
    int n_nodes = Node.rows();
    int n_el = Element.rows();
    int Ndofn = 2;
    int Nnel = Element.cols();
    // Material
    double density = 2670.0;
    double v_s =3.464e3;
    double v_p = 6.0e3;
    double G= pow(v_s,2)*density;
    double Lambda = pow(v_p,2)*density-2.0*G;
    double E  = G*(3.0*Lambda+2.0*G)/(Lambda+G);
    double nu = Lambda/(2.0*(Lambda+G));
    // Time
    double alpha = 0.4;
    double dt = alpha*dx/v_p;
    // Reyleigh Damping
    double beta =0.1;
    double q = beta*dt;
    double time_run = 6.0;
    int numt = time_run/dt;
    //numt = 1;
    VectorXd time = dt*VectorXd::LinSpaced(numt,1,numt);
    // Slip weakening friction parameters
    double Dc = 0.2;
    double mu_d= 0.5;
    double mu_s = 0.6;
    // Intialization
    // disp velocity current and next time step (new)
    VectorXd u_n = VectorXd::Zero(n_nodes*Ndofn,1);
    VectorXd v_n = VectorXd::Zero(n_nodes*Ndofn,1);
    VectorXd u_new = VectorXd::Zero(n_nodes*Ndofn,1);
    VectorXd v_new = VectorXd::Zero(n_nodes*Ndofn,1);
    VectorXd a_n = VectorXd::Zero(n_nodes*Ndofn,1);
    // slip and slip-rate
    std::vector<Eigen::Array<double, -1, 1> > delt_u_n(num_faults);
    std::vector<Eigen::Array<double, -1, 1> > delt_v_n(num_faults);
    std::vector<Eigen::Array<double, -1, 1> > T_c(num_faults);
    std::vector<Eigen::Array<double, -1, 1> > T_0(num_faults);
    std::vector<Eigen::Array<double, -1, 1> > tau_s(num_faults);

    // Vector containing number of elements on each faults (nx)
    std::vector<int> nx_faults(num_faults);
    for (int i=0;i<num_faults;i++)
    {
        nx_faults[i] =fault_nodes[2*i].size();
    }

    for (int i=0;i<num_faults;i++)
    {
        delt_u_n[i] = ArrayXd::Zero(Ndofn*(nx_faults[i]),1);
        delt_v_n[i] = ArrayXd::Zero(Ndofn*(nx_faults[i]),1);
        T_c[i] = ArrayXd::Zero(Ndofn*(nx_faults[i]),1);
        T_0[i] = ArrayXd::Zero(Ndofn*(nx_faults[i]),1);
       // tau_s[i] = ArrayXd::Zero(Ndofn*(nx_faults[i]),1);
        tau_s[i] = 0.6*ArrayXd::Ones((nx_faults[i]),1)*50.0e6;
    }
    VectorXd F_ext_global = VectorXd::Zero(n_nodes*Ndofn,1);

    VectorXd x = VectorXd::Zero(nx_faults[0], 1);
    for (int i=0; i<x.size(); i++)
    {
        x(i) = Node(fault_nodes[0][i],0);
    }
    std::ofstream x_output("results/fault_x_coord.txt");
    x_output << x;

    std::cout<<x<<std::endl;
    // Setting intial stress on the fault
    for (int j=0; j<num_faults;j++)
    {
        for (int i=0; i<nx_faults[j]; i++)
        {
            T_0[j](2*i+1) = -50.0e6;
            T_c[j](2*i+1) = T_0[j](2*i+1);
        }
        if (j==0)
        {
            VectorXd x = VectorXd::LinSpaced(nx_faults[j], x_min, x_max);
            for (int i=0 ; i<nx_faults[j]; i++)
            {
                //if ((x(i)<=(fault_pos(j,1)+fault_pos(j,2))/2+0.2e3)&&(x(i)>=(fault_pos(j,1)+fault_pos(j,2))/2-0.2e3))
                if ((x(i)<=(x_min+x_max)/2+0.6e3)&&(x(i)>=(x_min+x_max)/2-0.6e3))
                {
                    T_0[j](2*i) = 31.0e6;
                    T_c[j](2*i) = T_0[j](2*i);
                }
                else
                {
                    T_0[j](2*i) = 27.5e6;
                    T_c[j](2*i) = T_0[j](2*i);
                }
            }
        }
        else
        {
            for (int i=0 ; i<nx_faults[j]; i++)
            {
                T_0[j](2*i) = 27.5e6;
            }
        }
    }
    // Get the index degree of freedome for each element
    VectorXi index_el = VectorXi::Zero(Ndofn*Nnel,1);
    MatrixXi index_store = MatrixXi::Zero(Nnel*Ndofn,n_el);
    for (int i=0;i<n_el;i++)
    {
        bcdof(Element.row(i),dim,index_el);
        index_store.col(i) = index_el;
    }
  //  VectorXi BIE_top_surf_index = VectorXi::Zero(Ndofn*(BIE_top_surf_nodes.size()),1);
   // VectorXi BIE_bot_surf_index = VectorXi::Zero(Ndofn*(BIE_bot_surf_nodes.size()),1);
    VectorXi BIE_top_surf_index = VectorXi::Zero(Ndofn*(BIE_top.size()),1);
    VectorXi BIE_bot_surf_index = VectorXi::Zero(Ndofn*(BIE_bot.size()),1);
    std::vector<Eigen::ArrayXi> Fault_surf_index(num_faults*2);
    for (int i=0; i <num_faults*2; i++)
    {
        Fault_surf_index[i] = ArrayXi::Zero(Ndofn*(fault_nodes[i].size()),1);
    }

    // Getting the faults DOF index
    for (int i=0; i<num_faults*2;i++)
    {
        bcdof_ptr(fault_nodes[i], dim, Fault_surf_index[i].data());
    }

    bcdof_ptr(BIE_top,dim,BIE_top_surf_index.data());
    bcdof_ptr(BIE_bot,dim,BIE_bot_surf_index.data());
    //bcdof(BIE_top_surf_nodes,dim,BIE_top_surf_index);
    //bcdof(BIE_bot_surf_nodes,dim,BIE_bot_surf_index);
    // Calculating the Global Mass Vector (lumped mass)
    // Element mass
    double M=density*dx*dy*1.0;
    VectorXd M_el_vec = M/4*VectorXd::Ones(Nnel*Ndofn,1);
    VectorXd M_global_vec=VectorXd::Zero(n_nodes*Ndofn,1);
    for (int i=0 ; i<n_el;i++)
    {
        index_el = index_store.col(i);
        mapglobal(index_el,M_global_vec,M_el_vec);
    }
    // Element matrix
    MatrixXd ke = MatrixXd::Zero(8,8);
    MatrixXd coord = MatrixXd::Zero(4,2);
    VectorXi Element_0= Element.row(0);
    coord.row(0) = Node.row(Element_0(0));
    coord.row(1) = Node.row(Element_0(1));
    coord.row(2) = Node.row(Element_0(2));
    coord.row(3) = Node.row(Element_0(3));
    cal_ke (coord,E,nu,ke);
    // BIE part initiation
    // Setting up the material property for the BIE code
    Material BIE_top_mat = Material(E,nu,density);
    Material BIE_bot_mat = Material(E,nu,density);
    double length = x_max-x_min;
    // infinte bc BIE call infinite_boundary.cc
    PrecomputedKernel h11("kernels/nu_.25_h11.dat");
    PrecomputedKernel h12("kernels/nu_.25_k12.dat");
    PrecomputedKernel h22("kernels/nu_.25_h22.dat");
    InfiniteBoundary BIE_inf_top(length,nx_BIE,1.0,&BIE_top_mat,&h11,&h12,&h22);
    InfiniteBoundary BIE_inf_bot(length,nx_BIE,-1.0,&BIE_bot_mat,&h11,&h12,&h22);
    // BIE setting time step
    BIE_inf_top.setTimeStep(dt);
    BIE_inf_bot.setTimeStep(dt);
    // BIE initialization
    BIE_inf_top.init();
    BIE_inf_bot.init();
    printf("ready to start\n");
    // Output
    ofstream file;
    file.open("results/num_nodes_fault.bin",ios::binary);
    file.write((char*)(nx_faults.data()),nx_faults.size()*sizeof(int));
    file.close();

    file.open("results/u_n.bin",ios::binary);
   // file.write((char*)(u_n.data()),u_n.size()*sizeof(double));
    file.close();

    for (int i=0;i<num_faults;i++)
    {
        std::string slip = "results/slip_"+std::to_string(i)+".bin";
        file.open(slip);
        file.close();
        std::string slip_rate = "results/slip_rate_"+std::to_string(i)+".bin";
        file.open(slip_rate);
        file.close();
        std::string shear = "results/shear_"+std::to_string(i)+".bin";
        file.open(shear);
        file.close();
    }
    std::ofstream Element_output("results/Element.txt");
    std::ofstream Node_output("results/Node.txt");
    Node_output<<Node;
    Element_output<<Element;
    //    std::ofstream shear_x("results/shear.txt");
    //double start = omp_get_wtime();

    // Main time loop
    for (int j=0;j<numt;j++)
    {
        // Compute the global internal force
        VectorXd fe_global= VectorXd::Zero(n_nodes*Ndofn,1);
        cal_fe_global_const_ke(n_nodes, n_el, index_store, q, u_n, v_n, Ndofn, ke, fe_global);
        // Friction subroutine
        VectorXd F_total = F_ext_global-fe_global;
        for (int i=0 ; i<num_faults; i++)
        {
            VectorXd F_fault = VectorXd::Zero(Ndofn*(nx_faults[i]),1);
            VectorXd M_pos = VectorXd::Zero(nx_faults[i], 1);
            VectorXd M_neg = VectorXd::Zero(nx_faults[i],1);
            maplocal(Fault_surf_index[2*i], M_global_vec, M_pos);
            maplocal(Fault_surf_index[2*i+1], M_global_vec, M_neg);
            //std::cout<<M_pos<<std::endl;
            Slip_Weakening_lumpM(M_global_vec, Fault_surf_index[2*i], Fault_surf_index[2*i+1], fe_global, dt, dx, dy, nx_faults[i]-1, delt_v_n[i], delt_u_n[i], T_0[i], tau_s[i], mu_s, mu_d, Dc, Ndofn, M_pos, M_neg , F_fault, T_c[i], fault_angle);
            mapglobal(Fault_surf_index[2*i],F_total,-F_fault);
            mapglobal(Fault_surf_index[2*i+1],F_total,F_fault);
        }

        // Central Difference Time integration
        time_advance(u_n, v_n, F_total, M_global_vec, dt);
        // Get the slip and slip rate

        for (int i=0; i<num_faults; i++)
        {
            cal_slip_slip_rate_angle(u_n, v_n,  Fault_surf_index[2*i], Fault_surf_index[2*i+1] , Ndofn, nx_faults[i]-1, delt_u_n[i], delt_v_n[i],fault_angle);
        }
        // Correct the BIE surf nodes solutions from FEM with the BIE solution
        BIE_correct(BIE_top_surf_index, BIE_bot_surf_index, fe_global, Ndofn, nx_BIE-1, dx, BIE_inf_top, BIE_inf_bot, u_n, v_n);

      //  if (j%4==3)
       // {
        for (int i=0;i<num_faults;i++)
        {
            std::string slip = "results/slip_"+std::to_string(i)+".bin";
            file.open(slip,ios::binary | ios::app);
            file.write((char*)(delt_u_n[i].data()),delt_u_n[i].size()*sizeof(double));
            file.close();

            std::string slip_rate = "results/slip_rate_"+std::to_string(i)+".bin";
            file.open(slip_rate,ios::binary | ios::app);
            file.write((char*)(delt_v_n[i].data()),delt_v_n[i].size()*sizeof(double));
            file.close();

            std::string shear = "results/shear_"+std::to_string(i)+".bin";
            file.open(shear,ios::binary | ios::app);
            file.write((char*)(T_c[i].data()),T_c[i].size()*sizeof(double));
            file.close();
        }
        file.open("results/u_n.bin",ios::binary | ios::app);
        file.write((char*)(u_n.data()),u_n.size()*sizeof(double));
        file.close();
       // }
        printf("Simulation time = %f\n",time(j));
      //  double end_t = omp_get_wtime();
       // std::cout<<"time_cpu_t="<<end_t-start<<std::endl;
    //   std::cout<<"time_fem="<< time_fem<<std::endl;
    //   std::cout<<"time_bie="<< time_bie<<std::endl;
    }
    //double end = omp_get_wtime();
    //std::cout<<"time_cpu="<<end-start<<std::endl;
    return 0;
}

void read_matrix(std::string fileName, Eigen::MatrixXd &outputMat) {
    fstream cin;
    cin.open(fileName.c_str());
    if (cin.fail())
    {
        std::cerr << "Failed to open file: " << fileName << std::endl;
        std::cin.get(); }
    string s;
    vector <vector <double> > matrix;
    while (getline(cin, s)) {
        stringstream input(s);
        double temp;
        vector <double> currentLine;
        while (input >> temp)
            currentLine.push_back(temp);
        matrix.push_back(currentLine);
    }
    if (!igl::list_to_matrix(matrix, outputMat))
    { std::cerr << "list tom matrix error" << std::endl; std::cin.get();
        //return false;
    }
}

ext: cc


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

#include "test_utils/sample_graph.hpp"
#include "test_utils/logger.hpp"

#include "paal/data_structures/voronoi/capacitated_voronoi.hpp"
#include "paal/data_structures/object_with_copy.hpp"
#include "paal/data_structures/voronoi/voronoi_traits.hpp"

#include <boost/test/unit_test.hpp>

using namespace paal::data_structures;

std::vector<long long> fcapv{ 7, 7, 3, 1, 2, 2, 2, 1 };
int fcap(int i) { return fcapv[i]; }

std::vector<long long> cdemv{ 2, 2, 1, 3, 3, 1, 1, 2 };
int cdem(int i) { return cdemv[i]; }

BOOST_AUTO_TEST_SUITE(capacitated_voronoi_test_suite)

BOOST_AUTO_TEST_CASE(GeneratorLocationvoronoiutionWithClientAssignmentsTest) {
    LOGLN("Test 0");
    typedef sample_graphs_metrics SGM;
    auto gm = SGM::get_graph_metric_small();

    typedef capacitated_voronoi<decltype(gm), decltype(fcap), decltype(cdem)>
        voronoi;
    typedef voronoi::Generators GSet;
    typedef voronoi::Vertices VSet;
    voronoi vor(GSet{}, VSet{ SGM::A, SGM::B, SGM::C, SGM::D, SGM::E }, gm,
                fcap, cdem);

    /*for(int i = 0; i < 5; ++i)
        LOGLN(gm(SGM::A, i));

    for(int i = 0; i < 5; ++i)
        LOGLN(gm(SGM::B, i));*/

    vor.add_generator(SGM::A);
    auto ab_min_a = vor.add_generator(SGM::B);
    auto b_min_ab = vor.rem_generator(SGM::A);
    BOOST_CHECK_EQUAL(vor.add_generator(SGM::A), -b_min_ab);
    BOOST_CHECK_EQUAL(vor.rem_generator(SGM::B), -ab_min_a);
}

BOOST_AUTO_TEST_CASE(test_1) {
    LOGLN("Test 1");
    typedef sample_graphs_metrics SGM;
    auto gm = SGM::get_graph_metric_small();

    typedef capacitated_voronoi<decltype(gm), decltype(fcap), decltype(cdem)>
        voronoi;
    typedef paal::data_structures::voronoi_traits<voronoi> VT;
    typedef VT::GeneratorsSet GSet;
    typedef VT::VerticesSet VSet;
    voronoi vor(GSet{ SGM::A, SGM::B },
                VSet{ SGM::A, SGM::B, SGM::C, SGM::D, SGM::E }, gm, fcap, cdem);

    vor.add_generator(SGM::C);
    vor.rem_generator(SGM::A);
    vor.add_generator(SGM::A);
    vor.rem_generator(SGM::C);
    vor.add_generator(SGM::D);
    vor.rem_generator(SGM::A);
}

template <typename voronoi> void rem_add(voronoi &v, int g) {
    auto back = v.rem_generator(g);
    auto ret = v.add_generator(g);
    assert(-back == ret);
}

template <typename voronoi>
void rem_add_owc(paal::data_structures::object_with_copy<voronoi> &v, int g) {
    auto back = v.invoke_on_copy(&voronoi::rem_generator, g);
    auto ret = v.invoke_on_copy(&voronoi::add_generator, g);
    assert(-back == ret);
    back = v.invoke(&voronoi::rem_generator, g);
    ret = v.invoke(&voronoi::add_generator, g);
    assert(-back == ret);
}

BOOST_AUTO_TEST_CASE(test_2) {
    LOGLN("Test 2");
    typedef sample_graphs_metrics SGM;
    auto gm = SGM::get_graph_metric_medium();

    typedef capacitated_voronoi<decltype(gm), decltype(fcap), decltype(cdem)>
        voronoi;
    typedef paal::data_structures::voronoi_traits<voronoi> VT;
    typedef VT::GeneratorsSet GSet;
    typedef VT::VerticesSet VSet;
    voronoi vor(
        GSet{ SGM::A, SGM::B, SGM::C, SGM::D, SGM::E, SGM::F, SGM::G, SGM::H },
        VSet{ SGM::A, SGM::B, SGM::C, SGM::D, SGM::E, SGM::F, SGM::G, SGM::H },
        gm, fcap, cdem);
    for (int i = 0; i < 8; ++i) {
        rem_add(vor, i);
    }
}

BOOST_AUTO_TEST_CASE(test_3) {
    LOGLN("Test 3");
    typedef sample_graphs_metrics SGM;
    auto gm = SGM::get_graph_metric_small();

    typedef capacitated_voronoi<decltype(gm), decltype(fcap), decltype(cdem)>
        voronoi;
    typedef paal::data_structures::voronoi_traits<voronoi> VT;
    typedef VT::GeneratorsSet GSet;
    typedef VT::VerticesSet VSet;
    voronoi vor(GSet{ SGM::A /*, SGM::B*/ /*, SGM::C, SGM::D, SGM::E*/ },
                VSet{ SGM::A, SGM::B, SGM::C, SGM::D, SGM::E }, gm, fcap, cdem);

    voronoi vCopy(vor);

    for (int i = 0; i < 1 /*5*/; ++i) {
        rem_add(vCopy, i);
    }
}

BOOST_AUTO_TEST_CASE(test_4) {
    LOGLN("Test 4");
    typedef sample_graphs_metrics SGM;
    auto gm = SGM::get_graph_metric_medium();

    typedef capacitated_voronoi<decltype(gm), decltype(fcap), decltype(cdem)>
        voronoi;
    typedef paal::data_structures::voronoi_traits<voronoi> VT;
    typedef VT::GeneratorsSet GSet;
    typedef VT::VerticesSet VSet;
    voronoi vor(
        GSet{ SGM::A, SGM::B, SGM::C, SGM::D, SGM::E, SGM::F, SGM::G, SGM::H },
        VSet{ SGM::A, SGM::B, SGM::C, SGM::D, SGM::E, SGM::F, SGM::G, SGM::H },
        gm, fcap, cdem);
    for (int i = 0; i < 8; ++i) {
        paal::data_structures::object_with_copy<voronoi> owc(vor);
        rem_add_owc(owc, i);
    }
}
BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: Kommeren/AA

max_issues_repo_name: Kommeren/AA

max_forks_repo_name: Kommeren/AA


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

#define BOOST_THREAD_VERSION 4
#define BOOST_THREAD_PROVIDES_EXECUTORS

#include <boost/thread.hpp>
#include <boost/thread/thread_pool.hpp>
#include <cassert>

auto createFuture()
{
    boost::promise<void> promise;
    promise.set_value();
    return promise.get_future();
}

auto stepOne(boost::basic_thread_pool &executor)
{
    auto sendFuture = createFuture();
    auto wrappedFuture = sendFuture.then(executor, [](auto f) mutable {
        return createFuture();
    });

    return wrappedFuture.unwrap();
}

auto stepTwo(boost::basic_thread_pool &executor)
{
    auto future = stepOne(executor);
    return future.then(executor, [](auto f) {
        assert(f.is_ready());
    });
}

int main()
{
    boost::basic_thread_pool executor{1};
    stepTwo(executor).get();
}


text:
#ifndef LINE_REGION_LIST_HPP_4D3UIS3SDF
#define LINE_REGION_LIST_HPP_4D3UIS3SDF

#include <log4cxx/logger.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/helpers/exception.h>
#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/unordered_map.hpp>
#include <boost/multi_array.hpp>
#include <fstream>
#include <iostream>

//namespace std {using namespace __gnu_cxx;}
using namespace std;

namespace prhlt {
    class Line_Region_List{
        public:
            Line_Region_List(string ex_file_name, int ex_page_start, int ex_page_end);
            ~Line_Region_List();
            vector< vector <int> >  get_line_limits();
            vector< vector <int> >  get_search_zones();
        private:
            vector< vector <int> >  line_limits;
            vector< vector <int> >  search_zones;
            log4cxx::LoggerPtr logger;
            float average_line_size;
            float average_interline_size;
            int page_start;
            int page_end;
            string file_name;
            void clear_limits_list();
            void clear_search_list();
            void load_file();
            void calculate_search_zones();
    };
}

#endif /* end of include guard*/

max_stars_repo_name: jkloe/pageDistanceBasedContourGenerator

max_issues_repo_name: jkloe/pageDistanceBasedContourGenerator

max_forks_repo_name: jkloe/pageDistanceBasedContourGenerator


text:
/*
 BSD 3-Clause License

 Copyright (c) 2016, Bluecadet
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.

 * Neither the name of the copyright holder nor the names of its
 contributors may be used to endorse or promote products derived from
 this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/params/Params.h"
#include "cinder/log.h"

#include "bluecadet/analytics/AnalyticsClient.h"
#include "cinder/Utilities.h"

 // Used to generate UUID; You can also generate one offline and hard code it in your app.
//#include <boost/uuid/uuid.hpp>
//#include <boost/uuid/uuid_generators.hpp>
//#include <boost/uuid/uuid_io.hpp>

using namespace ci;
using namespace ci::app;
using namespace std;

using namespace bluecadet::analytics;

class BasicSampleApp : public App {
public:
	void setup() override;
	void setupParams();
	void update() override;
	void draw() override;

	params::InterfaceGlRef mParams;
};

void BasicSampleApp::setup() {

	// UUID according to RFC 4122 spec (required). Can be hard coded into your app or randomly generated as below (boost optional).
	//string clientId = "00000000-0000-0000-0000-000000000000";
	//string clientId = boost::uuids::to_string(boost::uuids::random_generator()());
	string clientId = trim(loadString(loadUrl("https://www.uuidgenerator.net/api/version1"))); // trim since uuid gen uses extra characters

	// Change this to your app's GA ID (required). Important: GA API doesn't return any reporting errors, so make sure to validate your id.
	string gaId = "UA-74778167-1";

	// The name of your app (required).
	string appName = "Analytics Sample";

	// Can be used to filter events by app version later on (optional).
	string appVersion = "1.0";

	// Setup needs to be called before tracking hits.
	AnalyticsClient::getInstance()->setup(clientId, gaId, appName, appVersion);
	AnalyticsClient::getInstance()->setCustomQuery("&cd3=DefaultCustomQueryFromClient");

	setupParams();
}

void BasicSampleApp::setupParams() {
	mParams = params::InterfaceGl::create("BasicSampleApp", getWindowSize());
	mParams->setPosition(ivec2(0));

	mParams->addText("Config");
	mParams->addParam<string>("Client ID", [](string v) { AnalyticsClient::getInstance()->setClientId(v); }, [] { return AnalyticsClient::getInstance()->getClientId(); });
	mParams->addParam<string>("GA ID", [](string v) { AnalyticsClient::getInstance()->setGaId(v); }, [] { return AnalyticsClient::getInstance()->getGaId(); });
	mParams->addParam<string>("App Name", [](string v) { AnalyticsClient::getInstance()->setAppName(v); }, [] { return AnalyticsClient::getInstance()->getAppName(); });
	mParams->addParam<string>("App Version", [](string v) { AnalyticsClient::getInstance()->setAppVersion(v); }, [] { return AnalyticsClient::getInstance()->getAppVersion(); });

	mParams->addSeparator();
	mParams->addText("Tracking");
	mParams->addButton("Track 1 Event", [] {
		AnalyticsClient::getInstance()->trackEvent("Test Category", "Test Action");
	});
	mParams->addButton("Track 1 Event with Custom Dimensions A", [] {
		AnalyticsClient::getInstance()->trackEvent("Test Category", "Test Action", "", -1, "&cd1=first-a&cd2=second-a");
	});
	mParams->addButton("Track 1 Event with Custom Dimensions B", [] {
		AnalyticsClient::getInstance()->trackEvent("Test Category", "Test Action", "", -1, "&cd1=first-b&cd2=second-b");
	});
	mParams->addButton("Track 150 Events", [] {
		for (int i = 0; i < 150; ++i) {
			AnalyticsClient::getInstance()->trackEvent("Test Category", "Test Action");
		}
	});
	mParams->addButton("Track 1,500 Events", [] {
		for (int i = 0; i < 1500; ++i) {
			AnalyticsClient::getInstance()->trackEvent("Test Category", "Test Action");
		}
	});
	mParams->addButton("Track 1 Screen View", [] {
		AnalyticsClient::getInstance()->trackScreenView("Test Screen");
	});
	mParams->addButton("Track 150 Screen Views", [] {
		for (int i = 0; i < 150; ++i) {
			AnalyticsClient::getInstance()->trackScreenView("Test Screen");
		}
	});

	mParams->addSeparator();
	mParams->addButton("Quit", [this] { quit(); }, "key=q");
}

void BasicSampleApp::update() {
}

void BasicSampleApp::draw() {
	gl::clear(Color(0, 0, 0));
	mParams->draw();
}

CINDER_APP(BasicSampleApp, RendererGl)

max_stars_repo_name: bluecadet/Cinder-BluecadetAnalytics

max_issues_repo_name: bluecadet/Cinder-BluecadetAnalytics

max_forks_repo_name: bluecadet/Cinder-BluecadetAnalytics


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

#include <cstdlib>
#include <iostream>

#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/range.hpp>
#include <boost/coroutine/all.hpp>

#ifdef BOOST_COROUTINES_UNIDIRECT
void power( boost::coroutines::coroutine< int >::push_type & sink, int number, int exponent)
{
    int counter = 0;
    int result = 1;
    while ( counter++ < exponent)
    {
            result = result * number;
            sink( result);
    }
}

int main()
{
    {
        std::cout << "using range functions" << std::endl;
        boost::coroutines::coroutine< int >::pull_type source( boost::bind( power, _1, 2, 8) );
        boost::coroutines::coroutine< int >::pull_type::iterator e( boost::end( source) );
        for ( boost::coroutines::coroutine< int >::pull_type::iterator i( boost::begin( source) );
              i != e; ++i)
            std::cout << * i <<  " ";
    }

    {
        std::cout << "\nusing BOOST_FOREACH" << std::endl;
        boost::coroutines::coroutine< int >::pull_type source( boost::bind( power, _1, 2, 8) );
        BOOST_FOREACH( int i, source)
        { std::cout << i <<  " "; }
    }

    std::cout << "\nDone" << std::endl;

    return EXIT_SUCCESS;
}
#else
typedef boost::coroutines::coroutine< int() >       coro1_t;
typedef boost::coroutines::coroutine< void( int) >  coro2_t;
typedef boost::range_iterator< coro1_t >::type      iterator_t;

void power( coro2_t & c, int number, int exponent)
{
    int counter = 0;
    int result = 1;
    while ( counter++ < exponent)
    {
            result = result * number;
            c( result);
    }
}

int main()
{
    {
        std::cout << "using range functions" << std::endl;
        coro1_t c( boost::bind( power, _1, 2, 8) );
        iterator_t e( boost::end( c) );
        for ( iterator_t i( boost::begin( c) ); i != e; ++i)
            std::cout << * i <<  " ";
    }

    {
        std::cout << "\nusing BOOST_FOREACH" << std::endl;
        coro1_t c( boost::bind( power, _1, 2, 8) );
        BOOST_FOREACH( int i, c)
        { std::cout << i <<  " "; }
    }

    std::cout << "\nDone" << std::endl;

    return EXIT_SUCCESS;
}
#endif

max_stars_repo_name: NixaSoftware/CVis

max_issues_repo_name: NixaSoftware/CVis

max_forks_repo_name: NixaSoftware/CVis


text:
//  Copyright (c) 2001-2011 Hartmut Kaiser
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#if !defined(BOOST_SPIRIT_KARMA_REAL_UTILS_FEB_23_2007_0841PM)
#define BOOST_SPIRIT_KARMA_REAL_UTILS_FEB_23_2007_0841PM

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/config.hpp>
#include <boost/config/no_tr1/cmath.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/limits.hpp>

#include <boost/spirit/home/support/char_class.hpp>
#include <boost/spirit/home/support/unused.hpp>
#include <boost/spirit/home/support/detail/pow10.hpp>
#include <boost/spirit/home/support/detail/sign.hpp>
#include <boost/spirit/home/karma/detail/generate_to.hpp>
#include <boost/spirit/home/karma/detail/string_generate.hpp>
#include <boost/spirit/home/karma/numeric/detail/numeric_utils.hpp>

namespace boost { namespace spirit { namespace karma
{
    ///////////////////////////////////////////////////////////////////////////
    //
    //  The real_inserter template takes care of the floating point number to
    //  string conversion. The Policies template parameter is used to allow
    //  customization of the formatting process
    //
    ///////////////////////////////////////////////////////////////////////////
    template <typename T>
    struct real_policies;

    template <typename T
      , typename Policies = real_policies<T>
      , typename CharEncoding = unused_type
      , typename Tag = unused_type>
    struct real_inserter
    {
        template <typename OutputIterator, typename U>
        static bool
        call (OutputIterator& sink, U n, Policies const& p = Policies())
        {
            if (traits::test_nan(n)) {
                return p.template nan<CharEncoding, Tag>(
                    sink, n, p.force_sign(n));
            }
            else if (traits::test_infinite(n)) {
                return p.template inf<CharEncoding, Tag>(
                    sink, n, p.force_sign(n));
            }
            return p.template call<real_inserter>(sink, n, p);
        }

#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
# pragma warning(push)
# pragma warning(disable: 4100)   // 'p': unreferenced formal parameter
# pragma warning(disable: 4127)   // conditional expression is constant
# pragma warning(disable: 4267)   // conversion from 'size_t' to 'unsigned int', possible loss of data
#endif
        ///////////////////////////////////////////////////////////////////////
        //  This is the workhorse behind the real generator
        ///////////////////////////////////////////////////////////////////////
        template <typename OutputIterator, typename U>
        static bool
        call_n (OutputIterator& sink, U n, Policies const& p)
        {
        // prepare sign and get output format
            bool force_sign = p.force_sign(n);
            bool sign_val = false;
            int flags = p.floatfield(n);
            if (traits::test_negative(n))
            {
                n = -n;
                sign_val = true;
            }

        // The scientific representation requires the normalization of the
        // value to convert.

            // get correct precision for generated number
            unsigned precision = p.precision(n);
            if (std::numeric_limits<U>::digits10)
            {
                // limit generated precision to digits10, if defined
                precision = (std::min)(precision,
                    (unsigned)std::numeric_limits<U>::digits10 + 1);
            }

            // allow for ADL to find the correct overloads for log10 et.al.
            using namespace std;

            U dim = 0;
            if (0 == (Policies::fmtflags::fixed & flags) && !traits::test_zero(n))
            {
                dim = log10(n);
                if (dim > 0)
                    n /= spirit::traits::pow10<U>(traits::truncate_to_long::call(dim));
                else if (n < 1.) {
                    long exp = traits::truncate_to_long::call(-dim);
                    if (exp != -dim)
                        ++exp;
                    dim = -exp;
                    n *= spirit::traits::pow10<U>(exp);
                }
            }

        // prepare numbers (sign, integer and fraction part)
            U integer_part;
            U precexp = spirit::traits::pow10<U>(precision);
            U fractional_part = modf(n, &integer_part);

            fractional_part = floor(fractional_part * precexp + U(0.5));
            if (fractional_part >= precexp)
            {
                fractional_part = floor(fractional_part - precexp);
                integer_part += 1;    // handle rounding overflow
            }

        // if trailing zeros are to be omitted, normalize the precision and
        // fractional part
            U long_int_part = floor(integer_part);
            U long_frac_part = fractional_part;
            unsigned prec = precision;
            if (!p.trailing_zeros(n))
            {
                U frac_part_floor = long_frac_part;
                if (0 != long_frac_part) {
                    // remove the trailing zeros
                    while (0 != prec &&
                           0 == traits::remainder<10>::call(long_frac_part))
                    {
                        long_frac_part = traits::divide<10>::call(long_frac_part);
                        --prec;
                    }
                }
                else {
                    // if the fractional part is zero, we don't need to output
                    // any additional digits
                    prec = 0;
                }

                if (precision != prec)
                {
                    long_frac_part = frac_part_floor /
                        spirit::traits::pow10<U>(precision-prec);
                }
            }

        // call the actual generating functions to output the different parts
            if ((force_sign || sign_val) &&
                traits::test_zero(long_int_part) &&
                traits::test_zero(long_frac_part))
            {
                sign_val = false;     // result is zero, no sign please
                force_sign = false;
            }

        // generate integer part
            bool r = p.integer_part(sink, long_int_part, sign_val, force_sign);

        // generate decimal point
            r = r && p.dot(sink, long_frac_part, precision);

        // generate fractional part with the desired precision
            r = r && p.fraction_part(sink, long_frac_part, prec, precision);

            if (r && 0 == (Policies::fmtflags::fixed & flags)) {
                return p.template exponent<CharEncoding, Tag>(sink,
                    traits::truncate_to_long::call(dim));
            }
            return r;
        }

#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
# pragma warning(pop)
#endif

    };
}}}

#endif


text:
// OpenTissue, A toolbox for physical based simulation and animation.
// Copyright (C) 2007 Department of Computer Science, University of Copenhagen
//
#include <OpenTissue/configuration.h>
#include <OpenTissue/core/spline/spline.h>

#define BOOST_AUTO_TEST_MAIN
#include <boost/test/auto_unit_test.hpp>

// Boost Test declaration and Checking macros
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/test/floating_point_comparison.hpp>

typedef OpenTissue::spline::MathTypes<double, size_t>    math_types;
typedef math_types::vector_type                                vector_type;
typedef std::vector<double>                                    knot_container;
typedef std::vector<vector_type>                               point_container;

typedef OpenTissue::spline::NUBSpline<knot_container, point_container> spline_type;

BOOST_AUTO_TEST_SUITE(opentissue_spline_make_cubic_interpolation);

BOOST_AUTO_TEST_CASE(test_make_cubic_interpolation)
{
  point_container X;

  vector_type p0(2);  p0(0) = 0.0; p0(1) = 0.0;
  vector_type p1(2);  p1(0) = 1.0; p1(1) = 0.0;
  vector_type p2(2);  p2(0) = 2.0; p2(1) = 0.0;
  vector_type p3(2);  p3(0) = 3.0; p3(1) = 0.0;

  X.push_back(p0);
  X.push_back(p1);
  X.push_back(p2);
  X.push_back(p3);

  knot_container U;

  OpenTissue::spline::compute_chord_length_knot_vector(4, X, U);

  spline_type spline = OpenTissue::spline::make_cubic_interpolation( U, X );

  BOOST_CHECK( spline.get_order() == 4 );

  BOOST_CHECK( spline.get_knot_container().size() == 10 );
  BOOST_CHECK( spline.get_knot_container().size() == (spline.get_control_container().size()+4) );
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: ricortiz/OpenTissue

max_issues_repo_name: ricortiz/OpenTissue

max_forks_repo_name: ricortiz/OpenTissue


text:
/*=============================================================================
    Copyright (c) 2003 Jonathan de Halleux (dehalleux@pelikhan.com)
    http://spirit.sourceforge.net/

  Distributed under the Boost Software License, Version 1.0. (See accompanying
  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef BOOST_SPIRIT_ACTOR_ASSIGN_ACTOR_HPP
#define BOOST_SPIRIT_ACTOR_ASSIGN_ACTOR_HPP

#include <boost/spirit/home/classic/actor/ref_const_ref_actor.hpp>
#include <boost/spirit/home/classic/actor/ref_value_actor.hpp>
#include <boost/spirit/home/classic/namespace.hpp>

namespace boost {
namespace spirit {

BOOST_SPIRIT_CLASSIC_NAMESPACE_BEGIN

///////////////////////////////////////////////////////////////////////////
//  Summary:
//  A semantic action policy that applies the assignement operator.
//  (This doc uses convention available in actors.hpp)
//
//  Actions (what it does):
//      ref = value;
//      ref = T(first,last);
//      ref = value_ref;
//
//  Policy name:
//      assign_action
//
//  Policy holder, corresponding helper method:
//      ref_value_actor, assign_a( ref );
//      ref_const_ref_actor, assign_a( ref, value_ref );
//
//  () operators: both
//
//  See also ref_value_actor and ref_const_ref_actor for more details.
///////////////////////////////////////////////////////////////////////////
struct assign_action {
  template <typename T, typename ValueT>
  void act(T &ref_, ValueT const &value_) const {
    ref_ = value_;
  }
  template <typename T, typename IteratorT>
  void act(T &ref_, IteratorT const &first_, IteratorT const &last_) const {
    typedef T value_type;
#ifndef BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS
    value_type value(first_, last_);
#else
    value_type value;
    std::copy(first_, last_, std::inserter(value, value.end()));
#endif
    ref_ = value;
  }
};

// Deprecated. Please use assign_a
template <typename T> inline ref_value_actor<T, assign_action> assign(T &ref_) {
  return ref_value_actor<T, assign_action>(ref_);
}

template <typename T>
inline ref_value_actor<T, assign_action> assign_a(T &ref_) {
  return ref_value_actor<T, assign_action>(ref_);
}

template <typename T, typename ValueT>
inline ref_const_ref_actor<T, ValueT, assign_action>
assign_a(T &ref_, ValueT const &value_) {
  return ref_const_ref_actor<T, ValueT, assign_action>(ref_, value_);
}

BOOST_SPIRIT_CLASSIC_NAMESPACE_END

} // namespace spirit
} // namespace boost

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
/*!
 * *****************************************************************************
 *   \file genFaceMaps.cpp
 *   \author moennen
 *   \brief
 *   \date 2018-09-19
 *   *****************************************************************************/

#include "utils/cv_utils.h"
#include "utils/imgFileLst.h"

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

#include "libImg2ImgCNNInfEng/i2iCNNEngFactory.h"

#include <boost/filesystem.hpp>

#include <random>
#include <iostream>

using namespace std;
using namespace cv;
using namespace glm;
using namespace boost;

const string keys =
    "{help h usage ? |         | print this message   }"
    "{@faceMapsModel |         | face maps model      }"
    "{@faceImgLst    |         | face image list      }"
    "{@outDir        |         | output directories   }"
    "{faceDiscModel  |''       | face disc model      }"
    "{discValThres   |0.0      |    }"
    "{inCHW          |false    |    }"
    "{forceSize      |-1       |    }"
    "{gpu            |         |    }"
    "{show           |         |    }"
    "{nowrite        |         |    }";

int main( int argc, char* argv[] )
{
   CommandLineParser parser( argc, argv, keys );
   if ( parser.has( "help" ) )
   {
      parser.printMessage();
      return ( 0 );
   }

   const bool gpu = parser.get<bool>( "gpu" );
   const bool doShow = parser.get<bool>( "show" );
   const bool doWrite = !parser.get<bool>( "nowrite" );
   const bool inCHW = parser.get<bool>( "inCHW" );
   const int forceSize = parser.get<int>( "forceSize" );
   const float discValThres = parser.get<float>( "discValThres" );

   const filesystem::path outRootPath( parser.get<string>( "@outDir" ) );

   // Load background images
   ImgNFileLst imgLst( 1, parser.get<string>( "@faceImgLst" ).c_str(), "" );
   if ( imgLst.size() == 0 )
   {
      cerr << "Invalid face image list : " << parser.get<string>( "@faceImgLst" ) << endl;
      return -1;
   }

   //--- create the face maps inference engine
   const string mapsModelName = parser.get<string>( "@faceMapsModel" );
   const string mapsInputName = {"adsk_Front"};
   const array<string, 2> mapsOutputNames = {"adsk_UVD", "adsk_Normals"};
   const string discModelName = parser.get<string>( "faceDiscModel" );
   unique_ptr<I2ICNNEng> cnnMapsEngine(
       I2ICNNEngFactory::createCNNEngine( I2ICNNEng::CNNModelFormat::TENSORFLOW_PB ) );
   const string discOutputName = {"adsk_SynthFace"};
   unique_ptr<I2ICNNEng> cnnDiscEngine(
       discOutputName.empty()
           ? nullptr
           : I2ICNNEngFactory::createCNNEngine( I2ICNNEng::CNNModelFormat::TENSORFLOW_PB ) );

   //---
   ivec3 input_sz( ivec3( -1 ) );
   const int nbOutputs = mapsOutputNames.size();
   vector<Mat> outputs( nbOutputs );
   vector<float*> outputs_data( nbOutputs );
   vector<ivec3> outputs_sz( nbOutputs, ivec3( -1 ) );
   Mat disc_output;
   float *disc_output_data=nullptr;

   //--- inference loop
   for ( int s = 0; s < imgLst.size(); ++s )
   {
      // load the inputs data
      Mat input = cv_utils::imread32FC3( imgLst.filePath( s, 0 ), false, true );
      if ( input.empty() ) continue;
      if ( forceSize > 0 ) cv_utils::resizeTo( input, uvec2( forceSize, forceSize ) );
      if ( inCHW ) cv_utils::toCHW32F( input );
      const ivec3 isz( input.cols, input.rows, 3 );
      if ( !all( equal( isz, input_sz ) ) )
      {
         input_sz = isz;
         if ( !cnnMapsEngine->setFromFile(
                  I2ICNNEng::CNNModelFormat::TENSORFLOW_PB,
                  mapsModelName.c_str(),
                  1,
                  &mapsInputName,
                  &input_sz,
                  nbOutputs,
                  &mapsOutputNames[0] ) )
         {
            cerr << "Cannot load the model : " << mapsModelName << endl;
            return -1;
         }
         cnnMapsEngine->printAllOperations();

         for ( int i = 0; i < nbOutputs; ++i )
         {
            outputs_sz[i] = cnnMapsEngine->getOutputsShape( i );
            outputs[i] = Mat( outputs_sz[i].y, outputs_sz[i].x, CV_32FC( outputs_sz[i].z ) );
            outputs_data[i] = reinterpret_cast<float*>( outputs[i].data );
         }

         if ( cnnDiscEngine.get() )
         {
            if ( !cnnDiscEngine->setFromFile(
                     I2ICNNEng::CNNModelFormat::TENSORFLOW_PB,
                     discModelName.c_str(),
                     nbOutputs,
                     &mapsOutputNames[0],
                     &outputs_sz[0],
                     1,
                     &discOutputName ) )
            {
               cerr << "Cannot load the model : " << discModelName << endl;
               return -1;
            }
            cnnDiscEngine->printAllOperations();

            const ivec3 disc_output_sz = cnnDiscEngine->getOutputsShape( 0 );
            disc_output = Mat( disc_output_sz.y, disc_output_sz.x, CV_32FC( disc_output_sz.z ) );
            disc_output_data = (float*)disc_output.data;
         }
      }

      // perform the maps inference
      const float *input_data = (float*)input.data;
      if ( !cnnMapsEngine->run( &input_data, &outputs_data[0] ) ) continue;

      // perform the disc inference
      float discVal = 1.0;
      if ( cnnDiscEngine.get() && cnnDiscEngine->run( (const float **)&outputs_data[0], &disc_output_data ) )
      {
        discVal = mean(disc_output)[0];
      }

      // upload and write the maps
      char sampleId[16];
      sprintf( sampleId, "%08d_", s );
      const string outBasename( sampleId );
      const string outBasenameFull = ( outRootPath / filesystem::path( sampleId ) ).string();

      if ( doWrite && (discVal >= discValThres) )
      {
         imwrite( outBasenameFull + "c.png", input*255.0 );
         imwrite( outBasenameFull + "uvd.exr", outputs[0] );
         imwrite( outBasenameFull + "n.exr", outputs[1] );
      }

      if (discVal >= discValThres)
      {
        std::cout << outBasename + "c.png " << outBasename + "uvd.exr " << outBasename + "n.exr"
                  << std::endl;
      }
      else
      {
        std::cerr << "Filtered face with value = " << discVal << " / " << discValThres << endl;
      }

      if ( doShow )
      {

         imshow( "color", input );
         imshow( "uvdepth", outputs[0]  );
         imshow( "normals", outputs[1] );
         waitKey( 0 );
      }
   }

   return ( 0 );
}

max_stars_repo_name: moennen/sceneIllEst

max_issues_repo_name: moennen/sceneIllEst

max_forks_repo_name: moennen/sceneIllEst


text:
#ifndef TWITTERLIB_OBJECTS_USER_MENTION_HPP
#define TWITTERLIB_OBJECTS_USER_MENTION_HPP
#include <cstdint>
#include <string>

#include <boost/property_tree/ptree_fwd.hpp>

#include <twitterlib/objects/indices.hpp>

namespace twitter {

struct User_mention {
    std::int64_t id;
    Indices indices;
    std::string name;
    std::string screen_name;
};

/// Generates a string display of all data in \p user_mention.
[[nodiscard]] auto to_string(User_mention const& user_mention) -> std::string;

/// Create a User_mention object from a property tree.
[[nodiscard]] auto parse_user_mention(boost::property_tree::ptree const& tree)
    -> User_mention;

}  // namespace twitter
#endif  // TWITTERLIB_OBJECTS_USER_MENTION_HPP


text:
#pragma once

#include <boost/interprocess/offset_ptr.hpp>

#include <cstddef>
#include <memory>
#include <type_traits>

namespace ccls {
namespace db {
namespace impl {

template <typename T>
using offsetPointer = boost::interprocess::offset_ptr<T>;

}
} // namespace db
} // namespace ccls

ext: hh


text:
#include <boost/test/unit_test.hpp>

#include <smtrat-mcsat/smtrat-mcsat.h>
#include <smtrat-mcsat/explanations/fm/Explanation.h>

using namespace smtrat;

BOOST_AUTO_TEST_SUITE(Test_Explanation_FM);

BOOST_AUTO_TEST_CASE(Test_One)
{

	carl::Variable a = carl::freshRealVariable("a");
	carl::Variable b = carl::freshRealVariable("b");

	// Original constraints
	FormulaT c1(Poly(b), carl::Relation::EQ);
	FormulaT c2(Poly(a)*b-Rational(1), carl::Relation::EQ);

	mcsat::Bookkeeping bk;
	bk.pushConstraint(c1);
	bk.pushConstraint(c2);
	mcsat::fm::Explanation<mcsat::fm::DefaultSettings> expl;

	{
		bk.pushAssignment(a, Rational(-1), FormulaT(VariableAssignmentT(a, Rational(-1))));
		auto ref = FormulaT(carl::FormulaType::OR, {
			c1.negated(),
			c2.negated(),
			FormulaT(ConstraintT(Poly(a), carl::Relation::GEQ))
		});
		auto res = expl(bk, b, {c1,c2});
		assert(res);
		std::cout << *res << std::endl;
		std::cout << "Should be " << ref << std::endl;
		BOOST_CHECK(boost::get<FormulaT>(&*res) != nullptr);
		BOOST_CHECK(ref == boost::get<FormulaT>(*res));
		bk.popAssignment(a);
	}
	{
		bk.pushAssignment(a, Rational(1), FormulaT(VariableAssignmentT(a, Rational(1))));
		auto ref = FormulaT(carl::FormulaType::OR, {
			c1.negated(),
			c2.negated(),
			FormulaT(ConstraintT(Poly(a), carl::Relation::LEQ))
		});
		std::cout << "Should be " << ref << std::endl;
		auto res = expl(bk, b, {c1,c2});
		assert(res);
		std::cout << *res << std::endl;
		BOOST_CHECK(boost::get<FormulaT>(&*res) != nullptr);
		BOOST_CHECK(ref == boost::get<FormulaT>(*res));
		bk.popAssignment(a);
	}
}

BOOST_AUTO_TEST_CASE(Test_Two)
{

	carl::Variable x = carl::freshRealVariable("x");
	carl::Variable y = carl::freshRealVariable("y");

	// Original constraints
	FormulaT c1(Poly(y), carl::Relation::GREATER);
	FormulaT c2(Poly(x) + Poly(y), carl::Relation::LESS);

	mcsat::Bookkeeping bk;
	bk.pushConstraint(c1);
	bk.pushConstraint(c2);
	mcsat::fm::Explanation<mcsat::fm::DefaultSettings> expl;

	{
		bk.pushAssignment(x, Rational(0), FormulaT(VariableAssignmentT(x, Rational(0))));
		auto res = expl(bk, y, {c1,c2});
		assert(res);
		std::cout << *res << std::endl;
	}
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: ths-rwth/smtrat

max_issues_repo_name: ths-rwth/smtrat

max_forks_repo_name: ths-rwth/smtrat


text:
/*
 * This file is part of QCL, a small OpenCL interface which makes it quick and
 * easy to use OpenCL.
 *
 * Copyright (c) 2016,2017, Aksel Alpay
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef QCL_BOOST_COMPUTE_COMPAT_HPP
#define QCL_BOOST_COMPUTE_COMPAT_HPP

#define BOOST_COMPUTE_MEM_LEAK_WORKAROUND

#ifdef BOOST_COMPUTE_MEM_LEAK_WORKAROUND
#include "workaround/boost_compute_mem_leak.hpp"
#endif

#include <boost/compute.hpp>

#include "qcl.hpp"
#include "qcl_array.hpp"

namespace qcl {

template<class T>
static
boost::compute::buffer_iterator<T> create_buffer_iterator(const cl::Buffer& buffer,
                                                          std::size_t position)
{
  return boost::compute::make_buffer_iterator<T>(boost::compute::buffer{buffer.get()},
                                                 position);
}

template<class T>
static boost::compute::buffer_iterator<T>
create_buffer_iterator(const device_array<T>& array,
                       std::size_t position)
{
  return create_buffer_iterator<T>(array.get_buffer(), position);
}

boost::compute::context
static
create_boost_compute_context(const device_context_ptr& ctx)
{
  return boost::compute::context{ctx->get_context().get()};
}

template<class T>
struct to_boost_vector_type
{};

#define DECLARE_BOOST_VECTOR_TYPE_TRANSLATOR(cl_type, boost_type) \
  template<> \
  struct to_boost_vector_type<cl_type> \
  { \
    using type = boost_type; \
  }

DECLARE_BOOST_VECTOR_TYPE_TRANSLATOR(cl_float2, boost::compute::float2_);
DECLARE_BOOST_VECTOR_TYPE_TRANSLATOR(cl_float4, boost::compute::float4_);
DECLARE_BOOST_VECTOR_TYPE_TRANSLATOR(cl_float8, boost::compute::float8_);
DECLARE_BOOST_VECTOR_TYPE_TRANSLATOR(cl_float16, boost::compute::float16_);

DECLARE_BOOST_VECTOR_TYPE_TRANSLATOR(cl_double2, boost::compute::double2_);
DECLARE_BOOST_VECTOR_TYPE_TRANSLATOR(cl_double4, boost::compute::double4_);
DECLARE_BOOST_VECTOR_TYPE_TRANSLATOR(cl_double8, boost::compute::double8_);
DECLARE_BOOST_VECTOR_TYPE_TRANSLATOR(cl_double16, boost::compute::double16_);

}

#endif

max_stars_repo_name: illuhad/QuickCL

max_issues_repo_name: illuhad/QuickCL

max_forks_repo_name: illuhad/QuickCL


text:
#include <boost/config.hpp>

#ifdef BOOST_CLANG
#  define SYNTH_STRINGIFY(x) #x
#  define SYNTH_DISCLANGWARN_BEGIN(w) \
    _Pragma("clang diagnostic push") \
    _Pragma(SYNTH_STRINGIFY(clang diagnostic ignored w))
#  define SYNTH_DISCLANGWARN_END _Pragma("clang diagnostic pop")
#else
#  define SYNTH_DISCLANGWARN_BEGIN(w)
#  define SYNTH_DISCLANGWARN_END
#endif


text:
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_UNITS_DETAIL_PUSH_FRONT_OR_ADD_HPP
#define BOOST_UNITS_DETAIL_PUSH_FRONT_OR_ADD_HPP

#include <boost/mpl/plus.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/push_front.hpp>
#include <boost/mpl/pop_front.hpp>
#include <boost/type_traits/is_same.hpp>

#include <boost/units/units_fwd.hpp>
#include <boost/units/detail/push_front_if.hpp>

namespace boost {

namespace units {

template<class Item, class Next>
struct list;

namespace detail {

template<class T>
struct is_empty_dim;

/// add an instantiation of dim to Sequence.
template<bool>
struct push_front_or_add_impl;

template<>
struct push_front_or_add_impl<true>
{
    template<typename Sequence, typename T>
    struct apply
    {
        typedef typename mpl::plus<T, typename Sequence::item>::type item;
        typedef typename push_front_if<!is_empty_dim<item>::value>::template apply<
            typename Sequence::next,
            item
        > type;
    };
};

template<>
struct push_front_or_add_impl<false>
{
    template<typename Sequence, typename T>
    struct apply
    {
        typedef list<T, Sequence> type;
    };
};

template<typename Sequence, typename T>
struct push_front_or_add
{
    typedef typename push_front_or_add_impl<boost::is_same<typename T::tag_type, typename Sequence::item::tag_type>::value>::template apply<
        Sequence,
        T
    >::type type;
};

template<typename T>
struct push_front_or_add<dimensionless_type, T>
{
    typedef list<T, dimensionless_type> type;
};

} // namespace detail

} // namespace units

} // namespace boost

#endif

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
// Copyright (C) 2008-2018 Lorenzo Caminiti
// Distributed under the Boost Software License, Version 1.0 (see accompanying
// file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
// See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html

#include <vector>
#include <limits>
#include <cassert>

//[ifdef_function
// Use #ifdef to completely disable contract code compilation.
#include <boost/contract/core/config.hpp>
#ifndef BOOST_CONTRACT_NO_ALL
    #include <boost/contract.hpp>
#endif

int inc(int& x) {
    int result;
    #ifndef BOOST_CONTRACT_NO_OLDS
        boost::contract::old_ptr<int> old_x = BOOST_CONTRACT_OLDOF(x);
    #endif
    #ifndef BOOST_CONTRACT_NO_FUNCTIONS
        boost::contract::check c = boost::contract::function()
            #ifndef BOOST_CONTRACT_NO_PRECONDITIONS
                .precondition([&] {
                    BOOST_CONTRACT_ASSERT(x < std::numeric_limits<int>::max());
                })
            #endif
            #ifndef BOOST_CONTRACT_NO_POSTCONDITIONS
                .postcondition([&] {
                    BOOST_CONTRACT_ASSERT(x == *old_x + 1);
                    BOOST_CONTRACT_ASSERT(result == *old_x);
                })
            #endif
        ;
    #endif

    return result = x++;
}
//]

template<typename T>
class pushable {
    #ifndef BOOST_CONTRACT_NO_ALL
        friend class boost::contract::access;
    #endif

    #ifndef BOOST_CONTRACT_NO_INVARIANTS
        void invariant() const {
            BOOST_CONTRACT_ASSERT(capacity() <= max_size());
        }
    #endif

public:
    virtual void push_back(
        T const& x
        #ifndef BOOST_CONTRACT_NO_PUBLIC_FUNCTIONS
            , boost::contract::virtual_* v = 0
        #endif
    ) = 0;

protected:
    virtual unsigned capacity() const = 0;
    virtual unsigned max_size() const = 0;
};

template<typename T>
void pushable<T>::push_back(
    T const& x
    #ifndef BOOST_CONTRACT_NO_PUBLIC_FUNCTIONS
        , boost::contract::virtual_* v
    #endif
) {
    #ifndef BOOST_CONTRACT_NO_OLDS
        boost::contract::old_ptr<unsigned> old_capacity =
                BOOST_CONTRACT_OLDOF(v, capacity());
    #endif
    #ifndef BOOST_CONTRACT_NO_PUBLIC_FUNCTIONS
        boost::contract::check c = boost::contract::public_function(v, this)
            #ifndef BOOST_CONTRACT_NO_PRECONDITIONS
                .precondition([&] {
                    BOOST_CONTRACT_ASSERT(capacity() < max_size());
                })
            #endif
            #ifndef BOOST_CONTRACT_NO_POSTCONDITIONS
                .postcondition([&] {
                    BOOST_CONTRACT_ASSERT(capacity() >= *old_capacity);
                })
            #endif
        ;
    #endif
    assert(false); // Shall never execute this body.
}

//[ifdef_class
class integers
    #define BASES public pushable<int>
    :
        #ifndef BOOST_CONTRACT_NO_PRECONDITIONS
            private boost::contract::constructor_precondition<integers>, BASES
        #else
            BASES
        #endif
{
    #ifndef BOOST_CONTRACT_NO_ALL
        friend class boost::contract::access;
    #endif

    #ifndef BOOST_CONTRACT_NO_PUBLIC_FUNCTIONS
        typedef BOOST_CONTRACT_BASE_TYPES(BASES) base_types;
    #endif
    #undef BASES

    #ifndef BOOST_CONTRACT_NO_INVARIANTS
        void invariant() const {
            BOOST_CONTRACT_ASSERT(size() <= capacity());
        }
    #endif

public:
    integers(int from, int to) :
        #ifndef BOOST_CONTRACT_NO_PRECONDITIONS
            boost::contract::constructor_precondition<integers>([&] {
                BOOST_CONTRACT_ASSERT(from <= to);
            }),
        #endif
        vect_(to - from + 1)
    {
        #ifndef BOOST_CONTRACT_NO_CONSTRUCTORS
            boost::contract::check c = boost::contract::constructor(this)
                #ifndef BOOST_CONTRACT_NO_POSTCONDITIONS
                    .postcondition([&] {
                        BOOST_CONTRACT_ASSERT(int(size()) == (to - from + 1));
                    })
                #endif
            ;
        #endif

        for(int x = from; x <= to; ++x) vect_.at(x - from) = x;
    }

    virtual ~integers() {
        #ifndef BOOST_CONTRACT_NO_DESTRUCTORS
            // Check invariants.
            boost::contract::check c = boost::contract::destructor(this);
        #endif
    }

    virtual void push_back(
        int const& x
        #ifndef BOOST_CONTRACT_NO_PUBLIC_FUNCTIONS
            , boost::contract::virtual_* v = 0
        #endif
    ) /* override */ {
        #ifndef BOOST_CONTRACT_NO_OLDS
            boost::contract::old_ptr<unsigned> old_size;
        #endif
        #ifndef BOOST_CONTRACT_NO_PUBLIC_FUNCTIONS
            boost::contract::check c = boost::contract::public_function<
                    override_push_back>(v, &integers::push_back, this, x)
                #ifndef BOOST_CONTRACT_NO_PRECONDITIONS
                    .precondition([&] {
                        BOOST_CONTRACT_ASSERT(size() < max_size());
                    })
                #endif
                #ifndef BOOST_CONTRACT_NO_OLDS
                    .old([&] {
                        old_size = BOOST_CONTRACT_OLDOF(v, size());
                    })
                #endif
                #ifndef BOOST_CONTRACT_NO_POSTCONDITIONS
                    .postcondition([&] {
                        BOOST_CONTRACT_ASSERT(size() == *old_size + 1);
                    })
                #endif
                #ifndef BOOST_CONTRACT_NO_EXCEPTS
                    .except([&] {
                        BOOST_CONTRACT_ASSERT(size() == *old_size);
                    })
                #endif
            ;
        #endif

        vect_.push_back(x);
    }

private:
    #ifndef BOOST_CONTRACT_NO_PUBLIC_FUNCTIONS
        BOOST_CONTRACT_OVERRIDE(push_back)
    #endif

    /* ... */
//]

public: // Could program contracts for these too...
    unsigned size() const { return vect_.size(); }
    unsigned max_size() const { return vect_.max_size(); }
    unsigned capacity() const { return vect_.capacity(); }

private:
    std::vector<int> vect_;
};

int main() {
    integers i(1, 10);
    int x = 123;
    i.push_back(inc(x));
    assert(x == 124);
    assert(i.size() == 11);
    return 0;
}


text: #include <boost/gil/extension/io/jpeg_io_private.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
  // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
  // component of the Texas A&M University System.

  // All rights reserved.

  // The information and source code contained herein is the exclusive
  // property of TEES and may not be disclosed, examined or reproduced
  // in whole or in part without explicit written authorization from TEES.
*/

#include <iostream>
#include <string>
#include <stapl/paragraph/paragraph.hpp>
#include <boost/tokenizer.hpp>
#include <stapl/algorithms/MapReduce/MapReduce.hpp>

using namespace std;
using namespace stapl;
using namespace boost;

struct myTask : mr_task<string, int>
{
  void setup(string infile, string outfile, int split_size, string delimiter)
  {
    set_input_file(infile);
    set_output_file(outfile);
    set_split_size(split_size);
    set_delimiter(delimiter);
  }

  void parse(string const& text)
  {
    char_separator<char> sep(
      "/\r?\n/ ,./<>?;\':\"\\[]{}|-`~!@#$%^&*()_+= \t \r"
    );
    typedef tokenizer<char_separator<char> > tokenizer;
    tokenizer tokens(text, sep);
    for (tokenizer::iterator tok_iter = tokens.begin();
         tok_iter != tokens.end(); ++tok_iter)
      parser_emit(*tok_iter);
  }

  pair<string, int> map(string const& elem)
  {
    return make_pair(elem, 1);
  }

  pair<string, int> reduce(pair<string, int> p_old, pair<string, int> p_new)
  {
    return make_pair(p_old.first, p_old.second + p_new.second);
  }
};

stapl::exit_code stapl_main(int argc, char* argv[])
{
  if (get_location_id() == 0)
    cout << "testing wordcount on STAPL MapReduce...\t";

  string infname = string(argv[1]);
  string outfname = "results";
  myTask task;
  task.setup(infname, outfname, 20, " ");
  task.run();

  if (stapl::get_location_id() == 0) {
    std::map<string, int> lib_results;
    std::map<string, int> local_results;
    ifstream ifs;

    for (unsigned int i = 0; i < get_num_locations(); ++i) {
      stringstream ss;
      ss << outfname;
      ss << ".";
      ss << i;

      ifs.open(ss.str().c_str());
      pair<string, int> p;
      while (!ifs.eof()) {
        ifs >> p.first;
        ifs >> p.second;
        lib_results.insert(p);
      }
      ifs.close();
    }

    ifs.open(infname.c_str());
    size_t begin_of_file = ifs.tellg();
    ifs.seekg(0, std::ios::end);
    size_t fsize = size_t(ifs.tellg()) - begin_of_file;
    ifs.seekg(0, std::ios::beg);
    string tmp;
    tmp.resize(fsize);
    ifs.read(&tmp[0], fsize);
    // tmp[fsize] = '\0';
    ifs.close();

    char_separator<char> sep(
      "/\r?\n/ ,./<>?;\':\"\\[]{}|-`~!@#$%^&*()_+= \t \r"
    );
    typedef tokenizer<char_separator<char> > tokenizer;
    tokenizer tokens(tmp, sep);
    for (tokenizer::iterator tok_iter = tokens.begin();
         tok_iter != tokens.end(); ++tok_iter) {
      //insert_to local_results
      std::pair<string, int> p = make_pair(*tok_iter, 1);
      std::pair<std::map<string, int>::iterator, bool> result;
      result = local_results.insert(p);
      if (!result.second) {
        std::pair<string, int> newp = task.reduce((*(result.first)), p);
        result.first->second = newp.second;
      }
    }

#ifdef SHOW_LIB_RESULTS
    cout << "lib_results:" << endl;
    for (std::map<string, int>::iterator it = lib_results.begin();
         it != lib_results.end(); ++it) {
      cout << (*it).first << " " << (*it).second << endl;
    }

    cout << "local_results:" << endl;
    for (std::map<string, int>::iterator it = local_results.begin();
         it != local_results.end(); ++it) {
      cout << (*it).first << " " << (*it).second << endl;
    }
#endif

    if (lib_results == local_results)
      cout << "[passed]" << endl;
    else
      cout << "[FAILED]" << endl;

  }

  return EXIT_SUCCESS;
}