text:
#include "../../../util/ut_helpers/throws_with_msg.hpp"

#include <boost/ut.hpp>
#include <poac/util/semver/exception.hpp>
#include <poac/util/semver/interval.hpp>

int
main() {
  using namespace std::literals::string_literals;
  using namespace boost::ut;
  using namespace boost::ut::spec;

  using semver::Interval;

  describe("test satisfies") = [] {
    it("test1") = [] {
      Interval interval(">=1.66.0 and <1.70.0");
      expect(interval.satisfies("1.66.0"));
      expect(interval.satisfies("1.67.0"));
      expect(interval.satisfies("1.68.0"));
      expect(interval.satisfies("1.69.0"));
      expect(interval.satisfies("1.69.9"));
      expect(!interval.satisfies("1.70.0"));
    };

    it("test2") = [] {
      Interval interval(">=1.0.0-alpha and <1.0.0");
      expect(interval.satisfies("1.0.0-alpha"));
      expect(interval.satisfies("1.0.0-alpha.1"));
      expect(interval.satisfies("1.0.0-alpha.beta"));
      expect(interval.satisfies("1.0.0-beta"));
      expect(interval.satisfies("1.0.0-beta.2"));
      expect(interval.satisfies("1.0.0-beta.11"));
      expect(interval.satisfies("1.0.0-rc.1"));
      expect(!interval.satisfies("1.0.0"));
    };
  };

  "test is_wasteful_comparison_operation"_test = [] {
    using semver::redundant_interval_error;
    using poac::test::ut_helpers::throws_with_msg;

    throws_with_msg<redundant_interval_error>(
        [] { Interval("<2.0.0 and <1.0.0"); },
        "`<2.0.0 and <1.0.0` is redundant expression.\n"
        "Did you mean <2.0.0 ?"
    );
    throws_with_msg<redundant_interval_error>(
        [] { Interval("<1.0.0 and <2.0.0"); },
        "`<1.0.0 and <2.0.0` is redundant expression.\n"
        "Did you mean <2.0.0 ?"
    );

    throws_with_msg<redundant_interval_error>(
        [] { Interval("<=2.0.0 and <=1.0.0"); },
        "`<=2.0.0 and <=1.0.0` is redundant expression.\n"
        "Did you mean <=2.0.0 ?"
    );
    throws_with_msg<redundant_interval_error>(
        [] { Interval("<2.0.0 and <=1.0.0"); },
        "`<2.0.0 and <=1.0.0` is redundant expression.\n"
        "Did you mean <2.0.0 ?"
    );
    throws_with_msg<redundant_interval_error>(
        [] { Interval("<=2.0.0 and <1.0.0"); },
        "`<=2.0.0 and <1.0.0` is redundant expression.\n"
        "Did you mean <=2.0.0 ?"
    );

    throws_with_msg<redundant_interval_error>(
        [] { Interval("<1.0.0 and <1.0.0-alpha"); },
        "`<1.0.0 and <1.0.0-alpha` is redundant expression.\n"
        "Did you mean <1.0.0 ?"
    );
    // TODO(ken-matsui)
    //        expect(throws<redundant_interval_error>([] {
    //            Interval("<1.0.0-alpha and <1.0.0");
    //        }));
    //        expect(eq(
    //            "`<1.0.0-alpha and <1.0.0` is redundant expression.\n"
    //            "Did you mean <1.0.0 ?"s,
    //            [] {
    //                try {
    //                    Interval("<1.0.0-alpha and <1.0.0");
    //                } catch (const redundant_interval_error& e) {
    //                    return std::string(e.what());
    //                }
    //                return std::string();
    //            }()
    //        ));

    throws_with_msg<redundant_interval_error>(
        [] { Interval("<1.0.0 and <1.0.0"); },
        "`<1.0.0 and <1.0.0` is redundant expression.\n"
        "Did you mean <1.0.0 ?"
    );

    throws_with_msg<redundant_interval_error>(
        [] { Interval(">2.0.0 and >1.0.0"); },
        "`>2.0.0 and >1.0.0` is redundant expression.\n"
        "Did you mean >1.0.0 ?"
    );
    throws_with_msg<redundant_interval_error>(
        [] { Interval(">=2.0.0 and >=1.0.0"); },
        "`>=2.0.0 and >=1.0.0` is redundant expression.\n"
        "Did you mean >=1.0.0 ?"
    );
    throws_with_msg<redundant_interval_error>(
        [] { Interval(">2.0.0 and >=1.0.0"); },
        "`>2.0.0 and >=1.0.0` is redundant expression.\n"
        "Did you mean >=1.0.0 ?"
    );
    throws_with_msg<redundant_interval_error>(
        [] { Interval(">=2.0.0 and >1.0.0"); },
        "`>=2.0.0 and >1.0.0` is redundant expression.\n"
        "Did you mean >1.0.0 ?"
    );

    throws_with_msg<redundant_interval_error>(
        [] { Interval(">1.0.0-alpha and >1.0.0"); },
        "`>1.0.0-alpha and >1.0.0` is redundant expression.\n"
        "Did you mean >1.0.0-alpha ?"
    );
    throws_with_msg<redundant_interval_error>(
        [] { Interval(">1.0.0 and >1.0.0"); },
        "`>1.0.0 and >1.0.0` is redundant expression.\n"
        "Did you mean >1.0.0 ?"
    );
  };

  "test is_bounded_interval"_test = [] {
    using semver::strange_interval_error;

    expect(throws<strange_interval_error>([] { Interval("<1.0.0 and >2.0.0"); })
    );
    // TODO(ken-matsui): test the throwed messages
    expect(throws<strange_interval_error>([] {
      Interval("<1.0.0-alpha and >1.0.0");
    }));
  };
}

ext: cc

max_stars_repo_name: poacpm/cpm

max_issues_repo_name: poacpm/cpm

max_forks_repo_name: poacpm/cpm


text:
/*
(**************************************************************************)
(*                                                                        *)
(*                                Schifra                                 *)
(*                Reed-Solomon Error Correcting Code Library              *)
(*                                                                        *)
(* Release Version 0.0.1                                                  *)
(* http://www.schifra.com                                                 *)
(* Copyright (c) 2000-2018 Arash Partow, All Rights Reserved.             *)
(*                                                                        *)
(* The Schifra Reed-Solomon error correcting code library and all its     *)
(* components are supplied under the terms of the General Schifra License *)
(* agreement. The contents of the Schifra Reed-Solomon error correcting   *)
(* code library and all its components may not be copied or disclosed     *)
(* except in accordance with the terms of that agreement.                 *)
(*                                                                        *)
(* URL: http://www.schifra.com/license.html                               *)
(*                                                                        *)
(**************************************************************************)
*/

/*
   Description: This example will demonstrate the use of the Reed-Solomon
                encoder and decoder capabilities in a threaded context. One
                must note that the number of threads should not exceed the
                architecture's ability to efficiently and productively run the
                threads. A simple limiting strategy would be not to have more
                threads than the number of available cores on the processor.
*/

#include <cstddef>
#include <iostream>
#include <string>
#include <limits>

#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/thread.hpp>

#include "schifra_galois_field.hpp"
#include "schifra_galois_field_polynomial.hpp"
#include "schifra_sequential_root_generator_polynomial_creator.hpp"
#include "schifra_reed_solomon_encoder.hpp"
#include "schifra_reed_solomon_decoder.hpp"
#include "schifra_reed_solomon_block.hpp"
#include "schifra_error_processes.hpp"
#include "schifra_ecc_traits.hpp"
#include "schifra_utilities.hpp"

const std::size_t round_count = 1000;

template <typename Encoder, typename Decoder>
class process
{
public:

   process(const unsigned int& process_id,
           const Encoder& encoder,
           const Decoder& decoder,
           const std::vector<std::string>& message_list)
   : process_id_(process_id),
     total_time_(0.0),
     encoder_(encoder),
     decoder_(decoder),
     message_list_(message_list)
   {}

   process& operator=(const process& proc)
   {
      process_id_ = proc.process_id_;
      total_time_ = proc.total_time_;
      return *this;
   }

   double time() { return total_time_; }

   inline void execute()
   {
      schifra::traits::equivalent_encoder_decoder<Encoder,Decoder>();
      typedef schifra::reed_solomon::block<Encoder::trait::code_length,Encoder::trait::fec_length> block_type;

      std::vector<block_type> block_list(message_list_.size());

      for (std::size_t i = 0; i < message_list_.size(); ++i)
      {
         if (!encoder_.encode(message_list_[i],block_list[i]))
         {
            std::cout << "[" << process_id_ << "] (0)Error - Critical encoding failure!" << std::endl;
            return;
         }
         schifra::corrupt_message_all_errors00(block_list[i],0,3);
      }

      schifra::utils::timer timer;
      timer.start();

      for (std::size_t k = 0; k < round_count; ++k)
      {
         for (std::size_t i = 0; i < message_list_.size(); ++i)
         {
            if (!decoder_.decode(block_list[i]))
            {
               std::cout << "[" << process_id_ << "] (1)Error - Critical decoding failure!" << std::endl;
               return;
            }
            else if (!schifra::is_block_equivelent(block_list[i],message_list_[i]))
            {
               std::cout << "[" << process_id_ << "] (2)Error - Error correction failed!" << std::endl;
               return;
            }
         }
      }

      timer.stop();
      total_time_ = timer.time();
   }

private:

   unsigned int process_id_;
   double total_time_;
   const Encoder& encoder_;
   const Decoder& decoder_;
   const std::vector<std::string>& message_list_;
};

void generate_messages(const std::size_t data_length, std::vector<std::string>& message_list)
{
   for (unsigned int c = 0; c < 256; ++c)
   {
      message_list.push_back(std::string(data_length,static_cast<unsigned char>(c)));
   }
}

int main()
{
   /* Reed Solomon Code Parameters */
   const std::size_t code_length = 255;
   const std::size_t fec_length  =  32;
   const std::size_t data_length = code_length - fec_length;

   /* Finite Field Parameters */
   const std::size_t field_descriptor                =   8;
   const std::size_t generator_polynomial_index      = 120;
   const std::size_t generator_polynomial_root_count = fec_length;

   /* Instantiate Finite Field and Generator Polynomials */
   schifra::galois::field field(field_descriptor,
                                schifra::galois::primitive_polynomial_size06,
                                schifra::galois::primitive_polynomial06);

   schifra::galois::field_polynomial generator_polynomial(field);

   if (
        !schifra::make_sequential_root_generator_polynomial(field,
                                                            generator_polynomial_index,
                                                            generator_polynomial_root_count,
                                                            generator_polynomial)
      )
   {
      std::cout << "Error - Failed to create sequential root generator!" << std::endl;
      return 1;
   }

   typedef schifra::reed_solomon::encoder<code_length,fec_length> encoder_type;
   typedef schifra::reed_solomon::decoder<code_length,fec_length> decoder_type;
   typedef process<encoder_type,decoder_type>                     process_type;
   typedef boost::shared_ptr<process_type>                        process_ptr_type;

   /* Instantiate Encoder and Decoder (Codec) */
   encoder_type encoder(field,generator_polynomial);
   decoder_type decoder(field,generator_polynomial_index);

   std::vector<std::string> message_list;

   generate_messages(data_length,message_list);

   const unsigned int max_thread_count = 4; // number of functional cores.
   std::vector<process_ptr_type> process_list;

   boost::thread_group threads;

   for (unsigned int i = 0; i < max_thread_count; ++i)
   {
      process_list.push_back(process_ptr_type(new process_type(i,encoder,decoder,message_list)));
      threads.create_thread(boost::bind(&process_type::execute,process_list[i]));
   }

   threads.join_all();

   double time = -1.0;

   /* Determine the process with the longest running time. */
   for (std::size_t i = 0; i < process_list.size(); ++i)
   {
      time = ((time < process_list[i]->time()) ? process_list[i]->time() : time);
   }

   double mbps = (max_thread_count * round_count * message_list.size() * data_length * 8.0) / (1048576.0 * time);

   std::cout << "Blocks decoded: " << max_thread_count * round_count * message_list.size() << "\tTime: " << time <<"sec\tRate: " << mbps << "Mbps" << std::endl;

   return 0;
}

ext: cpp

max_stars_repo_name: siglabsoss/s-modem

max_issues_repo_name: siglabsoss/s-modem

max_forks_repo_name: siglabsoss/s-modem


text:
#include "wdict.h"
#include "common.h"
#include "globalVars.h"
#include "kbGraph.h"
#include "disambGraph.h"
#include "fileElem.h"
#include <string>
#include <iostream>
#include <fstream>
#include <syslog.h>

#include "ukbServer.h"

// Basename & friends
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>

// Program options

#include <boost/program_options.hpp>

using namespace ukb;
using namespace std;
using namespace boost;

/////////////////////////////////////////////////////////////
// Global variables

enum main_method {
	m_ppr,       // ppr, whole graph
	m_ppr_w2w,   // ppr_w2w, whole graph
	m_static,    // static, whole graph
	//	m_degree,    // degree, whole graph
	m_bfs,       // bfs subgraph
	m_dfs
};

enum dgraph_rank {
	r_ppr,
	r_ppr_w2w,
	r_static,
	r_degree
};

dgraph_rank dgraph_rank_method = r_ppr;

main_method opt_dmethod = m_ppr_w2w;
string cmdline;
bool opt_daemon = false;
bool opt_dump_dgraph = false;

// Program options stuff

/* Auxiliary functions for checking input for validity. */

/* Function used to check that 'opt1' and 'opt2' are not specified
   at the same time. */
void conflicting_options(const boost::program_options::variables_map& vm,
						 const char* opt1, const char* opt2)
{
	if (vm.count(opt1) && !vm[opt1].defaulted()
		&& vm.count(opt2) && !vm[opt2].defaulted())
		throw logic_error(string("Conflicting options '")
						  + opt1 + "' and '" + opt2 + "'.");
}

/* Function used to check that of 'for_what' is specified, then
   'required_option' is specified too. */
void option_dependency(const boost::program_options::variables_map& vm,
					   const char* for_what, const char* required_option)
{
	if (vm.count(for_what) && !vm[for_what].defaulted())
		if (vm.count(required_option) == 0 || vm[required_option].defaulted())
			throw logic_error(string("Option '") + for_what
							  + "' requires option '" + required_option + "'.");
}

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

// Main functions

// Disambiguate using disambiguation graph (dgraph) method

static void build_dgraph(CSentence & cs, DisambGraph & dgraph) {

	switch (opt_dmethod) {
	case m_dfs:
		if (glVars::dGraph::stopCosenses)
			build_dgraph_dfs_nocosenses(cs, dgraph);
		else build_dgraph_dfs(cs, dgraph);
		break;
	case m_bfs:
		build_dgraph_bfs(cs, dgraph);
		break;
	default:
		cerr << "build_dgraph: [E] logic error\n";
		exit(1);
	}
}

static bool rank_dgraph(const CSentence & cs,
						DisambGraph & dg,
						vector<float> & ranks) {

	bool ok = false;
	switch(dgraph_rank_method) {
	case r_ppr:
		//ok = (opt_dmethod == m_mention) ? dgraph_mention_ppr(cs, dg, ranks) : dgraph_ppr(cs, dg, ranks);
		ok = dgraph_ppr(cs, dg, ranks);
	break;
	case r_degree:
		ok = dgraph_degree(dg, ranks);
		break;
	case r_static:
		ok = dgraph_static(dg, ranks);
		break;
	case r_ppr_w2w:
		cerr << "rank_dgraph: [E] can't use ppr_w2w\n";
		exit(1);
		break;
	}
	return ok;
}

static void disamb_dgraph(CSentence & cs,
						  DisambGraph & dg,
						  vector<float> & ranks) {
		disamb_csentence_dgraph(cs, dg, ranks);
}

void dgraph_w2w_csent(CSentence & cs) {

	// fall back to static if csentence has only one word
	if (cs.size() == 1) {
		if (glVars::debug::warning)
			cerr << "dis_csent: using static for context " << cs.id() << endl;
		const vector<float> ranks = Kb::instance().static_prank();
		disamb_csentence_kb(cs, ranks);
	} else {
		DisambGraph dgraph;
		build_dgraph(cs, dgraph);
		vector<float> ranks;
		for(CSentence::iterator cw_it = cs.ubegin(), cw_end = cs.uend();
			cw_it != cw_end; ++cw_it) {
			if(!cw_it->is_tgtword()) continue;
			bool ok = dgraph_ppr(cs, dgraph, ranks, cw_it);
			if (!ok && glVars::debug::warning) {
				cerr << "dgraph_w2w_csent: [W] No ranks for sentence " << cs.id() << "\n";
				return;
			}
			disamb_cword_dgraph(cw_it, dgraph, ranks);
		}
	}
}

void dgraph_csent(CSentence & cs) {

	if (dgraph_rank_method == r_ppr_w2w) {
		dgraph_w2w_csent(cs);
		return;
	}

	// fall back to static if csentence has only one word
	if (cs.size() == 1) {
		if (glVars::debug::warning)
			cerr << "dis_csent: using static for context " << cs.id() << endl;
		const vector<float> & ranks = Kb::instance().static_prank();
		disamb_csentence_kb(cs, ranks);
	} else {
		DisambGraph dgraph;
		build_dgraph(cs, dgraph);
		vector<float> ranks;
		bool ok = rank_dgraph(cs, dgraph, ranks);
		if (!ok && glVars::debug::warning) {
			cerr << "dgraph_csent: [W] No ranks for sentence " << cs.id() << "\n";
			return;
		}
		disamb_dgraph(cs, dgraph, ranks);
	}
}

void ppr_csent(CSentence & cs) {

	vector<float> ranks;
	bool ok = calculate_kb_ppr(cs,ranks);
	if (!ok && glVars::debug::warning) {
		std::cerr << "ppr_csent: [W] Error in sentence " << cs.id() << "\n";
		return;
	}
	disamb_csentence_kb(cs, ranks);
}

// w2w approach
// for each target word
//   1. init pv with the synsets of the rest of words
//   2. run Personalized Pagerank
//   3. use rank for disambiguating word

void ppr_w2w_csent(CSentence & cs) {

	vector<float> ranks;
	int success_n = 0;

	vector<CWord>::iterator cw_it = cs.ubegin();
	vector<CWord>::iterator cw_end = cs.uend();
	for(; cw_it != cw_end; ++cw_it) {
		// Target word must be distinguished.
		if(!cw_it->is_tgtword()) continue;
		if (!cw_it->is_monosemous() &&
			calculate_kb_ppr_by_word(cs, cw_it, ranks)) {
			success_n++;
			cw_it->rank_synsets(ranks, glVars::csentence::mult_priors);
		}
		cw_it->disamb_cword();
	}
	if (!success_n && glVars::debug::warning) {
		std::cerr << "ppr_w2w_csent: [W] Error in sentence " << cs.id() << "\n";
		return;
	}
}

void static_csent(CSentence &cs) {

	static vector<float> ranks;
	if (!ranks.size()) {
		ranks = Kb::instance().static_prank();
	}
	disamb_csentence_kb(cs, ranks);
}

void dispatch_run_cs(CSentence & cs) {

	switch(opt_dmethod) {
	case m_bfs:
	case m_dfs:
		dgraph_csent(cs);
		break;
	case m_ppr:
		ppr_csent(cs);
		break;
	case m_ppr_w2w:
		ppr_w2w_csent(cs);
		break;
	case m_static:
		static_csent(cs);
		break;
	};
}

void dispatch_run(istream & is, ostream & os) {

	size_t l_n = 0;
	string cid, ctx;
	while (read_ukb_ctx(is, l_n, cid, ctx)) {
		try {
			CSentence cs(cid, ctx);
			if(ctx.size()) {
				dispatch_run_cs(cs);
				cs.print_csent(os);
			} else {
				if (glVars::debug::warning) {
					cerr << "[W] empty context " << cs.id() + " in line " + lexical_cast<string>(l_n) + "\n";
				}
			}
		} catch (ukb::wdict_error & e) {
			throw e;
		} catch (std::logic_error & e) {
			string msg = "[E] Bad context in line " + lexical_cast<string>(l_n) + "\n" + e.what();
			if (!glVars::input::swallow) throw std::runtime_error(msg);
			if (glVars::debug::warning) {
				cerr << msg << "\n";
			}
		}
	}
}

///////////////////////////////////////////////
// Server/clien functions

// Return FALSE means kill server

#ifdef UKB_SERVER
bool handle_server_read(sSession & session) {
	string ctx_id;
	string ctx;
	try {
		if (!session.receive(ctx)) return true;
		if (ctx == "stop") return false;
		session.send(cmdline);
		while(1) {
			if (!session.receive(ctx_id)) break;
			if (!session.receive(ctx)) break;
			CSentence cs(ctx_id, ctx);
			dispatch_run_cs(cs);
			ostringstream oss;
			cs.print_csent(oss);
			string oss_str(oss.str());
			if (!oss_str.length()) oss_str = "#"; // special line if not output
			session.send(oss_str);
		}
	} catch (std::exception& e)	{
		// send error and close the session.
		// Note: the server is still alive for new connections.
		session.send(e.what());
	}
	return true;
}

bool client(istream & is, ostream & os, unsigned int port) {
	// connect to ukb port and send data to it.
	sClient client("localhost", port);
	string server_cmd;
	string go("go");
	if (client.error()) {
		std::cerr << "Error when connecting: " << client.error_str() << std::endl;
		return false;
	}
	string id, ctx, out;
	size_t l_n = 0;
	try {
		client.send(go);
		client.receive(server_cmd);
		os << server_cmd << std::endl;
		while(read_line_noblank(is, id, l_n)) {
			if(!read_line_noblank(is, ctx, l_n)) return false;
			client.send(id);
			client.send(ctx);
			client.receive(out);
			if (out == "#") continue; // empty output for that context
			os << out;
			os.flush();
		}
	} catch (std::exception& e)	{
		std::cerr << e.what() << std::endl;
		return false;
	}
	return true;
}

bool client_stop_server(unsigned int port) {
	// connect to ukb port and tell it to stop
	sClient client("localhost", port);
	string stop("stop");
	if (client.error()) {
		std::cerr << "client_stop_server: [E] Error when connecting: " << client.error_str() << std::endl;
		return false;
	}
	try {
		client.send(stop);
	} catch (std::exception& e)	{
		std::cerr << e.what() << std::endl;
		return false;
	}
	return true;
}
#endif

void load_kb_and_dict(bool from_daemon) {

	if (from_daemon) {
		string aux("Loading KB ");
		aux += glVars::kb::fname;
		syslog(LOG_INFO | LOG_USER, "%s", aux.c_str());
	} else if (glVars::verbose) {
		cout << "Loading KB " + glVars::kb::fname + "\n";
	}
	Kb::create_from_binfile(glVars::kb::fname);
	// Explicitly load dictionary only if:
	// - there is a dictionary name (textual or binary)
	// - from_daemon is set
	if (!from_daemon) return;
	if (!(glVars::dict::text_fname.size() + glVars::dict::bin_fname.size())) return;
	string aux("Loading Dict ");
	aux += glVars::dict::text_fname.size() ? glVars::dict::text_fname : glVars::dict::bin_fname;
	syslog(LOG_INFO | LOG_USER, "%s", aux.c_str());
	// looking for "fake_entry" causes dictionary to be loaded in memory
	WDict_entries fake_entry = WDict::instance().get_entries("kaka", "");
	if (glVars::dict::altdict_fname.size()) {
		WDict::instance().read_alternate_file(glVars::dict::altdict_fname);
	}
}

void test() {

	size_t l_n = 0;

	glVars::dict::use_shuffle = false;
	string cid, ctx;
	read_ukb_ctx(cin, l_n, cid, ctx);
	CSentence cs(cid, ctx);
	cs.debug(cerr);
}

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

	map<string, dgraph_rank> map_dgraph_ranks;

	map_dgraph_ranks["ppr"] = r_ppr;
	map_dgraph_ranks["ppr_w2w"] = r_ppr_w2w;
	map_dgraph_ranks["degree"] = r_degree;
	map_dgraph_ranks["static"] = r_static;

	bool opt_do_test = false;
	bool opt_client = false;
	bool opt_shutdown = false;

	cmdline = string("!! -v ");
	cmdline += glVars::ukb_version;
	for (int i=0; i < argc; ++i) {
		cmdline += " ";
		cmdline += argv[i];
	}

	vector<string> input_files;
	string fullname_in;
	ifstream input_ifs;

#ifdef UKB_SERVER
	unsigned int port = 10000;
#endif
	size_t iterations = 0;
	float thresh = 0.0;
	bool check_convergence = false;

	using namespace boost::program_options;

	const char desc_header[] = "ukb_wsd: perform WSD with KB based algorithm\n"
		"Usage examples:\n"
		"ukb_wsd -D dict.txt -K kb.bin --ppr input.txt    -> Disambiguate input.txt using PPR technique according to graph kb.bin and dictionary dict.txt\n"
		"ukb_wsd -D dict.txt -K kb.bin --dgraph_dfs input.txt -> Disambiguate input.txt using disambiguation graph technique, according to graph kb.bin and dictionary dict.txt\n"
		"Options";

	//options_description po_desc(desc_header);

	options_description po_desc("General");

	po_desc.add_options()
		("help,h", "This page")
		("version", "Show version.")
		("kb_binfile,K", value<string>(), "Binary file of KB (see compile_kb).")
		("dict_file,D", value<string>(), "Dictionary text file.")
		("dict_binfile", value<string>(), "Dictionary binary file.")
		;

	options_description po_desc_wsd("WSD methods");
	po_desc_wsd.add_options()
		("ppr", "Given a text input file, disambiguate context using Personalized PageRank method.")
		("ppr_w2w", "Given a text input file, disambiguate context using Personalized PageRank method word by word (see README).")
		("static", "Given a text input file, disambiguate context using static pageRank over kb.")
		("dgraph_bfs", "Given a text input file, disambiguate context using disambiguation graph mehod (bfs).")
		("dgraph_dfs", "Given a text input file, disambiguate context using disambiguation graph mehod (dfs).")
		("nostatic", "Substract static ppv to final ranks.")
		("noprior", "Don't multiply priors to target word synsets if --ppr_w2w and --dict_weight are selected.")
		;

	options_description po_desc_input("Input options");
	po_desc_input.add_options()
		("nopos", "Don't filter words by Part of Speech.")
		("minput", "Do not die when dealing with malformed input.")
		("ctx_noweight", "Do not use weights of input words (defaut is use context weights).")
		;

	options_description po_desc_prank("pageRank general options");
	po_desc_prank.add_options()
		("prank_nibble", "Use PageRank approximation (PageRank-nibble). See also nibble_epsilon.")
		("prank_weight,w", "Use weights in pageRank calculation. Serialized graph edges must have some weight.")
		("prank_iter", value<size_t>(), "Number of iterations in pageRank. Default is 30.")
		("prank_threshold", value<float>(), "Threshold for stopping PageRank. Default is zero. Good value is 0.0001.")
		("prank_damping", value<float>(), "Set damping factor in PageRank equation. Default is 0.85.")
		("dgraph_rank", value<string>(), "Set disambiguation method for dgraphs. Options are: ppr(default), ppr_w2w, coherence, static, degree.")
		("dgraph_maxdepth", value<size_t>(), "If --dgraph_dfs is set, specify the maximum depth (default is 6).")
		("dgraph_nocosenses", "If --dgraph_dfs, stop DFS when finding one co-sense of target word in path.")
		("nibble_epsilon", value<float>(), "Error for approximate pageRank as computed by the nibble algorithm.")
		;

	options_description po_desc_dict("Dictionary options");
	po_desc_dict.add_options()
		("altdict", value<string>(), "Provide an alternative dictionary overriding the values of default dictionary.")
		("dict_weight", "Use weights when linking words to concepts (dict file has to have weights). This is the default setting.")
		("dict_noweight", "Do not use weights when linking words to concepts.")
		("smooth_dict_weight", value<float>(), "Smoothing factor to be added to every weight in dictionary concepts. Default is 1.")
		("dict_strict", "Be strict when reading the dictionary and stop when any error is found.")
		;

	options_description po_desc_output("Output options");
	po_desc_output.add_options()
		("allranks", "Write key file with all synsets associated with ranks.")
		("verbose,v", "Be verbose.")
		("no-monosemous", "Don't output anything for monosemous words.")
		("ties", "Output also in case of ties.")
		("rank_nonorm", "Do not normalize the ranks of target words.")
		("dump_dgraph", "Dump subgraphs using gaphviz format.")
		;

	options_description po_desc_server("Client/Server options");
	po_desc_server.add_options()
		("daemon", "Start a daemon listening to port. Assumes --port")
		("port", value<unsigned int>(), "Port to listen/send information.")
		("client", "Use client mode to send contexts to the ukb daemon. Bare in mind that the configuration is that of the server.")
		("shutdown", "Shutdown ukb daemon.")
		;

	options_description po_visible(desc_header);
	po_visible.add(po_desc).add(po_desc_wsd).add(po_desc_prank).add(po_desc_input).add(po_desc_dict).add(po_desc_output).add(po_desc_server);

	options_description po_hidden("Hidden");
	po_hidden.add_options()
		("bcomp_kb_binfile,M", value<string>(), "Backward compatibility with -K.")
		("bcomp_dictfile,W", value<string>(), "Backward compatibility with -D.")
		("only_ctx_words,C", "Backward compatibility with -C.")
		("concept_graph,G", "Backward compatibility with -G.")
		("dgraph", "Backward compatibility with --dgraph.")
		("nodict_weight", "alias of --dict_noweight")
		("test,t", "(Internal) Do a test.")
		("input-file",value<string>(), "Input file.")
		;
	options_description po_all("All options");
	po_all.add(po_visible).add(po_hidden);

	positional_options_description po_optdesc;
	po_optdesc.add("input-file", 1);
	//    po_optdesc.add("output-file", 1);

	try {

		variables_map vm;
		store(command_line_parser(argc, argv).
			  options(po_all).
			  positional(po_optdesc).
			  run(), vm);

		notify(vm);

		// If asked for help, don't do anything more

		if (vm.count("help")) {
			cout << po_visible << endl;
			exit(0);
		}

		if (vm.count("version")) {
			cout << glVars::ukb_version << endl;
			exit(0);
		}

		if (vm.count("nopos")) {
			glVars::input::filter_pos = false;
		}

		if (vm.count("minput")) {
			glVars::input::swallow = true;
		}

		if (vm.count("ctx_noweight")) {
			glVars::input::weight = false;
		}

		if (vm.count("ppr")) {
			opt_dmethod = m_ppr;
		}

		if (vm.count("ppr_w2w")) {
			opt_dmethod = m_ppr_w2w;
		}

		if (vm.count("static")) {
			opt_dmethod = m_static;
		}

		if (vm.count("dgraph_bfs")) {
			opt_dmethod = m_bfs;
		}

		if (vm.count("dgraph")) {
			opt_dmethod = m_bfs;
		}

		if (vm.count("dgraph_dfs")) {
			opt_dmethod = m_dfs;
		}

		if (vm.count("prank_iter")) {
			iterations = vm["prank_iter"].as<size_t>();
			check_convergence = true;
		}

		if (vm.count("prank_threshold")) {
			thresh = vm["prank_threshold"].as<float>();
			check_convergence = true;
		}

		if (vm.count("prank_damping")) {
			float dp = vm["prank_damping"].as<float>();
			if (dp <= 0.0 || dp > 1.0) {
				cerr << "Error: invalid prank_damping value " << dp << "\n";
				exit(-1);
			}
			glVars::prank::damping = dp;
		}

		if (vm.count("prank_nibble")) {
			glVars::prank::impl = glVars::nibble;
		}

		if (vm.count("nibble_epsilon")) {
			float dp = vm["nibble_epsilon"].as<float>();
			if (dp <= 0.0 || dp > 1.0) {
				cerr << "Error: invalid nibble_epsilon value " << dp << "\n";
				exit(-1);
			}
			glVars::prank::nibble_epsilon = dp;
		}

		if (vm.count("dgraph_maxdepth")) {
			size_t md = vm["dgraph_maxdepth"].as<size_t>();
			if (md == 0) {
				cerr << "Error: invalid dgraph_maxdepth of zero\n";
				exit(-1);
			}
			glVars::dGraph::max_depth = md;
		}

		if (vm.count("dgraph_nocosenses")) {
			glVars::dGraph::stopCosenses = true;
		}

		if (vm.count("dgraph_rank")) {
			string str = vm["dgraph_rank"].as<string>();
			map<string, dgraph_rank>::iterator it = map_dgraph_ranks.find(str);
			if (it == map_dgraph_ranks.end()) {
				cerr << "Error: invalid dgraph_rank method. Should be one of: ";
				for(map<string, dgraph_rank>::iterator iit = map_dgraph_ranks.begin();
					iit != map_dgraph_ranks.end(); ++iit)
					cerr << " " << iit->first;
				cerr << "\n";
				exit(-1);
			}
			dgraph_rank_method = it->second;
		}

		if (vm.count("nostatic")) {
			glVars::csentence::disamb_minus_static = true;
		}

		if (vm.count("noprior")) {
			glVars::csentence::mult_priors = false;
		}

		if (vm.count("bcomp_dictfile")) {
			glVars::dict::text_fname = vm["bcomp_dictfile"].as<string>();
		}

		if (vm.count("dict_file")) {
			glVars::dict::text_fname = vm["dict_file"].as<string>();
		}

		if (vm.count("dict_binfile")) {
			glVars::dict::bin_fname = vm["dict_binfile"].as<string>();
		}

		if (vm.count("dict_strict")) {
			glVars::dict::swallow = false;
		}

		if (vm.count("dict_weight")) {
			glVars::dict::use_weight = true;
		}

		if (vm.count("dict_noweight")) {
			glVars::dict::use_weight = false;
		}

		if (vm.count("nodict_weight")) {
			glVars::dict::use_weight = false;
		}

		if (vm.count("smooth_dict_weight")) {
			glVars::dict::weight_smoothfactor = vm["smooth_dict_weight"].as<float>();
		}

		if (vm.count("bcomp_kb_binfile")) {
			glVars::kb::fname = vm["bcomp_kb_binfile"].as<string>();
		}

		if (vm.count("kb_binfile")) {
			glVars::kb::fname = vm["kb_binfile"].as<string>();
		}

		if (vm.count("rank_alg")) {
			glVars::RankAlg alg = glVars::get_algEnum(vm["rank_alg"].as<string>());
			if (alg == glVars::no_alg) {
				cerr << "Error: Undefined rank algorithm " << vm["rank_alg"].as<string>() << endl;
				exit(-1);
			}
			glVars::rAlg = alg;
		}

		if (vm.count("prank_weight")) {
			glVars::prank::use_weight = true;
		}

		if (vm.count("input-file")) {
			fullname_in = vm["input-file"].as<string>();
		}

		if (vm.count("verbose")) {
			glVars::verbose = 1;
			glVars::debug::warning = 1;
		}

		if (vm.count("allranks")) {
			glVars::output::allranks = true;
		}

		if (vm.count("dump_dgraph")) {
			opt_dump_dgraph = true;
		}

		if (vm.count("test")) {
			opt_do_test = true;
		}

		if (vm.count("no-monosemous")) {
			glVars::output::monosemous = false;
		}

		if (vm.count("ties")) {
			glVars::output::ties = true;
		}

		if (vm.count("rank_nonorm")) {
			glVars::output::norm_ranks = false;
		}

		if (vm.count("altdict")) {
			glVars::dict::altdict_fname = vm["altdict"].as<string>();
		}

		if (vm.count("daemon")) {
#ifdef UKB_SERVER
			opt_daemon = true;
#else
		cerr << "[E] server not available (compile ukb without -DUKB_SERVER switch)\n";
		exit(1);
#endif
		}

		if (vm.count("port")) {
#ifdef UKB_SERVER
			port = vm["port"].as<unsigned int>();;
#else
		cerr << "[E] server not available (compile ukb without -DUKB_SERVER switch)\n";
		exit(1);
#endif
		}

		if (vm.count("client")) {
#ifdef UKB_SERVER
			opt_client = true;
#else
			cerr << "[E] server not available (compile ukb without -DUKB_SERVER switch)\n";
			exit(1);
#endif
		}

		if (vm.count("shutdown")) {
#ifdef UKB_SERVER
			opt_shutdown = true;
#else
			cerr << "[E] server not available (compile ukb without -DUKB_SERVER switch)\n";
			exit(1);
#endif
		}

	} catch(std::exception& e) {
		cerr << e.what() << "\n";
		exit(-1);
	}

	if(opt_shutdown) {
#ifdef UKB_SERVER
		if (client_stop_server(port)) {
			cerr << "Stopped UKB daemon on port " << lexical_cast<string>(port) << "\n";
			return 0;
		} else {
			cerr << "Can not stop UKB daemon on port " << lexical_cast<string>(port) << "\n";
			return 1;
		}
#endif
	}

	// if not daemon, check input files (do it early before loading KB and dictionary)
	if (!fullname_in.size() and !opt_daemon) {
		cout << po_visible << endl;
		cout << "Error: No input" << endl;
		exit(-1);
	}

	if (check_convergence) set_pr_convergence(iterations, thresh);

	// if --daemon, fork server process (has to be done before loading KB and dictionary)
	if (opt_daemon) {
#ifdef UKB_SERVER
		try {
			// Get absolute names of KB and dict
			glVars::kb::fname =  get_fname_absolute(glVars::kb::fname);
			glVars::dict::text_fname = get_fname_absolute(glVars::dict::text_fname);
			glVars::dict::altdict_fname = get_fname_absolute(glVars::dict::altdict_fname);
		} catch(std::exception& e) {
			cerr << e.what() << "\n";
			return 1;
		}
		if (!glVars::kb::fname.size()) {
			cerr << "Error: no KB file\n";
			return 1;
		}
		// accept malformed contexts, as we don't want the daemon to die.
		glVars::input::swallow = true;
		cout << "Starting UKB WSD daemon on port " << lexical_cast<string>(port) << " ... \n";
		return start_daemon(port, &load_kb_and_dict, &handle_server_read);
#endif
	}

	// if not --client, load KB
	if (!opt_client) {
		if (!glVars::kb::fname.size()) {
			cerr << "Error: no KB file\n";
			exit(1);
		}
		try {
			load_kb_and_dict(false);
		} catch (std::exception & e) {
			cerr << e.what() << "\n";
			return 1;
		}
	}

	// create stream from input file
	if (fullname_in == "-" ) {
		// read from <STDIN>
		cmdline += " <STDIN>";
		fullname_in = "<STDIN>";
	} else {
		input_ifs.open(fullname_in.c_str(), ofstream::in);
		if (!input_ifs) {
			cerr << "[E] Can't open " << fullname_in << endl;
			exit(-1);
		}
		// redirect std::cin to read from file
		std::cin.rdbuf(input_ifs.rdbuf());
	}

	if (opt_client) {
#ifdef UKB_SERVER
		// TODO :
		// - check parameters
		// - cmdline
		return !client(std::cin, std::cout, port);
#endif
	}

	if (opt_do_test) {
		test();
		return 0;
	}

	cout << cmdline << "\n";

	try {
		dispatch_run(std::cin, std::cout);
	} catch (std::exception & e) {
		cerr << "[E] Error reading " << fullname_in << "\n" << e.what() << "\n";
		return 0;
	}

	return 0;
}

max_stars_repo_name: MWTA/Text-Mining

max_issues_repo_name: MWTA/Text-Mining

max_forks_repo_name: MWTA/Text-Mining


text:
/*
 * Copyright (c) 2011-2012 by Michael Berlin, Zuse Institute Berlin
 *
 * Licensed under the BSD License, see LICENSE file for details.
 *
 */

#include <boost/scoped_ptr.hpp>
#include <iostream>
#include <string>

#include "libxtreemfs/client.h"
#include "libxtreemfs/file_handle.h"
#include "libxtreemfs/helper.h"
#include "libxtreemfs/system_user_mapping.h"
#include "libxtreemfs/user_mapping.h"
#include "libxtreemfs/volume.h"
#include "libxtreemfs/xtreemfs_exception.h"
#include "rmfs.xtreemfs/rmfs_options.h"
#include "util/logging.h"

using namespace std;
using namespace xtreemfs;
using namespace xtreemfs::pbrpc;
using namespace xtreemfs::util;

int main(int argc, char* argv[]) {
  // Parse command line options.
  RmfsOptions options;
  bool invalid_commandline_parameters = false;
  try {
    options.ParseCommandLine(argc, argv);
  } catch(const XtreemFSException& e) {
    cout << "Invalid parameters found, error: " << e.what() << endl << endl;
    invalid_commandline_parameters = true;
  }
  // Display help if needed.
  if (options.empty_arguments_list || invalid_commandline_parameters) {
    cout << options.ShowCommandLineUsage() << endl;
    return 1;
  }
  if (options.show_help) {
    cout << options.ShowCommandLineHelp() << endl;
    return 1;
  }
  // Show only the version.
  if (options.show_version) {
    cout << options.ShowVersion("rmfs.xtreemfs") << endl;
    return 1;
  }

  // Safety question
  if (!options.force) {
    string answer;
    cout << "Do you really want to delete the volume: \""
         << options.xtreemfs_url << "\"?" << endl
         << "Answer with \"YES\" to proceed: ";

    getline(cin, answer);
    if (answer != "YES") {
      return 1;
    }
  }

  bool success = true;
  boost::scoped_ptr<SystemUserMapping> system_user_mapping;
  boost::scoped_ptr<Client> client;
  try {
    // Start logging manually (although it would be automatically started by
    // ClientImplementation()) as its required by UserMapping.
    initialize_logger(options.log_level_string,
                      options.log_file_path,
                      LEVEL_WARN);

    // Set user_credentials.
    system_user_mapping.reset(SystemUserMapping::GetSystemUserMapping());
    // Check if the user specified an additional user mapping in options.
    UserMapping* additional_um = UserMapping::CreateUserMapping(
        options.additional_user_mapping_type,
        options);
    if (additional_um) {
      system_user_mapping->RegisterAdditionalUserMapping(additional_um);
      system_user_mapping->StartAdditionalUserMapping();
    }

    UserCredentials user_credentials;
    system_user_mapping->GetUserCredentialsForCurrentUser(&user_credentials);
    if (user_credentials.username().empty()) {
      cout << "Error: No name found for the current user (using the configured "
          "UserMapping: " << options.additional_user_mapping_type << ")\n";
      return 1;
    }
    // The groups won't be checked and therefore may be empty.

    // Create a new client and start it.
    client.reset(Client::CreateClient(
        "DIR-host-not-required-for-rmfs",  // Using a bogus value as DIR address.  // NOLINT
        user_credentials,
        options.GenerateSSLOptions(),
        options));
    client->Start();

    // Delete the volume.
    Auth auth;
    if (options.admin_password.empty()) {
      auth.set_auth_type(AUTH_NONE);
    } else {
      auth.set_auth_type(AUTH_PASSWORD);
      auth.mutable_auth_passwd()->set_password(options.admin_password);
    }
    cout << "Trying to delete the volume: " << options.xtreemfs_url << endl;

    client->DeleteVolume(options.mrc_service_address,
                         auth,
                         user_credentials,
                         options.volume_name);
  } catch (const XtreemFSException& e) {
    success = false;
    cout << "Failed to delete the volume, error:\n"
         << "\t" << e.what() << endl;
  }

  // Cleanup.
  if (client) {
    client->Shutdown();
  }
  system_user_mapping->StopAdditionalUserMapping();

  if (success) {
    cout << "Successfully deleted the volume \"" << options.volume_name
             << "\" at MRC: " << options.mrc_service_address << "\n"
         << "\n"
         << "The disk space on the OSDs, occupied by the objects of the\n"
            "files of the deleted volume, is not freed yet.\n"
         << "Run the tool 'xtfs_cleanup' to free it." << endl;
    return 0;
  } else {
    return 1;
  }
}


text:
// Copyright (C) 2003  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.

#include <sstream>
#include <string>
#include <ctime>
#include <cstdlib>

#include <dlib/conditioning_class.h>

#include "tester.h"
#include "conditioning_class.h"

namespace
{

    class conditioning_class_tester : public tester
    {
    public:
        conditioning_class_tester (
        ) :
            tester ("test_conditioning_class",
                    "Runs tests on the conditioning_class component.")
        {}

        void perform_test (
        )
        {
            dlog << LINFO << "testing kernel_1a";
            conditioning_class_kernel_test<
                conditioning_class<256>::kernel_1a,
                conditioning_class<2>::kernel_1a
                >();
            print_spinner();

            dlog << LINFO << "testing kernel_2a";
            conditioning_class_kernel_test<
                conditioning_class<256>::kernel_2a,
                conditioning_class<2>::kernel_2a
                >();
            print_spinner();

            dlog << LINFO << "testing kernel_3a";
            conditioning_class_kernel_test<
                conditioning_class<256>::kernel_3a,
                conditioning_class<2>::kernel_3a
                >();
            print_spinner();

            dlog << LINFO << "testing kernel_4a";
            conditioning_class_kernel_test<
                conditioning_class<256>::kernel_4a,
                conditioning_class<2>::kernel_4a
                >();
            print_spinner();

            dlog << LINFO << "testing kernel_4b";
            conditioning_class_kernel_test<
                conditioning_class<256>::kernel_4b,
                conditioning_class<2>::kernel_4b
                >();
            print_spinner();

            dlog << LINFO << "testing kernel_4c";
            conditioning_class_kernel_test<
                conditioning_class<256>::kernel_4c,
                conditioning_class<2>::kernel_4c
                >();
            print_spinner();

            dlog << LINFO << "testing kernel_4d";
            conditioning_class_kernel_test<
                conditioning_class<256>::kernel_4d,
                conditioning_class<2>::kernel_4d
                >();
            print_spinner();

        }
    } a;

}

max_stars_repo_name: yatonon/dlib-face


text:
//           Copyright Matthew Pulver 2018 - 2019.
// Distributed under the Boost Software License, Version 1.0.
//      (See accompanying file LICENSE_1_0.txt or copy at
//           https://www.boost.org/LICENSE_1_0.txt)

#include "test_autodiff.hpp"
#include <boost/math/tools/test_value.hpp>

BOOST_AUTO_TEST_SUITE(test_autodiff_4)

BOOST_AUTO_TEST_CASE_TEMPLATE(lround_llround_lltrunc_truncl, T,
                              all_float_types) {
  using boost::math::llround;
  using boost::math::lltrunc;
  using boost::math::lround;
  using boost::multiprecision::llround;
  using boost::multiprecision::lltrunc;
  using boost::multiprecision::lround;
  using detail::llround;
  using detail::lltrunc;
  using detail::lround;
  using detail::truncl;
  using std::truncl;

  constexpr std::size_t m = 3;
  const auto &cx = static_cast<T>(3.25);
  auto x = make_fvar<T, m>(cx);
  auto yl = lround(x);
  BOOST_CHECK_EQUAL(yl, lround(cx));
  auto yll = llround(x);
  BOOST_CHECK_EQUAL(yll, llround(cx));
  BOOST_CHECK_EQUAL(lltrunc(cx), lltrunc(x));

#ifndef BOOST_NO_CXX17_IF_CONSTEXPR
  if constexpr (!bmp::is_number<T>::value &&
                !bmp::is_number_expression<T>::value) {
    BOOST_CHECK_EQUAL(truncl(x), truncl(cx));
  }
#endif
}

BOOST_AUTO_TEST_CASE_TEMPLATE(equality, T, all_float_types) {
  BOOST_MATH_STD_USING
  using boost::math::epsilon_difference;
  using boost::math::fpclassify;
  using boost::math::ulp;
  using std::fpclassify;

  constexpr std::size_t m = 3;
  // check zeros
  {
    auto x = make_fvar<T, m>(0.0);
    auto y = T(-0.0);
    BOOST_CHECK_EQUAL(x.derivative(0u), y);
  }
}

#if defined(BOOST_AUTODIFF_TESTING_INCLUDE_MULTIPRECISION)
BOOST_AUTO_TEST_CASE_TEMPLATE(multiprecision, T, multiprecision_float_types) {
  using boost::multiprecision::fabs;
  using detail::fabs;
  using std::fabs;

  const T eps = 3000 * std::numeric_limits<T>::epsilon();
  constexpr std::size_t Nw = 3;
  constexpr std::size_t Nx = 2;
  constexpr std::size_t Ny = 4;
  constexpr std::size_t Nz = 3;
  const auto w = make_fvar<T, Nw>(11);
  const auto x = make_fvar<T, 0, Nx>(12);
  const auto y = make_fvar<T, 0, 0, Ny>(13);
  const auto z = make_fvar<T, 0, 0, 0, Nz>(14);
  const auto v =
      mixed_partials_f(w, x, y, z); // auto = autodiff_fvar<T,Nw,Nx,Ny,Nz>
  // Calculated from Mathematica symbolic differentiation.
  const T answer = BOOST_MATH_TEST_VALUE(T, 1976.31960074779771777988187529041872090812118921875499076582535951111845769110560421820940516423255314);
  // BOOST_CHECK_CLOSE(v.derivative(Nw,Nx,Ny,Nz), answer, eps); // Doesn't work
  // for cpp_dec_float
  const T relative_error =
      static_cast<T>(fabs(v.derivative(Nw, Nx, Ny, Nz) / answer - 1));
  BOOST_CHECK_LT(relative_error, eps);
}
#endif

BOOST_AUTO_TEST_CASE_TEMPLATE(acosh_hpp, T, all_float_types) {
  using boost::math::acosh;
  using test_constants = test_constants_t<T>;
  static constexpr auto m = test_constants::order;

  test_detail::RandomSample<T> x_sampler{1, 100};
  for (auto i : boost::irange(test_constants::n_samples)) {
    std::ignore = i;
    auto x = x_sampler.next();
    auto autodiff_v = acosh(make_fvar<T, m>(x));
    auto anchor_v = acosh(x);
    BOOST_CHECK_CLOSE(autodiff_v.derivative(0u), anchor_v,
                      1e3 * test_constants::pct_epsilon());
  }
}

BOOST_AUTO_TEST_CASE_TEMPLATE(asinh_hpp, T, all_float_types) {
  using boost::math::asinh;
  using test_constants = test_constants_t<T>;
  static constexpr auto m = test_constants::order;

  test_detail::RandomSample<T> x_sampler{-100, 100};
  for (auto i : boost::irange(test_constants::n_samples)) {
    std::ignore = i;
    auto x = x_sampler.next();

    auto autodiff_v = asinh(make_fvar<T, m>(x));
    auto anchor_v = asinh(x);
    BOOST_CHECK_CLOSE(autodiff_v.derivative(0u), anchor_v,
                      1e3 * test_constants::pct_epsilon());
  }
}

BOOST_AUTO_TEST_CASE_TEMPLATE(atanh_hpp, T, all_float_types) {
  using boost::math::nextafter;
  using std::nextafter;

  using boost::math::atanh;
  using test_constants = test_constants_t<T>;
  static constexpr auto m = test_constants::order;

  test_detail::RandomSample<T> x_sampler{-1, 1};
  for (auto i : boost::irange(test_constants::n_samples)) {
    std::ignore = i;
    auto x = nextafter(x_sampler.next(), T(0));

    auto autodiff_v = atanh(make_fvar<T, m>(x));
    auto anchor_v = atanh(x);
    BOOST_CHECK_CLOSE(autodiff_v.derivative(0u), anchor_v,
                      1e3 * test_constants::pct_epsilon());
  }
}

BOOST_AUTO_TEST_CASE_TEMPLATE(atan_hpp, T, all_float_types) {
  using boost::math::float_prior;
  using boost::math::fpclassify;
  using boost::math::signbit;
  using boost::math::differentiation::detail::atan;
  using boost::multiprecision::atan;
  using boost::multiprecision::fabs;
  using boost::multiprecision::fpclassify;
  using boost::multiprecision::signbit;
  using detail::fabs;
  using std::atan;
  using std::fabs;

  using test_constants = test_constants_t<T>;
  static constexpr auto m = test_constants::order;

  test_detail::RandomSample<T> x_sampler{-1, 1};
  for (auto i : boost::irange(test_constants::n_samples)) {
    std::ignore = i;
    auto x = T(1);
    while (fpclassify(T(fabs(x) - 1)) == FP_ZERO) {
      x = x_sampler.next();
    }

    auto autodiff_v = atan(make_fvar<T, m>(x));
    auto anchor_v = atan(x);
    BOOST_CHECK_CLOSE(autodiff_v.derivative(0u), anchor_v,
                      1e3 * test_constants::pct_epsilon());
  }
}

BOOST_AUTO_TEST_CASE_TEMPLATE(bernoulli_hpp, T, all_float_types) {

  using boost::multiprecision::min;
  using std::min;
  using test_constants = test_constants_t<T>;
  static constexpr auto m = test_constants::order;

  for (auto i : boost::irange(test_constants::n_samples)) {
    {
      auto autodiff_v = boost::math::bernoulli_b2n<autodiff_fvar<T, m>>(i);
      auto anchor_v = boost::math::bernoulli_b2n<T>(i);
      BOOST_CHECK_CLOSE(autodiff_v.derivative(0u), anchor_v,
                        50 * test_constants::pct_epsilon());
    }
    {
      auto i_ = (min)(19, i);
      auto autodiff_v = boost::math::tangent_t2n<autodiff_fvar<T, m>>(i_);
      auto anchor_v = boost::math::tangent_t2n<T>(i_);
      BOOST_CHECK_CLOSE(autodiff_v.derivative(0u), anchor_v,
                        50 * test_constants::pct_epsilon());
    }
  }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: jamesfolberth/math

max_issues_repo_name: jamesfolberth/math

max_forks_repo_name: jamesfolberth/math


text:
#include <execinfo.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

#include <iostream>
#include <stdexcept>
#include <string>

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

#include <QAction>
#include <QApplication>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QMainWindow>
#include <QMenu>

#include <Eigen/Core>

#include <qt_node_editor/connected_edge.h>
#include <qt_node_editor/graph_widget.h>
#include <qt_node_editor/node.h>

#include <dependency_graph/graph.h>
#include <possumwood_sdk/app.h>
#include <possumwood_sdk/gl.h>
#include <dependency_graph/attr.inl>
#include <dependency_graph/datablock.inl>
#include <dependency_graph/metadata.inl>
#include <dependency_graph/node_base.inl>

#include "adaptor.h"
#include "common.h"
#include "error_dialog.h"
#include "gl_init.h"
#include "main_window.h"

namespace po = boost::program_options;

using std::cout;
using std::endl;
using std::flush;

void signalHandler(int sig) {
	void* array[100];
	size_t size;

	size = backtrace(array, 100);

	fprintf(stderr,
	        "\nSIGNAL %d CAUGHT. This is probably an error in the application. Please create an issue at "
	        "https://github.com/martin-pr/possumwood/issues, with steps to reproduce and the following stacktrace:\n",
	        sig);
	backtrace_symbols_fd(array, size, STDERR_FILENO);
	exit(1);
}

int main(int argc, char* argv[]) {
	// // Declare the supported options.
	po::options_description desc("Allowed options");
	desc.add_options()("help", "produce help message")("scene", po::value<std::string>(), "open a scene file");

	// process the options
	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	if(vm.count("help")) {
		cout << desc << "\n";
		return 1;
	}

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

	// install segfault handler
	signal(SIGSEGV, signalHandler);

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

	// create the possumwood application
	std::unique_ptr<possumwood::App> papp(new possumwood::App());
	// load all plugins into an RAII container - loading of plugins requires path expansion from the main app instance
	std::unique_ptr<PluginsRAII> plugins(new PluginsRAII());

	{
		GL_CHECK_ERR;

		{
			QSurfaceFormat format = QSurfaceFormat::defaultFormat();
			// way higher than currently supported - will fall back to highest
			format.setVersion(6, 0);
			format.setProfile(QSurfaceFormat::CoreProfile);

#ifndef NDEBUG
			format.setOption(QSurfaceFormat::DebugContext);
#endif

			format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);

			QSurfaceFormat::setDefaultFormat(format);
		}

		// initialise eigen
		Eigen::initParallel();

		GL_CHECK_ERR;

// nice scaling on High DPI displays is support in Qt 5.6+
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
		QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
		QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif

		GL_CHECK_ERR;

		// create the application object
		QApplication app(argc, argv);

		GL_CHECK_ERR;

		// make a main window
		MainWindow win;
		win.setWindowIcon(QIcon(":icons/app.png"));
		win.showMaximized();

		GL_CHECK_ERR;

		std::cout << "OpenGL version supported by this platform is " << glGetString(GL_VERSION) << std::endl;

		GL_CHECK_ERR;

		// open the scene file, if specified on the command line
		if(vm.count("scene"))
			win.loadFile(vm["scene"].as<std::string>());

		GL_CHECK_ERR;

		// and start the main application loop
		app.exec();

		GL_CHECK_ERR;
	}

	// delete the application before unloading plugins - app will need metadata from plugins to close cleanly
	papp.reset();
	plugins.reset();

	return 0;
}

max_stars_repo_name: martin-pr/possumwood

max_issues_repo_name: martin-pr/possumwood

max_forks_repo_name: martin-pr/possumwood


text:
#include "global.h"
#include "shutdown.h"
#include "RoleFactory.h"
#include "config/constraints.h"
#include "dclass/file/read.h"
#include "dclass/dc/Class.h"
using dclass::Class;

#include <boost/filesystem.hpp>
#include <cstring>
#include <string>  // std::string
#include <vector>  // std::vector
#include <fstream> // std::ifstream
using namespace std;

static LogCategory mainlog("main", "Main");

static ConfigGroup general_config("general");
static ConfigVariable<vector<string> > dc_files("dc_files", vector<string>(), general_config);
static ConfigVariable<string> eventlogger_addr("eventlogger", "", general_config);
static ValidAddressConstraint valid_eventlogger_addr(eventlogger_addr);

static ConfigList uberdogs_config("uberdogs");
static ConfigVariable<doid_t> uberdog_id("id", INVALID_DO_ID, uberdogs_config);
static ConfigVariable<string> uberdog_class("class", "", uberdogs_config);
static ConfigVariable<bool> uberdog_anon("anonymous", false, uberdogs_config);
static InvalidDoidConstraint id_not_invalid(uberdog_id);
static ReservedDoidConstraint id_not_reserved(uberdog_id);
static BooleanValueConstraint anonymous_is_boolean(uberdog_anon);

static void printHelp(ostream &s);
static void printCompiledOptions(ostream &s);

int main(int argc, char *argv[])
{
    string cfg_file;

#ifdef WIN32
    bool prettyPrint = false;
#else
    bool prettyPrint = true;
#endif

    int config_arg_index = -1;
    cfg_file = "astrond.yml";
    LogSeverity sev = g_logger->get_min_severity();
    for(int i = 1; i < argc; i++) {
        if((strcmp(argv[i], "--log") == 0 || strcmp(argv[i], "-L") == 0) && i + 1 < argc) {
            delete g_logger;
            g_logger = new Logger(argv[++i], sev);
        } else if((strcmp(argv[i], "--loglevel") == 0 || strcmp(argv[i], "-l") == 0) && i + 1 < argc) {
            string llstr(argv[++i]);
            if(llstr == "packet") {
                sev = LSEVERITY_PACKET;
                g_logger->set_min_severity(sev);
            } else if(llstr == "trace") {
                sev = LSEVERITY_TRACE;
                g_logger->set_min_severity(sev);
            } else if(llstr == "debug") {
                sev = LSEVERITY_DEBUG;
                g_logger->set_min_severity(sev);
            } else if(llstr == "info") {
                sev = LSEVERITY_INFO;
                g_logger->set_min_severity(sev);
            } else if(llstr == "warning") {
                sev = LSEVERITY_INFO;
                g_logger->set_min_severity(sev);
            } else if(llstr == "security") {
                sev = LSEVERITY_SECURITY;
                g_logger->set_min_severity(sev);
            } else if(llstr != "error" && llstr != "fatal") {
                cerr << "Unknown log-level \"" << llstr << "\"." << endl;
                printHelp(cerr);
                return 1;
            }
        } else if(strcmp(argv[i], "--pretty") == 0 || strcmp(argv[i], "-p") == 0) {
            prettyPrint = true;
        } else if(strcmp(argv[i], "--boring") == 0 || strcmp(argv[i], "-b") == 0) {
            prettyPrint = false;
        } else if(strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
            printHelp(cout);
            return 0;
        } else if(strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-v") == 0) {
            cout << "A Server Technology for Realtime Object Networking (Astron)\n"
                 "http://github.com/astron/astron\n"

#ifdef GIT_SHA1
                 "Revision: " << GIT_SHA1 << "\n"
#else
                 "Revision: NOT-IN-GIT\n"
#endif
                 "Compiled at " << __TIME__ << " on " << __DATE__ << endl;

            printCompiledOptions(cout);

            return 0;
        } else if(argv[i][0] == '-') {
            cerr << "Unrecognized option \"" << string(argv[i]) << "\".\n";
            printHelp(cerr);
            return 1;
        } else {
            if(config_arg_index != -1) {
                cerr << "Recieved additional positional argument \""
                     << string(argv[i]) << "\" but can only accept one."
                     << "\n  First positional: \""
                     << string(argv[config_arg_index]) << "\".\n";
            } else {
                config_arg_index = i;
            }
        }
    }

    g_logger->set_color_enabled(prettyPrint);

    if(config_arg_index != -1) {
        string filename = "";
        cfg_file = argv[config_arg_index];

        try {
            // seperate path
            boost::filesystem::path p(cfg_file);
            boost::filesystem::path dir = p.parent_path();
            filename = p.filename().string();
            string dir_str = dir.string();

            // change directory
            if(!dir_str.empty()) {
                boost::filesystem::current_path(dir_str);
            }
        } catch(const boost::filesystem::filesystem_error&) {
            mainlog.fatal() << "Could not change working directory to config directory.\n";
            return 1;
        }

        cfg_file = filename;
    }

    mainlog.info() << "Loading configuration file...\n";

    ifstream file(cfg_file.c_str());
    if(!file.is_open()) {
        mainlog.fatal() << "Failed to open configuration file \"" << cfg_file << "\".\n";
        return 1;
    }

    if(!g_config->load(file)) {
        mainlog.fatal() << "Errors parsing YAML configuration file \"" << cfg_file << "\"!\n";
        return 1;
    }
    file.close();

    if(!ConfigGroup::root().validate(g_config->copy_node())) {
        mainlog.fatal() << "Configuration file contains errors.\n";
        return 1;
    }

    dclass::File* dcf = new dclass::File();
    dcf->add_keyword("required");
    dcf->add_keyword("ram");
    dcf->add_keyword("db");
    dcf->add_keyword("broadcast");
    dcf->add_keyword("clrecv");
    dcf->add_keyword("clsend");
    dcf->add_keyword("ownsend");
    dcf->add_keyword("ownrecv");
    dcf->add_keyword("airecv");
    vector<string> dc_file_names = dc_files.get_val();
    for(auto it = dc_file_names.begin(); it != dc_file_names.end(); ++it) {
        bool ok = dclass::append(dcf, *it);
        if(!ok) {
            mainlog.fatal() << "Could not read DC file " << *it << endl;
            return 1;
        }
    }
    g_dcf = dcf;

    // Now hook up our speciailize signal handler
    astron_handle_signals();

    try {
        // Initialize configured MessageDirector
        MessageDirector::singleton.init_network();
        g_eventsender.init(eventlogger_addr.get_val());

        // Load uberdog metadata from configuration
        ConfigNode udnodes = g_config->copy_node()["uberdogs"];
        if(!udnodes.IsNull()) {
            for(auto it = udnodes.begin(); it != udnodes.end(); ++it) {
                ConfigNode udnode = *it;
                Uberdog ud;

                // Get the uberdog's class
                const Class* dcc = g_dcf->get_class_by_name(udnode["class"].as<std::string>());
                if(!dcc) {
                    // Make sure it exists
                    mainlog.fatal() << "For uberdog " << udnode["id"].as<doid_t>()
                                    << " Distributed class " << udnode["class"].as<std::string>()
                                    << " does not exist!" << std::endl;
                    return 1;
                }

                // Setup uberdog
                ud.dcc = dcc;
                ud.anonymous = udnode["anonymous"].as<bool>();
                g_uberdogs[udnode["id"].as<doid_t>()] = ud;
            }
        }

        // Initialize configured roles
        ConfigNode node = g_config->copy_node();
        node = node["roles"];
        for(auto it = node.begin(); it != node.end(); ++it) {
            RoleFactory::singleton().instantiate_role((*it)["type"].as<std::string>(), *it);
        }
    }
    // This exception is propogated if astron_shutdown is called
    catch(const ShutdownException& e) {
        return e.exit_code();
    }

    // Run the main event loop
    int exit_code = 0;
    try {
        io_service.run();
    }

    // This exception is propogated if astron_shutdown is called
    catch(const ShutdownException& e) {
        exit_code = e.exit_code();
    }

    // Catch any other exception that propogates
    catch(const exception &e) {
        mainlog.fatal() << "Uncaught exception from the main event loop: "
                        << e.what() << endl;
        return 1;
    }

    return exit_code;
}

// printHelp outputs the cli help-text to the given stream.
void printHelp(ostream &s)
{
    s << "Usage:    astrond [options]... [CONFIG_FILE]\n"
      "\n"
      "Astrond is a distributed server daemon.\n"
      "By default Astron looks for a configuration file in the current\n"
      "working directory as \"astrond.yml\".  A different config file path\n"
      "can be specified as a positional argument.\n"
      "\n"
      "-h, --help      Print this help dialog.\n"
      "-v, --version   Print Version, Module and Compilation Information\n"
      "-L, --log       Specify a file to write log messages to.\n"
      "-p, --pretty    Enables colored pretty printing. \n"
      "-b, --boring    Disables colored pretty printing. \n"
      "-l, --loglevel  Specify the minimum log level that should be logged;\n"
      "                  Security, Error, and Fatal will always be logged;\n"
#ifdef ASTRON_DEBUG_MESSAGES
      "                (available): packet, trace, debug, info, warning, security\n"
#else
      "                (available): info, warning, security\n"
      "                (unavailable): packet, trace, debug\n"
      "                        [build with -DCMAKE_BUILD_TYPE=Debug]\n"
#endif
      "\n"
      "Example:\n"
      "    astrond /tmp/my_config_file.yaml\n"
      "\n";
    s.flush();
}

void printCompiledOptions(ostream &s)
{
    s << "Compilation options: "

      //If on, datagrams and dclass fields will use 32-bit length tags instead of 16-bit.
#ifdef ASTRON_32BIT_DATAGRAMS
      "32-bit length tag Datagrams, "
#else
      "16-bit length tag Datagrams, "
#endif

      //If on, channels will be 128-bit and doids and zones will be 64-bit (instead of 64/32).
#ifdef ASTRON_128BIT_CHANNELS
      "128-bit channel space, 64-bit distributed object id's, 64-bit zones"
#else
      "64-bit channel space, 32-bit distributed object id's, 32-bit zones"
#endif
      << "\n";

    //Now print what parts are compiled in.
    s << "Components: "
#ifdef BUILD_STATESERVER
      "State Server "
#ifdef BUILD_STATESERVER_DBSS
      "(With DBSS capablities)"
#endif //End DBSS
      ", "
#endif //End SS

#ifdef BUILD_EVENTLOGGER
      "Event Logger, "
#endif

#ifdef BUILD_CLIENTAGENT
      "Client Agent, "
#endif

#ifdef BUILD_DBSERVER
      "Database "

#ifdef BUILD_DB_YAML
      "(With YAML Support) "
#endif //End DB_YAML

#ifdef BUILD_DB_SQL
      "(With SQL DB Support) "
#endif //End DB_SQL

#endif //End DBSERVER
      "\n";

}

max_stars_repo_name: Hawkheart/Astron

max_issues_repo_name: Hawkheart/Astron

max_forks_repo_name: Hawkheart/Astron


text:
#include "burger/net/TcpClient.h"
#include "burger/base/Log.h"
#include "burger/net/EventLoopThread.h"
#include "burger/net/IBuffer.h"
#include <boost/noncopyable.hpp>
#include <mutex>
#include <iostream>
#include <string>
// 客户端codec未拆分出来，只是当做个server的测试

using namespace burger;
using namespace burger::net;
using namespace std::placeholders;

class ChatClient : boost::noncopyable {
public:
    ChatClient(EventLoop* loop, const InetAddress& serverAddr)
        : client_(loop, serverAddr, "ChatClient") {
        client_.setConnectionCallback(
            std::bind(&ChatClient::onConnection, this, _1));
        client_.setMessageCallback(
            std::bind(&ChatClient::onMessage, this, _1, _2, _3));
        client_.enableRetry();
    }

    void connect() {
        client_.connect();
    }

    void disconnect() {
        client_.disconnect();
    }

    void write(const std::string& msg) {
        std::lock_guard<std::mutex> lock(mutex_);
        if (connection_) {
            wrapAndSend(connection_, msg);
        }
    }

private:
    void onConnection(const TcpConnectionPtr& conn) {
        std::lock_guard<std::mutex> lock(mutex_);
        if (conn->isConnected()) {
            connection_ = conn;
        } else {
            connection_.reset();
        }
    }

    void onMessage(const TcpConnectionPtr& conn,
                    IBuffer& buf,
                    Timestamp receiveTime) {
        while (buf.getReadableBytes() >= kHeaderLen) {// kHeaderLen == 4
            // FIXME: use Buffer::peekInt32()
            const void* data = buf.peek();
            int32_t be32 = *static_cast<const int32_t*>(data); // SIGBUS
            const int32_t len = sockets::networkToHost32(be32);
            if (len > 65536 || len < 0) {
                ERROR("Invalid length {}", len);
                conn->shutdown();  // FIXME: disable reading
                break;
            } else if (buf.getReadableBytes() >= len + kHeaderLen) {
                buf.retrieve(kHeaderLen);
                std::string message(buf.peek(), len);
                onStringMessage(conn, message, receiveTime);
                buf.retrieve(len);
            } else {
                break;
            }
        }
    }
    void onStringMessage(const TcpConnectionPtr&,
                        const std::string& msg,
                        Timestamp) {
        std::cout << "<<< " << msg << std::endl;
    }

    void wrapAndSend(const TcpConnectionPtr& conn,
                const std::string& msg) {
        Buffer buf;
        buf.append(msg.data(), msg.size());
        int32_t len = static_cast<int32_t>(msg.size());
        int32_t be32 = sockets::hostToNetwork32(len);
        buf.prepend(&be32, sizeof be32);
        conn->send(buf);
    }
private:
    TcpClient client_;
    std::mutex mutex_;
    TcpConnectionPtr connection_;
    const static size_t kHeaderLen = sizeof(int32_t);
};

int main(int argc, char* argv[]) {
    if (argc > 2) {
        EventLoopThread loopThread;
        uint16_t port = static_cast<uint16_t>(atoi(argv[2]));
        InetAddress serverAddr(argv[1], port);

        ChatClient client(loopThread.startLoop(), serverAddr);
        client.connect();
        std::string line;
        while (std::getline(std::cin, line)) {
            client.write(line);
        }
        client.disconnect();
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    } else {
        std::cout << "Usage:" << argv[0] << " host_ip port" << std::endl;
    }
}

max_stars_repo_name: BurgerGroup/Burger

max_issues_repo_name: chanchann/Burger

max_forks_repo_name: chanchann/Burger


text:
/* example for using class array<>
 * (C) Copyright Nicolai M. Josuttis 2001.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */

#include <string>
#include <iostream>
#include <boost/array.hpp>

template <class T>
void print_elements (const T& x);

int main()
{
    // create array of four seasons
    boost::array<std::string,4> seasons = {
        { "spring", "summer", "autumn", "winter" }
    };

    // copy and change order
    boost::array<std::string,4> seasons_orig = seasons;
    for (unsigned i=seasons.size()-1; i>0; --i) {
        std::swap(seasons.at(i),seasons.at((i+1)%seasons.size()));
    }

    std::cout << "one way:   ";
    print_elements(seasons);

    // try swap()
    std::cout << "other way: ";
    std::swap(seasons,seasons_orig);
    print_elements(seasons);

    // try reverse iterators
    std::cout << "reverse:   ";
    for (boost::array<std::string,4>::reverse_iterator pos
           =seasons.rbegin(); pos<seasons.rend(); ++pos) {
        std::cout << " " << *pos;
    }
    std::cout << std::endl;

    return 0;  // makes Visual-C++ compiler happy
}

template <class T>
void print_elements (const T& x)
{
    for (unsigned i=0; i<x.size(); ++i) {
        std::cout << " " << x[i];
    }
    std::cout << std::endl;
}


text:
// (C) Copyright Michael Glassford 2004.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

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

#if defined(BOOST_HAS_WINTHREADS) && defined(BOOST_THREAD_BUILD_DLL)

    #include <boost/thread/detail/tss_hooks.hpp>

    #define WIN32_LEAN_AND_MEAN
    #include <windows.h>

    #if defined(__BORLANDC__)
        extern "C" BOOL WINAPI DllEntryPoint(HINSTANCE /*hInstance*/, DWORD dwReason, LPVOID /*lpReserved*/)
    #elif defined(_WIN32_WCE)
        extern "C" BOOL WINAPI DllMain(HANDLE /*hInstance*/, DWORD dwReason, LPVOID /*lpReserved*/)
    #else
        extern "C" BOOL WINAPI DllMain(HINSTANCE /*hInstance*/, DWORD dwReason, LPVOID /*lpReserved*/)
    #endif
    {
        switch(dwReason)
        {
            case DLL_PROCESS_ATTACH:
            {
                boost::on_process_enter();
                boost::on_thread_enter();
                break;
            }

            case DLL_THREAD_ATTACH:
            {
                boost::on_thread_enter();
                break;
            }

            case DLL_THREAD_DETACH:
            {
                boost::on_thread_exit();
                break;
            }

            case DLL_PROCESS_DETACH:
            {
                boost::on_thread_exit();
                boost::on_process_exit();
                break;
            }
        }

        return TRUE;
    }

namespace boost
{
    void tss_cleanup_implemented()
    {
        /*
        This function's sole purpose is to cause a link error in cases where
        automatic tss cleanup is not implemented by Boost.Threads as a
        reminder that user code is responsible for calling the necessary
        functions at the appropriate times (and for implementing an a
        tss_cleanup_implemented() function to eliminate the linker's
        missing symbol error).

        If Boost.Threads later implements automatic tss cleanup in cases
        where it currently doesn't (which is the plan), the duplicate
        symbol error will warn the user that their custom solution is no
        longer needed and can be removed.
        */
    }
}

#endif //defined(BOOST_HAS_WINTHREADS) && defined(BOOST_THREAD_BUILD_DLL)

max_stars_repo_name: Faham/bric-n-brac

max_issues_repo_name: Faham/bric-n-brac

max_forks_repo_name: Faham/bric-n-brac


text:
// Copyright (c) 2015-2016
// Author: Chrono Law
#ifndef _NGX_WRAPPER_HPP
#define _NGX_WRAPPER_HPP

#include <boost/type_traits.hpp>

//#include "Nginx.hpp"

// T = ngx_list_t, ngx_array_t, ngx_pool_t, ...
template<typename T>
class NgxWrapper
{
public:
    typedef typename boost::remove_pointer<T>::type wrapped_type;

    typedef wrapped_type* pointer_type;
    typedef wrapped_type& reference_type;
private:
    pointer_type m_ptr = nullptr;
protected:
    NgxWrapper(pointer_type p):m_ptr(p)
    {
        //assert(p);
    }

    NgxWrapper(reference_type x):m_ptr(&x)
    {}

    ~NgxWrapper() = default;

public:
    pointer_type get() const
    {
        return m_ptr;
    }

    operator pointer_type () const
    {
        return get();
    }

    pointer_type operator->() const
    {
        return get();
    }
public:
    operator bool () const
    {
        return get();
    }
//public:
//    operator reference_type () const
//    {
//        return *get();
//    }
};

#endif  //_NGX_WRAPPER_HPP

ext: hpp