text:
/*=============================================================================

  NifTK: A software platform for medical image computing.

  Copyright (c) University College London (UCL). All rights reserved.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.

  See LICENSE.txt in the top level directory for details.

=============================================================================*/

#include "mitkOpenCVFileIOUtils.h"
#include <niftkVTKFunctions.h>
#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
#include <fstream>
#include <mitkLogMacros.h>
#include <mitkExceptionMacro.h>
#include <mitkTimeStampsContainer.h>
#include <mitkIOUtil.h>
#include <niftkFileHelper.h>
#include <boost/math/special_functions/fpclassify.hpp>

namespace mitk {

//---------------------------------------------------------------------------
bool CheckIfDirectoryContainsTrackingMatrices(const std::string& directory)
{
  boost::regex timeStampFilter ( "([0-9]{19})(.txt)");
  boost::filesystem::directory_iterator endItr;

  for ( boost::filesystem::directory_iterator it(directory); it != endItr ; ++it)
  {
    if ( boost::filesystem::is_regular_file (it->status()) )
    {
      boost::cmatch what;
      std::string stringthing = it->path().filename().string();
      if ( boost::regex_match( stringthing.c_str(), what, timeStampFilter) )
      {
        return true;
      }
    }
  }
  return false;
}

//---------------------------------------------------------------------------
std::vector<std::string> FindTrackingMatrixDirectories(const std::string& directory)
{
  std::vector<std::string> directories;
  boost::filesystem::recursive_directory_iterator endItr;

  for ( boost::filesystem::recursive_directory_iterator it(directory); it != endItr ; ++it)
  {
    if ( boost::filesystem::is_directory (it->status()) )
    {
      if ( CheckIfDirectoryContainsTrackingMatrices(it->path().string()))
      {
         directories.push_back(it->path().string());
      }
    }
  }
  std::sort (directories.begin(), directories.end());
  return directories;
}

//---------------------------------------------------------------------------
mitk::TimeStampsContainer FindTrackingTimeStamps(std::string directory)
{
  boost::filesystem::directory_iterator endItr;
  boost::regex timeStampFilter ( "([0-9]{19})(.txt)");
  TimeStampsContainer returnStamps;

  for ( boost::filesystem::directory_iterator it(directory);it != endItr ; ++it)
  {
    if ( boost::filesystem::is_regular_file (it->status()) )
    {
      boost::cmatch what;
      std::string stringThing = it->path().filename().string();
      if ( boost::regex_match( stringThing.c_str(), what, timeStampFilter) )
      {
        returnStamps.Insert(boost::lexical_cast<unsigned long long>(it->path().filename().stem().string().c_str()));
      }
    }
  }
  returnStamps.Sort();
  return returnStamps;
}

//---------------------------------------------------------------------------
std::vector<std::string> FindVideoFrameMapFiles(const std::string directory)
{
  boost::filesystem::recursive_directory_iterator endItr;
  boost::regex frameLogFilter ( "(.+)(framemap.log)");
  std::vector<std::string> returnStrings;

  for ( boost::filesystem::recursive_directory_iterator it(directory); it != endItr ; ++it)
  {
    if ( boost::filesystem::is_regular_file (it->status()) )
    {
      boost::cmatch what;
      const std::string stringThing = it->path().filename().string();

      if ( boost::regex_match( stringThing.c_str(), what, frameLogFilter) )
      {
        returnStrings.push_back(it->path().string());
      }
    }
  }
  return returnStrings;
}

//---------------------------------------------------------------------------
bool ReadTrackerMatrix(const std::string& filename, cv::Mat& outputMatrix)
{
  bool isSuccessful = false;
  if (outputMatrix.rows != 4)
  {
    mitkThrow() << "ReadTrackerMatrix: Matrix does not have 4 rows" << std::endl;
  }
  if (outputMatrix.cols != 4)
  {
    mitkThrow() << "ReadTrackerMatrix: Matrix does not have 4 columns" << std::endl;
  }
  if (outputMatrix.type() != CV_64FC1)
  {
    mitkThrow() << "ReadTrackerMatrix: Matrix is not single channel 64 bit float (64FC1) " << std::endl;
  }

  cv::Matx44d matrix;
  isSuccessful = ReadTrackerMatrix(filename, matrix);
  if (isSuccessful)
  {
    for ( int row = 0 ; row < 4 ; row ++ )
    {
      for ( int col = 0 ; col < 4 ; col ++ )
      {
        outputMatrix.at<double>(row,col) = matrix(row, col);
      }
    }
  }
  return isSuccessful;
}

//---------------------------------------------------------------------------
bool ReadTrackerMatrix(const std::string& filename, cv::Matx44d& outputMatrix)
{
  bool isSuccessful = false;
  std::ifstream fin;

  fin.exceptions(std::ifstream::failbit | std::ifstream::badbit);

  try
  {
    fin.open(filename);
  }
  catch ( std::exception e )
  {
    MITK_WARN << "ReadTrackerMatrix: Failed to open matrix file " << filename << " with exception " << e.what() ;
    isSuccessful = false;
    return isSuccessful;
  }

  try
  {
    for ( int row = 0 ; row < 4 ; row ++ )
    {
      for ( int col = 0 ; col < 4 ; col ++ )
      {
        if ( ! ( fin >> outputMatrix(row, col) ) )
        {
          return isSuccessful;
        }
      }
    }
  }
  catch ( std::exception& e )
  {
    MITK_WARN << "ReadTrackerMatrix: Failed to read full file " << filename << " with exception " << e.what() ;
    isSuccessful = false;
    return isSuccessful;
  }
  isSuccessful = true;
  return isSuccessful;
}

//---------------------------------------------------------------------------
bool SaveTrackerMatrix(const std::string& filename, cv::Mat& outputMatrix)
{
  bool isSuccessful = false;
  if (outputMatrix.rows != 4)
  {
    mitkThrow() << "SaveTrackerMatrix: Matrix does not have 4 rows" << std::endl;
  }
  if (outputMatrix.cols != 4)
  {
    mitkThrow() << "SaveTrackerMatrix: Matrix does not have 4 columns" << std::endl;
  }

  cv::Matx44d matrix;
  for ( int row = 0 ; row < 4 ; row ++ )
  {
    for ( int col = 0 ; col < 4 ; col ++ )
    {
      matrix(row, col) = outputMatrix.at<double>(row,col);
    }
  }

  isSuccessful = SaveTrackerMatrix(filename, matrix);
  return isSuccessful;
}

//---------------------------------------------------------------------------
bool SaveTrackerMatrix(const std::string& filename, cv::Matx44d& outputMatrix)
{
  bool isSuccessful = false;
  std::ofstream fout(filename.c_str());
  if ( !fout )
  {
    MITK_WARN << "SaveTrackerMatrix: Failed to open matrix file " << filename;
    return isSuccessful;
  }
  for ( int row = 0 ; row < 4 ; row ++ )
  {
    for ( int col = 0 ; col < 4 ; col ++ )
    {
      fout << outputMatrix(row,col);
      if ( col < 3 )
      {
        fout << " ";
      }
    }
    fout << std::endl;
  }
  fout.close();
  isSuccessful = true;
  return isSuccessful;
}

//---------------------------------------------------------------------------
cv::VideoCapture* InitialiseVideoCapture ( std::string filename , bool ignoreErrors )
{
  cv::VideoCapture* capture = new cv::VideoCapture (filename);
  if ( ! capture )
  {
    mitkThrow() << "Failed to open " << filename << " for video capture" << std::endl;
  }
  //try and get some information about the capture, if these calls fail it may be that
  //the capture may still work but will exhibit undesirable behaviour, see trac 3718
  int videoWidth = capture->get(CV_CAP_PROP_FRAME_WIDTH);
  int videoHeight = capture->get(CV_CAP_PROP_FRAME_HEIGHT);

  if ( videoWidth == 0 || videoHeight == 0 )
  {
    //try a bit harder
    MITK_WARN << "mitk::InitialiseVideo detected errors with video file decoding, trying again with getting a frame.";
    cv::Mat videoImage;
    if ( capture->read(videoImage) )
    {
      videoWidth = videoImage.cols;
      videoHeight = videoImage.rows;
    }
    else
    {
      MITK_WARN << "mitk::InitialiseVideo detected errors with video file decoding, trying again with getting a frame, after hard coding the codec to h264.";
      //try forcing the codec to what we commonly use
      capture->set(CV_CAP_PROP_FOURCC, CV_FOURCC('h','2','6','4'));
      if ( capture->read(videoImage) )
      {
        videoWidth = videoImage.cols;
        videoHeight = videoImage.rows;
      }
    }
    if ( videoWidth == 0 || videoHeight == 0 )
    {
      if ( ! ignoreErrors )
      {
        mitkThrow() << "Problem opening video file for capture. You may want to try rebuilding openCV with ffmpeg support or if available and you're feeling brave over riding video read errors with an ignoreVideoErrors parameter.";
      }
      else
      {
        MITK_WARN << "mitk::InitialiseVideo detected errors with video file decoding but persevering any way as ignoreErrors is set true";
      }
    }
    //try and return to the start
    capture->set(CV_CAP_PROP_POS_FRAMES,0);
  }
  MITK_INFO << "Opened " << filename << " for capture using codec " << capture->get(CV_CAP_PROP_FOURCC);
  return capture;
}

//---------------------------------------------------------------------------
bool TestVideoWriterCodec ( int codec )
{

  cv::VideoWriter* writer = new cv::VideoWriter;
  std::string outfile = niftk::CreateUniqueTempFileName ( "video", ".avi" );
  double framerate = 25.0;
  cv::Size2i size = cv::Size2i (640,480);
  bool isColour = true;
  bool ok = false;
  try
  {
    writer->open (outfile, codec, framerate, size, isColour);

    cv::Mat frame = cv::Mat::eye(size, CV_8UC3);
    for ( unsigned int i = 0 ; i < 2 ; i ++ )
    {
      writer->write(frame);
    }
    writer->release();

    if ( ! (niftk::FileIsEmpty(outfile)))
    {
      //on mac, we get a file size of 128 returned even when the video writer fails, I don't know why
      if ( ! (  niftk::FileSize(outfile) == 128 ) )
      {
        MITK_INFO << "TestVideoWriterCodec OK: " << outfile << " is not empty: " << niftk::FileSize(outfile);
        ok = true;
      }
      else
      {
        MITK_INFO << "TestVideoWriterCodec FAIL: " << outfile << " has size " <<  niftk::FileSize(outfile);
      }
    }
    else
    {
      MITK_INFO << "TestVideoWriterCodec FAIL: " << outfile << " is empty: " << niftk::FileSize(outfile);
    }
  }
  catch (...)
  {
    MITK_INFO << "TestVideoWriterCodec FAIL: Caught an exception: " << outfile;
    ok = false;
  }
  niftk::FileDelete (outfile);
  return ok;
}

//---------------------------------------------------------------------------
cv::VideoWriter* CreateVideoWriter ( std::string filename , double framesPerSecond,
   cv::Size imageSize, int codec, bool isColour )
{

  cv::VideoWriter* writer = new cv::VideoWriter;
  //test the codec
  if ( mitk::TestVideoWriterCodec ( codec ) )
  {
    writer->open (filename, codec, framesPerSecond, imageSize, isColour);
  }
  else
  {
    MITK_INFO << "Failed to write to " << filename << "using codec " << codec << "falling back to MJPEG";
    codec = CV_FOURCC ('M','J','P','G');
    writer->open(filename, codec, framesPerSecond, imageSize, isColour);
  }

  return writer;
}

//---------------------------------------------------------------------------
unsigned long long ExtractTimeStampOrThrow(const std::string& name)
{
  // Parse timestamp.
  boost::regex timeStampFilter ( "([0-9]{19})");
  boost::cmatch what;
  unsigned long long timeStamp = 0;

  if ( boost::regex_match( (niftk::Basename(name)).c_str(), what, timeStampFilter) )
  {
    timeStamp = boost::lexical_cast<unsigned long long>(niftk::Basename(name));

    if (timeStamp ==0)
    {
      std::ostringstream errorMessage;
      errorMessage << "Failed to extract timestamp from name:" << name << std::endl;
      mitkThrow() << errorMessage.str();
    }
  }
  else
  {
    std::ostringstream errorMessage;
    errorMessage << "Could not match timestamp in name:" << name << std::endl;
    mitkThrow() << errorMessage.str();
  }

  return timeStamp;
}

//---------------------------------------------------------------------------
std::vector< std::pair<unsigned long long, cv::Point3d> > LoadTimeStampedTranslations(const std::string& directory)
{
  std::vector< std::pair<unsigned long long, cv::Point3d> > timeStampedTranslations;

  std::vector<std::string> trackingFiles = niftk::GetFilesInDirectory(directory);
  std::sort(trackingFiles.begin(), trackingFiles.end());

  for (unsigned int i = 0; i < trackingFiles.size(); i++)
  {
    std::string fileName = trackingFiles[i];
    if (fileName.empty())
    {
      mitkThrow() << "Can't load empty file name";
    }

    unsigned long long timeStamp = ExtractTimeStampOrThrow(fileName);

    vtkSmartPointer<vtkMatrix4x4> mat = niftk::LoadMatrix4x4FromFile(fileName);

    cv::Point3d translation;
    translation.x = mat->GetElement(0, 3);
    translation.y = mat->GetElement(1, 3);
    translation.z = mat->GetElement(2, 3);

    timeStampedTranslations.push_back(std::pair<unsigned long long, cv::Point3d>(timeStamp, translation));
  }

  return timeStampedTranslations;
}

//---------------------------------------------------------------------------
std::vector< std::pair<unsigned long long, cv::Point3d> > LoadTimeStampedPoints(const std::string& directory)
{
  std::vector< std::pair<unsigned long long, cv::Point3d> > timeStampedPoints;

  std::vector<std::string> pointFiles = niftk::GetFilesInDirectory(directory);
  std::sort(pointFiles.begin(), pointFiles.end());

  for (unsigned int i = 0; i < pointFiles.size(); i++)
  {
    cv::Point3d point;
    std::string fileName = pointFiles[i];

    if(fileName.size() > 0)
    {
      std::ifstream myfile(fileName.c_str());
      if (myfile.is_open())
      {
        point.x = 0;
        point.y = 0;
        point.z = 0;

        myfile >> point.x;
        myfile >> point.y;
        myfile >> point.z;

        if (myfile.bad() || myfile.eof() || myfile.fail())
        {
          std::ostringstream errorMessage;
          errorMessage << "Could not load point file:" << fileName << std::endl;
          mitkThrow() << errorMessage.str();
        }
        myfile.close();
      }
    }

    unsigned long long timeStamp = ExtractTimeStampOrThrow(fileName);
    timeStampedPoints.push_back(std::pair<unsigned long long, cv::Point3d>(timeStamp, point));
  }

  return timeStampedPoints;
}

//---------------------------------------------------------------------------
void LoadTimeStampedPoints(std::vector< std::pair<unsigned long long, cv::Point3d> >& points,
    std::vector <mitk::ProjectedPointPair>& screenPoints, const std::string& fileName)
{
  if (fileName.length() == 0)
  {
    mitkThrow() << "Filename should not be empty." << std::endl;
  }

  std::ifstream myfile(fileName.c_str());
  if (myfile.is_open())
  {
    cv::Point3d point;

    do
    {
      mitk::TimeStampsContainer::TimeStamp timeStamp = 0;
      double x = 0;
      double y = 0;
      double z = 0;
      double lx = 0;
      double ly = 0;
      double rx = 0;
      double ry = 0;

      myfile >> timeStamp;
      myfile >> x;
      myfile >> y;
      myfile >> z;
      myfile >> lx;
      myfile >> ly;
      myfile >> rx;
      myfile >> ry;

      if (timeStamp > 0 && !boost::math::isnan(x) && !boost::math::isnan(y) && !boost::math::isnan(z)) // any other validation?
      {
        point.x = x;
        point.y = y;
        point.z = z;
        points.push_back(std::pair<unsigned long long, cv::Point3d>(timeStamp, point));

        mitk::ProjectedPointPair  pointPair( cv::Point2d(lx,ly), cv::Point2d (rx,ry));
        pointPair.SetTimeStamp(timeStamp);
        screenPoints.push_back ( pointPair );
      }

    }
    while (!myfile.bad() && !myfile.eof() && !myfile.fail());

    myfile.close();
  }
  else
  {
    mitkThrow() << "Failed to open file " << fileName << " for reading." << std::endl;
  }
}
//---------------------------------------------------------------------------
void LoadTimeStampedPoints(std::vector< std::pair<unsigned long long, cv::Point2d> >& points,
     const std::string& fileName)
{
  if (fileName.length() == 0)
  {
    mitkThrow() << "Filename should not be empty." << std::endl;
  }

  std::ifstream myfile(fileName.c_str());
  if (myfile.is_open())
  {
    cv::Point2d point;

    do
    {
      mitk::TimeStampsContainer::TimeStamp timeStamp = 0;
      double x = 0;
      double y = 0;

      myfile >> timeStamp;
      myfile >> x;
      myfile >> y;

      if (timeStamp > 0 && !boost::math::isnan(x) && !boost::math::isnan(y) ) // any other validation?
      {
        point.x = x;
        point.y = y;
        points.push_back(std::pair<unsigned long long, cv::Point2d>(timeStamp, point));
      }

    }
    while (!myfile.bad() && !myfile.eof() && !myfile.fail());
    myfile.close();
  }
  else
  {
    mitkThrow() << "Failed to open file " << fileName << " for reading." << std::endl;
  }
}

//---------------------------------------------------------------------------
void SaveTimeStampedPoints(const std::vector< std::pair<unsigned long long, cv::Point3d> >& points, const std::string& fileName)
{
  if (fileName.length() == 0)
  {
    mitkThrow() << "Filename should not be empty." << std::endl;
  }

  std::ofstream myfile(fileName.c_str());
  if (myfile.is_open())
  {
    for (unsigned long int i = 0; i < points.size(); i++)
    {
      myfile << points[i].first << " " << points[i].second.x << " " << points[i].second.y << " " << points[i].second.z << std::endl;
    }

    myfile.close();
  }
  else
  {
    mitkThrow() << "Failed to open file " << fileName << " for writing." << std::endl;
  }
}
//---------------------------------------------------------------------------
void SavePickedObjects ( const std::vector < mitk::PickedObject > & points, std::ostream& os )
{
  boost::property_tree::ptree pt;
  pt.add ("picked_object_list.version", 1);
  for ( std::vector<PickedObject>::const_iterator it = points.begin() ; it < points.end() ; ++it )
  {
    if ( it->m_Points.size() != 0 )
    {
      boost::property_tree::ptree& node = pt.add("picked_object_list.picked_object", "");
      node.put("id",it->m_Id);
      node.put("frame",it->m_FrameNumber);
      node.put("channel", it->m_Channel);
      node.put("timestamp",it->m_TimeStamp);

      boost::property_tree::ptree& points = node.add("points", "");
      for ( unsigned int i = 0 ; i < it->m_Points.size() ; i ++ )
      {
        boost::property_tree::ptree& coordinate = points.add("coordinate", "");
        std::ostringstream xyzstream;
        xyzstream << it->m_Points[i].x << " " << it->m_Points[i].y << " " << it->m_Points[i].z;
        coordinate.put("<xmlattr>.xyz", xyzstream.str());
      }
      if ( it->m_IsLine )
      {
        node.put("<xmlattr>.line",  true);
      }
      else
      {
        node.put("<xmlattr>.line", false);
      }
    }
  }
  boost::property_tree::xml_writer_settings<std::string> settings(' ',2);
  boost::property_tree::write_xml (os, pt, settings);

}

//---------------------------------------------------------------------------
void LoadPickedObjectsFromDirectory (  std::vector < mitk::PickedObject > & points, const std::string& directory ,
    const double& yScale )
{
  boost::regex timeStampFilter ( "([0-9]{19})(.+)(Points.xml)");
  boost::filesystem::directory_iterator endItr;
  unsigned int fileInCount = 0;

  for ( boost::filesystem::directory_iterator it(directory); it != endItr ; ++it)
  {
    if ( boost::filesystem::is_regular_file (it->status()) )
    {
      boost::cmatch what;
      std::string stringthing = it->path().filename().string();
      if ( boost::regex_match( stringthing.c_str(), what, timeStampFilter) )
      {
        std::ifstream fin ( it->path().string() );
        if ( fin )
        {
          mitk::LoadPickedObjects ( points, fin, yScale );
          ++fileInCount;
          fin.close();
        }
        else
        {
          MITK_ERROR << "Failed to open " << it->path().string();
        }
      }
    }
  }
  MITK_INFO << "Read " << fileInCount << " picked object files from directory " << directory;
}

//---------------------------------------------------------------------------
void LoadPickedObjects (  std::vector < mitk::PickedObject > & points, std::istream& is, const double& yScale )
{
  boost::property_tree::ptree pt;
  try
    {
    boost::property_tree::read_xml (is, pt);
    BOOST_FOREACH ( boost::property_tree::ptree::value_type const& v , pt.get_child("picked_object_list") )
    {
      if ( v.first == "picked_object" )
      {
        mitk::PickedObject po;
        po.m_Id = v.second.get<int> ("id");
        po.m_FrameNumber = v.second.get<unsigned int> ("frame");
        po.m_Channel = v.second.get<std::string> ( "channel" );
        po.m_TimeStamp = v.second.get<unsigned long long > ("timestamp");
        po.m_IsLine = v.second.get<bool> ("<xmlattr>.line", false);
        BOOST_FOREACH ( boost::property_tree::ptree::value_type const& coord , v.second.get_child("points" ) )
        {
           if ( coord.first == "coordinate" )
           {
             std::string xyz = coord.second.get<std::string>("<xmlattr>.xyz", "");
             std::stringstream xyzstream(xyz);
             cv::Point3d point;
             xyzstream >> point.x >> point.y >> point.z;
             point.y *= yScale;
             po.m_Points.push_back(point);
           }
        }
        points.push_back(po);
      }
    }
  }
  catch(const std::runtime_error& e)
  {
    MITK_ERROR << "Caught " << e.what();
  }
}

//-----------------------------------------------------------------------------
std::vector<cv::Mat> LoadMatricesFromDirectory (const std::string& fullDirectoryName)
{
  std::vector<std::string> files = niftk::GetFilesInDirectory(fullDirectoryName);
  std::sort(files.begin(),files.end(),niftk::NumericStringCompare);
  std::vector<cv::Mat> myMatrices;

  if (files.size() > 0)
  {
    for(unsigned int i = 0; i < files.size();i++)
    {
      cv::Mat Matrix = cvCreateMat(4,4,CV_64FC1);
      std::ifstream fin(files[i].c_str());
      for ( int row = 0; row < 4; row ++ )
      {
        for ( int col = 0; col < 4; col ++ )
        {
          fin >> Matrix.at<double>(row,col);
        }
      }
      myMatrices.push_back(Matrix);
    }
  }
  else
  {
    mitkThrow() << "No files found in directory!" << std::endl;
  }

  if (myMatrices.size() == 0)
  {
    mitkThrow() << "No Matrices found in directory!" << std::endl;
  }
  std::cout << "Loaded " << myMatrices.size() << " Matrices from " << fullDirectoryName << std::endl;
  return myMatrices;
}

//-----------------------------------------------------------------------------
std::vector<cv::Mat> LoadOpenCVMatricesFromDirectory (const std::string& fullDirectoryName)
{
  std::vector<std::string> files = niftk::GetFilesInDirectory(fullDirectoryName);
  std::sort(files.begin(),files.end());
  std::vector<cv::Mat> myMatrices;

  if (files.size() > 0)
  {
    for(unsigned int i = 0; i < files.size();i++)
    {
      if ( niftk::FilenameHasPrefixAndExtension(files[i],"",".extrinsic.xml") )
      {
        cv::Mat Extrinsic = (cv::Mat)cvLoadImage(files[i].c_str());
        if (Extrinsic.rows != 4 )
        {
          mitkThrow() << "Failed to load camera intrinsic params" << std::endl;
        }
        else
        {
          myMatrices.push_back(Extrinsic);
          std::cout << "Loaded: " << Extrinsic << std::endl << "From " << files[i] << std::endl;
        }
      }
    }
  }
  else
  {
    mitkThrow() << "No files found in directory!";
  }

  if (myMatrices.size() == 0)
  {
    mitkThrow() << "No Matrices found in directory!";
  }
  std::cout << "Loaded " << myMatrices.size() << " Matrices from " << fullDirectoryName << std::endl;
  return myMatrices;
}

//-----------------------------------------------------------------------------
std::vector<cv::Mat> LoadMatricesFromExtrinsicFile (const std::string& fullFileName)
{

  std::vector<cv::Mat> myMatrices;
  std::ifstream fin(fullFileName.c_str());

  cv::Mat RotationVector = cvCreateMat(3,1,CV_64FC1);
  cv::Mat TranslationVector = cvCreateMat(3,1,CV_64FC1);
  double temp_d[6];
  while ( fin >> temp_d[0] >> temp_d[1] >> temp_d[2] >> temp_d[3] >> temp_d[4] >> temp_d[5] )
  {
    RotationVector.at<double>(0,0) = temp_d[0];
    RotationVector.at<double>(1,0) = temp_d[1];
    RotationVector.at<double>(2,0) = temp_d[2];
    TranslationVector.at<double>(0,0) = temp_d[3];
    TranslationVector.at<double>(1,0) = temp_d[4];
    TranslationVector.at<double>(2,0) = temp_d[5];

    cv::Mat Matrix = cvCreateMat(4,4,CV_64FC1);
    cv::Mat RotationMatrix = cvCreateMat(3,3,CV_64FC1);
    cv::Rodrigues (RotationVector, RotationMatrix);

    for ( int row = 0; row < 3; row ++ )
    {
      for ( int col = 0; col < 3; col ++ )
      {
        Matrix.at<double>(row,col) = RotationMatrix.at<double>(row,col);
      }
    }

    for ( int row = 0; row < 3; row ++ )
    {
      Matrix.at<double>(row,3) = TranslationVector.at<double>(row,0);
    }
    for ( int col = 0; col < 3; col ++ )
    {
      Matrix.at<double>(3,col) = 0.0;
    }
    Matrix.at<double>(3,3) = 1.0;
    myMatrices.push_back(Matrix);
  }
  return myMatrices;
}

//-----------------------------------------------------------------------------
void LoadStereoCameraParametersFromDirectory (const std::string& directory,
  cv::Mat* leftCameraIntrinsic, cv::Mat* leftCameraDistortion,
  cv::Mat* rightCameraIntrinsic, cv::Mat* rightCameraDistortion,
  cv::Mat* rightToLeftRotationMatrix, cv::Mat* rightToLeftTranslationVector,
  cv::Mat* leftCameraToTracker)
{
  boost::filesystem::directory_iterator end_itr;
  boost::regex leftIntrinsicFilter ("(.+)(left.intrinsic.txt)");
  boost::regex rightIntrinsicFilter ("(.+)(right.intrinsic.txt)");
  boost::regex r2lFilter ("(.+)(r2l.txt)");
  boost::regex handeyeFilter ("(.+)(left.handeye.txt)");

  std::vector<std::string> leftIntrinsicFiles;
  std::vector<std::string> rightIntrinsicFiles;
  std::vector<std::string> r2lFiles;
  std::vector<std::string> handeyeFiles;

  for ( boost::filesystem::directory_iterator it(directory);it != end_itr ; ++it)
  {
    if ( boost::filesystem::is_regular_file (it->status()) )
    {
      boost::cmatch what;
      char *  stringthing = new char [512] ;
      strcpy (stringthing,it->path().string().c_str());
      if ( boost::regex_match( stringthing,what,leftIntrinsicFilter) )
      {
        leftIntrinsicFiles.push_back(it->path().string());
      }
      if ( boost::regex_match( stringthing,what,rightIntrinsicFilter) )
      {
        rightIntrinsicFiles.push_back(it->path().string());
      }
      if ( boost::regex_match( stringthing,what,r2lFilter) )
      {
        r2lFiles.push_back(it->path().string());
      }
      if ( boost::regex_match( stringthing,what,handeyeFilter) )
      {
        handeyeFiles.push_back(it->path().string());
      }
    }
  }

  if ( leftIntrinsicFiles.size() != 1 )
  {
    mitkThrow() << "Found the wrong number of left intrinsic files";
  }

  if ( rightIntrinsicFiles.size() != 1 )
  {
    mitkThrow() << "Found the wrong number of right intrinsic files";
  }

  if ( r2lFiles.size() != 1 )
  {
    mitkThrow() << "Found the wrong number of right to left files" << std::endl;
  }

  if ( handeyeFiles.size() != 1 )
  {
    mitkThrow() << "Found the wrong number of handeye files" << std::endl;
  }

  std::cout << "Loading left intrinsics from  " << leftIntrinsicFiles[0] << std::endl;
  LoadCameraIntrinsicsFromPlainText (leftIntrinsicFiles[0],leftCameraIntrinsic, leftCameraDistortion);
  std::cout << "Loading right intrinsics from  " << rightIntrinsicFiles[0] << std::endl;
  LoadCameraIntrinsicsFromPlainText (rightIntrinsicFiles[0],rightCameraIntrinsic, rightCameraDistortion);
  std::cout << "Loading right to left from  " << r2lFiles[0] << std::endl;
  LoadStereoTransformsFromPlainText (r2lFiles[0],rightToLeftRotationMatrix, rightToLeftTranslationVector);
  std::cout << "Loading handeye from  " << handeyeFiles[0] << std::endl;
  LoadHandeyeFromPlainText (handeyeFiles[0],leftCameraToTracker);

}

//-----------------------------------------------------------------------------
void LoadCameraIntrinsicsFromPlainText (const std::string& filename,
    cv::Mat* CameraIntrinsic, cv::Mat* CameraDistortion)
{
  std::ifstream fin(filename.c_str());
  // make sure we throw an exception if parsing fails for any reason.
  fin.exceptions(std::ifstream::failbit | std::ifstream::badbit);

  for ( int row = 0; row < 3; row ++ )
  {
    for ( int col = 0; col < 3; col ++ )
    {
       fin >> CameraIntrinsic->at<double>(row,col);
    }
  }

  if (CameraDistortion != 0)
  {
    // this should work around any row-vs-column vector opencv matrix confusion issues.
    for (int row = 0; row < CameraDistortion->size().height; ++row)
    {
      for (int col = 0; col < CameraDistortion->size().width; ++col)
      {
        fin >> CameraDistortion->at<double>(row, col);
      }
    }
  }
}

//-----------------------------------------------------------------------------
void LoadStereoTransformsFromPlainText (const std::string& filename,
    cv::Mat* rightToLeftRotationMatrix, cv::Mat* rightToLeftTranslationVector)
{
  std::ifstream fin(filename.c_str());
  // make sure we throw an exception if parsing fails for any reason.
  fin.exceptions(std::ifstream::failbit | std::ifstream::badbit);

  for ( int row = 0; row < 3; row ++ )
  {
    for ( int col = 0; col < 3; col ++ )
    {
       fin >> rightToLeftRotationMatrix->at<double>(row,col);
    }
  }

  for (int row = 0; row < rightToLeftTranslationVector->size().height; ++row)
  {
    for (int col = 0; col < rightToLeftTranslationVector->size().width; ++col)
    {
      fin >> rightToLeftTranslationVector->at<double>(row, col);
    }
  }
}

//-----------------------------------------------------------------------------
void LoadHandeyeFromPlainText (const std::string& filename,
    cv::Mat* leftCameraToTracker)
{
  std::ifstream fin(filename.c_str());
  for ( int row = 0; row < 4; row ++ )
  {
    for ( int col = 0; col < 4; col ++ )
    {
       fin >> leftCameraToTracker->at<double>(row,col);
    }
  }

}

//-----------------------------------------------------------------------------
mitk::PickedPointList::Pointer LoadPickedPointListFromDirectoryOfMPSFiles (const std::string& directory,
    unsigned int frameNumber, unsigned long long timestamp, std::string channel,
    cv::Scalar scalar )
{
  boost::regex pointFilter ( "(points.mps)");
  boost::regex lineFilter ( "(line_)([0-9]{2})(.mps)");
  boost::filesystem::directory_iterator endItr;

  std::vector < mitk::PickedObject > pickedObjects;
  for ( boost::filesystem::directory_iterator it(directory); it != endItr ; ++it)
  {
    if ( boost::filesystem::is_regular_file (it->status()) )
    {
      boost::cmatch what;
      std::string filename = it->path().filename().string();

      if (  boost::regex_match( filename.c_str(), what, pointFilter) ||  boost::regex_match( filename.c_str(), what, lineFilter) )
      {
        mitk::PointSet::Pointer pointSet = mitk::IOUtil::LoadPointSet ( it->path().string() );

        mitk::PointSet::DataType* itkPointSet = pointSet->GetPointSet(0);
        mitk::PointSet::PointsContainer* points = itkPointSet->GetPoints();
        mitk::PointSet::PointsIterator pIt;
        mitk::PointSet::PointType point;
        mitk::PointSet::PointIdentifier iD;

        if ( boost::regex_match( filename.c_str(), what, pointFilter) )
        {
          MITK_INFO << "found point file " << filename;

          for (pIt = points->Begin(); pIt != points->End(); ++pIt)
          {
            iD = pIt->Index();
            point = pointSet->GetPoint(iD);
            cv::Point3d cvPoint;

            cvPoint.x = point[0];
            cvPoint.y = point[1];
            cvPoint.z = point[2];

            mitk::PickedObject pickedObject ( channel, frameNumber, timestamp, scalar );
            pickedObject.m_IsLine = false;
            pickedObject.m_Id = iD;
            pickedObject.m_Points.push_back ( cvPoint );

            pickedObjects.push_back ( pickedObject );
          }
        }
        if ( boost::regex_match( filename.c_str(), what, lineFilter) )
        {
          std::string::const_iterator i_char = filename.begin();

          char number[2];
          number[0] = *(i_char + 5);
          number[1] = *(i_char + 6);
          unsigned int lineID = boost::lexical_cast<unsigned int>(number[0]) * 10 + boost::lexical_cast<unsigned int>(number[1]);
          MITK_INFO << "found line file file " << filename << " , with ID " << number[0] << number [1] << " , "  << lineID;
          mitk::PointSet::Pointer pointSet = mitk::IOUtil::LoadPointSet ( it->path().string() );

          mitk::PickedObject pickedObject ( channel, frameNumber, timestamp, scalar );
          pickedObject.m_IsLine = true;
          pickedObject.m_Id = lineID;

          for (pIt = points->Begin(); pIt != points->End(); ++pIt)
          {
            iD = pIt->Index();
            point = pointSet->GetPoint(iD);
            cv::Point3d cvPoint;

            cvPoint.x = point[0];
            cvPoint.y = point[1];
            cvPoint.z = point[2];

            pickedObject.m_Points.push_back ( cvPoint );

          }
          pickedObjects.push_back ( pickedObject );
        }
      }
    }
  }
  mitk::PickedPointList::Pointer returnPickedPoints = mitk::PickedPointList::New();
  returnPickedPoints->SetFrameNumber ( frameNumber );
  returnPickedPoints->SetChannel ( channel );
  returnPickedPoints->SetTimeStamp ( timestamp );
  returnPickedPoints->SetPickedObjects ( pickedObjects );
  return returnPickedPoints;
}

} // end namespace

ext: cxx

max_stars_repo_name: NifTK/NifTK

max_issues_repo_name: NifTK/NifTK

max_forks_repo_name: NifTK/NifTK


text:
#if !defined(_CONNECTIONINFO_H)
#define _CONNECTIONINFO_H

#include <boost/asio.hpp>
#include <ConnectionRemoteEndpoint.hpp>
#include <Connection.hpp>

class ConnectionInfo {

	friend class TCPConnection;
	friend class UDPConnection;

	friend bool operator<(const ConnectionInfo&, const ConnectionInfo&);
	friend bool operator==(const ConnectionInfo&, const ConnectionInfo&);

public:

	ConnectionInfo(const ConnectionInfo& connectioninfo) {
		this->connection_ = connectioninfo.connection_;
	}

	/* Visual Studio 2013 doesn't support default move constructors... */
	ConnectionInfo(ConnectionInfo&& connectioninfo) {
		this->connection_ = connectioninfo.connection_;
	}

	~ConnectionInfo() = default;

	Connection* getConnection() {
		return this->connection_.get();
	}

	size_t hash() const {
		return this->connection_->hash();
	}

private:

	ConnectionInfo(std::shared_ptr<Connection> connection) {
		this->connection_ = connection;
	}

	std::shared_ptr<Connection> connection_;

};

inline bool operator<(const ConnectionInfo& ci1, const ConnectionInfo& ci2) {
	return ci1.connection_->endpoint_less_than(ci2.connection_.get());
}

inline bool operator==(const ConnectionInfo& ci1, const ConnectionInfo& ci2) {
	return ci1.connection_->endpoint_equals(ci2.connection_.get());
}

// Needed for Clang
namespace std {
template<>
struct hash<ConnectionInfo> {
    size_t operator()(const ConnectionInfo &ci) const {
        return ci.hash();
    }
};
}

#endif

ext: hpp


text:
// Copyright (C) 2005-2006 Alain Miniussi <alain.miniussi -at- oca.eu>.

// Use, modification and distribution is subject to 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)

// Message Passing Interface 1.1 -- Section 4. MPI Collectives

/** @file inplace.hpp
 *
 *  This header provides helpers to indicate to MPI collective operation
 *  that a buffer can be use both as an input and output.
 */
#ifndef BOOST_MPI_INPLACE_HPP
#define BOOST_MPI_INPLACE_HPP

#include <boost/mpi/communicator.hpp>
#include <vector>

namespace boost {
namespace mpi {

/**
 *  @brief Wrapper type to explicitly indicate that a input data
 * can be overriden with an output value.
 */
template <typename T> struct inplace_t {
  inplace_t(T &inout) : buffer(inout) {}
  T &buffer;
};

template <typename T> struct inplace_t<T *> {
  inplace_t(T *inout) : buffer(inout) {}
  T *buffer;
};

/**
 *  @brief Wrapp a input data to indicate that it can be overriden
 *  with an ouput value.
 *  @param inout the contributing input value, it will be overriden
 *  with the output value where one is expected. If it is a pointer,
 *  the number of elements will be provided separatly.
 *  @returns The wrapped value or pointer.
 */
template <typename T> inplace_t<T> inplace(T &inout) {
  return inplace_t<T>(inout);
}
/**
 * \overload
 */
template <typename T> inplace_t<T *> inplace(T *inout) {
  return inplace_t<T *>(inout);
}
} // namespace mpi
} // namespace boost

#endif // BOOST_MPI_INPLACE_HPP

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
#include <boost/shared_ptr.hpp>

#include <boost/gil/gil_all.hpp>

#include <boost/gil/extension/io/bmp_io.hpp>
#include <boost/gil/extension/sdl/sdl_wrapper.hpp>

using namespace std;
using namespace boost;
using namespace gil;
using namespace sdl;

int main( int argc, char* argv[] )
{
    typedef sdl_window<> window_t;
    typedef shared_ptr< window_t > window_ptr_t;

    window_ptr_t win( new window_t( 640
                             , 480 ));

    sdl_service ss;
    ss.add_window( win );
    ss.run();

    return 0;
}

ext: cpp

max_stars_repo_name: boost-gil/gil-contributions

max_issues_repo_name: boost-gil/gil-contributions-archive

max_forks_repo_name: boost-gil/gil-contributions-archive


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

#pragma once

#include <atomic>
#include <boost/lockfree/queue.hpp>
#include <boost/lockfree/spsc_queue.hpp>
#include <cstdint>
#include <cstdio>

#include "Log.hpp"
#include "LogMessage.hpp"

#include "Werk/Utility/Action.hpp"

namespace werk
{

/**
 * A log that can do its I/O on a `BackgroundThread`.
 */
class AsyncLog : public Log, public Action
{
public:

	AsyncLog(const std::string &name, const Clock *clock, FILE *file=stdout, Clock *realTimeClock=nullptr) :
		Log(name, clock), Action(name + "_Writer"), _file(file), _realTimeClock(realTimeClock),
		_nextSendSequenceNumber(0), _nextReceiveSequenceNumber(0) { }

	virtual void log(LogLevel level, const char *format, ...) override;
	virtual void logRaw(LogLevel level, const char *rawMessage) override;

	//Background task to write the logs
	virtual void execute() override;

private:
	FILE *_file;
	Clock *_realTimeClock;

	std::atomic<uint64_t> _nextSendSequenceNumber;
	boost::lockfree::queue<LogMessage, boost::lockfree::capacity<4096> > _messages;
	uint64_t _nextReceiveSequenceNumber;
};

}

max_stars_repo_name: AgalmicVentures/Werk

max_issues_repo_name: AgalmicVentures/Werk

max_forks_repo_name: AgalmicVentures/Werk


text:
// main.cc (2015-05-07)
// Yan Gaofeng (yangaofeng@360.cn)
#include <iostream>
#include <boost/function.hpp>

using namespace std;
using namespace boost;

int func1(int i) { return i * 5; }
bool func2(int i, double d) { return (i > d); }

int main()
{
    function1<int, int> f1;
    f1 = &func1;
    cout << f1(10) << endl;

    function2<bool, int, double> f2;
    f2 = &func2;
    cout << f2(10, 1.1) << endl;

    return 0;
}

ext: cc


text:
//
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.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/cppalliance/json
//

#ifndef BOOST_JSON_DEFAULT_RESOURCE_HPP
#define BOOST_JSON_DEFAULT_RESOURCE_HPP

#include <boost/json/detail/config.hpp>
#include <new>

namespace boost {
namespace json {
namespace detail {

/** A simple memory resource that uses operator new and delete.
*/
class default_resource final
    : public memory_resource
{
public:
    void*
    do_allocate(
        std::size_t n,
        std::size_t) override
    {
        return ::operator new(n);
    }

    void
    do_deallocate(
        void* p,
        std::size_t,
        std::size_t) override
    {
        ::operator delete(p);
    }

    bool
    do_is_equal(
        memory_resource const& mr) const noexcept override
    {
        return this == &mr;
    }
};

} // detail
} // json
} // boost

#endif

max_stars_repo_name: rtobar/json

max_issues_repo_name: rtobar/json

max_forks_repo_name: rtobar/json


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

#include "include/Isomorph.hh"
#include "include/IsomorphSpace.hh"
#include "../model/include/Hypergraphe.hh"
#include "../model/include/HyperVertex.hh"
#include "../model/include/HyperEdge.hh"
#include <thread>
#include <boost/graph/isomorphism.hpp>
#include <gecode/search.hh>

Isomorph::Isomorph(const boost::shared_ptr<HypergrapheAbstrait>& ptrHypergrapheAbstraitA,
				   const boost::shared_ptr<HypergrapheAbstrait>& ptrHypergrapheAbstraitB)
				   : _ptrHypergrapheAbstraitA(ptrHypergrapheAbstraitA),
					 _ptrHypergrapheAbstraitB(ptrHypergrapheAbstraitB) {

}

void
Isomorph::runAlgorithme() {

	bool ret = false;

	if( _ptrHypergrapheAbstraitA->getHyperEdgeList().size() != _ptrHypergrapheAbstraitB->getHyperEdgeList().size() ||
		_ptrHypergrapheAbstraitA->getHyperVertexList().size() != _ptrHypergrapheAbstraitB->getHyperVertexList().size()
	  ) {
		_result.setBooleanResult( ret );
		return;
	}

	IsomorphSpace * is = new IsomorphSpace(_ptrHypergrapheAbstraitA, _ptrHypergrapheAbstraitB);
	is->postConstraints();

	unsigned int nbrThreadsSupported( std::thread::hardware_concurrency() );

	if( nbrThreadsSupported <= 0 ) {
		nbrThreadsSupported = 1;
	};

	Gecode::Search::Options opt;
	opt.threads = nbrThreadsSupported;

	Gecode::DFS<IsomorphSpace> ensembleSolution(is, opt);

	if( ensembleSolution.next() ) ret = true;
	else ret = false;

	delete is;

	_result.setBooleanResult( ret );
}

RStructure
Isomorph::getResult() const {
	return _result;
}

Isomorph::~Isomorph() {
}

max_stars_repo_name: ehzawad/HyperGraphLib

max_issues_repo_name: ehzawad/HyperGraphLib

max_forks_repo_name: ehzawad/HyperGraphLib


text:
// kv_dictionary_test_harness.cpp

/*======
This file is part of Percona Server for MongoDB.

Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved.

    Percona Server for MongoDB is free software: you can redistribute
    it and/or modify it under the terms of the GNU Affero General
    Public License, version 3, as published by the Free Software
    Foundation.

    Percona Server for MongoDB 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public
    License along with Percona Server for MongoDB.  If not, see
    <http://www.gnu.org/licenses/>.
======= */

#include <algorithm>
#include <vector>

#include <boost/scoped_ptr.hpp>

#include "mongo/db/storage/kv/dictionary/kv_dictionary.h"
#include "mongo/db/storage/kv/dictionary/kv_dictionary_test_harness.h"
#include "mongo/db/storage/kv/slice.h"
#include "mongo/unittest/unittest.h"

namespace mongo {

    using boost::scoped_ptr;

    TEST( KVDictionary, Simple1 ) {
        scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
        scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() );

        {
            const Slice hi = Slice::of("hi");
            const Slice there = Slice::of("there");

            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                Slice value;
                WriteUnitOfWork uow( opCtx.get() );
                Status status = db->insert( opCtx.get(), hi, there, false );
                ASSERT( status.isOK() );
                status = db->get( opCtx.get(), hi, value );
                ASSERT( status.isOK() );
                status = db->remove( opCtx.get(), hi );
                ASSERT( status.isOK() );
                status = db->get( opCtx.get(), hi, value );
                ASSERT( status.code() == ErrorCodes::NoSuchKey );
                uow.commit();
            }
        }

    }

    TEST( KVDictionary, Simple2 ) {
        scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
        scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() );

        const Slice hi = Slice::of("hi");
        const Slice there = Slice::of("there");
        const Slice apple = Slice::of("apple");
        const Slice bears = Slice::of("bears");

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                WriteUnitOfWork uow( opCtx.get() );
                Status status = db->insert( opCtx.get(), hi, there, false );
                ASSERT( status.isOK() );
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                WriteUnitOfWork uow( opCtx.get() );
                Status status = db->insert( opCtx.get(), apple, bears, false );
                ASSERT( status.isOK() );
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                Slice value;
                Status status = db->get( opCtx.get(), hi, value );
                ASSERT( status.isOK() );
                ASSERT( value.size() == 6 );
                ASSERT( std::string( "there" ) == std::string( value.data() ) );
            }

            {
                Slice value;
                Status status = db->get( opCtx.get(), apple, value );
                ASSERT( status.isOK() );
                ASSERT( value.size() == 6 );
                ASSERT( std::string( "bears" ) == std::string( value.data() ) );
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                WriteUnitOfWork uow( opCtx.get() );
                Status status = db->remove( opCtx.get(), hi );
                ASSERT( status.isOK() );
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                Slice value;
                Status status = db->get( opCtx.get(), hi, value );
                ASSERT( status.code() == ErrorCodes::NoSuchKey );
            }

            {
                Slice value;
                Status status = db->get( opCtx.get(), apple, value );
                ASSERT( status.isOK() );
                ASSERT( value.size() == 6 );
                ASSERT( std::string( "bears" ) == std::string( value.data() ) );
            }

            {
                WriteUnitOfWork uow( opCtx.get() );
                Status status = db->remove( opCtx.get(), apple  );
                ASSERT( status.isOK() );
                uow.commit();
            }

            {
                Slice value;
                Status status = db->get( opCtx.get(), apple, value );
                ASSERT( status.code() == ErrorCodes::NoSuchKey );
            }
        }
    }

    TEST( KVDictionary, InsertSerialGetSerial ) {
        scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
        scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() );

        const unsigned char nKeys = 100;
        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                Slice value;
                WriteUnitOfWork uow( opCtx.get() );
                for (unsigned char i = 0; i < nKeys; i++) {
                    const Slice slice = Slice::of(i);
                    Status status = db->insert( opCtx.get(), slice, slice, false );
                    ASSERT( status.isOK() );
                }
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                for (unsigned char i = 0; i < nKeys; i++) {
                    Slice value;
                    Status status = db->get( opCtx.get(), Slice::of(i), value );
                    ASSERT( status.isOK() );
                    ASSERT( value.as<unsigned char>() == i );
                }
            }
        }

    }

    static int _rng(int i) { return std::rand() % i; }

    TEST( KVDictionary, InsertRandomGetSerial ) {
        scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
        scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() );

        const unsigned char nKeys = 100;
        {
            std::vector<unsigned char> keys;
            for (unsigned char i = 0; i < nKeys; i++) {
                keys.push_back(i);
            }
            std::srand(unsigned(time(0)));
            std::random_shuffle(keys.begin(), keys.end(), _rng);

            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                Slice value;
                WriteUnitOfWork uow( opCtx.get() );
                for (unsigned char i = 0; i < nKeys; i++) {
                    const Slice slice = Slice::of(keys[i]);
                    Status status = db->insert( opCtx.get(), slice, slice, false );
                    ASSERT( status.isOK() );
                }
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                Slice value;
                for (unsigned char i = 0; i < nKeys; i++) {
                    Status status = db->get( opCtx.get(), Slice::of(i), value );
                    ASSERT( status.isOK() );
                    ASSERT( value.as<unsigned char>() == i );
                }
            }
        }

    }

    TEST( KVDictionary, InsertRandomCursor ) {
        scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
        scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() );

        const unsigned char nKeys = 100;
        {
            std::vector<unsigned char> keys;
            for (unsigned char i = 0; i < nKeys; i++) {
                keys.push_back(i);
            }
            std::srand(unsigned(time(0)));
            std::random_shuffle(keys.begin(), keys.end(), _rng);

            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                Slice value;
                WriteUnitOfWork uow( opCtx.get() );
                for (unsigned char i = 0; i < nKeys; i++) {
                    const Slice slice = Slice::of(keys[i]);
                    Status status = db->insert( opCtx.get(), slice, slice, false );
                    ASSERT( status.isOK() );
                }
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                Slice value;
                const int direction = 1;
                unsigned char i = 0;
                for (scoped_ptr<KVDictionary::Cursor> c(db->getCursor(opCtx.get(), direction));
                     c->ok(); c->advance(opCtx.get()), i++) {
                    ASSERT( c->currKey().as<unsigned char>() == i );
                    ASSERT( c->currVal().as<unsigned char>() == i );
                }
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                Slice value;
                const int direction = -1;
                unsigned char i = nKeys - 1;
                for (scoped_ptr<KVDictionary::Cursor> c(db->getCursor(opCtx.get(), direction));
                     c->ok(); c->advance(opCtx.get()), i--) {
                    ASSERT( c->currKey().as<unsigned char>() == i );
                    ASSERT( c->currVal().as<unsigned char>() == i );
                }
            }
        }

    }

    TEST( KVDictionary, InsertDeleteCursor ) {
        scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
        scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() );

        const unsigned char nKeys = 100;
        std::vector<unsigned char> keys;
        for (unsigned char i = 0; i < nKeys; i++) {
            keys.push_back(i);
        }
        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                Slice value;
                WriteUnitOfWork uow( opCtx.get() );
                for (unsigned char i = 0; i < nKeys; i++) {
                    const Slice slice = Slice::of(keys[i]);
                    Status status = db->insert( opCtx.get(), slice, slice, false );
                    ASSERT( status.isOK() );
                }
                uow.commit();
            }
        }

        std::srand(unsigned(time(0)));
        std::random_shuffle(keys.begin(), keys.end(), _rng);

        std::set<unsigned char> remainingKeys;
        std::set<unsigned char> deletedKeys;

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                WriteUnitOfWork uow( opCtx.get() );
                for (unsigned char i = 0; i < nKeys; i++) {
                    unsigned char k = keys[i];
                    if (i < (nKeys / 2)) {
                        Status status = db->remove( opCtx.get(), Slice::of(k) );
                        ASSERT( status.isOK() );
                        deletedKeys.insert(k);
                    } else {
                        remainingKeys.insert(k);
                    }
                }
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                const int direction = 1;
                unsigned char i = 0;
                for (scoped_ptr<KVDictionary::Cursor> c(db->getCursor(opCtx.get(), direction));
                     c->ok(); c->advance(opCtx.get()), i++) {
                    unsigned char k = c->currKey().as<unsigned char>();
                    ASSERT( remainingKeys.count(k) == 1 );
                    ASSERT( deletedKeys.count(k) == 0 );
                    ASSERT( k == c->currVal().as<unsigned char>()  );
                    remainingKeys.erase(k);
                }
                ASSERT( remainingKeys.empty() );
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                for (std::set<unsigned char>::const_iterator it = deletedKeys.begin();
                     it != deletedKeys.end(); it++) {
                    unsigned char k = *it;
                    Slice value;
                    Status status = db->get( opCtx.get(), Slice::of(k), value );
                    ASSERT( status.code() == ErrorCodes::NoSuchKey );
                    ASSERT( value.size() == 0 );
                }
            }
        }

    }

    TEST( KVDictionary, CursorSeekForward ) {
        scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
        scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() );

        const unsigned char nKeys = 101; // even number makes the test magic more complicated
        std::vector<unsigned char> keys;
        for (unsigned char i = 0; i < nKeys; i++) {
            keys.push_back(i);
        }
        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                Slice value;
                WriteUnitOfWork uow( opCtx.get() );
                for (unsigned char i = 0; i < nKeys; i += 2) {
                    const Slice slice = Slice::of(keys[i]);
                    Status status = db->insert( opCtx.get(), slice, slice, false );
                    ASSERT( status.isOK() );
                }
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                scoped_ptr<KVDictionary::Cursor> cursor( db->getCursor( opCtx.get(), 1 ) );
                for (unsigned char i = 0; i < nKeys; i++) {
                    cursor->seek( opCtx.get(), Slice::of(keys[i]) );
                    if ( i % 2 == 0 ) {
                        ASSERT( cursor->currKey().as<unsigned char>() == i );
                    } else if ( i + 1 < nKeys ) {
                        ASSERT( cursor->currKey().as<unsigned char>() == i + 1);
                    }
                }
            }
            {
                scoped_ptr<KVDictionary::Cursor> cursor( db->getCursor( opCtx.get(), -1 ) );
                for (unsigned char i = 1; i < nKeys; i++) {
                    cursor->seek(opCtx.get(), Slice::of(keys[i]));
                    if ( i % 2 == 0 ) {
                        ASSERT( cursor->currKey().as<unsigned char>() == i );
                    } else {
                        ASSERT( cursor->currKey().as<unsigned char>() == i - 1 );
                    }
                }
            }
        }

    }

}

max_stars_repo_name: Tokutek/tokumxse

max_issues_repo_name: Tokutek/tokumxse

max_forks_repo_name: Tokutek/tokumxse


text:
#ifndef IRC_CLIENT_HPP
#define IRC_CLIENT_HPP

#include <deque>
#include <functional>
#include <string>
#include <string_view>
#include <unordered_map>

#include <boost/asio.hpp>

namespace kq::irc
{

namespace asio = boost::asio;

struct settings
{
    std::string host;
    int port;
    std::string nick;
};

class client
{
public:
    using message_handler =
        std::function<
            void(
                std::string_view,
                std::string_view,
                std::string_view
            )
        >;

    client(
        asio::io_context& ctx,
        irc::settings const& settings
    );

    void join(std::string_view channel);

    void say(
        std::string_view receiver,
        std::string_view message
    );

    void send_line(std::string data);

    void register_handler(
        std::string name,
        message_handler handler
    );

    void register_on_connect(
        std::function<void()> handler
    );

    auto const& get_settings() const {
        return settings;
    }

private:
    using tcp = asio::ip::tcp;

    void connect();

    void identify();

    void on_hostname_resolved(
        boost::system::error_code const& error,
        tcp::resolver::results_type results
    );

    void on_connected(
        boost::system::error_code const& error
    );

    void await_new_line();

    void on_new_line(
        std::string const& line
    );

    void handle_message(
        std::string_view who,
        std::string const& type,
        std::string_view where,
        std::string_view message
    );

    void send_raw();

    void handle_write(
        boost::system::error_code const& error,
        std::size_t bytes_read
    );

    asio::io_context& ctx;
    irc::settings settings;
    tcp::socket socket;
    asio::streambuf in_buf;
    std::unordered_map<
        std::string,
        std::vector<message_handler>
    > handlers;
    std::vector<std::function<void()>> on_connect_handlers;

    std::deque<std::string> to_write;
};

}

#endif // IRC_CLIENT_HPP

max_stars_repo_name: KrzaQ/boost-asio-irc-client

max_issues_repo_name: KrzaQ/boost-asio-irc-client

max_forks_repo_name: KrzaQ/boost-asio-irc-client


text:
// Interface to ros_control controllers
// Author: Max Schwarz <max.schwarz@uni-bonn.de>

#include <robotcontrol/hw/roscontrolinterface.h>
#include <robotcontrol/model/robotmodel.h>
#include <dynamic_reconfigure/Reconfigure.h>
#include <boost/make_shared.hpp>
#include <std_msgs/Float64.h>
#include <pluginlib/class_list_macros.h>

namespace robotcontrol
{

ROSControlInterface::ROSJoint::ROSJoint(const std::string& name)
 : velocityMode("joints/" + name + "/velocityMode", false)
 , p_gain("rosControlInterface/joints/" + name + "/PGain", 0.0, 5.0, 1000.0, 100.0)
 , i_gain("rosControlInterface/joints/" + name + "/IGain", 0.0, 0.05, 10.0, 0.0)
 , d_gain("rosControlInterface/joints/" + name + "/DGain", 0.0, 0.05, 10.0, 1.0)
{
	this->name = name;
}

void ROSControlInterface::ROSJoint::handleState(const control_msgs::JointControllerStateConstPtr& state)
{
	feedback.torque = state->command;
}

ROSControlInterface::ROSControlInterface()
 : m_nh("~")
 , m_mechDampingRatio("rosControlInterface/jointMechDampingRatio", 0.0, 0.01, 1.0, 0.25)
{
	m_nh.param("prefix", m_prefix, std::string(""));

	// Get the joint states here as fast as possible (disable Nagle's algorithm)
	m_sub_js = m_nh.subscribe(
		m_prefix + "/joint_states", 50,
		&ROSControlInterface::handleJointState, this,
		ros::TransportHints().tcpNoDelay()
	);

	m_lastReconfig.fromNSec(0);
	m_lastTorque = 0.0;
}

ROSControlInterface::~ROSControlInterface()
{
}

boost::shared_ptr<Joint> ROSControlInterface::createJoint(const std::string& name)
{
	boost::shared_ptr<ROSJoint> joint = boost::make_shared<ROSJoint>(name);

	std::string topic;
	std::string stateTopic;
	std::string pidSrv;
	if(joint->velocityMode())
	{
		topic = m_prefix + "/" + name + "_velocity_controller/command";
		stateTopic = m_prefix + "/" + name + "_velocity_controller/state";
		pidSrv = m_prefix + "/" + name + "_velocity_controller/pid/set_parameters";
	}
	else
	{
		topic = m_prefix + "/" + name + "_position_controller/command";
		stateTopic = m_prefix + "/" + name + "_position_controller/state";
		pidSrv = m_prefix + "/" + name + "_position_controller/pid/set_parameters";
	}

	joint->pub_cmd = m_nh.advertise<std_msgs::Float64>(topic, 1);
	joint->sub_state = m_nh.subscribe(stateTopic, 1, &ROSJoint::handleState, joint.get());
	joint->srv_set_pid = m_nh.serviceClient<dynamic_reconfigure::Reconfigure>(pidSrv, false);

	m_jointMap[name] = joint;

	return joint;
}

bool ROSControlInterface::init(RobotModel* model)
{
	m_model = model;

	initReconfigure();
	m_lastReconfig.fromNSec(0);
	m_lastTorque = 0.0;

	return true;
}

void ROSControlInterface::handleJointState(const sensor_msgs::JointStateConstPtr& js)
{
	m_last_js = js;
}

bool ROSControlInterface::readJointStates()
{
	ros::spinOnce();

	if(!m_last_js)
		return true;

	for(size_t i = 0; i < m_last_js->name.size(); ++i)
	{
		std::map<std::string, boost::shared_ptr<ROSJoint> >::iterator it = m_jointMap.find(m_last_js->name[i]);

		if(it == m_jointMap.end())
			continue;

		const boost::shared_ptr<ROSJoint>& joint = it->second;

		joint->feedback.pos = m_last_js->position[i];
		joint->feedback.stamp = m_last_js->header.stamp;
	}

	m_last_js.reset();

	return true;
}

bool ROSControlInterface::sendJointTargets()
{
	for(size_t i = 0; i < m_model->numJoints(); ++i)
	{
		ROSJoint* joint = rosJoint(i);

		std_msgs::Float64 msg;
		if(joint->velocityMode())
			msg.data = joint->cmd.vel;
		else
			msg.data = joint->cmd.pos;
		joint->pub_cmd.publish(msg);
	}

	return true;
}

void ROSControlInterface::initReconfigure()
{
	dynamic_reconfigure::DoubleParameter dparam;
	dparam.value = 0.0;
	m_reconfig_pid.request.config.doubles.assign(DRO_COUNT, dparam);
	m_reconfig_pid.request.config.doubles[DRO_P_GAIN].name = "p";
	m_reconfig_pid.request.config.doubles[DRO_I_GAIN].name = "i";
	m_reconfig_pid.request.config.doubles[DRO_D_GAIN].name = "d";
}

bool ROSControlInterface::setStiffness(float torque)
{
	// Display a throttled info message that fading is active
	ROS_INFO_THROTTLE(0.4, "Fading is active (%.3f)", torque);

	// Decide whether to actually send something
	ros::Time now = ros::Time::now();
	double elapsedTime = (now - m_lastReconfig).toSec();
	bool actuallySend = (((torque == 0 || torque == 1) && fabs(torque - m_lastTorque) > 0.001) || elapsedTime > 0.3);

	// Update the joint stiffnesses by updating the PID gains of the gazebo joints
	if(actuallySend)
	{
		m_lastReconfig = now;
		m_lastTorque = torque;
		std::map<std::string, boost::shared_ptr<ROSJoint> >::iterator it;
		for(it = m_jointMap.begin(); it != m_jointMap.end(); ++it)
		{
			boost::shared_ptr<ROSJoint>& joint = it->second;
			m_reconfig_pid.request.config.doubles[DRO_P_GAIN].value = joint->p_gain() * torque;
			m_reconfig_pid.request.config.doubles[DRO_I_GAIN].value = joint->i_gain() * torque;
			m_reconfig_pid.request.config.doubles[DRO_D_GAIN].value = joint->d_gain() * (torque + (1 - torque)*m_mechDampingRatio());
			joint->srv_set_pid.call(m_reconfig_pid);
		}
	}

	// Return that we successfully set the stiffness
	return true;
}

void ROSControlInterface::getDiagnostics(DiagnosticsPtr ptr)
{
}

}

PLUGINLIB_EXPORT_CLASS(robotcontrol::ROSControlInterface, robotcontrol::HardwareInterface)


text:
// Copyright (C) 2018 Vicente Botet
//
//  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)

#define BOOST_THREAD_VERSION 4

#include <boost/thread/detail/nullary_function.hpp>
#include <boost/system/detail/error_code.ipp>

int main(int argc, char* argv[])
{
    boost::detail::nullary_function<void ()> f1;
    auto f2 = f1;
}

max_stars_repo_name: Jackarain/tinyrpc

max_issues_repo_name: avplayer/cxxrpc

max_forks_repo_name: avplayer/cxxrpc


text:
/*
	All rights reserved. Use of this source code is governed by the
	3-clause BSD License in LICENSE.txt.
*/
/* This file is formatted with:
    astyle --style=kr --indent=tab=2 --one-line=keep-blocks --brackets=break-closing
*/
#include <nanogui/screen.h>
#include <nanogui/window.h>
#include <nanogui/messagedialog.h>
#include <nanogui/vscrollpanel.h>
#include <nanogui/formhelper.h>
#include <nanogui/theme.h>
#include <nanogui/tabwidget.h>
#include <nanogui/common.h>
#if defined(_WIN32)
#include <windows.h>
#endif
#include <nanogui/opengl.h>
#include <nanogui/glutil.h>

#include <iostream>
#include <fstream>
#include <locale>
#include <string>
#include <vector>
#include <set>
#include "propertymonitor.h"
#include "draghandle.h"
#include "skeleton.h"
#include "panelscreen.h"
#include "editorproject.h"
#include "editorsettings.h"
#include "editorgui.h"
#include "thememanager.h"

#include <libgen.h>
#include <zmq.hpp>
#include <cJSON.h>
#include <MessageEncoding.h>
#include <MessagingInterface.h>
#include <signal.h>
#include <SocketMonitor.h>
#include <ConnectionManager.h>
#include <circularbuffer.h>
#include <symboltable.h>
#include <Logger.h>
#include <DebugExtra.h>

#include <boost/thread.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include "palette.h"
#include "selectablebutton.h"
#include "userwindow.h"
#include "editor.h"
#include "structureswindow.h"
#include "objectwindow.h"
#include "patternswindow.h"
#include "themewindow.h"
#include "propertywindow.h"
#include "helper.h"
#include "screenswindow.h"
#include "toolbar.h"
#include "propertyformhelper.h"
#include "viewswindow.h"
#include "startupwindow.h"
#include "editorwidget.h"
#include "colourhelper.h"

// settings file parser globals
#define __MAIN__ 1
#include "settingslang.h"
SymbolTable globals;
std::list<Structure *>st_structures;
std::map<std::string, Structure *>structures;
extern FILE *st_yyin;
int st_yyparse();
extern int st_yycharno;
extern int st_yylineno;
const char *st_yyfilename = 0;

#include "hmilang.h"
extern std::list<Structure *>hm_structures;
extern std::list<StructureClass *> hm_classes;
extern FILE *yyin;
int yyparse();
extern int yycharno;
extern int yylineno;
const char *yyfilename = 0;
const char *filename = 0;

long full_screen_mode = 0;
int run_only = 0;

extern long collect_history;

int num_errors = 0;
std::list<std::string>error_messages;
std::list<std::string>settings_files;
std::list<std::string> source_files;

using std::cout;
using std::cerr;
using std::endl;
using std::locale;
using nanogui::Vector2i;
using nanogui::Vector2f;
using nanogui::Vector2d;
using nanogui::MatrixXd;
using nanogui::Matrix3d;

namespace po = boost::program_options;

extern const int DEBUG_ALL;
#define DEBUG_BASIC ( 1 & debug)
extern int debug;
extern int saved_debug;
std::string tag_file_name;

extern const char *program_name;

//extern int cw_out;
//extern std::string host;
extern const char *local_commands;
extern ProgramState program_state;
extern struct timeval start;

extern void setup_signals();

std::string stripEscapes(const std::string &s);
//StructureClass *findClass(const std::string &name);

Handle::Mode all_handles[] = {
	Handle::POSITION,
	Handle::RESIZE_TL,
	Handle::RESIZE_T,
	Handle::RESIZE_TR,
	Handle::RESIZE_R,
	Handle::RESIZE_BL,
	Handle::RESIZE_L,
	Handle::RESIZE_BR,
	Handle::RESIZE_B
};

class Proxy {
public:

};

class ItemProxy {
public:
	ItemProxy(PropertyFormHelper *pfh, nanogui::Widget *w) : helper(pfh), item(w) {
		getAll();
	}
	void getAll() {
		if (!item) return;
		x = item->position().x();
		y = item->position().y();
		//tbd
	}
	void setAll() {
		if (!item) return;
		item->setPosition(nanogui::Vector2i(x,y));
		//tbd
	}
	void link(nanogui::Widget *w) {
		item = w;
		getAll();
		helper->clear();
		helper->addVariable("x pos", x);
		helper->addVariable("y pos", y);
	}
	int x;
	int y;
private:
	PropertyFormHelper *helper;
	nanogui::Widget *item;
};

class ScreenProjectButton : public SelectableButton {
	public:
	ScreenProjectButton(const std::string kind, Palette *pal, nanogui::Widget *parent,
			const std::string &caption)
		: SelectableButton(kind, pal, parent, caption), project(0) { }
	void setProject( Structure *s) { project = s; }
	Structure *getScreen() { return project; }
	private:
	Structure *project;
};

bool loadProjectFiles(std::list<std::string> &files_and_directories) {
	using namespace boost::filesystem;

	Structure *settings = EditorSettings::find("EditorSettings");
	if (!settings) settings = EditorSettings::create();
	assert(settings);
	bool base_checked = false;

	std::list<path> files;
	{
		std::list<std::string> errors;
		std::list<std::string>::iterator fd_iter = files_and_directories.begin();
		while (fd_iter != files_and_directories.end()) {
			path fp = (*fd_iter++).c_str();
			if (!exists(fp)) {
				std::stringstream error;
				error << "file/directory does not exist: " << fp.c_str();
				errors.push_back(error.str());
			}
			if (is_regular_file(fp)) {
				std::string ext = boost::filesystem::extension(fp);
			 	if (ext == ".humid") files.push_back(fp);
			}
			else if (is_directory(fp)) {
				if (!base_checked) {
					base_checked = true;
					settings->getProperties().add("project_base", Value(fp.string().c_str(), Value::t_string));
					EditorSettings::setDirty();
					EditorSettings::flush();
				}
				collect_humid_files(fp, files);
			}
		}
		if (!errors.empty()) {
			std::cerr << "Errors during load; cannot continue\n";
			for (const auto & error : errors) { std::cerr << error << "\n"; }
			return false;
		}
	}

	std::string base = "";
	if (settings) base = settings->getProperties().find("project_base").asString();
	assert(boost::filesystem::is_directory(base));
	std::cout << "Project Base: " << base << "\n";

	/* load configuration from files named on the commandline */
	int opened_file = 0;
	std::set<std::string>loaded_files;
	std::list<path>::const_iterator f_iter = files.begin();
	while (f_iter != files.end())
	{
		const char *filename = (*f_iter).string().c_str();
		std::string fname(filename);

		if (filename[0] != '-')
		{
			// strip project path from the file name
			if (base.length() && fname.find(base) == 0) {
				fname = fname.substr(base.length()+1);
				if (loaded_files.count(fname)) {
					continue; // already loaded this one-line
				}
				loaded_files.insert(fname);
			}
			if (exists(filename)) {
				opened_file = 1;
				yyin = fopen(filename, "r");
				if (yyin)
				{
					yylineno = 1;
					yycharno = 1;
					yyfilename = fname.c_str();
					yyparse();
					fclose(yyin);
				}
				else
				{
					std::stringstream ss;
					ss << "## - Error: failed to load project file: " << filename;
					error_messages.push_back(ss.str());
					++num_errors;
				}
			}
		}
		else if (strlen(filename) == 1) /* '-' means stdin */
		{
			opened_file = 1;
			std::cerr << "\nProcessing stdin\n";
			yyfilename = "stdin";
			yyin = stdin;
			yylineno = 1;
			yycharno = 1;
			yyparse();
		}
		f_iter++;
	}
	return true;

}

nanogui::Vector2i fixPositionInWindow(const nanogui::Vector2i &pos, const nanogui::Vector2i &siz, const nanogui::Vector2i &area);

CircularBuffer *UserWindow::getDataBuffer(const std::string item) {
	std::map<std::string, CircularBuffer *>::iterator found = data.find(item);
	if (found == data.end()) return nullptr;
	//	addDataBuffer(item, gui->sampleBufferSize());
	return (*found).second;
}

bool applyWindowSettings(Structure *item, nanogui::Widget *widget) {
	if (widget) {
		nanogui::Screen *screen = dynamic_cast<nanogui::Screen*>(widget);
		if (item->getName() != "Structures") {
			const Value &vw(item->getProperties().find("w"));
			const Value &vh(item->getProperties().find("h"));
			long w, h;
			if (vw.asInteger(w) && vh.asInteger(h)) {
				if (screen) {
					screen->setSize(nanogui::Vector2i(w, h));
					std::cout << item->getName() << " screen size: " << w << "," << h << "\n";
				}
				else {
					widget->setSize(nanogui::Vector2i(w, h));
					widget->setFixedSize(nanogui::Vector2i(w, h));
					std::cout << item->getName() << " size: " << w << "," << h << "\n";
				}
			}
		}
		{
			const Value &vx(item->getProperties().find("x"));
			const Value &vy(item->getProperties().find("y"));
			long x, y;
			if (vx.asInteger(x) && vy.asInteger(y)) {
				if (screen)
					screen->setPosition(nanogui::Vector2i(x, y));
				else {
					nanogui::Vector2i pos(x,y);
					pos = fixPositionInWindow(pos, widget->size(), widget->parent()->size());
					//std::cout << item->getName() << " position: " << pos.x() << "," << pos.y() << "\n";

					widget->setPosition(pos);
				}
			}
		}
		{
			SkeletonWindow *skel = dynamic_cast<SkeletonWindow*>(widget);
			if (skel) {
				const Value &sx(item->getProperties().find("sx")); // position when shrunk
				const Value &sy(item->getProperties().find("sy")); // position when shrunk
				long x, y;
				if (sx.asInteger(x) && sy.asInteger(y)) {
					nanogui::Vector2i pos(x, y);
					pos = fixPositionInWindow(pos, widget->size(), widget->parent()->size());
					//std::cout << item->getName() << " shrunk position: " << pos.x() << "," << pos.y() << "\n";

					skel->setShrunkPos(pos);
				}
			}
		}

		long vis = 0;
		const Value &vis_prop(item->getProperties().find("visible"));
		if (vis_prop != SymbolTable::Null && vis_prop.asInteger(vis))
		{
			if (!vis) std::cout << item->getName() << " is invisible\n";
			EDITOR->gui()->getViewManager().set(item->getName(), vis);
		}
		else
			EDITOR->gui()->getViewManager().set(item->getName(), true);
		return true;
	}
	else return false;
}

bool updateSettingsStructure(const std::string name, nanogui::Widget *widget) {
	if (!widget) return false;
	SkeletonWindow *skel = dynamic_cast<SkeletonWindow *>(widget);

	Structure *s = EditorSettings::find(name);
	if (!s) {
		s = new Structure(nullptr, name, "WINDOW");
		st_structures.push_back(s);
		EditorSettings::setDirty();
	}
	const nanogui::Vector2i &pos(widget->position());
	SymbolTable &properties(s->getProperties());
	if (skel && skel->isShrunk()) {
		properties.add("sx", pos.x());
		properties.add("sy", pos.y());
		skel->setShrunkPos(pos);
	}
	else {
		properties.add("x", pos.x());
		properties.add("y", pos.y());
		properties.add("w", widget->width());
		properties.add("h", widget->height());
	}
	if (!EDITOR->gui()->getViewManager().get(name).visible)
		properties.add("visible", 0);
	return true;
}

StartupWindow *EditorGUI::getStartupWindow() { return w_startup; }
PropertyWindow *EditorGUI::getPropertyWindow() { return w_properties; }
ObjectWindow *EditorGUI::getObjectWindow() { return w_objects; }
ThemeWindow *EditorGUI::getThemeWindow() { return w_theme; }
UserWindow *EditorGUI::getUserWindow() { return w_user; }
Toolbar *EditorGUI::getToolbar() { return w_toolbar; }
StructuresWindow *EditorGUI::getStructuresWindow() { return w_structures; }
PatternsWindow *EditorGUI::getPatternsWindow() { return w_patterns; }
ScreensWindow *EditorGUI::getScreensWindow() { return w_screens; }
ViewsWindow *EditorGUI::getViewsWindow() { return w_views; }

void loadSettingsFiles(std::list<std::string> &files) {

	/* load configuration from files named on the commandline */
	int opened_file = 0;
	std::list<std::string>::iterator f_iter = files.begin();
	while (f_iter != files.end())
	{
		const char *filename = (*f_iter).c_str();
		if (filename[0] != '-')
		{
			opened_file = 1;
			st_yyin = fopen(filename, "r");
			if (st_yyin)
			{
				st_yylineno = 1;
				st_yycharno = 1;
				st_yyfilename = filename;
				st_yyparse();
				fclose(st_yyin);
			}
			else
			{
				std::stringstream ss;
				ss << "## - Error: failed to load config: " << filename;
				error_messages.push_back(ss.str());
				++num_errors;
			}
		}
		else if (strlen(filename) == 1) /* '-' means stdin */
		{
			opened_file = 1;
			std::cerr << "\nProcessing stdin\n";
			st_yyfilename = "stdin";
			st_yyin = stdin;
			st_yylineno = 1;
			st_yycharno = 1;
			st_yyparse();
		}
		f_iter++;
	}
}

int main(int argc, const char ** argv ) {
	char *pn = strdup(argv[0]);
	program_name = strdup(basename(pn));
	free(pn);

	//std:cout << "running from the " << boost::filesystem::current_path().string() << " directory\n";
	//std::string home_path(getenv("HOME"));
	//assert(boost::filesystem::current_path().string().find(home_path) == 0);

	zmq::context_t context;
	MessagingInterface::setContext(&context);

	Logger::instance();
	Logger::instance()->setLevel(Logger::Debug);
	//LogState::instance()->insert(DebugExtra::instance()->DEBUG_CHANNELS);

	int cw_port = 5555;
	std::string hostname;

	setup_signals();

	po::options_description generic("Commandline options");
	generic.add_options()
	("help", "produce help message")
	("debug",po::value<int>(&debug)->default_value(0), "set debug level")
	("host", po::value<std::string>(&hostname)->default_value("localhost"),"remote host (localhost)")
	("cwport",po::value<int>(&cw_port)->default_value(5555), "clockwork port (5555)")
	("tags", po::value<std::string>(&tag_file_name)->default_value(""),"clockwork tag file")
	("full_screen",po::value<long>(&full_screen_mode)->default_value(0), "full screen")
	("run_only", po::value<int>(&run_only)->default_value(0), "run only (default 0)")
	;
	po::options_description hidden("Hidden options");
	hidden.add_options()
    ("source-file", po::value< std::vector<std::string> >(), "source file")
    ;
	po::options_description cmdline_options;
	cmdline_options.add(generic).add(hidden);

	po::positional_options_description p;
	p.add("source-file", -1);

	po::variables_map vm;
	try {
		po::store(po::command_line_parser(argc, argv).
		options(cmdline_options).positional(p).run(), vm);
		po::notify(vm);
	}
	catch (std::exception e) {
		std::cerr << e.what() << "\n";
		exit(2);
	}

	if (vm.count("help")) {
		std::cout << generic << "\n";
		return 1;
	}

	if (vm.count("cwout")) cw_port = vm["cwout"].as<int>();
	if (vm.count("host")) hostname = vm["host"].as<std::string>();
	if (vm.count("debug")) debug = vm["debug"].as<int>();
	if (vm.count("tags")) tag_file_name = vm["tags"].as<std::string>();
	if (vm.count("run_only")) run_only = vm["run_only"].as<int>();
	if (DEBUG_BASIC) std::cout << "Debugging\n";

	std::string home(".");
	char *home_env = nullptr;
	if ( (home_env = getenv("HOME")) != nullptr )
		home = home_env;
	std::string fname(home);
	fname += "/.humidrc";
	settings_files.push_back(fname);
	loadSettingsFiles(settings_files);
	for (auto item : st_structures) {
		std::cout << "Loaded settings item: " << item->getName() << " : " << item->getKind() << "\n";
		structures[item->getName()] = item;
	}
	Structure::loadBuiltins();
	Structure *es = EditorSettings::find("EditorSettings");
	if (!es)
		es = EditorSettings::create();

	gettimeofday(&start, 0);

	try {
		nanogui::init();

		GLFWmonitor* primary = glfwGetPrimaryMonitor();
		const GLFWvidmode* mode = glfwGetVideoMode(primary);
		int widthMM, heightMM;
		glfwGetMonitorPhysicalSize(primary, &widthMM, &heightMM);
		const double dpi = mode->width / (widthMM / 25.4);

		{
			if (vm.count("source-file")) {
				const std::vector<std::string> &files( vm["source-file"].as< std::vector<std::string> >() );
				for (auto s : files) {
					int found = s.rfind("/");
					if (found == s.length()-1) s.erase(found);
					source_files.push_back(s);
				}
				if (!loadProjectFiles(source_files)) {
					return EXIT_FAILURE;
				}
				auto errors = checkStructureClasses();
				if (!errors.empty()) {
					std::cerr << "Errors detected:\n";
					for (const auto error : errors) {
						std::cerr << "    " << error << "\n";
					}
					return EXIT_FAILURE;
				}
				for (auto sc : hm_classes) {
					SymbolTable defaults = default_properties(sc);
					if (!defaults.empty()) {
						std::cout << "found defaults for " << sc->getName() << "\n";
						sc->setDefaults(defaults);
					}
				}
			}
			StructureClass *system_class = findClass("SYSTEM");
			if (!system_class) {
				system_class = new StructureClass("SYSTEM", "");
				hm_classes.push_back(system_class);
			}
			EditorGUI::systemSettings(findStructure("System"));
			if (!EditorGUI::systemSettings()) {
				EditorGUI::systemSettings(system_class->instantiate(nullptr, "System"));
			}

			// if necessary create a project settings structure to store the
			// nominated connection details
			Structure *project_settings = findStructure("ProjectSettings");
			if (!project_settings) {
				StructureClass *psc = new StructureClass("PROJECTSETTINGS", "");
				hm_classes.push_back(psc);
				project_settings = psc->instantiate(nullptr, "ProjectSettings");
				if (cw_port && hostname.length()) { // user supplied a host, setup the required connection object
					Structure *conn = new Structure(nullptr, "Remote", "CONNECTION");
					conn->getProperties().add("host", hostname.c_str());
					conn->getProperties().add("port", cw_port);
					Parameter p(conn->getName());
					p.machine = conn;
					psc->addLocal(p);
				}
				psc->getProperties().add("asset_path", Value(".", Value::t_string));
			}
			if (!project_settings->getStructureDefinition()) {
				project_settings->setStructureDefinition(findClass("PROJECTSETTINGS"));
			}
			auto asset_path = project_settings->getStringProperty("asset_path");
			if (asset_path.empty()) {
				project_settings->getProperties().add("asset_path", Value(".", Value::t_string));
				project_settings->setChanged(true);
			}

			Value full_screen_v = EditorGUI::systemSettings()->getProperties().find("full_screen");
			long full_screen = 1;
			full_screen_v.asInteger(full_screen);
			if (vm.count("full_screen")) full_screen = vm["full_screen"].as<long>();

			long width = mode->width;
			long height = mode->height;
			std::cout << "intial videomode: " << width << "x" << height << "\n";
			{
				const Value width_v = EditorGUI::systemSettings()->getProperties().find("main_window_width");
				const Value height_v = EditorGUI::systemSettings()->getProperties().find("main_window_height");
				width_v.asInteger(width);
				height_v.asInteger(height);
			}
			if (run_only) {
				const Value width_v = EditorGUI::systemSettings()->getProperties().find("panel_width");
				const Value height_v = EditorGUI::systemSettings()->getProperties().find("panel_height");
				width_v.asInteger(width);
				height_v.asInteger(height);
			}

			std::cout << "settings videomode: " << width << "x" << height << " fullscreen:" << full_screen << "\n";

			nanogui::ref<EditorGUI> app = (full_screen)
					? new EditorGUI(width, height, full_screen != 0)
					: new EditorGUI(width, height);
			ThemeManager::instance().setContext(app->nvgContext());
			for (auto settings : Structure::findStructureClasses("THEME")) {
				ThemeManager::instance().addTheme(settings->getName(), ThemeManager::instance().createTheme(settings));
			}
			if (auto main_theme = ThemeManager::instance().findTheme("EditorTheme")) {
				app->setTheme(main_theme);
			}
			else {
				main_theme = ThemeManager::instance().createTheme();
				ThemeManager::instance().addTheme("EditorTheme", main_theme);
				app->setTheme(main_theme);
			}

			app->createWindows();

			if (!EditorGUI::systemSettings()->getStructureDefinition()) {
				EditorGUI::systemSettings()->setStructureDefinition(findClass("SYSTEM"));
			}

			Value remote_screen(EditorGUI::systemSettings()->getProperties().find("remote_screen"));
			if (remote_screen == SymbolTable::Null) {
				EditorGUI::systemSettings()->getProperties().add("remote_screen", Value("P_Screen", Value::t_string));
				remote_screen = EditorGUI::systemSettings()->getProperties().find("remote_screen");
			}
			{
				LinkableProperty *lp = app->findLinkableProperty(remote_screen.asString());
				if (lp) {
					lp->link(app->getUserWindow());
				}
			}
			Value remote_dialog(EditorGUI::systemSettings()->getProperties().find("remote_dialog"));
			if (remote_dialog != SymbolTable::Null) {
				LinkableProperty *lp = app->findLinkableProperty(remote_dialog.asString());
				if (lp) {
					std::cout << "WARNING: should not do this\n";
					//lp->link(app->getUserWindow());
				}
			}
			app->setVisible(true);

			if (!app->getUserWindow()->structure()) {
				const Value &active(EditorGUI::systemSettings()->getProperties().find("active_screen"));
				if (active == SymbolTable::Null) {
					app->getScreensWindow()->selectFirst();
				}
				else {
					app->getScreensWindow()->select(active.asString());
				}
			}

			nanogui::mainloop();
		}

		nanogui::shutdown();
	}
	catch (const std::runtime_error &e) {
		std::string error_msg = std::string("Caught a fatal error: ") + std::string(e.what());
#if defined(_WIN32)
		MessageBoxA(nullptr, error_msg.c_str(), NULL, MB_ICONERROR | MB_OK);
#else
		std::cerr << error_msg << endl;
#endif
		return -1;
	}

	return 0;
}

max_stars_repo_name: latproc/humid

max_issues_repo_name: latproc/humid

max_forks_repo_name: latproc/humid


text:
#include <iostream>
#include <Eigen/Dense>
#include <math.h>
#include <time.h>
#include <fstream>

#define EIGEN_MPL2_ONLY

using namespace std;
using Eigen::MatrixXd;
using Eigen::MatrixXi;

MatrixXi rand_gen(int dim, int max) {
    MatrixXd r = MatrixXd::Random(dim, dim);
    return (r * max).cast<int>();
}

MatrixXi form_array(MatrixXi priv, MatrixXi shared, bool is_client, int max) {
    return ((is_client)? priv * shared : shared * priv)
    .unaryExpr([max](const int x) { return x % max; });
}

MatrixXi rm_det(MatrixXi matrix) {
    matrix.row(0).setZero();
    return matrix;
}

MatrixXi find_shared(MatrixXi priv, MatrixXi recv, bool is_client, int max) {
    return ((is_client)? priv * recv : recv * priv)
    .unaryExpr([max](const int x) { return x % max; });
}

MatrixXi add_det(MatrixXi matrix) {
    matrix.row(0).setOnes();
    return matrix;
}

MatrixXi encrypt_str(MatrixXi matrix, string str) {
    int length = matrix.size() * ceil(float(str.length()) / matrix.size());

    MatrixXi chars;
    chars.resize(1, length);
    chars = MatrixXi::Constant(1, length, 5);

    for (int x = 0; x < str.length(); x++) {
        chars(0, x) = int(str.at(x));
    }

    chars.resize(matrix.rows(), chars.size()/matrix.rows());
    return matrix * chars;
}

string decrypt_str(MatrixXi shared, MatrixXi recv) {
    MatrixXd chars = shared.cast<double>().inverse() * recv.cast<double>();
    chars.resize(1, chars.size());

    string result = "";

    for (int x = 0; x < chars.size(); x++) {
        if (int(chars(0, x)) == 5) { break; }
        result += char(round(chars(0, x)));
    }

    return result;
}

void write_binary(const char* filename, const MatrixXi matrix) {
    ofstream out(filename, ios::out | ios::binary | ios::trunc);
    typename MatrixXi::Index rows=matrix.rows(), cols=matrix.cols();
    out.write((char*) (&rows), sizeof(typename MatrixXi::Index));
    out.write((char*) (&cols), sizeof(typename MatrixXi::Index));
    out.write((char*) matrix.data(), rows * cols * sizeof(typename MatrixXi::Scalar) );
    out.close();
}

void read_binary(const char* filename, MatrixXi& matrix) {
    ifstream in(filename, ios::in | ios::binary);
    typename MatrixXi::Index rows=0, cols=0;
    in.read((char*) (&rows), sizeof(typename MatrixXi::Index));
    in.read((char*) (&cols), sizeof(typename MatrixXi::Index));
    matrix.resize(rows, cols);
    in.read( (char *) matrix.data() , rows * cols * sizeof(typename MatrixXi::Scalar) );
    in.close();
}

int main() {
    MatrixXi a, b, G, Ga, Gb, bGa, aGb, readaGb;
    a = rand_gen(5, 256);
    b = rand_gen(5, 256);
    G = rm_det(rand_gen(5, 256));

    cout << "A:\n" << a << endl;

    Ga = form_array(a, G, true, 255);
    Gb = form_array(b, G, false, 255);

    cout << "Ga:\n" << Ga << endl;

    bGa = add_det(find_shared(b, Ga, false, 255));
    aGb = add_det(find_shared(a, Gb, true, 255));

    cout << "aGb - bGa:\n" << aGb - bGa << endl;

    cout << decrypt_str(bGa, encrypt_str(bGa, "hello world")) << endl;

    string test_string = "";
    for (int x = 0; x < (1048576/8); x++) { test_string += "."; }

    clock_t t = clock();
    decrypt_str(bGa, encrypt_str(aGb, test_string));
    t = clock() - t;

    cout << "Encryption/decryption time for 1mb was " << float(t)/CLOCKS_PER_SEC << "s" << endl;

    write_binary("binary.dat", aGb);
    read_binary("binary.dat", readaGb);

    cout << readaGb - aGb << endl;

    return 0;
}

max_stars_repo_name: FoxNerdSaysMoo/MatricalEncryption

max_issues_repo_name: FoxNerdSaysMoo/MatricalEncryption

max_forks_repo_name: FoxNerdSaysMoo/MatricalEncryption


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2012 Desire Nuentsa Wakam <desire.nuentsa_wakam@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed

#define EIGEN_NO_DEBUG_SMALL_PRODUCT_BLOCKS
#include "sparse.h"
#include <Eigen/SPQRSupport>

template<typename MatrixType,typename DenseMat>
int generate_sparse_rectangular_problem(MatrixType& A, DenseMat& dA, int maxRows = 300, int maxCols = 300)
{
  eigen_assert(maxRows >= maxCols);
  typedef typename MatrixType::Scalar Scalar;
  int rows = internal::random<int>(1,maxRows);
  int cols = internal::random<int>(1,rows);
  double density = (std::max)(8./(rows*cols), 0.01);

  A.resize(rows,rows);
  dA.resize(rows,rows);
  initSparse<Scalar>(density, dA, A,ForceNonZeroDiag);
  A.makeCompressed();
  return rows;
}

template<typename Scalar> void test_spqr_scalar()
{
  typedef SparseMatrix<Scalar,ColMajor> MatrixType;
  MatrixType A;
  Matrix<Scalar,Dynamic,Dynamic> dA;
  typedef Matrix<Scalar,Dynamic,1> DenseVector;
  DenseVector refX,x,b;
  SPQR<MatrixType> solver;
  generate_sparse_rectangular_problem(A,dA);

  Index m = A.rows();
  b = DenseVector::Random(m);
  solver.compute(A);
  if (solver.info() != Success)
  {
    std::cerr << "sparse QR factorization failed\n";
    exit(0);
    return;
  }
  x = solver.solve(b);
  if (solver.info() != Success)
  {
    std::cerr << "sparse QR factorization failed\n";
    exit(0);
    return;
  }
  //Compare with a dense solver
  refX = dA.colPivHouseholderQr().solve(b);
  VERIFY(x.isApprox(refX,test_precision<Scalar>()));
}
void test_spqr_support()
{
  CALL_SUBTEST_1(test_spqr_scalar<double>());
  CALL_SUBTEST_2(test_spqr_scalar<std::complex<double> >());
}

max_stars_repo_name: Achierius/SysSim

max_issues_repo_name: Achierius/SysSim

max_forks_repo_name: Achierius/SysSim