<commit_before>#include "rosplan_planning_system/PlannerInterface/FFPlannerInterface.h"

namespace KCL_rosplan {

	/*-------------*/
	/* constructor */
	/*-------------*/

	FFPlannerInterface::FFPlannerInterface(ros::NodeHandle& nh)
	{
		node_handle = &nh;

		plan_server = new actionlib::SimpleActionServer<rosplan_dispatch_msgs::PlanAction>((*node_handle), "start_planning", boost::bind(&PlannerInterface::runPlanningServerAction, this, _1), false);

		// publishing raw planner output
		std::string plannerTopic = "planner_output";
		node_handle->getParam("planner_topic", plannerTopic);
		plan_publisher = node_handle->advertise<std_msgs::String>(plannerTopic, 1, true);

		// start planning action server
		plan_server->start();
	}

	FFPlannerInterface::~FFPlannerInterface()
	{
		delete plan_server;
	}

	/**
	 * Runs external commands
	 */
	std::string FFPlannerInterface::runCommand(std::string cmd) {
		std::string data;
		FILE *stream;
		char buffer[1000];
		stream = popen(cmd.c_str(), "r");
		while ( fgets(buffer, 1000, stream) != NULL )
			data.append(buffer);
		pclose(stream);
		return data;
	}

	/*------------------*/
	/* Plan and process */
	/*------------------*/

	/**
	 * passes the problem to the Planner; the plan to post-processing.
	 */
	bool FFPlannerInterface::runPlanner() {

		// save problem to file for POPF
		if(use_problem_topic && problem_instance_recieved) {
			ROS_INFO("KCL: (%s) (%s) Writing problem to file.", ros::this_node::getName().c_str(), problem_name.c_str());
			std::ofstream dest;
			dest.open((problem_path).c_str());
			dest << problem_instance;
			dest.close();
		}

		// prepare the planner command line
		std::string str = planner_command;
		std::size_t dit = str.find("DOMAIN");
		if(dit!=std::string::npos) str.replace(dit,6,domain_path);
		std::size_t pit = str.find("PROBLEM");
		if(pit!=std::string::npos) str.replace(pit,7,problem_path);
		std::string commandString = str + " > " + data_path + "plan.pddl";

		// call the planer
		ROS_INFO("KCL: (%s) (%s) Running: %s", ros::this_node::getName().c_str(), problem_name.c_str(),  commandString.c_str());
		std::string plan = runCommand(commandString.c_str());
		ROS_INFO("KCL: (%s) (%s) Planning complete", ros::this_node::getName().c_str(), problem_name.c_str());

		// check the planner solved the problem
		std::ifstream planfile;
		planfile.open((data_path + "plan.pddl").c_str());
		std::string line;
		std::stringstream ss;

		bool solved = false;

		while (std::getline(planfile, line)) {

			// skip lines until there is a plan
			if(line.compare("ff: found legal plan as follows") != 0) {
				continue;
			}

			// skip the empty line
			while (std::getline(planfile, line)) {
				if (line.length()<2) break;
			}

			// actions look like this:
			// step    0: got_place C1
			//         1: find_object V1 C1
			solved = true;
			while (std::getline(planfile, line)) {

				if (line.length()<2) break;

				unsigned int pos = line.find(' ');
				bool action = false;
				while(pos != std::string::npos && pos < line.length()) {
					if(line.substr(pos,1) != " ") {
						action = true;
						line = line.substr(pos);
						break;
					}
					pos++;
				}
				if(action) ss << line << " [0.001]" << std::endl;
			}
			planner_output = ss.str();
		}
		planfile.close();

		if(!solved) ROS_INFO("KCL: (%s) (%s) Plan was unsolvable.", ros::this_node::getName().c_str(), problem_name.c_str());
		else ROS_INFO("KCL: (%s) (%s) Plan was solved.", ros::this_node::getName().c_str(), problem_name.c_str());

		return solved;
	}

} // close namespace

	/*-------------*/
	/* Main method */
	/*-------------*/

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

		srand (static_cast <unsigned> (time(0)));

		ros::init(argc,argv,"rosplan_planner_interface");
		ros::NodeHandle nh("~");

		KCL_rosplan::FFPlannerInterface pi(nh);

		// subscribe to problem instance
		std::string problemTopic = "problem_instance";
		nh.getParam("problem_topic", problemTopic);
		ros::Subscriber problem_sub = nh.subscribe(problemTopic, 1, &KCL_rosplan::PlannerInterface::problemCallback, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));

		// start the planning services
		ros::ServiceServer service1 = nh.advertiseService("planning_server", &KCL_rosplan::PlannerInterface::runPlanningServerDefault, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));
		ros::ServiceServer service2 = nh.advertiseService("planning_server_params", &KCL_rosplan::PlannerInterface::runPlanningServerParams, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));

		ROS_INFO("KCL: (%s) Ready to receive", ros::this_node::getName().c_str());
		ros::spin();

		return 0;
	}
<commit_msg>Update FFPlannerInterface.cpp<commit_after>#include "rosplan_planning_system/PlannerInterface/FFPlannerInterface.h"

namespace KCL_rosplan {

	/*-------------*/
	/* constructor */
	/*-------------*/

	FFPlannerInterface::FFPlannerInterface(ros::NodeHandle& nh)
	{
		node_handle = &nh;

		plan_server = new actionlib::SimpleActionServer<rosplan_dispatch_msgs::PlanAction>((*node_handle), "start_planning", boost::bind(&PlannerInterface::runPlanningServerAction, this, _1), false);

		// publishing raw planner output
		std::string plannerTopic = "planner_output";
		node_handle->getParam("planner_topic", plannerTopic);
		plan_publisher = node_handle->advertise<std_msgs::String>(plannerTopic, 1, true);

		// start planning action server
		plan_server->start();
	}

	FFPlannerInterface::~FFPlannerInterface()
	{
		delete plan_server;
	}

	/**
	 * Runs external commands
	 */
	std::string FFPlannerInterface::runCommand(std::string cmd) {
		std::string data;
		FILE *stream;
		char buffer[1000];
		stream = popen(cmd.c_str(), "r");
		while ( fgets(buffer, 1000, stream) != NULL )
			data.append(buffer);
		pclose(stream);
		return data;
	}

	/*------------------*/
	/* Plan and process */
	/*------------------*/

	/**
	 * passes the problem to the Planner; the plan to post-processing.
	 */
	bool FFPlannerInterface::runPlanner() {

		// save problem to file for planner
		if(use_problem_topic && problem_instance_recieved) {
			ROS_INFO("KCL: (%s) (%s) Writing problem to file.", ros::this_node::getName().c_str(), problem_name.c_str());
			std::ofstream dest;
			dest.open((problem_path).c_str());
			dest << problem_instance;
			dest.close();
		}

		// prepare the planner command line
		std::string str = planner_command;
		std::size_t dit = str.find("DOMAIN");
		if(dit!=std::string::npos) str.replace(dit,6,domain_path);
		std::size_t pit = str.find("PROBLEM");
		if(pit!=std::string::npos) str.replace(pit,7,problem_path);
		std::string commandString = str + " > " + data_path + "plan.pddl";

		// call the planer
		ROS_INFO("KCL: (%s) (%s) Running: %s", ros::this_node::getName().c_str(), problem_name.c_str(),  commandString.c_str());
		std::string plan = runCommand(commandString.c_str());
		ROS_INFO("KCL: (%s) (%s) Planning complete", ros::this_node::getName().c_str(), problem_name.c_str());

		// check the planner solved the problem
		std::ifstream planfile;
		planfile.open((data_path + "plan.pddl").c_str());
		std::string line;
		std::stringstream ss;

		bool solved = false;

		while (std::getline(planfile, line)) {

			// skip lines until there is a plan
			if(line.compare("ff: found legal plan as follows") != 0) {
				continue;
			}

			// skip the empty line
			while (std::getline(planfile, line)) {
				if (line.length()<2) break;
			}

			// actions look like this:
			// step    0: got_place C1
			//         1: find_object V1 C1
			solved = true;
			while (std::getline(planfile, line)) {

				if (line.length()<2) break;

				unsigned int pos = line.find(' ');
				bool action = false;
				while(pos != std::string::npos && pos < line.length()) {
					if(line.substr(pos,1) != " ") {
						action = true;
						line = line.substr(pos);
						break;
					}
					pos++;
				}
				if(action) ss << line << " [0.001]" << std::endl;
			}
			planner_output = ss.str();
		}
		planfile.close();

		if(!solved) ROS_INFO("KCL: (%s) (%s) Plan was unsolvable.", ros::this_node::getName().c_str(), problem_name.c_str());
		else ROS_INFO("KCL: (%s) (%s) Plan was solved.", ros::this_node::getName().c_str(), problem_name.c_str());

		return solved;
	}

} // close namespace

	/*-------------*/
	/* Main method */
	/*-------------*/

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

		srand (static_cast <unsigned> (time(0)));

		ros::init(argc,argv,"rosplan_planner_interface");
		ros::NodeHandle nh("~");

		KCL_rosplan::FFPlannerInterface pi(nh);

		// subscribe to problem instance
		std::string problemTopic = "problem_instance";
		nh.getParam("problem_topic", problemTopic);
		ros::Subscriber problem_sub = nh.subscribe(problemTopic, 1, &KCL_rosplan::PlannerInterface::problemCallback, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));

		// start the planning services
		ros::ServiceServer service1 = nh.advertiseService("planning_server", &KCL_rosplan::PlannerInterface::runPlanningServerDefault, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));
		ros::ServiceServer service2 = nh.advertiseService("planning_server_params", &KCL_rosplan::PlannerInterface::runPlanningServerParams, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));

		ROS_INFO("KCL: (%s) Ready to receive", ros::this_node::getName().c_str());
		ros::spin();

		return 0;
	}
<|endoftext|>


<commit_before>/*
 *
 * Author: Jeffrey Leung
 * Last edited: 2015-12-21
 *
 * This C++ header file contains the LabyrinthMap class which creates, updates,
 * and displays a map of a given Labyrinth.
 *
 */

#include <stdexcept>

#include "../include/labyrinth_map.hpp"

// This method returns whether a given Wall coordinate has a wall in the
// given direction.
// An exception is thrown if:
//   d is kNone (invalid_argument)
bool LabyrinthMapCoordinateBorder::IsWall( Direction d ) const
{
  switch( d )
  {
    case Direction::kNorth:
      return wall_north_;
    case Direction::kEast:
      return wall_east_;
    case Direction::kSouth:
      return wall_south_;
    case Direction::kWest:
      return wall_west_;
    default:
      throw std::invalid_argument( "Error: IsWall() was given an invalid " \
        "direction (kNone)." );
  }
}

// This method creates the Wall of a given Wall coordinate.
// May be used to set a Wall which has already been set.
// An exception is thrown if:
//   d is kNone (invalid_argument)
void LabyrinthMapCoordinateBorder::RemoveWall( Direction d )
{
  switch( d )
  {
    case Direction::kNorth:
      wall_north_ = false;
      return;
    case Direction::kEast:
      wall_east_ = false;
      return;
    case Direction::kSouth:
      wall_south_ = false;
      return;
    case Direction::kWest:
      wall_west_ = false;
      return;
    default:
      throw std::invalid_argument( "Error: SetWall() was given an invalid "\
        "direction (kNone)." );
  }
  return;
}

// This method returns whether a given Wall coordinate has the exit.
bool LabyrinthMapCoordinateBorder::IsExit() const
{
  return exit_;
}

// This method sets whether or not a given Wall coordinate has the exit.
// May be used to set an exit where the exit already exists, or to remove
// an exit where none exists.
void LabyrinthMapCoordinateBorder::SetExit( bool b )
{
  exit_ = b;
}

// This method returns the inhabitant of the current Room.
Inhabitant LabyrinthMapCoordinateRoom::HasInhabitant() const
{
  return i_;
}

// This method sets the current inhabitant of the map's Room.
// May be used to set the inhabitant to the same inhabitant, or to
// no inhabitant.
void LabyrinthMapCoordinateRoom::SetInhabitant( Inhabitant inh )
{
  i_ = inh;
}

// This method returns whether the treasure is in a given Room.
bool LabyrinthMapCoordinateRoom::HasTreasure() const
{
  return treasure_;
}

// This method sets whether or not the treasure is in the given map's Room.
// May be used to set the treasure when there is already a treasure in
// the Room, or to remove the treasure when there is no treasure already.
void LabyrinthMapCoordinateRoom::SetTreasure( bool b )
{
  treasure_ = b;
}

// Parameterized constructor
// An exception is thrown if:
//   l is null (invalid_argument)
LabyrinthMap::LabyrinthMap( Labyrinth* l,
                            unsigned int x_size,
                            unsigned int y_size )
{
  if( l == nullptr )
  {
    throw std::invalid_argument( "Error: LabyrinthMap() was given an "\
      "invalid (null) pointer for the Labyrinth." );
  }

  l_ = l;
  x_size_ = x_size;
  y_size_ = y_size;

  map_x_size_ = x_size * 2 + 1;
  map_y_size_ = y_size * 2 + 1;

  // Creation of the map array
  map_ = new LabyrinthMapCoordinate**[ map_y_size_ ];
  for( unsigned int i = 0; i < map_y_size_; ++i )
  {
    map_[i] = new LabyrinthMapCoordinate*[ map_x_size_ ];
  }

  // Creation of the individual map rooms/borders
  Coordinate c;
  for( unsigned int y = 0; y < map_y_size_; ++y )
  {
    for( unsigned int x = 0; x < map_x_size_; ++x )
    {
      c.x = x;
      c.y = y;
      if( IsRoom(c) )
      {
        map_[x][y] = new LabyrinthMapCoordinateRoom;
      }
      else
      {
        map_[x][y] = new LabyrinthMapCoordinateBorder;
      }
    }
  }

  //TODO Remove excess bounds on the exterior of the Labyrinth
  //TODO Initialization of the border coordinates

  //Update();  //TODO Uncomment when Update() is implemented
}

// This method returns true if the Coordinate is within the bounds
// of the Map, and false otherwise.
bool LabyrinthMap::WithinBoundsOfMap( const Coordinate c ) const
{
  return ( -1 < c.x && c.x < map_x_size_ &&
           -1 < c.y && c.y < map_y_size_ );
}

// This private method returns true if the coordinate designates a Room in
// the map, and false if it designates a Border.
// An exception is thrown if:
//   The coordinate is outside of the Map (domain_error)
bool LabyrinthMap::IsRoom( const Coordinate c ) const
{
  if( WithinBoundsOfMap(c) )
  {
    return c.x % 2 == 1 && c.y % 2 == 1;
  }
  else
  {
    throw std::domain_error( "Error: IsRoom() was given a Coordinate "\
      "outside of the Map." );
  }
}

//TODO Implementation of labyrinth_map.hpp
<commit_msg>Removing lower bounds check for unsigned values.<commit_after>/*
 *
 * Author: Jeffrey Leung
 * Last edited: 2015-12-21
 *
 * This C++ header file contains the LabyrinthMap class which creates, updates,
 * and displays a map of a given Labyrinth.
 *
 */

#include <stdexcept>

#include "../include/labyrinth_map.hpp"

// This method returns whether a given Wall coordinate has a wall in the
// given direction.
// An exception is thrown if:
//   d is kNone (invalid_argument)
bool LabyrinthMapCoordinateBorder::IsWall( Direction d ) const
{
  switch( d )
  {
    case Direction::kNorth:
      return wall_north_;
    case Direction::kEast:
      return wall_east_;
    case Direction::kSouth:
      return wall_south_;
    case Direction::kWest:
      return wall_west_;
    default:
      throw std::invalid_argument( "Error: IsWall() was given an invalid " \
        "direction (kNone)." );
  }
}

// This method creates the Wall of a given Wall coordinate.
// May be used to set a Wall which has already been set.
// An exception is thrown if:
//   d is kNone (invalid_argument)
void LabyrinthMapCoordinateBorder::RemoveWall( Direction d )
{
  switch( d )
  {
    case Direction::kNorth:
      wall_north_ = false;
      return;
    case Direction::kEast:
      wall_east_ = false;
      return;
    case Direction::kSouth:
      wall_south_ = false;
      return;
    case Direction::kWest:
      wall_west_ = false;
      return;
    default:
      throw std::invalid_argument( "Error: SetWall() was given an invalid "\
        "direction (kNone)." );
  }
  return;
}

// This method returns whether a given Wall coordinate has the exit.
bool LabyrinthMapCoordinateBorder::IsExit() const
{
  return exit_;
}

// This method sets whether or not a given Wall coordinate has the exit.
// May be used to set an exit where the exit already exists, or to remove
// an exit where none exists.
void LabyrinthMapCoordinateBorder::SetExit( bool b )
{
  exit_ = b;
}

// This method returns the inhabitant of the current Room.
Inhabitant LabyrinthMapCoordinateRoom::HasInhabitant() const
{
  return i_;
}

// This method sets the current inhabitant of the map's Room.
// May be used to set the inhabitant to the same inhabitant, or to
// no inhabitant.
void LabyrinthMapCoordinateRoom::SetInhabitant( Inhabitant inh )
{
  i_ = inh;
}

// This method returns whether the treasure is in a given Room.
bool LabyrinthMapCoordinateRoom::HasTreasure() const
{
  return treasure_;
}

// This method sets whether or not the treasure is in the given map's Room.
// May be used to set the treasure when there is already a treasure in
// the Room, or to remove the treasure when there is no treasure already.
void LabyrinthMapCoordinateRoom::SetTreasure( bool b )
{
  treasure_ = b;
}

// Parameterized constructor
// An exception is thrown if:
//   l is null (invalid_argument)
LabyrinthMap::LabyrinthMap( Labyrinth* l,
                            unsigned int x_size,
                            unsigned int y_size )
{
  if( l == nullptr )
  {
    throw std::invalid_argument( "Error: LabyrinthMap() was given an "\
      "invalid (null) pointer for the Labyrinth." );
  }

  l_ = l;
  x_size_ = x_size;
  y_size_ = y_size;

  map_x_size_ = x_size * 2 + 1;
  map_y_size_ = y_size * 2 + 1;

  // Creation of the map array
  map_ = new LabyrinthMapCoordinate**[ map_y_size_ ];
  for( unsigned int i = 0; i < map_y_size_; ++i )
  {
    map_[i] = new LabyrinthMapCoordinate*[ map_x_size_ ];
  }

  // Creation of the individual map rooms/borders
  Coordinate c;
  for( unsigned int y = 0; y < map_y_size_; ++y )
  {
    for( unsigned int x = 0; x < map_x_size_; ++x )
    {
      c.x = x;
      c.y = y;
      if( IsRoom(c) )
      {
        map_[x][y] = new LabyrinthMapCoordinateRoom;
      }
      else
      {
        map_[x][y] = new LabyrinthMapCoordinateBorder;
      }
    }
  }

  //TODO Remove excess bounds on the exterior of the Labyrinth
  //TODO Initialization of the border coordinates

  //Update();  //TODO Uncomment when Update() is implemented
}

// This method returns true if the Coordinate is within the bounds
// of the Map, and false otherwise.
bool LabyrinthMap::WithinBoundsOfMap( const Coordinate c ) const
{
  return ( c.x < map_x_size_ &&
           c.y < map_y_size_ );
}

// This private method returns true if the coordinate designates a Room in
// the map, and false if it designates a Border.
// An exception is thrown if:
//   The coordinate is outside of the Map (domain_error)
bool LabyrinthMap::IsRoom( const Coordinate c ) const
{
  if( WithinBoundsOfMap(c) )
  {
    return c.x % 2 == 1 && c.y % 2 == 1;
  }
  else
  {
    throw std::domain_error( "Error: IsRoom() was given a Coordinate "\
      "outside of the Map." );
  }
}

//TODO Implementation of labyrinth_map.hpp
<|endoftext|>


<commit_before><commit_msg>Marked NotificationTest.TestDOMUIMessageCallback as FAILS after r61174 due to DOM UI bindings being disabled for non-chrome:// URLs.<commit_after><|endoftext|>


<commit_before>#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>

#include <boost/program_options.hpp>

#include "BasicSort.hpp"
#include "BitonicSort.hpp"
// #include "QuickSort.hpp"
#include "MergeSort.hpp"
#include "CSVTools.hpp"

#define THREAD_START		1
#define	SIZE_START			10
#define	DEFAULT_ELEMENTS	100
#define DEFAULT_THREADS		4
#define DEFAULT_GAP			10
#define DEFAULT_SAVE_FILE	"results.csv"

#define FIELD_WIDTH			10

#define PROG_NAME			"Laser Patroll Sorting Benchmark Application"
#define VERSION_STRING		"Version: Alpha"

// Potential return values.
const int SUCCESS                   = 0;
const int ERROR_ON_COMMAND_LINE     = 1;
const int ERROR_UNHANDLED_EXCEPTION = 2;

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

	try {
		// Setup and configure the input parser.
		namespace po = boost::program_options;
		po::variables_map vm;
		bool sweep;
		bool no_bitonic, no_merge, no_basic;

		// Add options here
		po::options_description generic("Program Options");
		generic.add_options()
			("help,h", "Prints out help information.")
			("version,v", "Prints out version information.");

		po::options_description configuration("Configuration Options");
		configuration.add_options()
			("size,s", po::value<size_t>()->default_value(DEFAULT_ELEMENTS),
				"Number of elements to sort.")
			("threads,t", po::value<size_t>()->default_value(DEFAULT_THREADS),
				"Number of threads to use for sorting.")
			("sweep,z", po::value(&sweep)->zero_tokens(),
				"Runs sweep mode. Increment threads by 1 to <threads> and "
				"multiple size from 10 by <gap>.")
			("file,f", po::value<std::string>(),
				"File name to save output data in.");

		po::options_description sweep_po("Sweep Options (Used only if <sweep> is set)");
		sweep_po.add_options()
			("gap,g", po::value<size_t>()->default_value(DEFAULT_GAP),
				"Specifies the multiple factor to multiply vector size by"
				" in sweep mode.")
			("init_size,w",
				po::value<size_t>()->default_value(SIZE_START),
				"The initial data size to use in sweep mode.");

		po::options_description tests_po("Exclude Tests:");
		tests_po.add_options()
			("basic", po::value(&no_basic)->zero_tokens(),
				"Excludes basic sort from tests.")
			("bitonic", po::value(&no_bitonic)->zero_tokens(),
				"Excludes bitonic sort from tests.")
			("merge", po::value(&no_merge)->zero_tokens(),
				"Excludes merge sort from tests.");

		po::options_description cmd_line_options;
		cmd_line_options.add(generic).add(configuration).add(sweep_po).add(tests_po);

		// Try to parse the input parameters.
		try {
			po::store(po::parse_command_line(argc, argv, cmd_line_options),
				vm);

			// --help option
			if( vm.count("help") ) {
				std::cout << std::endl << PROG_NAME << std::endl <<
					VERSION_STRING << std::endl <<
					cmd_line_options << std::endl;
				return SUCCESS;
			}

			// --version options
			if( vm.count("version") ) {
				std::cout << std::endl << PROG_NAME << std::endl <<
					VERSION_STRING << std::endl;
			}

			po::notify(vm);
		}
		catch(po::error& e) {
			std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
			std::cerr << cmd_line_options << std::endl;
			return ERROR_ON_COMMAND_LINE;
		}

		// Input parameters were good. Now actually run the program.

		// First, get the parameters from the argument parser.
		const size_t num_threads = vm["threads"].as<size_t>();
		const size_t max_data_size	= vm["size"].as<size_t>();
		const size_t desired_gap	= vm["gap"].as<size_t>();

		// Variables used for loops below.
		size_t thread_init, size_init;

		if(sweep) {
			thread_init = THREAD_START;
			size_init	= vm["init_size"].as<size_t>();
		} else {
			thread_init	= num_threads;
			size_init	= max_data_size;
		}

		// Instantiate the sort classes.
		//QuickSort					quick_sort;
		MergeSort	*				merge_sort	= new MergeSort();
		BasicSort	*				basic_sort	= new BasicSort();
		BitonicSort	*				bio_sort	= new BitonicSort();

		CSVTools    *				csv;

		if(vm.count("file"))
			csv = new CSVTools(vm["file"].as<std::string>());

		// User has requested that data is swept.
		for(size_t curr_thread = thread_init; curr_thread <= num_threads; curr_thread++)
		{
			for(size_t curr_size = size_init; curr_size <= max_data_size; curr_size *= desired_gap)
			{
				std::cout << "Threads:             " <<
					std::setw(FIELD_WIDTH) << curr_thread << std::endl;
				std::cout << "Data Size:           " <<
					std::setw(FIELD_WIDTH) <<  curr_size << std::endl;

				SortCommon::DataType const * input_data = new SortCommon::DataType();
				input_data = SortCommon::NewData(curr_size);

				if(!no_basic)
				{
					double basic_time	= basic_sort->
						BenchmarkSort(input_data, curr_thread);
					if( vm.count("file") )
					{
						csv->WriteResult(BasicSort::kTableKey, curr_thread,
							curr_size, basic_time);
					}
					std::cout << "Basic Sort Time:     " << std::fixed  <<
						std::setw(FIELD_WIDTH) << basic_time << std::endl;
				}

				if(!no_bitonic)
				{
					double bio_time		= bio_sort->
						BenchmarkSort(input_data, curr_thread);
					if( vm.count("file") )
					{
						csv->WriteResult(BitonicSort::kTableKey, curr_thread,
							curr_size, bio_time);
					}
					std::cout << "Bitonic Sort Time:   " << std::fixed <<
						std::setw(FIELD_WIDTH) << bio_time << std::endl;
				}

				if(!no_merge)
				{
					double merge_time	= merge_sort->
						BenchmarkSort(input_data, curr_thread);
					if( vm.count("file") )
					{
						csv->WriteResult(MergeSort::kTableKey, curr_thread,
							curr_size, merge_time);
					}
					std::cout << "MergeSort Sort Time: " << std::fixed <<
						std::setw(FIELD_WIDTH) << merge_time << std::endl;
				}

				std::cout << std::endl;

				delete input_data;
			}
		}
		return SUCCESS;

	}
	catch(std::exception& e) {
		std::cerr << "Unhandled Exception reached the top of main: "
			<< e.what() << ", application will now exit" << std::endl;
		return ERROR_UNHANDLED_EXCEPTION;
 	}

}
<commit_msg>Fixing issue with sweep not having default value and setting csv to NULL.<commit_after>#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>

#include <boost/program_options.hpp>

#include "BasicSort.hpp"
#include "BitonicSort.hpp"
// #include "QuickSort.hpp"
#include "MergeSort.hpp"
#include "CSVTools.hpp"

#define THREAD_START		1
#define	SIZE_START			10
#define	DEFAULT_ELEMENTS	100
#define DEFAULT_THREADS		4
#define DEFAULT_GAP			10
#define DEFAULT_SAVE_FILE	"results.csv"

#define FIELD_WIDTH			10

#define PROG_NAME			"Laser Patroll Sorting Benchmark Application"
#define VERSION_STRING		"Version: Alpha"

// Potential return values.
const int SUCCESS                   = 0;
const int ERROR_ON_COMMAND_LINE     = 1;
const int ERROR_UNHANDLED_EXCEPTION = 2;

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

	try {
		// Setup and configure the input parser.
		namespace po = boost::program_options;
		po::variables_map vm;
		bool sweep 		= false;
		bool no_bitonic = false;
		bool no_merge 	= false;
		bool no_basic 	= false;

		// Add options here
		po::options_description generic("Program Options");
		generic.add_options()
			("help,h", "Prints out help information.")
			("version,v", "Prints out version information.");

		po::options_description configuration("Configuration Options");
		configuration.add_options()
			("size,s", po::value<size_t>()->default_value(DEFAULT_ELEMENTS),
				"Number of elements to sort.")
			("threads,t", po::value<size_t>()->default_value(DEFAULT_THREADS),
				"Number of threads to use for sorting.")
			("sweep,z", po::value(&sweep)->zero_tokens(),
				"Runs sweep mode. Increment threads by 1 to <threads> and "
				"multiple size from 10 by <gap>.")
			("file,f", po::value<std::string>(),
				"File name to save output data in.");

		po::options_description sweep_po("Sweep Options (Used only if <sweep> is set)");
		sweep_po.add_options()
			("gap,g", po::value<size_t>()->default_value(DEFAULT_GAP),
				"Specifies the multiple factor to multiply vector size by"
				" in sweep mode.")
			("init_size,w",
				po::value<size_t>()->default_value(SIZE_START),
				"The initial data size to use in sweep mode.");

		po::options_description tests_po("Exclude Tests:");
		tests_po.add_options()
			("basic", po::value(&no_basic)->zero_tokens(),
				"Excludes basic sort from tests.")
			("bitonic", po::value(&no_bitonic)->zero_tokens(),
				"Excludes bitonic sort from tests.")
			("merge", po::value(&no_merge)->zero_tokens(),
				"Excludes merge sort from tests.");

		po::options_description cmd_line_options;
		cmd_line_options.add(generic).add(configuration).add(sweep_po).add(tests_po);

		// Try to parse the input parameters.
		try {
			po::store(po::parse_command_line(argc, argv, cmd_line_options),
				vm);

			// --help option
			if( vm.count("help") ) {
				std::cout << std::endl << PROG_NAME << std::endl <<
					VERSION_STRING << std::endl <<
					cmd_line_options << std::endl;
				return SUCCESS;
			}

			// --version options
			if( vm.count("version") ) {
				std::cout << std::endl << PROG_NAME << std::endl <<
					VERSION_STRING << std::endl;
			}

			po::notify(vm);
		}
		catch(po::error& e) {
			std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
			std::cerr << cmd_line_options << std::endl;
			return ERROR_ON_COMMAND_LINE;
		}

		// Input parameters were good. Now actually run the program.

		// First, get the parameters from the argument parser.
		const size_t num_threads = vm["threads"].as<size_t>();
		const size_t max_data_size	= vm["size"].as<size_t>();
		const size_t desired_gap	= vm["gap"].as<size_t>();

		// Variables used for loops below.
		size_t thread_init, size_init;

		if(sweep) {
			thread_init = THREAD_START;
			size_init	= vm["init_size"].as<size_t>();
		} else {
			thread_init	= num_threads;
			size_init	= max_data_size;
		}

		// Instantiate the sort classes.
		//QuickSort					quick_sort;
		MergeSort	*				merge_sort	= new MergeSort();
		BasicSort	*				basic_sort	= new BasicSort();
		BitonicSort	*				bio_sort	= new BitonicSort();

		CSVTools    *				csv         = NULL;

		if(vm.count("file"))
			csv = new CSVTools(vm["file"].as<std::string>());

		// User has requested that data is swept.
		for(size_t curr_thread = thread_init; curr_thread <= num_threads; curr_thread++)
		{
			for(size_t curr_size = size_init; curr_size <= max_data_size; curr_size *= desired_gap)
			{
				std::cout << "Threads:             " <<
					std::setw(FIELD_WIDTH) << curr_thread << std::endl;
				std::cout << "Data Size:           " <<
					std::setw(FIELD_WIDTH) <<  curr_size << std::endl;

				SortCommon::DataType const * input_data = new SortCommon::DataType();
				input_data = SortCommon::NewData(curr_size);

				if(!no_basic)
				{
					double basic_time	= basic_sort->
						BenchmarkSort(input_data, curr_thread);
					if( vm.count("file") )
					{
						csv->WriteResult(BasicSort::kTableKey, curr_thread,
							curr_size, basic_time);
					}
					std::cout << "Basic Sort Time:     " << std::fixed  <<
						std::setw(FIELD_WIDTH) << basic_time << std::endl;
				}

				if(!no_bitonic)
				{
					double bio_time		= bio_sort->
						BenchmarkSort(input_data, curr_thread);
					if( vm.count("file") )
					{
						csv->WriteResult(BitonicSort::kTableKey, curr_thread,
							curr_size, bio_time);
					}
					std::cout << "Bitonic Sort Time:   " << std::fixed <<
						std::setw(FIELD_WIDTH) << bio_time << std::endl;
				}

				if(!no_merge)
				{
					double merge_time	= merge_sort->
						BenchmarkSort(input_data, curr_thread);
					if( vm.count("file") )
					{
						csv->WriteResult(MergeSort::kTableKey, curr_thread,
							curr_size, merge_time);
					}
					std::cout << "MergeSort Sort Time: " << std::fixed <<
						std::setw(FIELD_WIDTH) << merge_time << std::endl;
				}

				std::cout << std::endl;

				delete input_data;
			}
		}
		return SUCCESS;

	}
	catch(std::exception& e) {
		std::cerr << "Unhandled Exception reached the top of main: "
			<< e.what() << ", application will now exit" << std::endl;
		return ERROR_UNHANDLED_EXCEPTION;
 	}

}
<|endoftext|>


<commit_before>#include "../include/level_factory.hpp"
#include "../engine/include/persistence_dat.hpp"
#include "../engine/include/observable.hpp"
#include "../engine/include/log.hpp"
#include <unordered_map>
#include <vector>

using namespace mindscape;

typedef mindscape::GameObjectFactory::Options Opts;

/**
 * @brief Updates Game level.
 *
 * Initiates changing of level, such as changes of scenes.
 *
 * @param level Level to be changed.
 * @param path Path of new level.
 * @return void.
 */
void LevelFactory::update_level(engine::Level *level, std::string path) {
    DEBUG("Started: update_level()");

    std::vector<engine::GameObject *> new_objects = execute_dat(level, path);

    for (auto game_object : new_objects) {
        level->activate_game_object(game_object);
        game_object->load();
    }

    DEBUG("Ended: update_level()");
}

/**
 * @brief Executes Level's data.
 *
 * Sets all dimension, coordinates, audios and game's objects in the level.
 *
 * @param level Level to be changed.
 * @param path Path of the level.
 * @return GameObject Vector of new game objects.
 */
std::vector<engine::GameObject *> LevelFactory::execute_dat(
    engine::Level *level, std::string path) {
    DEBUG("Started: GameObject execute_dat()");

    std::vector<std::string> includes;
    std::vector<engine::GameObject *> added_game_objects;

    GameObjectFactory mindscape_factory = GameObjectFactory();

    engine::PersistenceDat *persistence =
        engine::PersistenceDat::get_instance();
    engine::PersistenceMap *objects = persistence->load(path);

    if (!!objects) {
        for (auto it = objects->begin(); it < objects->end(); it++) {
            std::unordered_map<std::string, std::string> object = *it;

            Opts type = static_cast<Opts>(std::stoi(object["type"]));

            if (type == Opts::HITBOX) {
                std::pair<int, int> dimensions;
                std::pair<int, int> displacement;

                dimensions.first = std::stoi(object["size_x"]);
                dimensions.second = std::stoi(object["size_y"]);

                displacement.first = std::stoi(object["displ_x"]);
                displacement.second = std::stoi(object["displ_y"]);

                mindscape_factory.fabricate_hitbox(level->get_object_by_name(
                object["belongs_to"]), displacement, dimensions);
            }

            else if (type == Opts::IMAGE) {
                int priority = 0;
                priority = std::stoi(object["priority"]);

                std::pair<int, int> displacement;
                std::pair<int, int> dimensions_on_screen;
                std::pair<int, int> dimensions_on_texture;
                std::pair<int, int> coordinatesOnTexture;

                displacement.first = std::stoi(object["displ_x"]);
                displacement.second = std::stoi(object["displ_y"]);

                dimensions_on_screen.first = std::stoi(object["screen_x"]);
                dimensions_on_screen.second = std::stoi(object["screen_y"]);
                dimensions_on_texture.first = std::stoi(object["tex_x"]);
                dimensions_on_texture.second = std::stoi(object["tex_y"]);

                coordinatesOnTexture.first = std::stoi(object["tex_coord_x"]);
                coordinatesOnTexture.second = std::stoi(object["tex_coord_y"]);

                mindscape_factory.fabricate_image(
                    level->get_object_by_name(object["belongs_to"]),
                    object["path"], displacement, priority,
                    dimensions_on_screen, dimensions_on_texture,
                    coordinatesOnTexture
                );
            }

            else if (type == Opts::TEXT) {
                int priority = 0;
                priority = std::stoi(object["priority"]);
                std::string text = object["text"];
                std::string font_path = object["font_path"];

                int font_size = 0;
                font_size = std::stoi(object["font_size"]);

                std::pair<int, int> displacement;

                displacement.first = std::stoi(object["displ_x"]);
                displacement.second = std::stoi(object["displ_y"]);

                mindscape_factory.fabricate_text(
                    level->get_object_by_name(object["belongs_to"]),
                    text, font_path, font_size, displacement, priority
                );
            }

            else if (type == Opts::AUDIO) {
                int audio_type = 0;
                std::string name = "";
                std::string path = "";

                audio_type = std::stoi(object["audio_type"]);
                name = object["id"];
                path = object["path"];

                mindscape_factory.fabricate_audio(
                    level->get_object_by_name(object["belongs_to"]),
                    name, path, audio_type
                );
            }

            else if (type == Opts::ACTION) {
                mindscape_factory.fabricate_action(
                    level->get_object_by_name(object["belongs_to"]),
                    std::stoi(object["command"]), object["param"]
                );
            }

            else if (type == Opts::TRANSLATION) {
                int key = 0;
                std::string event_name = "";

                event_name = object["event_name"];
                key = std::stoi(object["key"]);

                mindscape_factory.fabricate_translation(
                    level->get_object_by_name(object["belongs_to"]),
                    key, event_name
                );
            }

            else {
                engine::GameObject * constructed_obj =
                    mindscape_factory.fabricate(
                        type, object["id"],
                        std::make_pair(std::stoi(object["x"]),
                        std::stoi(object["y"])), std::stoi(object["priority"])
                    );

                if (object.count("follows") > 0) { //if follow key is declared

                    engine::Observable * observable =
                        level->get_object_by_name(object["follows"]);

                    observable->attach_observer(constructed_obj);
                }
                level->add_object(constructed_obj);
                added_game_objects.push_back(constructed_obj);
            }
        }
    }

    return added_game_objects;

    DEBUG("Ended: GameObject execute_dat()");
}

/**
 * @brief Fabricates Game Level.
 *
 * Realizes all the process to build the game level.
 *
 * @fn execute_dat Decribed above.
 * @param path Path of the level datas.
 * @return GameObject Vector of new game objects.
 */
engine::Level *LevelFactory::fabricate_level(std::string path) {
    INFO("Building Game Level");

    engine::Level *level = new engine::Level();
    execute_dat(level, path);

    return level;

    DEBUG("Ended: Building Game level");
}

/**
 * @brief Fabricates Menu.
 *
 * Returns a level null for fabricates the menu.
 *
 * @return Level null.
 */
engine::Level* LevelFactory::fabricate_menu(){
    INFO("Fabricates the menu");

    return NULL;
}

/**
 * @brief Fabricates Game Over.
 *
 * Returns a level null for fabricates game over.
 *
 * @return Level null.
 */
engine::Level* LevelFactory::fabricate_game_over(){
    INFO("Fabricates Game Over");

    return NULL;
}
<commit_msg>[DEFAULT BEHAVIOR] Applies default behavior in level_factory.cpp<commit_after>#include "../include/level_factory.hpp"
#include "../engine/include/persistence_dat.hpp"
#include "../engine/include/observable.hpp"
#include "../engine/include/log.hpp"
#include <unordered_map>
#include <vector>

using namespace mindscape;

typedef mindscape::GameObjectFactory::Options Opts;

/**
 * @brief Updates Game level.
 *
 * Initiates changing of level, such as changes of scenes.
 *
 * @param level Level to be changed.
 * @param path Path of new level.
 * @return void.
 */
void LevelFactory::update_level(engine::Level *level, std::string path) {
    DEBUG("Started: update_level()");

    std::vector<engine::GameObject *> new_objects = execute_dat(level, path);

    for (auto game_object : new_objects) {
        level->activate_game_object(game_object);
        game_object->load();
    }

    DEBUG("Ended: update_level()");
}

/**
 * @brief Executes Level's data.
 *
 * Sets all dimension, coordinates, audios and game's objects in the level.
 *
 * @param level Level to be changed.
 * @param path Path of the level.
 * @return GameObject Vector of new game objects.
 */
std::vector<engine::GameObject *> LevelFactory::execute_dat(
    engine::Level *level, std::string path) {
    DEBUG("Started: GameObject execute_dat()");

    std::vector<std::string> includes;
    std::vector<engine::GameObject *> added_game_objects;

    GameObjectFactory mindscape_factory = GameObjectFactory();
    engine::PersistenceDat *persistence =
        engine::PersistenceDat::get_instance();
    engine::PersistenceMap *objects = persistence->load(path);

    if (!!objects) {
        for (auto it = objects->begin(); it < objects->end(); it++) {
            std::unordered_map<std::string, std::string> object = *it;

            Opts type = static_cast<Opts>(std::stoi(object["type"]));

            if (type == Opts::HITBOX) {
                std::pair<int, int> dimensions;
                std::pair<int, int> displacement;

                dimensions.first = std::stoi(object["size_x"]);
                dimensions.second = std::stoi(object["size_y"]);

                displacement.first = std::stoi(object["displ_x"]);
                displacement.second = std::stoi(object["displ_y"]);

                mindscape_factory.fabricate_hitbox(level->get_object_by_name(
                object["belongs_to"]), displacement, dimensions);
            }

            else if (type == Opts::IMAGE) {
                int priority = 0;
                priority = std::stoi(object["priority"]);

                std::pair<int, int> displacement;

                displacement.first = std::stoi(object["displ_x"]);
                displacement.second = std::stoi(object["displ_y"]);

                std::pair<int, int> dimensions_on_screen;

                dimensions_on_screen.first = std::stoi(object["screen_x"]);
                dimensions_on_screen.second = std::stoi(object["screen_y"]);

                std::pair<int, int> dimensions_on_texture;

                dimensions_on_texture.first = std::stoi(object["tex_x"]);
                dimensions_on_texture.second = std::stoi(object["tex_y"]);

                std::pair<int, int> coordinatesOnTexture;

                coordinatesOnTexture.first = std::stoi(object["tex_coord_x"]);
                coordinatesOnTexture.second = std::stoi(object["tex_coord_y"]);

                mindscape_factory.fabricate_image(
                    level->get_object_by_name(object["belongs_to"]),
                    object["path"], displacement, priority,
                    dimensions_on_screen, dimensions_on_texture,
                    coordinatesOnTexture
                );
            }

            else if (type == Opts::TEXT) {
                int priority = 0;
                priority = std::stoi(object["priority"]);

                std::string text = object["text"];
                std::string font_path = object["font_path"];

                int font_size = 0;
                font_size = std::stoi(object["font_size"]);

                std::pair<int, int> displacement;

                displacement.first = std::stoi(object["displ_x"]);
                displacement.second = std::stoi(object["displ_y"]);

                mindscape_factory.fabricate_text(
                    level->get_object_by_name(object["belongs_to"]),
                    text, font_path, font_size, displacement, priority
                );
            }

            else if (type == Opts::AUDIO) {
                int audio_type = 0;
                std::string name = "";
                std::string path = "";

                audio_type = std::stoi(object["audio_type"]);
                name = object["id"];
                path = object["path"];

                mindscape_factory.fabricate_audio(
                    level->get_object_by_name(object["belongs_to"]),
                    name, path, audio_type
                );
            }

            else if (type == Opts::ACTION) {
                mindscape_factory.fabricate_action(
                    level->get_object_by_name(object["belongs_to"]),
                    std::stoi(object["command"]), object["param"]
                );
            }

            else if (type == Opts::TRANSLATION) {
                int key = 0;
                std::string event_name = "";

                event_name = object["event_name"];
                key = std::stoi(object["key"]);

                mindscape_factory.fabricate_translation(
                    level->get_object_by_name(object["belongs_to"]),
                    key, event_name
                );
            }

            else {
                engine::GameObject * constructed_obj =
                    mindscape_factory.fabricate(
                        type, object["id"],
                        std::make_pair(std::stoi(object["x"]),
                        std::stoi(object["y"])), std::stoi(object["priority"])
                    );

                /* If follow key is declared */
                if (object.count("follows") > 0) {
                    engine::Observable * observable =
                        level->get_object_by_name(object["follows"]);

                    observable->attach_observer(constructed_obj);
                }
                else {
                    INFO("Follow Key is not declared");
                }

                level->add_object(constructed_obj);
                added_game_objects.push_back(constructed_obj);
            }
        }
    }
    else {
        /* Do nothing */
    }

    return added_game_objects;

    DEBUG("Ended: GameObject execute_dat()");
}

/**
 * @brief Fabricates Game Level.
 *
 * Realizes all the process to build the game level.
 *
 * @fn execute_dat Decribed above.
 * @param path Path of the level datas.
 * @return GameObject Vector of new game objects.
 */
engine::Level *LevelFactory::fabricate_level(std::string path) {
    INFO("Building Game Level");

    engine::Level *level = new engine::Level();
    execute_dat(level, path);

    return level;

    DEBUG("Ended: Building Game level");
}

/**
 * @brief Fabricates Menu.
 *
 * Returns a level null for fabricates the menu.
 *
 * @return Level null.
 */
engine::Level* LevelFactory::fabricate_menu(){
    INFO("Fabricates the menu");

    return NULL;
}

/**
 * @brief Fabricates Game Over.
 *
 * Returns a level null for fabricates game over.
 *
 * @return Level null.
 */
engine::Level* LevelFactory::fabricate_game_over(){
    INFO("Fabricates Game Over");

    return NULL;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: filid.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2004-05-10 14:21:28 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _FILID_HXX_
#include "filid.hxx"
#endif
#ifndef _SHELL_HXX_
#include "shell.hxx"
#endif

using namespace fileaccess;
using namespace com::sun::star;
using namespace com::sun::star::ucb;

FileContentIdentifier::FileContentIdentifier(
    shell* pMyShell,
    const rtl::OUString& aUnqPath,
    sal_Bool IsNormalized )
    : m_pMyShell( pMyShell ),
      m_bNormalized( IsNormalized )
{
    if( IsNormalized )
    {
        m_pMyShell->getUrlFromUnq( aUnqPath,m_aContentId );
        m_aNormalizedId = aUnqPath;
        m_pMyShell->getScheme( m_aProviderScheme );
    }
    else
    {
        m_pMyShell->getUnqFromUrl( aUnqPath,m_aNormalizedId );
        m_aContentId = aUnqPath;
        m_pMyShell->getScheme( m_aProviderScheme );
    }
}

FileContentIdentifier::~FileContentIdentifier()
{
}

void SAL_CALL
FileContentIdentifier::acquire(
    void )
    throw()
{
    OWeakObject::acquire();
}

void SAL_CALL
FileContentIdentifier::release(
                void )
  throw()
{
  OWeakObject::release();
}

uno::Any SAL_CALL
FileContentIdentifier::queryInterface(
    const uno::Type& rType )
    throw( uno::RuntimeException )
{
    uno::Any aRet = cppu::queryInterface( rType,
                                          SAL_STATIC_CAST( lang::XTypeProvider*, this),
                                          SAL_STATIC_CAST( XContentIdentifier*, this) );
    return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType );
}

uno::Sequence< sal_Int8 > SAL_CALL
FileContentIdentifier::getImplementationId()
    throw( uno::RuntimeException )
{
    static cppu::OImplementationId* pId = NULL;
    if ( !pId )
    {
        osl::Guard< osl::Mutex > aGuard( osl::Mutex::getGlobalMutex() );
        if ( !pId )
        {
            static cppu::OImplementationId id( sal_False );
            pId = &id;
        }
    }
    return (*pId).getImplementationId();
}

uno::Sequence< uno::Type > SAL_CALL
FileContentIdentifier::getTypes(
    void )
    throw( uno::RuntimeException )
{
    static cppu::OTypeCollection* pCollection = NULL;
    if ( !pCollection ) {
        osl::Guard< osl::Mutex > aGuard( osl::Mutex::getGlobalMutex() );
        if ( !pCollection )
        {
            static cppu::OTypeCollection collection(
                getCppuType( static_cast< uno::Reference< lang::XTypeProvider >* >( 0 ) ),
                getCppuType( static_cast< uno::Reference< XContentIdentifier >* >( 0 ) ) );
            pCollection = &collection;
        }
    }
    return (*pCollection).getTypes();
}

rtl::OUString
SAL_CALL
FileContentIdentifier::getContentIdentifier(
    void )
    throw( uno::RuntimeException )
{
    return m_aContentId;
}

rtl::OUString SAL_CALL
FileContentIdentifier::getContentProviderScheme(
    void )
    throw( uno::RuntimeException )
{
    return m_aProviderScheme;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.94); FILE MERGED 2005/09/05 18:45:00 rt 1.5.94.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: filid.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 15:23:59 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _FILID_HXX_
#include "filid.hxx"
#endif
#ifndef _SHELL_HXX_
#include "shell.hxx"
#endif

using namespace fileaccess;
using namespace com::sun::star;
using namespace com::sun::star::ucb;

FileContentIdentifier::FileContentIdentifier(
    shell* pMyShell,
    const rtl::OUString& aUnqPath,
    sal_Bool IsNormalized )
    : m_pMyShell( pMyShell ),
      m_bNormalized( IsNormalized )
{
    if( IsNormalized )
    {
        m_pMyShell->getUrlFromUnq( aUnqPath,m_aContentId );
        m_aNormalizedId = aUnqPath;
        m_pMyShell->getScheme( m_aProviderScheme );
    }
    else
    {
        m_pMyShell->getUnqFromUrl( aUnqPath,m_aNormalizedId );
        m_aContentId = aUnqPath;
        m_pMyShell->getScheme( m_aProviderScheme );
    }
}

FileContentIdentifier::~FileContentIdentifier()
{
}

void SAL_CALL
FileContentIdentifier::acquire(
    void )
    throw()
{
    OWeakObject::acquire();
}

void SAL_CALL
FileContentIdentifier::release(
                void )
  throw()
{
  OWeakObject::release();
}

uno::Any SAL_CALL
FileContentIdentifier::queryInterface(
    const uno::Type& rType )
    throw( uno::RuntimeException )
{
    uno::Any aRet = cppu::queryInterface( rType,
                                          SAL_STATIC_CAST( lang::XTypeProvider*, this),
                                          SAL_STATIC_CAST( XContentIdentifier*, this) );
    return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType );
}

uno::Sequence< sal_Int8 > SAL_CALL
FileContentIdentifier::getImplementationId()
    throw( uno::RuntimeException )
{
    static cppu::OImplementationId* pId = NULL;
    if ( !pId )
    {
        osl::Guard< osl::Mutex > aGuard( osl::Mutex::getGlobalMutex() );
        if ( !pId )
        {
            static cppu::OImplementationId id( sal_False );
            pId = &id;
        }
    }
    return (*pId).getImplementationId();
}

uno::Sequence< uno::Type > SAL_CALL
FileContentIdentifier::getTypes(
    void )
    throw( uno::RuntimeException )
{
    static cppu::OTypeCollection* pCollection = NULL;
    if ( !pCollection ) {
        osl::Guard< osl::Mutex > aGuard( osl::Mutex::getGlobalMutex() );
        if ( !pCollection )
        {
            static cppu::OTypeCollection collection(
                getCppuType( static_cast< uno::Reference< lang::XTypeProvider >* >( 0 ) ),
                getCppuType( static_cast< uno::Reference< XContentIdentifier >* >( 0 ) ) );
            pCollection = &collection;
        }
    }
    return (*pCollection).getTypes();
}

rtl::OUString
SAL_CALL
FileContentIdentifier::getContentIdentifier(
    void )
    throw( uno::RuntimeException )
{
    return m_aContentId;
}

rtl::OUString SAL_CALL
FileContentIdentifier::getContentProviderScheme(
    void )
    throw( uno::RuntimeException )
{
    return m_aProviderScheme;
}
<|endoftext|>


<commit_before>/*$Id$
 *
 * This source file is a part of the Fresco Project.
 * Copyright (C) 1998 Graydon Hoare <graydon@fresco.org>
 * Copyright (C) 1999, 2000 Stefan Seefeld <stefan@fresco.org>
 * http://www.fresco.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */

#include <Fresco/config.hh>
#include <Fresco/DrawingKit.hh>
#include <Fresco/DrawTraversal.hh>
#include <Fresco/Region.hh>
#include <Fresco/IO.hh>
#include "TextChunk.hh"

#include <strstream>

using namespace Fresco;

using namespace Berlin::TextKit;

TextChunk::TextChunk(Unichar u, const Fresco::Graphic::Requisition &r)
  : _width(r.x.natural), _height(r.y.natural), _xalign(r.x.align), _yalign(r.y.align), _char(u), _obj_name(0)
{
}

TextChunk::~TextChunk()
{
  if (_obj_name) free(const_cast<char*>(_obj_name));
}

void TextChunk::request(Fresco::Graphic::Requisition &r)
{
  r.x.defined = true;
  r.x.minimum = r.x.natural = r.x.maximum = _width;
  r.x.align   = _xalign;
  r.y.defined = true;
  r.y.minimum = r.y.natural = r.y.maximum = _height;
  r.y.align   = _yalign;
}

const char *TextChunk::object_name()
{
  if (_obj_name) return _obj_name;
  std::ostringstream buf;
  buf << "Char ";
  if (_char < 128) buf << (char)_char << std::ends;
  else buf << _char << std::ends;
  _obj_name = strdup(buf.str().c_str());
  return _obj_name;
}

void TextChunk::get_text(Babylon::String &u)
{
  u = Babylon::String(_char);
}

unsigned long TextChunk::get_length()
{
  return 1;
}

void TextChunk::draw(DrawTraversal_ptr traversal)
{
  DrawingKit_var drawing = traversal->drawing();
  drawing->draw_char(_char);
}
<commit_msg>s/strstream/sstream/<commit_after>/*$Id$
 *
 * This source file is a part of the Fresco Project.
 * Copyright (C) 1998 Graydon Hoare <graydon@fresco.org>
 * Copyright (C) 1999, 2000 Stefan Seefeld <stefan@fresco.org>
 * http://www.fresco.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */

#include <Fresco/config.hh>
#include <Fresco/DrawingKit.hh>
#include <Fresco/DrawTraversal.hh>
#include <Fresco/Region.hh>
#include <Fresco/IO.hh>
#include "TextChunk.hh"

#include <sstream>

using namespace Fresco;

using namespace Berlin::TextKit;

TextChunk::TextChunk(Unichar u, const Fresco::Graphic::Requisition &r)
  : _width(r.x.natural), _height(r.y.natural), _xalign(r.x.align), _yalign(r.y.align), _char(u), _obj_name(0)
{
}

TextChunk::~TextChunk()
{
  if (_obj_name) free(const_cast<char*>(_obj_name));
}

void TextChunk::request(Fresco::Graphic::Requisition &r)
{
  r.x.defined = true;
  r.x.minimum = r.x.natural = r.x.maximum = _width;
  r.x.align   = _xalign;
  r.y.defined = true;
  r.y.minimum = r.y.natural = r.y.maximum = _height;
  r.y.align   = _yalign;
}

const char *TextChunk::object_name()
{
  if (_obj_name) return _obj_name;
  std::ostringstream buf;
  buf << "Char ";
  if (_char < 128) buf << (char)_char << std::ends;
  else buf << _char << std::ends;
  _obj_name = strdup(buf.str().c_str());
  return _obj_name;
}

void TextChunk::get_text(Babylon::String &u)
{
  u = Babylon::String(_char);
}

unsigned long TextChunk::get_length()
{
  return 1;
}

void TextChunk::draw(DrawTraversal_ptr traversal)
{
  DrawingKit_var drawing = traversal->drawing();
  drawing->draw_char(_char);
}
<|endoftext|>


<commit_before>//   Copyright 2016-2019 Jean-Francois Poilpret
//
//   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 <fastarduino/time.h>
#include <fastarduino/i2c_device.h>
#include <fastarduino/devices/mcp23017.h>

constexpr const i2c::I2CMode I2C_MODE = i2c::I2CMode::Fast;

using MCP = devices::MCP23017<I2C_MODE>;
using MCP_PORT = devices::MCP23017Port;

static inline uint8_t shift_pattern(uint8_t pattern, uint8_t shift, bool direction)
{
	if (direction) shift = 8 - shift;
	uint16_t result = (pattern << shift);
	return result | (result >> 8);
}

static inline uint8_t calculate_pattern(uint8_t switches)
{
	switch ((~switches) & 0x07)
	{
		case 0x00:
		return 0x01;

		case 0x01:
		return 0x03;

		case 0x02:
		return 0x07;

		case 0x03:
		return 0x0F;

		case 0x04:
		return 0x55;

		case 0x05:
		return 0x33;

		case 0x06:
		return 0x11;

		case 0x07:
		return 0xDB;
	}
}

int main() __attribute__((OS_main));
int main()
{
	board::init();
	sei();

	// Start TWI interface
	//====================
	i2c::I2CManager<I2C_MODE> manager;
	manager.begin();

	// Initialize chip
	//=================
	time::delay_ms(100);
	MCP mcp{manager, 0x00};
	mcp.configure_gpio<MCP_PORT::PORT_AB>(0x0F00, 0x0F00);
	// mcp.configure_gpio<MCP_PORT::PORT_A>(0x00);
	// mcp.configure_gpio<MCP_PORT::PORT_B>(0x0F, 0x0F);

	mcp.values<MCP_PORT::PORT_AB>(0x0011);
	time::delay_ms(1000);
	mcp.values<MCP_PORT::PORT_AB>(0x0000);

	// Loop of the LED chaser
	uint8_t switches = (mcp.values<MCP_PORT::PORT_AB>() >> 8) & 0x0F;
	bool direction = (~switches) & 0x08;
	uint8_t pattern = calculate_pattern(switches);
	while (true)
	{
		uint8_t new_switches = (mcp.values<MCP_PORT::PORT_AB>() >> 8) & 0x0F;
		if (switches != new_switches)
		{
			switches = new_switches;
			direction = (~switches) & 0x08;
			pattern = calculate_pattern(switches);
		}
		for (uint8_t i = 0; i < 8; ++i)
		{
			mcp.values<MCP_PORT::PORT_AB>(shift_pattern(pattern, i, direction));
			time::delay_ms(250);
		}
	}

	// Stop TWI interface
	//===================
	manager.end();
}
<commit_msg>Remove obsolete comments.<commit_after>//   Copyright 2016-2019 Jean-Francois Poilpret
//
//   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 <fastarduino/time.h>
#include <fastarduino/i2c_device.h>
#include <fastarduino/devices/mcp23017.h>

constexpr const i2c::I2CMode I2C_MODE = i2c::I2CMode::Fast;

using MCP = devices::MCP23017<I2C_MODE>;
using MCP_PORT = devices::MCP23017Port;

static inline uint8_t shift_pattern(uint8_t pattern, uint8_t shift, bool direction)
{
	if (direction) shift = 8 - shift;
	uint16_t result = (pattern << shift);
	return result | (result >> 8);
}

static inline uint8_t calculate_pattern(uint8_t switches)
{
	switch ((~switches) & 0x07)
	{
		case 0x00:
		return 0x01;

		case 0x01:
		return 0x03;

		case 0x02:
		return 0x07;

		case 0x03:
		return 0x0F;

		case 0x04:
		return 0x55;

		case 0x05:
		return 0x33;

		case 0x06:
		return 0x11;

		case 0x07:
		return 0xDB;
	}
}

int main() __attribute__((OS_main));
int main()
{
	board::init();
	sei();

	// Start TWI interface
	//====================
	i2c::I2CManager<I2C_MODE> manager;
	manager.begin();

	// Initialize chip
	//=================
	time::delay_ms(100);
	MCP mcp{manager, 0x00};
	mcp.configure_gpio<MCP_PORT::PORT_AB>(0x0F00, 0x0F00);

	mcp.values<MCP_PORT::PORT_AB>(0x0011);
	time::delay_ms(1000);
	mcp.values<MCP_PORT::PORT_AB>(0x0000);

	// Loop of the LED chaser
	uint8_t switches = (mcp.values<MCP_PORT::PORT_AB>() >> 8) & 0x0F;
	bool direction = (~switches) & 0x08;
	uint8_t pattern = calculate_pattern(switches);
	while (true)
	{
		uint8_t new_switches = (mcp.values<MCP_PORT::PORT_AB>() >> 8) & 0x0F;
		if (switches != new_switches)
		{
			switches = new_switches;
			direction = (~switches) & 0x08;
			pattern = calculate_pattern(switches);
		}
		for (uint8_t i = 0; i < 8; ++i)
		{
			mcp.values<MCP_PORT::PORT_AB>(shift_pattern(pattern, i, direction));
			time::delay_ms(250);
		}
	}

	// Stop TWI interface
	//===================
	manager.end();
}
<|endoftext|>


<commit_before>
#include "local_tree.h"
#include "matrices.h"

namespace argweaver {

using namespace std;

//=============================================================================
// Sample recombinations

double recomb_prob_unnormalized(const ArgModel *model, const LocalTree *tree,
                                const LineageCounts &lineages,
                                const State &last_state,
                                const State &state,
                                const NodePoint &recomb, bool internal)
{
    const int k = recomb.time;
    const int j = state.time;

    int root_time;
    int recomb_parent_age;
    if (internal) {
        int subtree_root = tree->nodes[tree->root].child[0];
        int maintree_root = tree->nodes[tree->root].child[1];
        root_time = max(tree->nodes[maintree_root].age, last_state.time);
        recomb_parent_age = (recomb.node == subtree_root ||
                             tree->nodes[recomb.node].parent == -1 ||
                             recomb.node == last_state.node) ?
            last_state.time :
            tree->nodes[tree->nodes[recomb.node].parent].age;
    } else {
        root_time = max(tree->nodes[tree->root].age, last_state.time);
        recomb_parent_age = (recomb.node == -1 ||
                             tree->nodes[recomb.node].parent == -1 ||
                             recomb.node == last_state.node) ?
            last_state.time :
            tree->nodes[tree->nodes[recomb.node].parent].age;
    }

    int nbranches_k = lineages.nbranches[k]
        + int(k < last_state.time);
    int nrecombs_k = lineages.nrecombs[k]
        + int(k <= last_state.time)
        + int(k == last_state.time)
        - int(k == root_time);

    // The commented-out section would be correct if we were rounding
    // recombs to nearest time point in the same way as coals (keep because
    // hope to make this change eventually)
    /*double precomb = nbranches_k*model->coal_time_steps[2*k]/nrecombs_k;
    if (k > 0) {
	int m=k-1;
	int nbranches_m = lineages.nbranches[m]
            + int(m < last_state.time)
            - int(m < recomb_parent_age);
	int nrecombs_m = lineages.nrecombs[m]
            + int(m <= last_state.time)
            + int(m == last_state.time);
	precomb += nbranches_m*model->coal_time_steps[2*k-1]/nrecombs_m;
    }*/
    double precomb = nbranches_k * model->time_steps[k] / nrecombs_k;

    // probability of not coalescing before time j-1
    double sum = 0.0;
    for (int m=k; m<j-1; m++) {
        int nbranches_m = lineages.nbranches[m]
            + int(m < last_state.time)
            - int(m < recomb_parent_age);
	sum += (model->time_steps[m] * nbranches_m
		/ (2.0 * model->popsizes[m]));
    }

    // probability of coalescing at time j
    double pcoal = 1.0;
    int nbranches_j = lineages.nbranches[j]
        + int(j < last_state.time)
        - int(j < recomb_parent_age);
    assert(nbranches_j > 0);
    if (k == j) {
        // in this case coalesce event must happen between time
        // j,j+1/2 (coal_time_step[2j])
        // NOTE: if k == ntimes - 2, coalescence is probability 1.0
        if (j < model->ntimes - 2) {
            pcoal = 1.0 - exp(-model->coal_time_steps[2*j] * nbranches_j
                              / (2.0 * model->popsizes[j]));
        }
    } else {
        // otherwise it could happen anytime between j-1/2 and j+1/2
	int m = j - 1;
	int nbranches_m = lineages.nbranches[m]
            + int(m < last_state.time)
            - int(m < recomb_parent_age);
	// have to not coalesce in the first half interval before j
	sum += (model->coal_time_steps[2*m] * nbranches_m
                / (2.0 * model->popsizes[m]));

        // NOTE: if k == ntimes - 2, coalescence is probability 1.0
        if (j < model->ntimes - 2) {
            pcoal = 1.0 - exp(
                -model->coal_time_steps[2*j-1] * nbranches_m
                / (2.0 * model->popsizes[m])
                - model->coal_time_steps[2*j] * nbranches_j
                / (2.0 * model->popsizes[j]));
        }
    }

    // probability of recoalescing on a choosen branch
    int ncoals_j = lineages.ncoals[j]
        - int(j <= recomb_parent_age) - int(j == recomb_parent_age);
    pcoal /= ncoals_j;

    return precomb * exp(- sum) * pcoal;
}

// Returns the possible recombination events that are compatiable with
// the transition (last_state -> state).
void get_possible_recomb(const LocalTree *tree,
                         const State last_state, const State state,
                         bool internal, vector<NodePoint> &candidates)
{
    // represents the branch above the new node in the tree.
    const int new_node = -1;

    int end_time = min(state.time, last_state.time);
    if (state.node == last_state.node) {
        // y = v, k in [0, min(timei, last_timei)]
        // y = node, k in Sr(node)
        for (int k=tree->nodes[state.node].age; k<=end_time; k++)
            candidates.push_back(NodePoint(state.node, k));
    }

    if (internal) {
        const int subtree_root = tree->nodes[tree->root].child[0];
        const int subtree_root_age = tree->nodes[subtree_root].age;
        for (int k=subtree_root_age; k<=end_time; k++)
            candidates.push_back(NodePoint(subtree_root, k));
    } else {
        for (int k=0; k<=end_time; k++)
            candidates.push_back(NodePoint(new_node, k));
    }
}

void sample_recombinations(
    const LocalTrees *trees, const ArgModel *model,
    ArgHmmMatrixIter *matrix_iter,
    int *thread_path, vector<int> &recomb_pos, vector<NodePoint> &recombs,
    bool internal)
{
    States states;
    LineageCounts lineages(model->ntimes);
    vector <NodePoint> candidates;
    vector <double> probs;

    // loop through local blocks
    for (matrix_iter->begin(); matrix_iter->more(); matrix_iter->next()) {

        // get local block information
        ArgHmmMatrices &matrices = matrix_iter->ref_matrices();
        LocalTree *tree = matrix_iter->get_tree_spr()->tree;
        lineages.count(tree, internal);
        matrices.states_model.get_coal_states(tree, states);
        int next_recomb = -1;

        // don't sample recombination if there is no state space
        if (internal && states.size() == 0)
            continue;

        int start = matrix_iter->get_block_start();
        int end = matrix_iter->get_block_end();
        if (matrices.transmat_switch || start == trees->start_coord) {
            // don't allow new recomb at start if we are switching blocks
            start++;
        }

        // loop through positions in block
        for (int i=start; i<end; i++) {

            if (thread_path[i] == thread_path[i-1]) {
                // no change in state, recombination is optional

                if (i > next_recomb) {
                    // sample the next recomb pos
                    int last_state = thread_path[i-1];
                    TransMatrix *m = matrices.transmat;
                    int a = states[last_state].time;
                    double self_trans = m->get(
                        tree, states, last_state, last_state);
                    double rate = 1.0 - (m->norecombs[a] / self_trans);

                    // NOTE: the min prevents large floats from overflowing
                    // when cast to int
                    next_recomb = int(min(double(end), i + expovariate(rate)));
                }

                if (i < next_recomb)
                    continue;
            }

            // sample recombination
            next_recomb = -1;
            State state = states[thread_path[i]];
            State last_state = states[thread_path[i-1]];

            // there must be a recombination
            // either because state changed or we choose to recombine
            // find candidates
            candidates.clear();
            get_possible_recomb(tree, last_state, state, internal, candidates);

            // compute probability of each candidate
            probs.clear();
            for (vector<NodePoint>::iterator it=candidates.begin();
                 it != candidates.end(); ++it) {
                probs.push_back(recomb_prob_unnormalized(
                    model, tree, lineages, last_state, state, *it, internal));
            }

            // sample recombination
            recomb_pos.push_back(i);
            recombs.push_back(candidates[sample(&probs[0], probs.size())]);

            assert(recombs[recombs.size()-1].time <= min(state.time,
                                                         last_state.time));
        }
    }
}

} // namespace argweaver
<commit_msg>remove tabs<commit_after>
#include "local_tree.h"
#include "matrices.h"

namespace argweaver {

using namespace std;

//=============================================================================
// Sample recombinations

double recomb_prob_unnormalized(const ArgModel *model, const LocalTree *tree,
                                const LineageCounts &lineages,
                                const State &last_state,
                                const State &state,
                                const NodePoint &recomb, bool internal)
{
    const int k = recomb.time;
    const int j = state.time;

    int root_time;
    int recomb_parent_age;
    if (internal) {
        int subtree_root = tree->nodes[tree->root].child[0];
        int maintree_root = tree->nodes[tree->root].child[1];
        root_time = max(tree->nodes[maintree_root].age, last_state.time);
        recomb_parent_age = (recomb.node == subtree_root ||
                             tree->nodes[recomb.node].parent == -1 ||
                             recomb.node == last_state.node) ?
            last_state.time :
            tree->nodes[tree->nodes[recomb.node].parent].age;
    } else {
        root_time = max(tree->nodes[tree->root].age, last_state.time);
        recomb_parent_age = (recomb.node == -1 ||
                             tree->nodes[recomb.node].parent == -1 ||
                             recomb.node == last_state.node) ?
            last_state.time :
            tree->nodes[tree->nodes[recomb.node].parent].age;
    }

    int nbranches_k = lineages.nbranches[k]
        + int(k < last_state.time);
    int nrecombs_k = lineages.nrecombs[k]
        + int(k <= last_state.time)
        + int(k == last_state.time)
        - int(k == root_time);

    // The commented-out section would be correct if we were rounding
    // recombs to nearest time point in the same way as coals (keep because
    // hope to make this change eventually)
    /*double precomb = nbranches_k*model->coal_time_steps[2*k]/nrecombs_k;
    if (k > 0) {
        int m=k-1;
        int nbranches_m = lineages.nbranches[m]
            + int(m < last_state.time)
            - int(m < recomb_parent_age);
        int nrecombs_m = lineages.nrecombs[m]
            + int(m <= last_state.time)
            + int(m == last_state.time);
        precomb += nbranches_m*model->coal_time_steps[2*k-1]/nrecombs_m;
    }*/
    double precomb = nbranches_k * model->time_steps[k] / nrecombs_k;

    // probability of not coalescing before time j-1
    double sum = 0.0;
    for (int m=k; m<j-1; m++) {
        int nbranches_m = lineages.nbranches[m]
            + int(m < last_state.time)
            - int(m < recomb_parent_age);
        sum += (model->time_steps[m] * nbranches_m
                / (2.0 * model->popsizes[m]));
    }

    // probability of coalescing at time j
    double pcoal = 1.0;
    int nbranches_j = lineages.nbranches[j]
        + int(j < last_state.time)
        - int(j < recomb_parent_age);
    assert(nbranches_j > 0);
    if (k == j) {
        // in this case coalesce event must happen between time
        // j,j+1/2 (coal_time_step[2j])
        // NOTE: if k == ntimes - 2, coalescence is probability 1.0
        if (j < model->ntimes - 2) {
            pcoal = 1.0 - exp(-model->coal_time_steps[2*j] * nbranches_j
                              / (2.0 * model->popsizes[j]));
        }
    } else {
        // otherwise it could happen anytime between j-1/2 and j+1/2
        int m = j - 1;
        int nbranches_m = lineages.nbranches[m]
            + int(m < last_state.time)
            - int(m < recomb_parent_age);
        // have to not coalesce in the first half interval before j
        sum += (model->coal_time_steps[2*m] * nbranches_m
                / (2.0 * model->popsizes[m]));

        // NOTE: if k == ntimes - 2, coalescence is probability 1.0
        if (j < model->ntimes - 2) {
            pcoal = 1.0 - exp(
                -model->coal_time_steps[2*j-1] * nbranches_m
                / (2.0 * model->popsizes[m])
                - model->coal_time_steps[2*j] * nbranches_j
                / (2.0 * model->popsizes[j]));
        }
    }

    // probability of recoalescing on a choosen branch
    int ncoals_j = lineages.ncoals[j]
        - int(j <= recomb_parent_age) - int(j == recomb_parent_age);
    pcoal /= ncoals_j;

    return precomb * exp(- sum) * pcoal;
}

// Returns the possible recombination events that are compatiable with
// the transition (last_state -> state).
void get_possible_recomb(const LocalTree *tree,
                         const State last_state, const State state,
                         bool internal, vector<NodePoint> &candidates)
{
    // represents the branch above the new node in the tree.
    const int new_node = -1;

    int end_time = min(state.time, last_state.time);
    if (state.node == last_state.node) {
        // y = v, k in [0, min(timei, last_timei)]
        // y = node, k in Sr(node)
        for (int k=tree->nodes[state.node].age; k<=end_time; k++)
            candidates.push_back(NodePoint(state.node, k));
    }

    if (internal) {
        const int subtree_root = tree->nodes[tree->root].child[0];
        const int subtree_root_age = tree->nodes[subtree_root].age;
        for (int k=subtree_root_age; k<=end_time; k++)
            candidates.push_back(NodePoint(subtree_root, k));
    } else {
        for (int k=0; k<=end_time; k++)
            candidates.push_back(NodePoint(new_node, k));
    }
}

void sample_recombinations(
    const LocalTrees *trees, const ArgModel *model,
    ArgHmmMatrixIter *matrix_iter,
    int *thread_path, vector<int> &recomb_pos, vector<NodePoint> &recombs,
    bool internal)
{
    States states;
    LineageCounts lineages(model->ntimes);
    vector <NodePoint> candidates;
    vector <double> probs;

    // loop through local blocks
    for (matrix_iter->begin(); matrix_iter->more(); matrix_iter->next()) {

        // get local block information
        ArgHmmMatrices &matrices = matrix_iter->ref_matrices();
        LocalTree *tree = matrix_iter->get_tree_spr()->tree;
        lineages.count(tree, internal);
        matrices.states_model.get_coal_states(tree, states);
        int next_recomb = -1;

        // don't sample recombination if there is no state space
        if (internal && states.size() == 0)
            continue;

        int start = matrix_iter->get_block_start();
        int end = matrix_iter->get_block_end();
        if (matrices.transmat_switch || start == trees->start_coord) {
            // don't allow new recomb at start if we are switching blocks
            start++;
        }

        // loop through positions in block
        for (int i=start; i<end; i++) {

            if (thread_path[i] == thread_path[i-1]) {
                // no change in state, recombination is optional

                if (i > next_recomb) {
                    // sample the next recomb pos
                    int last_state = thread_path[i-1];
                    TransMatrix *m = matrices.transmat;
                    int a = states[last_state].time;
                    double self_trans = m->get(
                        tree, states, last_state, last_state);
                    double rate = 1.0 - (m->norecombs[a] / self_trans);

                    // NOTE: the min prevents large floats from overflowing
                    // when cast to int
                    next_recomb = int(min(double(end), i + expovariate(rate)));
                }

                if (i < next_recomb)
                    continue;
            }

            // sample recombination
            next_recomb = -1;
            State state = states[thread_path[i]];
            State last_state = states[thread_path[i-1]];

            // there must be a recombination
            // either because state changed or we choose to recombine
            // find candidates
            candidates.clear();
            get_possible_recomb(tree, last_state, state, internal, candidates);

            // compute probability of each candidate
            probs.clear();
            for (vector<NodePoint>::iterator it=candidates.begin();
                 it != candidates.end(); ++it) {
                probs.push_back(recomb_prob_unnormalized(
                    model, tree, lineages, last_state, state, *it, internal));
            }

            // sample recombination
            recomb_pos.push_back(i);
            recombs.push_back(candidates[sample(&probs[0], probs.size())]);

            assert(recombs[recombs.size()-1].time <= min(state.time,
                                                         last_state.time));
        }
    }
}

} // namespace argweaver
<|endoftext|>


<commit_before>// Time:  O(4^n)
// Space: O(n)

class Solution {
public:
    vector<string> addOperators(string num, int target) {
        vector<string> result;
        vector<string> expr;
        addOperatorsDFS(num, target, 0, 0, 0, &expr, &result);
        return result;
    }

    void addOperatorsDFS(const string& s, const int& target, const int& pos,
                         const int& operand1, const int& operand2, vector<string> *expr,
                         vector<string> *result) {
        if (pos == s.length()) {
            if (operand1 + operand2 == target) {
                result->emplace_back(move(join(*expr)));
            }
            return;
        }

        int num = 0;
        string num_str;
        for (int i = pos; i < s.length(); ++i) {
            num_str.push_back(s[i]);
            // Check if the value exceeds the max of INT.
            if (num_str.length() == to_string(numeric_limits<int>::max()).length() &&
                num_str > to_string(numeric_limits<int>::max())) {
                break;
            }

            num = num * 10 + s[i] - '0';

            // Case '+':
            expr->emplace_back("+"), expr->emplace_back(num_str);
            addOperatorsDFS(s, target, i + 1, operand1 + operand2, num, expr, result);
            expr->pop_back(), expr->pop_back();

            // '-' and '*' could be used only if the expression is not empty.
            if (!expr->empty()) {
                // Case '-':
                expr->emplace_back("-"), expr->emplace_back(num_str);
                addOperatorsDFS(s, target, i + 1, operand1 + operand2, -num, expr, result);
                expr->pop_back(), expr->pop_back();

                // Case '*':
                expr->emplace_back("*"), expr->emplace_back(num_str);
                addOperatorsDFS(s, target, i + 1, operand1, operand2 * num, expr, result);
                expr->pop_back(), expr->pop_back();
            }

            // Char is '0'.
            if (num == 0) {
                break;
            }
        }
    }

    string join(const vector<string>& expr) {
        string e;
        for (int i = 0; i < expr.size(); ++i) {
            if (i == 0 && expr[i] == "+") {  // Skip '+' at the beginning of the string.
                continue;
            }
            e.append(expr[i]);
        }
        return e;
    }
};
<commit_msg>Update expression-add-operators.cpp<commit_after>// Time:  O(4^n)
// Space: O(n)

class Solution {
public:
    vector<string> addOperators(string num, int target) {
        vector<string> result;
        vector<string> expr;
        addOperatorsDFS(num, target, 0, 0, 0, &expr, &result);
        return result;
    }

    void addOperatorsDFS(const string& s, const int& target, const int& pos,
                         const int& operand1, const int& operand2, vector<string> *expr,
                         vector<string> *result) {
        if (pos == s.length()) {
            if (operand1 + operand2 == target) {
                result->emplace_back(move(join(*expr)));
            }
            return;
        }

        int num = 0;
        string num_str;
        for (int i = pos; i < s.length(); ++i) {
            num_str.push_back(s[i]);
            num = num * 10 + s[i] - '0';
            // Avoid overflow and "00...".
            if (to_string(num) != num_str) {
                break;
            }

            // Case '+':
            expr->emplace_back("+"), expr->emplace_back(num_str);
            addOperatorsDFS(s, target, i + 1, operand1 + operand2, num, expr, result);
            expr->pop_back(), expr->pop_back();

            // '-' and '*' could be used only if the expression is not empty.
            if (!expr->empty()) {
                // Case '-':
                expr->emplace_back("-"), expr->emplace_back(num_str);
                addOperatorsDFS(s, target, i + 1, operand1 + operand2, -num, expr, result);
                expr->pop_back(), expr->pop_back();

                // Case '*':
                expr->emplace_back("*"), expr->emplace_back(num_str);
                addOperatorsDFS(s, target, i + 1, operand1, operand2 * num, expr, result);
                expr->pop_back(), expr->pop_back();
            }
        }
    }

    string join(const vector<string>& expr) {
        string e;
        for (int i = 0; i < expr.size(); ++i) {
            if (i == 0 && expr[i] == "+") {  // Skip '+' at the beginning of the string.
                continue;
            }
            e.append(expr[i]);
        }
        return e;
    }
};
<|endoftext|>


<commit_before>// Time:  O(n)
// Space: O(1)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode dummy = ListNode(0);
        dummy.next = head;
        ListNode *cur = head, *cur_dummy = &dummy;
        int len = 0;

        while (cur) {
            ListNode *next_cur = cur->next;
            len = (len + 1) % k;

            if (len == 0) {
                ListNode *next_dummy = cur_dummy->next;
                reverse(&cur_dummy, cur->next);
                cur_dummy = next_dummy;
            }
            cur = next_cur;
        }
        return dummy.next;
    }

    void reverse(ListNode **begin, const ListNode *end) {
        ListNode *first = (*begin)->next;
        ListNode *cur = first->next;

        while (cur != end) {
            first->next = cur->next;
            cur->next = (*begin)->next;
            (*begin)->next = cur;
            cur = first->next;
        }
    }
};
<commit_msg>Update reverse-nodes-in-k-group.cpp<commit_after>// Time:  O(n)
// Space: O(1)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode dummy{0};
        dummy.next = head;
        ListNode *cur = head, *cur_dummy = &dummy;
        int len = 0;

        while (cur) {
            ListNode *next_cur = cur->next;
            len = (len + 1) % k;

            if (len == 0) {
                ListNode *next_dummy = cur_dummy->next;
                reverse(&cur_dummy, cur->next);
                cur_dummy = next_dummy;
            }
            cur = next_cur;
        }
        return dummy.next;
    }

    void reverse(ListNode **begin, const ListNode *end) {
        ListNode *first = (*begin)->next;
        ListNode *cur = first->next;

        while (cur != end) {
            first->next = cur->next;
            cur->next = (*begin)->next;
            (*begin)->next = cur;
            cur = first->next;
        }
    }
};
<|endoftext|>


<commit_before>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
 *
 * 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 "monkit.h"
#include "dmaManager.h"
#include "MemwriteIndication.h"
#include "MemwriteRequest.h"

#ifdef BOARD_xsim
static int numWords = 0x5000/4;
static int iterCnt = 1;
#elif defined(SIMULATION)
static int numWords = 4096;
static int iterCnt = 1;
#else
static int numWords = 0x1240000/4; // make sure to allocate at least one entry of each size
static int iterCnt = 1; // was 128
#endif
#ifdef PCIE
static int burstLen = 32;
#else
static int burstLen = 16;
#endif

#ifdef NumEngineServers
int numEngineServers = NumEngineServers;
#else
int numEngineServers = 1;
#endif

static sem_t test_sem;
static size_t alloc_sz = numWords*sizeof(unsigned int);

class MemwriteIndication : public MemwriteIndicationWrapper
{
public:
    MemwriteIndication(int id, int tile=DEFAULT_TILE) : MemwriteIndicationWrapper(id,tile) {}
    void started(uint32_t words) {
        fprintf(stderr, "Memwrite::started: words=%x\n", words);
    }
    void writeDone ( uint32_t srcGen ) {
        fprintf(stderr, "Memwrite::writeDone (%08x)\n", srcGen);
        sem_post(&test_sem);
    }
    void reportStateDbg(uint32_t streamWrCnt, uint32_t srcGen) {
        fprintf(stderr, "Memwrite::reportStateDbg: streamWrCnt=%08x srcGen=%d\n", streamWrCnt, srcGen);
    }
};

int main(int argc, const char **argv)
{
    int mismatch = 0;
    uint32_t sg = 0;
    int max_error = 10;

    if (sem_init(&test_sem, 1, 0)) {
        fprintf(stderr, "error: failed to init test_sem\n");
        exit(1);
    }
    fprintf(stderr, "testmemwrite: start %s %s\n", __DATE__, __TIME__);
    DmaManager *dma = platformInit();
    MemwriteRequestProxy *device = new MemwriteRequestProxy(IfcNames_MemwriteRequestS2H);
    MemwriteIndication deviceIndication(IfcNames_MemwriteIndicationH2S);

    alloc_sz *= numEngineServers;

    fprintf(stderr, "main::allocating %lx bytes of memory...\n", (long)alloc_sz);
    int dstAlloc = portalAlloc(alloc_sz, 0);
    unsigned int *dstBuffer = (unsigned int *)portalMmap(dstAlloc, alloc_sz);
#ifdef FPGA0_CLOCK_FREQ
    long req_freq = FPGA0_CLOCK_FREQ, freq = 0;
    setClockFrequency(0, req_freq, &freq);
    fprintf(stderr, "Requested FCLK[0]=%ld actually %ld\n", req_freq, freq);
#endif
    unsigned int ref_dstAlloc = dma->reference(dstAlloc);
    for (int i = 0; i < numWords*numEngineServers; i++)
        dstBuffer[i] = 0xDEADBEEF;
    portalCacheFlush(dstAlloc, dstBuffer, alloc_sz, 1);
    fprintf(stderr, "testmemwrite: flush and invalidate complete\n");
    fprintf(stderr, "testmemwrite: starting write %08x\n", numWords);

    burstLen = 2; // words
    while (burstLen <= 2) {
      portalTimerStart(0);
      device->startWrite(ref_dstAlloc, 0, numWords, burstLen, iterCnt);
      sem_wait(&test_sem);
      mismatch = 0;
      for (int i = 0; i < numWords; i++) {
        if (dstBuffer[i] != sg) {
	  mismatch++;
	  if (max_error-- > 0)
	    fprintf(stderr, "testmemwrite: [%d] actual %08x expected %08x\n", i, dstBuffer[i], sg);
        }
        sg++;
      }
      platformStatistics();
      fprintf(stderr, "testmemwrite: mismatch count %d.\n", mismatch);
      burstLen *= 2;
      if (mismatch)
	exit(mismatch);

      // now try with larger burstLen
      burstLen *= 2;
    }
}
<commit_msg>restore iteration count<commit_after>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
 *
 * 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 "monkit.h"
#include "dmaManager.h"
#include "MemwriteIndication.h"
#include "MemwriteRequest.h"

#ifdef BOARD_xsim
static int numWords = 0x5000/4;
static int iterCnt = 1;
#elif defined(SIMULATION)
static int numWords = 4096;
static int iterCnt = 8;
#else
static int numWords = 0x1240000/4; // make sure to allocate at least one entry of each size
static int iterCnt = 128;
#endif
#ifdef PCIE
static int burstLen = 32;
#else
static int burstLen = 16;
#endif

#ifdef NumEngineServers
int numEngineServers = NumEngineServers;
#else
int numEngineServers = 1;
#endif

static sem_t test_sem;
static size_t alloc_sz = numWords*sizeof(unsigned int);

class MemwriteIndication : public MemwriteIndicationWrapper
{
public:
    MemwriteIndication(int id, int tile=DEFAULT_TILE) : MemwriteIndicationWrapper(id,tile) {}
    void started(uint32_t words) {
        fprintf(stderr, "Memwrite::started: words=%x\n", words);
    }
    void writeDone ( uint32_t srcGen ) {
        fprintf(stderr, "Memwrite::writeDone (%08x)\n", srcGen);
        sem_post(&test_sem);
    }
    void reportStateDbg(uint32_t streamWrCnt, uint32_t srcGen) {
        fprintf(stderr, "Memwrite::reportStateDbg: streamWrCnt=%08x srcGen=%d\n", streamWrCnt, srcGen);
    }
};

int main(int argc, const char **argv)
{
    int mismatch = 0;
    uint32_t sg = 0;
    int max_error = 10;

    if (sem_init(&test_sem, 1, 0)) {
        fprintf(stderr, "error: failed to init test_sem\n");
        exit(1);
    }
    fprintf(stderr, "testmemwrite: start %s %s\n", __DATE__, __TIME__);
    DmaManager *dma = platformInit();
    MemwriteRequestProxy *device = new MemwriteRequestProxy(IfcNames_MemwriteRequestS2H);
    MemwriteIndication deviceIndication(IfcNames_MemwriteIndicationH2S);

    alloc_sz *= numEngineServers;

    fprintf(stderr, "main::allocating %lx bytes of memory...\n", (long)alloc_sz);
    int dstAlloc = portalAlloc(alloc_sz, 0);
    unsigned int *dstBuffer = (unsigned int *)portalMmap(dstAlloc, alloc_sz);
#ifdef FPGA0_CLOCK_FREQ
    long req_freq = FPGA0_CLOCK_FREQ, freq = 0;
    setClockFrequency(0, req_freq, &freq);
    fprintf(stderr, "Requested FCLK[0]=%ld actually %ld\n", req_freq, freq);
#endif
    unsigned int ref_dstAlloc = dma->reference(dstAlloc);
    for (int i = 0; i < numWords*numEngineServers; i++)
        dstBuffer[i] = 0xDEADBEEF;
    portalCacheFlush(dstAlloc, dstBuffer, alloc_sz, 1);
    fprintf(stderr, "testmemwrite: flush and invalidate complete\n");
    fprintf(stderr, "testmemwrite: starting write %08x\n", numWords);

    burstLen = 2; // words
    while (burstLen <= 2) {
      portalTimerStart(0);
      device->startWrite(ref_dstAlloc, 0, numWords, burstLen, iterCnt);
      sem_wait(&test_sem);
      mismatch = 0;
      for (int i = 0; i < numWords; i++) {
        if (dstBuffer[i] != sg) {
	  mismatch++;
	  if (max_error-- > 0)
	    fprintf(stderr, "testmemwrite: [%d] actual %08x expected %08x\n", i, dstBuffer[i], sg);
        }
        sg++;
      }
      platformStatistics();
      fprintf(stderr, "testmemwrite: mismatch count %d.\n", mismatch);
      burstLen *= 2;
      if (mismatch)
	exit(mismatch);

      // now try with larger burstLen
      burstLen *= 2;
    }
}
<|endoftext|>