<commit_before>#include "Landmarks.hh"

Landmarks::Landmark::Landmark()
{
  this->pos[0] = 0.0;
  this->pos[1] = 0.0;
  this->id = -1;
  this->life = LIFE;
  this->totalTimeObserved = 0;
  this->range = -1;
  this->bearing = -1;
}

Landmarks::Landmark::~Landmark()
{}

Landmarks::Landmarks(double degrees)
{
  std::vector<std::pair<int, int> > idCpy(MAXLANDMARKS);
  std::vector<Landmarks::Landmark *> landmarkCpy(MAXLANDMARKS);
  this->DBSize = 0;
  this->EKFLandmarks = 0;
  this->degreePerScan = degrees;
  this->IDtoID = idCpy;
  this->landmarkDB = landmarkCpy;
}

/**
 * @TODO: Clean LandmarkDB
 **/
Landmarks::~Landmarks()
{
  for (unsigned int i = 0; i < this->landmarkDB.size(); ++i)
    {
      delete (this->landmarkDB[i]);
    }
}

int Landmarks::getDBSize() const
{
  return (this->DBSize);
}

int Landmarks::getSLamId(int id) const
{
  for(int i = 0; i < this->EKFLandmarks; ++i)
    {
      if(IDtoID[i].first == id)
	return (IDtoID[i].second);
    }
  return (-1);
}

int Landmarks::addSlamId(int landmarkID, int slamID)
{
  std::pair<int, int> newSlamID;

  newSlamID.first = landmarkID;
  newSlamID.second = slamID;
  this->IDtoID[EKFLandmarks] = newSlamID;
  ++this->EKFLandmarks;
  return (0);
}

int Landmarks::getAssociation(Landmark &lm)
{
  for(int i = 0; i < this->DBSize; ++i)
    {
      if(this->distance(lm, (*landmarkDB[i])) < MAXERROR && landmarkDB[i]->id != -1)
	{
	  landmarkDB[i]->life = LIFE;
	  ++landmarkDB[i]->totalTimeObserved;
	  landmarkDB[i]->bearing = lm.bearing;
	  landmarkDB[i]->range = lm.range;
	  return (landmarkDB[i]->id);
	}
    }
  return (-1);
}

double Landmarks::distance(double x1, double y1, double x2, double y2) const
{
  return (sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)));
}

double Landmarks::distance(const Landmark &lm1, const Landmark &lm2) const
{
  return (sqrt(pow(lm1.pos[0] - lm2.pos[0], 2) + pow(lm1.pos[1] - lm2.pos[1], 2)));
}

int Landmarks::addToDB(const Landmark &lm)
{
  Landmarks::Landmark	*new_elem;

  if(static_cast<unsigned int>(DBSize + 1) < this->landmarkDB.size())
    {
      new_elem = new Landmarks::Landmark();

      new_elem->pos[0] = lm.pos[0];
      new_elem->pos[1] = lm.pos[1];
      new_elem->life = LIFE;
      new_elem->id = DBSize;
      new_elem->totalTimeObserved = 1;
      new_elem->bearing = lm.bearing;
      new_elem->range = lm.range;
      new_elem->a = lm.a;
      new_elem->b = lm.b;

      landmarkDB[DBSize] = new_elem;
      ++DBSize;
      return (DBSize - 1);
    }
  return (-1);
}

double Landmarks::distanceToLine(double x, double y, double a, double b)
{
  double ao = -1.0 / a;
  double bo = y - ao * x;
  double px = (b - bo) / (ao - a);
  double py = ((ao * (b - bo)) / (ao - a)) + bo;
  return (this->distance(x, y, px, py));
}

std::vector<Landmarks::Landmark *> Landmarks::getLandmarkDB() const
{
  std::vector<Landmark *> res(this->DBSize);

  for (int i = 0; i < this->DBSize; ++i)
    res[i] = new Landmarks::Landmark(*this->landmarkDB[i]);
  return (res);
}

void Landmarks::getClosestAssociation(Landmark *lm, int &id, int &totalTimeObserved)
{
  int closestLandmark = 0;
  double temp;
  double leastDistance = 99999; // 100k meter, big distance

  for(int i = 0; i < DBSize; ++i)
    {
      if(static_cast<unsigned int>(landmarkDB[i]->totalTimeObserved) > MINOBSERVATIONS)
	{
	  temp = this->distance(*lm, *landmarkDB[i]);
	  if(temp < leastDistance)
	    {
	      leastDistance = temp;
	      closestLandmark = landmarkDB[i]->id;
	    }
	}
    }
  if(leastDistance == 99999)
    id = -1;
  else
    {
      id = landmarkDB[closestLandmark]->id;
      totalTimeObserved = landmarkDB[closestLandmark]->totalTimeObserved;
    }
}

void Landmarks::leastSquaresLineEstimate(double cameradata[], double robotPosition[], int selectPoints[], int arraySize, double &a, double &b)
{
  double y; //y coordinate
  double x; //x coordinate
  double sumY = 0; //sum of y coordinates
  double sumYY = 0; //sum of y^2 for each coordinate
  double sumX = 0; //sum of x coordinates
  double sumXX = 0; //sum of x^2 for each coordinate
  double sumYX = 0; //sum of y*x for each point

  for(int i = 0; i < arraySize; ++i)
    {
      //convert ranges and bearing to coordinates
      x = (cos((selectPoints[i] * this->degreePerScan * CONVERSION) + robotPosition[2] * CONVERSION) * cameradata[selectPoints[i]]) + robotPosition[0];
      y = (sin((selectPoints[i] * this->degreePerScan * CONVERSION) + robotPosition[2] * CONVERSION) * cameradata[selectPoints[i]]) + robotPosition[1];
      sumY += y;
      sumYY += pow(y,2);
      sumX += x;
      sumXX += pow(x,2);
      sumYX += y * x;
    }
  b = (sumY * sumXX - sumX * sumYX) / (arraySize * sumXX - pow(sumX, 2));
  a = (arraySize * sumYX - sumX * sumY) / (arraySize * sumXX - pow(sumX, 2));
}

Landmarks::Landmark *Landmarks::getLandmark(double range, int readingNo, double robotPosition[])
{
  Landmarks::Landmark *lm = new Landmarks::Landmark();
  int id = -1;
  int totalTimeObserved = 0;

  lm->pos[0] = (cos((readingNo * this->degreePerScan * CONVERSION) +
		    (robotPosition[2] * CONVERSION)) * range) + robotPosition[0];
  lm->pos[1] = (sin((readingNo * this->degreePerScan * CONVERSION) +
		    (robotPosition[2] * CONVERSION)) * range) + robotPosition[0];
  lm->range = range;
  lm->bearing = readingNo;
  this->getClosestAssociation(lm, id, totalTimeObserved);
  lm->id = id;
  return (lm);
}
<commit_msg>SLAM: update Landmark function implementation<commit_after>#include "Landmarks.hh"

Landmarks::Landmark::Landmark()
{
  this->pos[0] = 0.0;
  this->pos[1] = 0.0;
  this->id = -1;
  this->life = LIFE;
  this->totalTimeObserved = 0;
  this->range = -1;
  this->bearing = -1;
}

Landmarks::Landmark::~Landmark()
{}

Landmarks::Landmarks(double degrees)
{
  std::vector<std::pair<int, int> > idCpy(MAXLANDMARKS);
  std::vector<Landmarks::Landmark *> landmarkCpy(MAXLANDMARKS);
  this->DBSize = 0;
  this->EKFLandmarks = 0;
  this->degreePerScan = degrees;
  this->IDtoID = idCpy;
  this->landmarkDB = landmarkCpy;
}

/**
 * @TODO: Clean LandmarkDB
 **/
Landmarks::~Landmarks()
{
  for (unsigned int i = 0; i < this->landmarkDB.size(); ++i)
    {
      delete (this->landmarkDB[i]);
    }
}

int Landmarks::getDBSize() const
{
  return (this->DBSize);
}

int Landmarks::getSLamId(int id) const
{
  for(int i = 0; i < this->EKFLandmarks; ++i)
    {
      if(IDtoID[i].first == id)
	return (IDtoID[i].second);
    }
  return (-1);
}

int Landmarks::addSlamId(int landmarkID, int slamID)
{
  std::pair<int, int> newSlamID;

  newSlamID.first = landmarkID;
  newSlamID.second = slamID;
  this->IDtoID[EKFLandmarks] = newSlamID;
  ++this->EKFLandmarks;
  return (0);
}

int Landmarks::getAssociation(Landmark &lm)
{
  for(int i = 0; i < this->DBSize; ++i)
    {
      if(this->distance(lm, (*landmarkDB[i])) < MAXERROR && landmarkDB[i]->id != -1)
	{
	  landmarkDB[i]->life = LIFE;
	  ++landmarkDB[i]->totalTimeObserved;
	  landmarkDB[i]->bearing = lm.bearing;
	  landmarkDB[i]->range = lm.range;
	  return (landmarkDB[i]->id);
	}
    }
  return (-1);
}

double Landmarks::distance(double x1, double y1, double x2, double y2) const
{
  return (sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)));
}

double Landmarks::distance(const Landmark &lm1, const Landmark &lm2) const
{
  return (sqrt(pow(lm1.pos[0] - lm2.pos[0], 2) + pow(lm1.pos[1] - lm2.pos[1], 2)));
}

int Landmarks::addToDB(const Landmark &lm)
{
  Landmarks::Landmark	*new_elem;

  if(static_cast<unsigned int>(DBSize + 1) < this->landmarkDB.size())
    {
      new_elem = new Landmarks::Landmark();

      new_elem->pos[0] = lm.pos[0];
      new_elem->pos[1] = lm.pos[1];
      new_elem->life = LIFE;
      new_elem->id = DBSize;
      new_elem->totalTimeObserved = 1;
      new_elem->bearing = lm.bearing;
      new_elem->range = lm.range;
      new_elem->a = lm.a;
      new_elem->b = lm.b;

      landmarkDB[DBSize] = new_elem;
      ++DBSize;
      return (DBSize - 1);
    }
  return (-1);
}

double Landmarks::distanceToLine(double x, double y, double a, double b)
{
  // calculate point on line closest to (x, y)
  // use this point to calculate distance between them

  double ao = -1.0 / a;
  double bo = y - ao * x;
  double px = (b - bo) / (ao - a);
  double py = ((ao * (b - bo)) / (ao - a)) + bo;
  return (this->distance(x, y, px, py));
}

std::vector<Landmarks::Landmark *> Landmarks::getLandmarkDB() const
{
  std::vector<Landmark *> res(this->DBSize);

  for (int i = 0; i < this->DBSize; ++i)
    res[i] = new Landmarks::Landmark(*this->landmarkDB[i]);
  return (res);
}

void Landmarks::getClosestAssociation(Landmark *lm, int &id, int &totalTimeObserved)
{
  int closestLandmark = 0;
  double temp;
  double leastDistance = 99999; // 100k meter, big distance

  for(int i = 0; i < DBSize; ++i)
    {
      if(static_cast<unsigned int>(landmarkDB[i]->totalTimeObserved) > MINOBSERVATIONS)
	{
	  temp = this->distance(*lm, *landmarkDB[i]);
	  if(temp < leastDistance)
	    {
	      leastDistance = temp;
	      closestLandmark = landmarkDB[i]->id;
	    }
	}
    }
  if(leastDistance == 99999)
    id = -1;
  else
    {
      id = landmarkDB[closestLandmark]->id;
      totalTimeObserved = landmarkDB[closestLandmark]->totalTimeObserved;
    }
}

void Landmarks::leastSquaresLineEstimate(double cameradata[], double robotPosition[], int selectPoints[], int arraySize, double &a, double &b)
{
  double y; //y coordinate
  double x; //x coordinate
  double sumY = 0; //sum of y coordinates
  double sumYY = 0; //sum of y^2 for each coordinate
  double sumX = 0; //sum of x coordinates
  double sumXX = 0; //sum of x^2 for each coordinate
  double sumYX = 0; //sum of y*x for each point

  for(int i = 0; i < arraySize; ++i)
    {
      //convert ranges and bearing to coordinates
      x = (cos((selectPoints[i] * this->degreePerScan * CONVERSION) + robotPosition[2] * CONVERSION) * cameradata[selectPoints[i]]) + robotPosition[0];
      y = (sin((selectPoints[i] * this->degreePerScan * CONVERSION) + robotPosition[2] * CONVERSION) * cameradata[selectPoints[i]]) + robotPosition[1];
      sumY += y;
      sumYY += pow(y,2);
      sumX += x;
      sumXX += pow(x,2);
      sumYX += y * x;
    }
  b = (sumY * sumXX - sumX * sumYX) / (arraySize * sumXX - pow(sumX, 2));
  a = (arraySize * sumYX - sumX * sumY) / (arraySize * sumXX - pow(sumX, 2));
}

Landmarks::Landmark *Landmarks::getLandmark(double range, int readingNo, double robotPosition[])
{
  Landmarks::Landmark *lm = new Landmarks::Landmark();
  int id = -1;
  int totalTimeObserved = 0;

  lm->pos[0] = (cos((readingNo * this->degreePerScan * CONVERSION) +
		    (robotPosition[2] * CONVERSION)) * range) + robotPosition[0];
  lm->pos[1] = (sin((readingNo * this->degreePerScan * CONVERSION) +
		    (robotPosition[2] * CONVERSION)) * range) + robotPosition[0];
  lm->range = range;
  lm->bearing = readingNo;
  this->getClosestAssociation(lm, id, totalTimeObserved);
  lm->id = id;
  return (lm);
}

Landmarks::Landmark *Landmarks::udpdateLandmark(Landmark *lm)
{
  int newId = this->getAssociation(*lm);

  if (newId == -1)
    newId = this->addToDB(*lm);

  lm->id = newId;
  return (lm);
}
<|endoftext|>


<commit_before>#include "Header.h"

void Block::fullfil(sf::Texture &_textura) {
	int i = 0;
	for (int a = 0; a < 400; (a += 100)) {
		for (int b = 0; b < 400; (b += 100)) {
			this->allBlocks[i] = new Block;
			this->allBlocks[i]->posX = b;
			this->allBlocks[i]->posY = a;
			this->allBlocks[i]->singleBlock.setTexture(_textura);
			this->allBlocks[i]->empty = true;
			i++;
		}
	}
}
void Block::search(int & state) {
	//rand positions from sixteen positions
	if (state == 0) {
		int first = 3;//rand() % 16 + 0;
		this->allBlocks[first]->empty = false;
		state = 1;
	}
	else{
		int next = 2;// rand() % 15 + 0;
		while (this->allBlocks[next]->empty == false) {
			next = rand() % 15 + 0;
		}
		this->allBlocks[next]->empty = false;
	}
}
void Block::changePosLeft() {
	//for (int i = 0; i < 4; i++) {
	if (this->allBlocks[3]->empty == false) { //gdy 300,0 nie jest pusty
		if (this->allBlocks[2]->empty == false) { //gdy 200,0 nie jest pusty
			if (this->allBlocks[1]->empty == false) {
				if (this->allBlocks[0]->empty == false) {
					this->allBlocks[0]->empty = false;
				}
				else if (this->allBlocks[0]->empty == true) {
					this->allBlocks[3]->empty = true;
					this->allBlocks[0]->empty = false;
				}
			}
			else if (this->allBlocks[1]->empty == true) {
				this->allBlocks[1]->empty = false;
				this->allBlocks[0]->empty = true;
			}
		}
		else if (this->allBlocks[2]->empty == true) {
			this->allBlocks[3]->empty = true;
			this->allBlocks[2]->empty = false;
			this->allBlocks[1]->empty = true;
		}
	}
	else if (this->allBlocks[3]->empty == true) {
		this->allBlocks[3]->empty = false;
		this->allBlocks[2]->empty = true;
	}
}
Block::~Block(){
	std::cout << "DESTRUKTOR KLASY BLOCK" << std::endl;
}
<commit_msg>Sample of another algorythm<commit_after>#include "Header.h"

void Block::fullfil(sf::Texture &_textura) {
	int i = 0;
	for (int a = 0; a < 400; (a += 100)) {
		for (int b = 0; b < 400; (b += 100)) {
			this->allBlocks[i] = new Block;
			this->allBlocks[i]->posX = b;
			this->allBlocks[i]->posY = a;
			this->allBlocks[i]->singleBlock.setTexture(_textura);
			this->allBlocks[i]->empty = true;
			i++;
		}
	}
}
void Block::search(int & state) {
	//rand positions from sixteen positions
	if (state == 0) {
		int first = 3;//rand() % 16 + 0;
		this->allBlocks[first]->empty = false;
		state = 1;
	}
	else{
		int next = 2;// rand() % 15 + 0;
		while (this->allBlocks[next]->empty == false) {
			next = rand() % 15 + 0;
		}
		this->allBlocks[next]->empty = false;
	}
}
void Block::changePosLeft() {
	//for (int i = 0; i < 4; i++) { //TODO od lewej
	if (this->allBlocks[0]->empty == true) {

	}
	else {

	}
}
Block::~Block(){
	std::cout << "DESTRUKTOR KLASY BLOCK" << std::endl;
}
<|endoftext|>


<commit_before>#include "MPBuilder.h"

MPBuilder::MPBuilder(const BMessage &msg, const BMessenger &msgr, BString windowTitle, int ideaID)
	:	BWindow(BRect(100, 100, 900, 700), windowTitle, B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE), launcherMessage(msg), launcherMessenger(msgr)
{
	// initialize controls
	BRect r = Bounds();
	r.bottom = r.bottom - 50;
	availableThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_SINGLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);
	orderedThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_SINGLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);
	builderTextView = new BTextView(BRect(0, 0, r.right, 100), NULL, BRect(10, 10, r.right, 100), B_FOLLOW_ALL, B_WILL_DRAW);
	rightButton = new BButton(BRect(10, 10, 90, 35), NULL, ">", new BMessage(MOVE_RIGHT), B_FOLLOW_NONE, B_WILL_DRAW);
	leftButton = new BButton(BRect(10, 10, 90, 35), NULL, "<", new BMessage(MOVE_LEFT), B_FOLLOW_NONE, B_WILL_DRAW);
	topButton = new BButton(BRect(10, 10, 90, 35), NULL, "TOP", new BMessage(MOVE_TOP), B_FOLLOW_NONE, B_WILL_DRAW);
	upButton = new BButton(BRect(10, 10, 90, 35), NULL, "UP", new BMessage(MOVE_UP), B_FOLLOW_NONE, B_WILL_DRAW);
	downButton = new BButton(BRect(10, 10, 90, 35), NULL, "DOWN", new BMessage(MOVE_DOWN), B_FOLLOW_NONE, B_WILL_DRAW);
	bottomButton = new BButton(BRect(10, 10, 90, 35), NULL, "BOTTOM", new BMessage(MOVE_BOTTOM), B_FOLLOW_NONE, B_WILL_DRAW);
	backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW);
	backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
	AddChild(backView);
	// gui layout builder
	backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0));
	backView->AddChild(BGridLayoutBuilder()
		.Add(new BuilderMenu(), 0, 0, 10, 1)
		.Add(new BStringView(BRect(10, 10, 200, 30), NULL, "All Available Thoughts"), 0, 1)
		.Add(new BStringView(BRect(10, 10, 200, 30), NULL, "Ordered Thoughts"), 5, 1)
		.Add(new BScrollView("scroll_available", availableThoughtListView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 2, 4, 10)
		.Add(rightButton, 4, 4)
		.Add(leftButton, 4, 5)
		.Add(topButton, 4, 6)
		.Add(upButton, 4, 7)
		.Add(downButton, 4, 8)
		.Add(bottomButton, 4, 9)
		.Add(new BScrollView("scroll_ordered", orderedThoughtListView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 5, 2, 5, 10)
		.Add(new BScrollView("scroll_editor", builderTextView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 12, 10, 5)
		.SetInsets(0, 0, 0, 0)
	);

	currentideaID = ideaID; // pass current idea id selected to builder window to use

	mpdb = OpenSqliteDB(); // open mpdb db
	if(mpdb == NULL) // if db doesn't exist
	{
		eAlert = new ErrorAlert("1.21 Sql Error: Sql DB was not opened properly");
		eAlert->Launch();
	}
	else
	{
		PopulateBuilderListViews();
		availableThoughtListView->SetSelectionMessage(new BMessage(DISPLAY_AVAIL_TEXT));
		availableThoughtListView->SetInvocationMessage(new BMessage(MOVE_RIGHT));
		orderedThoughtListView->SetSelectionMessage(new BMessage(DISPLAY_ORDER_TEXT));
		orderedThoughtListView->SetInvocationMessage(new BMessage(MOVE_LEFT));
	}
}
void MPBuilder::MessageReceived(BMessage* msg)
{
	switch(msg->what)
	{
		case MOVE_RIGHT: // add item to ordered list
			printf("move right\r\n");
			break;
		case DISPLAY_AVAIL_TEXT: // display preview text from item id
			selected = availableThoughtListView->CurrentSelection(); // selected list item value
			if(selected >= 0) // if something is selected
			{
				IdeaStringItem* item;
				item = dynamic_cast<IdeaStringItem*>(availableThoughtListView->ItemAt(selected));
				builderTextView->SetText(item->Text());
			}
			break;
		default:
		{
			BWindow::MessageReceived(msg);
			break;
		}
	}
}
bool MPBuilder::QuitRequested(void)
{
	// on quit, show launcher with message
	launcherMessage.MakeEmpty();
	launcherMessage.AddInt64("showLauncher", 1);
	launcherMessenger.SendMessage(&launcherMessage);
	return true;
}
void MPBuilder::PopulateBuilderListViews(void)
{
	availableThoughtListView->MakeEmpty();
	orderedThoughtListView->MakeEmpty();
	sqlValue = sqlite3_get_table(mpdb, tmpString, &selectResult, &nrow, &ncol, &sqlErrMsg);
	if(sqlValue == SQLITE_OK) // if sql query was successful
	{
		// use the number of returned rows to set the arrays...
		availtextArray = new BString[nrow];
		availidArray = new int[nrow];
	}
	else // sql select failed
	{
		eAlert = new ErrorAlert("1.25 Sql Error: No Available Thoughts Exist. Please Create Some First.");
		eAlert->Launch();
	}
	sqlite3_free_table(selectResult); // free table either way
	sqlValue = sqlite3_prepare_v2(mpdb, "select ideaname, ideaid, ideatext from ideatable where ismp = 0 and mpid is null", -1, &ideaStatement, NULL);
	if(sqlValue == SQLITE_OK) // sql statement was prepared
	{
		int i = 0;
		while(sqlite3_step(ideaStatement) == SQLITE_ROW) // step through the sql return values
		{
			tmpString = sqlite3_mprintf("%s", sqlite3_column_text(ideaStatement, 0));
			availableThoughtListView->AddItem(new IdeaStringItem(tmpString, sqlite3_column_int(ideaStatement, 1)));
			availtextArray[i] = sqlite3_mprintf("%s", sqlite3_column_text(ideaStatement, 2));
			availidArray[i] = sqlite3_column_int(ideaStatement, 1);
			i++;
		}
	}
	else // sql select failed
	{
		eAlert = new ErrorAlert("1.22 Sql Error: No Available Thoughts Exist. Please Create Some First.");
		eAlert->Launch();
	}
	sqlite3_finalize(ideaStatement); // finish with sql statement
	/*
   sqlValue = sqlite3_get_table(mpdb, tmpString, &selectResult, &nrow, &ncol, &sqlErrMsg);
    if(sqlValue == SQLITE_OK) // if sql query was successful
    {
     for(int i = 0; i < nrow; i++)
     {
         tmpString = selectResult[(i*ncol) + 2];
         tmpString += ". ";
        tmpString += selectResult[(i*ncol)+3];
         this->openListView->AddItem(new BStringItem(tmpString));
      }
    }
    else // sql select failed
    {
         eAlert = new ErrorAlert("No Masterpiece Exist.  Please Create One First.\r\n1.4 SQL Error: ", sqlErrMsg);
         eAlert->Launch();
    }
    sqlite3_free_table(selectResult); // free table either way
	*/
	if(currentideaID != -1) // if id has a real value...
	{
		// populate the ordered list items from here with the information from passed id...
		// select ideaname, ideaid, ideatext from ideatable where ismp = 0 and mpid = currentideaID
		sqlValue = sqlite3_prepare_v2(mpdb, "select ideaname, ideaid, ideatext from ideatable where ismp=0 and mpid=?", -1, &ideaStatement, NULL);
		if(sqlValue == SQLITE_OK) // sql statement was prepared
		{
			if(sqlite3_bind_int(ideaStatement, 1, currentideaID) == SQLITE_OK)
			{
				while(sqlite3_step(ideaStatement) == SQLITE_ROW) // step through the sql return values
				{
					tmpString = sqlite3_mprintf("%s", sqlite3_column_text(ideaStatement, 0));
					orderedThoughtListView->AddItem(new IdeaStringItem(tmpString, sqlite3_column_int(ideaStatement, 1)));
				}
			}
			else
			{
				eAlert = new ErrorAlert("1.24 Sql Error: Sql bind failed.");
				eAlert->Launch();
			}
		}
		else // sql select failed
		{
			eAlert = new ErrorAlert("1.23 Sql Error: No Ordered Thoughts Exist.  Please Add Some First.");
			eAlert->Launch();
		}
	}
}
<commit_msg>something went wrong at runtime with my arrays...<commit_after>#include "MPBuilder.h"

MPBuilder::MPBuilder(const BMessage &msg, const BMessenger &msgr, BString windowTitle, int ideaID)
	:	BWindow(BRect(100, 100, 900, 700), windowTitle, B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE), launcherMessage(msg), launcherMessenger(msgr)
{
	// initialize controls
	BRect r = Bounds();
	r.bottom = r.bottom - 50;
	availableThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_SINGLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);
	orderedThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_SINGLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);
	builderTextView = new BTextView(BRect(0, 0, r.right, 100), NULL, BRect(10, 10, r.right, 100), B_FOLLOW_ALL, B_WILL_DRAW);
	rightButton = new BButton(BRect(10, 10, 90, 35), NULL, ">", new BMessage(MOVE_RIGHT), B_FOLLOW_NONE, B_WILL_DRAW);
	leftButton = new BButton(BRect(10, 10, 90, 35), NULL, "<", new BMessage(MOVE_LEFT), B_FOLLOW_NONE, B_WILL_DRAW);
	topButton = new BButton(BRect(10, 10, 90, 35), NULL, "TOP", new BMessage(MOVE_TOP), B_FOLLOW_NONE, B_WILL_DRAW);
	upButton = new BButton(BRect(10, 10, 90, 35), NULL, "UP", new BMessage(MOVE_UP), B_FOLLOW_NONE, B_WILL_DRAW);
	downButton = new BButton(BRect(10, 10, 90, 35), NULL, "DOWN", new BMessage(MOVE_DOWN), B_FOLLOW_NONE, B_WILL_DRAW);
	bottomButton = new BButton(BRect(10, 10, 90, 35), NULL, "BOTTOM", new BMessage(MOVE_BOTTOM), B_FOLLOW_NONE, B_WILL_DRAW);
	backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW);
	backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
	AddChild(backView);
	// gui layout builder
	backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0));
	backView->AddChild(BGridLayoutBuilder()
		.Add(new BuilderMenu(), 0, 0, 10, 1)
		.Add(new BStringView(BRect(10, 10, 200, 30), NULL, "All Available Thoughts"), 0, 1)
		.Add(new BStringView(BRect(10, 10, 200, 30), NULL, "Ordered Thoughts"), 5, 1)
		.Add(new BScrollView("scroll_available", availableThoughtListView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 2, 4, 10)
		.Add(rightButton, 4, 4)
		.Add(leftButton, 4, 5)
		.Add(topButton, 4, 6)
		.Add(upButton, 4, 7)
		.Add(downButton, 4, 8)
		.Add(bottomButton, 4, 9)
		.Add(new BScrollView("scroll_ordered", orderedThoughtListView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 5, 2, 5, 10)
		.Add(new BScrollView("scroll_editor", builderTextView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 12, 10, 5)
		.SetInsets(0, 0, 0, 0)
	);

	currentideaID = ideaID; // pass current idea id selected to builder window to use

	mpdb = OpenSqliteDB(); // open mpdb db
	if(mpdb == NULL) // if db doesn't exist
	{
		eAlert = new ErrorAlert("1.21 Sql Error: Sql DB was not opened properly");
		eAlert->Launch();
	}
	else
	{
		PopulateBuilderListViews();
		availableThoughtListView->SetSelectionMessage(new BMessage(DISPLAY_AVAIL_TEXT));
		availableThoughtListView->SetInvocationMessage(new BMessage(MOVE_RIGHT));
		orderedThoughtListView->SetSelectionMessage(new BMessage(DISPLAY_ORDER_TEXT));
		orderedThoughtListView->SetInvocationMessage(new BMessage(MOVE_LEFT));
	}
}
void MPBuilder::MessageReceived(BMessage* msg)
{
	switch(msg->what)
	{
		case MOVE_RIGHT: // add item to ordered list
			printf("move right\r\n");
			break;
		case DISPLAY_AVAIL_TEXT: // display preview text from item id
			selected = availableThoughtListView->CurrentSelection(); // selected list item value
			if(selected >= 0) // if something is selected
			{
				IdeaStringItem* item;
				item = dynamic_cast<IdeaStringItem*>(availableThoughtListView->ItemAt(selected));
				//builderTextView->SetText(availtextArray[item->ReturnID()]);
			}
			break;
		default:
		{
			BWindow::MessageReceived(msg);
			break;
		}
	}
}
bool MPBuilder::QuitRequested(void)
{
	// on quit, show launcher with message
	launcherMessage.MakeEmpty();
	launcherMessage.AddInt64("showLauncher", 1);
	launcherMessenger.SendMessage(&launcherMessage);
	return true;
}
void MPBuilder::PopulateBuilderListViews(void)
{
	availableThoughtListView->MakeEmpty();
	orderedThoughtListView->MakeEmpty();
	sqlValue = sqlite3_get_table(mpdb, tmpString, &selectResult, &nrow, &ncol, &sqlErrMsg);
	if(sqlValue == SQLITE_OK) // if sql query was successful
	{
		// use the number of returned rows to set the arrays...
		availtextArray = new BString[nrow];
		availidArray = new int[nrow];
	}
	else // sql select failed
	{
		eAlert = new ErrorAlert("1.25 Sql Error: No Available Thoughts Exist. Please Create Some First.");
		eAlert->Launch();
	}
	sqlite3_free_table(selectResult); // free table either way
	sqlValue = sqlite3_prepare_v2(mpdb, "select ideaname, ideaid, ideatext from ideatable where ismp = 0 and mpid is null", -1, &ideaStatement, NULL);
	if(sqlValue == SQLITE_OK) // sql statement was prepared
	{
		int i = 0;
		while(sqlite3_step(ideaStatement) == SQLITE_ROW) // step through the sql return values
		{
			tmpString = sqlite3_mprintf("%s", sqlite3_column_text(ideaStatement, 0));
			availableThoughtListView->AddItem(new IdeaStringItem(tmpString, sqlite3_column_int(ideaStatement, 1)));
			//availtextArray[i] = sqlite3_mprintf("%s", sqlite3_column_text(ideaStatement, 2));
			//availidArray[i] = sqlite3_column_int(ideaStatement, 1);
			i++;
		}
	}
	else // sql select failed
	{
		eAlert = new ErrorAlert("1.22 Sql Error: No Available Thoughts Exist. Please Create Some First.");
		eAlert->Launch();
	}
	sqlite3_finalize(ideaStatement); // finish with sql statement
	if(currentideaID != -1) // if id has a real value...
	{
		// populate the ordered list items from here with the information from passed id...
		// select ideaname, ideaid, ideatext from ideatable where ismp = 0 and mpid = currentideaID
		sqlValue = sqlite3_prepare_v2(mpdb, "select ideaname, ideaid, ideatext from ideatable where ismp=0 and mpid=?", -1, &ideaStatement, NULL);
		if(sqlValue == SQLITE_OK) // sql statement was prepared
		{
			if(sqlite3_bind_int(ideaStatement, 1, currentideaID) == SQLITE_OK)
			{
				while(sqlite3_step(ideaStatement) == SQLITE_ROW) // step through the sql return values
				{
					tmpString = sqlite3_mprintf("%s", sqlite3_column_text(ideaStatement, 0));
					orderedThoughtListView->AddItem(new IdeaStringItem(tmpString, sqlite3_column_int(ideaStatement, 1)));
				}
			}
			else
			{
				eAlert = new ErrorAlert("1.24 Sql Error: Sql bind failed.");
				eAlert->Launch();
			}
		}
		else // sql select failed
		{
			eAlert = new ErrorAlert("1.23 Sql Error: No Ordered Thoughts Exist.  Please Add Some First.");
			eAlert->Launch();
		}
	}
}
<|endoftext|>


<commit_before>/*
Filename:	ModbusRTULib.cpp
Author:		Fusion
Contact:	admin@fusiondev.pw
Date:		27.03.2017
*/

#include <Arduino.h>

namespace ModbusRTU
{

	uint16_t crc16(const uint8_t *nData, uint16_t wLength)
	{
		static const unsigned short wCRCTable[] = {
			0X0000, 0XC0C1, 0XC181, 0X0140, 0XC301, 0X03C0, 0X0280, 0XC241,
			0XC601, 0X06C0, 0X0780, 0XC741, 0X0500, 0XC5C1, 0XC481, 0X0440,
			0XCC01, 0X0CC0, 0X0D80, 0XCD41, 0X0F00, 0XCFC1, 0XCE81, 0X0E40,
			0X0A00, 0XCAC1, 0XCB81, 0X0B40, 0XC901, 0X09C0, 0X0880, 0XC841,
			0XD801, 0X18C0, 0X1980, 0XD941, 0X1B00, 0XDBC1, 0XDA81, 0X1A40,
			0X1E00, 0XDEC1, 0XDF81, 0X1F40, 0XDD01, 0X1DC0, 0X1C80, 0XDC41,
			0X1400, 0XD4C1, 0XD581, 0X1540, 0XD701, 0X17C0, 0X1680, 0XD641,
			0XD201, 0X12C0, 0X1380, 0XD341, 0X1100, 0XD1C1, 0XD081, 0X1040,
			0XF001, 0X30C0, 0X3180, 0XF141, 0X3300, 0XF3C1, 0XF281, 0X3240,
			0X3600, 0XF6C1, 0XF781, 0X3740, 0XF501, 0X35C0, 0X3480, 0XF441,
			0X3C00, 0XFCC1, 0XFD81, 0X3D40, 0XFF01, 0X3FC0, 0X3E80, 0XFE41,
			0XFA01, 0X3AC0, 0X3B80, 0XFB41, 0X3900, 0XF9C1, 0XF881, 0X3840,
			0X2800, 0XE8C1, 0XE981, 0X2940, 0XEB01, 0X2BC0, 0X2A80, 0XEA41,
			0XEE01, 0X2EC0, 0X2F80, 0XEF41, 0X2D00, 0XEDC1, 0XEC81, 0X2C40,
			0XE401, 0X24C0, 0X2580, 0XE541, 0X2700, 0XE7C1, 0XE681, 0X2640,
			0X2200, 0XE2C1, 0XE381, 0X2340, 0XE101, 0X21C0, 0X2080, 0XE041,
			0XA001, 0X60C0, 0X6180, 0XA141, 0X6300, 0XA3C1, 0XA281, 0X6240,
			0X6600, 0XA6C1, 0XA781, 0X6740, 0XA501, 0X65C0, 0X6480, 0XA441,
			0X6C00, 0XACC1, 0XAD81, 0X6D40, 0XAF01, 0X6FC0, 0X6E80, 0XAE41,
			0XAA01, 0X6AC0, 0X6B80, 0XAB41, 0X6900, 0XA9C1, 0XA881, 0X6840,
			0X7800, 0XB8C1, 0XB981, 0X7940, 0XBB01, 0X7BC0, 0X7A80, 0XBA41,
			0XBE01, 0X7EC0, 0X7F80, 0XBF41, 0X7D00, 0XBDC1, 0XBC81, 0X7C40,
			0XB401, 0X74C0, 0X7580, 0XB541, 0X7700, 0XB7C1, 0XB681, 0X7640,
			0X7200, 0XB2C1, 0XB381, 0X7340, 0XB101, 0X71C0, 0X7080, 0XB041,
			0X5000, 0X90C1, 0X9181, 0X5140, 0X9301, 0X53C0, 0X5280, 0X9241,
			0X9601, 0X56C0, 0X5780, 0X9741, 0X5500, 0X95C1, 0X9481, 0X5440,
			0X9C01, 0X5CC0, 0X5D80, 0X9D41, 0X5F00, 0X9FC1, 0X9E81, 0X5E40,
			0X5A00, 0X9AC1, 0X9B81, 0X5B40, 0X9901, 0X59C0, 0X5880, 0X9841,
			0X8801, 0X48C0, 0X4980, 0X8941, 0X4B00, 0X8BC1, 0X8A81, 0X4A40,
			0X4E00, 0X8EC1, 0X8F81, 0X4F40, 0X8D01, 0X4DC0, 0X4C80, 0X8C41,
			0X4400, 0X84C1, 0X8581, 0X4540, 0X8701, 0X47C0, 0X4680, 0X8641,
			0X8201, 0X42C0, 0X4380, 0X8341, 0X4100, 0X81C1, 0X8081, 0X4040 };

		unsigned char nTemp;
		unsigned short wCRCWord = 0xFFFF;

		while (wLength--)
		{
			nTemp = *nData++ ^ wCRCWord;
			wCRCWord >>= 8;
			wCRCWord ^= wCRCTable[nTemp];
		}
		return wCRCWord;
	}

	uint16_t endianSwap16(uint16_t a)
	{
		a = ((a & 0x00FF) << 8) | ((a & 0xFF00) >> 8);
		return a;
	}

	uint32_t endianSwap32(uint32_t a)
	{
		a = ((a & 0x000000FF) << 24) |
			((a & 0x0000FF00) << 8) |
			((a & 0x00FF0000) >> 8) |
			((a & 0xFF000000) >> 24);
		return a;
	}
}<commit_msg>Updated author info.<commit_after>/*
Filename:	ModbusRTULib.cpp
Author:		norgor
Date:		27.03.2017
*/

#include <Arduino.h>

namespace ModbusRTU
{

	uint16_t crc16(const uint8_t *nData, uint16_t wLength)
	{
		static const unsigned short wCRCTable[] = {
			0X0000, 0XC0C1, 0XC181, 0X0140, 0XC301, 0X03C0, 0X0280, 0XC241,
			0XC601, 0X06C0, 0X0780, 0XC741, 0X0500, 0XC5C1, 0XC481, 0X0440,
			0XCC01, 0X0CC0, 0X0D80, 0XCD41, 0X0F00, 0XCFC1, 0XCE81, 0X0E40,
			0X0A00, 0XCAC1, 0XCB81, 0X0B40, 0XC901, 0X09C0, 0X0880, 0XC841,
			0XD801, 0X18C0, 0X1980, 0XD941, 0X1B00, 0XDBC1, 0XDA81, 0X1A40,
			0X1E00, 0XDEC1, 0XDF81, 0X1F40, 0XDD01, 0X1DC0, 0X1C80, 0XDC41,
			0X1400, 0XD4C1, 0XD581, 0X1540, 0XD701, 0X17C0, 0X1680, 0XD641,
			0XD201, 0X12C0, 0X1380, 0XD341, 0X1100, 0XD1C1, 0XD081, 0X1040,
			0XF001, 0X30C0, 0X3180, 0XF141, 0X3300, 0XF3C1, 0XF281, 0X3240,
			0X3600, 0XF6C1, 0XF781, 0X3740, 0XF501, 0X35C0, 0X3480, 0XF441,
			0X3C00, 0XFCC1, 0XFD81, 0X3D40, 0XFF01, 0X3FC0, 0X3E80, 0XFE41,
			0XFA01, 0X3AC0, 0X3B80, 0XFB41, 0X3900, 0XF9C1, 0XF881, 0X3840,
			0X2800, 0XE8C1, 0XE981, 0X2940, 0XEB01, 0X2BC0, 0X2A80, 0XEA41,
			0XEE01, 0X2EC0, 0X2F80, 0XEF41, 0X2D00, 0XEDC1, 0XEC81, 0X2C40,
			0XE401, 0X24C0, 0X2580, 0XE541, 0X2700, 0XE7C1, 0XE681, 0X2640,
			0X2200, 0XE2C1, 0XE381, 0X2340, 0XE101, 0X21C0, 0X2080, 0XE041,
			0XA001, 0X60C0, 0X6180, 0XA141, 0X6300, 0XA3C1, 0XA281, 0X6240,
			0X6600, 0XA6C1, 0XA781, 0X6740, 0XA501, 0X65C0, 0X6480, 0XA441,
			0X6C00, 0XACC1, 0XAD81, 0X6D40, 0XAF01, 0X6FC0, 0X6E80, 0XAE41,
			0XAA01, 0X6AC0, 0X6B80, 0XAB41, 0X6900, 0XA9C1, 0XA881, 0X6840,
			0X7800, 0XB8C1, 0XB981, 0X7940, 0XBB01, 0X7BC0, 0X7A80, 0XBA41,
			0XBE01, 0X7EC0, 0X7F80, 0XBF41, 0X7D00, 0XBDC1, 0XBC81, 0X7C40,
			0XB401, 0X74C0, 0X7580, 0XB541, 0X7700, 0XB7C1, 0XB681, 0X7640,
			0X7200, 0XB2C1, 0XB381, 0X7340, 0XB101, 0X71C0, 0X7080, 0XB041,
			0X5000, 0X90C1, 0X9181, 0X5140, 0X9301, 0X53C0, 0X5280, 0X9241,
			0X9601, 0X56C0, 0X5780, 0X9741, 0X5500, 0X95C1, 0X9481, 0X5440,
			0X9C01, 0X5CC0, 0X5D80, 0X9D41, 0X5F00, 0X9FC1, 0X9E81, 0X5E40,
			0X5A00, 0X9AC1, 0X9B81, 0X5B40, 0X9901, 0X59C0, 0X5880, 0X9841,
			0X8801, 0X48C0, 0X4980, 0X8941, 0X4B00, 0X8BC1, 0X8A81, 0X4A40,
			0X4E00, 0X8EC1, 0X8F81, 0X4F40, 0X8D01, 0X4DC0, 0X4C80, 0X8C41,
			0X4400, 0X84C1, 0X8581, 0X4540, 0X8701, 0X47C0, 0X4680, 0X8641,
			0X8201, 0X42C0, 0X4380, 0X8341, 0X4100, 0X81C1, 0X8081, 0X4040 };

		unsigned char nTemp;
		unsigned short wCRCWord = 0xFFFF;

		while (wLength--)
		{
			nTemp = *nData++ ^ wCRCWord;
			wCRCWord >>= 8;
			wCRCWord ^= wCRCTable[nTemp];
		}
		return wCRCWord;
	}

	uint16_t endianSwap16(uint16_t a)
	{
		a = ((a & 0x00FF) << 8) | ((a & 0xFF00) >> 8);
		return a;
	}

	uint32_t endianSwap32(uint32_t a)
	{
		a = ((a & 0x000000FF) << 24) |
			((a & 0x0000FF00) << 8) |
			((a & 0x00FF0000) >> 8) |
			((a & 0xFF000000) >> 24);
		return a;
	}
}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <libgen.h>

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

#include "db/filename.h"
#include "leveldb/env.h"
#include "leveldb/db.h"
#include "leveldb/cache.h"
#include "leveldb/filter_policy.h"
#include "leveldb/slice.h"
#include "db/table_cache.h"
#include "db/version_edit.h"
#include "table/format.h"
#include "table/block.h"
#include "table/filter_block.h"
#include "util/cache2.h"

//#include "util/logging.h"
//#include "db/log_reader.h"

void command_help();

int
main(
    int argc,
    char ** argv)
{
    bool error_seen, index_keys, all_keys, block_info, csv_header, counter_info,
        running, no_csv, summary_only;
    int error_counter;
    char ** cursor;

    running=true;
    error_seen=false;

    block_info=false;
    counter_info=false;
    index_keys=false;
    csv_header=false;
    all_keys=false;
    no_csv=false;
    summary_only=false;

    error_counter=0;

    for (cursor=argv+1; NULL!=*cursor && running; ++cursor)
    {
        // option flag?
        if ('-'==**cursor)
        {
            char flag;

            flag=*((*cursor)+1);
            switch(flag)
            {
                case 'b':  block_info=true; break;
                case 'c':  counter_info=true; break;
                case 'h':  csv_header=true; break;
                case 'i':  index_keys=true; break;
                case 'k':  all_keys=true; break;
                case 'n':  no_csv=true; break;
                case 's':  summary_only=true; break;
                default:
                    fprintf(stderr, " option \'%c\' is not valid\n", flag);
                    command_help();
                    running=false;
                    error_counter=1;
                    error_seen=true;
                    break;
            }   // switch
        }   // if

        // sst file
        else
        {
            leveldb::Options options;
            leveldb::DoubleCache double_cache(options);
            leveldb::ReadOptions read_options;
            std::string table_name, dbname, path_temp;
            leveldb::Env * env;
            leveldb::FileMetaData meta;
            leveldb::TableCache * table_cache;
            env=leveldb::Env::Default();

            const int search_level = -2;
            const bool is_overlapped = search_level < 3; // temporary: see TableCache::Evict()

            // make copy since basename() and dirname() may modify
            path_temp=*cursor;
            dbname=dirname((char *)path_temp.c_str());
            dbname=MakeTieredDbname(dbname, options);
            path_temp=*cursor;
            table_name=basename((char *)path_temp.c_str());
            meta.number=strtol(table_name.c_str(), NULL, 10);

            options.filter_policy=leveldb::NewBloomFilterPolicy(10);
            table_cache=new leveldb::TableCache(dbname, &options, double_cache.GetFileCache(), double_cache);
            table_name = leveldb::TableFileName(options, meta.number, search_level);

            // open table, step 1 get file size
            leveldb::Status status = env->GetFileSize(table_name, &meta.file_size);
            if (!status.ok())
            {
                fprintf(stderr, "%s: GetFileSize failed (%s)\n", table_name.c_str(),status.ToString().c_str());
                error_seen=true;
                error_counter=10;
            }   // if

            //open table, step 2 find table (cache or open)
            if (status.ok())
            {
                leveldb::Cache::Handle * fhandle;

                fhandle=NULL;

                status=table_cache->TEST_FindTable(meta.number, meta.file_size, search_level, &fhandle);

                // count keys and size keys/filter
                if (status.ok())
                {
                    leveldb::Table* table;
                    leveldb::Iterator *it, *it2;
                    int count, count2, total, block_count;
                    size_t tot_size, smallest_block, tot_compress, tot_uncompress;
                    bool first;
                    leveldb::Status status;
                    leveldb::RandomAccessFile * file;

                    total=0;
                    count=0;
                    count2=0;
                    tot_size=0;

                    table = reinterpret_cast<leveldb::TableAndFile*>(table_cache->TEST_GetInternalCache()->Value(fhandle))->table;
                    table->ReadFilter();
                    file = reinterpret_cast<leveldb::TableAndFile*>(table_cache->TEST_GetInternalCache()->Value(fhandle))->file;
                    it = table->TEST_GetIndexBlock()->NewIterator(options.comparator);

                    // walk keys in index block
                    if (index_keys)
                    {
                        for (it->SeekToFirst(), count=0; it->Valid(); it->Next())
                        {
                            ++count;
                            if (it->status().ok())
                            {
                                leveldb::ParsedInternalKey parsed;
                                leveldb::Slice key = it->key();
                                leveldb::Slice value = it->value();

                                ParseInternalKey(key, &parsed);
                                printf("key %zd, value %zd: %s\n", key.size(), value.size(), parsed.DebugStringHex().c_str());
                            }   // if
                            else
                            {
                                fprintf(stderr, "%s: index iterator failed (%s)\n", table_name.c_str(),it->status().ToString().c_str());
                            }   // else
                        }   // for
                    }   // if

                    // Walk all blocks (but nothing within block)
                    smallest_block=0;
                    first=true;
                    block_count=0;
                    tot_compress=0;
                    tot_uncompress=0;

                    for (it->SeekToFirst(), count=0; it->Valid() && !summary_only; it->Next())
                    {
                        leveldb::BlockContents contents;
                        leveldb::BlockHandle bhandle;
                        leveldb::Slice slice;

                        ++block_count;
                        slice=it->value();
                        bhandle.DecodeFrom(&slice);

                        if (block_info)
                        {
                            printf("block %d, offset %" PRIu64 ", size %" PRIu64 ", next %" PRIu64 "\n",
                                   block_count, bhandle.offset(), bhandle.size(), bhandle.offset()+bhandle.size());
                        }   // if

                        tot_compress+=bhandle.size();
                        status=leveldb::ReadBlock(file, read_options, bhandle, &contents);
                        if (status.ok())
                        {
                            if (first)
                            {
                                first=false;
                                smallest_block=contents.data.size();
                            }   // if
                            else if (contents.data.size()<smallest_block)
                            {
                                smallest_block=contents.data.size();
                            }   // else if
                            tot_uncompress+=contents.data.size();

                            if (contents.heap_allocated)
                            {
                                delete [] contents.data.data();
                            }   // if
                        }   // if
                        else
                        {
                            fprintf(stderr, "ReadBlock failed on block %d\n", block_count);
                        }   // else
                    }   // for

                    // Walk all keys in each block.
                    for (it->SeekToFirst(), count=0; it->Valid() && !summary_only; it->Next())
                    {
                        ++count;
                        it2=leveldb::Table::TEST_BlockReader(table, read_options, it->value());
                        for (it2->SeekToFirst(), count2=0; it2->Valid(); it2->Next())
                        {
                            ++count2;
                            ++total;
                            if (it2->status().ok())
                            {
                                tot_size+=it2->value().size();

                                if (all_keys)
                                {
                                    leveldb::ParsedInternalKey parsed;
                                    leveldb::Slice key = it2->key();

                                    ParseInternalKey(key, &parsed);
                                    printf("%s block_key %s\n", parsed.DebugStringHex().c_str(), table_name.c_str());
                                }   // if
                            }   // if
                            else
                            {
                                fprintf(stderr, "%s: value iterator failed, location [%d, %d] (%s)\n",
                                       table_name.c_str(),count, count2,it2->status().ToString().c_str());
                            }   // else
                        }   // for

                        delete it2;
                    }   // for

                    delete it;

                    if (!no_csv)
                    {
                        if (csv_header)
                        {
                            csv_header=false;
                            printf("Table File, File size, Index size, Index key count, ");
                            printf("total key count, total value size, average value size, smallest block, ratio*100, ");
                            printf("table object size, filter size");

                            if (counter_info)
                            {
                                unsigned loop;
                                leveldb::SstCounters counters;

                                counters=table->GetSstCounters();

                                for (loop=0; loop<counters.Size(); ++loop)
                                    printf(", Counter %u", loop);
                            }   // if

                            printf("\n");
                        }   // if

                        printf("%s, %" PRIu64 ", %zd, %d,",
                               table_name.c_str(), meta.file_size, table->TEST_GetIndexBlock()->size(), count);

                        printf(" %d, %zd, %zd, %zd, %zd,",
                               total, tot_size, (0!=total) ? tot_size/total : 0, smallest_block,
                               (0!=tot_compress) ? (tot_uncompress*100)/tot_compress: 0);

                        printf(" %zd, %zd",
                               table->TEST_TableObjectSize(), table->TEST_FilterDataSize());

                        if (counter_info || summary_only)
                        {
                            unsigned loop;
                            leveldb::SstCounters counters;

                            counters=table->GetSstCounters();

                            for (loop=0; loop<counters.Size(); ++loop)
                                printf(", %" PRIu64 "", counters.Value(loop));
                        }   // if

                        printf("\n");
                    }   // if

                    // cleanup
                    table_cache->Evict(meta.number, is_overlapped);
                }   // if
                else
                {
                    fprintf(stderr, "%s: FindTable failed (%s)\n", table_name.c_str(),status.ToString().c_str());
                    error_seen=true;
                    error_counter=1;
                }   // else
            }   // if

            // cleanup
            delete table_cache;
            delete options.filter_policy;

        }   // else
    }   // for

    if (1==argc)
        command_help();

    return( error_seen && 0!=error_counter ? 1 : 0 );

}   // main

void
command_help()
{
    fprintf(stderr, "sst_scan [option | file]*\n");
    fprintf(stderr, "  options\n");
    fprintf(stderr, "      -b  print details about block\n");
    fprintf(stderr, "      -c  print sst counters\n");
    fprintf(stderr, "      -h  print csv formatted header line (once)\n");
    fprintf(stderr, "      -i  print index keys\n");
    fprintf(stderr, "      -k  print all keys\n");
    fprintf(stderr, "      -n  NO csv data (or header)\n");
}   // command_help

namespace leveldb {

}  // namespace leveldb

<commit_msg>hack together code to print riak key<commit_after>#include <stdlib.h>
#include <libgen.h>
#include <arpa/inet.h>

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

#include "db/filename.h"
#include "leveldb/env.h"
#include "leveldb/db.h"
#include "leveldb/cache.h"
#include "leveldb/filter_policy.h"
#include "leveldb/slice.h"
#include "db/table_cache.h"
#include "db/version_edit.h"
#include "table/format.h"
#include "table/block.h"
#include "table/filter_block.h"
#include "util/cache2.h"

//#include "util/logging.h"
//#include "db/log_reader.h"

void command_help();
bool PrintSextKey(leveldb::Slice & Cursor, int Limit=1);
bool PrintSextAtom(leveldb::Slice & Cursor);

int
main(
    int argc,
    char ** argv)
{
    bool error_seen, index_keys, all_keys, block_info, csv_header, counter_info,
        running, no_csv, summary_only, riak_translations;
    int error_counter;
    char ** cursor;

    running=true;
    error_seen=false;

    block_info=false;
    counter_info=false;
    index_keys=false;
    csv_header=false;
    all_keys=false;
    no_csv=false;
    summary_only=false;
    riak_translations=false;

    error_counter=0;

    for (cursor=argv+1; NULL!=*cursor && running; ++cursor)
    {
        // option flag?
        if ('-'==**cursor)
        {
            char flag;

            flag=*((*cursor)+1);
            switch(flag)
            {
                case 'b':  block_info=true; break;
                case 'c':  counter_info=true; break;
                case 'h':  csv_header=true; break;
                case 'i':  index_keys=true; break;
                case 'k':  all_keys=true; break;
                case 'n':  no_csv=true; break;
                case 'r':  riak_translations=true; break;
                case 's':  summary_only=true; break;
                default:
                    fprintf(stderr, " option \'%c\' is not valid\n", flag);
                    command_help();
                    running=false;
                    error_counter=1;
                    error_seen=true;
                    break;
            }   // switch
        }   // if

        // sst file
        else
        {
            leveldb::Options options;
            leveldb::DoubleCache double_cache(options);
            leveldb::ReadOptions read_options;
            std::string table_name, dbname, path_temp;
            leveldb::Env * env;
            leveldb::FileMetaData meta;
            leveldb::TableCache * table_cache;
            env=leveldb::Env::Default();

            const int search_level = -2;
            const bool is_overlapped = search_level < 3; // temporary: see TableCache::Evict()

            // make copy since basename() and dirname() may modify
            path_temp=*cursor;
            dbname=dirname((char *)path_temp.c_str());
            dbname=MakeTieredDbname(dbname, options);
            path_temp=*cursor;
            table_name=basename((char *)path_temp.c_str());
            meta.number=strtol(table_name.c_str(), NULL, 10);

            options.filter_policy=leveldb::NewBloomFilterPolicy(10);
            table_cache=new leveldb::TableCache(dbname, &options, double_cache.GetFileCache(), double_cache);
            table_name = leveldb::TableFileName(options, meta.number, search_level);

            // open table, step 1 get file size
            leveldb::Status status = env->GetFileSize(table_name, &meta.file_size);
            if (!status.ok())
            {
                fprintf(stderr, "%s: GetFileSize failed (%s)\n", table_name.c_str(),status.ToString().c_str());
                error_seen=true;
                error_counter=10;
            }   // if

            //open table, step 2 find table (cache or open)
            if (status.ok())
            {
                leveldb::Cache::Handle * fhandle;

                fhandle=NULL;

                status=table_cache->TEST_FindTable(meta.number, meta.file_size, search_level, &fhandle);

                // count keys and size keys/filter
                if (status.ok())
                {
                    leveldb::Table* table;
                    leveldb::Iterator *it, *it2;
                    int count, count2, total, block_count;
                    size_t tot_size, smallest_block, tot_compress, tot_uncompress;
                    bool first;
                    leveldb::Status status;
                    leveldb::RandomAccessFile * file;

                    total=0;
                    count=0;
                    count2=0;
                    tot_size=0;

                    table = reinterpret_cast<leveldb::TableAndFile*>(table_cache->TEST_GetInternalCache()->Value(fhandle))->table;
                    table->ReadFilter();
                    file = reinterpret_cast<leveldb::TableAndFile*>(table_cache->TEST_GetInternalCache()->Value(fhandle))->file;
                    it = table->TEST_GetIndexBlock()->NewIterator(options.comparator);

                    // walk keys in index block
                    if (index_keys)
                    {
                        for (it->SeekToFirst(), count=0; it->Valid(); it->Next())
                        {
                            ++count;
                            if (it->status().ok())
                            {
                                leveldb::ParsedInternalKey parsed;
                                leveldb::Slice key = it->key();
                                leveldb::Slice value = it->value();

                                ParseInternalKey(key, &parsed);
                                printf("key %zd, value %zd: %s\n", key.size(), value.size(), parsed.DebugStringHex().c_str());
                            }   // if
                            else
                            {
                                fprintf(stderr, "%s: index iterator failed (%s)\n", table_name.c_str(),it->status().ToString().c_str());
                            }   // else
                        }   // for
                    }   // if

                    // Walk all blocks (but nothing within block)
                    smallest_block=0;
                    first=true;
                    block_count=0;
                    tot_compress=0;
                    tot_uncompress=0;

                    for (it->SeekToFirst(), count=0; it->Valid() && !summary_only; it->Next())
                    {
                        leveldb::BlockContents contents;
                        leveldb::BlockHandle bhandle;
                        leveldb::Slice slice;

                        ++block_count;
                        slice=it->value();
                        bhandle.DecodeFrom(&slice);

                        if (block_info)
                        {
                            printf("block %d, offset %" PRIu64 ", size %" PRIu64 ", next %" PRIu64 "\n",
                                   block_count, bhandle.offset(), bhandle.size(), bhandle.offset()+bhandle.size());
                        }   // if

                        tot_compress+=bhandle.size();
                        status=leveldb::ReadBlock(file, read_options, bhandle, &contents);
                        if (status.ok())
                        {
                            if (first)
                            {
                                first=false;
                                smallest_block=contents.data.size();
                            }   // if
                            else if (contents.data.size()<smallest_block)
                            {
                                smallest_block=contents.data.size();
                            }   // else if
                            tot_uncompress+=contents.data.size();

                            if (contents.heap_allocated)
                            {
                                delete [] contents.data.data();
                            }   // if
                        }   // if
                        else
                        {
                            fprintf(stderr, "ReadBlock failed on block %d\n", block_count);
                        }   // else
                    }   // for

                    // Walk all keys in each block.
                    for (it->SeekToFirst(), count=0; it->Valid() && !summary_only; it->Next())
                    {
                        ++count;
                        it2=leveldb::Table::TEST_BlockReader(table, read_options, it->value());
                        for (it2->SeekToFirst(), count2=0; it2->Valid(); it2->Next())
                        {
                            ++count2;
                            ++total;
                            if (it2->status().ok())
                            {
                                tot_size+=it2->value().size();

                                if (all_keys)
                                {
                                    leveldb::ParsedInternalKey parsed;
                                    leveldb::Slice key = it2->key();

                                    ParseInternalKey(key, &parsed);
                                    printf("%s block_key %s\n", parsed.DebugStringHex().c_str(), table_name.c_str());

                                    if (riak_translations && '\x10'==*parsed.user_key.data())
                                    {
                                        leveldb::Slice cursor_slice;
                                        cursor_slice=parsed.user_key;
                                        printf("     ");
                                        PrintSextKey(cursor_slice);
                                        printf("\n");
                                    }   // if
                                }   // if
                            }   // if
                            else
                            {
                                fprintf(stderr, "%s: value iterator failed, location [%d, %d] (%s)\n",
                                       table_name.c_str(),count, count2,it2->status().ToString().c_str());
                            }   // else
                        }   // for

                        delete it2;
                    }   // for

                    delete it;

                    if (!no_csv)
                    {
                        if (csv_header)
                        {
                            csv_header=false;
                            printf("Table File, File size, Index size, Index key count, ");
                            printf("total key count, total value size, average value size, smallest block, ratio*100, ");
                            printf("table object size, filter size");

                            if (counter_info)
                            {
                                unsigned loop;
                                leveldb::SstCounters counters;

                                counters=table->GetSstCounters();

                                for (loop=0; loop<counters.Size(); ++loop)
                                    printf(", Counter %u", loop);
                            }   // if

                            printf("\n");
                        }   // if

                        printf("%s, %" PRIu64 ", %zd, %d,",
                               table_name.c_str(), meta.file_size, table->TEST_GetIndexBlock()->size(), count);

                        printf(" %d, %zd, %zd, %zd, %zd,",
                               total, tot_size, (0!=total) ? tot_size/total : 0, smallest_block,
                               (0!=tot_compress) ? (tot_uncompress*100)/tot_compress: 0);

                        printf(" %zd, %zd",
                               table->TEST_TableObjectSize(), table->TEST_FilterDataSize());

                        if (counter_info || summary_only)
                        {
                            unsigned loop;
                            leveldb::SstCounters counters;

                            counters=table->GetSstCounters();

                            for (loop=0; loop<counters.Size(); ++loop)
                                printf(", %" PRIu64 "", counters.Value(loop));
                        }   // if

                        printf("\n");
                    }   // if

                    // cleanup
                    table_cache->Evict(meta.number, is_overlapped);
                }   // if
                else
                {
                    fprintf(stderr, "%s: FindTable failed (%s)\n", table_name.c_str(),status.ToString().c_str());
                    error_seen=true;
                    error_counter=1;
                }   // else
            }   // if

            // cleanup
            delete table_cache;
            delete options.filter_policy;

        }   // else
    }   // for

    if (1==argc)
        command_help();

    return( error_seen && 0!=error_counter ? 1 : 0 );

}   // main

void
command_help()
{
    fprintf(stderr, "sst_scan [option | file]*\n");
    fprintf(stderr, "  options\n");
    fprintf(stderr, "      -b  print details about block\n");
    fprintf(stderr, "      -c  print sst counters\n");
    fprintf(stderr, "      -h  print csv formatted header line (once)\n");
    fprintf(stderr, "      -i  print index keys\n");
    fprintf(stderr, "      -k  print all keys\n");
    fprintf(stderr, "      -n  NO csv data (or header)\n");
}   // command_help

/**
 * Recursive routine to give idea of key contents
 */
bool
PrintSextKey(
    leveldb::Slice & Cursor,
    int Limit)
{
    int loop;
    bool good(true);

    for (loop=0; loop<Limit && good; ++loop)
    {
        if (0<loop)
            printf(",");

        switch(*Cursor.data())
        {
            case(16):   // tuple
            {
                uint32_t count;

                Cursor.remove_prefix(1);
                count=ntohl(*(uint32_t*)Cursor.data());
                Cursor.remove_prefix(4);

                printf("{");
                good=PrintSextKey(Cursor, count);
                printf("}");
                break;
            }   // tuple

            case(12):   // atom
            {
                Cursor.remove_prefix(1);
                good=PrintSextAtom(Cursor);
                break;
            }   // atom

            case(18):   // binary
            {
                Cursor.remove_prefix(1);
                printf("<<");
                good=PrintSextAtom(Cursor);
                printf(">>");
                break;
            }   // atom
        }   // switch
    }   // for

    return(good);

}   // PrintSextKey

bool
PrintSextAtom(
    leveldb::Slice & Cursor)
{
    bool good(true);
    uint8_t mask(0x80);
    char output;

    while(good && (uint8_t)*Cursor.data() & mask)
    {
        switch(mask)
        {
            case(0x80):
            {
                output=(*Cursor.data() & 0x7f) << 1;
                Cursor.remove_prefix(1);
                output+=(*Cursor.data() & 0x80) >> 7;
                printf("%c",output);
                mask=0x40;
                break;
            }

            case(0x40):
            {
                output=(*Cursor.data() & 0x3f) << 2;
                Cursor.remove_prefix(1);
                output+=(*Cursor.data() & 0xc0) >> 6;
                printf("%c",output);
                mask=0x20;
                break;
            }

            case(0x20):
            {
                output=(*Cursor.data() & 0x1f) << 3;
                Cursor.remove_prefix(1);
                output+=(*Cursor.data() & 0xe0) >> 5;
                printf("%c",output);
                mask=0x10;
                break;
            }

            case(0x10):
            {
                output=(*Cursor.data() & 0x0f) << 4;
                Cursor.remove_prefix(1);
                output+=(*Cursor.data() & 0xf0) >> 4;
                printf("%c",output);
                mask=0x08;
                break;
            }

            case(0x08):
            {
                output=(*Cursor.data() & 0x07) << 5;
                Cursor.remove_prefix(1);
                output+=(*Cursor.data() & 0xf8) >> 3;
                printf("%c",output);
                mask=0x04;
                break;
            }

            case(0x04):
            {
                output=(*Cursor.data() & 0x03) << 6;
                Cursor.remove_prefix(1);
                output+=(*Cursor.data() & 0xfc) >> 2;
                printf("%c",output);
                mask=0x02;
                break;
            }

            case(0x02):
            {
                output=(*Cursor.data() & 0x01) << 7;
                Cursor.remove_prefix(1);
                output+=(*Cursor.data() & 0xfe) >> 1;
                printf("%c",output);
                mask=0x01;
                break;
            }

            case(0x01):
            {
                Cursor.remove_prefix(1);
                output=*Cursor.data();
                Cursor.remove_prefix(1);
                printf("%c",output);
                mask=0x80;
                break;
            }
        }   // switch

    }   // while

    Cursor.remove_prefix(2);

    return(good);

}   // PrintSextAtom

namespace leveldb {

}  // namespace leveldb

<|endoftext|>


<commit_before>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <Reduction.hpp>

namespace TuneBench {

reductionConf::reductionConf() : isa::OpenCL::KernelConf(), nrItemsPerBlock(1) {}

std::string reductionConf::print() const {
  return isa::utils::toString(nrItemsPerBlock) + " " + isa::OpenCL::KernelConf::print();
}

std::string * getReductionOpenCL(const reductionConf & conf, const std::string & inputDataName, const std::string & outputDataName) {
  std::string * code = new std::string();

  // Begin kernel's template
  *code = "__kernel void reduction(__global const " + inputDataName + " * const restrict input, __global " + outputDataName + " * const restrict output) {\n"
    "const unsigned int firstItem = (get_group_id(0) * " + isa::utils::toString(conf.getNrItemsPerBlock()) + ") + get_local_id(0);\n"
    "__local " + dataName + " buffer[" + isa::utils::toString(conf.getNrThreadsD0()) + "];\n"
    "<%DEF%>"
    "\n"
    "// First compute phase\n"
    "for ( unsigned int item = firstItem; item < firstItem + " + isa::utils::toString(conf.getNrItemsPerBlock()) + "; item += " + isa::utils::toString(conf.getNrThreadsD0() * conf.getNrItemsD0()) + " ) {\n"
    "<%COMPUTE%>"
    "}\n"
    "// In-thread reduce phase\n"
    "<%REDUCE%>"
    "buffer[get_local_id(0)] = accumulator0;\n"
    "barrier(CLK_LOCAL_MEM_FENCE);\n"
    "// Parallel reduce phase\n"
    "unsigned int threshold = " + isa::utils::toString(conf.getNrThreadsD0() / 2) + ";\n"
    "for ( unsigned int item = get_local_id(0); threshold > 0; threshold /= 2 ) {\n"
    "if ( item < threshold ) {\n"
    "accumulator0 += buffer[item + threshold];\n"
    "buffer[item] = accumulator0;\n"
    "}\n"
    "barrier(CLK_LOCAL_MEM_FENCE);\n"
    "}\n"
    "// Store\n"
    "if ( get_local_id(0) == 0 ) {\n"
    "output[get_group_id(0)] = accumulator0;\n"
    "}\n"
    "}\n";
  std::string def_sTemplate = dataName + " accumulator<%NUM%> = 0;\n";
  std::string compute_sTemplate = "accumulator<%NUM%> += input[item + <%OFFSET%>];\n";
  std::string reduce_sTemplate = "accumulator0 += accumulator<%NUM%>;\n";
  // End kernel's template

  std::string * def_s = new std::string();
  std::string * compute_s = new std::string();
  std::string * reduce_s = new std::string();

  for ( unsigned int item = 0; item < conf.getNrItemsD0(); item++ ) {
    std::string item_s = isa::utils::toString(item);
    std::string offset_s = isa::utils::toString(item * conf.getNrThreadsD0());
    std::string * temp = 0;

    temp = isa::utils::replace(&def_sTemplate, "<%NUM%>", item_s);
    def_s->append(*temp);
    delete temp;
    temp = isa::utils::replace(&compute_sTemplate, "<%NUM%>", item_s);
    if ( item == 0 ) {
      std::string empty_s("");
      temp = isa::utils::replace(temp, " + <%OFFSET%>", empty_s, true);
    } else {
      temp = isa::utils::replace(temp, "<%OFFSET%>", offset_s, true);
    }
    compute_s->append(*temp);
    delete temp;
    if ( item > 0 ) {
      temp = isa::utils::replace(&reduce_sTemplate, "<%NUM%>", item_s);
      reduce_s->append(*temp);
      delete temp;
    }
  }
  code = isa::utils::replace(code, "<%DEF%>", *def_s, true);
  code = isa::utils::replace(code, "<%COMPUTE%>", *compute_s, true);
  code = isa::utils::replace(code, "<%REDUCE%>", *reduce_s, true);
  delete def_s;
  delete compute_s;
  delete reduce_s;

  return code;
}

} // TuneBench

<commit_msg>Typo.<commit_after>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <Reduction.hpp>

namespace TuneBench {

reductionConf::reductionConf() : isa::OpenCL::KernelConf(), nrItemsPerBlock(1) {}

std::string reductionConf::print() const {
  return isa::utils::toString(nrItemsPerBlock) + " " + isa::OpenCL::KernelConf::print();
}

std::string * getReductionOpenCL(const reductionConf & conf, const std::string & inputDataName, const std::string & outputDataName) {
  std::string * code = new std::string();

  // Begin kernel's template
  *code = "__kernel void reduction(__global const " + inputDataName + " * const restrict input, __global " + outputDataName + " * const restrict output) {\n"
    "const unsigned int firstItem = (get_group_id(0) * " + isa::utils::toString(conf.getNrItemsPerBlock()) + ") + get_local_id(0);\n"
    "__local " + inputDataName + " buffer[" + isa::utils::toString(conf.getNrThreadsD0()) + "];\n"
    "<%DEF%>"
    "\n"
    "// First compute phase\n"
    "for ( unsigned int item = firstItem; item < firstItem + " + isa::utils::toString(conf.getNrItemsPerBlock()) + "; item += " + isa::utils::toString(conf.getNrThreadsD0() * conf.getNrItemsD0()) + " ) {\n"
    "<%COMPUTE%>"
    "}\n"
    "// In-thread reduce phase\n"
    "<%REDUCE%>"
    "buffer[get_local_id(0)] = accumulator0;\n"
    "barrier(CLK_LOCAL_MEM_FENCE);\n"
    "// Parallel reduce phase\n"
    "unsigned int threshold = " + isa::utils::toString(conf.getNrThreadsD0() / 2) + ";\n"
    "for ( unsigned int item = get_local_id(0); threshold > 0; threshold /= 2 ) {\n"
    "if ( item < threshold ) {\n"
    "accumulator0 += buffer[item + threshold];\n"
    "buffer[item] = accumulator0;\n"
    "}\n"
    "barrier(CLK_LOCAL_MEM_FENCE);\n"
    "}\n"
    "// Store\n"
    "if ( get_local_id(0) == 0 ) {\n"
    "output[get_group_id(0)] = accumulator0;\n"
    "}\n"
    "}\n";
  std::string def_sTemplate = inputDataName + " accumulator<%NUM%> = 0;\n";
  std::string compute_sTemplate = "accumulator<%NUM%> += input[item + <%OFFSET%>];\n";
  std::string reduce_sTemplate = "accumulator0 += accumulator<%NUM%>;\n";
  // End kernel's template

  std::string * def_s = new std::string();
  std::string * compute_s = new std::string();
  std::string * reduce_s = new std::string();

  for ( unsigned int item = 0; item < conf.getNrItemsD0(); item++ ) {
    std::string item_s = isa::utils::toString(item);
    std::string offset_s = isa::utils::toString(item * conf.getNrThreadsD0());
    std::string * temp = 0;

    temp = isa::utils::replace(&def_sTemplate, "<%NUM%>", item_s);
    def_s->append(*temp);
    delete temp;
    temp = isa::utils::replace(&compute_sTemplate, "<%NUM%>", item_s);
    if ( item == 0 ) {
      std::string empty_s("");
      temp = isa::utils::replace(temp, " + <%OFFSET%>", empty_s, true);
    } else {
      temp = isa::utils::replace(temp, "<%OFFSET%>", offset_s, true);
    }
    compute_s->append(*temp);
    delete temp;
    if ( item > 0 ) {
      temp = isa::utils::replace(&reduce_sTemplate, "<%NUM%>", item_s);
      reduce_s->append(*temp);
      delete temp;
    }
  }
  code = isa::utils::replace(code, "<%DEF%>", *def_s, true);
  code = isa::utils::replace(code, "<%COMPUTE%>", *compute_s, true);
  code = isa::utils::replace(code, "<%REDUCE%>", *reduce_s, true);
  delete def_s;
  delete compute_s;
  delete reduce_s;

  return code;
}

} // TuneBench

<|endoftext|>


<commit_before>#include <iostream>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>

#include <boost/python.hpp>

#include "sdd/sdd.hh"

/*------------------------------------------------------------------------------------------------*/

namespace sdd { namespace python {

using namespace boost::python;

/*------------------------------------------------------------------------------------------------*/

struct py_identifier
{
  object py;

  py_identifier(object p)
		: py(p)
  {}

  py_identifier(const py_identifier& v)
		: py(v.py)
  {}

  py_identifier&
  operator=(const py_identifier& v)
  {
    py = v.py;
    return *this;
  }

  bool
  operator==(const py_identifier& rhs)
  const
  {
    return call_method<bool>(py.ptr(), "__eq__", rhs.py);
  }

  bool
  operator<(const py_identifier& rhs)
  const
  {
    return call_method<bool>(py.ptr(), "__lt__", rhs.py);
  }

  std::size_t
  hash()
  const
  {
    return static_cast<std::size_t>(call_method<long>(py.ptr(), "__hash__"));
  }

  std::string
  name()
  const
  {
    return call_method<std::string>(py.ptr(), "__str__");
  }
};

std::ostream&
operator<<(std::ostream& os, const py_identifier& v)
{
  return os << v.name();
}

/*------------------------------------------------------------------------------------------------*/

struct py_values
{
  object py;

  py_values()
    : py() // None
  {}

  py_values(object p)
		: py(p)
  {}

  py_values(const py_values& v)
		: py(v.py)
  {}

  py_values&
  operator=(const py_values& v)
  {
    py = v.py;
    return *this;
  }

  bool
  operator==(const py_values& rhs)
  const
  {
    return call_method<bool>(py.ptr(), "__eq__", rhs.py);
  }

  bool
  operator<(const py_values& rhs)
  const
  {
    if (rhs.empty())
    {
      return false;
    }
    else if (this->empty())
    {
      return true;
    }
    else
    {
      return call_method<bool>(py.ptr(), "__lt__", rhs.py);
    }
  }

  std::size_t
  hash()
  const
  {
    return empty()
         ? std::hash<int>()(0)
         : static_cast<std::size_t>(call_method<long>(py.ptr() , "__hash__" ));
  }

  std::string
  name()
  const
  {
    return call_method<std::string>(py.ptr(), "__str__" );
  }

  bool
  empty()
  const
  {
    return size() == 0;
  }

  std::size_t
  size()
  const
  {
    return py.is_none() ? 0 : call_method<std::size_t>(py.ptr(), "__len__" );
  }
};

std::ostream&
operator<<(std::ostream& os, const py_values& v)
{
  return os << v.name();
}

py_values
sum(const py_values& lhs, const py_values& rhs)
{
  if (not lhs.empty())
  {
    if (not rhs.empty())
    {
      return py_values(call_method<object>(lhs.py.ptr(), "__or__", rhs.py));
    }
    else
    {
      return lhs;
    }
  }
  else
  {
    return rhs;
  }
}

py_values
difference(const py_values& lhs, const py_values& rhs)
{
  if (not lhs.empty())
  {
    if (not rhs.empty())
    {
      return py_values(call_method<object>(lhs.py.ptr(), "__sub__", rhs.py));
    }
    else
    {
      return lhs;
    }
  }
  else
  {
    return lhs;
  }
}

py_values
intersection(const py_values& lhs, const py_values& rhs)
{
  if (not lhs.empty())
  {
    if (not rhs.empty())
    {
      return py_values(call_method<object>(lhs.py.ptr(), "__and__", rhs.py));
    }
    else
    {
      return rhs;
    }
  }
  else
  {
    return lhs;
  }
}

}
 namespace values {

  template <>
  struct values_traits<python::py_values>
  {
    static constexpr bool stateful = false;
    static constexpr bool fast_iterable = false;
    static constexpr bool has_value_type = false;
  };

}

namespace python {

/*------------------------------------------------------------------------------------------------*/

struct configuration
  : public sdd::conf1
{
  using Variable = int;
  using Identifier = py_identifier;
  using Values = py_values;
};

/*------------------------------------------------------------------------------------------------*/

double
count_combinations(SDD<configuration> s)
{
  return sdd::count_combinations(s).template convert_to<double>();
}

/*------------------------------------------------------------------------------------------------*/

struct _manager
{
  std::shared_ptr<manager<configuration>> ptr;

  _manager()
    : ptr(new manager<configuration>(std::move(manager<configuration>::init())))
  {}
};

/*------------------------------------------------------------------------------------------------*/

BOOST_PYTHON_MODULE(_sdd)
{
  class_<_manager>("_manager");

  class_<SDD<configuration>>("SDD", init<int, object, SDD<configuration>>())
    .def(init<int, SDD<configuration>, SDD<configuration>>())
    .def(self_ns::str(self))
    .def(self + self)
    .def(self - self)
    .def(self & self)
    .def(self == self)
    .def(self < self)
    .def("__hash__", &SDD<configuration>::hash)
    ;

  def("zero", &zero<configuration>);
  def("one", &one<configuration>);

  def("count_combinations", &count_combinations);
}

/*------------------------------------------------------------------------------------------------*/

}} // namespace sdd::python

namespace std {

/*------------------------------------------------------------------------------------------------*/

template <>
struct hash<sdd::python::py_identifier>
{
  std::size_t
  operator()(const sdd::python::py_identifier& id)
  const
  {
    return id.hash();
  }
};

template <>
struct hash<sdd::python::py_values>
{
  std::size_t
  operator()(const sdd::python::py_values& val)
  const
  {
    return val.hash();
  }
};

/*------------------------------------------------------------------------------------------------*/

} // namespace std
<commit_msg>[python] Remove useless (for now) custom py_identifier. Just use a string.<commit_after>#include <iostream>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>

#include <boost/python.hpp>

#include "sdd/sdd.hh"

/*------------------------------------------------------------------------------------------------*/

namespace sdd { namespace python {

using namespace boost::python;

/*------------------------------------------------------------------------------------------------*/

struct py_values
{
  object py;

  py_values()
    : py() // None
  {}

  py_values(object p)
		: py(p)
  {}

  py_values(const py_values& v)
		: py(v.py)
  {}

  py_values&
  operator=(const py_values& v)
  {
    py = v.py;
    return *this;
  }

  bool
  operator==(const py_values& rhs)
  const
  {
    return call_method<bool>(py.ptr(), "__eq__", rhs.py);
  }

  bool
  operator<(const py_values& rhs)
  const
  {
    if (rhs.empty())
    {
      return false;
    }
    else if (this->empty())
    {
      return true;
    }
    else
    {
      return call_method<bool>(py.ptr(), "__lt__", rhs.py);
    }
  }

  std::size_t
  hash()
  const
  {
    return empty()
         ? std::hash<int>()(0)
         : static_cast<std::size_t>(call_method<long>(py.ptr() , "__hash__" ));
  }

  std::string
  name()
  const
  {
    return call_method<std::string>(py.ptr(), "__str__" );
  }

  bool
  empty()
  const
  {
    return size() == 0;
  }

  std::size_t
  size()
  const
  {
    return py.is_none() ? 0 : call_method<std::size_t>(py.ptr(), "__len__" );
  }
};

std::ostream&
operator<<(std::ostream& os, const py_values& v)
{
  return os << v.name();
}

py_values
sum(const py_values& lhs, const py_values& rhs)
{
  if (not lhs.empty())
  {
    if (not rhs.empty())
    {
      return py_values(call_method<object>(lhs.py.ptr(), "__or__", rhs.py));
    }
    else
    {
      return lhs;
    }
  }
  else
  {
    return rhs;
  }
}

py_values
difference(const py_values& lhs, const py_values& rhs)
{
  if (not lhs.empty())
  {
    if (not rhs.empty())
    {
      return py_values(call_method<object>(lhs.py.ptr(), "__sub__", rhs.py));
    }
    else
    {
      return lhs;
    }
  }
  else
  {
    return lhs;
  }
}

py_values
intersection(const py_values& lhs, const py_values& rhs)
{
  if (not lhs.empty())
  {
    if (not rhs.empty())
    {
      return py_values(call_method<object>(lhs.py.ptr(), "__and__", rhs.py));
    }
    else
    {
      return rhs;
    }
  }
  else
  {
    return lhs;
  }
}

}
 namespace values {

  template <>
  struct values_traits<python::py_values>
  {
    static constexpr bool stateful = false;
    static constexpr bool fast_iterable = false;
    static constexpr bool has_value_type = false;
  };

}

namespace python {

/*------------------------------------------------------------------------------------------------*/

struct configuration
  : public sdd::conf1
{
  using Variable = int;
  using Identifier = std::string;
  using Values = py_values;
};

/*------------------------------------------------------------------------------------------------*/

double
count_combinations(SDD<configuration> s)
{
  return sdd::count_combinations(s).template convert_to<double>();
}

/*------------------------------------------------------------------------------------------------*/

struct _manager
{
  std::shared_ptr<manager<configuration>> ptr;

  _manager()
    : ptr(new manager<configuration>(std::move(manager<configuration>::init())))
  {}
};

/*------------------------------------------------------------------------------------------------*/

BOOST_PYTHON_MODULE(_sdd)
{
  class_<_manager>("_manager");

  class_<SDD<configuration>>("SDD", init<int, object, SDD<configuration>>())
    .def(init<int, SDD<configuration>, SDD<configuration>>())
    .def(self_ns::str(self))
    .def(self + self)
    .def(self - self)
    .def(self & self)
    .def(self == self)
    .def(self < self)
    .def("__hash__", &SDD<configuration>::hash)
    ;

  def("zero", &zero<configuration>);
  def("one", &one<configuration>);

  def("count_combinations", &count_combinations);
}

/*------------------------------------------------------------------------------------------------*/

}} // namespace sdd::python

namespace std {

/*------------------------------------------------------------------------------------------------*/

template <>
struct hash<sdd::python::py_values>
{
  std::size_t
  operator()(const sdd::python::py_values& val)
  const
  {
    return val.hash();
  }
};

/*------------------------------------------------------------------------------------------------*/

} // namespace std
<|endoftext|>


<commit_before>/*
   Copyright (C) 2012
   Andy Warner
   This file is part of the sockstr class library.

   The sockstr class library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The sockstr class 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 the sockstr library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
   02111-1307 USA.  */

//
// File       : StreamBuf.cpp
//
// Class      : StreamBuf
//
// Description: Subclass of std::streambuf that uses sockets.
//

//
// INCLUDE FILES
//
#include "config.h"
#include <cassert>

#include <sockstr/StreamBuf.h>
#include <sockstr/Stream.h>

using namespace sockstr;

//
// MACRO DEFINITIONS
//

//
// TYPE DEFINITIONS
//

//
// CLASS MEMBER FUNCTION DEFINITIONS
//

StreamBuf::StreamBuf()
    : stream(0)
{
    setg(inbuff, inbuff+sizeof(inbuff), inbuff+sizeof(inbuff));
    setp(outbuff, outbuff+sizeof(outbuff));
}

StreamBuf::StreamBuf(Stream* strm)
    : stream(strm)
{
    setg(inbuff, inbuff+sizeof(inbuff), inbuff+sizeof(inbuff));
    setp(outbuff, outbuff+sizeof(outbuff));
}

StreamBuf::~StreamBuf()
{

}

StreamBuf* StreamBuf::open(Stream* strm)
{
    stream = strm;
    return this;
}

// virtual protected members overridden from Standard C++ Library std::streambuf

int StreamBuf::overflow(int ch)
{
    char chr = (char) ch;
    if (stream)
    {
        if (sizeof(outbuff) < 2)
        {
            if (ch != EOF)
            {	// unbuffered
                stream->write(&chr, 1);
            }
            return ch;
        }

        if (pptr() == epptr())
        {
            stream->write(pbase(), pptr() - pbase());
            if (stream->queryStatus() != SC_OK)
                return EOF;

            setp(outbuff, outbuff+sizeof(outbuff));
        }

        if (ch != EOF)
        {
            *pptr() = chr;
            pbump(1);
        }
    }
    else if (sizeof(outbuff) > 1)
    {
        setp(outbuff, outbuff+sizeof(outbuff));

        *this->pptr() = chr;
        this->pbump(1);
    }

    return ch;
}

int StreamBuf::pbackfail(int ch)
{
    char chr = (char) ch;
    if (eback() == gptr())
        return EOF;

    gbump(-1);
    if (ch != EOF)
    {
        *gptr() = chr;
    }

    return ch;
}

int StreamBuf::sync()
{
    if (pptr() == pbase())
        return EOF;

    if (stream && stream->is_open() && stream->good())
    {
        stream->write(pbase(), pptr() - pbase());
        if (stream->queryStatus() != SC_OK)
            return EOF;

        setp(outbuff, outbuff+sizeof(outbuff));
        return 0;
    }

    return EOF;
}

int StreamBuf::uflow()
{
    char chr = underflow();
    if (gptr() < egptr())
        gbump(1);

    return chr;
}

int StreamBuf::underflow()
{
    char chr = EOF;
    if (stream)
    {
        int sz = stream->read(inbuff, sizeof(inbuff));
        if (sz < 1)
            return EOF;
        setg(inbuff, inbuff, inbuff + sz);

        chr = *gptr();
    }
    return chr;
}

<commit_msg>Reset streambuf pointers on stream error.<commit_after>/*
   Copyright (C) 2012
   Andy Warner
   This file is part of the sockstr class library.

   The sockstr class library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The sockstr class 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 the sockstr library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
   02111-1307 USA.  */

//
// File       : StreamBuf.cpp
//
// Class      : StreamBuf
//
// Description: Subclass of std::streambuf that uses sockets.
//

//
// INCLUDE FILES
//
#include "config.h"
#include <cassert>

#include <sockstr/StreamBuf.h>
#include <sockstr/Stream.h>

using namespace sockstr;

//
// MACRO DEFINITIONS
//

//
// TYPE DEFINITIONS
//

//
// CLASS MEMBER FUNCTION DEFINITIONS
//

StreamBuf::StreamBuf()
    : stream(0)
{
    setg(inbuff, inbuff+sizeof(inbuff), inbuff+sizeof(inbuff));
    setp(outbuff, outbuff+sizeof(outbuff));
}

StreamBuf::StreamBuf(Stream* strm)
    : stream(strm)
{
    setg(inbuff, inbuff+sizeof(inbuff), inbuff+sizeof(inbuff));
    setp(outbuff, outbuff+sizeof(outbuff));
}

StreamBuf::~StreamBuf()
{

}

StreamBuf* StreamBuf::open(Stream* strm)
{
    stream = strm;
    return this;
}

// virtual protected members overridden from Standard C++ Library std::streambuf

int StreamBuf::overflow(int ch)
{
    char chr = (char) ch;
    if (stream)
    {
        if (sizeof(outbuff) < 2)
        {
            if (ch != EOF)
            {	// unbuffered
                stream->write(&chr, 1);
            }
            return ch;
        }

        if (pptr() == epptr())
        {
            stream->write(pbase(), pptr() - pbase());
            if (stream->queryStatus() != SC_OK)
                return EOF;

            setp(outbuff, outbuff+sizeof(outbuff));
        }

        if (ch != EOF)
        {
            *pptr() = chr;
            pbump(1);
        }
    }
    else if (sizeof(outbuff) > 1)
    {
        setp(outbuff, outbuff+sizeof(outbuff));

        *this->pptr() = chr;
        this->pbump(1);
    }

    return ch;
}

int StreamBuf::pbackfail(int ch)
{
    char chr = (char) ch;
    if (eback() == gptr())
        return EOF;

    gbump(-1);
    if (ch != EOF)
    {
        *gptr() = chr;
    }

    return ch;
}

int StreamBuf::sync()
{
    if (pptr() == pbase())
        return EOF;

    if (stream && stream->is_open() && stream->good())
    {
        stream->write(pbase(), pptr() - pbase());
        if (stream->queryStatus() != SC_OK)
            return EOF;

        setp(outbuff, outbuff+sizeof(outbuff));
        return 0;
    }
    else
    {
        setg(inbuff, inbuff+sizeof(inbuff), inbuff+sizeof(inbuff));
        setp(outbuff, outbuff+sizeof(outbuff));
    }

    return EOF;
}

int StreamBuf::uflow()
{
    char chr = underflow();
    if (gptr() < egptr())
        gbump(1);

    return chr;
}

int StreamBuf::underflow()
{
    char chr = EOF;
    if (stream)
    {
        int sz = stream->read(inbuff, sizeof(inbuff));
        if (sz < 1)
            return EOF;
        setg(inbuff, inbuff, inbuff + sz);

        chr = *gptr();
    }
    return chr;
}

<|endoftext|>


<commit_before>#include <string.h>
#include "Utils.h"

std::string Utils::GetLine(Framework::CStream* stream, bool nIgnoreCR)
{
	std::string result;
	unsigned char nChar = 0;
	stream->Read(&nChar, 1);
	while(!stream->IsEOF())
	{
		if(!(nIgnoreCR && (nChar == '\r')))
		{
			result += nChar;
		}
		stream->Read(&nChar, 1);
		if(nChar == '\n') break;
	}
	return result;
}
<commit_msg>Fixed Utils::GetLine not properly giving away empty lines.<commit_after>#include <string.h>
#include "Utils.h"

std::string Utils::GetLine(Framework::CStream* stream, bool nIgnoreCR)
{
	std::string result;
	unsigned char nChar = 0;
	stream->Read(&nChar, 1);
	while(!stream->IsEOF())
	{
		if(nChar == '\n') break;
		if(!(nIgnoreCR && (nChar == '\r')))
		{
			result += nChar;
		}
		stream->Read(&nChar, 1);
	}
	return result;
}
<|endoftext|>