<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

#ifndef FEATURE_STYLE_PROCESSOR_HPP
#define FEATURE_STYLE_PROCESSOR_HPP

// mapnik
#include <mapnik/envelope.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/map.hpp>
#include <mapnik/attribute_collector.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/scale_denominator.hpp>
// boost
#include <boost/progress.hpp>
//stl
#include <vector>

namespace mapnik
{
   template <typename Processor>
   class feature_style_processor
   {
         struct symbol_dispatch : public boost::static_visitor<>
         {
               symbol_dispatch (Processor & output,
                                Feature const& f,
                                proj_transform const& prj_trans)
                  : output_(output),
                    f_(f),
                    prj_trans_(prj_trans)  {}

               template <typename T>
               void operator () (T const& sym) const
               {
                  output_.process(sym,f_,prj_trans_);
               }

               Processor & output_;
               Feature const& f_;
               proj_transform const& prj_trans_;
         };
      public:
         feature_style_processor(Map const& m)
            : m_(m) {}

         void apply()
         {
#ifdef MAPNIK_DEBUG
            boost::progress_timer t(std::clog);
#endif
            Processor & p = static_cast<Processor&>(*this);
            p.start_map_processing(m_);

            try
            {
               projection proj(m_.srs()); // map projection
               double scale_denom = scale_denominator(m_,proj.is_geographic());
#ifdef MAPNIK_DEBUG
               std::clog << "scale denominator = " << scale_denom << "\n";
#endif
               std::vector<Layer>::const_iterator itr = m_.layers().begin();
               std::vector<Layer>::const_iterator end = m_.layers().end();

               while (itr != end)
               {
                  if (itr->isVisible(scale_denom))
                  {
                     apply_to_layer(*itr, p, proj, scale_denom);
                  }
                  ++itr;
               }
            }
            catch (proj_init_error& ex)
            {
               std::clog << "proj_init_error:" << ex.what() << "\n";
            }

            p.end_map_processing(m_);
         }
      private:
         void apply_to_layer(Layer const& lay, Processor & p,
                             projection const& proj0,double scale_denom)
         {
            p.start_layer_processing(lay);
            boost::shared_ptr<datasource> ds=lay.datasource();
            if (ds)
            {
               Envelope<double> const& ext=m_.getCurrentExtent();
               projection proj1(lay.srs());
               proj_transform prj_trans(proj0,proj1);

               Envelope<double> layer_ext = lay.envelope();
               double lx0 = layer_ext.minx();
               double ly0 = layer_ext.miny();
               double lz0 = 0.0;
               double lx1 = layer_ext.maxx();
               double ly1 = layer_ext.maxy();
               double lz1 = 0.0;
               // back project layers extent into main map projection
               prj_trans.backward(lx0,ly0,lz0);
               prj_trans.backward(lx1,ly1,lz1);

               // if no intersection then nothing to do for layer
               if ( lx0 > ext.maxx() || lx1 < ext.minx() || ly0 > ext.maxy() || ly1 < ext.miny() )
               {
                  return;
               }

               // clip query bbox
               lx0 = std::max(ext.minx(),lx0);
               ly0 = std::max(ext.miny(),ly0);
               lx1 = std::min(ext.maxx(),lx1);
               ly1 = std::min(ext.maxy(),ly1);

               prj_trans.forward(lx0,ly0,lz0);
               prj_trans.forward(lx1,ly1,lz1);
               Envelope<double> bbox(lx0,ly0,lx1,ly1);

               double resolution = m_.getWidth()/bbox.width();
               query q(bbox,resolution); //BBOX query

               std::vector<std::string> const& style_names = lay.styles();
               std::vector<std::string>::const_iterator stylesIter = style_names.begin();
               std::vector<std::string>::const_iterator stylesEnd = style_names.end();
               for (;stylesIter != stylesEnd; ++stylesIter)
               {
                  std::set<std::string> names;
                  attribute_collector<Feature> collector(names);
                  std::vector<rule_type*> if_rules;
                  std::vector<rule_type*> else_rules;

                  bool active_rules=false;

                  boost::optional<feature_type_style const&> style=m_.find_style(*stylesIter);
                  if (!style) continue;

                  const std::vector<rule_type>& rules=(*style).get_rules();
                  std::vector<rule_type>::const_iterator ruleIter=rules.begin();
                  std::vector<rule_type>::const_iterator ruleEnd=rules.end();

                  for (;ruleIter!=ruleEnd;++ruleIter)
                  {
                     if (ruleIter->active(scale_denom))
                     {
                        active_rules=true;
                        ruleIter->accept(collector);

                        if (ruleIter->has_else_filter())
                        {
                           else_rules.push_back(const_cast<rule_type*>(&(*ruleIter)));
                        }
                        else
                        {
                           if_rules.push_back(const_cast<rule_type*>(&(*ruleIter)));
                        }
                     }
                  }
                  std::set<std::string>::const_iterator namesIter=names.begin();
                  std::set<std::string>::const_iterator namesEnd =names.end();

                  // push all property names
                  for (;namesIter!=namesEnd;++namesIter)
                  {
                     q.add_property_name(*namesIter);
                  }
                  if (active_rules)
                  {
                     featureset_ptr fs=ds->features(q);
                     if (fs)
                     {
                        feature_ptr feature;
                        while ((feature = fs->next()))
                        {
                           bool do_else=true;
                           std::vector<rule_type*>::const_iterator itr=if_rules.begin();
                           std::vector<rule_type*>::const_iterator end=if_rules.end();
                           for (;itr != end;++itr)
                           {
                              filter_ptr const& filter=(*itr)->get_filter();
                              if (filter->pass(*feature))
                              {
                                 do_else=false;
                                 const symbolizers& symbols = (*itr)->get_symbolizers();
                                 symbolizers::const_iterator symIter=symbols.begin();
                                 symbolizers::const_iterator symEnd =symbols.end();
                                 for (;symIter != symEnd;++symIter)
                                 {
                                    boost::apply_visitor
                                       (symbol_dispatch(p,*feature,prj_trans),*symIter);
                                 }
                              }
                           }
                           if (do_else)
                           {
                              //else filter
                              std::vector<rule_type*>::const_iterator itr=
                                 else_rules.begin();
                              std::vector<rule_type*>::const_iterator end=
                                 else_rules.end();
                              for (;itr != end;++itr)
                              {
                                 const symbolizers& symbols = (*itr)->get_symbolizers();
                                 symbolizers::const_iterator symIter= symbols.begin();
                                 symbolizers::const_iterator symEnd = symbols.end();

                                 for (;symIter!=symEnd;++symIter)
                                 {
                                    boost::apply_visitor
                                       (symbol_dispatch(p,*feature,prj_trans),*symIter);
                                 }
                              }
                           }
                        }
                     }
                  }
               }
            }
            p.end_layer_processing(lay);
         }
         Map const& m_;
   };
}

#endif //FEATURE_STYLE_PROCESSOR_HPP
<commit_msg>+ use 'buffered' extent in bbox query<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

#ifndef FEATURE_STYLE_PROCESSOR_HPP
#define FEATURE_STYLE_PROCESSOR_HPP

// mapnik
#include <mapnik/envelope.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/map.hpp>
#include <mapnik/attribute_collector.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/scale_denominator.hpp>
// boost
#include <boost/progress.hpp>
//stl
#include <vector>

namespace mapnik
{
   template <typename Processor>
   class feature_style_processor
   {
         struct symbol_dispatch : public boost::static_visitor<>
         {
               symbol_dispatch (Processor & output,
                                Feature const& f,
                                proj_transform const& prj_trans)
                  : output_(output),
                    f_(f),
                    prj_trans_(prj_trans)  {}

               template <typename T>
               void operator () (T const& sym) const
               {
                  output_.process(sym,f_,prj_trans_);
               }

               Processor & output_;
               Feature const& f_;
               proj_transform const& prj_trans_;
         };
      public:
         feature_style_processor(Map const& m)
            : m_(m) {}

         void apply()
         {
#ifdef MAPNIK_DEBUG
            boost::progress_timer t(std::clog);
#endif
            Processor & p = static_cast<Processor&>(*this);
            p.start_map_processing(m_);

            try
            {
               projection proj(m_.srs()); // map projection
               double scale_denom = scale_denominator(m_,proj.is_geographic());
#ifdef MAPNIK_DEBUG
               std::clog << "scale denominator = " << scale_denom << "\n";
#endif
               std::vector<Layer>::const_iterator itr = m_.layers().begin();
               std::vector<Layer>::const_iterator end = m_.layers().end();

               while (itr != end)
               {
                  if (itr->isVisible(scale_denom))
                  {
                     apply_to_layer(*itr, p, proj, scale_denom);
                  }
                  ++itr;
               }
            }
            catch (proj_init_error& ex)
            {
               std::clog << "proj_init_error:" << ex.what() << "\n";
            }

            p.end_map_processing(m_);
         }
      private:
         void apply_to_layer(Layer const& lay, Processor & p,
                             projection const& proj0,double scale_denom)
         {
            p.start_layer_processing(lay);
            boost::shared_ptr<datasource> ds=lay.datasource();
            if (ds)
            {
               Envelope<double> ext = m_.get_buffered_extent();
               projection proj1(lay.srs());
               proj_transform prj_trans(proj0,proj1);

               Envelope<double> layer_ext = lay.envelope();
               double lx0 = layer_ext.minx();
               double ly0 = layer_ext.miny();
               double lz0 = 0.0;
               double lx1 = layer_ext.maxx();
               double ly1 = layer_ext.maxy();
               double lz1 = 0.0;
               // back project layers extent into main map projection
               prj_trans.backward(lx0,ly0,lz0);
               prj_trans.backward(lx1,ly1,lz1);

               // if no intersection then nothing to do for layer
               if ( lx0 > ext.maxx() || lx1 < ext.minx() || ly0 > ext.maxy() || ly1 < ext.miny() )
               {
                  return;
               }

               // clip query bbox
               lx0 = std::max(ext.minx(),lx0);
               ly0 = std::max(ext.miny(),ly0);
               lx1 = std::min(ext.maxx(),lx1);
               ly1 = std::min(ext.maxy(),ly1);

               prj_trans.forward(lx0,ly0,lz0);
               prj_trans.forward(lx1,ly1,lz1);
               Envelope<double> bbox(lx0,ly0,lx1,ly1);

               double resolution = m_.getWidth()/bbox.width();
               query q(bbox,resolution); //BBOX query

               std::vector<std::string> const& style_names = lay.styles();
               std::vector<std::string>::const_iterator stylesIter = style_names.begin();
               std::vector<std::string>::const_iterator stylesEnd = style_names.end();
               for (;stylesIter != stylesEnd; ++stylesIter)
               {
                  std::set<std::string> names;
                  attribute_collector<Feature> collector(names);
                  std::vector<rule_type*> if_rules;
                  std::vector<rule_type*> else_rules;

                  bool active_rules=false;

                  boost::optional<feature_type_style const&> style=m_.find_style(*stylesIter);
                  if (!style) continue;

                  const std::vector<rule_type>& rules=(*style).get_rules();
                  std::vector<rule_type>::const_iterator ruleIter=rules.begin();
                  std::vector<rule_type>::const_iterator ruleEnd=rules.end();

                  for (;ruleIter!=ruleEnd;++ruleIter)
                  {
                     if (ruleIter->active(scale_denom))
                     {
                        active_rules=true;
                        ruleIter->accept(collector);

                        if (ruleIter->has_else_filter())
                        {
                           else_rules.push_back(const_cast<rule_type*>(&(*ruleIter)));
                        }
                        else
                        {
                           if_rules.push_back(const_cast<rule_type*>(&(*ruleIter)));
                        }
                     }
                  }
                  std::set<std::string>::const_iterator namesIter=names.begin();
                  std::set<std::string>::const_iterator namesEnd =names.end();

                  // push all property names
                  for (;namesIter!=namesEnd;++namesIter)
                  {
                     q.add_property_name(*namesIter);
                  }
                  if (active_rules)
                  {
                     featureset_ptr fs=ds->features(q);
                     if (fs)
                     {
                        feature_ptr feature;
                        while ((feature = fs->next()))
                        {
                           bool do_else=true;
                           std::vector<rule_type*>::const_iterator itr=if_rules.begin();
                           std::vector<rule_type*>::const_iterator end=if_rules.end();
                           for (;itr != end;++itr)
                           {
                              filter_ptr const& filter=(*itr)->get_filter();
                              if (filter->pass(*feature))
                              {
                                 do_else=false;
                                 const symbolizers& symbols = (*itr)->get_symbolizers();
                                 symbolizers::const_iterator symIter=symbols.begin();
                                 symbolizers::const_iterator symEnd =symbols.end();
                                 for (;symIter != symEnd;++symIter)
                                 {
                                    boost::apply_visitor
                                       (symbol_dispatch(p,*feature,prj_trans),*symIter);
                                 }
                              }
                           }
                           if (do_else)
                           {
                              //else filter
                              std::vector<rule_type*>::const_iterator itr=
                                 else_rules.begin();
                              std::vector<rule_type*>::const_iterator end=
                                 else_rules.end();
                              for (;itr != end;++itr)
                              {
                                 const symbolizers& symbols = (*itr)->get_symbolizers();
                                 symbolizers::const_iterator symIter= symbols.begin();
                                 symbolizers::const_iterator symEnd = symbols.end();

                                 for (;symIter!=symEnd;++symIter)
                                 {
                                    boost::apply_visitor
                                       (symbol_dispatch(p,*feature,prj_trans),*symIter);
                                 }
                              }
                           }
                        }
                     }
                  }
               }
            }
            p.end_layer_processing(lay);
         }
         Map const& m_;
   };
}

#endif //FEATURE_STYLE_PROCESSOR_HPP
<|endoftext|>


<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_UI_CONNECTED_BUTTONS_HPP
#define RJ_UI_CONNECTED_BUTTONS_HPP

#include "button.hpp"
#include <rectojump/global/common.hpp>

#include <mlk/signals_slots/slot.h>

namespace rj
{
	namespace ui
	{
		template<typename T>
		using btn_ptr = mlk::sptr<T>;

		using base_btn_ptr = btn_ptr<button>;

		struct button_event
		{base_btn_ptr button; mlk::slot<> event;};

		class connected_buttons : public sf::Drawable
		{
			std::map<int, button_event> m_buttons;
			int m_current_pressed_index{0};
			int m_current_add_index{0};

		public:
			mlk::slot<base_btn_ptr&> on_active_button;
			mlk::slot<base_btn_ptr&> on_inactive_button;

			connected_buttons() = default;

			void update(dur duration)
			{
				for(auto& a : m_buttons)
				{
					// update all buttons
					a.second.button->update(duration);

					// get current pressed button
					if(!a.second.button->is_pressed() && !a.second.button->is_hover())
						on_inactive_button(a.second.button);
					if(a.second.button->is_pressed())
					{
						m_current_pressed_index = a.first;
						a.second.event();
					}
				}
				// call the custom user settings
				if(m_current_pressed_index != -1)
					on_active_button(m_buttons[m_current_pressed_index].button);
			}

			template<typename Button_Type, typename... Args>
			btn_ptr<Button_Type> add_button(Args&&... args)
			{
				auto ptr(std::make_shared<Button_Type>(std::forward<Args>(args)...));
				m_buttons.emplace(m_current_add_index, button_event{ptr, {}});
				++m_current_add_index;
				return ptr;
			}

			template<typename Button_Type, typename Func, typename... Args>
			btn_ptr<Button_Type> add_button_event(Func&& f, Args&&... args)
			{
				auto ptr(std::make_shared<Button_Type>(std::forward<Args>(args)...));
				m_buttons.emplace(m_current_add_index, button_event{ptr, {f}});
				++m_current_add_index;
				return ptr;
			}

			void inactivate() noexcept
			{m_current_pressed_index = -1;}

			const base_btn_ptr& get_active_btn() const noexcept
			{return m_buttons.at(m_current_pressed_index).button;}

		private:
			void draw(sf::RenderTarget& target, sf::RenderStates states) const override
			{
				for(auto& a : m_buttons)
					target.draw(*a.second.button, states);
			}
		};
	}
}

#endif // RJ_UI_CONNECTED_BUTTONS_HPP
<commit_msg>connected_buttons: added get_buttons()<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_UI_CONNECTED_BUTTONS_HPP
#define RJ_UI_CONNECTED_BUTTONS_HPP

#include "button.hpp"
#include <rectojump/global/common.hpp>

#include <mlk/signals_slots/slot.h>

namespace rj
{
	namespace ui
	{
		template<typename T>
		using btn_ptr = mlk::sptr<T>;

		using base_btn_ptr = btn_ptr<button>;

		struct button_event
		{base_btn_ptr button; mlk::slot<> event;};

		class connected_buttons : public sf::Drawable
		{
			std::map<int, button_event> m_buttons;
			int m_current_pressed_index{0};
			int m_current_add_index{0};

		public:
			mlk::slot<base_btn_ptr&> on_active_button;
			mlk::slot<base_btn_ptr&> on_inactive_button;

			connected_buttons() = default;

			void update(dur duration)
			{
				for(auto& a : m_buttons)
				{
					// update all buttons
					a.second.button->update(duration);

					// get current pressed button
					if(!a.second.button->is_pressed() && !a.second.button->is_hover())
						on_inactive_button(a.second.button);
					if(a.second.button->is_pressed())
					{
						m_current_pressed_index = a.first;
						a.second.event();
					}
				}
				// call the custom user settings
				if(m_current_pressed_index != -1)
					on_active_button(m_buttons[m_current_pressed_index].button);
			}

			template<typename Button_Type, typename... Args>
			btn_ptr<Button_Type> add_button(Args&&... args)
			{
				auto ptr(std::make_shared<Button_Type>(std::forward<Args>(args)...));
				m_buttons.emplace(m_current_add_index, button_event{ptr, {}});
				++m_current_add_index;
				return ptr;
			}

			template<typename Button_Type, typename Func, typename... Args>
			btn_ptr<Button_Type> add_button_event(Func&& f, Args&&... args)
			{
				auto ptr(std::make_shared<Button_Type>(std::forward<Args>(args)...));
				m_buttons.emplace(m_current_add_index, button_event{ptr, {f}});
				++m_current_add_index;
				return ptr;
			}

			void inactivate() noexcept
			{m_current_pressed_index = -1;}

			const base_btn_ptr& get_active_btn() const noexcept
			{return m_buttons.at(m_current_pressed_index).button;}

			auto get_buttons()
			-> const decltype(m_buttons)&
			{return m_buttons;}

		private:
			void draw(sf::RenderTarget& target, sf::RenderStates states) const override
			{
				for(auto& a : m_buttons)
					target.draw(*a.second.button, states);
			}
		};
	}
}

#endif // RJ_UI_CONNECTED_BUTTONS_HPP
<|endoftext|>


<commit_before>#include <iostream>
#include <vw/Plate/RpcServices.h>
#include <vw/Plate/Amqp.h>
#include <vw/Core/ProgressCallback.h>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <cerrno>

#include <sys/types.h>
#include <fcntl.h>

using namespace vw;
using namespace vw::platefile;

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

namespace fs = boost::filesystem;
namespace po = boost::program_options;
namespace io = boost::iostreams;

struct Options {
  std::string filename;
  uint32 clients;
  uint32 id;
  uint32 timeout;
  uint32 block_size;
  uint32 block_count;
  std::string server;
  bool verify;
  bool append;
  bool fsync;
};

VW_DEFINE_EXCEPTION(Usage, Exception);

void handle_arguments(int argc, char *argv[], Options& opt)
{
  bool help = false;

  po::options_description options("Options");
  options.add_options()
    ("rabbitmq,r",    po::value(&opt.server),   "rabbitmq server (host:port)")
    ("file,f",        po::value(&opt.filename), "File to append to")
    ("num-clients,n", po::value(&opt.clients),  "Number of clients.")
    ("id,i",          po::value(&opt.id),       "This client's id.")
    ("timeout,t",     po::value(&opt.timeout)->default_value(30000), "timeout in ms.")
    ("verify,v",      "Check the file instead of writing it")
    ("append",        "Use O_APPEND rather than lseek (this will mess up lustre!)")
    ("fsync",         "Call fsync before closing")
    ("block-size,b",  po::value(&opt.block_size)->default_value(4),  "How much should each client write?")
    ("block-count,c", po::value(&opt.block_count)->default_value(std::numeric_limits<uint32>().max()), "How many times should each client write?")
    ("help,h",        "Display this help message.");

  po::variables_map vm;
  po::store( po::command_line_parser( argc, argv ).options(options).run(), vm );
  po::notify( vm );

  std::ostringstream out;

#define REQUIRE(name) do {\
  if (!vm.count(#name)) {\
    out << "Error: missing required parameter \"" #name "\"" << std::endl;\
    help = true;\
  }\
} while (0)

  opt.verify = vm.count("verify");
  help = vm.count("help");
  opt.append = vm.count("append");

  if (!opt.verify)
    REQUIRE(id);

  REQUIRE(num-clients);
  REQUIRE(file);

#undef REQUIRE

  if( help )
    vw_throw(Usage() << out.str() << "Usage: " << argv[0] << "\n" << options << "\n");

  VW_ASSERT( opt.clients > 0,      Usage() << "Error: # of clients must be > 0."     );
  VW_ASSERT( opt.id < opt.clients, Usage() << "Error: # of clients must be > id."    );
  VW_ASSERT( opt.clients < 10000,  Usage() << "Error: # of clients must be < 10000." );
}

const std::string& queue_name(const Options& opt) {
  static std::string x = std::string("client_") + vw::stringify(opt.id);
  return x;
}
const std::string& next_queue_name(const Options& opt) {
  static std::string x = std::string("client_") + vw::stringify((opt.id+1) % opt.clients );
  return x;
}

void run(const Options& opt) {
  // On first pass with client id 0, there's no message to read.
  bool first_node = (opt.id == 0);

  std::string host = "localhost",
              port = "5672";

  if (!opt.server.empty()) {
      size_t ret = opt.server.find_last_of(":");
      if (ret == std::string::npos)
          host = opt.server;
      else {
          host = opt.server.substr(0,ret);
          port = opt.server.substr(ret+1);
      }
  }

  boost::shared_ptr<AmqpConnection> conn(new AmqpConnection(host, boost::lexical_cast<int>(port)));
  AmqpRpcDumbClient node(conn, "lustre_torture", queue_name(opt));
  node.bind_service(queue_name(opt));

  const std::string& next = next_queue_name(opt);
  ByteArray send_msg(next.size() + 2);
  send_msg[0] = 'G';
  send_msg[1] = 'O';
  std::copy(next.begin(), next.end(), send_msg.begin()+2);

  const std::string& me = queue_name(opt);
  ByteArray want_msg(me.size() + 2);
  want_msg[0] = 'G';
  want_msg[1] = 'O';
  std::copy(me.begin(), me.end(), want_msg.begin()+2);

  TerminalProgressCallback pc( "plate.tools.lustre_torture", "");

  {
      std::string sending(send_msg.begin(), send_msg.end()),
                  recving(want_msg.begin(), want_msg.end());

      vw_out(InfoMessage) << "I am [" << me << "] sending[" << sending << "] expecting[" << recving << "]" << std::endl
                          << "Ready to create "
                          << opt.clients * opt.block_size * opt.block_count / 1024. / 1024.
                          << "MB file! Waiting 5 seconds for everyone to start." << std::endl;
  }
  sleep(5);

  uint32 blocks_written = 0;
  uint32 tick = opt.block_count / 100;
  while (blocks_written < opt.block_count) {
    if (blocks_written % tick == 0) {
      pc.report_incremental_progress(.01);
      pc.print_progress();
    }
    int fd;
    if (first_node) {
      first_node = false;
      // truncate file and create it if necessary
      fd = open(opt.filename.c_str(), O_WRONLY|O_TRUNC|O_CREAT, 0660);
      VW_ASSERT(fd >= 0, IOErr() << "Could not truncate file " << opt.filename << ": " << strerror(errno));
    } else {
      SharedByteArray msg;
      node.get_bytes(msg, opt.timeout);
      VW_ASSERT(want_msg.size() == msg->size(),
              IOErr() << "Received an incorrectly-sized message");
      VW_ASSERT(std::equal(want_msg.begin(), want_msg.end(), msg->begin()),
              LogicErr() << "Got the wrong message.");

      if (opt.append)
        fd = open(opt.filename.c_str(), O_WRONLY|O_APPEND);
      else
        fd = open(opt.filename.c_str(), O_WRONLY);

      VW_ASSERT(fd >= 0, IOErr() << "Could not open file " << opt.filename << ": " << strerror(errno));

      if (!opt.append) {
        off_t offset = (opt.clients * blocks_written + opt.id) * opt.block_size;
        VW_ASSERT(lseek(fd, offset, SEEK_SET) > 0,
            IOErr() << "Could not seek in file");
      }
    }

    std::string s_id = boost::lexical_cast<std::string>(opt.id);
    s_id.insert(0, opt.block_size-s_id.size(), '0');
    VW_ASSERT(s_id.size() == opt.block_size, LogicErr() << "Must pad s_id to block size");

    // struct flock lock;
    // lock.l_type   = F_WRLCK;
    // lock.l_whence = SEEK_END;
    // lock.l_start  = 0;
    // // len == 0 means "lock to end of file, even if file grows"
    // lock.l_len    = 0;

    // // Try to set the write lock, and wait until it's available. lock is released on close.
    // VW_ASSERT(fcntl(fd, F_SETLKW, &lock) >= 0,
    //         IOErr() << "Could not get write lock: " << strerror(errno));

    VW_ASSERT(write(fd, s_id.c_str(), s_id.size()) == (ssize_t)s_id.size(),
            IOErr() << "Failed to write all data to file");
    blocks_written++;

    if (opt.fsync)
      VW_ASSERT(fsync(fd) == 0, IOErr() << "Could not fsync: " << strerror(errno));

    close(fd);
    node.send_bytes(send_msg, next);
  }
  pc.report_finished();
}

void verify(const Options& opt) {
    std::ifstream file(opt.filename.c_str(), std::ios::binary);
    VW_ASSERT(file.is_open(), LogicErr() << "Could not open file: " << opt.filename << " (" << strerror(errno) << ")");

    uint32 id = 0, next;
    std::vector<char> bytes(opt.block_size+1, 0);
    uint32 failed = 0;
    int32 first_failure = -1;

    TerminalProgressCallback pc( "plate.tools.lustre_torture", "");
    uint32 tick = (opt.clients * opt.block_count) / 100;

    uint32 blocks_read = 0;
    while (file.read(&bytes[0], opt.block_size)) {
      if (blocks_read++ % tick == 0) {
        pc.report_incremental_progress(.01);
        pc.print_progress();
      }
      try {
        next = boost::lexical_cast<uint32>(&bytes[0]);
      } catch (const boost::bad_lexical_cast&) {
        next = -1;
      }
      if (next != id) {
        failed++;
        if (first_failure == -1)
            first_failure = blocks_read-1;
      }
      id = (id + 1) % opt.clients;
    }
    pc.report_finished();

    VW_ASSERT(failed == 0, LogicErr() << "Verification failed on " << failed << " blocks (first failure at block " << first_failure << ")");
}

int main(int argc, char *argv[]) {
  Options opt;
  try {
    handle_arguments(argc, argv, opt);
    if (opt.verify)
      verify(opt);
    else
      run(opt);
  } catch (const Usage& e) {
    std::cout << e.what() << std::endl;
    return 1;
  } catch (const AMQPTimeout&) {
    std::cout << "Timeout!" << std::endl;
    return 0;
  } catch (const Exception& e) {
    std::cerr << "Error: " << e.what() << std::endl;
    return 1;
  }
  return 0;
}
<commit_msg>new version of torture, closer to real blob usage<commit_after>#include <iostream>
#include <vw/Plate/RpcServices.h>
#include <vw/Plate/Amqp.h>
#include <vw/Core/ProgressCallback.h>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <cerrno>

#include <sys/types.h>
#include <fcntl.h>

using namespace vw;
using namespace vw::platefile;

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

namespace fs = boost::filesystem;
namespace po = boost::program_options;
namespace io = boost::iostreams;

struct Options {
  std::string filename;
  uint32 clients;
  uint32 id;
  uint32 timeout;
  uint32 block_size;
  uint32 block_count;
  std::string server;
  bool verify;
  bool fsync;
};

VW_DEFINE_EXCEPTION(Usage, Exception);

void handle_arguments(int argc, char *argv[], Options& opt)
{
  bool help = false;

  po::options_description options("Options");
  options.add_options()
    ("rabbitmq,r",    po::value(&opt.server),   "rabbitmq server (host:port)")
    ("file,f",        po::value(&opt.filename), "File to append to")
    ("num-clients,n", po::value(&opt.clients),  "Number of clients.")
    ("id,i",          po::value(&opt.id),       "This client's id.")
    ("timeout,t",     po::value(&opt.timeout)->default_value(30000), "timeout in ms.")
    ("verify,v",      "Check the file instead of writing it")
    ("fsync",         "Call fsync before closing")
    ("block-size,b",  po::value(&opt.block_size)->default_value(4),  "How much should each client write?")
    ("block-count,c", po::value(&opt.block_count)->default_value(std::numeric_limits<uint32>().max()), "How many times should each client write?")
    ("help,h",        "Display this help message.");

  po::variables_map vm;
  po::store( po::command_line_parser( argc, argv ).options(options).run(), vm );
  po::notify( vm );

  std::ostringstream out;

#define REQUIRE(name) do {\
  if (!vm.count(#name)) {\
    out << "Error: missing required parameter \"" #name "\"" << std::endl;\
    help = true;\
  }\
} while (0)

  opt.verify = vm.count("verify");
  help = vm.count("help");

  if (!opt.verify)
    REQUIRE(id);

  REQUIRE(num-clients);
  REQUIRE(file);

#undef REQUIRE

  if( help )
    vw_throw(Usage() << out.str() << "Usage: " << argv[0] << "\n" << options << "\n");

  VW_ASSERT( opt.clients > 0,      Usage() << "Error: # of clients must be > 0."     );
  VW_ASSERT( opt.id < opt.clients, Usage() << "Error: # of clients must be > id."    );
  VW_ASSERT( opt.clients < 10000,  Usage() << "Error: # of clients must be < 10000." );
}

const std::string& queue_name(const Options& opt) {
  static std::string x = std::string("client_") + vw::stringify(opt.id);
  return x;
}
const std::string& next_queue_name(const Options& opt) {
  static std::string x = std::string("client_") + vw::stringify((opt.id+1) % opt.clients );
  return x;
}

void run(const Options& opt) {
  // On first pass with client id 0, there's no message to read.
  bool first_node = (opt.id == 0);

  std::string host = "localhost",
              port = "5672";

  if (!opt.server.empty()) {
      size_t ret = opt.server.find_last_of(":");
      if (ret == std::string::npos)
          host = opt.server;
      else {
          host = opt.server.substr(0,ret);
          port = opt.server.substr(ret+1);
      }
  }

  boost::shared_ptr<AmqpConnection> conn(new AmqpConnection(host, boost::lexical_cast<int>(port)));
  AmqpRpcDumbClient node(conn, "lustre_torture", queue_name(opt));
  node.bind_service(queue_name(opt));

  const std::string& next = next_queue_name(opt);
  ByteArray send_msg(next.size() + 2);
  send_msg[0] = 'G';
  send_msg[1] = 'O';
  std::copy(next.begin(), next.end(), send_msg.begin()+2);

  const std::string& me = queue_name(opt);
  ByteArray want_msg(me.size() + 2);
  want_msg[0] = 'G';
  want_msg[1] = 'O';
  std::copy(me.begin(), me.end(), want_msg.begin()+2);

  TerminalProgressCallback pc( "plate.tools.lustre_torture", "");

  {
      std::string sending(send_msg.begin(), send_msg.end()),
                  recving(want_msg.begin(), want_msg.end());

      vw_out(InfoMessage) << "I am [" << me << "] sending[" << sending << "] expecting[" << recving << "]" << std::endl
                          << "Ready to create "
                          << opt.clients * opt.block_size * opt.block_count / 1024. / 1024.
                          << "MB file! Waiting 5 seconds for everyone to start." << std::endl;
  }
  sleep(5);

  uint32 blocks_written = 0;
  uint32 tick = opt.block_count / 100;

  double increment;
  if (tick == 0) {
    tick = 1;
    increment = 1./opt.block_count;
  } else {
    increment = .01;
  }

  while (blocks_written < opt.block_count) {
    if (blocks_written % tick == 0) {
      pc.report_incremental_progress(increment);
      pc.print_progress();
    }
    int fd;
    ssize_t ret;

    // eof offset should contain the offset of where the next write should go
    int64 eof_offset;
    // Just check to make sure we're doing 64-bit io
    BOOST_STATIC_ASSERT(sizeof(eof_offset) == sizeof(off_t));

    if (first_node) {
      first_node = false;
      // truncate file and create it if necessary
      fd = open(opt.filename.c_str(), O_RDWR|O_TRUNC|O_CREAT, 0660);
      VW_ASSERT(fd >= 0, IOErr() << "Could not truncate file " << opt.filename << ": " << strerror(errno));

      eof_offset = sizeof(eof_offset);
      ret = lseek(fd, 0, SEEK_SET);
      VW_ASSERT(ret == 0, IOErr() << "Failed to seek to intial eof ptr location");

      ret = write(fd, reinterpret_cast<char*>(&eof_offset), sizeof(eof_offset));
      VW_ASSERT(ret == sizeof(eof_offset), IOErr() << "Failed to write initial eof ptr");

    } else {
      SharedByteArray msg;
      node.get_bytes(msg, opt.timeout);
      VW_ASSERT(want_msg.size() == msg->size(),
              IOErr() << "Received an incorrectly-sized message");
      VW_ASSERT(std::equal(want_msg.begin(), want_msg.end(), msg->begin()),
              LogicErr() << "Got the wrong message.");

      fd = open(opt.filename.c_str(), O_RDWR);
      VW_ASSERT(fd >= 0, IOErr() << "Could not open file " << opt.filename << ": " << strerror(errno));
    }

    std::string s_id = boost::lexical_cast<std::string>(opt.id);
    s_id.insert(0, opt.block_size-s_id.size(), '0');
    VW_ASSERT(s_id.size() == opt.block_size, LogicErr() << "Must pad s_id to block size");

    // Seek to EOF value
    ret = lseek(fd, 0, SEEK_SET);
    VW_ASSERT(ret == 0, IOErr() << "Failed to seek to eof ptr location");

    // Read EOF value
    ret = read(fd, reinterpret_cast<char*>(&eof_offset), sizeof(eof_offset));
    VW_ASSERT(ret == sizeof(eof_offset), IOErr() << "Failed to read eof offset");

    // Make sure our offset matches the expected one
    int64 expected_offset = (opt.clients * blocks_written + opt.id) * opt.block_size + sizeof(eof_offset);
    VW_ASSERT(expected_offset == eof_offset,
        IOErr() << "Corruption! EOF offset is " << eof_offset << " and we expected " << expected_offset);

    // Seek to new data location
    ret = lseek(fd, eof_offset, SEEK_SET);
    VW_ASSERT(ret == eof_offset, IOErr() << "Failed to seek to start of data");

    // Write data there
    ret = write(fd, s_id.c_str(), s_id.size());
    VW_ASSERT(ret == (ssize_t)s_id.size(), IOErr() << "Failed to write all data to file");

    // Record that we wrote data
    eof_offset += s_id.size();
    blocks_written++;

    // Seek back to EOF value
    ret = lseek(fd, 0, SEEK_SET);
    VW_ASSERT(ret == 0, IOErr() << "Failed to seek to eof ptr location, second time");

    // write updated EOF value
    ret = write(fd, reinterpret_cast<char*>(&eof_offset), sizeof(eof_offset));
    VW_ASSERT(ret == sizeof(eof_offset), IOErr() << "Failed to write eof ptr to file");

    if (opt.fsync)
      VW_ASSERT(fsync(fd) == 0, IOErr() << "Could not fsync: " << strerror(errno));

    close(fd);
    node.send_bytes(send_msg, next);
  }
  pc.report_finished();
}

void verify(const Options& opt) {
    std::ifstream file(opt.filename.c_str(), std::ios::binary);
    VW_ASSERT(file.is_open(), LogicErr() << "Could not open file: " << opt.filename << " (" << strerror(errno) << ")");

    uint32 id = 0, next;
    std::vector<char> bytes(opt.block_size+1, 0);
    uint32 failed = 0;
    int32 first_failure = -1;

    TerminalProgressCallback pc( "plate.tools.lustre_torture", "");
    uint32 tick = (opt.clients * opt.block_count) / 100;
    double increment;
    if (tick == 0) {
      tick = 1;
      increment = 1./(opt.block_count * opt.clients);
    } else {
      increment = .01;
    }

    uint32 blocks_read = 0;
    int64 eof_offset, calculated_eof_offset;

    file.seekg(0, std::ios::end);
    calculated_eof_offset = file.tellg();
    file.seekg(0, std::ios::beg);

    file.read(reinterpret_cast<char*>(&eof_offset), sizeof(eof_offset));

    VW_ASSERT(eof_offset == calculated_eof_offset,
        LogicErr() << "Expected an eof offset of " << calculated_eof_offset << " but the file had " << eof_offset);

    file.seekg(sizeof(eof_offset), std::ios::beg);

    while (file.read(&bytes[0], opt.block_size)) {
      if (blocks_read++ % tick == 0) {
        pc.report_incremental_progress(increment);
        pc.print_progress();
      }
      try {
        next = boost::lexical_cast<uint32>(&bytes[0]);
      } catch (const boost::bad_lexical_cast&) {
        next = -1;
      }
      if (next != id) {
        failed++;
        if (first_failure == -1)
            first_failure = blocks_read-1;
      }
      id = (id + 1) % opt.clients;
    }
    pc.report_finished();

    VW_ASSERT(failed == 0, LogicErr() << "Verification failed on " << failed << " blocks (first failure at block " << first_failure << ")");
}

int main(int argc, char *argv[]) {
  Options opt;
  try {
    handle_arguments(argc, argv, opt);
    if (opt.verify)
      verify(opt);
    else
      run(opt);
  } catch (const Usage& e) {
    std::cout << e.what() << std::endl;
    return 1;
  } catch (const AMQPTimeout&) {
    std::cout << "Timeout!" << std::endl;
    return 0;
  } catch (const Exception& e) {
    std::cerr << "Error: " << e.what() << std::endl;
    return 1;
  }
  return 0;
}
<|endoftext|>


<commit_before><commit_msg>Fix an error when calling ReplaceFile for files on a Windows file share.<commit_after><|endoftext|>


<commit_before>#ifndef CYCLE__H__
#define CYCLE__H__

#include "iterbase.hpp"

#include <utility>
#include <iterator>
#include <initializer_list>

namespace iter {

    //Forward declarations of Cycle and cycle
    template <typename Container>
    class Cycle;

    template <typename Container>
    Cycle<Container> cycle(Container &&);

    template <typename T>
    Cycle<std::initializer_list<T>> cycle(
            std::initializer_list<T> &&);

    template <typename Container>
    class Cycle {
        private:
            // The cycle function is the only thing allowed to create a Cycle
            friend Cycle cycle<Container>(Container &&);
            template <typename T>
            friend Cycle<std::initializer_list<T>> cycle(
                    std::initializer_list<T> &&);

            Container & container;

            // Value constructor for use only in the cycle function
            Cycle(Container && container) : container{container} { }
            Cycle () = delete;
            Cycle & operator=(const Cycle &) = delete;

        public:
            Cycle(const Cycle &) = default;
            class Iterator {
                private:
                    using iter_type = iterator_type<Container>;
                    iterator_type<Container> sub_iter;
                    const iterator_type<Container> begin;
                    const iterator_type<Container> end;
                public:
                    Iterator (iterator_type<Container> iter,
                            iterator_type<Container> end)
                        : sub_iter{iter},
                        begin{iter},
                        end{end}
                    { }

                    iterator_deref<Container> operator*() const {
                        return *this->sub_iter;
                    }

                    Iterator & operator++() {
                        ++this->sub_iter;
                        // reset to beginning upon reaching the end
                        if (!(this->sub_iter != this->end)) {
                            // explicit destruction with placement new in order
                            // to support iterators with no operator=
                            this->sub_iter.~iter_type();
                            new(&this->sub_iter) iterator_type<Container>(
                                    this->begin);
                        }
                        return *this;
                    }

                    constexpr bool operator!=(const Iterator &) const {
                        return true;
                    }
            };

            Iterator begin() const {
                return {std::begin(this->container),
                        std::end(this->container)};
            }

            Iterator end() const {
                return {std::end(this->container),
                        std::end(this->container)};
            }

    };

    // Helper function to instantiate an Filter
    template <typename Container>
    Cycle<Container> cycle(Container && container) {
        return {std::forward<Container>(container)};
    }

    template <typename T>
    Cycle<std::initializer_list<T>> cycle(std::initializer_list<T> && il)
    {
        return {std::move(il)};
    }
}

#endif //ifndef CYCLE__H__
<commit_msg>formats cycle<commit_after>#ifndef CYCLE__H__
#define CYCLE__H__

#include "iterbase.hpp"

#include <utility>
#include <iterator>
#include <initializer_list>

namespace iter {

    //Forward declarations of Cycle and cycle
    template <typename Container>
    class Cycle;

    template <typename Container>
    Cycle<Container> cycle(Container&&);

    template <typename T>
    Cycle<std::initializer_list<T>> cycle(std::initializer_list<T>&&);

    template <typename Container>
    class Cycle {
        private:
            // The cycle function is the only thing allowed to create a Cycle
            friend Cycle cycle<Container>(Container&&);
            template <typename T>
            friend Cycle<std::initializer_list<T>> cycle(
                    std::initializer_list<T>&&);

            Container & container;

            // Value constructor for use only in the cycle function
            Cycle(Container&& container) : container{container} { }
            Cycle() = delete;
            Cycle& operator=(const Cycle&) = delete;

        public:
            Cycle(const Cycle&) = default;
            class Iterator {
                private:
                    using iter_type = iterator_type<Container>;
                    iterator_type<Container> sub_iter;
                    const iterator_type<Container> begin;
                    const iterator_type<Container> end;
                public:
                    Iterator (iterator_type<Container> iter,
                            iterator_type<Container> end)
                        : sub_iter{iter},
                        begin{iter},
                        end{end}
                    { }

                    iterator_deref<Container> operator*() const {
                        return *this->sub_iter;
                    }

                    Iterator & operator++() {
                        ++this->sub_iter;
                        // reset to beginning upon reaching the end
                        if (!(this->sub_iter != this->end)) {
                            // explicit destruction with placement new in order
                            // to support iterators with no operator=
                            this->sub_iter.~iter_type();
                            new(&this->sub_iter) iterator_type<Container>(
                                    this->begin);
                        }
                        return *this;
                    }

                    constexpr bool operator!=(const Iterator &) const {
                        return true;
                    }
            };

            Iterator begin() const {
                return {std::begin(this->container),
                        std::end(this->container)};
            }

            Iterator end() const {
                return {std::end(this->container),
                        std::end(this->container)};
            }

    };

    // Helper function to instantiate an Filter
    template <typename Container>
    Cycle<Container> cycle(Container&& container) {
        return {std::forward<Container>(container)};
    }

    template <typename T>
    Cycle<std::initializer_list<T>> cycle(std::initializer_list<T>&& il)
    {
        return {std::move(il)};
    }
}

#endif //ifndef CYCLE__H__
<|endoftext|>


<commit_before>//===- MachineDominators.cpp - Machine Dominator Calculation --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements simple dominator construction algorithms for finding
// forward dominators on machine functions.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/Passes.h"

using namespace llvm;

TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
TEMPLATE_INSTANTIATION(class DominatorTreeBase<MachineBasicBlock>);

namespace {
  char MachineDominatorTree::ID = 0;
  RegisterPass<MachineDominatorTree>
  E("machinedomtree", "MachineDominator Tree Construction", true);
}

const PassInfo *llvm::MachineDominatorsID = E.getPassInfo();
<commit_msg>Fix build issue on certain compilers.<commit_after>//===- MachineDominators.cpp - Machine Dominator Calculation --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements simple dominator construction algorithms for finding
// forward dominators on machine functions.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/Passes.h"

using namespace llvm;

TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
TEMPLATE_INSTANTIATION(class DominatorTreeBase<MachineBasicBlock>);

char MachineDominatorTree::ID = 0;

namespace {
  RegisterPass<MachineDominatorTree>
  E("machinedomtree", "MachineDominator Tree Construction", true);
}

const PassInfo *llvm::MachineDominatorsID = E.getPassInfo();
<|endoftext|>


<commit_before>/*************************************************************************
* Copyright (C) 2013,  Gfif Developers                                   *
* Grupo de Fenomenologia de Interacciones Fundamentales                  *
* http://gfif.udea.edu.co                                                *
* División de ciencias de la computación Gfifdev                         *
* Class Created and Maintained By Omar Andres Zapata Mesa                *
* All rights reserved.                                                   *
*                                                                        *
*                                                                        *
* For the list of contributors see $ROOTSYS/README/CREDITS.              *
*************************************************************************/
#include<TRInterface.h>
#include<Rembedded.h>
#include<Rinterface.h>
#include<Rinternals.h>
#include<vector>

const char *argvs[] = {"rootr", "--gui=none", "--no-save", "--silent"};
ROOT::R::TRInterface *gR = new ROOT::R::TRInterface(5, argvs, true, false, true);
#include <readline/readline.h>
#include <readline/history.h>
//______________________________________________________________________________
/* Begin_Html

TRInterface class

The TRInterface class lets you procces R code from ROOT.

You can call R libraries and their functions, plot results in R or ROOT language

and to use the power of ROOT and R at the same time.

It also lets you pass scalars, vectors and matrices from ROOT to R

and from R to ROOT using TRObjectProxy.

To plot in R environment you should first call the method Xwin() to initiliaze the window's system

before calling the class' plotting methods.

NOTE In the same way that TROOT class have an unique global object gROOT,

TRInterface has gR. Not more objects of TRInterface class can be instantiated, but you can create objects using the methods
TRInterface& Instance() and TRInterface* InstancePtr() to create your objects or just to use directly gR object.

Show an example below:
End_Html
Begin_Macro(source)
{

//Create an exponential fit
//The idea is to create a set of numbers x,y with noise from ROOT,
//pass then to R and fit the data to x^3,
//get the fitted coefficient(power) and plot the points with noise,
//the known function and the fitted function.
//Author:: Omar Zapata
   TCanvas *c1 = new TCanvas("c1","Curve Fit",700,500);
   c1->SetGrid();

   // draw a frame for multiples graphs
   TMultiGraph *mg = new TMultiGraph();

   // create the first graph (points with gaussian noise)
   const Int_t n = 24;
   Double_t x1[n] ;
   Double_t y1[n] ;
   //Generate points along a X^3 with noise
   TRandom rg;
   rg.SetSeed(520);
   for (Int_t i = 0; i < n; i++) {
      x1[i] = rg.Uniform(0, 1);
      y1[i] = TMath::Power(x1[i], 3) + rg.Gaus() * 0.06;
   }

   TGraph *gr1 = new TGraph(n,x1,y1);
   gr1->SetMarkerColor(kBlue);
   gr1->SetMarkerStyle(8);
   gr1->SetMarkerSize(1);
   mg->Add(gr1);

      // create second graph
   TF1 *f_known=new TF1("f_known","pow(x,3)",0,1);
   TGraph *gr2 = new TGraph(f_known);
   gr2->SetMarkerColor(kRed);
   gr2->SetMarkerStyle(8);
   gr2->SetMarkerSize(1);
   mg->Add(gr2);

   //passing to R x and y values to fit
   gR->Assign(TVectorD(n, x1), "x");
   gR->Assign(TVectorD(n, y1), "y");
   //creating a R data frame
   gR->Parse("ds<-data.frame(x=x,y=y)");
   //fitting x and y to X^power using Nonlinear Least Squares
   gR->Parse("m <- nls(y ~ I(x^power),data = ds, start = list(power = 1),trace = T)");
   //getting the fitted value (power)
   ROOT::R::TRObjectProxy robj=gR->ParseEval("summary(m)$coefficients[1]");
   Double_t power=robj.ToScalar();

   TF1 *f_fitted=new TF1("f_fitted","pow(x,[0])",0,1);
   f_fitted->SetParameter(0,power);
   //plotting the fitted function
   TGraph *gr3 = new TGraph(f_fitted);
   gr3->SetMarkerColor(kGreen);
   gr3->SetMarkerStyle(8);
   gr3->SetMarkerSize(1);

   mg->Add(gr3);
   mg->Draw("ap");

   //displaying basic results
   TPaveText *pt = new TPaveText(0.1,0.6,0.5,0.9,"brNDC");
   pt->SetFillColor(18);
   pt->SetTextAlign(12);
   pt->AddText("Fitting x^power ");
   pt->AddText(" \"Blue\"   Points with gaussian noise to be fitted");
   pt->AddText(" \"Red\"    Known function x^3");
   TString fmsg;
   fmsg.Form(" \"Green\"  Fitted function with power=%.4lf",power);
   pt->AddText(fmsg);
   pt->Draw();
   c1->Update();
   return c1;
}
End_Macro */

using namespace ROOT::R;
ClassImp(TRInterface)

//Variables for READLINE
static SEXP
RComp_assignBufferSym,
RComp_assignStartSym,
RComp_assignEndSym,
RComp_assignTokenSym,
RComp_completeTokenSym,
RComp_getFileCompSym,
RComp_retrieveCompsSym;
SEXP rcompgen_rho;

//______________________________________________________________________________
char *R_completion_generator(const char *text, int state)
{
   static int list_index, ncomp;
   static char **compstrings;

   /* If this is a new word to complete, initialize now.  This
      involves saving 'text' to somewhere R can get at it, calling
      completeToken(), and retrieving the completions. */

   if (!state) {
      int i;
      SEXP completions,
           assignCall = PROTECT(Rf_lang2(RComp_assignTokenSym, Rf_mkString(text))),
           completionCall = PROTECT(Rf_lang1(RComp_completeTokenSym)),
           retrieveCall = PROTECT(Rf_lang1(RComp_retrieveCompsSym));
      const void *vmax = vmaxget();

      Rf_eval(assignCall, rcompgen_rho);
      Rf_eval(completionCall, rcompgen_rho);
      PROTECT(completions = Rf_eval(retrieveCall, rcompgen_rho));
      list_index = 0;
      ncomp = Rf_length(completions);
      if (ncomp > 0) {
         compstrings = (char **) malloc(ncomp * sizeof(char*));
         if (!compstrings)  return (char *)NULL;
         for (i = 0; i < ncomp; i++)
            compstrings[i] = strdup(Rf_translateChar(STRING_ELT(completions, i)));
      }
      UNPROTECT(4);
      vmaxset(vmax);
   }

   if (list_index < ncomp)
      return compstrings[list_index++];
   else {
      /* nothing matched or remaining, so return NULL. */
      if (ncomp > 0) free(compstrings);
   }
   return (char *)NULL;
}

//______________________________________________________________________________
char ** R_custom_completion(const char *text, int start, int end)
{
   char **matches = (char **)NULL;
   SEXP infile,
        linebufferCall = PROTECT(Rf_lang2(RComp_assignBufferSym,
                                          Rf_mkString(rl_line_buffer))),
                         startCall = PROTECT(Rf_lang2(RComp_assignStartSym, Rf_ScalarInteger(start))),
                         endCall = PROTECT(Rf_lang2(RComp_assignEndSym, Rf_ScalarInteger(end)));
   SEXP filecompCall;

   /* Don't want spaces appended at the end.  Need to do this
      everytime, as readline>=6 resets it to ' ' */
   rl_completion_append_character = '\0';

   Rf_eval(linebufferCall, rcompgen_rho);
   Rf_eval(startCall, rcompgen_rho);
   Rf_eval(endCall, rcompgen_rho);
   UNPROTECT(3);
   matches = rl_completion_matches(text, R_completion_generator);
   filecompCall = PROTECT(Rf_lang1(RComp_getFileCompSym));
   infile = PROTECT(Rf_eval(filecompCall, rcompgen_rho));
   if (!Rf_asLogical(infile)) rl_attempted_completion_over = 1;
   UNPROTECT(2);
   return matches;
}

//______________________________________________________________________________
TRInterface::TRInterface(const int argc, const char *argv[], const bool loadRcpp, const bool verbose, const bool interactive)
{
// The command line arguments are by deafult argc=0 and argv=NULL,
// The verbose mode are by default disabled but you can enable it to show procedures information in stdout/stderr
   if (RInside::instancePtr()) throw std::runtime_error("Can only have one TRInterface instance");
   fR = new RInside(argc, argv, loadRcpp, verbose, interactive);

   //installing the readline callbacks for completion in the
   //method Interactive
   rcompgen_rho = R_FindNamespace(Rf_mkString("utils"));
   RComp_assignBufferSym  = Rf_install(".assignLinebuffer");
   RComp_assignStartSym   = Rf_install(".assignStart");
   RComp_assignEndSym     = Rf_install(".assignEnd");
   RComp_assignTokenSym   = Rf_install(".assignToken");
   RComp_completeTokenSym = Rf_install(".completeToken");
   RComp_getFileCompSym   = Rf_install(".getFileComp");
   RComp_retrieveCompsSym = Rf_install(".retrieveCompletions");
   rl_attempted_completion_function = R_custom_completion;

}

//______________________________________________________________________________
Int_t  TRInterface::ParseEval(const TString &code, TRObjectProxy  &ans)
{
// Parse R code and returns status of execution.
// the RObject's response is saved in  ans
   SEXP fans;
   Int_t fResult = fR->parseEval(code.Data(), fans);
   ans = fans;
   return fResult;
}

//______________________________________________________________________________
void TRInterface::Parse(const TString &code, Bool_t exception)
{
// Parse R code. The argument exception is by defualt false, and
// if the code has some error prints an error and continues executing.
// if exception if true, the code it launches an exception and stop the execution.
   if (exception) fR->parseEvalQ((std::string)code);
   else fR->parseEvalQNT(code.Data());
}

//______________________________________________________________________________
TRObjectProxy TRInterface::ParseEval(const TString &code, Bool_t exception)
{
// Parse R code. The argument exception is by defualt false, and
// if the code has some error prints an error and continues executing.
//if exception if true, the code launches an exception and stop the execution.
//The RObject result of execution is returned in TRObjectProxy
   if (exception) return TRObjectProxy((SEXP)fR->parseEval(code.Data()));
   else return TRObjectProxy((SEXP)fR->parseEvalNT(code.Data()));
}

void TRInterface::SetVerbose(Bool_t status)
{
   //verbose mode shows you all procedures in stdout/stderr
   //very important to debug and to see the results.
   fR->setVerbose(status);
}

//______________________________________________________________________________
TRInterface::Binding TRInterface::operator[](const TString& name)
{
   return Binding(this, name);
}

//______________________________________________________________________________
void TRInterface::Xwin(TString opt)
{
   //Initiliaze the window's system to do plots.
   //every platform has it owns system.
   //see R manual for x11(unix based systems),windows(MS windows)
   if (opt.IsNull()) {
#if defined(R__WIN32)
      Parse("windows()");
#else
      Parse("x11()");
#endif
   } else {
#if defined(R__WIN32)
      Parse(TString("windows(" + opt + ")").Data());
#else
      Parse(TString("x11(" + opt + ")").Data());
#endif
   }
}

//______________________________________________________________________________
void TRInterface::Assign(const TRFunction &obj, const TString & name)
{
   //This method let you to pass c++ functions to R environment.
   fR->assign(*obj.f, name.Data());
}

//______________________________________________________________________________
void TRInterface::Interactive()
{
   //this method launch a R command line to run directly R code that you can
   //pass to ROOT calling the apropiate method.

   while (kTRUE) {
      char * line = readline("[r]:");
      if (!line) continue;
      if (*line) add_history(line);
      if (std::string(line) == ".q") break;
      Parse(line, false);
      free(line);
   }
}

<commit_msg>fixed number of arguments in TRInterface constructor that causes segfault.<commit_after>/*************************************************************************
* Copyright (C) 2013,  Gfif Developers                                   *
* Grupo de Fenomenologia de Interacciones Fundamentales                  *
* http://gfif.udea.edu.co                                                *
* División de ciencias de la computación Gfifdev                         *
* Class Created and Maintained By Omar Andres Zapata Mesa                *
* All rights reserved.                                                   *
*                                                                        *
*                                                                        *
* For the list of contributors see $ROOTSYS/README/CREDITS.              *
*************************************************************************/
#include<TRInterface.h>
#include<Rembedded.h>
#include<Rinterface.h>
#include<Rinternals.h>
#include<vector>

const char *argvs[] = {"rootr","--no-save", "--silent"};
ROOT::R::TRInterface *gR = new ROOT::R::TRInterface(3, argvs, true, false, true);
#include <readline/readline.h>
#include <readline/history.h>
//______________________________________________________________________________
/* Begin_Html

TRInterface class

The TRInterface class lets you procces R code from ROOT.

You can call R libraries and their functions, plot results in R or ROOT language

and to use the power of ROOT and R at the same time.

It also lets you pass scalars, vectors and matrices from ROOT to R

and from R to ROOT using TRObjectProxy.

To plot in R environment you should first call the method Xwin() to initiliaze the window's system

before calling the class' plotting methods.

NOTE In the same way that TROOT class have an unique global object gROOT,

TRInterface has gR. Not more objects of TRInterface class can be instantiated, but you can create objects using the methods
TRInterface& Instance() and TRInterface* InstancePtr() to create your objects or just to use directly gR object.

Show an example below:
End_Html
Begin_Macro(source)
{

//Create an exponential fit
//The idea is to create a set of numbers x,y with noise from ROOT,
//pass then to R and fit the data to x^3,
//get the fitted coefficient(power) and plot the points with noise,
//the known function and the fitted function.
//Author:: Omar Zapata
   TCanvas *c1 = new TCanvas("c1","Curve Fit",700,500);
   c1->SetGrid();

   // draw a frame for multiples graphs
   TMultiGraph *mg = new TMultiGraph();

   // create the first graph (points with gaussian noise)
   const Int_t n = 24;
   Double_t x1[n] ;
   Double_t y1[n] ;
   //Generate points along a X^3 with noise
   TRandom rg;
   rg.SetSeed(520);
   for (Int_t i = 0; i < n; i++) {
      x1[i] = rg.Uniform(0, 1);
      y1[i] = TMath::Power(x1[i], 3) + rg.Gaus() * 0.06;
   }

   TGraph *gr1 = new TGraph(n,x1,y1);
   gr1->SetMarkerColor(kBlue);
   gr1->SetMarkerStyle(8);
   gr1->SetMarkerSize(1);
   mg->Add(gr1);

      // create second graph
   TF1 *f_known=new TF1("f_known","pow(x,3)",0,1);
   TGraph *gr2 = new TGraph(f_known);
   gr2->SetMarkerColor(kRed);
   gr2->SetMarkerStyle(8);
   gr2->SetMarkerSize(1);
   mg->Add(gr2);

   //passing to R x and y values to fit
   gR->Assign(TVectorD(n, x1), "x");
   gR->Assign(TVectorD(n, y1), "y");
   //creating a R data frame
   gR->Parse("ds<-data.frame(x=x,y=y)");
   //fitting x and y to X^power using Nonlinear Least Squares
   gR->Parse("m <- nls(y ~ I(x^power),data = ds, start = list(power = 1),trace = T)");
   //getting the fitted value (power)
   ROOT::R::TRObjectProxy robj=gR->ParseEval("summary(m)$coefficients[1]");
   Double_t power=robj.ToScalar();

   TF1 *f_fitted=new TF1("f_fitted","pow(x,[0])",0,1);
   f_fitted->SetParameter(0,power);
   //plotting the fitted function
   TGraph *gr3 = new TGraph(f_fitted);
   gr3->SetMarkerColor(kGreen);
   gr3->SetMarkerStyle(8);
   gr3->SetMarkerSize(1);

   mg->Add(gr3);
   mg->Draw("ap");

   //displaying basic results
   TPaveText *pt = new TPaveText(0.1,0.6,0.5,0.9,"brNDC");
   pt->SetFillColor(18);
   pt->SetTextAlign(12);
   pt->AddText("Fitting x^power ");
   pt->AddText(" \"Blue\"   Points with gaussian noise to be fitted");
   pt->AddText(" \"Red\"    Known function x^3");
   TString fmsg;
   fmsg.Form(" \"Green\"  Fitted function with power=%.4lf",power);
   pt->AddText(fmsg);
   pt->Draw();
   c1->Update();
   return c1;
}
End_Macro */

using namespace ROOT::R;
ClassImp(TRInterface)

//Variables for READLINE
static SEXP
RComp_assignBufferSym,
RComp_assignStartSym,
RComp_assignEndSym,
RComp_assignTokenSym,
RComp_completeTokenSym,
RComp_getFileCompSym,
RComp_retrieveCompsSym;
SEXP rcompgen_rho;

//______________________________________________________________________________
char *R_completion_generator(const char *text, int state)
{
   static int list_index, ncomp;
   static char **compstrings;

   /* If this is a new word to complete, initialize now.  This
      involves saving 'text' to somewhere R can get at it, calling
      completeToken(), and retrieving the completions. */

   if (!state) {
      int i;
      SEXP completions,
           assignCall = PROTECT(Rf_lang2(RComp_assignTokenSym, Rf_mkString(text))),
           completionCall = PROTECT(Rf_lang1(RComp_completeTokenSym)),
           retrieveCall = PROTECT(Rf_lang1(RComp_retrieveCompsSym));
      const void *vmax = vmaxget();

      Rf_eval(assignCall, rcompgen_rho);
      Rf_eval(completionCall, rcompgen_rho);
      PROTECT(completions = Rf_eval(retrieveCall, rcompgen_rho));
      list_index = 0;
      ncomp = Rf_length(completions);
      if (ncomp > 0) {
         compstrings = (char **) malloc(ncomp * sizeof(char*));
         if (!compstrings)  return (char *)NULL;
         for (i = 0; i < ncomp; i++)
            compstrings[i] = strdup(Rf_translateChar(STRING_ELT(completions, i)));
      }
      UNPROTECT(4);
      vmaxset(vmax);
   }

   if (list_index < ncomp)
      return compstrings[list_index++];
   else {
      /* nothing matched or remaining, so return NULL. */
      if (ncomp > 0) free(compstrings);
   }
   return (char *)NULL;
}

//______________________________________________________________________________
char ** R_custom_completion(const char *text, int start, int end)
{
   char **matches = (char **)NULL;
   SEXP infile,
        linebufferCall = PROTECT(Rf_lang2(RComp_assignBufferSym,
                                          Rf_mkString(rl_line_buffer))),
                         startCall = PROTECT(Rf_lang2(RComp_assignStartSym, Rf_ScalarInteger(start))),
                         endCall = PROTECT(Rf_lang2(RComp_assignEndSym, Rf_ScalarInteger(end)));
   SEXP filecompCall;

   /* Don't want spaces appended at the end.  Need to do this
      everytime, as readline>=6 resets it to ' ' */
   rl_completion_append_character = '\0';

   Rf_eval(linebufferCall, rcompgen_rho);
   Rf_eval(startCall, rcompgen_rho);
   Rf_eval(endCall, rcompgen_rho);
   UNPROTECT(3);
   matches = rl_completion_matches(text, R_completion_generator);
   filecompCall = PROTECT(Rf_lang1(RComp_getFileCompSym));
   infile = PROTECT(Rf_eval(filecompCall, rcompgen_rho));
   if (!Rf_asLogical(infile)) rl_attempted_completion_over = 1;
   UNPROTECT(2);
   return matches;
}

//______________________________________________________________________________
TRInterface::TRInterface(const int argc, const char *argv[], const bool loadRcpp, const bool verbose, const bool interactive)
{
// The command line arguments are by deafult argc=0 and argv=NULL,
// The verbose mode are by default disabled but you can enable it to show procedures information in stdout/stderr
   if (RInside::instancePtr()) throw std::runtime_error("Can only have one TRInterface instance");
   fR = new RInside(argc, argv, loadRcpp, verbose, interactive);

   //installing the readline callbacks for completion in the
   //method Interactive
   rcompgen_rho = R_FindNamespace(Rf_mkString("utils"));
   RComp_assignBufferSym  = Rf_install(".assignLinebuffer");
   RComp_assignStartSym   = Rf_install(".assignStart");
   RComp_assignEndSym     = Rf_install(".assignEnd");
   RComp_assignTokenSym   = Rf_install(".assignToken");
   RComp_completeTokenSym = Rf_install(".completeToken");
   RComp_getFileCompSym   = Rf_install(".getFileComp");
   RComp_retrieveCompsSym = Rf_install(".retrieveCompletions");
   rl_attempted_completion_function = R_custom_completion;

}

//______________________________________________________________________________
Int_t  TRInterface::ParseEval(const TString &code, TRObjectProxy  &ans)
{
// Parse R code and returns status of execution.
// the RObject's response is saved in  ans
   SEXP fans;
   Int_t fResult = fR->parseEval(code.Data(), fans);
   ans = fans;
   return fResult;
}

//______________________________________________________________________________
void TRInterface::Parse(const TString &code, Bool_t exception)
{
// Parse R code. The argument exception is by defualt false, and
// if the code has some error prints an error and continues executing.
// if exception if true, the code it launches an exception and stop the execution.
   if (exception) fR->parseEvalQ((std::string)code);
   else fR->parseEvalQNT(code.Data());
}

//______________________________________________________________________________
TRObjectProxy TRInterface::ParseEval(const TString &code, Bool_t exception)
{
// Parse R code. The argument exception is by defualt false, and
// if the code has some error prints an error and continues executing.
//if exception if true, the code launches an exception and stop the execution.
//The RObject result of execution is returned in TRObjectProxy
   if (exception) return TRObjectProxy((SEXP)fR->parseEval(code.Data()));
   else return TRObjectProxy((SEXP)fR->parseEvalNT(code.Data()));
}

void TRInterface::SetVerbose(Bool_t status)
{
   //verbose mode shows you all procedures in stdout/stderr
   //very important to debug and to see the results.
   fR->setVerbose(status);
}

//______________________________________________________________________________
TRInterface::Binding TRInterface::operator[](const TString& name)
{
   return Binding(this, name);
}

//______________________________________________________________________________
void TRInterface::Xwin(TString opt)
{
   //Initiliaze the window's system to do plots.
   //every platform has it owns system.
   //see R manual for x11(unix based systems),windows(MS windows)
   if (opt.IsNull()) {
#if defined(R__WIN32)
      Parse("windows()");
#else
      Parse("x11()");
#endif
   } else {
#if defined(R__WIN32)
      Parse(TString("windows(" + opt + ")").Data());
#else
      Parse(TString("x11(" + opt + ")").Data());
#endif
   }
}

//______________________________________________________________________________
void TRInterface::Assign(const TRFunction &obj, const TString & name)
{
   //This method let you to pass c++ functions to R environment.
   fR->assign(*obj.f, name.Data());
}

//______________________________________________________________________________
void TRInterface::Interactive()
{
   //this method launch a R command line to run directly R code that you can
   //pass to ROOT calling the apropiate method.

   while (kTRUE) {
      char * line = readline("[r]:");
      if (!line) continue;
      if (*line) add_history(line);
      if (std::string(line) == ".q") break;
      Parse(line, false);
      free(line);
   }
}

<|endoftext|>


<commit_before>//===-- llvm/CodeGen/ObjectCodeEmitter.cpp -------------------- -*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/BinaryObject.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineRelocation.h"
#include "llvm/CodeGen/ObjectCodeEmitter.h"

//===----------------------------------------------------------------------===//
//                       ObjectCodeEmitter Implementation
//===----------------------------------------------------------------------===//

namespace llvm {

ObjectCodeEmitter::ObjectCodeEmitter() : BO(0) {}
ObjectCodeEmitter::ObjectCodeEmitter(BinaryObject *bo) : BO(bo) {}
ObjectCodeEmitter::~ObjectCodeEmitter() {}

/// setBinaryObject - set the BinaryObject we are writting to
void ObjectCodeEmitter::setBinaryObject(BinaryObject *bo) { BO = bo; }

/// emitByte - This callback is invoked when a byte needs to be
/// written to the data stream, without buffer overflow testing.
void ObjectCodeEmitter::emitByte(uint8_t B) {
  BO->emitByte(B);
}

/// emitWordLE - This callback is invoked when a 32-bit word needs to be
/// written to the data stream in little-endian format.
void ObjectCodeEmitter::emitWordLE(uint32_t W) {
  BO->emitWordLE(W);
}

/// emitWordBE - This callback is invoked when a 32-bit word needs to be
/// written to the data stream in big-endian format.
void ObjectCodeEmitter::emitWordBE(uint32_t W) {
  BO->emitWordBE(W);
}

/// emitDWordLE - This callback is invoked when a 64-bit word needs to be
/// written to the data stream in little-endian format.
void ObjectCodeEmitter::emitDWordLE(uint64_t W) {
  BO->emitDWordLE(W);
}

/// emitDWordBE - This callback is invoked when a 64-bit word needs to be
/// written to the data stream in big-endian format.
void ObjectCodeEmitter::emitDWordBE(uint64_t W) {
  BO->emitDWordBE(W);
}

/// emitAlignment - Align 'BO' to the necessary alignment boundary.
void ObjectCodeEmitter::emitAlignment(unsigned Alignment /* 0 */,
                                      uint8_t fill /* 0 */) {
  BO->emitAlignment(Alignment, fill);
}

/// emitULEB128Bytes - This callback is invoked when a ULEB128 needs to be
/// written to the data stream.
void ObjectCodeEmitter::emitULEB128Bytes(uint64_t Value) {
  BO->emitULEB128Bytes(Value);
}

/// emitSLEB128Bytes - This callback is invoked when a SLEB128 needs to be
/// written to the data stream.
void ObjectCodeEmitter::emitSLEB128Bytes(uint64_t Value) {
  BO->emitSLEB128Bytes(Value);
}

/// emitString - This callback is invoked when a String needs to be
/// written to the data stream.
void ObjectCodeEmitter::emitString(const std::string &String) {
  BO->emitString(String);
}

/// getCurrentPCValue - This returns the address that the next emitted byte
/// will be output to.
uintptr_t ObjectCodeEmitter::getCurrentPCValue() const {
  return BO->getCurrentPCOffset();
}

/// getCurrentPCOffset - Return the offset from the start of the emitted
/// buffer that we are currently writing to.
uintptr_t ObjectCodeEmitter::getCurrentPCOffset() const {
  return BO->getCurrentPCOffset();
}

/// addRelocation - Whenever a relocatable address is needed, it should be
/// noted with this interface.
void ObjectCodeEmitter::addRelocation(const MachineRelocation& relocation) {
  BO->addRelocation(relocation);
}

/// StartMachineBasicBlock - This should be called by the target when a new
/// basic block is about to be emitted.  This way the MCE knows where the
/// start of the block is, and can implement getMachineBasicBlockAddress.
void ObjectCodeEmitter::StartMachineBasicBlock(MachineBasicBlock *MBB) {
  if (MBBLocations.size() <= (unsigned)MBB->getNumber())
    MBBLocations.resize((MBB->getNumber()+1)*2);
  MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
}

/// getMachineBasicBlockAddress - Return the address of the specified
/// MachineBasicBlock, only usable after the label for the MBB has been
/// emitted.
uintptr_t
ObjectCodeEmitter::getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
  assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
         MBBLocations[MBB->getNumber()] && "MBB not emitted!");
  return MBBLocations[MBB->getNumber()];
}

/// getJumpTableEntryAddress - Return the address of the jump table with index
/// 'Index' in the function that last called initJumpTableInfo.
uintptr_t ObjectCodeEmitter::getJumpTableEntryAddress(unsigned Index) const {
  assert(JTLocations.size() > Index && "JT not emitted!");
  return JTLocations[Index];
}

/// getConstantPoolEntryAddress - Return the address of the 'Index' entry in
/// the constant pool that was last emitted with the emitConstantPool method.
uintptr_t ObjectCodeEmitter::getConstantPoolEntryAddress(unsigned Index) const {
  assert(CPLocations.size() > Index && "CP not emitted!");
  return CPLocations[Index];
}

/// getConstantPoolEntrySection - Return the section of the 'Index' entry in
/// the constant pool that was last emitted with the emitConstantPool method.
uintptr_t ObjectCodeEmitter::getConstantPoolEntrySection(unsigned Index) const {
  assert(CPSections.size() > Index && "CP not emitted!");
  return CPSections[Index];
}

/// getNoopSize - Returns the size of the no operation instruction

} // end namespace llvm

<commit_msg>Remove accidental commited comment<commit_after>//===-- llvm/CodeGen/ObjectCodeEmitter.cpp -------------------- -*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/BinaryObject.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineRelocation.h"
#include "llvm/CodeGen/ObjectCodeEmitter.h"

//===----------------------------------------------------------------------===//
//                       ObjectCodeEmitter Implementation
//===----------------------------------------------------------------------===//

namespace llvm {

ObjectCodeEmitter::ObjectCodeEmitter() : BO(0) {}
ObjectCodeEmitter::ObjectCodeEmitter(BinaryObject *bo) : BO(bo) {}
ObjectCodeEmitter::~ObjectCodeEmitter() {}

/// setBinaryObject - set the BinaryObject we are writting to
void ObjectCodeEmitter::setBinaryObject(BinaryObject *bo) { BO = bo; }

/// emitByte - This callback is invoked when a byte needs to be
/// written to the data stream, without buffer overflow testing.
void ObjectCodeEmitter::emitByte(uint8_t B) {
  BO->emitByte(B);
}

/// emitWordLE - This callback is invoked when a 32-bit word needs to be
/// written to the data stream in little-endian format.
void ObjectCodeEmitter::emitWordLE(uint32_t W) {
  BO->emitWordLE(W);
}

/// emitWordBE - This callback is invoked when a 32-bit word needs to be
/// written to the data stream in big-endian format.
void ObjectCodeEmitter::emitWordBE(uint32_t W) {
  BO->emitWordBE(W);
}

/// emitDWordLE - This callback is invoked when a 64-bit word needs to be
/// written to the data stream in little-endian format.
void ObjectCodeEmitter::emitDWordLE(uint64_t W) {
  BO->emitDWordLE(W);
}

/// emitDWordBE - This callback is invoked when a 64-bit word needs to be
/// written to the data stream in big-endian format.
void ObjectCodeEmitter::emitDWordBE(uint64_t W) {
  BO->emitDWordBE(W);
}

/// emitAlignment - Align 'BO' to the necessary alignment boundary.
void ObjectCodeEmitter::emitAlignment(unsigned Alignment /* 0 */,
                                      uint8_t fill /* 0 */) {
  BO->emitAlignment(Alignment, fill);
}

/// emitULEB128Bytes - This callback is invoked when a ULEB128 needs to be
/// written to the data stream.
void ObjectCodeEmitter::emitULEB128Bytes(uint64_t Value) {
  BO->emitULEB128Bytes(Value);
}

/// emitSLEB128Bytes - This callback is invoked when a SLEB128 needs to be
/// written to the data stream.
void ObjectCodeEmitter::emitSLEB128Bytes(uint64_t Value) {
  BO->emitSLEB128Bytes(Value);
}

/// emitString - This callback is invoked when a String needs to be
/// written to the data stream.
void ObjectCodeEmitter::emitString(const std::string &String) {
  BO->emitString(String);
}

/// getCurrentPCValue - This returns the address that the next emitted byte
/// will be output to.
uintptr_t ObjectCodeEmitter::getCurrentPCValue() const {
  return BO->getCurrentPCOffset();
}

/// getCurrentPCOffset - Return the offset from the start of the emitted
/// buffer that we are currently writing to.
uintptr_t ObjectCodeEmitter::getCurrentPCOffset() const {
  return BO->getCurrentPCOffset();
}

/// addRelocation - Whenever a relocatable address is needed, it should be
/// noted with this interface.
void ObjectCodeEmitter::addRelocation(const MachineRelocation& relocation) {
  BO->addRelocation(relocation);
}

/// StartMachineBasicBlock - This should be called by the target when a new
/// basic block is about to be emitted.  This way the MCE knows where the
/// start of the block is, and can implement getMachineBasicBlockAddress.
void ObjectCodeEmitter::StartMachineBasicBlock(MachineBasicBlock *MBB) {
  if (MBBLocations.size() <= (unsigned)MBB->getNumber())
    MBBLocations.resize((MBB->getNumber()+1)*2);
  MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
}

/// getMachineBasicBlockAddress - Return the address of the specified
/// MachineBasicBlock, only usable after the label for the MBB has been
/// emitted.
uintptr_t
ObjectCodeEmitter::getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
  assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
         MBBLocations[MBB->getNumber()] && "MBB not emitted!");
  return MBBLocations[MBB->getNumber()];
}

/// getJumpTableEntryAddress - Return the address of the jump table with index
/// 'Index' in the function that last called initJumpTableInfo.
uintptr_t ObjectCodeEmitter::getJumpTableEntryAddress(unsigned Index) const {
  assert(JTLocations.size() > Index && "JT not emitted!");
  return JTLocations[Index];
}

/// getConstantPoolEntryAddress - Return the address of the 'Index' entry in
/// the constant pool that was last emitted with the emitConstantPool method.
uintptr_t ObjectCodeEmitter::getConstantPoolEntryAddress(unsigned Index) const {
  assert(CPLocations.size() > Index && "CP not emitted!");
  return CPLocations[Index];
}

/// getConstantPoolEntrySection - Return the section of the 'Index' entry in
/// the constant pool that was last emitted with the emitConstantPool method.
uintptr_t ObjectCodeEmitter::getConstantPoolEntrySection(unsigned Index) const {
  assert(CPSections.size() > Index && "CP not emitted!");
  return CPSections[Index];
}

} // end namespace llvm

<|endoftext|>


<commit_before>#ifndef CYCLE__H__
#define CYCLE__H__

#include "iterbase.hpp"

#include <utility>
#include <iterator>
#include <initializer_list>

namespace iter {

    //Forward declarations of Cycle and cycle
    template <typename Container>
    class Cycle;

    template <typename Container>
    Cycle<Container> cycle(Container &&);

    template <typename T>
    Cycle<std::initializer_list<T>> cycle(
            std::initializer_list<T> &&);

    template <typename Container>
    class Cycle : public IterBase<Container>{
        private:
            // The cycle function is the only thing allowed to create a Cycle
            friend Cycle cycle<Container>(Container &&);
            template <typename T>
            friend Cycle<std::initializer_list<T>> cycle(
                    std::initializer_list<T> &&);

            using typename IterBase<Container>::contained_iter_type;

            using typename IterBase<Container>::contained_iter_ret;

            Container & container;

            // Value constructor for use only in the cycle function
            Cycle(Container && container) : container(container) { }
            Cycle () = delete;
            Cycle & operator=(const Cycle &) = delete;

        public:
            Cycle(const Cycle &) = default;
            class Iterator {
                private:
                    contained_iter_type sub_iter;
                    const contained_iter_type begin;
                    const contained_iter_type end;
                public:
                    Iterator (contained_iter_type iter,
                            contained_iter_type end) :
                        sub_iter(iter),
                        begin(iter),
                        end(end)
                    { }

                    contained_iter_ret operator*() const {
                        return *this->sub_iter;
                    }

                    Iterator & operator++() {
                        ++this->sub_iter;
                        // reset to beginning upon reaching the end
                        if (!(this->sub_iter != this->end)) {
                            // explicit destruction with placement new in order
                            // to support iterators with no operator=
                            this->sub_iter.~contained_iter_type();
                            new(&this->sub_iter) contained_iter_type(
                                    this->begin);
                        }
                        return *this;
                    }

                    constexpr bool operator!=(const Iterator &) const {
                        return true;
                    }
            };

            Iterator begin() const {
                return Iterator(std::begin(this->container),
                        std::end(this->container));
            }

            Iterator end() const {
                return Iterator(std::end(this->container),
                    std::end(this->container));
            }

    };

    // Helper function to instantiate an Filter
    template <typename Container>
    Cycle<Container> cycle(Container && container) {
        return Cycle<Container>(std::forward<Container>(container));
    }

    template <typename T>
    Cycle<std::initializer_list<T>> cycle(std::initializer_list<T> && il)
    {
        return Cycle<std::initializer_list<T>>(std::move(il));
    }
}

#endif //ifndef CYCLE__H__
<commit_msg>cycle uses new type aliases<commit_after>#ifndef CYCLE__H__
#define CYCLE__H__

#include "iterbase.hpp"

#include <utility>
#include <iterator>
#include <initializer_list>

namespace iter {

    //Forward declarations of Cycle and cycle
    template <typename Container>
    class Cycle;

    template <typename Container>
    Cycle<Container> cycle(Container &&);

    template <typename T>
    Cycle<std::initializer_list<T>> cycle(
            std::initializer_list<T> &&);

    template <typename Container>
    class Cycle {
        private:
            // The cycle function is the only thing allowed to create a Cycle
            friend Cycle cycle<Container>(Container &&);
            template <typename T>
            friend Cycle<std::initializer_list<T>> cycle(
                    std::initializer_list<T> &&);

            Container & container;

            // Value constructor for use only in the cycle function
            Cycle(Container && container) : container(container) { }
            Cycle () = delete;
            Cycle & operator=(const Cycle &) = delete;

        public:
            Cycle(const Cycle &) = default;
            class Iterator {
                private:
                    using iter_type = iterator_type<Container>;
                    iterator_type<Container> sub_iter;
                    const iterator_type<Container> begin;
                    const iterator_type<Container> end;
                public:
                    Iterator (iterator_type<Container> iter,
                            iterator_type<Container> end) :
                        sub_iter(iter),
                        begin(iter),
                        end(end)
                    { }

                    iterator_deref<Container> operator*() const {
                        return *this->sub_iter;
                    }

                    Iterator & operator++() {
                        ++this->sub_iter;
                        // reset to beginning upon reaching the end
                        if (!(this->sub_iter != this->end)) {
                            // explicit destruction with placement new in order
                            // to support iterators with no operator=
                            this->sub_iter.~iter_type();
                            new(&this->sub_iter) iterator_type<Container>(
                                    this->begin);
                        }
                        return *this;
                    }

                    constexpr bool operator!=(const Iterator &) const {
                        return true;
                    }
            };

            Iterator begin() const {
                return Iterator(std::begin(this->container),
                        std::end(this->container));
            }

            Iterator end() const {
                return Iterator(std::end(this->container),
                    std::end(this->container));
            }

    };

    // Helper function to instantiate an Filter
    template <typename Container>
    Cycle<Container> cycle(Container && container) {
        return Cycle<Container>(std::forward<Container>(container));
    }

    template <typename T>
    Cycle<std::initializer_list<T>> cycle(std::initializer_list<T> && il)
    {
        return Cycle<std::initializer_list<T>>(std::move(il));
    }
}

#endif //ifndef CYCLE__H__
<|endoftext|>


<commit_before><commit_msg>Ensures proper sorting order for persistence diagrams<commit_after><|endoftext|>


<commit_before>#line 2 "togo/debug_constraints.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.

@file
@brief Definitions for constraints.
*/

#pragma once

#include <togo/config.hpp>

#if defined(TOGO_USE_CONSTRAINTS)
	#include <togo/traits.hpp>
	#include <type_traits>

	#define TOGO_CONSTRAIN_POD(T)									\
		static_assert(												\
			std::is_standard_layout<T>::value,						\
			"T is not a POD type"									\
		)

	#define TOGO_CONSTRAIN_SAME(T, U)								\
		static_assert(												\
			is_same<T, U>::value,									\
			"T and U are not the same types"						\
		)

	#define TOGO_CONSTRAIN_INTEGRAL(T)								\
		static_assert(												\
			std::is_integral<T>::value,								\
			"T is not an integral type"								\
		)

	#define TOGO_CONSTRAIN_ARITHMETIC(T)							\
		static_assert(												\
			std::is_arithmetic<T>::value,							\
			"T is not an arithmetic type"							\
		)

	#define TOGO_CONSTRAIN_INTEGRAL_ARITHMETIC(T)					\
		static_assert(												\
			std::is_integral<T>::value &&							\
			std::is_arithmetic<T>::value,							\
			"T is not an integral arithmetic type"					\
		)

	#define TOGO_CONSTRAIN_FLOATING_POINT(T)						\
		static_assert(												\
			std::is_floating_point<T>::value,						\
			"T is not a floating-point type"						\
		)

	#define TOGO_CONSTRAIN_UNSIGNED(T)								\
		static_assert(												\
			is_unsigned<T>::value,									\
			"T is not an unsigned arithmetic type"					\
		)

	#define TOGO_CONSTRAIN_COMPARABLE(T)							\
		static_assert(												\
			std::is_pointer<T>::value ||							\
			(														\
				std::is_integral<T>::value &&						\
				std::is_arithmetic<T>::value						\
			),														\
			"T is not a permitted built-in comparable type"			\
		)
#else
	/// Statically assert that type T is of standard layout.
	#define TOGO_CONSTRAIN_POD(T)

	/// Statically assert that type T is the same as type U.
	#define TOGO_CONSTRAIN_SAME(T, U)

	/// Statically assert that type T is an integral type.
	#define TOGO_CONSTRAIN_INTEGRAL(T)

	/// Statically assert that type T is an arithmetic type.
	#define TOGO_CONSTRAIN_ARITHMETIC(T)

	/// Statically assert that type T is an integral arithmetic type.
	#define TOGO_CONSTRAIN_INTEGRAL_ARITHMETIC(T)

	/// Statically assert that type T is a floating-point type.
	#define TOGO_CONSTRAIN_FLOATING_POINT(T)

	/// Statically assert that type T is an unsigned arithmetic type.
	#define TOGO_CONSTRAIN_UNSIGNED(T)

	/// Statically assert that type T is a built-in comparable type.
	///
	/// Comparable types are arithmetic integrals and pointers.
	#define TOGO_CONSTRAIN_COMPARABLE(T)
#endif
<commit_msg>debug_constraints: removed use of stdlib where possible.¹<commit_after>#line 2 "togo/debug_constraints.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.

@file
@brief Definitions for constraints.
*/

#pragma once

#include <togo/config.hpp>

#if defined(TOGO_USE_CONSTRAINTS)
	#include <togo/traits.hpp>
	#include <type_traits>

	#define TOGO_CONSTRAIN_POD(T)									\
		static_assert(												\
			std::is_standard_layout<T>::value,						\
			"T is not a POD type"									\
		)

	#define TOGO_CONSTRAIN_SAME(T, U)								\
		static_assert(												\
			is_same<T, U>::value,									\
			"T and U are not the same types"						\
		)

	#define TOGO_CONSTRAIN_INTEGRAL(T)								\
		static_assert(												\
			is_integral<T>::value,									\
			"T is not an integral type"								\
		)

	#define TOGO_CONSTRAIN_ARITHMETIC(T)							\
		static_assert(												\
			is_arithmetic<T>::value,								\
			"T is not an arithmetic type"							\
		)

	#define TOGO_CONSTRAIN_INTEGRAL_ARITHMETIC(T)					\
		static_assert(												\
			is_integral<T>::value &&								\
			is_arithmetic<T>::value,								\
			"T is not an integral arithmetic type"					\
		)

	#define TOGO_CONSTRAIN_FLOATING_POINT(T)						\
		static_assert(												\
			is_floating_point<T>::value,							\
			"T is not a floating-point type"						\
		)

	#define TOGO_CONSTRAIN_UNSIGNED(T)								\
		static_assert(												\
			is_unsigned<T>::value,									\
			"T is not an unsigned arithmetic type"					\
		)

	#define TOGO_CONSTRAIN_COMPARABLE(T)							\
		static_assert(												\
			is_pointer<T>::value ||									\
			(														\
				is_integral<T>::value &&							\
				is_arithmetic<T>::value								\
			),														\
			"T is not a permitted built-in comparable type"			\
		)
#else
	/// Statically assert that type T is of standard layout.
	#define TOGO_CONSTRAIN_POD(T)

	/// Statically assert that type T is the same as type U.
	#define TOGO_CONSTRAIN_SAME(T, U)

	/// Statically assert that type T is an integral type.
	#define TOGO_CONSTRAIN_INTEGRAL(T)

	/// Statically assert that type T is an arithmetic type.
	#define TOGO_CONSTRAIN_ARITHMETIC(T)

	/// Statically assert that type T is an integral arithmetic type.
	#define TOGO_CONSTRAIN_INTEGRAL_ARITHMETIC(T)

	/// Statically assert that type T is a floating-point type.
	#define TOGO_CONSTRAIN_FLOATING_POINT(T)

	/// Statically assert that type T is an unsigned arithmetic type.
	#define TOGO_CONSTRAIN_UNSIGNED(T)

	/// Statically assert that type T is a built-in comparable type.
	///
	/// Comparable types are arithmetic integrals and pointers.
	#define TOGO_CONSTRAIN_COMPARABLE(T)
#endif
<|endoftext|>