text:
#include <stdexcept>

#include <boost/assign.hpp>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/function.hpp>
#include <boost/make_shared.hpp>

#include <ros/ros.h>
#include <std_msgs/Float64.h>
#include <std_msgs/UInt32.h>

#include <dynamic-graph/factory.h>
#include <dynamic-graph/command.h>
#include <dynamic-graph/linear-algebra.h>

#include "dynamic_graph_bridge/ros_init.hh"
#include "ros_publish.hh"

#define ENABLE_RT_LOG
#include <dynamic-graph/real-time-logger.h>

namespace dynamicgraph {

DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(RosPublish, "RosPublish");
const double RosPublish::ROS_JOINT_STATE_PUBLISHER_RATE = 0.01;

namespace command {
namespace rosPublish {

Add::Add(RosPublish& entity, const std::string& docstring)
    : Command(entity, boost::assign::list_of(Value::STRING)(Value::STRING)(Value::STRING), docstring) {}

Value Add::doExecute() {
  RosPublish& entity = static_cast<RosPublish&>(owner());
  std::vector<Value> values = getParameterValues();

  const std::string& type = values[0].value();
  const std::string& signal = values[1].value();
  const std::string& topic = values[2].value();

  if (type == "boolean")
    entity.add<bool>(signal, topic);
  else if (type == "double")
    entity.add<double>(signal, topic);
  else if (type == "unsigned")
    entity.add<unsigned int>(signal, topic);
  else if (type == "int")
    entity.add<int>(signal, topic);
  else if (type == "matrix")
    entity.add<Matrix>(signal, topic);
  else if (type == "vector")
    entity.add<Vector>(signal, topic);
  else if (type == "vector3")
    entity.add<specific::Vector3>(signal, topic);
  else if (type == "vector3Stamped")
    entity.add<std::pair<specific::Vector3, Vector> >(signal, topic);
  else if (type == "matrixHomo")
    entity.add<sot::MatrixHomogeneous>(signal, topic);
  else if (type == "matrixHomoStamped")
    entity.add<std::pair<sot::MatrixHomogeneous, Vector> >(signal, topic);
  else if (type == "twist")
    entity.add<specific::Twist>(signal, topic);
  else if (type == "twistStamped")
    entity.add<std::pair<specific::Twist, Vector> >(signal, topic);
  else if (type == "string")
    entity.add<std::string>(signal, topic);
  else
    throw std::runtime_error("bad type");
  return Value();
}

}  // namespace rosPublish
}  // end of namespace command.

const std::string RosPublish::docstring_(
    "Publish dynamic-graph signals as ROS topics.\n"
    "\n"
    "  Use command \"add\" to publish a new ROS topic.\n");

RosPublish::RosPublish(const std::string& n)
    : dynamicgraph::Entity(n),
      // RosPublish do not use callback so do not create a useless spinner.
      nh_(rosInit(false)),
      bindedSignal_(),
      trigger_(boost::bind(&RosPublish::trigger, this, _1, _2), sotNOSIGNAL,
               MAKE_SIGNAL_STRING(name, true, "int", "trigger")),
      rate_(0, 10000000),
      nextPublication_() {
  aofs_.open("/tmp/ros_publish.txt");
  dgADD_OSTREAM_TO_RTLOG(aofs_);

  try {
    if (ros::Time::isSimTime())
      nextPublication_ = ros::Time::now();
    else {
      clock_gettime(CLOCK_REALTIME, &nextPublicationRT_);
    }
  } catch (const std::exception& exc) {
    throw std::runtime_error("Failed to call ros::Time::now ():" + std::string(exc.what()));
  }
  signalRegistration(trigger_);
  trigger_.setNeedUpdateFromAllChildren(true);

  std::string docstring =
      "\n"
      "  Add a signal writing data to a ROS topic\n"
      "\n"
      "  Input:\n"
      "    - type: string among ['double', 'matrix', 'vector', 'vector3',\n"
      "                          'vector3Stamped', 'matrixHomo', "
      "'matrixHomoStamped',\n"
      "                          'twist', 'twistStamped'],\n"
      "    - signal: the signal name in dynamic-graph,\n"
      "    - topic:  the topic name in ROS.\n"
      "\n";
  addCommand("add", new command::rosPublish::Add(*this, docstring));
}

RosPublish::~RosPublish() { aofs_.close(); }

void RosPublish::display(std::ostream& os) const { os << CLASS_NAME << std::endl; }

void RosPublish::rm(const std::string& signal) {
  if (bindedSignal_.find(signal) == bindedSignal_.end()) return;

  if (signal == "trigger") {
    std::cerr << "The trigger signal should not be removed. Aborting." << std::endl;
    return;
  }

  // lock the mutex to avoid deleting the signal during a call to trigger
  boost::mutex::scoped_lock lock(mutex_);

  signalDeregistration(signal);
  bindedSignal_.erase(signal);
}

std::vector<std::string> RosPublish::list() const {
  std::vector<std::string> result(bindedSignal_.size());
  std::transform(bindedSignal_.begin(), bindedSignal_.end(),
      result.begin(), [](const auto& pair) { return pair.first; });
  return result;
}

void RosPublish::clear() {
  std::map<std::string, bindedSignal_t>::iterator it = bindedSignal_.begin();
  for (; it != bindedSignal_.end();) {
    if (it->first != "trigger") {
      rm(it->first);
      it = bindedSignal_.begin();
    } else {
      ++it;
    }
  }
}

int& RosPublish::trigger(int& dummy, int t) {
  typedef std::map<std::string, bindedSignal_t>::iterator iterator_t;
  ros::Time aTime;
  if (ros::Time::isSimTime()) {
    aTime = ros::Time::now();
    if (aTime <= nextPublication_) return dummy;

    nextPublication_ = aTime + rate_;
  } else {
    struct timespec aTimeRT;
    clock_gettime(CLOCK_REALTIME, &aTimeRT);
    nextPublicationRT_.tv_sec = aTimeRT.tv_sec + rate_.sec;
    nextPublicationRT_.tv_nsec = aTimeRT.tv_nsec + rate_.nsec;
    if (nextPublicationRT_.tv_nsec > 1000000000) {
      nextPublicationRT_.tv_nsec -= 1000000000;
      nextPublicationRT_.tv_sec += 1;
    }
  }

  boost::mutex::scoped_lock lock(mutex_);

  for (iterator_t it = bindedSignal_.begin(); it != bindedSignal_.end(); ++it) {
    boost::get<1>(it->second)(t);
  }
  return dummy;
}

std::string RosPublish::getDocString() const { return docstring_; }

}  // end of namespace dynamicgraph.


text:
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2018 Sylko Olzscher
 *
 */

#include "sml_to_log_consumer.h"
#include <cyng/async/task/task_builder.hpp>
#include <cyng/dom/reader.h>
#include <cyng/io/serializer.h>
#include <cyng/value_cast.hpp>
#include <cyng/set_cast.h>

#include <boost/uuid/random_generator.hpp>

namespace node
{

	sml_log_consumer::sml_log_consumer(cyng::async::base_task* btp
		, cyng::logging::log_ptr logger
		, std::size_t ntid	//	network task id
		, cyng::param_map_t cfg)
	: base_(*btp)
		, logger_(logger)
		, lines_()
	{
		CYNG_LOG_INFO(logger_, "initialize task #"
			<< base_.get_id()
			<< " <"
			<< base_.get_class_name()
			<< ">");
	}

	cyng::continuation sml_log_consumer::run()
	{
		CYNG_LOG_INFO(logger_, "sml_log_consumer is running");

		return cyng::continuation::TASK_CONTINUE;
	}

	void sml_log_consumer::stop()
	{
		CYNG_LOG_INFO(logger_, "task #"
			<< base_.get_id()
			<< " <"
			<< base_.get_class_name()
			<< " stopped");
	}

	cyng::continuation sml_log_consumer::process(std::uint64_t line
		, std::string target)
	{
		CYNG_LOG_INFO(logger_, "task #"
			<< base_.get_id()
			<< " <"
			<< base_.get_class_name()
			<< " create line "
			<< line
			<< ':'
			<< target);

		return cyng::continuation::TASK_CONTINUE;
	}

	cyng::continuation sml_log_consumer::process(std::uint64_t line
		, std::uint16_t code
		, std::size_t idx
		, cyng::tuple_t msg)
	{
		CYNG_LOG_INFO(logger_, "task #"
			<< base_.get_id()
			<< " <"
			<< base_.get_class_name()
			<< " line "
			<< line
			<< " received #"
			<< idx
			<< ':'
			<< sml::messages::name(code));
		return cyng::continuation::TASK_CONTINUE;
	}

	cyng::continuation sml_log_consumer::process(std::uint64_t line)
	{
		CYNG_LOG_INFO(logger_, "task #"
			<< base_.get_id()
			<< " <"
			<< base_.get_class_name()
			<< " close line "
			<< line);
		return cyng::continuation::TASK_CONTINUE;
	}

	//	EOM
	cyng::continuation sml_log_consumer::process(std::uint64_t line, std::size_t idx, std::uint16_t crc)
	{
		return cyng::continuation::TASK_CONTINUE;
	}

	void sml_log_consumer::cb(std::uint32_t channel
		, std::uint32_t source
		, std::string const& target
		, std::string const& protocol
		, cyng::vector_t&& prg)
	{
		CYNG_LOG_DEBUG(logger_, "db processor "
			<< channel
			<< ':'
			<< source
			<< ':'
			<< target
			<< " - "
			<< protocol
			<< " - "
			<< prg.size()
			<< " instructions");

	}
}

ext: cpp

max_stars_repo_name: solosTec/node

max_issues_repo_name: solosTec/node

max_forks_repo_name: solosTec/node


text:
/*******************************************************************************
*
*  Filename    : CombinePull.
*  Description : implementing combine pull Functions
*  Author      : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
*
*******************************************************************************/
#include "TstarAnalysis/LimitCalc/interface/CombinePull.hpp"
#include "TstarAnalysis/LimitCalc/interface/Common.hpp"

#include "ManagerUtils/Common/interface/ConfigReader.hpp"
#include "ManagerUtils/Maths/interface/Parameter.hpp"
#include "ManagerUtils/PlotUtils/interface/Common.hpp"
#include "ManagerUtils/SysUtils/interface/HiggsCombineSubmitter.hpp"
#include "ManagerUtils/SysUtils/interface/PathUtils.hpp"
#include "TstarAnalysis/Common/interface/PlotStyle.hpp"

#include <boost/format.hpp>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <utility>
#include <vector>

#include "RooFitResult.h"
#include "RooRealVar.h"
#include "TFile.h"

using namespace std;
using mgr::Parameter;

/******************************************************************************/

void
MakeCombinePull()
{
  const mgr::ConfigReader higgscfg( limnamer.SettingsDir() / "higgs_combine_settings.json" );

  const string cardfile = limnamer.TextFileName( "card" );

  const string scriptfilename = limnamer.TextFileName( "combpull" );

  const string storeroot = limnamer.RootFileName( "combpull" );

  cout << cardfile << endl;

  ofstream scriptfile( scriptfilename );

  scriptfile << "#!/bin/bash" << endl;

  scriptfile << boost::format( "cd %s/%s/src" )
    % higgscfg.GetStaticString( "Store Path" )
    % higgscfg.GetStaticString( "CMSSW Version" )
             << endl;

  scriptfile <<  "eval `scramv1 runtime -sh 2> /dev/null`" << endl;

  scriptfile << boost::format( "combine -M MaxLikelihoodFit %s" ) % cardfile << endl;

  scriptfile << boost::format( "cp mlfit.root %s" ) % storeroot << endl;

  scriptfile.close();

  system( ( "chmod +x " + scriptfilename ).c_str() );
  system( scriptfilename.c_str() );

  system( "sleep 5" );
}

/******************************************************************************/

static Parameter
MakeVarPull( const RooArgList& post, const RooArgList& pre, const string& name )
{
  vector<RooRealVar*> postvarlist;
  vector<RooRealVar*> prevarlist;

  for( int i = 0; i < post.getSize(); ++i ){
    RooRealVar* postvar = (RooRealVar*)( post.at( i ) );
    if( std::string( postvar->GetName() ).find( name ) != string::npos ){
      postvarlist.push_back( postvar );
    }
  }

  for( int i = 0; i < pre.getSize(); ++i ){
    RooRealVar* prevar = (RooRealVar*)( pre.at( i ) );
    if( std::string( prevar->GetName() ).find( name ) != string::npos ){
      prevarlist.push_back( prevar );
    }
  }

  if( postvarlist.size() && prevarlist.size() ){
    const double preval  = prevarlist.front()->getVal();
    const double preerr  = prevarlist.front()->getError();
    const double postval = postvarlist.front()->getVal();
    const double posterr = postvarlist.front()->getError();
    const double pull    = ( postval - preval ) / preerr;
    const double pullerr = posterr / preerr;
    return Parameter( pull, pullerr, pullerr );
  } else {
    cout << "Warning! parameter [" << name  << "] not found!" << endl;
    return Parameter( 0, 0, 0 );
  }
}

/******************************************************************************/

void
MakePullPlot()
{
  TFile* file               = TFile::Open( limnamer.RootFileName( "combpull" ).c_str(), "READ" );
  const RooArgList& postfit = ( (RooFitResult*)( file->Get( "fit_s" ) ) )->floatParsFinal();
  const RooArgSet& prefit   = *( (RooArgSet*)( file->Get( "nuisances_prefit" ) ) );

  vector<pair<string, Parameter> > pulllist;

  // Fitting paramter varibles
  // const string avarname   = limnamer.GetInput<string>( "masspoint" ) + "simfitbga";
  // const string bvarname   = limnamer.GetInput<string>( "masspoint" ) + "simfitbgb";
  // const string sysvarname = limnamer.GetInput<string>( "masspoint" ) + "simfitbgsys";

  // pulllist.emplace_back( "Bkg. parm 1", MakeVarPull( postfit, prefit, avarname ) );
  // pulllist.emplace_back( "Bkg. parm 2", MakeVarPull( postfit, prefit, bvarname ) );
  // pulllist.emplace_back( "Bkg. sys",    MakeVarPull( postfit, prefit, sysvarname ) );

  // Shape uncertainties
  for( size_t i = 0; i < uncsource.size(); ++i ){
    boost::format shapename( "%s%s_%s%s%s" );
    const string upname = boost::str(
      shapename
      % limnamer.GetInput<string>( "masspoint" ) % "keymastercoeff"
      % uncsource.at( i )  % "Up"     %"key"
      );
    const string dwname = boost::str(
      shapename
      % limnamer.GetInput<string>( "masspoint" ) % "keymastercoeff"
      % uncsource.at( i ) % "Down" %"key"
      );

    const Parameter uppull = MakeVarPull( postfit, prefit, upname );
    const Parameter dwpull = MakeVarPull( postfit, prefit, dwname );

    const Parameter pull(
      uppull.CentralValue() + dwpull.CentralValue(),
      ( uppull.AbsUpperError() + dwpull.AbsUpperError() ) /2,
      ( uppull.AbsUpperError() + dwpull.AbsUpperError() ) /2
      );

    pulllist.emplace_back( uncsource.at( i ), pull );
  }

  // Misc options
  pulllist.emplace_back( "lep sys.", MakeVarPull( postfit, prefit, "lepsys" ) );
  pulllist.emplace_back( "lumi.",    MakeVarPull( postfit, prefit, "lumi" ) );
  pulllist.emplace_back( "stat.",    MakeVarPull( postfit, prefit, "statunc" ) );

  for( const auto& mypair : pulllist ){
    cout << mypair.first << " " << mgr::FloatingPoint( mypair.second.CentralValue(), 10 ) << endl;
  }

  delete file;

  // Beginning plotting
  TCanvas* c = mgr::NewCanvas();

  TH1D* pullhist = new TH1D( "pull", "pull", pulllist.size(), 0, pulllist.size() );

  for( size_t i = 0; i < pulllist.size(); ++i ){
    const string name    = pulllist.at( i ).first;
    const Parameter pull = pulllist.at( i ).second;
    pullhist->GetXaxis()->SetBinLabel( i+1, name.c_str() );
    pullhist->SetBinContent( i+1, pull.CentralValue() );
    pullhist->SetBinError( i+1, pull.AbsAvgError() );
  }

  mgr::SetSinglePad( c );
  c->SetBottomMargin( 1.5 * PLOT_Y_MIN );

  const double ymax = std::max( mgr::GetYmax( pullhist ), 2.0 );
  mgr::SetAxis( pullhist );
  tstar::SetDataStyle( pullhist );
  pullhist->Draw( PS_DATA );
  pullhist->SetTitle( "" );
  pullhist->SetStats( 0 );
  pullhist->GetYaxis()->SetTitle( "Post-fit pull" );
  pullhist->SetMaximum( ymax * 1.2 );
  pullhist->SetMinimum( ymax * -1.2 );

  mgr::DrawCMSLabel( PRELIMINARY );
  mgr::DrawLuminosity( limnamer.GetExt<double>( "era", "Lumi" ) );

  const double xmin = 0;
  const double xmax = pulllist.size();
  TLine* cen        = new TLine( xmin, 0, xmax, 0 );
  TLine* midtop     = new TLine( xmin, 0.5, xmax, 0.5 );
  TLine* top        = new TLine( xmin, 1, xmax, 1 );
  TLine* midbot     = new TLine( xmin, -0.5, xmax, -0.5 );
  TLine* bot        = new TLine( xmin, -1, xmax, -1 );
  cen->Draw();
  midtop->Draw();
  top->Draw();
  midbot->Draw();
  bot->Draw();
  pullhist->Draw( PS_DATA PS_SAME );

  cen->SetLineColor( kGray );
  cen->SetLineStyle( 1 );
  cen->SetLineWidth( 3 );
  midtop->SetLineColor( KBLUE );
  midbot->SetLineColor( KBLUE );
  midtop->SetLineWidth( 3 );
  midbot->SetLineWidth( 3 );
  midtop->SetLineStyle( 2 );
  midbot->SetLineStyle( 2 );
  top->SetLineColor( KRED );
  bot->SetLineColor( KRED );
  top->SetLineWidth( 3 );
  bot->SetLineWidth( 3 );
  top->SetLineStyle( 3 );
  bot->SetLineStyle( 3 );

  boost::format massfmt( "M_{t*}=%dGeV/c^{2}" );
  const string masstag = boost::str( massfmt % GetInt( limnamer.GetInput<string>( "masspoint" ) ) );

  mgr::LatexMgr latex;
  latex.SetOrigin( PLOT_X_MIN, PLOT_Y_MAX + TEXT_MARGIN/2, BOTTOM_LEFT )
  .WriteLine( limnamer.GetExt<string>( "channel", "Root Name" ) )
  .SetOrigin( PLOT_X_TEXT_MAX, PLOT_Y_TEXT_MAX, TOP_RIGHT )
  .WriteLine( masstag );

  mgr::SaveToPDF( c, limnamer.PlotFileName( "combpull" ) );

  delete c;
  delete pullhist;
}

ext: cc

max_stars_repo_name: NTUHEP-Tstar/TstarAnalysis

max_issues_repo_name: NTUHEP-Tstar/TstarAnalysis

max_forks_repo_name: NTUHEP-Tstar/TstarAnalysis


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

#include "Constraint.h"
#include "Split.h"
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>

#include <bitset>
#include <string>

/**
\file Constraint.cpp
Defines Constraint class.
*/

using namespace boost;
using namespace boost::algorithm;

namespace lpcompare {

	/**
	Finds a ConstraintOp representation for the string op.

	\param op Operation to find ConstraintOp for.
	\return A ConstraintOp representing the operation.
	*/
	ConstraintOp get_constraintop(std::string op) {
		if (op == "=")
			return ConstraintOp::EQ;
		if (op == ">=")
			return ConstraintOp::GTE;
		if (op == ">")
			return ConstraintOp::GT;
		if (op == "<=")
			return ConstraintOp::LTE;
		if (op == "<")
			return ConstraintOp::LT;

		return ConstraintOp::EQ;
	}

	/**
	Finds a string representation for the ConstraintOp.

	\param op Operation to find string for.
	\return A string representing the ConstraintOp.
	*/
	std::string get_constraintop(ConstraintOp op) {
		if (op == ConstraintOp::EQ)
			return "=";
		if (op == ConstraintOp::GTE)
			return ">=";
		if (op == ConstraintOp::GT)
			return ">";
		if (op == ConstraintOp::LTE)
			return "<=";
		if (op == ConstraintOp::LT)
			return "<";

		return "=";
	}

	/**
	Splits a string into a vector.

	\param s String to split.
	\param d Delimiter array.
	\param ret Splitted string.
	*/
	void custom_split(std::string & s, char const* d, std::vector<std::string>& ret)
	{
		std::vector<std::string> output;

		std::bitset<255> delims;
		while (*d)
		{
			unsigned char code = *d++;
			delims[code] = true;
		}
		typedef std::string::const_iterator iter;
		iter beg;
		bool in_token = false;
		for (std::string::const_iterator it = s.begin(), end = s.end();
			it != end; ++it)
		{
			if (delims[*it])
			{
				if (in_token)
				{
					output.push_back(std::vector<std::string>::value_type(beg, it));
					in_token = false;
				}
			}
			else if (!in_token)
			{
				beg = it;
				in_token = true;
			}
		}
		if (in_token){
			iter end = s.end();
			output.push_back(std::vector<std::string>::value_type(beg, end));
		}

		output.swap(ret);
	}

	/**
	Parses a line of the LP file representing a Constraint.

	\param line Single line of an LP file.
	\return A Constraint instance representing line.
	*/
	Constraint *Constraint::Parse(std::string& line){

		Constraint *ret = new Constraint();

		std::vector<std::string> parts;

		custom_split(line, " \t\r\n", parts);

		if (parts.size() == 0)
			return nullptr;

		if (contains(parts[0], ":"))
			ret->Name = parts[0].substr(0, parts[0].length() - 1);

		char opChar = '+';
		double coeff = 1;
		std::string name = "";

		for (auto it = parts.begin() + 1; it != parts.end() - 2; ++it)
		{
			auto token = *it;

			if (name.length() > 0)
			{
				// add CoeffVar.
				auto term = new Term();
				term->varName = name;
				term->coeff = opChar == '+' ? coeff : -coeff;
				ret->Terms->push_back(*term);

				name = "";
				opChar = '+';
				coeff = 1;
			}

			if (token.length() == 1 && (token[0] == '-' || token[0] == '+'))
			{
				opChar = token[0];
			}

			if (isdigit(token[0]))
			{
				coeff = boost::lexical_cast<double>(token);
			}

			if (isalpha(token[0]))
			{
				name = token;
			}
		}

		if (name.length() > 0)
		{
			// add CoeffVar.
			auto term = new Term();
			term->varName = name;
			term->coeff = opChar == '+' ? coeff : -coeff;
			ret->Terms->push_back(*term);

			name = "";
			opChar = '+';
			coeff = 1;
		}

		std::sort(ret->Terms->begin(), ret->Terms->end());

		auto opstr = parts[parts.size() - 2];
		auto rhsstr = parts[parts.size() - 1];

		ret->Sign = get_constraintop(opstr);
		ret->RHS = boost::lexical_cast<double>(rhsstr);

		return ret;
	}

	/**
	Compares two Constraint instances for equality.

	\param other Other instance to compare self to.
	\return true if Constraint instances are equivalent.
	*/
	bool Constraint::operator==(const Constraint &other) const {
		bool eq = other.Sign == Sign;
		eq = eq && other.RHS == RHS;
		eq = eq && other.Terms->size() == Terms->size();
		eq = eq && std::equal(other.Terms->begin(), other.Terms->end(), Terms->begin());
		return eq;
	}

	/**
	Compares two Constraint instances for equality.

	\param other Other instance to compare self to.
	\return true if Constraint instances are not equivalent.
	*/
	bool Constraint::operator!=(const Constraint &other) const {
		return !(*this == other);
	}

	/**
	Returns an integer rank representing a ConstraintOp. Equivalent
	ConstraintOp instances have the same rank.

	\param op ConstraintOp to find rank of.
	\return An integer rank.
	*/
	int get_constraintop_val(ConstraintOp op) {
		if (op == ConstraintOp::EQ)
			return 0;
		if (op == ConstraintOp::GT || op == ConstraintOp::GTE)
			return 1;
		if (op == ConstraintOp::LT || op == ConstraintOp::LTE)
			return 2;

		return 0;
	}

	/**
	Compares two Constraint instances.

	\param other Other instance to compare self to.
	\return true if self is less than other.
	*/
	bool Constraint::operator<(const Constraint &other) const {

		auto sign = get_constraintop_val(Sign);
		auto sign_other = get_constraintop_val(other.Sign);

		if (sign > sign_other)
			return false;
		else if (sign < sign_other)
			return true;

		if (sign_other == sign && RHS > other.RHS)
			return false;
		else if (RHS < other.RHS)
			return true;

		if (sign_other == sign && other.RHS == RHS && Terms->size() > other.Terms->size())
			return false;
		else if (Terms->size() < other.Terms->size())
			return true;

		/* Terms assumed sorted. */
		if (sign_other == sign && RHS == other.RHS && Terms->size() == other.Terms->size()) {

			bool is_equal_sofar = true;
			for (auto it = Terms->begin(), it2 = other.Terms->begin();
				is_equal_sofar && it != Terms->end() && it2 != other.Terms->end(); ++it, ++it2) {

				if (*it2 != *it)
					is_equal_sofar = false;

				if (*it < *it2)
					return true;

				if (*it2 < *it)
					return false;
			}

			if (is_equal_sofar)
				return false;
		}

		if (other == *this)
			return false;

		return true;
	}

	/**
	Dumps a Constraint instance to an ostream in a text format.
	\param cons Constraint to dump.
	\param out
	*/
	void Constraint::dump(const Constraint &cons, std::ostream &out) {

		out << " Name: " << cons.Name << std::endl;
		out << "  " << cons.RHS << " " << get_constraintop(cons.Sign) << std::endl;

		for (auto term : *cons.Terms) {
			out << "  " << term.coeff << " * " << term.varName << std::endl;
		}

		out << std::endl;
	}
}

max_stars_repo_name: krk/cplexlpcompare

max_issues_repo_name: krk/cplexlpcompare

max_forks_repo_name: krk/cplexlpcompare


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

#include <vector>

#include "aisql_connection.hpp"
#include "aisql_conns_manage.hpp"

#include <boost/ref.hpp>
#include <boost/bind.hpp>

using namespace aisqlpp::db_config;
using aisqlpp::connection_ptr;

BOOST_AUTO_TEST_SUITE(mysql_conns_multi_instances)

BOOST_AUTO_TEST_CASE(mysql_conns_multi_simple)
{
    aisqlpp::conns_manage mng1(3, host, user, passwd, db);
    aisqlpp::conns_manage mng2(7, host, user, passwd, db);

    assert(mng1.free_count() == 3);
    assert(mng2.free_count() == 7);

    {
        connection_ptr p1 = mng1.request_conn();
        connection_ptr p2 = mng1.request_conn();
        connection_ptr p3 = mng1.request_conn();
        connection_ptr p4 = mng1.try_request_conn(100);

        connection_ptr p5 = mng2.try_request_conn(100);
        connection_ptr p6 = mng2.request_conn();
        assert(p4 == nullptr);
        mng1.free_conn(p2);
        assert(mng1.free_count() == 1);
        assert(mng2.free_count() == 5);

        connection_ptr p7 = mng2.request_conn();
    }

    assert(mng1.free_count() == 1);
    assert(mng2.free_count() == 4);

    cout << "mysql_conns_multi_simple FINISHED!" << endl;
}

BOOST_AUTO_TEST_CASE(mysql_conns_multi_stage2)
{
    aisqlpp::conns_manage mng1(3, host, user, passwd, db);
    aisqlpp::conns_manage mng2(7, host, user, passwd, db);
    aisqlpp::conns_manage mng3(3, host, user, passwd, db);

    assert(mng1.free_count() == 3);

    {
        assert(mng1.free_count() == 3);
        connection_ptr ptr;
        bool ret = mng1.request_scoped_conn(ptr);
        assert(ret && ptr);

        // reset should be free first
        ptr.reset();
        assert(!ptr);

        connection_ptr ptr2;
        ret = mng1.request_scoped_conn(ptr2);

        assert(mng1.free_count() == 2);

        ret = mng2.request_scoped_conn(ptr);

        assert(mng1.free_count() == 2);
        assert(mng2.free_count() == 6);

        mng1.conn_details();
        mng2.conn_details();

    }

    assert(mng1.free_count() == 3);
    assert(mng2.free_count() == 7);

    connection_ptr ptr;
    bool rett;
    rett = mng3.request_scoped_conn(ptr);
    assert(mng3.free_count() == 2);
    ptr.reset();
    assert(mng3.free_count() == 3);

    cout << "mysql_conns_multi_stage2 FINISHED!" << endl;
}

BOOST_AUTO_TEST_CASE(mysql_conns_multi_stage3)
{
    aisqlpp::conns_manage mng1(4, host, user, passwd, db);

    assert(mng1.free_count() == 4);

    {
        assert(mng1.free_count() == 4);
        connection_ptr ptr;
        bool ret = mng1.request_scoped_conn(ptr);
        assert(ret && ptr);

        // reset should be free first
        //ptr.reset();
        //assert(!ptr);

        ret = mng1.request_scoped_conn(ptr);

        cout << "SCOPED END FREE:" << mng1.free_count() << endl;
        assert(mng1.free_count() == 3);

    }

    cout << "END FREE:" << mng1.free_count() << endl;
    assert(mng1.free_count() == 4);

    cout << "mysql_conns_multi_stage3 FINISHED!" << endl;
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: taozhijiang/aisqlpp

max_issues_repo_name: taozhijiang/aisqlpp

max_forks_repo_name: taozhijiang/aisqlpp


text:
#include "constants.hpp"
#include <string>
#include <math.h>
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <tf/transform_broadcaster.h>
#include <boost/shared_ptr.hpp>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <sstream>
#include <limits>

using namespace std;

// A serial interface used to send commands to the Arduino that controls
// the motor controllers. (Yeah, recursion!)
// (C file descriptor)
int tty;
std::stringstream ss;

// for odometry
ros::Time currentTime;
ros::Time lastTime;
ros::Publisher odomPub;
boost::shared_ptr<tf::TransformBroadcaster> odomBroadcaster;
double x = 0;
double y = 0;
double theta = 0;
double vx = 0;
double vy = 0;
double vtheta = 0;
// Make current speeds always available (and query them only once per cycle)
double vLeftCur  = 0.0;
double vRightCur = 0.0;
// Cache speeds to only send data if they change
double vLeftLast     = 0.0;
double vRightLast    = 0.0;
double vRotLeftLast  = 0.0;
double vRotRightLast = 0.0;

// Used to form the Arduino commands
const char MOTOR_LEFT = 'l';
const char MOTOR_RIGHT = 'r';
const char MOTOR_FORWARD = 'f';
const char MOTOR_BACKWARD = 'b';
const char MOTOR_STOP = 's';

// The motors are stopped (not just set to speed 0.0) below this input speed.
const float STOP_THRESHOLD = 0.01f;

bool initTty()
{
	// http://timmurphy.org/2009/08/04/baud-rate-and-other-serial-comm-settings-in-c/
	tty = open("/dev/ttyACM0", O_RDWR | O_NOCTTY/* | O_NDELAY*/);
	if(tty < 0) {
		perror("open(\"/dev/ttyACM0\")");
		return false;
	}
	struct termios settings;
	tcgetattr(tty, &settings);
	cfsetospeed(&settings, B115200);
	cfsetispeed(&settings, B0 /*same as output*/);
	settings.c_cflag &= ~PARENB;	// no parity
	settings.c_cflag &= ~CSTOPB;	// one stop bit
	settings.c_cflag &= ~CSIZE;		// 8 bits per character
	settings.c_cflag |= CS8;
	settings.c_cflag &= ~CRTSCTS;	// Disable hardware flow control
	// settings.c_cflag &= ~HUPCL;		// Send modem disconnect when closing the fd
	settings.c_cflag |= CREAD;		// Enable receiver
	// settings.c_cflag |= CLOCAL;		// Ignore modem status lines
	settings.c_iflag &= ~(IXON | IXOFF | IXANY); // Disable start/stop I/O control
	settings.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // Disable user terminal features
	settings.c_oflag &= ~OPOST;		// Disable output postprocessing
	settings.c_cc[VMIN]  = 0;
	settings.c_cc[VTIME] = 0;
	if(tcsetattr(tty, TCSANOW, &settings) != 0) {
		perror("tcsetattr");
		return false;
	}
	tcflush(tty, TCOFLUSH);
	return true;
}

int readLine(char* const line, const ssize_t LINE_LENGTH)
{
	ssize_t bytesRead = 0;
	bool lineComplete = false;
	while(!lineComplete && bytesRead < LINE_LENGTH) {
		// Read bytes into temporary buffer
		char buffer[LINE_LENGTH];
		// ROS_INFO("a");
		ssize_t newBytesRead = read(tty, buffer, LINE_LENGTH);
		// ROS_INFO("b");
		if(newBytesRead < 0) {
			perror("read");
		}
		// Copy new bytes to 'line'
		for(ssize_t i = 0; i < newBytesRead && bytesRead < LINE_LENGTH; i++, bytesRead++) {
			line[bytesRead] = buffer[i];
			if(buffer[i] == '\n') {
				lineComplete = true;
			}
		}
	}
	return bytesRead;
}

void setDrive(const char motor, const char direction, const float spd = 0.0f)
{
	ss.str("");
	ss << "sd" << motor << direction;
	if(direction != MOTOR_STOP) {
		ss << std::hex << (int8_t)(spd * 255);
	}
	ss << std::endl;
	const char* output = ss.str().c_str();
	write(tty, output, ss.str().length());
	// ROS_INFO("%s", output);
	// check response
	char line[2];
	const int lineLength = readLine(line, 2);
	if(atoi(line) != 0) {
		ROS_INFO("Command failed: %s", output);
	}
}

void setRotation(const char motor, const char direction, const float spd = 0.0f)
{
	ss.str("");
	ss << "sr" << motor << direction;
	if(direction != MOTOR_STOP) {
		ss << std::hex << (int8_t)(spd * 255);
	}
	ss << std::endl;
	const char* output = ss.str().c_str();
	write(tty, output, ss.str().length());
	// check response
	char line[2];
	const int lineLength = readLine(line, 2);
	if(atoi(line) != 0) {
		ROS_INFO("Command failed: %s", output);
	}
}

/*
 * Returns the speed in m/s the given motor is moving the robot at.
 */
float getSpeed(const char motor)
{
	// Write command
	ss.str("");
	// "get drive left/right rate"
	ss << "gd" << motor << 'r' << std::endl;
	const char* output = ss.str().c_str();
	write(tty, output, ss.str().length());
	// ROS_INFO("%s", ss.str().c_str());

	// Read response
	// Expected: max. 11 characters (-2,147,483,647) + \n
	const int LINE_LENGTH = 11;
	char line[LINE_LENGTH] = {0};
	const int lineLength = readLine(line, LINE_LENGTH);

	// We receive the interval in µs bewtween two motor monitor ticks
	const int interval = atoi(line);
	// Compute motor revolution freq (Hz) from motor tick interval (µs)
	// Filter out division by zero and "stop" state
	const double freq = (interval == 0 || interval == 1000000) ? 0 : 1000000 / interval;
	// if(motor == MOTOR_RIGHT)
		// ROS_INFO("interval %c: %i freq: %f", motor, interval, freq);
	// Return the resulting robot speed for this motor (m/s)
	return freq * WHEEL_DIAMETER * M_PI / (3.0 * WHEEL_REDUCTION);
}

void velocityCallback(const geometry_msgs::Twist& msg) {
	// Store current motor speeds for later reference
	vLeftCur   = getSpeed(MOTOR_LEFT);
	vRightCur  = getSpeed(MOTOR_RIGHT);

	// Compute the motor speeds necessary to achieve the desired linear and angular motion
	// Adapted from:
	// https://code.google.com/p/differential-drive/source/browse/nodes/twist_to_motors.py
	// self.right = 1.0 * self.dx + self.dr * self.w / 2
	// self.left = 1.0 * self.dx - self.dr * self.w / 2
	double vLeft  = msg.linear.x - msg.angular.z * WHEEL_DISTANCE / (2.0);
	double vRight = msg.linear.x + msg.angular.z * WHEEL_DISTANCE / (2.0);
	double vRotLeft = msg.angular.y;
	double vRotRight = msg.angular.y;

	// Only send new commands to the Arduino if the input actually changed
	if(vLeft == vLeftLast && vRight == vRightLast
		&& vRotLeft == vRotLeftLast && vRotRight == vRotRightLast) {
		return;
	}
	vLeftLast     = vLeft;
	vRightLast    = vRight;
	vRotLeftLast  = vRotLeft;
	vRotRightLast = vRotLeft;

	// ROS_INFO("tl: %f tr: %f z: %f", vLeft, vRight, msg.angular.z);
	// Determine rotation directions
	char dLeft  = vLeft  > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD;
	char dRight = vRight > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD;

	// Map [-MAX_DRV_SPEED, MAX_DRV_SPEED] -> [0, 1] as we've extracted the directional component
	vLeft  = vLeft  < 0 ? vLeft  * -1.0 : vLeft;
	vRight = vRight < 0 ? vRight * -1.0 : vRight;
	vLeft  = min(1.0, max(0.0, vLeft  / MAX_DRV_SPEED));
	vRight = min(1.0, max(0.0, vRight / MAX_DRV_SPEED));
	// Stop the motors when stopping
	if(vLeft < STOP_THRESHOLD) {
		dLeft = MOTOR_STOP;
	}
	if(vRight < STOP_THRESHOLD) {
		dRight = MOTOR_STOP;
	}
	// Apply!
	setDrive(MOTOR_LEFT, dLeft, vLeft);
	setDrive(MOTOR_RIGHT, dRight, vRight);

	// Wheel disc rotation
	// Extract direction
	char dRotLeft = vRotLeft > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD;
	char dRotRight = vRotRight > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD;
	// Map speeds to [0, 1]
	vRotLeft  = vRotLeft < 0 ? vRotLeft * -1.0 : vRotLeft;
	vRotRight = vRotRight < 0 ? vRotRight * -1.0 : vRotRight;
	vRotLeft  = min(1.0, max(0.0, vRotLeft  / MAX_ROT_SPEED));
	vRotRight = min(1.0, max(0.0, vRotRight / MAX_ROT_SPEED));
	if(vRotLeft < STOP_THRESHOLD) {
		dRotLeft = MOTOR_STOP;
	}
	if(vRotRight < STOP_THRESHOLD) {
		dRotRight = MOTOR_STOP;
	}
	setRotation(MOTOR_LEFT, dRotLeft, vRotLeft);
	setRotation(MOTOR_RIGHT, dRotRight, vRotRight);
}

int main(int argc, char **argv) {
	ros::init(argc, argv, "enginecontrol");
	ros::NodeHandle n;
	currentTime = ros::Time::now();
	lastTime = ros::Time::now();
	if(!initTty()) {
		return 1;
	}

	// Just to make sure we're not going anywhere...
	setDrive(MOTOR_LEFT, MOTOR_STOP);
	setDrive(MOTOR_RIGHT, MOTOR_STOP);
	setRotation(MOTOR_LEFT, MOTOR_STOP);
	setRotation(MOTOR_RIGHT, MOTOR_STOP);

	// This is correct - we're borrowing the turtle's topics
	ros::Subscriber sub = n.subscribe("cmd_vel", 1, velocityCallback);
	ROS_INFO("enginecontrol up and running.");
	ros::spin();
	close(tty);
	return 0;
}

max_issues_repo_name: hmmwv-team/hmmwv

max_forks_repo_name: hmmwv-team/hmmwv


text:
/*
 * KENLMBatch.cpp
 *
 *  Created on: 4 Nov 2015
 *      Author: hieu
 */
#include <boost/foreach.hpp>
#include <sstream>
#include <vector>

#ifdef _linux
#include <pthread.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#include "KENLMBatch.h"
#include "../Phrase.h"
#include "../Scores.h"
#include "../System.h"
#include "../PhraseBased/Hypothesis.h"
#include "../PhraseBased/Manager.h"
#include "../PhraseBased/TargetPhraseImpl.h"
#include "lm/state.hh"
#include "lm/left.hh"
#include "util/exception.hh"
#include "util/tokenize_piece.hh"
#include "util/string_stream.hh"
#include "../legacy/FactorCollection.h"

using namespace std;

namespace Moses2
{

struct KenLMState: public FFState {
  lm::ngram::State state;
  virtual size_t hash() const {
    size_t ret = hash_value(state);
    return ret;
  }
  virtual bool operator==(const FFState& o) const {
    const KenLMState &other = static_cast<const KenLMState &>(o);
    bool ret = state == other.state;
    return ret;
  }

  virtual std::string ToString() const {
    stringstream ss;
    for (size_t i = 0; i < state.Length(); ++i) {
      ss << state.words[i] << " ";
    }
    return ss.str();
  }

};

/////////////////////////////////////////////////////////////////
class MappingBuilder: public lm::EnumerateVocab
{
public:
  MappingBuilder(FactorCollection &factorCollection, System &system,
                 std::vector<lm::WordIndex> &mapping) :
    m_factorCollection(factorCollection), m_system(system), m_mapping(mapping) {
  }

  void Add(lm::WordIndex index, const StringPiece &str) {
    std::size_t factorId = m_factorCollection.AddFactor(str, m_system, false)->GetId();
    if (m_mapping.size() <= factorId) {
      // 0 is <unk> :-)
      m_mapping.resize(factorId + 1);
    }
    m_mapping[factorId] = index;
  }

private:
  FactorCollection &m_factorCollection;
  std::vector<lm::WordIndex> &m_mapping;
  System &m_system;
};

/////////////////////////////////////////////////////////////////
KENLMBatch::KENLMBatch(size_t startInd, const std::string &line)
  :StatefulFeatureFunction(startInd, line)
  ,m_numHypos(0)
{
  cerr << "KENLMBatch::KENLMBatch" << endl;
  ReadParameters();
}

KENLMBatch::~KENLMBatch()
{
  // TODO Auto-generated destructor stub
}

void KENLMBatch::Load(System &system)
{
  cerr << "KENLMBatch::Load" << endl;
  FactorCollection &fc = system.GetVocab();

  m_bos = fc.AddFactor(BOS_, system, false);
  m_eos = fc.AddFactor(EOS_, system, false);

  lm::ngram::Config config;
  config.messages = NULL;

  FactorCollection &collection = system.GetVocab();
  MappingBuilder builder(collection, system, m_lmIdLookup);
  config.enumerate_vocab = &builder;
  config.load_method = m_load_method;

  m_ngram.reset(new Model(m_path.c_str(), config));
}

FFState* KENLMBatch::BlankState(MemPool &pool, const System &sys) const
{
  KenLMState *ret = new (pool.Allocate<KenLMState>()) KenLMState();
  return ret;
}

//! return the state associated with the empty hypothesis for a given sentence
void KENLMBatch::EmptyHypothesisState(FFState &state, const ManagerBase &mgr,
                                      const InputType &input, const Hypothesis &hypo) const
{
  KenLMState &stateCast = static_cast<KenLMState&>(state);
  stateCast.state = m_ngram->BeginSentenceState();
}

void KENLMBatch::EvaluateInIsolation(MemPool &pool, const System &system,
                                     const Phrase<Moses2::Word> &source, const TargetPhraseImpl &targetPhrase, Scores &scores,
                                     SCORE &estimatedScore) const
{
  // contains factors used by this LM
  float fullScore, nGramScore;
  size_t oovCount;

  CalcScore(targetPhrase, fullScore, nGramScore, oovCount);

  float estimateScore = fullScore - nGramScore;

  bool GetLMEnableOOVFeature = false;
  if (GetLMEnableOOVFeature) {
    float scoresVec[2], estimateScoresVec[2];
    scoresVec[0] = nGramScore;
    scoresVec[1] = oovCount;
    scores.PlusEquals(system, *this, scoresVec);

    estimateScoresVec[0] = estimateScore;
    estimateScoresVec[1] = 0;
    SCORE weightedScore = Scores::CalcWeightedScore(system, *this,
                          estimateScoresVec);
    estimatedScore += weightedScore;
  } else {
    scores.PlusEquals(system, *this, nGramScore);

    SCORE weightedScore = Scores::CalcWeightedScore(system, *this,
                          estimateScore);
    estimatedScore += weightedScore;
  }
}

void KENLMBatch::EvaluateInIsolation(MemPool &pool, const System &system, const Phrase<SCFG::Word> &source,
                                     const TargetPhrase<SCFG::Word> &targetPhrase, Scores &scores,
                                     SCORE &estimatedScore) const
{
}

void KENLMBatch::EvaluateWhenApplied(const ManagerBase &mgr,
                                     const Hypothesis &hypo, const FFState &prevState, Scores &scores,
                                     FFState &state) const
{
  KenLMState &stateCast = static_cast<KenLMState&>(state);

  const System &system = mgr.system;

  const lm::ngram::State &in_state =
    static_cast<const KenLMState&>(prevState).state;

  if (!hypo.GetTargetPhrase().GetSize()) {
    stateCast.state = in_state;
    return;
  }

  const std::size_t begin = hypo.GetCurrTargetWordsRange().GetStartPos();
  //[begin, end) in STL-like fashion.
  const std::size_t end = hypo.GetCurrTargetWordsRange().GetEndPos() + 1;
  const std::size_t adjust_end = std::min(end, begin + m_ngram->Order() - 1);

  std::size_t position = begin;
  Model::State aux_state;
  Model::State *state0 = &stateCast.state, *state1 = &aux_state;

  float score = m_ngram->Score(in_state, TranslateID(hypo.GetWord(position)),
                               *state0);
  ++position;
  for (; position < adjust_end; ++position) {
    score += m_ngram->Score(*state0, TranslateID(hypo.GetWord(position)),
                            *state1);
    std::swap(state0, state1);
  }

  if (hypo.GetBitmap().IsComplete()) {
    // Score end of sentence.
    std::vector<lm::WordIndex> indices(m_ngram->Order() - 1);
    const lm::WordIndex *last = LastIDs(hypo, &indices.front());
    score += m_ngram->FullScoreForgotState(&indices.front(), last,
                                           m_ngram->GetVocabulary().EndSentence(), stateCast.state).prob;
  } else if (adjust_end < end) {
    // Get state after adding a long phrase.
    std::vector<lm::WordIndex> indices(m_ngram->Order() - 1);
    const lm::WordIndex *last = LastIDs(hypo, &indices.front());
    m_ngram->GetState(&indices.front(), last, stateCast.state);
  } else if (state0 != &stateCast.state) {
    // Short enough phrase that we can just reuse the state.
    stateCast.state = *state0;
  }

  score = TransformLMScore(score);

  bool OOVFeatureEnabled = false;
  if (OOVFeatureEnabled) {
    std::vector<float> scoresVec(2);
    scoresVec[0] = score;
    scoresVec[1] = 0.0;
    scores.PlusEquals(system, *this, scoresVec);
  } else {
    scores.PlusEquals(system, *this, score);
  }
}

void KENLMBatch::CalcScore(const Phrase<Moses2::Word> &phrase, float &fullScore,
                           float &ngramScore, std::size_t &oovCount) const
{
  fullScore = 0;
  ngramScore = 0;
  oovCount = 0;

  if (!phrase.GetSize()) return;

  lm::ngram::ChartState discarded_sadly;
  lm::ngram::RuleScore<Model> scorer(*m_ngram, discarded_sadly);

  size_t position;
  if (m_bos == phrase[0][m_factorType]) {
    scorer.BeginSentence();
    position = 1;
  } else {
    position = 0;
  }

  size_t ngramBoundary = m_ngram->Order() - 1;

  size_t end_loop = std::min(ngramBoundary, phrase.GetSize());
  for (; position < end_loop; ++position) {
    const Word &word = phrase[position];
    lm::WordIndex index = TranslateID(word);
    scorer.Terminal(index);
    if (!index) ++oovCount;
  }
  float before_boundary = fullScore + scorer.Finish();
  for (; position < phrase.GetSize(); ++position) {
    const Word &word = phrase[position];
    lm::WordIndex index = TranslateID(word);
    scorer.Terminal(index);
    if (!index) ++oovCount;
  }
  fullScore += scorer.Finish();

  ngramScore = TransformLMScore(fullScore - before_boundary);
  fullScore = TransformLMScore(fullScore);
}

// Convert last words of hypothesis into vocab ids, returning an end pointer.
lm::WordIndex *KENLMBatch::LastIDs(const Hypothesis &hypo,
                                   lm::WordIndex *indices) const
{
  lm::WordIndex *index = indices;
  lm::WordIndex *end = indices + m_ngram->Order() - 1;
  int position = hypo.GetCurrTargetWordsRange().GetEndPos();
  for (;; ++index, --position) {
    if (index == end) return index;
    if (position == -1) {
      *index = m_ngram->GetVocabulary().BeginSentence();
      return index + 1;
    }
    *index = TranslateID(hypo.GetWord(position));
  }
}

void KENLMBatch::SetParameter(const std::string& key,
                              const std::string& value)
{
  //cerr << "key=" << key << " " << value << endl;
  if (key == "path") {
    m_path = value;
  } else if (key == "order") {
    // ignore
  } else if (key == "factor") {
    m_factorType = Scan<FactorType>(value);
  } else if (key == "lazyken") {
    m_load_method =
      boost::lexical_cast<bool>(value) ?
      util::LAZY : util::POPULATE_OR_READ;
  } else if (key == "load") {
    if (value == "lazy") {
      m_load_method = util::LAZY;
    } else if (value == "populate_or_lazy") {
      m_load_method = util::POPULATE_OR_LAZY;
    } else if (value == "populate_or_read" || value == "populate") {
      m_load_method = util::POPULATE_OR_READ;
    } else if (value == "read") {
      m_load_method = util::READ;
    } else if (value == "parallel_read") {
      m_load_method = util::PARALLEL_READ;
    } else {
      UTIL_THROW2("Unknown KenLM load method " << value);
    }
  } else {
    StatefulFeatureFunction::SetParameter(key, value);
  }

  //cerr << "SetParameter done" << endl;
}

void KENLMBatch::EvaluateWhenAppliedBatch(
  const Batch &batch) const
{
  {
    // write lock
    boost::unique_lock<boost::shared_mutex> lock(m_accessLock);
    m_batches.push_back(&batch);
    m_numHypos += batch.size();
  }
  //cerr << "m_numHypos=" << m_numHypos << endl;

  if (m_numHypos > 0) {
    // process batch
    EvaluateWhenAppliedBatch();

    m_batches.clear();
    m_numHypos = 0;

    m_threadNeeded.notify_all();
  } else {
    boost::mutex::scoped_lock lock(m_mutex);
    m_threadNeeded.wait(lock);
  }
}

void KENLMBatch::EvaluateWhenAppliedBatch() const
{
  BOOST_FOREACH(const Batch *batch, m_batches) {
    //cerr << "batch=" << batch->size() << endl;
    BOOST_FOREACH(Hypothesis *hypo, *batch) {
      hypo->EvaluateWhenApplied(*this);
    }
  }
}

void KENLMBatch::EvaluateWhenApplied(const SCFG::Manager &mgr,
                                     const SCFG::Hypothesis &hypo, int featureID, Scores &scores,
                                     FFState &state) const
{
  UTIL_THROW2("Not implemented");
}

}


text:
//
// Copyright (c) 2020 Ryan Janson (ryand.janson@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/ryanjanson/deflate
//

#ifndef BOOST_DEFLATE_EASY_HPP
#define BOOST_DEFLATE_EASY_HPP

#include <boost/deflate/config.hpp>
#include <boost/deflate/deflate_stream.hpp>
#include <boost/deflate/inflate_stream.hpp>
#include <string>
#include <vector>

namespace boost {
namespace deflate {

BOOST_DEFLATE_DECL
optional<std::string> easy_compress(string_view in, wrap wrapping = boost::deflate::wrap::none);

BOOST_DEFLATE_DECL
optional<std::string> easy_uncompress(string_view in, wrap wrapping = boost::deflate::wrap::none);

}
}

#endif //BOOST_DEFLATE_EASY_HPP

ext: hpp

max_stars_repo_name: ryanjanson/deflate

max_issues_repo_name: ryanjanson/deflate

max_forks_repo_name: ryanjanson/deflate


text:
/**  \file ublas_extra.hpp \brief Extra functions for Ublas library */
/*
-----------------------------------------------------------------------------
   Copyright (C) 2011 Ruben Martinez-Cantin <rmcantin@unizar.es>

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

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

   You should have received a copy of the GNU Affero General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
-----------------------------------------------------------------------------
*/

#ifndef __UBLAS_EXTRA_HPP__
#define __UBLAS_EXTRA_HPP__

#include <typeinfo>
#include <boost/numeric/ublas/vector.hpp>

namespace bayesopt
{
  /// Extra utils: math functions, ublas helpers, etc.
  namespace utils
  {
    template<class V, class D>
    void append(V& vect, D element)
    {
      typedef typename V::value_type VD;
      assert(typeid(VD) == typeid(D));

      // This method is super inefficient but there seems to be the uBlas style.
      const size_t size = vect.size();
      vect.resize(size+1,true);
      vect(size) = element;
    };

    template<class V, class I>
    void erase(V& vect, I begin)
    {
      typedef typename V::iterator VI;
      assert(typeid(VI) == typeid(I));

      for(VI it = begin; it != vect.end()-1; ++it)
	{
	  *it = *(it+1);
	}
      vect.resize(vect.size()-1);
    };

    template<class M>
    void erase_column(M& mat, size_t pos)
    {
      for(size_t i = pos; i < mat.size2()-1; ++i)
	{
	  column(mat,i) = column(mat,i+1);
	}
      mat.resize(mat.size1(),mat.size2()-1);
    };

    template<class M, class V>
    void add_to_diagonal(M& mat, const V& vec)
    {
      assert(mat.size1()==mat.size2());
      assert(mat.size1()==vec.size());
      const size_t ll = vec.size();
      for(size_t ii = 0; ii < ll; ++ii)
	{
	  mat(ii,ii) += vec(ii);
	}
    };

    boost::numeric::ublas::vector<double> array2vector(const double array[],
						       const size_t n);

  } //  namespace utils
} //namespace bayesopt

#endif

max_stars_repo_name: pchrapka/brain-modelling

max_issues_repo_name: pchrapka/brain-modelling

max_forks_repo_name: pchrapka/brain-modelling


text:
#include <benchmark/benchmark.h>

#include <sstream>
#include <string>
#include <string_view>
#include <boost/crc.hpp>
#include <fmt/format.h>

namespace openstudio::detail {
    bool checksumIgnore(char c) {
      // ignore all whitespace
      //bool result = (c == ' ' || c == '\t' || c == '\n' ||  c == '\v' || c == '\f' || c == '\r');

      // ignore just line feed
      bool result = (c == '\r');

      return result;
    }
}  // namespace detail

namespace openstudio_old {
  /// return 8 character hex checksum of istream
  std::string checksum(std::istream& is) {
    boost::crc_32_type crc;
    do {
      const std::streamsize n = 1024;
      char buffer[n];
      is.read(buffer, n);
      std::streamsize readSize = is.gcount();
      //crc.process_bytes(buffer, readSize);

      size_t stringSize = static_cast<size_t>(readSize);
      std::string str(buffer, stringSize);
      str.erase(std::remove_if(str.begin(), str.end(), openstudio::detail::checksumIgnore), str.end());
      stringSize = str.size();

      crc.process_bytes(str.c_str(), stringSize);
    } while (is);

    std::stringstream ss;
    ss << std::hex << std::uppercase << crc.checksum();
    std::string result = "00000000";
    std::string checksum = ss.str();
    result.replace(8 - checksum.size(), checksum.size(), checksum);

    return result;
  }

  /// return 8 character hex checksum of string
  std::string checksum(const std::string& s) {
    std::stringstream ss(s);
    return checksum(ss);
  }

}

namespace openstudio_new {

  /// return 8 character hex checksum of istream
  std::string checksum(std::istream& is) {
    boost::crc_32_type crc;
    do {
      const std::streamsize n = 1024;
      char buffer[n];
      is.read(buffer, n);
      std::streamsize readSize = is.gcount();
      //crc.process_bytes(buffer, readSize);

      size_t stringSize = static_cast<size_t>(readSize);
      std::string str(buffer, stringSize);
      str.erase(std::remove_if(str.begin(), str.end(), openstudio::detail::checksumIgnore), str.end());
      stringSize = str.size();

      crc.process_bytes(str.c_str(), stringSize);
    } while (is);

    return fmt::format("{:0>8X}", crc.checksum());
  }

  /// return 8 character hex checksum of string
  std::string checksum(const std::string& s) {
    std::stringstream ss(s);
    return checksum(ss);
  }

   /// return 8 character hex checksum of string
  std::string checksum_direct(std::string s) {
    s.erase(std::remove_if(s.begin(), s.end(), openstudio::detail::checksumIgnore), s.end());
    boost::crc_32_type crc;
    crc.process_bytes(s.data(), s.length());
    return fmt::format("{:0>8X}", crc.checksum());
  }

  std::string checksum_direct_const(const std::string& s) {
    std::string strCopy(s);
    strCopy.erase(std::remove_if(strCopy.begin(), strCopy.end(), openstudio::detail::checksumIgnore), strCopy.end());
    boost::crc_32_type crc;
    crc.process_bytes(strCopy.data(), strCopy.length());
    return fmt::format("{:0>8X}", crc.checksum());
  }
}

std::string makeTestStr(size_t len) {
    constexpr std::string_view testStr = "THIS is a quite long string, \r\nWith some newlines and co.\n";

    auto result = std::string(len, '\0');
    std::generate_n(begin(result), len, [&testStr, i = 0] () mutable { return testStr[i++ %  testStr.size()]; });
    // fmt::print("{}, {}", result.size(), result);
    return result;
}

// constexpr auto testStr = "this is a quite long string\rwith some newlines and co \nthis is a quite long string\rwith some newlines and co \nthis is a quite long string\rwith some newlines and co \nthis is a quite long string\rwith some newlines and co \nthis is a quite long string\rwith some newlines and co \nthis is a quite long string\rwith some newlines and co \nthis is a quite long string\rwith some newlines and co \nthis is a quite long string\rwith some newlines and co \nthis is a quite long string\rwith some newlines and co \nthis is a quite long string\rwith some newlines and co \n";

static void BM_CheckSumOld(benchmark::State& state) {
  auto testStr = makeTestStr(state.range(0));
  // fmt::print("Old impl: {}", s);

  for (auto _ : state) {
     auto s = openstudio_old::checksum(testStr);
     benchmark::DoNotOptimize(s);
  }
  state.SetComplexityN(state.range(0));

}

static void BM_CheckSumNew(benchmark::State& state) {

  auto testStr = makeTestStr(state.range(0));
  auto checkSumOld = openstudio_old::checksum(testStr);
  auto checkSumNew = openstudio_new::checksum(testStr);
  assert(checkSumNew == checkSumOld);
  // fmt::print("New impl: {}", s);

  for (auto _ : state) {
     auto s = openstudio_new::checksum(testStr);
     benchmark::DoNotOptimize(s);
  }

  state.SetComplexityN(state.range(0));
}

static void BM_CheckSumNewDirect(benchmark::State& state) {

  auto testStr = makeTestStr(state.range(0));
  auto checkSumOld = openstudio_old::checksum(testStr);
  auto checkSumNew = openstudio_new::checksum_direct(testStr);
  assert(checkSumNew == checkSumOld);
  // fmt::print("New impl: {}", s);

  for (auto _ : state) {
     auto s = openstudio_new::checksum_direct(testStr);
     benchmark::DoNotOptimize(s);
  }

  state.SetComplexityN(state.range(0));
}

BENCHMARK(BM_CheckSumOld)->RangeMultiplier(4)->Range(8, 8 << 16)->Complexity();
BENCHMARK(BM_CheckSumNew)->RangeMultiplier(4)->Range(8, 8 << 16)->Complexity();
BENCHMARK(BM_CheckSumNewDirect)->RangeMultiplier(4)->Range(8, 8 << 16)->Complexity();

max_stars_repo_name: jmarrec/CppBenchmarks

max_issues_repo_name: jmarrec/CppBenchmarks

max_forks_repo_name: jmarrec/CppBenchmarks


text:
#include "ge/rocket_document_asset.hpp"
#include "ge/rocket_subsystem.hpp"

#include "ge/json_helper.hpp"
#include "ge/rocket_font_asset.hpp"

#include <boost/filesystem.hpp>

using namespace ge;

std::shared_ptr<Rocket::Core::ElementDocument> rocket_document_asset::load_asset(
	asset_manager& manager, const char* asset_name, const char* filepath,
	const nlohmann::json& json_data)
{
	using namespace std::string_literals;

	auto rml_file_iter = json_data.find("rml_file");
	if (rml_file_iter == json_data.end()) {
		logger->error("Rocket document asset "s + asset_name + " located at " + filepath +
					  " didn't specifiy a rml_file field. Document will not be loaded. See "
					  "https://gentlemans.github.io/gentlemanly_engine/"
					  "structge_1_1rocket__document__asset.html for more details.");

		return nullptr;
	}
	std::string doc = *rml_file_iter;

	std::string path = boost::filesystem::absolute(doc, filepath).string();

#ifndef _NDEBUG
	// make sure the path exists
	if (!boost::filesystem::is_regular_file(path)) {
		logger->error("The rml_file specified in the rocket document asset "s + asset_name +
					  " located at " + filepath +
					  " doesn't exist. The full path was evaluated to be " + path);
	}
#endif

	// load fonts
	auto fonts_iter = json_data.find("required_fonts");
	if (fonts_iter != json_data.end() && fonts_iter->is_array()) {
		for (const std::string& font_name : *fonts_iter) {
			manager.get_asset<rocket_font_asset>(font_name.c_str());
		}
	}

	// get rocket subsystem
	auto rocketsub = manager.m_runtime->get_subsystem<rocket_subsystem>();
	if (!rocketsub) {
		logger->error(
			"Cannot load a rocket document without a rocket_subsystem loaded. Failing to load "
			"asset...");
		return nullptr;
	}

	return std::shared_ptr<Rocket::Core::ElementDocument>(
		rocketsub->m_context->LoadDocument(path.c_str()), [](Rocket::Core::ElementDocument*) {});
}

max_stars_repo_name: gentlemans/gentlemanly-engine

max_issues_repo_name: gentlemans/gentlemanly-engine

max_forks_repo_name: gentlemans/gentlemanly-engine


text: #include <boost/pending/property_serialize.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include "Utility.h"
#include <string>
#include <map>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cctype>
#include <stdlib.h>
#include <stdio.h>
#if	!defined(WIN32)
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <pwd.h>
#endif
#include <thread>
#include <iomanip>
#include <boost/asio/ip/host_name.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/algorithm/string.hpp>

using namespace std;

Utility::Utility()
{
}

Utility::~Utility()
{
}

std::map<std::string, int> Utility::getProcessList()
{
	const static char fname[] = "Utility::getProcessList() ";

	std::map<std::string, int> processList;
#if	!defined(WIN32)
	DIR* dir = opendir("/proc/");
	if (dir != NULL)
	{
		struct stat fstat;
		struct dirent* rent = NULL;
		while ((rent = readdir(dir)))
		{
			try
			{
				if (rent->d_type == DT_DIR && isNumber(rent->d_name))
				{
					string path = "/proc/";
					path += rent->d_name;
					path += "/cmdline";

					if (stat(path.c_str(), &fstat)) continue;
					if (S_ISDIR(fstat.st_mode)) continue;

					ifstream file(path.c_str());
					if (file.is_open() && !file.eof() && !file.fail() && !file.bad())
					{
						char maxCmdStrBuf[1024];
						memset(maxCmdStrBuf, 0, sizeof(maxCmdStrBuf));
						size_t getSize = file.get(maxCmdStrBuf, 1023, '\r').gcount();
						file.close();
						if (getSize > 0 && !file.fail() && !file.bad())
						{
							// Parse cmdline : https://stackoverflow.com/questions/1585989/how-to-parse-proc-pid-cmdline
							for (size_t i = 0; i < getSize; i++)
							{
								if (maxCmdStrBuf[i] == '\0') maxCmdStrBuf[i] = ' ';
								if (maxCmdStrBuf[i] == '\r') maxCmdStrBuf[i] = '\0';
							}
							std::string str = maxCmdStrBuf;
							str = stdStringTrim(str);
							processList[str] = atoi(rent->d_name);
						}
					}
				}
			}
			catch (const std::exception& e)
			{
				LOG(ERROR) << fname << "ERROR:" << e.what() << endl;
			}
			catch (...)
			{
				LOG(ERROR) << fname << "ERROR:" << "unknown exception" << endl;
			}
		}
		closedir(dir);
	}
#endif

	//for_each(processList.begin(), processList.end(), [](std::map<std::string, int>::reference p) {cout << "Process:[" << p.second << "]" << p.first << endl; });

	return processList;
}

bool Utility::isNumber(string s)
{
	return !s.empty() && std::find_if(s.begin(), s.end(), [](char c) { return !std::isdigit(c); }) == s.end();
}

void Utility::stringReplace(std::string & strBase, const std::string strSrc, const std::string strDst)
{
	std::string::size_type position = 0;
	std::string::size_type srcLen = strSrc.size();
	std::string::size_type dstLen = strDst.size();

	while ((position = strBase.find(strSrc, position)) != std::string::npos)
	{
		strBase.replace(position, srcLen, strDst);
		position += dstLen;
	}
}

std::string Utility::stdStringTrim(const std::string & str)
{
	char *line = const_cast <char *> (str.c_str());
	// trim the line on the left and on the right
	size_t len = str.length();
	size_t start = 0;
	while (isspace(*line))
	{
		++line;
		--len;
		++start;
	}
	while (len > 0 && isspace(line[len - 1]))
	{
		--len;
	}
	return len >= start ? str.substr(start, len) : str.substr(start);
}

std::string Utility::getSelfFullPath()
{
	#define MAXBUFSIZE 1024
	int count = 0;
	char buf[MAXBUFSIZE] = { 0 };
#if	!defined(WIN32)
	count = (int)readlink("/proc/self/exe", buf, MAXBUFSIZE);
#endif
	if (count < 0 || count >= MAXBUFSIZE)
	{
		printf("Failed\n");
		return buf;
	}
	else
	{
		buf[count] = '\0';
		return buf;
	}
}

void SignalHandle(const char* data, int size)
{
	std::string str = std::string(data, size);
	LOG(ERROR) << str;
}

void Utility::initLogging(const char* arg0)
{
	google::InitGoogleLogging(arg0);
#if	!defined(WIN32)
	string logDir;
	//https://linux.die.net/man/3/get_current_dir_name
	char* bufferPath = get_current_dir_name();
	if (0 != bufferPath)
	{
		logDir = bufferPath;
	}
	else
	{
		logDir = "/tmp";
	}

	logDir += "/log";
	if (access(logDir.c_str(), 0) != 0)
	{
		if (mkdir(logDir.c_str(), 0757) != 0)
		{
			logDir = ".";
		}
	}
	FLAGS_log_dir = logDir;
#else
	FLAGS_log_dir = ".";
#endif
	google::SetStderrLogging(google::GLOG_INFO);
	//std::system("mkdir -p log");
	google::SetLogDestination(google::INFO, "log/INFO.");
	google::SetLogDestination(google::WARNING, "log/WARN.");
	google::SetLogDestination(google::ERROR, "log/ERR.");
	auto logName = string("appmg.") + boost::asio::ip::host_name() + ".";
	google::SetLogFilenameExtension(logName.c_str());
	google::InstallFailureSignalHandler();
	google::InstallFailureWriter(&SignalHandle);
	FLAGS_stop_logging_if_full_disk = true;		// If disk is full
	FLAGS_max_log_size = 100;					// Set max log file size(1 GB)
	FLAGS_logbufsecs = 0;
}

unsigned long long Utility::getThreadId()
{
	std::ostringstream oss;
	oss << std::this_thread::get_id();
	std::string stid = oss.str();
	return std::stoull(stid);
}

std::chrono::system_clock::time_point Utility::convertStr2Time(const std::string & strTime)
{
	struct tm tm = { 0 };
	std::istringstream ss(strTime);
	// ss.imbue(std::locale("de_DE.utf-8"));
	ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");
	if (ss.fail())
	{
		string msg = "error when convert string to time :";
		msg += strTime;
		throw std::invalid_argument(msg);
	}
	return std::chrono::system_clock::from_time_t(std::mktime(&tm));
}

std::string Utility::convertTime2Str(const std::chrono::system_clock::time_point & time)
{
	// https://en.cppreference.com/w/cpp/io/manip/put_time
	auto timet = std::chrono::system_clock::to_time_t(time);
	std::tm tm = *std::localtime(&timet);
	std::stringstream ss;
	ss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S");
	return ss.str();
}

std::chrono::system_clock::time_point Utility::convertStr2DayTime(const std::string & strTime)
{
	struct tm tm = { 0 };
	std::istringstream ss(strTime);
	// ss.imbue(std::locale("de_DE.utf-8"));
	ss >> std::get_time(&tm, "%H:%M:%S");
	if (ss.fail())
	{
		string msg = "error when convert string to time :";
		msg += strTime;
		throw std::invalid_argument(msg);
	}
	// Give a fixed date.
	tm.tm_year = 2000 - 1900;
	tm.tm_mon = 1;
	tm.tm_mday = 17;
	return std::chrono::system_clock::from_time_t(std::mktime(&tm));
}

std::string Utility::convertDayTime2Str(const std::chrono::system_clock::time_point & time)
{
	// https://en.cppreference.com/w/cpp/io/manip/put_time
	auto timet = std::chrono::system_clock::to_time_t(time);
	std::tm tm = *std::localtime(&timet);
	std::stringstream ss;
	ss << std::put_time(&tm, "%H:%M:%S");
	return ss.str();
}

std::string Utility::getSystemPosixTimeZone()
{
	// https://stackoverflow.com/questions/2136970/how-to-get-the-current-time-zone/28259774#28259774
	struct tm local_tm;
	time_t cur_time = 0; // time(NULL);
	localtime_r(&cur_time, &local_tm);

	std::stringstream ss;
	ss << std::put_time(&local_tm, "%Z%z");
	auto str = ss.str();

	// remove un-used zero post-fix :
	// CST+0800  => CST+08
	auto len = str.length();
	for (size_t i = len - 1; i > 0; i--)
	{
		if (str[i] == '0')
		{
			str[i] = '\0';
		}
		else
		{
			str = str.c_str();
			break;
		}
	}
	return str;
}

std::string Utility::encode64(const std::string & val)
{
	using namespace boost::archive::iterators;
	using It = base64_from_binary<transform_width<std::string::const_iterator, 6, 8>>;
	auto tmp = std::string(It(std::begin(val)), It(std::end(val)));
	return tmp.append((3 - val.size() % 3) % 3, '=');
}

std::string Utility::decode64(const std::string & val)
{
	using namespace boost::archive::iterators;
	using It = transform_width<binary_from_base64<std::string::const_iterator>, 8, 6>;
	return boost::algorithm::trim_right_copy_if(std::string(It(std::begin(val)), It(std::end(val))), [](char c) {
		return c == '\0';
	});
}

void Utility::splitString(const std::string & source, std::vector<std::string>& result, const std::string & splitFlag)
{
	std::string::size_type pos1, pos2;
	pos2 = source.find(splitFlag);
	pos1 = 0;
	while (std::string::npos != pos2)
	{
		string str = stdStringTrim(source.substr(pos1, pos2 - pos1));
		if (str.length() > 0) result.push_back(str);

		pos1 = pos2 + splitFlag.size();
		pos2 = source.find(splitFlag, pos1);
	}
	if (pos1 != source.length())
	{
		string str = stdStringTrim(source.substr(pos1));
		if (str.length() > 0) result.push_back(str);
	}
}

bool Utility::startWith(const std::string & str, std::string head)
{
	if (str.length() >= head.length())
	{
		return (str.compare(0, head.size(), head) == 0);
	}
	return false;
}

bool Utility::getUid(std::string userName, long& uid, long& groupid)
{
	bool rt = false;
	struct passwd pwd;
	struct passwd *result = NULL;
	static auto bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
	if (bufsize == -1) bufsize = 16384;
	std::shared_ptr<char> buff(new char[bufsize], std::default_delete<char[]>());
	getpwnam_r(userName.c_str(), &pwd, buff.get(), bufsize, &result);
	if (result)
	{
		uid = pwd.pw_uid;
		groupid = pwd.pw_gid;
		rt = true;
	}
	else
	{
		LOG(ERROR) << "User does not exist: <" << userName << ">." << std::endl;
	}
	return rt;
}

void Utility::getEnvironmentSize(const std::map<std::string, std::string>& envMap, int & totalEnvSize, int & totalEnvArgs)
{
	// get env size
	if (!envMap.empty())
	{
		auto it = envMap.begin();
		while (it != envMap.end())
		{
			totalEnvSize += (int)(it->first.length() + it->second.length() + 2); // add for = and terminator
			totalEnvArgs++;
			it++;
		}
	}

	// initialize our environment size estimates
	const int numEntriesConst = 256;
	const int bufferSizeConst = 4 * 1024;

	totalEnvArgs += numEntriesConst;
	totalEnvSize += bufferSizeConst;
}

max_stars_repo_name: julyhurt/application-manager

max_issues_repo_name: julyhurt/application-manager

max_forks_repo_name: julyhurt/application-manager


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

#include "yb/tablet/transaction_participant.h"

#include <mutex>

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/mem_fun.hpp>

#include <boost/optional/optional.hpp>

#include <boost/uuid/uuid_io.hpp>
#include <boost/scope_exit.hpp>

#include "yb/rocksdb/write_batch.h"

#include "yb/client/transaction_rpc.h"

#include "yb/docdb/docdb_rocksdb_util.h"
#include "yb/docdb/docdb.h"

#include "yb/rpc/rpc.h"

#include "yb/tserver/tserver_service.pb.h"

#include "yb/util/locks.h"
#include "yb/util/monotime.h"

using namespace std::literals;
using namespace std::placeholders;

DEFINE_uint64(transaction_delay_status_reply_usec_in_tests, 0,
              "For tests only. Delay handling status reply by specified amount of usec.");

namespace yb {
namespace tablet {

namespace {

// Utility class to execute actions with specified delay.
class Delayer {
 public:
  void Delay(MonoTime when, std::function<void()> action) {
    {
      std::lock_guard<std::mutex> lock(mutex_);
      if (!thread_.joinable()) {
        thread_ = std::thread([this] {
          Execute();
        });
      }
      queue_.emplace_back(when, std::move(action));
      cond_.notify_one();
    }
  }

  ~Delayer() {
    {
      std::lock_guard<std::mutex> lock(mutex_);
      if (!thread_.joinable()) {
        return;
      }
      stop_ = true;
      cond_.notify_one();
    }
    thread_.join();
  }
 private:
  void Execute() {
    std::vector<std::function<void()>> actions;
    std::unique_lock<std::mutex> lock(mutex_);
    while (!stop_) {
      if (!queue_.empty()) {
        auto now = MonoTime::Now();
        auto it = queue_.begin();
        while (it != queue_.end() && it->first <= now) {
          actions.push_back(std::move(it->second));
          ++it;
        }
        if (it != queue_.begin()) {
          queue_.erase(queue_.begin(), it);
          lock.unlock();
          BOOST_SCOPE_EXIT(&lock, &actions) {
            actions.clear();
            lock.lock();
          } BOOST_SCOPE_EXIT_END;
          for (auto& action : actions) {
            action();
          }
        } else {
          cond_.wait_until(lock, queue_.front().first.ToSteadyTimePoint());
        }
      } else {
        cond_.wait(lock);
      }
    }
  }

  std::mutex mutex_;
  std::condition_variable cond_;
  std::thread thread_;
  bool stop_ = false;
  std::deque<std::pair<MonoTime, std::function<void()>>> queue_;
};

class RunningTransaction {
 public:
  RunningTransaction(TransactionMetadata metadata,
                     rpc::Rpcs* rpcs,
                     TransactionParticipantContext* context,
                     std::atomic<int64_t>* request_serial)
      : metadata_(std::move(metadata)),
        rpcs_(*rpcs),
        context_(*context),
        request_serial_(request_serial),
        get_status_handle_(rpcs->InvalidHandle()),
        abort_handle_(rpcs->InvalidHandle()) {
  }

  ~RunningTransaction() {
    rpcs_.Abort({&get_status_handle_, &abort_handle_});
  }

  const TransactionId& id() const {
    return metadata_.transaction_id;
  }

  const TransactionMetadata& metadata() const {
    return metadata_;
  }

  HybridTime local_commit_time() const {
    return local_commit_time_;
  }

  void SetLocalCommitTime(HybridTime time) {
    local_commit_time_ = time;
  }

  void RequestStatusAt(client::YBClient* client,
                       const StatusRequest& request,
                       std::unique_lock<std::mutex>* lock) const {
    if (last_known_status_hybrid_time_ > HybridTime::kMin) {
      auto transaction_status =
          GetStatusAt(request.global_limit_ht, last_known_status_hybrid_time_, last_known_status_);
      // If we don't have status at global_limit_ht, then we should request updated status.
      if (transaction_status) {
        lock->unlock();
        request.callback(
            TransactionStatusResult{*transaction_status, last_known_status_hybrid_time_});
        return;
      }
    }
    bool was_empty = status_waiters_.empty();
    status_waiters_.push_back(request);
    if (!was_empty) {
      return;
    }
    lock->unlock();
    SendStatusRequest(client, lock->mutex());
  }

  void Abort(client::YBClient* client,
             TransactionStatusCallback callback,
             std::unique_lock<std::mutex>* lock) const {
    bool was_empty = abort_waiters_.empty();
    abort_waiters_.push_back(std::move(callback));
    lock->unlock();
    if (!was_empty) {
      return;
    }
    tserver::AbortTransactionRequestPB req;
    req.set_tablet_id(metadata_.status_tablet);
    req.set_transaction_id(metadata_.transaction_id.begin(), metadata_.transaction_id.size());
    req.set_propagated_hybrid_time(context_.Now().ToUint64());
    rpcs_.RegisterAndStart(
        client::AbortTransaction(
            TransactionRpcDeadline(),
            nullptr /* tablet */,
            client,
            &req,
            std::bind(&RunningTransaction::AbortReceived, this, _1, _2, lock->mutex())),
        &abort_handle_);
  }

 private:
  static boost::optional<TransactionStatus> GetStatusAt(
      HybridTime time,
      HybridTime last_known_status_hybrid_time,
      TransactionStatus last_known_status) {
    switch (last_known_status) {
      case TransactionStatus::ABORTED:
        return TransactionStatus::ABORTED;
      case TransactionStatus::COMMITTED:
        return last_known_status_hybrid_time > time
            ? TransactionStatus::PENDING
            : TransactionStatus::COMMITTED;
      case TransactionStatus::PENDING:
        if (last_known_status_hybrid_time >= time) {
          return TransactionStatus::PENDING;
        }
        return boost::none;
      default:
        FATAL_INVALID_ENUM_VALUE(TransactionStatus, last_known_status);
    }
  }

  void SendStatusRequest(client::YBClient* client, std::mutex* mutex) const {
    tserver::GetTransactionStatusRequestPB req;
    req.set_tablet_id(metadata_.status_tablet);
    req.set_transaction_id(metadata_.transaction_id.begin(), metadata_.transaction_id.size());
    req.set_propagated_hybrid_time(context_.Now().ToUint64());
    int64_t serial_no = ++*request_serial_;
    rpcs_.RegisterAndStart(
        client::GetTransactionStatus(
            TransactionRpcDeadline(),
            nullptr /* tablet */,
            client,
            &req,
            std::bind(&RunningTransaction::StatusReceived, this, client, _1, _2, serial_no, mutex)),
        &get_status_handle_);
  }

  void StatusReceived(client::YBClient* client,
                      const Status& status,
                      const tserver::GetTransactionStatusResponsePB& response,
                      int64_t serial_no,
                      std::mutex* mutex) const {
    auto delay_usec = FLAGS_transaction_delay_status_reply_usec_in_tests;
    if (delay_usec > 0) {
      delayer_.Delay(
          MonoTime::Now() + MonoDelta::FromMicroseconds(delay_usec),
          std::bind(&RunningTransaction::DoStatusReceived, this, client, status, response,
                    serial_no, mutex));
    } else {
      DoStatusReceived(client, status, response, serial_no, mutex);
    }
  }

  void DoStatusReceived(client::YBClient* client,
                        const Status& status,
                        const tserver::GetTransactionStatusResponsePB& response,
                        int64_t serial_no,
                        std::mutex* mutex) const {
    if (response.has_propagated_hybrid_time()) {
      context_.UpdateClock(HybridTime(response.propagated_hybrid_time()));
    }

    rpcs_.Unregister(&get_status_handle_);
    decltype(status_waiters_) status_waiters;
    HybridTime time;
    TransactionStatus transaction_status;
    const bool ok = status.ok();
    bool send_new_request;
    {
      std::unique_lock<std::mutex> lock(*mutex);
      if (ok) {
        DCHECK(response.has_status_hybrid_time() ||
               response.status() == TransactionStatus::ABORTED);
        time = response.has_status_hybrid_time()
            ? HybridTime(response.status_hybrid_time())
            : HybridTime::kMax;
        if (last_known_status_hybrid_time_ <= time) {
          last_known_status_hybrid_time_ = time;
          last_known_status_ = response.status();
        }
        time = last_known_status_hybrid_time_;
        transaction_status = last_known_status_;

        status_waiters.reserve(status_waiters_.size());
        auto w = status_waiters_.begin();
        for (auto it = status_waiters_.begin(); it != status_waiters_.end(); ++it) {
          if (it->serial_no <= serial_no ||
              GetStatusAt(it->global_limit_ht, time, transaction_status) ||
              time < it->read_ht) {
            status_waiters.push_back(std::move(*it));
          } else {
            if (w != it) {
              *w = std::move(*it);
            }
            ++w;
          }
        }
        status_waiters_.erase(w, status_waiters_.end());
      } else {
        status_waiters_.swap(status_waiters);
      }
      send_new_request = !status_waiters_.empty();
    }
    if (send_new_request) {
      SendStatusRequest(client, mutex);
    }
    if (!ok) {
      for (const auto& waiter : status_waiters) {
        waiter.callback(status);
      }
      return;
    }
    for (const auto& waiter : status_waiters) {
      auto status_for_waiter = GetStatusAt(waiter.global_limit_ht, time, transaction_status);
      if (status_for_waiter) {
        // We know status at global_limit_ht, so could notify waiter.
        waiter.callback(TransactionStatusResult{*status_for_waiter, time});
      } else if (time >= waiter.read_ht) {
        // It means that between read_ht and global_limit_ht transaction was pending.
        // It implies that transaction was not committed before request was sent.
        // We could safely respond PENDING to caller.
        DCHECK_LE(waiter.serial_no, serial_no);
        waiter.callback(TransactionStatusResult{TransactionStatus::PENDING, time});
      } else {
        waiter.callback(STATUS_FORMAT(
            TryAgain,
            "Cannot determine transaction status with read_ht $0, and global_limit_ht $1, "
                "last known: $2 at $3",
            waiter.read_ht,
            waiter.global_limit_ht,
            TransactionStatus_Name(transaction_status),
            time));
      }
    }
  }

  static Result<TransactionStatusResult> MakeAbortResult(
      const Status& status,
      const tserver::AbortTransactionResponsePB& response) {
    if (!status.ok()) {
      return status;
    }

    HybridTime status_time = response.has_status_hybrid_time()
         ? HybridTime(response.status_hybrid_time())
         : HybridTime::kInvalid;
    return TransactionStatusResult{response.status(), status_time};
  }

  void AbortReceived(const Status& status,
                     const tserver::AbortTransactionResponsePB& response,
                     std::mutex* mutex) const {
    if (response.has_propagated_hybrid_time()) {
      context_.UpdateClock(HybridTime(response.propagated_hybrid_time()));
    }

    decltype(abort_waiters_) abort_waiters;
    {
      std::lock_guard<std::mutex> lock(*mutex);
      rpcs_.Unregister(&abort_handle_);
      abort_waiters_.swap(abort_waiters);
    }
    auto result = MakeAbortResult(status, response);
    for (const auto& waiter : abort_waiters) {
      waiter(result);
    }
  }

  TransactionMetadata metadata_;
  rpc::Rpcs& rpcs_;
  TransactionParticipantContext& context_;
  std::atomic<int64_t>* request_serial_;
  HybridTime local_commit_time_ = HybridTime::kInvalid;

  mutable TransactionStatus last_known_status_;
  mutable HybridTime last_known_status_hybrid_time_ = HybridTime::kMin;
  mutable std::vector<StatusRequest> status_waiters_;
  mutable rpc::Rpcs::Handle get_status_handle_;
  mutable rpc::Rpcs::Handle abort_handle_;
  mutable std::vector<TransactionStatusCallback> abort_waiters_;

  // Used only in tests.
  mutable Delayer delayer_;
};

} // namespace

class TransactionParticipant::Impl {
 public:
  explicit Impl(TransactionParticipantContext* context)
      : context_(*context), log_prefix_(context->tablet_id() + ": ") {}

  ~Impl() {
    transactions_.clear();
    rpcs_.Shutdown();
  }

  // Adds new running transaction.
  void Add(const TransactionMetadataPB& data, rocksdb::WriteBatch *write_batch) {
    auto metadata = TransactionMetadata::FromPB(data);
    if (!metadata.ok()) {
      LOG_WITH_PREFIX(DFATAL) << "Invalid transaction id: " << metadata.status().ToString();
      return;
    }
    bool store = false;
    {
      std::lock_guard<std::mutex> lock(mutex_);
      auto it = transactions_.find(metadata->transaction_id);
      if (it == transactions_.end()) {
        transactions_.emplace(*metadata, &rpcs_, &context_, &request_serial_);
        store = true;
      } else {
        DCHECK_EQ(it->metadata(), *metadata);
      }
    }
    if (store) {
      docdb::KeyBytes key;
      AppendTransactionKeyPrefix(metadata->transaction_id, &key);
      auto value = data.SerializeAsString();
      write_batch->Put(key.data(), value);
    }
  }

  HybridTime LocalCommitTime(const TransactionId& id) {
    std::lock_guard<std::mutex> lock(mutex_);
    auto it = transactions_.find(id);
    if (it == transactions_.end()) {
      return HybridTime::kInvalid;
    }
    return it->local_commit_time();
  }

  boost::optional<TransactionMetadata> Metadata(const TransactionId& id) {
    std::lock_guard<std::mutex> lock(mutex_);
    auto it = FindOrLoad(id);
    if (it == transactions_.end()) {
      return boost::none;
    }
    return it->metadata();
  }

  void RequestStatusAt(const StatusRequest& request) {
    std::unique_lock<std::mutex> lock(mutex_);
    auto it = FindOrLoad(*request.id);
    if (it == transactions_.end()) {
      lock.unlock();
      request.callback(
          STATUS_FORMAT(NotFound, "Request status of unknown transaction: $0", *request.id));
      return;
    }
    return it->RequestStatusAt(client(), request, &lock);
  }

  int64_t RegisterRequest() {
    return ++request_serial_;
  }

  void Abort(const TransactionId& id,
             TransactionStatusCallback callback) {
    std::unique_lock<std::mutex> lock(mutex_);
    auto it = FindOrLoad(id);
    if (it == transactions_.end()) {
      lock.unlock();
      callback(STATUS_FORMAT(NotFound, "Abort of unknown transaction: $0", id));
      return;
    }
    return it->Abort(client(), std::move(callback), &lock);
  }

  CHECKED_STATUS ProcessApply(const TransactionApplyData& data) {
    {
      std::lock_guard<std::mutex> lock(mutex_);
      // It is our last chance to load transaction metadata, if missing.
      // Because it will be deleted when intents are applied.
      FindOrLoad(data.transaction_id);
    }

    CHECK_OK(data.applier->ApplyIntents(data));

    {
      std::lock_guard<std::mutex> lock(mutex_);
      auto it = FindOrLoad(data.transaction_id);
      if (it == transactions_.end()) {
        // This situation is normal and could be caused by 2 scenarios:
        // 1) Write batch failed, but originator doesn't know that.
        // 2) Failed to notify status tablet that we applied transaction.
        LOG_WITH_PREFIX(WARNING) << "Apply of unknown transaction: " << data.transaction_id;
        return Status::OK();
      } else {
        transactions_.modify(it, [&data](RunningTransaction& transaction) {
          transaction.SetLocalCommitTime(data.commit_ht);
        });
        // TODO(dtxn) cleanup
      }
      if (data.mode == ProcessingMode::LEADER) {
        tserver::UpdateTransactionRequestPB req;
        req.set_tablet_id(data.status_tablet);
        auto& state = *req.mutable_state();
        state.set_transaction_id(data.transaction_id.begin(), data.transaction_id.size());
        state.set_status(TransactionStatus::APPLIED_IN_ONE_OF_INVOLVED_TABLETS);
        state.add_tablets(context_.tablet_id());

        auto handle = rpcs_.Prepare();
        if (handle != rpcs_.InvalidHandle()) {
          *handle = UpdateTransaction(
              TransactionRpcDeadline(),
              nullptr /* remote_tablet */,
              client(),
              &req,
              [this, handle](const Status& status, HybridTime propagated_hybrid_time) {
                context_.UpdateClock(propagated_hybrid_time);
                rpcs_.Unregister(handle);
                LOG_IF_WITH_PREFIX(WARNING, !status.ok()) << "Failed to send applied: " << status;
              });
          (**handle).SendRpc();
        }
      }
    }
    return Status::OK();
  }

  void SetDB(rocksdb::DB* db) {
    db_ = db;
  }

  TransactionParticipantContext* context() const {
    return &context_;
  }

 private:
  typedef boost::multi_index_container<RunningTransaction,
      boost::multi_index::indexed_by <
          boost::multi_index::hashed_unique <
              boost::multi_index::const_mem_fun<RunningTransaction,
                                                const TransactionId&,
                                                &RunningTransaction::id>
          >
      >
  > Transactions;

  // TODO(dtxn) unlock during load
  Transactions::const_iterator FindOrLoad(const TransactionId& id) {
    auto it = transactions_.find(id);
    if (it != transactions_.end()) {
      return it;
    }

    docdb::KeyBytes key;
    AppendTransactionKeyPrefix(id, &key);
    auto iter = docdb::CreateRocksDBIterator(db_,
                                             docdb::BloomFilterMode::DONT_USE_BLOOM_FILTER,
                                             boost::none,
                                             rocksdb::kDefaultQueryId);
    iter->Seek(key.data());
    if (!iter->Valid() || iter->key() != key.data()) {
      LOG_WITH_PREFIX(WARNING) << "Transaction not found: " << id;
      return it;
    }
    TransactionMetadataPB metadata_pb;

    if (!metadata_pb.ParseFromArray(iter->value().cdata(), iter->value().size())) {
      LOG_WITH_PREFIX(DFATAL) << "Unable to parse stored metadata: "
                              << iter->value().ToDebugHexString();
      return it;
    }

    auto metadata = TransactionMetadata::FromPB(metadata_pb);
    if (!metadata.ok()) {
      LOG_WITH_PREFIX(DFATAL) << "Loaded bad metadata: " << metadata.status();
      return it;
    }

    it = transactions_.emplace(std::move(*metadata), &rpcs_, &context_, &request_serial_).first;

    return it;
  }

  client::YBClient* client() const {
    return context_.client_future().get().get();
  }

  const std::string& LogPrefix() const {
    return log_prefix_;
  }

  TransactionParticipantContext& context_;
  std::string log_prefix_;

  rocksdb::DB* db_ = nullptr;
  std::mutex mutex_;
  rpc::Rpcs rpcs_;
  Transactions transactions_;
  std::atomic<int64_t> request_serial_{0};
};

TransactionParticipant::TransactionParticipant(TransactionParticipantContext* context)
    : impl_(new Impl(context)) {
}

TransactionParticipant::~TransactionParticipant() {
}

void TransactionParticipant::Add(const TransactionMetadataPB& data,
                                 rocksdb::WriteBatch *write_batch) {
  impl_->Add(data, write_batch);
}

boost::optional<TransactionMetadata> TransactionParticipant::Metadata(const TransactionId& id) {
  return impl_->Metadata(id);
}

HybridTime TransactionParticipant::LocalCommitTime(const TransactionId& id) {
  return impl_->LocalCommitTime(id);
}

void TransactionParticipant::RequestStatusAt(const StatusRequest& request) {
  return impl_->RequestStatusAt(request);
}

int64_t TransactionParticipant::RegisterRequest() {
  return impl_->RegisterRequest();
}

void TransactionParticipant::Abort(const TransactionId& id,
                                   TransactionStatusCallback callback) {
  return impl_->Abort(id, std::move(callback));
}

CHECKED_STATUS TransactionParticipant::ProcessApply(const TransactionApplyData& data) {
  return impl_->ProcessApply(data);
}

void TransactionParticipant::SetDB(rocksdb::DB* db) {
  impl_->SetDB(db);
}

TransactionParticipantContext* TransactionParticipant::context() const {
  return impl_->context();
}

} // namespace tablet
} // namespace yb

max_stars_repo_name: everyonce/yugabyte-db

max_issues_repo_name: everyonce/yugabyte-db

max_forks_repo_name: everyonce/yugabyte-db


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          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
//==============================================================================
#ifndef BOOST_SIMD_OPERATOR_FUNCTIONS_SIMD_SSE_SSE2_IS_EQUAL_HPP_INCLUDED
#define BOOST_SIMD_OPERATOR_FUNCTIONS_SIMD_SSE_SSE2_IS_EQUAL_HPP_INCLUDED
#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT
#include <boost/simd/operator/functions/is_equal.hpp>
#include <boost/simd/include/functions/simd/bitwise_cast.hpp>
#include <boost/simd/include/functions/simd/bitwise_and.hpp>
#include <boost/simd/include/functions/simd/minus.hpp>
#include <boost/simd/include/constants/zero.hpp>
#include <boost/simd/sdk/simd/logical.hpp>
#include <boost/dispatch/meta/downgrade.hpp>
#include <boost/simd/swar/functions/details/shuffle.hpp>

namespace boost { namespace simd { namespace ext
{
  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::is_equal_, boost::simd::tag::sse2_
                            , (A0)
                            , ((simd_<double_<A0>,boost::simd::tag::sse_>))
                              ((simd_<double_<A0>,boost::simd::tag::sse_>))
                            )
  {
    typedef typename meta::as_logical<A0>::type result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      return _mm_cmpeq_pd(a0,a1);
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::is_equal_, boost::simd::tag::sse2_
                            , (A0)
                            , ((simd_<single_<A0>,boost::simd::tag::sse_>))
                              ((simd_<single_<A0>,boost::simd::tag::sse_>))
                            )
  {
    typedef typename meta::as_logical<A0>::type result_type;

    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      return _mm_cmpeq_ps(a0,a1);
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::is_equal_, boost::simd::tag::sse2_
                            , (A0)
                            , ((simd_<ints8_<A0>,boost::simd::tag::sse_>))
                              ((simd_<ints8_<A0>,boost::simd::tag::sse_>))
                            )
  {
    typedef typename meta::as_logical<A0>::type result_type;

    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      return _mm_cmpeq_epi8(a0,a1);
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::is_equal_, boost::simd::tag::sse2_
                            , (A0)
                            , ((simd_<ints16_<A0>,boost::simd::tag::sse_>))
                              ((simd_<ints16_<A0>,boost::simd::tag::sse_>))
                            )
  {
    typedef typename meta::as_logical<A0>::type result_type;

    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      return _mm_cmpeq_epi16(a0,a1);
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::is_equal_, boost::simd::tag::sse2_
                            , (A0)
                            , ((simd_<ints32_<A0>,boost::simd::tag::sse_>))
                              ((simd_<ints32_<A0>,boost::simd::tag::sse_>))
                            )
  {
    typedef typename meta::as_logical<A0>::type result_type;

    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      return _mm_cmpeq_epi32(a0,a1);
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::is_equal_, boost::simd::tag::sse2_
                            , (A0)
                            , ((simd_<ints64_<A0>,boost::simd::tag::sse_>))
                              ((simd_<ints64_<A0>,boost::simd::tag::sse_>))
                            )
  {
    typedef typename meta::as_logical<A0>::type result_type;

    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      typedef typename dispatch::meta::downgrade<A0, unsigned>::type  type;
      type tmp      = bitwise_cast<type>(a0 - a1);
      tmp           = bitwise_cast<type>(boost::simd::eq(tmp,Zero<type>()));
      type shuffled = details::shuffle<1,0,3,2>(tmp);
      return bitwise_cast<result_type>(tmp & shuffled);
    }
  };
} } }

#endif
#endif


text:
// TestFileReadingUtilties

#ifndef _MSC_VER
#define BOOST_TEST_DYN_LINK
#endif
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE test_file_reading

#include <boost/test/unit_test.hpp>
#include "../tools/FileReadingUtilities.hpp"
#include <string>
#include <iostream>

BOOST_AUTO_TEST_SUITE(test_file_reading)

// test file exists
BOOST_AUTO_TEST_CASE(file_exists)
{
    BOOST_CHECK_EQUAL(tools::fileExists("tests/resources/strategy.config"), true);
    BOOST_CHECK_EQUAL(tools::fileExists("tests/TestStrategy.cpp"), true);

    BOOST_CHECK_EQUAL(tools::fileExists("fakeFile.txt"), false);
}

BOOST_AUTO_TEST_CASE(get_file_lines)
{
	std::vector<std::string> fileLines = tools::getLines("tests/resources/strategy.config");
	BOOST_CHECK_EQUAL(fileLines.empty(), false);

	BOOST_CHECK_EQUAL(fileLines[0], "# Strategy test config");
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: joshuakarbi/trader

max_issues_repo_name: joshuakarbi/trader

max_forks_repo_name: joshuakarbi/trader


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

#include "pattern.hpp"

#include <boost/assign/std/vector.hpp>

using namespace boost::assign;

namespace cirkit
{

  class pattern::priv
  {
  public:
    priv() {}

    initializer_map initializers;
    std::vector<std::string> inputs;
    std::vector<std::vector<unsigned> > patterns;
  };

  pattern::pattern()
    : d( new priv() )
  {
  }

  pattern::~pattern()
  {
    delete d;
  }

  void pattern::add_initializer( const std::string& name, unsigned value )
  {
    d->initializers[name] = value;
  }

  void pattern::add_input( const std::string& name )
  {
    d->inputs += name;
  }

  void pattern::add_pattern( const std::vector<unsigned>& pattern )
  {
    d->patterns += pattern;
  }

  const pattern::initializer_map& pattern::initializers() const
  {
    return d->initializers;
  }

  const std::vector<std::string>& pattern::inputs() const
  {
    return d->inputs;
  }

  const pattern::pattern_vec& pattern::patterns() const
  {
    return d->patterns;
  }

}

// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:

max_stars_repo_name: eletesta/cirkit

max_issues_repo_name: eletesta/cirkit

max_forks_repo_name: eletesta/cirkit


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

#include "basic_allele.h"
#include "clotho/utility/random_generator.hpp"
#include "clotho/utility/clotho_strings.hpp"

#include <boost/random/uniform_01.hpp>
#include <boost/random/bernoulli_distribution.hpp>

namespace clotho {
namespace utility {

template < class URNG >
class random_generator< URNG, basic_allele > {
public:
    typedef random_generator< URNG, basic_allele >  self_type;
    typedef basic_allele                            result_type;

    typedef typename result_type::real_type real_type;
    typedef typename result_type::key_type  key_type;

    typedef real_type selection_type;
    typedef real_type dominance_type;

    typedef boost::random::uniform_01< real_type >  dist_type;
    typedef boost::random::bernoulli_distribution< real_type > neutral_dist_type;

    random_generator( URNG & rng ) :
        m_rng( &rng )
        , m_neutral() {
    }

    random_generator( URNG & rng, boost::property_tree::ptree & config ) :
        m_rng( &rng )
        , m_neutral() {
        parseConfig( config );
    }

    random_generator( const self_type & other ) :
        m_rng( other.m_rng )
        , m_neutral( other.m_neutral.param() ) {
    }

    result_type operator()( unsigned int age = 0 ) {
        basic_allele al;

        generate(al, age);

        return al;
    }

    virtual ~random_generator() {}
protected:

    void generate( basic_allele & a, unsigned int age ) {
        a.m_key = m_uniform( *m_rng );

        a.m_neutral = m_neutral( *m_rng );
        if( !a.m_neutral ) {
            a.m_select = m_uniform( *m_rng );
            a.m_dom = m_uniform( *m_rng );
        }
        a.m_age = age;
    }

    void parseConfig( boost::property_tree::ptree & config ) {
        boost::property_tree::ptree lconfig;
        lconfig = config.get_child( ALLELE_BLOCK_K, lconfig );

        boost::property_tree::ptree nblock;
        nblock = lconfig.get_child( NEUTRAL_BLOCK_K, nblock );

        real_type p = nblock.get< real_type >( P_K, m_neutral.p() );

        nblock.put( P_K, p );

        lconfig.put_child( NEUTRAL_BLOCK_K, nblock );
        config.put_child( ALLELE_BLOCK_K, lconfig );

        typename neutral_dist_type::param_type tmp( p );
        m_neutral.param( tmp );
    }

    URNG *  m_rng;
    dist_type   m_uniform;
    neutral_dist_type m_neutral;
};

}   // namespace clotho {
}   // namespace utility {

#endif  // BASIC_ALLELE_GENERATOR_HPP_

max_stars_repo_name: putnampp/clotho

max_issues_repo_name: putnampp/clotho

max_forks_repo_name: putnampp/clotho