<commit_before>// Copyright (c) 2012 Plenluno All rights reserved.

#include <gtest/gtest.h>
#include <libnode/node.h>
#include <libnode/timer.h>

#include <libj/console.h>
#include <libj/status.h>

namespace libj {
namespace node {

class GTestTimerOnTimeout : LIBJ_JS_FUNCTION(GTestTimerOnTimeout)
 public:
    GTestTimerOnTimeout() {}

    void setId(Value id) {
        id_ = id;
    }

    Value operator()(JsArray::Ptr args) {
        clearTimeout(id_);
        clear_++;
        return Status::OK;
    }

    static UInt getClearCount() {
        return clear_;
    }

 private:
    static UInt clear_;

    Value id_;
};

UInt GTestTimerOnTimeout::clear_ = 0;

TEST(GTestTimer, TestSetTimeout) {
    GTestTimerOnTimeout::Ptr onTimeout1(new GTestTimerOnTimeout());
    Value id1 = setTimeout(onTimeout1, 100);
    onTimeout1->setId(id1);

    GTestTimerOnTimeout::Ptr onTimeout2(new GTestTimerOnTimeout());
    Value id2 = setInterval(onTimeout2, 75);
    onTimeout2->setId(id2);

    GTestTimerOnTimeout::Ptr onTimeout3(new GTestTimerOnTimeout());
    Value id3 = setInterval(onTimeout3, 100);
    onTimeout3->setId(id3);

    node::run();
    ASSERT_EQ(3, GTestTimerOnTimeout::getClearCount());
}

class GTestTimerOnInterval : LIBJ_JS_FUNCTION(GTestTimerOnInterval)
 public:
    GTestTimerOnInterval() : count_(0) {}

    void setId(Value id) {
        id_ = id;
    }

    void setCount(Int cnt) {
        count_ = cnt;
    }

    Value operator()(JsArray::Ptr args) {
        if (count_) {
            console::log(String::valueOf(count_--));
        } else {
            clearInterval(id_);
            clear_++;
        }
        return Status::OK;
    }

    static UInt getClearCount() {
        return clear_;
    }

 private:
    static UInt clear_;

    Value id_;
    Int count_;
};

UInt GTestTimerOnInterval::clear_ = 0;

TEST(GTestTimer, TestSetInterval) {
    GTestTimerOnInterval::Ptr onInterval1(new GTestTimerOnInterval());
    Value id1 = setInterval(onInterval1, 100);
    onInterval1->setId(id1);
    onInterval1->setCount(6);

    GTestTimerOnInterval::Ptr onInterval2(new GTestTimerOnInterval());
    Value id2 = setInterval(onInterval2, 75);
    onInterval2->setId(id2);
    onInterval2->setCount(8);

    node::run();
    ASSERT_EQ(2, GTestTimerOnInterval::getClearCount());
}

}  // namespace node
}  // namespace libj
<commit_msg>add new tests for clearTimeout and clearInterval<commit_after>// Copyright (c) 2012 Plenluno All rights reserved.

#include <gtest/gtest.h>
#include <libnode/node.h>
#include <libnode/timer.h>

#include <libj/console.h>
#include <libj/status.h>

namespace libj {
namespace node {

class GTestTimerOnTimeout : LIBJ_JS_FUNCTION(GTestTimerOnTimeout)
 public:
    GTestTimerOnTimeout() {}

    void setId(Value id) {
        id_ = id;
    }

    Value operator()(JsArray::Ptr args) {
        clearTimeout(id_);
        clear_++;
        return Status::OK;
    }

    static UInt getClearCount() {
        return clear_;
    }

    static void clearClearCount() {
        clear_ = 0;
    }

 private:
    static UInt clear_;

    Value id_;
};

UInt GTestTimerOnTimeout::clear_ = 0;

TEST(GTestTimer, TestSetTimeout) {
    GTestTimerOnTimeout::Ptr onTimeout1(new GTestTimerOnTimeout());
    Value id1 = setTimeout(onTimeout1, 100);
    onTimeout1->setId(id1);

    GTestTimerOnTimeout::Ptr onTimeout2(new GTestTimerOnTimeout());
    Value id2 = setTimeout(onTimeout2, 75);
    onTimeout2->setId(id2);

    GTestTimerOnTimeout::Ptr onTimeout3(new GTestTimerOnTimeout());
    Value id3 = setTimeout(onTimeout3, 100);
    onTimeout3->setId(id3);

    node::run();
    ASSERT_EQ(3, GTestTimerOnTimeout::getClearCount());
}

TEST(GTestTimer, TestClearTimeout) {
    GTestTimerOnTimeout::clearClearCount();

    GTestTimerOnTimeout::Ptr onTimeout1(new GTestTimerOnTimeout());
    Value id1 = setTimeout(onTimeout1, 1000);
    onTimeout1->setId(id1);

    GTestTimerOnTimeout::Ptr onTimeout2(new GTestTimerOnTimeout());
    Value id2 = setTimeout(onTimeout2, 100);
    onTimeout2->setId(id1);

    node::run();
    ASSERT_EQ(1, GTestTimerOnTimeout::getClearCount());
}

class GTestTimerOnInterval : LIBJ_JS_FUNCTION(GTestTimerOnInterval)
 public:
    GTestTimerOnInterval() : count_(0) {}

    void setId(Value id) {
        id_ = id;
    }

    void setCount(Int cnt) {
        count_ = cnt;
    }

    Value operator()(JsArray::Ptr args) {
        if (count_) {
            console::log(String::valueOf(count_--));
        } else {
            clearInterval(id_);
            clear_++;
        }
        return Status::OK;
    }

    static UInt getClearCount() {
        return clear_;
    }

    static void clearClearCount() {
        clear_ = 0;
    }

 private:
    static UInt clear_;

    Value id_;
    Int count_;
};

UInt GTestTimerOnInterval::clear_ = 0;

TEST(GTestTimer, TestSetInterval) {
    GTestTimerOnInterval::Ptr onInterval1(new GTestTimerOnInterval());
    Value id1 = setInterval(onInterval1, 100);
    onInterval1->setId(id1);
    onInterval1->setCount(6);

    GTestTimerOnInterval::Ptr onInterval2(new GTestTimerOnInterval());
    Value id2 = setInterval(onInterval2, 75);
    onInterval2->setId(id2);
    onInterval2->setCount(8);

    node::run();
    ASSERT_EQ(2, GTestTimerOnInterval::getClearCount());
}

TEST(GTestTimer, TestClearInterval) {
    GTestTimerOnTimeout::clearClearCount();
    GTestTimerOnInterval::clearClearCount();

    GTestTimerOnInterval::Ptr onInterval(new GTestTimerOnInterval());
    Value id1 = setInterval(onInterval, 1000);
    onInterval->setId(id1);
    onInterval->setCount(5);

    GTestTimerOnTimeout::Ptr onTimeout(new GTestTimerOnTimeout());
    Value id2 = setTimeout(onTimeout, 100);
    onTimeout->setId(id1);

    node::run();
    ASSERT_EQ(1, GTestTimerOnTimeout::getClearCount());
    ASSERT_EQ(0, GTestTimerOnInterval::getClearCount());
}

}  // namespace node
}  // namespace libj
<|endoftext|>


<commit_before>#include "RBufferStream.h"

RBufferStream::RBufferStream()
  : mBuffer(NULL)
  , mMaxSize(0)
  , mPos(0)
{
}

int
RBufferStream::available()
{
  return static_cast<int>(mMaxSize - mPos);
}

int
RBufferStream::read()
{
  if(mPos < mMaxSize)
  {
    int result = static_cast<int>(mBuffer[mPos]);

    mPos++;

    return result;
  }

  return -1;
}

int
RBufferStream::peek()
{
  if(mPos < mMaxSize)
  {
    int result = static_cast<int>(mBuffer[mPos]);

    return result;
  }

  return -1;
}

void
RBufferStream::flush()
{
}

size_t
RBufferStream::write(uint8_t c)
{
  if(mPos < mMaxSize)
  {
    mBuffer[mPos] = c;

    mPos++;

    return 1;
  }

  return 0;
}

void
RBufferStream::reset()
{
  mPos = 0;
}
<commit_msg>Added missing setBuffer() implementation<commit_after>#include "RBufferStream.h"

RBufferStream::RBufferStream()
  : mBuffer(NULL)
  , mMaxSize(0)
  , mPos(0)
{
}

void
RBufferStream::setBuffer(uint8_t *buffer, rsize maxSize)
{
  mBuffer  = buffer;
  mMaxSize = maxSize;
  mPos     = 0;
}

int
RBufferStream::available()
{
  return static_cast<int>(mMaxSize - mPos);
}

int
RBufferStream::read()
{
  if(mPos < mMaxSize)
  {
    int result = static_cast<int>(mBuffer[mPos]);

    mPos++;

    return result;
  }

  return -1;
}

int
RBufferStream::peek()
{
  if(mPos < mMaxSize)
  {
    int result = static_cast<int>(mBuffer[mPos]);

    return result;
  }

  return -1;
}

void
RBufferStream::flush()
{
}

size_t
RBufferStream::write(uint8_t c)
{
  if(mPos < mMaxSize)
  {
    mBuffer[mPos] = c;

    mPos++;

    return 1;
  }

  return 0;
}

void
RBufferStream::reset()
{
  mPos = 0;
}
<|endoftext|>


<commit_before>#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int totaltime(NumericVector x, int local_minimum) {

  //Instantiate output object
  int output_object = 0;
  int output_size = 0;

  //For each input object...
  for(int i = 0; i < x.size(); ++i) {

    //If the value is below the local minimum...
    if(x[i] <= local_minimum){

      //Add it to the output object
      output_object += x[i];

      //Increment the size counter
      output_size += 1;

    }

  }

  //Add a mean value to the output object to factor in the time period for the 'last' read
  output_object += (output_object/output_size);

  //Return
  return output_object;
}
<commit_msg>My first ever divide-by-zero error. ALL THE FEELS.<commit_after>#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int totaltime(NumericVector x, int local_minimum) {

  //Instantiate output object
  int output_object = 0;
  int output_size = 0;

  //For each input object...
  for(int i = 0; i < x.size(); ++i) {

    //If the value is below the local minimum...
    if(x[i] <= local_minimum){

      //Add it to the output object
      output_object += x[i];

      //Increment the size counter
      output_size += 1;

    }

  }

  //Solve for divide-by-zero error
  if(output_object > 0){

    //Add a mean value to the output object to factor in the time period for the 'last' read
    output_object += (output_object/output_size);
  }
  //Return
  return output_object;
}
<|endoftext|>


<commit_before>/* Copyright (C) 2005-2008 Damien Stehle.
   Copyright (C) 2007 David Cade.
   Copyright (C) 2011 Xavier Pujol.

   This file is part of fplll. fplll 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.

   fplll 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 Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public License
   along with fplll. If not, see <http://www.gnu.org/licenses/>. */

/* Template source file */

#include "hlll.h"
#include "util.h"

FPLLL_BEGIN_NAMESPACE

template <class ZT, class FT> void HLLLReduction<ZT, FT>::lll()
{
  int k     = 1;
  int k_max = 0;
  FT s;
  FT tmp;
  FT sum;
  FT delta_      = delta;  // TODO: not exactly the good value
  int start_time = cputime();
  long expo_k1_k1, expo_k_k1, expo_k_k;

  m.update_R(0);

  if (verbose)
    print_params();

  while (k < m.get_d())
  {
    if (k > k_max)
    {
      if (verbose)
      {
        cerr << "Discovering vector " << k + 1 << "/" << m.get_d()
             << " cputime=" << cputime() - start_time << endl;
      }
      k_max = k;
    }

    size_reduction(k);

    m.get_R(s, k, k - 1, expo_k_k1);
    s.mul(s, s);  // s = R(k, k - 1)^2
    m.get_R(tmp, k, k, expo_k_k);
    tmp.mul(tmp, tmp);  // tmp = R(k, k)^2
    s.add(tmp, s);      // s = R(k, k - 1)^2 + R(k, k)^2
    m.get_R(tmp, k - 1, k - 1, expo_k1_k1);
    tmp.mul(tmp, tmp);
    tmp.mul(delta_, tmp);  // tmp = delta_ * R(k - 1, k - 1)^2

    if (expo_k1_k1 > -1)
      s.mul_2si(s, 2 * (expo_k_k - expo_k1_k1));
    if (tmp <= s)
      k++;
    else
    {
      m.swap(k - 1, k);
      k = max(k - 1, 1);
    }
  }
}

template <class ZT, class FT> void HLLLReduction<ZT, FT>::size_reduction(int kappa)
{
  vector<FT> xf(kappa);
  FT ftmp0, ftmp1;
  long expo0 = -1;
  long expo1 = -1;
  // for all i > max_index, xf[i] == 0.
  int max_index;

  do
  {
    max_index = -1;
    m.update_R(kappa, kappa);

    for (int i = kappa - 1; i >= 0; i--)
    {
      m.get_R(ftmp1, kappa, i, expo0);  // expo0 = row_expo[kappa]
      m.get_R(ftmp0, i, i, expo1);      // expo1 = row_expo[i]

      ftmp1.div(ftmp1, ftmp0);  // x[i] = R(kappa, i) / R(i, i)
      /* If T = mpfr or dpe, enable_row_expo must be false and then, expo0 - expo1 == 0 (required by
       * rnd_we with this types) */
      ftmp1.rnd_we(ftmp1, expo0 - expo1);
      xf[i].neg(ftmp1);

      if (ftmp1.cmp(0.0) != 0)
      {
        for (int j = 0; j < i; j++)
        {
          m.get_R(ftmp1, i, j, expo0);      // expo0 = row_expo[i]
          ftmp1.mul(xf[i], ftmp1);          // ftmp1 = x[i] * R(i, j)
          m.get_R(ftmp0, kappa, j, expo0);  // expo0 = row_expo[kappa]
          ftmp0.add(ftmp0, ftmp1);          // ftmp0 = R(kappa, j) + x[i] * R(i, j)
          m.set_R(ftmp0, kappa, j);
        }
        max_index = max(max_index, i);
      }
    }

    m.norm_square_b_row(ftmp1, kappa, expo0);  // ftmp1 = ||b[kappa]||^2
    m.addmul_b_rows(kappa, xf);
    m.norm_square_b_row(ftmp0, kappa, expo1);  // ftmp0 = ||b[kappa]||^2
    ftmp1.mul(sr, ftmp1);                      // ftmp1 = 2^(-cd) * ftmp1

    if (expo1 > -1)
      ftmp0.mul_2si(ftmp0, expo1 - expo0);
  } while (ftmp0.cmp(ftmp1) <= 0);

  if (max_index == -1)
    m.update_R_last(kappa);
  else
    m.update_R(kappa);
}

// Works only there is no row_expo.
template <class ZT, class FT>
bool is_hlll_reduced(MatHouseholder<ZT, FT> &m, double delta, double eta)
{
  FT ftmp0;
  FT ftmp1;
  FT delta_ = delta;
  m.update_R();
  long expo;

  for (int i = 0; i < m.get_d(); i++)
  {
    for (int j = 0; j < i; j++)
    {
      m.get_R(ftmp0, i, j, expo);
      m.get_R(ftmp1, j, j, expo);
      ftmp1.div(ftmp0, ftmp1);
      ftmp1.abs(ftmp1);
      if (ftmp1.cmp(0.5) > 0)
        return false;
    }
  }
  for (int i = 1; i < m.get_d(); i++)
  {
    m.norm_square_b_row(ftmp0, i, expo);  // ftmp0 = ||b[i]||^2
    m.norm_square_R_row(ftmp1, i, i - 1, expo);
    ftmp1.sub(ftmp0, ftmp1);  // ftmp1 = ||b[i]||^2 - sum_{i = 0}^{i < i - 1}R[i][i]^2
    m.get_R(ftmp0, i - 1, i - 1, expo);
    ftmp0.mul(ftmp0, ftmp0);
    ftmp0.mul(delta_, ftmp0);  // ftmp0 = delta_ * R(i - 1, i - 1)^2

    if (ftmp0.cmp(ftmp1) > 0)
      return false;
  }
  return true;
}

/** instantiate functions **/

template class HLLLReduction<Z_NR<long>, FP_NR<double>>;
template class HLLLReduction<Z_NR<double>, FP_NR<double>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<double>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<double>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<double>> &m,
                                            double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<double>>(MatHouseholder<Z_NR<long>, FP_NR<double>> &m,
                                           double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<double>>(MatHouseholder<Z_NR<double>, FP_NR<double>> &m,
                                             double delta, double eta);

#ifdef FPLLL_WITH_LONG_DOUBLE
template class HLLLReduction<Z_NR<long>, FP_NR<long double>>;
template class HLLLReduction<Z_NR<double>, FP_NR<long double>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<long double>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<long double>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<long double>> &m,
                                                 double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<long double>>(MatHouseholder<Z_NR<long>, FP_NR<long double>> &m,
                                                double delta, double eta);
template bool is_hlll_reduced<Z_NR<double>, FP_NR<long double>>(
    MatHouseholder<Z_NR<double>, FP_NR<long double>> &m, double delta, double eta);
#endif

#ifdef FPLLL_WITH_QD
template class HLLLReduction<Z_NR<long>, FP_NR<dd_real>>;
template class HLLLReduction<Z_NR<double>, FP_NR<dd_real>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<dd_real>>;

template class HLLLReduction<Z_NR<long>, FP_NR<qd_real>>;
template class HLLLReduction<Z_NR<double>, FP_NR<qd_real>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<qd_real>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<qd_real>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<qd_real>> &m,
                                             double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<qd_real>>(MatHouseholder<Z_NR<long>, FP_NR<qd_real>> &m,
                                            double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<qd_real>>(MatHouseholder<Z_NR<double>, FP_NR<qd_real>> &m,
                                              double delta, double eta);
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<dd_real>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<dd_real>> &m,
                                             double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<dd_real>>(MatHouseholder<Z_NR<long>, FP_NR<dd_real>> &m,
                                            double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<dd_real>>(MatHouseholder<Z_NR<double>, FP_NR<dd_real>> &m,
                                              double delta, double eta);
#endif

#ifdef FPLLL_WITH_DPE
template class HLLLReduction<Z_NR<long>, FP_NR<dpe_t>>;
template class HLLLReduction<Z_NR<double>, FP_NR<dpe_t>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<dpe_t>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<dpe_t>> &m,
                                           double delta, double eta);
template bool is_hlll_reduced<Z_NR<long>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<long>, FP_NR<dpe_t>> &m,
                                                        double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<double>, FP_NR<dpe_t>> &m,
                                            double delta, double eta);
#endif

template class HLLLReduction<Z_NR<long>, FP_NR<mpfr_t>>;
template class HLLLReduction<Z_NR<double>, FP_NR<mpfr_t>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<mpfr_t>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<mpfr_t>> &m,
                                            double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<long>, FP_NR<mpfr_t>> &m,
                                           double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<double>, FP_NR<mpfr_t>> &m,
                                             double delta, double eta);

FPLLL_END_NAMESPACE
<commit_msg>Move an update of R out of the do-while loop.<commit_after>/* Copyright (C) 2005-2008 Damien Stehle.
   Copyright (C) 2007 David Cade.
   Copyright (C) 2011 Xavier Pujol.

   This file is part of fplll. fplll 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.

   fplll 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 Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public License
   along with fplll. If not, see <http://www.gnu.org/licenses/>. */

/* Template source file */

#include "hlll.h"
#include "util.h"

FPLLL_BEGIN_NAMESPACE

template <class ZT, class FT> void HLLLReduction<ZT, FT>::lll()
{
  int k     = 1;
  int k_max = 0;
  FT s;
  FT tmp;
  FT sum;
  FT delta_      = delta;  // TODO: not exactly the good value
  int start_time = cputime();
  long expo_k1_k1, expo_k_k1, expo_k_k;

  m.update_R(0);

  if (verbose)
    print_params();

  while (k < m.get_d())
  {
    if (k > k_max)
    {
      if (verbose)
      {
        cerr << "Discovering vector " << k + 1 << "/" << m.get_d()
             << " cputime=" << cputime() - start_time << endl;
      }
      k_max = k;
    }

    size_reduction(k);

    m.get_R(s, k, k - 1, expo_k_k1);
    s.mul(s, s);  // s = R(k, k - 1)^2
    m.get_R(tmp, k, k, expo_k_k);
    tmp.mul(tmp, tmp);  // tmp = R(k, k)^2
    s.add(tmp, s);      // s = R(k, k - 1)^2 + R(k, k)^2
    m.get_R(tmp, k - 1, k - 1, expo_k1_k1);
    tmp.mul(tmp, tmp);
    tmp.mul(delta_, tmp);  // tmp = delta_ * R(k - 1, k - 1)^2

    if (expo_k1_k1 > -1)
      s.mul_2si(s, 2 * (expo_k_k - expo_k1_k1));
    if (tmp <= s)
      k++;
    else
    {
      m.swap(k - 1, k);
      k = max(k - 1, 1);
    }
  }
}

template <class ZT, class FT> void HLLLReduction<ZT, FT>::size_reduction(int kappa)
{
  vector<FT> xf(kappa);
  FT ftmp0, ftmp1;
  long expo0 = -1;
  long expo1 = -1;
  // for all i > max_index, xf[i] == 0.
  int max_index;
  bool reduce = true;

  m.update_R(kappa, kappa);

  do
  {
    max_index = -1;

    for (int i = kappa - 1; i >= 0; i--)
    {
      m.get_R(ftmp1, kappa, i, expo0);  // expo0 = row_expo[kappa]
      m.get_R(ftmp0, i, i, expo1);      // expo1 = row_expo[i]

      ftmp1.div(ftmp1, ftmp0);  // x[i] = R(kappa, i) / R(i, i)
      /* If T = mpfr or dpe, enable_row_expo must be false and then, expo0 - expo1 == 0 (required by
       * rnd_we with this types) */
      ftmp1.rnd_we(ftmp1, expo0 - expo1);
      xf[i].neg(ftmp1);

      if (ftmp1.cmp(0.0) != 0)
      {
        for (int j = 0; j < i; j++)
        {
          m.get_R(ftmp1, i, j, expo0);      // expo0 = row_expo[i]
          ftmp1.mul(xf[i], ftmp1);          // ftmp1 = x[i] * R(i, j)
          m.get_R(ftmp0, kappa, j, expo0);  // expo0 = row_expo[kappa]
          ftmp0.add(ftmp0, ftmp1);          // ftmp0 = R(kappa, j) + x[i] * R(i, j)
          m.set_R(ftmp0, kappa, j);
        }
        max_index = max(max_index, i);
      }
    }

    m.norm_square_b_row(ftmp1, kappa, expo0);  // ftmp1 = ||b[kappa]||^2
    m.addmul_b_rows(kappa, xf);
    m.norm_square_b_row(ftmp0, kappa, expo1);  // ftmp0 = ||b[kappa]||^2
    ftmp1.mul(sr, ftmp1);                      // ftmp1 = 2^(-cd) * ftmp1

    if (expo1 > -1)
      ftmp0.mul_2si(ftmp0, expo1 - expo0);

    if (ftmp0.cmp(ftmp1) <= 0)
    {
      m.update_R(kappa, kappa);
    }
    else
      reduce = false;

  } while (reduce);

  if (max_index == -1)
    m.update_R_last(kappa);
  else
    m.update_R(kappa);
}

// Works only there is no row_expo.
template <class ZT, class FT>
bool is_hlll_reduced(MatHouseholder<ZT, FT> &m, double delta, double eta)
{
  FT ftmp0;
  FT ftmp1;
  FT delta_ = delta;
  m.update_R();
  long expo;

  for (int i = 0; i < m.get_d(); i++)
  {
    for (int j = 0; j < i; j++)
    {
      m.get_R(ftmp0, i, j, expo);
      m.get_R(ftmp1, j, j, expo);
      ftmp1.div(ftmp0, ftmp1);
      ftmp1.abs(ftmp1);
      if (ftmp1.cmp(0.5) > 0)
        return false;
    }
  }
  for (int i = 1; i < m.get_d(); i++)
  {
    m.norm_square_b_row(ftmp0, i, expo);  // ftmp0 = ||b[i]||^2
    m.norm_square_R_row(ftmp1, i, i - 1, expo);
    ftmp1.sub(ftmp0, ftmp1);  // ftmp1 = ||b[i]||^2 - sum_{i = 0}^{i < i - 1}R[i][i]^2
    m.get_R(ftmp0, i - 1, i - 1, expo);
    ftmp0.mul(ftmp0, ftmp0);
    ftmp0.mul(delta_, ftmp0);  // ftmp0 = delta_ * R(i - 1, i - 1)^2

    if (ftmp0.cmp(ftmp1) > 0)
      return false;
  }
  return true;
}

/** instantiate functions **/

template class HLLLReduction<Z_NR<long>, FP_NR<double>>;
template class HLLLReduction<Z_NR<double>, FP_NR<double>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<double>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<double>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<double>> &m,
                                            double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<double>>(MatHouseholder<Z_NR<long>, FP_NR<double>> &m,
                                           double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<double>>(MatHouseholder<Z_NR<double>, FP_NR<double>> &m,
                                             double delta, double eta);

#ifdef FPLLL_WITH_LONG_DOUBLE
template class HLLLReduction<Z_NR<long>, FP_NR<long double>>;
template class HLLLReduction<Z_NR<double>, FP_NR<long double>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<long double>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<long double>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<long double>> &m,
                                                 double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<long double>>(MatHouseholder<Z_NR<long>, FP_NR<long double>> &m,
                                                double delta, double eta);
template bool is_hlll_reduced<Z_NR<double>, FP_NR<long double>>(
    MatHouseholder<Z_NR<double>, FP_NR<long double>> &m, double delta, double eta);
#endif

#ifdef FPLLL_WITH_QD
template class HLLLReduction<Z_NR<long>, FP_NR<dd_real>>;
template class HLLLReduction<Z_NR<double>, FP_NR<dd_real>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<dd_real>>;

template class HLLLReduction<Z_NR<long>, FP_NR<qd_real>>;
template class HLLLReduction<Z_NR<double>, FP_NR<qd_real>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<qd_real>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<qd_real>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<qd_real>> &m,
                                             double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<qd_real>>(MatHouseholder<Z_NR<long>, FP_NR<qd_real>> &m,
                                            double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<qd_real>>(MatHouseholder<Z_NR<double>, FP_NR<qd_real>> &m,
                                              double delta, double eta);
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<dd_real>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<dd_real>> &m,
                                             double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<dd_real>>(MatHouseholder<Z_NR<long>, FP_NR<dd_real>> &m,
                                            double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<dd_real>>(MatHouseholder<Z_NR<double>, FP_NR<dd_real>> &m,
                                              double delta, double eta);
#endif

#ifdef FPLLL_WITH_DPE
template class HLLLReduction<Z_NR<long>, FP_NR<dpe_t>>;
template class HLLLReduction<Z_NR<double>, FP_NR<dpe_t>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<dpe_t>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<dpe_t>> &m,
                                           double delta, double eta);
template bool is_hlll_reduced<Z_NR<long>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<long>, FP_NR<dpe_t>> &m,
                                                        double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<double>, FP_NR<dpe_t>> &m,
                                            double delta, double eta);
#endif

template class HLLLReduction<Z_NR<long>, FP_NR<mpfr_t>>;
template class HLLLReduction<Z_NR<double>, FP_NR<mpfr_t>>;
template class HLLLReduction<Z_NR<mpz_t>, FP_NR<mpfr_t>>;
template bool
is_hlll_reduced<Z_NR<mpz_t>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<mpfr_t>> &m,
                                            double delta, double eta);
template bool
is_hlll_reduced<Z_NR<long>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<long>, FP_NR<mpfr_t>> &m,
                                           double delta, double eta);
template bool
is_hlll_reduced<Z_NR<double>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<double>, FP_NR<mpfr_t>> &m,
                                             double delta, double eta);

FPLLL_END_NAMESPACE
<|endoftext|>


<commit_before>// Sietronics Sieray CPI format
// Licence: Lesser GNU Public License 2.1 (LGPL)

#define BUILDING_XYLIB
#include "cpi.h"
#include "util.h"

using namespace std;
using namespace xylib::util;

namespace xylib {

const FormatInfo CpiDataSet::fmt_info(
    "cpi",
    "Sietronics Sieray CPI",
    "cpi",
    false,                      // whether binary
    false,                      // whether has multi-blocks
    &CpiDataSet::ctor,
    &CpiDataSet::check
);

bool CpiDataSet::check(istream &f, string*)
{
    string line;
    getline(f, line);
    return str_startwith(line, "SIETRONICS XRD SCAN");
}

void CpiDataSet::load_data(std::istream &f)
{
    /* format example:
        SIETRONICS XRD SCAN
        10.00
        155.00
        0.010
        Cu
        1.54056
        1-1-1900
        0.600
        HH117 CaO:Nb2O5 neutron batch .0
        SCANDATA
        8992
        9077
        9017
        9018
        9129
        9057
        ...
    */

    Block* blk = new Block;

    string s;
    getline (f, s); // first line
    getline (f, s);//xmin
    double xmin = my_strtod(s);
    getline (f, s); //xmax
    getline (f, s); //xstep
    double xstep = my_strtod(s);
    StepColumn *xcol = new StepColumn(xmin, xstep);
    blk->add_column(xcol);

    // ignore the rest of the header
    while (getline(f, s))
        if (str_startwith(s, "SCANDATA"))
            break;
    format_assert(this, f, "missing SCANDATA");

    // data
    VecColumn *ycol = new VecColumn();
    while (getline(f, s))
        ycol->add_val(my_strtod(s));

    blk->add_column(ycol);
    add_block(blk);
}

} // namespace xylib

<commit_msg>fix compilation with MSVC++<commit_after>// Sietronics Sieray CPI format
// Licence: Lesser GNU Public License 2.1 (LGPL)

#define BUILDING_XYLIB
#include "cpi.h"
#include "util.h"

using namespace std;
using namespace xylib::util;

namespace xylib {

const FormatInfo CpiDataSet::fmt_info(
    "cpi",
    "Sietronics Sieray CPI",
    "cpi",
    false,                      // whether binary
    false,                      // whether has multi-blocks
    &CpiDataSet::ctor,
    &CpiDataSet::check
);

bool CpiDataSet::check(istream &f, string*)
{
    string line;
    getline(f, line);
    return str_startwith(line, "SIETRONICS XRD SCAN");
}

void CpiDataSet::load_data(std::istream &f)
{
    /* format example:
        SIETRONICS XRD SCAN
        10.00
        155.00
        0.010
        Cu
        1.54056
        1-1-1900
        0.600
        HH117 CaO:Nb2O5 neutron batch .0
        SCANDATA
        8992
        9077
        9017
        9018
        9129
        9057
        ...
    */

    Block* blk = new Block;

    string s;
    getline (f, s); // first line
    getline (f, s);//xmin
    double xmin = my_strtod(s);
    getline (f, s); //xmax
    getline (f, s); //xstep
    double xstep = my_strtod(s);
    StepColumn *xcol = new StepColumn(xmin, xstep);
    blk->add_column(xcol);

    // ignore the rest of the header
    while (getline(f, s))
        if (str_startwith(s, "SCANDATA"))
            break;
    format_assert(this, !f.eof(), "missing SCANDATA");

    // data
    VecColumn *ycol = new VecColumn();
    while (getline(f, s))
        ycol->add_val(my_strtod(s));

    blk->add_column(ycol);
    add_block(blk);
}

} // namespace xylib

<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2010, Johannes Schlatow.
// 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 <iostream>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "Transport.h"
#include "TransportSSH.h"
#include "TransportRSYNC.h"
#include "TransportCurl.h"

////////////////////////////////////////////////////////////////////////////////
Transport::Transport (const Uri& uri)
{
  executable = "";
  this->uri = uri;
}

////////////////////////////////////////////////////////////////////////////////
Transport::~Transport ()
{
}

////////////////////////////////////////////////////////////////////////////////
Transport* Transport::getTransport(const Uri& uri)
{
  if (uri.protocol == "ssh")
  {
    return new TransportSSH(uri);
  }
  else if (uri.protocol == "rsync")
  {
    return new TransportRSYNC(uri);
  }
  else if ( (uri.protocol == "http")
         || (uri.protocol == "https")
         || (uri.protocol == "ftp") )
  {
    return new TransportCurl(uri);
  }

  return NULL;
}

////////////////////////////////////////////////////////////////////////////////
int Transport::execute()
{
  if (executable == "")
    return -1;

  pid_t child_pid = fork();

  if (child_pid == 0)
  {
    // this is done by the child process
    char shell[] = "sh";
    char opt[]   = "-c";

    std::string cmdline = executable;

    std::vector <std::string>::iterator it;
    for (it = arguments.begin(); it != arguments.end(); ++it)
    {
      std::string tmp = *it;
      cmdline += " " + tmp;
    }

    char** argv = new char*[4];
    argv[0] = shell;                  // sh
    argv[1] = opt;                    // -c
    argv[2] = (char*)cmdline.c_str();	// e.g. scp undo.data user@host:.task/
    argv[3] = NULL;                   // required by execv

    int ret = execvp("sh", argv);
    delete[] argv;

    exit(ret);
  }
  else
  {
    // this is done by the parent process
    int child_status;

    pid_t pid = waitpid(child_pid, &child_status, 0);

    if (pid == -1)
      return -1;
    else
      return child_status;
  }
}

////////////////////////////////////////////////////////////////////////////////
bool Transport::is_directory(const std::string& path)
{
  return path[path.length()-1] == '/';
}

////////////////////////////////////////////////////////////////////////////////
bool Transport::is_filelist(const std::string& path)
{
  return (path.find ("*") != std::string::npos)
      || (path.find ("?") != std::string::npos)
      || (path.find ("{") != std::string::npos);
}

////////////////////////////////////////////////////////////////////////////////

<commit_msg>Bug #570<commit_after>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2010, Johannes Schlatow.
// 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 <iostream>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "Transport.h"
#include "TransportSSH.h"
#include "TransportRSYNC.h"
#include "TransportCurl.h"

////////////////////////////////////////////////////////////////////////////////
Transport::Transport (const Uri& uri)
{
  executable = "";
  this->uri = uri;
}

////////////////////////////////////////////////////////////////////////////////
Transport::~Transport ()
{
}

////////////////////////////////////////////////////////////////////////////////
Transport* Transport::getTransport(const Uri& uri)
{
  if (uri.protocol == "ssh")
  {
    return new TransportSSH(uri);
  }
  else if (uri.protocol == "rsync")
  {
    return new TransportRSYNC(uri);
  }
  else if ( (uri.protocol == "http")
         || (uri.protocol == "https")
         || (uri.protocol == "ftp") )
  {
    return new TransportCurl(uri);
  }

  return NULL;
}

////////////////////////////////////////////////////////////////////////////////
int Transport::execute()
{
  if (executable == "")
    return -1;

  pid_t child_pid = fork();

  if (child_pid == 0)
  {
    // this is done by the child process
    char shell[] = "bash";
    char opt[]   = "-c";

    std::string cmdline = executable;

    std::vector <std::string>::iterator it;
    for (it = arguments.begin(); it != arguments.end(); ++it)
    {
      std::string tmp = *it;
      cmdline += " " + tmp;
    }

    char** argv = new char*[4];
    argv[0] = shell;                  // sh
    argv[1] = opt;                    // -c
    argv[2] = (char*)cmdline.c_str();	// e.g. scp undo.data user@host:.task/
    argv[3] = NULL;                   // required by execv

    int ret = execvp("sh", argv);
    delete[] argv;

    exit(ret);
  }
  else
  {
    // this is done by the parent process
    int child_status;

    pid_t pid = waitpid(child_pid, &child_status, 0);

    if (pid == -1)
      return -1;
    else
      return child_status;
  }
}

////////////////////////////////////////////////////////////////////////////////
bool Transport::is_directory(const std::string& path)
{
  return path[path.length()-1] == '/';
}

////////////////////////////////////////////////////////////////////////////////
bool Transport::is_filelist(const std::string& path)
{
  return (path.find ("*") != std::string::npos)
      || (path.find ("?") != std::string::npos)
      || (path.find ("{") != std::string::npos);
}

////////////////////////////////////////////////////////////////////////////////

<|endoftext|>


<commit_before>/*************************************************************************/
/*  detect_prime.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.                */
/*************************************************************************/

#ifdef X11_ENABLED
#if defined(OPENGL_ENABLED)

#include "detect_prime.h"

#include "core/print_string.h"
#include "core/ustring.h"

#include <stdlib.h>

#include <GL/gl.h>
#include <GL/glx.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include <cstring>

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092

typedef GLXContext (*GLXCREATECONTEXTATTRIBSARBPROC)(Display *, GLXFBConfig, GLXContext, Bool, const int *);

struct vendor {
	const char *glxvendor;
	int priority;
};

vendor vendormap[] = {
	{ "Advanced Micro Devices, Inc.", 30 },
	{ "AMD", 30 },
	{ "NVIDIA Corporation", 30 },
	{ "X.Org", 30 },
	{ "Intel Open Source Technology Center", 20 },
	{ "Intel", 20 },
	{ "nouveau", 10 },
	{ "Mesa Project", 0 },
	{ nullptr, 0 }
};

// Runs inside a child. Exiting will not quit the engine.
void create_context() {
	Display *x11_display = XOpenDisplay(nullptr);
	Window x11_window;
	GLXContext glx_context;

	GLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (GLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte *)"glXCreateContextAttribsARB");

	static int visual_attribs[] = {
		GLX_RENDER_TYPE, GLX_RGBA_BIT,
		GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
		GLX_DOUBLEBUFFER, true,
		GLX_RED_SIZE, 1,
		GLX_GREEN_SIZE, 1,
		GLX_BLUE_SIZE, 1,
		GLX_DEPTH_SIZE, 24,
		None
	};

	int fbcount;
	GLXFBConfig fbconfig = nullptr;
	XVisualInfo *vi = nullptr;

	XSetWindowAttributes swa;
	swa.event_mask = StructureNotifyMask;
	swa.border_pixel = 0;
	unsigned long valuemask = CWBorderPixel | CWColormap | CWEventMask;

	GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs, &fbcount);
	if (!fbc) {
		exit(1);
	}

	vi = glXGetVisualFromFBConfig(x11_display, fbc[0]);

	fbconfig = fbc[0];

	static int context_attribs[] = {
		GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
		GLX_CONTEXT_MINOR_VERSION_ARB, 3,
		GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
		GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
		None
	};

	glx_context = glXCreateContextAttribsARB(x11_display, fbconfig, nullptr, true, context_attribs);

	swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone);
	x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, 10, 10, 0, vi->depth, InputOutput, vi->visual, valuemask, &swa);

	if (!x11_window) {
		exit(1);
	}

	glXMakeCurrent(x11_display, x11_window, glx_context);
	XFree(vi);
}

int detect_prime() {
	pid_t p;
	int priorities[2] = {};
	String vendors[2];
	String renderers[2];

	vendors[0] = "Unknown";
	vendors[1] = "Unknown";
	renderers[0] = "Unknown";
	renderers[1] = "Unknown";

	for (int i = 0; i < 2; ++i) {
		int fdset[2];

		if (pipe(fdset) == -1) {
			print_verbose("Failed to pipe(), using default GPU");
			return 0;
		}

		// Fork so the driver initialization can crash without taking down the engine.
		p = fork();

		if (p > 0) {
			// Main thread

			int stat_loc = 0;
			char string[201];
			string[200] = '\0';

			close(fdset[1]);

			waitpid(p, &stat_loc, 0);

			if (!stat_loc) {
				// No need to do anything complicated here. Anything less than
				// PIPE_BUF will be delivered in one read() call.
				// Leave it 'Unknown' otherwise.
				if (read(fdset[0], string, sizeof(string) - 1) > 0) {
					vendors[i] = string;
					renderers[i] = string + strlen(string) + 1;
				}
			}

			close(fdset[0]);

		} else {
			// In child, exit() here will not quit the engine.

			char string[201];

			close(fdset[0]);

			if (i) {
				setenv("DRI_PRIME", "1", 1);
			}
			create_context();

			const char *vendor = (const char *)glGetString(GL_VENDOR);
			const char *renderer = (const char *)glGetString(GL_RENDERER);

			unsigned int vendor_len = strlen(vendor) + 1;
			unsigned int renderer_len = strlen(renderer) + 1;

			if (vendor_len + renderer_len >= sizeof(string)) {
				renderer_len = 200 - vendor_len;
			}

			memcpy(&string, vendor, vendor_len);
			memcpy(&string[vendor_len], renderer, renderer_len);

			if (write(fdset[1], string, vendor_len + renderer_len) == -1) {
				print_verbose("Couldn't write vendor/renderer string.");
			}
			close(fdset[1]);
			exit(0);
		}
	}

	int preferred = 0;
	int priority = 0;

	if (vendors[0] == vendors[1]) {
		print_verbose("Only one GPU found, using default.");
		return 0;
	}

	for (int i = 1; i >= 0; --i) {
		vendor *v = vendormap;
		while (v->glxvendor) {
			if (v->glxvendor == vendors[i]) {
				priorities[i] = v->priority;

				if (v->priority >= priority) {
					priority = v->priority;
					preferred = i;
				}
			}
			++v;
		}
	}

	print_verbose("Found renderers:");
	for (int i = 0; i < 2; ++i) {
		print_verbose("Renderer " + itos(i) + ": " + renderers[i] + " with priority: " + itos(priorities[i]));
	}

	print_verbose("Using renderer: " + renderers[preferred]);
	return preferred;
}

#endif
#endif
<commit_msg>Set default priority on PRIME detection vendor struct.<commit_after>/*************************************************************************/
/*  detect_prime.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.                */
/*************************************************************************/

#ifdef X11_ENABLED
#if defined(OPENGL_ENABLED)

#include "detect_prime.h"

#include "core/print_string.h"
#include "core/ustring.h"

#include <stdlib.h>

#include <GL/gl.h>
#include <GL/glx.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include <cstring>

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092

typedef GLXContext (*GLXCREATECONTEXTATTRIBSARBPROC)(Display *, GLXFBConfig, GLXContext, Bool, const int *);

struct vendor {
	const char *glxvendor;
	int priority = 0;
};

vendor vendormap[] = {
	{ "Advanced Micro Devices, Inc.", 30 },
	{ "AMD", 30 },
	{ "NVIDIA Corporation", 30 },
	{ "X.Org", 30 },
	{ "Intel Open Source Technology Center", 20 },
	{ "Intel", 20 },
	{ "nouveau", 10 },
	{ "Mesa Project", 0 },
	{ nullptr, 0 }
};

// Runs inside a child. Exiting will not quit the engine.
void create_context() {
	Display *x11_display = XOpenDisplay(nullptr);
	Window x11_window;
	GLXContext glx_context;

	GLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (GLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte *)"glXCreateContextAttribsARB");

	static int visual_attribs[] = {
		GLX_RENDER_TYPE, GLX_RGBA_BIT,
		GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
		GLX_DOUBLEBUFFER, true,
		GLX_RED_SIZE, 1,
		GLX_GREEN_SIZE, 1,
		GLX_BLUE_SIZE, 1,
		GLX_DEPTH_SIZE, 24,
		None
	};

	int fbcount;
	GLXFBConfig fbconfig = nullptr;
	XVisualInfo *vi = nullptr;

	XSetWindowAttributes swa;
	swa.event_mask = StructureNotifyMask;
	swa.border_pixel = 0;
	unsigned long valuemask = CWBorderPixel | CWColormap | CWEventMask;

	GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs, &fbcount);
	if (!fbc) {
		exit(1);
	}

	vi = glXGetVisualFromFBConfig(x11_display, fbc[0]);

	fbconfig = fbc[0];

	static int context_attribs[] = {
		GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
		GLX_CONTEXT_MINOR_VERSION_ARB, 3,
		GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
		GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
		None
	};

	glx_context = glXCreateContextAttribsARB(x11_display, fbconfig, nullptr, true, context_attribs);

	swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone);
	x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, 10, 10, 0, vi->depth, InputOutput, vi->visual, valuemask, &swa);

	if (!x11_window) {
		exit(1);
	}

	glXMakeCurrent(x11_display, x11_window, glx_context);
	XFree(vi);
}

int detect_prime() {
	pid_t p;
	int priorities[2] = {};
	String vendors[2];
	String renderers[2];

	vendors[0] = "Unknown";
	vendors[1] = "Unknown";
	renderers[0] = "Unknown";
	renderers[1] = "Unknown";

	for (int i = 0; i < 2; ++i) {
		int fdset[2];

		if (pipe(fdset) == -1) {
			print_verbose("Failed to pipe(), using default GPU");
			return 0;
		}

		// Fork so the driver initialization can crash without taking down the engine.
		p = fork();

		if (p > 0) {
			// Main thread

			int stat_loc = 0;
			char string[201];
			string[200] = '\0';

			close(fdset[1]);

			waitpid(p, &stat_loc, 0);

			if (!stat_loc) {
				// No need to do anything complicated here. Anything less than
				// PIPE_BUF will be delivered in one read() call.
				// Leave it 'Unknown' otherwise.
				if (read(fdset[0], string, sizeof(string) - 1) > 0) {
					vendors[i] = string;
					renderers[i] = string + strlen(string) + 1;
				}
			}

			close(fdset[0]);

		} else {
			// In child, exit() here will not quit the engine.

			char string[201];

			close(fdset[0]);

			if (i) {
				setenv("DRI_PRIME", "1", 1);
			}
			create_context();

			const char *vendor = (const char *)glGetString(GL_VENDOR);
			const char *renderer = (const char *)glGetString(GL_RENDERER);

			unsigned int vendor_len = strlen(vendor) + 1;
			unsigned int renderer_len = strlen(renderer) + 1;

			if (vendor_len + renderer_len >= sizeof(string)) {
				renderer_len = 200 - vendor_len;
			}

			memcpy(&string, vendor, vendor_len);
			memcpy(&string[vendor_len], renderer, renderer_len);

			if (write(fdset[1], string, vendor_len + renderer_len) == -1) {
				print_verbose("Couldn't write vendor/renderer string.");
			}
			close(fdset[1]);
			exit(0);
		}
	}

	int preferred = 0;
	int priority = 0;

	if (vendors[0] == vendors[1]) {
		print_verbose("Only one GPU found, using default.");
		return 0;
	}

	for (int i = 1; i >= 0; --i) {
		vendor *v = vendormap;
		while (v->glxvendor) {
			if (v->glxvendor == vendors[i]) {
				priorities[i] = v->priority;

				if (v->priority >= priority) {
					priority = v->priority;
					preferred = i;
				}
			}
			++v;
		}
	}

	print_verbose("Found renderers:");
	for (int i = 0; i < 2; ++i) {
		print_verbose("Renderer " + itos(i) + ": " + renderers[i] + " with priority: " + itos(priorities[i]));
	}

	print_verbose("Using renderer: " + renderers[preferred]);
	return preferred;
}

#endif
#endif
<|endoftext|>


<commit_before>#include "Simlink.h"

Simlink::Simlink() {
    sf::RenderWindow window(sf::VideoMode(1200, 900), "Fido Simulator");

    sf::Texture texture;
    if (!texture.loadFromFile("background.png")) {
        return EXIT_FAILURE;
    } sf::Sprite background(texture);

    sf::Font font;
    if (!font.loadFromFile("sansation.ttf")) {
        return EXIT_FAILURE;
    } sf::Text text("Hello SFML", font, 50);
    text.setColor(sf::Color::Black);

    sf::Music music;
    if (!music.openFromFile("nice_music.ogg")) {
        return EXIT_FAILURE;
    } music.play();

    while (window.isOpen()) {
        mainLoop(window,background);
    }

}

void Simlink::mainLoop(sf::RenderWindow& window,sf::Sprite background) {
    sf::Event event;
    while (window.pollEvent(event)) {
        switch (event.type) {
            case sf::Event::Closed:
                window.close();
                break;
            case sf::Event::KeyPressed:
                if (event.key.code == sf::Keyboard::Escape) window.close();
                break;
            case sf::Event::MouseButtonPressed:
                if (event.mouseButton.button == sf::Mouse::Left) {
                    click = true;
                    cx = event.mouseButton.x;
                    cy = event.mouseButton.y;
                } break;
            case sf::Event::MouseButtonReleased:
                if (event.mouseButton.button == sf::Mouse::Left)
                    click = false;
                break;
            case sf::Event::MouseMoved:
                if (click) {
                    cx = event.mouseMove.x;
                    cy = event.mouseMove.y;
                } break;
            default:
                break;
        }

    }

    window.clear();

    window.draw(background);

    ///window.draw(text);

    window.display();
}

<commit_msg>fixed exits<commit_after>#include "Simlink.h"

Simlink::Simlink() {
    sf::RenderWindow window(sf::VideoMode(1200, 900), "Fido Simulator");

    sf::Texture texture;
    if (!texture.loadFromFile("background.png")) {
        exit(EXIT_FAILURE);
    } sf::Sprite background(texture);

    sf::Font font;
    if (!font.loadFromFile("sansation.ttf")) {
		exit(EXIT_FAILURE);
    } sf::Text text("Hello SFML", font, 50);
    text.setColor(sf::Color::Black);

    sf::Music music;
    if (!music.openFromFile("nice_music.ogg")) {
		exit(EXIT_FAILURE);
    } music.play();

    while (window.isOpen()) {
        mainLoop(window,background);
    }

}

void Simlink::mainLoop(sf::RenderWindow& window,sf::Sprite background) {
    sf::Event event;
    while (window.pollEvent(event)) {
        switch (event.type) {
            case sf::Event::Closed:
                window.close();
                break;
            case sf::Event::KeyPressed:
                if (event.key.code == sf::Keyboard::Escape) window.close();
                break;
            case sf::Event::MouseButtonPressed:
                if (event.mouseButton.button == sf::Mouse::Left) {
                    click = true;
                    cx = event.mouseButton.x;
                    cy = event.mouseButton.y;
                } break;
            case sf::Event::MouseButtonReleased:
                if (event.mouseButton.button == sf::Mouse::Left)
                    click = false;
                break;
            case sf::Event::MouseMoved:
                if (click) {
                    cx = event.mouseMove.x;
                    cy = event.mouseMove.y;
                } break;
            default:
                break;
        }

    }

    window.clear();

    window.draw(background);

    ///window.draw(text);

    window.display();
}

<|endoftext|>


<commit_before>class Solution {
public:
    // dynamic programming solution - O(n) time, O(n) space
	// (non-optimal, as it turns out, since the problem can be reduced to the fibonacci sequence for which there is a closed formula for this, but it was accepted)
    int climbStairs(int n) {
        vector<int> counts {1,1}; // 1 way to split a 1, and 1 way to split a 0 just to provide a base case that works with the rest (if n is positive, it won't come up in and of itself)
        for (int i = 2; i <= n; i++) {
            counts.push_back(counts[i-2] + counts[i-1];);
        }
        return counts[n];
    }
};
<commit_msg>typo fix<commit_after>class Solution {
public:
    // dynamic programming solution - O(n) time, O(n) space
	// (non-optimal, as it turns out, since the problem can be reduced to the fibonacci sequence for which there is a closed formula for this, but it was accepted)
    int climbStairs(int n) {
        vector<int> counts {1,1}; // 1 way to split a 1, and 1 way to split a 0 just to provide a base case that works with the rest (if n is positive, it won't come up in and of itself)
        for (int i = 2; i <= n; i++) {
            counts.push_back(counts[i-2] + counts[i-1]);
        }
        return counts[n];
    }
};
<|endoftext|>


<commit_before>/******************************************************************************
    SDLMessageBox.cpp

  Copyright (c) 2013 Jeffrey Carpenter
  All rights reserved.

******************************************************************************/
#include "SDLMessageBox.h"

SDLMessageBox::SDLMessageBox ( void )
{
  #ifdef DEBUG_MESSAGEBOX_OBJ
    std::cout << "SDLMessageBox::SDLMessageBox (): " << "Hello, world!" << std::endl << std::endl;
  #endif

  this->enabled = true;

  window_borders.clear();

  for ( int i = 0; i < window_borders.size(); i++ )
    window_borders[i].setColor ( 0, 0, 0 );

  this->geometry.setCoords ( 0, 0, 0, 0 );
}

SDLMessageBox::~SDLMessageBox ( void )
{
  #ifdef DEBUG_MESSAGEBOX_OBJ
    std::cout << "SDLMessageBox::~SDLMessageBox (): " << "Goodbye cruel world!" << std::endl << std::endl;
  #endif

  this->enabled = false;
}

void SDLMessageBox::Init ( unsigned int x, unsigned int y, unsigned int width, unsigned int height )
{
  // init geometry coords w/ arguments list
  this->geometry.setCoords ( x, y, width, height );
}

bool SDLMessageBox::isEnabled ( void )
{
  if ( this->enabled == true )
    return true;
  else
    return false;
}

void SDLMessageBox::disable ( void )
{
 this->enabled = false;
}

void SDLMessageBox::enable ( void )
{
  this->enabled = true;
}

void SDLMessageBox::setBorder ( GColor &border_colors )
{
  this->window_borders.push_back ( border_colors );

  #ifdef DEBUG_MESSAGEBOX
    std::cout << "window_borders: " << this->window_borders.getRed() << "\n\n";
    std::cout << "window_borders: " << this->window_borders.getGreen() << "\n\n";
    std::cout << "window_borders: " << this->window_borders.getBlue() << "\n\n";
  #endif
}

void SDLMessageBox::setBackground ( SDLGradient *gradient )
{
  this->background = gradient;
}

void SDLMessageBox::Update ( void )
{
  //
}

void SDLMessageBox::Draw ( SDL_Surface *video_buffer, unsigned int x, unsigned int y, unsigned int width, unsigned int height )
{
  unsigned int padding = 1;
  unsigned int x_offset = x + width; //unsigned int x_offset = ( x + width ) - padding;
  unsigned int y_offset = y + height; //unsigned int y_offset = ( y + height ) - padding;

  if ( this->background != NULL )
  {
    GColor starting ( 66, 66, 66 );
    GColor ending ( 99, 99, 99 );
    background->Init ( starting, ending, x, y, width, height, 0, 0, 0 );
    background->Draw ( video_buffer, x, y, width, height, 0 );
  }

  Gfx::lockSurface ( video_buffer );

  Gfx::drawLine ( video_buffer, x, y, x_offset - padding, y, this->window_borders[0].getColor() ); // top0
  Gfx::drawLine ( video_buffer, x, y + 1, x_offset - padding, y + 1, this->window_borders[1].getColor() ); // top1

  Gfx::drawLine ( video_buffer, x, y + 1, x, y_offset - padding, this->window_borders[2].getColor()  ); // left1
  Gfx::drawLine ( video_buffer, x + 1, y + 2, x + 1, y_offset - padding, this->window_borders[3].getColor() ); // left2

  Gfx::drawLine ( video_buffer, x, y_offset - padding, x_offset - padding, y_offset - padding, this->window_borders[4].getColor() ); // bottom1
  Gfx::drawLine ( video_buffer, x_offset - padding, y, x_offset - padding, y_offset - padding, this->window_borders[5].getColor() ); // right1

  Gfx::unlockSurface ( video_buffer );
}
<commit_msg>Added two more lines into messagebox for additional depth clarity<commit_after>/******************************************************************************
    SDLMessageBox.cpp

  Copyright (c) 2013 Jeffrey Carpenter
  All rights reserved.

******************************************************************************/
#include "SDLMessageBox.h"

SDLMessageBox::SDLMessageBox ( void )
{
  #ifdef DEBUG_MESSAGEBOX_OBJ
    std::cout << "SDLMessageBox::SDLMessageBox (): " << "Hello, world!" << std::endl << std::endl;
  #endif

  this->enabled = true;

  window_borders.clear();

  for ( int i = 0; i < window_borders.size(); i++ )
    window_borders[i].setColor ( 0, 0, 0 );

  this->geometry.setCoords ( 0, 0, 0, 0 );
}

SDLMessageBox::~SDLMessageBox ( void )
{
  #ifdef DEBUG_MESSAGEBOX_OBJ
    std::cout << "SDLMessageBox::~SDLMessageBox (): " << "Goodbye cruel world!" << std::endl << std::endl;
  #endif

  this->enabled = false;
}

void SDLMessageBox::Init ( unsigned int x, unsigned int y, unsigned int width, unsigned int height )
{
  // init geometry coords w/ arguments list
  this->geometry.setCoords ( x, y, width, height );
}

bool SDLMessageBox::isEnabled ( void )
{
  if ( this->enabled == true )
    return true;
  else
    return false;
}

void SDLMessageBox::disable ( void )
{
 this->enabled = false;
}

void SDLMessageBox::enable ( void )
{
  this->enabled = true;
}

void SDLMessageBox::setBorder ( GColor &border_colors )
{
  this->window_borders.push_back ( border_colors );

  #ifdef DEBUG_MESSAGEBOX
    std::cout << "window_borders: " << this->window_borders.getRed() << "\n\n";
    std::cout << "window_borders: " << this->window_borders.getGreen() << "\n\n";
    std::cout << "window_borders: " << this->window_borders.getBlue() << "\n\n";
  #endif
}

void SDLMessageBox::setBackground ( SDLGradient *gradient )
{
  this->background = gradient;
}

void SDLMessageBox::Update ( void )
{
  //
}

void SDLMessageBox::Draw ( SDL_Surface *video_buffer, unsigned int x, unsigned int y, unsigned int width, unsigned int height )
{
  unsigned int padding = 1;
  unsigned int x_offset = x + width; //unsigned int x_offset = ( x + width ) - padding;
  unsigned int y_offset = y + height; //unsigned int y_offset = ( y + height ) - padding;

  if ( this->background != NULL )
  {
    GColor starting ( 66, 66, 66 );
    GColor ending ( 99, 99, 99 );
    background->Init ( starting, ending, x, y, width, height, 0, 0, 0 );
    background->Draw ( video_buffer, x, y, width, height, 0 );
  }

  Gfx::lockSurface ( video_buffer );

  Gfx::drawLine ( video_buffer, x, y, x_offset - padding, y, this->window_borders[0].getColor() ); // top0
  Gfx::drawLine ( video_buffer, x, y + 1, x_offset - padding, y + 1, this->window_borders[1].getColor() ); // top1

  Gfx::drawLine ( video_buffer, x, y + 1, x, y_offset - padding, this->window_borders[2].getColor()  ); // left1
  Gfx::drawLine ( video_buffer, x + 1, y + 2, x + 1, y_offset - padding, this->window_borders[3].getColor() ); // left2

  Gfx::drawLine ( video_buffer, x, y_offset - padding, x_offset - padding, y_offset - padding, this->window_borders[4].getColor() ); // bottom1
  Gfx::drawLine ( video_buffer, x, y_offset, x_offset + padding, y_offset, this->window_borders[5].getColor() ); // bottom2

  Gfx::drawLine ( video_buffer, x_offset - padding, y, x_offset - padding, y_offset + padding, this->window_borders[6].getColor() ); // right1
  Gfx::drawLine ( video_buffer, x_offset, y, x_offset, y_offset + padding, this->window_borders[7].getColor() ); // right2

  Gfx::unlockSurface ( video_buffer );
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)
 *
 * Released under the MIT license, see LICENSE.txt
 */

#include <deque>
#include <cassert>
#include <locale>
#include "halBranchMutations.h"

using namespace std;
using namespace hal;

const string BranchMutations::inversionBedTag = "V";
const string BranchMutations::insertionBedTag = "I";
const string BranchMutations::deletionBedTag = "D";
const string BranchMutations::transpositionBedTag = "P";
const string BranchMutations::duplicationBedTag = "U";
const string BranchMutations::gapInsertionBedTag = "GI";
const string BranchMutations::gapDeletionBedTag = "GD";
string BranchMutations::substitutionBedTag(char parent, char child)
{
  assert(parent == toupper(parent));
  assert(child == toupper(child));
  assert(isNucleotide(parent) && parent != 'N' &&
         isNucleotide(child) && child != 'N');
  return string("S_") + parent + child;
}

BranchMutations::BranchMutations()
{

}

BranchMutations::~BranchMutations()
{

}

void BranchMutations::analyzeBranch(AlignmentConstPtr alignment,
                                    hal_size_t gapThreshold,
                                    double nThreshold,
                                    ostream* refBedStream,
                                    ostream* parentBedStream,
                                    ostream* snpBedStream,
                                    const Genome* reference,
                                    hal_index_t startPosition,
                                    hal_size_t length)
{
  assert(reference != NULL);
  if (length == 0)
  {
    throw hal_exception("Cannot convert zero length sequence");
  }
  if (reference->getParent() == NULL)
  {
    throw hal_exception("Reference genome must have parent");
  }

  _reference = reference;
  _start = startPosition;
  _length = length;
  _alignment = alignment;
  _maxGap = gapThreshold;
  _nThreshold = nThreshold;
  _refStream = refBedStream;
  _parentStream = parentBedStream;
  _snpStream = snpBedStream;
  _refName = _reference->getName();
  _parName = _reference->getParent()->getName();

  writeHeaders();

  hal_index_t end = startPosition + (hal_index_t)length - 1;

  _top  = reference->getTopSegmentIterator();
  _top->toSite(startPosition);
  _bottom1 = reference->getParent()->getBottomSegmentIterator();
  _bottom2 = reference->getParent()->getBottomSegmentIterator();

  _rearrangement = reference->getRearrangement(_top->getArrayIndex(),
                                               _maxGap, _nThreshold);

  do {
    _sequence = _reference->getSequenceBySite(
      _rearrangement->getLeftBreakpoint()->getStartPosition());
    switch (_rearrangement->getID())
    {
    case Rearrangement::Deletion:
      writeDeletion();
      break;
    case Rearrangement::Inversion:
    case Rearrangement::Transposition:
    case Rearrangement::Insertion:
      writeInsertionOrInversion();
      break;
    case Rearrangement::Duplication:
      writeDuplication();
    default:
      break;
    }
    writeSubstitutions();
    writeGapInsertions();
  }
  while (_rearrangement->identifyNext() == true &&
         _rearrangement->getLeftBreakpoint()->getStartPosition() <= end);

  // kind of stupid, but we do a second pass to get the gapped deletions
  _top  = reference->getTopSegmentIterator();
  _top->toSite(startPosition);
  _rearrangement = reference->getRearrangement(_top->getArrayIndex(), 0,
                                               _nThreshold, true);
  do {
    switch (_rearrangement->getID())
    {
    case Rearrangement::Deletion:
      writeGapDeletion();
    default:
      break;
    }
  }
  while (_rearrangement->identifyNext() == true &&
         _rearrangement->getLeftBreakpoint()->getStartPosition() <= end);
}

void BranchMutations::writeInsertionOrInversion()
{
  assert(_refStream != NULL);
  hal_size_t startPos = _rearrangement->getLeftBreakpoint()->getStartPosition();
  hal_size_t endPos = _rearrangement->getRightBreakpoint()->getEndPosition();

  assert(startPos < _start + _length && endPos >= _start);

  if (startPos < _start)
  {
    startPos = _start;
  }
  if (endPos >= _start + _length)
  {
    endPos = _start + _length - 1;
  }

  *_refStream << _sequence->getName() << '\t'
              << startPos - _sequence->getStartPosition() << '\t'
              << endPos + 1 - _sequence->getStartPosition() << '\t';

  if (_rearrangement->getID() ==  Rearrangement::Inversion)
  {
    *_refStream << inversionBedTag << '\t';
  }
  else if (_rearrangement->getID() ==  Rearrangement::Insertion)
  {
    *_refStream << insertionBedTag << '\t';
  }
  else
  {
    assert(_rearrangement->getID() ==  Rearrangement::Transposition);
    *_refStream << transpositionBedTag << '\t';
  }

  *_refStream << _parName << '\t' << _refName << '\n';
}

void BranchMutations::writeSubstitutions()
{
  if (_snpStream == NULL)
  {
    return;
  }
  string tstring, bstring;
  hal_size_t pos;
  _top->copy(_rearrangement->getLeftBreakpoint());
  assert(_top->getReversed() == false);
  do {
    if (_top->hasParent())
    {
      _bottom1->toParent(_top);
      _top->getString(tstring);
      _bottom1->getString(bstring);
      assert(tstring.length() == bstring.length());

      for (hal_index_t i = 0; i < (hal_index_t)tstring.length(); ++i)
      {
        pos = i + _top->getStartPosition();
        char c = toupper(tstring[i]);
        char p = toupper(bstring[i]);

        if (pos >= _start && pos < _start + _length &&
            c != 'N' && p != 'N' && c != p)
        {
          *_snpStream << _sequence->getName() << '\t'
                      << pos - _sequence->getStartPosition() << '\t'
                      << pos + 1 - _sequence->getStartPosition() << '\t'
                      << substitutionBedTag(p, c) << '\t'
                      << _parName << '\t' << _refName<< '\n';
        }
      }
    }
    _top->toRight();
  }
  while (_top->getArrayIndex() <
         _rearrangement->getRightBreakpoint()->getArrayIndex());
}

void BranchMutations::writeGapInsertions()
{
  hal_size_t startPos, endPos;
  _top->copy(_rearrangement->getLeftBreakpoint());
  do {
    if (_top->hasParent() == false && _top->getLength() <= _maxGap)
    {
      startPos = _top->getStartPosition();
      endPos = _top->getEndPosition();
      assert(startPos < _start + _length && endPos >= _start);
      if (startPos < _start)
      {
        startPos = _start;
      }
      if (endPos >= _start + _length)
      {
        endPos = _start + _length - 1;
      }

      *_refStream << _sequence->getName() << '\t'
                  << startPos - _sequence->getStartPosition() << '\t'
                  << endPos + 1 - _sequence->getStartPosition() << '\t'
                  << gapInsertionBedTag << '\t'
                  << _parName << '\t' << _refName << '\n';
    }
    _top->toRight();
  }
  while (_top->getArrayIndex() <
         _rearrangement->getRightBreakpoint()->getArrayIndex());

}

void BranchMutations::writeDeletion()
{
  if (_parentStream == NULL)
  {
    return;
  }

  pair<hal_index_t, hal_index_t> pos = _rearrangement->getDeletedRange();
  assert((pos.second - pos.first) + 1 > (hal_index_t)_maxGap);
  const Sequence* seq = _reference->getParent()->getSequenceBySite(pos.first);
  assert(seq != NULL);

  *_parentStream << seq->getName() << '\t'
                 << pos.first - seq->getStartPosition() << '\t'
                 << pos.second + 1 - seq->getStartPosition() << '\t'
                 << deletionBedTag << '\t'
                 << _parName << '\t' << _refName << '\n';
}

void BranchMutations::writeGapDeletion()
{
  if (_parentStream == NULL)
  {
    return;
  }

  pair<hal_index_t, hal_index_t> pos = _rearrangement->getDeletedRange();
  if ((pos.second - pos.first) + 1 < (hal_index_t)_maxGap)
  {
    const Sequence* seq = _reference->getParent()->getSequenceBySite(pos.first);
    assert(seq != NULL);

    *_parentStream << seq->getName() << '\t'
                   << pos.first - seq->getStartPosition() << '\t'
                   << pos.second + 1 - seq->getStartPosition() << '\t'
                   << gapDeletionBedTag << '\t'
                   << _parName << '\t' << _refName << '\n';
  }
}

void BranchMutations::writeDuplication()
{
  if (_parentStream == NULL)
  {
    return;
  }
  pair<hal_index_t, hal_index_t> pos = _rearrangement->getDuplicatedRange();

  const Sequence* seq = _reference->getParent()->getSequenceBySite(pos.first);
  assert(seq != NULL);

  *_parentStream << seq->getName() << '\t'
                 << pos.first - seq->getStartPosition() << '\t'
                 << pos.second + 1 - seq->getStartPosition() << '\t'
                 << duplicationBedTag << '\t'
                 << _parName << '\t' << _refName << '\n';
}

void BranchMutations::writeHeaders()
{
  string header("#Sequence\tStart\tEnd\tMutationID\tParentGenome\tChildGenome\n"
                "#I=Insertion D=Deletion GI(D)=GapInsertion(GapDeletion) "
                "V=Inversion P=Transposition U=Duplication\n");
  if (_refStream->tellp() == streampos(0))
  {
    *_refStream << header;
  }
  if (_parentStream && _parentStream->tellp() == streampos(0))
  {
    *_parentStream << header;
  }
  if (_snpStream && _snpStream->tellp() == streampos(0))
  {
    *_snpStream << header;
  }

}
<commit_msg>fix range error in branch mutations<commit_after>/*
 * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)
 *
 * Released under the MIT license, see LICENSE.txt
 */

#include <deque>
#include <cassert>
#include <locale>
#include "halBranchMutations.h"

using namespace std;
using namespace hal;

const string BranchMutations::inversionBedTag = "V";
const string BranchMutations::insertionBedTag = "I";
const string BranchMutations::deletionBedTag = "D";
const string BranchMutations::transpositionBedTag = "P";
const string BranchMutations::duplicationBedTag = "U";
const string BranchMutations::gapInsertionBedTag = "GI";
const string BranchMutations::gapDeletionBedTag = "GD";
string BranchMutations::substitutionBedTag(char parent, char child)
{
  assert(parent == toupper(parent));
  assert(child == toupper(child));
  assert(isNucleotide(parent) && parent != 'N' &&
         isNucleotide(child) && child != 'N');
  return string("S_") + parent + child;
}

BranchMutations::BranchMutations()
{

}

BranchMutations::~BranchMutations()
{

}

void BranchMutations::analyzeBranch(AlignmentConstPtr alignment,
                                    hal_size_t gapThreshold,
                                    double nThreshold,
                                    ostream* refBedStream,
                                    ostream* parentBedStream,
                                    ostream* snpBedStream,
                                    const Genome* reference,
                                    hal_index_t startPosition,
                                    hal_size_t length)
{
  assert(reference != NULL);
  if (length == 0)
  {
    throw hal_exception("Cannot convert zero length sequence");
  }
  if (reference->getParent() == NULL)
  {
    throw hal_exception("Reference genome must have parent");
  }

  _reference = reference;
  _start = startPosition;
  _length = length;
  _alignment = alignment;
  _maxGap = gapThreshold;
  _nThreshold = nThreshold;
  _refStream = refBedStream;
  _parentStream = parentBedStream;
  _snpStream = snpBedStream;
  _refName = _reference->getName();
  _parName = _reference->getParent()->getName();

  writeHeaders();

  hal_index_t end = startPosition + (hal_index_t)length - 1;

  _top  = reference->getTopSegmentIterator();
  _top->toSite(startPosition);
  _bottom1 = reference->getParent()->getBottomSegmentIterator();
  _bottom2 = reference->getParent()->getBottomSegmentIterator();

  _rearrangement = reference->getRearrangement(_top->getArrayIndex(),
                                               _maxGap, _nThreshold);

  do {
    _sequence = _reference->getSequenceBySite(
      _rearrangement->getLeftBreakpoint()->getStartPosition());
    switch (_rearrangement->getID())
    {
    case Rearrangement::Deletion:
      writeDeletion();
      break;
    case Rearrangement::Inversion:
    case Rearrangement::Transposition:
    case Rearrangement::Insertion:
      writeInsertionOrInversion();
      break;
    case Rearrangement::Duplication:
      writeDuplication();
    default:
      break;
    }
    writeSubstitutions();
    writeGapInsertions();
  }
  while (_rearrangement->identifyNext() == true &&
         _rearrangement->getLeftBreakpoint()->getStartPosition() <= end);

  // kind of stupid, but we do a second pass to get the gapped deletions
  _top  = reference->getTopSegmentIterator();
  _top->toSite(startPosition);
  _rearrangement = reference->getRearrangement(_top->getArrayIndex(), 0,
                                               _nThreshold, true);
  do {
    switch (_rearrangement->getID())
    {
    case Rearrangement::Deletion:
      writeGapDeletion();
    default:
      break;
    }
  }
  while (_rearrangement->identifyNext() == true &&
         _rearrangement->getLeftBreakpoint()->getStartPosition() <= end);
}

void BranchMutations::writeInsertionOrInversion()
{
  assert(_refStream != NULL);
  hal_size_t startPos = _rearrangement->getLeftBreakpoint()->getStartPosition();
  hal_size_t endPos = _rearrangement->getRightBreakpoint()->getEndPosition();

  assert(startPos < _start + _length && endPos >= _start);

  if (startPos < _start)
  {
    startPos = _start;
  }
  if (endPos >= _start + _length)
  {
    endPos = _start + _length - 1;
  }

  *_refStream << _sequence->getName() << '\t'
              << startPos - _sequence->getStartPosition() << '\t'
              << endPos + 1 - _sequence->getStartPosition() << '\t';

  if (_rearrangement->getID() ==  Rearrangement::Inversion)
  {
    *_refStream << inversionBedTag << '\t';
  }
  else if (_rearrangement->getID() ==  Rearrangement::Insertion)
  {
    *_refStream << insertionBedTag << '\t';
  }
  else
  {
    assert(_rearrangement->getID() ==  Rearrangement::Transposition);
    *_refStream << transpositionBedTag << '\t';
  }

  *_refStream << _parName << '\t' << _refName << '\n';
}

void BranchMutations::writeSubstitutions()
{
  if (_snpStream == NULL)
  {
    return;
  }
  string tstring, bstring;
  hal_size_t pos;
  _top->copy(_rearrangement->getLeftBreakpoint());
  assert(_top->getReversed() == false);
  do {
    if (_top->hasParent())
    {
      _bottom1->toParent(_top);
      _top->getString(tstring);
      _bottom1->getString(bstring);
      assert(tstring.length() == bstring.length());

      for (hal_index_t i = 0; i < (hal_index_t)tstring.length(); ++i)
      {
        pos = i + _top->getStartPosition();
        char c = toupper(tstring[i]);
        char p = toupper(bstring[i]);

        if (pos >= _start && pos < _start + _length &&
            c != 'N' && p != 'N' && c != p)
        {
          *_snpStream << _sequence->getName() << '\t'
                      << pos - _sequence->getStartPosition() << '\t'
                      << pos + 1 - _sequence->getStartPosition() << '\t'
                      << substitutionBedTag(p, c) << '\t'
                      << _parName << '\t' << _refName<< '\n';
        }
      }
    }
    _top->toRight();
  }
  while (_top->getArrayIndex() <
         _rearrangement->getRightBreakpoint()->getArrayIndex());
}

void BranchMutations::writeGapInsertions()
{
  hal_size_t startPos, endPos;
  _top->copy(_rearrangement->getLeftBreakpoint());
  do {
    if (_top->hasParent() == false && _top->getLength() <= _maxGap)
    {
      startPos = _top->getStartPosition();
      endPos = _top->getEndPosition();

      if (startPos < _start)
      {
        startPos = _start;
      }
      if (endPos >= _start + _length)
      {
        endPos = _start + _length - 1;
      }
      if (startPos >= _start && endPos <= _start + _length - 1)
      {
        *_refStream << _sequence->getName() << '\t'
                    << startPos - _sequence->getStartPosition() << '\t'
                    << endPos + 1 - _sequence->getStartPosition() << '\t'
                    << gapInsertionBedTag << '\t'
                    << _parName << '\t' << _refName << '\n';
      }
    }
    _top->toRight();
  }
  while (_top->getArrayIndex() <
         _rearrangement->getRightBreakpoint()->getArrayIndex());

}

void BranchMutations::writeDeletion()
{
  if (_parentStream == NULL)
  {
    return;
  }

  pair<hal_index_t, hal_index_t> pos = _rearrangement->getDeletedRange();
  assert((pos.second - pos.first) + 1 > (hal_index_t)_maxGap);
  const Sequence* seq = _reference->getParent()->getSequenceBySite(pos.first);
  assert(seq != NULL);

  *_parentStream << seq->getName() << '\t'
                 << pos.first - seq->getStartPosition() << '\t'
                 << pos.second + 1 - seq->getStartPosition() << '\t'
                 << deletionBedTag << '\t'
                 << _parName << '\t' << _refName << '\n';
}

void BranchMutations::writeGapDeletion()
{
  if (_parentStream == NULL)
  {
    return;
  }

  pair<hal_index_t, hal_index_t> pos = _rearrangement->getDeletedRange();
  if ((pos.second - pos.first) + 1 < (hal_index_t)_maxGap)
  {
    const Sequence* seq = _reference->getParent()->getSequenceBySite(pos.first);
    assert(seq != NULL);

    *_parentStream << seq->getName() << '\t'
                   << pos.first - seq->getStartPosition() << '\t'
                   << pos.second + 1 - seq->getStartPosition() << '\t'
                   << gapDeletionBedTag << '\t'
                   << _parName << '\t' << _refName << '\n';
  }
}

void BranchMutations::writeDuplication()
{
  if (_parentStream == NULL)
  {
    return;
  }
  pair<hal_index_t, hal_index_t> pos = _rearrangement->getDuplicatedRange();

  const Sequence* seq = _reference->getParent()->getSequenceBySite(pos.first);
  assert(seq != NULL);

  *_parentStream << seq->getName() << '\t'
                 << pos.first - seq->getStartPosition() << '\t'
                 << pos.second + 1 - seq->getStartPosition() << '\t'
                 << duplicationBedTag << '\t'
                 << _parName << '\t' << _refName << '\n';
}

void BranchMutations::writeHeaders()
{
  string header("#Sequence\tStart\tEnd\tMutationID\tParentGenome\tChildGenome\n"
                "#I=Insertion D=Deletion GI(D)=GapInsertion(GapDeletion) "
                "V=Inversion P=Transposition U=Duplication\n");
  if (_refStream->tellp() == streampos(0))
  {
    *_refStream << header;
  }
  if (_parentStream && _parentStream->tellp() == streampos(0))
  {
    *_parentStream << header;
  }
  if (_snpStream && _snpStream->tellp() == streampos(0))
  {
    *_snpStream << header;
  }

}
<|endoftext|>


<commit_before>#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <cstdint>
#include <intrin.h>
#include <xmmintrin.h>
#include <pmmintrin.h>

typedef double Real;

#define AVX_ALIGN __declspec(align(32))

AVX_ALIGN class vec4 {
public:
  union {
    struct {
      Real x, y, z, w;
    };
    __m256d packed;
  };
  inline vec4()
  {
    packed = _mm256_setzero_pd();
  }
  inline vec4( const Real value )
  {
    packed = _mm256_broadcast_sd( &value );
  }
  inline vec4( __m256d& rhs ): packed( rhs )
  {
  }
  inline vec4( Real _x, Real _y, Real _z, Real _w )
  {
    packed = _mm256_setr_pd( _x, _y, _z, _w );
  }
  //! Load four 32-byte boundary aligned sample values into vector
  inline void load( const Real* values )
  {
    packed = _mm256_load_pd( values );
  }
  //! Load four unaligned sample values into vector
  inline void loadUnaligned( const Real* values )
  {
    packed = _mm256_loadu_pd( values );
  }
  //! Store four sample values from vector to 32-byte boundary aligned memory
  inline void store( Real* values )
  {
    _mm256_stream_pd( values, packed );
  }
  //! Store four sample values from vector to unaligned memory
  inline void storeUnaligned( Real* values )
  {
    _mm256_store_pd( values, packed );
  }
  //! Set all vector members to single value
  inline void set( const Real* value )
  {
    packed = _mm256_broadcast_sd( value );
  }
  //! Set vector members individually
  inline void set( Real _x, Real _y, Real _z, Real _w )
  {
    packed = _mm256_setr_pd( _x, _y, _z, _w );
  }
  //! v = a + b
  inline vec4 operator + ( const vec4& rhs ) const
  {
    return _mm256_add_pd( packed, rhs.packed );
  }
  //! v = a - b
  inline vec4 operator - ( const vec4& rhs ) const
  {
    return _mm256_sub_pd( packed, rhs.packed );
  }
  //! v = a & b (bitwise and)
  inline vec4 operator & ( const vec4& rhs ) const
  {
    return _mm256_and_pd( packed, rhs.packed );
  }
  //! v = a | b (bitwise or)
  inline vec4 operator | ( const vec4& rhs ) const
  {
    return _mm256_or_pd( packed, rhs.packed );
  }
  //! v = a ^ b (bitwise xor)
  inline vec4 operator ^ ( const vec4& rhs ) const
  {
    return _mm256_xor_pd( packed, rhs.packed );
  }
  //! v = a * b
  inline vec4 operator * ( const Real scalar ) const
  {
    auto im = _mm256_set1_pd( scalar );
    return _mm256_mul_pd( packed, im );
  }
  //! v = a * b
  inline vec4 operator * ( const vec4& rhs ) const
  {
    return _mm256_mul_pd( packed, rhs.packed );
  }
  //! v = a / b
  inline vec4 operator / ( const Real scalar ) const
  {
    auto im = _mm256_set1_pd( scalar );
    return _mm256_div_pd( packed, im );
  }
  //! v = a / b
  inline vec4 operator / ( const vec4& rhs ) const
  {
    return _mm256_div_pd( packed, rhs.packed );
  }
  //! a == b
  inline bool operator == ( const vec4& rhs ) const
  {
    auto ret = _mm256_cmp_pd( packed, rhs.packed, _CMP_NEQ_OS );
    return ( _mm256_movemask_pd( ret ) == 0 );
  }
  //! a != b
  inline bool operator != ( const vec4& rhs ) const
  {
    auto ret = _mm256_cmp_pd( packed, rhs.packed, _CMP_EQ_OS );
    return ( _mm256_movemask_pd( ret ) == 0 );
  }
  //! v = round(a)
  inline vec4 round() const
  {
    return _mm256_round_pd( packed, _MM_FROUND_NINT );
  }
  //! v = ceil(a)
  inline vec4 ceil() const
  {
    return _mm256_round_pd( packed, _MM_FROUND_CEIL );
  }
  //! v = floor(a)
  inline vec4 floor() const
  {
    return _mm256_round_pd( packed, _MM_FROUND_FLOOR );
  }
  //! v = trunc(a)
  inline vec4 trunc() const
  {
    return _mm256_round_pd( packed, _MM_FROUND_TRUNC );
  }
  //! v = sqrt(a)
  inline vec4 sqrt() const
  {
    return _mm256_sqrt_pd( packed );
  }
  //! f = x + y + z + w
  inline Real sum() const
  {
    auto hadd = _mm256_hadd_pd( packed, packed );
    auto hi = _mm256_extractf128_pd( hadd, 1 );
    auto lo = _mm256_castpd256_pd128( hadd );
    auto ret = _mm_add_sd( lo, hi );
    return _mm_cvtsd_f64( ret );
  }
  //! v = a * b + c (fused multiply & add)
  static inline vec4 fma( const vec4& a, const vec4& b, const vec4& c )
  {
    return _mm256_fmadd_pd( a.packed, b.packed, c.packed );
  }
  //! v = a * b - c (fused multiply & subtract)
  static inline vec4 fms( const vec4& a, const vec4& b, const vec4& c )
  {
    return _mm256_fmsub_pd( a.packed, b.packed, c.packed );
  }
};

class Complex {
public:
  Real real;
  Real imaginary;
public:
  inline Complex(): real( 0.0 ), imaginary( 0.0 )
  {
  }
  inline Complex( const Real real_, const Real imaginary_ = 0.0 ) :
  real( real_ ), imaginary( imaginary_ )
  {
  }
  //! equality
  inline bool operator == ( const Complex& rhs ) const
  {
    return ( real == rhs.real && imaginary == rhs.imaginary );
  }
  //! addition
  inline Complex operator + ( const Complex& rhs ) const
  {
    return Complex( real + rhs.real, imaginary + rhs.imaginary );
  }
  //! subtraction
  inline Complex operator - ( const Complex& rhs ) const
  {
    return Complex( real - rhs.real, imaginary - rhs.imaginary );
  }
  //! multiplication
  inline Complex operator * ( const Complex& rhs ) const
  {
    auto rr = ( ( real * rhs.real ) - ( imaginary * rhs.imaginary ) );
    auto ir = ( ( imaginary * rhs.real ) + ( real * rhs.imaginary ) );
    return Complex( rr, ir );
  }
  //! division
  inline Complex operator / ( const Complex& rhs ) const
  {
    auto tmp = ( rhs.real * rhs.real + rhs.imaginary * rhs.imaginary );
    auto rr = ( ( real * rhs.real + imaginary * rhs.imaginary ) / tmp );
    auto ir = ( ( imaginary * rhs.real - real * rhs.imaginary ) / tmp );
    return Complex( rr, ir );
  }
  //! negation (unary minus)
  inline Complex operator - () const
  {
    return Complex( -real, -imaginary );
  }
};

int main( int argc, char** argv, char** env )
{
  printf( "playground\n" );

  vec4 a( 1, 2, 3, 4 );
  vec4 b( 5, 6, 7, 8 );
  vec4 c = a + b;
  vec4 d;

  printf( "a: %f %f %f %f\n", a.x, a.y, a.z, a.w );
  printf( "b: %f %f %f %f\n", b.x, b.y, b.z, b.w );
  printf( "c: %f %f %f %f\n", c.x, c.y, c.z, c.w );
  printf( "d: %f %f %f %f\n", d.x, d.y, d.z, d.w );

  vec4 e( 1, 0, 3.31, -4 );
  vec4 f( 1, -0.0, 3.31, -4.000 );

  printf( "comparison = %s\n", e == f ? "true" : "false" );

  return EXIT_SUCCESS;
}<commit_msg>Add magnitude, abs & arg for Complex<commit_after>#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <cstdint>
#include <intrin.h>
#include <xmmintrin.h>
#include <pmmintrin.h>
#include <math.h>

typedef double Real;

#define AVX_ALIGN __declspec(align(32))

AVX_ALIGN class vec4 {
public:
  union {
    struct {
      Real x, y, z, w;
    };
    __m256d packed;
  };
  inline vec4()
  {
    packed = _mm256_setzero_pd();
  }
  inline vec4( const Real value )
  {
    packed = _mm256_broadcast_sd( &value );
  }
  inline vec4( __m256d& rhs ): packed( rhs )
  {
  }
  inline vec4( Real _x, Real _y, Real _z, Real _w )
  {
    packed = _mm256_setr_pd( _x, _y, _z, _w );
  }
  //! Load four 32-byte boundary aligned sample values into vector
  inline void load( const Real* values )
  {
    packed = _mm256_load_pd( values );
  }
  //! Load four unaligned sample values into vector
  inline void loadUnaligned( const Real* values )
  {
    packed = _mm256_loadu_pd( values );
  }
  //! Store four sample values from vector to 32-byte boundary aligned memory
  inline void store( Real* values )
  {
    _mm256_stream_pd( values, packed );
  }
  //! Store four sample values from vector to unaligned memory
  inline void storeUnaligned( Real* values )
  {
    _mm256_store_pd( values, packed );
  }
  //! Set all vector members to single value
  inline void set( const Real* value )
  {
    packed = _mm256_broadcast_sd( value );
  }
  //! Set vector members individually
  inline void set( Real _x, Real _y, Real _z, Real _w )
  {
    packed = _mm256_setr_pd( _x, _y, _z, _w );
  }
  //! v = a + b
  inline vec4 operator + ( const vec4& rhs ) const
  {
    return _mm256_add_pd( packed, rhs.packed );
  }
  //! v = a - b
  inline vec4 operator - ( const vec4& rhs ) const
  {
    return _mm256_sub_pd( packed, rhs.packed );
  }
  //! v = a & b (bitwise and)
  inline vec4 operator & ( const vec4& rhs ) const
  {
    return _mm256_and_pd( packed, rhs.packed );
  }
  //! v = a | b (bitwise or)
  inline vec4 operator | ( const vec4& rhs ) const
  {
    return _mm256_or_pd( packed, rhs.packed );
  }
  //! v = a ^ b (bitwise xor)
  inline vec4 operator ^ ( const vec4& rhs ) const
  {
    return _mm256_xor_pd( packed, rhs.packed );
  }
  //! v = a * b
  inline vec4 operator * ( const Real scalar ) const
  {
    auto im = _mm256_set1_pd( scalar );
    return _mm256_mul_pd( packed, im );
  }
  //! v = a * b
  inline vec4 operator * ( const vec4& rhs ) const
  {
    return _mm256_mul_pd( packed, rhs.packed );
  }
  //! v = a / b
  inline vec4 operator / ( const Real scalar ) const
  {
    auto im = _mm256_set1_pd( scalar );
    return _mm256_div_pd( packed, im );
  }
  //! v = a / b
  inline vec4 operator / ( const vec4& rhs ) const
  {
    return _mm256_div_pd( packed, rhs.packed );
  }
  //! a == b
  inline bool operator == ( const vec4& rhs ) const
  {
    auto ret = _mm256_cmp_pd( packed, rhs.packed, _CMP_NEQ_OS );
    return ( _mm256_movemask_pd( ret ) == 0 );
  }
  //! a != b
  inline bool operator != ( const vec4& rhs ) const
  {
    auto ret = _mm256_cmp_pd( packed, rhs.packed, _CMP_EQ_OS );
    return ( _mm256_movemask_pd( ret ) == 0 );
  }
  //! v = round(a)
  inline vec4 round() const
  {
    return _mm256_round_pd( packed, _MM_FROUND_NINT );
  }
  //! v = ceil(a)
  inline vec4 ceil() const
  {
    return _mm256_round_pd( packed, _MM_FROUND_CEIL );
  }
  //! v = floor(a)
  inline vec4 floor() const
  {
    return _mm256_round_pd( packed, _MM_FROUND_FLOOR );
  }
  //! v = trunc(a)
  inline vec4 trunc() const
  {
    return _mm256_round_pd( packed, _MM_FROUND_TRUNC );
  }
  //! v = sqrt(a)
  inline vec4 sqrt() const
  {
    return _mm256_sqrt_pd( packed );
  }
  //! f = x + y + z + w
  inline Real sum() const
  {
    auto hadd = _mm256_hadd_pd( packed, packed );
    auto hi = _mm256_extractf128_pd( hadd, 1 );
    auto lo = _mm256_castpd256_pd128( hadd );
    auto ret = _mm_add_sd( lo, hi );
    return _mm_cvtsd_f64( ret );
  }
  //! v = a * b + c (fused multiply & add)
  static inline vec4 fma( const vec4& a, const vec4& b, const vec4& c )
  {
    return _mm256_fmadd_pd( a.packed, b.packed, c.packed );
  }
  //! v = a * b - c (fused multiply & subtract)
  static inline vec4 fms( const vec4& a, const vec4& b, const vec4& c )
  {
    return _mm256_fmsub_pd( a.packed, b.packed, c.packed );
  }
};

class Complex {
public:
  Real real;
  Real imaginary;
public:
  inline Complex(): real( 0.0 ), imaginary( 0.0 )
  {
  }
  inline Complex( const Real real_, const Real imaginary_ = 0.0 ) :
  real( real_ ), imaginary( imaginary_ )
  {
  }
  //! equality
  inline bool operator == ( const Complex& rhs ) const
  {
    return ( real == rhs.real && imaginary == rhs.imaginary );
  }
  //! addition
  inline Complex operator + ( const Complex& rhs ) const
  {
    return Complex( real + rhs.real, imaginary + rhs.imaginary );
  }
  //! subtraction
  inline Complex operator - ( const Complex& rhs ) const
  {
    return Complex( real - rhs.real, imaginary - rhs.imaginary );
  }
  //! multiplication
  inline Complex operator * ( const Complex& rhs ) const
  {
    auto rr = ( ( real * rhs.real ) - ( imaginary * rhs.imaginary ) );
    auto ir = ( ( imaginary * rhs.real ) + ( real * rhs.imaginary ) );
    return Complex( rr, ir );
  }
  //! division
  inline Complex operator / ( const Complex& rhs ) const
  {
    auto tmp = ( rhs.real * rhs.real + rhs.imaginary * rhs.imaginary );
    auto rr = ( ( real * rhs.real + imaginary * rhs.imaginary ) / tmp );
    auto ir = ( ( imaginary * rhs.real - real * rhs.imaginary ) / tmp );
    return Complex( rr, ir );
  }
  //! negation (unary minus)
  inline Complex operator - () const
  {
    return Complex( -real, -imaginary );
  }
  //! magnitude
  inline Real magnitude() const
  {
    return ( real * real + imaginary * imaginary );
  }
  //! absolute (magnitude)
  inline Real abs() const
  {
    return sqrt( magnitude() );
  }
  inline Real arg() const
  {
    return atan2( real, imaginary );
  }
};

int main( int argc, char** argv, char** env )
{
  printf( "playground\n" );

  vec4 a( 1, 2, 3, 4 );
  vec4 b( 5, 6, 7, 8 );
  vec4 c = a + b;
  vec4 d;

  printf( "a: %f %f %f %f\n", a.x, a.y, a.z, a.w );
  printf( "b: %f %f %f %f\n", b.x, b.y, b.z, b.w );
  printf( "c: %f %f %f %f\n", c.x, c.y, c.z, c.w );
  printf( "d: %f %f %f %f\n", d.x, d.y, d.z, d.w );

  vec4 e( 1, 0, 3.31, -4 );
  vec4 f( 1, -0.0, 3.31, -4.000 );

  printf( "comparison = %s\n", e == f ? "true" : "false" );

  return EXIT_SUCCESS;
}<|endoftext|>