<commit_before>#include "View.h"

using namespace std;

static View NullView = View(0,0);
static Cluster<double> NullCluster = Cluster<double>(0);

View::View(int NUM_COLS, double CRP_ALPHA) {
  num_cols = NUM_COLS;
  crp_alpha = CRP_ALPHA;
  num_vectors = 0;
}

void View::print() {
  std::set<Cluster<double>*>::iterator it = clusters.begin();
  for(; it!=clusters.end(); it++) {
    std::cout << **it << std::endl;
  }
}

double View::get_score() const {
  return score;
}

double View::get_num_vectors() const {
  return num_vectors;
}

double View::get_num_cols() const {
  return num_cols;
}

Cluster<double>& View::get_new_cluster() {
  Cluster<double> *p_new_cluster = new Cluster<double>(num_cols);
  clusters.insert(p_new_cluster);
  return *p_new_cluster;
}

Cluster<double>& View::get_cluster(int cluster_idx) {
  assert(cluster_idx <= clusters.size());
  bool not_new = cluster_idx < clusters.size();
  if(not_new) {
    std::set<Cluster<double>*>::iterator it = clusters.begin();
    std::advance(it, cluster_idx);
    return **it;
  } else {
    return get_new_cluster();
  }
}

double View::calc_cluster_vector_logp(std::vector<double> vd, Cluster<double> which_cluster) const {
  int cluster_count = which_cluster.get_count();
  double crp_logp_delta, data_logp_delta, score_delta;
  // NOTE: non-mutating, so presume vector is not in state
  // so use num_vectors, not num_vectors - 1
  // should try to cache counts in some way
  crp_logp_delta = numerics::calc_cluster_crp_logp(cluster_count,
						   num_vectors,
						   crp_alpha);
  data_logp_delta = which_cluster.calc_data_logp(vd);
  score_delta = crp_logp_delta + data_logp_delta;
  return score_delta;
}

std::vector<double> View::calc_cluster_vector_logps(std::vector<double> vd) const {
  std::vector<double> logps;
  std::set<Cluster<double>*>::iterator it = clusters.begin();
  for(; it!=clusters.end(); it++) {
    logps.push_back(calc_cluster_vector_logp(vd, **it));
  }
  Cluster<double> empty_cluster(num_cols);
  logps.push_back(calc_cluster_vector_logp(vd, empty_cluster));
  return logps;
}

double View::draw_rand_u() {
  rng.next();
}

int View::draw_rand_i(int max) {
  return rng.nexti(max);
}

void View::transition_z(std::vector<double> vd, int row_idx) {
  std::vector<double> unorm_logps = calc_cluster_vector_logps(vd);
  double rand_u = draw_rand_u();
  int draw = numerics::draw_sample_unnormalized(unorm_logps, rand_u);
  Cluster<double> &which_cluster = get_cluster(draw);
  insert_row(vd, which_cluster, row_idx);
}

std::vector<int> View::shuffle_row_indices() {
  std::vector<int> original_order;
  map<int, Cluster<double>*>::iterator it = cluster_lookup.begin();
  for(; it!=cluster_lookup.end(); it++) {
    original_order.push_back(it->first);
  }
  std::vector<int> shuffled_order;
  while(original_order.size()!=0) {
    int draw = draw_rand_i(original_order.size());
    int row_idx = original_order[draw];
    shuffled_order.push_back(row_idx);
    original_order.erase(original_order.begin() + draw);
  }
  return shuffled_order;
}

void View::transition_zs(map<int, vector<double> > row_data_map) {
  vector<int> shuffled_row_indices = shuffle_row_indices();
  std::cout << "shuffled_row_indices: " << shuffled_row_indices << endl;
  vector<int>::iterator it = shuffled_row_indices.begin();
  for(; it!=shuffled_row_indices.end(); it++) {
    int row_idx = *it;
    vector<double> vd = row_data_map[row_idx];
    cout << "shuffling row: " << row_idx << " :: " << vd << endl;
    remove_row(vd, row_idx);
    transition_z(vd, row_idx);
  }
}

double View::insert_row(std::vector<double> vd, Cluster<double>& which_cluster, int row_idx) {
  double score_delta = calc_cluster_vector_logp(vd, which_cluster);
  which_cluster.insert_row(vd, row_idx);
  cluster_lookup[row_idx] = &which_cluster;
  score += score_delta;
  num_vectors += 1;
  return score_delta;
}

void View::remove_if_empty(Cluster<double>& which_cluster) {
  if(which_cluster.get_count()==0) {
    clusters.erase(clusters.find(&which_cluster));
    delete &which_cluster;
  }
}

double View::remove_row(std::vector<double> vd, int row_idx) {
  Cluster<double> &which_cluster = *(cluster_lookup[row_idx]);
  cluster_lookup.erase(cluster_lookup.find(row_idx));
  which_cluster.remove_row(vd, row_idx);
  num_vectors -= 1;
  double score_delta = calc_cluster_vector_logp(vd, which_cluster);
  remove_if_empty(which_cluster);
  score -= score_delta;
  return score_delta;
}

std::vector<int> View::get_cluster_counts() const {
  std::vector<int> counts;
  std::set<Cluster<double>*>::const_iterator it = clusters.begin();
  for(; it!=clusters.end(); it++) {
    int count = (**it).get_count();
    counts.push_back(count);
  }
  return counts;
}

double View::get_crp_score() const {
  std::vector<int> cluster_counts = get_cluster_counts();
  return numerics::calc_crp_alpha_conditional(cluster_counts, crp_alpha, -1, true);
}
<commit_msg>move remove_row operation to transition_z from transition_zs "transition" suggests its still in the model<commit_after>#include "View.h"

using namespace std;

static View NullView = View(0,0);
static Cluster<double> NullCluster = Cluster<double>(0);

View::View(int NUM_COLS, double CRP_ALPHA) {
  num_cols = NUM_COLS;
  crp_alpha = CRP_ALPHA;
  num_vectors = 0;
}

void View::print() {
  std::set<Cluster<double>*>::iterator it = clusters.begin();
  for(; it!=clusters.end(); it++) {
    std::cout << **it << std::endl;
  }
}

double View::get_score() const {
  return score;
}

double View::get_num_vectors() const {
  return num_vectors;
}

double View::get_num_cols() const {
  return num_cols;
}

Cluster<double>& View::get_new_cluster() {
  Cluster<double> *p_new_cluster = new Cluster<double>(num_cols);
  clusters.insert(p_new_cluster);
  return *p_new_cluster;
}

Cluster<double>& View::get_cluster(int cluster_idx) {
  assert(cluster_idx <= clusters.size());
  bool not_new = cluster_idx < clusters.size();
  if(not_new) {
    std::set<Cluster<double>*>::iterator it = clusters.begin();
    std::advance(it, cluster_idx);
    return **it;
  } else {
    return get_new_cluster();
  }
}

double View::calc_cluster_vector_logp(std::vector<double> vd, Cluster<double> which_cluster) const {
  int cluster_count = which_cluster.get_count();
  double crp_logp_delta, data_logp_delta, score_delta;
  // NOTE: non-mutating, so presume vector is not in state
  // so use num_vectors, not num_vectors - 1
  // should try to cache counts in some way
  crp_logp_delta = numerics::calc_cluster_crp_logp(cluster_count,
						   num_vectors,
						   crp_alpha);
  data_logp_delta = which_cluster.calc_data_logp(vd);
  score_delta = crp_logp_delta + data_logp_delta;
  return score_delta;
}

std::vector<double> View::calc_cluster_vector_logps(std::vector<double> vd) const {
  std::vector<double> logps;
  std::set<Cluster<double>*>::iterator it = clusters.begin();
  for(; it!=clusters.end(); it++) {
    logps.push_back(calc_cluster_vector_logp(vd, **it));
  }
  Cluster<double> empty_cluster(num_cols);
  logps.push_back(calc_cluster_vector_logp(vd, empty_cluster));
  return logps;
}

double View::draw_rand_u() {
  rng.next();
}

int View::draw_rand_i(int max) {
  return rng.nexti(max);
}

void View::transition_z(std::vector<double> vd, int row_idx) {
  remove_row(vd, row_idx);
  std::vector<double> unorm_logps = calc_cluster_vector_logps(vd);
  double rand_u = draw_rand_u();
  int draw = numerics::draw_sample_unnormalized(unorm_logps, rand_u);
  Cluster<double> &which_cluster = get_cluster(draw);
  insert_row(vd, which_cluster, row_idx);
}

std::vector<int> View::shuffle_row_indices() {
  std::vector<int> original_order;
  map<int, Cluster<double>*>::iterator it = cluster_lookup.begin();
  for(; it!=cluster_lookup.end(); it++) {
    original_order.push_back(it->first);
  }
  std::vector<int> shuffled_order;
  while(original_order.size()!=0) {
    int draw = draw_rand_i(original_order.size());
    int row_idx = original_order[draw];
    shuffled_order.push_back(row_idx);
    original_order.erase(original_order.begin() + draw);
  }
  return shuffled_order;
}

void View::transition_zs(map<int, vector<double> > row_data_map) {
  vector<int> shuffled_row_indices = shuffle_row_indices();
  std::cout << "shuffled_row_indices: " << shuffled_row_indices << endl;
  vector<int>::iterator it = shuffled_row_indices.begin();
  for(; it!=shuffled_row_indices.end(); it++) {
    int row_idx = *it;
    vector<double> vd = row_data_map[row_idx];
    cout << "shuffling row: " << row_idx << " :: " << vd << endl;
    transition_z(vd, row_idx);
  }
}

double View::insert_row(std::vector<double> vd, Cluster<double>& which_cluster, int row_idx) {
  double score_delta = calc_cluster_vector_logp(vd, which_cluster);
  which_cluster.insert_row(vd, row_idx);
  cluster_lookup[row_idx] = &which_cluster;
  score += score_delta;
  num_vectors += 1;
  return score_delta;
}

void View::remove_if_empty(Cluster<double>& which_cluster) {
  if(which_cluster.get_count()==0) {
    clusters.erase(clusters.find(&which_cluster));
    delete &which_cluster;
  }
}

double View::remove_row(std::vector<double> vd, int row_idx) {
  Cluster<double> &which_cluster = *(cluster_lookup[row_idx]);
  cluster_lookup.erase(cluster_lookup.find(row_idx));
  which_cluster.remove_row(vd, row_idx);
  num_vectors -= 1;
  double score_delta = calc_cluster_vector_logp(vd, which_cluster);
  remove_if_empty(which_cluster);
  score -= score_delta;
  return score_delta;
}

std::vector<int> View::get_cluster_counts() const {
  std::vector<int> counts;
  std::set<Cluster<double>*>::const_iterator it = clusters.begin();
  for(; it!=clusters.end(); it++) {
    int count = (**it).get_count();
    counts.push_back(count);
  }
  return counts;
}

double View::get_crp_score() const {
  std::vector<int> cluster_counts = get_cluster_counts();
  return numerics::calc_crp_alpha_conditional(cluster_counts, crp_alpha, -1, true);
}
<|endoftext|>


<commit_before>/*
  Copyright (c) 2013, Randolph Voorhies, Shane Grant
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
      * Neither the name of cereal nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES AND SHANE GRANT BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <cereal/cereal.hpp>
#include <cereal/archives/binary.hpp>
#include <cereal/archives/json.hpp>

#include <cereal/types/string.hpp>
#include <cereal/types/utility.hpp>
#include <cereal/types/memory.hpp>
#include <cereal/types/complex.hpp>
#include <cereal/types/base_class.hpp>
#include <cereal/types/array.hpp>
#include <cereal/types/vector.hpp>
#include <cereal/types/map.hpp>

#include <cereal/external/rapidjson/filestream.h>

#include <sstream>
#include <fstream>
#include <cassert>
#include <complex>
#include <iostream>
#include <iomanip>
#include <string>

// ###################################
struct Test1
{
  int a;

  private:
    friend class cereal::access;
    template<class Archive>
    void serialize(Archive & ar)
    {
      ar(CEREAL_NVP(a));
    }
};

// ###################################
class Test2
{
  public:
    Test2() {}
    Test2( int x ) : a( x ) {}
    int a;

  private:
    friend class cereal::access;

    template<class Archive>
      void save(Archive & ar) const
      {
        ar(a);
      }

    template<class Archive>
      void load(Archive & ar)
      {
        ar(a);
      }
};

// ###################################
struct Test3
{
  int a;
};

template<class Archive>
void serialize(Archive & ar, Test3 & t)
{
  ar(CEREAL_NVP(t.a));
}

namespace test4
{
  // ###################################
  struct Test4
  {
    int a;
  };

  template<class Archive>
  void save(Archive & ar, Test4 const & t)
  {
    ar(CEREAL_NVP(t.a));
  }

  template<class Archive>
  void load(Archive & ar, Test4 & t)
  {
    ar(CEREAL_NVP(t.a));
  }
}

class Private
{
  public:
    Private() : a('z') {}

  private:
    char a;

    friend class cereal::access;

    template<class Archive>
      void serialize(Archive & ar)
      {
        ar(a);
      }
};

struct Everything
{
  int x;
  int y;
  Test1 t1;
  Test2 t2;
  Test3 t3;
  test4::Test4 t4;
  std::string s;

  template<class Archive>
  void serialize(Archive & ar)
  {
    ar(CEREAL_NVP(x));
    ar(CEREAL_NVP(y));
    ar(CEREAL_NVP(t1));
    ar(CEREAL_NVP(t2));
    ar(CEREAL_NVP(t3));
    ar(CEREAL_NVP(t4));
    ar(CEREAL_NVP(s));
  }

  bool operator==(Everything const & o)
  {
    return
      x == o.x &&
      y == o.y &&
      t1.a == o.t1.a &&
      t2.a == o.t2.a &&
      t3.a == o.t3.a &&
      t4.a == o.t4.a &&
      s == o.s;
  }
};

struct SubFixture
{
  SubFixture() : a( 3 ),
    b( 9999 ),
    c( 100.1f ),
    d( 2000.9 ),
    s( "hello, world!" )
  {}

  int a;
  uint64_t b;
  float c;
  double d;
  std::string s;

    template<class Archive>
      void serialize(Archive & ar)
      {
        ar( CEREAL_NVP(a),
            b,
            c,
            CEREAL_NVP(d),
            CEREAL_NVP(s) );
      }
    void change()
    {
      a = 4;
      b = 4;
      c = 4;
      d = 4;
      s = "4";
    }
};

struct Fixture
{
  SubFixture f1, f2, f3;
  int array[4];

  Fixture()
  {
    array[0] = 1;
    array[1] = 2;
    array[2] = 3;
    array[3] = 4;
  }

  template<class Archive>
  void save(Archive & ar) const
  {
    ar( f1,
        CEREAL_NVP(f2),
        f3 );
    ar.saveBinaryValue( array, sizeof(int)*4, "cool array man" );
  }

  template<class Archive>
  void load(Archive & ar)
  {
    ar( f1,
        CEREAL_NVP(f2),
        f3 );
    ar.loadBinaryValue( array, sizeof(int)*4 );
  }

    void change()
    {
      f1.change();
      f2.change();
      f3.change();
    }
};

struct AAA
{
  AAA() : one( 1 ), two( 2 ), three( { {1, 2, 3}, { 4, 5, 6 }, {} } ) {}
  int one, two;

  std::vector<std::vector<int>> three;

  template<class Archive>
    void serialize(Archive & ar)
    {
      ar( CEREAL_NVP(one), CEREAL_NVP(two) );
      //ar( CEREAL_NVP(three) );
    }
};

class Stuff
{
  public:
    Stuff() {}

    void fillData()
    {
      std::vector<std::complex<float>> t1{ {0, -1.0f},
                          { 0, -2.9932f },
                          { 0, -3.5f } };
      std::vector<std::complex<float>> t2{ {1.0f, 0},
                     { 2.2f, 0 },
                     { 3.3f, 0 } };
      data["imaginary"] = t1;
      data["real"] = t2;
    }

  private:
    std::map<std::string, std::vector<std::complex<float>>> data;

    friend class cereal::access;

    template <class Archive>
    void serialize( Archive & ar )
    {
      ar( CEREAL_NVP(data) );
    }
};

struct OOJson
{
  OOJson() = default;
  OOJson( int aa, int bb, bool cc, double dd ) :
    a( aa ), b( bb ), c{ cc, dd }
  {
    d[0] = 0; d[1] = 1; d[2] = 2;
  }

  int a;
  int b;
  std::pair<bool, double> c;
  float d[3];

  template <class Archive>
  void serialize( Archive & ar )
  {
    ar( CEREAL_NVP(c) );
    ar( CEREAL_NVP(a) );
    ar( b );
    ar( CEREAL_NVP(d) );
  }
};

// ######################################################################
int main()
{
  std::cout << std::boolalpha << std::endl;

  {
    std::ofstream os("file.json");
    cereal::JSONOutputArchive oar( os, 5 );

    //auto f = std::make_shared<Fixture>();
    //auto f2 = f;
    //oar( f );
    //oar( f2 );
    Stuff s; s.fillData();
    oar( cereal::make_nvp("best data ever", s) );
  }

  {
    std::ifstream is("file.json");
    std::string str((std::istreambuf_iterator<char>(is)), std::istreambuf_iterator<char>());
    std::cout << "---------------------" << std::endl << str << std::endl << "---------------------" << std::endl;
  }

  {
    cereal::JSONOutputArchive archive( std::cout );
    bool arr[] = {true, false};
    std::vector<int> vec = {1, 2, 3, 4, 5};
    archive( CEREAL_NVP(vec),
        arr );
    auto f = std::make_shared<Fixture>();
    auto f2 = f;
    archive( f );
    archive( f2 );

    enum Bla
    {
      x,
      y
    };

    archive( Bla::x );
  }

  // test out of order
  std::stringstream oos;
  {
    cereal::JSONOutputArchive ar(oos);
    cereal::JSONOutputArchive ar2(std::cout);

    ar( cereal::make_nvp( "1", 1 ),
        cereal::make_nvp( "2", 2 ),
        3,
        0, // unused
        cereal::make_nvp( "4", 4 ),
        cereal::make_nvp( "5", 5 ) );

    int x = 33;
    ar.saveBinaryValue( &x, sizeof(int), "bla" );

    ar2( cereal::make_nvp( "1", 1 ),
         cereal::make_nvp( "2", 2 ),
         3,
         0, // unused
         cereal::make_nvp( "4", 4 ),
         cereal::make_nvp( "5", 5 ) );
    ar2.saveBinaryValue( &x, sizeof(int), "bla" );

    OOJson oo( 1, 2, 3, 4 );
    ar( CEREAL_NVP(oo) );
    ar2( CEREAL_NVP(oo) );

    // boost stuff
    ar & cereal::make_nvp("usingop&", oo ) & 5;
    ar << 5 << 4 << 3;

    ar2 & cereal::make_nvp("usingop&", oo ) & 5;
    ar2 << 5 << 4 << 3;
  }

  {
    cereal::JSONInputArchive ar(oos);
    int i1, i2, i3, i4, i5, x;

    ar( i1 );
    ar( cereal::make_nvp( "2", i2 ), i3 );

    ar( cereal::make_nvp( "4", i4 ),
        i5 );

    ar.loadBinaryValue( &x, sizeof(int) );

    OOJson ii;
    ar( cereal::make_nvp("oo", ii) );
    ar( cereal::make_nvp( "2", i2 ) );

    std::cout << i1 << " " << i2 << " " << i3 << " " << i4 << " " << i5 << std::endl;
    std::cout << x << std::endl;
    std::cout << ii.a << " " << ii.b << " " << ii.c.first << " " << ii.c.second << " ";
    for( auto z : ii.d )
      std::cout << z << " ";
    std::cout << std::endl;

  }

  //{
  //  std::ifstream is("file.json");
  //  cereal::JSONInputArchive iar( is );

  //  std::shared_ptr<Fixture> f, f2;
  //  iar( f, f2 );
  //  assert( f->array[0] == 1 );
  //  assert( f->array[1] == 2 );
  //  assert( f->array[2] == 3 );
  //  assert( f->array[3] == 4 );
  //}

  return 0;
}
<commit_msg>testing boost ops<commit_after>/*
  Copyright (c) 2013, Randolph Voorhies, Shane Grant
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
      * Neither the name of cereal nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES AND SHANE GRANT BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <cereal/cereal.hpp>
#include <cereal/archives/binary.hpp>
#include <cereal/archives/json.hpp>

#include <cereal/types/string.hpp>
#include <cereal/types/utility.hpp>
#include <cereal/types/memory.hpp>
#include <cereal/types/complex.hpp>
#include <cereal/types/base_class.hpp>
#include <cereal/types/array.hpp>
#include <cereal/types/vector.hpp>
#include <cereal/types/map.hpp>

#include <cereal/external/rapidjson/filestream.h>

#include <sstream>
#include <fstream>
#include <cassert>
#include <complex>
#include <iostream>
#include <iomanip>
#include <string>

// ###################################
struct Test1
{
  int a;

  private:
    friend class cereal::access;
    template<class Archive>
    void serialize(Archive & ar)
    {
      ar(CEREAL_NVP(a));
    }
};

// ###################################
class Test2
{
  public:
    Test2() {}
    Test2( int x ) : a( x ) {}
    int a;

  private:
    friend class cereal::access;

    template<class Archive>
      void save(Archive & ar) const
      {
        ar(a);
      }

    template<class Archive>
      void load(Archive & ar)
      {
        ar(a);
      }
};

// ###################################
struct Test3
{
  int a;
};

template<class Archive>
void serialize(Archive & ar, Test3 & t)
{
  ar(CEREAL_NVP(t.a));
}

namespace test4
{
  // ###################################
  struct Test4
  {
    int a;
  };

  template<class Archive>
  void save(Archive & ar, Test4 const & t)
  {
    ar(CEREAL_NVP(t.a));
  }

  template<class Archive>
  void load(Archive & ar, Test4 & t)
  {
    ar(CEREAL_NVP(t.a));
  }
}

class Private
{
  public:
    Private() : a('z') {}

  private:
    char a;

    friend class cereal::access;

    template<class Archive>
      void serialize(Archive & ar)
      {
        ar(a);
      }
};

struct Everything
{
  int x;
  int y;
  Test1 t1;
  Test2 t2;
  Test3 t3;
  test4::Test4 t4;
  std::string s;

  template<class Archive>
  void serialize(Archive & ar)
  {
    ar(CEREAL_NVP(x));
    ar(CEREAL_NVP(y));
    ar(CEREAL_NVP(t1));
    ar(CEREAL_NVP(t2));
    ar(CEREAL_NVP(t3));
    ar(CEREAL_NVP(t4));
    ar(CEREAL_NVP(s));
  }

  bool operator==(Everything const & o)
  {
    return
      x == o.x &&
      y == o.y &&
      t1.a == o.t1.a &&
      t2.a == o.t2.a &&
      t3.a == o.t3.a &&
      t4.a == o.t4.a &&
      s == o.s;
  }
};

struct SubFixture
{
  SubFixture() : a( 3 ),
    b( 9999 ),
    c( 100.1f ),
    d( 2000.9 ),
    s( "hello, world!" )
  {}

  int a;
  uint64_t b;
  float c;
  double d;
  std::string s;

    template<class Archive>
      void serialize(Archive & ar)
      {
        ar( CEREAL_NVP(a),
            b,
            c,
            CEREAL_NVP(d),
            CEREAL_NVP(s) );
      }
    void change()
    {
      a = 4;
      b = 4;
      c = 4;
      d = 4;
      s = "4";
    }
};

struct Fixture
{
  SubFixture f1, f2, f3;
  int array[4];

  Fixture()
  {
    array[0] = 1;
    array[1] = 2;
    array[2] = 3;
    array[3] = 4;
  }

  template<class Archive>
  void save(Archive & ar) const
  {
    ar( f1,
        CEREAL_NVP(f2),
        f3 );
    ar.saveBinaryValue( array, sizeof(int)*4, "cool array man" );
  }

  template<class Archive>
  void load(Archive & ar)
  {
    ar( f1,
        CEREAL_NVP(f2),
        f3 );
    ar.loadBinaryValue( array, sizeof(int)*4 );
  }

    void change()
    {
      f1.change();
      f2.change();
      f3.change();
    }
};

struct AAA
{
  AAA() : one( 1 ), two( 2 ), three( { {1, 2, 3}, { 4, 5, 6 }, {} } ) {}
  int one, two;

  std::vector<std::vector<int>> three;

  template<class Archive>
    void serialize(Archive & ar)
    {
      ar( CEREAL_NVP(one), CEREAL_NVP(two) );
      //ar( CEREAL_NVP(three) );
    }
};

class Stuff
{
  public:
    Stuff() {}

    void fillData()
    {
      std::vector<std::complex<float>> t1{ {0, -1.0f},
                          { 0, -2.9932f },
                          { 0, -3.5f } };
      std::vector<std::complex<float>> t2{ {1.0f, 0},
                     { 2.2f, 0 },
                     { 3.3f, 0 } };
      data["imaginary"] = t1;
      data["real"] = t2;
    }

  private:
    std::map<std::string, std::vector<std::complex<float>>> data;

    friend class cereal::access;

    template <class Archive>
    void serialize( Archive & ar )
    {
      ar( CEREAL_NVP(data) );
    }
};

struct OOJson
{
  OOJson() = default;
  OOJson( int aa, int bb, bool cc, double dd ) :
    a( aa ), b( bb ), c{ cc, dd }
  {
    d[0] = 0; d[1] = 1; d[2] = 2;
  }

  int a;
  int b;
  std::pair<bool, double> c;
  float d[3];

  template <class Archive>
  void serialize( Archive & ar )
  {
    ar( CEREAL_NVP(c) );
    ar( CEREAL_NVP(a) );
    ar( b );
    ar( CEREAL_NVP(d) );
  }
};

// ######################################################################
int main()
{
  std::cout << std::boolalpha << std::endl;

  {
    std::ofstream os("file.json");
    cereal::JSONOutputArchive oar( os, 5 );

    //auto f = std::make_shared<Fixture>();
    //auto f2 = f;
    //oar( f );
    //oar( f2 );
    Stuff s; s.fillData();
    oar( cereal::make_nvp("best data ever", s) );
  }

  {
    std::ifstream is("file.json");
    std::string str((std::istreambuf_iterator<char>(is)), std::istreambuf_iterator<char>());
    std::cout << "---------------------" << std::endl << str << std::endl << "---------------------" << std::endl;
  }

  {
    cereal::JSONOutputArchive archive( std::cout );
    bool arr[] = {true, false};
    std::vector<int> vec = {1, 2, 3, 4, 5};
    archive( CEREAL_NVP(vec),
        arr );
    auto f = std::make_shared<Fixture>();
    auto f2 = f;
    archive( f );
    archive( f2 );

    enum Bla
    {
      x,
      y
    };

    archive( Bla::x );
  }

  // test out of order
  std::stringstream oos;
  {
    cereal::JSONOutputArchive ar(oos);
    cereal::JSONOutputArchive ar2(std::cout);

    ar( cereal::make_nvp( "1", 1 ),
        cereal::make_nvp( "2", 2 ),
        3,
        0, // unused
        cereal::make_nvp( "4", 4 ),
        cereal::make_nvp( "5", 5 ) );

    int x = 33;
    ar.saveBinaryValue( &x, sizeof(int), "bla" );

    ar2( cereal::make_nvp( "1", 1 ),
         cereal::make_nvp( "2", 2 ),
         3,
         0, // unused
         cereal::make_nvp( "4", 4 ),
         cereal::make_nvp( "5", 5 ) );
    ar2.saveBinaryValue( &x, sizeof(int), "bla" );

    OOJson oo( 1, 2, 3, 4 );
    ar( CEREAL_NVP(oo) );
    ar2( CEREAL_NVP(oo) );

    // boost stuff
    ar & cereal::make_nvp("usingop&", oo ) & 6;
    ar << 5 << 4 << 3;

    ar2 & cereal::make_nvp("usingop&", oo ) & 6;
    ar2 << 5 << 4 << 3;
  }

  {
    cereal::JSONInputArchive ar(oos);
    int i1, i2, i3, i4, i5, x;

    ar( i1 );
    ar( cereal::make_nvp( "2", i2 ), i3 );

    ar( cereal::make_nvp( "4", i4 ),
        i5 );

    ar.loadBinaryValue( &x, sizeof(int) );

    OOJson ii;
    ar( cereal::make_nvp("oo", ii) );
    ar( cereal::make_nvp( "2", i2 ) );

    std::cout << i1 << " " << i2 << " " << i3 << " " << i4 << " " << i5 << std::endl;
    std::cout << x << std::endl;
    std::cout << ii.a << " " << ii.b << " " << ii.c.first << " " << ii.c.second << " ";
    for( auto z : ii.d )
      std::cout << z << " ";
    std::cout << std::endl;

    OOJson oo;
    ar >> cereal::make_nvp("usingop&", oo );
    std::cout << oo.a << " " << oo.b << " " << oo.c.first << " " << oo.c.second << " ";
    for( auto z : oo.d )
      std::cout << z << " ";

    int aa, a, b, c;
    ar & aa & a & b & c;
    std::cout << aa << " " << a << " " << b << " " << c << std::endl;

  }

  //{
  //  std::ifstream is("file.json");
  //  cereal::JSONInputArchive iar( is );

  //  std::shared_ptr<Fixture> f, f2;
  //  iar( f, f2 );
  //  assert( f->array[0] == 1 );
  //  assert( f->array[1] == 2 );
  //  assert( f->array[2] == 3 );
  //  assert( f->array[3] == 4 );
  //}

  return 0;
}
<|endoftext|>


<commit_before>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <iostream>
#include <cstring>

using namespace cv;
using namespace std;

Mat calculate_energy(Mat I){
    Mat Ix,Iy;

    Sobel(I,Ix,CV_32F,1,0);
    convertScaleAbs(Ix,Ix);

    Sobel(I,Iy,CV_32F,0,1);
    convertScaleAbs(Iy,Iy);

    Mat energy;
    addWeighted(Ix, 0.5, Iy, 0.5, 0, energy, CV_8U);

    return energy;
}

Mat calculate_energy2(Mat I){
    int Y = I.rows,X = I.cols;
    Mat energy = Mat(Y, X, CV_32S);

    for(int x = 0;x < X;++x){
        for(int y = 0;y < Y;++y){
            int val = 0;

            if(x > 0 && x + 1 < X)
                val += abs((int)I.at<uchar>(y,x + 1) - (int)I.at<uchar>(y,x - 1));
            else if(x > 0)
                val += 2 * abs((int)I.at<uchar>(y,x) - (int)I.at<uchar>(y,x - 1));
            else
                val += 2 * abs((int)I.at<uchar>(y,x + 1) - (int)I.at<uchar>(y,x));

            if(y > 0 && y + 1 < Y)
                val += abs((int)I.at<uchar>(y + 1,x) - (int)I.at<uchar>(y - 1,x));
            else if(y > 0)
                val += 2 * abs((int)I.at<uchar>(y,x) - (int)I.at<uchar>(y - 1,x));
            else
                val += 2 * abs((int)I.at<uchar>(y + 1,x) - (int)I.at<uchar>(y,x));

            energy.at<int>(y,x) = val;
        }
    }

    return energy;
}

int query(int bit[], int idx){
    int ret = 0;

    for(int x = idx;x > 0;x -= x & -x)
        ret += bit[x];

    return ret;
}

void update(int bit[], int maxX, int idx){
    for(int x = idx;x < maxX;x += x & -x)
        ++bit[x];
}

int main(){
    Mat_<Vec3b> I = imread("../bench.jpg");

    imshow("seam-carving",I);
    waitKey(0);

    int Y = I.rows,X = I.cols;
    int Y0 = Y,X0 = X;

    Mat gray,energy;

    //cvtColor(I,gray,CV_BGR2GRAY);
    //energy = calculate_energy(gray);
    //imshow("seam-carving",energy);
    //waitKey(0);

    unsigned int dpH[X][Y],dpV[X][Y];
    int dirH[X][Y],dirV[X][Y];
    vector<int> posH[X],posV[Y];
    int bitH[Y + 1],bitV[X + 1];

    Mat seams = I.clone();

    // Horizontal seams

    for(int it = 0;it < 50;++it){
        cvtColor(I,gray,CV_BGR2GRAY);
        energy = calculate_energy2(gray);

        for(int y = 0;y < Y;++y)
            dpH[0][y] = energy.at<uchar>(y,0);

        for(int x = 1;x < X;++x){
            for(int y = 0;y < Y;++y){
                uint val = energy.at<uchar>(y,x);
                dpH[x][y] = -1;

                if(y > 0 && (dpH[x][y] == -1 || val + dpH[x - 1][y - 1] < dpH[x][y])){
                    dpH[x][y] = val + dpH[x - 1][y - 1];
                    dirH[x][y] = -1;
                }

                if(dpH[x][y] == -1 || val + dpH[x - 1][y] < dpH[x][y]){
                    dpH[x][y] = val + dpH[x - 1][y];
                    dirH[x][y] = 0;
                }

                if(y + 1 < Y && (dpH[x][y] == -1 || val + dpH[x - 1][y + 1] < dpH[x][y])){
                    dpH[x][y] = val + dpH[x - 1][y + 1];
                    dirH[x][y] = 1;
                }
            }
        }

        unsigned int bestH = dpH[X - 1][0];
        int cury = 0;

        for(int y = 0;y < Y;++y){
            if(dpH[X - 1][y] < bestH){
                bestH = dpH[X - 1][y];
                cury = y;
            }
        }

        //cout << "cury = " << cury << endl;
        //cout << "bestH = " << bestH << endl;

        Mat_<Vec3b> tmp(Y - 1,X);

        for(int x = X - 1,cont = 0;x >= 0;--x,++cont){
            posH[x].push_back(cury);

            for(int i = 0;i < Y;++i){
                if(i < cury) tmp.at<Vec3b>(i,x) = I.at<Vec3b>(i,x);
                else if(i > cury) tmp.at<Vec3b>(i - 1,x) = I.at<Vec3b>(i,x);
            }

            if(x > 0)
                cury = cury + dirH[x][cury];
        }

        I = tmp;
        --Y;
    }

    //imwrite("seam_horizontal2.jpg", I);

    for(int x = 0;x < X;++x){
        memset(bitH,0,sizeof bitH);

        for(int i = 0;i < posH[x].size();++i){
            int y = posH[x][i];
            update(bitH,Y0 + 1,y + 1);
            y += query(bitH,y + 1) - 1;

            seams.at<Vec3b>(y,x) = Vec3b(0,0,255);
        }
    }

    // Vertical seams

    for(int it = 0;it < 100;++it){
        cvtColor(I,gray,CV_BGR2GRAY);
        energy = calculate_energy2(gray);

        for(int x = 0;x < X;++x)
            dpV[x][0] = energy.at<uint>(0,x);

        for(int y = 1;y < Y;++y){
            for(int x = 0;x < X;++x){
                uint val = energy.at<uint>(y,x);
                dpV[x][y] = -1;

                if(x > 0 && (dpV[x][y] == -1 || val + dpV[x - 1][y - 1] < dpV[x][y])){
                    dpV[x][y] = val + dpV[x - 1][y - 1];
                    dirV[x][y] = -1;
                }

                if(dpV[x][y] == -1 || val + dpV[x][y - 1] < dpV[x][y]){
                    dpV[x][y] = val + dpV[x][y - 1];
                    dirV[x][y] = 0;
                }

                if(x + 1 < X && (dpV[x][y] == -1 || val + dpV[x + 1][y - 1] < dpV[x][y])){
                    dpV[x][y] = val + dpV[x + 1][y - 1];
                    dirV[x][y] = 1;
                }
            }
        }

        unsigned int bestV = dpV[0][Y - 1];
        int curx = 0;

        for(int x = 0;x < X;++x){
            if(dpV[x][Y - 1] < bestV){
                bestV = dpV[x][Y - 1];
                curx = x;
            }
        }

        Mat_<Vec3b> tmp(Y,X - 1);

        for(int y = Y - 1;y >= 0;--y){
            posV[y].push_back(curx);

            for(int i = 0;i < X;++i){
                if(i < curx) tmp.at<Vec3b>(y,i) = I.at<Vec3b>(y,i);
                else if(i > curx) tmp.at<Vec3b>(y,i - 1) = I.at<Vec3b>(y,i);
            }

            if(y > 0)
                curx = curx + dirV[curx][y];
        }

        I = tmp;
        --X;
    }

    imshow("seams",seams);
    imshow("seam-carving-out",I);
    waitKey(0);

    return 0;
}<commit_msg>show horizontal and vertical seams<commit_after>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <iostream>
#include <cstring>

using namespace cv;
using namespace std;

/*Mat calculate_energy(Mat I){
    Mat Ix,Iy;

    Sobel(I,Ix,CV_32F,1,0);
    convertScaleAbs(Ix,Ix);

    Sobel(I,Iy,CV_32F,0,1);
    convertScaleAbs(Iy,Iy);

    Mat energy;
    addWeighted(Ix, 0.5, Iy, 0.5, 0, energy, CV_8U);

    return energy;
}*/

Mat calculate_energy(Mat I){
    int Y = I.rows,X = I.cols;
    Mat energy = Mat(Y, X, CV_32S);

    for(int x = 0;x < X;++x){
        for(int y = 0;y < Y;++y){
            int val = 0;

            if(x > 0 && x + 1 < X)
                val += abs((int)I.at<uchar>(y,x + 1) - (int)I.at<uchar>(y,x - 1));
            else if(x > 0)
                val += 2 * abs((int)I.at<uchar>(y,x) - (int)I.at<uchar>(y,x - 1));
            else
                val += 2 * abs((int)I.at<uchar>(y,x + 1) - (int)I.at<uchar>(y,x));

            if(y > 0 && y + 1 < Y)
                val += abs((int)I.at<uchar>(y + 1,x) - (int)I.at<uchar>(y - 1,x));
            else if(y > 0)
                val += 2 * abs((int)I.at<uchar>(y,x) - (int)I.at<uchar>(y - 1,x));
            else
                val += 2 * abs((int)I.at<uchar>(y + 1,x) - (int)I.at<uchar>(y,x));

            energy.at<int>(y,x) = val;
        }
    }

    return energy;
}

int main(){
    Mat_<Vec3b> I = imread("../bench.jpg");

    imshow("seam-carving",I);
    waitKey(0);

    int Y = I.rows,X = I.cols;
    int Y0 = Y,X0 = X;

    Mat gray,energy;

    //cvtColor(I,gray,CV_BGR2GRAY);
    //energy = calculate_energy(gray);
    //imshow("seam-carving",energy);
    //waitKey(0);

    unsigned int dpH[X][Y],dpV[X][Y];
    int dirH[X][Y],dirV[X][Y];
    vector<int> posH[X],posV[Y];
    pair<int, int> pos[X][Y];

    for(int i = 0;i < X;++i)
        for(int j = 0;j < Y;++j)
            pos[i][j] = make_pair(i,j);

    Mat seams = I.clone();

    // Horizontal seams

    for(int it = 0;it < 50;++it){
        cvtColor(I,gray,CV_BGR2GRAY);
        energy = calculate_energy(gray);

        for(int y = 0;y < Y;++y)
            dpH[0][y] = energy.at<int>(y,0);

        for(int x = 1;x < X;++x){
            for(int y = 0;y < Y;++y){
                uint val = energy.at<int>(y,x);
                dpH[x][y] = -1;

                if(y > 0 && (dpH[x][y] == -1 || val + dpH[x - 1][y - 1] < dpH[x][y])){
                    dpH[x][y] = val + dpH[x - 1][y - 1];
                    dirH[x][y] = -1;
                }

                if(dpH[x][y] == -1 || val + dpH[x - 1][y] < dpH[x][y]){
                    dpH[x][y] = val + dpH[x - 1][y];
                    dirH[x][y] = 0;
                }

                if(y + 1 < Y && (dpH[x][y] == -1 || val + dpH[x - 1][y + 1] < dpH[x][y])){
                    dpH[x][y] = val + dpH[x - 1][y + 1];
                    dirH[x][y] = 1;
                }
            }
        }

        unsigned int bestH = dpH[X - 1][0];
        int cury = 0;

        for(int y = 0;y < Y;++y){
            if(dpH[X - 1][y] < bestH){
                bestH = dpH[X - 1][y];
                cury = y;
            }
        }

        Mat_<Vec3b> tmp(Y - 1,X);

        for(int x = X - 1,cont = 0;x >= 0;--x,++cont){
            posH[x].push_back(cury);

            for(int i = 0;i < Y;++i){
                if(i < cury){
                    tmp.at<Vec3b>(i,x) = I.at<Vec3b>(i,x);
                }else if(i > cury){
                    tmp.at<Vec3b>(i - 1,x) = I.at<Vec3b>(i,x);
                    pos[x][i - 1] = pos[x][i];
                }else{
                    seams.at<Vec3b>(pos[x][i].second, pos[x][i].first) = Vec3b(0,0,255);
                }
            }

            if(x > 0)
                cury = cury + dirH[x][cury];
        }

        I = tmp;
        --Y;
    }

    // Vertical seams

    for(int it = 0;it < 100;++it){
        cvtColor(I,gray,CV_BGR2GRAY);
        energy = calculate_energy(gray);

        for(int x = 0;x < X;++x)
            dpV[x][0] = energy.at<int>(0,x);

        for(int y = 1;y < Y;++y){
            for(int x = 0;x < X;++x){
                int val = energy.at<int>(y,x);
                dpV[x][y] = -1;

                if(x > 0 && (dpV[x][y] == -1 || val + dpV[x - 1][y - 1] < dpV[x][y])){
                    dpV[x][y] = val + dpV[x - 1][y - 1];
                    dirV[x][y] = -1;
                }

                if(dpV[x][y] == -1 || val + dpV[x][y - 1] < dpV[x][y]){
                    dpV[x][y] = val + dpV[x][y - 1];
                    dirV[x][y] = 0;
                }

                if(x + 1 < X && (dpV[x][y] == -1 || val + dpV[x + 1][y - 1] < dpV[x][y])){
                    dpV[x][y] = val + dpV[x + 1][y - 1];
                    dirV[x][y] = 1;
                }
            }
        }

        unsigned int bestV = dpV[0][Y - 1];
        int curx = 0;

        for(int x = 0;x < X;++x){
            if(dpV[x][Y - 1] < bestV){
                bestV = dpV[x][Y - 1];
                curx = x;
            }
        }

        Mat_<Vec3b> tmp(Y,X - 1);

        for(int y = Y - 1;y >= 0;--y){
            posV[y].push_back(curx);

            for(int i = 0;i < X;++i){
                if(i < curx){
                    tmp.at<Vec3b>(y,i) = I.at<Vec3b>(y,i);
                }else if(i > curx){
                    tmp.at<Vec3b>(y,i - 1) = I.at<Vec3b>(y,i);
                    pos[i - 1][y] = pos[i][y];
                }else{
                    seams.at<Vec3b>(pos[i][y].second, pos[i][y].first) = Vec3b(0,0,255);
                }
            }

            if(y > 0)
                curx = curx + dirV[curx][y];
        }

        I = tmp;
        --X;
    }

    imshow("seams",seams);
    //imwrite("seams.jpg", seams);
    imshow("seam-carving-out",I);
    //imwrite("seam-carving-out-2.jpg",I);
    waitKey(0);

    return 0;
}<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

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

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/
#ifndef _mitkExtendedLabelStatisticsImageFilter_hxx
#define _mitkExtendedLabelStatisticsImageFilter_hxx

#include "mitkExtendedLabelStatisticsImageFilter.h"

#include "itkImageRegionIterator.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkProgressReporter.h"

#include "itkImageFileWriter.h"

namespace itk
{
  template< class TInputImage , class TLabelImage>
  ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >
    ::ExtendedLabelStatisticsImageFilter()
    : LabelStatisticsImageFilter()
  {
    m_LabelStatisticsCoefficients;
  }

  template< class TInputImage, class TLabelImage >
  typename ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::RealType
    ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >
    ::GetKurtosis(LabelPixelType label) const
  {
    CoefficientsMapConstIterator mapIt;

    mapIt = m_LabelStatisticsCoefficients.find(label);
    if ( mapIt == m_LabelStatisticsCoefficients.end() )
    {
      // label does not exist, return a default value
      return NumericTraits< PixelType >::Zero;
    }
    else
    {
      return ( *mapIt ).second.m_Kurtosis;
    }
  }

  template< class TInputImage, class TLabelImage >
  typename ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::RealType
    ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >
    ::GetSkewness(LabelPixelType label) const
  {
    CoefficientsMapConstIterator mapIt;

    mapIt = m_LabelStatisticsCoefficients.find(label);
    if ( mapIt == m_LabelStatisticsCoefficients.end() )
    {
      // label does not exist, return a default value
      return NumericTraits< PixelType >::Zero;
    }
    else
    {
      return ( *mapIt ).second.m_Skewness;
    }
  }

  template< class TInputImage, class TLabelImage >
  void
    ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::
    ComputeTheSkewnessAndCurtosis()
  {
    MapIterator mapIt;
    TLabelImage::RegionType Subregion;

    double baseOfSkewnessAndCurtosis;
    double Kurtosis = 0.0;
    double Skewness = 0.0;

    std::list< LabelPixelType> relevantLabels;
    bool maskNonEmpty = false;
    LabelPixelType i;
    for ( i = 1; i < 100; ++i )
    {
      if ( this->HasLabel( i ) )
      {
        relevantLabels.push_back( i );
        maskNonEmpty = true;
        m_LabelStatisticsCoefficients.insert( std::make_pair(i, CoefficientsClass()) );
      }
    }

    if ( maskNonEmpty )
    {
      std::list< LabelPixelType >::iterator it;
      for ( it = relevantLabels.begin(), i = 0;
        it != relevantLabels.end();
        ++it, ++i )
      {
        double Sigma = GetSigma( *it );
        double Mean     = GetMean( *it );
        Subregion = Superclass::GetRegion(*it);

        ImageRegionConstIteratorWithIndex< TInputImage > it1 (this->GetInput(),
          Subregion);
        ImageRegionConstIterator< TLabelImage > labelIt (this->GetLabelInput(),
          Subregion);

        for (it1.GoToBegin(); !it1.IsAtEnd(); ++it1, ++labelIt)
        {
          if (labelIt.Get() == *it)
          {
            baseOfSkewnessAndCurtosis = (  it1.Get() -Mean ) / Sigma ;
            Kurtosis += baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis;
            Skewness += baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis;
          }
        }

        m_LabelStatisticsCoefficients[*it].m_Skewness = double(Skewness/GetCount(*it));
        m_LabelStatisticsCoefficients[*it].m_Kurtosis = double(Kurtosis/GetCount(*it));
      }
    }
  }

  template< class TInputImage, class TLabelImage >
  void ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::
    AfterThreadedGenerateData()
  {
    Superclass::AfterThreadedGenerateData();

    ComputeTheSkewnessAndCurtosis();
  }

} // end namespace itk

#endif<commit_msg>removed unused includes<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

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

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/
#ifndef _mitkExtendedLabelStatisticsImageFilter_hxx
#define _mitkExtendedLabelStatisticsImageFilter_hxx

#include "mitkExtendedLabelStatisticsImageFilter.h"

#include "itkImageRegionConstIteratorWithIndex.h"

namespace itk
{
  template< class TInputImage , class TLabelImage>
  ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >
    ::ExtendedLabelStatisticsImageFilter()
    : LabelStatisticsImageFilter()
  {
    m_LabelStatisticsCoefficients;
  }

  template< class TInputImage, class TLabelImage >
  typename ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::RealType
    ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >
    ::GetKurtosis(LabelPixelType label) const
  {
    CoefficientsMapConstIterator mapIt;

    mapIt = m_LabelStatisticsCoefficients.find(label);
    if ( mapIt == m_LabelStatisticsCoefficients.end() )
    {
      // label does not exist, return a default value
      return NumericTraits< PixelType >::Zero;
    }
    else
    {
      return ( *mapIt ).second.m_Kurtosis;
    }
  }

  template< class TInputImage, class TLabelImage >
  typename ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::RealType
    ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >
    ::GetSkewness(LabelPixelType label) const
  {
    CoefficientsMapConstIterator mapIt;

    mapIt = m_LabelStatisticsCoefficients.find(label);
    if ( mapIt == m_LabelStatisticsCoefficients.end() )
    {
      // label does not exist, return a default value
      return NumericTraits< PixelType >::Zero;
    }
    else
    {
      return ( *mapIt ).second.m_Skewness;
    }
  }

  template< class TInputImage, class TLabelImage >
  void
    ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::
    ComputeTheSkewnessAndCurtosis()
  {
    MapIterator mapIt;
    TLabelImage::RegionType Subregion;

    double baseOfSkewnessAndCurtosis;
    double Kurtosis = 0.0;
    double Skewness = 0.0;

    std::list< LabelPixelType> relevantLabels;
    bool maskNonEmpty = false;
    LabelPixelType i;
    for ( i = 1; i < 100; ++i )
    {
      if ( this->HasLabel( i ) )
      {
        relevantLabels.push_back( i );
        maskNonEmpty = true;
        m_LabelStatisticsCoefficients.insert( std::make_pair(i, CoefficientsClass()) );
      }
    }

    if ( maskNonEmpty )
    {
      std::list< LabelPixelType >::iterator it;
      for ( it = relevantLabels.begin(), i = 0;
        it != relevantLabels.end();
        ++it, ++i )
      {
        double Sigma = GetSigma( *it );
        double Mean     = GetMean( *it );
        Subregion = Superclass::GetRegion(*it);

        ImageRegionConstIteratorWithIndex< TInputImage > it1 (this->GetInput(),
          Subregion);
        ImageRegionConstIterator< TLabelImage > labelIt (this->GetLabelInput(),
          Subregion);

        for (it1.GoToBegin(); !it1.IsAtEnd(); ++it1, ++labelIt)
        {
          if (labelIt.Get() == *it)
          {
            baseOfSkewnessAndCurtosis = (  it1.Get() -Mean ) / Sigma ;
            Kurtosis += baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis;
            Skewness += baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis;
          }
        }

        m_LabelStatisticsCoefficients[*it].m_Skewness = double(Skewness/GetCount(*it));
        m_LabelStatisticsCoefficients[*it].m_Kurtosis = double(Kurtosis/GetCount(*it));
      }
    }
  }

  template< class TInputImage, class TLabelImage >
  void ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::
    AfterThreadedGenerateData()
  {
    Superclass::AfterThreadedGenerateData();

    ComputeTheSkewnessAndCurtosis();
  }

} // end namespace itk

#endif<|endoftext|>


<commit_before>// Copyright (c) 2017, WNProject Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.txt file.

#include "WNWindow/inc/WNXCBWindow.h"
#include "WNApplicationData/inc/WNApplicationData.h"
#include "WNExecutable/inc/WNEntryData.h"
#include "WNMultiTasking/inc/WNJobPool.h"
#include "WNMultiTasking/inc/WNJobSignal.h"

namespace wn {
namespace runtime {
namespace window {

window_error xcb_window::initialize() {
  m_job_pool->add_job(
      &m_destroy_signal, &xcb_window::dispatch_loop, this, nullptr);
  return window_error::ok;
}

void xcb_window::dispatch_loop(void*) {
  m_job_pool->call_blocking_function([&]() {
    m_data.connection = xcb_connect(NULL, NULL);
    if (m_data.connection == nullptr) {
      return;
    }

    const xcb_setup_t* setup = xcb_get_setup(m_data.connection);
    m_screen = xcb_setup_roots_iterator(setup).data;

    if (m_screen == nullptr) {
      xcb_disconnect(m_data.connection);
      m_data.connection = nullptr;
      m_creation_signal->increment(1);
      m_create_signal.increment(1);
      return;
    }

    m_data.window = xcb_generate_id(m_data.connection);

    uint32_t values[1] = {XCB_EVENT_MASK_STRUCTURE_NOTIFY};

    xcb_create_window(m_data.connection, XCB_COPY_FROM_PARENT, m_data.window,
        m_screen->root, m_x, m_y, m_width, m_height, 10,
        XCB_WINDOW_CLASS_INPUT_OUTPUT, m_screen->root_visual, XCB_CW_EVENT_MASK,
        values);

    if (m_creation_signal) {
      m_creation_signal->increment(1);
    }

    const char* protocol = "WM_PROTOCOLS";
    xcb_intern_atom_cookie_t cookie =
        xcb_intern_atom(m_data.connection, true, strlen(protocol), protocol);
    xcb_intern_atom_reply_t* reply =
        xcb_intern_atom_reply(m_data.connection, cookie, NULL);

    const char* delete_window = "WM_DELETE_WINDOW";
    cookie = xcb_intern_atom(
        m_data.connection, true, strlen(delete_window), delete_window);
    m_delete_window = xcb_intern_atom_reply(m_data.connection, cookie, NULL);

    xcb_change_property(m_data.connection, XCB_PROP_MODE_REPLACE, m_data.window,
        reply->atom, 4, 32, 1, &m_delete_window->atom);

    free(reply);

    xcb_map_window(m_data.connection, m_data.window);

    xcb_flush(m_data.connection);

    m_create_signal.increment(1);

    xcb_generic_event_t* event;
    while ((event = xcb_wait_for_event(m_data.connection))) {
      switch (event->response_type & 0x7F) {
        case XCB_CLIENT_MESSAGE:
          if ((*(xcb_client_message_event_t*)event).data.data32[0] ==
              m_delete_window->atom) {
            free(event);
            return;
          }
        case XCB_DESTROY_NOTIFY:
          free(event);
          return;
        default:
          break;
      }
      free(event);
    }
  });
}

}  // namespace window
}  // namespace runtime
}  // namespace wn
<commit_msg>Fix bug in XCB swapchain.<commit_after>// Copyright (c) 2017, WNProject Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.txt file.

#include "WNWindow/inc/WNXCBWindow.h"
#include "WNApplicationData/inc/WNApplicationData.h"
#include "WNExecutable/inc/WNEntryData.h"
#include "WNMultiTasking/inc/WNJobPool.h"
#include "WNMultiTasking/inc/WNJobSignal.h"

namespace wn {
namespace runtime {
namespace window {

window_error xcb_window::initialize() {
  m_job_pool->add_job(
      &m_destroy_signal, &xcb_window::dispatch_loop, this, nullptr);
  return window_error::ok;
}

void xcb_window::dispatch_loop(void*) {
  m_job_pool->call_blocking_function([&]() {
    m_data.connection = xcb_connect(NULL, NULL);
    if (m_data.connection == nullptr) {
      return;
    }

    const xcb_setup_t* setup = xcb_get_setup(m_data.connection);
    m_screen = xcb_setup_roots_iterator(setup).data;

    if (m_screen == nullptr) {
      xcb_disconnect(m_data.connection);
      m_data.connection = nullptr;
      m_creation_signal->increment(1);
      m_create_signal.increment(1);
      return;
    }

    m_data.window = xcb_generate_id(m_data.connection);

    uint32_t values[1] = {XCB_EVENT_MASK_STRUCTURE_NOTIFY};

    xcb_create_window(m_data.connection, XCB_COPY_FROM_PARENT, m_data.window,
        m_screen->root, m_x, m_y, m_width, m_height, 10,
        XCB_WINDOW_CLASS_INPUT_OUTPUT, m_screen->root_visual, XCB_CW_EVENT_MASK,
        values);

    const char* protocol = "WM_PROTOCOLS";
    xcb_intern_atom_cookie_t cookie =
        xcb_intern_atom(m_data.connection, true, strlen(protocol), protocol);
    xcb_intern_atom_reply_t* reply =
        xcb_intern_atom_reply(m_data.connection, cookie, NULL);

    const char* delete_window = "WM_DELETE_WINDOW";
    cookie = xcb_intern_atom(
        m_data.connection, true, strlen(delete_window), delete_window);
    m_delete_window = xcb_intern_atom_reply(m_data.connection, cookie, NULL);

    xcb_change_property(m_data.connection, XCB_PROP_MODE_REPLACE, m_data.window,
        reply->atom, 4, 32, 1, &m_delete_window->atom);

    free(reply);

    xcb_map_window(m_data.connection, m_data.window);

    xcb_flush(m_data.connection);

    if (m_creation_signal) {
      m_creation_signal->increment(1);
    }

    m_create_signal.increment(1);

    xcb_generic_event_t* event;
    while ((event = xcb_wait_for_event(m_data.connection))) {
      switch (event->response_type & 0x7F) {
        case XCB_CLIENT_MESSAGE:
          if ((*(xcb_client_message_event_t*)event).data.data32[0] ==
              m_delete_window->atom) {
            free(event);
            return;
          }
        case XCB_DESTROY_NOTIFY:
          free(event);
          return;
        default:
          break;
      }
      free(event);
    }
  });
}

}  // namespace window
}  // namespace runtime
}  // namespace wn
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o - %s | FileCheck %s

namespace std {
  typedef decltype(sizeof(int)) size_t;

  // libc++'s implementation
  template <class _E>
  class initializer_list
  {
    const _E* __begin_;
    size_t    __size_;

    initializer_list(const _E* __b, size_t __s)
      : __begin_(__b),
        __size_(__s)
    {}

  public:
    typedef _E        value_type;
    typedef const _E& reference;
    typedef const _E& const_reference;
    typedef size_t    size_type;

    typedef const _E* iterator;
    typedef const _E* const_iterator;

    initializer_list() : __begin_(nullptr), __size_(0) {}

    size_t    size()  const {return __size_;}
    const _E* begin() const {return __begin_;}
    const _E* end()   const {return __begin_ + __size_;}
  };
}

void fn1(int i) {
  // CHECK: define void @_Z3fn1i
  // temporary array
  // CHECK: [[array:%[^ ]+]] = alloca [3 x i32]
  // CHECK: getelementptr inbounds [3 x i32]* [[array]], i{{32|64}} 0
  // CHECK-NEXT: store i32 1, i32*
  // CHECK-NEXT: getelementptr
  // CHECK-NEXT: store
  // CHECK-NEXT: getelementptr
  // CHECK-NEXT: load
  // CHECK-NEXT: store
  // init the list
  // CHECK-NEXT: getelementptr
  // CHECK-NEXT: getelementptr inbounds [3 x i32]*
  // CHECK-NEXT: store i32*
  // CHECK-NEXT: getelementptr
  // CHECK-NEXT: store i{{32|64}} 3
  std::initializer_list<int> intlist{1, 2, i};
}

struct destroyme1 {
  ~destroyme1();
};
struct destroyme2 {
  ~destroyme2();
};

void fn2() {
  // CHECK: define void @_Z3fn2v
  void target(std::initializer_list<destroyme1>);
  // objects should be destroyed before dm2, after call returns
  target({ destroyme1(), destroyme1() });
  // CHECK: call void @_ZN10destroyme1D1Ev
  destroyme2 dm2;
  // CHECK: call void @_ZN10destroyme2D1Ev
}

void fn3() {
  // CHECK: define void @_Z3fn3v
  // objects should be destroyed after dm2
  auto list = { destroyme1(), destroyme1() };
  destroyme2 dm2;
  // CHECK: call void @_ZN10destroyme2D1Ev
  // CHECK: call void @_ZN10destroyme1D1Ev
}
<commit_msg>Add a testcase to show that temporaries from the initializer list are destroyed correctly.<commit_after>// RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o - %s | FileCheck %s

namespace std {
  typedef decltype(sizeof(int)) size_t;

  // libc++'s implementation
  template <class _E>
  class initializer_list
  {
    const _E* __begin_;
    size_t    __size_;

    initializer_list(const _E* __b, size_t __s)
      : __begin_(__b),
        __size_(__s)
    {}

  public:
    typedef _E        value_type;
    typedef const _E& reference;
    typedef const _E& const_reference;
    typedef size_t    size_type;

    typedef const _E* iterator;
    typedef const _E* const_iterator;

    initializer_list() : __begin_(nullptr), __size_(0) {}

    size_t    size()  const {return __size_;}
    const _E* begin() const {return __begin_;}
    const _E* end()   const {return __begin_ + __size_;}
  };
}

void fn1(int i) {
  // CHECK: define void @_Z3fn1i
  // temporary array
  // CHECK: [[array:%[^ ]+]] = alloca [3 x i32]
  // CHECK: getelementptr inbounds [3 x i32]* [[array]], i{{32|64}} 0
  // CHECK-NEXT: store i32 1, i32*
  // CHECK-NEXT: getelementptr
  // CHECK-NEXT: store
  // CHECK-NEXT: getelementptr
  // CHECK-NEXT: load
  // CHECK-NEXT: store
  // init the list
  // CHECK-NEXT: getelementptr
  // CHECK-NEXT: getelementptr inbounds [3 x i32]*
  // CHECK-NEXT: store i32*
  // CHECK-NEXT: getelementptr
  // CHECK-NEXT: store i{{32|64}} 3
  std::initializer_list<int> intlist{1, 2, i};
}

struct destroyme1 {
  ~destroyme1();
};
struct destroyme2 {
  ~destroyme2();
};
struct witharg1 {
  witharg1(const destroyme1&);
  ~witharg1();
};

void fn2() {
  // CHECK: define void @_Z3fn2v
  void target(std::initializer_list<destroyme1>);
  // objects should be destroyed before dm2, after call returns
  // CHECK: call void @_Z6targetSt16initializer_listI10destroyme1E
  target({ destroyme1(), destroyme1() });
  // CHECK: call void @_ZN10destroyme1D1Ev
  destroyme2 dm2;
  // CHECK: call void @_ZN10destroyme2D1Ev
}

void fn3() {
  // CHECK: define void @_Z3fn3v
  // objects should be destroyed after dm2
  auto list = { destroyme1(), destroyme1() };
  destroyme2 dm2;
  // CHECK: call void @_ZN10destroyme2D1Ev
  // CHECK: call void @_ZN10destroyme1D1Ev
}

void fn4() {
  // CHECK: define void @_Z3fn4v
  void target(std::initializer_list<witharg1>);
  // objects should be destroyed before dm2, after call returns
  // CHECK: call void @_ZN8witharg1C1ERK10destroyme1
  // CHECK: call void @_Z6targetSt16initializer_listI8witharg1E
  target({ witharg1(destroyme1()), witharg1(destroyme1()) });
  // CHECK: call void @_ZN8witharg1D1Ev
  // CHECK: call void @_ZN10destroyme1D1Ev
  destroyme2 dm2;
  // CHECK: call void @_ZN10destroyme2D1Ev
}

void fn5() {
  // CHECK: define void @_Z3fn5v
  // temps should be destroyed before dm2
  // objects should be destroyed after dm2
  // CHECK: call void @_ZN8witharg1C1ERK10destroyme1
  auto list = { witharg1(destroyme1()), witharg1(destroyme1()) };
  // CHECK: call void @_ZN10destroyme1D1Ev
  destroyme2 dm2;
  // CHECK: call void @_ZN10destroyme2D1Ev
  // CHECK: call void @_ZN8witharg1D1Ev
}
<|endoftext|>


<commit_before>;
#include "../Flare.h"
#include "FlareSpacecraft.h"
#include "Subsystems/FlareSpacecraftDamageSystem.h"
#include "../Game/FlarePlanetarium.h"
#include "FlareSpacecraftSpinningComponent.h"

/*----------------------------------------------------
	Constructor
----------------------------------------------------*/

UFlareSpacecraftSpinningComponent::UFlareSpacecraftSpinningComponent(const class FObjectInitializer& PCIP)
	: Super(PCIP)
	, RotationAxisRoll(true)
	, RotationAxisYaw(false)
	, RotationSpeed(20)
{
}

/*----------------------------------------------------
	Gameplay
----------------------------------------------------*/

void UFlareSpacecraftSpinningComponent::BeginPlay()
{
	Super::BeginPlay();
	SetCollisionProfileName("BlockAllDynamic");
}

void UFlareSpacecraftSpinningComponent::TickComponent(float DeltaSeconds, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)
{
	Super::TickComponent(DeltaSeconds, TickType, ThisTickFunction);
	AFlareSpacecraft* Ship = GetSpacecraft();
	if (!Ship)
	{
		return;
	}

	// Update
	if (!Ship->IsPresentationMode() && Ship->GetDamageSystem()->IsAlive())
	{
		// Rotation axis
		FRotator Axis;
		if (RotationAxisRoll)
		{
			Axis = FRotator(0, 0, 1);
		}
		else if (RotationAxisYaw)
		{
			Axis = FRotator(0, 1, 0);
		}
		else
		{
			Axis = FRotator(1, 0, 0);
		}

		// Sun-looker
		if (LookForSun)
		{
			AFlarePlanetarium* Planetarium = Ship->GetGame()->GetPlanetarium();
			if (Planetarium)
			{
				FRotator SunRotator = Planetarium->GetSunDirection().Rotation();
				FRotator SpinnerRotator = GetComponentRotation();
				FRotator Delta = SunRotator - SpinnerRotator;

				// Does not work, because Roll axis if zero when extracted from a direction... :)

				if (RotationAxisRoll)
				{
					Delta = FRotator(0, 0, Delta.Roll);
				}
				else if (RotationAxisYaw)
				{
					Delta = FRotator(0, Delta.Yaw, 0);
				}
				else
				{
					Delta = FRotator(Delta.Pitch, 0, 0);
				}

				AddLocalRotation(RotationSpeed * DeltaSeconds * Delta);
			}
		}

		// Simple spinner
		else
		{
			AddLocalRotation(RotationSpeed * DeltaSeconds * Axis);
		}
	}
}

<commit_msg>Fixed sun-searching components, mostly (#114)<commit_after>;
#include "../Flare.h"
#include "FlareSpacecraft.h"
#include "Subsystems/FlareSpacecraftDamageSystem.h"
#include "../Game/FlarePlanetarium.h"
#include "FlareSpacecraftSpinningComponent.h"

/*----------------------------------------------------
	Constructor
----------------------------------------------------*/

UFlareSpacecraftSpinningComponent::UFlareSpacecraftSpinningComponent(const class FObjectInitializer& PCIP)
	: Super(PCIP)
	, RotationAxisRoll(true)
	, RotationAxisYaw(false)
	, RotationSpeed(20)
{
}

/*----------------------------------------------------
	Gameplay
----------------------------------------------------*/

void UFlareSpacecraftSpinningComponent::BeginPlay()
{
	Super::BeginPlay();
	SetCollisionProfileName("BlockAllDynamic");
}

void UFlareSpacecraftSpinningComponent::TickComponent(float DeltaSeconds, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)
{
	Super::TickComponent(DeltaSeconds, TickType, ThisTickFunction);
	AFlareSpacecraft* Ship = GetSpacecraft();
	if (!Ship)
	{
		return;
	}

	// Update
	if (!Ship->IsPresentationMode() && Ship->GetDamageSystem()->IsAlive())
	{
		// Rotation axis
		FRotator Axis;
		if (RotationAxisRoll)
		{
			Axis = FRotator(0, 0, 1);
		}
		else if (RotationAxisYaw)
		{
			Axis = FRotator(0, 1, 0);
		}
		else
		{
			Axis = FRotator(1, 0, 0);
		}

		// Sun-looker
		if (LookForSun)
		{
			AFlarePlanetarium* Planetarium = Ship->GetGame()->GetPlanetarium();
			if (Planetarium)
			{
				FVector X(1, 0, 0);
				FVector Y(0, 1, 0);
				FVector Z(0, 0, 1);

				FRotator SunRotator = Planetarium->GetSunDirection().Rotation();
				FRotator SpinnerRotator = GetComponentRotation();
				FRotator Delta;

				// Compute the angle difference
				SunRotator.Normalize();
				SpinnerRotator.Normalize();
				float Angle = FMath::Acos(FVector::DotProduct(SunRotator.RotateVector(X), SpinnerRotator.RotateVector(Z)));
				// TODO : angle has a 50% chance of being the wrong way depending on orientation...

				// Use the correct axis
				if (RotationAxisRoll)
				{
					Delta = FQuat(X, Angle).Rotator();
				}
				else if (RotationAxisYaw)
				{
					Delta = FQuat(Z, Angle).Rotator();
				}
				else
				{
					Delta = FQuat(Y, Angle).Rotator();
				}

				// Update
				float DegreesAngle = FMath::RadiansToDegrees(Angle);
				if (DegreesAngle > 1)
				{
					AddLocalRotation(RotationSpeed * DeltaSeconds * Delta);
				}
			}
		}

		// Simple spinner
		else
		{
			AddLocalRotation(RotationSpeed * DeltaSeconds * Axis);
		}
	}
}

<|endoftext|>


<commit_before>#undef BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
#define BOOST_TEST_MODULE path_element_tests

// boost.test
#include <boost/test/included/unit_test.hpp>

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

// mapnik
#include <mapnik/map.hpp>
#include <mapnik/rule.hpp>
#include <mapnik/feature_type_style.hpp>
#include <mapnik/svg/output/svg_renderer.hpp>
#include <mapnik/text/placements/dummy.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/expression.hpp>
#include <mapnik/color_factory.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/agg_renderer.hpp>

// stl
#include <fstream>
#include <iterator>

namespace fs = boost::filesystem;
using namespace mapnik;

const std::string srs_lcc="+proj=lcc +ellps=GRS80 +lat_0=49 +lon_0=-95 +lat+1=49 +lat_2=77 \
                       +datum=NAD83 +units=m +no_defs";
const std::string srs_merc="+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 \
                       +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over";

void prepare_map(Map & m)
{
    // Provinces (polygon)
    feature_type_style provpoly_style;
    {
        rule r;
        r.set_filter(parse_expression("[NAME_EN] = 'Ontario'"));
        {
            polygon_symbolizer poly_sym;
            put(poly_sym, keys::fill, color(250, 190, 183));
            r.append(std::move(poly_sym));
        }
        provpoly_style.add_rule(std::move(r));
    }
    {
        rule r;
        r.set_filter(parse_expression("[NOM_FR] = 'Québec'"));
        {
            polygon_symbolizer poly_sym;
            put(poly_sym, keys::fill, color(217, 235, 203));
            r.append(std::move(poly_sym));
        }
        provpoly_style.add_rule(std::move(r));
    }
    m.insert_style("provinces",provpoly_style);

    // Provinces (polyline)
    feature_type_style provlines_style;
    {
        rule r;
        {
            line_symbolizer line_sym;
            put(line_sym,keys::stroke,color(0,0,0));
            put(line_sym,keys::stroke_width,1.0);
            dash_array dash;
            dash.emplace_back(8,4);
            dash.emplace_back(2,2);
            dash.emplace_back(2,2);
            put(line_sym,keys::stroke_dasharray,dash);
            r.append(std::move(line_sym));
        }
        provlines_style.add_rule(std::move(r));
    }
    m.insert_style("provlines",provlines_style);

    // Drainage
    feature_type_style qcdrain_style;
    {
        rule r;
        r.set_filter(parse_expression("[HYC] = 8"));
        {
            polygon_symbolizer poly_sym;
            put(poly_sym, keys::fill, color(153, 204, 255));
            r.append(std::move(poly_sym));
        }
        qcdrain_style.add_rule(std::move(r));
    }
    m.insert_style("drainage",qcdrain_style);

    // Roads 3 and 4 (The "grey" roads)
    feature_type_style roads34_style;
    {
        rule r;
        r.set_filter(parse_expression("[CLASS] = 3 or [CLASS] = 4"));
        {
            line_symbolizer line_sym;
            put(line_sym,keys::stroke,color(171,158,137));
            put(line_sym,keys::stroke_width,2.0);
            put(line_sym,keys::stroke_linecap,ROUND_CAP);
            put(line_sym,keys::stroke_linejoin,ROUND_JOIN);
            r.append(std::move(line_sym));
        }
        roads34_style.add_rule(std::move(r));
    }
    m.insert_style("smallroads",roads34_style);

    // Roads 2 (The thin yellow ones)
    feature_type_style roads2_style_1;
    {
        rule r;
        r.set_filter(parse_expression("[CLASS] = 2"));
        {
            line_symbolizer line_sym;
            put(line_sym,keys::stroke,color(171,158,137));
            put(line_sym,keys::stroke_width,4.0);
            put(line_sym,keys::stroke_linecap,ROUND_CAP);
            put(line_sym,keys::stroke_linejoin,ROUND_JOIN);
            r.append(std::move(line_sym));
        }
        roads2_style_1.add_rule(std::move(r));
    }
    m.insert_style("road-border", roads2_style_1);

    feature_type_style roads2_style_2;
    {
        rule r;
        r.set_filter(parse_expression("[CLASS] = 2"));
        {
            line_symbolizer line_sym;
            put(line_sym,keys::stroke,color(255,250,115));
            put(line_sym,keys::stroke_width,2.0);
            put(line_sym,keys::stroke_linecap,ROUND_CAP);
            put(line_sym,keys::stroke_linejoin,ROUND_JOIN);
            r.append(std::move(line_sym));
        }
        roads2_style_2.add_rule(std::move(r));
    }
    m.insert_style("road-fill", roads2_style_2);

    // Roads 1 (The big orange ones, the highways)
    feature_type_style roads1_style_1;
    {
        rule r;
        r.set_filter(parse_expression("[CLASS] = 1"));
        {
            line_symbolizer line_sym;
            put(line_sym,keys::stroke,color(188,149,28));
            put(line_sym,keys::stroke_width,7.0);
            put(line_sym,keys::stroke_linecap,ROUND_CAP);
            put(line_sym,keys::stroke_linejoin,ROUND_JOIN);
            r.append(std::move(line_sym));
        }
        roads1_style_1.add_rule(std::move(r));
    }
    m.insert_style("highway-border", roads1_style_1);

    feature_type_style roads1_style_2;
    {
        rule r;
        r.set_filter(parse_expression("[CLASS] = 1"));
        {
            line_symbolizer line_sym;
            put(line_sym,keys::stroke,color(242,191,36));
            put(line_sym,keys::stroke_width,5.0);
            put(line_sym,keys::stroke_linecap,ROUND_CAP);
            put(line_sym,keys::stroke_linejoin,ROUND_JOIN);
            r.append(std::move(line_sym));
        }
        roads1_style_2.add_rule(std::move(r));
    }
    m.insert_style("highway-fill", roads1_style_2);

    // Populated Places
    feature_type_style popplaces_style;
    {
        rule r;
        {
            text_symbolizer text_sym;
            text_placements_ptr placement_finder = std::make_shared<text_placements_dummy>();
            placement_finder->defaults.format->face_name = "DejaVu Sans Book";
            placement_finder->defaults.format->text_size = 10;
            placement_finder->defaults.format->fill = color(0,0,0);
            placement_finder->defaults.format->halo_fill = color(255,255,200);
            placement_finder->defaults.format->halo_radius = 1;
            placement_finder->defaults.set_old_style_expression(parse_expression("[GEONAME]"));
            put<text_placements_ptr>(text_sym, keys::text_placements_, placement_finder);
            r.append(std::move(text_sym));
        }
        popplaces_style.add_rule(std::move(r));
    }

    m.insert_style("popplaces",popplaces_style );

    // layers
    // Provincial  polygons
    {
        parameters p;
        p["type"]="shape";
        p["file"]="demo/data/boundaries";
        p["encoding"]="latin1";
        layer lyr("Provinces");
        lyr.set_datasource(datasource_cache::instance().create(p));
        lyr.set_srs(srs_lcc);
        lyr.add_style("provinces");
        m.add_layer(lyr);
    }

    // Drainage
    {
        parameters p;
        p["type"]="shape";
        p["file"]="demo/data/qcdrainage";
        layer lyr("Quebec Hydrography");
        lyr.set_datasource(datasource_cache::instance().create(p));
        lyr.set_srs(srs_lcc);
        lyr.add_style("drainage");
        m.add_layer(lyr);
    }

    {
        parameters p;
        p["type"]="shape";
        p["file"]="demo/data/ontdrainage";
        layer lyr("Ontario Hydrography");
        lyr.set_datasource(datasource_cache::instance().create(p));
        lyr.set_srs(srs_lcc);
        lyr.add_style("drainage");
        m.add_layer(lyr);
    }

    // Provincial boundaries
    {
        parameters p;
        p["type"]="shape";
        p["file"]="demo/data/boundaries_l";
        layer lyr("Provincial borders");
        lyr.set_srs(srs_lcc);
        lyr.set_datasource(datasource_cache::instance().create(p));
        lyr.add_style("provlines");
        m.add_layer(lyr);
    }

    // Roads
    {
        parameters p;
        p["type"]="shape";
        p["file"]="demo/data/roads";
        layer lyr("Roads");
        lyr.set_srs(srs_lcc);
        lyr.set_datasource(datasource_cache::instance().create(p));
        lyr.add_style("smallroads");
        lyr.add_style("road-border");
        lyr.add_style("road-fill");
        lyr.add_style("highway-border");
        lyr.add_style("highway-fill");

        m.add_layer(lyr);
    }

    // popplaces
    {
        parameters p;
        p["type"]="shape";
        p["file"]="demo/data/popplaces";
        p["encoding"] = "latin1";
        layer lyr("Populated Places");
        lyr.set_srs(srs_lcc);
        lyr.set_datasource(datasource_cache::instance().create(p));
        lyr.add_style("popplaces");
        m.add_layer(lyr);
    }
}

void render_to_file(Map const& m, const std::string output_filename)
{
    std::ofstream output_stream(output_filename.c_str());

    if(output_stream)
    {
        using svg_ren = svg_renderer<std::ostream_iterator<char> >;
        std::ostream_iterator<char> output_stream_iterator(output_stream);
        svg_ren renderer(m, output_stream_iterator);
        renderer.apply();
        output_stream.close();
        fs::path output_filename_path =
            fs::system_complete(fs::path(".")) / fs::path(output_filename);
        BOOST_CHECK_MESSAGE(fs::exists(output_filename_path),
                            "File '"+output_filename_path.string()+"' was created.");
    }
    else
    {
        BOOST_FAIL("Could not create create/open file '"+output_filename+"'.");
    }
}

BOOST_AUTO_TEST_CASE(path_element_test_case_1)
{
    std::cout << " looking for 'shape.input' plugin in ./plugins/input/" << "\n";
    datasource_cache::instance().register_datasources("plugins/input/");
    Map m(800,600);
    m.set_background(parse_color("white"));
    m.set_srs(srs_merc);
    prepare_map(m);
    m.zoom_to_box(box2d<double>(-8024477.28459,5445190.38849,-7381388.20071,5662941.44855));
    render_to_file(m, "path_element_test_case_1.svg");
    mapnik::image_32 buf(m.width(),m.height());
    mapnik::agg_renderer<mapnik::image_32> ren(m,buf);
    ren.apply();
    mapnik::save_to_file(buf,"path_element_test_case_1.png");
}
<commit_msg>fix compile of svg renderer tests<commit_after>#undef BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
#define BOOST_TEST_MODULE path_element_tests

// boost
#include <boost/test/included/unit_test.hpp>
#include <boost/filesystem.hpp>

// mapnik
#include <mapnik/map.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/rule.hpp>
#include <mapnik/feature_type_style.hpp>
#include <mapnik/svg/output/svg_renderer.hpp>
#include <mapnik/text/placements/dummy.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/expression.hpp>
#include <mapnik/color_factory.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/agg_renderer.hpp>

// stl
#include <fstream>
#include <iterator>

namespace fs = boost::filesystem;
using namespace mapnik;

const std::string srs_lcc="+proj=lcc +ellps=GRS80 +lat_0=49 +lon_0=-95 +lat+1=49 +lat_2=77 \
                       +datum=NAD83 +units=m +no_defs";
const std::string srs_merc="+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 \
                       +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over";

void prepare_map(Map & m)
{
    // Provinces (polygon)
    feature_type_style provpoly_style;
    {
        rule r;
        r.set_filter(parse_expression("[NAME_EN] = 'Ontario'"));
        {
            polygon_symbolizer poly_sym;
            put(poly_sym, keys::fill, color(250, 190, 183));
            r.append(std::move(poly_sym));
        }
        provpoly_style.add_rule(std::move(r));
    }
    {
        rule r;
        r.set_filter(parse_expression("[NOM_FR] = 'Québec'"));
        {
            polygon_symbolizer poly_sym;
            put(poly_sym, keys::fill, color(217, 235, 203));
            r.append(std::move(poly_sym));
        }
        provpoly_style.add_rule(std::move(r));
    }
    m.insert_style("provinces",provpoly_style);

    // Provinces (polyline)
    feature_type_style provlines_style;
    {
        rule r;
        {
            line_symbolizer line_sym;
            put(line_sym,keys::stroke,color(0,0,0));
            put(line_sym,keys::stroke_width,1.0);
            dash_array dash;
            dash.emplace_back(8,4);
            dash.emplace_back(2,2);
            dash.emplace_back(2,2);
            put(line_sym,keys::stroke_dasharray,dash);
            r.append(std::move(line_sym));
        }
        provlines_style.add_rule(std::move(r));
    }
    m.insert_style("provlines",provlines_style);

    // Drainage
    feature_type_style qcdrain_style;
    {
        rule r;
        r.set_filter(parse_expression("[HYC] = 8"));
        {
            polygon_symbolizer poly_sym;
            put(poly_sym, keys::fill, color(153, 204, 255));
            r.append(std::move(poly_sym));
        }
        qcdrain_style.add_rule(std::move(r));
    }
    m.insert_style("drainage",qcdrain_style);

    // Roads 3 and 4 (The "grey" roads)
    feature_type_style roads34_style;
    {
        rule r;
        r.set_filter(parse_expression("[CLASS] = 3 or [CLASS] = 4"));
        {
            line_symbolizer line_sym;
            put(line_sym,keys::stroke,color(171,158,137));
            put(line_sym,keys::stroke_width,2.0);
            put(line_sym,keys::stroke_linecap,ROUND_CAP);
            put(line_sym,keys::stroke_linejoin,ROUND_JOIN);
            r.append(std::move(line_sym));
        }
        roads34_style.add_rule(std::move(r));
    }
    m.insert_style("smallroads",roads34_style);

    // Roads 2 (The thin yellow ones)
    feature_type_style roads2_style_1;
    {
        rule r;
        r.set_filter(parse_expression("[CLASS] = 2"));
        {
            line_symbolizer line_sym;
            put(line_sym,keys::stroke,color(171,158,137));
            put(line_sym,keys::stroke_width,4.0);
            put(line_sym,keys::stroke_linecap,ROUND_CAP);
            put(line_sym,keys::stroke_linejoin,ROUND_JOIN);
            r.append(std::move(line_sym));
        }
        roads2_style_1.add_rule(std::move(r));
    }
    m.insert_style("road-border", roads2_style_1);

    feature_type_style roads2_style_2;
    {
        rule r;
        r.set_filter(parse_expression("[CLASS] = 2"));
        {
            line_symbolizer line_sym;
            put(line_sym,keys::stroke,color(255,250,115));
            put(line_sym,keys::stroke_width,2.0);
            put(line_sym,keys::stroke_linecap,ROUND_CAP);
            put(line_sym,keys::stroke_linejoin,ROUND_JOIN);
            r.append(std::move(line_sym));
        }
        roads2_style_2.add_rule(std::move(r));
    }
    m.insert_style("road-fill", roads2_style_2);

    // Roads 1 (The big orange ones, the highways)
    feature_type_style roads1_style_1;
    {
        rule r;
        r.set_filter(parse_expression("[CLASS] = 1"));
        {
            line_symbolizer line_sym;
            put(line_sym,keys::stroke,color(188,149,28));
            put(line_sym,keys::stroke_width,7.0);
            put(line_sym,keys::stroke_linecap,ROUND_CAP);
            put(line_sym,keys::stroke_linejoin,ROUND_JOIN);
            r.append(std::move(line_sym));
        }
        roads1_style_1.add_rule(std::move(r));
    }
    m.insert_style("highway-border", roads1_style_1);

    feature_type_style roads1_style_2;
    {
        rule r;
        r.set_filter(parse_expression("[CLASS] = 1"));
        {
            line_symbolizer line_sym;
            put(line_sym,keys::stroke,color(242,191,36));
            put(line_sym,keys::stroke_width,5.0);
            put(line_sym,keys::stroke_linecap,ROUND_CAP);
            put(line_sym,keys::stroke_linejoin,ROUND_JOIN);
            r.append(std::move(line_sym));
        }
        roads1_style_2.add_rule(std::move(r));
    }
    m.insert_style("highway-fill", roads1_style_2);

    // Populated Places
    feature_type_style popplaces_style;
    {
        rule r;
        {
            text_symbolizer text_sym;
            text_placements_ptr placement_finder = std::make_shared<text_placements_dummy>();
            placement_finder->defaults.format_defaults.face_name = "DejaVu Sans Book";
            placement_finder->defaults.format_defaults.text_size = mapnik::value_integer(10);
            placement_finder->defaults.format_defaults.fill = color(0,0,0);
            placement_finder->defaults.format_defaults.halo_fill = color(255,255,200);
            placement_finder->defaults.format_defaults.halo_radius = mapnik::value_integer(1);
            placement_finder->defaults.set_old_style_expression(parse_expression("[GEONAME]"));
            put<text_placements_ptr>(text_sym, keys::text_placements_, placement_finder);
            r.append(std::move(text_sym));
        }
        popplaces_style.add_rule(std::move(r));
    }

    m.insert_style("popplaces",popplaces_style );

    // layers
    // Provincial  polygons
    {
        parameters p;
        p["type"]="shape";
        p["file"]="demo/data/boundaries";
        p["encoding"]="latin1";
        layer lyr("Provinces");
        lyr.set_datasource(datasource_cache::instance().create(p));
        lyr.set_srs(srs_lcc);
        lyr.add_style("provinces");
        m.add_layer(lyr);
    }

    // Drainage
    {
        parameters p;
        p["type"]="shape";
        p["file"]="demo/data/qcdrainage";
        layer lyr("Quebec Hydrography");
        lyr.set_datasource(datasource_cache::instance().create(p));
        lyr.set_srs(srs_lcc);
        lyr.add_style("drainage");
        m.add_layer(lyr);
    }

    {
        parameters p;
        p["type"]="shape";
        p["file"]="demo/data/ontdrainage";
        layer lyr("Ontario Hydrography");
        lyr.set_datasource(datasource_cache::instance().create(p));
        lyr.set_srs(srs_lcc);
        lyr.add_style("drainage");
        m.add_layer(lyr);
    }

    // Provincial boundaries
    {
        parameters p;
        p["type"]="shape";
        p["file"]="demo/data/boundaries_l";
        layer lyr("Provincial borders");
        lyr.set_srs(srs_lcc);
        lyr.set_datasource(datasource_cache::instance().create(p));
        lyr.add_style("provlines");
        m.add_layer(lyr);
    }

    // Roads
    {
        parameters p;
        p["type"]="shape";
        p["file"]="demo/data/roads";
        layer lyr("Roads");
        lyr.set_srs(srs_lcc);
        lyr.set_datasource(datasource_cache::instance().create(p));
        lyr.add_style("smallroads");
        lyr.add_style("road-border");
        lyr.add_style("road-fill");
        lyr.add_style("highway-border");
        lyr.add_style("highway-fill");

        m.add_layer(lyr);
    }

    // popplaces
    {
        parameters p;
        p["type"]="shape";
        p["file"]="demo/data/popplaces";
        p["encoding"] = "latin1";
        layer lyr("Populated Places");
        lyr.set_srs(srs_lcc);
        lyr.set_datasource(datasource_cache::instance().create(p));
        lyr.add_style("popplaces");
        m.add_layer(lyr);
    }
}

void render_to_file(Map const& m, const std::string output_filename)
{
    std::ofstream output_stream(output_filename.c_str());

    if(output_stream)
    {
        using svg_ren = svg_renderer<std::ostream_iterator<char> >;
        std::ostream_iterator<char> output_stream_iterator(output_stream);
        svg_ren renderer(m, output_stream_iterator);
        renderer.apply();
        output_stream.close();
        fs::path output_filename_path =
            fs::system_complete(fs::path(".")) / fs::path(output_filename);
        BOOST_CHECK_MESSAGE(fs::exists(output_filename_path),
                            "File '"+output_filename_path.string()+"' was created.");
    }
    else
    {
        BOOST_FAIL("Could not create create/open file '"+output_filename+"'.");
    }
}

BOOST_AUTO_TEST_CASE(path_element_test_case_1)
{
    std::cout << " looking for 'shape.input' plugin in ./plugins/input/" << "\n";
    datasource_cache::instance().register_datasources("plugins/input/");
    Map m(800,600);
    m.set_background(parse_color("white"));
    m.set_srs(srs_merc);
    prepare_map(m);
    m.zoom_to_box(box2d<double>(-8024477.28459,5445190.38849,-7381388.20071,5662941.44855));
    render_to_file(m, "path_element_test_case_1.svg");
    mapnik::image_32 buf(m.width(),m.height());
    mapnik::agg_renderer<mapnik::image_32> ren(m,buf);
    ren.apply();
    mapnik::save_to_file(buf,"path_element_test_case_1.png");
}
<|endoftext|>


<commit_before>#ifndef SILICIUM_REACTIVE_LINUX_INOTIFY_HPP
#define SILICIUM_REACTIVE_LINUX_INOTIFY_HPP

#include <silicium/observable.hpp>
#include <silicium/override.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/swap.hpp>
#include <boost/optional.hpp>
#include <sys/inotify.h>
#include <dirent.h>

namespace Si
{
	namespace linux
	{
		struct file_notification
		{
			boost::uint32_t mask;
			boost::filesystem::path name;
		};

		struct watch_descriptor
		{
			watch_descriptor() BOOST_NOEXCEPT
			{
			}

			watch_descriptor(int notifier, int watch) BOOST_NOEXCEPT
				: notifier(notifier)
				, watch(watch)
			{
			}

			watch_descriptor(watch_descriptor &&other) BOOST_NOEXCEPT
				: notifier(other.notifier)
				, watch(other.watch)
			{
				other.notifier = -1;
			}

			~watch_descriptor() BOOST_NOEXCEPT
			{
				if (notifier == -1)
				{
					return;
				}
				inotify_rm_watch(notifier, watch);
			}

			watch_descriptor &operator = (watch_descriptor &&other) BOOST_NOEXCEPT
			{
				boost::swap(notifier, other.notifier);
				boost::swap(watch, other.watch);
				return *this;
			}

		private:

			int notifier = -1;
			int watch = -1;
		};

		struct inotify_observable : observable<std::vector<file_notification>>, boost::noncopyable
		{
			typedef std::vector<file_notification> element_type;

			inotify_observable();
			explicit inotify_observable(boost::asio::io_service &io);
			watch_descriptor watch(boost::filesystem::path const &target, boost::uint32_t mask);
			watch_descriptor watch(boost::filesystem::path const &target, boost::uint32_t mask, boost::system::error_code &ec);
			virtual void async_get_one(observer<element_type> &receiver) SILICIUM_OVERRIDE;
			virtual void cancel() SILICIUM_OVERRIDE;

		private:

			boost::optional<boost::asio::posix::stream_descriptor> notifier;
			std::vector<char> read_buffer;
			observer<element_type> *receiver_ = nullptr;
		};
	}
}

#endif
<commit_msg>devirtualize inotify_observable<commit_after>#ifndef SILICIUM_REACTIVE_LINUX_INOTIFY_HPP
#define SILICIUM_REACTIVE_LINUX_INOTIFY_HPP

#include <silicium/observer.hpp>
#include <silicium/override.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/swap.hpp>
#include <boost/optional.hpp>
#include <sys/inotify.h>
#include <dirent.h>

namespace Si
{
	namespace linux
	{
		struct file_notification
		{
			boost::uint32_t mask;
			boost::filesystem::path name;
		};

		struct watch_descriptor
		{
			watch_descriptor() BOOST_NOEXCEPT
			{
			}

			watch_descriptor(int notifier, int watch) BOOST_NOEXCEPT
				: notifier(notifier)
				, watch(watch)
			{
			}

			watch_descriptor(watch_descriptor &&other) BOOST_NOEXCEPT
				: notifier(other.notifier)
				, watch(other.watch)
			{
				other.notifier = -1;
			}

			~watch_descriptor() BOOST_NOEXCEPT
			{
				if (notifier == -1)
				{
					return;
				}
				inotify_rm_watch(notifier, watch);
			}

			watch_descriptor &operator = (watch_descriptor &&other) BOOST_NOEXCEPT
			{
				boost::swap(notifier, other.notifier);
				boost::swap(watch, other.watch);
				return *this;
			}

		private:

			int notifier = -1;
			int watch = -1;
		};

		struct inotify_observable : private boost::noncopyable
		{
			typedef std::vector<file_notification> element_type;

			inotify_observable();
			explicit inotify_observable(boost::asio::io_service &io);
			watch_descriptor watch(boost::filesystem::path const &target, boost::uint32_t mask);
			watch_descriptor watch(boost::filesystem::path const &target, boost::uint32_t mask, boost::system::error_code &ec);
			void async_get_one(observer<element_type> &receiver);
			void cancel();

		private:

			boost::optional<boost::asio::posix::stream_descriptor> notifier;
			std::vector<char> read_buffer;
			observer<element_type> *receiver_ = nullptr;
		};
	}
}

#endif
<|endoftext|>


<commit_before>// FindDlg.cpp : implementation file
//

#include "stdafx.h"
#include "passwordsafe.h"

#if defined(POCKET_PC)
  #include "pocketpc/resource.h"
#else
  #include "resource.h"
#endif
#include "FindDlg.h"
#include "DboxMain.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CFindDlg dialog

CFindDlg *CFindDlg::self = NULL; // for Singleton pattern

void CFindDlg::Doit(CWnd *pParent)
{
  if (self == NULL) {
    self = new CFindDlg(pParent);
    if (self != NULL)
      if (self->Create(CFindDlg::IDD))
	self->ShowWindow(SW_SHOW);
  } else {
    self->BringWindowToTop();
  }
}

CFindDlg::CFindDlg(CWnd* pParent /*=NULL*/)
  : super(CFindDlg::IDD, pParent), m_indices(NULL),
    m_lastshown(-1), m_numFound(0),
    m_last_search_text(_T("")), m_last_cs_search(FALSE)
{
  //{{AFX_DATA_INIT(CFindDlg)
  m_cs_search = FALSE;
  m_search_text = _T("");
  m_status = _T("");
	//}}AFX_DATA_INIT
}

CFindDlg::~CFindDlg()
{
  delete[] m_indices;
  self = NULL;
}

void CFindDlg::DoDataExchange(CDataExchange* pDX)
{
	super::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CFindDlg)
	DDX_Check(pDX, IDC_FIND_CS, m_cs_search);
	DDX_Text(pDX, IDC_FIND_TEXT, m_search_text);
#if !defined(POCKET_PC)
	DDX_Text(pDX, IDC_STATUS, m_status);
#endif
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CFindDlg, super)
	//{{AFX_MSG_MAP(CFindDlg)
	ON_BN_CLICKED(IDOK, OnFind)
#if defined(POCKET_PC)
	ON_BN_CLICKED(IDCANCEL, OnCancel)
#else
	ON_BN_CLICKED(IDCANCEL, OnClose)
#endif
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFindDlg message handlers

void CFindDlg::OnFind()
{

  DboxMain* pParent = (DboxMain*) GetParent();
  ASSERT(pParent != NULL);

  const int numEntries = pParent->GetNumEntries();

  if (numEntries == 0) {
    // Right Thing would be to disable find menu item if list is empty
    m_status = _T("Password list is empty.");
    UpdateData(FALSE);
    return;
  }

  UpdateData(TRUE);

  if (m_search_text.IsEmpty()) {
    m_status = _T("Please enter a search string");
    UpdateData(FALSE);
    return;
  }

  // If the user changes the search text or cs, then this is a new search:
  if (m_search_text != m_last_search_text ||
      m_cs_search != m_last_cs_search) {
    m_last_search_text = m_search_text;
    m_last_cs_search = m_cs_search;
    m_lastshown = -1;
  }

  if (m_lastshown == -1) {

    if (m_indices != NULL) {
      // take care of the pathological case where someone added or deleted
      // an entry while this dialog box is open
      delete[] m_indices;
    }
    m_indices = new int[numEntries];

    m_numFound = pParent->FindAll(m_search_text, m_cs_search, m_indices);

    switch (m_numFound) {
    case 0:
      m_status = _T("No matches found.");
      break;
    case 1:
      m_status = _T("Found 1 match.");
      break;
    default:
      // {kjp} this kludge is needed because the declaration of CString in <afx.h> defines
      // {kjp} FormatMessage as implemented, but if you take a look at the source for
      // {kjp} CString in strex.cpp you'll see that it's only actully implemented if the
      // {kjp} platform is not WinCE.  Methinks this is a bug in afx.h
#if defined(POCKET_PC)
      m_status.Format( _T("Found %d matches."), m_numFound );
#else
      m_status.FormatMessage(_T("Found %1!d! matches."), m_numFound);
#endif
      break;
    }
    UpdateData(FALSE);
  } // m_lastshown == -1

  // OK, so now we have a (possibly empty) list of items to select.

  if (m_numFound > 0) {
    m_lastshown = (m_lastshown + 1) % m_numFound; //from -1 to 0, cycle afterwards
    pParent->SelectEntry(m_indices[m_lastshown], TRUE);
  }
  if (m_numFound > 1) {
      SetDlgItemText(IDOK, _T("Find Next"));
  }
  // don't call super::OnOK - user will Cancel() to close dbox
}

#if defined(POCKET_PC)
void CFindDlg::OnCancel()
{
	self = NULL;
	super::DestroyWindow();
}
#else
void CFindDlg::OnClose()
{
  self = NULL;
  super::OnCancel();
}
#endif
<commit_msg>[1082510] - Find dialog no longer obscures parent.<commit_after>// FindDlg.cpp : implementation file
//

#include "stdafx.h"
#include "passwordsafe.h"

#if defined(POCKET_PC)
  #include "pocketpc/resource.h"
#else
  #include "resource.h"
#endif
#include "FindDlg.h"
#include "DboxMain.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CFindDlg dialog

CFindDlg *CFindDlg::self = NULL; // for Singleton pattern

void CFindDlg::Doit(CWnd *pParent)
{
  if (self == NULL) {
    self = new CFindDlg(pParent);
    if (self != NULL)
      if (self->Create(CFindDlg::IDD)) {
	RECT myRect, parentRect;
	// move find dialog so that it doesn't overlap its parent
	pParent->GetWindowRect(&parentRect);
	self->GetWindowRect(&myRect);
	// Move the dialog to the right if parent is on left side
	// of screen,and vice versa
	int screenCenter = GetSystemMetrics(SM_CXSCREEN)/2;
	int parentCenter = (parentRect.right + parentRect.left)/2;

	if (parentCenter < screenCenter) {
	  // move right
	  myRect.right = parentRect.right + myRect.right - myRect.left;
	  myRect.left = parentRect.right;
	} else { // move left
	  myRect.left = parentRect.left - (myRect.right - myRect.left);
	  myRect.right = parentRect.left;
	}
	self-> MoveWindow(&myRect);
	self->ShowWindow(SW_SHOW);
      }
  } else {
    self->BringWindowToTop();
  }
}

CFindDlg::CFindDlg(CWnd* pParent /*=NULL*/)
  : super(CFindDlg::IDD, pParent), m_indices(NULL),
    m_lastshown(-1), m_numFound(0),
    m_last_search_text(_T("")), m_last_cs_search(FALSE)
{
  //{{AFX_DATA_INIT(CFindDlg)
  m_cs_search = FALSE;
  m_search_text = _T("");
  m_status = _T("");
	//}}AFX_DATA_INIT
}

CFindDlg::~CFindDlg()
{
  delete[] m_indices;
  self = NULL;
}

void CFindDlg::DoDataExchange(CDataExchange* pDX)
{
	super::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CFindDlg)
	DDX_Check(pDX, IDC_FIND_CS, m_cs_search);
	DDX_Text(pDX, IDC_FIND_TEXT, m_search_text);
#if !defined(POCKET_PC)
	DDX_Text(pDX, IDC_STATUS, m_status);
#endif
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CFindDlg, super)
	//{{AFX_MSG_MAP(CFindDlg)
	ON_BN_CLICKED(IDOK, OnFind)
#if defined(POCKET_PC)
	ON_BN_CLICKED(IDCANCEL, OnCancel)
#else
	ON_BN_CLICKED(IDCANCEL, OnClose)
#endif
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFindDlg message handlers

void CFindDlg::OnFind()
{

  DboxMain* pParent = (DboxMain*) GetParent();
  ASSERT(pParent != NULL);

  const int numEntries = pParent->GetNumEntries();

  if (numEntries == 0) {
    // Right Thing would be to disable find menu item if list is empty
    m_status = _T("Password list is empty.");
    UpdateData(FALSE);
    return;
  }

  UpdateData(TRUE);

  if (m_search_text.IsEmpty()) {
    m_status = _T("Please enter a search string");
    UpdateData(FALSE);
    return;
  }

  // If the user changes the search text or cs, then this is a new search:
  if (m_search_text != m_last_search_text ||
      m_cs_search != m_last_cs_search) {
    m_last_search_text = m_search_text;
    m_last_cs_search = m_cs_search;
    m_lastshown = -1;
  }

  if (m_lastshown == -1) {

    if (m_indices != NULL) {
      // take care of the pathological case where someone added or deleted
      // an entry while this dialog box is open
      delete[] m_indices;
    }
    m_indices = new int[numEntries];

    m_numFound = pParent->FindAll(m_search_text, m_cs_search, m_indices);

    switch (m_numFound) {
    case 0:
      m_status = _T("No matches found.");
      break;
    case 1:
      m_status = _T("Found 1 match.");
      break;
    default:
      // {kjp} this kludge is needed because the declaration of CString in <afx.h> defines
      // {kjp} FormatMessage as implemented, but if you take a look at the source for
      // {kjp} CString in strex.cpp you'll see that it's only actully implemented if the
      // {kjp} platform is not WinCE.  Methinks this is a bug in afx.h
#if defined(POCKET_PC)
      m_status.Format( _T("Found %d matches."), m_numFound );
#else
      m_status.FormatMessage(_T("Found %1!d! matches."), m_numFound);
#endif
      break;
    }
    UpdateData(FALSE);
  } // m_lastshown == -1

  // OK, so now we have a (possibly empty) list of items to select.

  if (m_numFound > 0) {
    m_lastshown = (m_lastshown + 1) % m_numFound; //from -1 to 0, cycle afterwards
    pParent->SelectEntry(m_indices[m_lastshown], TRUE);
  }
  if (m_numFound > 1) {
      SetDlgItemText(IDOK, _T("Find Next"));
  }
  // don't call super::OnOK - user will Cancel() to close dbox
}

#if defined(POCKET_PC)
void CFindDlg::OnCancel()
{
	self = NULL;
	super::DestroyWindow();
}
#else
void CFindDlg::OnClose()
{
  self = NULL;
  super::OnCancel();
}
#endif
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

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

#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "otbImageIOFactory.h"
#include "itkExceptionObject.h"
#include <iostream>

int otbImageIOFactoryNew(int argc, char* argv [])
{
  otb::ImageIOFactory * lImageIOFactory;

  return EXIT_SUCCESS;
}
<commit_msg>WRG: otbImageIOFactoryNew.cxx:29: warning: unused variable lImageIOFactory<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

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

#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "otbImageIOFactory.h"
#include "itkExceptionObject.h"
#include <iostream>

int otbImageIOFactoryNew(int argc, char* argv [])
{
  otb::ImageIOFactory * lImageIOFactory;
  lImageIOFactory = NULL;
  return EXIT_SUCCESS;
}
<|endoftext|>