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

#include "etj_map_statistics.h"
#include <sqlite3.h>
#include <algorithm>
#include "etj_utilities.h"
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include "g_local.h"

MapStatistics::MapStatistics() : _previousLevelTime(0), _currentMillisecondsPlayed(0), _currentMillisecondsOnServer(0), _currentMap(nullptr)
{

}

std::vector<const MapStatistics::MapInformation *> MapStatistics::getMostPlayed()
{
	std::vector<const MapInformation *> mostPlayed;
	for (auto& map : _maps)
	{
		mostPlayed.push_back(&map);
	}

	std::sort(mostPlayed.begin(), mostPlayed.end(), [](const MapInformation *lhs, const MapInformation *rhs)
	{
		return lhs->secondsPlayed > rhs->secondsPlayed;
	});

	return std::move(mostPlayed);
}

std::vector<const MapStatistics::MapInformation *> MapStatistics::getLeastPlayed()
{
	std::vector<const MapInformation *> mostPlayed;
	for (auto& map : _maps)
	{
		mostPlayed.push_back(&map);
	}

	std::sort(mostPlayed.begin(), mostPlayed.end(), [](const MapInformation *lhs, const MapInformation *rhs)
	{
		return lhs->secondsPlayed < rhs->secondsPlayed;
	});

	return std::move(mostPlayed);
}

const std::vector<std::string> *MapStatistics::getCurrentMaps()
{
	return &_currentMaps;
}

std::vector<std::string> MapStatistics::getMaps()
{
	std::vector<std::string> maps;

	for (auto& map: _maps)
	{
		if (map.isOnServer)
		{
			maps.push_back(map.name);
		}
	}

	return std::move(maps);
}

const MapStatistics::MapInformation *MapStatistics::getMapInformation(const std::string& mapName)
{
	const MapInformation *mi = nullptr;
	if (mapName.length() == 0)
	{
		mi = _currentMap;
	}
	else
	{
		auto it = std::find_if(_maps.begin(), _maps.end(), [&mapName](const MapInformation& mapInformation)
		{
			return mapInformation.name == mapName;
		});

		if (it == _maps.end())
		{
			return nullptr;
		}

		mi = &(*it);
	}
	return mi;
}

void MapStatistics::increasePassedCount(const char *mapName)
{
	auto it = std::find_if(_maps.begin(), _maps.end(), [&mapName](const MapInformation& mi)
	{
		return mi.name == mapName;
	});

	if (it == _maps.end())
	{
		Utilities::Error(std::string("Error: Could not find map ") + mapName);
		return;
	}

	it->changed = true;
	++it->votesPassed;
}

void MapStatistics::increaseCallvoteCount(const char *mapName)
{
	auto it = std::find_if(_maps.begin(), _maps.end(), [&mapName](const MapInformation& mi)
	{
		return mi.name == mapName;
	});

	if (it == _maps.end())
	{
		Utilities::Error(std::string("Error: Could not find map ") + mapName);
		return;
	}

	it->changed = true;
	++it->callvoted;
}

void MapStatistics::saveChanges()
{
	if (!_currentMap)
	{
		Utilities::Log("Notification: Map was changed before a new map was loaded. No map statistics were saved.");
		return;
	}
	_currentMap->changed       = true;
	_currentMap->secondsPlayed = _originalSecondsPlayed + (_currentMillisecondsPlayed / 1000);
	_currentMap->timesPlayed  += 1;
	time_t t;
	time(&t);
	_currentMap->lastPlayed = static_cast<int>(t);

	sqlite3 *db = nullptr;
	auto    rc  = sqlite3_open(Utilities::getPath(_databaseName).c_str(), &db);
	if (rc != SQLITE_OK)
	{
		Utilities::Error((boost::format("MapStatistics::saveChanges: Error: Failed to open database. (%d) %s.\n") % rc % sqlite3_errmsg(db)).str());
		return;
	}

	rc = sqlite3_exec(db, "BEGIN TRANSACTION;", nullptr, nullptr, nullptr);
	if (rc != SQLITE_OK)
	{
		Utilities::Error((boost::format("MapStatistics::saveChanges: Error: Failed to start transaction. (%d) %s.\n") % rc % sqlite3_errmsg(db)).str());
		return;
	}

	for (auto &map : _maps)
	{
		if (map.changed)
		{
			rc = sqlite3_exec(db, (boost::format("UPDATE map_statistics SET seconds_played=%d, callvoted=%d, votes_passed=%d, times_played=%d, last_played=%d WHERE id=%d;")
			                       % map.secondsPlayed % map.callvoted % map.votesPassed % map.timesPlayed % map.lastPlayed % map.id
			                       ).str().c_str(), nullptr, nullptr, nullptr);
			if (rc != SQLITE_OK)
			{
				Utilities::Error((boost::format("MapStatistics::saveChanges: Error: Failed to update map. (%d) %s.\n") % rc % sqlite3_errmsg(db)).str());
				return;
			}
		}
	}

	rc = sqlite3_exec(db, "END TRANSACTION;", nullptr, nullptr, nullptr);
	if (rc != SQLITE_OK)
	{
		Utilities::Error((boost::format("MapStatistics::saveChanges: Error: Failed to end transaction. (%d) %s.\n") % rc % sqlite3_errmsg(db)).str());
		return;
	}

	rc = sqlite3_close(db);
	if (rc != SQLITE_OK)
	{
		Utilities::Error((boost::format("MapStatistics::saveChanges: Error: Failed to close sqlite db. (%d) %s") % rc % sqlite3_errmsg(db)).str());
	}
}

void MapStatistics::runFrame(int levelTime)
{
	auto diff = levelTime - _previousLevelTime;
	_previousLevelTime = levelTime;

	_currentMillisecondsOnServer += diff;
	if (Utilities::anyonePlaying())
	{
		_currentMillisecondsPlayed += diff;
		_currentMap->secondsPlayed  = _originalSecondsPlayed + (_currentMillisecondsPlayed / 1000);
	}
}

void MapStatistics::resetFields()
{
	_maps.clear();
	_currentMap                  = nullptr;
	_currentMillisecondsOnServer = 0;
	_currentMillisecondsPlayed   = 0;
	_databaseName                = "";
	_originalSecondsPlayed       = 0;
	_previousLevelTime           = 0;
}

bool MapStatistics::initialize(std::string database, const std::string& currentMap)
{
	resetFields();

	if (database.length() == 0)
	{
		database = "maps_database.db";
	}

	_databaseName = database;
	if (!loadFromDatabase())
	{
		// TODO: error handling
		return false;
	}

	addNewMaps();

	setCurrentMap(currentMap);

	_originalSecondsPlayed = _currentMap->secondsPlayed;

	return true;
}

const MapStatistics::MapInformation *MapStatistics::getCurrentMap() const
{
	return _currentMap;
}

void MapStatistics::setCurrentMap(const std::string currentMap)
{
	auto it = std::find_if(_maps.begin(), _maps.end(), [&currentMap](const MapInformation& iteratee)
	{
		return iteratee.name == currentMap;
	});

	if (it == _maps.end())
	{
		Utilities::Error((boost::format("Error: Failed to set the current map to %s. Map could not be found in the maps vector. Map count: %d\n")
		                  % currentMap % _maps.size()).str());
		return;
	}

	_currentMap = &(*it);
}

void MapStatistics::addNewMaps()
{
	auto                     maps     = Utilities::getMaps();
	auto                     mapCount = 0;
	std::vector<std::string> newMaps;
	_currentMaps = maps;
	std::sort(_currentMaps.begin(), _currentMaps.end());

	for (auto &map : maps)
	{
		++mapCount;
		auto it = std::find_if(_maps.begin(), _maps.end(), [&map](const MapInformation& mi)
		{
			return mi.name == map;
		});

		if (it != _maps.end())
		{
			it->isOnServer = true;
			// skip maps that are already in the array
			continue;
		}

		Utilities::Console((boost::format("Notification: New map %s found.\n") % map).str());

		MapInformation mapInformation;
		mapInformation.name       = map;
		mapInformation.isOnServer = true;

		_maps.push_back(std::move(mapInformation));
		newMaps.push_back(map);
	}

	auto count = newMaps.size();
	saveNewMaps(std::move(newMaps));

	Utilities::Console((boost::format("%d maps on the server. Added %d new maps.\n")
	                    % mapCount % count).str());
}

void MapStatistics::saveNewMaps(std::vector<std::string> newMaps)
{
	sqlite3 *db = nullptr;
	auto    rc  = sqlite3_open(Utilities::getPath(_databaseName).c_str(), &db);
	if (rc != SQLITE_OK)
	{
		Utilities::Error((boost::format("MapStatistics::saveNewMaps: Error: Could not open map database %s\n") % _databaseName).str());
		return;
	}

	for (auto newMap : newMaps)
	{
		std::string sqlEscapedMapName = newMap;
		boost::replace_all(sqlEscapedMapName, "'", "''");
		// Map names won't be doing any SQL injection
		rc = sqlite3_exec(db,
		                  (boost::format("INSERT INTO map_statistics (name, seconds_played, callvoted, votes_passed, times_played, last_played) VALUES ('%s', 0, 0, 0, 0, 0);") % sqlEscapedMapName).str().c_str(), nullptr, nullptr, nullptr);
		if (rc != SQLITE_OK)
		{
			Utilities::Error((boost::format("MapStatistics::saveNewMaps: Error: Failed to execute statement: (%d) %s") % rc % sqlite3_errmsg(db)).str());
			sqlite3_close(db);
			return;
		}

		auto newMapIter = std::find_if(_maps.begin(), _maps.end(), [&newMap](const MapInformation& mi)
		{
			return mi.name == newMap;
		});

		if (newMapIter == _maps.end())
		{
			Utilities::Error("MapStatistics::saveNewMaps: Error: newMapIter == _maps.end()");
			return;
		}
		newMapIter->id = sqlite3_last_insert_rowid(db);
	}

	sqlite3_close(db);
}

bool MapStatistics::loadFromDatabase()
{
	if (!createDatabase())
	{
		return false;
	}

	if (!loadMaps())
	{
		return false;
	}

	return true;
}

bool MapStatistics::loadMaps()
{
	sqlite3 *db = nullptr;

	auto rc = sqlite3_open(Utilities::getPath(_databaseName).c_str(), &db);
	if (rc != SQLITE_OK)
	{
		Utilities::Error((boost::format("MapStatistics::loadMaps: Error: Failed to open database %s\n")
		                  % _databaseName).str());
		return false;
	}

	// id INTEGER PRIMARY KEY AUTOINCREMENT, seconds_played INTEGER NOT NULL, callvoted INTEGER NOT NULL, votes_passed INTEGER NOT NULL, times_played INTEGER NOT NULL
	sqlite3_stmt *stmt = nullptr;
	rc = sqlite3_prepare(db, "SELECT id, name, seconds_played, callvoted, votes_passed, times_played, last_played FROM map_statistics;", -1, &stmt, nullptr);
	if (rc != SQLITE_OK)
	{
		Utilities::Error((boost::format("MapStatistics::loadMaps: Error: Failed to prepare statement: (%d) %s\n")
		                  % rc % sqlite3_errmsg(db)).str());
		sqlite3_close(db);
		return false;
	}

	rc = sqlite3_step(stmt);
	while (rc == SQLITE_ROW)
	{
		MapInformation mi;

		mi.id = sqlite3_column_int(stmt, 0);
		auto name = reinterpret_cast<const char *>(sqlite3_column_text(stmt, 1));
		mi.name          = name ? name : "";
		mi.secondsPlayed = sqlite3_column_int(stmt, 2);
		mi.callvoted     = sqlite3_column_int(stmt, 3);
		mi.votesPassed   = sqlite3_column_int(stmt, 4);
		mi.timesPlayed   = sqlite3_column_int(stmt, 5);
		mi.lastPlayed    = sqlite3_column_int(stmt, 6);
		mi.isOnServer    = false;

		_maps.push_back(mi);
		rc = sqlite3_step(stmt);
	}

	if (rc != SQLITE_DONE)
	{
		Utilities::Error((boost::format("MapStatistics::loadMaps: Error: Reading map statistics failed. (%d) %s\n")
		                  % rc % sqlite3_errmsg(db)).str());
		sqlite3_finalize(stmt);
		sqlite3_close(db);
		return false;
	}

	sqlite3_finalize(stmt);
	sqlite3_close(db);

	return true;
}

bool MapStatistics::createDatabase()
{
	sqlite3 *db = nullptr;
	auto    rc  = sqlite3_open(Utilities::getPath(_databaseName).c_str(), &db);
	if (rc != SQLITE_OK)
	{
		Utilities::Error((boost::format("MapStatistics::createDatabase: Error: Failed to open database %s\n")
		                  % _databaseName).str());
		return false;
	}

	char *errorMessage = nullptr;
	rc = sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS map_statistics (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, seconds_played INTEGER NOT NULL, callvoted INTEGER NOT NULL, votes_passed INTEGER NOT NULL, times_played INTEGER NOT NULL, last_played INTEGER NOT NULL);", nullptr, nullptr, &errorMessage);
	if (rc != SQLITE_OK)
	{
		sqlite3_free(errorMessage);
		sqlite3_close(db);
		Utilities::Error((boost::format("MapStatistics::createDatabase: Error: Failed to create database %s. (%d) %s")
		                  % _databaseName % rc % errorMessage).str());
		return false;
	}
	sqlite3_free(errorMessage);
	sqlite3_close(db);
	return true;
}

const char *MapStatistics::randomMap() const
{
	static char mapName[256];
	const int MAX_TRIES = 15;
	std::random_device                 rd;
	std::mt19937                       re(rd());
	std::uniform_int_distribution<int> ui(0, _maps.size() - 1);

	mapName[0] = 0;

	int mapIdx = -1;
	// try to select a valid random map
	for (int tries = 0; tries < MAX_TRIES; tries++)
	{
		int testIdx = ui(re);
		if (isValidMap(&_maps[testIdx]))
		{
			mapIdx = testIdx;
		}
	}
	// fallback, iterate map list and select first valid map
	if (mapIdx < 0)
	{
		for (int i = 0; i < _maps.size(); i++)
		{
			if (isValidMap(&_maps[i]))
			{
				mapIdx = i;
				break;
			}
		}
	}

	if (mapIdx >= 0)
	{
		strcpy(mapName, _maps[mapIdx].name.c_str());
	}

	return mapName;
}

bool MapStatistics::isValidMap(const MapInformation* mapInfo) const
{
	return	mapInfo != _currentMap &&
			mapInfo->isOnServer &&
			strstr(Q_strlwr(g_blockedMaps.string), mapInfo->name.c_str()) == nullptr;
}

MapStatistics::~MapStatistics()
{
}

max_stars_repo_name: jackeri/etjump

max_issues_repo_name: jackeri/etjump

max_forks_repo_name: jackeri/etjump


text:
#define BOOST_AUTO_TEST_MAIN
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/output_test_stream.hpp>
#include <iostream>
#include "./../include/Logging.h"

using namespace boost::unit_test;
using namespace Logging;

BOOST_AUTO_TEST_SUITE( LoggingTestSuite )

struct cout_redirect {
    cout_redirect( std::streambuf * new_buffer )
        : old( std::cout.rdbuf( new_buffer ) )
    { }

    ~cout_redirect( ) {
        std::cout.rdbuf( old );
    }

private:
    std::streambuf * old;
};

BOOST_AUTO_TEST_CASE( LoggingOutputTest )
{
    boost::test_tools::output_test_stream output;
    {
        cout_redirect guard( output.rdbuf( ) );
		logInfoMessage("Test Info Logging");
    }

    BOOST_CHECK( output.is_equal( "[INFO] Test Info Logging\n" ) );
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: ElliotAlexander/EDSAC-FORTRAN-Compiler

max_issues_repo_name: ElliotAlexander/EDSAC-FORTRAN-Compiler

max_forks_repo_name: ElliotAlexander/EDSAC-FORTRAN-Compiler


text:
//
// Recorder - a GPS logger app for Windows Mobile
// Copyright (C) 2006-2019 Michael Fink
//
/// \file RecorderView.h Recorder view class implementation
//
#include "stdafx.h"
#include "resourceppc.h"
#include "RecorderView.h"
#include "Application.hpp"
#include <boost/bind.hpp>

CRecorderView::~CRecorderView() throw()
{
   // stop assigning key
   m_app.DisplayOffManager().StopAssign();
   // stop switching off display
   m_app.DisplayOffManager().SwitchOn();
}

BOOL CRecorderView::PreTranslateMessage(MSG* pMsg)
{
   return IsDialogMessage(pMsg);
}

LRESULT CRecorderView::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
   DoDataExchange(DDX_LOAD);
   m_btnAssignKey.EnableWindow(TRUE);
   m_btnSwitchOff.EnableWindow(m_app.DisplayOffManager().AssignedKey() == 0 ? FALSE : TRUE);

   m_editLogFilename.SetWindowText(_T("\\testlog.txt"));

   return 1;
}

LRESULT CRecorderView::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
   m_app.Receiver().SetInputCheckCallback();
   return 0;
}

#include <atldlgs.h>

LRESULT CRecorderView::OnBtnClickedBrowseFilename(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
   DoDataExchange(DDX_SAVE, IDC_EDIT_LOG_FILENAME);

   CString cszFilename;
   m_editLogFilename.GetWindowText(cszFilename);

   WTL::CFileDialog fileDlg(FALSE, // save file
      _T("txt"),
      cszFilename,
      OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
      _T("Text files (*.txt)\0*.txt\0All files (*.*)\0*.*\0\0"),
      m_hWnd);
   fileDlg.m_ofn.lStructSize = sizeof(OPENFILENAME);

   if (IDOK == fileDlg.DoModal())
   {
      m_editLogFilename.SetWindowText(fileDlg.m_ofn.lpstrFile);

      DoDataExchange(DDX_LOAD, IDC_EDIT_LOG_FILENAME);
   }

   return 0;
}

LRESULT CRecorderView::OnBtnClickedStartStop(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
   if (m_bLogging)
   {
      // already running: stop logging
      m_app.CloseNMEALog();
      m_bLogging = false;
      m_btnStartStop.SetWindowText(_T("Start"));

      m_app.Receiver().Stop();
   }
   else
   {
      // not running yet; get filename
      DoDataExchange(DDX_SAVE, IDC_EDIT_LOG_FILENAME);

      CString cszFilename;
      m_editLogFilename.GetWindowText(cszFilename);

      // open log file
      m_app.AppendNMEALog(cszFilename);

      m_bLogging = true;
      m_btnStartStop.SetWindowText(_T("Stop"));

      m_app.Receiver().SetInputCheckCallback(boost::bind(&CRecorderView::OnTestOutput, this, _1));

      m_app.Receiver().Start();
   }
   return 0;
}

LRESULT CRecorderView::OnBtnClickedAssignKey(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
   if (!m_bAssignActive)
   {
      m_bAssignActive = true;

      // starting assigning a key
      T_fnOnHardwareKey fnOnHardwareKey = boost::bind(&CRecorderView::OnAssignedHardwareKey, this, _1);
      m_app.DisplayOffManager().AssignKey(fnOnHardwareKey);

      m_btnAssignKey.SetWindowText(_T("Cancel assign"));
   }
   else
   {
      // stopping assigning a key
      m_bAssignActive = false;
      m_app.DisplayOffManager().StopAssign();

      m_btnAssignKey.SetWindowText(_T("Assign key"));
   }
   return 0;
}

void CRecorderView::OnAssignedHardwareKey(UINT uiKey)
{
   if (uiKey == 0)
      return; // no key was assigned

   m_btnSwitchOff.EnableWindow(TRUE);

   CString cszKeyName = m_app.DisplayOffManager().GetKeyName(uiKey);

   m_stAssignedKey.SetWindowText(_T("Key: ") + cszKeyName);

   m_btnAssignKey.SetWindowText(_T("Assign key"));

   m_app.DisplayOffManager().StopAssign();
}

void CRecorderView::OnSwitchOnHardwareKey(UINT uiKey)
{
   /*
   // If we would stop the hardware key manager at this point, it would
   // somehow pass on the key up to the OS, and the default action for the
   // key would be carried out. So simulate a click on the "cancel" button
   // here.
   PostMessage(WM_COMMAND,
      MAKEWPARAM(IDC_BUTTON_CANCEL, BN_CLICKED),
      (LPARAM)m_hWnd);
   */
}

LRESULT CRecorderView::OnBtnClickedSwitchOff(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
   if (m_app.DisplayOffManager().AssignedKey() == 0)
      return 0; // do nothing; no key assigned yet

   // switch off display
   T_fnOnHardwareKey fnOnHardwareKey = boost::bind(&CRecorderView::OnSwitchOnHardwareKey, this, _1);
   m_app.DisplayOffManager().SwitchOff(fnOnHardwareKey);

   return 0;
}

void CRecorderView::OnTestOutput(const CString& cszText)
{
   GetDlgItem(IDC_EDIT_TEST_OUTPUT).SetWindowText(cszText);
}

max_stars_repo_name: vividos/OldStuff

max_issues_repo_name: vividos/OldStuff

max_forks_repo_name: vividos/OldStuff


text:
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sstream>
#include <cstdlib>
#include <cassert>
#include <iostream>

#include "codec/bpv6.h"
#include "app_patterns/BpSinkPattern.h"
#include <boost/thread.hpp>
#include <boost/bind/bind.hpp>
#include <boost/make_unique.hpp>
#include "Uri.h"
#include "TcpclInduct.h"
#include "TcpclV4Induct.h"
#include "codec/BundleViewV7.h"

BpSinkPattern::BpSinkPattern() : m_timerAcs(m_ioService), m_timerTransferRateStats(m_ioService) {}

BpSinkPattern::~BpSinkPattern() {
    Stop();
}

void BpSinkPattern::Stop() {

    if (m_ioServiceThreadPtr) {
        m_timerAcs.cancel();
        m_timerTransferRateStats.cancel();
        m_ioServiceThreadPtr->join();
        m_ioServiceThreadPtr.reset(); //delete it
    }

    m_inductManager.Clear();

    std::cout << "totalPayloadBytesRx: " << m_totalPayloadBytesRx << "\n";
    std::cout << "totalBundleBytesRx: " << m_totalBundleBytesRx << "\n";
    std::cout << "m_totalBundlesVersion6Rx: " << m_totalBundlesVersion6Rx << "\n";
    std::cout << "m_totalBundlesVersion7Rx: " << m_totalBundlesVersion7Rx << "\n";
    for (std::size_t i = 0; i < m_hopCounts.size(); ++i) {
        if (m_hopCounts[i] != 0) {
            std::cout << "received " << m_hopCounts[i] << " bundles with a hop count of " << i << ".\n";
        }
    }
}

bool BpSinkPattern::Init(InductsConfig_ptr & inductsConfigPtr, OutductsConfig_ptr & outductsConfigPtr,
    bool isAcsAware, const cbhe_eid_t & myEid, uint32_t processingLagMs, const uint64_t maxBundleSizeBytes, const uint64_t myBpEchoServiceId)
{
    m_tcpclOpportunisticRemoteNodeId = 0;
    m_myEid = myEid;
    m_myEidUriString = Uri::GetIpnUriString(m_myEid.nodeId, m_myEid.serviceId);
    m_myEidEcho.Set(myEid.nodeId, myBpEchoServiceId);

    m_totalPayloadBytesRx = 0;
    m_totalBundleBytesRx = 0;
    m_totalBundlesVersion6Rx = 0;
    m_totalBundlesVersion7Rx = 0;
    m_hopCounts.assign(256, 0);
    m_lastPreviousNode.Set(0, 0);

    m_lastPayloadBytesRx = 0;
    m_lastBundleBytesRx = 0;
    m_lastBundlesRx = 0;

    m_nextCtebCustodyId = 0;

    m_tcpclInductPtr = NULL;

    M_EXTRA_PROCESSING_TIME_MS = processingLagMs;
    if (inductsConfigPtr) {
        m_inductManager.LoadInductsFromConfig(boost::bind(&BpSinkPattern::WholeBundleReadyCallback, this, boost::placeholders::_1),
            *inductsConfigPtr, myEid.nodeId, UINT16_MAX, maxBundleSizeBytes,
            boost::bind(&BpSinkPattern::OnNewOpportunisticLinkCallback, this, boost::placeholders::_1, boost::placeholders::_2),
            boost::bind(&BpSinkPattern::OnDeletedOpportunisticLinkCallback, this, boost::placeholders::_1));
    }

    if (outductsConfigPtr) {
        m_hasSendCapability = true;
        m_hasSendCapabilityOverTcpclBidirectionalInduct = false;
        m_outductManager.LoadOutductsFromConfig(*outductsConfigPtr, myEid.nodeId, UINT16_MAX, maxBundleSizeBytes, boost::bind(&BpSinkPattern::WholeBundleReadyCallback, this, boost::placeholders::_1));
        while (!m_outductManager.AllReadyToForward()) {
            std::cout << "waiting for outduct to be ready...\n";
            boost::this_thread::sleep(boost::posix_time::milliseconds(500));
        }
    }
    else if ((inductsConfigPtr) && ((inductsConfigPtr->m_inductElementConfigVector[0].convergenceLayer == "tcpcl_v3") || (inductsConfigPtr->m_inductElementConfigVector[0].convergenceLayer == "tcpcl_v4"))) {
        m_hasSendCapability = true;
        m_hasSendCapabilityOverTcpclBidirectionalInduct = true;
        std::cout << "this bpsink pattern detected tcpcl convergence layer which is bidirectional.. supporting custody transfer\n";
    }
    else {
        m_hasSendCapability = false;
        m_hasSendCapabilityOverTcpclBidirectionalInduct = false;
    }

    if (m_hasSendCapability) {
        m_custodyTransferManagerPtr = boost::make_unique<CustodyTransferManager>(isAcsAware, myEid.nodeId, myEid.serviceId);
        if (isAcsAware) {
            m_timerAcs.expires_from_now(boost::posix_time::seconds(1));
            m_timerAcs.async_wait(boost::bind(&BpSinkPattern::AcsNeedToSend_TimerExpired, this, boost::asio::placeholders::error));
        }
    }
    m_lastPtime = boost::posix_time::microsec_clock::universal_time();
    m_timerTransferRateStats.expires_from_now(boost::posix_time::seconds(5));
    m_timerTransferRateStats.async_wait(boost::bind(&BpSinkPattern::TransferRate_TimerExpired, this, boost::asio::placeholders::error));
    m_ioServiceThreadPtr = boost::make_unique<boost::thread>(boost::bind(&boost::asio::io_service::run, &m_ioService));

    return true;
}

bool BpSinkPattern::Process(padded_vector_uint8_t & rxBuf, const std::size_t messageSize) {

    if (M_EXTRA_PROCESSING_TIME_MS) {
        boost::this_thread::sleep(boost::posix_time::milliseconds(M_EXTRA_PROCESSING_TIME_MS));
    }

    const uint8_t firstByte = rxBuf[0];
    const bool isBpVersion6 = (firstByte == 6);
    const bool isBpVersion7 = (firstByte == ((4U << 5) | 31U));  //CBOR major type 4, additional information 31 (Indefinite-Length Array)
    if (isBpVersion6) {
        BundleViewV6 bv;
        if (!bv.LoadBundle(rxBuf.data(), rxBuf.size())) { //invalid bundle
            std::cerr << "malformed bundle\n";
            return false;
        }
        Bpv6CbhePrimaryBlock & primary = bv.m_primaryBlockView.header;
        const cbhe_eid_t finalDestEid(primary.m_destinationEid);
        const cbhe_eid_t srcEid(primary.m_sourceNodeId);

        static constexpr BPV6_BUNDLEFLAG requiredPrimaryFlagsForEcho = BPV6_BUNDLEFLAG::SINGLETON;
        const bool isEcho = (((primary.m_bundleProcessingControlFlags & requiredPrimaryFlagsForEcho) == requiredPrimaryFlagsForEcho) && (finalDestEid == m_myEidEcho));
        if (isEcho && (!m_hasSendCapability)) {
            std::cout << "a ping request was received but this bpsinkpattern does not have send capability.. ignoring bundle\n";
            return false;
        }

        if ((!isEcho) && (finalDestEid != m_myEid)) {
            std::cerr << "bundle received has a destination that doesn't match my eid\n";
            return false;
        }

        //accept custody
        if (m_hasSendCapability) { //has bidirectionality
            static const BPV6_BUNDLEFLAG requiredPrimaryFlagsForCustody = BPV6_BUNDLEFLAG::SINGLETON | BPV6_BUNDLEFLAG::CUSTODY_REQUESTED;

            if (isEcho) {
                primary.m_destinationEid = primary.m_sourceNodeId;
                primary.m_sourceNodeId = m_myEidEcho;
                bv.m_primaryBlockView.SetManuallyModified();
                bv.Render(messageSize + 10);
                Forward_ThreadSafe(srcEid, bv.m_frontBuffer); //srcEid is the new destination
                return true;
            }
            else if ((primary.m_bundleProcessingControlFlags & requiredPrimaryFlagsForCustody) == requiredPrimaryFlagsForCustody) {
                const uint64_t newCtebCustodyId = m_nextCtebCustodyId++;
                m_mutexCtm.lock();
                const bool successfullyProcessedCustody = m_custodyTransferManagerPtr->ProcessCustodyOfBundle(bv, true,
                    newCtebCustodyId, BPV6_ACS_STATUS_REASON_INDICES::SUCCESS__NO_ADDITIONAL_INFORMATION,
                    m_custodySignalRfc5050RenderedBundleView);
                m_mutexCtm.unlock();
                if (!successfullyProcessedCustody) {
                    std::cerr << "error unable to process custody\n";
                    return false;
                }
                else {
                    if (m_custodySignalRfc5050RenderedBundleView.m_renderedBundle.size()) {
                        //send a classic rfc5050 custody signal due to acs disabled or bundle received has an invalid cteb
                        const cbhe_eid_t & custodySignalDestEid = m_custodySignalRfc5050RenderedBundleView.m_primaryBlockView.header.m_destinationEid;
                        Forward_ThreadSafe(custodySignalDestEid, m_custodySignalRfc5050RenderedBundleView.m_frontBuffer);
                    }
                    else if (m_custodyTransferManagerPtr->GetLargestNumberOfFills() > 100) {
                        boost::asio::post(m_ioService, boost::bind(&BpSinkPattern::SendAcsFromTimerThread, this));
                    }
                }
            }
        }

        std::vector<BundleViewV6::Bpv6CanonicalBlockView*> blocks;
        bv.GetCanonicalBlocksByType(BPV6_BLOCK_TYPE_CODE::PAYLOAD, blocks);
        if (blocks.size() != 1) {
            std::cerr << "error payload block not found\n";
            return false;
        }
        Bpv6CanonicalBlock & payloadBlock = *(blocks[0]->headerPtr);
        m_totalPayloadBytesRx += payloadBlock.m_blockTypeSpecificDataLength;
        m_totalBundleBytesRx += messageSize;
        ++m_totalBundlesVersion6Rx;

        if (!ProcessPayload(payloadBlock.m_blockTypeSpecificDataPtr, payloadBlock.m_blockTypeSpecificDataLength)) {
            std::cerr << "error ProcessPayload\n";
            return false;
        }
    }
    else if (isBpVersion7) {
        BundleViewV7 bv;
        if (!bv.LoadBundle(rxBuf.data(), rxBuf.size())) { //invalid bundle
            std::cerr << "malformed bpv7 bundle\n";
            return false;
        }
        Bpv7CbhePrimaryBlock & primary = bv.m_primaryBlockView.header;
        const cbhe_eid_t finalDestEid = primary.m_destinationEid;
        const cbhe_eid_t srcEid = primary.m_sourceNodeId;

        static constexpr BPV7_BUNDLEFLAG requiredPrimaryFlagsForEcho = BPV7_BUNDLEFLAG::NO_FLAGS_SET;
        const bool isEcho = (((primary.m_bundleProcessingControlFlags & requiredPrimaryFlagsForEcho) == requiredPrimaryFlagsForEcho) && (finalDestEid == m_myEidEcho));
        if (isEcho && (!m_hasSendCapability)) {
            std::cout << "a ping request was received but this bpsinkpattern does not have send capability.. ignoring bundle\n";
            return false;
        }

        if ((!isEcho) && (finalDestEid != m_myEid)) {
            std::cerr << "bundle received has a destination that doesn't match my eid\n";
            return false;
        }

        //get previous node
        std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocks;
        bv.GetCanonicalBlocksByType(BPV7_BLOCK_TYPE_CODE::PREVIOUS_NODE, blocks);
        if (blocks.size() > 1) {
            std::cout << "error in BpSinkPattern::Process: version 7 bundle received has multiple previous node blocks\n";
            return false;
        }
        else if (blocks.size() == 1) {
            if (Bpv7PreviousNodeCanonicalBlock* previousNodeBlockPtr = dynamic_cast<Bpv7PreviousNodeCanonicalBlock*>(blocks[0]->headerPtr.get())) {
                if (m_lastPreviousNode != previousNodeBlockPtr->m_previousNode) {
                    m_lastPreviousNode = previousNodeBlockPtr->m_previousNode;
                    std::cout << "bp version 7 bundles coming in from previous node " << m_lastPreviousNode << "\n";
                }
                //update the previous node in case this is an echo
                previousNodeBlockPtr->m_previousNode = m_myEidEcho;
                blocks[0]->SetManuallyModified();
            }
            else {
                std::cout << "error in BpSinkPattern::Process: dynamic_cast to Bpv7PreviousNodeCanonicalBlock failed\n";
                return false;
            }
        }
        else if (isEcho) { //prepend new previous node block
            std::unique_ptr<Bpv7CanonicalBlock> blockPtr = boost::make_unique<Bpv7PreviousNodeCanonicalBlock>();
            Bpv7PreviousNodeCanonicalBlock & block = *(reinterpret_cast<Bpv7PreviousNodeCanonicalBlock*>(blockPtr.get()));

            block.m_blockProcessingControlFlags = BPV7_BLOCKFLAG::REMOVE_BLOCK_IF_IT_CANT_BE_PROCESSED;
            block.m_blockNumber = bv.GetNextFreeCanonicalBlockNumber();
            block.m_crcType = BPV7_CRC_TYPE::CRC32C;
            block.m_previousNode = m_myEidEcho;
            bv.PrependMoveCanonicalBlock(blockPtr);
        }

        //get hop count if exists
        bv.GetCanonicalBlocksByType(BPV7_BLOCK_TYPE_CODE::HOP_COUNT, blocks);
        if (blocks.size() > 1) {
            std::cout << "error in BpSinkPattern::Process: version 7 bundle received has multiple hop count blocks\n";
            return false;
        }
        else if (blocks.size() == 1) {
            if (Bpv7HopCountCanonicalBlock* hopCountBlockPtr = dynamic_cast<Bpv7HopCountCanonicalBlock*>(blocks[0]->headerPtr.get())) {
                //the hop count value SHOULD initially be zero and SHOULD be increased by 1 on each hop.
                const uint64_t newHopCount = hopCountBlockPtr->m_hopCount + 1;
                //When a bundle's hop count exceeds its
                //hop limit, the bundle SHOULD be deleted for the reason "hop limit
                //exceeded", following the bundle deletion procedure defined in
                //Section 5.10.
                //Hop limit MUST be in the range 1 through 255.
                if ((newHopCount > hopCountBlockPtr->m_hopLimit) || (newHopCount > 255)) {
                    std::cout << "notice: BpSinkPattern::Process dropping version 7 bundle with hop count " << newHopCount << "\n";
                    return false;
                }
                ++m_hopCounts[newHopCount];
                //update the hop count in case this is an echo
                hopCountBlockPtr->m_hopCount = newHopCount;
                blocks[0]->SetManuallyModified();
            }
            else {
                std::cout << "error in BpSinkPattern::Process: dynamic_cast to Bpv7HopCountCanonicalBlock failed\n";
                return false;
            }
        }

        if (m_hasSendCapability) { //has bidirectionality
            if (isEcho) {
                primary.m_destinationEid = primary.m_sourceNodeId;
                primary.m_sourceNodeId = m_myEidEcho;
                bv.m_primaryBlockView.SetManuallyModified();
                bv.Render(messageSize + 10);
                Forward_ThreadSafe(srcEid, bv.m_frontBuffer); //srcEid is the new destination
                return true;
            }
        }

        //get payload block
        bv.GetCanonicalBlocksByType(BPV7_BLOCK_TYPE_CODE::PAYLOAD, blocks);

        if (blocks.size() != 1) {
            std::cerr << "error payload block not found\n";
            return false;
        }

        const uint64_t payloadDataLength = blocks[0]->headerPtr->m_dataLength;
        const uint8_t * payloadDataPtr = blocks[0]->headerPtr->m_dataPtr;
        m_totalPayloadBytesRx += payloadDataLength;
        m_totalBundleBytesRx += messageSize;
        ++m_totalBundlesVersion7Rx;

        if (!ProcessPayload(payloadDataPtr, payloadDataLength)) {
            std::cerr << "error ProcessPayload\n";
            return false;
        }
    }

    return true;
}

void BpSinkPattern::WholeBundleReadyCallback(padded_vector_uint8_t & wholeBundleVec) {
    //if more than 1 BpSinkAsync context, must protect shared resources with mutex.  Each BpSinkAsync context has
    //its own processing thread that calls this callback
    Process(wholeBundleVec, wholeBundleVec.size());
}

void BpSinkPattern::AcsNeedToSend_TimerExpired(const boost::system::error_code& e) {
    if (e != boost::asio::error::operation_aborted) {
        // Timer was not cancelled, take necessary action.
        SendAcsFromTimerThread();

        m_timerAcs.expires_from_now(boost::posix_time::seconds(1));
        m_timerAcs.async_wait(boost::bind(&BpSinkPattern::AcsNeedToSend_TimerExpired, this, boost::asio::placeholders::error));
    }
    else {
        std::cout << "timer stopped\n";
    }
}

void BpSinkPattern::TransferRate_TimerExpired(const boost::system::error_code& e) {
    if (e != boost::asio::error::operation_aborted) {
        // Timer was not cancelled, take necessary action.
        boost::posix_time::ptime finishedTime = boost::posix_time::microsec_clock::universal_time();
        const uint64_t totalPayloadBytesRx = m_totalPayloadBytesRx;
        const uint64_t totalBundleBytesRx = m_totalBundleBytesRx;
        const uint64_t totalBundlesRx = m_totalBundlesVersion6Rx + m_totalBundlesVersion7Rx;
        boost::posix_time::time_duration diff = finishedTime - m_lastPtime;
        const uint64_t diffTotalPayloadBytesRx = totalPayloadBytesRx - m_lastPayloadBytesRx;
        const uint64_t diffBundleBytesRx = totalBundleBytesRx - m_lastBundleBytesRx;
        const uint64_t diffBundlesRx = totalBundlesRx - m_lastBundlesRx;
        if (diffTotalPayloadBytesRx || diffBundleBytesRx || diffBundlesRx) {
            double payloadRateMbps = (diffTotalPayloadBytesRx * 8.0) / (diff.total_microseconds());
            double bundleRateMbps = (diffBundleBytesRx * 8.0) / (diff.total_microseconds());
            double bundlesPerSecond = (diffBundlesRx * 1e6) / (diff.total_microseconds());

            printf("Payload Only Rate: %0.4f Mbits/sec, Total Rate: %0.4f Mbits/sec, %0.4f Bundles/sec: \n", payloadRateMbps, bundleRateMbps, bundlesPerSecond);
        }

        m_lastPayloadBytesRx = totalPayloadBytesRx;
        m_lastBundleBytesRx = totalBundleBytesRx;
        m_lastBundlesRx = totalBundlesRx;
        m_lastPtime = finishedTime;
        m_timerTransferRateStats.expires_from_now(boost::posix_time::seconds(5));
        m_timerTransferRateStats.async_wait(boost::bind(&BpSinkPattern::TransferRate_TimerExpired, this, boost::asio::placeholders::error));
    }
    else {
        std::cout << "transfer rate timer stopped\n";
    }
}

void BpSinkPattern::SendAcsFromTimerThread() {
    //std::cout << "send acs, fills = " << ctm.GetLargestNumberOfFills() << "\n";
    std::list<BundleViewV6> newAcsRenderedBundleViewList;
    m_mutexCtm.lock();
    const bool generatedSuccessfully = m_custodyTransferManagerPtr->GenerateAllAcsBundlesAndClear(newAcsRenderedBundleViewList);
    m_mutexCtm.unlock();
    if (generatedSuccessfully) {
        for (std::list<BundleViewV6>::iterator it = newAcsRenderedBundleViewList.begin(); it != newAcsRenderedBundleViewList.end(); ++it) {
            //send an acs custody signal due to acs send timer
            const cbhe_eid_t & custodySignalDestEid = it->m_primaryBlockView.header.m_destinationEid;
            Forward_ThreadSafe(custodySignalDestEid, it->m_frontBuffer);
        }
    }
}

void BpSinkPattern::OnNewOpportunisticLinkCallback(const uint64_t remoteNodeId, Induct * thisInductPtr) {
    if (m_tcpclInductPtr = dynamic_cast<TcpclInduct*>(thisInductPtr)) {
        std::cout << "New opportunistic link detected on Tcpcl induct for ipn:" << remoteNodeId << ".*\n";
        m_tcpclOpportunisticRemoteNodeId = remoteNodeId;
    }
    else if (m_tcpclInductPtr = dynamic_cast<TcpclV4Induct*>(thisInductPtr)) {
        std::cout << "New opportunistic link detected on TcpclV4 induct for ipn:" << remoteNodeId << ".*\n";
        m_tcpclOpportunisticRemoteNodeId = remoteNodeId;
    }
    else {
        std::cerr << "error in BpSinkPattern::OnNewOpportunisticLinkCallback: Induct ptr cannot cast to TcpclInduct or TcpclV4Induct\n";
    }
}
void BpSinkPattern::OnDeletedOpportunisticLinkCallback(const uint64_t remoteNodeId) {
    m_tcpclOpportunisticRemoteNodeId = 0;
    std::cout << "Deleted opportunistic link on Tcpcl induct for ipn:" << remoteNodeId << ".*\n";
}

bool BpSinkPattern::Forward_ThreadSafe(const cbhe_eid_t & destEid, std::vector<uint8_t> & bundleToMoveAndSend) {
    bool successForward = false;
    if (m_hasSendCapabilityOverTcpclBidirectionalInduct) {
        //if (destEid.nodeId != m_tcpclOpportunisticRemoteNodeId) {
        //    std::cerr << "error: node id " << destEid.nodeId << " does not match tcpcl opportunistic link node id " << m_tcpclOpportunisticRemoteNodeId << std::endl;
        //}
        //else if (m_tcpclInductPtr) {
        //note BpSink has no routing capability so it must send to the only connection available to it
        if (m_tcpclInductPtr) {
            m_mutexForward.lock();
            //successForward = m_tcpclInductPtr->ForwardOnOpportunisticLink(destEid.nodeId, bundleToMoveAndSend, 3);
            successForward = m_tcpclInductPtr->ForwardOnOpportunisticLink(m_tcpclOpportunisticRemoteNodeId, bundleToMoveAndSend, 3);
            m_mutexForward.unlock();
        }
        else {
            std::cerr << "error: tcpcl induct does not exist to forward\n";
        }
    }
    else {
        m_mutexForward.lock();
        successForward = m_outductManager.Forward_Blocking(destEid, bundleToMoveAndSend, 3);
        m_mutexForward.unlock();
    }
    if (!successForward) {
        std::cerr << "error forwarding for 3 seconds\n";
    }
    else {
        //std::cout << "success forwarding\n";
    }
    return successForward;
}


text:
/***********************************************************************************************************************
 *  OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 *  following conditions are met:
 *
 *  (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
 *  disclaimer.
 *
 *  (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 *  following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 *  (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote
 *  products derived from this software without specific prior written permission from the respective party.
 *
 *  (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative
 *  works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without
 *  specific prior written permission from Alliance for Sustainable Energy, LLC.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR
 *  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 *  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *  AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **********************************************************************************************************************/

#ifndef UTILITIES_CORE_FILEREFERENCE_HPP
#define UTILITIES_CORE_FILEREFERENCE_HPP

#include "../UtilitiesAPI.hpp"

#include "Enum.hpp"
#include "Path.hpp"
#include "UUID.hpp"

#include "../time/DateTime.hpp"

#include <boost/optional.hpp>

#include <vector>

namespace openstudio {

/** \class FileReferenceType
 *  \brief Type of files we expect to handle with FileReference.
 *  \details See the OPENSTUDIO_ENUM documentation in utilities/core/Enum.hpp. The actual macro
 *  call is:
 *  \code
OPENSTUDIO_ENUM( FileReferenceType,
    ((Unknown)(unknown))
    ((CSV)(csv))
    ((EPW)(epw))
    ((IDF)(idf))
    ((OSC)(osc))
    ((OSM)(osm))
    ((RB)(rb))
    ((SQL)(sql))
    ((XML)(xml)) );
 *  \endcode */
OPENSTUDIO_ENUM( FileReferenceType,
    ((Unknown)(unknown))
    ((CSV)(csv))
    ((EPW)(epw))
    ((IDF)(idf))
    ((OSC)(osc))
    ((OSM)(osm))
    ((RB)(rb))
    ((SQL)(sql))
    ((XML)(xml))
    ((OSSR)(ossr)) );

class UTILITIES_API FileReference {
 public:
  /** @name Constructors and Destructors */
  //@{

  explicit FileReference(const openstudio::path& p);

  /** De-serialization constructor. Not for general use. */
  FileReference(const openstudio::UUID& uuid,
                const openstudio::UUID& versionUUID,
                const std::string& name,
                const std::string& displayName,
                const std::string& description,
                const openstudio::path& p,
                const FileReferenceType& fileType,
                const DateTime& timestampLast,
                const std::string& checksumCreate,
                const std::string& checksumLast);

  virtual ~FileReference() {}

  FileReference clone() const;

  //@}
  /** @name Getters */
  //@{

  openstudio::UUID uuid() const;

  openstudio::UUID versionUUID() const;

  std::string name() const;

  std::string displayName() const;

  std::string description() const;

  openstudio::path path() const;

  FileReferenceType fileType() const;

  /** Last modified time of this file, or time object was created if path
   *  does not actually exist on the file system. */
  DateTime timestampLast() const;

  /** Checksum at time this object was created, if file exists. Otherwise
   *  "00000000". */
  std::string checksumCreate() const;

  std::string checksumLast() const;

  //@}
  /** @name Setters */
  //@{

  void setName(const std::string& newName);

  void setDisplayName(const std::string& newDisplayName);

  void setDescription(const std::string& newDescription);

  void setPath(const openstudio::path& newPath);

  bool makePathAbsolute(const openstudio::path& searchDirectory);

  /** Save the path as relative to basePath, or just keep the file name and extension if
   *  basePath.empty(). */
  bool makePathRelative(const openstudio::path& basePath=openstudio::path());

  /** Returns true and updates timestampLast and checksumLast if file is located. */
  bool update(const openstudio::path& searchDirectory);

  //@}
 private:
  openstudio::UUID m_uuid;
  openstudio::UUID m_versionUUID;
  std::string m_name;
  std::string m_displayName;
  std::string m_description;
  openstudio::path m_path;
  FileReferenceType m_fileType;
  DateTime m_timestampLast;
  std::string m_checksumCreate;
  std::string m_checksumLast;

  REGISTER_LOGGER("openstudio.utilities.FileReference");

};

/** \relates FileReference*/
typedef boost::optional<FileReference> OptionalFileReference;

/** \relates FileReference*/
typedef std::vector<FileReference> FileReferenceVector;

namespace detail {

  /** Places attribute's data in a QVariant for JSON serialization. */
  UTILITIES_API QVariant toVariant(const FileReference& fileReference);

  /** Deserializes json variant to FileReference. */
  UTILITIES_API FileReference toFileReference(const QVariant& variant, const VersionString& version);

}

} // openstudio

#endif // UTILITIES_CORE_FILEREFERENCE_HPP

ext: hpp

max_stars_repo_name: hongyuanjia/OpenStudio

max_issues_repo_name: hongyuanjia/OpenStudio

max_forks_repo_name: hongyuanjia/OpenStudio


text:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "lxml"
#include <boost/test/unit_test.hpp>


text:
/* The MIT License (MIT)

Copyright (c) 2015 Gabriel Corona

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <cstdlib>

#include <exception>

#include <boost/asio/io_service.hpp>

#include "dnsfwd.hpp"

int main(int argc, char** argv)
{
  try {
    dnsfwd::config config;
    setup_config(config, argc, argv);

    boost::asio::io_service io_service;
    dnsfwd::service service(io_service, std::move(config));
    io_service.run();
    return 0;
  }
  catch (std::exception& e) {
    LOG(CRIT) << e.what() << "\n";
    return 1;
  }
}

max_stars_repo_name: randomstuff/dnsfwd

max_issues_repo_name: randomstuff/dnsfwd

max_forks_repo_name: randomstuff/dnsfwd


text:
/**
 *  Copyright 2014-2016 CyberVision, 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 <boost/test/unit_test.hpp>

#include "kaa/KaaClientProperties.hpp"

#if __GNUC__
    #define FILE_SEPARATOR '/'
#else
    #define FILE_SEPARATOR '\\'
#endif

namespace kaa {

BOOST_AUTO_TEST_SUITE(KaaClientPropertiesTestSuite)

BOOST_AUTO_TEST_CASE(DefaultPropertiesTest)
{
    KaaClientProperties properties;

    BOOST_CHECK_EQUAL(properties.getWorkingDirectoryPath(), KaaClientProperties::DEFAULT_WORKING_DIR);
    BOOST_CHECK_EQUAL(properties.getStateFileName(), KaaClientProperties::DEFAULT_WORKING_DIR + KaaClientProperties::DEFAULT_STATE_FILE);
    BOOST_CHECK_EQUAL(properties.getPublicKeyFileName(), KaaClientProperties::DEFAULT_WORKING_DIR + KaaClientProperties::DEFAULT_PUB_KEY_FILE);
    BOOST_CHECK_EQUAL(properties.getPrivateKeyFileName(), KaaClientProperties::DEFAULT_WORKING_DIR + KaaClientProperties::DEFAULT_PRIV_KEY_FILE);
    BOOST_CHECK_EQUAL(properties.getLogsDatabaseFileName(), KaaClientProperties::DEFAULT_WORKING_DIR + KaaClientProperties::DEFAULT_LOGS_DB);
    BOOST_CHECK_EQUAL(properties.getConfigurationFileName(), KaaClientProperties::DEFAULT_WORKING_DIR + KaaClientProperties::DEFAULT_CONF_FILE);
}

BOOST_AUTO_TEST_CASE(SetWorkingDirTest)
{
    KaaClientProperties properties;

    std::string newWorkingPath = "/home/kaa/client-cpp/test";

    properties.setWorkingDirectoryPath(newWorkingPath);
    BOOST_CHECK(properties.getWorkingDirectoryPath() != newWorkingPath);

    newWorkingPath.push_back(FILE_SEPARATOR);
    BOOST_CHECK_EQUAL(properties.getWorkingDirectoryPath(), newWorkingPath);

    BOOST_CHECK_EQUAL(properties.getStateFileName(), newWorkingPath + KaaClientProperties::DEFAULT_STATE_FILE);
    BOOST_CHECK_EQUAL(properties.getPublicKeyFileName(), newWorkingPath + KaaClientProperties::DEFAULT_PUB_KEY_FILE);
    BOOST_CHECK_EQUAL(properties.getPrivateKeyFileName(), newWorkingPath + KaaClientProperties::DEFAULT_PRIV_KEY_FILE);
    BOOST_CHECK_EQUAL(properties.getLogsDatabaseFileName(), newWorkingPath + KaaClientProperties::DEFAULT_LOGS_DB);
    BOOST_CHECK_EQUAL(properties.getConfigurationFileName(), newWorkingPath + KaaClientProperties::DEFAULT_CONF_FILE);
}

BOOST_AUTO_TEST_CASE(SetStateFileNameTest)
{
    KaaClientProperties properties;

    const std::string newStateFileName = "test_state_file.txt";
    properties.setStateFileName(newStateFileName);

    BOOST_CHECK_EQUAL(properties.getStateFileName(), properties.getWorkingDirectoryPath() + newStateFileName);
}

BOOST_AUTO_TEST_CASE(SetPublicKeyFileNameTest)
{
    KaaClientProperties properties;

    const std::string newPublicKeyFileName = "test_public_key_file.txt";
    properties.setPublicKeyFileName(newPublicKeyFileName);

    BOOST_CHECK_EQUAL(properties.getPublicKeyFileName(), properties.getWorkingDirectoryPath() + newPublicKeyFileName);
}

BOOST_AUTO_TEST_CASE(SetPrivateKeyFileNameTest)
{
    KaaClientProperties properties;

    const std::string newPrivateKeyFileName = "test_private_key_file.txt";
    properties.setPrivateKeyFileName(newPrivateKeyFileName);

    BOOST_CHECK_EQUAL(properties.getPrivateKeyFileName(), properties.getWorkingDirectoryPath() + newPrivateKeyFileName);
}

BOOST_AUTO_TEST_CASE(SetLogsDatabaseFileNameTest)
{
    KaaClientProperties properties;

    const std::string newLogsDatabaseFileName = "test_logs_database_file.txt";
    properties.setLogsDatabaseFileName(newLogsDatabaseFileName);

    BOOST_CHECK_EQUAL(properties.getLogsDatabaseFileName(), properties.getWorkingDirectoryPath() + newLogsDatabaseFileName);
}

BOOST_AUTO_TEST_CASE(SetConfigurationFileNameTest)
{
    KaaClientProperties properties;

    const std::string newConfigurationFileName = "test_configuration_file.txt";
    properties.setConfigurationFileName(newConfigurationFileName);

    BOOST_CHECK_EQUAL(properties.getConfigurationFileName(), properties.getWorkingDirectoryPath() + newConfigurationFileName);
}

BOOST_AUTO_TEST_CASE(SetArbitraryPropertyTest)
{
    KaaClientProperties properties;

    const std::string propertyName = "RandomProperty";
    const std::string propertyValue = "RandomPropertyValue";

    properties.setProperty(propertyName, propertyValue);

    BOOST_CHECK_EQUAL(properties.getProperty(propertyName), propertyValue);
}

BOOST_AUTO_TEST_CASE(GetUnknownPropertyTest)
{
    KaaClientProperties properties;

    const std::string unknownPropertyName = "UnknownProperty";
    const std::string defaultPropertyValue = "DefaultValue";

    BOOST_CHECK_EQUAL(properties.getProperty(unknownPropertyName, defaultPropertyValue), defaultPropertyValue);
}

BOOST_AUTO_TEST_SUITE_END()

} /* namespace kaa */


text:
// Copyright 2014-2015 SDL plc
// 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.
/** \file

    ICU (unicode) helpers.
*/

#ifndef ICU_JG201276_HPP
#define ICU_JG201276_HPP
#pragma once

#include <sdl/Util/Delete.hpp>
#include <sdl/Util/IcuHeaders.hpp>
#include <sdl/Util/LogHelper.hpp>
#include <sdl/Util/String32.hpp>
#include <sdl/Util/StringBuilder.hpp>
#include <sdl/Util/Utf8.hpp>
#include <sdl/Exception.hpp>
#include <sdl/Types.hpp>
#include <boost/optional.hpp>
#include <locale>
#include <vector>
#include <locale.h>

namespace sdl {

/// note: actual icu namespace is icu_NN e.g. icu_50
using icu::StringPiece;
using icu::UnicodeString;
using icu::Locale;
// UChar32 is in global ns, in machine.h. is int32_t
typedef shared_ptr<Locale const> LocalePtr;

inline icu::StringPiece icuStringPiece(Slice s) {
  return icu::StringPiece(s.first, s.second - s.first);
}

inline icu::StringPiece icuStringPiece(std::string const& s) {
  return s;
}

inline Slice toSlice(icu::StringPiece const& s) {
  char const* data = s.data();
  return Slice(data, data + s.size());
}

namespace Util {

typedef icu::Normalizer2 IcuNormalizer2;
typedef IcuNormalizer2 const* IcuNormalizer2Ptr;
/**
   compose: turn base char + accents into a single unicode point if

   decompose: expand e.g. accents so they follow base letter (if >1, in
   canonical order). inverse of compose

   K means "compatability" - characters that could be represented as two unicode
   glyphs, but due to historical use, are a single glyph (e.g. some ligatures)
   (destructive many:1)

   these may be used only after static init
 */
#if 0
extern IcuNormalizer2Ptr gNfc, gNfkc, gNfd, gNfkd;
inline IcuNormalizer2Ptr getNfc() { return gNfc; }
inline IcuNormalizer2Ptr getNfkc() { return gNfkc; }
inline IcuNormalizer2Ptr getNfd() { return gNfd; }
inline IcuNormalizer2Ptr getNfkd() { return gNfkd; }
#else
IcuNormalizer2Ptr getNfc();
IcuNormalizer2Ptr getNfkc();
IcuNormalizer2Ptr getNfd();
IcuNormalizer2Ptr getNfkd();
#endif

/// not ok for s == out. does NOT assign to out if s is already normalized.
bool maybeIcuNormalize(icu::UnicodeString const& s, icu::UnicodeString& out, IcuNormalizer2Ptr normalize);

/// checks exactly whether s was normalized. normalizes into out if it wasn't. this is slower than
/// maybeIcuNormalize but has the same result except the return value is strictly reflecting the normalization
/// status of s.
bool neededIcuNormalize(icu::UnicodeString const& s, icu::UnicodeString& out, IcuNormalizer2Ptr normalize);

/// ok for utf8 == out since we make a copy. does NOT assign to out if utf8 is already normalized.
bool maybeIcuNormalize(icu::StringPiece utf8, std::string& out, IcuNormalizer2Ptr normalize);

/// \return whether out was assigned to (w/ normalized utf8). if utf8 was already normalized (false) then out
/// is not modified
inline bool maybeIcuNormalize(Slice utf8, std::string& out, IcuNormalizer2Ptr normalize) {
  return maybeIcuNormalize(icuStringPiece(utf8), out, normalize);
}

/// \return whether out was assigned to (w/ normalized utf8). if utf8 was already normalized (false) then out
/// is not modified
inline bool maybeIcuNormalize(std::string const& in, std::string& out, IcuNormalizer2Ptr normalize) {
  return maybeIcuNormalize(icu::StringPiece(in), out, normalize);
}

/// \return normalize and return string
inline std::string& icuNormalize(std::string& out, IcuNormalizer2Ptr normalize) {
  maybeIcuNormalize(out, out, normalize);
  return out;
}

/** \param icuLanguageName empty string = default, else two-letter or three-letter ISO-639 code. This
   parameter can instead be an ICU style C locale (e.g. "en_US"), but the other parameters must not be used.

    \param icuCountryCode 2-letter country code (e.g. US). \param icuLocaleName if empty, return default

*/

/**
   e.g. Utf8Chars = vector<char> or string. appends utf8 to vec.
*/

template <class Utf8Chars>
inline void appendFromIcu(UnicodeString const& ustr, Utf8Chars& vec) {
  UChar const* begin = ustr.getBuffer();
  appendUtf8From16(vec, begin, begin + ustr.length());
}

/**
   e.g. Utf8Chars = vector<char> or string. sets ustr to vec utf8->UnicodeString

   (Illegal input is replaced with U+FFFD)
*/
template <class Utf8Buf>
inline void toIcu(UnicodeString& ustr, Utf8Buf const& vec) {
  UChar* out = ustr.getBuffer((int)vec.size());  // ascii upper bound on # of UTF16 code points needed
  ustr.releaseBuffer(utf8::unchecked::utf8to16(vec.begin(), vec.end(), out) - out);
}

template <class Utf8Iter>
inline void toIcu(UnicodeString& ustr, Utf8Iter begin, Utf8Iter end) {
  int maxSize = (int)(end - begin);  // ascii upper bound on # of UTF16 code points needed
  UChar* out = ustr.getBuffer(maxSize);
  int actualSize = (int)(utf8::unchecked::utf8to16(begin, end, out) - out);
  ustr.releaseBuffer(actualSize);
}

namespace {
unsigned const kIcuErrorInReplacing(-1);
}

/// like toIcu, set ustr to utf8 but return the number of U+FFEE replacements performed. \return
/// kIcuErrorInReplacing (max unsigned)
unsigned toIcuReplacing(UnicodeString& ustr, icu::StringPiece utf8);

///(Illegal input is replaced with U+FFFD)
inline icu::UnicodeString toIcu(std::string const& s) {
  return icu::UnicodeString::fromUTF8(s);
}

inline icu::UnicodeString toIcu(std::string const& s, std::string::size_type start, int32_t len) {
  return icu::UnicodeString::fromUTF8(icu::StringPiece(&s[0] + start, len));
}

inline std::size_t getNumGraphemes(icu::UnicodeString const& ustr) {
  using namespace icu;
  UErrorCode err = U_ZERO_ERROR;
  char* locale = ::setlocale(LC_ALL, NULL);
  Util::AutoDelete<BreakIterator> iter(BreakIterator::createCharacterInstance(locale, err));
  assert(U_SUCCESS(err));
  iter->setText(ustr);

  std::size_t count = 0;
  while (iter->next() != BreakIterator::DONE) {
    ++count;
  }
  return count;
}

inline std::size_t getNumGraphemes(std::string const& s) {
  return getNumGraphemes(toIcu(s));
}

namespace {
/**
   From ICU docs:
   // When converting from UTF-16 to UTF-8, the result will have at most 3 times
   // as many bytes as the source has UChars.
   // The "worst cases" are writing systems like Indic, Thai and CJK with
   // 3:1 bytes:UChars.

   */
const int32_t maxUtf8PerUtf16 = 3;
}

/**
   \return # of bytes copied to bytesOut (<= bytesCapacity) from str[startUChar]....
*/
inline int32_t fromIcu(icu::UnicodeString const& str, char* bytesOut, int32_t bytesCapacity,
                       int32_t startUChar, int32_t lenUChar, UChar32 invalidCharReplacement = 0xFFFD) {
  using namespace icu;
  UErrorCode errorCode = U_ZERO_ERROR;
  int32_t bytesCopied;
  u_strToUTF8WithSub(bytesOut, bytesCapacity, &bytesCopied, str.getBuffer() + startUChar, lenUChar,
                     invalidCharReplacement, 0, &errorCode);
  return bytesCopied;
}

/**
   quickly convert a utf-16 substring from str[startUChar] ... str[startUChar+lenUChar] to a char vector or
   std::string

   \param out a ByteVector = string or vector<char> - something with resize and contiguous array storage
   starting at &out[0]
*/
template <class ByteVector>
inline void fromIcu(icu::UnicodeString const& str, ByteVector& out, int32_t startUChar, int32_t lenUChar) {
  int32_t bytes = maxUtf8PerUtf16 * lenUChar;
  out.resize(bytes);
  out.resize(fromIcu(str, &out[0], bytes, startUChar, lenUChar));
}

template <class ByteVector>
inline void fromIcu(icu::UnicodeString const& str, ByteVector& out) {
  fromIcu(str, out, 0, str.length());
}

inline std::string fromIcu(icu::UnicodeString const& str, int32_t startUChar, int32_t lenUChar) {
  std::string r;
  fromIcu(str, r, startUChar, lenUChar);
  return r;
}

struct FromIcu : std::string {
  explicit FromIcu(icu::UnicodeString const& str) { fromIcu(str, *this); }
};

inline std::string fromIcu(icu::UnicodeString const& str) {
  // s.toUTF8String(r); // same result as this but faster
  std::string r;
  fromIcu(str, r);
  return r;
}

inline std::string fromIcu(UChar* cstr) {
  return fromIcu(icu::UnicodeString(cstr));
}

/// Nfc : Unicode normal form composed - "Normalization Form C (NFC) Canonical
/// Decomposition, followed by Canonical Composition"
bool isNfc(icu::UnicodeString const& s, bool K = false);

inline bool isNfc(icu::StringPiece const& s, bool K) {
  return isNfc(icu::UnicodeString::fromUTF8(s), K);
}

inline bool isNfc(Slice utf8, bool nfkc = false) {
  return isNfc(icu::StringPiece(utf8.first, len(utf8)), nfkc);
}

inline bool isNfc(std::string const& utf8, bool nfkc = false) {
  return isNfc(icu::StringPiece(utf8), nfkc);
}

inline void warnUnnormalized(icu::UnicodeString const& us, char const* normalization) {
  SDL_WARN(Icu.Nfc, fromIcu(us) << " (UnicodeString) is not " << normalization);
}

inline void warnNotNfc(icu::UnicodeString const& us) {
  SDL_WARN(Icu.Nfc, fromIcu(us) << " (UnicodeString) is not normal-form-composed (NFC)");
}

template <class S>
inline void warnNotNfc(S const& utf8) {
  SDL_WARN(Icu.Nfc, "'" << utf8 << "' (utf8) is not normal-form-composed (NFC)");
}

inline void warnNotNfc(icu::StringPiece const& utf8) {
  SDL_WARN(Icu.Nfc, "'" << toSlice(utf8) << "' (utf8) is not normal-form-composed (NFC)");
}

inline bool maybeIcuNormalizeWarn(icu::UnicodeString const& s, icu::UnicodeString& out,
                                  IcuNormalizer2Ptr norm, bool warnIfUnnormalized,
                                  char const* normalizationName = "normal-form-composed (NFC)") {
  if (warnIfUnnormalized) {
    if (neededIcuNormalize(s, out, norm)) {
      warnUnnormalized(s, normalizationName);
      return true;
    } else
      return false;
  } else
    return maybeIcuNormalize(s, out, norm);
}

/// \param[out] buf <- (s -> nfc) and wasNfc <- false, returning buf;
/// or else wasNfc <- true, returning s (Illegal input is replaced with U+FFFD)
inline UnicodeString const& maybeNormalizedToNfc(UnicodeString const& s, UnicodeString& buf, bool& wasNfc,
                                                 bool warnIfNotNfc = false, bool K = false) {

  return maybeIcuNormalizeWarn(s, buf, K ? getNfkc() : getNfc(), warnIfNotNfc) ? buf : s;
}

inline UnicodeString maybeNormalizedToNfc(icu::UnicodeString const& s, bool& wasNfc,
                                          bool warnIfNotNfc = false, bool K = false) {
  UnicodeString buf;
  return maybeNormalizedToNfc(s, buf, wasNfc, warnIfNotNfc, K);
}

inline UnicodeString normalizedToNfc(icu::UnicodeString const& s, bool warnIfNotNfc = false, bool K = false) {
  bool wasNfc;
  return maybeNormalizedToNfc(s, wasNfc, warnIfNotNfc, K);
}

inline bool isNfcWarn(UnicodeString const& us, bool K = false) {
  bool const r = isNfc(us, K);
  if (!r) warnNotNfc(us);
  return r;
}

inline bool isNfcWarn(icu::StringPiece const& us, bool K = false) {
  bool const r = isNfc(us, K);
  if (!r) warnNotNfc(us);
  return r;
}

inline bool isNfcWarn(std::string const& s, bool K = false) {
  return isNfcWarn(icu::StringPiece(s), K);
}

inline bool isNfcWarn(Slice utf8, bool K = false) {
  return isNfcWarn(icuStringPiece(utf8), K);
}

std::string parseErrorString(UParseError const& e);  /// ICU lacks a strerror-like for parse errors

VERBOSE_EXCEPTION_DECLARE(IcuException)

std::string icuLanguagesList(char const* sep = ", ");
std::string icuCountriesList(char const* sep = ", ");

inline std::string localeName(Locale const& locale) {
  UnicodeString r;
  return fromIcu(locale.getDisplayName(r));
}

inline LocalePtr getLocalePtr(std::string const& icuLanguageName = "en",
                              std::string const& icuCountryCode = "") {
  if (icuLanguageName.empty()) return LocalePtr(&Locale::getDefault(), DoNothing());
  char const* country = icuCountryCode.empty() ? 0 : icuCountryCode.c_str();
  if (icuLanguageName == "en_US") return LocalePtr(&Locale::getUS(), DoNothing());
  if (icuLanguageName == "en_GB")  // bad ISO. should be UK
    return LocalePtr(&Locale::getUK(), DoNothing());
  LocalePtr r((new Locale(icuLanguageName.c_str(), country)));
  std::string describeArgs("locale config: language(ISO-639)=");
  describeArgs += icuLanguageName;
  if (country) {
    describeArgs += " country(ISO-3166)=";
    describeArgs += icuCountryCode;
  }
  if (r->isBogus()) SDL_THROW_LOG(ICU.Locale, ConfigException, "got bogus ICU Locale for " << describeArgs);
  std::string isoLanguage = r->getISO3Language();
  if (isoLanguage.empty())
    SDL_THROW_LOG(ICU.Locale, ConfigException, "ICU Locale doesn't know language: " << describeArgs);
  SDL_INFO(ICU.Locale, "Found ICU Locale " << localeName(*r) << " for specification " << describeArgs);
  return r;
}

struct IcuLocaleConfig {
  LocalePtr locale_;
  operator Locale const&() const { return *locale_; }
  Locale const& locale() const { return *locale_; }
  std::string language, country;
  friend inline std::string to_string_impl(IcuLocaleConfig const& x) { return x.to_string_impl(); }
  std::string to_string_impl() const { return "language='" + language + "' country='" + country + "'"; }
  friend void validate(IcuLocaleConfig& x) { x.validate(); }
  void validate() {
    if (language.empty() && !country.empty())
      SDL_THROW_LOG(IcuLocaleConfig, ConfigException,
                    "don't specify country without specifying language: " << to_string_impl());
    if (language.size() > 3 && !country.empty())
      SDL_THROW_LOG(
          IcuLocaleConfig, ConfigException,
          "don't specify a language_country (e.g. en_US) --language while also specifying --country: "
              << to_string_impl());
    locale_ = getLocalePtr(language, country);
  }
  template <class Config>
  void configure(Config& c) {
    c.is("ICU locale");
    c("language", &language)(
        "ICU language 2-3 letter ISO code, or language_country e.g. en_US. empty means icu (OS?) default. "
        "valid choices: "
        + icuLanguagesList());
    c("country", &country)("ICU country 2 letter ISO code. may be empty. valid choices: " + icuCountriesList());
    // TODO: region? script? probably unnecessary for our LPs
  }
};

struct IcuErrorCode : icu::ErrorCode {
  boost::optional<UParseError> optParse;
  std::string detail, prefix;
  bool assertSuccessOnDestroy;
  IcuErrorCode(std::string const& detail = "ERROR", std::string const& prefix = "sdl.IcuErrorCode",
               bool assertSuccessOnDestroy = true)
      : detail(detail), prefix(prefix), assertSuccessOnDestroy(assertSuccessOnDestroy) {}
  ~IcuErrorCode() {
    if (assertSuccessOnDestroy) this->assertSuccess();
  }
  UParseError& storeParseError();  // pass this to ICU methods that write a parse error
  std::string parseError() const;
  void fail() { handleFailure(); }

 protected:
  virtual void handleFailure() const {
    THROW_LOG_NAMESTR(prefix, IcuException, detail << ": " << this->errorName() << parseError());
  }
};

void globalIcuData(std::string pathString);  /// must be called before using any ICU APIs from multiple
/// threads, and before u_init() if you use it

// returns a PATH-format string (unix: /bin:/usr/bin , windows: c:/bin;c:/usr/bin )
std::string platformPathString(std::vector<std::string> const& dirs);

inline void globalIcuData(std::vector<std::string> const& dirnames) {
  globalIcuData(platformPathString(dirnames));
}
}

}

#endif

max_stars_repo_name: sdl-research/hyp

max_issues_repo_name: hypergraphs/hyp

max_forks_repo_name: hypergraphs/hyp


text:
#pragma once

#include <Eigen/Dense>
#include <cmath>
#include <iostream>
#include <robotics/common.hpp>
#include <vector>

namespace Robotics::LinearControl {

    /**
     * @brief A class for implementing a Linear-Quadratic Regulator
     * @todo: Refactor class to conform to the other controllers
     */
    template <int StateSize, int InputSize>
    class LQR {
        static_assert(StateSize > 0);
        static_assert(InputSize > 0);

        using VectorNx1 = ColumnVector<StateSize>;
        using VectorMx1 = ColumnVector<InputSize>;

        using MatrixNxN = SquareMatrix<StateSize>;
        using MatrixMxM = SquareMatrix<InputSize>;
        using InputMatrix = Matrix<StateSize, InputSize>;
        using GainMatrix = Matrix<InputSize, StateSize>;

        using State = VectorNx1;

      public:
        /**
         * @brief Creates a new Linear-Quadratic Regulator
         * @param A state matrix
         * @param B control matrix
         * @param Q state weights matrix
         * @param R control weights matrix
         * @todo pass a linear system as input
         */
        LQR(MatrixNxN A, InputMatrix B, MatrixNxN Q, MatrixMxM R)
            : A(A), B(B), Q(Q), R(R), K(ComputeGain())
        {
        }

        /**
         * @brief Solves the LQR problem
         * @param initial the initial state
         * @param target the target state
         * @return a vector containing the state along the whole path
         * @todo this behavior should be in a user-defined loop, refactor so that only one step is
         * carried out at a time
         */
        std::vector<State> Solve(State initial, State target, double dt)
        {
            std::vector<State> path{initial};
            path.reserve((unsigned int)std::round(max_time / dt)
                         + 1);  // TODO: currently assuming the worst case

            State x = initial - target;
            VectorMx1 u;

            bool path_found = false;
            double time = 0;
            double goal_dist_squared = std::pow(goal_dist, 2);

            while (time < max_time) {
                time += dt;

                u = Input(x);
                x = A * x + B * u;

                path.push_back(x + target);

                if (x.squaredNorm() <= goal_dist_squared) {
                    path_found = true;
                    break;
                }
            }

            if (!path_found) {
                std::cerr << "Couldn't find a path\n";
                return {};
            }

            return path;
        }

        /**
         * @brief Sets the maximum simulation time
         * @param limit time limit
         * @todo remove
         */
        void SetTimeLimit(double limit) { max_time = limit; }

        /**
         * @brief Sets the tolerance w.r.t. the target
         * @param tol tolerance
         * @todo remove, the user should decide when to exit
         */
        void SetFinalPositionTolerance(double tol) { goal_dist = tol; }

        /**
         * @brief Sets the maximum number of iterations
         * @param limit maximum number of iterations
         * @todo remove, the user should decide when to exit
         */
        void SetIterationsLimit(int limit) { max_iter = limit; }

        /**
         * @brief Sets the tolerance for the resolution of the Discrete Algebraic Riccati Equation
         * @param tol tolerance
         */
        void SetDARETolerance(double tol) { eps = tol; }

      private:
        VectorMx1 Input(State x) const { return -K * x; }

        /**
         * @brief Computes the LQR problem gain matrix
         * @return
         */
        GainMatrix ComputeGain()
        {
            MatrixNxN X = SolveDARE();
            return (B.transpose() * X * B + R).inverse() * (B.transpose() * X * A);
        }

        /**
         * @brief Solves a discrete-time algebraic Riccati equation
         * @return
         */
        MatrixNxN SolveDARE() const
        {
            MatrixNxN X = Q, Xn = Q;
            for (auto _ = 0; _ < max_iter; _++) {
                Xn = A.transpose() * X * A
                     - A.transpose() * X * B * (R + B.transpose() * X * B).inverse() * B.transpose()
                           * X * A
                     + Q;
                if ((Xn - X).template lpNorm<Eigen::Infinity>() < eps) break;
                X = Xn;
            }
            return Xn;
        }

        MatrixNxN A;
        InputMatrix B;
        MatrixNxN Q;
        MatrixMxM R;
        GainMatrix K;

        double max_time{100.0};
        double goal_dist{0.1};
        int max_iter{10};
        double eps{0.01};
    };

}  // namespace Robotics::LinearControl

max_issues_repo_name: imthemd/CppRobotics

max_forks_repo_name: imthemd/CppRobotics


text:
#ifndef OSRM_INCLUDE_UTIL_IO_HPP_
#define OSRM_INCLUDE_UTIL_IO_HPP_

#include "util/log.hpp"

#include <boost/filesystem.hpp>
#include <boost/numeric/conversion/cast.hpp>

#include <cstddef>
#include <cstdint>

#include <bitset>
#include <fstream>
#include <stxxl/vector>
#include <vector>

#include "storage/io.hpp"
#include "util/fingerprint.hpp"

namespace osrm
{
namespace util
{

template <typename simple_type>
void deserializeAdjacencyArray(const std::string &filename,
                               std::vector<std::uint32_t> &offsets,
                               std::vector<simple_type> &data)
{
    storage::io::FileReader file(filename, storage::io::FileReader::HasNoFingerprint);

    file.DeserializeVector(offsets);
    file.DeserializeVector(data);

    // offsets have to match up with the size of the data
    if (offsets.empty() || (offsets.back() != boost::numeric_cast<std::uint32_t>(data.size())))
        throw util::exception(
            "Error in " + filename +
            (offsets.empty() ? "Offsets are empty" : "Offset and data size do not match") +
            SOURCE_REF);
}

} // namespace util
} // namespace osrm

#endif // OSRM_INCLUDE_UTIL_IO_HPP_

max_stars_repo_name: mbeckem/msc

max_issues_repo_name: mbeckem/msc

max_forks_repo_name: mbeckem/msc


text:
//  Copyright (c) 2001-2011 Joel de Guzman
//  Copyright (c) 2001-2017 Hartmut Kaiser
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#if !defined(PHYLANX_AST_PARSER_SKIPPER_HPP)
#define PHYLANX_AST_PARSER_SKIPPER_HPP

#include <phylanx/config.hpp>

#include <boost/spirit/include/qi.hpp>

namespace phylanx { namespace ast { namespace parser
{
    namespace qi = boost::spirit::qi;
    namespace ascii = boost::spirit::ascii;

    ///////////////////////////////////////////////////////////////////////////
    //  The skipper grammar
    template <typename Iterator>
    struct skipper : qi::grammar<Iterator>
    {
        skipper() : skipper::base_type(start)
        {
            qi::char_type char_;
            ascii::space_type space;
            qi::eol_type eol;
            qi::eoi_type eoi;

            start =
                    space                               // tab/space/cr/lf
                |   "/*" >> *(char_ - "*/") >> "*/"     // C-style comments
                |   "//" >> *(char_ - end) >> end       // C++-style comments
                |   "#" >> *(char_ - end) >> end        // bash-style comments
                ;

            end = eol | eoi;
        }

        qi::rule<Iterator> start;
        qi::rule<Iterator> end;
    };
}}}

#endif


text:
#include <NTL/GF2EX.h>
#include <NTL/GF2XFactoring.h>

namespace NTL {

void HalfGCD(GF2EX&,GF2EX&);
void PlainRem(GF2EX& r, const GF2EX& a, const GF2EX& b, GF2XVec& x);

}

NTL_CLIENT

#define TIME_IT(t, action) \
do { \
   double _t0, _t1; \
   long _iter = 1; \
   long _cnt = 0; \
   do { \
      _t0 = GetTime(); \
      for (long _i = 0; _i < _iter; _i++) { action; _cnt++; } \
      _t1 = GetTime(); \
   } while ( _t1 - _t0 < 2 && (_iter *= 2)); \
   t = (_t1 - _t0)/_iter; \
} while(0)

void TestGCD1(long bnd, const GF2EX& a, const GF2EX& b)
{

   long n = deg(a) + 1;
   GF2EX u(INIT_SIZE, n), v(INIT_SIZE, n);
   GF2XVec tmp(n, 2*GF2E::WordLength());

   u = a;
   v = b;
   while (deg(v) > bnd) {
      PlainRem(u, u, v, tmp);
      swap(u, v);
   }

}

long test(long k)
{
   GF2X P;

   BuildIrred(P, k);
   GF2EPush push(P);

   for (long n = 42; ; n = long(n*1.4)) {
      cerr << ",";
      GF2EX d, a, b, u, v;
      random(a, n);
      SetCoeff(a, n);
      random(b, n);
      double t1, t2;
      TIME_IT(t1, u=a; v=b; HalfGCD(u, v));
      TIME_IT(t2, TestGCD1(deg(v), a, b));
      double t = t1/t2;
      if (t <= 1) return n;
   }
}

int main()
{
#if 1
   cerr << "0.5 " << test(32) << "\n";
   for (long i = 1; i <= 4; i+=1) {
      cerr << i << " " << test(64*i) << "\n";
   }
   for (long i = 8; i <= 16; i+=4) {
      cerr << i << " " << test(64*i) << "\n";
   }
#endif
   for (long i = 24; i <= 48; i+=8) {
      cerr << i << " " << test(64*i) << "\n";
   }
}


text:
#include <iostream>
#include <iomanip>
#include <sstream>
#include <map>
#include <boost/lexical_cast.hpp>

#include "stringview.hh"
#include "symbol_definitions.hh"
#include "grammar.hh"

namespace iod
{
  using namespace s;

  void parse_command_line(int argc, const char* argv[],
                          std::map<std::string, std::vector<stringview>>& args_map,
                          std::vector<stringview>& positionals)
  {

    stringview arg_name;
    for (int ai = 1; ai < argc; ai++)
    {
      const char* arg = argv[ai];
      int len = static_cast<int>(strlen(arg));

      int ndash = 0;

      if (arg[0] == '-')
        ndash = arg[1] == '-' ? 2 : 1;

      if (ndash > 0)
      {
        arg_name = stringview(arg + ndash, arg + len);

        // if we have an equal assignement -o=12.
        for (int i = 0; i < arg_name.size(); i++)
        {
          if (arg_name[i] == '=')
          {
            arg_name = stringview(arg_name.str, static_cast<size_t>(i));
            arg = arg_name.str + i + 1;
            len = static_cast<int>(strlen(arg));
            break;
          }
        }

        // Register swithes.
        if (ndash == 1)
        {
          for (int i = 0; i < arg_name.size(); i++)
            args_map[std::string(1, arg_name[i])].push_back("1");
          if (arg_name.size() > 1)
          {
            arg_name = stringview();
            ndash = 0;
          }
        }
        else
          args_map[arg_name.to_std_string()].push_back("1");

      }

      if (arg[0] != '-')
      {
        auto value = stringview(arg, static_cast<size_t>(len));
        if (arg_name.data())
        {
          assert(args_map[arg_name.to_std_string()].size() > 0);
          args_map[arg_name.to_std_string()].back() = value;
        }
        else
          positionals.push_back(value);

        arg_name = stringview();
        ndash = 0;

      }

    }

  }

  template <typename S, typename V>
  auto get_option_short_symbol(const assign_exp<S, V>& o)
  {
    return o.left;
  }

  template <typename S, typename V>
  auto get_option_symbol(const assign_exp<S, V>& o)
  {
    return o.left;
  }

  template <typename S1, typename S2, typename V>
  auto get_option_symbol(const assign_exp<logical_or_exp<S1, S2>, V>&)
  {
    return S1();
  }

  template <typename S1, typename S2, typename V>
  auto get_option_short_symbol(const assign_exp<logical_or_exp<S1, S2>, V>&)
  {
    return S2();
  }

  template <typename S, typename V>
  decltype(auto) get_option_value(const assign_exp<S, V>& o)
  {
    return o.right;
  }

  template <typename V>
  void parse_option_value(stringview str, std::vector<V>& v)
  {
    v.push_back(boost::lexical_cast<V>(str.str));
  }

  template <typename V>
  void parse_option_value(stringview str, V& v)
  {
    v = boost::lexical_cast<V>(str.str);
  }

  template <typename V>
  void parse_option_value(stringview str, V* v)
  {
    *v = boost::lexical_cast<V>(str.str);
  }

  namespace cl
  {
    template <typename... T>
    auto positionals(T&&... s)
    {
      return s::_iod_pcl_positionals = std::make_tuple(s...);
    }

    template <typename... T>
    auto required(T&&... s)
    {
      return s::_iod_pcl_required = std::make_tuple(s...);
    }

    template <typename... T>
    auto description(const std::string& gs, T&&... s)
    {
      return s::_iod_pcl_description = D(_description = gs,
                                         _options = D(s...));
    }
  }

  inline const std::string pcl_type_string(const void*) { return "void"; }
  inline const std::string pcl_type_string(const std::string*) { return "string"; }
  inline const std::string pcl_type_string(const int*) { return "int"; }
  inline const std::string pcl_type_string(const float*) { return "float"; }
  inline const std::string pcl_type_string(const double*) { return "double"; }
  inline const std::string pcl_type_string(const bool*) { return ""; }
  template <typename T>
  inline const std::string pcl_type_string(const std::vector<T>*) {
    return std::string("vector<") + pcl_type_string((T*)0) + ">";
  }

  template <typename T>
  inline const std::string pcl_type_string(const T*) { return "value"; }
  template <typename T>
  inline const std::string pcl_type_string(const T&) { return pcl_type_string((const T*)0); }

  template <typename... A, typename... T>
  auto parse_command_line(std::tuple<A...> attrs, int argc, const char* argv[],
                          T&&... opts)
  {

    std::map<std::string, std::vector<stringview>> args_map;
    std::vector<stringview> positional_values;
    parse_command_line(argc, argv, args_map, positional_values);

    auto options = D((get_option_symbol(opts) = get_option_value(opts))...);
    auto attrs_sio = iod::apply(attrs, D_caller());
    auto positionals = attrs_sio.get(_iod_pcl_positionals, std::make_tuple());

    auto required = attrs_sio.get(_iod_pcl_required, std::make_tuple());
    auto description = attrs_sio.get(_iod_pcl_description, D(_description = "", _options = D()));

    // Generation of the help message
    auto print_help = [&] ()
    {
      std::cout << "Usage: " << argv[0] << " [options...]";
      foreach(positionals) | [] (auto p)
      {
        std::cout << " [" << p.name() << "]";
      };
      std::cout << std::endl;
      std::cout << description.description << std::endl << std::endl;
      std::cout << "Available options:" << std::endl << std::endl;
      foreach(std::make_tuple(opts...)) | [&] (auto o)
      {
        auto opt_symbol = get_option_symbol(o);
        auto symbol = std::string(get_option_symbol(o).name());
        auto short_symbol = std::string(get_option_short_symbol(o).name());

        std::string symbols_str = (symbol.size() > 1 ? "--" : "-") + symbol;
        if (short_symbol != symbol)
          symbols_str += std::string("|") + (short_symbol.size() > 1 ? "--" : "-") + short_symbol;

        std::string req;
        foreach(required) | [&] (auto r) { if (r.equals(opt_symbol)) req += "[REQUIRED] "; };

        std::string desc = description.options.get(opt_symbol, "");
        std::string type_s = pcl_type_string(options[opt_symbol]);
        if (type_s.size()) type_s = " " + type_s;
        std::cout << "  " << std::setw(25) << std::left << (symbols_str + type_s) << req;
        for (unsigned i = 0; i < desc.size(); i++)
        {
          if (desc[i] != '\n')
            std::cout << desc[i];
          else std::cout << std::endl << std::setw(27) << " ";
        }
        std::cout << std::endl;
      };
    };

    // Display help on the --help switch.
    if (args_map.find("help") != args_map.end())
    {
      print_help();
#ifndef IOD_PCL_WITH_EXCEPTIONS
      exit(0);
#endif
      throw std::runtime_error("help");

    }

    auto parse_and_check_value = [&] (auto symbol, stringview elt)
      {
        try {
          parse_option_value(elt, options[symbol]);
        } catch (...)
        {
          std::stringstream ss;
          ss << "Invalid command line parameter " << symbol.name() << ": " << std::endl
          << "  Expected type " << pcl_type_string(options[symbol]) << " got " << elt.to_std_string()
          << std::endl;

#ifndef IOD_PCL_WITH_EXCEPTIONS
          std::cerr << ss.str() << std::endl;
          exit(1);
#else
          throw std::runtime_error(ss.str());
#endif
        }
      };

    // Parse options.
    std::map<std::string, bool> filled;
    foreach(std::make_tuple(opts...)) | [&] (auto o)
    {
      auto symbol = get_option_symbol(o);
      auto short_symbol = get_option_short_symbol(o);

      auto it = args_map.find(symbol.name());
      if (it == args_map.end() and
          strcmp(short_symbol.name(), symbol.name()))
        it = args_map.find(short_symbol.name());

      if (it != args_map.end() and it->second.size() > 0)
      {
        for (auto elt : it->second)
          parse_and_check_value(symbol, elt);
        filled[symbol.name()] = true;
      }
      else // Positional ?
      {
        unsigned position = 0;
        foreach(positionals) | [&] (auto p)
        {
          if (p.name() == symbol.name() and
              position < positional_values.size())
          {
            filled[symbol.name()] = true;
            parse_and_check_value(symbol, positional_values[position]);
          }
          position++;
        };
      }

    };

    // Check required args.
    std::vector<std::string> missing;
    foreach(required) | [&] (auto s)
    {
      if (filled.find(s.name()) == filled.end())
        missing.push_back(s.name());
    };

    // Error if at least one missing.
    if (missing.size() > 0)
    {
      std::stringstream err;
      if (missing.size() > 1)
      {
        err << "Error missing command line parameters: " << std::endl;
        for (auto m : missing)
          err << "  - " << m << std::endl;
      }
      else
        err << "Error missing required command line parameter " << missing[0] << std::endl;

#ifndef IOD_PCL_WITH_EXCEPTIONS
      std::cerr << err.str() << std::endl;
      exit(1);
#endif
      throw std::runtime_error(err.str());
    }

    return options;
  }

  template <typename... Q, typename... T, typename PS>
  auto parse_command_line(std::tuple<Q...> attrs,
                          int argc, const char* argv[],
                          assign_exp<_iod_pcl_positionals_t, PS> ps,
                          T&&... opts)
  {
    return parse_command_line(std::tuple_cat(attrs, std::make_tuple(ps)), argc, argv, opts...);
  }

  template <typename... Q, typename... T, typename PS>
  auto parse_command_line(std::tuple<Q...> attrs,
                          int argc, const char* argv[],
                          assign_exp<_iod_pcl_required_t, PS> ps,
                          T&&... opts)
  {
    return parse_command_line(std::tuple_cat(attrs, std::make_tuple(ps)), argc, argv, opts...);
  }

  template <typename... Q, typename... T, typename PS>
  auto parse_command_line(std::tuple<Q...> attrs,
                          int argc, const char* argv[],
                          assign_exp<_iod_pcl_description_t, PS> ps,
                          T&&... opts)
  {
    return parse_command_line(std::tuple_cat(attrs, std::make_tuple(ps)), argc, argv, opts...);
  }

  template <typename... T>
  auto parse_command_line(int argc, const char* argv[],
                          T&&... opts)
  {
    return parse_command_line(std::make_tuple(), argc, argv, opts...);
  }
}

ext: hh

max_issues_repo_name: mheyman/iod

max_forks_repo_name: mheyman/iod


text: #include <boost/serialization/void_cast.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef _CAMPAIGN_REFERENCE_GENERATOR_STREAM_TRANSFORMER_TEST_HPP_
#define _CAMPAIGN_REFERENCE_GENERATOR_STREAM_TRANSFORMER_TEST_HPP_

#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <boost/scoped_ptr.hpp>

class TempDirectory;

class CampaignReferenceGeneratorStreamTransformerTest : public CppUnit::TestFixture
{
private:
	CPPUNIT_TEST_SUITE( CampaignReferenceGeneratorStreamTransformerTest );
	CPPUNIT_TEST( testCampaignReferenceGenerator );
	CPPUNIT_TEST( testNonIntegerCampaignId );
	CPPUNIT_TEST( testMissingCampaignId );
	CPPUNIT_TEST_SUITE_END();

public:
	CampaignReferenceGeneratorStreamTransformerTest();
	virtual ~CampaignReferenceGeneratorStreamTransformerTest();

	void setUp();
	void tearDown();

	void testNonIntegerCampaignId();
	void testMissingCampaignId();
	void testCampaignReferenceGenerator();
};

#endif // _CAMPAIGN_REFERENCE_GENERATOR_STREAM_TRANSFORMER_TEST_HPP_

max_stars_repo_name: aol/DataProxyLibrary

max_issues_repo_name: aol/DataProxyLibrary

max_forks_repo_name: aol/DataProxyLibrary


text:
#include <iostream>
#include <boost/python.hpp>
#include <boost/python/wrapper.hpp>
#include <boost/python/object.hpp>
#include <boost/python/instance_holder.hpp>
#include <boost/python/return_value_policy.hpp>
#include <boost/python/return_internal_reference.hpp>
#include <boost/python/return_opaque_pointer.hpp>

using namespace std;
using namespace boost;
using namespace boost::python;

struct A{
    A(){};
    A(const A* a_self){
        name = a_self->name;
        value = a_self->value;
    }
    ~A(){};
    std::string name="name A";
    int value=10;

};
struct C {
  C(const char* _a, const A* _the_a) {
       a = new std::string(_a);
       the_a = new A(_the_a);
    }
  ~C() { delete a; }
  std::string *a;
  A* the_a;
};

std::string const& get_a(C const& c)
{
  return *(c.a);
}
A const& get_the_a(C const& c){
    return *(c.the_a);
}

BOOST_PYTHON_MODULE(design_member_pointer)
{
  using namespace boost::python;
  class_<A>("A", init<>())
    .def_readwrite("name", &A::name)
    .def_readwrite("value", &A::value)
    ;
  class_<C>("C", init<const char*, const A*>())
    .add_property("a", make_function(get_a, return_value_policy<copy_const_reference>()))
    .add_property("the_a", make_function(get_the_a, return_value_policy<copy_const_reference>()))
    ;
}


text:
#ifndef SHIFT_PROTO_SERVICE_HPP
#define SHIFT_PROTO_SERVICE_HPP

#include <cstddef>
#include <cstdint>
#include <list>
#include <stdexcept>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
#include <memory>
#include <string>
#include <utility>
#include <shift/core/boost_disable_warnings.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/variant/get.hpp>
#include <boost/variant/recursive_wrapper.hpp>
#include <boost/variant/variant.hpp>
#include <shift/core/boost_restore_warnings.hpp>
#include "shift/proto/types.hpp"
#include "shift/proto/namescope.hpp"

namespace shift::proto
{
struct service final : public namescope
{
  /// @see node::generate_uids.
  void generate_uids() override;

  bool is_provider = false;
  interface* service_interface = nullptr;
  type_path service_name;
  interface* callback_interface = nullptr;
  type_path callback_name;
};
}

#endif

max_stars_repo_name: cspanier/shift

max_issues_repo_name: cspanier/shift

max_forks_repo_name: cspanier/shift