text:
#pragma once
#ifndef ___FAKEFILTER_HPP___
#define ___FAKEFILTER_HPP___

#include "pcmwave.hpp"
#include "socket.hpp"
#include <boost/thread.hpp>
#include <memory>
#include <vector>

class FakeFilter
{
public:
    FakeFilter(){}
    virtual ~FakeFilter(){}

    virtual void reset() = 0;
    virtual PCMWave proc(const PCMWave& src) = 0;
};
using FakeFilterPtr = std::shared_ptr<FakeFilter>;

class FakeFilterSwitchUnit: public Unit
{
private:
    int nowIndex_;
    const std::vector<FakeFilterPtr> filters_;
    boost::mutex mtx_;

public:
    FakeFilterSwitchUnit(std::vector<FakeFilterPtr> filters);
    FakeFilterSwitchUnit(int nowIndex, std::vector<FakeFilterPtr> filters);

    // -1 : through
    void change(int index);

    void inputImpl(const PCMWave& src);
};

#endif

max_stars_repo_name: ushitora-anqou/cables

max_issues_repo_name: ushitora-anqou/cables

max_forks_repo_name: ushitora-anqou/cables


text:
/* adjacency_matrix_test.cpp source file
 *
 * Copyright Cromwell D. Enage 2004
 *
 * 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)
 */

/*
 * Defines the std::ios class and std::cout, its global output instance.
 */
#include <iostream>

/*
 * Defines the boost::property_map class template and the boost::get and
 * boost::put function templates.
 */
#include <boost/property_map.hpp>

/*
 * Defines the boost::graph_traits class template.
 */
#include <boost/graph/graph_traits.hpp>

/*
 * Defines the vertex and edge property tags.
 */
#include <boost/graph/properties.hpp>

/*
 * Defines the boost::adjacency_list class template and its associated
 * non-member function templates.
 */
#include <boost/graph/adjacency_list.hpp>

/*
 * Defines the boost::adjacency_matrix class template and its associated
 * non-member function templates.
 */
#include <boost/graph/adjacency_matrix.hpp>

#include <boost/test/minimal.hpp>

int test_main(int, char*[])
{
    // Use setS to keep out edges in order, so they match the adjacency_matrix.
   typedef boost::adjacency_list<boost::setS, boost::vecS, boost::undirectedS>
           Graph1;
   typedef boost::adjacency_matrix<boost::undirectedS>
           Graph2;
   typedef boost::property_map<Graph1, boost::vertex_index_t>::type
           IndexMap1;
   typedef boost::property_map<Graph2, boost::vertex_index_t>::type
           IndexMap2;

   Graph1 g1(24);
   Graph2 g2(24);

   boost::add_edge(boost::vertex(0, g1), boost::vertex(7, g1), g1);
   boost::add_edge(boost::vertex(0, g2), boost::vertex(7, g2), g2);
   boost::add_edge(boost::vertex(1, g1), boost::vertex(2, g1), g1);
   boost::add_edge(boost::vertex(1, g2), boost::vertex(2, g2), g2);
   boost::add_edge(boost::vertex(2, g1), boost::vertex(10, g1), g1);
   boost::add_edge(boost::vertex(2, g2), boost::vertex(10, g2), g2);
   boost::add_edge(boost::vertex(2, g1), boost::vertex(5, g1), g1);
   boost::add_edge(boost::vertex(2, g2), boost::vertex(5, g2), g2);
   boost::add_edge(boost::vertex(3, g1), boost::vertex(10, g1), g1);
   boost::add_edge(boost::vertex(3, g2), boost::vertex(10, g2), g2);
   boost::add_edge(boost::vertex(3, g1), boost::vertex(0, g1), g1);
   boost::add_edge(boost::vertex(3, g2), boost::vertex(0, g2), g2);
   boost::add_edge(boost::vertex(4, g1), boost::vertex(5, g1), g1);
   boost::add_edge(boost::vertex(4, g2), boost::vertex(5, g2), g2);
   boost::add_edge(boost::vertex(4, g1), boost::vertex(0, g1), g1);
   boost::add_edge(boost::vertex(4, g2), boost::vertex(0, g2), g2);
   boost::add_edge(boost::vertex(5, g1), boost::vertex(14, g1), g1);
   boost::add_edge(boost::vertex(5, g2), boost::vertex(14, g2), g2);
   boost::add_edge(boost::vertex(6, g1), boost::vertex(3, g1), g1);
   boost::add_edge(boost::vertex(6, g2), boost::vertex(3, g2), g2);
   boost::add_edge(boost::vertex(7, g1), boost::vertex(17, g1), g1);
   boost::add_edge(boost::vertex(7, g2), boost::vertex(17, g2), g2);
   boost::add_edge(boost::vertex(7, g1), boost::vertex(11, g1), g1);
   boost::add_edge(boost::vertex(7, g2), boost::vertex(11, g2), g2);
   boost::add_edge(boost::vertex(8, g1), boost::vertex(17, g1), g1);
   boost::add_edge(boost::vertex(8, g2), boost::vertex(17, g2), g2);
   boost::add_edge(boost::vertex(8, g1), boost::vertex(1, g1), g1);
   boost::add_edge(boost::vertex(8, g2), boost::vertex(1, g2), g2);
   boost::add_edge(boost::vertex(9, g1), boost::vertex(11, g1), g1);
   boost::add_edge(boost::vertex(9, g2), boost::vertex(11, g2), g2);
   boost::add_edge(boost::vertex(9, g1), boost::vertex(1, g1), g1);
   boost::add_edge(boost::vertex(9, g2), boost::vertex(1, g2), g2);
   boost::add_edge(boost::vertex(10, g1), boost::vertex(19, g1), g1);
   boost::add_edge(boost::vertex(10, g2), boost::vertex(19, g2), g2);
   boost::add_edge(boost::vertex(10, g1), boost::vertex(15, g1), g1);
   boost::add_edge(boost::vertex(10, g2), boost::vertex(15, g2), g2);
   boost::add_edge(boost::vertex(10, g1), boost::vertex(8, g1), g1);
   boost::add_edge(boost::vertex(10, g2), boost::vertex(8, g2), g2);
   boost::add_edge(boost::vertex(11, g1), boost::vertex(19, g1), g1);
   boost::add_edge(boost::vertex(11, g2), boost::vertex(19, g2), g2);
   boost::add_edge(boost::vertex(11, g1), boost::vertex(15, g1), g1);
   boost::add_edge(boost::vertex(11, g2), boost::vertex(15, g2), g2);
   boost::add_edge(boost::vertex(11, g1), boost::vertex(4, g1), g1);
   boost::add_edge(boost::vertex(11, g2), boost::vertex(4, g2), g2);
   boost::add_edge(boost::vertex(12, g1), boost::vertex(19, g1), g1);
   boost::add_edge(boost::vertex(12, g2), boost::vertex(19, g2), g2);
   boost::add_edge(boost::vertex(12, g1), boost::vertex(8, g1), g1);
   boost::add_edge(boost::vertex(12, g2), boost::vertex(8, g2), g2);
   boost::add_edge(boost::vertex(12, g1), boost::vertex(4, g1), g1);
   boost::add_edge(boost::vertex(12, g2), boost::vertex(4, g2), g2);
   boost::add_edge(boost::vertex(13, g1), boost::vertex(15, g1), g1);
   boost::add_edge(boost::vertex(13, g2), boost::vertex(15, g2), g2);
   boost::add_edge(boost::vertex(13, g1), boost::vertex(8, g1), g1);
   boost::add_edge(boost::vertex(13, g2), boost::vertex(8, g2), g2);
   boost::add_edge(boost::vertex(13, g1), boost::vertex(4, g1), g1);
   boost::add_edge(boost::vertex(13, g2), boost::vertex(4, g2), g2);
   boost::add_edge(boost::vertex(14, g1), boost::vertex(22, g1), g1);
   boost::add_edge(boost::vertex(14, g2), boost::vertex(22, g2), g2);
   boost::add_edge(boost::vertex(14, g1), boost::vertex(12, g1), g1);
   boost::add_edge(boost::vertex(14, g2), boost::vertex(12, g2), g2);
   boost::add_edge(boost::vertex(15, g1), boost::vertex(22, g1), g1);
   boost::add_edge(boost::vertex(15, g2), boost::vertex(22, g2), g2);
   boost::add_edge(boost::vertex(15, g1), boost::vertex(6, g1), g1);
   boost::add_edge(boost::vertex(15, g2), boost::vertex(6, g2), g2);
   boost::add_edge(boost::vertex(16, g1), boost::vertex(12, g1), g1);
   boost::add_edge(boost::vertex(16, g2), boost::vertex(12, g2), g2);
   boost::add_edge(boost::vertex(16, g1), boost::vertex(6, g1), g1);
   boost::add_edge(boost::vertex(16, g2), boost::vertex(6, g2), g2);
   boost::add_edge(boost::vertex(17, g1), boost::vertex(20, g1), g1);
   boost::add_edge(boost::vertex(17, g2), boost::vertex(20, g2), g2);
   boost::add_edge(boost::vertex(18, g1), boost::vertex(9, g1), g1);
   boost::add_edge(boost::vertex(18, g2), boost::vertex(9, g2), g2);
   boost::add_edge(boost::vertex(19, g1), boost::vertex(23, g1), g1);
   boost::add_edge(boost::vertex(19, g2), boost::vertex(23, g2), g2);
   boost::add_edge(boost::vertex(19, g1), boost::vertex(18, g1), g1);
   boost::add_edge(boost::vertex(19, g2), boost::vertex(18, g2), g2);
   boost::add_edge(boost::vertex(20, g1), boost::vertex(23, g1), g1);
   boost::add_edge(boost::vertex(20, g2), boost::vertex(23, g2), g2);
   boost::add_edge(boost::vertex(20, g1), boost::vertex(13, g1), g1);
   boost::add_edge(boost::vertex(20, g2), boost::vertex(13, g2), g2);
   boost::add_edge(boost::vertex(21, g1), boost::vertex(18, g1), g1);
   boost::add_edge(boost::vertex(21, g2), boost::vertex(18, g2), g2);
   boost::add_edge(boost::vertex(21, g1), boost::vertex(13, g1), g1);
   boost::add_edge(boost::vertex(21, g2), boost::vertex(13, g2), g2);
   boost::add_edge(boost::vertex(22, g1), boost::vertex(21, g1), g1);
   boost::add_edge(boost::vertex(22, g2), boost::vertex(21, g2), g2);
   boost::add_edge(boost::vertex(23, g1), boost::vertex(16, g1), g1);
   boost::add_edge(boost::vertex(23, g2), boost::vertex(16, g2), g2);

   IndexMap1 index_map1 = boost::get(boost::vertex_index_t(), g1);
   IndexMap2 index_map2 = boost::get(boost::vertex_index_t(), g2);
   boost::graph_traits<Graph1>::vertex_iterator vi1, vend1;
   boost::graph_traits<Graph2>::vertex_iterator vi2, vend2;

   boost::graph_traits<Graph1>::adjacency_iterator ai1, aend1;
   boost::graph_traits<Graph2>::adjacency_iterator ai2, aend2;

   for (boost::tie(vi1, vend1) = boost::vertices(g1), boost::tie(vi2, vend2) =boost::vertices(g2); vi1 != vend1; ++vi1, ++vi2)
   {
      BOOST_CHECK(boost::get(index_map1, *vi1) == boost::get(index_map2, *vi2));

      for (boost::tie(ai1, aend1) = boost::adjacent_vertices(*vi1, g1),
             boost::tie(ai2, aend2) = boost::adjacent_vertices(*vi2, g2);
           ai1 != aend1;
           ++ai1, ++ai2)
      {
        BOOST_CHECK(boost::get(index_map1, *ai1) == boost::get(index_map2, *ai2));
      }
   }

   boost::graph_traits<Graph1>::out_edge_iterator ei1, eend1;
   boost::graph_traits<Graph2>::out_edge_iterator ei2, eend2;

   for (boost::tie(vi1, vend1) = boost::vertices(g1),
          boost::tie(vi2, vend2) = boost::vertices(g2); vi1 != vend1; ++vi1, ++vi2)
   {
      BOOST_CHECK(boost::get(index_map1, *vi1) == boost::get(index_map2, *vi2));

      for (boost::tie(ei1, eend1) = boost::out_edges(*vi1, g1),
             boost::tie(ei2, eend2) = boost::out_edges(*vi2, g2);
           ei1 != eend1;
           ++ei1, ++ei2)
      {
        BOOST_CHECK(boost::get(index_map1, boost::target(*ei1, g1)) == boost::get(index_map2, boost::target(*ei2, g2)));
      }
   }

   return 0;
}

ext: cpp

max_stars_repo_name: spxuw/RFIM

max_issues_repo_name: spxuw/RFIM

max_forks_repo_name: spxuw/RFIM


text:
/**
 *  Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2012, Willow Garage, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: $
 * @brief This file is an app to convert two folders with tiffs to pointclouds
 * @copyright Copyright (2012) KU Leuven
 * @authors Koen Buys
 **/

#include <iostream>
#include <boost/filesystem.hpp>

#include <pcl/pcl_base.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/console/parse.h>
#include <pcl/console/print.h>
#include <pcl/io/pcd_io.h>

#include <pcl/io/vtk_lib_io.h>
#include <vtkSmartPointer.h>
#include <vtkImageViewer2.h>
#include <vtkTIFFReader.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>

using namespace pcl;

void processAndSave( vtkSmartPointer<vtkImageData>  depth_data,
                     vtkSmartPointer<vtkImageData>  rgb_data,
                     std::string                    time,
                     float                          focal_length,
                     bool                           format,
                     bool                           color,
                     bool                           depth,
                     bool                           use_output_path,
                     std::string                    output_path)
{
  // Retrieve the entries from the image data and copy them into the output RGB cloud
  int rgb_components = rgb_data->GetNumberOfScalarComponents();
  //std::cout << "RGB comp:" << rgb_components << std::endl;

  if(rgb_components != 3)
  {
    std::cout << "RGB image doesn't have 3 components, proceed with next image" << std::endl;
    return;
  }

  int rgb_dimensions[3];
  rgb_data->GetDimensions (rgb_dimensions);
  //std::cout << "RGB dim1: " << rgb_dimensions[0] << " dim2: " << rgb_dimensions[1] << " dim3: " << rgb_dimensions[2] << std::endl;

  // Retrieve the entries from the image data and copy them into the output RGB cloud
  int depth_components = depth_data->GetNumberOfScalarComponents();
  //std::cout << "Depth comp:" << depth_components << std::endl;

  if(depth_components != 1)
  {
    std::cout << "Depth image doesn't have a single component, proceed with next image" << std::endl;
    return;
  }

  int depth_dimensions[3];
  depth_data->GetDimensions (depth_dimensions);
  //std::cout << "Depth dim1: " << depth_dimensions[0] << " dim2: " << depth_dimensions[1] << " dim3: " << depth_dimensions[2] << std::endl;

  // Check if dimensions fit
  if(rgb_dimensions[0] != depth_dimensions[0] || rgb_dimensions[1] != depth_dimensions[1] || rgb_dimensions[2] != depth_dimensions[2])
  {
    std::cout << "RGB and Depth dimensions don't match, proceed with next image" << std::endl;
    return;
  }

  // Now let's create the clouds
  PointCloud<RGB>          pc_image;
  PointCloud<Intensity>    pc_depth;
  PointCloud<PointXYZRGBA> pc_xyzrgba;

  pc_image.width = pc_depth.width = pc_xyzrgba.width = rgb_dimensions[0];
  pc_image.height = pc_depth.height = pc_xyzrgba.height = rgb_dimensions[1];

  float constant = 1.0f / focal_length;
  float bad_point = std::numeric_limits<float>::quiet_NaN ();

  for(int v = 0; v < rgb_dimensions[1]; v++)
  {
    for(int u = 0; u < rgb_dimensions[0]; u++)
    {
      RGB           color_point;
      Intensity     depth_point;
      PointXYZRGBA  xyzrgba_point;

      color_point.r = xyzrgba_point.r = static_cast<uint8_t> (rgb_data->GetScalarComponentAsFloat(u,v,0,0));
      color_point.g = xyzrgba_point.g = static_cast<uint8_t> (rgb_data->GetScalarComponentAsFloat(u,v,0,1));
      color_point.b = xyzrgba_point.b = static_cast<uint8_t> (rgb_data->GetScalarComponentAsFloat(u,v,0,2));
      xyzrgba_point.a = 0;

      pc_image.points.push_back(color_point);
      pc_depth.points.push_back(depth_point);

      float d =  depth_data->GetScalarComponentAsFloat(u,v,0,0);
      depth_point.intensity = d;

      if(d != 0 && !pcl_isnan(d) && !pcl_isnan(d))
      {
        xyzrgba_point.z = d * 0.001f;
        xyzrgba_point.x = static_cast<float> (u) * d * 0.001f * constant;
        xyzrgba_point.y = static_cast<float> (v) * d * 0.001f * constant;
      }
      else
      {
        xyzrgba_point.z = xyzrgba_point.x = xyzrgba_point.y = bad_point;
      }
      pc_xyzrgba.points.push_back(xyzrgba_point);

    } // for u
  } // for v

  std::stringstream ss;

  if(depth)
  {
    if(use_output_path)
      ss << output_path << "/frame_" << time << "_depth.pcd";
    else
      ss << "frame_" << time << "_depth.pcd";
    pcl::io::savePCDFile (ss.str(), pc_depth, format);
    ss.str(""); //empty
  }

  if(color)
  {
    if(use_output_path)
      ss << output_path << "/frame_" << time << "_color.pcd";
    else
      ss << "frame_" << time << "_color.pcd";
    pcl::io::savePCDFile (ss.str(), pc_image, format);
    ss.str(""); //empty
  }

  if(use_output_path)
    ss << output_path << "/frame_" << time << "_xyzrgba.pcd";
  else
    ss << "frame_" << time << "_xyzrgba.pcd";
  pcl::io::savePCDFile (ss.str(), pc_xyzrgba, format);

  std::cout << "Saved " << time << " to pcd" << std::endl;
  return;
}

void print_usage(void)
{
  PCL_INFO("usage: convert -rgb <rgb_path> -depth <depth_path> -out <output_path> options\n");
  PCL_INFO("This program converts rgb and depth tiff files to pcd files");
  PCL_INFO("Options:\n");
  PCL_INFO("\t -v \t Set verbose output\n");
  PCL_INFO("\t -c \t Create color pcd output\n");
  PCL_INFO("\t -d \t Create depth output\n");
  PCL_INFO("\t -b \t Set to save pcd binary, otherwise ascii\n");
  PCL_INFO("\t -f \t Focal length, default 525\n");
  PCL_INFO("\t -h \t This help\n");
}

int main(int argc, char ** argv)
{
  // TODO: adjust these
  if(argc < 3)
  {
    print_usage();
    exit(-1);
  }

  bool verbose = 0;
  pcl::console::parse_argument (argc, argv, "-v", verbose);

  bool format = 0;
  pcl::console::parse_argument (argc, argv, "-b", format);

  bool color = 0;
  pcl::console::parse_argument (argc, argv, "-c", format);

  bool depth = 0;
  pcl::console::parse_argument (argc, argv, "-d", format);

  std::string rgb_path_, depth_path_, output_path_;

  if(pcl::console::parse_argument (argc, argv, "-rgb", rgb_path_) == 0)
  {
    PCL_ERROR("No RGB Path given\n");
    print_usage();
    exit(-1);
  }
  if(pcl::console::parse_argument (argc, argv, "-depth", depth_path_) == 0)
  {
    PCL_ERROR("No Depth Path given\n");
    print_usage();
    exit(-1);
  }
  bool use_output_path = false;
  if(pcl::console::parse_argument (argc, argv, "-out", output_path_) == 0)
  {
    PCL_ERROR("No Output Path given\n");
    print_usage();
    exit(-1);
  }
  else
  {
    use_output_path = true;
  }

  float focal_length = 525.0;
  pcl::console::parse_argument (argc, argv, "-f", focal_length);

  if(verbose)
    PCL_INFO ("Creating RGB Tiff List\n");

  std::vector<std::string> tiff_rgb_files;
  std::vector<boost::filesystem::path> tiff_rgb_paths;
  boost::filesystem::directory_iterator end_itr;

  if(boost::filesystem::is_directory(rgb_path_))
  {
    for (boost::filesystem::directory_iterator itr(rgb_path_); itr != end_itr; ++itr)
    {
      std::string ext = itr->path().extension().string();
      if(ext.compare(".tiff") == 0)
      {
        tiff_rgb_files.push_back (itr->path ().string ());
        tiff_rgb_paths.push_back (itr->path ());
      }
      else
      {
        // Found non tiff file
      }

      if(verbose)
      {
        std::cout << "Extension" << itr->path().extension() << std::endl;
        std::cout << "Filename" << itr->path().filename() << std::endl;
        //std::cout << "Root_dir" << itr->path().root_directory() << std::endl;
        //std::cout << "Root_path" << itr->path().root_path() << std::endl;
        //std::cout << "Root_name" << itr->path().root_name() << std::endl;
        //std::cout << "rel_path" << itr->path().relative_path() << std::endl;
        //std::cout << "parent_path" << itr->path().parent_path() << std::endl;
      }
    }
  }
  else
  {
    PCL_ERROR("RGB path is not a directory\n");
    exit(-1);
  }

  sort (tiff_rgb_files.begin (), tiff_rgb_files.end ());
  sort (tiff_rgb_paths.begin (), tiff_rgb_paths.end ());

  if(verbose)
    PCL_INFO ("Creating Depth Tiff List\n");

  std::vector<std::string> tiff_depth_files;
  std::vector<boost::filesystem::path> tiff_depth_paths;

  if(boost::filesystem::is_directory(depth_path_))
  {
    for (boost::filesystem::directory_iterator itr(depth_path_); itr != end_itr; ++itr)
    {
      std::string ext = itr->path().extension().string();
      if(ext.compare(".tiff") == 0)
      {
        tiff_depth_files.push_back (itr->path ().string ());
        tiff_depth_paths.push_back (itr->path ());
      }
      else
      {
        // Found non tiff file
      }

      if(verbose)
      {
        std::cout << "Extension" << itr->path().extension() << std::endl;
        std::cout << "Filename" << itr->path().filename() << std::endl;
      }
    }
  }
  else
  {
    PCL_ERROR("Depth path is not a directory\n");
    exit(-1);
  }

  sort (tiff_depth_files.begin (), tiff_depth_files.end ());
  sort (tiff_depth_paths.begin (), tiff_depth_paths.end ());

  for(unsigned int i=0; i<tiff_rgb_paths.size(); i++)
  {
    // Load the input file
    vtkSmartPointer<vtkImageData> rgb_data;
    vtkSmartPointer<vtkTIFFReader> reader = vtkSmartPointer<vtkTIFFReader>::New ();

    // Check if the file is correct
    int ret = reader->CanReadFile (tiff_rgb_files[i].c_str());
    // 0 can't read the file, 1 can't prove it
    if(ret == 0 || ret == 1)
    {
      std::cout << "We have a broken tiff file: " << tiff_rgb_files[i] << std::endl;
      continue;
    }
    // 2 can read it, 3 I'm the correct reader
    if(ret == 2 || ret == 3)
    {
      reader->SetFileName (tiff_rgb_files[i].c_str());
      reader->Update ();
      rgb_data = reader->GetOutput ();

      std::string rgb_filename = tiff_rgb_paths[i].filename().string();
      std::string rgb_time = rgb_filename.substr(6,22);

      //std::cout << "RGB Time: " << rgb_time << std::endl;

      // Try to read the depth file
      int found = 0; // indicates if a corresponding depth file was found
      // Find the correct file name
      for(size_t j = 0; j < tiff_depth_paths.size(); j++)
      {
        std::string depth_filename = tiff_depth_paths[i].filename().string();
        std::string depth_time = depth_filename.substr(6,22);

        if(depth_time.compare(rgb_time) == 0) // found the correct depth
        {
          //std::cout << "Depth Time: " << depth_time << std::endl;
          found = 1;

          // Process here!

          vtkSmartPointer<vtkImageData> depth_data;
          vtkSmartPointer<vtkTIFFReader> depth_reader = vtkSmartPointer<vtkTIFFReader>::New ();

          // Check if the file is correct
          int read = depth_reader->CanReadFile (tiff_depth_files[j].c_str());
          // 0 can't read the file, 1 can't prove it
          if(read == 0 || read == 1)
          {
            std::cout << "We have a broken tiff file: " << tiff_depth_files[j] << std::endl;
            continue;
          }
          // 2 can read it, 3 I'm the correct reader
          if(read == 2 || read == 3)
          {
            depth_reader->SetFileName (tiff_depth_files[j].c_str());
            depth_reader->Update ();
            depth_data = depth_reader->GetOutput ();

            processAndSave(depth_data, rgb_data, depth_time, focal_length, format, color, depth, use_output_path, output_path_);
          }

          // TODO: remove this depth entry from vector before break > speed up search time
          break;
        }
        else
        {
          // Continue with the next depth entry
          continue;
        }
        if(found == 0)
        {
          std::cout << "We couldn't find a Depth file for this RGB image" << std::endl;
        }
      } //for depth_paths
    } //if ret = 2 or 3
  } //for rgb paths
  return 0;
}


text:
#include <boost/test/unit_test.hpp>

#include "kllvm/ast/AST.h"

using namespace kllvm;

BOOST_AUTO_TEST_SUITE(ASTTest)

BOOST_AUTO_TEST_CASE(substitute) {
  KORESort::substitution subst;
  auto var = KORESortVariable::Create("foo");
  auto composite = KORECompositeSort::Create("bar");
  auto poly = KORECompositeSort::Create("baz");
  poly->addArgument(var);
  subst[*var] = composite;
  BOOST_CHECK_EQUAL(var->substitute(subst), composite);
  BOOST_CHECK_EQUAL(composite->substitute(subst), composite);
  auto expected = KORECompositeSort::Create("baz");
  expected->addArgument(composite);
  BOOST_CHECK_EQUAL(*poly->substitute(subst), *expected);
}

BOOST_AUTO_TEST_CASE(instantiate) {
  auto decl = KORESymbolDeclaration::Create("sym");
  auto var = KORESortVariable::Create("foo");
  decl->addObjectSortVariable(var);
  auto poly = KORECompositeSort::Create("baz");
  auto composite = KORECompositeSort::Create("bar");
  poly->addArgument(var);
  decl->getSymbol()->addArgument(poly);
  decl->getSymbol()->addArgument(composite);
  decl->getSymbol()->addSort(poly);
  auto sym = KORESymbol::Create("sym");
  sym->addFormalArgument(composite);
  sym->instantiateSymbol(decl.get());
  auto expected = KORECompositeSort::Create("baz");
  expected->addArgument(composite);
  BOOST_CHECK_EQUAL(*sym->getSort(), *expected);
  BOOST_CHECK_EQUAL(sym->getArguments().size(), 2);
  BOOST_CHECK_EQUAL(*sym->getArguments()[0], *expected);
  BOOST_CHECK_EQUAL(*sym->getArguments()[1], *composite);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: Baltoli/llvm-backend

max_issues_repo_name: Baltoli/llvm-backend

max_forks_repo_name: runtimeverification/llvm-backend


text:
#include <GL/glew.h>
#include "SimWindow.h"
#include "dart/external/lodepng/lodepng.h"
#include "SkeletonBuilder.h"
#include "Utils.h"
#include "Character.h"
#include <algorithm>
#include <fstream>
#include <boost/filesystem.hpp>
#include <GL/glut.h>
using namespace GUI;
using namespace dart::simulation;
using namespace dart::dynamics;

SimWindow::
SimWindow()
	:GLUTWindow(),mTrackCamera(false),mIsAuto(false),mIsCapture(false)
	,mShowRef(true),mShowCharacter(true)
{
	mWorld = std::make_shared<dart::simulation::World>();
	mCurFrame = 0;
	mDisplayTimeout = 33;
}

SimWindow::
SimWindow(std::string filename)
	:GLUTWindow(),mTrackCamera(false),mIsAuto(false),mIsCapture(false)
	,mShowRef(true),mShowCharacter(true),mSkeletonDrawType(0)
{
	this->mWorld = std::make_shared<dart::simulation::World>();

	std::ifstream ifs(filename);
	if(!ifs.is_open()){
		std::cout << "File doesn't exist" << std::endl;
		exit(0);
	}

	// read a number of characters
	std::string line;

	// read skeleton file
	ICC::Character* character;
	std::string skelfilename;

	std::getline(ifs, skelfilename);
	SkeletonPtr skel = ICC::SkeletonBuilder::buildFromFile(skelfilename);
	int nDof = skel->getNumDofs();
	this->mWorld->addSkeleton(skel);

	// for reference motion
	SkeletonPtr refSkel = skel->cloneSkeleton("Ref");
	this->mWorld->addSkeleton(refSkel);
	// character = new ICC::Humanoid(skelfilename);

	// SkeletonPtr modSkel = skel->clone("Mod");
	// mWorld->addSkeleton(modSkel);

	ICC::Utils::setSkeletonColor(skel, Eigen::Vector4d(0.73, 0.73, 0.78, 1.0));
	ICC::Utils::setSkeletonColor(refSkel, Eigen::Vector4d(235./255., 87./255., 87./255., 0.9));
	// ICC::SetSkeletonColor(modSkel, Eigen::Vector4d(93./255., 176./255., 89./255., 0.9));

	// read frame number
	std::getline(ifs, line);
	this->mTotalFrame = atoi(line.c_str());
	std::cout << "total frame : " << this->mTotalFrame << std::endl;

	// read joint angles per frame
	for(int i = 0; i < this->mTotalFrame; i++){
		std::getline(ifs, line);
		Eigen::VectorXd record = ICC::Utils::stringToVectorXd(line, nDof);
		this->mRecords.push_back(record);
	}

	for(int i = 0; i < this->mTotalFrame; i++){
		std::getline(ifs, line);
		Eigen::VectorXd ref = ICC::Utils::stringToVectorXd(line, nDof);
		this->mRefRecords.push_back(ref);
	}

	for(int i = 0; i < this->mTotalFrame; i++){
		std::getline(ifs, line);
		Eigen::VectorXd ref = ICC::Utils::stringToVectorXd(line, 3);
		this->mTargetRecords.push_back(ref);
	}

	mDisplayTimeout = 33;
	mCurFrame = 0;

	this->setFrame(this->mCurFrame);

	ifs.close();
}

void
SimWindow::
setFrame(int n)
{
	if( n < 0 || n >= this->mTotalFrame )
	{
		std::cout << "Frame exceeds limits" << std::endl;
		return;
	}

	SkeletonPtr skel = this->mWorld->getSkeleton("Humanoid");
	Eigen::VectorXd pos = this->mRecords[n];
	// pos.setZero();
	// pos[4] = 1.0;
	skel->setPositions(pos);

	skel = this->mWorld->getSkeleton("Ref");
	pos = this->mRefRecords[n];
	skel->setPositions(pos);

	if(this->mTrackCamera){
		Eigen::Vector3d com = this->mWorld->getSkeleton("Humanoid")->getRootBodyNode()->getCOM();
		Eigen::Isometry3d transform = this->mWorld->getSkeleton("Humanoid")->getRootBodyNode()->getTransform();
		com[1] = 0.8;

		Eigen::Vector3d camera_pos;
		// Eigen::Quaterniond t(Eigen::AngleAxisd(transform.linear()));
		// transform.linear() = ICC::GetYRotation(t).toRotationMatrix();
		camera_pos << -3, 1, 1.5;
		// camera_pos = transform * camera_pos;
		camera_pos = camera_pos + com;
		camera_pos[1] = 2;

		// mCamera->SetCamera(com, camera_pos, Eigen::Vector3d::UnitY());
		mCamera->setCenter(com);
	}

}
void
SimWindow::
nextFrame()
{
	this->mCurFrame+=1;
	this->mCurFrame %= this->mTotalFrame;
	this->setFrame(this->mCurFrame);
}
void
SimWindow::
nextFrameRealTime()
{
	int count = 1;
	this->mCurFrame += count;
	this->mCurFrame %= this->mTotalFrame;
	this->setFrame(this->mCurFrame);
}
void
SimWindow::
prevFrame()
{
	this->mCurFrame-=1;
	if( this->mCurFrame < 0 ) this->mCurFrame = this->mTotalFrame -1;
	this->setFrame(this->mCurFrame);
}
void
SimWindow::
drawSkeletons()
{
	auto skel = this->mWorld->getSkeleton("Ref");
	if(mShowRef){
		GUI::DrawSkeleton(skel, this->mSkeletonDrawType);
	}
	skel = this->mWorld->getSkeleton("Humanoid");
	if(mShowCharacter){
		GUI::DrawSkeleton(skel, this->mSkeletonDrawType);
	}
}

void
SimWindow::
drawGround()
{
	Eigen::Vector3d com_root = this->mWorld->getSkeleton("Humanoid")->getRootBodyNode()->getCOM();
	double ground_height = 0.0;//this->mWorld->getSkeleton("Ground")->getRootBodyNode()->getCOM()[1]+0.5;
	GUI::DrawGround((int)com_root[0], (int)com_root[2], ground_height);
}

void
SimWindow::
drawFlag(){
    Eigen::Vector2d goal;
    goal[0] = this->mTargetRecords[mCurFrame][0];
    goal[1] = this->mTargetRecords[mCurFrame][2];

    // glDisable(GL_LIGHTING);
    glLineWidth(10.0);

    Eigen::Vector3d orange= dart::Color::Orange();
    glColor3f(orange[0],orange[1],orange[2]);
    Eigen::Vector3d A, B, C;
    A = Eigen::Vector3d(0, 1.6, 0);
    B = Eigen::Vector3d(0, 1.97, 0);
    C = Eigen::Vector3d(0.3, 1.85, 0.3);
//            glVertex3f(this->mGoalRecords[this->mCurFrame][0], 1.6, this->mGoalRecords[this->mCurFrame][2]);
//            glVertex3f(this->mGoalRecords[this->mCurFrame][0], 1.97, this->mGoalRecords[this->mCurFrame][2]);
//            glVertex3f(this->mGoalRecords[this->mCurFrame][0]+0.3, 1.85, this->mGoalRecords[this->mCurFrame][2]+0.3);
//
//

    {
        glPushMatrix();
        glTranslatef(goal[0], 0.05, goal[1]);
        glRotatef(90, 1, 0, 0);
//            std::cout<<orange.transpose()<<std::endl; 1, 0.63, 0
        glColor3f(0.9, 0.53, 0.1);
        GUI::DrawCylinder(0.04, 0.1);
        glPopMatrix();

        glPushMatrix();
        glTranslatef(goal[0], 1.0, goal[1]);
        glRotatef(90, 1, 0, 0);
//            std::cout<<orange.transpose()<<std::endl; 1, 0.63, 0
        glColor3f(0.9, 0.53, 0.1);
        GUI::DrawCylinder(0.02, 2);
        glPopMatrix();

        glPushMatrix();
        glTranslatef(goal[0], 2.039, goal[1]);
        glColor3f(0.9, 0.53, 0.1);
        GUI::DrawSphere(0.04);
        glPopMatrix();
    }
    {
        glPushMatrix();
        glTranslatef(goal[0], 0.0, goal[1]);

        double initTheta = 40.0*std::cos(240/120.0);
        glRotated(initTheta, 0, 1, 0);

        int slice = 100;
        for (int i = 0; i < slice; i++) {
            Eigen::Vector3d p[5];
            p[1] = A + (C - A) * i / slice;
            p[2] = A + (C - A) * (i + 1) / slice;
            p[3] = B + (C - B) * (i + 1) / slice;
            p[4] = B + (C - B) * i / slice;

            for (int j = 4; j >= 1; j--) p[j][0] -= p[1][0], p[j][2] -= p[1][2];

            glPushMatrix();
            glRotated(1.0*std::cos(initTheta + (double)i/slice*2*M_PI) * std::exp(-(double)(slice-i)/slice), 0, 1, 0);

            glBegin(GL_QUADS);
            for (int j = 1; j <= 4; j++) glVertex3d(p[j][0], p[j][1], p[j][2]);
            glEnd();

            glTranslatef(p[2][0], 0, p[2][2]);

        }
        for (int i = 0; i < slice; i++) {
            glPopMatrix();
        }

        glPopMatrix();
    }

}

void
SimWindow::
display()
{

	glClearColor(0.9, 0.9, 0.9, 1);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glEnable(GL_DEPTH_TEST);
	Eigen::Vector3d com_root = this->mWorld->getSkeleton("Humanoid")->getRootBodyNode()->getCOM();
	Eigen::Vector3d com_front = this->mWorld->getSkeleton("Humanoid")->getRootBodyNode()->getTransform()*Eigen::Vector3d(0.0, 0.0, 2.0);
	mCamera->apply();
	// initLights(com_root[0], com_root[2]);

	glUseProgram(program);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glPushMatrix();
    glScalef(1.0, -1.0, 1.0);
	initLights(com_root[0], com_root[2], com_front[0], com_front[2]);
	drawSkeletons();
	drawFlag();
	glPopMatrix();
	initLights(com_root[0], com_root[2], com_front[0], com_front[2]);
	// glColor4f(0.7, 0.0, 0.0, 0.40);  /* 40% dark red floor color */
	drawGround();
	drawSkeletons();
	drawFlag();
	glDisable(GL_BLEND);

	glUseProgram(0);
	glutSwapBuffers();
	if(mIsCapture)
		this->screenshot();
	// glutPostRedisplay();
}
void
SimWindow::
keyboard(unsigned char key,int x,int y)
{
	switch(key)
	{
		case '1' :mShowCharacter= !mShowCharacter;break;
		case '2' :mShowRef= !mShowRef;break;
		case '[': this->prevFrame();break;
		case ']': this->nextFrame();break;
		case 'o': this->mCurFrame-=99; this->prevFrame();break;
		case 'p': this->mCurFrame+=99; this->nextFrame();break;
		case 's': std::cout << this->mCurFrame << std::endl;break;
		case 'r': this->mCurFrame=0;this->setFrame(this->mCurFrame);break;
		case 'C': mIsCapture = true; break;
		case 't': mTrackCamera = !mTrackCamera; this->setFrame(this->mCurFrame); break;
		case 'T': this->mSkeletonDrawType++; this->mSkeletonDrawType %= 2; break;
		case ' ':
			mIsAuto = !mIsAuto;
			break;
		case 27: exit(0);break;
		default : break;
	}
	// this->SetFrame(this->mCurFrame);

	// glutPostRedisplay();
}
void
SimWindow::
mouse(int button, int state, int x, int y)
{
	if(button == 3 || button == 4){
		if (button == 3)
		{
			mCamera->pan(0,-5,0,0);
		}
		else
		{
			mCamera->pan(0,5,0,0);
		}
	}
	else{
		if (state == GLUT_DOWN)
		{
			mIsDrag = true;
			mMouseType = button;
			mPrevX = x;
			mPrevY = y;
		}
		else
		{
			mIsDrag = false;
			mMouseType = 0;
		}
	}

	// glutPostRedisplay();
}
void
SimWindow::
motion(int x, int y)
{
	if (!mIsDrag)
		return;

	int mod = glutGetModifiers();
	if (mMouseType == GLUT_LEFT_BUTTON)
	{
		mCamera->translate(x,y,mPrevX,mPrevY);
	}
	else if (mMouseType == GLUT_RIGHT_BUTTON)
	{
		mCamera->rotate(x,y,mPrevX,mPrevY);
		// switch (mod)
		// {
		// case GLUT_ACTIVE_SHIFT:
		// 	mCamera->Zoom(x,y,mPrevX,mPrevY); break;
		// default:
		// 	mCamera->Pan(x,y,mPrevX,mPrevY); break;
		// }

	}
	mPrevX = x;
	mPrevY = y;
	// glutPostRedisplay();
}
void
SimWindow::
reshape(int w, int h)
{
	glViewport(0, 0, w, h);
	mCamera->apply();
}
void
SimWindow::
timer(int value)
{
	if( mIsAuto )
		this->nextFrameRealTime();

	glutTimerFunc(mDisplayTimeout, timerEvent,1);
	glutPostRedisplay();
}

void SimWindow::
screenshot() {
  static int count = 0;
  const char directory[8] = "frames";
  const char fileBase[8] = "Capture";
  char fileName[32];

  boost::filesystem::create_directories(directory);
  std::snprintf(fileName, sizeof(fileName), "%s%s%s%.4d.png",
                directory, "/", fileBase, count++);
  int tw = glutGet(GLUT_WINDOW_WIDTH);
  int th = glutGet(GLUT_WINDOW_HEIGHT);

  glReadPixels(0, 0,  tw, th, GL_RGBA, GL_UNSIGNED_BYTE, &mScreenshotTemp[0]);

  // reverse temp2 temp1
  for (int row = 0; row < th; row++) {
    memcpy(&mScreenshotTemp2[row * tw * 4],
           &mScreenshotTemp[(th - row - 1) * tw * 4], tw * 4);
  }

  unsigned result = lodepng::encode(fileName, mScreenshotTemp2, tw, th);

  // if there's an error, display it
  if (result) {
    std::cout << "lodepng error " << result << ": "
              << lodepng_error_text(result) << std::endl;
    return ;
  } else {
    std::cout << "wrote screenshot " << fileName << "\n";
    return ;
  }
}

max_stars_repo_name: gkhaos/ICC

max_issues_repo_name: gkhaos/ICC

max_forks_repo_name: gkhaos/ICC


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

#include <Common/FailPoint.h>

#include <boost/core/noncopyable.hpp>
#include <condition_variable>
#include <mutex>

namespace DB
{
std::unordered_map<String, std::shared_ptr<FailPointChannel>> FailPointHelper::fail_point_wait_channels;

#define APPLY_FOR_FAILPOINTS_ONCE(M)                              \
    M(exception_between_drop_meta_and_data)                       \
    M(exception_between_alter_data_and_meta)                      \
    M(exception_drop_table_during_remove_meta)                    \
    M(exception_between_rename_table_data_and_metadata)           \
    M(exception_between_create_database_meta_and_directory)       \
    M(exception_before_rename_table_old_meta_removed)             \
    M(exception_after_step_1_in_exchange_partition)               \
    M(exception_before_step_2_rename_in_exchange_partition)       \
    M(exception_after_step_2_in_exchange_partition)               \
    M(exception_before_step_3_rename_in_exchange_partition)       \
    M(exception_after_step_3_in_exchange_partition)               \
    M(region_exception_after_read_from_storage_some_error)        \
    M(region_exception_after_read_from_storage_all_error)         \
    M(exception_before_dmfile_remove_encryption)                  \
    M(exception_before_dmfile_remove_from_disk)                   \
    M(force_enable_region_persister_compatible_mode)              \
    M(force_disable_region_persister_compatible_mode)             \
    M(force_triggle_background_merge_delta)                       \
    M(force_triggle_foreground_flush)                             \
    M(exception_before_mpp_register_non_root_mpp_task)            \
    M(exception_before_mpp_register_tunnel_for_non_root_mpp_task) \
    M(exception_during_mpp_register_tunnel_for_non_root_mpp_task) \
    M(exception_before_mpp_non_root_task_run)                     \
    M(exception_during_mpp_non_root_task_run)                     \
    M(exception_before_mpp_register_root_mpp_task)                \
    M(exception_before_mpp_register_tunnel_for_root_mpp_task)     \
    M(exception_before_mpp_root_task_run)                         \
    M(exception_during_mpp_root_task_run)                         \
    M(exception_during_mpp_write_err_to_tunnel)                   \
    M(exception_during_mpp_close_tunnel)                          \
    M(exception_during_write_to_storage)                          \
    M(force_set_sst_to_dtfile_block_size)                         \
    M(force_set_sst_decode_rand)                                  \
    M(exception_before_page_file_write_sync)                      \
    M(force_set_segment_ingest_packs_fail)                        \
    M(segment_merge_after_ingest_packs)                           \
    M(force_formal_page_file_not_exists)                          \
    M(force_legacy_or_checkpoint_page_file_exists)                \
    M(exception_in_creating_set_input_stream)                     \
    M(exception_when_read_from_log)                               \
    M(exception_mpp_hash_build)

#define APPLY_FOR_FAILPOINTS(M)                              \
    M(force_set_page_file_write_errno)                       \
    M(force_split_io_size_4k)                                \
    M(minimum_block_size_for_cross_join)                     \
    M(random_exception_after_dt_write_done)                  \
    M(random_slow_page_storage_write)                        \
    M(random_exception_after_page_storage_sequence_acquired) \
    M(random_slow_page_storage_remove_expired_snapshots)     \
    M(random_slow_page_storage_list_all_live_files)          \
    M(force_set_safepoint_when_decode_block)                 \
    M(force_set_page_data_compact_batch)                     \
    M(force_set_dtfile_exist_when_acquire_id)                \
    M(force_no_local_region_for_mpp_task)                    \
    M(force_remote_read_for_batch_cop)                       \
    M(force_context_path)

#define APPLY_FOR_FAILPOINTS_ONCE_WITH_CHANNEL(M) \
    M(pause_after_learner_read)                   \
    M(hang_in_execution)                          \
    M(pause_before_dt_background_delta_merge)     \
    M(pause_until_dt_background_delta_merge)      \
    M(pause_before_apply_raft_cmd)                \
    M(pause_before_apply_raft_snapshot)           \
    M(pause_until_apply_raft_snapshot)

#define APPLY_FOR_FAILPOINTS_WITH_CHANNEL(M) \
    M(pause_when_reading_from_dt_stream)     \
    M(pause_when_writing_to_dt_store)        \
    M(pause_when_ingesting_to_dt_store)      \
    M(pause_when_altering_dt_store)          \
    M(pause_after_copr_streams_acquired)

namespace FailPoints
{
#define M(NAME) extern const char(NAME)[] = #NAME "";
APPLY_FOR_FAILPOINTS_ONCE(M)
APPLY_FOR_FAILPOINTS(M)
APPLY_FOR_FAILPOINTS_ONCE_WITH_CHANNEL(M)
APPLY_FOR_FAILPOINTS_WITH_CHANNEL(M)
#undef M
} // namespace FailPoints

#ifdef FIU_ENABLE
class FailPointChannel : private boost::noncopyable
{
public:
    // wake up all waiting threads when destroy
    ~FailPointChannel() { notifyAll(); }

    void wait()
    {
        std::unique_lock lock(m);
        cv.wait(lock);
    }

    void notifyAll()
    {
        std::unique_lock lock(m);
        cv.notify_all();
    }

private:
    std::mutex m;
    std::condition_variable cv;
};

void FailPointHelper::enableFailPoint(const String & fail_point_name)
{
#define SUB_M(NAME, flags)                                                                                \
    if (fail_point_name == FailPoints::NAME)                                                                \
    {                                                                                \
        /* FIU_ONETIME -- Only fail once; the point of failure will be automatically disabled afterwards.*/ \
        fiu_enable(FailPoints::NAME, 1, nullptr, flags);                                                    \
        return;                                                                                \
    }

#define M(NAME) SUB_M(NAME, FIU_ONETIME)
    APPLY_FOR_FAILPOINTS_ONCE(M)
#undef M
#define M(NAME) SUB_M(NAME, 0)
    APPLY_FOR_FAILPOINTS(M)
#undef M
#undef SUB_M

#define SUB_M(NAME, flags)                                                                                \
    if (fail_point_name == FailPoints::NAME)                                                                \
    {                                                                                \
        /* FIU_ONETIME -- Only fail once; the point of failure will be automatically disabled afterwards.*/ \
        fiu_enable(FailPoints::NAME, 1, nullptr, flags);                                                    \
        fail_point_wait_channels.try_emplace(FailPoints::NAME, std::make_shared<FailPointChannel>());       \
        return;                                                                                \
    }

#define M(NAME) SUB_M(NAME, FIU_ONETIME)
    APPLY_FOR_FAILPOINTS_ONCE_WITH_CHANNEL(M)
#undef M

#define M(NAME) SUB_M(NAME, 0)
    APPLY_FOR_FAILPOINTS_WITH_CHANNEL(M)
#undef M
#undef SUB_M

    throw Exception("Cannot find fail point " + fail_point_name, ErrorCodes::FAIL_POINT_ERROR);
}

void FailPointHelper::disableFailPoint(const String & fail_point_name)
{
    if (auto iter = fail_point_wait_channels.find(fail_point_name); iter != fail_point_wait_channels.end())
    {
        /// can not rely on deconstruction to do the notify_all things, because
        /// if someone wait on this, the deconstruct will never be called.
        iter->second->notifyAll();
        fail_point_wait_channels.erase(iter);
    }
    fiu_disable(fail_point_name.c_str());
}

void FailPointHelper::wait(const String & fail_point_name)
{
    if (auto iter = fail_point_wait_channels.find(fail_point_name); iter == fail_point_wait_channels.end())
        throw Exception("Can not find channel for fail point " + fail_point_name);
    else
    {
        auto ptr = iter->second;
        ptr->wait();
    }
}
#else
class FailPointChannel
{
};

void FailPointHelper::enableFailPoint(const String &) {}

void FailPointHelper::disableFailPoint(const String &) {}

void FailPointHelper::wait(const String &) {}
#endif

} // namespace DB

max_stars_repo_name: wuchong/tiflash

max_issues_repo_name: dragonly/tiflash

max_forks_repo_name: dragonly/tiflash


text:
/* $Id: title_screen.cpp 48740 2011-03-05 10:01:34Z mordante $ */
/*
   Copyright (C) 2008 - 2011 by Mark de Wever <koraq@xs4all.nl>
   Part of the Battle for Wesnoth Project http://www.wesnoth.org/

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.

   See the COPYING file for more details.
*/

#define GETTEXT_DOMAIN "wesnoth-lib"

#include "gui/dialogs/title_screen.hpp"

#include "display.hpp"
#include "game_config.hpp"
#include "game_preferences.hpp"
#include "gettext.hpp"
#include "log.hpp"
#include "gui/auxiliary/timer.hpp"
#include "gui/auxiliary/tips.hpp"
#include "gui/dialogs/debug_clock.hpp"
#include "gui/dialogs/language_selection.hpp"
#include "gui/widgets/button.hpp"
#include "gui/widgets/label.hpp"
#include "gui/widgets/multi_page.hpp"
#include "gui/widgets/progress_bar.hpp"
#include "gui/widgets/settings.hpp"
#include "gui/widgets/window.hpp"
#include "preferences_display.hpp"

#include <boost/bind.hpp>

#include <algorithm>

static lg::log_domain log_config("config");
#define ERR_CF LOG_STREAM(err, log_config)
#define WRN_CF LOG_STREAM(warn, log_config)

namespace gui2 {

/*WIKI
 * @page = GUIWindowDefinitionWML
 * @order = 2_title_screen
 *
 * == Title screen ==
 *
 * This shows the title screen.
 *
 * @begin{table}{dialog_widgets}
 * tutorial & & button & m &
 *         The button to start the tutorial. $
 *
 * campaign & & button & m &
 *         The button to start a campaign. $
 *
 * multiplayer & & button & m &
 *         The button to start multiplayer mode. $
 *
 * load & & button & m &
 *         The button to load a saved game. $
 *
 * editor & & button & m &
 *         The button to start the editor. $
 *
 * addons & & button & m &
 *         The button to start managing the addons. $
 *
 * language & & button & m &
 *         The button to select the game language. $
 *
 * credits & & button & m &
 *         The button to show Wesnoth's contributors. $
 *
 * quit & & button & m &
 *         The button to quit Wesnoth. $
 *
 * tips & & multi_page & m &
 *         A multi_page to hold all tips, when this widget is used the area of
 *         the tips doesn't need to be resized when the next or previous button
 *         is pressed. $
 *
 * -tip & & label & o &
 *         Shows the text of the current tip. $
 *
 * -source & & label & o &
 *         The source (the one who's quoted or the book referenced) of the
 *         current tip. $
 *
 * next_tip & & button & m &
 *         The button show the next tip of the day. $
 *
 * previous_tip & & button & m &
 *         The button show the previous tip of the day. $
 *
 * logo & & progress_bar & o &
 *         A progress bar to "animate" the Wesnoth logo. $
 *
 * revision_number & & control & o &
 *         A widget to show the version number when the version number is
 *         known. $
 *
 * @end{table}
 */

REGISTER_DIALOG(title_screen)

bool show_debug_clock_button = false;

static bool hotkey(twindow& window, const ttitle_screen::tresult result)
{
	window.set_retval(static_cast<twindow::tretval>(result));

	return true;
}

ttitle_screen::ttitle_screen()
	: logo_timer_id_(0)
	, debug_clock_(NULL)
{
}

ttitle_screen::~ttitle_screen()
{
	if(logo_timer_id_) {
		remove_timer(logo_timer_id_);
	}
	delete debug_clock_;
}

static void animate_logo(
		  unsigned long& timer_id
		, unsigned& percentage
		, tprogress_bar& progress_bar
		, twindow& window)
{
	assert(percentage <= 100);
	++percentage;
	progress_bar.set_percentage(percentage);

	/*
	 * The progress bar may overlap (actually underlap) other widgets, which
	 * the update invalidates, so make sure the whole window is redrawn to fix
	 * this possible problem. Of course this is expensive but the logo is
	 * animated once so the cost is only once.
	 */
	window.set_dirty();

	if(percentage == 100) {
		remove_timer(timer_id);
		timer_id = 0;
	}
}

static bool fullscreen(CVideo& video)
{
	preferences::set_fullscreen(video , !preferences::fullscreen());

	// Setting to fullscreen doesn't seem to generate a resize event.
	const SDL_Rect& rect = screen_area();

	SDL_Event event;
	event.type = SDL_VIDEORESIZE;
	event.resize.type = SDL_VIDEORESIZE;
	event.resize.w = rect.w;
	event.resize.h = rect.h;

	SDL_PushEvent(&event);

	return true;
}

void ttitle_screen::post_build(CVideo& video, twindow& window)
{
	/** @todo Should become a title screen hotkey. */
	window.register_hotkey(hotkey::TITLE_SCREEN__RELOAD_WML
				, boost::bind(
					  &hotkey
					, boost::ref(window)
					, RELOAD_GAME_DATA));

	window.register_hotkey(hotkey::HOTKEY_FULLSCREEN
			, boost::bind(fullscreen, boost::ref(video)));

	window.register_hotkey(hotkey::HOTKEY_LANGUAGE
				, boost::bind(
					  &hotkey
					, boost::ref(window)
					, CHANGE_LANGUAGE));

	window.register_hotkey(hotkey::HOTKEY_LOAD_GAME
				, boost::bind(
					  &hotkey
					, boost::ref(window)
					, LOAD_GAME));

	window.register_hotkey(hotkey::HOTKEY_HELP
				, boost::bind(
					  &hotkey
					, boost::ref(window)
					, SHOW_HELP));

	window.register_hotkey(hotkey::HOTKEY_PREFERENCES
				, boost::bind(
					  &hotkey
					, boost::ref(window)
					, EDIT_PREFERENCES));

	static const boost::function<void()> next_tip_wrapper = boost::bind(
			  &ttitle_screen::update_tip
			, this
			, boost::ref(window)
			, true);

	window.register_hotkey(hotkey::TITLE_SCREEN__NEXT_TIP
			, boost::bind(function_wrapper<bool, boost::function<void()> >
				, true
				, boost::cref(next_tip_wrapper)));

	static const boost::function<void()> previous_tip_wrapper = boost::bind(
			  &ttitle_screen::update_tip
			, this
			, boost::ref(window)
			, false);

	window.register_hotkey(hotkey::TITLE_SCREEN__PREVIOUS_TIP
			, boost::bind(function_wrapper<bool, boost::function<void()> >
				, true
				, boost::cref(previous_tip_wrapper)));

	window.register_hotkey(hotkey::TITLE_SCREEN__TUTORIAL
				, boost::bind(
					  &hotkey
					, boost::ref(window)
					, TUTORIAL));

	window.register_hotkey(hotkey::TITLE_SCREEN__TUTORIAL
				, boost::bind(
					  &hotkey
					, boost::ref(window)
					, TUTORIAL));

	window.register_hotkey(hotkey::TITLE_SCREEN__CAMPAIGN
				, boost::bind(
					  &hotkey
					, boost::ref(window)
					, NEW_CAMPAIGN));

	window.register_hotkey(hotkey::TITLE_SCREEN__MULTIPLAYER
				, boost::bind(
					  &hotkey
					, boost::ref(window)
					, MULTIPLAYER));

	window.register_hotkey(hotkey::TITLE_SCREEN__ADDONS
				, boost::bind(
					  &hotkey
					, boost::ref(window)
					, GET_ADDONS));

	window.register_hotkey(hotkey::TITLE_SCREEN__EDITOR
				, boost::bind(
					  &hotkey
					, boost::ref(window)
					, START_MAP_EDITOR));

	window.register_hotkey(hotkey::TITLE_SCREEN__CREDITS
				, boost::bind(
					  &hotkey
					, boost::ref(window)
					, SHOW_ABOUT));

	window.register_hotkey(hotkey::HOTKEY_QUIT_GAME
				, boost::bind(
					  &hotkey
					, boost::ref(window)
					, QUIT_GAME));
}

void ttitle_screen::pre_show(CVideo& video, twindow& window)
{
	set_restore(false);
	window.set_click_dismiss(false);
	window.set_enter_disabled(true);
	window.set_escape_disabled(true);

	/**** Set the version number ****/
	if(tcontrol* control
			= find_widget<tcontrol>(&window, "revision_number", false, false)) {

		control->set_label(_("Version ") + game_config::revision);
	}
	window.canvas()[0].set_variable("revision_number",
		variant(_("Version") + std::string(" ") + game_config::revision));

	/**** Set the tip of the day ****/
	tmulti_page& tip_pages = find_widget<tmulti_page>(&window, "tips", false);

	std::vector<ttip> tips(settings::get_tips());
	if(tips.empty()) {
		WRN_CF << "There are not tips of day available.\n";
	}

	foreach(const ttip& tip, tips) {

		string_map widget;
		std::map<std::string, string_map> page;

		widget["label"] = tip.text();
		widget["use_markup"] = "true";
		page["tip"] = widget;

		widget["label"] = tip.source();
		widget["use_markup"] = "true";
		page["source"] = widget;

		tip_pages.add_page(page);
	}

	update_tip(window, true);

	connect_signal_mouse_left_click(
			  find_widget<tbutton>(&window, "next_tip", false)
			, boost::bind(
				  &ttitle_screen::update_tip
				, this
				, boost::ref(window)
				, true));

	connect_signal_mouse_left_click(
			  find_widget<tbutton>(&window, "previous_tip", false)
			, boost::bind(
				  &ttitle_screen::update_tip
				, this
				, boost::ref(window)
				, false));

	if(game_config::images::game_title.empty()) {
		ERR_CF << "No title image defined\n";
	} else {
		window.canvas()[0].set_variable("background_image",
			variant(game_config::images::game_title));
	}

	/***** Set the logo *****/
	tprogress_bar* logo =
			find_widget<tprogress_bar>(&window, "logo", false, false);
	if(logo) {
		/*
		 * A 'singleton' value, since the progress bar only needs to progress
		 * once its state needs to be global.
		 */
		static unsigned percentage = preferences::startup_effect() ? 0 : 100;
		logo->set_percentage(percentage);

		if(percentage < 100) {
			/*
			 * The interval is empirically determined  so that the speed "felt"
			 * good.
			 */
			logo_timer_id_ = add_timer(30
					, boost::bind(animate_logo
						, boost::ref(logo_timer_id_)
						, boost::ref(percentage)
						, boost::ref(*logo)
						, boost::ref(window))
					, true);
		}
	}

	/***** Set the clock button. *****/
	tbutton& clock = find_widget<tbutton>(&window, "clock", false);
	clock.set_visible(show_debug_clock_button
			? twidget::VISIBLE
			: twidget::INVISIBLE);

	connect_signal_mouse_left_click(
			  clock
			, boost::bind(
				  &ttitle_screen::show_debug_clock_window
				, this
				, boost::ref(video)));
}

void ttitle_screen::update_tip(twindow& window, const bool previous)
{
	tmulti_page& tips = find_widget<tmulti_page>(&window, "tips", false);
	if(tips.get_page_count() == 0) {
		return;
	}

	int page = tips.get_selected_page();
	if(previous) {
		if(page <= 0) {
			page = tips.get_page_count();
		}
		--page;
	} else {
		++page;
		if(static_cast<unsigned>(page) >= tips.get_page_count()) {
			page = 0;
		}
	}

	tips.select_page(page);
}

void ttitle_screen::show_debug_clock_window(CVideo& video)
{
	assert(show_debug_clock_button);

	if(debug_clock_) {
		delete debug_clock_;
		debug_clock_ = NULL;
	} else {
		debug_clock_ = new tdebug_clock();
		debug_clock_->show(video, true);
	}
}

} // namespace gui2

max_stars_repo_name: blackberry/Wesnoth

max_issues_repo_name: blackberry/Wesnoth

max_forks_repo_name: blackberry/Wesnoth


text:
/**
 *
 * Modern Wheel : all the things that shouldn't be reinvented from one project to the other
 *
 * The MIT License (MIT)
 *
 * Copyright (C) 2015  Massimiliano Culpo
 *
 * 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 <mwheel/dlmanager.h>

#include <boost/predef.h>

#include <iostream>
#include <sstream>
#include <typeinfo>
#include <utility>

#ifdef BOOST_OS_UNIX
#include <dlfcn.h>
#else
#error "At present only Unix-like OS are supported"
#endif

using namespace std;

namespace mwheel {

void DLManager::load_library(const boost::filesystem::path &library_path) {
#ifdef BOOST_OS_UNIX
  auto handle = dlopen(library_path.c_str(), RTLD_LAZY);
  auto error_message = dlerror();
  if (error_message) {
    stringstream estream;
    estream << "ERROR : cannot load shared library " << library_path << endl;
    estream << "\t" << error_message << endl;
    throw error_loading_dynamic_library(estream.str());
  }
  m_dl_map.insert(make_pair(library_path, handle));
#endif
}

void DLManager::unload_library(const boost::filesystem::path &library_path) {
#ifdef BOOST_OS_UNIX
  auto it = DLMap::iterator(m_dl_map.find(library_path));
  // The library was not found
  if (it == m_dl_map.end()) {
    stringstream estream;
    estream << "ERROR : cannot trying to unload a shared library that was not previously loaded "
            << library_path << endl;
    estream << "\tDid you use a wrong name for the library to be unloaded?" << endl;
    throw library_not_loaded(estream.str());
  }
  // Close the library
  if (dlclose(it->second)) {
    auto error_message = dlerror();
    stringstream estream;
    estream << "ERROR : cannot unload shared library " << library_path << endl;
    estream << "\t" << error_message << endl;
    throw error_unloading_dynamic_library(estream.str());
  }
  m_dl_map.erase(it);
#endif
}

DLManager::~DLManager() {
#ifdef BOOST_OS_UNIX
  for (auto &x : m_dl_map) {
    dlclose(x.second);
    auto error_message = dlerror();
    if (error_message) {
      cerr << "ERROR : cannot unload shared library " << x.first << endl;
      cerr << "\t" << error_message << endl;
    }
  }
#endif
}
}


text:
#include <bio/bayesian_hierarchical_clustering.h>
#include <bio/random.h>
USING_BIO_NS

#include <boost/assign.hpp>
#include <boost/assert.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/progress.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/vector_property_map.hpp>
#include <boost/array.hpp>
using namespace boost;
using namespace boost::assign;
using boost::unit_test::test_suite;

#include <iostream>
using namespace std;

#ifndef _WIN32
# include <stdlib.h>
#endif //_WIN32

typedef boost::array<bool, 4> bool_data_t;
typedef std::vector<bool_data_t> bool_data_vec_t;
typedef bool_data_vec_t::const_iterator bool_data_it;
typedef std::set<bool_data_it> bool_data_set_t;
bool_data_vec_t bool_data;

typedef boost::array<double, 2> real_data_t;
typedef std::vector<real_data_t> real_data_vec_t;
typedef real_data_vec_t::const_iterator real_data_it;
typedef std::set<real_data_it> real_data_set_t;
real_data_vec_t real_data;

void
create_data()
{
	using namespace boost::assign;

	if (bool_data.empty())
	{
		bool_data +=
			list_of( true)( true)( true)( true ),
			list_of( true)(false)(false)(false ),
			list_of(false)( true)(false)(false ),
			list_of(false)(false)( true)(false ),
			list_of(false)(false)(false)( true ),
			list_of(false)( true)( true)( true ),
			list_of( true)(false)( true)( true ),
			list_of( true)( true)(false)( true ),
			list_of( true)( true)( true)(false ),
			list_of(false)(false)(false)(false );
	}

	if (real_data.empty())
	{
		real_data +=
			//list_of( 1.00)( 1.00),
			//list_of( 1.00)( 1.00),
			list_of( 1.00)( 1.00),
			//list_of(-1.00)( 1.00),
			//list_of(-1.00)( 1.00),
			list_of(-1.00)( 1.00),
			//list_of( 1.00)(-1.00),
			//list_of( 1.00)(-1.00),
			list_of( 1.00)(-1.00),
			//list_of(-1.00)(-1.00),
			//list_of(-1.00)(-1.00),
			list_of(-1.00)(-1.00),
			//list_of( 0.00)( 0.00),
			//list_of( 0.00)( 0.00),
			list_of( 0.00)( 0.00);
	}
}

ostream &
operator<<(ostream & os, const bool_data_t & bool_data)
{
	for (bool_data_t::const_iterator d = bool_data.begin();
		bool_data.end() != d;
		++d)
	{
		os << (*d ? "1" : "0");
	}
	return os;
}

ostream &
operator<<(ostream & os, const real_data_t & real_data)
{
	boost::io::ios_base_all_saver ias(os);
	//os.precision(3);
	os.unsetf(ios::adjustfield);
	os.unsetf(ios::floatfield);

	for (real_data_t::const_iterator d = real_data.begin();
		real_data.end() != d;
		++d)
	{
		os << *d << ":";
	}
	return os;
}

struct RandomScorer
{
	typedef double score_t;
	static score_t min_score() { return numeric_limits<score_t>::min(); }

	template <class Cluster>
	score_t
	operator()(
		const Cluster & cluster) const
	{
		return get_uniform_01();
	}

	template <class Cluster>
	score_t
	operator()(
		const Cluster & cluster_1,
		const Cluster & cluster_2) const
	{
		return get_uniform_01();
	}
};

template <class DataIt, class Scorer>
struct DfsVisitor : boost::default_dfs_visitor
{
	typedef typename ClusterTraits<DataIt, Scorer>::data_set_t data_set_t;
	data_set_t & data_set;

	DfsVisitor(data_set_t & data_set) : data_set(data_set) { }

	template < typename Vertex, typename Graph >
	void discover_vertex(Vertex u, const Graph & g)
	{
		if (g[u].first)
		{
			data_set.insert(g[u].second);
		}
	}
};

template <class Clusterer>
void
show_clusters(Clusterer & clusterer)
{
	typedef Clusterer clusterer_t;
	typedef typename clusterer_t::data_it data_it;
	typedef typename clusterer_t::scorer_t scorer_t;

	typename clusterer_t::tree_vertex_it v, end;
	for (tie(v, end) = vertices(clusterer.tree); end != v; ++v)
	{
		typedef DfsVisitor<data_it, scorer_t> dfs_visitor_t;
		typedef typename dfs_visitor_t::data_set_t data_set_t;
		data_set_t data_set;

		depth_first_visit(
			clusterer.tree,
			*v,
			dfs_visitor_t(data_set),
			vector_property_map<typename clusterer_t::tree_vertex>());

#ifdef VERBOSE_CHECKING
		for (typename data_set_t::const_iterator i = data_set.begin();
			data_set.end() != i;
			++i)
		{
			cout << **i << ",";
		}
		cout << endl;
#endif
	}
}

template <class ModelIt, class DataIt>
void
compare_models(
	ModelIt models_begin,
	ModelIt models_end,
	DataIt data_begin,
	DataIt data_end)
{
	boost::io::ios_base_all_saver ias(cout);
	cout.precision(9);
	cout.setf(ios::left, ios::adjustfield);
	cout.setf(ios::fixed, ios::floatfield);

	for (DataIt i = data_begin;
		data_end != i;
		++i)
	{
		typedef std::list<DataIt> data_it_list_t;
		data_it_list_t single_data_set = list_of(i);

		cout << *i << "\t";
		for (ModelIt m = models_begin;
			models_end != m;
			++m)
		{
			cout << "\t" << setw(12) << (*m)(single_data_set.begin(), single_data_set.end());
		}
		cout << endl;

		for (DataIt j = data_begin;
			data_end != j;
			++j)
		{
			data_it_list_t double_data_set = list_of(i)(j);

			cout << *i << "," << *j;
			for (ModelIt m = models_begin;
				models_end != m;
				++m)
			{
				cout << "\t" << setw(10) << (*m)(double_data_set.begin(), double_data_set.end());
			}
			cout << endl;

		}
	}
}

void
check_wishart_normal_prior()
{
	using namespace boost::assign;

	cout << "******* check_wishart_normal_prior()" << endl;

	create_data();

	typedef NormalWishartPrior model_t;
	typedef std::vector<model_t> model_vec_t;
	model_vec_t models(3);

	models[0] = model_t(2);
	models[0].s(0,0) = 1;
	models[0].s(1,0) = 0;
	models[0].s(0,1) = 0;
	models[0].s(1,1) = 1;
	models[0].m(0) = 0;
	models[0].m(1) = 0;
	models[0].r = 0.001;
	models[0].v = 2.0;

	models[1] = models[0];
	models[1].r = .1;

	models[2] = models[0];
	models[2].r = 1;

#ifdef VERBOSE_CHECKING
	compare_models(models.begin(), models.end(), real_data.begin(), real_data.end());
#endif
}

void
check_bernoulli_beta_prior()
{
	using namespace boost::assign;

	cout << "******* check_bernoulli_beta_prior()" << endl;

	create_data();

	typedef BernoulliBetaPrior model_t;
	typedef std::vector<model_t> model_vec_t;
	model_vec_t models(3);

	models[0] = model_t(4);
	models[0].alpha = list_of(1)(1)(1)(1);
	models[0].beta = list_of(1)(1)(1)(1);

	models[1] = models[0];
	models[1].alpha = list_of(1)(1)(1)(10);

	models[2] = models[0];
	models[2].beta = list_of(1)(1)(1)(10);

#ifdef VERBOSE_CHECKING
	compare_models(models.begin(), models.end(), bool_data.begin(), bool_data.end());
#endif
}

void
check_multinomial_dirichlet_prior()
{
	using namespace boost::assign;

	cout << "******* check_multinomial_dirichlet_prior()" << endl;

	create_data();

}

void
check_bayesian_hierarchical_clustering()
{
	using namespace boost::assign;

	cout << "******* check_bayesian_hierarchical_clustering()" << endl;

	create_data();

	if (false) //don't run for now
	{
#ifdef VERBOSE_CHECKING
		cout << "Random clustering" << endl;
#endif

		typedef RandomScorer scorer_t;
		scorer_t scorer;
		typedef TreeBuildingClusterer<bool_data_it, scorer_t> clusterer_t;
		clusterer_t clusterer;
		cluster<bool_data_it, scorer_t, clusterer_t>(
			bool_data.begin(),
			bool_data.end(),
			scorer,
			clusterer);

		show_clusters(clusterer);
	}

	if (false) //don't run for now
	{
#ifdef VERBOSE_CHECKING
		cout << "Bayesian clustering of bool data" << endl;
#endif

		typedef BernoulliBetaPrior model_t;
		typedef BayesianClusterScorer<BernoulliBetaPrior> scorer_t;
		typedef TreeBuildingClusterer<bool_data_it, scorer_t> clusterer_t;
		model_t model(4);
		model.alpha += 0.1,1.0,0.7,1.0;
		model.beta += 1.0,1.5,1.0,2.0;
		clusterer_t clusterer;
		scorer_t scorer(model);
		cluster<bool_data_it, scorer_t, clusterer_t>(
			bool_data.begin(),
			bool_data.end(),
			scorer,
			clusterer);

		show_clusters(clusterer);
	}

	{
#ifdef VERBOSE_CHECKING
		cout << "Bayesian clustering of real data" << endl;
#endif

		typedef NormalWishartPrior model_t;
		typedef BayesianClusterScorer<model_t> scorer_t;
		typedef TreeBuildingClusterer<real_data_it, scorer_t> clusterer_t;
		model_t model(2);
		model.s(0,0) = 1;
		model.s(1,0) = 0;
		model.s(0,1) = 0;
		model.s(1,1) = 1;
		model.m(0) = 0.0;
		model.m(1) = 0.0;
		model.r = 1;
		model.v = 3.0;
		clusterer_t clusterer;
		scorer_t scorer(model);
		cluster<real_data_it, scorer_t, clusterer_t>(
			real_data.begin(),
			real_data.end(),
			scorer,
			clusterer);

		show_clusters(clusterer);
	}
}

void register_clustering_tests(test_suite * test)
{
	test->add(BOOST_TEST_CASE(&check_bayesian_hierarchical_clustering), 0);
	test->add(BOOST_TEST_CASE(&check_multinomial_dirichlet_prior), 0);
	test->add(BOOST_TEST_CASE(&check_wishart_normal_prior), 0);
	test->add(BOOST_TEST_CASE(&check_bernoulli_beta_prior), 0);
}

max_stars_repo_name: JohnReid/biopsy

max_issues_repo_name: JohnReid/biopsy

max_forks_repo_name: JohnReid/biopsy