text:
#include "hosttracker.hh"
#include <boost/bind.hpp>

namespace vigil
{
  static Vlog_module lg("hosttracker");

  Host_location_event::Host_location_event(const ethernetaddr host_,
					   const list<hosttracker::location> loc_,
					   enum type type_):
    Event(static_get_name()), host(host_), eventType(type_)
  {
    for (list<hosttracker::location>::const_iterator i = loc_.begin();
	 i != loc_.end(); i++)
      loc.push_back(*(new hosttracker::location(i->dpid,
						i->port,
						i->lastTime)));
  }

  hosttracker::location::location(datapathid dpid_, uint16_t port_, time_t tv):
    dpid(dpid_), port(port_), lastTime(tv)
  { }

  void hosttracker::location::set(const hosttracker::location& loc)
  {
    dpid = loc.dpid;
    port = loc.port;
    lastTime = loc.lastTime;
  }

  void hosttracker::configure(const Configuration* c)
  {
    defaultnBindings = DEFAULT_HOST_N_BINDINGS;
    hostTimeout = DEFAULT_HOST_TIMEOUT;

    register_event(Host_location_event::static_get_name());
  }

  void hosttracker::install()
  {
  }

  void hosttracker::check_timeout()
  {
    if (hostlocation.size() == 0)
      return;

    time_t timenow;
    time(&timenow);

    hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \
      hostlocation.find(oldest_host());
    if (i == hostlocation.end())
      return;

    list<hosttracker::location>::iterator j = get_oldest(i->second);
    while (j->lastTime+hostTimeout < timenow)
    {
      //Remove old entry
      i->second.erase(j);
      if (i->second.size() == 0)
      	hostlocation.erase(i);

      //Get next oldest
      i = hostlocation.find(oldest_host());
      if (i == hostlocation.end())
	return;
      j = get_oldest(i->second);
    }

    //Post next one
    timeval tv = {get_oldest(i->second)->lastTime+hostTimeout-timenow, 0};
    post(boost::bind(&hosttracker::check_timeout, this), tv);
  }

  const ethernetaddr hosttracker::oldest_host()
  {
    ethernetaddr oldest((uint64_t) 0);
    time_t oldest_time = 0;
    hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \
      hostlocation.begin();
    while (i != hostlocation.end())
    {
      if (oldest_time == 0 ||
	  get_oldest(i->second)->lastTime < oldest_time)
      {
	oldest_time = get_oldest(i->second)->lastTime;
	oldest = i->first;
      }
      i++;
    }

    return oldest;
  }

  void hosttracker::add_location(ethernetaddr host, datapathid dpid,
				 uint16_t port, time_t tv, bool postEvent)
  {
    //Set default time as now
    if (tv == 0)
      time(&tv);

    add_location(host, hosttracker::location(dpid,port,tv), postEvent);
  }

  void hosttracker::add_location(ethernetaddr host, hosttracker::location loc,
				 bool postEvent)
  {
    hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \
      hostlocation.find(host);
    if (i == hostlocation.end())
    {
      //New host
      list<location> j = list<location>();
      j.push_front(loc);
      hostlocation.insert(make_pair(host,j));

      if (postEvent)
	post(new Host_location_event(host,j,Host_location_event::ADD));

      VLOG_DBG(lg, "New host %"PRIx64" at %"PRIx64":%"PRIx16"",
	       host.hb_long(), loc.dpid.as_host(), loc.port);
    }
    else
    {
      //Existing host
      list<location>::iterator k = i->second.begin();
      while (k->dpid != loc.dpid || k->port != loc.port)
      {
	k++;
	if (k == i->second.end())
	  break;
      }

      if (k == i->second.end())
      {
	//New location
	while (i->second.size() >= getBindingNumber(host))
	  i->second.erase(get_oldest(i->second));
	i->second.push_front(loc);
	VLOG_DBG(lg, "Host %"PRIx64" at new location %"PRIx64":%"PRIx16"",
		 i->first.hb_long(), loc.dpid.as_host(), loc.port);

	if (postEvent)
	  post(new Host_location_event(host,i->second,
				       Host_location_event::MODIFY));
      }
      else
      {
	//Update timeout
	k->lastTime = loc.lastTime;
	VLOG_DBG(lg, "Host %"PRIx64" at old location %"PRIx64":%"PRIx16"",
		 i->first.hb_long(), loc.dpid.as_host(), loc.port);
      }
    }

    VLOG_DBG(lg, "Added host %"PRIx64" to location %"PRIx64":%"PRIx16"",
	     host.hb_long(), loc.dpid.as_host(), loc.port);

    //Schedule timeout if first entry
    if (hostlocation.size() == 0)
    {
      timeval tv= {hostTimeout,0};
      post(boost::bind(&hosttracker::check_timeout, this), tv);
    }
  }

  void hosttracker::remove_location(ethernetaddr host, datapathid dpid,
				    uint16_t port, bool postEvent)
  {
    remove_location(host, hosttracker::location(dpid,port,0), postEvent);
  }

  void hosttracker::remove_location(ethernetaddr host,
				    hosttracker::location loc,
				    bool postEvent)
  {
    hash_map<ethernetaddr,list<hosttracker::location> >::iterator i =	\
      hostlocation.find(host);
    if (i != hostlocation.end())
    {
      bool changed = false;
      list<location>::iterator k = i->second.begin();
      while (k != i->second.end())
      {
	if (k->dpid == loc.dpid || k->port == loc.port)
	{
	  k = i->second.erase(k);
	  changed = true;
	}
	else
	  k++;
      }

      if (postEvent && changed)
	post(new Host_location_event(host,i->second,
				     (i->second.size() == 0)?
				     Host_location_event::REMOVE:
				     Host_location_event::MODIFY));

      if (i->second.size() == 0)
	hostlocation.erase(i);
    }
    else
      VLOG_DBG(lg, "Host %"PRIx64" has no location, cannot unset.",
               host.hb_long());
  }

  const hosttracker::location hosttracker::get_latest_location(ethernetaddr host)
  {
    list<hosttracker::location> locs = \
      (list<hosttracker::location>) get_locations(host);
    if (locs.size() == 0)
      return hosttracker::location(datapathid(), 0, 0);
    else
      return *(get_newest(locs));
  }

  const list<ethernetaddr> hosttracker::get_hosts()
  {
    list<ethernetaddr> hostlist;
    hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \
      hostlocation.begin();
    while (i != hostlocation.end())
    {
      hostlist.push_back(i->first);
      i++;
    }

    return hostlist;
  }

  const list<hosttracker::location> hosttracker::get_locations(ethernetaddr host)
  {
    hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \
      hostlocation.find(host);
    if (i == hostlocation.end())
      return list<hosttracker::location>();
    else
      return i->second;
  }

  list<hosttracker::location>::iterator
  hosttracker::get_newest(list<hosttracker::location>& loclist)
  {
    list<location>::iterator newest = loclist.begin();
    list<location>::iterator j = loclist.begin();
    while (j != loclist.end())
    {
      if (j->lastTime > newest->lastTime)
	newest = j;
      j++;
    }
    return newest;
  }

  list<hosttracker::location>::iterator
  hosttracker::get_oldest(list<hosttracker::location>& loclist)
  {
    list<location>::iterator oldest = loclist.begin();
    list<location>::iterator j = loclist.begin();
    while (j != loclist.end())
    {
      if (j->lastTime < oldest->lastTime)
	oldest = j;
      j++;
    }
    return oldest;
  }

  uint8_t hosttracker::getBindingNumber(ethernetaddr host)
  {
    hash_map<ethernetaddr,uint8_t>::iterator i = nBindings.find(host);
    if (i != nBindings.end())
      return i->second;

    return defaultnBindings;
  }

  const list<hosttracker::location> hosttracker::getLocations(ethernetaddr host)
  {
    hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \
      hostlocation.find(host);

    if (i == hostlocation.end())
      return list<hosttracker::location>();

    return i->second;
  }

  void hosttracker::getInstance(const Context* c,
				  hosttracker*& component)
  {
    component = dynamic_cast<hosttracker*>
      (c->get_by_interface(container::Interface_description
			      (typeid(hosttracker).name())));
  }

  REGISTER_COMPONENT(Simple_component_factory<hosttracker>,
		     hosttracker);
} // vigil namespace

ext: cc

max_stars_repo_name: ayjazz/OESS

max_issues_repo_name: ayjazz/OESS

max_forks_repo_name: ayjazz/OESS


text:
/*
  KeePass Password Safe - The Open-Source Password Manager
  Copyright (C) 2003-2021 Dominik Reichl <dominik.reichl@t-online.de>

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

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

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "StdAfx.h"
#include <ObjBase.h>
#include <AclAPI.h>
#include "FileTransactionEx.h"
#include "PwUtil.h"
#include "StrUtil.h"

#include <boost/scoped_array.hpp>

using boost::scoped_array;

LPCTSTR g_lpTempSuffix = _T(".tmp");
LPCTSTR g_lpTxfTempPrefix = _T("KeePass_TxF_");
LPCTSTR g_lpTxfTempSuffix = _T(".tmp");

CFileTransactionEx::CFileTransactionEx(LPCTSTR lpBaseFile, bool bTransacted) :
	m_bMadeUnhidden(false), m_pSec(NULL), m_hKernel32(NULL), m_hKtmW32(NULL),
	m_fnCreateTransaction(NULL), m_fnMoveFileTransacted(NULL),
	m_fnCommitTransaction(NULL)
{
	m_bTransacted = bTransacted;

	if(lpBaseFile == NULL) { ASSERT(FALSE); return; }

	scoped_array<TCHAR> aPath(new TCHAR[MAX_PATH + 1]);
	ZeroMemory(aPath.get(), (MAX_PATH + 1) * sizeof(TCHAR));
	DWORD r = GetFullPathName(lpBaseFile, MAX_PATH, aPath.get(), NULL);
	if((r == 0) || (r > MAX_PATH)) { ASSERT(FALSE); m_strBase = lpBaseFile; }
	else m_strBase = aPath.get();

	const DWORD dw = GetFileAttributes(m_strBase.c_str());
	if(dw != INVALID_FILE_ATTRIBUTES)
	{
		// Symbolic links are realized via reparse points;
		// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365503.aspx
		// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365680.aspx
		// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365006.aspx
		// Performing a file transaction on a symbolic link
		// would delete/replace the symbolic link instead of
		// writing to its target
		if((dw & FILE_ATTRIBUTE_REPARSE_POINT) != 0) m_bTransacted = false;
	}
	else
	{
		// If the base and the temporary file are in different
		// folders and the base file doesn't exist (i.e. we can't
		// backup the ACL), a transaction would cause the new file
		// to have the default ACL of the temporary folder instead
		// of the one of the base folder; therefore, we don't use
		// a transaction when the base file doesn't exist (this
		// also results in other applications monitoring the folder
		// to see one file creation only)
		m_bTransacted = false;
	}

	if(m_bTransacted)
	{
		m_strTemp = m_strBase + g_lpTempSuffix;
		TxfPrepare(); // Adjusts m_strTemp
	}
	else m_strTemp = m_strBase;
}

CFileTransactionEx::~CFileTransactionEx()
{
	const DWORD dwError = GetLastError();

	ASSERT(m_pSec == NULL);

	if(m_hKtmW32 != NULL)
	{
		m_fnCreateTransaction = NULL;
		m_fnCommitTransaction = NULL;

		VERIFY(FreeLibrary(m_hKtmW32));
		m_hKtmW32 = NULL;
	}

	if(m_hKernel32 != NULL)
	{
		m_fnMoveFileTransacted = NULL;

		VERIFY(FreeLibrary(m_hKernel32));
		m_hKernel32 = NULL;
	}

	for(size_t i = 0; i < m_vToDelete.size(); ++i)
	{
		if(GetFileAttributes(m_vToDelete[i].c_str()) != INVALID_FILE_ATTRIBUTES)
		{
			VERIFY(DeleteFile(m_vToDelete[i].c_str()));
		}
	}
	m_vToDelete.clear();

	SetLastError(dwError);
}

// Must set last error before returning false
bool CFileTransactionEx::OpenWrite(std_string& strOutBufferFile)
{
	if(m_strBase.size() == 0)
	{
		ASSERT(FALSE);
		strOutBufferFile = _T("");
		SetLastError(ERROR_INVALID_HANDLE);
		return false;
	}

	if(!m_bTransacted) m_bMadeUnhidden |= CPwUtil::UnhideFile(m_strTemp.c_str());

	strOutBufferFile = m_strTemp;
	return true;
}

// Must set last error before returning false
bool CFileTransactionEx::CommitWrite()
{
	if(m_strBase.size() == 0)
	{
		ASSERT(FALSE);
		SetLastError(ERROR_INVALID_HANDLE);
		return false;
	}

	bool r = true;
	if(!m_bTransacted)
	{
		if(m_bMadeUnhidden) CPwUtil::HideFile(m_strTemp.c_str(), true);
	}
	else r = CommitWriteTransaction();

	m_strBase = _T(""); // Dispose
	if(m_pSec != NULL) { VERIFY(LocalFree(m_pSec) == NULL); m_pSec = NULL; }

	return r;
}

bool CFileTransactionEx::CommitWriteTransaction()
{
	const bool bMadeUnhidden = CPwUtil::UnhideFile(m_strBase.c_str());

	const DWORD dwAttrib = GetFileAttributes(m_strBase.c_str());
	const bool bAttrib = (dwAttrib != INVALID_FILE_ATTRIBUTES);
	CNullableEx<FILETIME> otCreation;
	PACL pAcl = NULL;

	if(bAttrib) // Base file exists
	{
		if((dwAttrib & FILE_ATTRIBUTE_ENCRYPTED) != 0)
			DecryptFile(m_strBase.c_str(), 0); // For TxF

		otCreation = CPwUtil::GetFileCreationTime(m_strBase.c_str());

		if(GetNamedSecurityInfo(const_cast<LPTSTR>(m_strBase.c_str()),
			SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL,
			&pAcl, NULL, &m_pSec) != ERROR_SUCCESS)
			pAcl = NULL;
	}

	bool bFatalError = false;
	if(!TxfMove(bFatalError))
	{
		if(bFatalError) return false;

		if(bAttrib) // Base file exists
		{
			if(DeleteFile(m_strBase.c_str()) == FALSE) return false;
		}

		if(MoveFile(m_strTemp.c_str(), m_strBase.c_str()) == FALSE)
			return false;
	}
	else { ASSERT(pAcl != NULL); } // TxF success => NTFS => has ACL

	if(otCreation.HasValue())
		CPwUtil::SetFileCreationTime(m_strBase.c_str(), otCreation.GetValuePtr());
	if(bAttrib && ((dwAttrib & FILE_ATTRIBUTE_ENCRYPTED) != 0))
		EncryptFile(m_strBase.c_str());
	if(pAcl != NULL)
	{
		VERIFY(SetNamedSecurityInfo(const_cast<LPTSTR>(m_strBase.c_str()),
			SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, pAcl,
			NULL) == ERROR_SUCCESS);
	}
	if(bMadeUnhidden)
		CPwUtil::HideFile(m_strBase.c_str(), true);

	return true;
}

std_string CFileTransactionEx::TxfCreateID()
{
	GUID g;
	if(FAILED(CoCreateGuid(&g)))
	{
		ASSERT(FALSE);

		g.Data1 = GetTickCount();
		g.Data2 = static_cast<USHORT>(randXorShift());
		g.Data3 = static_cast<USHORT>(rand());

		LARGE_INTEGER li;
		QueryPerformanceCounter(&li);
		memcpy(&g.Data4[0], &li, 8);
	}

	CString strID;
	_UuidToString((BYTE*)&g, &strID);
	return std_string((LPCTSTR)strID);
}

bool CFileTransactionEx::TxfIsSupported(TCHAR chDriveLetter)
{
	if(chDriveLetter == _T('\0')) return false;

	TCHAR tszRoot[4];
	tszRoot[0] = chDriveLetter;
	tszRoot[1] = _T(':');
	tszRoot[2] = _T('\\');
	tszRoot[3] = _T('\0');

	const DWORD cch = MAX_PATH + 1;
	scoped_array<TCHAR> aName(new TCHAR[cch + 1]);
	DWORD dwSerial = 0, cchMaxComp = 0, uFlags = 0;
	scoped_array<TCHAR> aFileSystem(new TCHAR[cch + 1]);

	if(GetVolumeInformation(&tszRoot[0], aName.get(), cch, &dwSerial,
		&cchMaxComp, &uFlags, aFileSystem.get(), cch) == FALSE)
		return false;

	return ((uFlags & FILE_SUPPORTS_TRANSACTIONS) != 0);
}

void CFileTransactionEx::TxfPrepare()
{
	const bool bUni = (sizeof(TCHAR) >= 2);

	if(TxfIsUnusable()) return;

	if(m_hKtmW32 != NULL) { ASSERT(FALSE); return; }
	m_hKtmW32 = LoadLibrary(_T("KtmW32.dll"));
	if(m_hKtmW32 == NULL) return; // Windows <= XP

	m_fnCreateTransaction = (LPCREATETRANSACTION)GetProcAddress(m_hKtmW32,
		"CreateTransaction");
	if(m_fnCreateTransaction == NULL) { ASSERT(FALSE); return; }

	m_fnCommitTransaction = (LPCOMMITTRANSACTION)GetProcAddress(m_hKtmW32,
		"CommitTransaction");
	if(m_fnCommitTransaction == NULL) { ASSERT(FALSE); return; }

	if(m_hKernel32 != NULL) { ASSERT(FALSE); return; }
	m_hKernel32 = LoadLibrary(_T("Kernel32.dll"));
	if(m_hKernel32 == NULL) { ASSERT(FALSE); return; }

	m_fnMoveFileTransacted = (LPMOVEFILETRANSACTED)GetProcAddress(m_hKernel32,
		(bUni ? "MoveFileTransactedW" : "MoveFileTransactedA"));
	if(m_fnMoveFileTransacted == NULL) { ASSERT(FALSE); return; }

	std_string strID = TxfCreateID();

	TCHAR tszTempDir[MAX_PATH + 1];
	ZeroMemory(&tszTempDir[0], (MAX_PATH + 1) * sizeof(TCHAR));
	DWORD r = GetTempPath(MAX_PATH, &tszTempDir[0]);
	if((r == 0) || (r > MAX_PATH) || (tszTempDir[0] == _T('\0'))) { ASSERT(FALSE); return; }

	if(GetFileAttributes(&tszTempDir[0]) == INVALID_FILE_ATTRIBUTES)
	{
		ASSERT(FALSE);
		if(CreateDirectory(&tszTempDir[0], NULL) == FALSE) return;
	}

	std_string strTemp = &tszTempDir[0];
	if(strTemp[strTemp.size() - 1] != _T('\\')) strTemp += _T("\\");
	strTemp += g_lpTxfTempPrefix;
	strTemp += strID;
	strTemp += g_lpTxfTempSuffix;

	TCHAR chB = SU_GetDriveLetter(m_strBase.c_str());
	TCHAR chT = SU_GetDriveLetter(strTemp.c_str());
	if(!TxfIsSupported(chB)) return;
	if((chT != chB) && !TxfIsSupported(chT)) return;

	m_strTxfMidFallback = m_strTemp;
	m_strTemp = strTemp;

	m_vToDelete.push_back(strTemp);
}

bool CFileTransactionEx::TxfMove(bool& bFatalError)
{
	if(m_strTxfMidFallback.size() == 0) return false;

	if(TxfMoveWithTx()) return true;

	// Move the temporary file onto the base file's drive first,
	// such that it cannot happen that both the base file and
	// the temporary file are deleted/corrupted
	const DWORD f = (MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING);
	bool b = (MoveFileEx(m_strTemp.c_str(), m_strTxfMidFallback.c_str(), f) != FALSE);
	if(b) b = (MoveFileEx(m_strTxfMidFallback.c_str(), m_strBase.c_str(), f) != FALSE);
	if(!b) { ASSERT(FALSE); bFatalError = true; return false; }

	ASSERT(GetFileAttributes(m_strTemp.c_str()) == INVALID_FILE_ATTRIBUTES);
	ASSERT(GetFileAttributes(m_strTxfMidFallback.c_str()) == INVALID_FILE_ATTRIBUTES);
	return true;
}

bool CFileTransactionEx::TxfMoveWithTx()
{
	std_string strTx = PWM_PRODUCT_NAME_SHORT;
	strTx += _T(" TxF - ");
	strTx += TxfCreateID();
	if(strTx.size() >= MAX_TRANSACTION_DESCRIPTION_LENGTH)
		strTx = strTx.substr(0, MAX_TRANSACTION_DESCRIPTION_LENGTH - 1);
	std::basic_string<WCHAR> strTxW = _StringToUnicodeStl(strTx.c_str());

	HANDLE hTx = m_fnCreateTransaction(NULL, NULL, 0, 0, 0, 0,
		const_cast<LPWSTR>(strTxW.c_str()));
	if(hTx == INVALID_HANDLE_VALUE) { ASSERT(FALSE); return false; }

	if(m_fnMoveFileTransacted(m_strTemp.c_str(), m_strBase.c_str(), NULL,
		NULL, (MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING), hTx) == FALSE)
	{
		ASSERT(FALSE);
		TxfClosePrsv(hTx);
		return false;
	}

	if(m_fnCommitTransaction(hTx) == FALSE)
	{
		ASSERT(FALSE);
		TxfClosePrsv(hTx);
		return false;
	}

	ASSERT(GetFileAttributes(m_strTemp.c_str()) == INVALID_FILE_ATTRIBUTES);
	TxfClosePrsv(hTx);
	return true;
}

void CFileTransactionEx::TxfClosePrsv(HANDLE hTx)
{
	const DWORD dw = GetLastError();
	VERIFY(CloseHandle(hTx));
	SetLastError(dw);
}

bool CFileTransactionEx::TxfIsUnusable()
{
	// The bug in Microsoft's 'cldflt.sys' driver is fixed by the
	// Windows update 4530684;
	// https://support.microsoft.com/en-us/help/4530684/windows-10-update-kb4530684
	/* const DWORD cchMax = MAX_PATH;
	WCHAR wsz[cchMax];
	ZeroMemory(wsz, cchMax * sizeof(WCHAR));

	DWORD dwType = 0, cb = (cchMax - 4) * sizeof(WCHAR);

	if(RegGetValueW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
		L"ReleaseId", RRF_RT_REG_SZ, &dwType, wsz, &cb) == ERROR_SUCCESS)
	{
		// Due to a bug in Microsoft's 'cldflt.sys' driver, a TxF transaction
		// results in a Blue Screen of Death on Windows 10 1903/1909;
		// https://www.windowslatest.com/2019/10/20/windows-10-update-issues-bsod-broken-apps-and-defender-atp/
		// https://sourceforge.net/p/keepass/discussion/329221/thread/924b94ea48/
		if(wcscmp(wsz, L"1903") == 0) return true;
		if(wcscmp(wsz, L"1909") == 0) return true;
	} */

	return false;
}

ext: cpp

max_stars_repo_name: rrvt/KeePassLastPass

max_issues_repo_name: rrvt/KeePassLastPass

max_forks_repo_name: rrvt/KeePassLastPass


text:
/*
 *          Copyright Andrey Semashev 2007 - 2013.
 * 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)
 */
/*!
 * \file   sinks/frontend_requirements.hpp
 * \author Andrey Semashev
 * \date   22.04.2007
 *
 * The header contains definition of requirement tags that sink backend may declare
 * with regard to frontends. These requirements ensure that a backend will not
 * be used with an incompatible frontend.
 */

#ifndef BOOST_LOG_SINKS_FRONTEND_REQUIREMENTS_HPP_INCLUDED_
#define BOOST_LOG_SINKS_FRONTEND_REQUIREMENTS_HPP_INCLUDED_

#include <boost/mpl/aux_/na.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/inherit.hpp>
#include <boost/mpl/inherit_linearly.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_params_with_a_default.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/log/detail/config.hpp>
#include <boost/log/detail/header.hpp>

#ifdef BOOST_LOG_HAS_PRAGMA_ONCE
#pragma once
#endif

#ifndef BOOST_LOG_COMBINE_REQUIREMENTS_LIMIT
//! The macro specifies the maximum number of requirements that can be combined with the \c combine_requirements metafunction
#define BOOST_LOG_COMBINE_REQUIREMENTS_LIMIT 5
#endif

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

namespace sinks {

/*!
 * The sink backend expects pre-synchronized calls, all needed synchronization is implemented
 * in the frontend (IOW, only one thread is feeding records to the backend concurrently, but
 * it is possible for several threads to write sequentially). Note that if a frontend supports
 * synchronized record feeding, it will also report capable of concurrent record feeding.
 */
struct synchronized_feeding {};

#if !defined(BOOST_LOG_NO_THREADS)

/*!
 * The sink backend ensures all needed synchronization, it is capable to handle multithreaded calls
 */
struct concurrent_feeding : synchronized_feeding {};

#else // !defined(BOOST_LOG_NO_THREADS)

//  If multithreading is disabled, threading models become redundant
typedef synchronized_feeding concurrent_feeding;

#endif // !defined(BOOST_LOG_NO_THREADS)

/*!
 * The sink backend requires the frontend to perform log record formatting before feeding
 */
struct formatted_records {};

/*!
 * The sink backend supports flushing
 */
struct flushing {};

#ifdef BOOST_LOG_DOXYGEN_PASS

/*!
 * The metafunction combines multiple requirement tags into one type. The resulting type will
 * satisfy all specified requirements (i.e. \c has_requirement metafunction will return positive result).
 */
template< typename... RequirementsT >
struct combine_requirements;

#else

template< BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(BOOST_LOG_COMBINE_REQUIREMENTS_LIMIT, typename ReqT, mpl::na) >
struct combine_requirements :
    mpl::inherit_linearly<
        mpl::vector< BOOST_PP_ENUM_PARAMS(BOOST_LOG_COMBINE_REQUIREMENTS_LIMIT, ReqT) >,
        mpl::inherit2< mpl::_1, mpl::_2 >
    >
{
};

#endif // BOOST_LOG_DOXYGEN_PASS

/*!
 * A helper metafunction to check if a requirement is satisfied. The \c TestedT template argument
 * should be the type combining one or several requirements and \c RequiredT is the requirement
 * to test against. The metafunction will yield a positive result if \c TestedT supports \c RequiredT.
 */
template< typename TestedT, typename RequiredT >
struct has_requirement :
    public is_base_of< RequiredT, TestedT >
{
};

} // namespace sinks

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#include <boost/log/detail/footer.hpp>

#endif // BOOST_LOG_SINKS_FRONTEND_REQUIREMENTS_HPP_INCLUDED_

ext: hpp

max_stars_repo_name: Icenium/BoostSharp


text:
//
//  Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)
//
//  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)
//

#include <boost/locale/generator.hpp>
#include <boost/locale/info.hpp>
#include <boost/locale/message.hpp>
#include <iomanip>
#include "test_locale.hpp"

bool has_message(std::locale const &l)
{
    return std::has_facet<boost::locale::message_format<char> >(l);
}

struct test_facet : public std::locale::facet {
    test_facet() : std::locale::facet(0) {}
    static std::locale::id id;
};

std::locale::id test_facet::id;

int main()
{
    try {
        boost::locale::generator g;
        std::locale l=g("en_US.UTF-8");
        TEST(has_message(l));

        g.categories(g.categories() ^ boost::locale::message_facet);
        g.locale_cache_enabled(true);
        g("en_US.UTF-8");
        g.categories(g.categories() | boost::locale::message_facet);
        l=g("en_US.UTF-8");
        TEST(!has_message(l));
        g.clear_cache();
        g.locale_cache_enabled(false);
        l=g("en_US.UTF-8");
        TEST(has_message(l));
        g.characters(g.characters() ^ boost::locale::char_facet);
        l=g("en_US.UTF-8");
        TEST(!has_message(l));
        g.characters(g.characters() | boost::locale::char_facet);
        l=g("en_US.UTF-8");
        TEST(has_message(l));

        l=g("en_US.ISO8859-1");
        TEST(std::use_facet<boost::locale::info>(l).language()=="en");
        TEST(std::use_facet<boost::locale::info>(l).country()=="US");
        TEST(!std::use_facet<boost::locale::info>(l).utf8());
        TEST(std::use_facet<boost::locale::info>(l).encoding()=="iso8859-1");

        l=g("en_US.UTF-8");
        TEST(std::use_facet<boost::locale::info>(l).language()=="en");
        TEST(std::use_facet<boost::locale::info>(l).country()=="US");
        TEST(std::use_facet<boost::locale::info>(l).utf8());

        l=g("en_US.ISO8859-1");
        TEST(std::use_facet<boost::locale::info>(l).language()=="en");
        TEST(std::use_facet<boost::locale::info>(l).country()=="US");
        TEST(!std::use_facet<boost::locale::info>(l).utf8());
        TEST(std::use_facet<boost::locale::info>(l).encoding()=="iso8859-1");

        l=g("en_US.ISO8859-1");
        TEST(std::use_facet<boost::locale::info>(l).language()=="en");
        TEST(std::use_facet<boost::locale::info>(l).country()=="US");
        TEST(!std::use_facet<boost::locale::info>(l).utf8());
        TEST(std::use_facet<boost::locale::info>(l).encoding()=="iso8859-1");

        std::locale l_wt(std::locale::classic(),new test_facet);

        TEST(std::has_facet<test_facet>(g.generate(l_wt,"en_US.UTF-8")));
        TEST(std::has_facet<test_facet>(g.generate(l_wt,"en_US.ISO8859-1")));
        TEST(!std::has_facet<test_facet>(g("en_US.UTF-8")));
        TEST(!std::has_facet<test_facet>(g("en_US.ISO8859-1")));

        g.locale_cache_enabled(true);
        g.generate(l_wt,"en_US.UTF-8");
        g.generate(l_wt,"en_US.ISO8859-1");
        TEST(std::has_facet<test_facet>(g("en_US.UTF-8")));
        TEST(std::has_facet<test_facet>(g("en_US.ISO8859-1")));
        TEST(std::use_facet<boost::locale::info>(g("en_US.UTF-8")).utf8());
        TEST(!std::use_facet<boost::locale::info>(g("en_US.ISO8859-1")).utf8());

    }
    catch(std::exception const &e) {
        std::cerr << "Failed " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    FINALIZE();

}
// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
// boostinspect:noascii


text:
#include "gtfs/agency.hpp"
#include "gtfs/fare.hpp"
#include "gtfs/read_csv.hpp"
#include "gtfs/route.hpp"
#include "gtfs/shape.hpp"
#include "gtfs/stop.hpp"
#include "gtfs/trip.hpp"

#include "tool/container/dictionary.hpp"
#include "tool/io/stream_errors.hpp"

#include <iostream>
#include <string>

using namespace nepomuk::gtfs;
using namespace nepomuk;

// make sure we get a new main function here
#define BOOST_TEST_MAIN
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>

void prepareFixture(std::string const &name)
{
    boost::filesystem::path dir(name);
    boost::filesystem::create_directory(dir);
}

void makeInvalidAgency(std::string const &name)
{
    std::ofstream ofs(name + "/agency.txt");
    // presenting 'agencyname' instead of 'agencyname'. Should throw.
    ofs << "\"agencyname\",\"agency_url\",\"agency_timezone\"D,\"agency_lang\","
           "\"agency_phone\"\n";
    ofs << "\"S-Bahn Berlin "
           "GmbH\",\"http://www.s-bahn-berlin.de\",\"Europe/Berlin\",\"de\",\"\"\n";
}

void makeAgency(std::string const &name)
{
    std::ofstream ofs(name + "/agency.txt");
    ofs << "\"agency_id\",\"agency_name\",\"agency_url\",\"agency_timezone\",\"agency_lang\","
           "\"agency_phone\",\"agency_fare_url\",\"agency_email\r\"\n";
    ofs << "1,\"S-Bahn Berlin "
           "GmbH\",\"http://www.s-bahn-berlin.de\",\"Europe/"
           "Berlin\",\"de\",\"030\",\"www.fare.url\",\"mail@agency.de\r\"\n";
}

void checkAgencyFixture(Agency const &agency)
{
    const auto valid_id = agency.id && *agency.id == AgencyID{0};
    BOOST_CHECK(valid_id);
    const auto valid_name = agency.name == "S-Bahn Berlin GmbH";
    BOOST_CHECK(valid_name);
    const auto valid_url = agency.url == "http://www.s-bahn-berlin.de";
    BOOST_CHECK(valid_url);
    const auto valid_timezone = agency.timezone == "Europe/Berlin";
    BOOST_CHECK(valid_timezone);
    const auto valid_language = agency.language && *agency.language == "de";
    BOOST_CHECK(valid_language);
    const auto valid_phone = agency.phone && *agency.phone == "030";
    BOOST_CHECK(valid_phone);
    const auto valid_fare_url = agency.fare_url && *agency.fare_url == "www.fare.url";
    BOOST_CHECK(valid_fare_url);
    const auto valid_mail = agency.email && *agency.email == "mail@agency.de";
    BOOST_CHECK(valid_mail);
}

void makeMinimalAgency(std::string const &name)
{
    std::ofstream ofs(name + "/agency.txt");
    ofs << "\"agency_name\",\"agency_url\",\"agency_timezone\"\n";
    ofs << "\"S-Bahn Berlin GmbH\",\"http://www.s-bahn-berlin.de\",\"Europe/Berlin\r\"\n";
}

void makeMinimalAgencyInStops(std::string const &name)
{
    std::ofstream ofs(name + "/stops.txt");
    ofs << "\"agency_name\",\"agency_url\",\"agency_timezone\"\n";
    ofs << "\"S-Bahn Berlin GmbH\",\"http://www.s-bahn-berlin.de\",\"Europe/Berlin\"\n";
}

void checkMinimalAgencyFixture(Agency const &agency)
{
    const auto valid_name = agency.name == "S-Bahn Berlin GmbH";
    BOOST_CHECK(valid_name);
    const auto valid_url = agency.url == "http://www.s-bahn-berlin.de";
    BOOST_CHECK(valid_url);
    const auto valid_timezone = agency.timezone == "Europe/Berlin";
    BOOST_CHECK(valid_timezone);

    const auto no_optionals = !agency.id && !agency.language && !agency.phone && !agency.email;
    BOOST_CHECK(no_optionals);
}

void makeStops(std::string const &name)
{
    std::ofstream ofs(name + "/stops.txt");
    ofs << "\"stop_id\",\"stop_code\",\"stop_name\",\"stop_desc\",\"stop_lat\",\"stop_lon\","
           "\"location_type\",\"parent_station\",\"zone_id\",\"stop_url\",\"stop_timezone\","
           "\"wheelchair_boarding\"\n";
    ofs << "000008012716,\"123\",\"Rastow, "
           "Bahnhof\",\"its\",\"1.0000000\",\"1.0000000\",0,00000550215,1,,\"de\",0\n";
    ofs << "000008012717,\"456\",\"Restow, "
           "Bahnhof\",\"so beautiful\",\"2.0000000\",\"2.0000000\",1,00000550216,2,\"www.someurl."
           "com\",\"de\",1\n";
    ofs << "000008012718,\"\",\"Ristow, "
           "Bahnhof\",,\"3.0000000\",\"3.0000000\",,00000550217,3,,\"us\",2\n";
}

void checkStopFixture(std::vector<Stop> const &stops, tool::container::Dictionary const &dictionary)
{
    // we expect exactly three stops, see above
    BOOST_CHECK_EQUAL(stops.size(), 3);

    // stops include parent stop ids in every location
    const auto valid_ids =
        (stops[0].id == StopID{0}) && (stops[1].id == StopID{2}) && (stops[2].id == StopID{4});

    BOOST_CHECK(valid_ids);

    const auto valid_codes = stops[0].code && (*stops[0].code == "123") && stops[1].code &&
                             (*stops[1].code == "456") && !stops[2].code;
    BOOST_CHECK(valid_codes);

    const auto valid_names = (dictionary.get_string(stops[0].name) == "Rastow, Bahnhof") &&
                             (dictionary.get_string(stops[1].name) == "Restow, Bahnhof") &&
                             (dictionary.get_string(stops[2].name) == "Ristow, Bahnhof");
    BOOST_CHECK(valid_names);

    auto check_lat_lon = [](auto const lat_or_lon, const std::int32_t expected) {
        return static_cast<std::int32_t>(lat_or_lon) == expected;
    };

    const auto valid_location = check_lat_lon(stops[0].location.longitude, 1000000) &&
                                check_lat_lon(stops[0].location.latitude, 1000000) &&
                                check_lat_lon(stops[1].location.longitude, 2000000) &&
                                check_lat_lon(stops[1].location.latitude, 2000000) &&
                                check_lat_lon(stops[2].location.longitude, 3000000) &&
                                check_lat_lon(stops[2].location.latitude, 3000000);
    BOOST_CHECK(valid_location);

    const auto valid_types =
        stops[0].location_type && (*stops[0].location_type == LocationType::STOP) &&
        stops[1].location_type && (*stops[1].location_type == LocationType::STATION) &&
        stops[2].location_type && (*stops[2].location_type == LocationType::STOP);
    BOOST_CHECK(valid_types);

    const auto valid_parents = stops[0].parent_station && (*stops[0].parent_station == StopID{1}) &&
                               stops[1].parent_station && (*stops[1].parent_station == StopID{3}) &&
                               stops[2].parent_station && (*stops[2].parent_station == StopID{5});
    BOOST_CHECK(valid_parents);

    const auto valid_descriptions =
        stops[0].description && (dictionary.get_string(*stops[0].description) == "its") &&
        stops[1].description && (dictionary.get_string(*stops[1].description) == "so beautiful") &&
        !stops[2].description;
    BOOST_CHECK(valid_descriptions);

    const auto valid_zones = stops[0].zone_id && (stops[0].zone_id == ZoneID{0}) &&
                             stops[1].zone_id && (stops[1].zone_id == ZoneID{1}) &&
                             stops[2].zone_id && (stops[2].zone_id == ZoneID{2});
    BOOST_CHECK(valid_zones);

    const auto valid_urls = !stops[0].url && stops[1].url &&
                            (dictionary.get_string(*stops[1].url) == "www.someurl.com") &&
                            !stops[2].url;
    BOOST_CHECK(valid_urls);

    const auto valid_timezones = stops[0].timezone && (*stops[0].timezone == "de") &&
                                 stops[1].timezone && (*stops[1].timezone == "de") &&
                                 stops[2].timezone && (*stops[2].timezone == "us");
    BOOST_CHECK(valid_timezones);

    const auto valid_wheelchair =
        stops[0].wheelchair_access &&
        (*stops[0].wheelchair_access == accessibility::Wheelchair::INHERIT_OR_NONE) &&
        stops[1].wheelchair_access &&
        (*stops[1].wheelchair_access == accessibility::Wheelchair::SOME_OR_ALL) &&
        stops[2].wheelchair_access &&
        (*stops[2].wheelchair_access == accessibility::Wheelchair::NONE);
    BOOST_CHECK(valid_wheelchair);
}

void makeMinimalStops(std::string const &name)
{
    std::ofstream ofs(name + "/stops.txt");
    ofs << "\"stop_id\",\"stop_name\",\"stop_lat\",\"stop_lon\"\n";
    ofs << "000008012716,\"Rastow, "
           "Bahnhof\",\"1.0\",\"1.000000\"\n";
    ofs << "000008012717,\"Restow, "
           "Bahnhof\",\"2.00000\",\"2.00000\"\n";
    ofs << "000008012718,\"Ristow, "
           "Bahnhof\",\"3.00000\",\"3.00000\"\n";
}
void checkMinimalStopFixture(std::vector<Stop> const &stops,
                             tool::container::Dictionary const &dictionary)
{
    // we expect exactly three stops, see above
    BOOST_CHECK_EQUAL(stops.size(), 3);

    // minimal IDs do not conatin parent stop stations
    const auto valid_ids =
        (stops[0].id == StopID{0}) && (stops[1].id == StopID{2}) && (stops[2].id == StopID{4});
    BOOST_CHECK(valid_ids);

    const auto valid_names = (dictionary.get_string(stops[0].name) == "Rastow, Bahnhof") &&
                             (dictionary.get_string(stops[1].name) == "Restow, Bahnhof") &&
                             (dictionary.get_string(stops[2].name) == "Ristow, Bahnhof");
    BOOST_CHECK(valid_names);

    auto check_lat_lon = [](auto const lat_or_lon, const std::int32_t expected) {
        return static_cast<std::int32_t>(lat_or_lon) == expected;
    };

    const auto valid_location = check_lat_lon(stops[0].location.longitude, 1000000) &&
                                check_lat_lon(stops[0].location.latitude, 1000000) &&
                                check_lat_lon(stops[1].location.longitude, 2000000) &&
                                check_lat_lon(stops[1].location.latitude, 2000000) &&
                                check_lat_lon(stops[2].location.longitude, 3000000) &&
                                check_lat_lon(stops[2].location.latitude, 3000000);
    BOOST_CHECK(valid_location);

    const auto no_optionals = [](Stop const &stop) {
        return !stop.code && !stop.description && !stop.zone_id && !stop.url &&
               !stop.location_type && !stop.parent_station && !stop.timezone &&
               !stop.wheelchair_access;
    };

    BOOST_CHECK(no_optionals(stops[0]) && no_optionals(stops[1]) && no_optionals(stops[2]));
}

void makeMinimalStopsInAgency(std::string const &name)
{
    std::ofstream ofs(name + "/agency.txt");
    ofs << "\"stop_id\",\"stop_name\",\"stop_lat\",\"stop_lon\"\n";
    ofs << "000008012716,\"Rastow, "
           "Bahnhof\",\"53.457379000000\",\"11.431163000000\"\n";
    ofs << "000008012716,\"Rastow, "
           "Bahnhof\",\"53.457379000000\",\"11.431163000000\"\n";
    ofs << "000008012716,\"Rastow, "
           "Bahnhof\",\"53.457379000000\",\"11.431163000000\"\n";
}

void makeRoutes(std::string const &name)
{
    std::ofstream ofs(name + "/routes.txt");
    ofs << "\"route_id\",\"agency_id\",\"route_short_name\",\"route_long_name\",\"route_type\","
           "\"route_url\",\"route_color\",\"route_text_color\",\"route_desc\"\n";
    ofs << "17289_700,796,\"100\",\"10\",700,,,,\"most beautiful route\"\n";
    ofs << "17289_700,796,\"101\",\"11\",700,\"www.route.url\",\"#001122\",\"#221100\",\"great "
           "route\"\n";
}

void makeMinimalRoutes(std::string const &name)
{
    std::ofstream ofs(name + "/routes.txt");
    ofs << "\"route_id\",\"route_short_name\",\"route_long_name\",\"route_type\"\n";
    ofs << "17289_700,\"100\",\"100\",700\n";
}

void makeTrips(std::string const &name)
{
    std::ofstream ofs(name + "/trips.txt");
    ofs << "\"route_id\",\"service_id\",\"trip_id\",\"trip_headsign\",\"trip_short_name\","
           "\"direction_id\",\"block_id\",\"shape_id\",\"bikes_allowed\",\"wheelchair_"
           "accessible\r\"\n";
    ofs << "17289_700,1,59129500,\"Berlin, S+U Alexanderplatz Bhf/Memhardstr. "
           "(Berlin)\",\"\",\"0\",,48,,0\n";
    ofs << "17289_700,1,59129500,\"Berlin, S+U Alexanderplatz Bhf/Memhardstr. "
           "(Berlin)\",\"\",,,48,0,1\n";
    ofs << "17289_700,1,59129500,\"Berlin, S+U Alexanderplatz Bhf/Memhardstr. "
           "(Berlin)\",\"\",,,48,0,1\n";
    ofs << "17289_700,1,59129500,\"Berlin, S+U Alexanderplatz Bhf/Memhardstr. "
           "(Berlin)\",\"\",\"1\",,48,1,2\n";
    ofs << "17289_700,1,59129500,\"Berlin, S+U Alexanderplatz Bhf/Memhardstr. "
           "(Berlin)\",\"\",\"1\",,48,2,\n";
}
void makeMinimalTrips(std::string const &name)
{
    std::ofstream ofs(name + "/trips.txt");
    ofs << "\"route_id\",\"service_id\",\"trip_id\"\n";
    ofs << "17289_700,1,59129500";
}

void makeStopTimes(std::string const &name)
{
    std::ofstream ofs(name + "/stop_times.txt");
    ofs << "\"trip_id\",\"arrival_time\",\"departure_time\",\"stop_id\",\"stop_sequence\",\"pickup_"
           "type\",\"drop_off_type\",\"stop_headsign\",\"timepoint\",\"shape_dist_traveled\"\n";
    ofs << "59129500,6:29:00,6:29:00,070101003212,0,0,0,\"\",,0.1103\n";
    ofs << "59129500,6:29:00,6:29:00,070101003212,0,,1,\"\",0,0.1103\n";
    ofs << "59129500,6:29:00,6:29:00,070101003212,0,2,,\"\",1,0.1103\n";
    ofs << "61699126,6:29:00,6:29:00,070101003212,0,1,2,\"S+U Alexanderplatz\",,0.1103\n";
    ofs << "61699126,6:29:00,6:29:00,070101003212,0,3,3,\"S+U Alexanderplatz\",,0.1103\n";
}
void makeMinimalStopTimes(std::string const &name)
{
    std::ofstream ofs(name + "/stop_times.txt");
    ofs << "\"trip_id\",\"arrival_time\",\"departure_time\",\"stop_id\",\"stop_sequence\"\n";
    ofs << "59129500,6:29:00,6:29:00,070101003212,0\n";
    ofs << "59129500,6:29:00,6:29:00,070101003212,1\n";
    ofs << "59129500,6:29:00,6:29:00,070101003212,2\r\n";
    ofs << "61699126,6:29:00,6:29:00,070101003212,3\n";
    ofs << "61699126,6:29:00,6:29:00,070101003212,4\n";
}

void makeCalendar(std::string const &name)
{
    std::ofstream ofs(name + "/calendar.txt");
    ofs << "\"service_id\",\"monday\",\"tuesday\",\"wednesday\",\"thursday\",\"friday\","
           "\"saturday\",\"sunday\",\"start_date\",\"end_date\"\n";
    ofs << "1,1,1,1,1,1,0,0,20170119,20171209\n";
    ofs << "1,0,0,0,0,0,1,1,20170119,20171209\n";
}

void makeRequired(std::string const &name)
{
    makeAgency(name);
    makeStops(name);
    makeRoutes(name);
    makeTrips(name);
    makeStopTimes(name);
    makeCalendar(name);
}

void makeMinimalRequired(std::string const &name)
{
    makeMinimalAgency(name);
    makeMinimalStops(name);
    makeMinimalRoutes(name);
    makeMinimalTrips(name);
    makeMinimalStopTimes(name);
    makeCalendar(name);
}

void makeMinimalRequiredSwitched(std::string const &name)
{
    makeMinimalAgencyInStops(name);
    makeMinimalStopsInAgency(name);
    makeMinimalRoutes(name);
    makeMinimalTrips(name);
    makeMinimalStopTimes(name);
    makeCalendar(name);
}

void makeInvalidRequired(std::string const &name)
{
    makeInvalidAgency(name);
    makeStops(name);
    makeRoutes(name);
    makeTrips(name);
    makeStopTimes(name);
    makeCalendar(name);
}

void checkDatasetRequired(Dataset const &dataset)
{
    BOOST_CHECK(dataset.agencies.size() == 1);
    checkAgencyFixture(dataset.agencies.front());
    checkStopFixture(dataset.stops, dataset.dictionary);
}

void checkMinimalDataset(Dataset const &dataset)
{
    BOOST_CHECK(dataset.agencies.size() == 1);
    checkMinimalAgencyFixture(dataset.agencies.front());
    checkMinimalStopFixture(dataset.stops, dataset.dictionary);
}
void makeCalendarDates(std::string const &name)
{
    std::ofstream ofs(name + "/calendar_dates.txt");
    ofs << "\"service_id\",\"date\",\"exception_type\"\n";
    ofs << "1,20170123,2\n";
    ofs << "1,20170123,1\n";
}

void makeFareRules(std::string const &name)
{
    std::ofstream ofs(name + "/fare_rules.txt");
    ofs << "\"fare_id\",\"route_id\",\"origin_id\",\"destination_id\",\"contains_id\"\n";
    ofs << "1,2,1,3,\n";
}

void makeFareAttributes(std::string const &name)
{
    std::ofstream ofs(name + "/fare_attributes.txt");
    ofs << "\"fare_id\",\"price\",\"currency_type\",\"payment_method\",\"transfers\",\"transfer_"
           "duration\"\n";
    ofs << "1,2.3,EUR,0,,23\n";
    ofs << "1,2.3,EUR,0,0,23\n";
    ofs << "1,2.3,EUR,1,1,23\n";
    ofs << "1,2.3,EUR,1,2,23\n";
}

void makeShapes(std::string const &name)
{
    std::ofstream ofs(name + "/shapes.txt");
    ofs << "\"shape_id\",\"shape_pt_lat\",\"shape_pt_lon\",\"shape_pt_sequence\"\n";
    ofs << "1406,52.390931,13.067157,0\n";
    ofs << "1406,52.390931,13.067157,1\n";
}

void makeFrequencies(std::string const &name)
{
    std::ofstream ofs(name + "/frequencies.txt");
    ofs << "\"trip_id\",\"start_time\",\"end_time\",\"headway_secs\",\"exact_times\"\n";
    ofs << "1,13:10:57,25:08:11,200,1\n";
    ofs << "1,13:10:57,25:08:11,200,0\n";
    ofs << "1,13:10:57,25:08:11,200,\n";
}

void makeTransfers(std::string const &name)
{
    std::ofstream ofs(name + "/transfers.txt");
    ofs << "\"from_stop_id\",\"to_stop_id\",\"transfer_type\",\"min_transfer_time\",\"from_route_"
           "id\",\"to_route_id\",\"from_trip_id\",\"to_trip_id\"\n";
    ofs << "000008012716,000008012716,,1300,,,,\n";
    ofs << "000008012716,000008012716,1,2300,,,,\n";
    ofs << "000008012716,000008012716,2,4300,,,,\n";
    ofs << "000008012716,000008012716,3,5300,,,,\n";
    ofs << "000008010327,000008010327,2,240,,,61814935,61815841\n";
}

void makeFeedInfo(std::string const &name)
{
    std::ofstream ofs(name + "/feed_info.txt");
    ofs << "\"feed_publisher_name\",\"feed_publisher_url\",\"feed_lang\",\"feed_start_date\","
           "\"feed_end_date\",\"feed_version\"\n";
    ofs << "\"Some Nice "
           "Publisher\",\"www.publisher.url/not_found/\",\"GER\",20170101,20171212,\"v0.2.1\"\n";
}

void makeOptional(std::string const &name)
{
    makeCalendarDates(name);
    makeFareAttributes(name);
    makeFareRules(name);
    makeShapes(name);
    makeFrequencies(name);
    makeTransfers(name);
    makeFeedInfo(name);
}

void cleanUp(std::string const &name)
{
    boost::filesystem::path dir(name);
    remove_all(dir);
}

// create a datasource to read in
void makeFixture(std::string const &name)
{
    prepareFixture(name);
    makeRequired(name);
    makeOptional(name);
}

BOOST_AUTO_TEST_CASE(check_missing_required)
{
    std::string const name = "missing_required_files";
    prepareFixture(name);
    makeOptional(name);
    BOOST_CHECK_THROW(CSVDiscSource source(name), tool::io::FileNotFoundError);
    cleanUp(name);
}

BOOST_AUTO_TEST_CASE(read_csv)
{
    std::string const name = "valid";
    makeFixture(name);
    CSVDiscSource source(name);
    auto control = readCSV(source);
    checkDatasetRequired(control);
    cleanUp(name);
}

BOOST_AUTO_TEST_CASE(invalid_header_throws)
{
    std::string const name = "invalid_header";
    prepareFixture(name);
    makeInvalidRequired(name);
    CSVDiscSource source(name);
    BOOST_CHECK_THROW(readCSV(source), tool::io::InvalidFileError);
    cleanUp(name);
}

BOOST_AUTO_TEST_CASE(read_minimal)
{
    std::string const name = "minimal";
    prepareFixture(name);
    makeMinimalRequired(name);
    CSVDiscSource source(name);
    auto control = readCSV(source);
    checkMinimalDataset(control);
    cleanUp(name);
}

BOOST_AUTO_TEST_CASE(read_minimal_one_off)
{
    std::string const name = "minimal_one_off";
    prepareFixture(name);
    makeMinimalRequired(name);
    makeMinimalStopsInAgency(name);
    CSVDiscSource source(name);
    BOOST_CHECK_THROW(readCSV(source), tool::io::InvalidFileError);
    cleanUp(name);
}

BOOST_AUTO_TEST_CASE(check_switched_header)
{
    std::string const name = "parsing_wrong_file";
    prepareFixture(name);
    makeMinimalRequiredSwitched(name);

    CSVDiscSource source(name);
    BOOST_CHECK_THROW(readCSV(source), tool::io::InvalidFileError);

    cleanUp(name);
}

max_stars_repo_name: mapbox/nepomuk

max_issues_repo_name: mapbox/nepomuk

max_forks_repo_name: mapbox/nepomuk


text:
//
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_TYPE_TRAITS_HPP
#define BOOST_BEAST_TYPE_TRAITS_HPP

#include <boost/beast/core/detail/config.hpp>
#include <boost/beast/core/file_base.hpp>
#include <boost/beast/core/detail/type_traits.hpp>
#include <boost/asio/buffer.hpp>
#include <type_traits>

namespace boost {
namespace beast {

//------------------------------------------------------------------------------
//
// Handler concepts
//
//------------------------------------------------------------------------------

/** Determine if `T` meets the requirements of @b CompletionHandler.

    This trait checks whether a type meets the requirements for a completion
    handler, and is also callable with the specified signature.
    Metafunctions are used to perform compile time checking of template
    types. This type will be `std::true_type` if `T` meets the requirements,
    else the type will be `std::false_type`.

    @par Example

    Use with `static_assert`:

    @code
    struct handler
    {
        void operator()(error_code&);
    };

    static_assert(is_completion_handler<handler, void(error_code&)>::value,
        "Not a completion handler");
    @endcode
*/
template<class T, class Signature>
#if BOOST_BEAST_DOXYGEN
using is_completion_handler = std::integral_constant<bool, ...>;
#else
using is_completion_handler = std::integral_constant<bool,
    std::is_move_constructible<typename std::decay<T>::type>::value &&
    detail::is_invocable<T, Signature>::value>;
#endif

//------------------------------------------------------------------------------
//
// Stream concepts
//
//------------------------------------------------------------------------------

/** Determine if `T` has the `get_executor` member function.

    Metafunctions are used to perform compile time checking of template
    types. This type will be `std::true_type` if `T` has the member
    function with the correct signature, else type will be `std::false_type`.

    @par Example

    Use with tag dispatching:

    @code
    template<class T>
    void maybe_hello(T& t, std::true_type)
    {
        boost::asio::post(
            t.get_executor(),
            []
            {
                std::cout << "Hello, world!" << std::endl;
            });
    }

    template<class T>
    void maybe_hello(T&, std::false_type)
    {
        // T does not have get_executor
    }

    template<class T>
    void maybe_hello(T& t)
    {
        maybe_hello(t, has_get_executor<T>{});
    }
    @endcode

    Use with `static_assert`:

    @code
    struct stream
    {
        using executor_type = boost::asio::io_context::executor_type;
        executor_type get_executor() noexcept;
    };

    static_assert(has_get_executor<stream>::value, "Missing get_executor member");
    @endcode
*/
#if BOOST_BEAST_DOXYGEN
template<class T>
struct has_get_executor : std::integral_constant<bool, ...>{};
#else
template<class T, class = void>
struct has_get_executor : std::false_type {};

template<class T>
struct has_get_executor<T, beast::detail::void_t<decltype(
        std::declval<T&>().get_executor(),
    (void)0)>> : std::true_type {};
#endif

/** Alias for `T::lowest_layer_type` if it exists, else `T`

    This will be a type alias for `T::lowest_layer_type`
    if it exists, else it will be an alias for `T`.

    @par Example

    Declaring a wrapper:

    @code
    template<class Stream>
    struct stream_wrapper
    {
        using next_layer_type = typename std::remove_reference<Stream>::type;
        using lowest_layer_type = get_lowest_layer<stream_type>;
    };
    @endcode

    Defining a metafunction:

    @code
    /// Alias for `std::true_type` if `T` wraps another stream
    template<class T>
    using is_stream_wrapper : std::integral_constant<bool,
        ! std::is_same<T, get_lowest_layer<T>>::value> {};
    @endcode
*/
#if BOOST_BEAST_DOXYGEN
template<class T>
struct get_lowest_layer;
#else
template<class T>
using get_lowest_layer = typename detail::get_lowest_layer_helper<T>::type;
#endif

/** Determine if `T` meets the requirements of @b AsyncReadStream.

    Metafunctions are used to perform compile time checking of template
    types. This type will be `std::true_type` if `T` meets the requirements,
    else the type will be `std::false_type`.

    @par Example

    Use with `static_assert`:

    @code
    template<class AsyncReadStream>
    void f(AsyncReadStream& stream)
    {
        static_assert(is_async_read_stream<AsyncReadStream>::value,
            "AsyncReadStream requirements not met");
    ...
    @endcode

    Use with `std::enable_if` (SFINAE):

    @code
        template<class AsyncReadStream>
        typename std::enable_if<is_async_read_stream<AsyncReadStream>::value>::type
        f(AsyncReadStream& stream);
    @endcode
*/
#if BOOST_BEAST_DOXYGEN
template<class T>
struct is_async_read_stream : std::integral_constant<bool, ...>{};
#else
template<class T, class = void>
struct is_async_read_stream : std::false_type {};

template<class T>
struct is_async_read_stream<T, detail::void_t<decltype(
    std::declval<T>().async_read_some(
        std::declval<detail::MutableBufferSequence>(),
        std::declval<detail::ReadHandler>()),
            (void)0)>> : std::integral_constant<bool,
    has_get_executor<T>::value
        > {};
#endif

/** Determine if `T` meets the requirements of @b AsyncWriteStream.

    Metafunctions are used to perform compile time checking of template
    types. This type will be `std::true_type` if `T` meets the requirements,
    else the type will be `std::false_type`.

    @par Example

    Use with `static_assert`:

    @code
    template<class AsyncWriteStream>
    void f(AsyncWriteStream& stream)
    {
        static_assert(is_async_write_stream<AsyncWriteStream>::value,
            "AsyncWriteStream requirements not met");
    ...
    @endcode

    Use with `std::enable_if` (SFINAE):

    @code
    template<class AsyncWriteStream>
    typename std::enable_if<is_async_write_stream<AsyncWriteStream>::value>::type
    f(AsyncWriteStream& stream);
    @endcode
*/
#if BOOST_BEAST_DOXYGEN
template<class T>
struct is_async_write_stream : std::integral_constant<bool, ...>{};
#else
template<class T, class = void>
struct is_async_write_stream : std::false_type {};

template<class T>
struct is_async_write_stream<T, detail::void_t<decltype(
    std::declval<T>().async_write_some(
        std::declval<detail::ConstBufferSequence>(),
        std::declval<detail::WriteHandler>()),
            (void)0)>> : std::integral_constant<bool,
    has_get_executor<T>::value
        > {};
#endif

/** Determine if `T` meets the requirements of @b SyncReadStream.

    Metafunctions are used to perform compile time checking of template
    types. This type will be `std::true_type` if `T` meets the requirements,
    else the type will be `std::false_type`.

    @par Example

    Use with `static_assert`:

    @code
    template<class SyncReadStream>
    void f(SyncReadStream& stream)
    {
        static_assert(is_sync_read_stream<SyncReadStream>::value,
            "SyncReadStream requirements not met");
    ...
    @endcode

    Use with `std::enable_if` (SFINAE):

    @code
    template<class SyncReadStream>
    typename std::enable_if<is_sync_read_stream<SyncReadStream>::value>::type
    f(SyncReadStream& stream);
    @endcode
*/
#if BOOST_BEAST_DOXYGEN
template<class T>
struct is_sync_read_stream : std::integral_constant<bool, ...>{};
#else
template<class T, class = void>
struct is_sync_read_stream : std::false_type {};

template<class T>
struct is_sync_read_stream<T, detail::void_t<decltype(
    std::declval<std::size_t&>() = std::declval<T>().read_some(
        std::declval<detail::MutableBufferSequence>()),
    std::declval<std::size_t&>() = std::declval<T>().read_some(
        std::declval<detail::MutableBufferSequence>(),
        std::declval<boost::system::error_code&>()),
            (void)0)>> : std::true_type {};
#endif

/** Determine if `T` meets the requirements of @b SyncWriteStream.

    Metafunctions are used to perform compile time checking of template
    types. This type will be `std::true_type` if `T` meets the requirements,
    else the type will be `std::false_type`.

    @par Example

    Use with `static_assert`:

    @code
    template<class SyncReadStream>
    void f(SyncReadStream& stream)
    {
        static_assert(is_sync_read_stream<SyncReadStream>::value,
            "SyncReadStream requirements not met");
    ...
    @endcode

    Use with `std::enable_if` (SFINAE):

    @code
    template<class SyncReadStream>
    typename std::enable_if<is_sync_read_stream<SyncReadStream>::value>::type
    f(SyncReadStream& stream);
    @endcode
*/
#if BOOST_BEAST_DOXYGEN
template<class T>
struct is_sync_write_stream : std::integral_constant<bool, ...>{};
#else
template<class T, class = void>
struct is_sync_write_stream : std::false_type {};

template<class T>
struct is_sync_write_stream<T, detail::void_t<decltype(
    std::declval<std::size_t&>() = std::declval<T&>().write_some(
        std::declval<detail::ConstBufferSequence>()),
    std::declval<std::size_t&>() = std::declval<T&>().write_some(
        std::declval<detail::ConstBufferSequence>(),
        std::declval<boost::system::error_code&>()),
            (void)0)>> : std::true_type {};
#endif

/** Determine if `T` meets the requirements of @b AsyncStream.

    Metafunctions are used to perform compile time checking of template
    types. This type will be `std::true_type` if `T` meets the requirements,
    else the type will be `std::false_type`.

    @par Example

    Use with `static_assert`:

    @code
    template<class AsyncStream>
    void f(AsyncStream& stream)
    {
        static_assert(is_async_stream<AsyncStream>::value,
            "AsyncStream requirements not met");
    ...
    @endcode

    Use with `std::enable_if` (SFINAE):

    @code
    template<class AsyncStream>
    typename std::enable_if<is_async_stream<AsyncStream>::value>::type
    f(AsyncStream& stream);
    @endcode
*/
#if BOOST_BEAST_DOXYGEN
template<class T>
struct is_async_stream : std::integral_constant<bool, ...>{};
#else
template<class T>
using is_async_stream = std::integral_constant<bool,
    is_async_read_stream<T>::value && is_async_write_stream<T>::value>;
#endif

/** Determine if `T` meets the requirements of @b SyncStream.

    Metafunctions are used to perform compile time checking of template
    types. This type will be `std::true_type` if `T` meets the requirements,
    else the type will be `std::false_type`.

    @par Example

    Use with `static_assert`:

    @code
    template<class SyncStream>
    void f(SyncStream& stream)
    {
        static_assert(is_sync_stream<SyncStream>::value,
            "SyncStream requirements not met");
    ...
    @endcode

    Use with `std::enable_if` (SFINAE):

    @code
    template<class SyncStream>
    typename std::enable_if<is_sync_stream<SyncStream>::value>::type
    f(SyncStream& stream);
    @endcode
*/
#if BOOST_BEAST_DOXYGEN
template<class T>
struct is_sync_stream : std::integral_constant<bool, ...>{};
#else
template<class T>
using is_sync_stream = std::integral_constant<bool,
    is_sync_read_stream<T>::value && is_sync_write_stream<T>::value>;
#endif

//------------------------------------------------------------------------------
//
// File concepts
//
//------------------------------------------------------------------------------

/** Determine if `T` meets the requirements of @b File.

    Metafunctions are used to perform compile time checking of template
    types. This type will be `std::true_type` if `T` meets the requirements,
    else the type will be `std::false_type`.

    @par Example

    Use with `static_assert`:

    @code
    template<class File>
    void f(File& file)
    {
        static_assert(is_file<File>::value,
            "File requirements not met");
    ...
    @endcode

    Use with `std::enable_if` (SFINAE):

    @code
    template<class File>
    typename std::enable_if<is_file<File>::value>::type
    f(File& file);
    @endcode
*/
#if BOOST_BEAST_DOXYGEN
template<class T>
struct is_file : std::integral_constant<bool, ...>{};
#else
template<class T, class = void>
struct is_file : std::false_type {};

template<class T>
struct is_file<T, detail::void_t<decltype(
    std::declval<bool&>() = std::declval<T const&>().is_open(),
    std::declval<T&>().close(std::declval<error_code&>()),
    std::declval<T&>().open(
        std::declval<char const*>(),
        std::declval<file_mode>(),
        std::declval<error_code&>()),
    std::declval<std::uint64_t&>() = std::declval<T&>().size(
        std::declval<error_code&>()),
    std::declval<std::uint64_t&>() = std::declval<T&>().pos(
        std::declval<error_code&>()),
    std::declval<T&>().seek(
        std::declval<std::uint64_t>(),
        std::declval<error_code&>()),
    std::declval<std::size_t&>() = std::declval<T&>().read(
        std::declval<void*>(),
        std::declval<std::size_t>(),
        std::declval<error_code&>()),
    std::declval<std::size_t&>() = std::declval<T&>().write(
        std::declval<void const*>(),
        std::declval<std::size_t>(),
        std::declval<error_code&>()),
            (void)0)>> : std::integral_constant<bool,
    std::is_default_constructible<T>::value &&
    std::is_destructible<T>::value
        > {};
#endif

} // beast
} // boost

#endif

max_stars_repo_name: ramcn/gemmx

max_issues_repo_name: ramcn/gemmx

max_forks_repo_name: ramcn/gemmx


text:
//
// AsioServicePool.cpp - part of buzz-ftpd
// Copyright (c) 2011, cxxjoe
// Please refer to the LICENSE file for details.
//
// Based on:
// io_service_pool.cpp
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//

#include "AsioServicePool.h"
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <stdexcept>

CAsioServicePool::CAsioServicePool(size_t a_poolSize)
	: m_nextIndex(0)
{
	if(a_poolSize < 1)
	{
		throw new std::runtime_error("CAsioServicePool: pool size is zero.");
	}

	// Give all the io_services work to do so that their run() functions will not
	// exit until they are explicitly stopped.
	for(size_t i = 0; i < a_poolSize; i++)
	{
		PIOService l_ioService(new boost::asio::io_service());
		m_ioServices.push_back(l_ioService);

		PIOWork l_ioWork(new boost::asio::io_service::work(*l_ioService));
		m_ioWork.push_back(l_ioWork);
	}
}

void CAsioServicePool::Run()
{
	typedef boost::shared_ptr<boost::thread> PThread;

	// Create a pool of threads to run all of the io_services.
	std::vector<PThread> l_threads;
	for(size_t i = 0; i < m_ioServices.size(); i++)
	{
		PThread l_thread(new boost::thread(
			boost::bind(&boost::asio::io_service::run, m_ioServices[i])));

		l_threads.push_back(l_thread);
	}

	// Wait for all threads in the pool to exit.
	for(size_t i = 0; i < l_threads.size(); i++)
	{
		l_threads[i]->join();
	}
}

void CAsioServicePool::Stop()
{
	// Explicitly stop all io_services.
	for(size_t i = 0; i < m_ioServices.size(); i++)
	{
		m_ioServices[i]->stop();
	}
}

boost::asio::io_service& CAsioServicePool::GetIOService()
{
	// Use a round-robin scheme to choose the next io_service to use.
	boost::asio::io_service& l_ioService = *m_ioServices[m_nextIndex];

	m_nextIndex++;
	if(m_nextIndex == m_ioServices.size())
	{
		m_nextIndex = 0;
	}

	return l_ioService;
}

max_stars_repo_name: cmstest/buzz-ftpd

max_issues_repo_name: cmstest/buzz-ftpd

max_forks_repo_name: cmstest/buzz-ftpd


text:
#pragma once

// Some standard functions for dealing with rotation matrices and quaternions

#include <iostream>
#include <vector>
#include <Eigen/Dense>
#include <Eigen/Core>

using namespace Eigen;

const MatrixXd H = (MatrixXd() << MatrixXd::Zero(1, 3), MatrixXd::Identity(3, 3)).finished();
const MatrixXd T = (MatrixXd()  << 1, MatrixXd::Zero(1, 3), MatrixXd::Zero(3, 1), -MatrixXd::Identity(3, 3)).finished();

MatrixXd hat(VectorXd omega);
MatrixXd L(VectorXd Q);
MatrixXd R(VectorXd Q);
MatrixXd G(VectorXd Q);
MatrixXd G_tilde(VectorXd q);
MatrixXd rho(VectorXd phi);


text:
// (C) Copyright Francois Faure, iMAGIS-GRAVIR / UJF, 2001.
//
// 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)
//
// Revision History:
// 03 May 2001   Jeremy Siek
//      Generalized the property map iterator and moved that
//      part to boost/property_map.hpp. Also modified to
//      differentiate between const/mutable graphs and
//      added a workaround to avoid partial specialization.

// 02 May 2001   Francois Faure
//     Initial version.

#ifndef BOOST_GRAPH_PROPERTY_ITER_RANGE_HPP
#define BOOST_GRAPH_PROPERTY_ITER_RANGE_HPP

#include <boost/property_map/property_map_iterator.hpp>
#include <boost/graph/properties.hpp>
#include <boost/mpl/if.hpp>
#include <boost/type_traits/same_traits.hpp>

namespace boost {

//======================================================================
// graph property iterator range

  template <class Graph, class PropertyTag>
  class graph_property_iter_range {
    typedef typename property_map<Graph, PropertyTag>::type map_type;
    typedef typename property_map<Graph, PropertyTag>::const_type
      const_map_type;
    typedef typename property_kind<PropertyTag>::type Kind;
    typedef typename mpl::if_c<is_same<Kind, vertex_property_tag>::value,
       typename graph_traits<Graph>::vertex_iterator,
       typename graph_traits<Graph>::edge_iterator>::type iter;
  public:
    typedef typename property_map_iterator_generator<map_type, iter>::type
      iterator;
    typedef typename property_map_iterator_generator<const_map_type, iter>
      ::type const_iterator;
    typedef std::pair<iterator, iterator> type;
    typedef std::pair<const_iterator, const_iterator> const_type;
  };

  namespace detail {

    template<class Graph,class Tag>
    typename graph_property_iter_range<Graph,Tag>::type
    get_property_iter_range_kind(Graph& graph, const Tag& tag,
                                 const vertex_property_tag& )
    {
      typedef typename graph_property_iter_range<Graph,Tag>::iterator iter;
      return std::make_pair(iter(vertices(graph).first, get(tag, graph)),
                            iter(vertices(graph).second, get(tag, graph)));
    }

    template<class Graph,class Tag>
    typename graph_property_iter_range<Graph,Tag>::const_type
    get_property_iter_range_kind(const Graph& graph, const Tag& tag,
                                 const vertex_property_tag& )
    {
      typedef typename graph_property_iter_range<Graph,Tag>
        ::const_iterator iter;
      return std::make_pair(iter(vertices(graph).first, get(tag, graph)),
                            iter(vertices(graph).second, get(tag, graph)));
    }

    template<class Graph,class Tag>
    typename graph_property_iter_range<Graph,Tag>::type
    get_property_iter_range_kind(Graph& graph, const Tag& tag,
                                 const edge_property_tag& )
    {
      typedef typename graph_property_iter_range<Graph,Tag>::iterator iter;
      return std::make_pair(iter(edges(graph).first, get(tag, graph)),
                            iter(edges(graph).second, get(tag, graph)));
    }

    template<class Graph,class Tag>
    typename graph_property_iter_range<Graph,Tag>::const_type
    get_property_iter_range_kind(const Graph& graph, const Tag& tag,
                                 const edge_property_tag& )
    {
      typedef typename graph_property_iter_range<Graph,Tag>
        ::const_iterator iter;
      return std::make_pair(iter(edges(graph).first, get(tag, graph)),
                            iter(edges(graph).second, get(tag, graph)));
    }

  } // namespace detail

  //======================================================================
  // get an iterator range of properties

  template<class Graph, class Tag>
  typename graph_property_iter_range<Graph, Tag>::type
  get_property_iter_range(Graph& graph, const Tag& tag)
  {
    typedef typename property_kind<Tag>::type Kind;
    return detail::get_property_iter_range_kind(graph, tag, Kind());
  }

  template<class Graph, class Tag>
  typename graph_property_iter_range<Graph, Tag>::const_type
  get_property_iter_range(const Graph& graph, const Tag& tag)
  {
    typedef typename property_kind<Tag>::type Kind;
    return detail::get_property_iter_range_kind(graph, tag, Kind());
  }

} // namespace boost

#endif // BOOST_GRAPH_PROPERTY_ITER_RANGE_HPP


text:
//--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// Please do not modify this file. It will be re-generated
// running the code generator.
//--------------------------------------------------------------------------
#include "CommRobotinoObjects/CommPathNavigationPoseAnswerCore.hh"

// serialization/deserialization operators
//#include "CommRobotinoObjects/CommPathNavigationPoseAnswerACE.hh"

// include the hash.idl containing the hash constant
#include "hash.hh"
#include <assert.h>
#include <cstring>
#include <iostream>

// SmartUtils used in from_xml method
#include "smartKnuthMorrisPratt.hh"

#ifdef ENABLE_HASH
	#include <boost/functional/hash.hpp>
#endif

namespace CommRobotinoObjects
{
	const char* CommPathNavigationPoseAnswerCore::getCompiledHash()
	{
		return CommRobotinoObjectsIDL::REPO_HASH;
	}

	void CommPathNavigationPoseAnswerCore::getAllHashValues(std::list<std::string> &hashes)
	{
		// get own hash value
		hashes.push_back(getCompiledHash());
	}

	void CommPathNavigationPoseAnswerCore::checkAllHashValues(std::list<std::string> &hashes)
	{
		// check own hash value
		if (strcmp(getCompiledHash(), hashes.front().c_str()) != 0)
		{
			std::cerr << "###################################################" << std::endl;
			std::cerr << "WARNING: HASHES OF COMMUNICATION OBJECTS MISSMATCH!" << std::endl;
			std::cerr << "CommPathNavigationPoseAnswerCore hash" << std::endl;
			std::cerr << "Expected: " << getCompiledHash() << std::endl;
			std::cerr << "Received: " << hashes.front() << std::endl;
			std::cerr << "###################################################" << std::endl;
		}
		assert(strcmp(getCompiledHash(), hashes.front().c_str()) == 0);
		hashes.pop_front();

	}

	#ifdef ENABLE_HASH
	size_t CommPathNavigationPoseAnswerCore::generateDataHash(const DATATYPE &data)
	{
		size_t seed = 0;

		boost::hash_combine(seed, data.result);

		return seed;
	}
	#endif

	// default constructor
	CommPathNavigationPoseAnswerCore::CommPathNavigationPoseAnswerCore()
	:	idl_CommPathNavigationPoseAnswer()
	{
		setResult(CommRobotinoObjects::NodeRequestAnserType());
	}

	CommPathNavigationPoseAnswerCore::CommPathNavigationPoseAnswerCore(const DATATYPE &data)
	:	idl_CommPathNavigationPoseAnswer(data)
	{  }

	CommPathNavigationPoseAnswerCore::~CommPathNavigationPoseAnswerCore()
	{  }

	void CommPathNavigationPoseAnswerCore::to_ostream(std::ostream &os) const
	{
	  os << "CommPathNavigationPoseAnswer(";
	  getResult().to_ostream(os);
	  os << ") ";
	}

	// convert to xml stream
	void CommPathNavigationPoseAnswerCore::to_xml(std::ostream &os, const std::string &indent) const {
		os << indent << "<result>";
		getResult().to_xml(os, indent);
		os << indent << "</result>";
	}

	// restore from xml stream
	void CommPathNavigationPoseAnswerCore::from_xml(std::istream &is) {
		static const Smart::KnuthMorrisPratt kmp_result("<result>");

		if(kmp_result.search(is)) {
			CommRobotinoObjects::NodeRequestAnserType resultItem;
			resultItem.from_xml(is);
			setResult(resultItem);
		}
	}

	/*
	void CommPathNavigationPoseAnswerCore::get(ACE_Message_Block *&msg) const
	{
		// start with a default internal buffer size(will automatically grow if needed)
		ACE_OutputCDR cdr(ACE_DEFAULT_CDR_BUFSIZE);

		CommRobotinoObjectsIDL::HashList hashes;
		getAllHashValues(hashes);
		cdr << static_cast<ACE_CDR::Long>(hashes.size());
		for(CommRobotinoObjectsIDL::HashList::const_iterator it=hashes.begin(); it!=hashes.end(); it++)
		{
			cdr << ACE_CString(it->c_str());
		}

		// Here the actual serialization takes place using the OutputCDR serialization operator<<
		// (see CommPathNavigationPoseAnswerACE.hh)
		cdr << idl_CommPathNavigationPoseAnswer;

	#ifdef ENABLE_HASH
		ACE_CDR::ULong data_hash = generateDataHash(idl_CommPathNavigationPoseAnswer);
		cdr << data_hash;
		// std::cout << "CommPathNavigationPoseAnswerCore: current data hash: " << data_hash << std::endl;
	#endif

		// return a shallow copy of the serialized message
		// (no data is actually copied, only the internal reference counter is incremented)
		// in order to prevent memory leaks the caller of this get(msg) method must
		// manually free the memory by calling the release() method of the message block msg
		msg = cdr.begin()->duplicate();
	}

	void CommPathNavigationPoseAnswerCore::set(const ACE_Message_Block *msg)
	{
		ACE_InputCDR cdr(msg);

		CommRobotinoObjectsIDL::HashList hashes;
		ACE_CDR::Long hashes_size;
		cdr >> hashes_size;
		for(int i=0; i<hashes_size; ++i)
		{
			ACE_CString hash;
			cdr >> hash;
			hashes.push_back(hash.c_str());
		}
		checkAllHashValues(hashes);

		// Here the actual de-serialization takes place using the InputCDR serialization operator>>
		// (see CommPathNavigationPoseAnswerACE.hh)
		cdr >> idl_CommPathNavigationPoseAnswer;

	#ifdef ENABLE_HASH
		ACE_CDR::Long data_hash;
		cdr >> data_hash;
		ACE_CDR::Long own_hash = generateDataHash(idl_CommPathNavigationPoseAnswer);
		assert(data_hash == own_hash);
		// std::cout << "CommPathNavigationPoseAnswerCore: own data hash: " << own_hash << "; received data hash: " << data_hash << std::endl;
	#endif
	}
	*/
} /* namespace CommRobotinoObjects */


text:
#pragma once
#include <fstream>
#include <boost/beast/ssl.hpp>
#include "../config/config.hpp"

namespace web_server {
    namespace ssl {
        inline void load_server_certificate(boost::beast::net::ssl::context& ctx)
        {
            auto config = config::Instance->GetConfig();
            ctx.set_options(boost::asio::ssl::context::default_workarounds |
                            boost::asio::ssl::context::sslv23 |
                            boost::asio::ssl::context::no_sslv2 |
                            boost::asio::ssl::context::no_sslv3 |
                            boost::asio::ssl::context::single_dh_use);
            ctx.set_verify_mode(0);

            if (!std::filesystem::exists(config.ssl_settings.certificate_file)) {
                std::cout << "Failed to load ssl certificate file\n";
                exit(EXIT_FAILURE);
            }
            if (!std::filesystem::exists(config.ssl_settings.private_key_file)) {
                std::cout << "Failed to load ssl private key file\n";
                exit(EXIT_FAILURE);
            }

            std::ifstream certreader(config.ssl_settings.certificate_file);

            if (!certreader.is_open()) {
                std::cout << "Failed to open ssl certificate file\n";
                exit(EXIT_FAILURE);
            }

            std::string buffer;
            std::string cert;
            while (std::getline(certreader, buffer))
                cert += "\n" + buffer;
            certreader.close();

            std::ifstream keyreader(config.ssl_settings.private_key_file);

            if (!keyreader.is_open()) {
                std::cout << "Failed to open ssl private key file\n";
                exit(EXIT_FAILURE);
            }

            std::string key;
            while (std::getline(keyreader, buffer))
                key += "\n" + buffer;
            keyreader.close();

            ctx.use_certificate_chain(boost::asio::buffer(cert.data(), cert.size()));
            ctx.use_private_key(boost::asio::buffer(key.data(), key.size()), boost::asio::ssl::context::file_format::pem);
        }
    } // ssl
} // web_server


text:
/*
 * @Description: 实时显示，主要是点云
 * @Author: Ren Qian
 * @Date: 2020-02-29 03:19:45
 */
#ifndef LIDAR_LOCALIZATION_MAPPING_VIEWER_VIEWER_HPP_
#define LIDAR_LOCALIZATION_MAPPING_VIEWER_VIEWER_HPP_

#include <string>
#include <Eigen/Dense>
#include <yaml-cpp/yaml.h>

#include "lidar_localization/sensor_data/cloud_data.hpp"
#include "lidar_localization/sensor_data/key_frame.hpp"
#include "lidar_localization/sensor_data/pose_data.hpp"
#include "lidar_localization/models/cloud_filter/voxel_filter.hpp"

namespace lidar_localization {
class Viewer {
  public:
    Viewer();

    bool UpdateWithOptimizedKeyFrames(std::deque<KeyFrame>& optimized_key_frames);
    bool UpdateWithNewKeyFrame(std::deque<KeyFrame>& new_key_frames,
                               PoseData transformed_data,
                               CloudData cloud_data);

    bool SaveMap();
    Eigen::Matrix4f& GetCurrentPose();
    CloudData::CLOUD_PTR& GetCurrentScan();
    bool GetLocalMap(CloudData::CLOUD_PTR& local_map_ptr);
    bool GetGlobalMap(CloudData::CLOUD_PTR& local_map_ptr);
    bool HasNewLocalMap();
    bool HasNewGlobalMap();

  private:
    bool InitWithConfig();
    bool InitParam(const YAML::Node& config_node);
    bool InitDataPath(const YAML::Node& config_node);
    bool InitFilter(std::string filter_user,
                    std::shared_ptr<CloudFilterInterface>& filter_ptr,
                    const YAML::Node& config_node);

    bool OptimizeKeyFrames();
    bool JointGlobalMap(CloudData::CLOUD_PTR& global_map_ptr);
    bool JointLocalMap(CloudData::CLOUD_PTR& local_map_ptr);
    bool JointCloudMap(const std::deque<KeyFrame>& key_frames,
                             CloudData::CLOUD_PTR& map_cloud_ptr);

  private:
    std::string data_path_ = "";
    int local_frame_num_ = 20;

    std::string key_frames_path_ = "";
    std::string map_path_ = "";

    std::shared_ptr<CloudFilterInterface> frame_filter_ptr_;
    std::shared_ptr<CloudFilterInterface> local_map_filter_ptr_;
    std::shared_ptr<CloudFilterInterface> global_map_filter_ptr_;

    Eigen::Matrix4f pose_to_optimize_ = Eigen::Matrix4f::Identity();
    PoseData optimized_odom_;
    CloudData optimized_cloud_;
    std::deque<KeyFrame> optimized_key_frames_;
    std::deque<KeyFrame> all_key_frames_;

    bool has_new_global_map_ = false;
    bool has_new_local_map_ = false;
};
}

#endif


text:
// Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.

// 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)

#ifndef UUID_10F2D1EA17B511E0BA29FE0BDFD72085
#define UUID_10F2D1EA17B511E0BA29FE0BDFD72085

#include <boost/qvm/enable_if.hpp>
#include <boost/qvm/inline.hpp>
#include <boost/qvm/static_assert.hpp>
#include <boost/qvm/vec_traits.hpp>

namespace boost {
namespace qvm {
////////////////////////////////////////////////

template <int I, class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type>::type
    A(V const &a) {
  BOOST_STATIC_ASSERT(I >= 0);
  BOOST_STATIC_ASSERT(I < vec_traits<V>::dim);
  return vec_traits<V>::template read_element<I>(a);
}

template <int I, class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type &>::type
    A(V &a) {
  BOOST_STATIC_ASSERT(I >= 0);
  BOOST_STATIC_ASSERT(I < vec_traits<V>::dim);
  return vec_traits<V>::template write_element<I>(a);
}

template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type>::type
    X(V const &a) {
  BOOST_STATIC_ASSERT(0 < vec_traits<V>::dim);
  return vec_traits<V>::template read_element<0>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type>::type
    Y(V const &a) {
  BOOST_STATIC_ASSERT(1 < vec_traits<V>::dim);
  return vec_traits<V>::template read_element<1>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type>::type
    Z(V const &a) {
  BOOST_STATIC_ASSERT(2 < vec_traits<V>::dim);
  return vec_traits<V>::template read_element<2>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type>::type
    W(V const &a) {
  BOOST_STATIC_ASSERT(3 < vec_traits<V>::dim);
  return vec_traits<V>::template read_element<3>(a);
}

template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type &>::type
    X(V &a) {
  BOOST_STATIC_ASSERT(0 < vec_traits<V>::dim);
  return vec_traits<V>::template write_element<0>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type &>::type
    Y(V &a) {
  BOOST_STATIC_ASSERT(1 < vec_traits<V>::dim);
  return vec_traits<V>::template write_element<1>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type &>::type
    Z(V &a) {
  BOOST_STATIC_ASSERT(2 < vec_traits<V>::dim);
  return vec_traits<V>::template write_element<2>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type &>::type
    W(V &a) {
  BOOST_STATIC_ASSERT(3 < vec_traits<V>::dim);
  return vec_traits<V>::template write_element<3>(a);
}

template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type>::type
    A0(V const &a) {
  BOOST_STATIC_ASSERT(0 < vec_traits<V>::dim);
  return vec_traits<V>::template read_element<0>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type>::type
    A1(V const &a) {
  BOOST_STATIC_ASSERT(1 < vec_traits<V>::dim);
  return vec_traits<V>::template read_element<1>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type>::type
    A2(V const &a) {
  BOOST_STATIC_ASSERT(2 < vec_traits<V>::dim);
  return vec_traits<V>::template read_element<2>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type>::type
    A3(V const &a) {
  BOOST_STATIC_ASSERT(3 < vec_traits<V>::dim);
  return vec_traits<V>::template read_element<3>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type>::type
    A4(V const &a) {
  BOOST_STATIC_ASSERT(4 < vec_traits<V>::dim);
  return vec_traits<V>::template read_element<4>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type>::type
    A5(V const &a) {
  BOOST_STATIC_ASSERT(5 < vec_traits<V>::dim);
  return vec_traits<V>::template read_element<5>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type>::type
    A6(V const &a) {
  BOOST_STATIC_ASSERT(6 < vec_traits<V>::dim);
  return vec_traits<V>::template read_element<6>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type>::type
    A7(V const &a) {
  BOOST_STATIC_ASSERT(7 < vec_traits<V>::dim);
  return vec_traits<V>::template read_element<7>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type>::type
    A8(V const &a) {
  BOOST_STATIC_ASSERT(8 < vec_traits<V>::dim);
  return vec_traits<V>::template read_element<8>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type>::type
    A9(V const &a) {
  BOOST_STATIC_ASSERT(9 < vec_traits<V>::dim);
  return vec_traits<V>::template read_element<9>(a);
}

template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type &>::type
    A0(V &a) {
  BOOST_STATIC_ASSERT(0 < vec_traits<V>::dim);
  return vec_traits<V>::template write_element<0>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type &>::type
    A1(V &a) {
  BOOST_STATIC_ASSERT(1 < vec_traits<V>::dim);
  return vec_traits<V>::template write_element<1>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type &>::type
    A2(V &a) {
  BOOST_STATIC_ASSERT(2 < vec_traits<V>::dim);
  return vec_traits<V>::template write_element<2>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type &>::type
    A3(V &a) {
  BOOST_STATIC_ASSERT(3 < vec_traits<V>::dim);
  return vec_traits<V>::template write_element<3>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type &>::type
    A4(V &a) {
  BOOST_STATIC_ASSERT(4 < vec_traits<V>::dim);
  return vec_traits<V>::template write_element<4>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type &>::type
    A5(V &a) {
  BOOST_STATIC_ASSERT(5 < vec_traits<V>::dim);
  return vec_traits<V>::template write_element<5>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type &>::type
    A6(V &a) {
  BOOST_STATIC_ASSERT(6 < vec_traits<V>::dim);
  return vec_traits<V>::template write_element<6>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type &>::type
    A7(V &a) {
  BOOST_STATIC_ASSERT(7 < vec_traits<V>::dim);
  return vec_traits<V>::template write_element<7>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type &>::type
    A8(V &a) {
  BOOST_STATIC_ASSERT(8 < vec_traits<V>::dim);
  return vec_traits<V>::template write_element<8>(a);
}
template <class V>
BOOST_QVM_INLINE_TRIVIAL
    typename enable_if_c<is_vec<V>::value,
                         typename vec_traits<V>::scalar_type &>::type
    A9(V &a) {
  BOOST_STATIC_ASSERT(9 < vec_traits<V>::dim);
  return vec_traits<V>::template write_element<9>(a);
}

////////////////////////////////////////////////
} // namespace qvm
} // namespace boost

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
#include <Eigen/Dense>
#include <Eigen/LU>
#include <Eigen/SVD>
#include <iostream>
#include <chrono>

#include "align/lmkfit_pipe.h"
#include "align/rigid_pipe.h"
#include "align/bsfit_pipe.h"
#include "align/rigid_pipe.h"
#include "io/ply/meshio.h"

namespace
{
using namespace telef::io;
using namespace telef::align;

Eigen::MatrixXf select_rows(
    const Eigen::MatrixXf &mat,
    const std::vector<int> &inds,
    const int rows,
    const Eigen::Matrix4f transformation)
{
  Eigen::MatrixXf result(rows*inds.size(), mat.cols());
  for (size_t i=0; i<inds.size(); i++)
    {
      Eigen::Matrix3Xf pos = mat.block(3*inds[i],0,3,mat.cols());
      Eigen::Matrix3Xf tpos =
        (transformation * pos.colwise().homogeneous()).colwise().hnormalized();
      result.block(rows*i,0,rows,mat.cols()) = tpos.block(0,0,rows,mat.cols());
    }
  return result;
}

boost::shared_ptr<PCANonRigidAlignmentSuite>
step_position(boost::shared_ptr<PCANonRigidAlignmentSuite> in, float reg)
{
  const auto landmark3d = in->fittingSuite->landmark3d;
  Eigen::VectorXf ref = in->pca_model->getReferenceVector() +
    (in->pca_model->getExpressionBasisMatrix()*in->expressionCoeff);
  const auto lmkInds = in->pca_model->getLandmarks();
  const auto shapeRank = in->pca_model->getShapeRank();
  Eigen::MatrixXf shapeMat = in->pca_model->getShapeBasisMatrix();
  Eigen::MatrixXf shapeLmkMat = select_rows(shapeMat, lmkInds, 3, in->transformation);

  Eigen::MatrixXf regMat =
    reg*Eigen::MatrixXf::Identity(shapeRank, shapeRank);

  // Set up RHS
  Eigen::VectorXf b = Eigen::VectorXf::Zero(3*lmkInds.size());
  for(int i=0; i<landmark3d->size(); i++)
    {
      Eigen::VectorXf m = ref.segment(3*lmkInds[i],3);
      Eigen::VectorXf tm = (in->transformation*m.homogeneous()).hnormalized();
      b(3*i+0) = landmark3d->points[i].x - tm(0);
      b(3*i+1) = landmark3d->points[i].y - tm(1);
      b(3*i+2) = landmark3d->points[i].z - tm(2);
    }

  // Set up LHS
  Eigen::MatrixXf A = shapeLmkMat;

  Eigen::MatrixXf ATA = A.transpose()*A + regMat;
  Eigen::VectorXf ATb = A.transpose()*b;

  Eigen::VectorXf x = ATA.householderQr().solve(ATb);

  Eigen::VectorXf idCoeff = x;

  in->shapeCoeff = idCoeff;

  return in;
}

boost::shared_ptr<PCANonRigidAlignmentSuite>
step_shape(boost::shared_ptr<PCANonRigidAlignmentSuite> in)
{
  PCAGPUNonRigidFittingPipe shfit(10, 2500, 0.10, true, true, false);
  auto res = shfit(in);
  in->shapeCoeff = res->shapeCoeff;

  return in;
}

boost::shared_ptr<PCANonRigidAlignmentSuite>
step_expression(boost::shared_ptr<PCANonRigidAlignmentSuite> in)
{
  BsFitPipe bsfit;
  return bsfit(in);
}

boost::shared_ptr<PCANonRigidAlignmentSuite>
step_pose(boost::shared_ptr<PCANonRigidAlignmentSuite> in)
{
  PCARigidFittingPipe posefit;
  return posefit(in);
}
}

namespace telef::align
{

LmkFitPipe::LmkFitPipe(float reg) :
    m_reg(reg),
    m_prevShape()
{}

boost::shared_ptr<PCANonRigidAlignmentSuite>
LmkFitPipe::_processData(boost::shared_ptr<PCANonRigidAlignmentSuite> in)
{
  auto res = in;
  std::chrono::system_clock::time_point start = std::chrono::system_clock::now();
  if(0 == m_prevShape.size())
    {
      res = step_position(res, m_reg);
      Eigen::VectorXf shapeCoeff = res->shapeCoeff;
      for(int i=0; i<10; i++)
        {
            res = step_shape(res);
            //shapeCoeff = 0.8*shapeCoeff + 0.2*res->shapeCoeff;
            shapeCoeff = res->shapeCoeff;
            res = step_expression(res);
            res = step_pose(res);
        }
        m_prevShape = shapeCoeff;
        res->shapeCoeff = shapeCoeff;

        auto exr = in->pca_model->getExpressionRank();
        for(int i=0; i<exr; i++)
          {
            Eigen::VectorXf expressionCoeff = Eigen::VectorXf::Zero(exr);
            expressionCoeff(i) = 1.0f;
            ColorMesh bs = in->pca_model->genMesh(shapeCoeff, expressionCoeff);
            telef::io::ply::writePlyMesh("bs_"+std::to_string(i)+".ply", bs);
          }
    }
  else
    {
      res->shapeCoeff = m_prevShape;
    }
  std::chrono::duration<double> dur = std::chrono::system_clock::now()-start;
  std::cout << "Time (Lmkfit): " <<
    std::chrono::duration_cast<std::chrono::milliseconds>(dur).count() << "ms" << std::endl;
  return res;
}
}

max_stars_repo_name: ycjungSubhuman/Kinect-Face

max_issues_repo_name: ycjungSubhuman/Kinect-Face

max_forks_repo_name: ycjungSubhuman/Kinect-Face


text:
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

#include "stdafx.h"

#include <boost/test/unit_test.hpp>
#include "Common/boost-taef.h"
#include "Common/CryptoTest.h"

using namespace std;
using namespace Common;

namespace Common
{
    class AccountHelperTest
    {
    public:
        static void TraceAccountNames(map<wstring, wstring> const & accountNames);

    protected:
        SecurityTestSetup securityTestSetup_;
    };

    BOOST_FIXTURE_TEST_SUITE2(AccountHelperSuite, AccountHelperTest);

    BOOST_AUTO_TEST_CASE(GeneratePwd)
    {
        const wstring accountName = L"redmond\testAccount";
        const SecureString testSecret(L"test secret");
        SecureString password;
        auto error = AccountHelper::GeneratePasswordForNTLMAuthenticatedUser(
            accountName,
            testSecret,
            password);

        Trace.WriteInfo(TraceType, "errorCode={0}, password='{1}'", error, password);
        VERIFY_IS_TRUE(error.IsSuccess());
        VERIFY_IS_TRUE(!password.IsEmpty());

        SecureString password2;
        error = AccountHelper::GeneratePasswordForNTLMAuthenticatedUser(
            accountName,
            testSecret,
            password2);

        Trace.WriteInfo(TraceType, "errorCode={0}, password2='{1}'", error, password2);
        VERIFY_IS_TRUE(error.IsSuccess());
        VERIFY_ARE_EQUAL2(password, password2);
    }

    BOOST_AUTO_TEST_CASE(GeneratePwdFromX509)
    {
        InstallTestCertInScope testCert;

        const wstring accountName = L"redmond\testAccount";
        const SecureString testSecret(L"test secret");
        SecureString password;
        auto error = AccountHelper::GeneratePasswordForNTLMAuthenticatedUser(
            accountName,
            testSecret,
            X509Default::StoreLocation(),
            X509Default::StoreName(),
            testCert.Thumbprint()->ToStrings().first,
            password);

        Trace.WriteInfo(TraceType, "errorCode={0}, password='{1}'", error, password);
        VERIFY_IS_TRUE(error.IsSuccess());
        VERIFY_IS_TRUE(!password.IsEmpty());

        SecureString password2;
        error = AccountHelper::GeneratePasswordForNTLMAuthenticatedUser(
            accountName,
            testSecret,
            X509Default::StoreLocation(),
            X509Default::StoreName(),
            testCert.Thumbprint()->ToStrings().first,
            password2);

        Trace.WriteInfo(TraceType, "errorCode={0}, password2='{1}'", error, password2);
        VERIFY_IS_TRUE(error.IsSuccess());
        VERIFY_ARE_EQUAL2(password, password2);
    }

    BOOST_AUTO_TEST_CASE(GetAccountNamesFromX509CommonName)
    {
        // Install a certificate with a specified common name
        wstring commonName = wformatString("GetCnAccountNamesTest{0}", Guid::NewGuid());
        wstring subjectName = L"CN=" + commonName;
        InstallTestCertInScope testCert(subjectName);

        wstring actualCommonName;
        auto error = CryptoUtility::GetCertificateCommonName(
            testCert.CertContext(),
            actualCommonName);
        VERIFY_IS_TRUE(error.IsSuccess());
        VERIFY_ARE_EQUAL(testCert.SubjectName(), subjectName);
        VERIFY_ARE_EQUAL(commonName, actualCommonName);

        map<wstring, wstring> accountNames;
        error = AccountHelper::GetAccountNamesWithCertificateCommonName(
            commonName,
            testCert.StoreLocation(),
            testCert.StoreName(),
            true /*generateV1Account*/,
            accountNames);
        VERIFY_IS_TRUE(error.IsSuccess());

        TraceAccountNames(accountNames);

        // Expect one certificate for V1, one for V2, with the thumbprint equal to the testCert's thumbprint
        VERIFY_IS_TRUE(accountNames.size() == 2u);

        Thumbprint::SPtr thumbprint = testCert.Thumbprint();
        wstring expectedThumbprint = wformatString(thumbprint);

        for (auto const & accountName : accountNames)
        {
            wstring actualThumbprint = accountName.second;
            Trace.WriteInfo(TraceType, "GetAccountNamesFromX509CommonName: Verify expectedThumbprint {0} equals actual {1}", expectedThumbprint, actualThumbprint);
            VERIFY_ARE_EQUAL(expectedThumbprint, actualThumbprint);
        }

        //
        // Install one more certificate with the same common name
        //
        InstallTestCertInScope testCert2(subjectName);
        map<wstring, wstring> accountNames2;
        error = AccountHelper::GetAccountNamesWithCertificateCommonName(
            commonName,
            testCert2.StoreLocation(),
            testCert2.StoreName(),
            false,
            accountNames2);
        VERIFY_IS_TRUE(error.IsSuccess());

        TraceAccountNames(accountNames2);

        // V1 accounts are not generated, so expect 2 accounts using the new formats for the 2 certificates.
        VERIFY_IS_TRUE(accountNames2.size() == 2);

        wstring expectedThumbprint2 = wformatString(testCert2.Thumbprint());
        {
            auto it = find_if(accountNames2.begin(), accountNames2.end(),
                [expectedThumbprint](auto const & entry) { return expectedThumbprint == entry.second; });
            VERIFY_IS_TRUE(it != accountNames2.end());
            auto it2 = find_if(accountNames2.begin(), accountNames2.end(),
                [expectedThumbprint2](auto const & entry) { return expectedThumbprint2 == entry.second; });
            VERIFY_IS_TRUE(it2 != accountNames2.end());
        }

        //
        // Install a new certificate with expiration date higher than max supported of 2049. The expiration date is truncated.
        //
        InstallTestCertInScope testCert3(subjectName, nullptr, TimeSpan::FromHours(24 * 365 * 100) /*100 years*/);
        map<wstring, wstring> accountNames3;
        error = AccountHelper::GetAccountNamesWithCertificateCommonName(
            commonName,
            testCert3.StoreLocation(),
            testCert3.StoreName(),
            false /*generateV1Account*/,
            accountNames3);
        VERIFY_IS_TRUE(error.IsSuccess());

        TraceAccountNames(accountNames3);

        // V1 accounts are not generated, so expect 3 accounts using the new formats for the 3 certificates.
        VERIFY_IS_TRUE(accountNames3.size() == 3);

        wstring expectedThumbprint3 = wformatString(testCert3.Thumbprint());
        {
            auto it = find_if(accountNames3.begin(), accountNames3.end(),
                [expectedThumbprint](auto const & entry) { return expectedThumbprint == entry.second; });
            VERIFY_IS_TRUE(it != accountNames3.end());
            auto it2 = find_if(accountNames3.begin(), accountNames3.end(),
                [expectedThumbprint2](auto const & entry) { return expectedThumbprint2 == entry.second; });
            VERIFY_IS_TRUE(it2 != accountNames3.end());
            auto it3 = find_if(accountNames3.begin(), accountNames3.end(),
                [expectedThumbprint3](auto const & entry) { return expectedThumbprint3 == entry.second; });
            VERIFY_IS_TRUE(it3 != accountNames3.end());
        }

        testCert.Uninstall();
        testCert2.Uninstall();
        testCert3.Uninstall();
    }

    BOOST_AUTO_TEST_SUITE_END()
}

void AccountHelperTest::TraceAccountNames(
    map<wstring, wstring> const & accountNames)
{
    wstring traceInfo;
    StringWriter writer(traceInfo);
    for (auto const & entry : accountNames)
    {
        writer.Write("{0} - {1} ", entry.first, entry.second);
    }

    Trace.WriteInfo(TraceType, "GetAccountNamesFromX509CommonName: Found {0} account names: {1}", accountNames.size(), traceInfo);
}

max_stars_repo_name: gridgentoo/ServiceFabricAzure

max_issues_repo_name: gridgentoo/ServiceFabricAzure

max_forks_repo_name: gridgentoo/ServiceFabricAzure


text:
#include <iostream>
#include <boost/any.hpp>

void print(boost::any any) {
	std::cout << boost::any_cast<int>(any) << std::endl;
}

int main() {
	print(2);
}

max_stars_repo_name: taku-xhift/labo

max_issues_repo_name: taku-xhift/labo

max_forks_repo_name: taku-xhift/labo