<commit_before>#pragma once

#include "rapidcheck/gen/Tuple.h"
#include "rapidcheck/detail/ApplyTuple.h"

namespace rc {
namespace gen {
namespace detail {

// Member variables
template <typename Type, typename T>
class Lens<T(Type::*)> {
public:
  typedef T(Type::*MemberPtr);
  typedef Type Target;
  typedef T ValueType;

  Lens(MemberPtr ptr)
      : m_ptr(ptr) {}

  template <typename Arg>
  void set(Target &obj, Arg &&arg) const {
    obj.*m_ptr = std::move(std::forward<Arg>(arg));
  }

private:
  MemberPtr m_ptr;
};

// Member functions with single argument
template <typename Type, typename Ret, typename T>
class Lens<Ret (Type::*)(T)> {
public:
  typedef Ret (Type::*MemberPtr)(T);
  typedef Type Target;
  typedef Decay<T> ValueType;

  Lens(MemberPtr ptr)
      : m_ptr(ptr) {}

  template <typename Arg>
  void set(Target &obj, Arg &&arg) const {
    (obj.*m_ptr)(std::forward<Arg>(arg));
  }

private:
  MemberPtr m_ptr;
};

// Member functions with multiple arguments
template <typename Type, typename Ret, typename T1, typename T2, typename... Ts>
class Lens<Ret (Type::*)(T1, T2, Ts...)> {
public:
  typedef Ret (Type::*MemberPtr)(T1, T2, Ts...);
  typedef Type Target;
  typedef std::tuple<Decay<T1>, Decay<T2>, Decay<Ts>...> ValueType;

  Lens(MemberPtr ptr)
      : m_ptr(ptr) {}

  template <typename Arg>
  void set(Target &obj, Arg &&arg) const {
    rc::detail::applyTuple(
        std::forward<Arg>(arg),
        [&](Decay<T1> &&arg1, Decay<T2> &&arg2, Decay<Ts> &&... args) {
          (obj.*m_ptr)(std::move(arg1), std::move(arg2), std::move(args)...);
        });
  }

private:
  MemberPtr m_ptr;
};

template <typename Member, typename SourceType>
struct Binding {
  Binding(Lens<Member> &&l, Gen<SourceType> &&g)
      : lens(std::move(l))
      , gen(std::move(g)) {}

  Lens<Member> lens;
  Gen<SourceType> gen;
};

template <typename T>
T &deref(T &x) {
  return x;
}

template <typename T>
T &deref(std::unique_ptr<T> &x) {
  return *x;
}

template <typename T>
T &deref(std::shared_ptr<T> &x) {
  return *x;
}

template <typename T, typename Indexes, typename... Lenses>
class BuildMapper;

template <typename T, typename... Lenses, std::size_t... Indexes>
class BuildMapper<T, rc::detail::IndexSequence<Indexes...>, Lenses...> {
public:
  BuildMapper(const Lenses &... lenses)
      : m_lenses(std::move(lenses)...) {}

  T operator()(std::tuple<T, typename Lenses::ValueType...> &&tuple) const {
    T &obj = std::get<0>(tuple);
    auto dummy = {(std::get<Indexes>(m_lenses).set(
                       deref(obj), std::move(std::get<Indexes + 1>(tuple))),
                   0)...};
    (void)dummy; // Silence warning

    return std::move(obj);
  }

private:
  std::tuple<Lenses...> m_lenses;
};

} // namespace detail

template <typename T, typename... Args>
Gen<T> construct(Gen<Args>... gens) {
  return gen::map(gen::tuple(std::move(gens)...),
                  [](std::tuple<Args...> &&argsTuple) {
                    return rc::detail::applyTuple(
                        std::move(argsTuple),
                        [](Args &&... args) { return T(std::move(args)...); });
                  });
}

template <typename T, typename Arg, typename... Args>
Gen<T> construct() {
  return gen::construct<T>(gen::arbitrary<Arg>(), gen::arbitrary<Args>()...);
}

template <typename T, typename... Args>
Gen<std::unique_ptr<T>> makeUnique(Gen<Args>... gens) {
  return gen::map(gen::tuple(std::move(gens)...),
                  [](std::tuple<Args...> &&argsTuple) {
                    return rc::detail::applyTuple(
                        std::move(argsTuple),
                        [](Args &&... args) {
                          return std::unique_ptr<T>(new T(std::move(args)...));
                        });
                  });
}

template <typename T, typename... Args>
Gen<std::shared_ptr<T>> makeShared(Gen<Args>... gens) {
  return gen::map(gen::tuple(std::move(gens)...),
                  [](std::tuple<Args...> &&argsTuple) {
                    return rc::detail::applyTuple(std::move(argsTuple),
                                                  [](Args &&... args) {
                                                    return std::make_shared<T>(
                                                        std::move(args)...);
                                                  });
                  });
}

template <typename Member, typename T>
detail::Binding<Member, T> set(Member member, Gen<T> gen) {
  return detail::Binding<Member, T>(detail::Lens<Member>(member),
                                    std::move(gen));
}

template <typename Member>
detail::Binding<Member, typename detail::Lens<Member>::ValueType>
set(Member member) {
  using T = typename detail::Lens<Member>::ValueType;
  return set(member, gen::arbitrary<T>());
}

template <typename T, typename... Members, typename... SourceTypes>
Gen<T> build(Gen<T> gen, const detail::Binding<Members, SourceTypes> &... bs) {
  using Mapper =
      detail::BuildMapper<T,
                          rc::detail::MakeIndexSequence<sizeof...(Members)>,
                          detail::Lens<Members>...>;

  return gen::map(gen::tuple(std::move(gen), std::move(bs.gen)...),
                  Mapper(bs.lens...));
}

template <typename T, typename... Members, typename... SourceTypes>
Gen<T> build(const detail::Binding<Members, SourceTypes> &... bs) {
  return build<T>(fn::constant(shrinkable::lambda([] { return T(); })), bs...);
}

} // namespace gen
} // namespace rc
<commit_msg>Document a GCC hack<commit_after>#pragma once

#include "rapidcheck/gen/Tuple.h"
#include "rapidcheck/detail/ApplyTuple.h"

namespace rc {
namespace gen {
namespace detail {

// Member variables
template <typename Type, typename T>
class Lens<T(Type::*)> {
public:
  typedef T(Type::*MemberPtr);
  typedef Type Target;
  typedef T ValueType;

  Lens(MemberPtr ptr)
      : m_ptr(ptr) {}

  template <typename Arg>
  void set(Target &obj, Arg &&arg) const {
    obj.*m_ptr = std::move(std::forward<Arg>(arg));
  }

private:
  MemberPtr m_ptr;
};

// Member functions with single argument
template <typename Type, typename Ret, typename T>
class Lens<Ret (Type::*)(T)> {
public:
  typedef Ret (Type::*MemberPtr)(T);
  typedef Type Target;
  typedef Decay<T> ValueType;

  Lens(MemberPtr ptr)
      : m_ptr(ptr) {}

  template <typename Arg>
  void set(Target &obj, Arg &&arg) const {
    (obj.*m_ptr)(std::forward<Arg>(arg));
  }

private:
  MemberPtr m_ptr;
};

// Member functions with multiple arguments
template <typename Type, typename Ret, typename T1, typename T2, typename... Ts>
class Lens<Ret (Type::*)(T1, T2, Ts...)> {
public:
  typedef Ret (Type::*MemberPtr)(T1, T2, Ts...);
  typedef Type Target;
  typedef std::tuple<Decay<T1>, Decay<T2>, Decay<Ts>...> ValueType;

  Lens(MemberPtr ptr)
      : m_ptr(ptr) {}

  template <typename Arg>
  void set(Target &obj, Arg &&arg) const {
    rc::detail::applyTuple(
        std::forward<Arg>(arg),
        [&](Decay<T1> &&arg1, Decay<T2> &&arg2, Decay<Ts> &&... args) {
          (obj.*m_ptr)(std::move(arg1), std::move(arg2), std::move(args)...);
        });
  }

private:
  MemberPtr m_ptr;
};

template <typename Member, typename SourceType>
struct Binding {
  Binding(Lens<Member> &&l, Gen<SourceType> &&g)
      : lens(std::move(l))
      , gen(std::move(g)) {}

  Lens<Member> lens;
  Gen<SourceType> gen;
};

template <typename T>
T &deref(T &x) {
  return x;
}

template <typename T>
T &deref(std::unique_ptr<T> &x) {
  return *x;
}

template <typename T>
T &deref(std::shared_ptr<T> &x) {
  return *x;
}

template <typename T, typename Indexes, typename... Lenses>
class BuildMapper;

template <typename T, typename... Lenses, std::size_t... Indexes>
class BuildMapper<T, rc::detail::IndexSequence<Indexes...>, Lenses...> {
public:
  BuildMapper(const Lenses &... lenses)
      : m_lenses(std::move(lenses)...) {}

  T operator()(std::tuple<T, typename Lenses::ValueType...> &&tuple) const {
    T &obj = std::get<0>(tuple);
    auto dummy = {(std::get<Indexes>(m_lenses).set(
                       deref(obj), std::move(std::get<Indexes + 1>(tuple))),
                   0)...};
    (void)dummy; // Silence warning

    return std::move(obj);
  }

private:
  std::tuple<Lenses...> m_lenses;
};

} // namespace detail

template <typename T, typename... Args>
Gen<T> construct(Gen<Args>... gens) {
  return gen::map(gen::tuple(std::move(gens)...),
                  [](std::tuple<Args...> &&argsTuple) {
                    return rc::detail::applyTuple(
                        std::move(argsTuple),
                        [](Args &&... args) { return T(std::move(args)...); });
                  });
}

template <typename T, typename Arg, typename... Args>
Gen<T> construct() {
  return gen::construct<T>(gen::arbitrary<Arg>(), gen::arbitrary<Args>()...);
}

template <typename T, typename... Args>
Gen<std::unique_ptr<T>> makeUnique(Gen<Args>... gens) {
  return gen::map(gen::tuple(std::move(gens)...),
                  [](std::tuple<Args...> &&argsTuple) {
                    return rc::detail::applyTuple(
                        std::move(argsTuple),
                        [](Args &&... args) {
                          return std::unique_ptr<T>(new T(std::move(args)...));
                        });
                  });
}

template <typename T, typename... Args>
Gen<std::shared_ptr<T>> makeShared(Gen<Args>... gens) {
  return gen::map(gen::tuple(std::move(gens)...),
                  [](std::tuple<Args...> &&argsTuple) {
                    return rc::detail::applyTuple(std::move(argsTuple),
                                                  [](Args &&... args) {
                                                    return std::make_shared<T>(
                                                        std::move(args)...);
                                                  });
                  });
}

template <typename Member, typename T>
detail::Binding<Member, T> set(Member member, Gen<T> gen) {
  return detail::Binding<Member, T>(detail::Lens<Member>(member),
                                    std::move(gen));
}

template <typename Member>
detail::Binding<Member, typename detail::Lens<Member>::ValueType>
set(Member member) {
  using T = typename detail::Lens<Member>::ValueType;
  return set(member, gen::arbitrary<T>());
}

template <typename T, typename... Members, typename... SourceTypes>
Gen<T> build(Gen<T> gen, const detail::Binding<Members, SourceTypes> &... bs) {
  using Mapper =
      detail::BuildMapper<T,
                          rc::detail::MakeIndexSequence<sizeof...(Members)>,
                          detail::Lens<Members>...>;

  // GCC HACK - Variadics + lambdas don't work very well in GCC so we use an old
  // fashioned function object (the Mapper thing) to prevent GCC from crashing.
  // Use lambdas and applyTuple once we drop support for the crashing ones.
  return gen::map(gen::tuple(std::move(gen), std::move(bs.gen)...),
                  Mapper(bs.lens...));
}

template <typename T, typename... Members, typename... SourceTypes>
Gen<T> build(const detail::Binding<Members, SourceTypes> &... bs) {
  return build<T>(fn::constant(shrinkable::lambda([] { return T(); })), bs...);
}

} // namespace gen
} // namespace rc
<|endoftext|>


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

#ifndef RJ_UI_TEXTBOX_HPP
#define RJ_UI_TEXTBOX_HPP

#include "widget.hpp"
#include <rectojump/global/common.hpp>
#include <rectojump/shared/input.hpp>
#include <rectojump/shared/utils.hpp>

#include <mlk/containers/container_utl.h>
#include <mlk/time/simple_timer.h>

#include <stack>

namespace rj
{
	namespace ui
	{
		class textbox : public ui::widget, public sf::Transformable
		{
			sf::RectangleShape m_shape;
			sf::Text m_text, m_password_text;
			sf::VertexArray m_cursor{sf::Lines};
			sf::Color m_cursorcolor{sf::Color::Black};
			std::stack<char> m_char_stack;

			mlk::ullong m_cursor_blinkinterval{700};
			mlk::tm::simple_timer m_blinktimer{m_cursor_blinkinterval};
			bool m_focus{false}, m_cursor_visible{true}, m_password_mode{false};

		public:
			mlk::slot<> on_key_return;

			textbox() = default;

			textbox(const vec2f& size, const vec2f& pos, const sf::Font& font, const std::string& text = "") :
				m_shape{size},
				m_text{text, font},
				m_password_text{"", font}
			{
				this->setPosition(pos);
				this->init();
			}

			void update(dur)
			{
				if(inp::is_btn_pressed(btn::Left))
				{
					if(this->getGlobalBounds().intersects(inp::get_mousebounds<true>()))
						m_focus = true;
					else m_focus = false;
				}

				if(!m_focus)
					return;

				// input
				if(inp::get_last_textinput() != 0)
					this->update_text(inp::get_last_textinput());

				// cursor
				if(m_blinktimer.timed_out())
				{
					m_cursor_visible = !m_cursor_visible;
					m_blinktimer.restart();
				}
			}

			void addChar(char c) noexcept
			{if(!m_focus) return; this->update_text(c);}

			// sfml-func-style interface
			// setters
			void setSize(const vec2f& size) noexcept
			{m_shape.setSize(size); this->update_text_pos(); this->update_cursor();}

			void setFillColor(const sf::Color& color) noexcept
			{m_shape.setFillColor(color);}

			void setOutlineColor(const sf::Color& color) noexcept
			{m_shape.setOutlineColor(color);}

			void setOutlineThickness(float thickness) noexcept
			{m_shape.setOutlineThickness(thickness);}

			void setCursorBlinkInterval(mlk::ullong interval) noexcept
			{m_cursor_blinkinterval = interval;}

			void setCursorColor(const sf::Color& color) noexcept
			{m_cursorcolor = color; this->update_cursor();}

			void setTextColor(const sf::Color& color) noexcept
			{m_text.setColor(color); m_password_text.setColor(color);}

			void setTextSize(mlk::uint size) noexcept
			{m_text.setCharacterSize(size); m_password_text.setCharacterSize(size); this->update_text_pos(); this->update_cursor();}

			void setText(const std::string& str)
			{
				m_text.setString("");
				m_char_stack = std::stack<char>{};
				for(const auto& a : str)
					this->update_text(a);
			}

			void setPasswordMode(bool b) noexcept
			{m_password_mode = b; this->update_text_pos(); this->update_cursor();}

			// getters
			const vec2f& getSize() const noexcept
			{return m_shape.getSize();}

			const sf::Color& getFillColor() const noexcept
			{return m_shape.getFillColor();}

			const sf::Color& getOutlineColor() const noexcept
			{return m_shape.getOutlineColor();}

			float getOutlineThickness() const noexcept
			{return m_shape.getOutlineThickness();}

			mlk::ullong getCursorBlinkInterval() const noexcept
			{return m_cursor_blinkinterval;}

			const sf::Color& getCursorColor() const noexcept
			{return m_cursorcolor;}

			const sf::Color& getTextColor() const noexcept
			{return m_text.getColor();}

			mlk::uint getTextSize() const noexcept
			{return m_text.getCharacterSize();}

			std::string getText() const noexcept
			{
				std::string result;
				auto char_stack(m_char_stack);
				auto size(char_stack.size());
				for(std::size_t i{0}; i < size; ++i)
				{
					result += char_stack.top();
					char_stack.pop();
				}
				mlk::cnt::reverse_all(result);
				return result += m_text.getString();
			}

			sf::FloatRect getGlobalBounds() const noexcept
			{return {bounds_from_vec({this->getPosition().x - this->getOrigin().x, this->getPosition().y - this->getOrigin().y}, m_shape.getSize())};}

			bool getPasswordMode() const noexcept
			{return m_password_mode;}

		private:
			void init() noexcept
			{
				m_cursor.append({{0.f, 0.f}, m_cursorcolor});
				m_cursor.append({{0.f, 0.f}, m_cursorcolor});
				this->update_text_pos();
				this->update_cursor();
				this->update_password_mode();
				m_blinktimer.run();
			}

			void draw(sf::RenderTarget& target, sf::RenderStates states) const override
			{
				auto s(states);

				// shape
				s.transform = sf::Transformable::getTransform();
				target.draw(m_shape, s);

				// text
				if(m_password_mode)
					target.draw(m_password_text, s);
				else
					target.draw(m_text, s);

				// cursor
				if(m_cursor_visible && m_focus)
					target.draw(m_cursor, s);
			}

			void update_password_mode()
			{
				auto passwordchars(m_text.getString().toAnsiString());
				mlk::stl_string::set_all('*', passwordchars);
				m_password_text.setString(passwordchars);
			}

			void update_text(std::uint32_t u)
			{
				// return event
				if(u == 0x0d)
				{
					on_key_return();
					return;
				}

				if(u != 0x08 && (u < 0x20 || u > 0x7E))
					return;

				auto text(m_text.getString());
				auto shape_bounds(m_shape.getGlobalBounds());
				auto text_bounds(m_text.getGlobalBounds());

				// check bounds
				if(text_bounds.left + text_bounds.width > shape_bounds.left + shape_bounds.width)
				{
					// textbounds are bigger than shapebounds
					// save and delete first char
					m_char_stack.push(*text.begin());
					text.erase(0, 1);
				}

				// backspace
				if(u == 0x08)
				{
					// erase last char
					if(!text.isEmpty())
						text.erase(text.getSize() - 1, 1);

					// get last removed char
					if(!m_char_stack.empty())
					{
						text.insert(0, m_char_stack.top());
						m_char_stack.pop();
					}
				}
				else text += u; // append input char to full text

				m_text.setString(text);

				if(m_password_mode)
					this->update_password_mode();

				this->update_cursor();
			}

			void update_text_pos()
			{
				auto shape_bounds(m_shape.getGlobalBounds());
				auto text_bounds(m_text.getGlobalBounds());
				auto origin(vec2f{0.f, text_bounds.height} / 2.f);
				vec2f pos{shape_bounds.left, shape_bounds.top + shape_bounds.height / 2.f};

				m_text.setOrigin(origin);
				m_text.setPosition(pos);
				m_password_text.setOrigin(origin);
				m_password_text.setPosition(pos);
			}

			void update_cursor()
			{
				auto shape_bounds(m_shape.getGlobalBounds());
				auto text_bounds(m_password_mode ? m_password_text.getGlobalBounds() : m_text.getGlobalBounds());
				auto cursor_margin_tb(0.1f * shape_bounds.height); // top / bottom
				m_cursor[0].position = {shape_bounds.left + text_bounds.width, shape_bounds.top + cursor_margin_tb};
				m_cursor[0].color = m_cursorcolor;
				m_cursor[1].position = {shape_bounds.left + text_bounds.width, shape_bounds.top + shape_bounds.height - cursor_margin_tb};
				m_cursor[1].color = m_cursorcolor;
			}
		};
	}
}

#endif // RJ_UI_TEXTBOX_HPP
<commit_msg>ui > textbox: using inp::was_real_mousepress_left()<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_UI_TEXTBOX_HPP
#define RJ_UI_TEXTBOX_HPP

#include "widget.hpp"
#include <rectojump/global/common.hpp>
#include <rectojump/shared/input.hpp>
#include <rectojump/shared/utils.hpp>

#include <mlk/containers/container_utl.h>
#include <mlk/time/simple_timer.h>

#include <stack>

namespace rj
{
	namespace ui
	{
		class textbox : public ui::widget, public sf::Transformable
		{
			sf::RectangleShape m_shape;
			sf::Text m_text, m_password_text;
			sf::VertexArray m_cursor{sf::Lines};
			sf::Color m_cursorcolor{sf::Color::Black};
			std::stack<char> m_char_stack;

			mlk::ullong m_cursor_blinkinterval{700};
			mlk::tm::simple_timer m_blinktimer{m_cursor_blinkinterval};
			bool m_focus{false}, m_cursor_visible{true}, m_password_mode{false};

		public:
			mlk::slot<> on_key_return;

			textbox() = default;

			textbox(const vec2f& size, const vec2f& pos, const sf::Font& font, const std::string& text = "") :
				m_shape{size},
				m_text{text, font},
				m_password_text{"", font}
			{
				this->setPosition(pos);
				this->init();
			}

			void update(dur)
			{
				if(inp::was_real_mousepress_left())
				{
					if(this->getGlobalBounds().intersects(inp::get_mousebounds<true>()))
						m_focus = true;
					else m_focus = false;
				}

				if(!m_focus)
					return;

				// input
				if(inp::get_last_textinput() != 0)
					this->update_text(inp::get_last_textinput());

				// cursor
				if(m_blinktimer.timed_out())
				{
					m_cursor_visible = !m_cursor_visible;
					m_blinktimer.restart();
				}
			}

			void addChar(char c) noexcept
			{if(!m_focus) return; this->update_text(c);}

			// sfml-func-style interface
			// setters
			void setSize(const vec2f& size) noexcept
			{m_shape.setSize(size); this->update_text_pos(); this->update_cursor();}

			void setFillColor(const sf::Color& color) noexcept
			{m_shape.setFillColor(color);}

			void setOutlineColor(const sf::Color& color) noexcept
			{m_shape.setOutlineColor(color);}

			void setOutlineThickness(float thickness) noexcept
			{m_shape.setOutlineThickness(thickness);}

			void setCursorBlinkInterval(mlk::ullong interval) noexcept
			{m_cursor_blinkinterval = interval;}

			void setCursorColor(const sf::Color& color) noexcept
			{m_cursorcolor = color; this->update_cursor();}

			void setTextColor(const sf::Color& color) noexcept
			{m_text.setColor(color); m_password_text.setColor(color);}

			void setTextSize(mlk::uint size) noexcept
			{m_text.setCharacterSize(size); m_password_text.setCharacterSize(size); this->update_text_pos(); this->update_cursor();}

			void setText(const std::string& str)
			{
				m_text.setString("");
				m_char_stack = std::stack<char>{};
				for(const auto& a : str)
					this->update_text(a);
			}

			void setPasswordMode(bool b) noexcept
			{m_password_mode = b; this->update_text_pos(); this->update_cursor();}

			// getters
			const vec2f& getSize() const noexcept
			{return m_shape.getSize();}

			const sf::Color& getFillColor() const noexcept
			{return m_shape.getFillColor();}

			const sf::Color& getOutlineColor() const noexcept
			{return m_shape.getOutlineColor();}

			float getOutlineThickness() const noexcept
			{return m_shape.getOutlineThickness();}

			mlk::ullong getCursorBlinkInterval() const noexcept
			{return m_cursor_blinkinterval;}

			const sf::Color& getCursorColor() const noexcept
			{return m_cursorcolor;}

			const sf::Color& getTextColor() const noexcept
			{return m_text.getColor();}

			mlk::uint getTextSize() const noexcept
			{return m_text.getCharacterSize();}

			std::string getText() const noexcept
			{
				std::string result;
				auto char_stack(m_char_stack);
				auto size(char_stack.size());
				for(std::size_t i{0}; i < size; ++i)
				{
					result += char_stack.top();
					char_stack.pop();
				}
				mlk::cnt::reverse_all(result);
				return result += m_text.getString();
			}

			sf::FloatRect getGlobalBounds() const noexcept
			{return {bounds_from_vec({this->getPosition().x - this->getOrigin().x, this->getPosition().y - this->getOrigin().y}, m_shape.getSize())};}

			bool getPasswordMode() const noexcept
			{return m_password_mode;}

		private:
			void init() noexcept
			{
				m_cursor.append({{0.f, 0.f}, m_cursorcolor});
				m_cursor.append({{0.f, 0.f}, m_cursorcolor});
				this->update_text_pos();
				this->update_cursor();
				this->update_password_mode();
				m_blinktimer.run();
			}

			void draw(sf::RenderTarget& target, sf::RenderStates states) const override
			{
				auto s(states);

				// shape
				s.transform = sf::Transformable::getTransform();
				target.draw(m_shape, s);

				// text
				if(m_password_mode)
					target.draw(m_password_text, s);
				else
					target.draw(m_text, s);

				// cursor
				if(m_cursor_visible && m_focus)
					target.draw(m_cursor, s);
			}

			void update_password_mode()
			{
				auto passwordchars(m_text.getString().toAnsiString());
				mlk::stl_string::set_all('*', passwordchars);
				m_password_text.setString(passwordchars);
			}

			void update_text(std::uint32_t u)
			{
				// return event
				if(u == 0x0d)
				{
					on_key_return();
					return;
				}

				if(u != 0x08 && (u < 0x20 || u > 0x7E))
					return;

				auto text(m_text.getString());
				auto shape_bounds(m_shape.getGlobalBounds());
				auto text_bounds(m_text.getGlobalBounds());

				// check bounds
				if(text_bounds.left + text_bounds.width > shape_bounds.left + shape_bounds.width)
				{
					// textbounds are bigger than shapebounds
					// save and delete first char
					m_char_stack.push(*text.begin());
					text.erase(0, 1);
				}

				// backspace
				if(u == 0x08)
				{
					// erase last char
					if(!text.isEmpty())
						text.erase(text.getSize() - 1, 1);

					// get last removed char
					if(!m_char_stack.empty())
					{
						text.insert(0, m_char_stack.top());
						m_char_stack.pop();
					}
				}
				else text += u; // append input char to full text

				m_text.setString(text);

				if(m_password_mode)
					this->update_password_mode();

				this->update_cursor();
			}

			void update_text_pos()
			{
				auto shape_bounds(m_shape.getGlobalBounds());
				auto text_bounds(m_text.getGlobalBounds());
				auto origin(vec2f{0.f, text_bounds.height} / 2.f);
				vec2f pos{shape_bounds.left, shape_bounds.top + shape_bounds.height / 2.f};

				m_text.setOrigin(origin);
				m_text.setPosition(pos);
				m_password_text.setOrigin(origin);
				m_password_text.setPosition(pos);
			}

			void update_cursor()
			{
				auto shape_bounds(m_shape.getGlobalBounds());
				auto text_bounds(m_password_mode ? m_password_text.getGlobalBounds() : m_text.getGlobalBounds());
				auto cursor_margin_tb(0.1f * shape_bounds.height); // top / bottom
				m_cursor[0].position = {shape_bounds.left + text_bounds.width, shape_bounds.top + cursor_margin_tb};
				m_cursor[0].color = m_cursorcolor;
				m_cursor[1].position = {shape_bounds.left + text_bounds.width, shape_bounds.top + shape_bounds.height - cursor_margin_tb};
				m_cursor[1].color = m_cursorcolor;
			}
		};
	}
}

#endif // RJ_UI_TEXTBOX_HPP
<|endoftext|>


<commit_before>#ifndef V_SMC_INTERNAL_COMMON_HPP
#define V_SMC_INTERNAL_COMMON_HPP

#ifndef __STDC_CONSTANT_MACROS
#define __STDC_CONSTANT_MACROS
#endif // __STDC_CONSTANT_MACROS

#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <pair>
#include <map>
#include <set>
#include <deque>
#include <vector>
#include <iostream>
#include <stringstream>
#include <string>
#include <stdexcept>

#ifdef __INTEL_COMPILER
// #pragma warning(push)
#pragma warning(disable:2196)
#pragma warning(disable:2536)
#endif // __INTEL_COMPILER

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wall"
#pragma clang diagnostic ignored "-Wunique-enum"
#endif // __clang__

#include <Eigen/Dense>

#ifdef __INTEL_COMPILER
// #pragma warning(pop)
#endif // __INTEL_COMPILER

#ifdef __clang__
#pragma clang diagnostic pop
#endif // __clang__

#include <vSMC/internal/config.hpp>
#include <vSMC/internal/function.hpp>
#include <vSMC/rng/random.hpp>

#ifndef V_SMC_INDEX_TYPE
#define V_SMC_INDEX_TYPE EIGEN_DEFAULT_DENSE_INDEX_TYPE
#endif // V_SMC_INDEX_TYPE

namespace vSMC {

template <typename T> class Sampler;
template <typename T> class Particle;
template <typename T> class Monitor;
template <typename T> class Path;

template <typename T> class SingleParticle;
template <typename T> class ConstSingleParticle;
template <unsigned Dim = 1, typename T = double> class StateBase;

template <typename T> class InitializeSeq;
template <typename T> class MoveSeq;
template <typename T, unsigned Dim = 1> class MonitorSeq;
template <typename T> class PathSeq;

template <typename T> class InitializeTBB;
template <typename T> class MoveTBB;
template <typename T, unsigned Dim = 1> class MonitorTBB;
template <typename T> class PathTBB;

template <typename Base> class InitializeBase;
template <typename Base> class MoveBase;
template <typename Base> class MonitorBase;
template <typename Base> class PathBase;

/// \brief Resample scheme
///
/// \li MULTINOMIAL Multinomial resampling
/// \li RESIDUAL Reisudal resampling
/// \li STRATIFIED Startified resampling
/// \li SYSTEMATIC Systematic resampling
/// \li RESIDUAL_STRATIFIED Stratified resampling on the residuals
/// \li RESIDUAL_SYSTEMATIC Systematic resampling on the residuals
enum ResampleScheme {
    MULTINOMIAL,
    RESIDUAL,
    STRATIFIED,
    SYSTEMATIC,
    RESIDUAL_STRATIFIED,
    RESIDUAL_SYSTEMATIC
};

} // namespace vSMC

#endif // V_SMC_INTERNAL_COMMON_HPP
<commit_msg>fix header names<commit_after>#ifndef V_SMC_INTERNAL_COMMON_HPP
#define V_SMC_INTERNAL_COMMON_HPP

#ifndef __STDC_CONSTANT_MACROS
#define __STDC_CONSTANT_MACROS
#endif // __STDC_CONSTANT_MACROS

#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <utility>
#include <map>
#include <set>
#include <deque>
#include <vector>
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>

#ifdef __INTEL_COMPILER
// #pragma warning(push)
#pragma warning(disable:2196)
#pragma warning(disable:2536)
#endif // __INTEL_COMPILER

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wall"
#pragma clang diagnostic ignored "-Wunique-enum"
#endif // __clang__

#include <Eigen/Dense>

#ifdef __INTEL_COMPILER
// #pragma warning(pop)
#endif // __INTEL_COMPILER

#ifdef __clang__
#pragma clang diagnostic pop
#endif // __clang__

#include <vSMC/internal/config.hpp>
#include <vSMC/internal/function.hpp>
#include <vSMC/rng/random.hpp>

#ifndef V_SMC_INDEX_TYPE
#define V_SMC_INDEX_TYPE EIGEN_DEFAULT_DENSE_INDEX_TYPE
#endif // V_SMC_INDEX_TYPE

namespace vSMC {

template <typename T> class Sampler;
template <typename T> class Particle;
template <typename T> class Monitor;
template <typename T> class Path;

template <typename T> class SingleParticle;
template <typename T> class ConstSingleParticle;
template <unsigned Dim = 1, typename T = double> class StateBase;

template <typename T> class InitializeSeq;
template <typename T> class MoveSeq;
template <typename T, unsigned Dim = 1> class MonitorSeq;
template <typename T> class PathSeq;

template <typename T> class InitializeTBB;
template <typename T> class MoveTBB;
template <typename T, unsigned Dim = 1> class MonitorTBB;
template <typename T> class PathTBB;

template <typename Base> class InitializeBase;
template <typename Base> class MoveBase;
template <typename Base> class MonitorBase;
template <typename Base> class PathBase;

/// \brief Resample scheme
///
/// \li MULTINOMIAL Multinomial resampling
/// \li RESIDUAL Reisudal resampling
/// \li STRATIFIED Startified resampling
/// \li SYSTEMATIC Systematic resampling
/// \li RESIDUAL_STRATIFIED Stratified resampling on the residuals
/// \li RESIDUAL_SYSTEMATIC Systematic resampling on the residuals
enum ResampleScheme {
    MULTINOMIAL,
    RESIDUAL,
    STRATIFIED,
    SYSTEMATIC,
    RESIDUAL_STRATIFIED,
    RESIDUAL_SYSTEMATIC
};

} // namespace vSMC

#endif // V_SMC_INTERNAL_COMMON_HPP
<|endoftext|>


<commit_before>#ifndef V_SMC_INTERNAL_COMMON_HPP
#define V_SMC_INTERNAL_COMMON_HPP

#ifndef __STDC_CONSTANT_MACROS
#define __STDC_CONSTANT_MACROS
#endif // __STDC_CONSTANT_MACROS

#include <cassert>
#include <cmath>
#include <cstddef>
#include <deque>
#include <map>
#include <ostream>
#include <set>
#include <string>
#include <vector>

#ifdef __INTEL_COMPILER
// #pragma warning(push)
#pragma warning(disable:2196)
#pragma warning(disable:2536)
#endif // __INTEL_COMPILER

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wall"
#pragma clang diagnostic ignored "-Wunique-enum"
#endif // __clang__

#include <Eigen/Dense>

#ifdef __INTEL_COMPILER
// #pragma warning(pop)
#endif // __INTEL_COMPILER

#ifdef __clang__
#pragma clang diagnostic pop
#endif // __clang__

#include <vSMC/internal/config.hpp>
#include <vSMC/internal/function.hpp>
#include <vSMC/rng/random.hpp>

#ifndef V_SMC_INDEX_TYPE
#define V_SMC_INDEX_TYPE EIGEN_DEFAULT_DENSE_INDEX_TYPE
#endif // V_SMC_INDEX_TYPE

namespace vSMC {

template <typename T> class Sampler;
template <typename T> class Particle;
template <typename T> class Monitor;
template <typename T> class Path;

template <typename T> class SingleParticle;
template <typename T> class ConstSingleParticle;
template <unsigned Dim = 1, typename T = double> class StateBase;

template <typename T> class InitializeSeq;
template <typename T> class MoveSeq;
template <typename T, unsigned Dim = 1> class MonitorSeq;
template <typename T> class PathSeq;

template <typename T> class InitializeTBB;
template <typename T> class MoveTBB;
template <typename T, unsigned Dim = 1> class MonitorTBB;
template <typename T> class PathTBB;

template <typename Base> class InitializeBase;
template <typename Base> class MoveBase;
template <typename Base> class MonitorBase;
template <typename Base> class PathBase;

/// \brief Resample scheme
///
/// \li MULTINOMIAL Multinomial resampling
/// \li RESIDUAL Reisudal resampling
/// \li STRATIFIED Startified resampling
/// \li SYSTEMATIC Systematic resampling
/// \li RESIDUAL_STRATIFIED Stratified resampling on the residuals
/// \li RESIDUAL_SYSTEMATIC Systematic resampling on the residuals
enum ResampleScheme {
    MULTINOMIAL,
    RESIDUAL,
    STRATIFIED,
    SYSTEMATIC,
    RESIDUAL_STRATIFIED,
    RESIDUAL_SYSTEMATIC
};

} // namespace vSMC

#endif // V_SMC_INTERNAL_COMMON_HPP
<commit_msg>add stream header<commit_after>#ifndef V_SMC_INTERNAL_COMMON_HPP
#define V_SMC_INTERNAL_COMMON_HPP

#ifndef __STDC_CONSTANT_MACROS
#define __STDC_CONSTANT_MACROS
#endif // __STDC_CONSTANT_MACROS

#include <cassert>
#include <cmath>
#include <cstddef>
#include <map>
#include <set>
#include <deque>
#include <vector>
#include <istream>
#include <ostream>
#include <string>

#ifdef __INTEL_COMPILER
// #pragma warning(push)
#pragma warning(disable:2196)
#pragma warning(disable:2536)
#endif // __INTEL_COMPILER

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wall"
#pragma clang diagnostic ignored "-Wunique-enum"
#endif // __clang__

#include <Eigen/Dense>

#ifdef __INTEL_COMPILER
// #pragma warning(pop)
#endif // __INTEL_COMPILER

#ifdef __clang__
#pragma clang diagnostic pop
#endif // __clang__

#include <vSMC/internal/config.hpp>
#include <vSMC/internal/function.hpp>
#include <vSMC/rng/random.hpp>

#ifndef V_SMC_INDEX_TYPE
#define V_SMC_INDEX_TYPE EIGEN_DEFAULT_DENSE_INDEX_TYPE
#endif // V_SMC_INDEX_TYPE

namespace vSMC {

template <typename T> class Sampler;
template <typename T> class Particle;
template <typename T> class Monitor;
template <typename T> class Path;

template <typename T> class SingleParticle;
template <typename T> class ConstSingleParticle;
template <unsigned Dim = 1, typename T = double> class StateBase;

template <typename T> class InitializeSeq;
template <typename T> class MoveSeq;
template <typename T, unsigned Dim = 1> class MonitorSeq;
template <typename T> class PathSeq;

template <typename T> class InitializeTBB;
template <typename T> class MoveTBB;
template <typename T, unsigned Dim = 1> class MonitorTBB;
template <typename T> class PathTBB;

template <typename Base> class InitializeBase;
template <typename Base> class MoveBase;
template <typename Base> class MonitorBase;
template <typename Base> class PathBase;

/// \brief Resample scheme
///
/// \li MULTINOMIAL Multinomial resampling
/// \li RESIDUAL Reisudal resampling
/// \li STRATIFIED Startified resampling
/// \li SYSTEMATIC Systematic resampling
/// \li RESIDUAL_STRATIFIED Stratified resampling on the residuals
/// \li RESIDUAL_SYSTEMATIC Systematic resampling on the residuals
enum ResampleScheme {
    MULTINOMIAL,
    RESIDUAL,
    STRATIFIED,
    SYSTEMATIC,
    RESIDUAL_STRATIFIED,
    RESIDUAL_SYSTEMATIC
};

} // namespace vSMC

#endif // V_SMC_INTERNAL_COMMON_HPP
<|endoftext|>


<commit_before>/*
    open source routing machine
    Copyright (C) Dennis Luxen, 2010

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO General Public License as published by
the Free Software Foundation; either version 3 of the License, or
any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
or see http://www.gnu.org/licenses/agpl.txt.
 */

#include "Library/OSRM.h"

#include "Server/ServerFactory.h"

#include "Util/IniFile.h"
#include "Util/InputFileUtil.h"
#include "Util/OpenMPWrapper.h"
#include "Util/SimpleLogger.h"
#include "Util/UUID.h"

#ifdef __linux__
#include "Util/LinuxStackTrace.h"
#include <sys/mman.h>
#endif

#include <signal.h>

#include <boost/bind.hpp>
#include <boost/date_time.hpp>
#include <boost/thread.hpp>

#include <iostream>

#ifdef _WIN32
boost::function0<void> console_ctrl_function;

BOOL WINAPI console_ctrl_handler(DWORD ctrl_type)
{
  switch (ctrl_type)
  {
  case CTRL_C_EVENT:
  case CTRL_BREAK_EVENT:
  case CTRL_CLOSE_EVENT:
  case CTRL_SHUTDOWN_EVENT:
    console_ctrl_function();
    return TRUE;
  default:
    return FALSE;
  }
}
#endif

int main (int argc, char * argv[]) {
    LogPolicy::GetInstance().Unmute();
#ifdef __linux__
    if(!mlockall(MCL_CURRENT | MCL_FUTURE))
        SimpleLogger().Write(logWARNING) << "Process " << argv[0] << "could not be locked to RAM";
#endif
#ifdef __linux__

    installCrashHandler(argv[0]);
#endif

	// Bug - testing not necessary.  testDataFiles also tries to open the first
	// argv, which is the name of exec file
    //if(testDataFiles(argc, argv)==false) {
        //std::cerr << "[error] at least one data file name seems to be bogus!" << std::endl;
        //exit(-1);
    //}

    try {
        //std::cout << "fingerprint: " << UUID::GetInstance().GetUUID() << std::endl;

        std::cout << "starting up engines, compiled at " <<
                                        __DATE__ << ", " __TIME__ << std::endl;

#ifndef _WIN32
        int sig = 0;
        sigset_t new_mask;
        sigset_t old_mask;
        sigfillset(&new_mask);
        pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask);
#endif

        IniFile serverConfig((argc > 1 ? argv[1] : "server.ini"));
        OSRM routing_machine((argc > 1 ? argv[1] : "server.ini"));

        Server * s = ServerFactory::CreateServer(serverConfig);
        s->GetRequestHandlerPtr().RegisterRoutingMachine(&routing_machine);

        boost::thread t(boost::bind(&Server::Run, s));

#ifndef _WIN32
        sigset_t wait_mask;
        pthread_sigmask(SIG_SETMASK, &old_mask, 0);
        sigemptyset(&wait_mask);
        sigaddset(&wait_mask, SIGINT);
        sigaddset(&wait_mask, SIGQUIT);
        sigaddset(&wait_mask, SIGTERM);
        pthread_sigmask(SIG_BLOCK, &wait_mask, 0);
        std::cout << "[server] running and waiting for requests" << std::endl;
        sigwait(&wait_mask, &sig);
#else
        // Set console control handler to allow server to be stopped.
        console_ctrl_function = boost::bind(&Server::Stop, s);
        SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
        std::cout << "[server] running and waiting for requests" << std::endl;
        s->Run();
#endif

        std::cout << "[server] initiating shutdown" << std::endl;
        s->Stop();
        std::cout << "[server] stopping threads" << std::endl;

        if(!t.timed_join(boost::posix_time::seconds(2))) {
       	    SimpleLogger().Write(logDEBUG) << "Threads did not finish within 2 seconds. Hard abort!";
        }

        std::cout << "[server] freeing objects" << std::endl;
        delete s;
        std::cout << "[server] shutdown completed" << std::endl;
    } catch (std::exception& e) {
        std::cerr << "[fatal error] exception: " << e.what() << std::endl;
    }
#ifdef __linux__
    munlockall();
#endif

    return 0;
}
<commit_msg>Fix coverity error 1061544<commit_after>/*
    open source routing machine
    Copyright (C) Dennis Luxen, 2010

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO General Public License as published by
the Free Software Foundation; either version 3 of the License, or
any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
or see http://www.gnu.org/licenses/agpl.txt.
 */

#include "Library/OSRM.h"

#include "Server/ServerFactory.h"

#include "Util/IniFile.h"
#include "Util/InputFileUtil.h"
#include "Util/OpenMPWrapper.h"
#include "Util/SimpleLogger.h"
#include "Util/UUID.h"

#ifdef __linux__
#include "Util/LinuxStackTrace.h"
#include <sys/mman.h>
#endif

#include <signal.h>

#include <boost/bind.hpp>
#include <boost/date_time.hpp>
#include <boost/thread.hpp>

#include <iostream>

#ifdef _WIN32
boost::function0<void> console_ctrl_function;

BOOL WINAPI console_ctrl_handler(DWORD ctrl_type)
{
  switch (ctrl_type)
  {
  case CTRL_C_EVENT:
  case CTRL_BREAK_EVENT:
  case CTRL_CLOSE_EVENT:
  case CTRL_SHUTDOWN_EVENT:
    console_ctrl_function();
    return TRUE;
  default:
    return FALSE;
  }
}
#endif

int main (int argc, char * argv[]) {
    try {
        LogPolicy::GetInstance().Unmute();
#ifdef __linux__
        if(!mlockall(MCL_CURRENT | MCL_FUTURE)) {
            SimpleLogger().Write(logWARNING) << "Process " << argv[0] << "could not be locked to RAM";
        }
#endif
#ifdef __linux__

    installCrashHandler(argv[0]);
#endif

	// Bug - testing not necessary.  testDataFiles also tries to open the first
	// argv, which is the name of exec file
    //if(testDataFiles(argc, argv)==false) {
        //std::cerr << "[error] at least one data file name seems to be bogus!" << std::endl;
        //exit(-1);
    //}

        //std::cout << "fingerprint: " << UUID::GetInstance().GetUUID() << std::endl;

        SimpleLogger().Write(logWARNING) <<
            "starting up engines, compiled at " << __DATE__ << ", " __TIME__;

#ifndef _WIN32
        int sig = 0;
        sigset_t new_mask;
        sigset_t old_mask;
        sigfillset(&new_mask);
        pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask);
#endif

        IniFile serverConfig((argc > 1 ? argv[1] : "server.ini"));
        OSRM routing_machine((argc > 1 ? argv[1] : "server.ini"));

        Server * s = ServerFactory::CreateServer(serverConfig);
        s->GetRequestHandlerPtr().RegisterRoutingMachine(&routing_machine);

        boost::thread t(boost::bind(&Server::Run, s));

#ifndef _WIN32
        sigset_t wait_mask;
        pthread_sigmask(SIG_SETMASK, &old_mask, 0);
        sigemptyset(&wait_mask);
        sigaddset(&wait_mask, SIGINT);
        sigaddset(&wait_mask, SIGQUIT);
        sigaddset(&wait_mask, SIGTERM);
        pthread_sigmask(SIG_BLOCK, &wait_mask, 0);
        std::cout << "[server] running and waiting for requests" << std::endl;
        sigwait(&wait_mask, &sig);
#else
        // Set console control handler to allow server to be stopped.
        console_ctrl_function = boost::bind(&Server::Stop, s);
        SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
        std::cout << "[server] running and waiting for requests" << std::endl;
        s->Run();
#endif

        std::cout << "[server] initiating shutdown" << std::endl;
        s->Stop();
        std::cout << "[server] stopping threads" << std::endl;

        if(!t.timed_join(boost::posix_time::seconds(2))) {
       	    SimpleLogger().Write(logDEBUG) << "Threads did not finish within 2 seconds. Hard abort!";
        }

        std::cout << "[server] freeing objects" << std::endl;
        delete s;
        std::cout << "[server] shutdown completed" << std::endl;
    } catch (std::exception& e) {
        std::cerr << "[fatal error] exception: " << e.what() << std::endl;
    }
#ifdef __linux__
    munlockall();
#endif

    return 0;
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// File: mframeworkimpl.hpp
//
// Desc: Data Mining Framework.
//
// Copyright (c) 2014-2018. veyesys.com All rights reserved.
//------------------------------------------------------------------------------
#ifndef __M_FRAME_WORK_IMPL_HPP__
#define __M_FRAME_WORK_IMPL_HPP__

inline MFramework::MFramework(Factory &pFactory)
:m_pFactory(pFactory)
{
}
inline MFramework::~MFramework()
{
}

inline astring MFramework::GetPluginPath()
{
#ifdef WIN32
    char exeFullPath[MAX_PATH]; // Full path

    string strPath = "";

    GetModuleFileNameA(NULL,exeFullPath, MAX_PATH);
    strPath=(string)exeFullPath;    // Get full path of the file

    int pos = strPath.find_last_of('\\', strPath.length());

    return strPath.substr(0, pos);  // Return the directory without the file name
#else
    return "./";
#endif
}

inline BOOL MFramework::Init()
{
	/* Get all the modules list and init  */
	std::string dir;

	//dir = Path::current();
	std::string pluginPath = GetPluginPath() + "/mplugins/";

	dir = pluginPath;

	try
	{
		DirectoryIterator it(dir);
		DirectoryIterator end;
		while (it != end)
		{
			/* loop for each dir */
			if (it->isDirectory() == true)
			{
				astring strName = it->path();
				try
				{
					DirectoryIterator it2(it->path());
					DirectoryIterator end2;

					while (it2 != end2)
					{
						astring strName2 = it2->path();
						if (it2->path().find("mplugin") != std::string::npos)
						{
							//Find a plugin
							// Call mmodule to add
							astring strPluginName = it2->path();
						}
						++it2;
					}
				}
				catch (Poco::Exception& exc)
				{
					continue;
				}
			}

#if 0
			Path p(it->path());
			if ()
			std::cout << (it->isDirectory() ? 'd' : '-')
					  << (it->canRead() ? 'r' : '-')
					  << (it->canWrite() ? 'w' : '-')
					  << ' '
					  << DateTimeFormatter::format(it->getLastModified(), DateTimeFormat::SORTABLE_FORMAT)
					  << ' '
					  << p.getFileName()
					  << std::endl;
#endif
			++it;
		}
	}
	catch (Poco::Exception& exc)
	{
		std::cerr << exc.displayText() << std::endl;
	 	VDC_DEBUG( "Plugin init error \n");

		return FALSE;
	}
	/* Get all the device and add channel to all the modules */

	return TRUE;
}

inline BOOL MFramework::RetHandler(s32 id, MiningRet& ret, void * pParam)
{
	int dummy = errno;
	MFramework *pMFramework = (MFramework*)pParam;

	if (pMFramework)
	{
		return pMFramework->RetHandler1(id, ret);
	}

	return TRUE;
}

inline BOOL MFramework::RetHandler1(s32 id, MiningRet& ret)
{
	m_RetQueue.post(ret);

	return TRUE;
}

inline void MFramework::run()
{
	MiningRet ret;
	while (m_bExit != TRUE)
	{
		VDC_DEBUG("MFramework runing\n");
		if (m_RetQueue.size() > 0)
		{
			ret = m_RetQueue.pop();
			//send the ret va data to factory for showing
			continue;
		}else
		{
			ve_sleep(1000);
		}
	}
	return;
}

inline BOOL MFramework::DeviceChangeCallbackFunc(void* pData,
								FactoryDeviceChangeData change)
{
	if (pData)
	{
		MFramework * pthread = (MFramework *)pData;
		pthread->DeviceChangeCallbackFunc1(change);
	}
	return true;
}
inline BOOL MFramework::DeviceChangeCallbackFunc1(FactoryDeviceChangeData change)
{
	VDC_DEBUG( "Event Device Change Callback %d type %d Begin\n", change.id, change.type);

	if (change.type == FACTORY_DEVICE_OFFLINE)
	{

	}
	if (change.type == FACTORY_DEVICE_ONLINE)
	{

	}
	VDC_DEBUG( "Event Device Change Callback %d type %d End \n", change.id, change.type);

	return TRUE;
}

#endif /* __M_FRAME_WORK_HPP__ */
<commit_msg>debug mining<commit_after>//------------------------------------------------------------------------------
// File: mframeworkimpl.hpp
//
// Desc: Data Mining Framework.
//
// Copyright (c) 2014-2018. veyesys.com All rights reserved.
//------------------------------------------------------------------------------
#ifndef __M_FRAME_WORK_IMPL_HPP__
#define __M_FRAME_WORK_IMPL_HPP__

inline MFramework::MFramework(Factory &pFactory)
:m_pFactory(pFactory)
{
}
inline MFramework::~MFramework()
{
}

inline astring MFramework::GetPluginPath()
{
#ifdef WIN32
    char exeFullPath[MAX_PATH]; // Full path

    string strPath = "";

    GetModuleFileNameA(NULL,exeFullPath, MAX_PATH);
    strPath=(string)exeFullPath;    // Get full path of the file

    int pos = strPath.find_last_of('\\', strPath.length());

    return strPath.substr(0, pos);  // Return the directory without the file name
#else
    return "./";
#endif
}

inline BOOL MFramework::Init()
{
	/* Get all the modules list and init  */
	std::string dir;

	//dir = Path::current();
	std::string pluginPath = GetPluginPath() + "/mplugins/";

	dir = pluginPath;

	try
	{
		DirectoryIterator it(dir);
		DirectoryIterator end;
		while (it != end)
		{
			/* loop for each dir */
			if (it->isDirectory() == true)
			{
				astring strName = it->path();
				try
				{
					DirectoryIterator it2(it->path());
					DirectoryIterator end2;

					while (it2 != end2)
					{
						astring strName2 = it2->path();
						if (it2->path().find("mplugin") != std::string::npos)
						{
							//Find a plugin
							// Call mmodule to add
							astring strPluginName = it2->path();
							MiningModule * pModule =
									new MiningModule(strPluginName);
							if (pModule && pModule->Valid() == TRUE)
							{
								m_MModules[strPluginName] = pModule;
							}

						}
						++it2;
					}
				}
				catch (Poco::Exception& exc)
				{
					continue;
				}
			}

			++it;
		}
	}
	catch (Poco::Exception& exc)
	{
		std::cerr << exc.displayText() << std::endl;
	 	VDC_DEBUG( "Plugin init error \n");

		return FALSE;
	}
	/* Get all the device and add channel to all the modules */

	return TRUE;
}

inline BOOL MFramework::RetHandler(s32 id, MiningRet& ret, void * pParam)
{
	int dummy = errno;
	MFramework *pMFramework = (MFramework*)pParam;

	if (pMFramework)
	{
		return pMFramework->RetHandler1(id, ret);
	}

	return TRUE;
}

inline BOOL MFramework::RetHandler1(s32 id, MiningRet& ret)
{
	m_RetQueue.post(ret);

	return TRUE;
}

inline void MFramework::run()
{
	MiningRet ret;
	while (m_bExit != TRUE)
	{
		VDC_DEBUG("MFramework runing\n");
		if (m_RetQueue.size() > 0)
		{
			ret = m_RetQueue.pop();
			//send the ret va data to factory for showing
			continue;
		}else
		{
			ve_sleep(1000);
		}
	}
	return;
}

inline BOOL MFramework::DeviceChangeCallbackFunc(void* pData,
								FactoryDeviceChangeData change)
{
	if (pData)
	{
		MFramework * pthread = (MFramework *)pData;
		pthread->DeviceChangeCallbackFunc1(change);
	}
	return true;
}
inline BOOL MFramework::DeviceChangeCallbackFunc1(FactoryDeviceChangeData change)
{
	VDC_DEBUG( "Event Device Change Callback %d type %d Begin\n", change.id, change.type);

	if (change.type == FACTORY_DEVICE_OFFLINE)
	{

	}
	if (change.type == FACTORY_DEVICE_ONLINE)
	{

	}
	VDC_DEBUG( "Event Device Change Callback %d type %d End \n", change.id, change.type);

	return TRUE;
}

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


<commit_before>#include "rtkfdk_ggo.h"
#include "rtkGgoFunctions.h"
#include "rtkConfiguration.h"

#include "itkThreeDCircularProjectionGeometryXMLFile.h"
#include "itkProjectionsReader.h"
#include "itkFFTRampImageFilter.h"
#include "itkFDKWeightProjectionFilter.h"

#include "itkFDKBackProjectionImageFilter.h"
#ifdef CUDA_FOUND
#  include "itkCudaFDKBackProjectionImageFilter.h"
#endif

#include <itkImageFileWriter.h>
#include <itkRegularExpressionSeriesFileNames.h>
#include <itkTimeProbe.h>
#include <itkStreamingImageFilter.h>

int main(int argc, char * argv[])
{
  GGO(rtkfdk, args_info);

  typedef float OutputPixelType;
  const unsigned int Dimension = 3;

  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;

  // Generate file names
  itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New();
  names->SetDirectory(args_info.path_arg);
  names->SetNumericSort(false);
  names->SetRegularExpression(args_info.regexp_arg);
  names->SetSubMatch(0);

  // Projections reader
  typedef itk::ProjectionsReader< OutputImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileNames( names->GetFileNames() );
  reader->GenerateOutputInformation();

  // Geometry
  itk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader = itk::ThreeDCircularProjectionGeometryXMLFileReader::New();
  geometryReader->SetFilename(args_info.geometry_arg);
  geometryReader->GenerateOutputInformation();

  // Weight projections according to fdk algorithm
  typedef itk::FDKWeightProjectionFilter< OutputImageType > WeightFilterType;
  WeightFilterType::Pointer weightFilter = WeightFilterType::New();
  weightFilter->SetInput( reader->GetOutput() );
  weightFilter->SetSourceToDetectorDistance( geometryReader->GetOutputObject()->GetSourceToDetectorDistance() );

  // Ramp filter
  typedef itk::FFTRampImageFilter<OutputImageType> RampFilterType;
  RampFilterType::Pointer rampFilter = RampFilterType::New();
  rampFilter->SetInput( weightFilter->GetOutput() );
  rampFilter->SetTruncationCorrection(args_info.pad_arg);

  // Streaming filter
  typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamerType;
  StreamerType::Pointer streamer = StreamerType::New();
  streamer->SetInput( rampFilter->GetOutput() );
  streamer->SetNumberOfStreamDivisions( 1 + reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() / (1024*1024*4) );

  // Try to do all 2D pre-processing
  try {
    streamer->Update();
  } catch( itk::ExceptionObject & err ) {
    std::cerr << "ExceptionObject caught !" << std::endl;
    std::cerr << err << std::endl;
    return EXIT_FAILURE;
  }

  // Create reconstructed volume
  OutputImageType::Pointer tomography = rtk::CreateImageFromGgo<OutputImageType>(args_info);

  // Backprojection
  typedef itk::FDKBackProjectionImageFilter<OutputImageType, OutputImageType> BackProjectionFilterType;
  BackProjectionFilterType::Pointer bpFilter;
  if(!strcmp(args_info.hardware_arg, "cpu"))
    bpFilter = BackProjectionFilterType::New();
  else if(!strcmp(args_info.hardware_arg, "cuda"))
    {
#ifdef CUDA_FOUND
    bpFilter = itk::CudaFDKBackProjectionImageFilter::New();
#else
    std::cerr << "The program has not been compiled with cuda option" << std::endl;
    return EXIT_FAILURE;
#endif
    }
  bpFilter->SetInput( 0, tomography );
  bpFilter->SetInput( 1, streamer->GetOutput() );
  bpFilter->SetGeometry( geometryReader->GetOutputObject() );
  bpFilter->SetInPlace( true );

  // Write
  typedef itk::ImageFileWriter<  OutputImageType >  WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( args_info.output_arg );
  writer->SetInput( bpFilter->GetOutput() );

  try {
    writer->Update();
  } catch( itk::ExceptionObject & err ) {
    std::cerr << "ExceptionObject caught !" << std::endl;
    std::cerr << err << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}
<commit_msg>Fixed compilation issues with CUDA_FOUND<commit_after>#include "rtkfdk_ggo.h"
#include "rtkGgoFunctions.h"
#include "rtkConfiguration.h"

#include "itkThreeDCircularProjectionGeometryXMLFile.h"
#include "itkProjectionsReader.h"
#include "itkFFTRampImageFilter.h"
#include "itkFDKWeightProjectionFilter.h"

#include "itkFDKBackProjectionImageFilter.h"
#if CUDA_FOUND
#  include "itkCudaFDKBackProjectionImageFilter.h"
#endif

#include <itkImageFileWriter.h>
#include <itkRegularExpressionSeriesFileNames.h>
#include <itkTimeProbe.h>
#include <itkStreamingImageFilter.h>

int main(int argc, char * argv[])
{
  GGO(rtkfdk, args_info);

  typedef float OutputPixelType;
  const unsigned int Dimension = 3;

  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;

  // Generate file names
  itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New();
  names->SetDirectory(args_info.path_arg);
  names->SetNumericSort(false);
  names->SetRegularExpression(args_info.regexp_arg);
  names->SetSubMatch(0);

  // Projections reader
  typedef itk::ProjectionsReader< OutputImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileNames( names->GetFileNames() );
  reader->GenerateOutputInformation();

  // Geometry
  itk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader = itk::ThreeDCircularProjectionGeometryXMLFileReader::New();
  geometryReader->SetFilename(args_info.geometry_arg);
  geometryReader->GenerateOutputInformation();

  // Weight projections according to fdk algorithm
  typedef itk::FDKWeightProjectionFilter< OutputImageType > WeightFilterType;
  WeightFilterType::Pointer weightFilter = WeightFilterType::New();
  weightFilter->SetInput( reader->GetOutput() );
  weightFilter->SetSourceToDetectorDistance( geometryReader->GetOutputObject()->GetSourceToDetectorDistance() );

  // Ramp filter
  typedef itk::FFTRampImageFilter<OutputImageType> RampFilterType;
  RampFilterType::Pointer rampFilter = RampFilterType::New();
  rampFilter->SetInput( weightFilter->GetOutput() );
  rampFilter->SetTruncationCorrection(args_info.pad_arg);

  // Streaming filter
  typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamerType;
  StreamerType::Pointer streamer = StreamerType::New();
  streamer->SetInput( rampFilter->GetOutput() );
  streamer->SetNumberOfStreamDivisions( 1 + reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() / (1024*1024*4) );

  // Try to do all 2D pre-processing
  try {
    streamer->Update();
  } catch( itk::ExceptionObject & err ) {
    std::cerr << "ExceptionObject caught !" << std::endl;
    std::cerr << err << std::endl;
    return EXIT_FAILURE;
  }

  // Create reconstructed volume
  OutputImageType::Pointer tomography = rtk::CreateImageFromGgo<OutputImageType>(args_info);

  // Backprojection
  typedef itk::FDKBackProjectionImageFilter<OutputImageType, OutputImageType> BackProjectionFilterType;
  BackProjectionFilterType::Pointer bpFilter;
  if(!strcmp(args_info.hardware_arg, "cpu"))
    bpFilter = BackProjectionFilterType::New();
  else if(!strcmp(args_info.hardware_arg, "cuda"))
    {
#if CUDA_FOUND
    bpFilter = itk::CudaFDKBackProjectionImageFilter::New();
#else
    std::cerr << "The program has not been compiled with cuda option" << std::endl;
    return EXIT_FAILURE;
#endif
    }
  bpFilter->SetInput( 0, tomography );
  bpFilter->SetInput( 1, streamer->GetOutput() );
  bpFilter->SetGeometry( geometryReader->GetOutputObject() );
  bpFilter->SetInPlace( true );

  // Write
  typedef itk::ImageFileWriter<  OutputImageType >  WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( args_info.output_arg );
  writer->SetInput( bpFilter->GetOutput() );

  try {
    writer->Update();
  } catch( itk::ExceptionObject & err ) {
    std::cerr << "ExceptionObject caught !" << std::endl;
    std::cerr << err << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#pragma once

#include <gcl/mp/concepts.hpp>

namespace gcl::mp::value_traits
{
    template <auto... values>
    requires(std::equality_comparable_with<
             decltype(std::get<0>(std::tuple{values...})),
             decltype(values)>&&...) constexpr static auto equal_v = []() consteval
    {
        return ((values == std::get<0>(std::tuple{values...})) && ...);
    }
    ();
    template <auto... values>
    constexpr static auto not_equal_v = not equal_v<values...>;
}

namespace gcl::mp::value_traits::tests::equal
{
    static_assert(equal_v<>);
    static_assert(equal_v<true>);
    static_assert(equal_v<true, true>);
    static_assert(equal_v<true, true, true>);
    static_assert(equal_v<true, true, true, true>);

    static_assert(not not_equal_v<true>);
    static_assert(not_equal_v<true, false>);
    static_assert(not_equal_v<false, true>);
    static_assert(not_equal_v<false, true, true>);
    static_assert(not_equal_v<true, false, true>);
    static_assert(not_equal_v<true, true, false>);
    static_assert(not_equal_v<false, true, true, true>);
    static_assert(not_equal_v<true, false, true, true>);
    static_assert(not_equal_v<true, true, false, true>);
    static_assert(not_equal_v<true, true, true, false>);
}<commit_msg>[mp::value_traits] : equal_v : other implementation as comment, as only supported by Clang yet<commit_after>#pragma once

#include <gcl/mp/concepts.hpp>

namespace gcl::mp::value_traits
{
    template <auto... values>
    requires(std::equality_comparable_with<
             decltype(std::get<0>(std::tuple{values...})),
             decltype(values)>&&...) constexpr static auto equal_v = []() consteval
    {
        return ((values == std::get<0>(std::tuple{values...})) && ...);
    }
    ();
    // Only works for Clang yet, since 11.0.0
    // template <auto first_value, std::equality_comparable_with<decltype(first_value)> auto... values>
    // constexpr static auto equal_v = []() consteval
    // {
    //     return ((values == first_value) && ...);
    // }
    // ();
    template <auto... values>
    constexpr static auto not_equal_v = not equal_v<values...>;
}

namespace gcl::mp::value_traits::tests::equal
{
    static_assert(equal_v<true>);
    static_assert(equal_v<true, true>);
    static_assert(equal_v<true, true, true>);
    static_assert(equal_v<true, true, true, true>);

    static_assert(not not_equal_v<true>);
    static_assert(not_equal_v<true, false>);
    static_assert(not_equal_v<false, true>);
    static_assert(not_equal_v<false, true, true>);
    static_assert(not_equal_v<true, false, true>);
    static_assert(not_equal_v<true, true, false>);
    static_assert(not_equal_v<false, true, true, true>);
    static_assert(not_equal_v<true, false, true, true>);
    static_assert(not_equal_v<true, true, false, true>);
    static_assert(not_equal_v<true, true, true, false>);
}<|endoftext|>


<commit_before>#pragma once
#include <arm_neon.h>

// architecture-specific implementations of primitives for ARM NEON
// the tiling strategies are named as:
// _tile<lhs-rows><depth-elems><rhs-rows>

template <typename AccType>
void gemmBinary_neon_tile4x2x2(uint64_t * A, uint64_t * BT, AccType * CT, AccType alpha,
uint64_t rowsA, uint64_t depth_words, uint64_t rowsBT) {
  const uint64_t Atile = 4, BTtile = 2, DepthTile = 2;
  const size_t num_acc = Atile*BTtile;
  assert(rowsA % Atile == 0);
  assert(depth_words % DepthTile == 0);
  assert(rowsBT % BTTile == 0);

  for(uint64_t rBT = 0; rBT < rowsBT; rBT += BTtile) {
    uint64_t * BTptr = &BT[rBT * depth_words];
    for(uint64_t rA = 0; rA < rowsA; rA += Atile) {
      uint64_t * Aptr = &A[rA * depth_words];
      uint64_t acc[num_acc] = {0};
      uint8x16_t acc_neon[num_acc];
      // TODO could keep things in 16-bit accumulators for perf.
      uint64x2_t acc2_neon[num_acc];
      // initialize accumulators to zero
      for(size_t init = 0; init < num_acc; init++) {
        acc_neon[init] = vcombine_u8(vcreate_u8(0), vcreate_u8(0));
        acc2_neon[init] = vcombine_u64(vcreate_u64(0), vcreate_u64(0));
      }

      for(uint64_t d = 0; d < depth_words; d += DepthTile) {
        uint8x16_t a0, b0, a1, b1, a2, a3;

        a0 = vld1q_u8((uint8_t *) &Aptr[d + 0*depth_words]);
        a1 = vld1q_u8((uint8_t *) &Aptr[d + 1*depth_words]);
        a2 = vld1q_u8((uint8_t *) &Aptr[d + 2*depth_words]);
        a3 = vld1q_u8((uint8_t *) &Aptr[d + 3*depth_words]);
        b0 = vld1q_u8((uint8_t *) &BTptr[d]);
        b1 = vld1q_u8((uint8_t *) &BTptr[d + depth_words]);

        acc_neon[0] = vaddq_u8(acc_neon[0], vcntq_u8(vandq_u8(a0, b0)));
        acc_neon[1] = vaddq_u8(acc_neon[1], vcntq_u8(vandq_u8(a0, b1)));
        acc_neon[2] = vaddq_u8(acc_neon[2], vcntq_u8(vandq_u8(a1, b0)));
        acc_neon[3] = vaddq_u8(acc_neon[3], vcntq_u8(vandq_u8(a1, b1)));
        acc_neon[4] = vaddq_u8(acc_neon[4], vcntq_u8(vandq_u8(a2, b0)));
        acc_neon[5] = vaddq_u8(acc_neon[5], vcntq_u8(vandq_u8(a2, b1)));
        acc_neon[6] = vaddq_u8(acc_neon[6], vcntq_u8(vandq_u8(a3, b0)));
        acc_neon[7] = vaddq_u8(acc_neon[7], vcntq_u8(vandq_u8(a3, b1)));

        if((d & 7L) == 7L) {
          // hsum over 8-bit accumulators when end or overflow
          for(size_t init = 0; init < num_acc; init++) {
            acc2_neon[init] = vaddq_u64(acc2_neon[init], vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(acc_neon[init]))));
            acc_neon[init] = vcombine_u8(vcreate_u8(0), vcreate_u8(0));
          }
        }
      }
      /* move into regular accumulators */
      for(size_t init = 0; init < num_acc; init++) {
        uint64_t tmp[2];
        acc2_neon[init] = vaddq_u64(acc2_neon[init], vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(acc_neon[init]))));
        vst1q_u64(tmp, acc2_neon[init]);
        acc[init] = tmp[0] + tmp[1];
      }

      for(uint64_t at = 0; at < Atile; at++) {
        for(uint64_t bt = 0; bt < BTtile; bt++) {
          CT[(rBT + bt) * rowsA + (rA + at)] += acc[at * BTtile + bt] * alpha;
        }
      }
    }
  }
}

/* Bit-serial GEMM via a series of calls to gemmBinary.
   Note that rhs must be given in transposed form, and the result is also
   produced transposed.
*/
template <typename AccType>
void gemmBitSerial_neon_usingBinary(BitSerialMatrix * lhs, BitSerialMatrix * rhs, AccType * res) {
  // ensure that matrix shapes are compatible
  assert(lhs->ncols == rhs->ncols);
  const uint64_t lhsbits = lhs->nbits;
  const uint64_t rhsbits = rhs->nbits;
  // clear contents of result matrix by setting everything to zero
  memset(res, 0, lhs->nrows*rhs->nrows*sizeof(AccType));
  // call binary GEMM for each bit position
  for(uint64_t lbit = 0; lbit < lhsbits; lbit++) {
    bool neg_lhs = lhs->issigned && (lbit == lhsbits-1);
    for(uint64_t rbit = 0; rbit < rhsbits; rbit++) {
      bool neg_rhs = rhs->issigned && (rbit == rhsbits-1);
      bool neg = neg_rhs ^ neg_lhs;
      AccType alpha = neg ? -(1 << (lbit+rbit)) : (1 << (lbit+rbit));
      if(lhs->nrows % 4 == 0 && lhs->wordsPerRow() % 2 == 0 && rhs->nrows % 2 == 0) {
        gemmBinary_neon_tile4x2x2(lhs->bitplaneptr(lbit), rhs->bitplaneptr(rbit), res, alpha, lhs->nrows, lhs->wordsPerRow(), rhs->nrows);
      }
      else {
        gemmBinary_generic_naive(lhs->bitplaneptr(lbit), rhs->bitplaneptr(rbit), res, alpha, lhs->nrows, lhs->wordsPerRow(), rhs->nrows);
      }
    }
  }
}
<commit_msg>typo fix<commit_after>#pragma once
#include <arm_neon.h>

// architecture-specific implementations of primitives for ARM NEON
// the tiling strategies are named as:
// _tile<lhs-rows><depth-elems><rhs-rows>

template <typename AccType>
void gemmBinary_neon_tile4x2x2(uint64_t * A, uint64_t * BT, AccType * CT, AccType alpha,
uint64_t rowsA, uint64_t depth_words, uint64_t rowsBT) {
  const uint64_t Atile = 4, BTtile = 2, DepthTile = 2;
  const size_t num_acc = Atile*BTtile;
  assert(rowsA % Atile == 0);
  assert(depth_words % DepthTile == 0);
  assert(rowsBT % BTtile == 0);

  for(uint64_t rBT = 0; rBT < rowsBT; rBT += BTtile) {
    uint64_t * BTptr = &BT[rBT * depth_words];
    for(uint64_t rA = 0; rA < rowsA; rA += Atile) {
      uint64_t * Aptr = &A[rA * depth_words];
      uint64_t acc[num_acc] = {0};
      uint8x16_t acc_neon[num_acc];
      // TODO could keep things in 16-bit accumulators for perf.
      uint64x2_t acc2_neon[num_acc];
      // initialize accumulators to zero
      for(size_t init = 0; init < num_acc; init++) {
        acc_neon[init] = vcombine_u8(vcreate_u8(0), vcreate_u8(0));
        acc2_neon[init] = vcombine_u64(vcreate_u64(0), vcreate_u64(0));
      }

      for(uint64_t d = 0; d < depth_words; d += DepthTile) {
        uint8x16_t a0, b0, a1, b1, a2, a3;

        a0 = vld1q_u8((uint8_t *) &Aptr[d + 0*depth_words]);
        a1 = vld1q_u8((uint8_t *) &Aptr[d + 1*depth_words]);
        a2 = vld1q_u8((uint8_t *) &Aptr[d + 2*depth_words]);
        a3 = vld1q_u8((uint8_t *) &Aptr[d + 3*depth_words]);
        b0 = vld1q_u8((uint8_t *) &BTptr[d]);
        b1 = vld1q_u8((uint8_t *) &BTptr[d + depth_words]);

        acc_neon[0] = vaddq_u8(acc_neon[0], vcntq_u8(vandq_u8(a0, b0)));
        acc_neon[1] = vaddq_u8(acc_neon[1], vcntq_u8(vandq_u8(a0, b1)));
        acc_neon[2] = vaddq_u8(acc_neon[2], vcntq_u8(vandq_u8(a1, b0)));
        acc_neon[3] = vaddq_u8(acc_neon[3], vcntq_u8(vandq_u8(a1, b1)));
        acc_neon[4] = vaddq_u8(acc_neon[4], vcntq_u8(vandq_u8(a2, b0)));
        acc_neon[5] = vaddq_u8(acc_neon[5], vcntq_u8(vandq_u8(a2, b1)));
        acc_neon[6] = vaddq_u8(acc_neon[6], vcntq_u8(vandq_u8(a3, b0)));
        acc_neon[7] = vaddq_u8(acc_neon[7], vcntq_u8(vandq_u8(a3, b1)));

        if((d & 7L) == 7L) {
          // hsum over 8-bit accumulators when end or overflow
          for(size_t init = 0; init < num_acc; init++) {
            acc2_neon[init] = vaddq_u64(acc2_neon[init], vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(acc_neon[init]))));
            acc_neon[init] = vcombine_u8(vcreate_u8(0), vcreate_u8(0));
          }
        }
      }
      /* move into regular accumulators */
      for(size_t init = 0; init < num_acc; init++) {
        uint64_t tmp[2];
        acc2_neon[init] = vaddq_u64(acc2_neon[init], vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(acc_neon[init]))));
        vst1q_u64(tmp, acc2_neon[init]);
        acc[init] = tmp[0] + tmp[1];
      }

      for(uint64_t at = 0; at < Atile; at++) {
        for(uint64_t bt = 0; bt < BTtile; bt++) {
          CT[(rBT + bt) * rowsA + (rA + at)] += acc[at * BTtile + bt] * alpha;
        }
      }
    }
  }
}

/* Bit-serial GEMM via a series of calls to gemmBinary.
   Note that rhs must be given in transposed form, and the result is also
   produced transposed.
*/
template <typename AccType>
void gemmBitSerial_neon_usingBinary(BitSerialMatrix * lhs, BitSerialMatrix * rhs, AccType * res) {
  // ensure that matrix shapes are compatible
  assert(lhs->ncols == rhs->ncols);
  const uint64_t lhsbits = lhs->nbits;
  const uint64_t rhsbits = rhs->nbits;
  // clear contents of result matrix by setting everything to zero
  memset(res, 0, lhs->nrows*rhs->nrows*sizeof(AccType));
  // call binary GEMM for each bit position
  for(uint64_t lbit = 0; lbit < lhsbits; lbit++) {
    bool neg_lhs = lhs->issigned && (lbit == lhsbits-1);
    for(uint64_t rbit = 0; rbit < rhsbits; rbit++) {
      bool neg_rhs = rhs->issigned && (rbit == rhsbits-1);
      bool neg = neg_rhs ^ neg_lhs;
      AccType alpha = neg ? -(1 << (lbit+rbit)) : (1 << (lbit+rbit));
      if(lhs->nrows % 4 == 0 && lhs->wordsPerRow() % 2 == 0 && rhs->nrows % 2 == 0) {
        gemmBinary_neon_tile4x2x2(lhs->bitplaneptr(lbit), rhs->bitplaneptr(rbit), res, alpha, lhs->nrows, lhs->wordsPerRow(), rhs->nrows);
      }
      else {
        gemmBinary_generic_naive(lhs->bitplaneptr(lbit), rhs->bitplaneptr(rbit), res, alpha, lhs->nrows, lhs->wordsPerRow(), rhs->nrows);
      }
    }
  }
}
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file rlp.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 * RLP test functions.
 */

#include <fstream>
#include <sstream>
#include "JsonSpiritHeaders.h"
#include <libdevcore/Log.h>
#include <libdevcore/RLP.h>
#include <libdevcore/Common.h>
#include <boost/test/unit_test.hpp>
#include <algorithm>

using namespace std;
using namespace dev;
namespace js = json_spirit;

namespace dev
{
	namespace test
	{
		static void buildRLP(js::mValue& _v, RLPStream& _rlp)
		{
			if (_v.type() == js::array_type)
			{
				RLPStream s;
				for (auto& i: _v.get_array())
					buildRLP(i, s);
				_rlp.appendList(s.out());
			}
			else if (_v.type() == js::int_type)
				_rlp.append(_v.get_uint64());
			else if (_v.type() == js::str_type)
			{
				auto s = _v.get_str();
				if (s.size() && s[0] == '#')
					_rlp.append(bigint(s.substr(1)));
				else
					_rlp.append(s);
			}
		}

		static void getRLPTestCases(js::mValue& v)
		{
			string s = asString(contents("../../../tests/rlptest.json"));
			BOOST_REQUIRE_MESSAGE( s.length() > 0,
				"Contents of 'rlptest.json' is empty. Have you cloned the 'tests' repo branch develop?");
			js::read_string(s, v);
		}

		static void checkRLPTestCase(js::mObject& o)
		{
			BOOST_REQUIRE( o.count("in") > 0 );
			BOOST_REQUIRE( o.count("out") > 0 );
			BOOST_REQUIRE(!o["out"].is_null());
		}

		static void checkRLPAgainstJson(js::mValue& v, RLP& u)
		{
			if ( v.type() == js::str_type )
			{
				const std::string& expectedText = v.get_str();
				if ( expectedText.front() == '#' )
				{
					// Deal with bigint instead of a raw string
					std::string bigIntStr = expectedText.substr(1,expectedText.length()-1);
					std::stringstream bintStream(bigIntStr);
					bigint val;
					bintStream >> val;
					BOOST_CHECK( !u.isList() );
					BOOST_CHECK( !u.isNull() );
					BOOST_CHECK( u );             // operator bool()
					BOOST_CHECK(u == val);
				}
				else
				{
					BOOST_CHECK( !u.isList() );
					BOOST_CHECK( !u.isNull() );
					BOOST_CHECK( u.isData() );
					BOOST_CHECK( u );
					BOOST_CHECK( u.size() == expectedText.length() );
					BOOST_CHECK(u == expectedText);
				}
			}
			else if ( v.type() == js::int_type )
			{
				const int expectedValue = v.get_int();
				BOOST_CHECK( u.isInt() );
				BOOST_CHECK( !u.isList() );
				BOOST_CHECK( !u.isNull() );
				BOOST_CHECK( u );             // operator bool()
				BOOST_CHECK(u == expectedValue);
			}
			else if ( v.type() == js::array_type )
			{
				BOOST_CHECK( u.isList() );
				BOOST_CHECK( !u.isInt() );
				BOOST_CHECK( !u.isData() );
				js::mArray& arr = v.get_array();
				BOOST_CHECK( u.itemCount() == arr.size() );
				unsigned i;
				for( i = 0; i < arr.size(); i++ )
				{
					RLP item = u[i];
					checkRLPAgainstJson(arr[i], item);
				}
			}
			else
			{
				BOOST_ERROR("Invalid Javascript object!");
			}

		}
	}
}

BOOST_AUTO_TEST_CASE(rlp_encoding_test)
{
	cnote << "Testing RLP Encoding...";
	js::mValue v;
	dev::test::getRLPTestCases(v);

	for (auto& i: v.get_obj())
	{
		js::mObject& o = i.second.get_obj();
		cnote << i.first;
		dev::test::checkRLPTestCase(o);

		RLPStream s;
		dev::test::buildRLP(o["in"], s);

		std::string expectedText(o["out"].get_str());
		std::transform(expectedText.begin(), expectedText.end(), expectedText.begin(), ::tolower );

		const std::string& computedText = toHex(s.out());

		std::stringstream msg;
		msg << "Encoding Failed: expected: " << expectedText << std::endl;
		msg << " But Computed: " << computedText;

		BOOST_CHECK_MESSAGE(
			expectedText == computedText,
			msg.str()
			);
	}

}

BOOST_AUTO_TEST_CASE(rlp_decoding_test)
{
	cnote << "Testing RLP decoding...";
	// Uses the same test cases as encoding but in reverse.
	// We read into the string of hex values, convert to bytes,
	// and then compare the output structure to the json of the
	// input object.
	js::mValue v;
	dev::test::getRLPTestCases(v);
	for (auto& i: v.get_obj())
	{
		js::mObject& o = i.second.get_obj();
		cnote << i.first;
		dev::test::checkRLPTestCase(o);

		js::mValue& inputData = o["in"];
		bytes payloadToDecode = fromHex(o["out"].get_str());

		RLP payload(payloadToDecode);

		dev::test::checkRLPAgainstJson(inputData, payload);

	}
}

<commit_msg>Avoid attempt to reget chain on block reception. Send genesis block hash in hash chain.<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file rlp.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 * RLP test functions.
 */

#include <fstream>
#include <sstream>
#include <libdevcore/Log.h>
#include <libdevcore/RLP.h>
#include <libdevcore/Common.h>
#include <boost/test/unit_test.hpp>
#include <algorithm>
#include "JsonSpiritHeaders.h"

using namespace std;
using namespace dev;
namespace js = json_spirit;

namespace dev
{
	namespace test
	{
		static void buildRLP(js::mValue& _v, RLPStream& _rlp)
		{
			if (_v.type() == js::array_type)
			{
				RLPStream s;
				for (auto& i: _v.get_array())
					buildRLP(i, s);
				_rlp.appendList(s.out());
			}
			else if (_v.type() == js::int_type)
				_rlp.append(_v.get_uint64());
			else if (_v.type() == js::str_type)
			{
				auto s = _v.get_str();
				if (s.size() && s[0] == '#')
					_rlp.append(bigint(s.substr(1)));
				else
					_rlp.append(s);
			}
		}

		static void getRLPTestCases(js::mValue& v)
		{
			string s = asString(contents("../../../tests/rlptest.json"));
			BOOST_REQUIRE_MESSAGE( s.length() > 0,
				"Contents of 'rlptest.json' is empty. Have you cloned the 'tests' repo branch develop?");
			js::read_string(s, v);
		}

		static void checkRLPTestCase(js::mObject& o)
		{
			BOOST_REQUIRE( o.count("in") > 0 );
			BOOST_REQUIRE( o.count("out") > 0 );
			BOOST_REQUIRE(!o["out"].is_null());
		}

		static void checkRLPAgainstJson(js::mValue& v, RLP& u)
		{
			if ( v.type() == js::str_type )
			{
				const std::string& expectedText = v.get_str();
				if ( expectedText.front() == '#' )
				{
					// Deal with bigint instead of a raw string
					std::string bigIntStr = expectedText.substr(1,expectedText.length()-1);
					std::stringstream bintStream(bigIntStr);
					bigint val;
					bintStream >> val;
					BOOST_CHECK( !u.isList() );
					BOOST_CHECK( !u.isNull() );
					BOOST_CHECK( u );             // operator bool()
					BOOST_CHECK(u == val);
				}
				else
				{
					BOOST_CHECK( !u.isList() );
					BOOST_CHECK( !u.isNull() );
					BOOST_CHECK( u.isData() );
					BOOST_CHECK( u );
					BOOST_CHECK( u.size() == expectedText.length() );
					BOOST_CHECK(u == expectedText);
				}
			}
			else if ( v.type() == js::int_type )
			{
				const int expectedValue = v.get_int();
				BOOST_CHECK( u.isInt() );
				BOOST_CHECK( !u.isList() );
				BOOST_CHECK( !u.isNull() );
				BOOST_CHECK( u );             // operator bool()
				BOOST_CHECK(u == expectedValue);
			}
			else if ( v.type() == js::array_type )
			{
				BOOST_CHECK( u.isList() );
				BOOST_CHECK( !u.isInt() );
				BOOST_CHECK( !u.isData() );
				js::mArray& arr = v.get_array();
				BOOST_CHECK( u.itemCount() == arr.size() );
				unsigned i;
				for( i = 0; i < arr.size(); i++ )
				{
					RLP item = u[i];
					checkRLPAgainstJson(arr[i], item);
				}
			}
			else
			{
				BOOST_ERROR("Invalid Javascript object!");
			}

		}
	}
}

BOOST_AUTO_TEST_CASE(rlp_encoding_test)
{
	cnote << "Testing RLP Encoding...";
	js::mValue v;
	dev::test::getRLPTestCases(v);

	for (auto& i: v.get_obj())
	{
		js::mObject& o = i.second.get_obj();
		cnote << i.first;
		dev::test::checkRLPTestCase(o);

		RLPStream s;
		dev::test::buildRLP(o["in"], s);

		std::string expectedText(o["out"].get_str());
		std::transform(expectedText.begin(), expectedText.end(), expectedText.begin(), ::tolower );

		const std::string& computedText = toHex(s.out());

		std::stringstream msg;
		msg << "Encoding Failed: expected: " << expectedText << std::endl;
		msg << " But Computed: " << computedText;

		BOOST_CHECK_MESSAGE(
			expectedText == computedText,
			msg.str()
			);
	}

}

BOOST_AUTO_TEST_CASE(rlp_decoding_test)
{
	cnote << "Testing RLP decoding...";
	// Uses the same test cases as encoding but in reverse.
	// We read into the string of hex values, convert to bytes,
	// and then compare the output structure to the json of the
	// input object.
	js::mValue v;
	dev::test::getRLPTestCases(v);
	for (auto& i: v.get_obj())
	{
		js::mObject& o = i.second.get_obj();
		cnote << i.first;
		dev::test::checkRLPTestCase(o);

		js::mValue& inputData = o["in"];
		bytes payloadToDecode = fromHex(o["out"].get_str());

		RLP payload(payloadToDecode);

		dev::test::checkRLPAgainstJson(inputData, payload);

	}
}

<|endoftext|>


<commit_before>/*
    Copyright (c) 2010-2011 Sune Vuorela <sune@vuorela.dk>

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

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

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

*/

#include "qrcodebarcode.h"
#include <qrencode.h>
using namespace prison;
/**
@cond PRIVATE
*/
class QRCodeBarcode::Private {
  public:
};
/**
@endcond
*/

QRCodeBarcode::QRCodeBarcode() : AbstractBarcode(), d(0){

}

QRCodeBarcode::~QRCodeBarcode() {
  delete d;
}

QImage QRCodeBarcode::toImage(const QSizeF& size) {
  int width = qRound(qMin(size.width(),size.height()));
  if(data().size()==0 || width==0) {
    return QImage();
  }
  char* raw_string = qstrdup( data().toUtf8().trimmed().constData() );
  QRcode* code = QRcode_encodeString8bit(raw_string,0, QR_ECLEVEL_Q);
  free(raw_string);
  const int margin = 2;
  /*32 bit colors, 8 bit pr byte*/
  uchar* img = new uchar[4 *sizeof(char*)*(2*margin + code->width)*(2*margin* + code->width)];
  uchar* p = img;
  const char white = 0xff;
  const char black = 0x00;
  for(int row = 0 ; row < code->width+2*margin ; row++) {
    for(int col = 0 ; col < code->width+2*margin ; col++) {
      if(row < margin || row >= (code->width+margin) || col < margin || col >= (code->width+margin)) {
        /*4 bytes for color*/
        for(int i =0 ; i<4 ; i++) {
          *p = white;
          p++;
        }
      } else {
        int  c= (row-margin)*code->width + (col-margin);
        /*it is bit 1 that is the interesting bit for us from libqrencode*/
        if(code->data[c] & 1) {
          /*4 bytes for color*/
          for(int i =0 ; i<4 ; i++) {
            *p = black;
            p++;
          }
        } else {
          /*4 bytes for color*/
          for(int i =0 ; i<4 ; i++) {
            *p = white;
            p++;
          }
        }
      }
    }
  }
  QImage tmp(img,code->width+2*margin,code->width+2*margin,QImage::Format_RGB32);
  setMinimumSize(QSizeF(tmp.width()*4,tmp.height()*4));
  QImage ret = tmp.convertToFormat(QImage::Format_Mono).scaled(qMax(tmp.width()*4,width),qMax(tmp.height()*4,width)); //4 is determined by trial and error.
  free(img);
  QRcode_free(code);
  return ret;
}
<commit_msg>qrcodebarcode: Use delete[] to free memory allocated with new[].<commit_after>/*
    Copyright (c) 2010-2011 Sune Vuorela <sune@vuorela.dk>

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

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

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

*/

#include "qrcodebarcode.h"
#include <qrencode.h>
using namespace prison;
/**
@cond PRIVATE
*/
class QRCodeBarcode::Private {
  public:
};
/**
@endcond
*/

QRCodeBarcode::QRCodeBarcode() : AbstractBarcode(), d(0){

}

QRCodeBarcode::~QRCodeBarcode() {
  delete d;
}

QImage QRCodeBarcode::toImage(const QSizeF& size) {
  int width = qRound(qMin(size.width(),size.height()));
  if(data().size()==0 || width==0) {
    return QImage();
  }
  char* raw_string = qstrdup( data().toUtf8().trimmed().constData() );
  QRcode* code = QRcode_encodeString8bit(raw_string,0, QR_ECLEVEL_Q);
  free(raw_string);
  const int margin = 2;
  /*32 bit colors, 8 bit pr byte*/
  uchar* img = new uchar[4 *sizeof(char*)*(2*margin + code->width)*(2*margin* + code->width)];
  uchar* p = img;
  const char white = 0xff;
  const char black = 0x00;
  for(int row = 0 ; row < code->width+2*margin ; row++) {
    for(int col = 0 ; col < code->width+2*margin ; col++) {
      if(row < margin || row >= (code->width+margin) || col < margin || col >= (code->width+margin)) {
        /*4 bytes for color*/
        for(int i =0 ; i<4 ; i++) {
          *p = white;
          p++;
        }
      } else {
        int  c= (row-margin)*code->width + (col-margin);
        /*it is bit 1 that is the interesting bit for us from libqrencode*/
        if(code->data[c] & 1) {
          /*4 bytes for color*/
          for(int i =0 ; i<4 ; i++) {
            *p = black;
            p++;
          }
        } else {
          /*4 bytes for color*/
          for(int i =0 ; i<4 ; i++) {
            *p = white;
            p++;
          }
        }
      }
    }
  }
  QImage tmp(img,code->width+2*margin,code->width+2*margin,QImage::Format_RGB32);
  setMinimumSize(QSizeF(tmp.width()*4,tmp.height()*4));
  QImage ret = tmp.convertToFormat(QImage::Format_Mono).scaled(qMax(tmp.width()*4,width),qMax(tmp.height()*4,width)); //4 is determined by trial and error.
  delete[] img;
  QRcode_free(code);
  return ret;
}
<|endoftext|>


<commit_before><commit_msg>trace_processor: Fix metadata events missing ts<commit_after><|endoftext|>