<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2010, 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: test_plane_intersection.cpp 5686 2012-05-11 20:59:00Z gioia $
 */

#include <gtest/gtest.h>
#include <pcl/common/common.h>
#include <pcl/common/intersections.h>
#include <pcl/pcl_tests.h>

using namespace pcl;

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, lineWithLineIntersection)
{
  Eigen::VectorXf line_a(4);
  Eigen::VectorXf line_b(4);

  //case 1
  line_a[0] = 0.01f;
  line_a[1] = 0.02f;
  line_a[2] = 0.03f;
  line_a[3] = 0.4f;
  line_a[4] = 0.5f;
  line_a[5] = 0.6f;

  line_b[0] = 0.1f;
  line_b[1] = 0.2f;
  line_b[2] = 0.3f;
  line_b[3] = 0.04f;
  line_b[4] = 0.05f;
  line_b[5] = 0.06f;

  Eigen::Vector4f p1, p2;
  lineToLineSegment (line_a, line_b, p1, p2);

  Eigen::Vector4f point_case_1;
  bool result_case_1 = lineWithLineIntersection(line_a, line_b, point_case_1);

  double sqr_dist_case_1 = (p1 - p2).squaredNorm ();

  double default_sqr_eps = 1e-4;
  EXPECT_GT(sqr_dist_case_1, default_sqr_eps);
  Eigen::Vector4f zero(0.0f, 0.0f, 0.0f, 0.0f);

  EXPECT_EQ(point_case_1[0], zero[0]);
  EXPECT_EQ(point_case_1[1], zero[1]);
  EXPECT_EQ(point_case_1[2], zero[2]);
  EXPECT_EQ(point_case_1[3], zero[3]);

  EXPECT_FALSE(result_case_1);

  pcl::ModelCoefficients line_a_mod;
  pcl::ModelCoefficients line_b_mod;

  std::vector<float> values_a_case_1;
  values_a_case_1.push_back(line_a[0]);
  values_a_case_1.push_back(line_a[1]);
  values_a_case_1.push_back(line_a[2]);
  values_a_case_1.push_back(line_a[3]);
  values_a_case_1.push_back(line_a[4]);
  values_a_case_1.push_back(line_a[5]);

  std::vector<float> values_b_case_1;
  values_b_case_1.push_back(line_b[0]);
  values_b_case_1.push_back(line_b[1]);
  values_b_case_1.push_back(line_b[2]);
  values_b_case_1.push_back(line_b[3]);
  values_b_case_1.push_back(line_b[4]);
  values_b_case_1.push_back(line_b[5]);

  line_a_mod.values = values_a_case_1;
  line_b_mod.values = values_b_case_1;

  Eigen::Vector4f point_mod_1;
  EXPECT_FALSE(lineWithLineIntersection(line_a_mod, line_b_mod, point_mod_1));
  EXPECT_EQ(result_case_1, lineWithLineIntersection(line_a_mod, line_b_mod, point_mod_1));

  EXPECT_EQ(point_mod_1[0], zero[0]);
  EXPECT_EQ(point_mod_1[1], zero[1]);
  EXPECT_EQ(point_mod_1[2], zero[2]);
  EXPECT_EQ(point_mod_1[3], zero[3]);

  //case 2
  line_a[0] = 0.00100f;
  line_a[1] = 0.00200f;
  line_a[2] = 0.00300f;
  line_a[3] = 0.00400f;
  line_a[4] = 0.00500f;
  line_a[5] = 0.00600f;

  line_b[0] = 0.00157f;
  line_b[1] = 0.00233f;
  line_b[2] = 0.00378f;
  line_b[3] = 0.00495f;
  line_b[4] = 0.00565f;
  line_b[5] = 0.00666f;

  lineToLineSegment (line_a, line_b, p1, p2);

  Eigen::Vector4f point_case_2;
  double sqr_eps_case_2 = 1e-1;
  bool result_case_2 = lineWithLineIntersection(line_a, line_b, point_case_2, sqr_eps_case_2);

  double sqr_dist_case_2 = (p1 - p2).squaredNorm ();
  EXPECT_LT(sqr_dist_case_2, sqr_eps_case_2);

  EXPECT_EQ(point_case_2[0], p1[0]);
  EXPECT_EQ(point_case_2[1], p1[1]);
  EXPECT_EQ(point_case_2[2], p1[2]);
  EXPECT_EQ(point_case_2[3], p1[3]);

  EXPECT_TRUE(result_case_2);

  pcl::ModelCoefficients line_a_mod_2;
  pcl::ModelCoefficients line_b_mod_2;

  std::vector<float> values_a_case_2;
  values_a_case_2.push_back(0.1000f);
  values_a_case_2.push_back(0.2000f);
  values_a_case_2.push_back(0.3000f);
  values_a_case_2.push_back(0.4000f);
  values_a_case_2.push_back(0.5000f);
  values_a_case_2.push_back(0.6000f);

  std::vector<float> values_b_case_2;
  values_b_case_2.push_back(0.1001f);
  values_b_case_2.push_back(0.2001f);
  values_b_case_2.push_back(0.3001f);
  values_b_case_2.push_back(0.4001f);
  values_b_case_2.push_back(0.5001f);
  values_b_case_2.push_back(0.6001f);

  line_a_mod_2.values = values_a_case_2;
  line_b_mod_2.values = values_b_case_2;

  Eigen::Vector4f point_mod_2;
  Eigen::Vector4f point_mod_case_2;
  double sqr_mod_case_2 = 1e-1;

  Eigen::VectorXf coeff1 = Eigen::VectorXf::Map (&line_a_mod_2.values[0], line_a_mod_2.values.size ());
  Eigen::VectorXf coeff2 = Eigen::VectorXf::Map (&line_b_mod_2.values[0], line_b_mod_2.values.size ());

  Eigen::Vector4f p1_mod, p2_mod;
  lineToLineSegment (coeff1, coeff2, p1_mod, p2_mod);
  double sqr_mod_act_2 = (p1_mod - p2_mod).squaredNorm ();

  EXPECT_LT(sqr_mod_act_2, sqr_mod_case_2);
  EXPECT_EQ(lineWithLineIntersection (coeff1, coeff2, point_mod_case_2, sqr_mod_case_2),
                        lineWithLineIntersection(line_a_mod_2, line_b_mod_2, point_mod_2, sqr_mod_case_2));
  EXPECT_TRUE(lineWithLineIntersection(line_a_mod_2, line_b_mod_2, point_mod_2, sqr_mod_case_2));

  EXPECT_EQ(point_mod_2[0], point_mod_case_2[0]);
  EXPECT_EQ(point_mod_2[1], point_mod_case_2[1]);
  EXPECT_EQ(point_mod_2[2], point_mod_case_2[2]);
  EXPECT_EQ(point_mod_2[3], point_mod_case_2[3]);

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, planeWithPlaneIntersection)
{
  //Testing parallel planes
  const int k = 2;
  float x = 1.0f;
  float y = 2.0f;
  float z = 3.0f;
  float w = 4.0f;
  Eigen::Vector4f plane_a;
  plane_a.x() = x;
  plane_a.y() = y;
  plane_a.z() = z;
  plane_a.w() = w;

  EXPECT_EQ(1.0f, plane_a.x());
  EXPECT_EQ(2.0f, plane_a.y());
  EXPECT_EQ(3.0f, plane_a.z());
  EXPECT_EQ(4.0f, plane_a.w());

  Eigen::Vector4f plane_b;
  plane_b.x() = x;
  plane_b.y() = y;
  plane_b.z() = z;
  plane_b.w() = w + k;

  EXPECT_EQ(1.0f, plane_b.x());
  EXPECT_EQ(2.0f, plane_b.y());
  EXPECT_EQ(3.0f, plane_b.z());
  EXPECT_EQ(6.0f, plane_b.w());

  Eigen::VectorXf line;

  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 45));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 90));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 180));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 360));

  plane_b.x() = k * x;
  plane_b.y() = k * y;
  plane_b.z() = k * z;
  plane_b.w() = k * w;

  EXPECT_EQ(2.0f, plane_b.x());
  EXPECT_EQ(4.0f, plane_b.y());
  EXPECT_EQ(6.0f, plane_b.z());
  EXPECT_EQ(8.0f, plane_b.w());

  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 45));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 90));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 180));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 360));

  //overlapping planes
  plane_b.w() = w;
  EXPECT_EQ(4.0f, plane_b.w());

  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 45));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 90));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 180));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 360));

  //orthogonal planes
  plane_a.x() = 2.0f;
  plane_a.y() = 1.0f;
  plane_a.z() = -5.0f;
  plane_a.w() = 6.0f;
  EXPECT_EQ(2.0f, plane_a.x());
  EXPECT_EQ(1.0f, plane_a.y());
  EXPECT_EQ(-5.0f, plane_a.z());
  EXPECT_EQ(6.0f, plane_a.w());

  plane_b.x() = 2.0f;
  plane_b.y() = 1.0f;
  plane_b.z() = 1.0f;
  plane_b.w() = 7.0f;

  EXPECT_EQ(2.0f, plane_b.x());
  EXPECT_EQ(1.0f, plane_b.y());
  EXPECT_EQ(1.0f, plane_b.z());
  EXPECT_EQ(7.0f, plane_b.w());

  std::cout << std::endl;
  EXPECT_TRUE(planeWithPlaneIntersection(plane_a, plane_b, line, 0));

  //general planes
  plane_a.x() = 1.555f;
  plane_a.y() = 0.894f;
  plane_a.z() = 1.234f;
  plane_a.w() = 3.567f;

  plane_b.x() = 0.743f;
  plane_b.y() = 1.890f;
  plane_b.z() = 6.789f;
  plane_b.w() = 5.432f;

  std::cout << std::endl;
  EXPECT_TRUE(planeWithPlaneIntersection(plane_a, plane_b, line, 0));

}

//* ---[ */
int
main (int argc, char** argv)
{
  testing::InitGoogleTest (&argc, argv);
  return (RUN_ALL_TESTS ());
}
/* ]--- */

<commit_msg>Trying to solve the test failed on Linux 32bit, attempt number 2<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2010, 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: test_plane_intersection.cpp 5686 2012-05-11 20:59:00Z gioia $
 */

#include <gtest/gtest.h>
#include <pcl/common/common.h>
#include <pcl/common/intersections.h>
#include <pcl/pcl_tests.h>

using namespace pcl;

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, lineWithLineIntersection)
{
  Eigen::VectorXf line_a(6);
  Eigen::VectorXf line_b(6);

  //case 1
  line_a[0] = 0.01f;
  line_a[1] = 0.02f;
  line_a[2] = 0.03f;
  line_a[3] = 0.4f;
  line_a[4] = 0.5f;
  line_a[5] = 0.6f;

  line_b[0] = 0.1f;
  line_b[1] = 0.2f;
  line_b[2] = 0.3f;
  line_b[3] = 0.04f;
  line_b[4] = 0.05f;
  line_b[5] = 0.06f;

  Eigen::Vector4f p1, p2;
  lineToLineSegment (line_a, line_b, p1, p2);

  Eigen::Vector4f point_case_1;
  bool result_case_1 = lineWithLineIntersection(line_a, line_b, point_case_1);

  double sqr_dist_case_1 = (p1 - p2).squaredNorm ();

  double default_sqr_eps = 1e-4;
  EXPECT_GT(sqr_dist_case_1, default_sqr_eps);
  Eigen::Vector4f zero(0.0f, 0.0f, 0.0f, 0.0f);

  EXPECT_EQ(point_case_1[0], zero[0]);
  EXPECT_EQ(point_case_1[1], zero[1]);
  EXPECT_EQ(point_case_1[2], zero[2]);
  EXPECT_EQ(point_case_1[3], zero[3]);

  EXPECT_FALSE(result_case_1);

  pcl::ModelCoefficients line_a_mod;
  pcl::ModelCoefficients line_b_mod;

  std::vector<float> values_a_case_1;
  values_a_case_1.push_back(line_a[0]);
  values_a_case_1.push_back(line_a[1]);
  values_a_case_1.push_back(line_a[2]);
  values_a_case_1.push_back(line_a[3]);
  values_a_case_1.push_back(line_a[4]);
  values_a_case_1.push_back(line_a[5]);

  std::vector<float> values_b_case_1;
  values_b_case_1.push_back(line_b[0]);
  values_b_case_1.push_back(line_b[1]);
  values_b_case_1.push_back(line_b[2]);
  values_b_case_1.push_back(line_b[3]);
  values_b_case_1.push_back(line_b[4]);
  values_b_case_1.push_back(line_b[5]);

  line_a_mod.values = values_a_case_1;
  line_b_mod.values = values_b_case_1;

  Eigen::Vector4f point_mod_1;
  EXPECT_FALSE(lineWithLineIntersection(line_a_mod, line_b_mod, point_mod_1));
  EXPECT_EQ(result_case_1, lineWithLineIntersection(line_a_mod, line_b_mod, point_mod_1));

  EXPECT_EQ(point_mod_1[0], zero[0]);
  EXPECT_EQ(point_mod_1[1], zero[1]);
  EXPECT_EQ(point_mod_1[2], zero[2]);
  EXPECT_EQ(point_mod_1[3], zero[3]);

  //case 2
  line_a[0] = 0.00100f;
  line_a[1] = 0.00200f;
  line_a[2] = 0.00300f;
  line_a[3] = 0.00400f;
  line_a[4] = 0.00500f;
  line_a[5] = 0.00600f;

  line_b[0] = 0.00157f;
  line_b[1] = 0.00233f;
  line_b[2] = 0.00378f;
  line_b[3] = 0.00495f;
  line_b[4] = 0.00565f;
  line_b[5] = 0.00666f;

  lineToLineSegment (line_a, line_b, p1, p2);

  Eigen::Vector4f point_case_2;
  double sqr_eps_case_2 = 1e-1;
  bool result_case_2 = lineWithLineIntersection(line_a, line_b, point_case_2, sqr_eps_case_2);

  double sqr_dist_case_2 = (p1 - p2).squaredNorm ();
  EXPECT_LT(sqr_dist_case_2, sqr_eps_case_2);

  EXPECT_EQ(point_case_2[0], p1[0]);
  EXPECT_EQ(point_case_2[1], p1[1]);
  EXPECT_EQ(point_case_2[2], p1[2]);
  EXPECT_EQ(point_case_2[3], p1[3]);

  EXPECT_TRUE(result_case_2);

  pcl::ModelCoefficients line_a_mod_2;
  pcl::ModelCoefficients line_b_mod_2;

  std::vector<float> values_a_case_2;
  values_a_case_2.push_back(0.1000f);
  values_a_case_2.push_back(0.2000f);
  values_a_case_2.push_back(0.3000f);
  values_a_case_2.push_back(0.4000f);
  values_a_case_2.push_back(0.5000f);
  values_a_case_2.push_back(0.6000f);

  std::vector<float> values_b_case_2;
  values_b_case_2.push_back(0.1001f);
  values_b_case_2.push_back(0.2001f);
  values_b_case_2.push_back(0.3001f);
  values_b_case_2.push_back(0.4001f);
  values_b_case_2.push_back(0.5001f);
  values_b_case_2.push_back(0.6001f);

  line_a_mod_2.values = values_a_case_2;
  line_b_mod_2.values = values_b_case_2;

  Eigen::Vector4f point_mod_2;
  Eigen::Vector4f point_mod_case_2;
  double sqr_mod_case_2 = 1e-1;

  Eigen::VectorXf coeff1 = Eigen::VectorXf::Map (&line_a_mod_2.values[0], line_a_mod_2.values.size ());
  Eigen::VectorXf coeff2 = Eigen::VectorXf::Map (&line_b_mod_2.values[0], line_b_mod_2.values.size ());

  Eigen::Vector4f p1_mod, p2_mod;
  lineToLineSegment (coeff1, coeff2, p1_mod, p2_mod);
  double sqr_mod_act_2 = (p1_mod - p2_mod).squaredNorm ();

  EXPECT_LT(sqr_mod_act_2, sqr_mod_case_2);
  EXPECT_EQ(lineWithLineIntersection (coeff1, coeff2, point_mod_case_2, sqr_mod_case_2),
                        lineWithLineIntersection(line_a_mod_2, line_b_mod_2, point_mod_2, sqr_mod_case_2));
  EXPECT_TRUE(lineWithLineIntersection(line_a_mod_2, line_b_mod_2, point_mod_2, sqr_mod_case_2));

  EXPECT_EQ(point_mod_2[0], point_mod_case_2[0]);
  EXPECT_EQ(point_mod_2[1], point_mod_case_2[1]);
  EXPECT_EQ(point_mod_2[2], point_mod_case_2[2]);
  EXPECT_EQ(point_mod_2[3], point_mod_case_2[3]);

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, planeWithPlaneIntersection)
{
  //Testing parallel planes
  const int k = 2;
  float x = 1.0f;
  float y = 2.0f;
  float z = 3.0f;
  float w = 4.0f;
  Eigen::Vector4f plane_a;
  plane_a.x() = x;
  plane_a.y() = y;
  plane_a.z() = z;
  plane_a.w() = w;

  EXPECT_EQ(1.0f, plane_a.x());
  EXPECT_EQ(2.0f, plane_a.y());
  EXPECT_EQ(3.0f, plane_a.z());
  EXPECT_EQ(4.0f, plane_a.w());

  Eigen::Vector4f plane_b;
  plane_b.x() = x;
  plane_b.y() = y;
  plane_b.z() = z;
  plane_b.w() = w + k;

  EXPECT_EQ(1.0f, plane_b.x());
  EXPECT_EQ(2.0f, plane_b.y());
  EXPECT_EQ(3.0f, plane_b.z());
  EXPECT_EQ(6.0f, plane_b.w());

  Eigen::VectorXf line;

  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 45));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 90));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 180));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 360));

  plane_b.x() = k * x;
  plane_b.y() = k * y;
  plane_b.z() = k * z;
  plane_b.w() = k * w;

  EXPECT_EQ(2.0f, plane_b.x());
  EXPECT_EQ(4.0f, plane_b.y());
  EXPECT_EQ(6.0f, plane_b.z());
  EXPECT_EQ(8.0f, plane_b.w());

  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 45));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 90));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 180));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 360));

  //overlapping planes
  plane_b.w() = w;
  EXPECT_EQ(4.0f, plane_b.w());

  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 45));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 90));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 180));
  std::cout << std::endl;
  EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 360));

  //orthogonal planes
  plane_a.x() = 2.0f;
  plane_a.y() = 1.0f;
  plane_a.z() = -5.0f;
  plane_a.w() = 6.0f;
  EXPECT_EQ(2.0f, plane_a.x());
  EXPECT_EQ(1.0f, plane_a.y());
  EXPECT_EQ(-5.0f, plane_a.z());
  EXPECT_EQ(6.0f, plane_a.w());

  plane_b.x() = 2.0f;
  plane_b.y() = 1.0f;
  plane_b.z() = 1.0f;
  plane_b.w() = 7.0f;

  EXPECT_EQ(2.0f, plane_b.x());
  EXPECT_EQ(1.0f, plane_b.y());
  EXPECT_EQ(1.0f, plane_b.z());
  EXPECT_EQ(7.0f, plane_b.w());

  std::cout << std::endl;
  EXPECT_TRUE(planeWithPlaneIntersection(plane_a, plane_b, line, 0));

  //general planes
  plane_a.x() = 1.555f;
  plane_a.y() = 0.894f;
  plane_a.z() = 1.234f;
  plane_a.w() = 3.567f;

  plane_b.x() = 0.743f;
  plane_b.y() = 1.890f;
  plane_b.z() = 6.789f;
  plane_b.w() = 5.432f;

  std::cout << std::endl;
  EXPECT_TRUE(planeWithPlaneIntersection(plane_a, plane_b, line, 0));

}

//* ---[ */
int
main (int argc, char** argv)
{
  testing::InitGoogleTest (&argc, argv);
  return (RUN_ALL_TESTS ());
}
/* ]--- */

<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015
 * 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 "SoapyHackRF.hpp"
#include <SoapySDR/Registry.hpp>

static std::vector<SoapySDR::Kwargs> find_HackRF(const SoapySDR::Kwargs &args)
{
    std::vector<SoapySDR::Kwargs> results;

	hackrf_device_list_t *list;

	hackrf_init();

	list =hackrf_device_list();

	if (list->devicecount > 0) {

		for (int i = 0; i < list->devicecount; i++) {

			hackrf_device* device = NULL;
			uint8_t board_id = BOARD_ID_INVALID;
			read_partid_serialno_t read_partid_serialno;

			int ret=hackrf_device_list_open(list, i, &device);

			if(ret!=HACKRF_SUCCESS){
				hackrf_device_list_free(list);
				SoapySDR_logf( SOAPY_SDR_INFO, "Could not Open HackRF Device" );
				throw std::runtime_error("hackrf open failed");
			}

			SoapySDR::Kwargs options;

			hackrf_board_id_read(device, &board_id);

			options["device"] = hackrf_board_id_name((hackrf_board_id)board_id);

			char version_str[100];

			hackrf_version_string_read(device, &version_str[0], 100);

			options["version"] = version_str;

			hackrf_board_partid_serialno_read(device, &read_partid_serialno);

			char part_id_str[100];

			sprintf(part_id_str, "%08x%08x", read_partid_serialno.part_id[0], read_partid_serialno.part_id[1]);

			options["part_id"] = part_id_str;

			char serial_str[100];
			sprintf(serial_str, "%08x%08x%08x%08x", read_partid_serialno.serial_no[0], read_partid_serialno.serial_no[1], read_partid_serialno.serial_no[2], read_partid_serialno.serial_no[3]);
			options["serial"] = serial_str;

			results.push_back(options);

			hackrf_close(device);

		}

	}

	hackrf_device_list_free(list);

	hackrf_exit();

	return results;
}

static SoapySDR::Device *make_HackRF(const SoapySDR::Kwargs &args)
{
    return new SoapyHackRF(args);
}

static SoapySDR::Registry register_hackrf("hackrf", &find_HackRF, &make_HackRF, SOAPY_SDR_ABI_VERSION);
<commit_msg>fix mutliple devices hackrf_device_list_open<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015
 * 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 "SoapyHackRF.hpp"
#include <SoapySDR/Registry.hpp>

static std::vector<SoapySDR::Kwargs> find_HackRF(const SoapySDR::Kwargs &args)
{
    std::vector<SoapySDR::Kwargs> results;

	hackrf_device_list_t *list;

	hackrf_init();

	list =hackrf_device_list();

	if (list->devicecount > 0) {

		for (int i = 0; i < list->devicecount; i++) {

			hackrf_device* device = NULL;
			uint8_t board_id = BOARD_ID_INVALID;
			read_partid_serialno_t read_partid_serialno;

			hackrf_device_list_open(list, i, &device);

			SoapySDR::Kwargs options;

			if (device!=NULL) {

				hackrf_board_id_read(device, &board_id);

				options["device"] = hackrf_board_id_name((hackrf_board_id) board_id);

				char version_str[100];

				hackrf_version_string_read(device, &version_str[0], 100);

				options["version"] = version_str;

				hackrf_board_partid_serialno_read(device, &read_partid_serialno);

				char part_id_str[100];

				sprintf(part_id_str, "%08x%08x", read_partid_serialno.part_id[0], read_partid_serialno.part_id[1]);

				options["part_id"] = part_id_str;

				char serial_str[100];
				sprintf(serial_str, "%08x%08x%08x%08x", read_partid_serialno.serial_no[0],
						read_partid_serialno.serial_no[1], read_partid_serialno.serial_no[2],
						read_partid_serialno.serial_no[3]);
				options["serial"] = serial_str;

				results.push_back(options);

				hackrf_close(device);
			}

		}

	}

	hackrf_device_list_free(list);

	hackrf_exit();

	return results;
}

static SoapySDR::Device *make_HackRF(const SoapySDR::Kwargs &args)
{
    return new SoapyHackRF(args);
}

static SoapySDR::Registry register_hackrf("hackrf", &find_HackRF, &make_HackRF, SOAPY_SDR_ABI_VERSION);
<|endoftext|>


<commit_before>/* ioapi.c -- IO base function header for compress/uncompress .zip
   files using zlib + zip or unzip API

   Version 1.01h, December 28th, 2009

   Copyright (C) 1998-2009 Gilles Vollant
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <utki/config.hpp>

#include "zlib.h"
#include "ioapi.h"

/* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */

#ifndef SEEK_CUR
#define SEEK_CUR    1
#endif

#ifndef SEEK_END
#define SEEK_END    2
#endif

#ifndef SEEK_SET
#define SEEK_SET    0
#endif

voidpf ZCALLBACK fopen_file_func OF((
   voidpf opaque,
   const char* filename,
   int mode));

uLong ZCALLBACK fread_file_func OF((
   voidpf opaque,
   voidpf stream,
   void* buf,
   uLong size));

uLong ZCALLBACK fwrite_file_func OF((
   voidpf opaque,
   voidpf stream,
   const void* buf,
   uLong size));

long ZCALLBACK ftell_file_func OF((
   voidpf opaque,
   voidpf stream));

long ZCALLBACK fseek_file_func OF((
   voidpf opaque,
   voidpf stream,
   uLong offset,
   int origin));

int ZCALLBACK fclose_file_func OF((
   voidpf opaque,
   voidpf stream));

int ZCALLBACK ferror_file_func OF((
   voidpf opaque,
   voidpf stream));

voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode){
    FILE* file = NULL;
    const char* mode_fopen = NULL;
    if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
        mode_fopen = "rb";
    else
    if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
        mode_fopen = "r+b";
    else
    if (mode & ZLIB_FILEFUNC_MODE_CREATE)
        mode_fopen = "wb";

	if ((filename != NULL) && (mode_fopen != NULL)) {
#if M_COMPILER == M_COMPILER_MSVC
		fopen_s(&file, filename, mode_fopen);
#else
		file = fopen(filename, mode_fopen);
#endif
	}
    return file;
}

uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong size){
    uLong ret;
    ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream);
    return ret;
}

uLong ZCALLBACK fwrite_file_func (
   voidpf opaque,
   voidpf stream,
   const void* buf,
   uLong size)
{
    uLong ret;
    ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream);
    return ret;
}

long ZCALLBACK ftell_file_func (
   voidpf opaque,
   voidpf stream)
{
    long ret;
    ret = ftell((FILE *)stream);
    return ret;
}

long ZCALLBACK fseek_file_func (
   voidpf opaque,
   voidpf stream,
   uLong offset,
   int origin)
{
    int fseek_origin=0;
    long ret;
    switch (origin)
    {
    case ZLIB_FILEFUNC_SEEK_CUR :
        fseek_origin = SEEK_CUR;
        break;
    case ZLIB_FILEFUNC_SEEK_END :
        fseek_origin = SEEK_END;
        break;
    case ZLIB_FILEFUNC_SEEK_SET :
        fseek_origin = SEEK_SET;
        break;
    default: return -1;
    }
    ret = 0;
    if (fseek((FILE *)stream, offset, fseek_origin) != 0)
        ret = -1;
    return ret;
}

int ZCALLBACK fclose_file_func (
   voidpf opaque,
   voidpf stream)
{
    int ret;
    ret = fclose((FILE *)stream);
    return ret;
}

int ZCALLBACK ferror_file_func (
   voidpf opaque,
   voidpf stream)
{
    int ret;
    ret = ferror((FILE *)stream);
    return ret;
}

void fill_fopen_filefunc (
  zlib_filefunc_def* pzlib_filefunc_def)
{
    pzlib_filefunc_def->zopen_file = fopen_file_func;
    pzlib_filefunc_def->zread_file = fread_file_func;
    pzlib_filefunc_def->zwrite_file = fwrite_file_func;
    pzlib_filefunc_def->ztell_file = ftell_file_func;
    pzlib_filefunc_def->zseek_file = fseek_file_func;
    pzlib_filefunc_def->zclose_file = fclose_file_func;
    pzlib_filefunc_def->zerror_file = ferror_file_func;
    pzlib_filefunc_def->opaque = NULL;
}
<commit_msg>workaround warning about indentation<commit_after>/* ioapi.c -- IO base function header for compress/uncompress .zip
   files using zlib + zip or unzip API

   Version 1.01h, December 28th, 2009

   Copyright (C) 1998-2009 Gilles Vollant
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <utki/config.hpp>

#include "zlib.h"
#include "ioapi.h"

/* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */

#ifndef SEEK_CUR
#define SEEK_CUR    1
#endif

#ifndef SEEK_END
#define SEEK_END    2
#endif

#ifndef SEEK_SET
#define SEEK_SET    0
#endif

voidpf ZCALLBACK fopen_file_func OF((
   voidpf opaque,
   const char* filename,
   int mode));

uLong ZCALLBACK fread_file_func OF((
   voidpf opaque,
   voidpf stream,
   void* buf,
   uLong size));

uLong ZCALLBACK fwrite_file_func OF((
   voidpf opaque,
   voidpf stream,
   const void* buf,
   uLong size));

long ZCALLBACK ftell_file_func OF((
   voidpf opaque,
   voidpf stream));

long ZCALLBACK fseek_file_func OF((
   voidpf opaque,
   voidpf stream,
   uLong offset,
   int origin));

int ZCALLBACK fclose_file_func OF((
   voidpf opaque,
   voidpf stream));

int ZCALLBACK ferror_file_func OF((
   voidpf opaque,
   voidpf stream));

voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode){
    FILE* file = NULL;
    const char* mode_fopen = NULL;
    if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
        mode_fopen = "rb";
    else
    if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
        mode_fopen = "r+b";
    else
    if (mode & ZLIB_FILEFUNC_MODE_CREATE)
        mode_fopen = "wb";

    if ((filename != NULL) && (mode_fopen != NULL)) {
#if M_COMPILER == M_COMPILER_MSVC
        fopen_s(&file, filename, mode_fopen);
#else
        file = fopen(filename, mode_fopen);
#endif
    }
    return file;
}

uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong size){
    uLong ret;
    ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream);
    return ret;
}

uLong ZCALLBACK fwrite_file_func (
   voidpf opaque,
   voidpf stream,
   const void* buf,
   uLong size)
{
    uLong ret;
    ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream);
    return ret;
}

long ZCALLBACK ftell_file_func (
   voidpf opaque,
   voidpf stream)
{
    long ret;
    ret = ftell((FILE *)stream);
    return ret;
}

long ZCALLBACK fseek_file_func (
   voidpf opaque,
   voidpf stream,
   uLong offset,
   int origin)
{
    int fseek_origin=0;
    long ret;
    switch (origin)
    {
    case ZLIB_FILEFUNC_SEEK_CUR :
        fseek_origin = SEEK_CUR;
        break;
    case ZLIB_FILEFUNC_SEEK_END :
        fseek_origin = SEEK_END;
        break;
    case ZLIB_FILEFUNC_SEEK_SET :
        fseek_origin = SEEK_SET;
        break;
    default: return -1;
    }
    ret = 0;
    if (fseek((FILE *)stream, offset, fseek_origin) != 0)
        ret = -1;
    return ret;
}

int ZCALLBACK fclose_file_func (
   voidpf opaque,
   voidpf stream)
{
    int ret;
    ret = fclose((FILE *)stream);
    return ret;
}

int ZCALLBACK ferror_file_func (
   voidpf opaque,
   voidpf stream)
{
    int ret;
    ret = ferror((FILE *)stream);
    return ret;
}

void fill_fopen_filefunc (
  zlib_filefunc_def* pzlib_filefunc_def)
{
    pzlib_filefunc_def->zopen_file = fopen_file_func;
    pzlib_filefunc_def->zread_file = fread_file_func;
    pzlib_filefunc_def->zwrite_file = fwrite_file_func;
    pzlib_filefunc_def->ztell_file = ftell_file_func;
    pzlib_filefunc_def->zseek_file = fseek_file_func;
    pzlib_filefunc_def->zclose_file = fclose_file_func;
    pzlib_filefunc_def->zerror_file = ferror_file_func;
    pzlib_filefunc_def->opaque = NULL;
}
<|endoftext|>


<commit_before>//A ROOT macro that prepares Tree for TMVA training
//----------------------------------------------
//Author: Maxwell Cui
//Date: Aug 19, 2017
//----------------------------------------------

#include<iostream>
#include<cstdlib>
#include<string>
#include<fstream>

void create(TFile* inputTree, TString outputName)
{
  TTree *oldTree=new TTree;
  inputFile->GetObject("nominal_Loose",oldTree);

  //Deactive all branches
  oldTree->SetBranchStatus("*",0);

  //Active the interested branches
  oldTree->SetBranchStatus("ht",1);
  oldTree->SetBranchStatus("met_met",1);
  oldTree->SetBranchStatus("met_sumet",1);
  oldTree->SetBranchStatus("mu_pt",1);
  oldTree->SetBranchStatus("el_pt",1);
  oldTree->SetBranchStatus("mu",1);
  oldTree->SetBranchStatus("jet_pt",1);
  oldTree->SetBranchStatus("met_phi",1);
  oldTree->SetBranchStatus("SSee",1);
  oldTree->SetBranchStatus("SSmm",1);
  oldTree->SetBranchStatus("SSem",1);
  oldTree->SetBranchStatus("eee",1);
  oldTree->SetBranchStatus("eem",1);
  oldTree->SetBranchStatus("emm",1);
  oldTree->SetBranchStatus("mmm",1);
  oldTree->SetBranchStatus("lep_pt",1);
  oldTree->SetBranchStatus("jet_mv2c10",1);   //Using MV2c10 for b-tagging
  //oldTree->SetBranchStatus("weight_mc",1);

  //====================Output file==========================
  //
  TFile *outputFile=new TFile(outputName,"recreate");
  //
  //=========================================================

  //Copy to new tree
  TTree *newTree=oldTree->CloneTree();

  //Working with b-jet
  //
  // Declaration of leaf types
  Float_t         mu;
  vector<float>   *el_pt;
  vector<float>   *mu_pt;
  vector<float>   *jet_pt;
  vector<float>   *jet_mv2c20;
  Float_t         met_met;
  Float_t         met_phi;
  Float_t         met_sumet;
  Int_t           SSee;
  Int_t           SSmm;
  Int_t           SSem;
  Int_t           eee;
  Int_t           eem;
  Int_t           emm;
  Int_t           mmm;
  vector<float>   *lep_pt;
  Float_t         ht;

  // List of branches
  TBranch        *b_mu;   //!
  TBranch        *b_el_pt;   //!
  TBranch        *b_mu_pt;   //!
  TBranch        *b_jet_pt;   //!
  TBranch        *b_jet_mv2c20;   //!
  TBranch        *b_met_met;   //!
  TBranch        *b_met_sumet;
  TBranch        *b_met_phi;   //!
  TBranch        *b_SSee;   //!
  TBranch        *b_SSmm;   //!
  TBranch        *b_SSem;   //!
  TBranch        *b_eee;   //!
  TBranch        *b_eem;   //!
  TBranch        *b_emm;   //!
  TBranch        *b_mmm;   //!
  TBranch        *b_lep_pt;   //!
  TBranch        *b_ht;   //!

  //Set object pointer
  el_pt = 0;
  mu_pt = 0;
  jet_pt = 0;
  jet_mv2c20 = 0;
  lep_pt = 0;

  //Set branch addresses and brunch pointers
  oldTree->SetBranchAddress("mu", &mu, &b_mu);
  oldTree->SetBranchAddress("el_pt", &el_pt, &b_el_pt);
  oldTree->SetBranchAddress("mu_pt", &mu_pt, &b_mu_pt);
  oldTree->SetBranchAddress("jet_pt", &jet_pt, &b_jet_pt);
  oldTree->SetBranchAddress("jet_mv2c20", &jet_mv2c20, &b_jet_mv2c20);
  oldTree->SetBranchAddress("met_met", &met_met, &b_met_met);
  oldTree->SetBranchAddress("met_phi", &met_phi, &b_met_phi);
  oldTree->SetBranchAddress("met_sumet", &met_sumet, &b_met_sumet);
  oldTree->SetBranchAddress("SSee", &SSee, &b_SSee);
  oldTree->SetBranchAddress("SSmm", &SSmm, &b_SSmm);
  oldTree->SetBranchAddress("SSem", &SSem, &b_SSem);
  oldTree->SetBranchAddress("eee", &eee, &b_eee);
  oldTree->SetBranchAddress("eem", &eem, &b_eem);
  oldTree->SetBranchAddress("emm", &emm, &b_emm);
  oldTree->SetBranchAddress("mmm", &mmm, &b_mmm);
  oldTree->SetBranchAddress("lep_pt", &lep_pt, &b_lep_pt);
  oldTree->SetBranchAddress("ht", &ht, &b_ht);

  //Declare bjet variable
  Int_t bjet;

  //Add new branch
  TBranch *bjetBranch=newTree->Branch("bjet",&bjet,"bjet/I");

  Int_t nentries=(Int_t)oldTree->GetEntries();

  //Calculate bjet, algorithm is provided by Prof. Varnes
  for(Int_t i=0;i<nentries;i++)
    {
      oldTree->GetEntry(i);
      bj=0;
      if(SSee || SSem || SSmm || eee || eem || emm || mmm)
      	{
      	  for(unsigned int ibjet=0;ibjet<jet_mv2c10->size();ibjet++)
      	    {
      	      ///     if  (jet_mv2c10->at(ibjet) > 0.1758475) {  // 85% WP
	      if  (jet_mv2c10->at(ibjet) > 0.645925) {  // 77% WP
		//if (jet_mv2c10->at(ibjet) > 0.8244273) {  // 70% WP
		bjet_n++;
	      }

      	    }
      	}
      bjetBranch->Fill();
    }

  newTree->Print();
  newTree->Write();

  outputFile->Close();

  delete oldTree;
}

void prepTree()
{

  //Variable 'envName' can be the environmental variable on the system that
  //includes the path to the directory of the data files.
  //Please make sure that the variable is exported.

  const char* envName="MCDATA";
  std::string dataPATH=std::getenv(envName);

  std::ifstream inputFile("datafiles.txt");
  std::string fileName;

  while(std::getline(inputFile,fileName))
    {
      std::cout<<"Readig file: "<<dataPATH+fileName<<std::endl;
      TFile *bg=new TFile(dataPATH+fileName);
      create(bg,fileName);
      delete bg;
    }
  inputFile.close();
}
<commit_msg>update<commit_after>//A ROOT macro that prepares Tree for TMVA training
//----------------------------------------------
//Author: Maxwell Cui
//Date: Aug 19, 2017
//----------------------------------------------

#include<iostream>
#include<cstdlib>
#include<string>
#include<fstream>

void create(TFile* inputTree, TString outputName)
{
  TTree *oldTree=new TTree;
  inputTree->GetObject("nominal_Loose",oldTree);

  //Deactive all branches
  oldTree->SetBranchStatus("*",0);

  //Active the interested branches
  oldTree->SetBranchStatus("ht",1);
  oldTree->SetBranchStatus("met_met",1);
  oldTree->SetBranchStatus("met_sumet",1);
  oldTree->SetBranchStatus("mu_pt",1);
  oldTree->SetBranchStatus("el_pt",1);
  oldTree->SetBranchStatus("mu",1);
  oldTree->SetBranchStatus("jet_pt",1);
  oldTree->SetBranchStatus("met_phi",1);
  oldTree->SetBranchStatus("SSee",1);
  oldTree->SetBranchStatus("SSmm",1);
  oldTree->SetBranchStatus("SSem",1);
  oldTree->SetBranchStatus("eee",1);
  oldTree->SetBranchStatus("eem",1);
  oldTree->SetBranchStatus("emm",1);
  oldTree->SetBranchStatus("mmm",1);
  oldTree->SetBranchStatus("lep_pt",1);
  oldTree->SetBranchStatus("jet_mv2c10",1);   //Using MV2c10 for b-tagging
  //oldTree->SetBranchStatus("weight_mc",1);

  //====================Output file==========================
  //
  TFile *outputFile=new TFile(outputName,"recreate");
  //
  //=========================================================

  //Copy to new tree
  TTree *newTree=oldTree->CloneTree();

  //Working with b-jet
  //
  // Declaration of leaf types
  Float_t         mu;
  vector<float>   *el_pt;
  vector<float>   *mu_pt;
  vector<float>   *jet_pt;
  vector<float>   *jet_mv2c20;
  Float_t         met_met;
  Float_t         met_phi;
  Float_t         met_sumet;
  Int_t           SSee;
  Int_t           SSmm;
  Int_t           SSem;
  Int_t           eee;
  Int_t           eem;
  Int_t           emm;
  Int_t           mmm;
  vector<float>   *lep_pt;
  Float_t         ht;

  // List of branches
  TBranch        *b_mu;   //!
  TBranch        *b_el_pt;   //!
  TBranch        *b_mu_pt;   //!
  TBranch        *b_jet_pt;   //!
  TBranch        *b_jet_mv2c20;   //!
  TBranch        *b_met_met;   //!
  TBranch        *b_met_sumet;
  TBranch        *b_met_phi;   //!
  TBranch        *b_SSee;   //!
  TBranch        *b_SSmm;   //!
  TBranch        *b_SSem;   //!
  TBranch        *b_eee;   //!
  TBranch        *b_eem;   //!
  TBranch        *b_emm;   //!
  TBranch        *b_mmm;   //!
  TBranch        *b_lep_pt;   //!
  TBranch        *b_ht;   //!

  //Set object pointer
  el_pt = 0;
  mu_pt = 0;
  jet_pt = 0;
  jet_mv2c20 = 0;
  lep_pt = 0;

  //Set branch addresses and brunch pointers
  oldTree->SetBranchAddress("mu", &mu, &b_mu);
  oldTree->SetBranchAddress("el_pt", &el_pt, &b_el_pt);
  oldTree->SetBranchAddress("mu_pt", &mu_pt, &b_mu_pt);
  oldTree->SetBranchAddress("jet_pt", &jet_pt, &b_jet_pt);
  oldTree->SetBranchAddress("jet_mv2c20", &jet_mv2c20, &b_jet_mv2c20);
  oldTree->SetBranchAddress("met_met", &met_met, &b_met_met);
  oldTree->SetBranchAddress("met_phi", &met_phi, &b_met_phi);
  oldTree->SetBranchAddress("met_sumet", &met_sumet, &b_met_sumet);
  oldTree->SetBranchAddress("SSee", &SSee, &b_SSee);
  oldTree->SetBranchAddress("SSmm", &SSmm, &b_SSmm);
  oldTree->SetBranchAddress("SSem", &SSem, &b_SSem);
  oldTree->SetBranchAddress("eee", &eee, &b_eee);
  oldTree->SetBranchAddress("eem", &eem, &b_eem);
  oldTree->SetBranchAddress("emm", &emm, &b_emm);
  oldTree->SetBranchAddress("mmm", &mmm, &b_mmm);
  oldTree->SetBranchAddress("lep_pt", &lep_pt, &b_lep_pt);
  oldTree->SetBranchAddress("ht", &ht, &b_ht);

  //Declare bjet variable
  Int_t bjet;

  //Add new branch
  TBranch *bjetBranch=newTree->Branch("bjet",&bjet,"bjet/I");

  Int_t nentries=(Int_t)oldTree->GetEntries();

  //Calculate bjet, algorithm is provided by Prof. Varnes
  for(Int_t i=0;i<nentries;i++)
    {
      oldTree->GetEntry(i);
      bj=0;
      if(SSee || SSem || SSmm || eee || eem || emm || mmm)
      	{
      	  for(unsigned int ibjet=0;ibjet<jet_mv2c10->size();ibjet++)
      	    {
      	      ///     if  (jet_mv2c10->at(ibjet) > 0.1758475) {  // 85% WP
	      if  (jet_mv2c10->at(ibjet) > 0.645925) {  // 77% WP
		//if (jet_mv2c10->at(ibjet) > 0.8244273) {  // 70% WP
		bjet_n++;
	      }

      	    }
      	}
      bjetBranch->Fill();
    }

  newTree->Print();
  newTree->Write();

  outputFile->Close();

  delete oldTree;
}

void prepTree()
{

  //Variable 'envName' can be the environmental variable on the system that
  //includes the path to the directory of the data files.
  //Please make sure that the variable is exported.

  const char* envName="MCDATA";
  std::string dataPATH=std::getenv(envName);

  std::ifstream inputFile("datafiles.txt");
  std::string fileName;

  while(std::getline(inputFile,fileName))
    {
      std::cout<<"Readig file: "<<dataPATH+fileName<<std::endl;
      TFile *bg=new TFile(dataPATH+fileName);
      create(bg,fileName);
      delete bg;
    }
  inputFile.close();
}
<|endoftext|>


<commit_before>#ifndef __Data_general__
#define __Data_general__

#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <algorithm>    // has the for_each

using namespace std;

enum GenEd {
	// Foundation Studies
	FYW,   // First-Year Writing
	WRI,   // Writing in Context
	FOL,   // Foreign Language
	ORC,   // Oral Communication
	AQR,   // Abstract and Quantitative Reasoning
	SPM,   // Studies in Physical Movement

	// Core Studies
	HWC,   // Historical Studies in Western Culture
	MCD,   // Multicultural Studies: Domestic
	MCG,   // Multicultural Studies: Global
	ALSA,  // Artistic and Literary Studies: Artistic Studies
	ALSL,  // Artistic and Literary Studies: Literary Studies
	BTSB,  // Biblical and Theological Studies: Bible
	BTST,  // Biblical and Theological Studies: Theology
	SED,   // Studies in Natural Science: Scientific Exploration and Discovery
	IST,   // Studies in Natural Science: Integrated Scientific Topics
	HBS,   // Studies in Human Behavior and Society

	// Integrative Studies
	EIN    // Ethical Issues and Normative Perspectives
};

enum dept_t {
	AFAM,  //0 Africa and the Americas
	ALSO,  //1 Alternate Language Study Option
	AMCON, //2 American Conversation
	AMST,  //3 American Studies
	ARMS,  //4 American Racial and Multicultural Studies
	ART,   //5 Art and Art History
	ASIAN, //6 Asian Studies (AS)
	BIO,   //7 Biology (BI)
	BMOLS, //8 Biomolecular Science
	CHEM,  //9 Chemistry (CH)
	CHIN,  //10 Chinese
	CLASS, //11 Classics
	CSCI,  //12 Computer Science
	DANCE, //13 Dance
	ECON,  //14 Economics
	EDUC,  //15 Education
	ENGL,  //16 English
	ENVST, //17 Environmental Studies (ES)
	ESAC,  //18 Exercise Science Activity
	ESTH,  //19 Exercise Science Theory
	FAMST, //20 Family Studies
	FILM,  //21 Film Studies
	FREN,  //22 French
	GCON,  //23 Great Conversation
	GERM,  //24 German
	GREEK, //25 Greek
	HIST,  //26 History (HI)
	HSPST, //27 Hispanic Studies
	// Note: INTER used to be ID, but there was a system conflict.
	IDFA,  //28
	INTD,  //29 Interdepartmental
	INTER, //30 Interdisciplinary
	IS,    //31 Integrative Studies
	JAPAN, //32 Japanese
	LATIN, //33 Latin
	MATH,  //34 Mathematics
	MEDIA, //35 Media Studies
	MEDVL, //36 Medieval Studies
	MGMT,  //37 Management Studies
	MUSIC, //38 Music
	MUSPF, //39 Music Performance
	NEURO, //40 Neuroscience
	NORW,  //41 Norwegian
	NURS,  //42 Nursing
	PHIL,  //43 Philosphy
	PHYS,  //44 Physics
	PSCI,  //45 Political Science
	PSYCH, //46 Psychology
	REL,   //47 Religion (RE)
	RUSSN, //48 Russian
	SCICN, //49 Science Conversation
	SOAN,  //50 Sociology and Anthropology
	SPAN,  //51 Spanish
	STAT,  //52 Statistics
	SWRK,  //53 Social Work
	THEAT, //54 Theater
	WMGST, //55 Women's & Gender Studies
	WRIT,  //56 Writing
	NONE,
};

string tostring(int i) {
	ostringstream tmp;
	tmp << i;
	return tmp.str();
}

int stringToInt(string const& str) {
	istringstream i(str);
	int x;
	i >> x;
	return x;
}

float stringToFloat(string const& str) {
	istringstream i(str);
	float x;
	i >> x;
	return x;
}

vector<string> &split(const string &s, char delim, vector<string> &elems) {
	stringstream ss(s);
	string item;
	while (getline(ss, item, delim)) {
		elems.push_back(item);
	}
	return elems;
}

vector<string> split(const string &s, char delim) {
	// taken from http://stackoverflow.com/a/236803
	vector<string> elems;
	split(s, delim, elems);
	return elems;
}

string removeAllQuotes(string s) {
	s.erase(remove(s.begin(), s.end(), '\"'), s.end());
	return s;
}
string removeTrailingSlashes(string s) {
	s.erase(remove(s.begin(), s.end(), '/'), s.end());
	return s;
}
string removeTrailingText(string s, string toRemove) {
	if (s.find(toRemove) != s.npos)
		s.erase(s.find(toRemove));
	return s;
}

#endif
<commit_msg>Add more methods to data-general<commit_after>#ifndef __Data_general__
#define __Data_general__

#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <algorithm>    // has the for_each

using namespace std;

enum GenEd {
	// Foundation Studies
	FYW,   // First-Year Writing
	WRI,   // Writing in Context
	FOL,   // Foreign Language
	ORC,   // Oral Communication
	AQR,   // Abstract and Quantitative Reasoning
	SPM,   // Studies in Physical Movement

	// Core Studies
	HWC,   // Historical Studies in Western Culture
	MCD,   // Multicultural Studies: Domestic
	MCG,   // Multicultural Studies: Global
	ALSA,  // Artistic and Literary Studies: Artistic Studies
	ALSL,  // Artistic and Literary Studies: Literary Studies
	BTSB,  // Biblical and Theological Studies: Bible
	BTST,  // Biblical and Theological Studies: Theology
	SED,   // Studies in Natural Science: Scientific Exploration and Discovery
	IST,   // Studies in Natural Science: Integrated Scientific Topics
	HBS,   // Studies in Human Behavior and Society

	// Integrative Studies
	EIN    // Ethical Issues and Normative Perspectives
};

enum dept_t {
	AFAM,  //0 Africa and the Americas
	ALSO,  //1 Alternate Language Study Option
	AMCON, //2 American Conversation
	AMST,  //3 American Studies
	ARMS,  //4 American Racial and Multicultural Studies
	ART,   //5 Art and Art History
	ASIAN, //6 Asian Studies (AS)
	BIO,   //7 Biology (BI)
	BMOLS, //8 Biomolecular Science
	CHEM,  //9 Chemistry (CH)
	CHIN,  //10 Chinese
	CLASS, //11 Classics
	CSCI,  //12 Computer Science
	DANCE, //13 Dance
	ECON,  //14 Economics
	EDUC,  //15 Education
	ENGL,  //16 English
	ENVST, //17 Environmental Studies (ES)
	ESAC,  //18 Exercise Science Activity
	ESTH,  //19 Exercise Science Theory
	FAMST, //20 Family Studies
	FILM,  //21 Film Studies
	FREN,  //22 French
	GCON,  //23 Great Conversation
	GERM,  //24 German
	GREEK, //25 Greek
	HIST,  //26 History (HI)
	HSPST, //27 Hispanic Studies
	// Note: INTER used to be ID, but there was a system conflict.
	IDFA,  //28
	INTD,  //29 Interdepartmental
	INTER, //30 Interdisciplinary
	IS,    //31 Integrative Studies
	JAPAN, //32 Japanese
	LATIN, //33 Latin
	MATH,  //34 Mathematics
	MEDIA, //35 Media Studies
	MEDVL, //36 Medieval Studies
	MGMT,  //37 Management Studies
	MUSIC, //38 Music
	MUSPF, //39 Music Performance
	NEURO, //40 Neuroscience
	NORW,  //41 Norwegian
	NURS,  //42 Nursing
	PHIL,  //43 Philosphy
	PHYS,  //44 Physics
	PSCI,  //45 Political Science
	PSYCH, //46 Psychology
	REL,   //47 Religion (RE)
	RUSSN, //48 Russian
	SCICN, //49 Science Conversation
	SOAN,  //50 Sociology and Anthropology
	SPAN,  //51 Spanish
	STAT,  //52 Statistics
	SWRK,  //53 Social Work
	THEAT, //54 Theater
	WMGST, //55 Women's & Gender Studies
	WRIT,  //56 Writing
	NONE,
};

string tostring(int i) {
	ostringstream tmp;
	tmp << i;
	return tmp.str();
}

int stringToInt(string const& str) {
	istringstream i(str);
	int x;
	i >> x;
	return x;
}

float stringToFloat(string const& str) {
	istringstream i(str);
	float x;
	i >> x;
	return x;
}

vector<string> &split(const string &s, char delim, vector<string> &elems) {
	stringstream ss(s);
	string item;
	while (getline(ss, item, delim)) {
		elems.push_back(item);
	}
	return elems;
}

vector<string> split(const string &s, char delim) {
	// taken from http://stackoverflow.com/a/236803
	vector<string> elems;
	split(s, delim, elems);
	return elems;
}

string removeAllQuotes(string s) {
	s.erase(remove(s.begin(), s.end(), '\"'), s.end());
	return s;
}
string removeTrailingSlashes(string s) {
	s.erase(remove(s.begin(), s.end(), '/'), s.end());
	return s;
}
string removeTrailingText(string s, string toRemove) {
	if (s.find(toRemove) != s.npos)
		s.erase(s.find(toRemove));
	return s;
}
string removeStartingText(string s, string toRemove) {
	if (s.find(toRemove) != s.npos)
		s.erase(s.find_first_of(toRemove), s.find_first_of(toRemove)+toRemove.length());
	return s;
}

string deDoubleString(string s) {
	// Todo: write this.
	return s;
}

#endif
<|endoftext|>


<commit_before>#include "acmacs-base/acmacsd.hh"
#include "acmacs-base/fmt.hh"
#include "acmacs-base/argv.hh"
#include "acmacs-base/filesystem.hh"
#include "acmacs-base/temp-file.hh"
#include "acmacs-base/string-split.hh"
#include "acmacs-base/quicklook.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-map-draw/draw.hh"
#include "acmacs-map-draw/mod-applicator.hh"
#include "acmacs-map-draw/setup-dbs.hh"

// ----------------------------------------------------------------------

using namespace acmacs::argv;
struct Options : public argv
{
    Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }

    option<size_t>    p1{*this, "p1", dflt{0UL}, desc{"projection number of the first chart"}};
    option<size_t>    p2{*this, "p2", dflt{0UL}, desc{"projection number of the second chart"}};
    option<str_array> settings{*this, 's', desc{"settings.json (multiple -s possible)"}};
    option<double>    threshold{*this, "threshold", dflt{0.1}, desc{"arrow threshold"}};
    option<str>       subset{*this, "subset", dflt{"all"}, desc{"all, antigens, sera"}};
    option<str>       subset_antigens_clade{*this, "subset-antigens-clade", desc{"for antigens from this clade only"}};
    option<bool>      report{*this, "report", desc{"report common antigens/sera"}};
    option<bool>      clade{*this, "clade", desc{"color by clade"}};
    option<str>       viewport{*this, "viewport", dflt{""}, desc{"\"rel\" array of viewport, e.g. 2,2,-4"}};
    option<bool>      ql{*this, "ql"};
    option<bool>      open{*this, "open"};
    option<bool>      verbose{*this, 'v', "verbose"};

    argument<str>     chart1{*this, arg_name{"chart"}, mandatory};
    argument<str>     chart2{*this, arg_name{"secondary-chart"}};
    argument<str>     pdf{*this, arg_name{"output-pdf"}};
};

int main(int argc, char* const argv[])
{
    using namespace std::string_view_literals;
    int exit_code = 0;
    try {
        Options opt(argc, argv);
        ChartDraw chart_draw(std::make_shared<acmacs::chart::ChartModify>(acmacs::chart::import_from_file(opt.chart1, acmacs::chart::Verify::None, report_time::no)), opt.p1);
        const std::string secondary_chart((!opt.chart2->empty() && !string::endswith(*opt.chart2, ".pdf"sv)) ? opt.chart2 : opt.chart1);

        rjson::value settings{rjson::object{{"apply", rjson::array{"title"}}}};
        for (const auto& settings_file_name : {"acmacs-map-draw.json"sv}) {
            if (const auto filename = fmt::format("{}/share/conf/{}", acmacs::acmacsd_root(), settings_file_name); fs::exists(filename))
                settings.update(rjson::parse_file(filename, rjson::remove_comments::no));
            else
                fmt::print(stderr, "WARNING: cannot load \"{}\": file not found\n", filename);
        }
        for (auto fn : *opt.settings)
            settings.update(rjson::parse_file(fn, rjson::remove_comments::no));

        if (!opt.viewport->empty()) {
            const auto values = acmacs::string::split_into_double(*opt.viewport);
            settings["apply"].append(rjson::object{{"N", "viewport"}, {"rel", rjson::array(values.begin(), values.end())}});
        }
        if (opt.clade) {
            settings["apply"].append("size_reset");
            settings["apply"].append("all_grey");
            settings["apply"].append("egg");
            settings["apply"].append("clades");
            settings["apply"].append("vaccines");
        }

        if (opt.subset_antigens_clade.has_value())
            settings["apply"].append(rjson::object{{"N", "procrustes_arrows"},
                                                   {"chart", secondary_chart},
                                                   {"projection", *opt.p2},
                                                   {"subset_antigens", rjson::object{{"clade", *opt.subset_antigens_clade}}},
                                                   {"threshold", *opt.threshold},
                                                   {"report", *opt.report}});
        else
            settings["apply"].append(
                rjson::object{{"N", "procrustes_arrows"}, {"chart", secondary_chart}, {"projection", *opt.p2}, {"subset", *opt.subset}, {"threshold", *opt.threshold}, {"report", *opt.report}});

        try {
            apply_mods(chart_draw, settings["apply"], settings, acmacs::verbose_from(opt.verbose));
        }
        catch (std::exception& err) {
            // throw std::runtime_error{fmt::format("Cannot apply {}: {}\n settings:\n{}\n", settings["apply"], err, rjson::pretty(settings, rjson::emacs_indent::no))};
            throw std::runtime_error{fmt::format("{}", err)};
        }

        chart_draw.calculate_viewport();

        const std::string output_file{!opt.chart2->empty() && string::endswith(*opt.chart2, ".pdf"sv) ? *opt.chart2 : *opt.pdf};
        acmacs::file::temp temp_file(".pdf");
        const std::string output = output_file.empty() ? static_cast<std::string>(temp_file) : output_file;
        chart_draw.draw(output, 800, report_time::yes);

        if (opt.open || opt.ql || output_file.empty())
            acmacs::open_or_quicklook(opt.open || (output_file.empty() && !opt.ql), opt.ql, output);
    }
    catch (std::exception& err) {
        fmt::print(stderr, "ERROR {}\n", err);
        exit_code = 2;
    }
    return exit_code;
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>acmacs::string::endswith()<commit_after>#include "acmacs-base/acmacsd.hh"
#include "acmacs-base/fmt.hh"
#include "acmacs-base/argv.hh"
#include "acmacs-base/filesystem.hh"
#include "acmacs-base/temp-file.hh"
#include "acmacs-base/string-split.hh"
#include "acmacs-base/quicklook.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-map-draw/draw.hh"
#include "acmacs-map-draw/mod-applicator.hh"
#include "acmacs-map-draw/setup-dbs.hh"

// ----------------------------------------------------------------------

using namespace acmacs::argv;
struct Options : public argv
{
    Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }

    option<size_t>    p1{*this, "p1", dflt{0UL}, desc{"projection number of the first chart"}};
    option<size_t>    p2{*this, "p2", dflt{0UL}, desc{"projection number of the second chart"}};
    option<str_array> settings{*this, 's', desc{"settings.json (multiple -s possible)"}};
    option<double>    threshold{*this, "threshold", dflt{0.1}, desc{"arrow threshold"}};
    option<str>       subset{*this, "subset", dflt{"all"}, desc{"all, antigens, sera"}};
    option<str>       subset_antigens_clade{*this, "subset-antigens-clade", desc{"for antigens from this clade only"}};
    option<bool>      report{*this, "report", desc{"report common antigens/sera"}};
    option<bool>      clade{*this, "clade", desc{"color by clade"}};
    option<str>       viewport{*this, "viewport", dflt{""}, desc{"\"rel\" array of viewport, e.g. 2,2,-4"}};
    option<bool>      ql{*this, "ql"};
    option<bool>      open{*this, "open"};
    option<bool>      verbose{*this, 'v', "verbose"};

    argument<str>     chart1{*this, arg_name{"chart"}, mandatory};
    argument<str>     chart2{*this, arg_name{"secondary-chart"}};
    argument<str>     pdf{*this, arg_name{"output-pdf"}};
};

int main(int argc, char* const argv[])
{
    using namespace std::string_view_literals;
    int exit_code = 0;
    try {
        Options opt(argc, argv);
        ChartDraw chart_draw(std::make_shared<acmacs::chart::ChartModify>(acmacs::chart::import_from_file(opt.chart1, acmacs::chart::Verify::None, report_time::no)), opt.p1);
        const std::string secondary_chart((!opt.chart2->empty() && !acmacs::string::endswith(*opt.chart2, ".pdf"sv)) ? opt.chart2 : opt.chart1);

        rjson::value settings{rjson::object{{"apply", rjson::array{"title"}}}};
        for (const auto& settings_file_name : {"acmacs-map-draw.json"sv}) {
            if (const auto filename = fmt::format("{}/share/conf/{}", acmacs::acmacsd_root(), settings_file_name); fs::exists(filename))
                settings.update(rjson::parse_file(filename, rjson::remove_comments::no));
            else
                fmt::print(stderr, "WARNING: cannot load \"{}\": file not found\n", filename);
        }
        for (auto fn : *opt.settings)
            settings.update(rjson::parse_file(fn, rjson::remove_comments::no));

        if (!opt.viewport->empty()) {
            const auto values = acmacs::string::split_into_double(*opt.viewport);
            settings["apply"].append(rjson::object{{"N", "viewport"}, {"rel", rjson::array(values.begin(), values.end())}});
        }
        if (opt.clade) {
            settings["apply"].append("size_reset");
            settings["apply"].append("all_grey");
            settings["apply"].append("egg");
            settings["apply"].append("clades");
            settings["apply"].append("vaccines");
        }

        if (opt.subset_antigens_clade.has_value())
            settings["apply"].append(rjson::object{{"N", "procrustes_arrows"},
                                                   {"chart", secondary_chart},
                                                   {"projection", *opt.p2},
                                                   {"subset_antigens", rjson::object{{"clade", *opt.subset_antigens_clade}}},
                                                   {"threshold", *opt.threshold},
                                                   {"report", *opt.report}});
        else
            settings["apply"].append(
                rjson::object{{"N", "procrustes_arrows"}, {"chart", secondary_chart}, {"projection", *opt.p2}, {"subset", *opt.subset}, {"threshold", *opt.threshold}, {"report", *opt.report}});

        try {
            apply_mods(chart_draw, settings["apply"], settings, acmacs::verbose_from(opt.verbose));
        }
        catch (std::exception& err) {
            // throw std::runtime_error{fmt::format("Cannot apply {}: {}\n settings:\n{}\n", settings["apply"], err, rjson::pretty(settings, rjson::emacs_indent::no))};
            throw std::runtime_error{fmt::format("{}", err)};
        }

        chart_draw.calculate_viewport();

        const std::string output_file{!opt.chart2->empty() && acmacs::string::endswith(*opt.chart2, ".pdf"sv) ? *opt.chart2 : *opt.pdf};
        acmacs::file::temp temp_file(".pdf");
        const std::string output = output_file.empty() ? static_cast<std::string>(temp_file) : output_file;
        chart_draw.draw(output, 800, report_time::yes);

        if (opt.open || opt.ql || output_file.empty())
            acmacs::open_or_quicklook(opt.open || (output_file.empty() && !opt.ql), opt.ql, output);
    }
    catch (std::exception& err) {
        fmt::print(stderr, "ERROR {}\n", err);
        exit_code = 2;
    }
    return exit_code;
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>/*
   This file is part of the KDE project
   Copyright (C) 2002-2003 Daniel Molkentin <molkentin@kde.org>
   Copyright (C) 2004-2006 Michael Brade <brade@kde.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; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

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

#include <QMenu>
#include <QClipboard>
#include <QApplication>

#include <kactioncollection.h>
#include <kdebug.h>
#include <kaction.h>
#include <kmessagebox.h>
#include <kicon.h>
#include "knotes/resourcemanager.h"

#include "knotes_part.h"
#include "knotes_part_p.h"
#include "knotetip.h"
#include "knotesadaptor.h"

KNotesPart::KNotesPart( QObject *parent )
  :  KParts::ReadOnlyPart( parent ),
    mNotesView( new K3IconView() ),
    mNoteTip( new KNoteTip( mNotesView ) ),
    mNoteEditDlg( 0 ),
    mManager( new KNotesResourceManager() )
{
  (void) new KNotesAdaptor( this );
  QDBusConnection::sessionBus().registerObject("/KNotes", this);
  mNoteList.setAutoDelete( true );

  setInstance( new KInstance( "knotes" ) );

  // create the actions
  KAction *action  = new KAction(KIcon("knotes"), i18n("&New"), this);
  actionCollection()->addAction("file_new", action );
  connect(action, SIGNAL(triggered(bool)), SLOT( newNote() ));
  action->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_N));
  action  = new KAction(KIcon("text"), i18n("Rename..."), this);
  actionCollection()->addAction("edit_rename", action );
  connect(action, SIGNAL(triggered(bool)), SLOT( renameNote() ));
  action  = new KAction(KIcon("editdelete"), i18n("Delete"), this);
  actionCollection()->addAction("edit_delete", action );
  connect(action, SIGNAL(triggered(bool)), SLOT( killSelectedNotes() ));
  action->setShortcut(QKeySequence(Qt::Key_Delete));

  // TODO icons: s/editdelete/knotes_delete/ or the other way round in knotes

  // set the view up
  mNotesView->setSelectionMode( Q3IconView::Extended );
  mNotesView->setItemsMovable( false );
  mNotesView->setResizeMode( Q3IconView::Adjust );
  mNotesView->setSorting( true );

  connect( mNotesView, SIGNAL( executed( Q3IconViewItem* ) ),
           this, SLOT( editNote( Q3IconViewItem* ) ) );
  connect( mNotesView, SIGNAL( returnPressed( Q3IconViewItem* ) ),
           this, SLOT( editNote( Q3IconViewItem* ) ) );
  connect( mNotesView, SIGNAL( itemRenamed( Q3IconViewItem* ) ),
           this, SLOT( renamedNote( Q3IconViewItem* ) ) );
  connect( mNotesView, SIGNAL( contextMenuRequested( Q3IconViewItem*, const QPoint& ) ),
           this, SLOT( popupRMB( Q3IconViewItem*, const QPoint& ) ) );
  connect( mNotesView, SIGNAL( onItem( Q3IconViewItem* ) ),
           this, SLOT( slotOnItem( Q3IconViewItem* ) ) );
  connect( mNotesView, SIGNAL( onViewport() ),
           this, SLOT( slotOnViewport() ) );
  connect( mNotesView, SIGNAL( currentChanged( Q3IconViewItem* ) ),
           this, SLOT( slotOnCurrentChanged( Q3IconViewItem* ) ) );

  slotOnCurrentChanged( 0 );

  setWidget( mNotesView );
  setXMLFile( "knotes_part.rc" );

  // connect the resource manager
  connect( mManager, SIGNAL( sigRegisteredNote( KCal::Journal* ) ),
           this, SLOT( createNote( KCal::Journal* ) ) );
  connect( mManager, SIGNAL( sigDeregisteredNote( KCal::Journal* ) ),
           this, SLOT( killNote( KCal::Journal* ) ) );

  // read the notes
  mManager->load();
}

KNotesPart::~KNotesPart()
{
  delete mNoteTip;
  mNoteTip = 0;

  delete mManager;
  mManager = 0;
}

bool KNotesPart::openFile()
{
  return false;
}

// public KNotes D-Bus interface implementation

QString KNotesPart::newNote( const QString& name, const QString& text )
{
  // create the new note
  KCal::Journal *journal = new KCal::Journal();

  // new notes have the current date/time as title if none was given
  if ( !name.isEmpty() )
      journal->setSummary( name );
  else
      journal->setSummary( KGlobal::locale()->formatDateTime( QDateTime::currentDateTime() ) );

  // the body of the note
  journal->setDescription( text );

  // Edit the new note if text is empty
  if ( text.isNull() )
  {
    if ( !mNoteEditDlg )
      mNoteEditDlg = new KNoteEditDlg( widget() );

    mNoteEditDlg->setTitle( journal->summary() );
    mNoteEditDlg->setText( journal->description() );

    if ( mNoteEditDlg->exec() == QDialog::Accepted )
    {
      journal->setSummary( mNoteEditDlg->title() );
      journal->setDescription( mNoteEditDlg->text() );
    }
    else
    {
      delete journal;
      return "";
    }
  }

  mManager->addNewNote( journal );
  mManager->save();

  KNotesIconViewItem *note = mNoteList[ journal->uid() ];
  mNotesView->ensureItemVisible( note );
  mNotesView->setCurrentItem( note );

  return journal->uid();
}

QString KNotesPart::newNoteFromClipboard( const QString& name )
{
  const QString& text = QApplication::clipboard()->text();
  return newNote( name, text );
}

void KNotesPart::killNote( const QString& id )
{
  killNote( id, false );
}

void KNotesPart::killNote( const QString& id, bool force )
{
  KNotesIconViewItem *note = mNoteList[ id ];

  if ( note &&
       ( (!force && KMessageBox::warningContinueCancelList( mNotesView,
                    i18n( "Do you really want to delete this note?" ),
                    QStringList(mNoteList[ id ]->text()), i18n( "Confirm Delete" ),
                    KStandardGuiItem::del() ) == KMessageBox::Continue)
         || force )
     )
  {
    mManager->deleteNote( mNoteList[id]->journal() );
    mManager->save();
  }
}

QString KNotesPart::name( const QString& id ) const
{
  KNotesIconViewItem *note = mNoteList[ id ];
  if ( note )
    return note->text();
  else
    return QString();
}

QString KNotesPart::text( const QString& id ) const
{
  KNotesIconViewItem *note = mNoteList[ id ];
  if ( note )
    return note->journal()->description();
  else
    return QString();
}

void KNotesPart::setName( const QString& id, const QString& newName )
{
  KNotesIconViewItem *note = mNoteList[ id ];
  if ( note ) {
    note->setText( newName );
    mManager->save();
  }
}

void KNotesPart::setText( const QString& id, const QString& newText )
{
  KNotesIconViewItem *note = mNoteList[ id ];
  if ( note ) {
    note->journal()->setDescription( newText );
    mManager->save();
  }
}

QMap<QString, QString> KNotesPart::notes() const
{
  QMap<QString, QString> notes;
  Q3DictIterator<KNotesIconViewItem> it( mNoteList );

  for ( ; it.current(); ++it )
    notes.insert( (*it)->journal()->uid(), (*it)->journal()->summary() );

  return notes;
}

// private stuff

void KNotesPart::killSelectedNotes()
{
  QList<KNotesIconViewItem*> items;
  QStringList notes;

  KNotesIconViewItem *knivi;
  for ( Q3IconViewItem *it = mNotesView->firstItem(); it; it = it->nextItem() ) {
    if ( it->isSelected() ) {
      knivi = static_cast<KNotesIconViewItem *>( it );
      items.append( knivi );
      notes.append( knivi->text() );
    }
  }

  if ( items.isEmpty() )
    return;

  int ret = KMessageBox::warningContinueCancelList( mNotesView,
            i18np( "Do you really want to delete this note?",
                  "Do you really want to delete these %n notes?", items.count() ),
            notes, i18n( "Confirm Delete" ),
            KStandardGuiItem::del() );

  if ( ret == KMessageBox::Continue ) {
    QListIterator<KNotesIconViewItem*> kniviIt( items );
    while ( kniviIt.hasNext() ) {
      mManager->deleteNote( kniviIt.next()->journal() );
    }

    mManager->save();
  }
}

void KNotesPart::popupRMB( Q3IconViewItem *item, const QPoint& pos )
{
  QMenu *contextMenu = NULL;

  if ( item )
    contextMenu = static_cast<QMenu *>( factory()->container( "note_context", this ) );
  else
    contextMenu = static_cast<QMenu *>( factory()->container( "notepart_context", this ) );

  if ( !contextMenu )
    return;

  contextMenu->popup( pos );
}

void KNotesPart::slotOnItem( Q3IconViewItem *i )
{
  // TODO: disable (i.e. setNote( QString::null )) when mouse button pressed

  KNotesIconViewItem *item = static_cast<KNotesIconViewItem *>( i );
  mNoteTip->setNote( item );
}

void KNotesPart::slotOnViewport()
{
  mNoteTip->setNote( 0 );
}

// TODO: also with takeItem, clear(),

// create and kill the icon view item corresponding to the note, edit the note

void KNotesPart::createNote( KCal::Journal *journal )
{
  // make sure all fields are existent, initialize them with default values
  QString property = journal->customProperty( "KNotes", "BgColor" );
  if ( property.isNull() )
    journal->setCustomProperty( "KNotes", "BgColor", "#ffff00" );

  property = journal->customProperty( "KNotes", "FgColor" );
  if ( property.isNull() )
    journal->setCustomProperty( "KNotes", "FgColor", "#000000" );

  property = journal->customProperty( "KNotes", "RichText" );
  if ( property.isNull() )
    journal->setCustomProperty( "KNotes", "RichText", "true" );

  mNoteList.insert( journal->uid(), new KNotesIconViewItem( mNotesView, journal ) );
}

void KNotesPart::killNote( KCal::Journal *journal )
{
  mNoteList.remove( journal->uid() );
}

void KNotesPart::editNote( Q3IconViewItem *item )
{
  if ( !mNoteEditDlg )
    mNoteEditDlg = new KNoteEditDlg( widget() );

  KCal::Journal *journal = static_cast<KNotesIconViewItem *>( item )->journal();
  mNoteEditDlg->setTitle( journal->summary() );
  mNoteEditDlg->setText( journal->description() );

  if ( mNoteEditDlg->exec() == QDialog::Accepted ) {
    item->setText( mNoteEditDlg->title() );
    journal->setDescription( mNoteEditDlg->text() );
    mManager->save();
  }
}

void KNotesPart::renameNote()
{
  mNotesView->currentItem()->rename();
}

void KNotesPart::renamedNote( Q3IconViewItem* )
{
  mManager->save();
}

void KNotesPart::slotOnCurrentChanged( Q3IconViewItem* )
{
  QAction *renameAction = actionCollection()->action( "edit_rename" );
  QAction *deleteAction = actionCollection()->action( "edit_delete" );

  if ( !mNotesView->currentItem() ) {
    renameAction->setEnabled( false );
    deleteAction->setEnabled( false );
  } else {
    renameAction->setEnabled( true );
    deleteAction->setEnabled( true );
  }
}

#include "knotes_part.moc"
#include "knotes_part_p.moc"

<commit_msg>fix a msgmerge error<commit_after>/*
   This file is part of the KDE project
   Copyright (C) 2002-2003 Daniel Molkentin <molkentin@kde.org>
   Copyright (C) 2004-2006 Michael Brade <brade@kde.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; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

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

#include <QMenu>
#include <QClipboard>
#include <QApplication>

#include <kactioncollection.h>
#include <kdebug.h>
#include <kaction.h>
#include <kmessagebox.h>
#include <kicon.h>
#include "knotes/resourcemanager.h"

#include "knotes_part.h"
#include "knotes_part_p.h"
#include "knotetip.h"
#include "knotesadaptor.h"

KNotesPart::KNotesPart( QObject *parent )
  :  KParts::ReadOnlyPart( parent ),
    mNotesView( new K3IconView() ),
    mNoteTip( new KNoteTip( mNotesView ) ),
    mNoteEditDlg( 0 ),
    mManager( new KNotesResourceManager() )
{
  (void) new KNotesAdaptor( this );
  QDBusConnection::sessionBus().registerObject("/KNotes", this);
  mNoteList.setAutoDelete( true );

  setInstance( new KInstance( "knotes" ) );

  // create the actions
  KAction *action  = new KAction(KIcon("knotes"), i18n("&New"), this);
  actionCollection()->addAction("file_new", action );
  connect(action, SIGNAL(triggered(bool)), SLOT( newNote() ));
  action->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_N));
  action  = new KAction(KIcon("text"), i18n("Rename..."), this);
  actionCollection()->addAction("edit_rename", action );
  connect(action, SIGNAL(triggered(bool)), SLOT( renameNote() ));
  action  = new KAction(KIcon("editdelete"), i18n("Delete"), this);
  actionCollection()->addAction("edit_delete", action );
  connect(action, SIGNAL(triggered(bool)), SLOT( killSelectedNotes() ));
  action->setShortcut(QKeySequence(Qt::Key_Delete));

  // TODO icons: s/editdelete/knotes_delete/ or the other way round in knotes

  // set the view up
  mNotesView->setSelectionMode( Q3IconView::Extended );
  mNotesView->setItemsMovable( false );
  mNotesView->setResizeMode( Q3IconView::Adjust );
  mNotesView->setSorting( true );

  connect( mNotesView, SIGNAL( executed( Q3IconViewItem* ) ),
           this, SLOT( editNote( Q3IconViewItem* ) ) );
  connect( mNotesView, SIGNAL( returnPressed( Q3IconViewItem* ) ),
           this, SLOT( editNote( Q3IconViewItem* ) ) );
  connect( mNotesView, SIGNAL( itemRenamed( Q3IconViewItem* ) ),
           this, SLOT( renamedNote( Q3IconViewItem* ) ) );
  connect( mNotesView, SIGNAL( contextMenuRequested( Q3IconViewItem*, const QPoint& ) ),
           this, SLOT( popupRMB( Q3IconViewItem*, const QPoint& ) ) );
  connect( mNotesView, SIGNAL( onItem( Q3IconViewItem* ) ),
           this, SLOT( slotOnItem( Q3IconViewItem* ) ) );
  connect( mNotesView, SIGNAL( onViewport() ),
           this, SLOT( slotOnViewport() ) );
  connect( mNotesView, SIGNAL( currentChanged( Q3IconViewItem* ) ),
           this, SLOT( slotOnCurrentChanged( Q3IconViewItem* ) ) );

  slotOnCurrentChanged( 0 );

  setWidget( mNotesView );
  setXMLFile( "knotes_part.rc" );

  // connect the resource manager
  connect( mManager, SIGNAL( sigRegisteredNote( KCal::Journal* ) ),
           this, SLOT( createNote( KCal::Journal* ) ) );
  connect( mManager, SIGNAL( sigDeregisteredNote( KCal::Journal* ) ),
           this, SLOT( killNote( KCal::Journal* ) ) );

  // read the notes
  mManager->load();
}

KNotesPart::~KNotesPart()
{
  delete mNoteTip;
  mNoteTip = 0;

  delete mManager;
  mManager = 0;
}

bool KNotesPart::openFile()
{
  return false;
}

// public KNotes D-Bus interface implementation

QString KNotesPart::newNote( const QString& name, const QString& text )
{
  // create the new note
  KCal::Journal *journal = new KCal::Journal();

  // new notes have the current date/time as title if none was given
  if ( !name.isEmpty() )
      journal->setSummary( name );
  else
      journal->setSummary( KGlobal::locale()->formatDateTime( QDateTime::currentDateTime() ) );

  // the body of the note
  journal->setDescription( text );

  // Edit the new note if text is empty
  if ( text.isNull() )
  {
    if ( !mNoteEditDlg )
      mNoteEditDlg = new KNoteEditDlg( widget() );

    mNoteEditDlg->setTitle( journal->summary() );
    mNoteEditDlg->setText( journal->description() );

    if ( mNoteEditDlg->exec() == QDialog::Accepted )
    {
      journal->setSummary( mNoteEditDlg->title() );
      journal->setDescription( mNoteEditDlg->text() );
    }
    else
    {
      delete journal;
      return "";
    }
  }

  mManager->addNewNote( journal );
  mManager->save();

  KNotesIconViewItem *note = mNoteList[ journal->uid() ];
  mNotesView->ensureItemVisible( note );
  mNotesView->setCurrentItem( note );

  return journal->uid();
}

QString KNotesPart::newNoteFromClipboard( const QString& name )
{
  const QString& text = QApplication::clipboard()->text();
  return newNote( name, text );
}

void KNotesPart::killNote( const QString& id )
{
  killNote( id, false );
}

void KNotesPart::killNote( const QString& id, bool force )
{
  KNotesIconViewItem *note = mNoteList[ id ];

  if ( note &&
       ( (!force && KMessageBox::warningContinueCancelList( mNotesView,
              // I know this looks silly, but it avoids a duplicated translation with
              // KNotesPart::killSelectedNotes
              i18np( "Do you really want to delete this note?",
                     "Do you really want to delete these %n notes?", 1 ),
                    QStringList(mNoteList[ id ]->text()), i18n( "Confirm Delete" ),
                    KStandardGuiItem::del() ) == KMessageBox::Continue)
         || force )
     )
  {
    mManager->deleteNote( mNoteList[id]->journal() );
    mManager->save();
  }
}

QString KNotesPart::name( const QString& id ) const
{
  KNotesIconViewItem *note = mNoteList[ id ];
  if ( note )
    return note->text();
  else
    return QString();
}

QString KNotesPart::text( const QString& id ) const
{
  KNotesIconViewItem *note = mNoteList[ id ];
  if ( note )
    return note->journal()->description();
  else
    return QString();
}

void KNotesPart::setName( const QString& id, const QString& newName )
{
  KNotesIconViewItem *note = mNoteList[ id ];
  if ( note ) {
    note->setText( newName );
    mManager->save();
  }
}

void KNotesPart::setText( const QString& id, const QString& newText )
{
  KNotesIconViewItem *note = mNoteList[ id ];
  if ( note ) {
    note->journal()->setDescription( newText );
    mManager->save();
  }
}

QMap<QString, QString> KNotesPart::notes() const
{
  QMap<QString, QString> notes;
  Q3DictIterator<KNotesIconViewItem> it( mNoteList );

  for ( ; it.current(); ++it )
    notes.insert( (*it)->journal()->uid(), (*it)->journal()->summary() );

  return notes;
}

// private stuff

void KNotesPart::killSelectedNotes()
{
  QList<KNotesIconViewItem*> items;
  QStringList notes;

  KNotesIconViewItem *knivi;
  for ( Q3IconViewItem *it = mNotesView->firstItem(); it; it = it->nextItem() ) {
    if ( it->isSelected() ) {
      knivi = static_cast<KNotesIconViewItem *>( it );
      items.append( knivi );
      notes.append( knivi->text() );
    }
  }

  if ( items.isEmpty() )
    return;

  int ret = KMessageBox::warningContinueCancelList( mNotesView,
            i18np( "Do you really want to delete this note?",
                  "Do you really want to delete these %n notes?", items.count() ),
            notes, i18n( "Confirm Delete" ),
            KStandardGuiItem::del() );

  if ( ret == KMessageBox::Continue ) {
    QListIterator<KNotesIconViewItem*> kniviIt( items );
    while ( kniviIt.hasNext() ) {
      mManager->deleteNote( kniviIt.next()->journal() );
    }

    mManager->save();
  }
}

void KNotesPart::popupRMB( Q3IconViewItem *item, const QPoint& pos )
{
  QMenu *contextMenu = NULL;

  if ( item )
    contextMenu = static_cast<QMenu *>( factory()->container( "note_context", this ) );
  else
    contextMenu = static_cast<QMenu *>( factory()->container( "notepart_context", this ) );

  if ( !contextMenu )
    return;

  contextMenu->popup( pos );
}

void KNotesPart::slotOnItem( Q3IconViewItem *i )
{
  // TODO: disable (i.e. setNote( QString::null )) when mouse button pressed

  KNotesIconViewItem *item = static_cast<KNotesIconViewItem *>( i );
  mNoteTip->setNote( item );
}

void KNotesPart::slotOnViewport()
{
  mNoteTip->setNote( 0 );
}

// TODO: also with takeItem, clear(),

// create and kill the icon view item corresponding to the note, edit the note

void KNotesPart::createNote( KCal::Journal *journal )
{
  // make sure all fields are existent, initialize them with default values
  QString property = journal->customProperty( "KNotes", "BgColor" );
  if ( property.isNull() )
    journal->setCustomProperty( "KNotes", "BgColor", "#ffff00" );

  property = journal->customProperty( "KNotes", "FgColor" );
  if ( property.isNull() )
    journal->setCustomProperty( "KNotes", "FgColor", "#000000" );

  property = journal->customProperty( "KNotes", "RichText" );
  if ( property.isNull() )
    journal->setCustomProperty( "KNotes", "RichText", "true" );

  mNoteList.insert( journal->uid(), new KNotesIconViewItem( mNotesView, journal ) );
}

void KNotesPart::killNote( KCal::Journal *journal )
{
  mNoteList.remove( journal->uid() );
}

void KNotesPart::editNote( Q3IconViewItem *item )
{
  if ( !mNoteEditDlg )
    mNoteEditDlg = new KNoteEditDlg( widget() );

  KCal::Journal *journal = static_cast<KNotesIconViewItem *>( item )->journal();
  mNoteEditDlg->setTitle( journal->summary() );
  mNoteEditDlg->setText( journal->description() );

  if ( mNoteEditDlg->exec() == QDialog::Accepted ) {
    item->setText( mNoteEditDlg->title() );
    journal->setDescription( mNoteEditDlg->text() );
    mManager->save();
  }
}

void KNotesPart::renameNote()
{
  mNotesView->currentItem()->rename();
}

void KNotesPart::renamedNote( Q3IconViewItem* )
{
  mManager->save();
}

void KNotesPart::slotOnCurrentChanged( Q3IconViewItem* )
{
  QAction *renameAction = actionCollection()->action( "edit_rename" );
  QAction *deleteAction = actionCollection()->action( "edit_delete" );

  if ( !mNotesView->currentItem() ) {
    renameAction->setEnabled( false );
    deleteAction->setEnabled( false );
  } else {
    renameAction->setEnabled( true );
    deleteAction->setEnabled( true );
  }
}

#include "knotes_part.moc"
#include "knotes_part_p.moc"

<|endoftext|>


<commit_before>/*
 *   This file is part of ScalixAdmin.
 *
 *   Copyright (C) 2007 Trolltech ASA. All rights reserved.
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <kaboutdata.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <klocale.h>

#include "mainwindow.h"

static const char description[] = I18N_NOOP("Configuration Tool for Scalix Groupware Konnector");

static KCmdLineOptions options[] =
{
  KCmdLineLastOption
};

int main( int argc, char **argv )
{
  KAboutData aboutData( "scalixadmin", I18N_NOOP("ScalixAdmin"), "1.0", description,
                        KAboutData::License_GPL, "(c) 2007, Tobias Koenig" );
  aboutData.addAuthor( "Tobias Koenig",0, "tokoe@kde.org" );
  KCmdLineArgs::init( argc, argv, &aboutData );
  KCmdLineArgs::addCmdLineOptions( options );

  KApplication app;

  MainWindow *window = new MainWindow;
  window->show();

  app.setMainWidget( window );

  return app.exec();
}
<commit_msg>Make use of the translations<commit_after>/*
 *   This file is part of ScalixAdmin.
 *
 *   Copyright (C) 2007 Trolltech ASA. All rights reserved.
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <kaboutdata.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <klocale.h>

#include "mainwindow.h"

static const char description[] = I18N_NOOP("Configuration Tool for Scalix Groupware Konnector");

static KCmdLineOptions options[] =
{
  KCmdLineLastOption
};

int main( int argc, char **argv )
{
  KAboutData aboutData( "scalixadmin", I18N_NOOP("ScalixAdmin"), "1.0", description,
                        KAboutData::License_GPL, "(c) 2007, Tobias Koenig" );
  aboutData.addAuthor( "Tobias Koenig",0, "tokoe@kde.org" );
  KCmdLineArgs::init( argc, argv, &aboutData );
  KCmdLineArgs::addCmdLineOptions( options );

  KApplication app;

  KGlobal::locale()->insertCatalogue( "scalixadmin" );

  MainWindow *window = new MainWindow;
  window->show();

  app.setMainWidget( window );

  return app.exec();
}
<|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2011
  \file      main.cpp
  \author      (lord.tiran@gmail.com)
  \date      10.05.2009
  \brief       RDO
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- PLATFORM
#include "utils/platform.h"
// ----------------------------------------------------------------------- INCLUDES
#include <iostream>
#include <boost/program_options.hpp>

#ifdef OST_WINDOWS
const std::string SYSTEM_OS = "Windows";
#else
const std::string SYSTEM_OS = "Linux";
#endif
// ----------------------------------------------------------------------- SYNOPSIS
#include "utils/rdocommon.h"
// --------------------------------------------------------------------------------

namespace po = boost::program_options;

const std::string RDO_STUDIO_CONSOLE_VERSION = "0.1.0";
const std::string RDO_LANGUAGE_VERSION = "1.5";

int main(int argc, char *argv[])
{
	po::options_description description("rdo console studio v" +
	                                    RDO_STUDIO_CONSOLE_VERSION + " " +
	                                    SYSTEM_OS + " ( http://rdo.rk9.bmstu.ru )");
	description.add_options()
	        ("help,h", "display help message")
	        ("language,l", "display language version of RDO")
	        ("version,v", "display program version");
	po::variables_map options;
	try {
		po::store(po::parse_command_line(argc, argv, description), options);
	} catch (const std::exception& e) {
		std::cout << "command line error: " << e.what() << std::endl;
	}
	if (options.empty() || options.count("help")) {
		std::cout << description << std::endl;
	}
	else if (options.count("language")) {
		std::cout << "rdo language v" + RDO_LANGUAGE_VERSION << std::endl;
	}
	else if(options.count("version")) {
		std::cout << "rdo console studio v" + RDO_STUDIO_CONSOLE_VERSION << std::endl;
	}
	else {
		// main code slot
	}
	return 0;
}
<commit_msg> - updated rdo_studio_console : added _T() for string<commit_after>/*!
  \copyright (c) RDO-Team, 2011
  \file      main.cpp
  \author      (lord.tiran@gmail.com)
  \date      26.10.2011
  \brief       RDO
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- PLATFORM
#include "utils/platform.h"
// ----------------------------------------------------------------------- INCLUDES
#include <iostream>
#include <boost/program_options.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "utils/rdocommon.h"
// --------------------------------------------------------------------------------

#ifdef OST_WINDOWS
const tstring SYSTEM_OS = _T("Windows");
#else
const tstring SYSTEM_OS = _T("Linux");
#endif

namespace po = boost::program_options;

const tstring RDO_STUDIO_CONSOLE_VERSION = _T("0.1.0");
const tstring RDO_LANGUAGE_VERSION       = _T("1.5");

int main(int argc, char *argv[])
{
	po::options_description description(_T("rdo console studio v") +
	                                    RDO_STUDIO_CONSOLE_VERSION + " " +
	                                    SYSTEM_OS + _T(" ( http://rdo.rk9.bmstu.ru )"));
	description.add_options()
	        _T(("help,h", "display help message"))
	        _T(("language,l", "display language version of RDO"))
	        _T(("version,v", "display program version"));
	po::variables_map options;
	try
	{
		po::store(po::parse_command_line(argc, argv, description), options);
	}
	catch (CREF(std::exception) e)
	{
		std::cout << _T("command line error: ") << e.what() << std::endl;
	}
	if (options.empty() || options.count(_T("help")))
	{
		std::cout << description << std::endl;
	}
	else if (options.count(_T("language")))
	{
		std::cout << _T("rdo language v") + RDO_LANGUAGE_VERSION << std::endl;
	}
	else if (options.count(_T("version")))
	{
		std::cout << _T("rdo console studio v") + RDO_STUDIO_CONSOLE_VERSION << std::endl;
	}
	else
	{
		// main code slot
	}
	return 0;
}
<|endoftext|>


<commit_before>#ifndef WORKER_HPP
#define WORKER_HPP

#include <fixed_function.hpp>
#include <mpsc_bounded_queue.hpp>
#include <atomic>
#include <thread>

/**
 * @brief The Worker class owns task queue and executing thread.
 * In executing thread it tries to pop task from queue. If queue is empty
 * then it tries to steal task from the sibling worker. If stealing was unsuccessful
 * then spins with one millisecond delay.
 */
class Worker {
public:
    typedef FixedFunction<void(), 64> Task;

    /**
     * @brief Worker Constructor.
     * @param queue_size Length of undelaying task queue.
     */
    explicit Worker(size_t queue_size);

    /**
     * @brief start Create the executing thread and start tasks execution.
     * @param id Worker ID.
     * @param steal_donor Sibling worker to steal task from it.
     */
    void start(size_t id, Worker *steal_donor);

    /**
     * @brief stop Stop all worker's thread and stealing activity.
     * Waits until the executing thread became finished.
     */
    void stop();

    /**
     * @brief post Post task to queue.
     * @param handler Handler to be executed in executing thread.
     * @return true on success.
     */
    template <typename Handler>
    bool post(Handler &&handler);

    /**
     * @brief steal Steal one task from this worker queue.
     * @param task Place for stealed task to be stored.
     * @return true on success.
     */
    bool steal(Task &task);

    /**
     * @brief get_worker_id_for_this_thread Return worker ID associated with current thread if exists.
     * @return Worker ID.
     */
    static size_t getWorkerIdForCurrentThread();

private:
    Worker(const Worker&) = delete;
    Worker & operator=(const Worker&) = delete;

    /**
     * @brief thread_func Executing thread function.
     * @param id Worker ID to be associated with this thread.
     * @param steal_donor Sibling worker to steal task from it.
     */
    void threadFunc(size_t id, Worker *steal_donor);

    MPMCBoundedQueue<Task> m_queue;
    std::atomic<bool> m_running_flag;
    std::thread m_thread;
};

/// Implementation

inline Worker::Worker(size_t queue_size)
    : m_queue(queue_size)
    , m_running_flag(true)
{
}

inline void Worker::stop()
{
    m_running_flag.store(false, std::memory_order_relaxed);
    m_thread.join();
}

inline void Worker::start(size_t id, Worker *steal_donor)
{
    m_thread = std::thread(&Worker::threadFunc, this, id, steal_donor);
}

inline static size_t * thread_id()
{
    static thread_local size_t tss_id = -1u;
    return &tss_id;
}

inline size_t Worker::getWorkerIdForCurrentThread()
{
    return *thread_id();
}

template <typename Handler>
inline bool Worker::post(Handler &&handler)
{
    return m_queue.push(std::forward<Handler>(handler));
}

inline bool Worker::steal(Task &task)
{
    return m_queue.pop(task);
}

inline void Worker::threadFunc(size_t id, Worker *steal_donor)
{
    *thread_id() = id;

    Task handler;

    while (m_running_flag.load(std::memory_order_relaxed))
        if (m_queue.pop(handler) || steal_donor->steal(handler)) {
            try {handler();} catch (...) {}
        } else {
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
        }
}

#endif
<commit_msg>Update worker.hpp<commit_after>#ifndef WORKER_HPP
#define WORKER_HPP

#include <fixed_function.hpp>
#include <mpsc_bounded_queue.hpp>
#include <atomic>
#include <thread>

/**
 * @brief The Worker class owns task queue and executing thread.
 * In executing thread it tries to pop task from queue. If queue is empty
 * then it tries to steal task from the sibling worker. If stealing was unsuccessful
 * then spins with one millisecond delay.
 */
class Worker {
public:
    typedef FixedFunction<void(), 64> Task;

    /**
     * @brief Worker Constructor.
     * @param queue_size Length of undelaying task queue.
     */
    explicit Worker(size_t queue_size);

    /**
     * @brief start Create the executing thread and start tasks execution.
     * @param id Worker ID.
     * @param steal_donor Sibling worker to steal task from it.
     */
    void start(size_t id, Worker *steal_donor);

    /**
     * @brief stop Stop all worker's thread and stealing activity.
     * Waits until the executing thread became finished.
     */
    void stop();

    /**
     * @brief post Post task to queue.
     * @param handler Handler to be executed in executing thread.
     * @return true on success.
     */
    template <typename Handler>
    bool post(Handler &&handler);

    /**
     * @brief steal Steal one task from this worker queue.
     * @param task Place for stealed task to be stored.
     * @return true on success.
     */
    bool steal(Task &task);

    /**
     * @brief getWorkerIdForCurrentThread Return worker ID associated with current thread if exists.
     * @return Worker ID.
     */
    static size_t getWorkerIdForCurrentThread();

private:
    Worker(const Worker&) = delete;
    Worker & operator=(const Worker&) = delete;

    /**
     * @brief threadFunc Executing thread function.
     * @param id Worker ID to be associated with this thread.
     * @param steal_donor Sibling worker to steal task from it.
     */
    void threadFunc(size_t id, Worker *steal_donor);

    MPMCBoundedQueue<Task> m_queue;
    std::atomic<bool> m_running_flag;
    std::thread m_thread;
};

/// Implementation

inline Worker::Worker(size_t queue_size)
    : m_queue(queue_size)
    , m_running_flag(true)
{
}

inline void Worker::stop()
{
    m_running_flag.store(false, std::memory_order_relaxed);
    m_thread.join();
}

inline void Worker::start(size_t id, Worker *steal_donor)
{
    m_thread = std::thread(&Worker::threadFunc, this, id, steal_donor);
}

inline static size_t * thread_id()
{
    static thread_local size_t tss_id = -1u;
    return &tss_id;
}

inline size_t Worker::getWorkerIdForCurrentThread()
{
    return *thread_id();
}

template <typename Handler>
inline bool Worker::post(Handler &&handler)
{
    return m_queue.push(std::forward<Handler>(handler));
}

inline bool Worker::steal(Task &task)
{
    return m_queue.pop(task);
}

inline void Worker::threadFunc(size_t id, Worker *steal_donor)
{
    *thread_id() = id;

    Task handler;

    while (m_running_flag.load(std::memory_order_relaxed))
        if (m_queue.pop(handler) || steal_donor->steal(handler)) {
            try {handler();} catch (...) {}
        } else {
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
        }
}

#endif
<|endoftext|>