<commit_before>
#include "accurate_intersections_approx.hpp"
#include "accurate_intersections_incprec.hpp"
#include "accurate_intersections_resultant.hpp"
#include "geometry.hpp"
#include "line.hpp"
#include "quadric.hpp"
#include "quadric_classify.hpp"
#include "timer.hpp"

#include <fstream>
#include <iomanip>
#include <list>
#include <random>

#include <signal.h>
#include <unistd.h>

struct GlobalVars {
  bool run = true;
} globals;

void sigInt(int signum) { globals.run = false; }

template <int dim, typename fptype>
std::list<Geometry::Quadric<dim, fptype>> parseQuadrics(
    const char *fname, int *minExp, int *maxExp) {
  std::ifstream file(fname);
  if(!file.is_open()) {
    return std::list<Geometry::Quadric<dim, fptype>>();
  }
  int buf = 0;
  file >> buf;
  if(minExp != NULL) {
    *minExp = buf;
  }
  file >> buf;
  if(maxExp != NULL) {
    *maxExp = buf;
  }
  if(*minExp > 0) {
    std::cout
        << "Cannot generate a line with these exponents\n"
        << *minExp << ", " << *maxExp << "\n";
    exit(1);
  }
  std::cout << "Using " << *minExp << ", " << *maxExp
            << " as the range of exponents\n";

  using Qf = Geometry::Quadric<dim, fptype>;
  int qtypeCount[QuadricClassify::QUADT_ERRORINVALID];
  for(int i = 0; i < QuadricClassify::QUADT_ERRORINVALID;
      i++)
    qtypeCount[i] = 0;
  std::list<Qf> quads;
  int imQuads = 0;
  int numQuads = 0;
  while(!file.eof()) {
    Qf q;
    file >> q;
    QuadricClassify::QuadType type =
        QuadricClassify::classifyQuadric(q);
    if(!QuadricClassify::isImaginary(type) &&
       type != QuadricClassify::QUADT_ERROR &&
       type != QuadricClassify::QUADT_DEGENERATE &&
       type != QuadricClassify::QUADT_ERRORINVALID) {
      quads.push_back(q);
      qtypeCount[type]++;
    } else {
      std::cout << "Quadric " << numQuads
                << " is invalid, returned type "
                << QuadricClassify::QuadTypeNames[type]
                << "\n";
      imQuads++;
    }
    numQuads++;
  }
  for(int i = 0; i < QuadricClassify::QUADT_ERRORINVALID;
      i++) {
    std::cout << qtypeCount[i] << " "
              << QuadricClassify::QuadTypeNames[i] << "\n";
  }
  return quads;
}

bool isSameInt(mpfr::mpreal int1, mpfr::mpreal int2) {
  /* Use a heuristic on truth to determine whether adjacent
   * intersections occur at the same place.
   * This will basically be a threshold on the largest
   * different bit in the mantissa.
   */
  /* A relative heuristic does not work when one (or both!)
   * is 0 */
  if(int1 == 0.0 || int2 == 0.0) {
    constexpr const double eps = 0.000001;
    return (mpfr::fabs(int1 - int2) < eps);
  }
  mpfr::mpreal largest =
      mpfr::max(mpfr::fabs(int1), mpfr::fabs(int2));
  mp_exp_t largestExp = largest.get_exp();
  mpfr::mpreal diff = mpfr::fabs(int1 - int2);
  int p1 = int1.getPrecision(), p2 = int2.getPrecision();
  int minPrec = std::min(p1, p2);
  mp_exp_t maxExp = largestExp - minPrec * 1 / 48,
           diffExp = diff.get_exp();
  return maxExp >= diffExp;
}

template <typename ListTest, typename ListTrue>
bool validateResults(ListTest &inter, ListTrue &truth) {
  /* Note that because the same method is used to determine
   * if an intersection is in the list, these lists will be
   * the same length
   */
  if(inter->size() != truth->size()) {
    return false;
  }
  auto j = truth->begin();
  for(auto i = inter->begin();
      i != inter->end() || j != truth->end(); i++, j++) {
    if(i->q != j->q || i->intPos != j->intPos) {
      return false;
    }
  }
  return true;
}

template <typename List>
int countIP(List inter) {
  int numIP = 0;
  for(auto i : *inter) numIP += i.incPrecCount();
  return numIP;
}

using rngAlg = std::mt19937_64;

template <int dim, typename fptype>
using randLineGen = Geometry::Line<dim, fptype> (*)(
    rngAlg &rng, int minExp, int maxExp);

template <int dim, typename fptype, typename cmpAlg>
std::shared_ptr<std::list<cmpAlg>> __attribute__((noinline))
runTest(
    std::list<Geometry::Quadric<dim, fptype>> &quads,
    Geometry::Line<dim, fptype> &line, Timer::Timer &timer,
    double eps = std::numeric_limits<fptype>::infinity()) {
  timer.startTimer();
  auto inter =
      Geometry::sortIntersections<dim, fptype, cmpAlg>(
          line, quads, fptype(eps));
  timer.stopTimer();
  return inter;
}

template <int dim, typename fptype>
void intersectionTest(
    std::list<Geometry::Quadric<dim, fptype>> &quads,
    std::ostream &results, const int numTests,
    randLineGen<dim, fptype> rlgf, int minExp, int maxExp) {
  /* First build a scene of quadrics.
   * Then generate random lines on a disk centered at the
   * intersection of the cylinders.
   * Then sort the intersections
   * Finally validate them with a higher precision sort
   */
  using Vf = Geometry::Vector<dim, fptype>;
  using Pf = Geometry::Point<dim, fptype>;
  using Lf = Geometry::Line<dim, fptype>;

  std::random_device rd;
  rngAlg engine(rd());

  const double eps = 0.75 / (2 * quads.size());

  constexpr const int numTestTypes = 3;
  Timer::Timer testTimes[numTestTypes];
  struct TimeArr {
    struct TestData {
      long long ns;
      int numIP;
      bool correct;
    } mpTime, fpTime, resTime;
  } *times = new struct TimeArr[numTests];
  /* Run the tests */
  int t;
  for(t = 0; t < numTests && globals.run; t++) {
    Lf line = rlgf(engine, minExp, maxExp);
    /* Then sort the intersections */
    auto resultant = runTest<
        dim, fptype,
        Geometry::IntersectionResultant<dim, fptype>>(
        quads, line, testTimes[0], eps);
    auto fpApproximate = runTest<
        dim, fptype,
        Geometry::IntersectionApproximate<dim, fptype>>(
        quads, line, testTimes[1], eps);
    auto mpApproximate = runTest<
        dim, fptype,
        Geometry::IntersectionIncreasedPrec<dim, fptype>>(
        quads, line, testTimes[2], eps);

    times[t].resTime.ns = testTimes[0].instant_ns();
    times[t].fpTime.ns = testTimes[1].instant_ns();
    times[t].mpTime.ns = testTimes[2].instant_ns();

    times[t].mpTime.correct =
        validateResults(mpApproximate, resultant);
    times[t].fpTime.correct =
        validateResults(fpApproximate, resultant);

    times[t].resTime.numIP = countIP(resultant);
    times[t].fpTime.numIP = countIP(fpApproximate);
    times[t].mpTime.numIP = countIP(mpApproximate);
  }
  /* Output all of the results */
  results << "Test #, Approximate Times (ns), Approximates "
             "Correct Increased Precs, MP Time (ns), MP "
             "Correct, Resultants, Resultant Time (ns)\n";
  int resTotIP = 0;
  int fpTotIP = 0;
  int mpTotIP = 0;
  int resTotIncorrect = 0;
  int fpTotIncorrect = 0;
  for(int i = 0; i < t; i++) {
    results << i + 1 << ", " << times[i].fpTime.ns << ", "
            << times[i].fpTime.correct << ", "
            << times[i].mpTime.numIP << ", "
            << times[i].mpTime.ns << ", "
            << times[i].mpTime.correct
            << times[i].resTime.numIP << ", "
            << times[i].resTime.ns << "\n";
    resTotIP += times[i].resTime.numIP;
    mpTotIP += times[i].mpTime.numIP;
    resTotIncorrect += 1 - times[i].resTime.correct;
    fpTotIncorrect += 1 - times[i].fpTime.correct;
  }
  results << "\n"
          << "Total FP Time: " << testTimes[1].elapsed_s()
          << "." << std::setw(9) << std::setfill('0')
          << testTimes[1].elapsed_ns() << "\n"
          << "Total FP Disagreements: " << fpTotIncorrect
          << "\n\n"

          << "Total MP Computations: " << mpTotIP << "\n"
          << "Total MP Time (s): "
          << testTimes[2].elapsed_s() << "." << std::setw(9)
          << std::setfill('0') << testTimes[2].elapsed_ns()
          << "\n\n"

          << "Total Resultant Computations: " << resTotIP
          << "\n"
          << "Total Resultant Time (s): "
          << testTimes[0].elapsed_s() << "." << std::setw(9)
          << std::setfill('0') << testTimes[0].elapsed_ns()
          << "\n"
          << "Total Resultant Disagreements: "
          << resTotIncorrect << "\n";
  delete[] times;
}

void lockCPU() {
  const int numCPUs = sysconf(_SC_NPROCESSORS_ONLN);
  const int cpuSets =
      numCPUs / CPU_SETSIZE + ((numCPUs % CPU_SETSIZE) > 0);
  cpu_set_t *cpus = new cpu_set_t[cpuSets];
  const size_t cpuSize = sizeof(cpu_set_t[cpuSets]);
  sched_getaffinity(0, cpuSize, cpus);
  for(int i = 1; i < numCPUs; i++) CPU_CLR(i, cpus);
  CPU_SET(0, cpus);
  sched_setaffinity(0, cpuSize, cpus);
  delete[] cpus;
}

template <typename fptype>
bool checkExp(fptype fpVal, int minExp, int maxExp) {
  if(fpVal == fptype(0.0)) {
    return true;
  }
  GenericFP::fpconvert<fptype> *fpbits =
      reinterpret_cast<GenericFP::fpconvert<fptype> *>(
          &fpVal);
  int exponent = fpbits->exponent;
  exponent -= fpbits->centralExp;
  if(exponent < minExp || exponent > maxExp) {
    return false;
  } else {
    return true;
  }
}

template <int dim, typename fptype>
Geometry::Line<dim, fptype> defRandLine(rngAlg &rng,
                                        int minExp,
                                        int maxExp) {
  constexpr const fptype minPos = 0, maxPos = 1;
  std::uniform_real_distribution<fptype> genPos(minPos,
                                                maxPos);
  std::uniform_real_distribution<fptype> genDir(-1.0, 1.0);
  /* First build the line */
  Geometry::Vector<dim, fptype> lineDir;
  Geometry::Vector<dim, fptype> lineInt;
  for(int i = 0; i < dim; i++) {
    fptype tmp = genPos(rng);
    if(checkExp(tmp, minExp, maxExp)) {
      assert(MathFuncs::MathFuncs<fptype>::abs(tmp) >=
             9.5367431640625e-7);
      lineInt.set(i, tmp);
    }
    tmp = genDir(rng);
    if(checkExp(tmp, minExp, maxExp)) {
      assert(MathFuncs::MathFuncs<fptype>::abs(tmp) >=
             9.5367431640625e-7);
      lineDir.set(i, tmp);
    }
  }
  return Geometry::Line<dim, fptype>(
      Geometry::Point<dim, fptype>(lineInt), lineInt);
}

template <int dim, typename fptype>
Geometry::Line<dim, fptype> cylRandLine(rngAlg &rng,
                                        int minExp,
                                        int maxExp) {
  constexpr const fptype minPos = 0.375, maxPos = 0.625;
  std::uniform_real_distribution<fptype> genPos(minPos,
                                                maxPos);
  std::uniform_real_distribution<fptype> genDir(-1.0, 1.0);
  /* First build the line */
  Geometry::Vector<dim, fptype> lineDir;
  Geometry::Vector<dim, fptype> lineInt;
  lineInt.set(1, genPos(rng));
  for(int i = 0; i < dim; i++) {
    lineInt.set(i, lineInt.get(1));
    lineDir.set(i, genDir(rng));
  }
  lineInt.set(0, genPos(rng));
  return Geometry::Line<dim, fptype>(
      Geometry::Point<dim, fptype>(lineInt), lineInt);
}

int main(int argc, char **argv) {
  using fptype = float;
  constexpr const int dim = 3;
  lockCPU();
  std::list<Geometry::Quadric<dim, fptype>> quads;
  const char *outFName = "results";
  int numTests = 1e4;
  randLineGen<dim, fptype> rlg = cylRandLine<dim, fptype>;
  int minExp, maxExp;
  if(argc > 1) {
    quads = parseQuadrics<dim, fptype>(argv[1], &minExp,
                                       &maxExp);
    rlg = defRandLine<dim, fptype>;
    if(argc > 2) {
      outFName = argv[2];
      if(argc > 3) numTests = atoi(argv[3]);
    }
  } else {
    quads = parseQuadrics<dim, fptype>("cylinders.csg",
                                       &minExp, &maxExp);
  }
  std::ofstream results(outFName);
  signal(SIGINT, sigInt);
  intersectionTest(quads, results, numTests, defRandLine,
                   minExp, maxExp);
  return 0;
}
<commit_msg>Finish fixing the output of the timing intersections test<commit_after>
#include "accurate_intersections_approx.hpp"
#include "accurate_intersections_incprec.hpp"
#include "accurate_intersections_resultant.hpp"
#include "geometry.hpp"
#include "line.hpp"
#include "quadric.hpp"
#include "quadric_classify.hpp"
#include "timer.hpp"

#include <fstream>
#include <iomanip>
#include <list>
#include <random>

#include <signal.h>
#include <unistd.h>

struct GlobalVars {
  bool run = true;
} globals;

void sigInt(int signum) { globals.run = false; }

template <int dim, typename fptype>
std::list<Geometry::Quadric<dim, fptype>> parseQuadrics(
    const char *fname, int *minExp, int *maxExp) {
  std::ifstream file(fname);
  if(!file.is_open()) {
    return std::list<Geometry::Quadric<dim, fptype>>();
  }
  int buf = 0;
  file >> buf;
  if(minExp != NULL) {
    *minExp = buf;
  }
  file >> buf;
  if(maxExp != NULL) {
    *maxExp = buf;
  }
  if(*minExp > 0) {
    std::cout
        << "Cannot generate a line with these exponents\n"
        << *minExp << ", " << *maxExp << "\n";
    exit(1);
  }
  std::cout << "Using " << *minExp << ", " << *maxExp
            << " as the range of exponents\n";

  using Qf = Geometry::Quadric<dim, fptype>;
  int qtypeCount[QuadricClassify::QUADT_ERRORINVALID];
  for(int i = 0; i < QuadricClassify::QUADT_ERRORINVALID;
      i++)
    qtypeCount[i] = 0;
  std::list<Qf> quads;
  int imQuads = 0;
  int numQuads = 0;
  while(!file.eof()) {
    Qf q;
    file >> q;
    QuadricClassify::QuadType type =
        QuadricClassify::classifyQuadric(q);
    if(!QuadricClassify::isImaginary(type) &&
       type != QuadricClassify::QUADT_ERROR &&
       type != QuadricClassify::QUADT_DEGENERATE &&
       type != QuadricClassify::QUADT_ERRORINVALID) {
      quads.push_back(q);
      qtypeCount[type]++;
    } else {
      std::cout << "Quadric " << numQuads
                << " is invalid, returned type "
                << QuadricClassify::QuadTypeNames[type]
                << "\n";
      imQuads++;
    }
    numQuads++;
  }
  for(int i = 0; i < QuadricClassify::QUADT_ERRORINVALID;
      i++) {
    std::cout << qtypeCount[i] << " "
              << QuadricClassify::QuadTypeNames[i] << "\n";
  }
  return quads;
}

bool isSameInt(mpfr::mpreal int1, mpfr::mpreal int2) {
  /* Use a heuristic on truth to determine whether adjacent
   * intersections occur at the same place.
   * This will basically be a threshold on the largest
   * different bit in the mantissa.
   */
  /* A relative heuristic does not work when one (or both!)
   * is 0 */
  if(int1 == 0.0 || int2 == 0.0) {
    constexpr const double eps = 0.000001;
    return (mpfr::fabs(int1 - int2) < eps);
  }
  mpfr::mpreal largest =
      mpfr::max(mpfr::fabs(int1), mpfr::fabs(int2));
  mp_exp_t largestExp = largest.get_exp();
  mpfr::mpreal diff = mpfr::fabs(int1 - int2);
  int p1 = int1.getPrecision(), p2 = int2.getPrecision();
  int minPrec = std::min(p1, p2);
  mp_exp_t maxExp = largestExp - minPrec * 1 / 48,
           diffExp = diff.get_exp();
  return maxExp >= diffExp;
}

template <typename ListTest, typename ListTrue>
bool validateResults(ListTest &inter, ListTrue &truth) {
  /* Note that because the same method is used to determine
   * if an intersection is in the list, these lists will be
   * the same length
   */
  if(inter->size() != truth->size()) {
    return false;
  }
  auto j = truth->begin();
  for(auto i = inter->begin();
      i != inter->end() || j != truth->end(); i++, j++) {
    if(i->q != j->q || i->intPos != j->intPos) {
      return false;
    }
  }
  return true;
}

template <typename List>
int countIP(List inter) {
  int numIP = 0;
  for(auto i : *inter) numIP += i.incPrecCount();
  return numIP;
}

using rngAlg = std::mt19937_64;

template <int dim, typename fptype>
using randLineGen = Geometry::Line<dim, fptype> (*)(
    rngAlg &rng, int minExp, int maxExp);

template <int dim, typename fptype, typename cmpAlg>
std::shared_ptr<std::list<cmpAlg>> __attribute__((noinline))
runTest(
    std::list<Geometry::Quadric<dim, fptype>> &quads,
    Geometry::Line<dim, fptype> &line, Timer::Timer &timer,
    double eps = std::numeric_limits<fptype>::infinity()) {
  timer.startTimer();
  auto inter =
      Geometry::sortIntersections<dim, fptype, cmpAlg>(
          line, quads, fptype(eps));
  timer.stopTimer();
  return inter;
}

template <int dim, typename fptype>
void intersectionTest(
    std::list<Geometry::Quadric<dim, fptype>> &quads,
    std::ostream &results, const int numTests,
    randLineGen<dim, fptype> rlgf, int minExp, int maxExp) {
  /* First build a scene of quadrics.
   * Then generate random lines on a disk centered at the
   * intersection of the cylinders.
   * Then sort the intersections
   * Finally validate them with a higher precision sort
   */
  using Vf = Geometry::Vector<dim, fptype>;
  using Pf = Geometry::Point<dim, fptype>;
  using Lf = Geometry::Line<dim, fptype>;

  std::random_device rd;
  rngAlg engine(rd());

  const double eps = 0.75 / (2 * quads.size());

  constexpr const int numTestTypes = 3;
  Timer::Timer testTimes[numTestTypes];
  struct TimeArr {
    struct TestData {
      long long ns;
      int numIP;
      bool correct;
    } mpTime, fpTime, resTime;
  } *times = new struct TimeArr[numTests];
  /* Run the tests */
  int t;
  for(t = 0; t < numTests && globals.run; t++) {
    Lf line = rlgf(engine, minExp, maxExp);
    /* Then sort the intersections */
    auto resultant = runTest<
        dim, fptype,
        Geometry::IntersectionResultant<dim, fptype>>(
        quads, line, testTimes[0], eps);
    auto fpApproximate = runTest<
        dim, fptype,
        Geometry::IntersectionApproximate<dim, fptype>>(
        quads, line, testTimes[1], eps);
    auto mpApproximate = runTest<
        dim, fptype,
        Geometry::IntersectionIncreasedPrec<dim, fptype>>(
        quads, line, testTimes[2], eps);

    times[t].resTime.ns = testTimes[0].instant_ns();
    times[t].fpTime.ns = testTimes[1].instant_ns();
    times[t].mpTime.ns = testTimes[2].instant_ns();

    times[t].mpTime.correct =
        validateResults(mpApproximate, resultant);
    times[t].fpTime.correct =
        validateResults(fpApproximate, resultant);

    times[t].resTime.numIP = countIP(resultant);
    times[t].fpTime.numIP = countIP(fpApproximate);
    times[t].mpTime.numIP = countIP(mpApproximate);
  }
  /* Output all of the results */
  results << "Test #, Approximate Times (ns), Approximates "
             "Correct, Increased Precs, MP Time (ns), MP "
             "Correct, Resultants, Resultant Time (ns)\n";
  int resTotIP = 0;
  int fpTotIP = 0;
  int mpTotIP = 0;
  int mpTotIncorrect = 0;
  int fpTotIncorrect = 0;
  for(int i = 0; i < t; i++) {
    results << i + 1 << ", "
						<< times[i].fpTime.ns << ", "
            << times[i].fpTime.correct << ", "
            << times[i].mpTime.numIP << ", "
            << times[i].mpTime.ns << ", "
            << times[i].mpTime.correct << ", "
            << times[i].resTime.numIP << ", "
            << times[i].resTime.ns << "\n";
    resTotIP += times[i].resTime.numIP;
    mpTotIP += times[i].mpTime.numIP;
    fpTotIncorrect += 1 - times[i].fpTime.correct;
    mpTotIncorrect += 1 - times[i].mpTime.correct;
  }
  results << "\n"
          << "Total FP Time: " << testTimes[1].elapsed_s()
          << "." << std::setw(9) << std::setfill('0')
          << testTimes[1].elapsed_ns() << "\n"
          << "Total FP Disagreements: " << fpTotIncorrect
          << "\n\n"

          << "Total MP Computations: " << mpTotIP << "\n"
          << "Total MP Time (s): "
          << testTimes[2].elapsed_s() << "." << std::setw(9)
          << std::setfill('0') << testTimes[2].elapsed_ns()
          << "\n"
          << "Total Resultant Disagreements: "
          << mpTotIncorrect << "\n\n"

          << "Total Resultant Computations: " << resTotIP
          << "\n"
          << "Total Resultant Time (s): "
          << testTimes[0].elapsed_s() << "." << std::setw(9)
          << std::setfill('0') << testTimes[0].elapsed_ns()
          << "\n";
  delete[] times;
}

void lockCPU() {
  const int numCPUs = sysconf(_SC_NPROCESSORS_ONLN);
  const int cpuSets =
      numCPUs / CPU_SETSIZE + ((numCPUs % CPU_SETSIZE) > 0);
  cpu_set_t *cpus = new cpu_set_t[cpuSets];
  const size_t cpuSize = sizeof(cpu_set_t[cpuSets]);
  sched_getaffinity(0, cpuSize, cpus);
  for(int i = 1; i < numCPUs; i++) CPU_CLR(i, cpus);
  CPU_SET(0, cpus);
  sched_setaffinity(0, cpuSize, cpus);
  delete[] cpus;
}

template <typename fptype>
bool checkExp(fptype fpVal, int minExp, int maxExp) {
  if(fpVal == fptype(0.0)) {
    return true;
  }
  GenericFP::fpconvert<fptype> *fpbits =
      reinterpret_cast<GenericFP::fpconvert<fptype> *>(
          &fpVal);
  int exponent = fpbits->exponent;
  exponent -= fpbits->centralExp;
  if(exponent < minExp || exponent > maxExp) {
    return false;
  } else {
    return true;
  }
}

template <int dim, typename fptype>
Geometry::Line<dim, fptype> defRandLine(rngAlg &rng,
                                        int minExp,
                                        int maxExp) {
  constexpr const fptype minPos = 0, maxPos = 1;
  std::uniform_real_distribution<fptype> genPos(minPos,
                                                maxPos);
  std::uniform_real_distribution<fptype> genDir(-1.0, 1.0);
  /* First build the line */
  Geometry::Vector<dim, fptype> lineDir;
  Geometry::Vector<dim, fptype> lineInt;
  for(int i = 0; i < dim; i++) {
    fptype tmp = genPos(rng);
    if(checkExp(tmp, minExp, maxExp)) {
      assert(MathFuncs::MathFuncs<fptype>::abs(tmp) >=
             9.5367431640625e-7);
      lineInt.set(i, tmp);
    }
    tmp = genDir(rng);
    if(checkExp(tmp, minExp, maxExp)) {
      assert(MathFuncs::MathFuncs<fptype>::abs(tmp) >=
             9.5367431640625e-7);
      lineDir.set(i, tmp);
    }
  }
  return Geometry::Line<dim, fptype>(
      Geometry::Point<dim, fptype>(lineInt), lineInt);
}

template <int dim, typename fptype>
Geometry::Line<dim, fptype> cylRandLine(rngAlg &rng,
                                        int minExp,
                                        int maxExp) {
  constexpr const fptype minPos = 0.375, maxPos = 0.625;
  std::uniform_real_distribution<fptype> genPos(minPos,
                                                maxPos);
  std::uniform_real_distribution<fptype> genDir(-1.0, 1.0);
  /* First build the line */
  Geometry::Vector<dim, fptype> lineDir;
  Geometry::Vector<dim, fptype> lineInt;
  lineInt.set(1, genPos(rng));
  for(int i = 0; i < dim; i++) {
    lineInt.set(i, lineInt.get(1));
    lineDir.set(i, genDir(rng));
  }
  lineInt.set(0, genPos(rng));
  return Geometry::Line<dim, fptype>(
      Geometry::Point<dim, fptype>(lineInt), lineInt);
}

int main(int argc, char **argv) {
  using fptype = float;
  constexpr const int dim = 3;
  lockCPU();
  std::list<Geometry::Quadric<dim, fptype>> quads;
  const char *outFName = "results";
  int numTests = 1e4;
  randLineGen<dim, fptype> rlg = cylRandLine<dim, fptype>;
  int minExp, maxExp;
  if(argc > 1) {
    quads = parseQuadrics<dim, fptype>(argv[1], &minExp,
                                       &maxExp);
    rlg = defRandLine<dim, fptype>;
    if(argc > 2) {
      outFName = argv[2];
      if(argc > 3) numTests = atoi(argv[3]);
    }
  } else {
    quads = parseQuadrics<dim, fptype>("cylinders.csg",
                                       &minExp, &maxExp);
  }
  std::ofstream results(outFName);
  signal(SIGINT, sigInt);
  intersectionTest(quads, results, numTests, defRandLine,
                   minExp, maxExp);
  return 0;
}
<|endoftext|>


<commit_before>#include <thread>
#include "halley/tools/assets/import_assets_task.h"
#include "halley/tools/assets/check_assets_task.h"
#include "halley/tools/project/project.h"
#include "halley/tools/assets/import_assets_database.h"
#include "halley/resources/resource_data.h"
#include "halley/tools/file/filesystem.h"
#include "halley/tools/assets/asset_collector.h"
#include "halley/concurrency/concurrent.h"
#include "halley/tools/packer/asset_packer_task.h"
#include "halley/support/logger.h"
#include "halley/time/stopwatch.h"
#include "halley/support/debug.h"

using namespace Halley;

ImportAssetsTask::ImportAssetsTask(String taskName, ImportAssetsDatabase& db, std::shared_ptr<AssetImporter> importer, Path assetsPath, Vector<ImportAssetsDatabaseEntry> files, std::vector<String> deletedAssets, Project& project, bool packAfter)
	: EditorTask(taskName, true, true)
	, db(db)
	, importer(importer)
	, assetsPath(assetsPath)
	, project(project)
	, packAfter(packAfter)
	, files(std::move(files))
	, deletedAssets(std::move(deletedAssets))
	, totalImportTime(0)
{}

void ImportAssetsTask::run()
{
	Stopwatch timer;
	using namespace std::chrono_literals;
	auto lastSave = std::chrono::steady_clock::now();

	assetsImported = 0;
	assetsToImport = files.size();
	std::vector<Future<void>> tasks;

	constexpr bool parallelImport = !Debug::isDebug();

	for (size_t i = 0; i < files.size(); ++i) {
		auto importFunc = [&, i] () {
			if (isCancelled()) {
				return;
			}

			if (doImportAsset(files[i])) {
				++assetsImported;
				setProgress(float(assetsImported) * 0.98f / float(assetsToImport), files[i].assetId);
			}

			auto now = std::chrono::steady_clock::now();
			if (now - lastSave > 1s) {
				db.save();
				lastSave = now;
			}
		};

		if (parallelImport) {
			tasks.push_back(Concurrent::execute(Executors::getCPUAux(), importFunc));
		} else {
			importFunc();
		}
	}

	Concurrent::whenAll(tasks.begin(), tasks.end()).get();
	db.save();

	if (!isCancelled()) {
		setProgress(1.0f, "");

		if (!hasError()) {
			if (!outputAssets.empty()) {
				Concurrent::execute(Executors::getMainThread(), [project = &project, assets = outputAssets] () {
					project->reloadAssets(assets, false);
				});
			}

			if (files.size() == 1 && files[0].assetId == ":codegen") {
				Concurrent::execute(Executors::getMainThread(), [project = &project]() {
					project->reloadCodegen();
				});
			}

			if (packAfter) {
				addContinuation(EditorTaskAnchor(std::make_unique<AssetPackerTask>(project, std::move(outputAssets), std::move(deletedAssets))));
			}
		}
	}

	timer.pause();
	Time realTime = timer.elapsedNanoseconds() / 1000000000.0;
	Time importTime = totalImportTime / 1000000000.0;
	Logger::logInfo("Import took " + toString(realTime) + " seconds, on which " + toString(importTime) + " seconds of work were performed (" + toString(importTime / realTime) + "x realtime)");
}

bool ImportAssetsTask::doImportAsset(ImportAssetsDatabaseEntry& asset)
{
	Logger::logInfo("Importing " + asset.assetId);
	Stopwatch timer;

	auto result = importAsset(asset, [&] (const Path& path) { return db.getMetadata(path); }, *importer, assetsPath, [=] (float, const String&) -> bool { return !isCancelled(); });

	if (!result.success) {
		addError("\"" + asset.assetId + "\" - " + result.errorMsg);
		asset.additionalInputFiles = std::move(result.additionalInputs);
		db.markFailed(asset);

		return false;
	}

	// Check if it didn't get cancelled
	if (isCancelled()) {
		return false;
	}

	// Retrieve previous output from this asset, and remove any files which went missing
	auto previous = db.getOutFiles(asset.assetId);
	for (auto& f: previous) {
		for (auto& v: f.platformVersions) {
			if (std::find_if(result.outFiles.begin(), result.outFiles.end(), [&] (const std::pair<Path, Bytes>& r) { return r.first == v.second.filepath; }) == result.outFiles.end()) {
				// File no longer exists as part of this asset, remove it
				FileSystem::remove(assetsPath / v.second.filepath);
			}
		}
	}

	// Write files
	for (auto& outFile: result.outFiles) {
		auto path = assetsPath / outFile.first;
		Logger::logInfo("- " + asset.assetId + " -> " + path + " (" + String::prettySize(outFile.second.size()) + ")");
		FileSystem::writeFile(path, outFile.second);
	}

	// Add to list of output assets
	for (auto& o: result.out) {
		std::unique_lock<std::mutex> lock(mutex);
		outputAssets.insert(toString(o.type) + ":" + o.name);
	}

	// Store output in db
	asset.additionalInputFiles = std::move(result.additionalInputs);
	asset.outputFiles = std::move(result.out);
	db.markAsImported(asset);

	timer.pause();
	totalImportTime += timer.elapsedNanoseconds();

	return true;
}

ImportAssetsTask::ImportResult ImportAssetsTask::importAsset(const ImportAssetsDatabaseEntry& asset, const MetadataFetchCallback& metadataFetcher, const AssetImporter& importer, Path assetsPath, AssetCollector::ProgressReporter progressReporter)
{
	ImportResult result;

	try {
		// Create queue
		std::list<ImportingAsset> toLoad;

		// Load files from disk
		ImportingAsset importingAsset;
		importingAsset.assetId = asset.assetId;
		importingAsset.assetType = asset.assetType;
		for (auto& f: asset.inputFiles) {
			auto meta = metadataFetcher(f.getPath());
			auto data = FileSystem::readFile(asset.srcDir / f.getDataPath());
			if (data.empty()) {
				Logger::logError("Data for \"" + toString(asset.srcDir / f.getPath()) + "\" is empty.");
			}
			importingAsset.inputFiles.emplace_back(ImportingAssetFile(f.getPath(), std::move(data), meta ? meta.value() : Metadata()));
		}
		toLoad.emplace_back(std::move(importingAsset));

		// Import
		while (!toLoad.empty()) {
			auto cur = std::move(toLoad.front());
			toLoad.pop_front();

			AssetCollector collector(cur, assetsPath, importer.getAssetsSrc(), progressReporter);

			for (const auto& importer: importer.getImporters(cur.assetType)) {
				try {
					importer.get().import(cur, collector);
				} catch (...) {
					for (auto& i: collector.getAdditionalInputs()) {
						result.additionalInputs.push_back(std::move(i));
					}
					throw;
				}
			}

			for (auto& additional: collector.collectAdditionalAssets()) {
				toLoad.emplace_front(std::move(additional));
			}

			for (auto& outFile: collector.collectOutFiles()) {
				result.outFiles.push_back(std::move(outFile));
			}

			for (auto& o: collector.getAssets()) {
				result.out.push_back(std::move(o));
			}

			for (auto& i: collector.getAdditionalInputs()) {
				result.additionalInputs.push_back(std::move(i));
			}
		}

		result.success = true;
	} catch (std::exception& e) {
		result.errorMsg = e.what();
		result.success = false;
	}

	return result;
}
<commit_msg>Fix some constness.<commit_after>#include <thread>
#include "halley/tools/assets/import_assets_task.h"
#include "halley/tools/assets/check_assets_task.h"
#include "halley/tools/project/project.h"
#include "halley/tools/assets/import_assets_database.h"
#include "halley/resources/resource_data.h"
#include "halley/tools/file/filesystem.h"
#include "halley/tools/assets/asset_collector.h"
#include "halley/concurrency/concurrent.h"
#include "halley/tools/packer/asset_packer_task.h"
#include "halley/support/logger.h"
#include "halley/time/stopwatch.h"
#include "halley/support/debug.h"

using namespace Halley;

ImportAssetsTask::ImportAssetsTask(String taskName, ImportAssetsDatabase& db, std::shared_ptr<AssetImporter> importer, Path assetsPath, Vector<ImportAssetsDatabaseEntry> files, std::vector<String> deletedAssets, Project& project, bool packAfter)
	: EditorTask(taskName, true, true)
	, db(db)
	, importer(importer)
	, assetsPath(assetsPath)
	, project(project)
	, packAfter(packAfter)
	, files(std::move(files))
	, deletedAssets(std::move(deletedAssets))
	, totalImportTime(0)
{}

void ImportAssetsTask::run()
{
	Stopwatch timer;
	using namespace std::chrono_literals;
	auto lastSave = std::chrono::steady_clock::now();

	assetsImported = 0;
	assetsToImport = files.size();
	std::vector<Future<void>> tasks;

	constexpr bool parallelImport = !Debug::isDebug();

	for (size_t i = 0; i < files.size(); ++i) {
		auto importFunc = [&, i] () {
			if (isCancelled()) {
				return;
			}

			if (doImportAsset(files[i])) {
				++assetsImported;
				setProgress(float(assetsImported) * 0.98f / float(assetsToImport), files[i].assetId);
			}

			auto now = std::chrono::steady_clock::now();
			if (now - lastSave > 1s) {
				db.save();
				lastSave = now;
			}
		};

		if (parallelImport) {
			tasks.push_back(Concurrent::execute(Executors::getCPUAux(), importFunc));
		} else {
			importFunc();
		}
	}

	Concurrent::whenAll(tasks.begin(), tasks.end()).get();
	db.save();

	if (!isCancelled()) {
		setProgress(1.0f, "");

		if (!hasError()) {
			if (!outputAssets.empty()) {
				Concurrent::execute(Executors::getMainThread(), [project = &project, assets = outputAssets] () {
					project->reloadAssets(assets, false);
				});
			}

			if (files.size() == 1 && files[0].assetId == ":codegen") {
				Concurrent::execute(Executors::getMainThread(), [project = &project]() {
					project->reloadCodegen();
				});
			}

			if (packAfter) {
				addContinuation(EditorTaskAnchor(std::make_unique<AssetPackerTask>(project, std::move(outputAssets), std::move(deletedAssets))));
			}
		}
	}

	timer.pause();
	Time realTime = timer.elapsedNanoseconds() / 1000000000.0;
	Time importTime = totalImportTime / 1000000000.0;
	Logger::logInfo("Import took " + toString(realTime) + " seconds, on which " + toString(importTime) + " seconds of work were performed (" + toString(importTime / realTime) + "x realtime)");
}

bool ImportAssetsTask::doImportAsset(ImportAssetsDatabaseEntry& asset)
{
	Logger::logInfo("Importing " + asset.assetId);
	Stopwatch timer;

	auto result = importAsset(asset, [&] (const Path& path) { return db.getMetadata(path); }, *importer, assetsPath, [=] (float, const String&) -> bool { return !isCancelled(); });

	if (!result.success) {
		addError("\"" + asset.assetId + "\" - " + result.errorMsg);
		asset.additionalInputFiles = std::move(result.additionalInputs);
		db.markFailed(asset);

		return false;
	}

	// Check if it didn't get cancelled
	if (isCancelled()) {
		return false;
	}

	// Retrieve previous output from this asset, and remove any files which went missing
	auto previous = db.getOutFiles(asset.assetId);
	for (auto& f: previous) {
		for (auto& v: f.platformVersions) {
			if (std::find_if(result.outFiles.begin(), result.outFiles.end(), [&] (const std::pair<Path, Bytes>& r) { return r.first == v.second.filepath; }) == result.outFiles.end()) {
				// File no longer exists as part of this asset, remove it
				FileSystem::remove(assetsPath / v.second.filepath);
			}
		}
	}

	// Write files
	for (auto& outFile: result.outFiles) {
		auto path = assetsPath / outFile.first;
		Logger::logInfo("- " + asset.assetId + " -> " + path + " (" + String::prettySize(outFile.second.size()) + ")");
		FileSystem::writeFile(path, outFile.second);
	}

	// Add to list of output assets
	for (auto& o: result.out) {
		std::unique_lock<std::mutex> lock(mutex);
		outputAssets.insert(toString(o.type) + ":" + o.name);
	}

	// Store output in db
	asset.additionalInputFiles = std::move(result.additionalInputs);
	asset.outputFiles = std::move(result.out);
	db.markAsImported(asset);

	timer.pause();
	totalImportTime += timer.elapsedNanoseconds();

	return true;
}

ImportAssetsTask::ImportResult ImportAssetsTask::importAsset(const ImportAssetsDatabaseEntry& asset, const MetadataFetchCallback& metadataFetcher, const AssetImporter& importer, Path assetsPath, AssetCollector::ProgressReporter progressReporter)
{
	ImportResult result;

	try {
		// Create queue
		std::list<ImportingAsset> toLoad;

		// Load files from disk
		ImportingAsset importingAsset;
		importingAsset.assetId = asset.assetId;
		importingAsset.assetType = asset.assetType;
		for (const auto& f: asset.inputFiles) {
			auto meta = metadataFetcher(f.getPath());
			auto data = FileSystem::readFile(asset.srcDir / f.getDataPath());
			if (data.empty()) {
				Logger::logError("Data for \"" + toString(asset.srcDir / f.getPath()) + "\" is empty.");
			}
			importingAsset.inputFiles.emplace_back(ImportingAssetFile(f.getPath(), std::move(data), meta ? meta.value() : Metadata()));
		}
		toLoad.emplace_back(std::move(importingAsset));

		// Import
		while (!toLoad.empty()) {
			auto cur = std::move(toLoad.front());
			toLoad.pop_front();

			AssetCollector collector(cur, assetsPath, importer.getAssetsSrc(), progressReporter);

			for (const auto& assetImporter: importer.getImporters(cur.assetType)) {
				try {
					assetImporter.get().import(cur, collector);
				} catch (...) {
					for (const auto& i: collector.getAdditionalInputs()) {
						result.additionalInputs.push_back(i);
					}
					throw;
				}
			}

			for (auto& additional: collector.collectAdditionalAssets()) {
				toLoad.emplace_front(std::move(additional));
			}

			for (auto& outFile: collector.collectOutFiles()) {
				result.outFiles.push_back(std::move(outFile));
			}

			for (const auto& o: collector.getAssets()) {
				result.out.push_back(o);
			}

			for (const auto& i: collector.getAdditionalInputs()) {
				result.additionalInputs.push_back(i);
			}
		}

		result.success = true;
	} catch (std::exception& e) {
		result.errorMsg = e.what();
		result.success = false;
	}

	return result;
}
<|endoftext|>


<commit_before>#include <iostream>
#include<bits/stdc++.h>
using namespace std;

int calculate(int val[], int wt[], int W){
        int K[sizeof(val)/sizeof(val[0])+1][W+1];

        for(int i=0; i <= sizeof(val)/sizeof(val[0]); i++){
            for(int j=0; j <= W; j++){
                if(i == 0 || j == 0){
                    K[i][j] = 0;
                    continue;
                }
                if(j - wt[i-1] >= 0){
                    K[i][j] = max(K[i-1][j], K[i-1][j-wt[i-1]] + val[i-1]);
                }else{
                    K[i][j] = K[i-1][j];
                }
            }
        }
        return K[sizeof(val)/sizeof(val[0])][W];
    }

    int main(){

        int val[] = {60,20,15,30};
        int wt[] = {4,2,3,5};
        int r = calculate(val, wt, 8);
        cout<<r;
    return 0;
    }

<commit_msg>C++ way<commit_after>#include <iostream>
#include<bits/stdc++.h>
using namespace std;

int calculate(int val[], int wt[], int W){
        int K[sizeof(val)/sizeof(val[0])][W+1];
        for(i=0;i<sizeof(sizeof(val)/sizeof(val[0]));i++){
                K[i][0]=0;
        }
        for(j=0;j<W+1;j++){
                K[0][j]=1;
        }

        for(int i=1; i < sizeof(val)/sizeof(val[0]); i++){
            for(int j=0; j <= W; j++){

                if(j - wt[i] >= 0){
                    K[i][j] = max(K[i-1][j], K[i-1][j-wt[i]] + val[i]);
                }else{
                    K[i][j] = K[i-1][j];
                }
            }
        }
        return K[sizeof(val)/sizeof(val[0])][W];
    }

    int main(){

        int val[] = {60,20,15,30};
        int wt[] = {4,2,3,5};
        int r = calculate(val, wt, 8);
        cout<<r;
    return 0;
    }

<|endoftext|>


<commit_before>#include <miopen/temp_file.hpp>
#include <miopen/errors.hpp>

#ifndef WIN32
#include <unistd.h>
#else
#include <Windows.h>
#include <fcntl.h>
#include <io.h>
#define _O_EXCL         0x0400
#define O_EXCL          _O_EXCL
/* mkstemp extracted from libc/sysdeps/posix/tempname.c.  Copyright
(C) 1991-1999, 2000, 2001, 2006 Free Software Foundation, Inc.

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

static const char letters[] =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

/* Generate a temporary file name based on TMPL.  TMPL must match the
rules for mk[s]temp (i.e. end in "XXXXXX").  The name constructed
does not exist at the time of the call to mkstemp.  TMPL is
overwritten with the result.  */
static int
mkstemp(char *tmpl)
{
	int len;
	char *XXXXXX;
	static unsigned long long value;
	unsigned long long random_time_bits;
	unsigned int count;
	int fd = -1;
	int save_errno = errno;

	/* A lower bound on the number of temporary files to attempt to
	generate.  The maximum total number of temporary file names that
	can exist for a given template is 62**6.  It should never be
	necessary to try all these combinations.  Instead if a reasonable
	number of names is tried (we define reasonable as 62**3) fail to
	give the system administrator the chance to remove the problems.  */
#define ATTEMPTS_MIN (62 * 62 * 62)

	/* The number of times to attempt to generate a temporary file.  To
	conform to POSIX, this must be no smaller than TMP_MAX.  */
#if ATTEMPTS_MIN < TMP_MAX
	unsigned int attempts = TMP_MAX;
#else
	unsigned int attempts = ATTEMPTS_MIN;
#endif

	len = strlen(tmpl);
	if (len < 6 || strcmp(&tmpl[len - 6], "XXXXXX"))
	{
		errno = EINVAL;
		return -1;
	}

	/* This is where the Xs start.  */
	XXXXXX = &tmpl[len - 6];

	/* Get some more or less random data.  */
	{
		SYSTEMTIME      stNow;
		FILETIME ftNow;

		// get system time
		GetSystemTime(&stNow);
		stNow.wMilliseconds = 500;
		if (!SystemTimeToFileTime(&stNow, &ftNow))
		{
			errno = -1;
			return -1;
		}

		random_time_bits = (((unsigned long long)ftNow.dwHighDateTime << 32)
			| (unsigned long long)ftNow.dwLowDateTime);
	}
	value += random_time_bits ^ (unsigned long long)GetCurrentThreadId();

	for (count = 0; count < attempts; value += 7777, ++count)
	{
		unsigned long long v = value;

		/* Fill in the random bits.  */
		XXXXXX[0] = letters[v % 62];
		v /= 62;
		XXXXXX[1] = letters[v % 62];
		v /= 62;
		XXXXXX[2] = letters[v % 62];
		v /= 62;
		XXXXXX[3] = letters[v % 62];
		v /= 62;
		XXXXXX[4] = letters[v % 62];
		v /= 62;
		XXXXXX[5] = letters[v % 62];

		fd = open(tmpl, O_RDWR | O_CREAT | O_EXCL, _S_IREAD | _S_IWRITE);
		if (fd >= 0)
		{
			errno = save_errno;
			return fd;
		}
		else if (errno != EEXIST)
			return -1;
	}

	/* We got out of the loop because we ran out of combinations to try.  */
	errno = EEXIST;
	return -1;
}
#endif
namespace miopen {
TempFile::TempFile(const std::string& path_template)
    : _path((GetTempDirectoryPath().path / (path_template + "-XXXXXX")).string())
{
    _fd = mkstemp(&_path[0]);
    if(_fd == -1)
    {
        MIOPEN_THROW("Error: TempFile: mkstemp()");
    }
}

TempFile::~TempFile()
{
    const int remove_rc = std::remove(_path.c_str());
    const int close_rc  = close(_fd);
    if(remove_rc != 0 || close_rc != 0)
    {
#ifndef NDEBUG // Be quiet in release versions.
        std::fprintf(stderr,
                     "Error: TempFile: On removal of '%s', remove_rc = %d, close_rc = %d.\n",
                     _path.c_str(),
                     remove_rc,
                     close_rc);
#endif
    }
}

const TmpDir& TempFile::GetTempDirectoryPath()
{
    static const TmpDir dir("tmp");
    return dir;
}
} // namespace miopen
<commit_msg>windows build fix<commit_after>#include <miopen/temp_file.hpp>
#include <miopen/errors.hpp>

#ifndef WIN32
#include <unistd.h>
#else
#include <Windows.h>
#include <fcntl.h>
#include <io.h>
#define _O_EXCL 0x0400
#define O_EXCL _O_EXCL
/* mkstemp extracted from libc/sysdeps/posix/tempname.c.  Copyright
(C) 1991-1999, 2000, 2001, 2006 Free Software Foundation, Inc.

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

static const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

/* Generate a temporary file name based on TMPL.  TMPL must match the
rules for mk[s]temp (i.e. end in "XXXXXX").  The name constructed
does not exist at the time of the call to mkstemp.  TMPL is
overwritten with the result.  */
static int mkstemp(char* tmpl)
{
    int len;
    char* XXXXXX;
    static unsigned long long value;
    unsigned long long random_time_bits;
    unsigned int count;
    int fd         = -1;
    int save_errno = errno;

/* A lower bound on the number of temporary files to attempt to
generate.  The maximum total number of temporary file names that
can exist for a given template is 62**6.  It should never be
necessary to try all these combinations.  Instead if a reasonable
number of names is tried (we define reasonable as 62**3) fail to
give the system administrator the chance to remove the problems.  */
#define ATTEMPTS_MIN (62 * 62 * 62)

/* The number of times to attempt to generate a temporary file.  To
conform to POSIX, this must be no smaller than TMP_MAX.  */
#if ATTEMPTS_MIN < TMP_MAX
    unsigned int attempts = TMP_MAX;
#else
    unsigned int attempts = ATTEMPTS_MIN;
#endif

    len = strlen(tmpl);
    if(len < 6 || strcmp(&tmpl[len - 6], "XXXXXX"))
    {
        errno = EINVAL;
        return -1;
    }

    /* This is where the Xs start.  */
    XXXXXX = &tmpl[len - 6];

    /* Get some more or less random data.  */
    {
        SYSTEMTIME stNow;
        FILETIME ftNow;

        // get system time
        GetSystemTime(&stNow);
        stNow.wMilliseconds = 500;
        if(!SystemTimeToFileTime(&stNow, &ftNow))
        {
            errno = -1;
            return -1;
        }

        random_time_bits = (((unsigned long long)ftNow.dwHighDateTime << 32) |
                            (unsigned long long)ftNow.dwLowDateTime);
    }
    value += random_time_bits ^ (unsigned long long)GetCurrentThreadId();

    for(count = 0; count < attempts; value += 7777, ++count)
    {
        unsigned long long v = value;

        /* Fill in the random bits.  */
        XXXXXX[0] = letters[v % 62];
        v /= 62;
        XXXXXX[1] = letters[v % 62];
        v /= 62;
        XXXXXX[2] = letters[v % 62];
        v /= 62;
        XXXXXX[3] = letters[v % 62];
        v /= 62;
        XXXXXX[4] = letters[v % 62];
        v /= 62;
        XXXXXX[5] = letters[v % 62];

        fd = open(tmpl, O_RDWR | O_CREAT | O_EXCL, _S_IREAD | _S_IWRITE);
        if(fd >= 0)
        {
            errno = save_errno;
            return fd;
        }
        else if(errno != EEXIST)
            return -1;
    }

    /* We got out of the loop because we ran out of combinations to try.  */
    errno = EEXIST;
    return -1;
}
#endif
namespace miopen {
TempFile::TempFile(const std::string& path_template)
    : _path((GetTempDirectoryPath().path / (path_template + "-XXXXXX")).string())
{
    _fd = mkstemp(&_path[0]);
    if(_fd == -1)
    {
        MIOPEN_THROW("Error: TempFile: mkstemp()");
    }
}

TempFile::~TempFile()
{
    const int remove_rc = std::remove(_path.c_str());
    const int close_rc  = close(_fd);
    if(remove_rc != 0 || close_rc != 0)
    {
#ifndef NDEBUG // Be quiet in release versions.
        std::fprintf(stderr,
                     "Error: TempFile: On removal of '%s', remove_rc = %d, close_rc = %d.\n",
                     _path.c_str(),
                     remove_rc,
                     close_rc);
#endif
    }
}

const TmpDir& TempFile::GetTempDirectoryPath()
{
    static const TmpDir dir("tmp");
    return dir;
}
} // namespace miopen
<|endoftext|>


<commit_before>#include <cstdlib>
#include <ctime>
#include "lib/base64_sha1.hh"
#include <openssl/sha.h>

unsigned long generate_random_num() {
	return rand();
}

int main(int argc, char const *argv[])
{
	srand((unsigned)time(NULL));
	string key;
	string sh;

	cin >> key;

	cout << SHA1((unsigned char*)key.c_str(), key.size(), NULL) << endl;

	cout << generate_random_num() << endl;

	return 0;
}<commit_msg>Working sha1 encrypt<commit_after>#include <cstdio>
#include <cstdlib>
#include <ctime>
#include "lib/base64_sha1.hh"
#include <openssl/sha.h>

unsigned long generate_random_num() {
	return rand();
}

int main(int argc, char const *argv[])
{
	srand((unsigned)time(NULL));
	string key;
	unsigned char* c=new unsigned char[SHA_DIGEST_LENGTH];

	cin >> key;

	c=SHA1((unsigned char*)key.c_str(), key.size(), NULL);

	for(int i=0;i<20;++i) {
		printf("%02x", c[i]);
	}
	printf("\n");
	cout << generate_random_num() << endl;

	return 0;
}<|endoftext|>


<commit_before>/*************************************************************************/
/*  compression.cpp                                                      */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* 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 "compression.h"

#include "core/io/zip_io.h"
#include "core/project_settings.h"

#include "thirdparty/misc/fastlz.h"

#include <zlib.h>
#include <zstd.h>

int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size, Mode p_mode) {
	switch (p_mode) {
		case MODE_FASTLZ: {
			if (p_src_size < 16) {
				uint8_t src[16];
				memset(&src[p_src_size], 0, 16 - p_src_size);
				memcpy(src, p_src, p_src_size);
				return fastlz_compress(src, 16, p_dst);
			} else {
				return fastlz_compress(p_src, p_src_size, p_dst);
			}

		} break;
		case MODE_DEFLATE:
		case MODE_GZIP: {
			int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16;

			z_stream strm;
			strm.zalloc = zipio_alloc;
			strm.zfree = zipio_free;
			strm.opaque = Z_NULL;
			int level = p_mode == MODE_DEFLATE ? zlib_level : gzip_level;
			int err = deflateInit2(&strm, level, Z_DEFLATED, window_bits, 8, Z_DEFAULT_STRATEGY);
			if (err != Z_OK) {
				return -1;
			}

			strm.avail_in = p_src_size;
			int aout = deflateBound(&strm, p_src_size);
			strm.avail_out = aout;
			strm.next_in = (Bytef *)p_src;
			strm.next_out = p_dst;
			deflate(&strm, Z_FINISH);
			aout = aout - strm.avail_out;
			deflateEnd(&strm);
			return aout;

		} break;
		case MODE_ZSTD: {
			ZSTD_CCtx *cctx = ZSTD_createCCtx();
			ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, zstd_level);
			if (zstd_long_distance_matching) {
				ZSTD_CCtx_setParameter(cctx, ZSTD_c_enableLongDistanceMatching, 1);
				ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, zstd_window_log_size);
			}
			int max_dst_size = get_max_compressed_buffer_size(p_src_size, MODE_ZSTD);
			int ret = ZSTD_compressCCtx(cctx, p_dst, max_dst_size, p_src, p_src_size, zstd_level);
			ZSTD_freeCCtx(cctx);
			return ret;
		} break;
	}

	ERR_FAIL_V(-1);
}

int Compression::get_max_compressed_buffer_size(int p_src_size, Mode p_mode) {
	switch (p_mode) {
		case MODE_FASTLZ: {
			int ss = p_src_size + p_src_size * 6 / 100;
			if (ss < 66) {
				ss = 66;
			}
			return ss;

		} break;
		case MODE_DEFLATE:
		case MODE_GZIP: {
			int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16;

			z_stream strm;
			strm.zalloc = zipio_alloc;
			strm.zfree = zipio_free;
			strm.opaque = Z_NULL;
			int err = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, window_bits, 8, Z_DEFAULT_STRATEGY);
			if (err != Z_OK) {
				return -1;
			}
			int aout = deflateBound(&strm, p_src_size);
			deflateEnd(&strm);
			return aout;
		} break;
		case MODE_ZSTD: {
			return ZSTD_compressBound(p_src_size);
		} break;
	}

	ERR_FAIL_V(-1);
}

int Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size, Mode p_mode) {
	switch (p_mode) {
		case MODE_FASTLZ: {
			int ret_size = 0;

			if (p_dst_max_size < 16) {
				uint8_t dst[16];
				ret_size = fastlz_decompress(p_src, p_src_size, dst, 16);
				memcpy(p_dst, dst, p_dst_max_size);
			} else {
				ret_size = fastlz_decompress(p_src, p_src_size, p_dst, p_dst_max_size);
			}
			return ret_size;
		} break;
		case MODE_DEFLATE:
		case MODE_GZIP: {
			int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16;

			z_stream strm;
			strm.zalloc = zipio_alloc;
			strm.zfree = zipio_free;
			strm.opaque = Z_NULL;
			strm.avail_in = 0;
			strm.next_in = Z_NULL;
			int err = inflateInit2(&strm, window_bits);
			ERR_FAIL_COND_V(err != Z_OK, -1);

			strm.avail_in = p_src_size;
			strm.avail_out = p_dst_max_size;
			strm.next_in = (Bytef *)p_src;
			strm.next_out = p_dst;

			err = inflate(&strm, Z_FINISH);
			int total = strm.total_out;
			inflateEnd(&strm);
			ERR_FAIL_COND_V(err != Z_STREAM_END, -1);
			return total;
		} break;
		case MODE_ZSTD: {
			ZSTD_DCtx *dctx = ZSTD_createDCtx();
			if (zstd_long_distance_matching) {
				ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, zstd_window_log_size);
			}
			int ret = ZSTD_decompressDCtx(dctx, p_dst, p_dst_max_size, p_src, p_src_size);
			ZSTD_freeDCtx(dctx);
			return ret;
		} break;
	}

	ERR_FAIL_V(-1);
}

/**
	This will handle both Gzip and Deflat streams. It will automatically allocate the output buffer into the provided p_dst_vect Vector.
	This is required for compressed data who's final uncompressed size is unknown, as is the case for HTTP response bodies.
	This is much slower however than using Compression::decompress because it may result in multiple full copies of the output buffer.
*/
int Compression::decompress_dynamic(PoolVector<uint8_t> *p_dst, int p_max_dst_size, const uint8_t *p_src, int p_src_size, Mode p_mode) {
	int ret;
	uint8_t *dst = nullptr;
	int out_mark = 0;
	z_stream strm;

	ERR_FAIL_COND_V(p_src_size <= 0, Z_DATA_ERROR);

	// This function only supports GZip and Deflate
	int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16;
	ERR_FAIL_COND_V(p_mode != MODE_DEFLATE && p_mode != MODE_GZIP, Z_ERRNO);

	// Initialize the stream
	strm.zalloc = Z_NULL;
	strm.zfree = Z_NULL;
	strm.opaque = Z_NULL;
	strm.avail_in = 0;
	strm.next_in = Z_NULL;

	int err = inflateInit2(&strm, window_bits);
	ERR_FAIL_COND_V(err != Z_OK, -1);

	// Setup the stream inputs
	strm.next_in = (Bytef *)p_src;
	strm.avail_in = p_src_size;

	// Ensure the destination buffer is empty
	p_dst->resize(0);

	// decompress until deflate stream ends or end of file
	do {
		// Add another chunk size to the output buffer
		// This forces a copy of the whole buffer
		p_dst->resize(p_dst->size() + gzip_chunk);
		// Get pointer to the actual output buffer
		dst = p_dst->write().ptr();

		// Set the stream to the new output stream
		// Since it was copied, we need to reset the stream to the new buffer
		strm.next_out = &(dst[out_mark]);
		strm.avail_out = gzip_chunk;

		// run inflate() on input until output buffer is full and needs to be resized
		// or input runs out
		do {
			ret = inflate(&strm, Z_SYNC_FLUSH);

			switch (ret) {
				case Z_NEED_DICT:
					ret = Z_DATA_ERROR;
				case Z_DATA_ERROR:
				case Z_MEM_ERROR:
				case Z_STREAM_ERROR:
				case Z_BUF_ERROR:
					if (strm.msg) {
						WARN_PRINT(strm.msg);
					}
					(void)inflateEnd(&strm);
					p_dst->resize(0);
					return ret;
			}
		} while (strm.avail_out > 0 && strm.avail_in > 0);

		out_mark += gzip_chunk;

		// Encorce max output size
		if (p_max_dst_size > -1 && strm.total_out > (uint64_t)p_max_dst_size) {
			(void)inflateEnd(&strm);
			p_dst->resize(0);
			return Z_BUF_ERROR;
		}
	} while (ret != Z_STREAM_END);

	// If all done successfully, resize the output if it's larger than the actual output
	if (ret == Z_STREAM_END && (unsigned long)p_dst->size() > strm.total_out) {
		p_dst->resize(strm.total_out);
	}

	// clean up and return
	(void)inflateEnd(&strm);
	return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}

int Compression::zlib_level = Z_DEFAULT_COMPRESSION;
int Compression::gzip_level = Z_DEFAULT_COMPRESSION;
int Compression::zstd_level = 3;
bool Compression::zstd_long_distance_matching = false;
int Compression::zstd_window_log_size = 27; // ZSTD_WINDOWLOG_LIMIT_DEFAULT
int Compression::gzip_chunk = 16384;
<commit_msg>Fix decompression with FastLZ when buffer size is less than 16 bytes<commit_after>/*************************************************************************/
/*  compression.cpp                                                      */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* 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 "compression.h"

#include "core/io/zip_io.h"
#include "core/project_settings.h"

#include "thirdparty/misc/fastlz.h"

#include <zlib.h>
#include <zstd.h>

int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size, Mode p_mode) {
	switch (p_mode) {
		case MODE_FASTLZ: {
			if (p_src_size < 16) {
				uint8_t src[16];
				memset(&src[p_src_size], 0, 16 - p_src_size);
				memcpy(src, p_src, p_src_size);
				return fastlz_compress(src, 16, p_dst);
			} else {
				return fastlz_compress(p_src, p_src_size, p_dst);
			}

		} break;
		case MODE_DEFLATE:
		case MODE_GZIP: {
			int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16;

			z_stream strm;
			strm.zalloc = zipio_alloc;
			strm.zfree = zipio_free;
			strm.opaque = Z_NULL;
			int level = p_mode == MODE_DEFLATE ? zlib_level : gzip_level;
			int err = deflateInit2(&strm, level, Z_DEFLATED, window_bits, 8, Z_DEFAULT_STRATEGY);
			if (err != Z_OK) {
				return -1;
			}

			strm.avail_in = p_src_size;
			int aout = deflateBound(&strm, p_src_size);
			strm.avail_out = aout;
			strm.next_in = (Bytef *)p_src;
			strm.next_out = p_dst;
			deflate(&strm, Z_FINISH);
			aout = aout - strm.avail_out;
			deflateEnd(&strm);
			return aout;

		} break;
		case MODE_ZSTD: {
			ZSTD_CCtx *cctx = ZSTD_createCCtx();
			ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, zstd_level);
			if (zstd_long_distance_matching) {
				ZSTD_CCtx_setParameter(cctx, ZSTD_c_enableLongDistanceMatching, 1);
				ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, zstd_window_log_size);
			}
			int max_dst_size = get_max_compressed_buffer_size(p_src_size, MODE_ZSTD);
			int ret = ZSTD_compressCCtx(cctx, p_dst, max_dst_size, p_src, p_src_size, zstd_level);
			ZSTD_freeCCtx(cctx);
			return ret;
		} break;
	}

	ERR_FAIL_V(-1);
}

int Compression::get_max_compressed_buffer_size(int p_src_size, Mode p_mode) {
	switch (p_mode) {
		case MODE_FASTLZ: {
			int ss = p_src_size + p_src_size * 6 / 100;
			if (ss < 66) {
				ss = 66;
			}
			return ss;

		} break;
		case MODE_DEFLATE:
		case MODE_GZIP: {
			int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16;

			z_stream strm;
			strm.zalloc = zipio_alloc;
			strm.zfree = zipio_free;
			strm.opaque = Z_NULL;
			int err = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, window_bits, 8, Z_DEFAULT_STRATEGY);
			if (err != Z_OK) {
				return -1;
			}
			int aout = deflateBound(&strm, p_src_size);
			deflateEnd(&strm);
			return aout;
		} break;
		case MODE_ZSTD: {
			return ZSTD_compressBound(p_src_size);
		} break;
	}

	ERR_FAIL_V(-1);
}

int Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size, Mode p_mode) {
	switch (p_mode) {
		case MODE_FASTLZ: {
			int ret_size = 0;

			if (p_dst_max_size < 16) {
				uint8_t dst[16];
				fastlz_decompress(p_src, p_src_size, dst, 16);
				memcpy(p_dst, dst, p_dst_max_size);
				ret_size = p_dst_max_size;
			} else {
				ret_size = fastlz_decompress(p_src, p_src_size, p_dst, p_dst_max_size);
			}
			return ret_size;
		} break;
		case MODE_DEFLATE:
		case MODE_GZIP: {
			int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16;

			z_stream strm;
			strm.zalloc = zipio_alloc;
			strm.zfree = zipio_free;
			strm.opaque = Z_NULL;
			strm.avail_in = 0;
			strm.next_in = Z_NULL;
			int err = inflateInit2(&strm, window_bits);
			ERR_FAIL_COND_V(err != Z_OK, -1);

			strm.avail_in = p_src_size;
			strm.avail_out = p_dst_max_size;
			strm.next_in = (Bytef *)p_src;
			strm.next_out = p_dst;

			err = inflate(&strm, Z_FINISH);
			int total = strm.total_out;
			inflateEnd(&strm);
			ERR_FAIL_COND_V(err != Z_STREAM_END, -1);
			return total;
		} break;
		case MODE_ZSTD: {
			ZSTD_DCtx *dctx = ZSTD_createDCtx();
			if (zstd_long_distance_matching) {
				ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, zstd_window_log_size);
			}
			int ret = ZSTD_decompressDCtx(dctx, p_dst, p_dst_max_size, p_src, p_src_size);
			ZSTD_freeDCtx(dctx);
			return ret;
		} break;
	}

	ERR_FAIL_V(-1);
}

/**
	This will handle both Gzip and Deflat streams. It will automatically allocate the output buffer into the provided p_dst_vect Vector.
	This is required for compressed data who's final uncompressed size is unknown, as is the case for HTTP response bodies.
	This is much slower however than using Compression::decompress because it may result in multiple full copies of the output buffer.
*/
int Compression::decompress_dynamic(PoolVector<uint8_t> *p_dst, int p_max_dst_size, const uint8_t *p_src, int p_src_size, Mode p_mode) {
	int ret;
	uint8_t *dst = nullptr;
	int out_mark = 0;
	z_stream strm;

	ERR_FAIL_COND_V(p_src_size <= 0, Z_DATA_ERROR);

	// This function only supports GZip and Deflate
	int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16;
	ERR_FAIL_COND_V(p_mode != MODE_DEFLATE && p_mode != MODE_GZIP, Z_ERRNO);

	// Initialize the stream
	strm.zalloc = Z_NULL;
	strm.zfree = Z_NULL;
	strm.opaque = Z_NULL;
	strm.avail_in = 0;
	strm.next_in = Z_NULL;

	int err = inflateInit2(&strm, window_bits);
	ERR_FAIL_COND_V(err != Z_OK, -1);

	// Setup the stream inputs
	strm.next_in = (Bytef *)p_src;
	strm.avail_in = p_src_size;

	// Ensure the destination buffer is empty
	p_dst->resize(0);

	// decompress until deflate stream ends or end of file
	do {
		// Add another chunk size to the output buffer
		// This forces a copy of the whole buffer
		p_dst->resize(p_dst->size() + gzip_chunk);
		// Get pointer to the actual output buffer
		dst = p_dst->write().ptr();

		// Set the stream to the new output stream
		// Since it was copied, we need to reset the stream to the new buffer
		strm.next_out = &(dst[out_mark]);
		strm.avail_out = gzip_chunk;

		// run inflate() on input until output buffer is full and needs to be resized
		// or input runs out
		do {
			ret = inflate(&strm, Z_SYNC_FLUSH);

			switch (ret) {
				case Z_NEED_DICT:
					ret = Z_DATA_ERROR;
				case Z_DATA_ERROR:
				case Z_MEM_ERROR:
				case Z_STREAM_ERROR:
				case Z_BUF_ERROR:
					if (strm.msg) {
						WARN_PRINT(strm.msg);
					}
					(void)inflateEnd(&strm);
					p_dst->resize(0);
					return ret;
			}
		} while (strm.avail_out > 0 && strm.avail_in > 0);

		out_mark += gzip_chunk;

		// Encorce max output size
		if (p_max_dst_size > -1 && strm.total_out > (uint64_t)p_max_dst_size) {
			(void)inflateEnd(&strm);
			p_dst->resize(0);
			return Z_BUF_ERROR;
		}
	} while (ret != Z_STREAM_END);

	// If all done successfully, resize the output if it's larger than the actual output
	if (ret == Z_STREAM_END && (unsigned long)p_dst->size() > strm.total_out) {
		p_dst->resize(strm.total_out);
	}

	// clean up and return
	(void)inflateEnd(&strm);
	return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}

int Compression::zlib_level = Z_DEFAULT_COMPRESSION;
int Compression::gzip_level = Z_DEFAULT_COMPRESSION;
int Compression::zstd_level = 3;
bool Compression::zstd_long_distance_matching = false;
int Compression::zstd_window_log_size = 27; // ZSTD_WINDOWLOG_LIMIT_DEFAULT
int Compression::gzip_chunk = 16384;
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-2014, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
/*
 * Create default binning and initalise the binning component with this. In case
 * users already defined a binning, do not overwrite this.
 *
 *   Author: Markus Fasel
 */
#include "AliEMCalTriggerBinningComponent.h"
#include "AliEMCalTriggerBinningFactory.h"
#include <map>
#include <vector>
#include <TMath.h>
#include <TArrayD.h>

namespace EMCalTriggerPtAnalysis {

//______________________________________________________________________________
AliEMCalTriggerBinningFactory::AliEMCalTriggerBinningFactory() {
  /*
   * Default constructor, nothing to do
   */
}

//______________________________________________________________________________
void AliEMCalTriggerBinningFactory::Create(AliEMCalTriggerBinningComponent* const data) {
  /*
   * Initialise binning component with default binning
   *
   * @param data: the binning component to be initialised
   */
  TArrayD binLimits;
  if(!data->GetBinning("pt")){
    CreateDefaultPtBinning(binLimits);
    data->SetBinning("pt", binLimits);
  }
  if(!data->GetBinning("eta")){
    CreateDefaultEtaBinning(binLimits);
    data->SetBinning("eta", binLimits);
  }
  if(!data->GetBinning("phi")){
    CreateLinearBinning(binLimits, 100, 0, 2*TMath::Pi());
    data->SetBinning("phi", binLimits);
  }
  if(!data->GetBinning("zvertex")){
    CreateDefaultZVertexBinning(binLimits);
    data->SetBinning("zvertex", binLimits);
  }
  if(!data->GetBinning("centrality")){
	CreateLinearBinning(binLimits, 5, 0., 100.);
	data->SetBinning("centrality", binLimits);
  }
}

//______________________________________________________________________________
void AliEMCalTriggerBinningFactory::CreateDefaultPtBinning(TArrayD &binning) const{
  /*
   * Creating the default pt binning.
   *
   * @param binning: Array where to store the results.
   */
  std::vector<double> mybinning;
  std::map<double,double> definitions;
  definitions.insert(std::pair<double,double>(2.5, 0.1));
  definitions.insert(std::pair<double,double>(7., 0.25));
  definitions.insert(std::pair<double,double>(15., 0.5));
  definitions.insert(std::pair<double,double>(25., 1.));
  definitions.insert(std::pair<double,double>(40., 2.5));
  definitions.insert(std::pair<double,double>(50., 5.));
  definitions.insert(std::pair<double,double>(100., 10.));
  //definitions.insert(std::pair<double, double>(200., 20.));
  double currentval = 0;
  for(std::map<double,double>::iterator id = definitions.begin(); id != definitions.end(); ++id){
    double limit = id->first, binwidth = id->second;
    while(currentval < limit){
      currentval += binwidth;
      mybinning.push_back(currentval);
    }
  }
  binning.Set(mybinning.size());
  int ib = 0;
  for(std::vector<double>::iterator it = mybinning.begin(); it != mybinning.end(); ++it)
    binning[ib++] = *it;
}

//______________________________________________________________________________
void AliEMCalTriggerBinningFactory::CreateDefaultZVertexBinning(TArrayD &binning) const {
  /*
   * Creating default z-Vertex binning.
   *
   * @param binning: Array where to store the results.
   */
  std::vector<double> mybinning;
  double currentval = -10;
  mybinning.push_back(currentval);
  while(currentval < 10.){
    currentval += 5.;
    mybinning.push_back(currentval);
  }
  binning.Set(mybinning.size());
  int ib = 0;
  for(std::vector<double>::iterator it = mybinning.begin(); it != mybinning.end(); ++it)
    binning[ib++] = *it;
}

//______________________________________________________________________________
void AliEMCalTriggerBinningFactory::CreateDefaultEtaBinning(TArrayD& binning) const {
  /*
   * Creating default z-Vertex binning.
   *
   * @param binning: Array where to store the results.
   */
  std::vector<double> mybinning;
  double currentval = -0.8;
  mybinning.push_back(currentval);
  while(currentval < 0.8){
    currentval += 0.1;
    mybinning.push_back(currentval);
  }
  binning.Set(mybinning.size());
  int ib = 0;
  for(std::vector<double>::iterator it = mybinning.begin(); it != mybinning.end(); ++it)
    binning[ib++] = *it;
}

//______________________________________________________________________________
void AliEMCalTriggerBinningFactory::CreateLinearBinning(TArrayD& binning, int nbins, double min, double max) const {
  /*
   * Create any kind of linear binning from given ranges and stores it in the binning array.
   *
   * @param binning: output array
   * @param nbins: Number of bins
   * @param min: lower range
   * @param max: upper range
   */
  double binwidth = (max-min)/static_cast<double>(nbins);
  binning.Set(nbins+1);
  binning[0] = min;
  double currentlimit = min + binwidth;
  for(int ibin = 0; ibin < nbins; ibin++){
    binning[ibin+1] = currentlimit;
    currentlimit += binwidth;
  }
}

} /* namespace EMCalTriggerPtAnalysis */
<commit_msg>Make pt-binning broader, particularly at low pt<commit_after>/**************************************************************************
 * Copyright(c) 1998-2014, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
/*
 * Create default binning and initalise the binning component with this. In case
 * users already defined a binning, do not overwrite this.
 *
 *   Author: Markus Fasel
 */
#include "AliEMCalTriggerBinningComponent.h"
#include "AliEMCalTriggerBinningFactory.h"
#include <map>
#include <vector>
#include <TMath.h>
#include <TArrayD.h>

namespace EMCalTriggerPtAnalysis {

//______________________________________________________________________________
AliEMCalTriggerBinningFactory::AliEMCalTriggerBinningFactory() {
  /*
   * Default constructor, nothing to do
   */
}

//______________________________________________________________________________
void AliEMCalTriggerBinningFactory::Create(AliEMCalTriggerBinningComponent* const data) {
  /*
   * Initialise binning component with default binning
   *
   * @param data: the binning component to be initialised
   */
  TArrayD binLimits;
  if(!data->GetBinning("pt")){
    CreateDefaultPtBinning(binLimits);
    data->SetBinning("pt", binLimits);
  }
  if(!data->GetBinning("eta")){
    CreateDefaultEtaBinning(binLimits);
    data->SetBinning("eta", binLimits);
  }
  if(!data->GetBinning("phi")){
    CreateLinearBinning(binLimits, 100, 0, 2*TMath::Pi());
    data->SetBinning("phi", binLimits);
  }
  if(!data->GetBinning("zvertex")){
    CreateDefaultZVertexBinning(binLimits);
    data->SetBinning("zvertex", binLimits);
  }
  if(!data->GetBinning("centrality")){
	CreateLinearBinning(binLimits, 5, 0., 100.);
	data->SetBinning("centrality", binLimits);
  }
}

//______________________________________________________________________________
void AliEMCalTriggerBinningFactory::CreateDefaultPtBinning(TArrayD &binning) const{
  /*
   * Creating the default pt binning.
   *
   * @param binning: Array where to store the results.
   */
  std::vector<double> mybinning;
  std::map<double,double> definitions;
  definitions.insert(std::pair<double,double>(2.5, 0.1));
  definitions.insert(std::pair<double,double>(7., 0.25));
  definitions.insert(std::pair<double,double>(10., 0.5));
  definitions.insert(std::pair<double,double>(15., 1.));
  definitions.insert(std::pair<double,double>(20., 2.5));
  definitions.insert(std::pair<double,double>(30., 5.));
  definitions.insert(std::pair<double,double>(100., 10.));
  definitions.insert(std::pair<double, double>(200., 20.));
  double currentval = 0;
  for(std::map<double,double>::iterator id = definitions.begin(); id != definitions.end(); ++id){
    double limit = id->first, binwidth = id->second;
    while(currentval < limit){
      currentval += binwidth;
      mybinning.push_back(currentval);
    }
  }
  binning.Set(mybinning.size());
  int ib = 0;
  for(std::vector<double>::iterator it = mybinning.begin(); it != mybinning.end(); ++it)
    binning[ib++] = *it;
}

//______________________________________________________________________________
void AliEMCalTriggerBinningFactory::CreateDefaultZVertexBinning(TArrayD &binning) const {
  /*
   * Creating default z-Vertex binning.
   *
   * @param binning: Array where to store the results.
   */
  std::vector<double> mybinning;
  double currentval = -10;
  mybinning.push_back(currentval);
  while(currentval < 10.){
    currentval += 5.;
    mybinning.push_back(currentval);
  }
  binning.Set(mybinning.size());
  int ib = 0;
  for(std::vector<double>::iterator it = mybinning.begin(); it != mybinning.end(); ++it)
    binning[ib++] = *it;
}

//______________________________________________________________________________
void AliEMCalTriggerBinningFactory::CreateDefaultEtaBinning(TArrayD& binning) const {
  /*
   * Creating default z-Vertex binning.
   *
   * @param binning: Array where to store the results.
   */
  std::vector<double> mybinning;
  double currentval = -0.8;
  mybinning.push_back(currentval);
  while(currentval < 0.8){
    currentval += 0.1;
    mybinning.push_back(currentval);
  }
  binning.Set(mybinning.size());
  int ib = 0;
  for(std::vector<double>::iterator it = mybinning.begin(); it != mybinning.end(); ++it)
    binning[ib++] = *it;
}

//______________________________________________________________________________
void AliEMCalTriggerBinningFactory::CreateLinearBinning(TArrayD& binning, int nbins, double min, double max) const {
  /*
   * Create any kind of linear binning from given ranges and stores it in the binning array.
   *
   * @param binning: output array
   * @param nbins: Number of bins
   * @param min: lower range
   * @param max: upper range
   */
  double binwidth = (max-min)/static_cast<double>(nbins);
  binning.Set(nbins+1);
  binning[0] = min;
  double currentlimit = min + binwidth;
  for(int ibin = 0; ibin < nbins; ibin++){
    binning[ibin+1] = currentlimit;
    currentlimit += binwidth;
  }
}

} /* namespace EMCalTriggerPtAnalysis */
<|endoftext|>


<commit_before>/*****************************************************************************
 * Project: RooFit                                                           *
 * Package: RooFitCore                                                       *
 *    File: $Id: RooTrace.cc,v 1.21 2005/06/20 15:45:14 wverkerke Exp $
 * Authors:                                                                  *
 *   WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu       *
 *   DK, David Kirkby,    UC Irvine,         dkirkby@uci.edu                 *
 *                                                                           *
 * Copyright (c) 2000-2005, Regents of the University of California          *
 *                          and Stanford University. All rights reserved.    *
 *                                                                           *
 * Redistribution and use in source and binary forms,                        *
 * with or without modification, are permitted according to the terms        *
 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)             *
 *****************************************************************************/

// -- CLASS DESCRIPTION [AUX] --

#include "RooFitCore/RooFit.hh"

#include "RooFitCore/RooTrace.hh"
#include "RooFitCore/RooTrace.hh"
#include "RooFitCore/RooAbsArg.hh"

#include <iomanip>

ClassImp(RooTrace)
;

Bool_t RooTrace::_active(kFALSE) ;
Bool_t RooTrace::_verbose(kFALSE) ;
RooLinkedList RooTrace::_list ;
RooLinkedList RooTrace::_markList ;

void RooTrace::create2(const TObject* obj) {

  _list.Add((RooAbsArg*)obj) ;
  if (_verbose) {
    cout << "RooTrace::create: object " << obj << " of type " << obj->ClassName()
	 << " created " << endl ;
  }
}

void RooTrace::destroy2(const TObject* obj) {

  if (!_list.Remove((RooAbsArg*)obj)) {
    cout << "RooTrace::destroy: object " << obj << " of type " << obj->ClassName()
	 << " already deleted, or created before trace activation[" << obj->GetTitle() << "]" << endl ;
  } else if (_verbose) {
    cout << "RooTrace::destroy: object " << obj << " of type " << obj->ClassName()
	 << " destroyed [" << obj->GetTitle() << "]" << endl ;
  }
}

void RooTrace::mark()
{
  _markList = _list ;
}

void RooTrace::dump(ostream& os, Bool_t sinceMarked) {
  os << "List of RooFit objects allocated while trace active:" << endl ;

  char buf[100] ;
  Int_t i, nMarked(0) ;
  for(i=0 ; i<_list.GetSize() ; i++) {
    if (!sinceMarked || _markList.IndexOf(_list.At(i)) == -1) {
#ifdef R__B64
      sprintf(buf,"%010x : ",(ULong64_t)(void*)_list.At(i)) ;
#else
      sprintf(buf,"%010x : ",(UInt_t)(void*)_list.At(i)) ;
#endif
      os << buf << setw(20) << _list.At(i)->ClassName() << setw(0) << " - " << _list.At(i)->GetName() << endl ;
    } else {
      nMarked++ ;
    }
  }
  if (sinceMarked) os << nMarked << " marked objects suppressed" << endl ;
}
<commit_msg><commit_after>/*****************************************************************************
 * Project: RooFit                                                           *
 * Package: RooFitCore                                                       *
 *    File: $Id: RooTrace.cc,v 1.22 2005/06/20 18:15:16 wverkerke Exp $
 * Authors:                                                                  *
 *   WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu       *
 *   DK, David Kirkby,    UC Irvine,         dkirkby@uci.edu                 *
 *                                                                           *
 * Copyright (c) 2000-2005, Regents of the University of California          *
 *                          and Stanford University. All rights reserved.    *
 *                                                                           *
 * Redistribution and use in source and binary forms,                        *
 * with or without modification, are permitted according to the terms        *
 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)             *
 *****************************************************************************/

// -- CLASS DESCRIPTION [AUX] --

#include "RooFitCore/RooFit.hh"

#include "RooFitCore/RooTrace.hh"
#include "RooFitCore/RooTrace.hh"
#include "RooFitCore/RooAbsArg.hh"

#include <iomanip>

ClassImp(RooTrace)
;

Bool_t RooTrace::_active(kFALSE) ;
Bool_t RooTrace::_verbose(kFALSE) ;
RooLinkedList RooTrace::_list ;
RooLinkedList RooTrace::_markList ;

void RooTrace::create2(const TObject* obj) {

  _list.Add((RooAbsArg*)obj) ;
  if (_verbose) {
    cout << "RooTrace::create: object " << obj << " of type " << obj->ClassName()
	 << " created " << endl ;
  }
}

void RooTrace::destroy2(const TObject* obj) {

  if (!_list.Remove((RooAbsArg*)obj)) {
    cout << "RooTrace::destroy: object " << obj << " of type " << obj->ClassName()
	 << " already deleted, or created before trace activation[" << obj->GetTitle() << "]" << endl ;
  } else if (_verbose) {
    cout << "RooTrace::destroy: object " << obj << " of type " << obj->ClassName()
	 << " destroyed [" << obj->GetTitle() << "]" << endl ;
  }
}

void RooTrace::mark()
{
  _markList = _list ;
}

void RooTrace::dump(ostream& os, Bool_t sinceMarked) {
  os << "List of RooFit objects allocated while trace active:" << endl ;

  char buf[100] ;
  Int_t i, nMarked(0) ;
  for(i=0 ; i<_list.GetSize() ; i++) {
    if (!sinceMarked || _markList.IndexOf(_list.At(i)) == -1) {
#ifdef R__B64
      sprintf(buf,"%010x : ",(ULong64_t)(void*)_list.At(i)) ;
#else
      sprintf(buf,"%010x : ",(ULong_t)(void*)_list.At(i)) ;
#endif
      os << buf << setw(20) << _list.At(i)->ClassName() << setw(0) << " - " << _list.At(i)->GetName() << endl ;
    } else {
      nMarked++ ;
    }
  }
  if (sinceMarked) os << nMarked << " marked objects suppressed" << endl ;
}
<|endoftext|>