text:
#include "src/dimacsparser.h"
//#include <boost/lexical_cast.hpp>

#include "sampler.h"
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <unordered_map>
vector<Lit> Sampler::AddVariableDiffHelper(SATSolver *solver2,
                                           map<string, vector<Lit>> &all_vars) {
  size_t len = -1;
  vector<Lit> watches;
  assert(all_vars.size() > 0);
  int nvar = 0;

  for (auto id_lits : all_vars) {
    auto id = id_lits.first;
    auto lits = id_lits.second;
    len = lits.size();
    nvar++;
    if (nvar == 2) {
      break;
    }
  }
  string diff_file = out_dir_ + "//" + out_file_ + ".AddVariableDiffHelperHash";
  std::ofstream finalout(diff_file);
  vector<uint32_t> clause;
  auto new_watch = solver2->nVars() - 1;
  solver2->new_vars(len);
  for (int i = 0; i < len; ++i) {
    clause.clear();
    new_watch++;
    clause.push_back(new_watch);
    watches.push_back(Lit(new_watch, true));
    bool xor_bool = true;
    nvar = 0;
    for (auto id_vars : all_vars) {
      auto id = id_vars.first;
      auto &lits = id_vars.second;
      clause.push_back(lits[i].var());
      if (lits[i].sign())
        xor_bool = !xor_bool;
      nvar++;
      if (nvar == 2) {
        break;
      }
    }
    solver2->add_xor_clause(clause, xor_bool);
    finalout << "x" << (xor_bool ? "" : "-");
    for (auto v : clause)
      finalout << v + 1 << " ";
    finalout << "\n";
  }
  return watches;
}
Lit Sampler::AddVariableSameHelper(SATSolver *solver,
                                   map<string, vector<Lit>> &all_vars) {
  size_t len = 0;
  vector<Lit> clause;
  int nvar = 0;
  for (auto id_lits : all_vars) {
    auto id = id_lits.first;
    auto lits = id_lits.second;
    len = lits.size();
    nvar++;
    if (nvar == 2) {
      break;
    }
  }
  auto same_watch = solver->nVars();
  solver->new_var();
  clause.push_back(Lit(same_watch, false));
  string samefile = out_dir_ + "//" + out_file_ + ".AddVariableSameHelperHash";
  std::ofstream finalout(samefile);
  for (int i = 0; i < len; ++i) {
    vector<uint32_t> clause;
    auto new_watch = solver->nVars();
    solver->new_var();
    clause.push_back(new_watch);
    finalout << Lit(new_watch, true) << " " << Lit(same_watch, true) << "\n";
    solver->add_clause({Lit(new_watch, true), Lit(same_watch, true)});
    bool xor_bool = false;
    nvar = 0;
    for (auto id_vars : all_vars) {
      auto id = id_vars.first;
      auto &lits = id_vars.second;
      clause.push_back(lits[i].var());
      if (lits[i].sign())
        xor_bool = !xor_bool;
      if (lits[i].sign())
        xor_bool = !xor_bool;
      nvar++;
      if (nvar == 2) {
        break;
      }
    }
    solver->add_xor_clause(clause, xor_bool);
    finalout << "x" << (xor_bool ? "" : "-");
    for (auto v : clause)
      finalout << v + 1 << " ";
    finalout << "\n";
  }
  finalout.close();
  return Lit(same_watch, false);
}
void Sampler::AddVariableSameOrDiff(SATSolver *solver,
                                    map<string, vector<Lit>> &all_vars,
                                    map<string, vector<Lit>> diff_vars) {
  int len = -1;
  vector<Lit> watches;
  if (all_vars.size() != 0) {
    watches.push_back(AddVariableSameHelper(solver, all_vars));
  }
  if (diff_vars.size()) {
    auto ws = AddVariableDiffHelper(solver, diff_vars);
    for (auto w : ws) {
      watches.push_back(w);
    }
  }
  solver->add_clause(watches);
}

void Sampler::add_supported_options() {
  Count::add_supported_options();
  add_sample_options();
}
void Sampler::add_sample_options() {
  sampleOptions_.add_options()(
      "noninter", po::value(&sample_noninterference_)->default_value(1),
      "1: strict noninterference,-1: relaxed noninterference; 0 interference "
      "sample");
  sampleOptions_.add_options()("num_cxor_cls",
                               po::value(&num_cxor_cls_)->default_value(0),
                               "num_cxor_cls");
  sampleOptions_.add_options()("num_sxor_cls",
                               po::value(&num_sxor_cls_)->default_value(0),
                               "num_sxor_cls");
  sampleOptions_.add_options()("num_ixor_cls",
                               po::value(&num_ixor_cls_)->default_value(0),
                               "num_ixor_cls");
  sampleOptions_.add_options()("useOtherAlt",
                               po::value(&useOtherAlt)->default_value(false),
                               "useOtherAlt");
  sampleOptions_.add_options()("recordFull",
                               po::value(&record_full_)->default_value(false),
                               "record all variables into full sols");
  help_options_simple.add(sampleOptions_);
  help_options_complicated.add(sampleOptions_);
}
vector<uint32_t> Sampler::GetCIISS() {
  set<uint32_t> sample_vars;
  vector<string> labels = {CONTROLLED_, OTHER_ + "_0", OTHER_ + "_1",
                           SECRET_ + "_0", SECRET_ + "_1"};
  for (auto label : labels)
    for (auto l : symbol_vars[label]) {
      if (!useOtherAlt && label == (OTHER_ + "_1")) {
        continue;
      }
      sample_vars.insert(l.var());
    }
  vector<uint32_t> ret;
  for (auto var : sample_vars) {
    ret.push_back(var);
  }
  return ret;
}
vector<uint32_t> Sampler::GetVars(string label) {
  vector<uint32_t> sample_vars;
  for (auto l : symbol_vars[label]) {
    sample_vars.push_back(l.var());
  }
  return sample_vars;
}
vector<Lit> Sampler::getCISSModelLit(SATSolver *solver) {
  vector<Lit> ret;
  vector<string> labels = {CONTROLLED_, OTHER_ + "_0", SECRET_ + "_0",
                           SECRET_ + "_1",OBSERVABLE_+"_0"};
  auto &model = solver->get_model();
  for (auto label : labels) {
    if (symbol_vars.count(label) == 0)
      continue;
    for (auto l : symbol_vars[label]) {
      ret.push_back(Lit(l.var(), model[l.var()] == l_False));
    }
  }
  return ret;
}

vector<string> Sampler::getCIISSModel(SATSolver *solver) {
  string ret = "";
  std::stringstream ret2;
  vector<string> labels = {CONTROLLED_, OTHER_ + "_0", OTHER_ + "_1",
                           SECRET_ + "_0", SECRET_ + "_1"};
  vector<string> complete_labels = {
      CONTROLLED_,    OTHER_ + "_0",      OTHER_ + "_1",     SECRET_ + "_0",
      SECRET_ + "_1", OBSERVABLE_ + "_0", OBSERVABLE_ + "_1"};
  auto &model = solver->get_model();
  for (auto label : complete_labels) {
    if (symbol_vars.count(label) == 0)
      continue;
    if (!useOtherAlt && label == (OTHER_ + "_1")) {
      continue;
    }
    for (auto l : symbol_vars[label]) {
      ret2 << Lit(l.var(), model[l.var()] == l_False) << ", ";
    }
    ret2 << ", ";
  }
  for (auto label : labels) {
    if (symbol_vars.count(label) == 0) {
      ret += ", ";
      continue;
    }
    if (!useOtherAlt && label == (OTHER_ + "_1")) {
      ret += ", ";
      continue;
    }
    ret += "";
    for (auto l : symbol_vars[label]) {
      if (model[l.var()] == l_Undef || !used_vars.count(l.var()))
        ret += "x";
      else if (model[l.var()] == l_True)
        ret += l.sign() ? "0" : "1";
      else if (model[l.var()] == l_False)
        ret += l.sign() ? "1" : "0";
      ret += ", ";
    }
    ret += ", ";
  }
  return {ret2.str(), ret};
}
void Sampler::RecordSampleSol(vector<string> &sol) {

  if (!record_solution_)
    return;

  if (record_full_)
    *sample_sol_complete_f << sol[0] << endl;
  *sample_sol_f << sol[1] << endl;
}

void Sampler::RecordSampleSolSame(vector<string> &sol) {
  if (!record_solution_)
    return;
  if (record_full_)
    *sample_sol_complete_f_same << sol[0] << endl;
  *sample_sol_f_same << sol[1] << endl;
}
int64_t Sampler::bounded_sol_generation(SATSolver *solver,
                                        vector<uint32_t> &target_count_vars,
                                        uint32_t maxSolutions,
                                        const vector<Lit> &assumps) {

  vector<lbool> model;
  lbool ret;
  int solutions = 0, total_sol = 0;
  bool only_ind = true;
  vector<Lit> new_assumps(assumps);
  solver->new_var();
  struct timeval t0=now();
  uint32_t act_var = solver->nVars() - 1;
  new_assumps.push_back(Lit(act_var, true));
  if (new_assumps.size() > 1)
    solver->simplify(&new_assumps);
  while (solutions < maxSolutions) {
    ret = solver->solve(&new_assumps, only_ind);
    assert(ret == l_False || ret == l_True);
    if (conf.verbosity >= 2) {
      cout << "[appmc] bounded_sol_count ret: " << std::setw(7) << ret;
      if (ret == l_True) {
        cout << " sol no.  " << std::setw(3) << solutions;
      } else {
        cout << " No more. " << std::setw(3) << "";
      }
    }
    if (ret != l_True) {
      break;
    }
    solutions++;
    total_sol++;
    if (solutions < maxSolutions) {
      vector<Lit> lits, solution;
      for (const uint32_t var : target_count_vars) {
        if (solver->get_model()[var] != l_Undef && used_vars.count(var)) {
          lits.push_back(Lit(var, solver->get_model()[var] == l_True));
        }
      }

      auto cissmodel = getCIISSModel(solver);
      lits.push_back(Lit(act_var, false));
      solver->add_clause(lits);
      if (complementary_solver) {
        if (!useOtherAlt) {
          vector<Lit> sol_lits = getCISSModelLit(solver);
          if (complementary_solver->solve(&sol_lits) == l_True) {
            // not actual leakage
            RecordSampleSolSame(cissmodel);
            // std::cout<<"complementary_solver->solve(&sol_lits) == l_True\n";
            solutions--;
            if (total_sol > 20 * maxSolutions && duration(t0)>120) {
              break;
            }
            continue;
          }
        }
      }
      RecordSampleSol(cissmodel);
    }
  }
  // Remove clauses added
  solver->add_clause({Lit(act_var, false)});
  nESolver = total_sol;
  return solutions;
}

void Sampler::run() {
  solver = new SATSolver(&conf);
  solver = newCounterSolver(solver, (void *)&conf);
  inputfile = filesToRead[0];
  readInAFileToCache(solver, inputfile);
  setSecretVars();
  setCountVars();
  if (sample_noninterference_ > 0) {
    AddVariableSame(solver, all_observe_lits);
    AddVariableSame(solver, all_declass_lits);
    sample_sol_f = new std::ofstream(out_dir_ + "//" + out_file_ + ".same.csv",
                                     std::ofstream::out | std::ofstream::app);
    if (record_full_)
      sample_sol_complete_f =
          new std::ofstream(out_dir_ + "//" + out_file_ + ".same_complete.csv",
                            std::ofstream::out | std::ofstream::app);

  } else if (sample_noninterference_ < 0) {
    // sample relaxed noninterference;
    if (all_declass_lits.size() == 0)
      return;
    AddVariableDiff(solver, all_declass_lits);
    complementary_solver =
        new SATSolver(&conf); //;= newCounterSolver(&s2, (void *)&conf);
    complementary_solver =
        newCounterSolver(complementary_solver, (void *)&conf);
    readInAFile(complementary_solver, inputfile);
    AddVariableSame(complementary_solver, all_declass_lits);
    sample_sol_f = new std::ofstream(out_dir_ + "//" + out_file_ + ".same.csv",
                                     std::ofstream::out | std::ofstream::app);
    if (record_full_)
      sample_sol_complete_f =
          new std::ofstream(out_dir_ + "//" + out_file_ + ".same_complete.csv",
                            std::ofstream::out | std::ofstream::app);

  } else {
    // sample interferenceSet
    // SATSolver s2(&conf);
    complementary_solver =
        new SATSolver(&conf); //;= newCounterSolver(&s2, (void *)&conf);
    complementary_solver =
        newCounterSolver(complementary_solver, (void *)&conf);

    readInAFile(complementary_solver, inputfile);
    // AddVariableSameOrDiff(complementary_solver, all_observe_lits,
    //                    all_declass_lits);
    AddVariableSame(complementary_solver, all_observe_lits);
    AddVariableDiff(solver, all_observe_lits);
    sample_sol_f = new std::ofstream(out_dir_ + "//" + out_file_ + ".diff.csv",
                                     std::ofstream::out | std::ofstream::app);
    if (record_full_)
      sample_sol_complete_f =
          new std::ofstream(out_dir_ + "//" + out_file_ + ".diff_complete.csv",
                            std::ofstream::out | std::ofstream::app);
    sample_sol_f_same =
        new std::ofstream(out_dir_ + "//" + out_file_ + ".same.csv",
                          std::ofstream::out | std::ofstream::app);
    if (record_full_)
      sample_sol_complete_f_same =
          new std::ofstream(out_dir_ + "//" + out_file_ + ".same_complete.csv",
                            std::ofstream::out | std::ofstream::app);
    AddVariableSame(solver, all_declass_lits);
  }
  AddVariableDiff(solver, all_secret_lits);

  vector<uint32_t> CISS = GetCIISS();
  solver->set_sampling_vars(&CISS);
  // solver->simplify();
  vector<Lit> ciss_assump, c_assump, s_assump, salt_assump, i_assump,
      ialt_assump;
  vector<vector<uint32_t>> ciss_added_vars, c_added_vars, s_added_vars,
      salt_added_vars, i_added_vars, ialt_added_vars;
  vector<bool> ciss_rhs, c_rhs, s_rhs, salt_rhs, i_rhs, ialt_rhs;
  std::cout << "used_vars.size()=" << used_vars.size() << std::endl;
  int left = 0, right = CISS.size(), hash_count;
  if (num_xor_cls_ > 0) {
    hash_count = num_xor_cls_;
  } else
    hash_count = right - 10;
  nTotalSolutions = 0;
  perf = 0;
  start = now();
  for (int t = 0; t < nsample; ++t) {
    ciss_assump.clear();
    ciss_added_vars.clear();
    ciss_rhs.clear();
    c_added_vars.clear();
    s_added_vars.clear();
    salt_added_vars.clear();
    salt_added_vars.clear();
    i_added_vars.clear();
    ialt_added_vars.clear();
    c_rhs.clear();
    s_rhs.clear();
    salt_rhs.clear();
    i_rhs.clear();
    ialt_rhs.clear();
    c_assump.clear();
    s_assump.clear();
    salt_assump.clear();
    i_assump.clear();
    ialt_assump.clear();
    if (hash_count > 0)
      Count::Sample(solver, CISS, hash_count, ciss_assump, ciss_added_vars,
                    ciss_rhs, lit_Undef);
    if (num_cxor_cls_ > 0)
      Count::Sample(solver, GetVars(CONTROLLED_), num_cxor_cls_, c_assump,
                    c_added_vars, c_rhs, lit_Undef);
    if (num_sxor_cls_ > 0) {
      Count::Sample(solver, GetVars(SECRET_ + "_0"), num_sxor_cls_, s_assump,
                    s_added_vars, s_rhs, lit_Undef);
      Count::Sample(solver, GetVars(SECRET_ + "_1"), num_sxor_cls_, salt_assump,
                    salt_added_vars, salt_rhs, lit_Undef);
    }
    if (num_ixor_cls_ > 0) {
      Count::Sample(solver, GetVars(OTHER_ + "_0"), num_ixor_cls_, i_assump,
                    i_added_vars, i_rhs, lit_Undef);
      if (useOtherAlt)
        Count::Sample(solver, GetVars(OTHER_ + "_1"), num_ixor_cls_,
                      ialt_assump, ialt_added_vars, ialt_rhs, lit_Undef);
    }
    ciss_assump.insert(ciss_assump.end(), c_assump.begin(), c_assump.end());
    ciss_assump.insert(ciss_assump.end(), s_assump.begin(), s_assump.end());
    ciss_assump.insert(ciss_assump.end(), salt_assump.begin(),
                       salt_assump.end());
    ciss_assump.insert(ciss_assump.end(), i_assump.begin(), i_assump.end());
    ciss_assump.insert(ciss_assump.end(), ialt_assump.begin(),
                       ialt_assump.end());
    string victim_cnf_file = out_dir_ + "//" + out_file_ + ".sol.simp";
    std::ofstream finalout(victim_cnf_file);
    solver->dump_irred_clauses_ind_only(&finalout);
    // trimVar(solver,sample_vars);
    solver->simplify();
    auto nsol = bounded_sol_generation(solver, CISS, max_sol_, ciss_assump);
    double du = duration(start);
    perf = du / (nTotalSolutions + nsol);
    nTotalSolutions += nsol;
    cout << "sampling_rate:\t" << perf << "\t second per sol" << std::endl;
    cout << hash_count << "nsol=" << nsol << std::endl;

    if (nsol >= max_sol_ || nESolver >= (max_sol_ * 20)) {
      left = hash_count + 1;
      hash_count = (left + right) / 2;
    } else if (nsol == 0) {
      right = hash_count - 1;
      hash_count = (left + right) / 2;
    } else if (nsol < max_sol_ * 0.4) {
      hash_count = hash_count - floor(log2(max_sol_ / nsol)) + 1;
      left = hash_count;
      right = hash_count;
    } else {
      left = hash_count;
      right = hash_count;
    }
  }
}

int main(int argc, char **argv) {
  srand(time(NULL));
  Sampler sampler(argc, argv);
  // Count.conf.doRenumberVars = true;
  sampler.parseCommandLine();
  sampler.run();
}


text:
#include <ros/ros.h>
#include <tf2_ros/transform_broadcaster.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/NavSatFix.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/PointCloud2.h>
#include <geometry_msgs/PointStamped.h>
#include <Eigen/Dense>

//TODO: this might be better off in a util class / module

#define D2R(x) ((M_PI*x)/180.0)

void geo2ecef(Eigen::Vector3d & positionECEF, double latitude, double longitude, double ellipsoidalHeight) {
	/**WGS84 ellipsoid semi-major axis*/
	double a = 6378137.0;

	/**WGS84 ellipsoid first eccentricity squared*/
	double e2 = 0.081819190842622 * 0.081819190842622;

	double slat = sin(D2R(latitude));
	double clat = cos(D2R(latitude));
	double slon = sin(D2R(longitude));
	double clon = cos(D2R(longitude));

	double N = a / (sqrt(1 - e2 * slat * slat));
	double xTRF = (N + ellipsoidalHeight) * clat * clon;
	double yTRF = (N + ellipsoidalHeight) * clat * slon;
	double zTRF = (N * (1 - e2) + ellipsoidalHeight) * slat;

	positionECEF << xTRF, yTRF, zTRF;
};

class GeoreferenceProvider{
public:
	GeoreferenceProvider(): ecefLocalOrigin(0,0,0){
                odomPublisher=n.advertise<nav_msgs::Odometry>("odom", 50);

		depthRepublisher = n.advertise<geometry_msgs::PointStamped>("depth_ned",50);

                gpsSubscriber = n.subscribe("fix", 50, &GeoreferenceProvider::processGpsCallback,this);
                //attitudeSubscriber = n.subscribe("/imu/pos_ecef", 50, &GeoreferenceProvider::processPositionCallback,this);
		attitudeSubscriber = n.subscribe("/imu/data", 50, &GeoreferenceProvider::processAttitudeCallback,this);
		lidarSubscriber = n.subscribe("/velodyne_points",100,&GeoreferenceProvider::processLidarCallback,this);
		depthSubscriber = n.subscribe("/depth",100,&GeoreferenceProvider::processDepthCallback,this);

	}

	void processGpsCallback(const sensor_msgs::NavSatFix & msg){

		//Init ENU frame origin once we receive a first fix
		if(!gpsFixObtained && msg.status.status >= 0){
			gpsFixObtained = true;
			latitudeLocalOrigin = msg.latitude;
			longitudeLocalOrigin = msg.longitude;
			altitudeLocalOrigin = msg.altitude;

			ROS_INFO("GPS Fix obtained. Initializing NED transform at (%f,%f,%f)",latitudeLocalOrigin,longitudeLocalOrigin,altitudeLocalOrigin);

			geo2ecef(ecefLocalOrigin,latitudeLocalOrigin,longitudeLocalOrigin,altitudeLocalOrigin);

			ROS_INFO_STREAM("Local Origin:" << ecefLocalOrigin);

			//ENU
			//ecef2local << 	-sin(D2R(longitudeLocalOrigin)),	cos(D2R(longitudeLocalOrigin)),	0,
			//		-sin(D2R(latitudeLocalOrigin))*cos(D2R(longitudeLocalOrigin)), -sin(D2R(latitudeLocalOrigin))*sin(D2R(longitudeLocalOrigin)), cos(D2R(latitudeLocalOrigin)),
			//		cos(D2R(latitudeLocalOrigin))*cos(D2R(longitudeLocalOrigin)),cos(D2R(latitudeLocalOrigin))*sin(D2R(longitudeLocalOrigin)),sin(D2R(latitudeLocalOrigin));

			//NED
			ecef2local <<	-sin(D2R(latitudeLocalOrigin)) * cos(D2R(longitudeLocalOrigin)), -sin(D2R(latitudeLocalOrigin))*sin(D2R(longitudeLocalOrigin)),cos(D2R(latitudeLocalOrigin)),
				   	-sin(D2R(longitudeLocalOrigin)) , cos(D2R(longitudeLocalOrigin)), 0,
					-cos(D2R(latitudeLocalOrigin))*cos(D2R(longitudeLocalOrigin)), -cos(D2R(latitudeLocalOrigin))*sin(D2R(longitudeLocalOrigin)), -sin(D2R(latitudeLocalOrigin)) ;

			//ROS_INFO_STREAM("DCM:" << ecef2local);
		}
		else if(gpsFixObtained){
			processPosition(msg);
		}
	}

	void processAttitudeCallback(const sensor_msgs::Imu & msg){
		lastAttitude = msg;
	}

	void processLidarCallback(const sensor_msgs::PointCloud2 & msg){
		//std::cout << "Got lidar data" << std::endl;
	}

	void processDepthCallback(const geometry_msgs::PointStamped & msg){
		//FIXME: this is solved in the imagenex driver but not in the rosbag so we need to republish to NED frame
		geometry_msgs::PointStamped newMsg = msg;
		newMsg.point.z=-1 * msg.point.z;
		depthRepublisher.publish(newMsg);
	}

	/* Publish the odometry transform and Odometry message */
	void publishOdometry(Eigen::Vector3d & prpPointLocal){

		/* Broadcast the base_link to map transform */
                geometry_msgs::TransformStamped map_transform;
                map_transform.header.stamp = ros::Time::now(); //msg.header.stamp;
                map_transform.header.frame_id = "map"; //FIXME: we are assuming that the prp is the base_link origin
                map_transform.child_frame_id = "base_link";

                map_transform.transform.translation.x = prpPointLocal[0];
                map_transform.transform.translation.y = prpPointLocal[1];
                map_transform.transform.translation.z = prpPointLocal[2];
                map_transform.transform.rotation = lastAttitude.orientation;

                transformBroadcaster.sendTransform(map_transform);

                /* Publish the odometry message over ROS */
                nav_msgs::Odometry odom;
                odom.header.stamp = ros::Time::now();//msg.header.stamp;
                odom.header.frame_id = "odom";

                //set the position
                odom.pose.pose.position.x = prpPointLocal[0];
                odom.pose.pose.position.y = prpPointLocal[1];
                odom.pose.pose.position.z = prpPointLocal[2];

		//TODO: compensate attitude value using delta t, since our last attitude value dates from a little while back
                odom.pose.pose.orientation = lastAttitude.orientation;

                //set the velocity
                odom.child_frame_id = "base_link";
                //odom.twist.twist.linear.x = vx;
                //odom.twist.twist.linear.y = vy;
                //odom.twist.twist.angular.z = vth;

                //publish the message
                odomPublisher.publish(odom);
	}

	void processPosition(const sensor_msgs::NavSatFix & msg){
		if(gpsFixObtained){
			lastPosition = msg;

			//transform to ENU
			Eigen::Vector3d pointEcef;

			geo2ecef(pointEcef,msg.latitude,msg.longitude,msg.altitude);

			Eigen::Vector3d pointLocal = ecef2local * (pointEcef - ecefLocalOrigin);

			//Update odometry
			publishOdometry(pointLocal);
		}
	}

	void run(){
		ros::Rate r(10.0);

		//just spin...
		while(n.ok()){
			ros::spinOnce();
			r.sleep();
		}
	}

private:
	ros::NodeHandle n;
        ros::Publisher  odomPublisher;

	ros::Publisher  depthRepublisher;//FIXME: delete this

        ros::Subscriber gpsSubscriber;

        ros::Subscriber positionSubscriber;
	ros::Subscriber attitudeSubscriber;
	ros::Subscriber lidarSubscriber;
	ros::Subscriber depthSubscriber;

        tf2_ros::TransformBroadcaster transformBroadcaster;

	//These are used to georeference
	sensor_msgs::Imu 	lastAttitude;
	sensor_msgs::NavSatFix  lastPosition;

	bool gpsFixObtained = false;

	//This DCM is used to transform ECEF coordinates into a local NED frame centered at ecefEnuOrigin
	Eigen::Matrix3d	ecef2local;

	//The NED origin is set as the first position when a proper GPS fix is obtained
	Eigen::Vector3d ecefLocalOrigin;

	//NED origin in geodesic coordinates
	double latitudeLocalOrigin;
	double longitudeLocalOrigin;
	double altitudeLocalOrigin;
};

int main(int argc, char** argv){
  ros::init(argc, argv, "odometry_publisher");

  GeoreferenceProvider georefProvider;

  georefProvider.run();
}

ext: cpp

max_stars_repo_name: glabmoris/Poseidon

max_issues_repo_name: glabmoris/Poseidon

max_forks_repo_name: glabmoris/Poseidon


text:
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <iostream>
#include <cstdio>

#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/interprocess_condition.hpp>

struct trace_queue
{
   enum { LineSize = 100 };

   trace_queue()
      :  message_in(false)
   {}

   //Mutex to protect access to the queue
   boost::interprocess::interprocess_mutex      mutex;

   //Condition to wait when the queue is empty
   boost::interprocess::interprocess_condition  cond_empty;

   //Condition to wait when the queue is full
   boost::interprocess::interprocess_condition  cond_full;

   //Items to fill
   char   items[LineSize];

   //Is there any message
   bool message_in;
};

using namespace boost::interprocess;

int main ()
{

   //Erase previous shared memory
   shared_memory_object::remove("shared_memory");

   //Create a shared memory object.
   shared_memory_object shm
      (create_only               //only create
      ,"shared_memory"           //name
      ,read_write                //read-write mode
      );
   try{
      //Set size
      shm.truncate(sizeof(trace_queue));

      //Map the whole shared memory in this process
      mapped_region region
         (shm                       //What to map
         ,read_write //Map it as read-write
         );

      //Get the address of the mapped region
      void * addr       = region.get_address();

      //Construct the shared structure in memory
      trace_queue * data = new (addr) trace_queue;

      const int NumMsg = 10000000;

      for(int i = 0; i < NumMsg; ++i){
         scoped_lock<interprocess_mutex> lock(data->mutex);
         if(data->message_in){
            data->cond_full.wait(lock);
         }
         if(i == (NumMsg-1))
            std::sprintf(data->items, "%s", "last message");
         else
            std::sprintf(data->items, "%s_%d", "my_trace", i);

         //Notify to the other process that there is a message
         data->cond_empty.notify_one();

         //Mark message buffer as full
         data->message_in = true;
      }
   }
   catch(interprocess_exception &ex){
      shared_memory_object::remove("shared_memory");
      std::cout << ex.what() << std::endl;
      return 1;
   }

   //Erase shared memory
   shared_memory_object::remove("shared_memory");
   return 0;
}

max_stars_repo_name: cicerone/kosim

max_issues_repo_name: cicerone/kosim

max_forks_repo_name: cicerone/kosim


text:
////////////////////////////////////////////////////////////////////////////////
///
/// \file Error.hpp
/// ---------------
///
/// Copyright (c) 2017. Microblink Ltd. All rights reserved.
///
////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
#pragma once

#include <LogAndTimer/Log.hpp>
#include <Utils/disable_warnings.hpp>

#include <boost/assert.hpp>
#include <boost/core/ignore_unused.hpp>
MB_DISABLE_WARNING_PUSH
MB_DISABLE_WARNING_GCC( "-Wattributes" )
#include <boost/err/result_or_error.hpp>
MB_DISABLE_WARNING_POP

#ifndef NDEBUG
#include <exception>
#endif // NDEBUG
#include <string>
//------------------------------------------------------------------------------
namespace pping
{
//------------------------------------------------------------------------------

#if defined( NDEBUG ) || defined( PLATFORM_IOS ) || ( defined( __ANDROID__ ) && defined( __arm__ ) ) || defined( BOOST_NO_EXCEPTIONS )
    enum struct Failure : std::uint8_t { Failed };
#else
    using Failure = std::exception_ptr;
#endif // NDEBUG

template <typename Result>
using Fallible = boost::err::result_or_error
<
    Result,
    Failure
>;

template <typename T> class Ref;

template <typename Result>
using FallibleRef = Fallible<Ref<Result>>;

/// Returns a generic failure or the current exception (depending on the build
/// configuration).
inline Failure failure() noexcept
{
#if defined( NDEBUG ) || defined( PLATFORM_IOS ) || ( defined( __ANDROID__ ) && defined( __arm__ ) ) || defined( BOOST_NO_EXCEPTIONS )
    return Failure::Failed;
#else
    BOOST_ASSERT( std::current_exception() );
    return std::current_exception();
#endif // NDEBUG
}

template <typename Exception, typename ... Args>
Failure failure( Args ... args ) noexcept
{
#if defined( NDEBUG ) || defined( PLATFORM_IOS ) || ( defined( __ANDROID__ ) && defined( __arm__ ) ) || defined( BOOST_NO_EXCEPTIONS )
    boost::ignore_unused( args... );
    return Failure::Failed;
#else
    return std::make_exception_ptr( Exception( args...) );
#endif // NDEBUG
}

inline boost::err::no_err_t success() noexcept { return boost::err::no_err; }

inline void logError( Failure const & failure ) noexcept
{
#if defined( NDEBUG ) || defined( PLATFORM_IOS ) || ( defined( __ANDROID__ ) && defined( __arm__ ) ) || defined( BOOST_NO_EXCEPTIONS )
    boost::ignore_unused( failure );
    LOGD( "ZXing failure" );
#else
    try { std::rethrow_exception( failure ); }
    catch (std::exception const & e) { LOGD("ZXing failure: %s", e.what()); }
    catch (...)                      { LOGD("ZXing failure"); }
#endif // NDEBUG
}

/// Temporary utility macro for placing before throw expressions to cause a
/// break when the throw would happen - for easier prioritizing which throw
/// statements to eliminate first.
#define MB_ZXING_BREAK_ON_EXCEPTION() BOOST_ASSERT( !"Exception thrown in ZXing code" );

struct DisambiguationWrapper { Failure result; operator Failure && () && { return std::move( result ); } };

//------------------------------------------------------------------------------
} // namespace pping
//------------------------------------------------------------------------------

ext: hpp

max_stars_repo_name: microblink/zxing

max_issues_repo_name: microblink/zxing

max_forks_repo_name: microblink/zxing


text:
#ifndef MODELOBJECT_HPP_
#define MODELOBJECT_HPP_

/*
 * Copyright (c) 2014 Joost Kraaijeveld. See license.txt for details.
 * For information, bug reports and additions send an e-mail to RobotWorld@Askesis.nl.
 *
 * Author: jkr
 */

#include "Config.hpp"

#include <iostream>
#include <memory>
#include <string>
#include <boost/noncopyable.hpp>

#include "Notifier.hpp"
#include "ObjectId.hpp"

namespace Model
{
	class ModelObject;
	typedef std::shared_ptr<ModelObject> ModelObjectPtr;

	/**
	 *
	 */
	class ModelObject : public boost::noncopyable,
						public Base::Notifier,
						public std::enable_shared_from_this<ModelObject>
	{
		public:
			/**
			 * @name Constructors and destructor
			 */
			//@{
			/**
			 *
			 */
			ModelObject();
			/**
			 *
			 */
			virtual ~ModelObject();
			//@}
			/**
			 * @name Operators
			 */
			//@{
			/**
			 * Equal to operator which compares the objectIds
			 *
			 * @param aModelObject
			 * @return true if objectIds are the same, false otherwise
			 */
			bool operator==( const ModelObject& aModelObject) const
			{
				return objectId == aModelObject.objectId;
			}
			/**
			 * Less than operator which compares the objectIds
			 *
			 * @param aModelObject
			 * @return true if lhs.objectId is less than rhs.objectId, false otherwise
			 */
			bool operator<( const ModelObject& aModelObject) const
			{
				return objectId < aModelObject.objectId;
			}
			//@}
			/**
			 *
			 * @return the objectId (identity) of the ModelObject
			 */
			const Base::ObjectId& getObjectId() const {return  objectId;}
			/**
			 * Converts the contained ModelObject to a std::shared_ptr<DestinationType>
			 *
			 * @return std::shared_ptr<DestinationType>
			 */
			template< typename DestinationType>
			std::shared_ptr<DestinationType> toPtr()
			{
				return std::dynamic_pointer_cast<DestinationType>(shared_from_this());
			}
			/**
			 * @name Debug functions
			 */
			//@{
			/**
			 * Returns a 1-line description of the object
			 */
			virtual std::string asString() const;
			/**
			 * Returns a description of the object with all data of the object usable for debugging
			 */
			virtual std::string asDebugString() const;
			//@}
		protected:

		private:
			Base::ObjectId objectId;
	};
} // namespace Model
#endif // MODELOBJECT_HPP_

max_stars_repo_name: TheKevDev/robotworld

max_issues_repo_name: TheKevDev/robotworld

max_forks_repo_name: TheKevDev/robotworld


text:
/*
 * BSD 2-Clause License
 *
 * Copyright (c) 2020, Christoph Neuhauser
 * 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.
 *
 * 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 <fstream>
#include <algorithm>
#include <random>
#include <chrono>
#include <cmath>

#include <boost/algorithm/string/predicate.hpp>
#include <glm/glm.hpp>

#include <Utils/Events/Stream/Stream.hpp>
#include <Utils/File/Logfile.hpp>
#include <Utils/Convert.hpp>
#include <Utils/SciVis/ImportanceCriteria.hpp>
#include <Graphics/Shader/ShaderManager.hpp>
#include <Graphics/Shader/ShaderAttributes.hpp>
#include <Graphics/Renderer.hpp>

#include "MeshSerializer.hpp"

using namespace std;
using namespace sgl;

const uint32_t MESH_FORMAT_VERSION = 4u;

void writeMesh3D(const std::string &filename, const BinaryMesh &mesh) {
#ifndef __MINGW32__
    std::ofstream file(filename.c_str(), std::ofstream::binary);
    if (!file.is_open()) {
        Logfile::get()->writeError(std::string() + "Error in writeMesh3D: File \"" + filename + "\" not found.");
        return;
    }
 #else
    FILE *fileptr = fopen(filename.c_str(), "wb");
    if (fileptr == NULL) {
        Logfile::get()->writeError(std::string() + "Error in writeMesh3D: File \"" + filename + "\" not found.");
        return;
    }
 #endif

    sgl::BinaryWriteStream stream;
    stream.write((uint32_t)MESH_FORMAT_VERSION);
    stream.write((uint32_t)mesh.submeshes.size());

    for (const BinarySubMesh &submesh : mesh.submeshes) {
        stream.write(submesh.material);
        stream.write((uint32_t)submesh.vertexMode);
        stream.writeArray(submesh.indices);

        // Write attributes
        stream.write((uint32_t)submesh.attributes.size());
        for (const BinaryMeshAttribute &attribute : submesh.attributes) {
            stream.write(attribute.name);
            stream.write((uint32_t)attribute.attributeFormat);
            stream.write((uint32_t)attribute.numComponents);
            stream.writeArray(attribute.data);
        }

        // Write uniforms
        stream.write((uint32_t)submesh.uniforms.size());
        for (const BinaryMeshUniform &uniform : submesh.uniforms) {
            stream.write(uniform.name);
            stream.write((uint32_t)uniform.attributeFormat);
            stream.write((uint32_t)uniform.numComponents);
            stream.writeArray(uniform.data);
        }
    }

#ifndef __MINGW32__
    file.write((const char*)stream.getBuffer(), stream.getSize());
    file.close();
#else
    fwrite((const void*)stream.getBuffer(), stream.getSize(), 1, fileptr);
    fclose(fileptr);
#endif
}

void readMesh3D(const std::string &filename, BinaryMesh &mesh) {
#ifndef __MINGW32__
    std::ifstream file(filename.c_str(), std::ifstream::binary);
    if (!file.is_open()) {
        Logfile::get()->writeError(std::string() + "Error in readMesh3D: File \"" + filename + "\" not found.");
        return;
    }

    file.seekg(0, file.end);
    size_t size = file.tellg();
    file.seekg(0);
    char *buffer = new char[size];
    file.read(buffer, size);
    file.close();
#else
    /*
     * Using MinGW-w64, the code above doesn't work, as streamsize == ptrdiff_t == __PTRDIFF_TYPE__ == long int
     * is only 32-bits long, and thus is is faulty for large files > 2GiB.
     */
    FILE *fileptr = fopen(filename.c_str(), "rb");
    if (fileptr == NULL) {
        Logfile::get()->writeError(std::string() + "Error in readMesh3D: File \"" + filename + "\" not found.");
        return;
    }
    fseeko64(fileptr, 0L, SEEK_END);
    size_t size = ftello64 (fileptr);
    fseeko64(fileptr, 0L, SEEK_SET);
    char *buffer = new char[size];
    fseek(fileptr, 0L, SEEK_SET);
    uint64_t readSize = fread(buffer, 1, size, fileptr);
    assert(size == readSize);
    fclose(fileptr);
#endif

    sgl::BinaryReadStream stream(buffer, size);
    uint32_t version;
    stream.read(version);
    if (version != MESH_FORMAT_VERSION) {
        Logfile::get()->writeError(std::string() + "Error in readMesh3D: Invalid version in file \""
                + filename + "\".");
        return;
    }

    uint32_t numSubmeshes;
    stream.read(numSubmeshes);
    mesh.submeshes.resize(numSubmeshes);

    for (uint32_t i = 0; i < numSubmeshes; i++) {
        BinarySubMesh &submesh = mesh.submeshes.at(i);
        stream.read(submesh.material);
        uint32_t vertexMode;
        stream.read(vertexMode);
        submesh.vertexMode = (sgl::VertexMode)vertexMode;
        stream.readArray(mesh.submeshes.at(i).indices);

        // Read attributes
        uint32_t numAttributes;
        stream.read(numAttributes);
        submesh.attributes.resize(numAttributes);

        for (uint32_t j = 0; j < numAttributes; j++) {
            BinaryMeshAttribute &attribute = submesh.attributes.at(j);
            stream.read(attribute.name);
            uint32_t format;
            stream.read(format);
            attribute.attributeFormat = (sgl::VertexAttributeFormat)format;
            stream.read(attribute.numComponents);
            stream.readArray(attribute.data);
        }

        // Read uniforms
        uint32_t numUniforms;
        stream.read(numUniforms);
        submesh.uniforms.resize(numUniforms);

        for (uint32_t j = 0; j < numUniforms; j++) {
            BinaryMeshUniform &uniform = submesh.uniforms.at(j);
            stream.read(uniform.name);
            uint32_t format;
            stream.read(format);
            uniform.attributeFormat = (sgl::VertexAttributeFormat)format;
            stream.read(uniform.numComponents);
            stream.readArray(uniform.data);
        }
    }

    //delete[] buffer; // BinaryReadStream does deallocation
}

void MeshRenderer::render(sgl::ShaderProgramPtr passShader, bool isGBufferPass, int attributeIndex) {
    if (useProgrammableFetch) {
        for (SSBOEntry &ssboEntry : ssboEntries) {
            if (ssboEntry.bindingPoint >= 0 && (!boost::starts_with(ssboEntry.attributeName, "vertexAttribute")
                    || attributeIndex == sgl::fromString<int>(ssboEntry.attributeName.substr(15)))) {
                sgl::ShaderManager->bindShaderStorageBuffer(ssboEntry.bindingPoint, ssboEntry.attributeBuffer);
            }
        }
    }

    for (size_t i = 0; i < shaderAttributes.size(); i++) {
        //ShaderProgram *shader = shaderAttributes.at(i)->getShaderProgram();
        if (!boost::starts_with(passShader->getShaderList().front()->getFileID(), "PseudoPhongVorticity")
                && !boost::starts_with(passShader->getShaderList().front()->getFileID(), "DepthPeelingGatherDepthComplexity")
                && !isGBufferPass) {
            if (passShader->hasUniform("ambientColor")) {
                passShader->setUniform("ambientColor", materials.at(i).ambientColor);
            }
            if (passShader->hasUniform("diffuseColor")) {
                passShader->setUniform("diffuseColor", materials.at(i).diffuseColor);
            }
            if (passShader->hasUniform("specularColor")) {
                passShader->setUniform("specularColor", materials.at(i).specularColor);
            }
            if (passShader->hasUniform("specularExponent")) {
                passShader->setUniform("specularExponent", materials.at(i).specularExponent);
            }
            if (passShader->hasUniform("opacity")) {
                passShader->setUniform("opacity", materials.at(i).opacity);
            }
        }
        Renderer->render(shaderAttributes.at(i), passShader);
    }
}

void MeshRenderer::setNewShader(sgl::ShaderProgramPtr newShader) {
    for (size_t i = 0; i < shaderAttributes.size(); i++) {
        shaderAttributes.at(i) = shaderAttributes.at(i)->copy(newShader, false);
    }
}

sgl::AABB3 computeAABB(const std::vector<glm::vec3> &vertices) {
    if (vertices.size() < 1) {
        Logfile::get()->writeError("computeAABB: vertices.size() < 1");
        return sgl::AABB3();
    }

    glm::vec3 minV = glm::vec3(FLT_MAX, FLT_MAX, FLT_MAX);
    glm::vec3 maxV = glm::vec3(-FLT_MAX, -FLT_MAX, -FLT_MAX);
    for (const glm::vec3 &pt : vertices) {
        minV.x = std::min(minV.x, pt.x);
        minV.y = std::min(minV.y, pt.y);
        minV.z = std::min(minV.z, pt.z);
        maxV.x = std::max(maxV.x, pt.x);
        maxV.y = std::max(maxV.y, pt.y);
        maxV.z = std::max(maxV.z, pt.z);
    }

    return sgl::AABB3(minV, maxV);
}

std::vector<uint32_t> shuffleIndicesLines(const std::vector<uint32_t> &indices) {
    size_t numSegments = indices.size() / 2;
    std::vector<size_t> shuffleOffsets;
    for (size_t i = 0; i < numSegments; i++) {
        shuffleOffsets.push_back(i);
    }
    auto rng = std::default_random_engine{};
    rng.seed(std::chrono::system_clock::now().time_since_epoch().count());
    std::shuffle(std::begin(shuffleOffsets), std::end(shuffleOffsets), rng);

    std::vector<uint32_t> shuffledIndices;
    shuffledIndices.reserve(numSegments*2);
    for (size_t i = 0; i < numSegments; i++) {
        size_t lineIndex = shuffleOffsets.at(i);
        shuffledIndices.push_back(indices.at(lineIndex*2));
        shuffledIndices.push_back(indices.at(lineIndex*2+1));
    }

    return shuffledIndices;
}

std::vector<uint32_t> shuffleLineOrder(const std::vector<uint32_t> &indices) {
    size_t numSegments = indices.size() / 2;

    // 1. Compute list of all lines
    std::vector<std::vector<uint32_t>> lines;
    std::vector<uint32_t> currentLine;
    for (size_t i = 0; i < numSegments; i++) {
        uint32_t idx0 = indices.at(i*2);
        uint32_t idx1 = indices.at(i*2+1);

        // Start new line?
        if (i > 0 && idx0 != indices.at((i-1)*2+1)) {
            lines.push_back(currentLine);
            currentLine.clear();
        }

        // Add indices to line
        currentLine.push_back(idx0);
        currentLine.push_back(idx1);
    }
    if (currentLine.size() > 0) {
        lines.push_back(currentLine);
    }

    // 2. Shuffle line list
    auto rng = std::default_random_engine{};
    rng.seed(std::chrono::system_clock::now().time_since_epoch().count());
    std::shuffle(std::begin(lines), std::end(lines), rng);

    // 3. Reconstruct line list from shuffled lines
    std::vector<uint32_t> shuffledIndices;
    shuffledIndices.reserve(indices.size());
    for (const std::vector<uint32_t> &line : lines) {
        for (uint32_t idx : line) {
            shuffledIndices.push_back(idx);
        }
    }

    return shuffledIndices;
}

std::vector<uint32_t> shuffleIndicesTriangles(const std::vector<uint32_t> &indices) {
    size_t numSegments = indices.size() / 3;
    std::vector<size_t> shuffleOffsets;
    for (size_t i = 0; i < numSegments; i++) {
        shuffleOffsets.push_back(i);
    }
    auto rng = std::default_random_engine{};
    rng.seed(std::chrono::system_clock::now().time_since_epoch().count());
    std::shuffle(std::begin(shuffleOffsets), std::end(shuffleOffsets), rng);

    std::vector<uint32_t> shuffledIndices;
    shuffledIndices.reserve(numSegments*3);
    for (size_t i = 0; i < numSegments; i++) {
        size_t lineIndex = shuffleOffsets.at(i);
        shuffledIndices.push_back(indices.at(lineIndex*3));
        shuffledIndices.push_back(indices.at(lineIndex*3+1));
        shuffledIndices.push_back(indices.at(lineIndex*3+2));
    }

    return shuffledIndices;
}

struct LinePointData
{
    glm::vec3 vertexPosition;
    float vertexAttribute;
    glm::vec3 vertexTangent;
    float padding;
};

MeshRenderer parseMesh3d(const std::string &filename, sgl::ShaderProgramPtr shader, bool shuffleData,
        bool useProgrammableFetch, bool programmableFetchUseAoS, float lineRadius) {
    MeshRenderer meshRenderer(useProgrammableFetch);
    BinaryMesh mesh;
    readMesh3D(filename, mesh);

    if (!shader) {
        shader = ShaderManager->getShaderProgram({"PseudoPhong.Vertex", "PseudoPhong.Fragment"});
    }

    std::vector<sgl::ShaderAttributesPtr> &shaderAttributes = meshRenderer.shaderAttributes;
    std::vector<ObjMaterial> &materials = meshRenderer.materials;
    shaderAttributes.reserve(mesh.submeshes.size());
    materials.reserve(mesh.submeshes.size());

    // Bounding box of all submeshes combined
    AABB3 totalBoundingBox(glm::vec3(FLT_MAX, FLT_MAX, FLT_MAX), glm::vec3(-FLT_MAX, -FLT_MAX, -FLT_MAX));

    // Importance criterion attributes are bound to location 3 and onwards in vertex shader
    //int importanceCriterionLocationCounter = 3;

    // Iterate over all submeshes and create rendering data
    for (size_t i = 0; i < mesh.submeshes.size(); i++) {
        BinarySubMesh &submesh = mesh.submeshes.at(i);
        ShaderAttributesPtr renderData = ShaderManager->createShaderAttributes(shader);
        if (!useProgrammableFetch) {
            renderData->setVertexMode(submesh.vertexMode);
        } else {
            renderData->setVertexMode(VERTEX_MODE_TRIANGLES);
        }

        if (submesh.indices.size() > 0 && !useProgrammableFetch) {
            if (shuffleData && (submesh.vertexMode == VERTEX_MODE_LINES || submesh.vertexMode == VERTEX_MODE_TRIANGLES)) {
                std::vector<uint32_t> shuffledIndices;
                if (submesh.vertexMode == VERTEX_MODE_LINES) {
                    //shuffledIndices = shuffleIndicesLines(submesh.indices);
                    shuffledIndices = shuffleLineOrder(submesh.indices);
                } else if (submesh.vertexMode == VERTEX_MODE_TRIANGLES) {
                    shuffledIndices = shuffleIndicesTriangles(submesh.indices);
                } else {
                    Logfile::get()->writeError("ERROR in parseMesh3D: shuffleData and unsupported vertex mode!");
                    shuffledIndices = submesh.indices;
                }
                GeometryBufferPtr indexBuffer = Renderer->createGeometryBuffer(
                        sizeof(uint32_t)*shuffledIndices.size(), shuffledIndices.data(), INDEX_BUFFER);
                renderData->setIndexGeometryBuffer(indexBuffer, ATTRIB_UNSIGNED_INT);
            } else {
                GeometryBufferPtr indexBuffer = Renderer->createGeometryBuffer(
                        sizeof(uint32_t)*submesh.indices.size(), submesh.indices.data(), INDEX_BUFFER);
                renderData->setIndexGeometryBuffer(indexBuffer, ATTRIB_UNSIGNED_INT);
            }
        }
        if (submesh.indices.size() > 0 && useProgrammableFetch) {
            // Modify indices
            std::vector<uint32_t> fetchIndices;
            fetchIndices.reserve(submesh.indices.size()*3);
            // Iterate over all line segments
            for (size_t i = 0; i < submesh.indices.size(); i += 2) {
                uint32_t base0 = submesh.indices.at(i)*2;
                uint32_t base1 = submesh.indices.at(i+1)*2;
                // 0,2,3,0,3,1
                fetchIndices.push_back(base0);
                fetchIndices.push_back(base1);
                fetchIndices.push_back(base1+1);
                fetchIndices.push_back(base0);
                fetchIndices.push_back(base1+1);
                fetchIndices.push_back(base0+1);
            }
            GeometryBufferPtr indexBuffer = Renderer->createGeometryBuffer(
                    sizeof(uint32_t)*fetchIndices.size(), fetchIndices.data(), INDEX_BUFFER);
            renderData->setIndexGeometryBuffer(indexBuffer, ATTRIB_UNSIGNED_INT);
        }

        // For programmableFetchUseAoS
        std::vector<glm::vec3> vertexPositionData;
        std::vector<std::vector<float>> vertexAttributeData;
        std::vector<glm::vec3> vertexTangentData;

        for (size_t j = 0; j < submesh.attributes.size(); j++) {
            BinaryMeshAttribute &meshAttribute = submesh.attributes.at(j);
            GeometryBufferPtr attributeBuffer;

            // Assume only one component means importance criterion like vorticity, line width, ...
            if (meshAttribute.numComponents == 1) {
                ImportanceCriterionAttribute importanceCriterionAttribute;
                importanceCriterionAttribute.name = meshAttribute.name;

                // Copy values to mesh renderer data structure
                uint16_t *attributeValuesUnorm = (uint16_t*)meshAttribute.data.data();
                size_t numAttributeValues = meshAttribute.data.size() / sizeof(uint16_t);
                unpackUnorm16Array(attributeValuesUnorm, numAttributeValues, importanceCriterionAttribute.attributes);

                // Compute minimum and maximum value
                float minValue = FLT_MAX, maxValue = 0.0f;
#if _OPENMP >= 201107
                #pragma omp parallel for reduction(min:minValue) reduction(max:maxValue)
#endif
                for (size_t k = 0; k < numAttributeValues; k++) {
                    minValue = std::min(minValue, importanceCriterionAttribute.attributes[k]);
                    maxValue = std::max(maxValue, importanceCriterionAttribute.attributes[k]);
                }
                importanceCriterionAttribute.minAttribute = minValue;
                importanceCriterionAttribute.maxAttribute = maxValue;

                meshRenderer.importanceCriterionAttributes.push_back(importanceCriterionAttribute);

                // SSBOs can't directly perform process uint16_t -> float :(
                if (useProgrammableFetch && !programmableFetchUseAoS) {
                    attributeBuffer = Renderer->createGeometryBuffer(
                            numAttributeValues*sizeof(float), importanceCriterionAttribute.attributes.data(),
                            SHADER_STORAGE_BUFFER);
                } else if (useProgrammableFetch) {
                    int attributeIndex = sgl::fromString<int>(meshAttribute.name.substr(15));
                    if (attributeIndex >= vertexAttributeData.size()) {
                        vertexAttributeData.resize(attributeIndex+1);
                    }
                    vertexAttributeData.at(attributeIndex).resize(numAttributeValues);
                    for (size_t k = 0; k < numAttributeValues; k++) {
                        vertexAttributeData.at(attributeIndex).at(k) = importanceCriterionAttribute.attributes[k];
                    }
                }
            }

            BufferType bufferType = useProgrammableFetch ? SHADER_STORAGE_BUFFER : VERTEX_BUFFER;

            if (!(useProgrammableFetch && programmableFetchUseAoS)
                && !(meshAttribute.numComponents == 1 && useProgrammableFetch)
                && !(meshAttribute.numComponents == 3 && useProgrammableFetch)) {
                attributeBuffer = Renderer->createGeometryBuffer(
                        meshAttribute.data.size(), meshAttribute.data.data(), bufferType);
            }
            if (meshAttribute.numComponents == 3 && (useProgrammableFetch && !programmableFetchUseAoS)) {
                // vec3 problematic in std430 struct
                glm::vec3 *attributeValues = (glm::vec3*)meshAttribute.data.data();
                size_t numAttributeValues = meshAttribute.data.size() / sizeof(glm::vec3);
                std::vector<glm::vec4> vec4AttributeValues;
                vec4AttributeValues.reserve(numAttributeValues);
                for (size_t i = 0; i < numAttributeValues; i++) {
                    glm::vec3 vec3Value = attributeValues[i];
                    vec4AttributeValues.push_back(glm::vec4(vec3Value.x, vec3Value.y, vec3Value.z, 1.0f));
                }
                attributeBuffer = Renderer->createGeometryBuffer(
                        vec4AttributeValues.size()*sizeof(glm::vec4), vec4AttributeValues.data(), bufferType);
            }

            if (!useProgrammableFetch) {
                if (meshAttribute.numComponents == 1) {
                    // Importance criterion attributes are bound to location 3 and onwards in vertex shader
                    renderData->addGeometryBufferOptional(
                            attributeBuffer, meshAttribute.name.c_str(), meshAttribute.attributeFormat,
                            meshAttribute.numComponents, 0, 0, 0, ATTRIB_CONVERSION_FLOAT_NORMALIZED);
                } else {
                    bool isNormalizedColor = (meshAttribute.name == "vertexColor");
                    renderData->addGeometryBufferOptional(
                            attributeBuffer, meshAttribute.name.c_str(), meshAttribute.attributeFormat,
                            meshAttribute.numComponents, 0, 0, 0,
                            isNormalizedColor ? ATTRIB_CONVERSION_FLOAT_NORMALIZED : ATTRIB_CONVERSION_FLOAT);
                }
                meshRenderer.shaderAttributeNames.insert(meshAttribute.name);
            } else {
                if (programmableFetchUseAoS) {
                    if (meshAttribute.name == "vertexPosition") {
                        glm::vec3 *attributeValues = (glm::vec3*)meshAttribute.data.data();
                        size_t numAttributeValues = meshAttribute.data.size() / sizeof(glm::vec3);
                        vertexPositionData.reserve(numAttributeValues);
                        for (size_t i = 0; i < numAttributeValues; i++) {
                            vertexPositionData.push_back(attributeValues[i]);
                        }
                    } else if (meshAttribute.name == "vertexLineTangent") {
                        glm::vec3 *attributeValues = (glm::vec3*)meshAttribute.data.data();
                        size_t numAttributeValues = meshAttribute.data.size() / sizeof(glm::vec3);
                        vertexTangentData.reserve(numAttributeValues);
                        for (size_t i = 0; i < numAttributeValues; i++) {
                            vertexTangentData.push_back(attributeValues[i]);
                        }
                    }
                } else {
                    int bindingPoint = -1;
                    if (meshAttribute.name == "vertexPosition") {
                        bindingPoint = 2;
                    } else if (meshAttribute.name == "vertexLineTangent") {
                        bindingPoint = 3;
                    } else if (boost::starts_with(meshAttribute.name, "vertexAttribute")) {
                        bindingPoint = 4;
                    }
                    meshRenderer.ssboEntries.push_back(SSBOEntry(bindingPoint, meshAttribute.name, attributeBuffer));
                }
            }

            if (meshAttribute.name == "vertexPosition") {
                std::vector<glm::vec3> vertices;
                vertices.resize(meshAttribute.data.size() / sizeof(glm::vec3));
                memcpy(vertices.data(), meshAttribute.data.data(), meshAttribute.data.size());
                totalBoundingBox.combine(computeAABB(vertices));
            }
        }

        if (useProgrammableFetch && programmableFetchUseAoS) {
            for (size_t attributeIndex = 0; attributeIndex < vertexAttributeData.size(); attributeIndex++) {
                std::vector<LinePointData> linePointData;
                linePointData.resize(vertexPositionData.size());

                for (size_t i = 0; i < vertexPositionData.size(); i++) {
                    linePointData.at(i).vertexPosition = vertexPositionData.at(i);
                    linePointData.at(i).vertexAttribute = vertexAttributeData.at(attributeIndex).at(i);
                    linePointData.at(i).vertexTangent = vertexTangentData.at(i);
                    linePointData.at(i).padding = 0.0f;
                }

                GeometryBufferPtr attributeBuffer = Renderer->createGeometryBuffer(
                        linePointData.size()*sizeof(LinePointData), linePointData.data(),
                        SHADER_STORAGE_BUFFER);
                meshRenderer.ssboEntries.push_back(SSBOEntry(2, "vertexAttribute" + sgl::toString(attributeIndex),
                        attributeBuffer));
            }
        }

        shaderAttributes.push_back(renderData);
        materials.push_back(mesh.submeshes.at(i).material);
    }

    meshRenderer.boundingBox = totalBoundingBox;
    meshRenderer.boundingSphere = sgl::Sphere(totalBoundingBox.getCenter(), glm::length(totalBoundingBox.getExtent()));

    return meshRenderer;
}

max_stars_repo_name: chrismile/LineVis

max_issues_repo_name: chrismile/LineVis

max_forks_repo_name: chrismile/LineVis


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

#include <amqpprox_backendselector.h>
#include <amqpprox_backendselectorstore.h>
#include <amqpprox_backendstore.h>
#include <amqpprox_farm.h>
#include <amqpprox_farmstore.h>
#include <amqpprox_logging.h>
#include <amqpprox_partitionpolicy.h>
#include <amqpprox_partitionpolicystore.h>

#include <sstream>
#include <string>

#include <boost/algorithm/string.hpp>

namespace Bloomberg {
namespace amqpprox {

FarmControlCommand::FarmControlCommand(
    FarmStore *           store,
    BackendStore *        backendStore,
    BackendSelectorStore *backendSelectorStore,
    PartitionPolicyStore *partitionPolicyStore)
: d_store_p(store)
, d_backendStore_p(backendStore)
, d_backendSelectorStore_p(backendSelectorStore)
, d_partitionPolicyStore_p(partitionPolicyStore)
{
}

std::string FarmControlCommand::commandVerb() const
{
    return "FARM";
}

std::string FarmControlCommand::helpText() const
{
    return "("
           "ADD name selector backend* | "
           "PARTITION name policy | "
           "DELETE name | "
           "PRINT"
           ") - Change farms";
}

void FarmControlCommand::handleCommand(const std::string & /* command */,
                                       const std::string &  restOfCommand,
                                       const OutputFunctor &outputFunctor,
                                       Server * /* serverHandle */,
                                       Control * /* controlHandle */)
{
    ControlCommandOutput<OutputFunctor> output(outputFunctor);

    std::istringstream iss(restOfCommand);
    std::string        subcommand;
    iss >> subcommand;
    boost::to_upper(subcommand);

    if (subcommand == "ADD_MANUAL" || subcommand == "ADD") {
        std::string              name;
        std::string              backendSelector;
        std::vector<std::string> backends;
        iss >> name;
        iss >> backendSelector;

        if (!iss.good() || name.empty() || backendSelector.empty()) {
            output << "Farm name and selector must be provided.\n";
            return;
        }

        BackendSelector *selector =
            d_backendSelectorStore_p->getSelector(backendSelector);
        if (selector == nullptr) {
            output << "Selector '" << backendSelector << "' not found\n";
            return;
        }

        bool allBackendsOk = true;
        while (iss.good() && !iss.eof()) {
            std::string backendName;
            iss >> backendName;

            auto backend = d_backendStore_p->lookup(backendName);
            if (!backend) {
                allBackendsOk = false;
                output << "Backend '" << backendName << "' not found\n";
            }

            backends.emplace_back(backendName);
        }

        if (allBackendsOk) {
            std::unique_ptr<Farm> farmPtr(
                new Farm(name, backends, d_backendStore_p, selector));
            d_store_p->addFarm(std::move(farmPtr));
        }
        else {
            output
                << "Farm not inserted due to at least one missing Backend\n";
        }
    }
    else if (subcommand == "PARTITION") {
        std::string name;
        std::string partitionPolicy;
        iss >> name;
        iss >> partitionPolicy;

        if (name.empty() || partitionPolicy.empty()) {
            output << "Farm name and policy must be provided.\n";
            return;
        }

        PartitionPolicy *policy =
            d_partitionPolicyStore_p->getPolicy(partitionPolicy);
        if (policy == nullptr) {
            output << "Partition policy '" << partitionPolicy
                   << "' not found\n";
            return;
        }

        try {
            Farm &farm = d_store_p->getFarmByName(name);
            farm.addPartitionPolicy(policy);
        }
        catch (std::runtime_error &e) {
            output << "Farm '" << name << "' not found\n";
            return;
        }
    }
    else if (subcommand == "DELETE") {
        std::string name;
        iss >> name;
        if (name.empty()) {
            output << "Farm name not provided.";
        }
        else {
            d_store_p->removeFarmByName(name);
        }
    }
    else if (subcommand == "PRINT") {
        std::ostringstream oss;
        d_store_p->print(output);
    }
    else {
        output << "Subcommand '" << subcommand << "' not recognized.";
    }
}

}
}


text:
#ifndef PY_OPENGM_HDF5
#define PY_OPENGM_HDF5

#define PY_ARRAY_UNIQUE_SYMBOL PyArrayHandleHdf5

#ifndef OPENGM_PYTHON_INTERFACE
#define OPENGM_PYTHON_INTERFACE 1
#endif

#ifdef WITH_HDF5
#include <stdexcept>
#include <stddef.h>
#include <boost/python.hpp>
#include <opengm/graphicalmodel/graphicalmodel.hxx>
#include <opengm/graphicalmodel/graphicalmodel_hdf5.hxx>
#include "../export_typedes.hxx"

using namespace boost::python;

template<class GM>
void export_hdf5() {

   typedef GM PyGm;
    // export stuff in the hdf5 namespace
    //bp::class_<Util::String>("String");
    // etc.

   //------------------------------------------------------------------------------------
   // function to do hdf5 io
   //------------------------------------------------------------------------------------
   def("saveGraphicalModel",
      opengm::hdf5::save<PyGm>,
      (
      arg("gm"),
      arg("file"),
      arg("dataset")
      ),
      "saveGraphicalModel"
      );
   def("loadGraphicalModel",
      opengm::hdf5::load<PyGm>,
      (
      arg("gm"),
      arg("file"),
      arg("dataset")
      ),
      "loadGraphicalModel"
      );
}

template void export_hdf5<GmAdder>();

#endif //WITH_HDF5

#endif

ext: cxx

max_stars_repo_name: amueller/opengm

max_issues_repo_name: amueller/opengm

max_forks_repo_name: amueller/opengm


text:
// -----------------------------------------------------------------------------
// Copyright (c) 2015-2018 Benjamin Buch
//
// https://github.com/bebuch/mitrax
//
// 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)
// -----------------------------------------------------------------------------
#define BOOST_TEST_MODULE mitrax flat_iterator
#include <boost/test/unit_test.hpp>
#include <boost/mpl/list.hpp>

#include <mitrax/range/value_view_range.hpp>
#include <mitrax/range/value_factory_range.hpp>

#include <complex>
#include <iostream>

using namespace mitrax;

template < typename T >
auto rt_id(T&& v){
	return boost::typeindex::type_id_runtime(static_cast< T&& >(v));
}

template < typename T >
auto const id = boost::typeindex::type_id< T >();

BOOST_AUTO_TEST_SUITE(suite_range)

using types = boost::mpl::list< int, double, std::complex< float > >;

BOOST_AUTO_TEST_CASE_TEMPLATE(test_value_view_range, T, types){
	constexpr auto range = make_value_view_range(T(4));

	static_assert(is_range_v< decltype(range) >);

	BOOST_TEST((range[0] == T(4)));
}

BOOST_AUTO_TEST_CASE_TEMPLATE(test_value_factory_range, T, types){
	constexpr auto range = make_value_factory_range< T >(std::make_tuple(4));

	static_assert(is_range_v< decltype(range) >);

	BOOST_TEST((range[0] == T(4)));
}

BOOST_AUTO_TEST_CASE(test_value_factory_range_complex){
	constexpr auto range = make_value_factory_range< std::complex< float > >
		(std::make_tuple(4, 6));

	static_assert(is_range_v< decltype(range) >);

	BOOST_TEST((range[0] == std::complex< float >(4, 6)));
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: bebuch/Mitrax

max_issues_repo_name: bebuch/Mitrax

max_forks_repo_name: bebuch/Mitrax


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2015 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2015 Mateusz Loskot, London, UK.
// Copyright (c) 2013-2015 Adam Wulkiewicz, Lodz, Poland

// This file was modified by Oracle on 2013, 2014, 2015, 2017, 2018, 2019.
// Modifications copyright (c) 2013-2019, Oracle and/or its affiliates.

// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// Use, modification and distribution is 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)

#ifndef BOOST_GEOMETRY_STRATEGY_CARTESIAN_POINT_IN_POINT_HPP
#define BOOST_GEOMETRY_STRATEGY_CARTESIAN_POINT_IN_POINT_HPP

#include <cstddef>

#include <boost/geometry/core/access.hpp>
#include <boost/geometry/core/coordinate_dimension.hpp>
#include <boost/geometry/core/tags.hpp>

#include <boost/geometry/util/math.hpp>

#include <boost/geometry/strategies/covered_by.hpp>
#include <boost/geometry/strategies/within.hpp>

namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace within
{

template <std::size_t Dimension, std::size_t DimensionCount>
struct point_point_generic
{
    template <typename Point1, typename Point2>
    static inline bool apply(Point1 const& p1, Point2 const& p2)
    {
        if (! geometry::math::equals(get<Dimension>(p1), get<Dimension>(p2)))
        {
            return false;
        }
        return
            point_point_generic<Dimension + 1, DimensionCount>::apply(p1, p2);
    }
};

template <std::size_t DimensionCount>
struct point_point_generic<DimensionCount, DimensionCount>
{
    template <typename Point1, typename Point2>
    static inline bool apply(Point1 const&, Point2 const& )
    {
        return true;
    }
};

}} // namespace detail::within
#endif // DOXYGEN_NO_DETAIL

namespace strategy { namespace within
{

struct cartesian_point_point
{
    typedef cartesian_tag cs_tag;

    template <typename Point1, typename Point2>
    static inline bool apply(Point1 const& point1, Point2 const& point2)
    {
        return geometry::detail::within::point_point_generic
            <
                0, dimension<Point1>::type::value
            >::apply(point1, point2);
    }
};

#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS
namespace services
{

template <typename PointLike1, typename PointLike2, typename Tag1, typename Tag2>
struct default_strategy<PointLike1, PointLike2, Tag1, Tag2, pointlike_tag, pointlike_tag, cartesian_tag, cartesian_tag>
{
    typedef strategy::within::cartesian_point_point type;
};

} // namespace services
#endif

}} // namespace strategy::within

#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS
namespace strategy { namespace covered_by { namespace services
{

template <typename PointLike1, typename PointLike2, typename Tag1, typename Tag2>
struct default_strategy<PointLike1, PointLike2, Tag1, Tag2, pointlike_tag, pointlike_tag, cartesian_tag, cartesian_tag>
{
    typedef strategy::within::cartesian_point_point type;
};

}}} // namespace strategy::covered_by::services
#endif

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_STRATEGY_CARTESIAN_POINT_IN_POINT_HPP

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
/*******************************************************************************
 * Copyright (c) 2018-, UT-Battelle, LLC.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the MIT License
 * which accompanies this distribution.
 *
 * Contributors:
 *   Alexander J. McCaskey - initial API and implementation
 *   Thien Nguyen - implementation
 *******************************************************************************/
#include "clifford_gate_utils.hpp"
#include <Eigen/Dense>
#include <cassert>
#include <cmath>
#include <set>

namespace {
double mod_2pi(double theta) {
  while (theta > M_PI or theta <= -M_PI) {
    if (theta > M_PI) {
      theta = theta - 2 * M_PI;
    } else if (theta <= -M_PI) {
      theta = theta + 2 * M_PI;
    }
  }
  assert(theta >= -M_PI && theta <= M_PI);
  return theta;
}
} // namespace
namespace qcor {
namespace utils {
GenRot_t computeRotationInPauliFrame(const GenRot_t &in_rot,
                                     PauliLabel in_newPauli,
                                     PauliLabel in_netPauli) {
  auto [theta1, theta2, theta3] = in_rot;

  theta1 = mod_2pi(theta1);
  theta2 = mod_2pi(theta2);
  theta3 = mod_2pi(theta3);
  if (in_netPauli == PauliLabel::X || in_netPauli == PauliLabel::Z) {
    theta2 *= -1.0;
  }
  if (in_netPauli == PauliLabel::X || in_netPauli == PauliLabel::Y) {
    theta3 *= -1.0;
    theta1 *= -1.0;
  }

  // if x or y
  if (in_newPauli == PauliLabel::X || in_newPauli == PauliLabel::Y) {
    theta1 = -theta1 + M_PI;
    theta2 = theta2 + M_PI;
  }
  // if y or z
  if (in_newPauli == PauliLabel::Y || in_newPauli == PauliLabel::Z) {
    theta1 = theta1 + M_PI;
  }

  // make everything between - pi and pi
  theta1 = mod_2pi(theta1);
  theta2 = mod_2pi(theta2);
  theta3 = mod_2pi(theta3);
  return std::make_tuple(theta1, theta2, theta3);
}

GenRot_t invU3Gate(const GenRot_t &in_rot) {
  auto [theta1, theta2, theta3] = in_rot;
  theta1 = mod_2pi(M_PI - theta1);
  theta2 = mod_2pi(-theta2);
  theta3 = mod_2pi(-theta3 + M_PI);
  return std::make_tuple(theta1, theta2, theta3);
}

SrepDict_t computeGateSymplecticRepresentations(
    const std::vector<std::string> &in_gateList) {
  static const SrepDict_t standardDict = []() {
    std::unordered_map<std::string, Smatrix_t> complete_s_dict;
    std::unordered_map<std::string, Pvec_t> complete_p_dict;

    // The Pauli gates
    complete_s_dict["I"] = std::vector<std::vector<int>>{{1, 0}, {0, 1}};
    complete_s_dict["X"] = std::vector<std::vector<int>>{{1, 0}, {0, 1}};
    complete_s_dict["Y"] = std::vector<std::vector<int>>{{1, 0}, {0, 1}};
    complete_s_dict["Z"] = std::vector<std::vector<int>>{{1, 0}, {0, 1}};

    complete_p_dict["I"] = std::vector<int>{0, 0};
    complete_p_dict["X"] = std::vector<int>{0, 2};
    complete_p_dict["Y"] = std::vector<int>{2, 2};
    complete_p_dict["Z"] = std::vector<int>{2, 0};

    // Five single qubit gates that each represent one of five classes of
    // Cliffords that equivalent up to Pauli gates and are not equivalent to
    // idle (that class is covered by any one of the Pauli gates above).
    complete_s_dict["H"] = std::vector<std::vector<int>>{{0, 1}, {1, 0}};
    complete_s_dict["P"] = std::vector<std::vector<int>>{{1, 0}, {1, 1}};
    complete_s_dict["PH"] = std::vector<std::vector<int>>{{0, 1}, {1, 1}};
    complete_s_dict["HP"] = std::vector<std::vector<int>>{{1, 1}, {1, 0}};
    complete_s_dict["HPH"] = std::vector<std::vector<int>>{{1, 1}, {0, 1}};
    complete_p_dict["H"] = std::vector<int>{0, 0};
    complete_p_dict["P"] = std::vector<int>{1, 0};
    complete_p_dict["PH"] = std::vector<int>{0, 1};
    complete_p_dict["HP"] = std::vector<int>{3, 0};
    complete_p_dict["HPH"] = std::vector<int>{0, 3};
    // The full 1-qubit Cliffor group, using the same labelling as in
    // extras.rb.group
    complete_s_dict["C0"] = std::vector<std::vector<int>>{{1, 0}, {0, 1}};
    complete_p_dict["C0"] = std::vector<int>{0, 0};
    complete_s_dict["C1"] = std::vector<std::vector<int>>{{1, 1}, {1, 0}};
    complete_p_dict["C1"] = std::vector<int>{1, 0};
    complete_s_dict["C2"] = std::vector<std::vector<int>>{{0, 1}, {1, 1}};
    complete_p_dict["C2"] = std::vector<int>{0, 1};
    complete_s_dict["C3"] = std::vector<std::vector<int>>{{1, 0}, {0, 1}};
    complete_p_dict["C3"] = std::vector<int>{0, 2};
    complete_s_dict["C4"] = std::vector<std::vector<int>>{{1, 1}, {1, 0}};
    complete_p_dict["C4"] = std::vector<int>{1, 2};
    complete_s_dict["C5"] = std::vector<std::vector<int>>{{0, 1}, {1, 1}};
    complete_p_dict["C5"] = std::vector<int>{0, 3};
    complete_s_dict["C6"] = std::vector<std::vector<int>>{{1, 0}, {0, 1}};
    complete_p_dict["C6"] = std::vector<int>{2, 2};
    complete_s_dict["C7"] = std::vector<std::vector<int>>{{1, 1}, {1, 0}};
    complete_p_dict["C7"] = std::vector<int>{3, 2};
    complete_s_dict["C8"] = std::vector<std::vector<int>>{{0, 1}, {1, 1}};
    complete_p_dict["C8"] = std::vector<int>{2, 3};
    complete_s_dict["C9"] = std::vector<std::vector<int>>{{1, 0}, {0, 1}};
    complete_p_dict["C9"] = std::vector<int>{2, 0};
    complete_s_dict["C10"] = std::vector<std::vector<int>>{{1, 1}, {1, 0}};
    complete_p_dict["C10"] = std::vector<int>{3, 0};
    complete_s_dict["C11"] = std::vector<std::vector<int>>{{0, 1}, {1, 1}};
    complete_p_dict["C11"] = std::vector<int>{2, 1};
    complete_s_dict["C12"] = std::vector<std::vector<int>>{{0, 1}, {1, 0}};
    complete_p_dict["C12"] = std::vector<int>{0, 0};
    complete_s_dict["C13"] = std::vector<std::vector<int>>{{1, 1}, {0, 1}};
    complete_p_dict["C13"] = std::vector<int>{0, 1};
    complete_s_dict["C14"] = std::vector<std::vector<int>>{{1, 0}, {1, 1}};
    complete_p_dict["C14"] = std::vector<int>{1, 0};
    complete_s_dict["C15"] = std::vector<std::vector<int>>{{0, 1}, {1, 0}};
    complete_p_dict["C15"] = std::vector<int>{0, 2};
    complete_s_dict["C16"] = std::vector<std::vector<int>>{{1, 1}, {0, 1}};
    complete_p_dict["C16"] = std::vector<int>{0, 3};
    complete_s_dict["C17"] = std::vector<std::vector<int>>{{1, 0}, {1, 1}};
    complete_p_dict["C17"] = std::vector<int>{1, 2};
    complete_s_dict["C18"] = std::vector<std::vector<int>>{{0, 1}, {1, 0}};
    complete_p_dict["C18"] = std::vector<int>{2, 2};
    complete_s_dict["C19"] = std::vector<std::vector<int>>{{1, 1}, {0, 1}};
    complete_p_dict["C19"] = std::vector<int>{2, 3};
    complete_s_dict["C20"] = std::vector<std::vector<int>>{{1, 0}, {1, 1}};
    complete_p_dict["C20"] = std::vector<int>{3, 2};
    complete_s_dict["C21"] = std::vector<std::vector<int>>{{0, 1}, {1, 0}};
    complete_p_dict["C21"] = std::vector<int>{2, 0};
    complete_s_dict["C22"] = std::vector<std::vector<int>>{{1, 1}, {0, 1}};
    complete_p_dict["C22"] = std::vector<int>{2, 1};
    complete_s_dict["C23"] = std::vector<std::vector<int>>{{1, 0}, {1, 1}};
    complete_p_dict["C23"] = std::vector<int>{3, 0};
    // The CNOT gate, CPHASE gate, and SWAP gate.
    complete_s_dict["CNOT"] = std::vector<std::vector<int>>{
        {1, 0, 0, 0}, {1, 1, 0, 0}, {0, 0, 1, 1}, {0, 0, 0, 1}};
    complete_s_dict["CPHASE"] = std::vector<std::vector<int>>{
        {1, 0, 0, 0}, {0, 1, 0, 0}, {0, 1, 1, 0}, {1, 0, 0, 1}};
    complete_s_dict["SWAP"] = std::vector<std::vector<int>>{
        {0, 1, 0, 0}, {1, 0, 0, 0}, {0, 0, 0, 1}, {0, 0, 1, 0}};
    complete_p_dict["CNOT"] = std::vector<int>{0, 0, 0, 0};
    complete_p_dict["CPHASE"] = std::vector<int>{0, 0, 0, 0};
    complete_p_dict["SWAP"] = std::vector<int>{0, 0, 0, 0};

    SrepDict_t result;
    for (const auto &[k, v] : complete_s_dict) {
      assert(complete_p_dict.find(k) != complete_p_dict.end());
      result[k] = std::make_pair(v, complete_p_dict[k]);
    }
    return result;
  }();

  if (!in_gateList.empty()) {
    // Filter a subset of gates:
    SrepDict_t result;
    for (const auto &gateLabel : in_gateList) {
      const auto iter = standardDict.find(gateLabel);
      assert(iter != standardDict.end());
      result[gateLabel] = iter->second;
    }
    return result;
  }
  return standardDict;
}

Srep_t computeLayerSymplecticRepresentations(const CliffordGateLayer_t &layers,
                                             int nQubits,
                                             const SrepDict_t &srep_dict) {
  // Initilize
  Pvec_t p(2 * nQubits, 0);
  Smatrix_t s(2 * nQubits, p);
  std::set<int> seen_qubits;
  for (const auto &[name, operands] : layers) {
    const auto iter = srep_dict.find(name);
    assert(iter != srep_dict.end());
    const auto &[matrix, phase] = iter->second;
    const auto nforgate = operands.size();
    assert(nforgate > 0);
    for (int ind1 = 0; ind1 < operands.size(); ++ind1) {
      const auto qindex1 = operands[ind1];
      assert(seen_qubits.find(qindex1) == seen_qubits.end());
      seen_qubits.emplace(qindex1);
      for (int ind2 = 0; ind2 < operands.size(); ++ind2) {
        const auto qindex2 = operands[ind2];
        // Put in the symp matrix elements
        s[qindex1][qindex2] = matrix[ind1][ind2];
        s[qindex1][qindex2 + nQubits] = matrix[ind1][ind2 + nforgate];
        s[qindex1 + nQubits][qindex2] = matrix[ind1 + nforgate][ind2];
        s[qindex1 + nQubits][qindex2 + nQubits] =
            matrix[ind1 + nforgate][ind2 + nforgate];
      }
      // Put in the phase elements
      p[qindex1] = phase[ind1];
      p[qindex1 + nQubits] = phase[ind1 + nforgate];
    }
  }

  return std::make_pair(s, p);
}

Srep_t composeCliffords(const Srep_t &C1, const Srep_t &C2) {
  assert(C1.first.size() == C2.first.size());
  assert(C1.second.size() == C2.second.size());
  assert(C1.first.size() % 2 == 0);
  const int n = C1.first.size() / 2;
  using Mat_t = Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic>;
  using Vec_t = Eigen::Matrix<int, Eigen::Dynamic, 1>;
  Mat_t s1(2 * n, 2 * n);
  Mat_t s2(2 * n, 2 * n);
  Vec_t p1(2 * n);
  Vec_t p2(2 * n);
  // Load to eigen for processing
  for (int i = 0; i < 2 * n; ++i) {
    for (int j = 0; j < 2 * n; ++j) {
      s1(i, j) = C1.first[i][j];
      s2(i, j) = C2.first[i][j];
    }
    p1(i) = C1.second[i];
    p2(i) = C2.second[i];
  }

  Mat_t s = s2 * s1;
  // Mod 2
  for (int i = 0; i < 2 * n; ++i) {
    for (int j = 0; j < 2 * n; ++j) {
      s(i, j) = s(i, j) % 2;
    }
  }

  Mat_t u = Mat_t::Zero(2 * n, 2 * n);
  u(Eigen::seq(n, 2 * n - 1), Eigen::seq(0, n - 1)) = Mat_t::Identity(n, n);

  Vec_t vec1 = s1.transpose() * p2;
  Mat_t inner = (s2.transpose() * u) * s2;
  const auto strictly_upper_triangle = [](const Mat_t &m) -> Mat_t {
    auto l = m.rows();
    Mat_t out = m;

    for (int i = 0; i < l; ++i) {
      for (int j = 0; j < i + 1; ++j) {
        out(i, j) = 0;
      }
    }
    return out;
  };

  // Returns a diagonal matrix containing the diagonal of m.
  const auto diagonal_as_matrix = [](const Mat_t &m) -> Mat_t {
    auto l = m.rows();
    Mat_t out = Mat_t::Zero(l, l);
    for (int i = 0; i < l; ++i) {
      out(i, i) = m(i, i);
    }

    return out;
  };

  // Returns a 1D array containing the diagonal of the input square 2D array m.
  const auto diagonal_as_vec = [](const Mat_t &m) -> Mat_t {
    auto l = m.rows();
    Vec_t vec = Vec_t::Zero(l);
    for (int i = 0; i < l; ++i) {
      vec(i) = m(i, i);
    }

    return vec;
  };

  Mat_t matrix = 2 * strictly_upper_triangle(inner) + diagonal_as_matrix(inner);
  Vec_t vec2 = diagonal_as_vec((s1.transpose() * matrix) * s1);
  Vec_t vec3 = s1.transpose() * diagonal_as_vec(inner);
  Vec_t p = p1 + vec1 + vec2 - vec3;
  for (int i = 0; i < p.size(); ++i) {
    p(i) = p(i) % 4;
  }

  Pvec_t p_res(2 * n, 0);
  Smatrix_t s_res(2 * n, p_res);
  for (int i = 0; i < 2 * n; ++i) {
    for (int j = 0; j < 2 * n; ++j) {
      s_res[i][j] = s(i, j);
    }
    p_res[i] = p(i);
  }
  return std::make_pair(s_res, p_res);
}

Srep_t computeCircuitSymplecticRepresentations(
    const std::vector<CliffordGateLayer_t> &layers, int nQubits,
    const SrepDict_t &srep_dict) {
  // Initilize
  Pvec_t p(2 * nQubits, 0);
  Smatrix_t s(2 * nQubits, p);
  // S must be initialized as an identity matrix
  for (int i = 0; i < 2 * nQubits; ++i) {
    s[i][i] = 1;
  }
  for (const auto &layer : layers) {
    const auto layerRep =
        computeLayerSymplecticRepresentations(layer, nQubits, srep_dict);

    std::tie(s, p) = composeCliffords(std::make_pair(s, p), layerRep);
  }
  return std::make_pair(s, p);
}

std::vector<PauliLabel> find_pauli_labels(const Pvec_t &pvec) {
  assert(pvec.size() % 2 == 0);
  const auto n = pvec.size() / 2;
  std::vector<int> v(n, 0);
  for (int i = 0; i < n; ++i) {
    v[i] = (pvec[i] / 2) + 2 * (pvec[n + i] / 2);
  }
  // [0,0]=I, [2,0]=Z, [0,2]=X, and [2,2]=Y.
  std::vector<PauliLabel> result;
  for (const auto &el : v) {
    assert(el < 4);
    static const std::vector<PauliLabel> ARRAY{PauliLabel::I, PauliLabel::Z,
                                               PauliLabel::X, PauliLabel::Y};
    result.emplace_back(ARRAY[el]);
  }
  return result;
}
} // namespace utils
} // namespace qcor

max_stars_repo_name: vetter/qcor

max_issues_repo_name: vetter/qcor

max_forks_repo_name: vetter/qcor


text:
#pragma once
#include <vector>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/access.hpp>

namespace snn::internal
{
    class LayerOptimizer
    {
    private:
        friend class boost::serialization::access;
        template <class Archive>
        void serialize(Archive& ar, unsigned version) {}

    public:
        LayerOptimizer() = default; // use restricted to Boost library only
        LayerOptimizer(const LayerOptimizer& layer) = default;
        virtual ~LayerOptimizer() = default;

        virtual std::unique_ptr<LayerOptimizer> clone(LayerOptimizer* optimizer) const = 0;

        virtual void applyBefore(std::vector<float>& inputs) = 0;
        virtual void applyAfterForBackpropagation(std::vector<float>& outputs) = 0;

        virtual bool operator==(const LayerOptimizer& optimizer) const = 0;
        virtual bool operator!=(const LayerOptimizer& optimizer) const = 0;
    };
}

max_stars_repo_name: sehe/StraightforwardNeuralNetwork

max_issues_repo_name: sehe/StraightforwardNeuralNetwork

max_forks_repo_name: sehe/StraightforwardNeuralNetwork


text:
#include "IOLoop.h"
#include "TimerQueue.h"
#include "CurrentThread.h"
#include <glog/logging.h>
#include <boost/asio/post.hpp>
#include <boost/asio/dispatch.hpp>

namespace IOEvent
{

thread_local IOLoop *t_inThisThreadLoop = nullptr;
IOLoop::IOLoop()
	:ioContext_(1),
	timerQueue_(std::make_unique<TimerQueue>(this)),
	work_(make_work_guard(ioContext_)),
	threadId_(CurrentThread::tid()),
	quit_(false)
{
	if (t_inThisThreadLoop)
	{
		LOG(FATAL) << "Another IOLoop :" << t_inThisThreadLoop << " exists in this thread :" << threadId_;
	}
	else
	{
		t_inThisThreadLoop = this;
	}
}

IOLoop::~IOLoop()
{
	LOG(WARNING) << "IOLoop :" << this << " of thread :" << threadId_
		<< " destructs in thread :" << CurrentThread::tid();
	if (!quit_)
	{
		quit();
	}
}

bool IOLoop::isInLoopThread() const
{
	return CurrentThread::tid() == threadId_;
}

void IOLoop::assertInLoopThread()
{
	if (!isInLoopThread())
	{
		abortNotInLoopThread();
	}
}

TimerId IOLoop::runAt(const Timestamp & when, TimerCallback cb)
{
	return timerQueue_->addTimer(std::move(cb), when, 0.0);
}

TimerId IOLoop::runAfter(double delay, TimerCallback cb)
{
	Timestamp time(addTime(Timestamp::now(), delay));
	return runAt(time, std::move(cb));
}

TimerId IOLoop::runEvery(double interval, TimerCallback cb)
{
	Timestamp time(addTime(Timestamp::now(), interval));
	return timerQueue_->addTimer(std::move(cb), time, interval);
}

void IOLoop::dispatch(FuncCallback cb)
{
	if (isInLoopThread())
	{
		cb();
	}
	else
	{
		post(cb);
	}
}

void IOLoop::post(FuncCallback cb)
{
	boost::asio::post(ioContext_, std::move(cb));
}

io_context *IOLoop::getContext()
{
	return &ioContext_;
}

void IOLoop::cancel(TimerId timerId)
{
	timerQueue_->cancel(std::move(timerId));
}

void IOLoop::loop()
{
	assertInLoopThread();
	ioContext_.run();
}

void IOLoop::quit()
{
	quit_ = true;
	post(std::bind(&IOLoop::quitInThisThread, this));
}

void IOLoop::abortNotInLoopThread()
{
	LOG(FATAL) << "IOLoop::abortNotInLoopThread - IOLoop " << this
		<< " was created in threadId_ = " << threadId_
		<< ", current thread id = " << CurrentThread::tid();
}

void IOLoop::quitInThisThread()
{
	assertInLoopThread();
	work_.reset();
	ioContext_.stop();
}

}

max_stars_repo_name: Txhua/IOLoop

max_issues_repo_name: Txhua/IOLoop

max_forks_repo_name: Txhua/IOLoop


text: #include <boost/asio/basic_streambuf.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**
 * BCL to FASTQ file converter
 * Copyright (c) 2007-2017 Illumina, Inc.
 *
 * This software is covered by the accompanying EULA
 * and certain third party copyright/licenses, and any user of this
 * source file is bound by the terms therein.
 *
 * \file ThreadPool.hh
 *
 * \brief Definition of helpers for thread pool.
 *
 * \author Aaron Day
 */

#ifndef BCL2FASTQ_CONVERSION_THREAD_POOL_HH
#define BCL2FASTQ_CONVERSION_THREAD_POOL_HH

#include "conversion/Stage.hh"
#include "conversion/TaskQueue.hh"
#include "common/SystemCompatibility.hh"
#include <boost/noncopyable.hpp>
#include <vector>
#include <thread>
#include <mutex>
#include <boost/exception_ptr.hpp>

namespace bcl2fastq
{
namespace conversion
{

/*
 * Generic thread pool. Specifiy number of threads on construction. The worker
 * threads will pull tasks off of the TaskQueue and exectue them.
 */

class ThreadPool : boost::noncopyable
{
public:
    ThreadPool(uint32_t   numThreads,
               TaskQueue& dataQueue,
               Terminator& terminator);

    ~ThreadPool() { }

private:
class JoinThreads : boost::noncopyable
{
public:
    JoinThreads(std::vector<std::thread>& threads,
                boost::exception_ptr& firstThreadException);

    ~JoinThreads();

private:
    boost::exception_ptr& firstThreadException_;
    std::vector<std::thread>& threads_;
};

    void workerThread(uint32_t threadNum);

    TaskQueue& dataQueue_;

    Terminator& terminator_;

    /// \brief Thread synchronisation mutex.
    std::mutex mut_;

    /// \brief Exception thrown by worker thread.
    boost::exception_ptr firstThreadException_;

    std::vector<std::thread> threads_;
    JoinThreads              joiner_;
};

} // namespace conversion
} // namespace bcl2fastq

#endif // BCL2FASTQ_CONVERSION_THREAD_POOL_HH

ext: hh


text:
#include "request_id.h"
// boost random is using a deprecated header in 1.69
// See: https://github.com/boostorg/random/issues/49
#define BOOST_PENDING_INTEGER_LOG2_HPP
#include <boost/integer/integer_log2.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

namespace onnxruntime {
namespace server {
namespace util {
std::string InternalRequestId() {
  return boost::uuids::to_string(boost::uuids::random_generator()());
}
const std::string MS_REQUEST_ID_HEADER = "x-ms-request-id";
const std::string MS_CLIENT_REQUEST_ID_HEADER = "x-ms-client-request-id";
}  // namespace util
}  // namespace server
}  // namespace onnxruntime

ext: cc

max_stars_repo_name: hqucms/onnxruntime

max_issues_repo_name: hqucms/onnxruntime

max_forks_repo_name: hqucms/onnxruntime


text:
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Name:        src/wpl/content.cpp
 * Project:     WebPageLayout: Command line program to create Website.
 * Purpose:     Read content from existing website.
 * Author:      Nick Matthews
 * Created:     22th Febuary 2017
 * Copyright:   Copyright (c) 2017, Nick Matthews.
 * Licence:     Boost
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
 * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
 * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 * Distributed under the Boost Software License, Version 1.0.
 * See accompanying file license.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt
 *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

 */

#include "content.h"

#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/filesystem.hpp>

#include <iostream>
#include <sstream>

namespace fs = boost::filesystem;

using std::string;

string todays_date()
{
    using namespace boost::gregorian;
    static const char* month[] = {
        "January", "Febuary", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
    };
    date today = day_clock::local_day();
    date::ymd_type ymd = today.year_month_day();
    std::stringstream str;

    str << ymd.day << "";
    switch (ymd.day)
    {
    case 1: case 21: case 31:
        str << "st";
        break;
    case 2: case 22:
        str << "nd";
        break;
    case 3: case 23:
        str << "rd";
        break;
    default:
        str << "th";
    }
    str << " " << month[ymd.month-1] << " " << ymd.year;

    return str.str();
}

string get_file_contents(const string& filename)
{
    std::ifstream in(filename);
    std::stringstream sstr;
    sstr << in.rdbuf();
    return sstr.str();
}

bool get_content(Content& content, const string& filename)
{
    content.text = "\n
Page Under Construction
\n\n";
    content.create_date = "
" + todays_date() + "
";

    string text = get_file_contents(filename);

    size_t pos1 = text.find("<div id=\"content\"");
    if (pos1 == string::npos) {
        pos1 = text.find("
", pos1);
    if (pos1 == string::npos) {
        return false;
    }
    pos1 += 2;
    size_t pos2 = text.find("
", pos1);
    if (pos2 == string::npos) {
        pos2 = text.find("
\n<hr", pos1);
    }
    if (pos2 == string::npos) {
        pos2 = text.find("
\n\n<hr", pos1);
    }
    if (pos2 == string::npos) {
        return false;
    }
    content.text = text.substr(pos1, pos2 - pos1);

    pos1 = text.find("
");
    if (pos1 == string::npos) {
        pos1 = text.find("
");
    }
    if (pos1 == string::npos) {
        return true;
    }
    pos1 += 22;
    pos2 = text.find("
", pos1);
    if (pos2 == string::npos) {
        return true;
    }
    content.create_date = text.substr(pos1, pos2 - pos1);

    return true;
}

// End of src/wpl/content.cpp

max_stars_repo_name: nickmat/WebPageLayout

max_issues_repo_name: nickmat/WebPageLayout

max_forks_repo_name: nickmat/WebPageLayout


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

class lib1 {
	public:
      	lib1();
  ~lib1();
  void print_exist();
};


text:
#include "monitor.hpp"

#ifdef file_monitor_USE_BOOST
#include <boost/next_prior.hpp>
#include <boost/range/iterator_range.hpp>

file_monitor::path_t file_monitor::relative_child_path(file_monitor::path_t const& base,
                                                       file_monitor::path_t const& child)
{
  file_monitor::path_t result;
  auto prefix = std::distance(base.begin(), base.end());
  auto range = boost::make_iterator_range(boost::next(child.begin(), prefix), child.end());

  for (auto const& each : range)
    result /= each;

  return result;
}
#else
file_monitor::path_t file_monitor::relative_child_path(file_monitor::path_t const& base,
                                                       file_monitor::path_t const& child)
{
  return child.lexically_relative(base);
}
#endif

std::uint32_t file_monitor::adler32(std::uint8_t const* data, std::size_t size)
{
  std::uint32_t ADLER_PRIME = 65521;
  std::uint32_t a = 1;
  std::uint32_t b = 0;

  for (std::size_t i = 0; i < size; ++i)
  {
    a = (a + data[i]) % ADLER_PRIME;
    b = (b + a) % ADLER_PRIME;
  }

  return (b << 16U) | a;
}


text:
#include "core/geometry.hpp"

#include <ogrsf_frmts.h> // C++ API for GDAL
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <iterator>
#include <vector>
#include <sstream>

#include "boost/geometry/extensions/gis/io/wkb/read_wkb.hpp"
#include "boost/geometry/extensions/gis/io/wkb/write_wkb.hpp"

std::ostream& FMM::CORE::operator<<(std::ostream& os,
    const FMM::CORE::LineString& rhs){
  os<< std::setprecision(12) << boost::geometry::wkt(rhs.line);
  return os;
};

FMM::CORE::LineString FMM::CORE::ogr2linestring(const OGRLineString *line){
  int binary_size = line->WkbSize();
  std::vector<unsigned char> wkb(binary_size);
  // http://www.gdal.org/ogr__core_8h.html#a36cc1f4d807ba8f6fb8951f3adf251e2
  line->exportToWkb(wkbNDR,&wkb[0]);
  LineString l;
  boost::geometry::read_wkb(wkb.begin(),wkb.end(),l.get_geometry());
  return l;
};

FMM::CORE::LineString FMM::CORE::ogr2linestring(
  const OGRMultiLineString *mline){
  FMM::CORE::LineString l;
  if (!mline->IsEmpty() && mline->getNumGeometries()>0){
    const OGRGeometry *line = mline->getGeometryRef(0);
    int binary_size = line->WkbSize();
    std::vector<unsigned char> wkb(binary_size);
    line->exportToWkb(wkbNDR,&wkb[0]);
    boost::geometry::read_wkb(wkb.begin(),wkb.end(),l.get_geometry());
  }
  return l;
};

FMM::CORE::LineString FMM::CORE::wkt2linestring(const std::string &wkt){
  FMM::CORE::LineString line;
  boost::geometry::read_wkt(wkt,line.get_geometry());
  return line;
};

OGRLineString *FMM::CORE::linestring2ogr(const FMM::CORE::LineString &line){
  std::vector<unsigned char> wkb;
  boost::geometry::write_wkb(line.get_geometry_const(),std::back_inserter(wkb));
  OGRGeometry *poGeometry;
  OGRGeometryFactory::createFromWkb(&wkb[0], NULL, &poGeometry);
  return (OGRLineString *) poGeometry;
};

OGRPoint *FMM::CORE::point2ogr(const FMM::CORE::Point &p){
  std::vector<unsigned char> wkb;
  boost::geometry::write_wkb(p,std::back_inserter(wkb));
  OGRGeometry *poGeometry;
  OGRGeometryFactory::createFromWkb(&wkb[0], NULL, &poGeometry);
  return (OGRPoint *) poGeometry;
};

max_stars_repo_name: jczaplew/fmm

max_issues_repo_name: jczaplew/fmm

max_forks_repo_name: jczaplew/fmm


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

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

#include <DhtClient.h>
#include <DhtCore.h>
#include <Options.h>

#include "tests.h"
#include <config.h>
#include <debug.h>

using namespace std;
using namespace DaqDB;

static const unsigned int TESTCLIENT_PORT = 31852;

bool testDhtConnect(KVStoreBase *kvs) {
    bool result = true;

    DhtOptions options;
    DhtNeighbor local;
    local.ip = "localhost";
    local.port = TESTCLIENT_PORT;
    local.local = true;
    options.maskLength = 8;
    options.maskOffset = 0;

    DhtNeighbor neighbor;
    neighbor.ip = "localhost";
    neighbor.port = 31850;
    neighbor.keyRange.start = "0";
    neighbor.keyRange.end = "255";

    options.neighbors.push_back(&local);
    options.neighbors.push_back(&neighbor);

    auto serverStatus = kvs->getProperty("daqdb.dht.status");
    if (serverStatus.find("DHT server: inactive") != std::string::npos) {
        DAQDB_INFO << "DHT server not started" << flush;
        return false;
    }

    auto core = new DhtCore(options);
    core->initNexus();
    core->initClient();
    if (core->getClient()->state == DhtClientState::DHT_CLIENT_READY) {
        DAQDB_INFO << "DHT client started successfully" << flush;
    } else {
        DAQDB_INFO << "Can not start DHT client" << flush;
        return false;
    }
    auto neighborNode = core->getNeighbors()->front();
    auto connected = core->getClient()->ping(*neighborNode);
    if (!connected) {
        DAQDB_INFO << "Can not connect to neighbor" << flush;
        return false;
    }

    return result;
}

max_stars_repo_name: gjerecze/daqdb

max_issues_repo_name: gjerecze/daqdb

max_forks_repo_name: gjerecze/daqdb