<commit_before>//============================================================================
// Name        : addTwoNumbers.cpp
// Author      :
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;

struct ListNode {
	int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    	int x, y, sum;
    	int flag = false;
    	x = l1 -> val;
    	y = l2 -> val;
    	sum = x + y;
    	if(sum > 9){
    		sum = sum % 10;
    		flag = true;
    	}
        ListNode* s = new ListNode(sum);
        ListNode* p = s;
        l1 = l1 -> next;
        l2 = l2 -> next;
        while(l1 != NULL || l2 != NULL){
        	x = l1 != NULL ? l1 -> val : 0;
        	y = l2 != NULL ? l2 -> val : 0;
        	sum = x + y;
        	if(flag)
        		sum++;
        	if(sum > 9){
        		sum = sum % 10;
        		flag = true;
        	}else{
        		flag = false;
        	}
        	ListNode* t = new ListNode(sum);
        	p -> next = t;
        	p = t;
        	t = NULL;
        }
        if(flag){
        	ListNode* t = new ListNode(1);
        	p -> next = t;
        	p = t;
        	t = NULL;
        }
        l1 = l1 != NULL ? l1 -> next : NULL;
        l2 = l2 != NULL ? l2 -> next : NULL;
        return s;
    }
};

int main() {
	int val;
	int len1, len2;
	cin >> len1 >> len2;
	cin >> val;
	ListNode* l1 = new ListNode(val);
	ListNode* p = l1;
	for(int i = 0; i < len1; i++){
		cin >> val;
		ListNode* t1 = new ListNode(val);
		p -> next = t1;
		p = t1;
		t1 = NULL;
	}
	ListNode* l2 = new ListNode(val);
	ListNode* p = l2;
	for(int j = 0; j < len2; j++){
		cin >> val;
		ListNode* t2 = new ListNode(val);
		p -> next = t2;
		p = t2;
		t2 = NULL;
	}
	Solution sol;
	ListNode* ans = sol.addTwoNumbers(l1, l2);
	p = ans;
	while(p != NULL){
		cout << p -> val << " ";
		p = p -> next;
	}
	return 0;
}
<commit_msg>modify error about point p<commit_after>//============================================================================
// Name        : addTwoNumbers.cpp
// Author      :
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;

struct ListNode {
	int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    	int x, y, sum;
    	int flag = false;
    	x = l1 -> val;
    	y = l2 -> val;
    	sum = x + y;
    	if(sum > 9){
    		sum = sum % 10;
    		flag = true;
    	}
        ListNode* s = new ListNode(sum);
        ListNode* p = s;
        l1 = l1 -> next;
        l2 = l2 -> next;
        while(l1 != NULL || l2 != NULL){
        	x = l1 != NULL ? l1 -> val : 0;
        	y = l2 != NULL ? l2 -> val : 0;
        	sum = x + y;
        	if(flag)
        		sum++;
        	if(sum > 9){
        		sum = sum % 10;
        		flag = true;
        	}else{
        		flag = false;
        	}
        	ListNode* t = new ListNode(sum);
        	p -> next = t;
        	p = t;
        	t = NULL;
        }
        if(flag){
        	ListNode* t = new ListNode(1);
        	p -> next = t;
        	p = t;
        	t = NULL;
        }
        l1 = l1 != NULL ? l1 -> next : NULL;
        l2 = l2 != NULL ? l2 -> next : NULL;
        return s;
    }
};

int main() {
	int val;
	int len1, len2;
	cin >> len1 >> len2;
	cin >> val;
	ListNode* l1 = new ListNode(val);
	ListNode* p = l1;
	for(int i = 0; i < len1; i++){
		cin >> val;
		ListNode* t1 = new ListNode(val);
		p -> next = t1;
		p = t1;
		t1 = NULL;
	}
	ListNode* l2 = new ListNode(val);
	p = l2;
	for(int j = 0; j < len2; j++){
		cin >> val;
		ListNode* t2 = new ListNode(val);
		p -> next = t2;
		p = t2;
		t2 = NULL;
	}
	Solution sol;
	ListNode* ans = sol.addTwoNumbers(l1, l2);
	p = ans;
	while(p != NULL){
		cout << p -> val << " ";
		p = p -> next;
	}
	return 0;
}
<|endoftext|>


<commit_before>#ifndef PARTICLE_SMOOTHER
#define PARTICLE_SMOOTHER

#include "particle_filter.hpp"
#include <cmath>

namespace mcmc_utilities
{
  /**
     a particle smoother
   */
  template <typename T_p,typename T_state,typename T_obs,typename T_t>
  class particle_smoother
  {
  public:
    typedef typename element_type_trait<T_state>::element_type T_state1;
  private:
    /**
       verbose level, to determine how much information to be outputed to the screen or log file
     */
    int verbose_level;

    /**
       no copy constructor
     */
    particle_smoother(const particle_smoother&);
  public:
    typedef typename element_type_trait<T_state>::element_type stat_element_type;
    typedef typename element_type_trait<T_obs>::element_type obs_element_type;

  private:
    /**
       a inner class for the particle filter, forward filtering
     */
    class smoother_model
      :public pf_model<T_p,T_state,T_obs,T_t>
    {
    private:
      particle_smoother<T_p,T_state,T_obs,T_t>* pps;

    public:
      smoother_model(particle_smoother<T_p,T_state,T_obs,T_t>* _pps)
	:pps(_pps)
      {}

    private:
      T_p do_evol_log_prob(const T_state& x,const T_t& t,const T_state& prev_stat,const T_t& prev_t)const
      {
	return pps->evol_log_prob(x,t,prev_stat,prev_t);
      }

      T_p do_obs_log_prob(const T_obs& y,const T_state& x,const T_t& t)const
      {
	return pps->obs_log_prob(y,x,t);
      }

      std::pair<T_state1,T_state1> do_state_var_range(const T_t& t,const T_state& prev_state,const T_t& prev_t,size_t ndim)const
      {
	return pps->state_var_range(t,prev_state,prev_t,ndim);
      }

      std::vector<T_state1> do_init_points(const T_t& t,const T_state& prev_state,const T_t& prev_t,size_t ndim)const
      {
	return pps->init_points(t,prev_state,prev_t,ndim);
      }
    }sm;

    /**
       backward particle filter model
     */
    class smoother_model_reverse
      :public pf_model<T_p,T_state,T_obs,T_t>
    {
    private:
      particle_smoother<T_p,T_state,T_obs,T_t>* pps;
    public:
      smoother_model_reverse(particle_smoother<T_p,T_state,T_obs,T_t>* _pps)
	:pps(_pps)
      {}

    private:
      T_p do_evol_log_prob(const T_state& x,const T_t& t,const T_state& future_stat,const T_t& future_t)const
      {
	return pps->evol_log_prob_rev(x,t,future_stat,future_t);
      }

      T_p do_obs_log_prob(const T_obs& y,const T_state& x,const T_t& t)const
      {
	return pps->obs_log_prob(y,x,t);
      }

      std::pair<T_state1,T_state1> do_state_var_range(const T_t& t,const T_state& future_state,const T_t& future_t,size_t ndim)const
      {
	return pps->state_var_range_rev(t,future_state,future_t,ndim);
      }

      std::vector<T_state1> do_init_points(const T_t& t,const T_state& future_state,const T_t& future_t,size_t ndim)const
      {
	return pps->init_points_rev(t,future_state,future_t,ndim);
      }
    }sm_rev;
  public:
    /**
       storing all the realizations of particles during the filtering
     */
    std::vector<std::vector<particle<T_p,T_state> > > history;

    /**
       list of time (or other system evolution index)
     */
    std::vector<T_t> t_list;

    /**
       observed quantity list
     */
    std::vector<T_obs> obs_list;
  public:

    /**
       default constructor
     */
    particle_smoother()
      :verbose_level(0),sm(this),sm_rev(this)
    {}

    /**
       destructor
     */
    virtual ~particle_smoother(){}

    /**
       set verbose level
     */
    void set_verbose(int n)
    {
      verbose_level=n;
    }
  public:

    /**
       load initial particle list
     */
    void load(const std::vector<T_obs>& obs,const std::vector<T_t>& t_vec,const std::vector<particle<T_p,T_state> >& ps,T_t t0,base_urand<T_p>& rng)
    {
      history.clear();
      obs_list.clear();
      std::vector<particle<T_p,T_state> > particles(ps);
      //size_t nparticles=ps.size();
      T_t prev_t(t0);
      /**
	 perform a forward particle filter
       */
      for(size_t i=0;i<obs.size();++i)
	{
	  sm.update_sir(obs.at(i),t_vec.at(i),particles,prev_t,rng);
	  history.push_back(particles);
	  t_list.push_back(t_vec[i]);
	  obs_list.push_back(obs[i]);
	  if(verbose_level)
	    {
	      std::cerr<<"loaded "<<i<<" of "<<obs.size()<<std::endl;
	    }
	}
    }

    /**
       backward simulation
     */
    void backward_simulate(base_urand<T_p>& rng)
    {
      std::vector<particle<T_p,T_state> > particles(history.back());
      //size_t nparticles=particles.size();
      T_t future_t(t_list.back());

      for(int i=obs_list.size()-2;i>=0;--i)
	{
	  sm_rev.update_sir(obs_list.at(i),t_list.at(i),particles,future_t,rng);
	  history[i]=particles;
	  if(verbose_level)
	    {
	      std::cerr<<"bs:"<<(obs_list.size()-1-i)<<" of "<<obs_list.size()<<std::endl;
	    }
	}
    }

    /**
       forward simulation
     */
    void forward_simulate(base_urand<T_p>& rng)
    {
      std::vector<particle<T_p,T_state> > particles(history.front());
      //size_t nparticles=particles.size();
      T_t prev_t(t_list.front());

      for(int i=1;i!=obs_list.size();++i)
	{
	  sm.update_sir(obs_list.at(i),t_list.at(i),particles,prev_t,rng);
	  history[i]=particles;
	  if(verbose_level)
	    {
	      std::cerr<<"fs:"<<i<<" of "<<obs_list.size()<<std::endl;
	    }
	}
    }

    /**
       draw realizations from previously simulated particles
     */
    std::vector<T_state> draw_realization(base_urand<T_p>& rng)
    {
      std::vector<T_state> result(history.size());
      for(int i=history.size()-1;i>=0;--i)
	{
	  std::vector<T_p> weights(history[i].size());
	  if(false&&i!=history.size()-1)
	    {
	      for(int j=0;j<history[i].size();++j)
		{
		  weights[j]=history[i][j].weight*std::exp(evol_log_prob(result[i+1],t_list[i+1],history[i][j].state,t_list[i]));
		}
	    }
	  else
	    {
	      for(int j=0;j<history[i].size();++j)
		{
		  weights[j]=history[i][j].weight;
		}
	    }
	  std::vector<T_p> weight_cdf(history[i].size());
	  weight_cdf[0]=weights[0];
	  for(size_t j=1;j<weights.size();++j)
	    {
	      weight_cdf[j]=weight_cdf[j-1]+weights[j];
	    }
	  T_p p=rng()*weight_cdf.back();
	  size_t n=0;
	  bool changed=false;
	  for(size_t j=0;j<weight_cdf.size();++j)
	    {
	      if(weight_cdf[j]>=p)
		{
		  n=j;
		  changed=true;
		  break;
		}
	    }
	  assert(changed);
	  result[i]=history[i][n].state;
	}
      return result;
    }

  public:
    /**
       following function members are the evolution model, observation model variable range, initial points.
       see particle_filter.hpp for the details
     */

    T_p evol_log_prob(const T_state& x,const T_t& t,const T_state& prev_state,const T_t& prev_t)const
    {
      return do_evol_log_prob(x,t,prev_state,prev_t);
    }

    T_p evol_log_prob_rev(const T_state& x,const T_t& t,const T_state& future_state,const T_t& future_t)const
    {
      return do_evol_log_prob_rev(x,t,future_state,future_t);
    }

    T_p obs_log_prob(const T_obs& y,const T_state& x,const T_t& t)const
    {
      return do_obs_log_prob(y,x,t);
    }

    std::pair<T_state1,T_state1> state_var_range(const T_t& t,const T_state& prev_state,const T_t& prev_t,size_t ndim)const
    {
      return do_state_var_range(t,prev_state,prev_t,ndim);
    }

    std::pair<T_state1,T_state1> state_var_range_rev(const T_t& t,const T_state& future_state,const T_t& future_t,size_t ndim)const
    {
      return do_state_var_range_rev(t,future_state,future_t,ndim);
    }

    std::vector<T_state1> init_points(const T_t& t,const T_state& prev_state,const T_t& prev_t,size_t ndim)const
    {
      return do_init_points(t,prev_state,prev_t,ndim);
    }

    std::vector<T_state1> init_points_rev(const T_t& t,const T_state& prev_state,const T_t& prev_t,size_t ndim)const
    {
      return do_init_points_rev(t,prev_state,prev_t,ndim);
    }

  private:
    virtual T_p do_evol_log_prob(const T_state& x,const T_t& t,const T_state& prev_stat,const T_t& prev_t)const=0;
    virtual T_p do_evol_log_prob_rev(const T_state& x,const T_t& t,const T_state& prev_stat,const T_t& prev_t)const=0;
    virtual T_p do_obs_log_prob(const T_obs& y,const T_state& x,const T_t& t)const=0;
    virtual std::pair<T_state1,T_state1> do_state_var_range(const T_t& t,const T_state& prev_state,const T_t& prev_t,size_t ndim)const=0;
    virtual std::pair<T_state1,T_state1> do_state_var_range_rev(const T_t& t,const T_state& future_state,const T_t& future_t,size_t ndim)const=0;

    virtual std::vector<T_state1> do_init_points(const T_t& t,const T_state& prev_state,const T_t& prev_t,size_t ndim)const
    {
      return std::vector<T_state1>();
    }

    virtual std::vector<T_state1> do_init_points_rev(const T_t& t,const T_state& future_state,const T_t& future_t,size_t ndim)const
    {
      return std::vector<T_state1>();
    }
  };
}

#endif
<commit_msg>make draw_realization to be const in particle_smoother.hpp<commit_after>#ifndef PARTICLE_SMOOTHER
#define PARTICLE_SMOOTHER

#include "particle_filter.hpp"
#include <cmath>

namespace mcmc_utilities
{
  /**
     a particle smoother
   */
  template <typename T_p,typename T_state,typename T_obs,typename T_t>
  class particle_smoother
  {
  public:
    typedef typename element_type_trait<T_state>::element_type T_state1;
  private:
    /**
       verbose level, to determine how much information to be outputed to the screen or log file
     */
    int verbose_level;

    /**
       no copy constructor
     */
    particle_smoother(const particle_smoother&);
  public:
    typedef typename element_type_trait<T_state>::element_type stat_element_type;
    typedef typename element_type_trait<T_obs>::element_type obs_element_type;

  private:
    /**
       a inner class for the particle filter, forward filtering
     */
    class smoother_model
      :public pf_model<T_p,T_state,T_obs,T_t>
    {
    private:
      particle_smoother<T_p,T_state,T_obs,T_t>* pps;

    public:
      smoother_model(particle_smoother<T_p,T_state,T_obs,T_t>* _pps)
	:pps(_pps)
      {}

    private:
      T_p do_evol_log_prob(const T_state& x,const T_t& t,const T_state& prev_stat,const T_t& prev_t)const
      {
	return pps->evol_log_prob(x,t,prev_stat,prev_t);
      }

      T_p do_obs_log_prob(const T_obs& y,const T_state& x,const T_t& t)const
      {
	return pps->obs_log_prob(y,x,t);
      }

      std::pair<T_state1,T_state1> do_state_var_range(const T_t& t,const T_state& prev_state,const T_t& prev_t,size_t ndim)const
      {
	return pps->state_var_range(t,prev_state,prev_t,ndim);
      }

      std::vector<T_state1> do_init_points(const T_t& t,const T_state& prev_state,const T_t& prev_t,size_t ndim)const
      {
	return pps->init_points(t,prev_state,prev_t,ndim);
      }
    }sm;

    /**
       backward particle filter model
     */
    class smoother_model_reverse
      :public pf_model<T_p,T_state,T_obs,T_t>
    {
    private:
      particle_smoother<T_p,T_state,T_obs,T_t>* pps;
    public:
      smoother_model_reverse(particle_smoother<T_p,T_state,T_obs,T_t>* _pps)
	:pps(_pps)
      {}

    private:
      T_p do_evol_log_prob(const T_state& x,const T_t& t,const T_state& future_stat,const T_t& future_t)const
      {
	return pps->evol_log_prob_rev(x,t,future_stat,future_t);
      }

      T_p do_obs_log_prob(const T_obs& y,const T_state& x,const T_t& t)const
      {
	return pps->obs_log_prob(y,x,t);
      }

      std::pair<T_state1,T_state1> do_state_var_range(const T_t& t,const T_state& future_state,const T_t& future_t,size_t ndim)const
      {
	return pps->state_var_range_rev(t,future_state,future_t,ndim);
      }

      std::vector<T_state1> do_init_points(const T_t& t,const T_state& future_state,const T_t& future_t,size_t ndim)const
      {
	return pps->init_points_rev(t,future_state,future_t,ndim);
      }
    }sm_rev;
  public:
    /**
       storing all the realizations of particles during the filtering
     */
    std::vector<std::vector<particle<T_p,T_state> > > history;

    /**
       list of time (or other system evolution index)
     */
    std::vector<T_t> t_list;

    /**
       observed quantity list
     */
    std::vector<T_obs> obs_list;
  public:

    /**
       default constructor
     */
    particle_smoother()
      :verbose_level(0),sm(this),sm_rev(this)
    {}

    /**
       destructor
     */
    virtual ~particle_smoother(){}

    /**
       set verbose level
     */
    void set_verbose(int n)
    {
      verbose_level=n;
    }
  public:

    /**
       load initial particle list
     */
    void load(const std::vector<T_obs>& obs,const std::vector<T_t>& t_vec,const std::vector<particle<T_p,T_state> >& ps,T_t t0,base_urand<T_p>& rng)
    {
      history.clear();
      obs_list.clear();
      std::vector<particle<T_p,T_state> > particles(ps);
      //size_t nparticles=ps.size();
      T_t prev_t(t0);
      /**
	 perform a forward particle filter
       */
      for(size_t i=0;i<obs.size();++i)
	{
	  sm.update_sir(obs.at(i),t_vec.at(i),particles,prev_t,rng);
	  history.push_back(particles);
	  t_list.push_back(t_vec[i]);
	  obs_list.push_back(obs[i]);
	  if(verbose_level)
	    {
	      std::cerr<<"loaded "<<i<<" of "<<obs.size()<<std::endl;
	    }
	}
    }

    /**
       backward simulation
     */
    void backward_simulate(base_urand<T_p>& rng)
    {
      std::vector<particle<T_p,T_state> > particles(history.back());
      //size_t nparticles=particles.size();
      T_t future_t(t_list.back());

      for(int i=obs_list.size()-2;i>=0;--i)
	{
	  sm_rev.update_sir(obs_list.at(i),t_list.at(i),particles,future_t,rng);
	  history[i]=particles;
	  if(verbose_level)
	    {
	      std::cerr<<"bs:"<<(obs_list.size()-1-i)<<" of "<<obs_list.size()<<std::endl;
	    }
	}
    }

    /**
       forward simulation
     */
    void forward_simulate(base_urand<T_p>& rng)
    {
      std::vector<particle<T_p,T_state> > particles(history.front());
      //size_t nparticles=particles.size();
      T_t prev_t(t_list.front());

      for(int i=1;i!=obs_list.size();++i)
	{
	  sm.update_sir(obs_list.at(i),t_list.at(i),particles,prev_t,rng);
	  history[i]=particles;
	  if(verbose_level)
	    {
	      std::cerr<<"fs:"<<i<<" of "<<obs_list.size()<<std::endl;
	    }
	}
    }

    /**
       draw realizations from previously simulated particles
     */
    std::vector<T_state> draw_realization(base_urand<T_p>& rng)const
    {
      std::vector<T_state> result(history.size());
      for(int i=history.size()-1;i>=0;--i)
	{
	  std::vector<T_p> weights(history[i].size());
	  if(false&&i!=history.size()-1)
	    {
	      for(int j=0;j<history[i].size();++j)
		{
		  weights[j]=history[i][j].weight*std::exp(evol_log_prob(result[i+1],t_list[i+1],history[i][j].state,t_list[i]));
		}
	    }
	  else
	    {
	      for(int j=0;j<history[i].size();++j)
		{
		  weights[j]=history[i][j].weight;
		}
	    }
	  std::vector<T_p> weight_cdf(history[i].size());
	  weight_cdf[0]=weights[0];
	  for(size_t j=1;j<weights.size();++j)
	    {
	      weight_cdf[j]=weight_cdf[j-1]+weights[j];
	    }
	  T_p p=rng()*weight_cdf.back();
	  size_t n=0;
	  bool changed=false;
	  for(size_t j=0;j<weight_cdf.size();++j)
	    {
	      if(weight_cdf[j]>=p)
		{
		  n=j;
		  changed=true;
		  break;
		}
	    }
	  assert(changed);
	  result[i]=history[i][n].state;
	}
      return result;
    }

  public:
    /**
       following function members are the evolution model, observation model variable range, initial points.
       see particle_filter.hpp for the details
     */

    T_p evol_log_prob(const T_state& x,const T_t& t,const T_state& prev_state,const T_t& prev_t)const
    {
      return do_evol_log_prob(x,t,prev_state,prev_t);
    }

    T_p evol_log_prob_rev(const T_state& x,const T_t& t,const T_state& future_state,const T_t& future_t)const
    {
      return do_evol_log_prob_rev(x,t,future_state,future_t);
    }

    T_p obs_log_prob(const T_obs& y,const T_state& x,const T_t& t)const
    {
      return do_obs_log_prob(y,x,t);
    }

    std::pair<T_state1,T_state1> state_var_range(const T_t& t,const T_state& prev_state,const T_t& prev_t,size_t ndim)const
    {
      return do_state_var_range(t,prev_state,prev_t,ndim);
    }

    std::pair<T_state1,T_state1> state_var_range_rev(const T_t& t,const T_state& future_state,const T_t& future_t,size_t ndim)const
    {
      return do_state_var_range_rev(t,future_state,future_t,ndim);
    }

    std::vector<T_state1> init_points(const T_t& t,const T_state& prev_state,const T_t& prev_t,size_t ndim)const
    {
      return do_init_points(t,prev_state,prev_t,ndim);
    }

    std::vector<T_state1> init_points_rev(const T_t& t,const T_state& prev_state,const T_t& prev_t,size_t ndim)const
    {
      return do_init_points_rev(t,prev_state,prev_t,ndim);
    }

  private:
    virtual T_p do_evol_log_prob(const T_state& x,const T_t& t,const T_state& prev_stat,const T_t& prev_t)const=0;
    virtual T_p do_evol_log_prob_rev(const T_state& x,const T_t& t,const T_state& prev_stat,const T_t& prev_t)const=0;
    virtual T_p do_obs_log_prob(const T_obs& y,const T_state& x,const T_t& t)const=0;
    virtual std::pair<T_state1,T_state1> do_state_var_range(const T_t& t,const T_state& prev_state,const T_t& prev_t,size_t ndim)const=0;
    virtual std::pair<T_state1,T_state1> do_state_var_range_rev(const T_t& t,const T_state& future_state,const T_t& future_t,size_t ndim)const=0;

    virtual std::vector<T_state1> do_init_points(const T_t& t,const T_state& prev_state,const T_t& prev_t,size_t ndim)const
    {
      return std::vector<T_state1>();
    }

    virtual std::vector<T_state1> do_init_points_rev(const T_t& t,const T_state& future_state,const T_t& future_t,size_t ndim)const
    {
      return std::vector<T_state1>();
    }
  };
}

#endif
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/// \author James Hughes
/// \date   September 2012

#include <iostream>
#include <QMouseEvent>
#include <arc-look-at/ArcLookAt.hpp>

#include "GLWidget.h"

namespace Spire = CPM_SPIRE_NS;

namespace CPM_QT_GLVIEW_NS {

//------------------------------------------------------------------------------
GLWidget::GLWidget(GLCallback init, GLCallback update, const QGLFormat& format) :
    QGLWidget(format),
    mContext(new GLContext(this)),
    mCallbackFunction(update),
    mArcLookAt(new CPM_LOOK_AT_NS::ArcLookAt)
{
  std::vector<std::string> shaderSearchDirs;
  shaderSearchDirs.push_back("shaders");

  // Create an instance of spire and hook it up to a timer.
  mSpire = std::shared_ptr<Spire::Interface>(
      new Spire::Interface(mContext, shaderSearchDirs));
  mTimer = new QTimer(this);
  connect(mTimer, SIGNAL(timeout()), this, SLOT(updateRenderer()));
  mTimer->start(35);

  // Let the client initialize their graphics code.
  init(mSpire, glm::mat4(), mPerspective);

  // We must disable auto buffer swap on the 'paintEvent'.
  setAutoBufferSwap(false);
}

//------------------------------------------------------------------------------
GLWidget::~GLWidget()
{
  if (mSpire != nullptr)
  {
    mSpire.reset();
  }
}

//------------------------------------------------------------------------------
void GLWidget::closeEvent(QCloseEvent *evt)
{
  if (mSpire != nullptr)
  {
    mSpire.reset();
  }
  QGLWidget::closeEvent(evt);
}

//------------------------------------------------------------------------------
void GLWidget::resizeGL(int width, int height)
{
  mSpire->makeCurrent();
  GL(glViewport(0, 0, static_cast<GLsizei>(width), static_cast<GLsizei>(height)));

  // Build the perspective matrix.
  float aspect = static_cast<float>(mScreenWidth) /
                 static_cast<float>(mScreenHeight);
  mPerspective = glm::perspective(getDefaultFOVY(), aspect, getDefaultZNear(), getDefaultZFar());
}

//------------------------------------------------------------------------------
void GLWidget::initializeGL()
{

}

//------------------------------------------------------------------------------
void GLWidget::updateRenderer()
{
  mContext->makeCurrent();    // Required on windows...

  // Do not even attempt to render if the framebuffer is not complete.
  // This can happen when the rendering window is hidden (in SCIRun5 for
  // example);
  if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
    return;

  if (mCallbackFunction)
    mCallbackFunction(mSpire, mArcLookAt->getWorldViewTransform(), mPerspective);
}

//------------------------------------------------------------------------------
glm::vec2 GLWidget::calculateScreenSpaceCoords(const glm::ivec2& mousePos)
{
  float windowOriginX = 0.0f;
  float windowOriginY = 0.0f;

  // Transform incoming mouse coordinates into screen space.
  glm::vec2 mouseScreenSpace;
  mouseScreenSpace.x = 2.0f * (static_cast<float>(mousePos.x) - windowOriginX)
      / static_cast<float>(mScreenWidth) - 1.0f;
  mouseScreenSpace.y = 2.0f * (static_cast<float>(mousePos.y) - windowOriginY)
      / static_cast<float>(mScreenHeight) - 1.0f;
  mouseScreenSpace.y = -mouseScreenSpace.y;

  return mouseScreenSpace;
}

//------------------------------------------------------------------------------
void GLWidget::mouseMoveEvent(QMouseEvent* event)
{
  glm::vec2 screenSpace = calculateScreenSpaceCoords(glm::ivec2(event->x(), event->y()));
  if (event->buttons() & Qt::LeftButton)
    mArcLookAt->doRotation(screenSpace);
  else if (event->buttons() & Qt::RightButton)
    mArcLookAt->doPan(screenSpace);
}

//------------------------------------------------------------------------------
void GLWidget::mousePressEvent(QMouseEvent* event)
{
  glm::vec2 screenSpace = calculateScreenSpaceCoords(glm::ivec2(event->x(), event->y()));
  mArcLookAt->doReferenceDown(screenSpace);
}

//------------------------------------------------------------------------------
void GLWidget::mouseReleaseEvent(QMouseEvent*)
{
}

//------------------------------------------------------------------------------
void GLWidget::wheelEvent(QWheelEvent* event)
{
  mArcLookAt->doZoom(static_cast<float>(event->delta()) / 100.0f);
}

} // namespace CPM_QT_GLVIEW_NS

<commit_msg>Fix buffer swap.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/// \author James Hughes
/// \date   September 2012

#include <iostream>
#include <QMouseEvent>
#include <arc-look-at/ArcLookAt.hpp>

#include "GLWidget.h"

namespace Spire = CPM_SPIRE_NS;

namespace CPM_QT_GLVIEW_NS {

//------------------------------------------------------------------------------
GLWidget::GLWidget(GLCallback init, GLCallback update, const QGLFormat& format) :
    QGLWidget(format),
    mContext(new GLContext(this)),
    mCallbackFunction(update),
    mArcLookAt(new CPM_LOOK_AT_NS::ArcLookAt)
{
  std::vector<std::string> shaderSearchDirs;
  shaderSearchDirs.push_back("shaders");

  // Create an instance of spire and hook it up to a timer.
  mSpire = std::shared_ptr<Spire::Interface>(
      new Spire::Interface(mContext, shaderSearchDirs));
  mTimer = new QTimer(this);
  connect(mTimer, SIGNAL(timeout()), this, SLOT(updateRenderer()));
  mTimer->start(35);

  // Let the client initialize their graphics code.
  init(mSpire, glm::mat4(), mPerspective);

  // We must disable auto buffer swap on the 'paintEvent'.
  setAutoBufferSwap(false);
}

//------------------------------------------------------------------------------
GLWidget::~GLWidget()
{
  if (mSpire != nullptr)
  {
    mSpire.reset();
  }
}

//------------------------------------------------------------------------------
void GLWidget::closeEvent(QCloseEvent *evt)
{
  if (mSpire != nullptr)
  {
    mSpire.reset();
  }
  QGLWidget::closeEvent(evt);
}

//------------------------------------------------------------------------------
void GLWidget::resizeGL(int width, int height)
{
  mSpire->makeCurrent();
  GL(glViewport(0, 0, static_cast<GLsizei>(width), static_cast<GLsizei>(height)));

  mScreenWidth = width;
  mScreenHeight = height;

  // Build the perspective matrix.
  float aspect = static_cast<float>(mScreenWidth) /
                 static_cast<float>(mScreenHeight);
  mPerspective = glm::perspective(getDefaultFOVY(), aspect, getDefaultZNear(), getDefaultZFar());
}

//------------------------------------------------------------------------------
void GLWidget::initializeGL()
{

}

//------------------------------------------------------------------------------
void GLWidget::updateRenderer()
{
  mContext->makeCurrent();

  // Do not even attempt to render if the framebuffer is not complete.
  // This can happen when the rendering window is hidden (in SCIRun5 for
  // example);
  if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
    return;

  if (mCallbackFunction)
    mCallbackFunction(mSpire, mArcLookAt->getWorldViewTransform(), mPerspective);

  mContext->swapBuffers();
}

//------------------------------------------------------------------------------
glm::vec2 GLWidget::calculateScreenSpaceCoords(const glm::ivec2& mousePos)
{
  float windowOriginX = 0.0f;
  float windowOriginY = 0.0f;

  // Transform incoming mouse coordinates into screen space.
  glm::vec2 mouseScreenSpace;
  mouseScreenSpace.x = 2.0f * (static_cast<float>(mousePos.x) - windowOriginX)
      / static_cast<float>(mScreenWidth) - 1.0f;
  mouseScreenSpace.y = 2.0f * (static_cast<float>(mousePos.y) - windowOriginY)
      / static_cast<float>(mScreenHeight) - 1.0f;
  mouseScreenSpace.y = -mouseScreenSpace.y;

  return mouseScreenSpace;
}

//------------------------------------------------------------------------------
void GLWidget::mouseMoveEvent(QMouseEvent* event)
{
  glm::vec2 screenSpace = calculateScreenSpaceCoords(glm::ivec2(event->x(), event->y()));
  if (event->buttons() & Qt::LeftButton)
    mArcLookAt->doRotation(screenSpace);
  else if (event->buttons() & Qt::RightButton)
    mArcLookAt->doPan(screenSpace);
}

//------------------------------------------------------------------------------
void GLWidget::mousePressEvent(QMouseEvent* event)
{
  glm::vec2 screenSpace = calculateScreenSpaceCoords(glm::ivec2(event->x(), event->y()));
  mArcLookAt->doReferenceDown(screenSpace);
}

//------------------------------------------------------------------------------
void GLWidget::mouseReleaseEvent(QMouseEvent*)
{
}

//------------------------------------------------------------------------------
void GLWidget::wheelEvent(QWheelEvent* event)
{
  mArcLookAt->doZoom(static_cast<float>(event->delta()) / 100.0f);
}

} // namespace CPM_QT_GLVIEW_NS

<|endoftext|>


<commit_before>/** \brief Utility for deleting partial or entire MARC records based on an input list.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2015 Universitätsbiblothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <algorithm>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <unordered_set>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include "Compiler.h"
#include "MarcUtil.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"

static void Usage() __attribute__((noreturn));

static void Usage() {
    std::cerr << "Usage: " << progname << " deletion_list input_marc output_marc\n";
    std::exit(EXIT_FAILURE);
}

static std::set<std::string> unknown_types;

// Use the following indicators to select whether to fully delete a record or remove its local data
// For a description of indicators
// c.f. https://wiki.bsz-bw.de/doku.php?id=v-team:daten:datendienste:sekkor (20160426)
const char FULL_RECORD_DELETE_INDICATORS[] = { 'A', 'B', 'C', 'D', 'E' };
const char LOCAL_DATA_DELETE_INDICATORS[] = { '3', '4', '5', '9' };
const size_t MIN_LINE_LENGTH = 21;

void ExtractDeletionIds(File * const deletion_list, std::unordered_set <std::string> * const delete_full_record_ids,
                        std::unordered_set <std::string> *const local_deletion_ids)
{

    const size_t PPN_LENGTH = 9;
    const size_t PPN_START_INDEX = 12;
    const size_t SEPARATOR_INDEX = PPN_START_INDEX - 1;

    unsigned line_no(0);
loop_top:
    while (not deletion_list->eof()) {
	const std::string line(StringUtil::Trim(deletion_list->getline()));
        ++line_no;
	if (unlikely(line.empty())) // Ignore empty lines.
	    continue;
        if (line.length() < PPN_START_INDEX)
            Error("short line " + std::to_string(line_no) + " in deletion list file \"" + deletion_list->getPath()
		  + "\": \"" + line + "\"!");
        for (char indicator : FULL_RECORD_DELETE_INDICATORS) {
            if (line[SEPARATOR_INDEX] == indicator) {
                delete_full_record_ids->insert(line.substr(PPN_START_INDEX)); // extract PPN
                goto loop_top;
            }
        }
        for (char indicator : LOCAL_DATA_DELETE_INDICATORS) {
            if (line[SEPARATOR_INDEX] == indicator) {
                if (line.length() < MIN_LINE_LENGTH)
                    Error("unexpected line length " + std::to_string(line.length()) + " for local entry on line "
                          + std::to_string(line_no) + " in deletion list file \"" + deletion_list->getPath() + "\"!");
                local_deletion_ids->insert(line.substr(PPN_START_INDEX, PPN_LENGTH)); // extract ELN
                goto loop_top;
            }
        }
        unknown_types.emplace(line.substr(SEPARATOR_INDEX, 1));
    }
}

int MatchLocalID(const std::unordered_set <std::string> &local_ids, const std::vector <DirectoryEntry> &dir_entries,
                 const std::vector <std::string> &field_data) {
    for (size_t i(0); i < dir_entries.size(); ++i) {
        if (dir_entries[i].getTag() != "LOK")
            continue;

        const Subfields subfields(field_data[i]);
        if (not subfields.hasSubfield('0'))
            continue;

        const std::string subfield_contents(subfields.getFirstSubfieldValue('0'));
        if (not StringUtil::StartsWith(subfield_contents, "001 ")
            or local_ids.find(subfield_contents.substr(4)) == local_ids.end())
            continue;

        return i;
    }

    return -1;
}

class MatchTag {
    const std::string tag_to_match_;
public:
    explicit MatchTag(const std::string &tag_to_match) : tag_to_match_(tag_to_match) { }

    bool operator()(const DirectoryEntry &dir_entry) const { return dir_entry.getTag() == tag_to_match_; }
};

/** \brief Deletes LOK sections if their pseudo tags are found in "local_deletion_ids"
 *  \return True if at least one local section has been deleted, else false.
 */
bool DeleteLocalSections(const std::vector<DirectoryEntry> &dir_entries, const std::vector<std::string> &fields,
			 const std::unordered_set <std::string> &local_deletion_ids, MarcUtil::Record * const record)
{
    bool modified(false);

    ssize_t start_local_match;
    while ((start_local_match = MatchLocalID(local_deletion_ids, dir_entries, fields)) != -1) {
	// We now expect a field "000" before the current "001" field.  (This is just a sanity check!):
	--start_local_match;
	if (start_local_match <= 0)
	    Error("weird data structure (1)!");
	const Subfields subfields1(fields[start_local_match]);
	if (not subfields1.hasSubfield('0')
	    or not StringUtil::StartsWith(subfields1.getFirstSubfieldValue('0'), "000 "))
	    Error("missing or empty local field \"000\"! (EPN: "
		  + fields[start_local_match + 1].substr(8) + ", PPN: " + fields[0] + ")");

	// Now we need to find the index one past the end of the local record.  This would
	// be either the "000" field of the next local record or one past the end of the overall
	// MARC record.
	size_t end_local_match(start_local_match + 2);
	while (end_local_match < fields.size()) {
	    const Subfields subfields2(fields[end_local_match]);
	    if (not subfields2.hasSubfield('0'))
		Error("weird data structure (2)!");
	    if (StringUtil::StartsWith(subfields2.getFirstSubfieldValue('0'), "000 "))
		break;

	    ++end_local_match;
	}

        for (ssize_t dir_entry_index(end_local_match - 1); dir_entry_index >= start_local_match; --dir_entry_index)
	    record->deleteField(dir_entry_index);

	modified = true;
    }

    return modified;
}

void ProcessRecords(const std::unordered_set <std::string> &title_deletion_ids,
                    const std::unordered_set <std::string> &local_deletion_ids, File *const input,
                    File *const output)
{
    unsigned total_record_count(0), deleted_record_count(0), modified_record_count(0);
    while (MarcUtil::Record record = MarcUtil::Record::BinaryFactory(input)) {
        ++total_record_count;

	const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries());
        if (dir_entries[0].getTag() != "001")
            Error("First field is not \"001\"!");

	const std::vector<std::string> &fields(record.getFields());
        if (title_deletion_ids.find(fields[0]) != title_deletion_ids.end())
            ++deleted_record_count;
        else { // Look for local (LOK) data sets that may need to be deleted.
            if (not DeleteLocalSections(dir_entries, fields, local_deletion_ids, &record))
		record.write(output);
            else {
                // Only keep records that still have at least one "LOK" tag:
                if (std::find_if(dir_entries.cbegin(), dir_entries.cend(), MatchTag("LOK")) == dir_entries.cend())
                    ++deleted_record_count;
                else {
                    ++modified_record_count;
		    record.write(output);
                }
            }
        }
    }

    std::cerr << "Read " << total_record_count << " records.\n";
    std::cerr << "Deleted " << deleted_record_count << " records.\n";
    std::cerr << "Modified " << modified_record_count << " records.\n";
}

int main(int argc, char *argv[]) {
    progname = argv[0];

    if (argc != 4)
        Usage();

    const std::string deletion_list_filename(argv[1]);
    File deletion_list(deletion_list_filename, "r");
    if (not deletion_list)
        Error("can't open \"" + deletion_list_filename + "\" for reading!");

    std::unordered_set <std::string> title_deletion_ids, local_deletion_ids;
    ExtractDeletionIds(&deletion_list, &title_deletion_ids, &local_deletion_ids);

    const std::string marc_input_filename(argv[2]);
    File marc_input(marc_input_filename, "r");
    if (not marc_input)
        Error("can't open \"" + marc_input_filename + "\" for reading!");

    const std::string marc_output_filename(argv[3]);
    File marc_output(marc_output_filename, "w");
    if (not marc_output)
        Error("can't open \"" + marc_output_filename + "\" for writing!");

    try {
        ProcessRecords(title_deletion_ids, local_deletion_ids, &marc_input, &marc_output);
    } catch (const std::exception &e) {
        Error("Caught exception: " + std::string(e.what()));
    }

    if (not unknown_types.empty())
        Error("Unknown types: " + StringUtil::Join(unknown_types, ", "));
}
<commit_msg>Removed deleting records that have no local data after modification<commit_after>/** \brief Utility for deleting partial or entire MARC records based on an input list.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2015 Universitätsbiblothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <algorithm>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <unordered_set>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include "Compiler.h"
#include "MarcUtil.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"

static void Usage() __attribute__((noreturn));

static void Usage() {
    std::cerr << "Usage: " << progname << " deletion_list input_marc output_marc\n";
    std::exit(EXIT_FAILURE);
}

static std::set<std::string> unknown_types;

// Use the following indicators to select whether to fully delete a record or remove its local data
// For a description of indicators
// c.f. https://wiki.bsz-bw.de/doku.php?id=v-team:daten:datendienste:sekkor (20160426)
const char FULL_RECORD_DELETE_INDICATORS[] = { 'A', 'B', 'C', 'D', 'E' };
const char LOCAL_DATA_DELETE_INDICATORS[] = { '3', '4', '5', '9' };
const size_t MIN_LINE_LENGTH = 21;

void ExtractDeletionIds(File * const deletion_list, std::unordered_set <std::string> * const delete_full_record_ids,
                        std::unordered_set <std::string> *const local_deletion_ids)
{

    const size_t PPN_LENGTH = 9;
    const size_t PPN_START_INDEX = 12;
    const size_t SEPARATOR_INDEX = PPN_START_INDEX - 1;

    unsigned line_no(0);
loop_top:
    while (not deletion_list->eof()) {
	const std::string line(StringUtil::Trim(deletion_list->getline()));
        ++line_no;
	if (unlikely(line.empty())) // Ignore empty lines.
	    continue;
        if (line.length() < PPN_START_INDEX)
            Error("short line " + std::to_string(line_no) + " in deletion list file \"" + deletion_list->getPath()
		  + "\": \"" + line + "\"!");
        for (char indicator : FULL_RECORD_DELETE_INDICATORS) {
            if (line[SEPARATOR_INDEX] == indicator) {
                delete_full_record_ids->insert(line.substr(PPN_START_INDEX)); // extract PPN
                goto loop_top;
            }
        }
        for (char indicator : LOCAL_DATA_DELETE_INDICATORS) {
            if (line[SEPARATOR_INDEX] == indicator) {
                if (line.length() < MIN_LINE_LENGTH)
                    Error("unexpected line length " + std::to_string(line.length()) + " for local entry on line "
                          + std::to_string(line_no) + " in deletion list file \"" + deletion_list->getPath() + "\"!");
                local_deletion_ids->insert(line.substr(PPN_START_INDEX, PPN_LENGTH)); // extract ELN
                goto loop_top;
            }
        }
        unknown_types.emplace(line.substr(SEPARATOR_INDEX, 1));
    }
}

int MatchLocalID(const std::unordered_set <std::string> &local_ids, const std::vector <DirectoryEntry> &dir_entries,
                 const std::vector <std::string> &field_data) {
    for (size_t i(0); i < dir_entries.size(); ++i) {
        if (dir_entries[i].getTag() != "LOK")
            continue;

        const Subfields subfields(field_data[i]);
        if (not subfields.hasSubfield('0'))
            continue;

        const std::string subfield_contents(subfields.getFirstSubfieldValue('0'));
        if (not StringUtil::StartsWith(subfield_contents, "001 ")
            or local_ids.find(subfield_contents.substr(4)) == local_ids.end())
            continue;

        return i;
    }

    return -1;
}

class MatchTag {
    const std::string tag_to_match_;
public:
    explicit MatchTag(const std::string &tag_to_match) : tag_to_match_(tag_to_match) { }

    bool operator()(const DirectoryEntry &dir_entry) const { return dir_entry.getTag() == tag_to_match_; }
};

/** \brief Deletes LOK sections if their pseudo tags are found in "local_deletion_ids"
 *  \return True if at least one local section has been deleted, else false.
 */
bool DeleteLocalSections(const std::vector<DirectoryEntry> &dir_entries, const std::vector<std::string> &fields,
			 const std::unordered_set <std::string> &local_deletion_ids, MarcUtil::Record * const record)
{
    bool modified(false);

    ssize_t start_local_match;
    while ((start_local_match = MatchLocalID(local_deletion_ids, dir_entries, fields)) != -1) {
	// We now expect a field "000" before the current "001" field.  (This is just a sanity check!):
	--start_local_match;
	if (start_local_match <= 0)
	    Error("weird data structure (1)!");
	const Subfields subfields1(fields[start_local_match]);
	if (not subfields1.hasSubfield('0')
	    or not StringUtil::StartsWith(subfields1.getFirstSubfieldValue('0'), "000 "))
	    Error("missing or empty local field \"000\"! (EPN: "
		  + fields[start_local_match + 1].substr(8) + ", PPN: " + fields[0] + ")");

	// Now we need to find the index one past the end of the local record.  This would
	// be either the "000" field of the next local record or one past the end of the overall
	// MARC record.
	size_t end_local_match(start_local_match + 2);
	while (end_local_match < fields.size()) {
	    const Subfields subfields2(fields[end_local_match]);
	    if (not subfields2.hasSubfield('0'))
		Error("weird data structure (2)!");
	    if (StringUtil::StartsWith(subfields2.getFirstSubfieldValue('0'), "000 "))
		break;

	    ++end_local_match;
	}

        for (ssize_t dir_entry_index(end_local_match - 1); dir_entry_index >= start_local_match; --dir_entry_index)
	    record->deleteField(dir_entry_index);

	modified = true;
    }

    return modified;
}

void ProcessRecords(const std::unordered_set <std::string> &title_deletion_ids,
                    const std::unordered_set <std::string> &local_deletion_ids, File *const input,
                    File *const output)
{
    unsigned total_record_count(0), deleted_record_count(0), modified_record_count(0);
    while (MarcUtil::Record record = MarcUtil::Record::BinaryFactory(input)) {
        ++total_record_count;

	const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries());
        if (dir_entries[0].getTag() != "001")
            Error("First field is not \"001\"!");

	const std::vector<std::string> &fields(record.getFields());
        if (title_deletion_ids.find(fields[0]) != title_deletion_ids.end())
            ++deleted_record_count;
        else { // Look for local (LOK) data sets that may need to be deleted.
            if (not DeleteLocalSections(dir_entries, fields, local_deletion_ids, &record))
		record.write(output);
            else {
                // Unlike former versions we no longer delete records without local data
                ++modified_record_count;
		record.write(output);
            }
        }
    }

    std::cerr << "Read " << total_record_count << " records.\n";
    std::cerr << "Deleted " << deleted_record_count << " records.\n";
    std::cerr << "Modified " << modified_record_count << " records.\n";
}

int main(int argc, char *argv[]) {
    progname = argv[0];

    if (argc != 4)
        Usage();

    const std::string deletion_list_filename(argv[1]);
    File deletion_list(deletion_list_filename, "r");
    if (not deletion_list)
        Error("can't open \"" + deletion_list_filename + "\" for reading!");

    std::unordered_set <std::string> title_deletion_ids, local_deletion_ids;
    ExtractDeletionIds(&deletion_list, &title_deletion_ids, &local_deletion_ids);

    const std::string marc_input_filename(argv[2]);
    File marc_input(marc_input_filename, "r");
    if (not marc_input)
        Error("can't open \"" + marc_input_filename + "\" for reading!");

    const std::string marc_output_filename(argv[3]);
    File marc_output(marc_output_filename, "w");
    if (not marc_output)
        Error("can't open \"" + marc_output_filename + "\" for writing!");

    try {
        ProcessRecords(title_deletion_ids, local_deletion_ids, &marc_input, &marc_output);
    } catch (const std::exception &e) {
        Error("Caught exception: " + std::string(e.what()));
    }

    if (not unknown_types.empty())
        Error("Unknown types: " + StringUtil::Join(unknown_types, ", "));
}
<|endoftext|>


<commit_before>/** \brief Utility for deleting partial or entire MARC records based on an input list.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2015 Universitätsbiblothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <algorithm>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <unordered_set>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include "MarcUtil.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"

static void Usage() __attribute__((noreturn));

static void Usage() {
    std::cerr << "Usage: " << progname << " deletion_list input_marc output_marc\n";
    std::exit(EXIT_FAILURE);
}

void ExtractDeletionIds(FILE *const deletion_list, std::unordered_set <std::string> *const title_deletion_ids,
                        std::unordered_set <std::string> *const local_deletion_ids) {
    unsigned line_no(0);
    char line[100];
    while (std::fgets(line, sizeof(line), deletion_list) != nullptr) {
        ++line_no;
        size_t line_length(std::strlen(line));
        if (line_length < 13)
            Error("short line in deletion list file: \"" + std::string(line) + "\"!");
        if (line[line_length - 1] == '\n') {
            line[line_length - 1] = '\0';
            --line_length;
        }
        if (line[11] == 'A')
            title_deletion_ids->insert(line + 12); // extract PPN
        else if (line[11] == '9') {
            if (line_length != 25)
                Error("unexpected line length for local entry on line " + std::to_string(line_no) + "!");
            local_deletion_ids->insert(std::string(line).substr(12, 9)); // extract ELN
        }
    }

    std::fclose(deletion_list);
}

int MatchLocalID(const std::unordered_set <std::string> &local_ids, const std::vector <DirectoryEntry> &dir_entries,
                 const std::vector <std::string> &field_data) {
    for (size_t i(0); i < dir_entries.size(); ++i) {
        if (dir_entries[i].getTag() != "LOK")
            continue;

        const Subfields subfields(field_data[i]);
        if (not subfields.hasSubfield('0'))
            continue;

        const std::string subfield_contents(subfields.getFirstSubfieldValue('0'));
        if (not StringUtil::StartsWith(subfield_contents, "001 ")
            or local_ids.find(subfield_contents.substr(4)) == local_ids.end())
            continue;

        return i;
    }

    return -1;
}

class MatchTag {
    const std::string tag_to_match_;
public:
    explicit MatchTag(const std::string &tag_to_match) : tag_to_match_(tag_to_match) { }

    bool operator()(const DirectoryEntry &dir_entry) const { return dir_entry.getTag() == tag_to_match_; }
};

void ProcessRecords(const std::unordered_set <std::string> &title_deletion_ids,
                    const std::unordered_set <std::string> &local_deletion_ids, FILE *const input,
                    FILE *const output) {
    unsigned total_record_count(0), deleted_record_count(0), modified_record_count(0);
    while (MarcUtil::Record record = MarcUtil::Record(input)) {
        ++total_record_count;

	const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries());
        if (dir_entries[0].getTag() != "001")
            Error("First field is not \"001\"!");

        ssize_t start_local_match;
	const std::vector<std::string> &fields(record.getFields());
        if (title_deletion_ids.find(fields[0]) != title_deletion_ids.end()) {
            ++deleted_record_count;
            std::cout << "Deleted record with ID " << fields[0] << '\n';
        } else { // Look for local data sets that may need to be deleted.
            bool modified(false);
            while ((start_local_match = MatchLocalID(local_deletion_ids, dir_entries, fields)) != -1) {
                // We now expect a field "000" before the current "001" field:
                --start_local_match;
                if (start_local_match <= 0)
                    Error("weird data structure (1)!");
                const Subfields subfields1(fields[start_local_match]);
                if (not subfields1.hasSubfield('0')
                    or not StringUtil::StartsWith(subfields1.getFirstSubfieldValue('0'), "000 "))
                    Error("missing or empty local field \"000\"! (EPN: "
                          + fields[start_local_match + 1].substr(8) + ", PPN: " + fields[0] + ")");

                // Now we need to find the index one past the end of the local record.  This would
                // be either the "000" field of the next local record or one past the end of the overall
                // MARC record.
                bool found_next_000(false);
                size_t end_local_match(start_local_match + 2);
                while (end_local_match < fields.size()) {
                    const Subfields subfields2(fields[end_local_match]);
                    if (not subfields2.hasSubfield('0'))
                        Error("weird data (2)!");
                    if (StringUtil::StartsWith(subfields2.getFirstSubfieldValue('0'), "000 ")) {
                        found_next_000 = true;
                        break;
                    }

                    ++end_local_match;
                }
                if (not found_next_000)
                    ++end_local_match;

                for (ssize_t dir_entry(end_local_match - 1); dir_entry >= start_local_match; --dir_entry)
                    record.deleteField(dir_entry);

                modified = true;
            }

            if (not modified)
		record.write(output);
            else {
                // Only keep records that still have at least one "LOK" tag:
                if (std::find_if(dir_entries.cbegin(), dir_entries.cend(), MatchTag("LOK")) == dir_entries.cend())
                    ++deleted_record_count;
                else {
                    ++modified_record_count;
		    record.write(output);
                }
            }
        }
    }

    std::cerr << "Read " << total_record_count << " records.\n";
    std::cerr << "Deleted " << deleted_record_count << " records.\n";
    std::cerr << "Modified " << modified_record_count << " records.\n";

    std::fclose(input);
    std::fclose(output);
}

int main(int argc, char *argv[]) {
    progname = argv[0];

    if (argc != 4)
        Usage();

    const std::string deletion_list_filename(argv[1]);
    FILE *deletion_list = std::fopen(deletion_list_filename.c_str(), "rb");
    if (deletion_list == nullptr)
        Error("can't open \"" + deletion_list_filename + "\" for reading!");

    std::unordered_set <std::string> title_deletion_ids, local_deletion_ids;
    ExtractDeletionIds(deletion_list, &title_deletion_ids, &local_deletion_ids);

    const std::string marc_input_filename(argv[2]);
    FILE *marc_input = std::fopen(marc_input_filename.c_str(), "rb");
    if (marc_input == nullptr)
        Error("can't open \"" + marc_input_filename + "\" for reading!");

    const std::string marc_output_filename(argv[3]);
    FILE *marc_output = std::fopen(marc_output_filename.c_str(), "wb");
    if (marc_output == nullptr)
        Error("can't open \"" + marc_output_filename + "\" for writing!");

    try {
        ProcessRecords(title_deletion_ids, local_deletion_ids, marc_input, marc_output);
    } catch (const std::exception &e) {
        Error("Caught exception: " + std::string(e.what()));
    }
}
<commit_msg>Fixed an off-by-two error.<commit_after>/** \brief Utility for deleting partial or entire MARC records based on an input list.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2015 Universitätsbiblothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <algorithm>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <unordered_set>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include "MarcUtil.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"

static void Usage() __attribute__((noreturn));

static void Usage() {
    std::cerr << "Usage: " << progname << " deletion_list input_marc output_marc\n";
    std::exit(EXIT_FAILURE);
}

void ExtractDeletionIds(FILE *const deletion_list, std::unordered_set <std::string> *const title_deletion_ids,
                        std::unordered_set <std::string> *const local_deletion_ids) {
    unsigned line_no(0);
    char line[100];
    while (std::fgets(line, sizeof(line), deletion_list) != nullptr) {
        ++line_no;
        size_t line_length(std::strlen(line));
        if (line_length < 13)
            Error("short line in deletion list file: \"" + std::string(line) + "\"!");
        if (line[line_length - 1] == '\n') {
            line[line_length - 1] = '\0';
            --line_length;
        }
        if (line[11] == 'A')
            title_deletion_ids->insert(line + 12); // extract PPN
        else if (line[11] == '9') {
            if (line_length != 25)
                Error("unexpected line length for local entry on line " + std::to_string(line_no) + "!");
            local_deletion_ids->insert(std::string(line).substr(12, 9)); // extract ELN
        }
    }

    std::fclose(deletion_list);
}

int MatchLocalID(const std::unordered_set <std::string> &local_ids, const std::vector <DirectoryEntry> &dir_entries,
                 const std::vector <std::string> &field_data) {
    for (size_t i(0); i < dir_entries.size(); ++i) {
        if (dir_entries[i].getTag() != "LOK")
            continue;

        const Subfields subfields(field_data[i]);
        if (not subfields.hasSubfield('0'))
            continue;

        const std::string subfield_contents(subfields.getFirstSubfieldValue('0'));
        if (not StringUtil::StartsWith(subfield_contents, "001 ")
            or local_ids.find(subfield_contents.substr(4)) == local_ids.end())
            continue;

        return i;
    }

    return -1;
}

class MatchTag {
    const std::string tag_to_match_;
public:
    explicit MatchTag(const std::string &tag_to_match) : tag_to_match_(tag_to_match) { }

    bool operator()(const DirectoryEntry &dir_entry) const { return dir_entry.getTag() == tag_to_match_; }
};

/** \brief Deletes LOK sections if their pseudo tags are found in "local_deletion_ids"
 *  \return True if at least one local section has been deleted, else false.
 */
bool DeleteLocalSections(const std::vector<DirectoryEntry> &dir_entries, const std::vector<std::string> &fields,
			 const std::unordered_set <std::string> &local_deletion_ids, MarcUtil::Record * const record)
{
    bool modified(false);

    ssize_t start_local_match;
    while ((start_local_match = MatchLocalID(local_deletion_ids, dir_entries, fields)) != -1) {
	// We now expect a field "000" before the current "001" field.  (This is just a sanity check!):
	--start_local_match;
	if (start_local_match <= 0)
	    Error("weird data structure (1)!");
	const Subfields subfields1(fields[start_local_match]);
	if (not subfields1.hasSubfield('0')
	    or not StringUtil::StartsWith(subfields1.getFirstSubfieldValue('0'), "000 "))
	    Error("missing or empty local field \"000\"! (EPN: "
		  + fields[start_local_match + 1].substr(8) + ", PPN: " + fields[0] + ")");

	// Now we need to find the index one past the end of the local record.  This would
	// be either the "000" field of the next local record or one past the end of the overall
	// MARC record.
	size_t end_local_match(start_local_match + 2);
	while (end_local_match < fields.size()) {
	    const Subfields subfields2(fields[end_local_match]);
	    if (not subfields2.hasSubfield('0'))
		Error("weird data structure (2)!");
	    if (StringUtil::StartsWith(subfields2.getFirstSubfieldValue('0'), "000 ")) {
		--end_local_match;
		break;
	    }

	    ++end_local_match;
	}

	for (ssize_t dir_entry_index(end_local_match - 1); dir_entry_index >= start_local_match; --dir_entry_index)
	    record->deleteField(dir_entry_index);

	modified = true;
    }

    return modified;
}

void ProcessRecords(const std::unordered_set <std::string> &title_deletion_ids,
                    const std::unordered_set <std::string> &local_deletion_ids, FILE *const input,
                    FILE *const output) {
    unsigned total_record_count(0), deleted_record_count(0), modified_record_count(0);
    while (MarcUtil::Record record = MarcUtil::Record(input)) {
        ++total_record_count;

	const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries());
        if (dir_entries[0].getTag() != "001")
            Error("First field is not \"001\"!");

	const std::vector<std::string> &fields(record.getFields());
        if (title_deletion_ids.find(fields[0]) != title_deletion_ids.end()) {
            ++deleted_record_count;
            std::cout << "Deleted record with ID " << fields[0] << '\n';
        } else { // Look for local (LOK) data sets that may need to be deleted.
            if (not DeleteLocalSections(dir_entries, fields, local_deletion_ids, &record))
		record.write(output);
            else {
                // Only keep records that still have at least one "LOK" tag:
                if (std::find_if(dir_entries.cbegin(), dir_entries.cend(), MatchTag("LOK")) == dir_entries.cend())
                    ++deleted_record_count;
                else {
                    ++modified_record_count;
		    record.write(output);
                }
            }
        }
    }

    std::cerr << "Read " << total_record_count << " records.\n";
    std::cerr << "Deleted " << deleted_record_count << " records.\n";
    std::cerr << "Modified " << modified_record_count << " records.\n";

    std::fclose(input);
    std::fclose(output);
}

int main(int argc, char *argv[]) {
    progname = argv[0];

    if (argc != 4)
        Usage();

    const std::string deletion_list_filename(argv[1]);
    FILE *deletion_list = std::fopen(deletion_list_filename.c_str(), "rb");
    if (deletion_list == nullptr)
        Error("can't open \"" + deletion_list_filename + "\" for reading!");

    std::unordered_set <std::string> title_deletion_ids, local_deletion_ids;
    ExtractDeletionIds(deletion_list, &title_deletion_ids, &local_deletion_ids);

    const std::string marc_input_filename(argv[2]);
    FILE *marc_input = std::fopen(marc_input_filename.c_str(), "rb");
    if (marc_input == nullptr)
        Error("can't open \"" + marc_input_filename + "\" for reading!");

    const std::string marc_output_filename(argv[3]);
    FILE *marc_output = std::fopen(marc_output_filename.c_str(), "wb");
    if (marc_output == nullptr)
        Error("can't open \"" + marc_output_filename + "\" for writing!");

    try {
        ProcessRecords(title_deletion_ids, local_deletion_ids, marc_input, marc_output);
    } catch (const std::exception &e) {
        Error("Caught exception: " + std::string(e.what()));
    }
}
<|endoftext|>


<commit_before><commit_msg>:construction: chore(Parallel): updated the implementation of parallel gc with channels<commit_after><|endoftext|>


<commit_before>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#ifndef DO_GRAPHICS_EVENTS_HPP
#define DO_GRAPHICS_EVENTS_HPP

#include <DO/Core/EigenExtension.hpp>

namespace DO {

  /*!
    \ingroup Graphics

    \defgroup Event Event handling functions
    \todo Investigate if it is useful. I don't remember.
    @{
   */

  enum EventType {
    NO_EVENT,
    KEY_PRESSED /*= QEvent::KeyPress*/,
    KEY_RELEASED /*= QEvent::KeyRelease*/,
    MOUSE_PRESSED /*= QEvent::MouseButtonPress*/,
    MOUSE_RELEASED /*= QEvent::MouseButtonRelease*/,
    MOUSE_PRESSED_AND_MOVED /*= QEvent::MouseMove*/
  };

  //! Values are copy-pasted from Qt's documentation.
  enum KeyModifierType {
    KEY_NOMODIFIER = 0x00000000,
    KEY_SHIFT = 0x02000000,
    KEY_CTRL = 0x04000000,
    KEY_ALT = 0x08000000,
    KEY_META = 0x10000000
  };

  //! Values are copy-pasted from Qt's documentation.
  enum KeyType {
    KEY_UNKNOWN = 0x01ffffff,
    // Special keys.
    KEY_ESCAPE = 0x01000000,
    KEY_TAB =	0x01000001,
    KEY_BACKTAB = 0x01000002,
    KEY_BACKSPACE = 0x01000003,
    KEY_RETURN = 0x01000004,
    KEY_ENTER = 0x01000005,
    KEY_INSERT = 0x01000006,
    KEY_DELETE = 0x01000007,
    KEY_PAUSE = 0x01000008,
    KEY_PRINT = 0x01000009,
    KEY_SYSREQ = 0x0100000a,
    KEY_CLEAR = 0x0100000b,
    KEY_HOME = 0x01000010,
    KEY_END = 0x01000011,
    // Arrow keys.
    KEY_LEFT = 0x01000012,
    KEY_UP = 0x01000013,
    KEY_RIGHT = 0x01000014,
    KEY_DOWN = 0x01000015,
    KEY_PAGEUP = 0x01000016,
    KEY_PAGEDOWN = 0x01000017
  };

  //! Values are copy-pasted from Qt's documentation.
  enum MouseButton {
    MOUSE_NO_BUTTON = 0x00000000 /*Qt::NoButton*/,
    MOUSE_LEFT_BUTTON = 0x00000001 /*Qt::LeftButton*/,
    MOUSE_RIGHT_BUTTON = 0x00000002 /*Qt::RightButton*/,
    MOUSE_MIDDLE_BUTTON = 0x00000004 /*Qt::MiddleButton*/,
  };

  struct Event
  {
    EventType type;
    int buttons;
    Point2i mousePos;
    int key;
    int keyModifiers;
  };

  inline Event noEvent()
  {
    Event e;
    e.type = NO_EVENT;
    e.key = KEY_UNKNOWN;
    e.keyModifiers = KEY_NOMODIFIER;
    e.buttons = MOUSE_NO_BUTTON;
    e.mousePos << -1, -1;
    return e;
  }

  inline Event keyPressed(int key, int keyModifiers = KEY_NOMODIFIER)
  {
    Event e;
    e.type = KEY_PRESSED;
    e.key = key;
    e.keyModifiers = keyModifiers;
    e.buttons = MOUSE_NO_BUTTON;
    e.mousePos << -1, -1;
    return e;
  }

  inline Event keyReleased(int key, int keyModifiers = KEY_NOMODIFIER)
  {
    Event e;
    e.type = KEY_RELEASED;
    e.key = key;
    e.keyModifiers = keyModifiers;
    e.buttons = MOUSE_NO_BUTTON;
    e.mousePos << -1, -1;
    return e;
  }

  inline Event mousePressed(int x, int y, int buttons,
                            int keyModifiers = KEY_NOMODIFIER)
  {
    Event e;
    e.type = MOUSE_PRESSED;
    e.key = KEY_UNKNOWN;
    e.keyModifiers = keyModifiers;
    e.buttons = buttons;
    e.mousePos << x, y;
    return e;
  }

  inline Event mouseReleased(int x, int y, int buttons,
                             int keyModifiers = KEY_NOMODIFIER)
  {
    Event e;
    e.type = MOUSE_RELEASED;
    e.key = KEY_UNKNOWN;
    e.keyModifiers = keyModifiers;
    e.buttons = buttons;
    e.mousePos << x, y;
    return e;
  }

  inline Event mouseMoved(int x, int y, int buttons,
                          int keyModifiers = KEY_NOMODIFIER)
  {
    Event e;
    e.type = MOUSE_PRESSED_AND_MOVED;
    e.key = KEY_UNKNOWN;
    e.keyModifiers = keyModifiers;
    e.buttons = buttons;
    e.mousePos << x, y;
    return e;
  }

}  /* namespace DO */

#endif /* DO_GRAPHICS_EVENTS_HPP */
<commit_msg>Fix warnings and reformat code a little bit.<commit_after>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#ifndef DO_GRAPHICS_EVENTS_HPP
#define DO_GRAPHICS_EVENTS_HPP

#include <DO/Core/EigenExtension.hpp>

namespace DO {

  /*!
    \ingroup Graphics

    \defgroup Event Event handling functions
    \todo Investigate if it is useful. I don't remember.
    @{
   */

  //! \brief I/O event types.
  enum EventType
  {
    NO_EVENT,
    KEY_PRESSED,            /*! QEvent::KeyPress */
    KEY_RELEASED,           /*! QEvent::KeyRelease */
    MOUSE_PRESSED,          /*! QEvent::MouseButtonPress */
    MOUSE_RELEASED,         /*! QEvent::MouseButtonRelease */
    MOUSE_PRESSED_AND_MOVED /*! QEvent::MouseMove */
  };

  //! Key modifiers values (copy-pasted from Qt's documentation).
  enum KeyModifierType
  {
    KEY_NOMODIFIER  = 0x00000000,
    KEY_SHIFT       = 0x02000000,
    KEY_CTRL        = 0x04000000,
    KEY_ALT         = 0x08000000,
    KEY_META        = 0x10000000
  };

  //! Key type values (copy-pasted from Qt's documentation).
  enum KeyType
  {
    KEY_UNKNOWN   = 0x01ffffff,
    // Special keys.
    KEY_ESCAPE    = 0x01000000,
    KEY_TAB       =	0x01000001,
    KEY_BACKTAB   = 0x01000002,
    KEY_BACKSPACE = 0x01000003,
    KEY_RETURN    = 0x01000004,
    KEY_ENTER     = 0x01000005,
    KEY_INSERT    = 0x01000006,
    KEY_DELETE    = 0x01000007,
    KEY_PAUSE     = 0x01000008,
    KEY_PRINT     = 0x01000009,
    KEY_SYSREQ    = 0x0100000a,
    KEY_CLEAR     = 0x0100000b,
    KEY_HOME      = 0x01000010,
    KEY_END       = 0x01000011,
    // Arrow keys.
    KEY_LEFT      = 0x01000012,
    KEY_UP        = 0x01000013,
    KEY_RIGHT     = 0x01000014,
    KEY_DOWN      = 0x01000015,
    KEY_PAGEUP    = 0x01000016,
    KEY_PAGEDOWN  = 0x01000017
  };

  //! Mouse button values (copy-pasted from Qt's documentation).
  enum MouseButton
  {
    MOUSE_NO_BUTTON     = 0x00000000, /*! Qt::NoButton */
    MOUSE_LEFT_BUTTON   = 0x00000001, /*! Qt::LeftButton */
    MOUSE_RIGHT_BUTTON  = 0x00000002, /*! Qt::RightButton */
    MOUSE_MIDDLE_BUTTON = 0x00000004  /*! Qt::MiddleButton */
  };

  //! \brief I/O event structure.
  struct Event
  {
    EventType type;
    int buttons;
    Point2i mousePos;
    int key;
    int keyModifiers;
  };

  //! \brief Helper function to return a "no-event" Event.
  inline Event noEvent()
  {
    Event e;
    e.type = NO_EVENT;
    e.key = KEY_UNKNOWN;
    e.keyModifiers = KEY_NOMODIFIER;
    e.buttons = MOUSE_NO_BUTTON;
    e.mousePos << -1, -1;
    return e;
  }

  //! \brief Helper function to return a "key-pressed" Event.
  inline Event keyPressed(int key, int keyModifiers = KEY_NOMODIFIER)
  {
    Event e;
    e.type = KEY_PRESSED;
    e.key = key;
    e.keyModifiers = keyModifiers;
    e.buttons = MOUSE_NO_BUTTON;
    e.mousePos << -1, -1;
    return e;
  }

  //! \brief Helper function to return a "key-released" Event.
  inline Event keyReleased(int key, int keyModifiers = KEY_NOMODIFIER)
  {
    Event e;
    e.type = KEY_RELEASED;
    e.key = key;
    e.keyModifiers = keyModifiers;
    e.buttons = MOUSE_NO_BUTTON;
    e.mousePos << -1, -1;
    return e;
  }

  //! \brief Helper function to return a "mouse-pressed" Event.
  inline Event mousePressed(int x, int y, int buttons,
                            int keyModifiers = KEY_NOMODIFIER)
  {
    Event e;
    e.type = MOUSE_PRESSED;
    e.key = KEY_UNKNOWN;
    e.keyModifiers = keyModifiers;
    e.buttons = buttons;
    e.mousePos << x, y;
    return e;
  }

  //! \brief Helper function to return a "mouse-pressed" Event.
  inline Event mouseReleased(int x, int y, int buttons,
                             int keyModifiers = KEY_NOMODIFIER)
  {
    Event e;
    e.type = MOUSE_RELEASED;
    e.key = KEY_UNKNOWN;
    e.keyModifiers = keyModifiers;
    e.buttons = buttons;
    e.mousePos << x, y;
    return e;
  }

  //! \brief Helper function to return a "mouse-moved" Event.
  inline Event mouseMoved(int x, int y, int buttons,
                          int keyModifiers = KEY_NOMODIFIER)
  {
    Event e;
    e.type = MOUSE_PRESSED_AND_MOVED;
    e.key = KEY_UNKNOWN;
    e.keyModifiers = keyModifiers;
    e.buttons = buttons;
    e.mousePos << x, y;
    return e;
  }

}  /* namespace DO */

#endif /* DO_GRAPHICS_EVENTS_HPP */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AxisItemConverter.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 00:20:55 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef CHART_AXISITEMCONVERTER_HXX
#define CHART_AXISITEMCONVERTER_HXX

#ifndef _COM_SUN_STAR_CHART2_XAXIS_HPP_
#include <com/sun/star/chart2/XAxis.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_EXPLICITSCALEDATA_HPP_
#include <com/sun/star/chart2/ExplicitScaleData.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_EXPLICITINCREMENTDATA_HPP_
#include <com/sun/star/chart2/ExplicitIncrementData.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_
#include <com/sun/star/awt/Size.hpp>
#endif

#include "ItemConverter.hxx"
#include "chartview/NumberFormatterWrapper.hxx"

#include <vector>
#include <memory>

class SdrModel;

namespace chart
{
namespace wrapper
{

class AxisItemConverter : public ::comphelper::ItemConverter
{
public:
    AxisItemConverter(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet > & rPropertySet,
        SfxItemPool& rItemPool,
        SdrModel& rDrawModel,
        NumberFormatterWrapper * pNumFormatter,
        ::com::sun::star::chart2::ExplicitScaleData * pScale = NULL,
        ::com::sun::star::chart2::ExplicitIncrementData * pIncrement = NULL,
        double * pExplicitOrigin = NULL,
        ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize =
            ::std::auto_ptr< ::com::sun::star::awt::Size >() );
    virtual ~AxisItemConverter();

    virtual void FillItemSet( SfxItemSet & rOutItemSet ) const;
    virtual bool ApplyItemSet( const SfxItemSet & rItemSet );

protected:
    virtual const USHORT * GetWhichPairs() const;
    virtual bool GetItemPropertyName( USHORT nWhichId, ::rtl::OUString & rOutName ) const;

    virtual void FillSpecialItem( USHORT nWhichId, SfxItemSet & rOutItemSet ) const
        throw( ::com::sun::star::uno::Exception );
    virtual bool ApplySpecialItem( USHORT nWhichId, const SfxItemSet & rItemSet )
        throw( ::com::sun::star::uno::Exception );

private:
    ::std::vector< ItemConverter * >               m_aConverters;
    ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::XAxis >  m_xAxis;
    ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::XBoundedCoordinateSystem >
                                                   m_xCoordinateSystem;
    sal_Int32                                      m_nDimension;
    NumberFormatterWrapper *                       m_pNumberFormatterWrapper;

    ::com::sun::star::chart2::ExplicitScaleData *       m_pExplicitScale;
    ::com::sun::star::chart2::ExplicitIncrementData *   m_pExplicitIncrement;
    double *                                                m_pExplicitOrigin;
};

} //  namespace wrapper
} //  namespace chart

// CHART_AXISITEMCONVERTER_HXX
#endif
<commit_msg>INTEGRATION: CWS chart2mst3 (1.6.4); FILE MERGED 2007/03/19 15:04:26 iha 1.6.4.7: #i73605#, #i75389# use correct numberformat for scale tabpage and numbers tabpage 2006/09/24 09:12:53 iha 1.6.4.6: #i61970# correct implementation of axis at 2006/04/10 12:25:06 iha 1.6.4.5: api restructure axis, grids, scales and increments 2005/10/13 17:38:46 iha 1.6.4.4: renamed BoundedCoordinateSystem to CoordinateSystem 2005/10/07 11:24:17 bm 1.6.4.3: RESYNC: (1.6-1.7); FILE MERGED 2005/07/12 12:56:57 bm 1.6.4.2: use named properties for gradients etc. in chart model 2004/05/07 09:14:06 bm 1.6.4.1: enabling member-ids for all items<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AxisItemConverter.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 17:52:11 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef CHART_AXISITEMCONVERTER_HXX
#define CHART_AXISITEMCONVERTER_HXX

#ifndef _COM_SUN_STAR_CHART2_EXPLICITSCALEDATA_HPP_
#include <com/sun/star/chart2/ExplicitScaleData.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_EXPLICITINCREMENTDATA_HPP_
#include <com/sun/star/chart2/ExplicitIncrementData.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XAXIS_HPP_
#include <com/sun/star/chart2/XAxis.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XCHARTDOCUMENT_HPP_
#include <com/sun/star/chart2/XChartDocument.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_
#include <com/sun/star/awt/Size.hpp>
#endif

#include "ItemConverter.hxx"

#include <vector>
#include <memory>

class SdrModel;

namespace chart
{
namespace wrapper
{

class AxisItemConverter : public ::comphelper::ItemConverter
{
public:
    AxisItemConverter(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet > & rPropertySet,
        SfxItemPool& rItemPool,
        SdrModel& rDrawModel,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XChartDocument > & xChartDoc,
        ::com::sun::star::chart2::ExplicitScaleData * pScale = NULL,
        ::com::sun::star::chart2::ExplicitIncrementData * pIncrement = NULL,
        ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize =
            ::std::auto_ptr< ::com::sun::star::awt::Size >() );
    virtual ~AxisItemConverter();

    virtual void FillItemSet( SfxItemSet & rOutItemSet ) const;
    virtual bool ApplyItemSet( const SfxItemSet & rItemSet );

protected:
    virtual const USHORT * GetWhichPairs() const;
    virtual bool GetItemProperty( tWhichIdType nWhichId, tPropertyNameWithMemberId & rOutProperty ) const;

    virtual void FillSpecialItem( USHORT nWhichId, SfxItemSet & rOutItemSet ) const
        throw( ::com::sun::star::uno::Exception );
    virtual bool ApplySpecialItem( USHORT nWhichId, const SfxItemSet & rItemSet )
        throw( ::com::sun::star::uno::Exception );

private:
    ::std::vector< ItemConverter * >               m_aConverters;
    ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::XAxis >  m_xAxis;

    ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::XChartDocument >      m_xChartDoc;

    ::com::sun::star::chart2::ExplicitScaleData *       m_pExplicitScale;
    ::com::sun::star::chart2::ExplicitIncrementData *   m_pExplicitIncrement;
};

} //  namespace wrapper
} //  namespace chart

// CHART_AXISITEMCONVERTER_HXX
#endif
<|endoftext|>