<commit_before>//
//  LevelManager.cpp
//  Created by Matt Kaufmann on 01/10/14.
//

#include "ExampleGame/Components/LevelManager/LevelManager.h"
#include "ExampleGame/Components/ComponentTypes/ComponentTypeIds.h"
#include "ExampleGame/Components/LevelManager/LevelFileTags.h"
#include "ExampleGame/Components/ShadyCamera/ShadyCamera.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"

// These includes can probably go away once we load objects from prefabs.
#include "ExampleGame/Components/GameScripts/SampleGameScript.h"
#include "ExampleGame/Components/GameScripts/Units/PlayerUnit.h"
#include "ExampleGame/Components/Grid/GridNavigator.h"
#include "ExampleGame/Components/Grid/GridRoom.h"
#include "Vajra/Engine/Components/DerivedComponents/Renderer/MeshRenderer.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/SceneGraph/SceneGraph3D.h"
#include "Vajra/Framework/DeviceUtils/FileSystemUtils/FileSystemUtils.h"

#include <fstream>

ComponentIdType LevelManager::componentTypeId = COMPONENT_TYPE_ID_LEVEL_MANAGER;

LevelManager::LevelManager() : Component() {
	this->init();
}

LevelManager::LevelManager(Object* object_) : Component(object_) {
	this->init();
}

LevelManager::~LevelManager() {
	this->destroy();
}

void LevelManager::HandleMessage(MessageChunk messageChunk) {
	switch (messageChunk->GetMessageType()) {
		case MESSAGE_TYPE_FRAME_EVENT:
			this->update();
			break;
	}
}

void LevelManager::LoadLevelFromFile(std::string levelFilename) {
	std::ifstream ifs;
	ifs.open(levelFilename, std::ios_base::in);

	ASSERT(!ifs.fail(), "Loading level data from file %s", levelFilename.c_str());

	std::string tag;
	ifs >> tag;
	ASSERT(tag == LEVEL_NAME_TAG, "Reading level name from file %s", levelFilename.c_str());
	ifs >> this->currentLevelName;

	SINGLETONS->GetGridManager()->loadGridDataFromStream(ifs);
	this->loadStaticDataFromStream(ifs);
	this->loadUnitDataFromStream(ifs);
	this->loadCameraDataFromStream(ifs);

	ifs.close();

	this->isPaused = false;
}

void LevelManager::init() {
	//this->shadyCam = nullptr;
	this->isPaused = true;
	this->currentLevelName = "";

	this->addSubscriptionToMessageType(MESSAGE_TYPE_FRAME_EVENT, this->GetTypeId(), false);
}

void LevelManager::destroy() {
	this->removeSubscriptionToAllMessageTypes(this->GetTypeId());
}

void LevelManager::update() {
	if (!this->isPaused) {

	}
}

void LevelManager::loadStaticDataFromStream(std::istream& ifs) {
	std::string tag;

	// Static Geometry
	int nStaticObjs;
	ifs >> tag;
	ASSERT(tag == NUM_STATIC_TAG, "Loading static objects for level %s", SINGLETONS->GetLevelManager()->GetCurrentLevelName().c_str());
	ifs >> nStaticObjs;

	for (int i = 0; i < nStaticObjs; ++i) {
		std::string prefab;
		int objWestBound, objSouthBound, objWidth, objHeight; // Cell bounds
		float rotation;
		ifs >> prefab >> objWestBound >> objSouthBound >> objWidth >> objHeight >> rotation;

		// Temporary code; Eventually we should be doing this by reading from a prefab.
		GameObject* staticObj = new GameObject(ENGINE->GetSceneGraph3D());
		ENGINE->GetSceneGraph3D()->GetRootGameObject()->AddChild(staticObj->GetId());

		// Add the object to the grid
		SINGLETONS->GetGridManager()->placeStaticObjectOnGrid(staticObj->GetId(), objWestBound, objSouthBound, objWidth, objHeight);
		staticObj->GetTransform()->SetOrientation(rotation, YAXIS);
	}
}

void LevelManager::loadUnitDataFromStream(std::istream& ifs) {
	std::string tag;

	// Player Units
	int nPlayerUnits;
	ifs >> tag;
	ASSERT(tag == NUM_PLAYERS_TAG, "Loading player units for level %s", SINGLETONS->GetLevelManager()->GetCurrentLevelName().c_str());
	ifs >> nPlayerUnits;

	for (int i = 0; i < nPlayerUnits; ++i) {
		std::string unitType; // Unit type
		int gX, gZ;           // Starting position
		float rotation;       // Orientation
		ifs >> unitType >> gX >> gZ >> rotation;

		// Temporary code; Eventually we should be doing this by reading from a prefab.
		GameObject* unitObj = new GameObject(ENGINE->GetSceneGraph3D());
		ENGINE->GetSceneGraph3D()->GetRootGameObject()->AddChild(unitObj->GetId());
		MeshRenderer* unitRenderer = unitObj->AddComponent<MeshRenderer>();
		unitRenderer->InitMesh(FRAMEWORK->GetFileSystemUtils()->GetDeviceModelResourcesPath() + "Suzanne.model");
		unitObj->AddComponent<SampleGameScript>();
		unitObj->AddComponent<GridNavigator>();
		unitObj->AddComponent<PlayerUnit>();

		// Add the unit to the grid
		SINGLETONS->GetGridManager()->placeUnitOnGrid(unitObj->GetId(), gX, gZ);
		unitObj->GetTransform()->SetOrientation(rotation, YAXIS);
	}

	// Enemy Units
	int nEnemyUnits;
	ifs >> tag;
	ASSERT(tag == NUM_ENEMIES_TAG, "Loading enemy units for level %s", SINGLETONS->GetLevelManager()->GetCurrentLevelName().c_str());
	ifs >> nEnemyUnits;

	for (int i = 0; i < nEnemyUnits; ++i) {
		std::string unitType; // Unit type
		int gX, gZ;           // Starting position
		float rotation;       // Orientation
		int nCommands;        // Number of AI commands
		ifs >> unitType >> gX >> gZ >> rotation >> nCommands;
		for (int j = 0; j < nCommands; ++j) {
			std::string command;
			ifs >> command;
		}
	}
}

void LevelManager::loadCameraDataFromStream(std::istream& ifs) {
	// The level data file will specify which unit the camera should focus on by default
	std::string tag;
	std::string startingUnit;
	ifs >> tag;
	ASSERT(tag == UNIT_START_TAG, "Loading starting unit for level %s", SINGLETONS->GetLevelManager()->GetCurrentLevelName().c_str());
	ifs >> startingUnit;

	// Create the ShadyCamera; this should possibly be a prefab as well.
	GameObject* camera = new GameObject(ENGINE->GetSceneGraph3D());
	ENGINE->GetSceneGraph3D()->GetRootGameObject()->AddChild(camera->GetId());
	ShadyCamera* cameraComponent = camera->AddComponent<ShadyCamera>();
	cameraComponent->SetCameraType(CAMERA_TYPE_PERSPECTIVE);
	ENGINE->GetSceneGraph3D()->SetMainCameraId(camera->GetId());
	cameraComponent->SetGridManager(SINGLETONS->GetGridManager());

	// TODO [Hack] Figure out a better way to do this.
	int gX = SINGLETONS->GetGridManager()->gridRooms[0]->westBound;
	int gZ = SINGLETONS->GetGridManager()->gridRooms[0]->southBound;
	cameraComponent->MoveToRoom(gX, gZ);
}

void LevelManager::endLevel(bool /*success*/) {
	this->isPaused = true;
	//LevelEnd.EndLevel(success);
}
<commit_msg>Addressed comment on pull request<commit_after>//
//  LevelManager.cpp
//  Created by Matt Kaufmann on 01/10/14.
//

#include "ExampleGame/Components/LevelManager/LevelManager.h"
#include "ExampleGame/Components/ComponentTypes/ComponentTypeIds.h"
#include "ExampleGame/Components/LevelManager/LevelFileTags.h"
#include "ExampleGame/Components/ShadyCamera/ShadyCamera.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"

// These includes can probably go away once we load objects from prefabs.
#include "ExampleGame/Components/GameScripts/SampleGameScript.h"
#include "ExampleGame/Components/GameScripts/Units/PlayerUnit.h"
#include "ExampleGame/Components/Grid/GridNavigator.h"
#include "ExampleGame/Components/Grid/GridRoom.h"
#include "Vajra/Engine/Components/DerivedComponents/Renderer/MeshRenderer.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/SceneGraph/SceneGraph3D.h"
#include "Vajra/Framework/DeviceUtils/FileSystemUtils/FileSystemUtils.h"

#include <fstream>

ComponentIdType LevelManager::componentTypeId = COMPONENT_TYPE_ID_LEVEL_MANAGER;

LevelManager::LevelManager() : Component() {
	this->init();
}

LevelManager::LevelManager(Object* object_) : Component(object_) {
	this->init();
}

LevelManager::~LevelManager() {
	this->destroy();
}

void LevelManager::HandleMessage(MessageChunk messageChunk) {
	switch (messageChunk->GetMessageType()) {
		case MESSAGE_TYPE_FRAME_EVENT:
			this->update();
			break;
	}
}

void LevelManager::LoadLevelFromFile(std::string levelFilename) {
	std::ifstream ifs;
	ifs.open(levelFilename, std::ios_base::in);

	ASSERT(!ifs.fail(), "Loading level data from file %s", levelFilename.c_str());

	std::string tag;
	ifs >> tag;
	ASSERT(tag == LEVEL_NAME_TAG, "Reading level name from file %s", levelFilename.c_str());
	ifs >> this->currentLevelName;

	SINGLETONS->GetGridManager()->loadGridDataFromStream(ifs);
	this->loadStaticDataFromStream(ifs);
	this->loadUnitDataFromStream(ifs);
	this->loadCameraDataFromStream(ifs);

	ifs.close();

	this->isPaused = false;
}

void LevelManager::init() {
	//this->shadyCam = nullptr;
	this->isPaused = true;
	this->currentLevelName = "";

	this->addSubscriptionToMessageType(MESSAGE_TYPE_FRAME_EVENT, this->GetTypeId(), false);
}

void LevelManager::destroy() {
	this->removeSubscriptionToAllMessageTypes(this->GetTypeId());
}

void LevelManager::update() {
	if (!this->isPaused) {

	}
}

void LevelManager::loadStaticDataFromStream(std::istream& ifs) {
	std::string tag;

	// Static Geometry
	int nStaticObjs;
	ifs >> tag;
	ASSERT(tag == NUM_STATIC_TAG, "Loading static objects for level %s", SINGLETONS->GetLevelManager()->GetCurrentLevelName().c_str());
	ifs >> nStaticObjs;

	for (int i = 0; i < nStaticObjs; ++i) {
		std::string prefab;
		int objWestBound, objSouthBound, objWidth, objHeight; // Cell bounds
		float rotation;
		ifs >> prefab >> objWestBound >> objSouthBound >> objWidth >> objHeight >> rotation;

		// Temporary code; Eventually we should be doing this by reading from a prefab.
		GameObject* staticObj = new GameObject(ENGINE->GetSceneGraph3D());
		ENGINE->GetSceneGraph3D()->GetRootGameObject()->AddChild(staticObj->GetId());

		// Add the object to the grid
		SINGLETONS->GetGridManager()->placeStaticObjectOnGrid(staticObj->GetId(), objWestBound, objSouthBound, objWidth, objHeight);
		staticObj->GetTransform()->SetOrientation(rotation, YAXIS);
	}
}

void LevelManager::loadUnitDataFromStream(std::istream& ifs) {
	std::string tag;

	// Player Units
	int nPlayerUnits;
	ifs >> tag;
	ASSERT(tag == NUM_PLAYERS_TAG, "Loading player units for level %s", SINGLETONS->GetLevelManager()->GetCurrentLevelName().c_str());
	ifs >> nPlayerUnits;

	for (int i = 0; i < nPlayerUnits; ++i) {
		std::string unitType; // Unit type
		int gX, gZ;           // Starting position
		float rotation;       // Orientation
		ifs >> unitType >> gX >> gZ >> rotation;

		// Temporary code; Eventually we should be doing this by reading from a prefab.
		GameObject* unitObj = new GameObject(ENGINE->GetSceneGraph3D());
		ENGINE->GetSceneGraph3D()->GetRootGameObject()->AddChild(unitObj->GetId());
		MeshRenderer* unitRenderer = unitObj->AddComponent<MeshRenderer>();
		unitRenderer->InitMesh(FRAMEWORK->GetFileSystemUtils()->GetDeviceModelResourcesPath() + "Suzanne.model");
		unitObj->AddComponent<SampleGameScript>();
		unitObj->AddComponent<GridNavigator>();
		unitObj->AddComponent<PlayerUnit>();

		// Add the unit to the grid
		SINGLETONS->GetGridManager()->placeUnitOnGrid(unitObj->GetId(), gX, gZ);
		unitObj->GetTransform()->SetOrientation(rotation, YAXIS);
	}

	// Enemy Units
	int nEnemyUnits;
	ifs >> tag;
	ASSERT(tag == NUM_ENEMIES_TAG, "Loading enemy units for level %s", SINGLETONS->GetLevelManager()->GetCurrentLevelName().c_str());
	ifs >> nEnemyUnits;

	for (int i = 0; i < nEnemyUnits; ++i) {
		std::string unitType; // Unit type
		int gX, gZ;           // Starting position
		float rotation;       // Orientation
		int nCommands;        // Number of AI commands
		ifs >> unitType >> gX >> gZ >> rotation >> nCommands;
		for (int j = 0; j < nCommands; ++j) {
			std::string command;
			ifs >> command;
		}
	}
}

void LevelManager::loadCameraDataFromStream(std::istream& ifs) {
	// The level data file will specify which unit the camera should focus on by default
	std::string tag;
	std::string startingUnit;
	ifs >> tag;
	ASSERT(tag == UNIT_START_TAG, "Loading starting unit for level %s", SINGLETONS->GetLevelManager()->GetCurrentLevelName().c_str());
	ifs >> startingUnit;

	// Create the ShadyCamera; this should possibly be a prefab as well.
	GameObject* camera = new GameObject(ENGINE->GetSceneGraph3D());
	ENGINE->GetSceneGraph3D()->GetRootGameObject()->AddChild(camera->GetId());
	ShadyCamera* cameraComponent = camera->AddComponent<ShadyCamera>();
	ENGINE->GetSceneGraph3D()->SetMainCameraId(camera->GetId());
	cameraComponent->SetGridManager(SINGLETONS->GetGridManager());

	// TODO [Hack] Figure out a better way to do this.
	int gX = SINGLETONS->GetGridManager()->gridRooms[0]->westBound;
	int gZ = SINGLETONS->GetGridManager()->gridRooms[0]->southBound;
	cameraComponent->MoveToRoom(gX, gZ);
}

void LevelManager::endLevel(bool /*success*/) {
	this->isPaused = true;
	//LevelEnd.EndLevel(success);
}
<|endoftext|>


<commit_before>#ifndef PLATEROBJECT_HPP
#define PLATEROBJECT_HPP
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
    #include <wx/wx.h>
#endif

#include "ExPolygonCollection.hpp"
#include "Model.hpp"

namespace Slic3r { namespace GUI {

class PlaterObject {
public:
    std::string name {""};
    size_t identifier {0U};
    std::string input_file {""};
    int input_file_obj_idx {-1};

    bool selected {false};
    int selected_instance {-1};

    Slic3r::ExPolygonCollection thumbnail;
    Slic3r::ExPolygonCollection transformed_thumbnail;

    // read only
    std::vector<Slic3r::ExPolygonCollection> instance_thumbnails;

    Slic3r::ExPolygonCollection& make_thumbnail(const Slic3r::Model model, int obj_idx);
    Slic3r::ExPolygonCollection& make_thumbnail(const std::shared_ptr<Slic3r::Model> model, int obj_idx);

    Slic3r::ExPolygonCollection& transform_thumbnail(const Slic3r::Model model, int obj_idx);
    Slic3r::ExPolygonCollection& transform_thumbnail(const std::shared_ptr<Slic3r::Model> model, int obj_idx);

protected:
    const std::string LogChannel {"PlaterObject"};

};

}} // Namespace Slic3r::GUI
#endif
<commit_msg>use integers instead of size_t for object identifiers.<commit_after>#ifndef PLATEROBJECT_HPP
#define PLATEROBJECT_HPP
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
    #include <wx/wx.h>
#endif

#include "ExPolygonCollection.hpp"
#include "Model.hpp"

namespace Slic3r { namespace GUI {

class PlaterObject {
public:
    std::string name {""};
    int identifier {0};
    std::string input_file {""};
    int input_file_obj_idx {-1};

    bool selected {false};
    int selected_instance {-1};

    Slic3r::ExPolygonCollection thumbnail;
    Slic3r::ExPolygonCollection transformed_thumbnail;

    // read only
    std::vector<Slic3r::ExPolygonCollection> instance_thumbnails;

    Slic3r::ExPolygonCollection& make_thumbnail(const Slic3r::Model model, int obj_idx);
    Slic3r::ExPolygonCollection& make_thumbnail(const std::shared_ptr<Slic3r::Model> model, int obj_idx);

    Slic3r::ExPolygonCollection& transform_thumbnail(const Slic3r::Model model, int obj_idx);
    Slic3r::ExPolygonCollection& transform_thumbnail(const std::shared_ptr<Slic3r::Model> model, int obj_idx);

protected:
    const std::string LogChannel {"PlaterObject"};

};

}} // Namespace Slic3r::GUI
#endif
<|endoftext|>


<commit_before><commit_msg>[FlashPy]: check matrix when getting types.<commit_after><|endoftext|>


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

#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/process_util.h"
#include "base/utf_string_conversions.h"
#include "pcrecpp.h"  // NOLINT
#include "syzygy/wsdump/process_working_set.h"

namespace {

class RegexpProcessFilter: public base::ProcessFilter {
 public:
  RegexpProcessFilter();

  bool Initialize(const std::string& regexpr);

  virtual bool Includes(const base::ProcessEntry& entry) const OVERRIDE;

 private:
  pcrecpp::RE expr_;
};

RegexpProcessFilter::RegexpProcessFilter() : expr_("") {
}

bool RegexpProcessFilter::Initialize(const std::string& regexpr) {
  pcrecpp::RE_Options options;
  options.set_utf8(true);
  options.set_caseless(true);
  pcrecpp::RE new_expr(regexpr, options);

  if (!new_expr.error().empty()) {
    LOG(ERROR) << "Failed to initialize regular expression, error: "
        << new_expr.error();
    return false;
  }

  expr_ = new_expr;
  DCHECK_EQ("", new_expr.error());

  return true;
}

bool RegexpProcessFilter::Includes(const base::ProcessEntry& entry) const {
  return expr_.PartialMatch(WideToUTF8(entry.exe_file()));
}

} // namespace

static const char kUsage[] =
"Usage: wsdump [--process-name=<process_re>]\n"
"\n"
"    Captures and outputs working set statistics for all processes,\n"
"    or only for processess whose executable name matches <process_re>.\n"
"\n"
"    The output is tab-separated, where a process heading starts a line with\n"
"    an executable name, followed by the process PID and parent PID.\n"
"    Following a process heading is a tab-prefixed line for each module that\n"
"    appear in its working set, where the line has the following columns\n"
"      * Module path.\n"
"      * Total number of pages.\n"
"      * Number of shareable pages.\n"
"      * Number of shared pages.\n"
"      * Number of read-only (non-executable) pages.\n"
"      * Number of writable pages.\n"
"      * Number of executable pages.\n"
"\n"
"Example output:\n"
"\n"
"notepad++.exe  4648  3600\n"
"  Total:  4402  2694  2377  4402  2694  2377  963  1714 1725\n"
"  C:\\PROGRA~2\\Sophos\\SOPHOS~1\\SOPHOS~1.DLL  3  3  3 3  3  3  1  0  2\n"
"  C:\\Windows\\SysWOW64\\ntdll.dll  84  78  78  84  78 78  1  5  78\n";

static int Usage() {
  std::cout << kUsage;
  return 1;
}

int main(int argc, char** argv) {
  base::AtExitManager at_exit_manager;
  CommandLine::Init(argc, argv);

  if (!logging::InitLogging(L"", logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
      logging::DONT_LOCK_LOG_FILE, logging::APPEND_TO_OLD_LOG_FILE,
      logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS)) {
    return 1;
  }

  CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  DCHECK(cmd_line != NULL);

  if (cmd_line->HasSwitch("help") || !cmd_line->args().empty()) {
    return Usage();
  }

  // If the process-name is empty or missing we match all processes.
  std::string process_re = cmd_line->GetSwitchValueASCII("process-name");
  RegexpProcessFilter filter;
  if (!filter.Initialize(process_re)) {
    LOG(ERROR) << "Incorrect process filter regular expression.";
    return 1;
  }

  struct ProcessInfo {
    ProcessInfo() : pid(0), parent_pid(0) {
    }

    std::wstring exe_file;
    base::ProcessId pid;
    base::ProcessId parent_pid;
    ProcessWorkingSet ws;
  };
  typedef std::list<ProcessInfo> WorkingSets;
  WorkingSets working_sets;

  const base::ProcessEntry* entry = NULL;
  base::ProcessIterator process_iterator(&filter);
  while (entry = process_iterator.NextProcessEntry()) {
    working_sets.push_back(ProcessInfo());
    ProcessInfo& info = working_sets.back();
    if (info.ws.Initialize(entry->pid())) {
      info.exe_file = entry->exe_file();
      info.pid = entry->pid();
      info.parent_pid = entry->parent_pid();
    } else {
      LOG(ERROR) << "Unable to capture working set information for pid: "
          << entry->pid();
      working_sets.pop_back();
    }
  }

  WorkingSets::const_iterator it = working_sets.begin();
  for (; it != working_sets.end(); ++it) {
    std::cout << it->exe_file << "\t"
        << it->pid << "\t"
        << it->parent_pid << std::endl;

    const ProcessWorkingSet& ws = it->ws;
    std::cout << "\tTotal: "
        << "\t" << ws.total_stats().pages
        << "\t" << ws.total_stats().shareable_pages
        << "\t" << ws.total_stats().shared_pages
        << "\t" << ws.total_stats().pages
        << "\t" << ws.total_stats().shareable_pages
        << "\t" << ws.total_stats().shared_pages
        << "\t" << ws.total_stats().read_only_pages
        << "\t" << ws.total_stats().writable_pages
        << "\t" << ws.total_stats().executable_pages << std::endl;

    ProcessWorkingSet::ModuleStatsVector::const_iterator jt =
        ws.module_stats().begin();
    for (; jt != ws.module_stats().end(); ++jt) {
      std::cout << "\t" << jt->module_name
          << "\t" << jt->pages
          << "\t" << jt->shareable_pages
          << "\t" << jt->shared_pages
          << "\t" << jt->pages
          << "\t" << jt->shareable_pages
          << "\t" << jt->shared_pages
          << "\t" << jt->read_only_pages
          << "\t" << jt->writable_pages
          << "\t" << jt->executable_pages << std::endl;
    }
  }

  return 1;
}
<commit_msg>Switch wsdump to JSON output.<commit_after>// Copyright 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <iostream>
#include <list>

#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/json/string_escape.h"
#include "base/logging.h"
#include "base/process_util.h"
#include "base/utf_string_conversions.h"
#include "pcrecpp.h"  // NOLINT
#include "syzygy/wsdump/process_working_set.h"

namespace {

class RegexpProcessFilter: public base::ProcessFilter {
 public:
  RegexpProcessFilter();

  bool Initialize(const std::string& regexpr);

  virtual bool Includes(const base::ProcessEntry& entry) const OVERRIDE;

 private:
  pcrecpp::RE expr_;
};

RegexpProcessFilter::RegexpProcessFilter() : expr_("") {
}

bool RegexpProcessFilter::Initialize(const std::string& regexpr) {
  pcrecpp::RE_Options options;
  options.set_utf8(true);
  options.set_caseless(true);
  pcrecpp::RE new_expr(regexpr, options);

  if (!new_expr.error().empty()) {
    LOG(ERROR) << "Failed to initialize regular expression, error: "
        << new_expr.error();
    return false;
  }

  expr_ = new_expr;
  DCHECK_EQ("", new_expr.error());

  return true;
}

bool RegexpProcessFilter::Includes(const base::ProcessEntry& entry) const {
  return expr_.PartialMatch(WideToUTF8(entry.exe_file()));
}

const char kUsage[] =
"Usage: wsdump [--process-name=<process_re>]\n"
"\n"
"    Captures and outputs working set statistics for all processes,\n"
"    or only for processess whose executable name matches <process_re>.\n"
"\n"
"    The output is JSON encoded array, where each element of the array\n"
"    is a dictionary describing a process. Each process has the following\n"
"    items:\n"
"      * exe_file - the process' executable file, e.g. \"chrome.exe\".\n"
"      * pid - the process ID.\n"
"      * parent_pid - the parent process ID.\n"
"      * modules - an array of dictionaries, one for each module in the\n"
"        process working set.\n"
"    Each module has the following keys:\n"
"      * module_name - the module file name, e.g. \"C:\\temp\\xyz.dll\"\n"
"      * pages - total number of pages from this module in the working set.\n"
"      * shareable_pages - shareable pages in the working set.\n"
"      * shared_pages - shared pages in the working set.\n"
"      * read_only_pages - read-only pages in the working set.\n"
"      * writable_pages - writable pages in the working set.\n"
"      * executable_pages - executable pages in the working set.\n"
"\n"
"Example Output:\n"
"[\n"
"  {\n"
"    \"exe_file\": \"devenv.exe\",\n"
"    \"pid\": 5772,\n"
"    \"parent_pid\": 3804,\n"
"    \"modules\": [\n"
"      {\n"
"        \"module_name\": \"Total\",\n"
"        \"pages\": 34145,\n"
"        \"shareable_pages\": 10515,\n"
"        \"shared_pages\": 4847,\n"
"        \"pages\": 34145,\n"
"        \"shareable_pages\": 10515,\n"
"        \"shared_pages\": 4847,\n"
"        \"read_only_pages\": 1951,\n"
"        \"writable_pages\": 23235,\n"
"        \"executable_pages\": 8959\n"
"      },\n"
"      {\n"
" ... \n";

int Usage() {
  std::cout << kUsage;
  return 1;
}

struct ProcessInfo {
  ProcessInfo() : pid(0), parent_pid(0) {
  }

  std::wstring exe_file;
  base::ProcessId pid;
  base::ProcessId parent_pid;
  ProcessWorkingSet ws;
};

void OutputKeyValue(const char* key,
                    const std::wstring& value,
                    int indent,
                    bool trailing_comma) {
  std::cout << std::string(indent, ' ')
      << base::GetDoubleQuotedJson(key) << ": "
      << base::GetDoubleQuotedJson(value)
      << (trailing_comma ? "," : "") << "\n";
}

template <class Streamable>
void OutputKeyValue(const char* key,
                    const Streamable& value,
                    int indent,
                    bool trailing_comma) {
  std::cout << std::string(indent, ' ')
      << base::GetDoubleQuotedJson(key) << ": "
      << value
      << (trailing_comma ? "," : "") << "\n";
}

void OutputModule(const std::wstring& module_name,
                  const ProcessWorkingSet::Stats& stats,
                  bool trailing_comma) {
  std::cout << "      {\n";
  OutputKeyValue("module_name", module_name, 8, true);
  OutputKeyValue("pages", stats.pages, 8, true);
  OutputKeyValue("shareable_pages", stats.shareable_pages, 8, true);
  OutputKeyValue("shared_pages", stats.shared_pages, 8, true);
  OutputKeyValue("pages", stats.pages, 8, true);
  OutputKeyValue("shareable_pages", stats.shareable_pages, 8, true);
  OutputKeyValue("shared_pages", stats.shared_pages, 8, true);
  OutputKeyValue("read_only_pages", stats.read_only_pages, 8, true);
  OutputKeyValue("writable_pages", stats.writable_pages, 8, true);
  OutputKeyValue("executable_pages", stats.executable_pages, 8, false);
  std::cout << "      }" << (trailing_comma ? "," : "") << "\n";
}

void OutputProcessInfo(const ProcessInfo& info) {
  std::cout << "  {\n";
  OutputKeyValue("exe_file", info.exe_file, 4, true);
  OutputKeyValue("pid", info.pid, 4, true);
  OutputKeyValue("parent_pid", info.parent_pid, 4, true);
  std::cout << "    \"modules\": [\n";

  OutputModule(L"Total", info.ws.total_stats(), true);
  ProcessWorkingSet::ModuleStatsVector::const_iterator it =
      info.ws.module_stats().begin();
  ProcessWorkingSet::ModuleStatsVector::const_iterator end =
      info.ws.module_stats().end();
  for (; it != end; ++it)
    OutputModule(it->module_name, *it, it + 1 != end);

  std::cout << "    ]\n";
  std::cout << "  }\n";
}

} // namespace

int main(int argc, char** argv) {
  base::AtExitManager at_exit_manager;
  CommandLine::Init(argc, argv);

  if (!logging::InitLogging(L"", logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
      logging::DONT_LOCK_LOG_FILE, logging::APPEND_TO_OLD_LOG_FILE,
      logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS)) {
    return 1;
  }

  CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  DCHECK(cmd_line != NULL);

  if (cmd_line->HasSwitch("help") || !cmd_line->args().empty()) {
    return Usage();
  }

  // If the process-name is empty or missing we match all processes.
  std::string process_re = cmd_line->GetSwitchValueASCII("process-name");
  RegexpProcessFilter filter;
  if (!filter.Initialize(process_re)) {
    LOG(ERROR) << "Incorrect process filter regular expression.";
    return 1;
  }

  typedef std::list<ProcessInfo> WorkingSets;
  WorkingSets working_sets;

  const base::ProcessEntry* entry = NULL;
  base::ProcessIterator process_iterator(&filter);
  while (entry = process_iterator.NextProcessEntry()) {
    working_sets.push_back(ProcessInfo());
    ProcessInfo& info = working_sets.back();
    if (info.ws.Initialize(entry->pid())) {
      info.exe_file = entry->exe_file();
      info.pid = entry->pid();
      info.parent_pid = entry->parent_pid();
    } else {
      LOG(ERROR) << "Unable to capture working set information for pid: "
          << entry->pid();
      working_sets.pop_back();
    }
  }

  std::cout << "[\n";
  WorkingSets::const_iterator it = working_sets.begin();
  for (; it != working_sets.end(); ++it)
    OutputProcessInfo(*it);
  std::cout << "]\n";

  return 1;
}
<|endoftext|>


<commit_before>/* --- This file is distributed under the MIT Open Source License, as detailed
   in "LICENSE.TXT" in the root of the programming_by_contract repository --- */

// needed to test programming_by_contract with NDEBUG!
#ifndef NDEBUG
#  define NDEBUG 1
#endif

#include "hurchalla/programming_by_contract/programming_by_contract.h"
#include "testhelper_assert_handler.h"
#include "hurchalla/programming_by_contract/assert_handler.h"

#include "gtest/gtest.h"

#include <type_traits>

// This macro doesn't strictly test that the expression does not exit -
// If the expression exits with a value of 0 it will pass this macro
#ifndef EXPECT_NO_EXIT
    #define EXPECT_NO_EXIT(EXPRESSION) do \
           { EXPECT_EXIT(EXPRESSION; exit(0), testing::ExitedWithCode(0), ""); } while(0)
#endif

// confirm the contract-asserts have zero overhead when NDEBUG is defined
static_assert(std::is_same<decltype(precondition(true)), void>::value, "");
static_assert(std::is_same<decltype(precondition2(true)), void>::value, "");
static_assert(std::is_same<decltype(precondition3(true)), void>::value, "");
static_assert(std::is_same<decltype(postcondition(true)), void>::value, "");
static_assert(std::is_same<decltype(postcondition2(true)), void>::value, "");
static_assert(std::is_same<decltype(postcondition3(true)), void>::value, "");
static_assert(std::is_same<decltype(assert_body(true)), void>::value, "");
static_assert(std::is_same<decltype(assert_body2(true)), void>::value, "");
static_assert(std::is_same<decltype(assert_body3(true)), void>::value, "");
static_assert(std::is_same<decltype(invariant(true)), void>::value, "");
static_assert(std::is_same<decltype(invariant2(true)), void>::value, "");
static_assert(std::is_same<decltype(invariant3(true)), void>::value, "");
static_assert(std::is_same<decltype(precondition(false)), void>::value, "");
static_assert(std::is_same<decltype(precondition2(false)), void>::value, "");
static_assert(std::is_same<decltype(precondition3(false)), void>::value, "");
static_assert(std::is_same<decltype(postcondition(false)), void>::value, "");
static_assert(std::is_same<decltype(postcondition2(false)), void>::value, "");
static_assert(std::is_same<decltype(postcondition3(false)), void>::value, "");
static_assert(std::is_same<decltype(assert_body(false)), void>::value, "");
static_assert(std::is_same<decltype(assert_body2(false)), void>::value, "");
static_assert(std::is_same<decltype(assert_body3(false)), void>::value, "");
static_assert(std::is_same<decltype(invariant(false)), void>::value, "");
static_assert(std::is_same<decltype(invariant2(false)), void>::value, "");
static_assert(std::is_same<decltype(invariant3(false)), void>::value, "");

namespace {
    // since all the programming by contract asserts map to void when NDEBUG
    // is defined, we expect they will never exit/abort when NDEBUG is defined.
	TEST(PbcNdebugTest, PreconditionsHandlerLevel3) {
        setTestHandlerPreconditionAssertLevel(3);
		EXPECT_NO_EXIT(precondition(true));
		EXPECT_NO_EXIT(precondition2(true));
		EXPECT_NO_EXIT(precondition3(true));
		EXPECT_NO_EXIT(precondition(false));
		EXPECT_NO_EXIT(precondition2(false));
		EXPECT_NO_EXIT(precondition3(false));
	}
	TEST(PbcNdebugTest, PreconditionsHandlerLevel0) {
		setTestHandlerPreconditionAssertLevel(0);
		EXPECT_NO_EXIT(precondition(true));
		EXPECT_NO_EXIT(precondition2(true));
		EXPECT_NO_EXIT(precondition3(true));
		EXPECT_NO_EXIT(precondition(false));
		EXPECT_NO_EXIT(precondition2(false));
		EXPECT_NO_EXIT(precondition3(false));
	}
	TEST(PbcNdebugTest, GeneralAssertsHandlerLevel3) {
		setTestHandlerAssertLevel(3);
		EXPECT_NO_EXIT(assert_body(false));
		EXPECT_NO_EXIT(assert_body2(false));
		EXPECT_NO_EXIT(assert_body3(false));
		EXPECT_NO_EXIT(postcondition(false));
		EXPECT_NO_EXIT(postcondition2(false));
		EXPECT_NO_EXIT(postcondition3(false));
		EXPECT_NO_EXIT(invariant(false));
		EXPECT_NO_EXIT(invariant2(false));
		EXPECT_NO_EXIT(invariant3(false));
		EXPECT_NO_EXIT(assert_body(true));
		EXPECT_NO_EXIT(assert_body2(true));
		EXPECT_NO_EXIT(assert_body3(true));
		EXPECT_NO_EXIT(postcondition(true));
		EXPECT_NO_EXIT(postcondition2(true));
		EXPECT_NO_EXIT(postcondition3(true));
		EXPECT_NO_EXIT(invariant(true));
		EXPECT_NO_EXIT(invariant2(true));
		EXPECT_NO_EXIT(invariant3(true));
	}
	TEST(PbcNdebugTest, GeneralAssertsHandlerLevel0) {
		setTestHandlerAssertLevel(0);
		EXPECT_NO_EXIT(assert_body(false));
		EXPECT_NO_EXIT(assert_body2(false));
		EXPECT_NO_EXIT(assert_body3(false));
		EXPECT_NO_EXIT(postcondition(false));
		EXPECT_NO_EXIT(postcondition2(false));
		EXPECT_NO_EXIT(postcondition3(false));
		EXPECT_NO_EXIT(invariant(false));
		EXPECT_NO_EXIT(invariant2(false));
		EXPECT_NO_EXIT(invariant3(false));
		EXPECT_NO_EXIT(assert_body(true));
		EXPECT_NO_EXIT(assert_body2(true));
		EXPECT_NO_EXIT(assert_body3(true));
		EXPECT_NO_EXIT(postcondition(true));
		EXPECT_NO_EXIT(postcondition2(true));
		EXPECT_NO_EXIT(postcondition3(true));
		EXPECT_NO_EXIT(invariant(true));
		EXPECT_NO_EXIT(invariant2(true));
		EXPECT_NO_EXIT(invariant3(true));
	}
}
<commit_msg>improve macros and formatting<commit_after>/* --- This file is distributed under the MIT Open Source License, as detailed
   in "LICENSE.TXT" in the root of the programming_by_contract repository --- */

// needed to test programming_by_contract with NDEBUG!
#ifndef NDEBUG
#  define NDEBUG 1
#endif

#include "hurchalla/programming_by_contract/programming_by_contract.h"
#include "testhelper_assert_handler.h"
#include "hurchalla/programming_by_contract/assert_handler.h"

#include "gtest/gtest.h"

#include <type_traits>

// This macro doesn't strictly test that the expression does not exit -
// If the expression exits with a value of 0 it will pass this macro
#ifndef PBC_EXPECT_NO_EXIT
    #define PBC_EXPECT_NO_EXIT(EXPRESSION) do \
           { EXPECT_EXIT(EXPRESSION; exit(0), testing::ExitedWithCode(0), ""); \
           } while(0)
#endif

// confirm the contract-asserts have zero overhead when NDEBUG is defined
static_assert(std::is_same<decltype(precondition(true)), void>::value, "");
static_assert(std::is_same<decltype(precondition2(true)), void>::value, "");
static_assert(std::is_same<decltype(precondition3(true)), void>::value, "");
static_assert(std::is_same<decltype(postcondition(true)), void>::value, "");
static_assert(std::is_same<decltype(postcondition2(true)), void>::value, "");
static_assert(std::is_same<decltype(postcondition3(true)), void>::value, "");
static_assert(std::is_same<decltype(assert_body(true)), void>::value, "");
static_assert(std::is_same<decltype(assert_body2(true)), void>::value, "");
static_assert(std::is_same<decltype(assert_body3(true)), void>::value, "");
static_assert(std::is_same<decltype(invariant(true)), void>::value, "");
static_assert(std::is_same<decltype(invariant2(true)), void>::value, "");
static_assert(std::is_same<decltype(invariant3(true)), void>::value, "");
static_assert(std::is_same<decltype(precondition(false)), void>::value, "");
static_assert(std::is_same<decltype(precondition2(false)), void>::value, "");
static_assert(std::is_same<decltype(precondition3(false)), void>::value, "");
static_assert(std::is_same<decltype(postcondition(false)), void>::value, "");
static_assert(std::is_same<decltype(postcondition2(false)), void>::value, "");
static_assert(std::is_same<decltype(postcondition3(false)), void>::value, "");
static_assert(std::is_same<decltype(assert_body(false)), void>::value, "");
static_assert(std::is_same<decltype(assert_body2(false)), void>::value, "");
static_assert(std::is_same<decltype(assert_body3(false)), void>::value, "");
static_assert(std::is_same<decltype(invariant(false)), void>::value, "");
static_assert(std::is_same<decltype(invariant2(false)), void>::value, "");
static_assert(std::is_same<decltype(invariant3(false)), void>::value, "");

namespace {
    // since all the programming by contract asserts map to void when NDEBUG
    // is defined, we expect they will never exit/abort when NDEBUG is defined.
	TEST(PbcNdebugTest, PreconditionsHandlerLevel3) {
        setTestHandlerPreconditionAssertLevel(3);
		PBC_EXPECT_NO_EXIT(precondition(true));
		PBC_EXPECT_NO_EXIT(precondition2(true));
		PBC_EXPECT_NO_EXIT(precondition3(true));
		PBC_EXPECT_NO_EXIT(precondition(false));
		PBC_EXPECT_NO_EXIT(precondition2(false));
		PBC_EXPECT_NO_EXIT(precondition3(false));
	}
	TEST(PbcNdebugTest, PreconditionsHandlerLevel0) {
		setTestHandlerPreconditionAssertLevel(0);
		PBC_EXPECT_NO_EXIT(precondition(true));
		PBC_EXPECT_NO_EXIT(precondition2(true));
		PBC_EXPECT_NO_EXIT(precondition3(true));
		PBC_EXPECT_NO_EXIT(precondition(false));
		PBC_EXPECT_NO_EXIT(precondition2(false));
		PBC_EXPECT_NO_EXIT(precondition3(false));
	}
	TEST(PbcNdebugTest, GeneralAssertsHandlerLevel3) {
		setTestHandlerAssertLevel(3);
		PBC_EXPECT_NO_EXIT(assert_body(false));
		PBC_EXPECT_NO_EXIT(assert_body2(false));
		PBC_EXPECT_NO_EXIT(assert_body3(false));
		PBC_EXPECT_NO_EXIT(postcondition(false));
		PBC_EXPECT_NO_EXIT(postcondition2(false));
		PBC_EXPECT_NO_EXIT(postcondition3(false));
		PBC_EXPECT_NO_EXIT(invariant(false));
		PBC_EXPECT_NO_EXIT(invariant2(false));
		PBC_EXPECT_NO_EXIT(invariant3(false));
		PBC_EXPECT_NO_EXIT(assert_body(true));
		PBC_EXPECT_NO_EXIT(assert_body2(true));
		PBC_EXPECT_NO_EXIT(assert_body3(true));
		PBC_EXPECT_NO_EXIT(postcondition(true));
		PBC_EXPECT_NO_EXIT(postcondition2(true));
		PBC_EXPECT_NO_EXIT(postcondition3(true));
		PBC_EXPECT_NO_EXIT(invariant(true));
		PBC_EXPECT_NO_EXIT(invariant2(true));
		PBC_EXPECT_NO_EXIT(invariant3(true));
	}
	TEST(PbcNdebugTest, GeneralAssertsHandlerLevel0) {
		setTestHandlerAssertLevel(0);
		PBC_EXPECT_NO_EXIT(assert_body(false));
		PBC_EXPECT_NO_EXIT(assert_body2(false));
		PBC_EXPECT_NO_EXIT(assert_body3(false));
		PBC_EXPECT_NO_EXIT(postcondition(false));
		PBC_EXPECT_NO_EXIT(postcondition2(false));
		PBC_EXPECT_NO_EXIT(postcondition3(false));
		PBC_EXPECT_NO_EXIT(invariant(false));
		PBC_EXPECT_NO_EXIT(invariant2(false));
		PBC_EXPECT_NO_EXIT(invariant3(false));
		PBC_EXPECT_NO_EXIT(assert_body(true));
		PBC_EXPECT_NO_EXIT(assert_body2(true));
		PBC_EXPECT_NO_EXIT(assert_body3(true));
		PBC_EXPECT_NO_EXIT(postcondition(true));
		PBC_EXPECT_NO_EXIT(postcondition2(true));
		PBC_EXPECT_NO_EXIT(postcondition3(true));
		PBC_EXPECT_NO_EXIT(invariant(true));
		PBC_EXPECT_NO_EXIT(invariant2(true));
		PBC_EXPECT_NO_EXIT(invariant3(true));
	}
}
<|endoftext|>


<commit_before>/**
 * \file dcs/macro.hpp
 *
 * \brief Provide C-preprocessor (macro) support.
 *
 * \author Marco Guazzone (marco.guazzone@gmail.com)
 *
 *

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

#ifndef DCS_MACRO_HPP
#define DCS_MACRO_HPP

namespace dcs { namespace macro { namespace detail {

// See: http://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/
template <typename T>
inline void suppress_unused_variable_warning(T const&) {}

}}} // Namespace dcs::macro::detail

/// Expands the given argument.
#define DCS_MACRO_EXPAND(x) x

/// The character '#' (hash).
#define DCS_MACRO_HASH_SYM #

/// Prefixes the given argument with the character '#' (hash).
#define DCS_MACRO_HASHIFY(x) DCS_MACRO_EXPAND(DCS_MACRO_HASH_SYM)x

/// Concatenates the two specified arguments.
#define DCS_MACRO_JOIN(x,y) x##y

/// Stringifies (quote) the given argument.
#define DCS_MACRO_QUOTE(x) #x

/// Tells if we're compiling with a C++11 compatible compiler
#if __cplusplus >= 201103L
# define DCS_MACRO_CXX11
#else
# undef DCS_MACRO_CXX11
#endif // DCS_MACRO_CXX111

/// Tells if we're compiling with a C++14 compatible compiler
#if __cplusplus >= 201300L
# define DCS_MACRO_CXX14
#else
# undef DCS_MACRO_CXX14
#endif // DCS_MACRO_CXX114

/// Suppresses the "unused variable" warning issued during compilation.
// TODO: see also boost/core/ignore_used.hpp
#define DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING(x) \
	::dcs::macro::detail::suppress_unused_variable_warning(x)

/// Declares a function, a variable or a type declaration x as deprecated, and
/// provides a suitable message m.
/// Usage:
/// - DCS_MACRO_DECL_DEPRECATED(extern int v, "Variable v is deprecated");
/// - DCS_MACRO_DECL_DEPRECATED(int v, "Variable v is deprecated");
/// - DCS_MACRO_DECL_DEPRECATED(int v, "Variable v is deprecated") = 0;
/// - int DCS_MACRO_DECL_DEPRECATED(v, "Variable v is deprecated") = 0, z = 1;
/// - DCS_MACRO_DECL_DEPRECATED(void f(int), "Function f is deprecated");
/// - DCS_MACRO_DECL_DEPRECATED(void f(int) { }, "Function f is deprecated")
/// - void f (DCS_MACRO_DECL_DEPRECATED(int x, "Parameter x is deprecated")) { }
/// - DCS_MACRO_DECL_DEPRECATED(typedef int I, "Type I is deprecated");
/// - enum DCS_MACRO_DECL_DEPRECATED(E, "Enum E is deprecated") { };
/// - struct DCS_MACRO_DECL_DEPRECATED(S, "Struct S is deprecated");
/// - struct DCS_MACRO_DECL_DEPRECATED(S { }, "Struct S is deprecated");
/// - template <typename T> class DCS_MACRO_DECL_DEPRECATED(C { }, "Template class C is deprecated");
/// - template <> class DCS_MACRO_DECL_DEPRECATED(C<int> { }, "Template specialization C<int> is deprecated");
#ifdef DCS_MACRO_CXX14
// See: http://josephmansfield.uk/articles/marking-deprecated-c++14.html
# define DCS_MACRO_DECL_DEPRECATED(x,m) [[deprecated(m)]] x
#else
//# if defined(_WIN32) || defined(__HP_cc)
# if defined(_MSC_VER)
// If the compiler encounters the use of a deprecated identifier,
// a C4996 warning is thrown
// See: https://msdn.microsoft.com/en-us/library/044swk7y.aspx
#  define DCS_MACRO_DECL_DEPRECATED(x,m) __declspec(deprecated(m)) x
//# elif defined(__GNUC__) && defined(__linux__)
# elif defined(__GNUC__)
// See:
// - https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
// - https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html
// - https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html
#  define DCS_MACRO_DECL_DEPRECATED(x,m) x __attribute__ ((deprecated(m)))
//# elif defined(__SUNPRO_C)
//#  define DCS_MACRO_DECL_DEPRECATED
# else
// Don't know how to make it. Sorry!
// Add a warning comment.
#  define DCS_MACRO_DECL_DEPRECATED(x,m) /*XXX: Deprecated declaration!!*/ x
# endif
#endif // DCS_MACRO_CXX14

/// Marks a function, a variable or a type declaration that should be exported from DLLs or binaries for runtime linking.
#if defined(_WIN32) || defined(__HP_cc)
# define DCS_MACRO_DECL_EXPORT __declspec(dllexport)
#elif defined(__GNUC__) && defined(__linux__)
# define DCS_MACRO_DECL_EXPORT __attribute__ ((visibility("default")))
#elif defined(__SUNPRO_C)
# define DCS_MACRO_DECL_EXPORT __global
#else
# define DCS_MACRO_DECL_EXPORT
#endif

#endif // DCS_MACRO_HPP
<commit_msg>[macro] Bug-fix: corrected macro for C++11<commit_after>/**
 * \file dcs/macro.hpp
 *
 * \brief Provide C-preprocessor (macro) support.
 *
 * \author Marco Guazzone (marco.guazzone@gmail.com)
 *
 *

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

#ifndef DCS_MACRO_HPP
#define DCS_MACRO_HPP

namespace dcs { namespace macro { namespace detail {

// See: http://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/
template <typename T>
inline void suppress_unused_variable_warning(T const&) {}

}}} // Namespace dcs::macro::detail

/// Expands the given argument.
#define DCS_MACRO_EXPAND(x) x

/// The character '#' (hash).
#define DCS_MACRO_HASH_SYM #

/// Prefixes the given argument with the character '#' (hash).
#define DCS_MACRO_HASHIFY(x) DCS_MACRO_EXPAND(DCS_MACRO_HASH_SYM)x

/// Concatenates the two specified arguments.
#define DCS_MACRO_JOIN(x,y) x##y

/// Stringifies (quote) the given argument.
#define DCS_MACRO_QUOTE(x) #x

/// Tells if we're compiling with a C++11 compatible compiler
#if __cplusplus >= 201103L
# define DCS_MACRO_CXX11
#else
# undef DCS_MACRO_CXX11
#endif // DCS_MACRO_CXX111

/// Tells if we're compiling with a C++14 compatible compiler
#if __cplusplus >= 201402L
# define DCS_MACRO_CXX14
#else
# undef DCS_MACRO_CXX14
#endif // DCS_MACRO_CXX114

/// Suppresses the "unused variable" warning issued during compilation.
// TODO: see also boost/core/ignore_used.hpp
#define DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING(x) \
	::dcs::macro::detail::suppress_unused_variable_warning(x)

/// Declares a function, a variable or a type declaration x as deprecated, and
/// provides a suitable message m.
/// Usage:
/// - DCS_MACRO_DECL_DEPRECATED(extern int v, "Variable v is deprecated");
/// - DCS_MACRO_DECL_DEPRECATED(int v, "Variable v is deprecated");
/// - DCS_MACRO_DECL_DEPRECATED(int v, "Variable v is deprecated") = 0;
/// - int DCS_MACRO_DECL_DEPRECATED(v, "Variable v is deprecated") = 0, z = 1;
/// - DCS_MACRO_DECL_DEPRECATED(void f(int), "Function f is deprecated");
/// - DCS_MACRO_DECL_DEPRECATED(void f(int) { }, "Function f is deprecated")
/// - void f (DCS_MACRO_DECL_DEPRECATED(int x, "Parameter x is deprecated")) { }
/// - DCS_MACRO_DECL_DEPRECATED(typedef int I, "Type I is deprecated");
/// - enum DCS_MACRO_DECL_DEPRECATED(E, "Enum E is deprecated") { };
/// - struct DCS_MACRO_DECL_DEPRECATED(S, "Struct S is deprecated");
/// - struct DCS_MACRO_DECL_DEPRECATED(S { }, "Struct S is deprecated");
/// - template <typename T> class DCS_MACRO_DECL_DEPRECATED(C { }, "Template class C is deprecated");
/// - template <> class DCS_MACRO_DECL_DEPRECATED(C<int> { }, "Template specialization C<int> is deprecated");
#ifdef DCS_MACRO_CXX14
// See: http://josephmansfield.uk/articles/marking-deprecated-c++14.html
# define DCS_MACRO_DECL_DEPRECATED(x,m) [[deprecated(m)]] x
#else
//# if defined(_WIN32) || defined(__HP_cc)
# if defined(_MSC_VER)
// If the compiler encounters the use of a deprecated identifier,
// a C4996 warning is thrown
// See: https://msdn.microsoft.com/en-us/library/044swk7y.aspx
#  define DCS_MACRO_DECL_DEPRECATED(x,m) __declspec(deprecated(m)) x
//# elif defined(__GNUC__) && defined(__linux__)
# elif defined(__GNUC__)
// See:
// - https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
// - https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html
// - https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html
#  define DCS_MACRO_DECL_DEPRECATED(x,m) x __attribute__ ((deprecated(m)))
//# elif defined(__SUNPRO_C)
//#  define DCS_MACRO_DECL_DEPRECATED
# else
// Don't know how to make it. Sorry!
// Add a warning comment.
#  define DCS_MACRO_DECL_DEPRECATED(x,m) /*XXX: Deprecated declaration!!*/ x
# endif
#endif // DCS_MACRO_CXX14

/// Marks a function, a variable or a type declaration that should be exported from DLLs or binaries for runtime linking.
#if defined(_WIN32) || defined(__HP_cc)
# define DCS_MACRO_DECL_EXPORT __declspec(dllexport)
#elif defined(__GNUC__) && defined(__linux__)
# define DCS_MACRO_DECL_EXPORT __attribute__ ((visibility("default")))
#elif defined(__SUNPRO_C)
# define DCS_MACRO_DECL_EXPORT __global
#else
# define DCS_MACRO_DECL_EXPORT
#endif

#endif // DCS_MACRO_HPP
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>

using namespace std;

bool IsPrime(int x) {
  if (x == 1) return false;
  for (int i = 2; i * i <= x; ++i) {
    if (x % i == 0) {
      return false;
    }
  }
  return true;
}

bool ProcessCase() {
  int a, d, n;
  cin >> a >> d >> n;
  if (a == 0 && d == 0 && n == 0) return false;
  int x = a;
  int count = 0;
  while (true) {
    if (IsPrime(x)) {
      ++count;
    }
    if (count == n) {
      cout << x << endl;
      return true;
    }
    x += d;
  }
}

int main() {
  while (ProcessCase());
  return 0;
}<commit_msg>Update 1141.<commit_after>#include <iostream>
#include <vector>

using namespace std;

const int MAX_N = 1000000;

vector<int> is_prime_table;

bool IsPrime(int x) {
  if (x == 1) return false;
  for (int i = 2; i * i <= x; ++i) {
    if (x % i == 0) {
      return false;
    }
  }
  return true;
}

bool ProcessCase() {
  int a, d, n;
  cin >> a >> d >> n;
  if (a == 0 && d == 0 && n == 0) return false;
  int x = a;
  int count = 0;
  while (true) {
    if (is_prime_table[x]) {
      ++count;
    }
    if (count == n) {
      cout << x << endl;
      return true;
    }
    x += d;
  }
}

int main() {
  is_prime_table.assign(MAX_N + 1, false);
  for (int i = 1; i <= MAX_N; ++i) {
    is_prime_table[i] = IsPrime(i);
  }
  while (ProcessCase());
  return 0;
}<|endoftext|>


<commit_before>/*!
 * \file socket.cpp
 * \author Nathan Eloe
 * \brief Implementation of the quasi-singleton socket class
 */

#include "socket.h"
#include "context.h"

namespace zmqcpp
{
  std::shared_ptr<zmq::context_t> Context::m_ctx = nullptr;
  thread_local std::map<std::string, std::shared_ptr<zmq::socket_t>> Socket::m_conn;
  std::map<std::string, std::shared_ptr<zmq::socket_t>> Socket::m_bind;

  void Socket::connect(const char* endpt, const bool persist)
  {
    std::string ep(endpt);
    if (!persist)
    {
      m_sock = std::make_shared<zmq::socket_t>(zmq::socket_t(Context::get(), m_type));
      m_sock->connect(endpt);
    }
    else
    {
      if (m_conn.count(ep) == 0)
      {
	m_conn[ep] = std::make_shared<zmq::socket_t>(zmq::socket_t(Context::get(), m_type));
	//m_conn[ep] = std::shared_ptr<zmq::socket_t>(new zmq::socket_t(Context::get(), m_type), [] (zmq::socket_t* p) {p -> close(); delete p;});
	m_conn[ep]->connect(endpt);
      }
      m_sock = m_conn[ep];
    }
  }

  void Socket::bind(const char* endpt, const bool persist)
  {
    std::string ep(endpt);
    if (!persist)
    {
      m_sock = std::make_shared<zmq::socket_t>(zmq::socket_t(Context::get(), m_type));
      m_sock->bind(endpt);
    }
    else
    {
      if (m_bind.count(ep) == 0)
      {
	m_bind[ep] = std::make_shared<zmq::socket_t>(zmq::socket_t(Context::get(), m_type));
	m_bind[ep]->bind(endpt);
      }
      m_sock = m_bind[ep];
    }
  }

  zmq::socket_t& Socket::raw_sock()
  {
    if (!m_sock)
      throw no_endpt();
    return *m_sock;
  }

}<commit_msg>remove a bit of commented code<commit_after>/*!
 * \file socket.cpp
 * \author Nathan Eloe
 * \brief Implementation of the quasi-singleton socket class
 */

#include "socket.h"
#include "context.h"

namespace zmqcpp
{
  std::shared_ptr<zmq::context_t> Context::m_ctx = nullptr;
  thread_local std::map<std::string, std::shared_ptr<zmq::socket_t>> Socket::m_conn;
  std::map<std::string, std::shared_ptr<zmq::socket_t>> Socket::m_bind;

  void Socket::connect(const char* endpt, const bool persist)
  {
    std::string ep(endpt);
    if (!persist)
    {
      m_sock = std::make_shared<zmq::socket_t>(zmq::socket_t(Context::get(), m_type));
      m_sock->connect(endpt);
    }
    else
    {
      if (m_conn.count(ep) == 0)
      {
	m_conn[ep] = std::make_shared<zmq::socket_t>(zmq::socket_t(Context::get(), m_type));
	m_conn[ep]->connect(endpt);
      }
      m_sock = m_conn[ep];
    }
  }

  void Socket::bind(const char* endpt, const bool persist)
  {
    std::string ep(endpt);
    if (!persist)
    {
      m_sock = std::make_shared<zmq::socket_t>(zmq::socket_t(Context::get(), m_type));
      m_sock->bind(endpt);
    }
    else
    {
      if (m_bind.count(ep) == 0)
      {
	m_bind[ep] = std::make_shared<zmq::socket_t>(zmq::socket_t(Context::get(), m_type));
	m_bind[ep]->bind(endpt);
      }
      m_sock = m_bind[ep];
    }
  }

  zmq::socket_t& Socket::raw_sock()
  {
    if (!m_sock)
      throw no_endpt();
    return *m_sock;
  }

}<|endoftext|>


<commit_before>#include "socket.h"

#include <stdio.h>
#include <string.h>

#if defined(_WIN32)
#pragma comment( lib, "wsock32.lib" )
#pragma comment( lib, "Ws2_32.lib" )
#else
#include <errno.h>
#endif

#if defined(_WIN32)
typedef int socklen_t;
#endif

#if defined(_WIN32)
#define BNS_SOCKET_ERROR() printf("Socket error: %d\n", WSAGetLastError())
#else
#define BNS_SOCKET_ERROR() printf("Socket error: %d\n", WSAGetLastError())
#endif

IPV4Addr::IPV4Addr(int _addr, short _port){
	addr = _addr;
	port = _port;
}

IPV4Addr::IPV4Addr(unsigned char a, unsigned char b, unsigned char c, unsigned char d, short _port){
	addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
	port = htons(_port);
}

IPV4Addr::IPV4Addr(const char* hostName, int _port){
#if defined(_WIN32)
	struct addrinfo hints = {};
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;

	struct addrinfo* result;
	int error = getaddrinfo(hostName, NULL, &hints, &result);
	if (result != nullptr) {
		addr = ((sockaddr_in*)(result->ai_addr))->sin_addr.s_addr;
		port = htons(_port);
		freeaddrinfo(result);
	}
	else {
		printf("\nError resolving host: '%s'\n", hostName);
	}
#else
#endif
}

void IPV4Addr::WriteToString(char* buffer, int bufferSize){
	int hostAddr = ntohl(addr);
	short hostPort = ntohs(port);
	snprintf(buffer, bufferSize, "%d.%d.%d.%d:%d", (hostAddr >> 24), (hostAddr >> 16) & 0xFF, (hostAddr >> 8) & 0xFF, hostAddr & 0xFF, hostPort);
}

sockaddr_in IPV4Addr::ToSockAddr(){
	sockaddr_in ip = {};
	ip.sin_addr.s_addr = addr;
	ip.sin_port = port;
	ip.sin_family = AF_INET;

	return ip;
}

bool Socket::Create(SocketProtocol _protocol, SocketBlockingType _blockingType){
	protocol = _protocol;
	blockingType = _blockingType;

	if (protocol == SP_UDP){
		handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	}
	else if (protocol == SP_TCP){
		handle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	}
	else{
		//uuuuhhhh...
	}

	if (handle <= 0){
	}

#if defined(_WIN32)
	if (_blockingType == SBT_NonBlocking){
		u_long nonBlocking = 1;
		if (ioctlsocket( handle, FIONBIO, &nonBlocking ) != 0){
			printf( "failed to set non-blocking\n" );
			return false;
		}
	}
#else
	if (_blockingType == SBT_NonBlocking){
		int nonBlocking = 1;
		if (fcntl( handle, F_SETFL, O_NONBLOCK, nonBlocking) == -1){
			printf( "failed to set non-blocking\n" );
			return false;
		}
	}
#endif

return true;
}

bool Socket::Bind(int _port /*= 0*/){
	sockaddr_in address;
	address.sin_family = AF_INET;
	address.sin_addr.s_addr = INADDR_ANY;
	address.sin_port = htons((unsigned short)_port);

	source.addr = htonl((127 << 24) | 1);

	int retVal = bind(handle, (const sockaddr*) &address, sizeof(sockaddr_in));

	if (retVal < 0 ){
		printf( "failed to bind socket\n" );
		return false;
	}

	if (_port == 0) {
		sockaddr boundAddr;

		socklen_t boundLen = sizeof(sockaddr);
		int val = getsockname(handle, &boundAddr, &boundLen);

		if (val != 0) {
#if defined(_WIN32)
	printf("\nWarning: could not determine port of socket (error %d).\n", WSAGetLastError());
#else
	printf("\nWarning: could not determine port of socket.\n");
#endif
			source.port = 0;
		}
		else {
			source.port = ((sockaddr_in*)(&boundAddr))->sin_port;
		}
	}
	else {
		source.port = htons(_port);
	}
	return true;
}

bool Socket::Connect(IPV4Addr addr){
	destination = addr;
	source = IPV4Addr(127, 0, 0, 1, source.port);

	sockaddr_in dstAddr = destination.ToSockAddr();
	int ret = connect(handle, (sockaddr*)(&dstAddr), sizeof(dstAddr));

	if (ret != 0) {
#if defined(_WIN32)
		int err = WSAGetLastError();
		printf("connect failed (err: %d)\n", err);
#else
		printf("connect failed\n");
#endif
		return false;
	}
	else {
		return true;
	}
}

bool Socket::SetBlocking(SocketBlockingType bt) {
#if defined(_WIN32)
	u_long iMode = (bt == SBT_NonBlocking ? 1 : 0);
	int rv = ioctlsocket(handle, FIONBIO, &iMode);

	return rv == 0;
#else
	return false;
#endif
}

bool Socket::SendData(const void* buffer, int buffLength, int* bytesSent){
	char srcAddr[256] = {};
	char dstAddr[256] = {};

	source.WriteToString(srcAddr, sizeof(srcAddr));
	destination.WriteToString(dstAddr, sizeof(dstAddr));

	printf("Sending %d bytes from '%s' to '%s'\n", buffLength, srcAddr, dstAddr);

	sockaddr_in address = destination.ToSockAddr();

	int sentBytes = sendto(handle, (const char*)buffer, buffLength, 0, (sockaddr*)&address, sizeof(sockaddr_in));

	if (sentBytes != buffLength){
#if defined(_WIN32)
		int lastErr = WSAGetLastError();
		printf("failed to send packet (err: %d)\n", lastErr);
#else
		printf("failed to send packet.\n");
#endif
		return false;
	}

	*bytesSent = sentBytes;

	return true;
}

bool Socket::ReceiveData(void* buffer, int buffLength, int* bytesReceived, IPV4Addr* outAddr){
	sockaddr_in from = {};

	socklen_t fromLen = sizeof(from);
	int receivedBytes = recvfrom(handle, (char*)buffer, buffLength, 0, (sockaddr*)&from, &fromLen);

	if (receivedBytes == -1 && errno != EWOULDBLOCK){
		printf("Socket encountered error '%s'\n", strerror(errno));
	}

	IPV4Addr addr;
	addr.addr = from.sin_addr.s_addr;
	addr.port = from.sin_port;

	*outAddr = addr;

	*bytesReceived = receivedBytes;

	return receivedBytes > 0;
}

bool Socket::Listen(int backlog){
	int retVal = listen(handle, backlog);

	if (retVal == 0){
		return true;
	}
	else{
		BNS_SOCKET_ERROR();
		return false;
	}
}

bool Socket::AcceptConnection(Socket* outSocket){
	sockaddr_in from = {};
	socklen_t fromLen = sizeof(from);
	int rv = accept(handle, (sockaddr*)&from, &fromLen);

	if (rv < 0){
		return false;
	}
	else{
		*outSocket = *this;
		outSocket->handle = rv;

		IPV4Addr addr;
		addr.addr = from.sin_addr.s_addr;
		addr.port = from.sin_port;

		outSocket->destination = addr;

		return true;
	}
}

bool Socket::Destroy(){
#if defined(_WIN32)
	// TODO: close for windows
	closesocket(handle);
	return true;
#else
	close(handle);
	return true;
#endif
}

bool isSocketSystemInitialised = false;

bool StartUpSocketSystem(){
#if defined(_WIN32)
	WSADATA WsaData;
    return WSAStartup(MAKEWORD(2,2), &WsaData) == NO_ERROR;
#else
	return true;
#endif
}

bool ShutdownSocketSystem(){
	return true;
}

#if defined(SOCKET_TEST_MAIN)

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

	if(StartUpSocketSystem()){
		printf("Failed to init socket system, exiting.\n");
		return -1;
	}

	Socket sock1;
	sock1.Create(SP_UDP, SBT_NonBlocking);
	sock1.Bind(12245);

	Socket sock2;
	sock2.Create(SP_UDP, SBT_NonBlocking);
	sock2.Bind(12243);

	sock1.Connect(sock2.source);

	const char* dataToSend = "Hello World";

	int bytesSent = 0;
	sock1.SendData(dataToSend, strlen(dataToSend)+1, &bytesSent);

	usleep(1000);

	char packet[256];
	int bytesReceived = 0;
	int timeout = 0;
	while (bytesReceived <= 0){
		IPV4Addr addr;
		sock2.ReceiveData(packet, sizeof(packet), &bytesReceived, &addr);
		usleep(1000);

		timeout++;
		if (timeout > 10){
			break;
		}
	}

	printf("Received '%s' from socket.\n", packet);

	if (strcmp(packet, dataToSend) != 0){
		return -1;
	}

	return 0;
}

#endif
<commit_msg>Windows fixes.<commit_after>#include "socket.h"

#include <stdio.h>
#include <string.h>

#if defined(_WIN32)
#pragma comment( lib, "wsock32.lib" )
#pragma comment( lib, "Ws2_32.lib" )
#else
#include <errno.h>
#endif

#if defined(_WIN32)
typedef int socklen_t;
#endif

#if defined(_WIN32)
#define BNS_SOCKET_ERROR() printf("Socket error: %d\n", WSAGetLastError())
#else
#define BNS_SOCKET_ERROR() printf("Socket error: %d\n", WSAGetLastError())
#endif

IPV4Addr::IPV4Addr(int _addr, short _port){
	addr = _addr;
	port = _port;
}

IPV4Addr::IPV4Addr(unsigned char a, unsigned char b, unsigned char c, unsigned char d, short _port){
	addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
	port = htons(_port);
}

IPV4Addr::IPV4Addr(const char* hostName, int _port){
#if defined(_WIN32)
	struct addrinfo hints = {};
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;

	struct addrinfo* result;
	int error = getaddrinfo(hostName, NULL, &hints, &result);
	if (result != nullptr) {
		addr = ((sockaddr_in*)(result->ai_addr))->sin_addr.s_addr;
		port = htons(_port);
		freeaddrinfo(result);
	}
	else {
		printf("\nError resolving host: '%s'\n", hostName);
	}
#else
#endif
}

void IPV4Addr::WriteToString(char* buffer, int bufferSize){
	int hostAddr = ntohl(addr);
	short hostPort = ntohs(port);
	snprintf(buffer, bufferSize, "%d.%d.%d.%d:%d", (hostAddr >> 24), (hostAddr >> 16) & 0xFF, (hostAddr >> 8) & 0xFF, hostAddr & 0xFF, hostPort);
}

sockaddr_in IPV4Addr::ToSockAddr(){
	sockaddr_in ip = {};
	ip.sin_addr.s_addr = addr;
	ip.sin_port = port;
	ip.sin_family = AF_INET;

	return ip;
}

bool Socket::Create(SocketProtocol _protocol, SocketBlockingType _blockingType){
	protocol = _protocol;
	blockingType = _blockingType;

	if (protocol == SP_UDP){
		handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	}
	else if (protocol == SP_TCP){
		handle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	}
	else{
		//uuuuhhhh...
	}

	if (handle <= 0){
	}

#if defined(_WIN32)
	if (_blockingType == SBT_NonBlocking){
		u_long nonBlocking = 1;
		if (ioctlsocket( handle, FIONBIO, &nonBlocking ) != 0){
			printf( "failed to set non-blocking\n" );
			return false;
		}
	}
#else
	if (_blockingType == SBT_NonBlocking){
		int nonBlocking = 1;
		if (fcntl( handle, F_SETFL, O_NONBLOCK, nonBlocking) == -1){
			printf( "failed to set non-blocking\n" );
			return false;
		}
	}
#endif

return true;
}

bool Socket::Bind(int _port /*= 0*/){
	sockaddr_in address;
	address.sin_family = AF_INET;
	address.sin_addr.s_addr = INADDR_ANY;
	address.sin_port = htons((unsigned short)_port);

	source.addr = htonl((127 << 24) | 1);

	int retVal = bind(handle, (const sockaddr*) &address, sizeof(sockaddr_in));

	if (retVal < 0 ){
		printf( "failed to bind socket\n" );
		return false;
	}

	if (_port == 0) {
		sockaddr boundAddr;

		socklen_t boundLen = sizeof(sockaddr);
		int val = getsockname(handle, &boundAddr, &boundLen);

		if (val != 0) {
#if defined(_WIN32)
	printf("\nWarning: could not determine port of socket (error %d).\n", WSAGetLastError());
#else
	printf("\nWarning: could not determine port of socket.\n");
#endif
			source.port = 0;
		}
		else {
			source.port = ((sockaddr_in*)(&boundAddr))->sin_port;
		}
	}
	else {
		source.port = htons(_port);
	}
	return true;
}

bool Socket::Connect(IPV4Addr addr){
	destination = addr;
	source = IPV4Addr(127, 0, 0, 1, source.port);

	sockaddr_in dstAddr = destination.ToSockAddr();
	int ret = connect(handle, (sockaddr*)(&dstAddr), sizeof(dstAddr));

	if (ret != 0) {
#if defined(_WIN32)
		int err = WSAGetLastError();
		printf("connect failed (err: %d)\n", err);
#else
		printf("connect failed\n");
#endif
		return false;
	}
	else {
		return true;
	}
}

bool Socket::SetBlocking(SocketBlockingType bt) {
#if defined(_WIN32)
	u_long iMode = (bt == SBT_NonBlocking ? 1 : 0);
	int rv = ioctlsocket(handle, FIONBIO, &iMode);

	return rv == 0;
#else
	return false;
#endif
}

bool Socket::SendData(const void* buffer, int buffLength, int* bytesSent){
	char srcAddr[256] = {};
	char dstAddr[256] = {};

	source.WriteToString(srcAddr, sizeof(srcAddr));
	destination.WriteToString(dstAddr, sizeof(dstAddr));

	printf("Sending %d bytes from '%s' to '%s'\n", buffLength, srcAddr, dstAddr);

	sockaddr_in address = destination.ToSockAddr();

	int sentBytes = sendto(handle, (const char*)buffer, buffLength, 0, (sockaddr*)&address, sizeof(sockaddr_in));

	if (sentBytes != buffLength){
#if defined(_WIN32)
		int lastErr = WSAGetLastError();
		printf("failed to send packet (err: %d)\n", lastErr);
#else
		printf("failed to send packet.\n");
#endif
		return false;
	}

	*bytesSent = sentBytes;

	return true;
}

bool Socket::ReceiveData(void* buffer, int buffLength, int* bytesReceived, IPV4Addr* outAddr){
	sockaddr_in from = {};

	socklen_t fromLen = sizeof(from);
	int receivedBytes = recvfrom(handle, (char*)buffer, buffLength, 0, (sockaddr*)&from, &fromLen);

	if (receivedBytes == -1 && errno != 0 && errno != EWOULDBLOCK){
		printf("Socket encountered error '%s'\n", strerror(errno));
	}

	IPV4Addr addr;
	addr.addr = from.sin_addr.s_addr;
	addr.port = from.sin_port;

	*outAddr = addr;

	*bytesReceived = receivedBytes;

	return receivedBytes > 0;
}

bool Socket::Listen(int backlog){
	int retVal = listen(handle, backlog);

	if (retVal == 0){
		return true;
	}
	else{
		BNS_SOCKET_ERROR();
		return false;
	}
}

bool Socket::AcceptConnection(Socket* outSocket){
	sockaddr_in from = {};
	socklen_t fromLen = sizeof(from);
	int rv = accept(handle, (sockaddr*)&from, &fromLen);

	if (rv < 0){
		return false;
	}
	else{
		*outSocket = *this;
		outSocket->handle = rv;

		IPV4Addr addr;
		addr.addr = from.sin_addr.s_addr;
		addr.port = from.sin_port;

		outSocket->destination = addr;

		return true;
	}
}

bool Socket::Destroy(){
#if defined(_WIN32)
	// TODO: close for windows
	closesocket(handle);
	return true;
#else
	close(handle);
	return true;
#endif
}

bool isSocketSystemInitialised = false;

bool StartUpSocketSystem(){
#if defined(_WIN32)
	WSADATA WsaData;
    return WSAStartup(MAKEWORD(2,2), &WsaData) == NO_ERROR;
#else
	return true;
#endif
}

bool ShutdownSocketSystem(){
	return true;
}

#if defined(SOCKET_TEST_MAIN)

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

	if(StartUpSocketSystem()){
		printf("Failed to init socket system, exiting.\n");
		return -1;
	}

	Socket sock1;
	sock1.Create(SP_UDP, SBT_NonBlocking);
	sock1.Bind(12245);

	Socket sock2;
	sock2.Create(SP_UDP, SBT_NonBlocking);
	sock2.Bind(12243);

	sock1.Connect(sock2.source);

	const char* dataToSend = "Hello World";

	int bytesSent = 0;
	sock1.SendData(dataToSend, strlen(dataToSend)+1, &bytesSent);

	usleep(1000);

	char packet[256];
	int bytesReceived = 0;
	int timeout = 0;
	while (bytesReceived <= 0){
		IPV4Addr addr;
		sock2.ReceiveData(packet, sizeof(packet), &bytesReceived, &addr);
		usleep(1000);

		timeout++;
		if (timeout > 10){
			break;
		}
	}

	printf("Received '%s' from socket.\n", packet);

	if (strcmp(packet, dataToSend) != 0){
		return -1;
	}

	return 0;
}

#endif
<|endoftext|>


<commit_before>#include "Ephemeris.h"
#include "Elements.h"
#include "Properties.h"
#include <lucid/math/Algorithm.h>
#include <lucid/math/Constants.h>
#include <lucid/core/FileReader.h>

namespace  core = ::lucid:: core;
namespace  math = ::lucid:: math;
namespace orbit = ::lucid::orbit;

///
///
///

namespace { /// anonymous

	inline orbit::matrix3x3_t Rx(float32_t theta)
	{
		float32_t c = ::cosf(theta);
		float32_t s = ::sinf(theta);

		return orbit::matrix3x3_t(1, 0, 0, 0, c, s, 0, -s, c);
	}

	inline orbit::matrix3x3_t Rz(float32_t theta)
	{
		float32_t c = ::cosf(theta);
		float32_t s = ::sinf(theta);

		return orbit::matrix3x3_t(c, s, 0, -s, c, 0, 0, 0, 1);
	}

}	///	anonymous

///
///
///

namespace lucid {
namespace orbit {

	Ephemeris::Ephemeris()
	{
		///	create the 'special' entry that defines the 'center' of the system

		Properties properties;
		properties.description = "solar system barycenter";

		_names.insert(std::make_pair("SSB", 0));
		_properties.insert(std::make_pair(0, properties));
		_entries.insert(std::make_pair(0, Entry()));
	}

	Ephemeris::~Ephemeris()
	{
	}

	void Ephemeris::initialize(std::string const &path)
	{
		core::FileReader reader(path);

		size_t bodyCount = 0;
		reader.read(bodyCount);
		for (size_t bodyIndex = 0; bodyIndex < bodyCount; ++bodyIndex)
		{
			Properties properties;
			Entry entry;

			size_t hid = 0;
			reader.read(hid);

			std::string target;
			reader.read(target);

			reader.read(entry.center);
			LUCID_VALIDATE(_properties.end() != _properties.find(entry.center), "'" + target + "' specifies unknown center object");

			reader.read(properties.description);
			reader.read(properties.GM);
			reader.read(properties.mass);
			reader.read(properties.radius);

			size_t elementsCount = 0;
			reader.read(elementsCount);

			for (size_t elementsIndex = 0; elementsIndex < elementsCount; ++elementsIndex)
			{
				Elements elements;
				reader.read(&elements, sizeof(elements));
				entry.elements.push_back(elements);
			}

			_names.insert(std::make_pair(target, hid));
			_properties.insert(std::make_pair(hid, properties));
			_entries.insert(std::make_pair(hid, entry));
		}
	}

	size_t Ephemeris::lookup(std::string const &target) const
	{
		auto iter = _names.find(target);
		LUCID_VALIDATE(iter != _names.end(), "unknown target '" + target + "' specified");

		return iter->second;
	}

	void Ephemeris::lookup(Properties &properties, std::string const &target) const
	{
		lookup(properties, lookup(target));
	}

	void Ephemeris::lookup(Properties &properties, size_t target) const
	{
		auto iter = _properties.find(target);
		LUCID_VALIDATE(iter != _properties.end(), "unknown target id specified");

		properties = iter->second;
	}

	size_t Ephemeris::lookup(Elements &elements, std::string const &target, float32_t jdn) const
	{
		return lookup(elements, lookup(target), jdn);
	}

	size_t Ephemeris::lookup(Elements &elements, size_t target, float32_t jdn) const
	{
		auto iter = _entries.find(target);
		LUCID_VALIDATE(iter != _entries.end(), "unknown target id specified");

		Entry const &entry = iter->second;
		size_t const count = entry.elements.size();

		LUCID_VALIDATE(0 < count, "target does not define orbital elements");

		///	find the closest entry to the given julian day.
		///	for now, it is a simple linear scan through the list.
		///	test {

		size_t index = 0;
		float32_t a = ::fabsf(entry.elements[index].JDN - jdn);
		for (size_t i = 1; i < count; ++i)
		{
			float32_t b = ::fabsf(entry.elements[i].JDN - jdn);
			if (b < a)
			{
				index = i;
				a = b;
			}
			else
			{
				break;
			}
		}

		///	} test

		elements = entry.elements[index];

		return entry.center;
	}

	void Ephemeris::compute(vector3_t &position, vector3_t &velocity, std::string const &target, float32_t jdn) const
	{
		compute(position, velocity, lookup(target), jdn);
	}

	void Ephemeris::compute(vector3_t &position, vector3_t &velocity, size_t target, float32_t jdn) const
	{
		Elements elements;
		size_t cid = lookup(elements, target, jdn);

		Properties centerProperties;
		lookup(centerProperties, cid);

		float32_t const spd = 86400.f;
		float32_t const  dt = spd * (jdn - elements.JDN);
		float32_t const  GM = centerProperties.GM;
		float32_t const   e = elements.EC;
		float32_t const   a = elements.A;

		float32_t MA = elements.MA + dt * ::sqrtf(GM / ::powf(a, 3.f));
		MA = ::fmodf(MA, math::constants::two_pi<float32_t>());
		MA = (MA < 0.f) ? MA + math::constants::two_pi<float32_t>(): MA;

		float32_t EA[2] = { MA, 0.f };

		///	TBD: determine completion criteria
		float32_t err = 1.f;
		while (err > math::constants::tol<float32_t>())
		{
			EA[1] = EA[0] - (EA[0] - e * ::sinf(EA[0]) - MA) / (1.f - e * ::cosf(EA[0]));
			std::swap(EA[0], EA[1]);
			err = 0.f;
		}

		float32_t TA = 2.f * ::atan2f(::sqrtf(1.f + e) * ::sinf(0.5f * EA[0]), ::sqrtf(1.f - e) * ::cosf(0.5f * EA[0]));
		float32_t  r = a * (1.f - e * ::cosf(EA[0]));

		position = r * vector3_t(::cosf(TA), ::sinf(TA), 0.f);
		velocity = ::sqrtf(GM * a) / r * vector3_t(-::sinf(EA[0]), ::sqrt(1.f - e * e) * ::cosf(EA[0]), 0.f);

		matrix3x3_t R = Rz(-elements.OM) * Rx(-elements.IN) * Rz(-elements.W);

		position = R * position;
		velocity = R * velocity;
	}

	Ephemeris &Ephemeris::instance()
	{
		static Ephemeris theInstance;
		return theInstance;
	}

}	///	orbit
}	///	lucid
<commit_msg>added convergence criteria for Newton-Raphson algo.  running into the expected precision issues using float.<commit_after>#include "Ephemeris.h"
#include "Elements.h"
#include "Properties.h"
#include <lucid/math/Algorithm.h>
#include <lucid/math/Constants.h>
#include <lucid/core/FileReader.h>

namespace  core = ::lucid:: core;
namespace  math = ::lucid:: math;
namespace orbit = ::lucid::orbit;

///
///
///

namespace { /// anonymous

	inline orbit::matrix3x3_t Rx(float32_t theta)
	{
		float32_t c = ::cosf(theta);
		float32_t s = ::sinf(theta);

		return orbit::matrix3x3_t(1, 0, 0, 0, c, s, 0, -s, c);
	}

	inline orbit::matrix3x3_t Rz(float32_t theta)
	{
		float32_t c = ::cosf(theta);
		float32_t s = ::sinf(theta);

		return orbit::matrix3x3_t(c, s, 0, -s, c, 0, 0, 0, 1);
	}

}	///	anonymous

///
///
///

namespace lucid {
namespace orbit {

	Ephemeris::Ephemeris()
	{
		///	create the 'special' entry that defines the 'center' of the system

		Properties properties;
		properties.description = "solar system barycenter";

		_names.insert(std::make_pair("SSB", 0));
		_properties.insert(std::make_pair(0, properties));
		_entries.insert(std::make_pair(0, Entry()));
	}

	Ephemeris::~Ephemeris()
	{
	}

	void Ephemeris::initialize(std::string const &path)
	{
		core::FileReader reader(path);

		size_t bodyCount = 0;
		reader.read(bodyCount);
		for (size_t bodyIndex = 0; bodyIndex < bodyCount; ++bodyIndex)
		{
			Properties properties;
			Entry entry;

			size_t hid = 0;
			reader.read(hid);

			std::string target;
			reader.read(target);

			reader.read(entry.center);
			LUCID_VALIDATE(_properties.end() != _properties.find(entry.center), "'" + target + "' specifies unknown center object");

			reader.read(properties.description);
			reader.read(properties.GM);
			reader.read(properties.mass);
			reader.read(properties.radius);

			size_t elementsCount = 0;
			reader.read(elementsCount);

			for (size_t elementsIndex = 0; elementsIndex < elementsCount; ++elementsIndex)
			{
				Elements elements;
				reader.read(&elements, sizeof(elements));
				entry.elements.push_back(elements);
			}

			_names.insert(std::make_pair(target, hid));
			_properties.insert(std::make_pair(hid, properties));
			_entries.insert(std::make_pair(hid, entry));
		}
	}

	size_t Ephemeris::lookup(std::string const &target) const
	{
		auto iter = _names.find(target);
		LUCID_VALIDATE(iter != _names.end(), "unknown target '" + target + "' specified");

		return iter->second;
	}

	void Ephemeris::lookup(Properties &properties, std::string const &target) const
	{
		lookup(properties, lookup(target));
	}

	void Ephemeris::lookup(Properties &properties, size_t target) const
	{
		auto iter = _properties.find(target);
		LUCID_VALIDATE(iter != _properties.end(), "unknown target id specified");

		properties = iter->second;
	}

	size_t Ephemeris::lookup(Elements &elements, std::string const &target, float32_t jdn) const
	{
		return lookup(elements, lookup(target), jdn);
	}

	size_t Ephemeris::lookup(Elements &elements, size_t target, float32_t jdn) const
	{
		auto iter = _entries.find(target);
		LUCID_VALIDATE(iter != _entries.end(), "unknown target id specified");

		Entry const &entry = iter->second;
		size_t const count = entry.elements.size();

		LUCID_VALIDATE(0 < count, "target does not define orbital elements");

		///	find the closest entry to the given julian day.
		///	for now, it is a simple linear scan through the list.
		///	test {

		size_t index = 0;
		float32_t a = ::fabsf(entry.elements[index].JDN - jdn);
		for (size_t i = 1; i < count; ++i)
		{
			float32_t b = ::fabsf(entry.elements[i].JDN - jdn);
			if (b < a)
			{
				index = i;
				a = b;
			}
			else
			{
				break;
			}
		}

		///	} test

		elements = entry.elements[index];

		return entry.center;
	}

	void Ephemeris::compute(vector3_t &position, vector3_t &velocity, std::string const &target, float32_t jdn) const
	{
		compute(position, velocity, lookup(target), jdn);
	}

	void Ephemeris::compute(vector3_t &position, vector3_t &velocity, size_t target, float32_t jdn) const
	{
		Elements elements;
		size_t cid = lookup(elements, target, jdn);

		Properties centerProperties;
		lookup(centerProperties, cid);

		float32_t const tolsq = math::constants::tol_tol<float32_t>();
		float32_t const   spd = 86400.f;
		float32_t const    dt = spd * (jdn - elements.JDN);
		float32_t const    GM = centerProperties.GM;
		float32_t const     e = elements.EC;
		float32_t const     a = elements.A;

		float32_t MA = elements.MA + dt * ::sqrtf(GM / ::powf(a, 3.f));
		MA = ::fmodf(MA, math::constants::two_pi<float32_t>());
		MA = (MA < 0.f) ? MA + math::constants::two_pi<float32_t>(): MA;

		float32_t EA[2] = { MA, 0.f };

		float32_t err = EA[0] - EA[1];
		size_t iter = 0;

		while (((err * err) > tolsq) && (iter < 5))
		{
			EA[1] = EA[0] - (EA[0] - e * ::sinf(EA[0]) - MA) / (1.f - e * ::cosf(EA[0]));
			err = EA[1] - EA[0];
			std::swap(EA[0], EA[1]);

			++iter;
		}

		float32_t TA = 2.f * ::atan2f(::sqrtf(1.f + e) * ::sinf(0.5f * EA[0]), ::sqrtf(1.f - e) * ::cosf(0.5f * EA[0]));
		float32_t  r = a * (1.f - e * ::cosf(EA[0]));

		position = r * vector3_t(::cosf(TA), ::sinf(TA), 0.f);
		velocity = ::sqrtf(GM * a) / r * vector3_t(-::sinf(EA[0]), ::sqrt(1.f - e * e) * ::cosf(EA[0]), 0.f);

		matrix3x3_t R = Rz(-elements.OM) * Rx(-elements.IN) * Rz(-elements.W);

		position = R * position;
		velocity = R * velocity;
	}

	Ephemeris &Ephemeris::instance()
	{
		static Ephemeris theInstance;
		return theInstance;
	}

}	///	orbit
}	///	lucid
<|endoftext|>