<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <hspp/Accounts/Player.h>
#include <hspp/Cards/Character.h>

#include <algorithm>

namespace Hearthstonepp
{
Character::Character(Card& card) : Entity(card)
{
    if (!card.id.empty())
    {
#ifndef HEARTHSTONEPP_MACOSX
        m_attack = card.attack.has_value() ? card.attack.value() : 0;
        health = card.health.has_value() ? card.health.value() : 0;
#else
        m_attack = card.attack.value_or(0);
        health = card.health.value_or(0);
#endif
        maxHealth = health;
    }
}

Character* Character::Clone() const
{
    return new Character(*this);
}

size_t Character::GetAttack() const
{
    return m_attack;
}

void Character::SetAttack(size_t attack)
{
    m_attack = attack;
}

bool Character::CanAttack() const
{
    // If the value of attack is 0, returns false
    if (GetAttack() == 0)
    {
        return false;
    }

    // If the character is frozen, returns false
    if (GetGameTag(GameTag::FROZEN) == 1)
    {
        return false;
    }

    // If attack count is 0, returns false
    if (attackableCount == 0)
    {
        return false;
    }

    return true;
}

bool Character::IsValidAttackTarget(Player& opponent, Character* target) const
{
    auto validTargets = GetValidAttackTargets(opponent);
    if (std::find(validTargets.begin(), validTargets.end(), target) ==
        validTargets.end())
    {
        return false;
    }

    const Hero* hero = dynamic_cast<Hero*>(target);
    return (hero == nullptr) ||
           (hero->GetGameTag(GameTag::CANNOT_ATTACK_HEROES) == 1);
}

std::vector<Character*> Character::GetValidAttackTargets(Player& opponent)
{
    bool isExistTauntInField = false;
    std::vector<Character*> targets;
    std::vector<Character*> targetsHaveTaunt;

    for (auto& minion : opponent.field)
    {
        if (minion->GetGameTag(GameTag::STEALTH) == 0)
        {
            if (minion->GetGameTag(GameTag::TAUNT) == 1)
            {
                isExistTauntInField = true;
                targetsHaveTaunt.emplace_back(minion);
                continue;
            }

            if (!isExistTauntInField)
            {
                targets.emplace_back(minion);
            }
        }
    }

    if (isExistTauntInField)
    {
        return targetsHaveTaunt;
    }

    if (opponent.hero->GetGameTag(GameTag::CANNOT_ATTACK_HEROES) == 0 &&
        opponent.hero->GetGameTag(GameTag::IMMUNE) == 0 &&
        opponent.hero->GetGameTag(GameTag::STEALTH) == 0)
    {
        targets.emplace_back(opponent.hero);
    }

    return targets;
}

size_t Character::TakeDamage(Character& source, size_t damage)
{
    (void)source;

    if (GetGameTag(GameTag::DIVINE_SHIELD) == 1)
    {
        SetGameTag(GameTag::DIVINE_SHIELD, 0);
        return 0;
    }

    if (GetGameTag(GameTag::IMMUNE) == 1)
    {
        return 0;
    }

    health = (health <= damage) ? 0 : health - damage;

    return damage;
}
}  // namespace Hearthstonepp<commit_msg>fix: Unit test fail (Incorrect condition)<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <hspp/Accounts/Player.h>
#include <hspp/Cards/Character.h>

#include <algorithm>

namespace Hearthstonepp
{
Character::Character(Card& card) : Entity(card)
{
    if (!card.id.empty())
    {
#ifndef HEARTHSTONEPP_MACOSX
        m_attack = card.attack.has_value() ? card.attack.value() : 0;
        health = card.health.has_value() ? card.health.value() : 0;
#else
        m_attack = card.attack.value_or(0);
        health = card.health.value_or(0);
#endif
        maxHealth = health;
    }
}

Character* Character::Clone() const
{
    return new Character(*this);
}

size_t Character::GetAttack() const
{
    return m_attack;
}

void Character::SetAttack(size_t attack)
{
    m_attack = attack;
}

bool Character::CanAttack() const
{
    // If the value of attack is 0, returns false
    if (GetAttack() == 0)
    {
        return false;
    }

    // If the character is frozen, returns false
    if (GetGameTag(GameTag::FROZEN) == 1)
    {
        return false;
    }

    // If attack count is 0, returns false
    if (attackableCount == 0)
    {
        return false;
    }

    return true;
}

bool Character::IsValidAttackTarget(Player& opponent, Character* target) const
{
    auto validTargets = GetValidAttackTargets(opponent);
    if (std::find(validTargets.begin(), validTargets.end(), target) ==
        validTargets.end())
    {
        return false;
    }

    const Hero* hero = dynamic_cast<Hero*>(target);
    return !(hero != nullptr &&
             hero->GetGameTag(GameTag::CANNOT_ATTACK_HEROES) == 1);
}

std::vector<Character*> Character::GetValidAttackTargets(Player& opponent)
{
    bool isExistTauntInField = false;
    std::vector<Character*> targets;
    std::vector<Character*> targetsHaveTaunt;

    for (auto& minion : opponent.field)
    {
        if (minion->GetGameTag(GameTag::STEALTH) == 0)
        {
            if (minion->GetGameTag(GameTag::TAUNT) == 1)
            {
                isExistTauntInField = true;
                targetsHaveTaunt.emplace_back(minion);
                continue;
            }

            if (!isExistTauntInField)
            {
                targets.emplace_back(minion);
            }
        }
    }

    if (isExistTauntInField)
    {
        return targetsHaveTaunt;
    }

    if (opponent.hero->GetGameTag(GameTag::CANNOT_ATTACK_HEROES) == 0 &&
        opponent.hero->GetGameTag(GameTag::IMMUNE) == 0 &&
        opponent.hero->GetGameTag(GameTag::STEALTH) == 0)
    {
        targets.emplace_back(opponent.hero);
    }

    return targets;
}

size_t Character::TakeDamage(Character& source, size_t damage)
{
    (void)source;

    if (GetGameTag(GameTag::DIVINE_SHIELD) == 1)
    {
        SetGameTag(GameTag::DIVINE_SHIELD, 0);
        return 0;
    }

    if (GetGameTag(GameTag::IMMUNE) == 1)
    {
        return 0;
    }

    health = (health <= damage) ? 0 : health - damage;

    return damage;
}
}  // namespace Hearthstonepp<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_FUN_DIAG_PRE_MULTIPLY_HPP
#define STAN_MATH_REV_FUN_DIAG_PRE_MULTIPLY_HPP

#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/eval.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/multiply.hpp>

#include <iostream>

namespace stan {
namespace math {

/**
 * Return the elementwise multiplication of the specified
 * matrices.
 *
 * @tparam Mat1 type of the first matrix or expression
 * @tparam Mat2 type of the second matrix or expression
 *
 * @param m1 First matrix or expression
 * @param m2 Second matrix or expression
 * @return Elementwise product of matrices.
 */
template <typename Mat1, typename Mat2,
          require_all_matrix_t<Mat1, Mat2>* = nullptr,
          require_any_rev_matrix_t<Mat1, Mat2>* = nullptr>
/* template <typename Mat1, typename Mat2,
					require_eigen_vector_t<Mat1>* = nullptr,
          require_eigen_t<Mat2>* = nullptr> */
// template <typename Mat1, typename Mat2>
auto diag_pre_multiply(const Mat1& m1, const Mat2& m2) {
	std::cout << "I am using rev." << std::endl;
  // check_matching_dims("elt_multiply", "m1", m1, "m2", m2);

	check_size_match("diag_pre_multiply", "m1.size()", m1.size(), "m2.rows()",
                   m2.rows());
  using inner_ret_type = decltype(value_of(m1).asDiagonal() * value_of(m2));
  using ret_type = return_var_matrix_t<inner_ret_type, Mat1, Mat2>;
  if (!is_constant<Mat1>::value && !is_constant<Mat2>::value) {
    arena_t<promote_scalar_t<var, Mat1>> arena_m1 = m1;
    arena_t<promote_scalar_t<var, Mat2>> arena_m2 = m2;
    arena_t<ret_type> ret(arena_m1.val().asDiagonal() * arena_m2.val());
    reverse_pass_callback([ret, arena_m1, arena_m2]() mutable {
      for (int i = 0; i < arena_m2.cols(); ++i) {
        for (int j = 0; j < arena_m2.rows(); ++j) {
          const auto ret_adj = ret.adj().coeffRef(i, j);
          arena_m1.adj().coeffRef(i) += arena_m2.val().coeff(i, j) * ret_adj;
          arena_m2.adj().coeffRef(i, j) += arena_m1.val().coeff(i) * ret_adj;
        }
      }
    });
    return ret_type(ret);
  } else if (!is_constant<Mat1>::value) {
		std::cout << "Inside else if." << std::endl;
    arena_t<promote_scalar_t<var, Mat1>> arena_m1 = m1;
    arena_t<promote_scalar_t<double, Mat2>> arena_m2 = value_of(m2);
    arena_t<ret_type> ret(arena_m1.val().asDiagonal() * arena_m2);
		std::cout << ret << std::endl;
		std::cout << "ret.adj(): " << std::endl << ret.adj() << std::endl
			<< "---------------" << std::endl;
    reverse_pass_callback([ret, arena_m1, arena_m2]() mutable {
			for (int i = 0; i < arena_m1.size(); ++i) {
				for (int j = 0; j < arena_m1.size(); ++j) {
					arena_m1.adj().coeffRef(i) += arena_m2.val().coeff(i, j) *
						ret.adj().coeffRef(i, j);
				}
			}
			std::cout << "ret.adj(): " << std::endl << ret.adj() << std::endl
			<< "---------------" << std::endl;
			std::cout << "ret.adj().array(): " << std::endl << ret.adj().array() << std::endl
			<< "---------------" << std::endl;
			// arena.m1.adj().coeffRef(i) +=
      // arena_m1.adj().array() += arena_m2.array() * ret.adj().array(); // CHANGE HERE!
    });
    return ret_type(ret);
  } else if (!is_constant<Mat2>::value) {
    arena_t<promote_scalar_t<double, Mat1>> arena_m1 = value_of(m1);
    arena_t<promote_scalar_t<var, Mat2>> arena_m2 = m2;
		arena_t<ret_type> ret(arena_m1.asDiagonal() * arena_m2.val());
		std::cout << "Initialized adj():" << std::endl << arena_m2.adj()
			<< std::endl << "-------------------" << std::endl;
		std::cout << "Initialized adj().coeffRef:" << std::endl << arena_m2.adj().coeffRef(0, 0)
			<< std::endl << "-------------------" << std::endl;
		std::cout << "arena_m1.val():" << std::endl << arena_m1.val()
			<< std::endl << "-------------------" << std::endl;
		std::cout << "ret.adj():" << std::endl << ret.adj()
			<< std::endl << "-------------------" << std::endl;
		std::cout << "m1.size():" << std::endl << arena_m1.size()
			<< std::endl << "-------------------" << std::endl;
		std::cout << "ret:" << std::endl << ret
			<< std::endl << "-------------------" << std::endl;
    reverse_pass_callback([ret, arena_m1, arena_m2]() mutable {
			std::cout << "hh" << std::endl;
			/* for (int i = 0; i < arena_m1.size(); ++i) {
				for (int j = 0; j < arena_m1.size(); ++j) {
					std::cout << "oo" << std::endl;
					// arena_m2.adj().coeffRef(i,j) += 2;
					//arena_m2.adj().coeffRef(i,j) += arena_m1.val().coeff(i); *
					//	ret.adj().coeffRef(i, j);
				}
			} */
    });
		std::cout << "Works here." << std::endl;
    return ret_type(ret);
  }
}

}  // namespace math
}  // namespace stan

#endif
<commit_msg>Cleaned up couts.<commit_after>#ifndef STAN_MATH_REV_FUN_DIAG_PRE_MULTIPLY_HPP
#define STAN_MATH_REV_FUN_DIAG_PRE_MULTIPLY_HPP

#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/eval.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/multiply.hpp>

#include <iostream>

namespace stan {
namespace math {

/**
 * Return the elementwise multiplication of the specified
 * matrices.
 *
 * @tparam Mat1 type of the first matrix or expression
 * @tparam Mat2 type of the second matrix or expression
 *
 * @param m1 First matrix or expression
 * @param m2 Second matrix or expression
 * @return Elementwise product of matrices.
 */
template <typename Mat1, typename Mat2,
          require_all_matrix_t<Mat1, Mat2>* = nullptr,
          require_any_rev_matrix_t<Mat1, Mat2>* = nullptr>
/* template <typename Mat1, typename Mat2,
					require_eigen_vector_t<Mat1>* = nullptr,
          require_eigen_t<Mat2>* = nullptr> */
// template <typename Mat1, typename Mat2>
auto diag_pre_multiply(const Mat1& m1, const Mat2& m2) {
	std::cout << "I am using rev." << std::endl;
  // check_matching_dims("elt_multiply", "m1", m1, "m2", m2);

	check_size_match("diag_pre_multiply", "m1.size()", m1.size(), "m2.rows()",
                   m2.rows());
  using inner_ret_type = decltype(value_of(m1).asDiagonal() * value_of(m2));
  using ret_type = return_var_matrix_t<inner_ret_type, Mat1, Mat2>;
  if (!is_constant<Mat1>::value && !is_constant<Mat2>::value) {
    arena_t<promote_scalar_t<var, Mat1>> arena_m1 = m1;
    arena_t<promote_scalar_t<var, Mat2>> arena_m2 = m2;
    arena_t<ret_type> ret(arena_m1.val().asDiagonal() * arena_m2.val());
    reverse_pass_callback([ret, arena_m1, arena_m2]() mutable {
      for (int i = 0; i < arena_m2.cols(); ++i) {
        for (int j = 0; j < arena_m2.rows(); ++j) {
          const auto ret_adj = ret.adj().coeffRef(i, j);
          arena_m1.adj().coeffRef(i) += arena_m2.val().coeff(i, j) * ret_adj;
          arena_m2.adj().coeffRef(i, j) += arena_m1.val().coeff(i) * ret_adj;
        }
      }
    });
    return ret_type(ret);
  } else if (!is_constant<Mat1>::value) {
    arena_t<promote_scalar_t<var, Mat1>> arena_m1 = m1;
    arena_t<promote_scalar_t<double, Mat2>> arena_m2 = value_of(m2);
    arena_t<ret_type> ret(arena_m1.val().asDiagonal() * arena_m2);
    reverse_pass_callback([ret, arena_m1, arena_m2]() mutable {
			for (int i = 0; i < arena_m1.size(); ++i) {
				for (int j = 0; j < arena_m1.size(); ++j) {
					arena_m1.adj().coeffRef(i) += arena_m2.val().coeff(i, j) *
						ret.adj().coeffRef(i, j);
				}
			}
    });
    return ret_type(ret);
  } else if (!is_constant<Mat2>::value) {
    arena_t<promote_scalar_t<double, Mat1>> arena_m1 = value_of(m1);
    arena_t<promote_scalar_t<var, Mat2>> arena_m2 = m2;
		arena_t<ret_type> ret(arena_m1.asDiagonal() * arena_m2.val());
		std::cout << "Initialized adj():" << std::endl << arena_m2.adj()
			<< std::endl << "-------------------" << std::endl;
		std::cout << "Initialized adj().coeffRef:" << std::endl << arena_m2.adj().coeffRef(0, 0)
			<< std::endl << "-------------------" << std::endl;
		std::cout << "arena_m1.val():" << std::endl << arena_m1.val()
			<< std::endl << "-------------------" << std::endl;
		std::cout << "ret.adj():" << std::endl << ret.adj()
			<< std::endl << "-------------------" << std::endl;
		std::cout << "m1.size():" << std::endl << arena_m1.size()
			<< std::endl << "-------------------" << std::endl;
		std::cout << "ret:" << std::endl << ret
			<< std::endl << "-------------------" << std::endl;
    reverse_pass_callback([ret, arena_m1, arena_m2]() mutable {
			std::cout << "hh" << std::endl;
			/* for (int i = 0; i < arena_m1.size(); ++i) {
				for (int j = 0; j < arena_m1.size(); ++j) {
					std::cout << "oo" << std::endl;
					// arena_m2.adj().coeffRef(i,j) += 2;
					//arena_m2.adj().coeffRef(i,j) += arena_m1.val().coeff(i); *
					//	ret.adj().coeffRef(i, j);
				}
			} */
    });
		std::cout << "Works here." << std::endl;
    return ret_type(ret);
  }
}

}  // namespace math
}  // namespace stan

#endif
<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_FUN_ORDERED_CONSTRAIN_HPP
#define STAN_MATH_REV_FUN_ORDERED_CONSTRAIN_HPP

#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/functor/reverse_pass_callback.hpp>
#include <stan/math/rev/core/arena_matrix.hpp>
#include <stan/math/rev/fun/value_of.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <cmath>
#include <tuple>
#include <vector>

namespace stan {
namespace math {

/**
 * Return an increasing ordered vector derived from the specified
 * free vector.  The returned constrained vector will have the
 * same dimensionality as the specified free vector.
 *
 * @param x Free vector of scalars
 * @return Increasing ordered vector
 */
template <typename T, require_rev_matrix_t<T>* = nullptr>
inline auto ordered_constrain(const T& x) {
  using ret_type = plain_type_t<T>;

  using std::exp;

  size_t N = x.size();
  if (N == 0) {
    return ret_type(x);
  }

  Eigen::VectorXd y_val(N);
  arena_t<T> arena_x = x;
  arena_t<Eigen::VectorXd> exp_x(N - 1);

  y_val.coeffRef(0) = value_of(x)(0);
  for (int n = 1; n < N; ++n) {
    exp_x.coeffRef(n - 1) = exp(value_of(arena_x)(n));
    y_val.coeffRef(n) = y_val.coeff(n - 1) + exp_x.coeff(n - 1);
  }

  arena_t<ret_type> y = y_val;

  reverse_pass_callback([arena_x, y, exp_x]() mutable {
    double rolling_adjoint_sum = 0.0;

    for (int n = arena_x.size() - 1; n > 0; --n) {
      rolling_adjoint_sum += y.adj().coeff(n);
      arena_x.adj().coeffRef(n) += exp_x.coeff(n - 1) * rolling_adjoint_sum;
    }
    arena_x.adj().coeffRef(0) += rolling_adjoint_sum + y.adj().coeff(0);
  });

  return ret_type(y);
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>ordered_constrain not tested for `var<mat>` (Issue #2101)<commit_after>#ifndef STAN_MATH_REV_FUN_ORDERED_CONSTRAIN_HPP
#define STAN_MATH_REV_FUN_ORDERED_CONSTRAIN_HPP

#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/functor/reverse_pass_callback.hpp>
#include <stan/math/rev/core/arena_matrix.hpp>
#include <stan/math/rev/fun/value_of.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <cmath>
#include <tuple>
#include <vector>

namespace stan {
namespace math {

/**
 * Return an increasing ordered vector derived from the specified
 * free vector.  The returned constrained vector will have the
 * same dimensionality as the specified free vector.
 *
 * @param x Free vector of scalars
 * @return Increasing ordered vector
 */
template <typename T, require_eigen_col_vector_vt<is_var, T>* = nullptr>
inline auto ordered_constrain(const T& x) {
  using ret_type = plain_type_t<T>;

  using std::exp;

  size_t N = x.size();
  if (N == 0) {
    return ret_type(x);
  }

  Eigen::VectorXd y_val(N);
  arena_t<T> arena_x = x;
  arena_t<Eigen::VectorXd> exp_x(N - 1);

  y_val.coeffRef(0) = value_of(x)(0);
  for (int n = 1; n < N; ++n) {
    exp_x.coeffRef(n - 1) = exp(value_of(arena_x)(n));
    y_val.coeffRef(n) = y_val.coeff(n - 1) + exp_x.coeff(n - 1);
  }

  arena_t<ret_type> y = y_val;

  reverse_pass_callback([arena_x, y, exp_x]() mutable {
    double rolling_adjoint_sum = 0.0;

    for (int n = arena_x.size() - 1; n > 0; --n) {
      rolling_adjoint_sum += y.adj().coeff(n);
      arena_x.adj().coeffRef(n) += exp_x.coeff(n - 1) * rolling_adjoint_sum;
    }
    arena_x.adj().coeffRef(0) += rolling_adjoint_sum + y.adj().coeff(0);
  });

  return ret_type(y);
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before><commit_msg>Activated an aditional unit test on windows.<commit_after><|endoftext|>


<commit_before>#include "queryconfig.h"

#include <thread>

annis::QueryConfig::QueryConfig()
  : optimize(true), forceFallback(false), avoidNestedBySwitch(true) ,
    numOfBackgroundTasks(0), threadPool(nullptr)

{
  size_t numOfCPUs = std::thread::hardware_concurrency();
  if(numOfCPUs > 0)
  {
    numOfBackgroundTasks = numOfCPUs-1;
    threadPool = std::make_shared<ThreadPool>(numOfBackgroundTasks);
  }
}
<commit_msg>Default to non parallel QueryConfig.<commit_after>#include "queryconfig.h"

#include <thread>

annis::QueryConfig::QueryConfig()
  : optimize(true), forceFallback(false), avoidNestedBySwitch(true) ,
    numOfBackgroundTasks(0), threadPool(nullptr)

{
//  size_t numOfCPUs = std::thread::hardware_concurrency();
//  if(numOfCPUs > 0)
//  {
//    numOfBackgroundTasks = numOfCPUs-1;
//    threadPool = std::make_shared<ThreadPool>(numOfBackgroundTasks);
//  }
}
<|endoftext|>


<commit_before>#ifndef MPACK_AVLITERATOR_IMPL_HPP
#define MPACK_AVLITERATOR_IMPL_HPP

namespace MPACK
{
	namespace Algorithm
	{
		template<class T> AVL<T>::Iterator::Iterator()
		{
		}

		template<class T> AVL<T>::Iterator::Iterator(const Iterator& other)
			: m_avl(other.m_avl), m_node(other.m_node), m_count(other.m_count)
		{
		}

		template<class T> const typename AVL<T>::Iterator& AVL<T>::Iterator::operator= (const typename AVL<T>::Iterator& other)
		{
			m_avl = other.m_avl;
			m_node = other.m_node;
			m_count = other.m_count;
			return other;
		}

		template<class T> T AVL<T>::Iterator::operator* () const
		{
			return m_node->m_value;
		}

		template<class T> const T* AVL<T>::Iterator::operator-> () const
		{
			return &m_node->m_value;
		}

		template<class T> typename AVL<T>::Iterator& AVL<T>::Iterator::operator++ ()
		{
			Next();
			return *this;
		}

		template<class T> typename AVL<T>::Iterator AVL<T>::Iterator::operator++ (int)
		{
			Iterator tempIt=*this;
			Next();
			return tempIt;
		}

		template<class T> typename AVL<T>::Iterator& AVL<T>::Iterator::operator-- ()
		{
			Prev();
			return *this;
		}

		template<class T> typename AVL<T>::Iterator AVL<T>::Iterator::operator-- (int)
		{
			Iterator tempIt=*this;
			Prev();
			return tempIt;
		}

		template<class T> bool AVL<T>::Iterator::operator!= (const Iterator &other) const
		{
			return this->m_node!=other.m_node || this->m_count!=other.m_count;
		}

		template<class T> bool AVL<T>::Iterator::operator== (const Iterator &other) const
		{
			return this->m_node==other.m_node && this->m_count==other.m_count;
		}

		template<class T> AVL<T>::Iterator::Iterator(AVL<T> *avl, AVLNode<T> *node, int count)
			: m_avl(avl), m_node(node), m_count(count)
		{
		}

		template<class T> void AVL<T>::Iterator::Next()
		{
			++m_count;
			if(m_count > m_node->m_count)
			{
				m_avl->m_param1 = m_node->m_value;
				m_node = m_avl->Next(m_avl->m_root);
				if(m_node)
				{
					m_count = 1;
				}
				else
				{
					m_count = 0;
				}
			}
		}

		template<class T> void AVL<T>::Iterator::Prev()
		{
			--m_count;
			if(m_count <= 0)
			{
				m_avl->m_param1 = m_node->m_value;
				m_node = m_avl->Prev(m_avl->m_root);
				if(m_node)
				{
					m_count = m_node->m_count;
				}
				else
				{
					m_count=0;
				}
			}
		}
	}
}

#endif
<commit_msg>Fix AVLIterator warning<commit_after>#ifndef MPACK_AVLITERATOR_IMPL_HPP
#define MPACK_AVLITERATOR_IMPL_HPP

namespace MPACK
{
	namespace Algorithm
	{
		template<class T> AVL<T>::Iterator::Iterator()
			: m_avl(NULL), m_node(NULL), m_count(0)
		{
		}

		template<class T> AVL<T>::Iterator::Iterator(const Iterator& other)
			: m_avl(other.m_avl), m_node(other.m_node), m_count(other.m_count)
		{
		}

		template<class T> const typename AVL<T>::Iterator& AVL<T>::Iterator::operator= (const typename AVL<T>::Iterator& other)
		{
			m_avl = other.m_avl;
			m_node = other.m_node;
			m_count = other.m_count;
			return other;
		}

		template<class T> T AVL<T>::Iterator::operator* () const
		{
			return m_node->m_value;
		}

		template<class T> const T* AVL<T>::Iterator::operator-> () const
		{
			return &m_node->m_value;
		}

		template<class T> typename AVL<T>::Iterator& AVL<T>::Iterator::operator++ ()
		{
			Next();
			return *this;
		}

		template<class T> typename AVL<T>::Iterator AVL<T>::Iterator::operator++ (int)
		{
			Iterator tempIt=*this;
			Next();
			return tempIt;
		}

		template<class T> typename AVL<T>::Iterator& AVL<T>::Iterator::operator-- ()
		{
			Prev();
			return *this;
		}

		template<class T> typename AVL<T>::Iterator AVL<T>::Iterator::operator-- (int)
		{
			Iterator tempIt=*this;
			Prev();
			return tempIt;
		}

		template<class T> bool AVL<T>::Iterator::operator!= (const Iterator &other) const
		{
			return this->m_node!=other.m_node || this->m_count!=other.m_count;
		}

		template<class T> bool AVL<T>::Iterator::operator== (const Iterator &other) const
		{
			return this->m_node==other.m_node && this->m_count==other.m_count;
		}

		template<class T> AVL<T>::Iterator::Iterator(AVL<T> *avl, AVLNode<T> *node, int count)
			: m_avl(avl), m_node(node), m_count(count)
		{
		}

		template<class T> void AVL<T>::Iterator::Next()
		{
			++m_count;
			if(m_count > m_node->m_count)
			{
				m_avl->m_param1 = m_node->m_value;
				m_node = m_avl->Next(m_avl->m_root);
				if(m_node)
				{
					m_count = 1;
				}
				else
				{
					m_count = 0;
				}
			}
		}

		template<class T> void AVL<T>::Iterator::Prev()
		{
			--m_count;
			if(m_count <= 0)
			{
				m_avl->m_param1 = m_node->m_value;
				m_node = m_avl->Prev(m_avl->m_root);
				if(m_node)
				{
					m_count = m_node->m_count;
				}
				else
				{
					m_count=0;
				}
			}
		}
	}
}

#endif
<|endoftext|>


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

#ifndef _OPCODES_HXX
#define _OPCODES_HXX

#include "sbintern.hxx"

#ifdef MTW
#undef _NUMBER
#endif

// Ein Opcode ist entweder 1, 3 oder 5 Bytes lang, je nach numerischen
// Wert des Opcodes (s.u.).

enum SbiOpcode {
    // Alle Opcodes ohne Operanden
    _NOP = 0,

    SbOP0_START = _NOP,

    // Operatoren
    // die folgenden Operatoren sind genauso angeordnet
    // wie der enum SbxVarOp
    _EXP, _MUL, _DIV, _MOD, _PLUS, _MINUS, _NEG,
    _EQ,  _NE,  _LT,  _GT, _LE, _GE,
    _IDIV, _AND, _OR, _XOR, _EQV, _IMP, _NOT,
    _CAT,
    // Ende enum SbxVarOp
    _LIKE, _IS,
    // Laden/speichern
    _ARGC,              // neuen Argv einrichten
    _ARGV,              // TOS ==> aktueller Argv
    _INPUT,             // Input ==> TOS
    _LINPUT,            // Line Input ==> TOS
    _GET,               // TOS anfassen
    _SET,               // Speichern Objekt TOS ==> TOS-1
    _PUT,               // TOS ==> TOS-1
    _PUTC,              // TOS ==> TOS-1, dann ReadOnly
    _DIM,               // DIM
    _REDIM,             // REDIM
    _REDIMP,            // REDIM PRESERVE
    _ERASE,             // TOS loeschen
    // Verzweigen
    _STOP,              // Programmende
    _INITFOR,           // FOR-Variable initialisieren
    _NEXT,              // FOR-Variable inkrementieren
    _CASE,              // Anfang CASE
    _ENDCASE,           // Ende CASE
    _STDERROR,          // Standard-Fehlerbehandlung
    _NOERROR,           // keine Fehlerbehandlung
    _LEAVE,             // UP verlassen
    // E/A
    _CHANNEL,           // TOS = Kanalnummer
    _BPRINT,            // print TOS
    _PRINTF,            // print TOS in field
    _BWRITE,            // write TOS
    _RENAME,            // Rename Tos+1 to Tos
    _PROMPT,            // TOS = Prompt for Input
    _RESTART,           // Restartpunkt definieren
    _CHAN0,             // I/O-Kanal 0
    // Sonstiges
    _EMPTY,             // Leeren Ausdruck auf Stack
    _ERROR,             // TOS = Fehlercode
    _LSET,              // Speichern Objekt TOS ==> TOS-1
    _RSET,              // Speichern Objekt TOS ==> TOS-1
    _REDIMP_ERASE,      // Copies array to be later used by REDIM PRESERVE before erasing it
    _INITFOREACH,
    SbOP0_END,

    // Alle Opcodes mit einem Operanden

    _NUMBER = 0x40,     // Laden einer numerischen Konstanten (+ID)

    SbOP1_START = _NUMBER,

    _SCONST,            // Laden einer Stringkonstanten (+ID)
    _CONST,             // Immediate Load (+Wert)
    _ARGN,              // Speichern eines named Args in Argv (+StringID)
    _PAD,               // String auf feste Laenge bringen (+Laenge)
    // Verzweigungen
    _JUMP,              // Sprung (+Target)
    _JUMPT,             // TOS auswerten, bedingter Sprung (+Target)
    _JUMPF,             // TOS auswerten, bedingter Sprung (+Target)
    _ONJUMP,            // TOS auswerten, Sprung in JUMP-Tabelle (+MaxVal)
    _GOSUB,             // UP-Aufruf (+Target)
    _RETURN,            // UP-Return (+0 oder Target)
    _TESTFOR,           // FOR-Variable testen, inkrementieren (+Endlabel)
    _CASETO,            // Tos+1 <= Case <= Tos, 2xremove (+Target)
    _ERRHDL,            // Fehler-Handler (+Offset)
    _RESUME,            // Resume nach Fehlern (+0 or 1 or Label)
    // E/A
    _CLOSE,             // (+Kanal/0)
    _PRCHAR,            // (+char)
    // Verwaltung
    _SETCLASS,          // Set + Klassennamen testen (+StringId)
    _TESTCLASS,         // Check TOS class (+StringId)
    _LIB,               // Libnamen fuer Declare-Procs setzen (+StringId)
    _BASED,             // TOS wird um BASE erhoeht, BASE davor gepusht (+base)
    // Typanpassung im Argv
    _ARGTYP,            // Letzten Parameter in Argv konvertieren (+Typ)

    SbOP1_END,

    // Alle Opcodes mit zwei Operanden

    _RTL = 0x80,        // Laden aus RTL (+StringID+Typ)

    SbOP2_START = _RTL,

    _FIND,              // Laden (+StringID+Typ)
    _ELEM,              // Laden Element (+StringID+Typ)
    _PARAM,             // Parameter (+Offset+Typ)
    // Verzweigen
    _CALL,              // DECLARE-Methode rufen (+StringID+Typ)
    _CALLC,             // Cdecl-DECLARE-Methode rufen (+StringID+Typ)
    _CASEIS,            // Case-Test (+Test-Opcode+True-Target)
    // Verwaltung
    _STMNT,             // Beginn eines Statements (+Line+Col)
    // E/A
    _OPEN,              // (+SvStreamFlags+Flags)
    // Objekte
    _LOCAL,             // Lokale Variable definieren (+StringID+Typ)
    _PUBLIC,            // Modulglobale Variable (+StringID+Typ)
    _GLOBAL,            // Globale Variable definieren, public-Anweisung (+StringID+Typ)
    _CREATE,            // Objekt kreieren (+StringId+StringID)
    _STATIC,            // Statische Variabl (+StringID+Typ) JSM
    _TCREATE,           // User Defined Objekt kreieren
    _DCREATE,           // Objekt-Array kreieren (+StringId+StringID)
    _GLOBAL_P,          // Globale Variable definieren, die beim Neustart von Basic
                        // nicht ueberschrieben wird, P=PERSIST (+StringID+Typ)
    _FIND_G,            // Sucht globale Variable mit Spezialbehandlung wegen _GLOBAL_P
    _DCREATE_REDIMP,    // Objekt-Array redimensionieren (+StringId+StringID)
    _FIND_CM,           // Search inside a class module (CM) to enable global search in time
    SbOP2_END

};

#endif
<commit_msg>INTEGRATION: CWS npower4 (1.10.78); FILE MERGED 2006/10/18 20:29:17 npower 1.10.78.1: #i64884# changes for default properties<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: opcodes.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: vg $ $Date: 2006-11-02 16:32:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _OPCODES_HXX
#define _OPCODES_HXX

#include "sbintern.hxx"

#ifdef MTW
#undef _NUMBER
#endif

// Ein Opcode ist entweder 1, 3 oder 5 Bytes lang, je nach numerischen
// Wert des Opcodes (s.u.).

enum SbiOpcode {
    // Alle Opcodes ohne Operanden
    _NOP = 0,

    SbOP0_START = _NOP,

    // Operatoren
    // die folgenden Operatoren sind genauso angeordnet
    // wie der enum SbxVarOp
    _EXP, _MUL, _DIV, _MOD, _PLUS, _MINUS, _NEG,
    _EQ,  _NE,  _LT,  _GT, _LE, _GE,
    _IDIV, _AND, _OR, _XOR, _EQV, _IMP, _NOT,
    _CAT,
    // Ende enum SbxVarOp
    _LIKE, _IS,
    // Laden/speichern
    _ARGC,              // neuen Argv einrichten
    _ARGV,              // TOS ==> aktueller Argv
    _INPUT,             // Input ==> TOS
    _LINPUT,            // Line Input ==> TOS
    _GET,               // TOS anfassen
    _SET,               // Speichern Objekt TOS ==> TOS-1
    _PUT,               // TOS ==> TOS-1
    _PUTC,              // TOS ==> TOS-1, dann ReadOnly
    _DIM,               // DIM
    _REDIM,             // REDIM
    _REDIMP,            // REDIM PRESERVE
    _ERASE,             // TOS loeschen
    // Verzweigen
    _STOP,              // Programmende
    _INITFOR,           // FOR-Variable initialisieren
    _NEXT,              // FOR-Variable inkrementieren
    _CASE,              // Anfang CASE
    _ENDCASE,           // Ende CASE
    _STDERROR,          // Standard-Fehlerbehandlung
    _NOERROR,           // keine Fehlerbehandlung
    _LEAVE,             // UP verlassen
    // E/A
    _CHANNEL,           // TOS = Kanalnummer
    _BPRINT,            // print TOS
    _PRINTF,            // print TOS in field
    _BWRITE,            // write TOS
    _RENAME,            // Rename Tos+1 to Tos
    _PROMPT,            // TOS = Prompt for Input
    _RESTART,           // Restartpunkt definieren
    _CHAN0,             // I/O-Kanal 0
    // Sonstiges
    _EMPTY,             // Leeren Ausdruck auf Stack
    _ERROR,             // TOS = Fehlercode
    _LSET,              // Speichern Objekt TOS ==> TOS-1
    _RSET,              // Speichern Objekt TOS ==> TOS-1
    _REDIMP_ERASE,      // Copies array to be later used by REDIM PRESERVE before erasing it
    _INITFOREACH,
    _VBASET,            // VBA-like Set
    SbOP0_END,

    // Alle Opcodes mit einem Operanden

    _NUMBER = 0x40,     // Laden einer numerischen Konstanten (+ID)

    SbOP1_START = _NUMBER,

    _SCONST,            // Laden einer Stringkonstanten (+ID)
    _CONST,             // Immediate Load (+Wert)
    _ARGN,              // Speichern eines named Args in Argv (+StringID)
    _PAD,               // String auf feste Laenge bringen (+Laenge)
    // Verzweigungen
    _JUMP,              // Sprung (+Target)
    _JUMPT,             // TOS auswerten, bedingter Sprung (+Target)
    _JUMPF,             // TOS auswerten, bedingter Sprung (+Target)
    _ONJUMP,            // TOS auswerten, Sprung in JUMP-Tabelle (+MaxVal)
    _GOSUB,             // UP-Aufruf (+Target)
    _RETURN,            // UP-Return (+0 oder Target)
    _TESTFOR,           // FOR-Variable testen, inkrementieren (+Endlabel)
    _CASETO,            // Tos+1 <= Case <= Tos, 2xremove (+Target)
    _ERRHDL,            // Fehler-Handler (+Offset)
    _RESUME,            // Resume nach Fehlern (+0 or 1 or Label)
    // E/A
    _CLOSE,             // (+Kanal/0)
    _PRCHAR,            // (+char)
    // Verwaltung
    _SETCLASS,          // Set + Klassennamen testen (+StringId)
    _TESTCLASS,         // Check TOS class (+StringId)
    _LIB,               // Libnamen fuer Declare-Procs setzen (+StringId)
    _BASED,             // TOS wird um BASE erhoeht, BASE davor gepusht (+base)
    // Typanpassung im Argv
    _ARGTYP,            // Letzten Parameter in Argv konvertieren (+Typ)
    SbOP1_END,

    // Alle Opcodes mit zwei Operanden

    _RTL = 0x80,        // Laden aus RTL (+StringID+Typ)

    SbOP2_START = _RTL,

    _FIND,              // Laden (+StringID+Typ)
    _ELEM,              // Laden Element (+StringID+Typ)
    _PARAM,             // Parameter (+Offset+Typ)
    // Verzweigen
    _CALL,              // DECLARE-Methode rufen (+StringID+Typ)
    _CALLC,             // Cdecl-DECLARE-Methode rufen (+StringID+Typ)
    _CASEIS,            // Case-Test (+Test-Opcode+True-Target)
    // Verwaltung
    _STMNT,             // Beginn eines Statements (+Line+Col)
    // E/A
    _OPEN,              // (+SvStreamFlags+Flags)
    // Objekte
    _LOCAL,             // Lokale Variable definieren (+StringID+Typ)
    _PUBLIC,            // Modulglobale Variable (+StringID+Typ)
    _GLOBAL,            // Globale Variable definieren, public-Anweisung (+StringID+Typ)
    _CREATE,            // Objekt kreieren (+StringId+StringID)
    _STATIC,            // Statische Variabl (+StringID+Typ) JSM
    _TCREATE,           // User Defined Objekt kreieren
    _DCREATE,           // Objekt-Array kreieren (+StringId+StringID)
    _GLOBAL_P,          // Globale Variable definieren, die beim Neustart von Basic
                        // nicht ueberschrieben wird, P=PERSIST (+StringID+Typ)
    _FIND_G,            // Sucht globale Variable mit Spezialbehandlung wegen _GLOBAL_P
    _DCREATE_REDIMP,    // Objekt-Array redimensionieren (+StringId+StringID)
    _FIND_CM,           // Search inside a class module (CM) to enable global search in time
    SbOP2_END

};

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "volum_group.h"
#include "volum.h"
#include "mounter.h"

#include "protocol/galaxy.pb.h"
#include "agent/volum/volum.h"
#include "boost/algorithm/string/split.hpp"
#include "boost/algorithm/string/classification.hpp"
#include "boost/filesystem/path.hpp"
#include "boost/filesystem/operations.hpp"
#include "util/error_code.h"
#include "util/path_tree.h"
#include "boost/lexical_cast/lexical_cast_old.hpp"

#include <glog/logging.h>
#include <gflags/gflags.h>
#include <iostream>

DECLARE_string(mount_templat);

namespace baidu {
namespace galaxy {
namespace volum {
VolumGroup::VolumGroup() :
    gc_index_(-1)
{
}

VolumGroup::~VolumGroup()
{
}

void VolumGroup::SetGcIndex(int gc_index)
{
    assert(gc_index >= 0);
    gc_index_ = gc_index;
}

void VolumGroup::AddDataVolum(const baidu::galaxy::proto::VolumRequired& data_volum)
{
    boost::shared_ptr<baidu::galaxy::proto::VolumRequired> volum(new baidu::galaxy::proto::VolumRequired());
    volum->CopyFrom(data_volum);
    dv_description_.push_back(volum);
}

void VolumGroup::SetWorkspaceVolum(const baidu::galaxy::proto::VolumRequired& ws_volum)
{
    ws_description_.reset(new baidu::galaxy::proto::VolumRequired);
    ws_description_->CopyFrom(ws_volum);
}

void VolumGroup::SetContainerId(const std::string& container_id)
{
    container_id_ = container_id;
}

baidu::galaxy::util::ErrorCode VolumGroup::Construct()
{
    workspace_volum_ = Construct(this->ws_description_);

    if (NULL == workspace_volum_.get()) {
        return ERRORCODE(-1, "workspace volum is empty");
    }

    baidu::galaxy::util::ErrorCode ec;
    for (size_t i = 0; i < dv_description_.size(); i++) {
        boost::shared_ptr<Volum> v = Construct(dv_description_[i]);

        if (v.get() == NULL) {
            ec = ERRORCODE(-1,
                    "construct volum(%s->%s) failed",
                    dv_description_[i]->source_path().c_str(),
                    dv_description_[i]->dest_path().c_str());

            break;
        }

        data_volum_.push_back(v);
    }

    if (data_volum_.size() != dv_description_.size()) {
        for (size_t i = 0; i < data_volum_.size(); i++) {
            data_volum_[i]->Destroy();
        }

        return ec;
    }

    return ERRORCODE_OK;
}

baidu::galaxy::util::ErrorCode VolumGroup::Destroy()
{
    int ret = 0;

    for (size_t i = 0; i < data_volum_.size(); i++) {
        if (0 != data_volum_[i]->Destroy()) {
            return ERRORCODE(-1,
                    "failed in destroying data volum(%s->%s)",
                    data_volum_[i]->SourcePath().c_str(),
                    data_volum_[i]->TargetPath().c_str());
        }
    }

    if (0 != workspace_volum_->Destroy()) {
        return ERRORCODE(-1,
                "failed in destroying workspace volum");
    }

    return ERRORCODE_OK;
}

int VolumGroup::ExportEnv(std::map<std::string, std::string>& env)
{
    env["baidu_galaxy_container_workspace_path"] = workspace_volum_->Description()->dest_path();
    env["baidu_galaxy_container_workspace_abstargetpath"] = workspace_volum_->TargetPath();
    env["baidu_galaxy_container_workspace_abssourcepath"] = workspace_volum_->SourcePath();
    env["baidu_galaxy_container_workspace_datavolum_size"] = boost::lexical_cast<std::string>(data_volum_.size());
    return 0;
}

boost::shared_ptr<google::protobuf::Message> VolumGroup::Report()
{
    boost::shared_ptr<google::protobuf::Message> ret;
    return ret;
}

boost::shared_ptr<Volum> VolumGroup::Construct(boost::shared_ptr<baidu::galaxy::proto::VolumRequired> dp)
{
    assert(NULL != dp.get());
    assert(gc_index_ >= 0);
    boost::shared_ptr<Volum> volum = Volum::CreateVolum(dp);

    if (NULL == volum.get()) {
        return volum;
    }

    volum->SetDescription(dp);
    volum->SetContainerId(this->container_id_);
    volum->SetGcIndex(gc_index_);

    if (0 != volum->Construct()) {
        volum.reset();
    }

    return volum;
}

// FIX: a single class
int VolumGroup::MountRootfs()
{
    std::vector<std::string> vm;
    boost::split(vm, FLAGS_mount_templat, boost::is_any_of(","));

    std::string container_path = baidu::galaxy::path::ContainerRootPath(container_id_);

    for (size_t i = 0; i < vm.size(); i++) {
        if (vm[i].empty()) {
            continue;
        }

        boost::system::error_code ec;
        boost::filesystem::path path(container_path);
        path.append(vm[i]);

        if (!boost::filesystem::exists(path, ec) && !boost::filesystem::create_directories(path, ec)) {
            LOG(WARNING) << "create_directories failed: " << path.string() << ": " << ec.message();
            return -1;
        }

        if (boost::filesystem::is_directory(path, ec)) {
            LOG(INFO) << "create_directories sucessfully: " << path.string();
        }

        if ("/proc" == vm[i]) {
            baidu::galaxy::util::ErrorCode errc = MountProc(path.string());

            if (0 != errc.Code()) {
                LOG(WARNING) << "mount " << vm[i] << "for container " << container_id_ << " failed " << errc.Message();
                return -1;
            }

            LOG(INFO) << "mount successfully: " << vm[i] << " -> " << path.string();
        } else {
            baidu::galaxy::util::ErrorCode errc = MountDir(vm[i], path.string());

            if (0 != errc.Code()) {
                LOG(WARNING) << "mount " << vm[i] << "for container " << container_id_ << " failed " << errc.Message();
                return -1;
            }

            LOG(INFO) << "mount successfully: " << vm[i] << " -> " << path.string();
        }
    }

    return 0;
}

}
}
}
<commit_msg>rm unused var<commit_after>// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "volum_group.h"
#include "volum.h"
#include "mounter.h"

#include "protocol/galaxy.pb.h"
#include "agent/volum/volum.h"
#include "boost/algorithm/string/split.hpp"
#include "boost/algorithm/string/classification.hpp"
#include "boost/filesystem/path.hpp"
#include "boost/filesystem/operations.hpp"
#include "util/error_code.h"
#include "util/path_tree.h"
#include "boost/lexical_cast/lexical_cast_old.hpp"

#include <glog/logging.h>
#include <gflags/gflags.h>
#include <iostream>

DECLARE_string(mount_templat);

namespace baidu {
namespace galaxy {
namespace volum {
VolumGroup::VolumGroup() :
    gc_index_(-1)
{
}

VolumGroup::~VolumGroup()
{
}

void VolumGroup::SetGcIndex(int gc_index)
{
    assert(gc_index >= 0);
    gc_index_ = gc_index;
}

void VolumGroup::AddDataVolum(const baidu::galaxy::proto::VolumRequired& data_volum)
{
    boost::shared_ptr<baidu::galaxy::proto::VolumRequired> volum(new baidu::galaxy::proto::VolumRequired());
    volum->CopyFrom(data_volum);
    dv_description_.push_back(volum);
}

void VolumGroup::SetWorkspaceVolum(const baidu::galaxy::proto::VolumRequired& ws_volum)
{
    ws_description_.reset(new baidu::galaxy::proto::VolumRequired);
    ws_description_->CopyFrom(ws_volum);
}

void VolumGroup::SetContainerId(const std::string& container_id)
{
    container_id_ = container_id;
}

baidu::galaxy::util::ErrorCode VolumGroup::Construct()
{
    workspace_volum_ = Construct(this->ws_description_);

    if (NULL == workspace_volum_.get()) {
        return ERRORCODE(-1, "workspace volum is empty");
    }

    baidu::galaxy::util::ErrorCode ec;
    for (size_t i = 0; i < dv_description_.size(); i++) {
        boost::shared_ptr<Volum> v = Construct(dv_description_[i]);

        if (v.get() == NULL) {
            ec = ERRORCODE(-1,
                    "construct volum(%s->%s) failed",
                    dv_description_[i]->source_path().c_str(),
                    dv_description_[i]->dest_path().c_str());

            break;
        }

        data_volum_.push_back(v);
    }

    if (data_volum_.size() != dv_description_.size()) {
        for (size_t i = 0; i < data_volum_.size(); i++) {
            data_volum_[i]->Destroy();
        }

        return ec;
    }

    return ERRORCODE_OK;
}

baidu::galaxy::util::ErrorCode VolumGroup::Destroy()
{
    for (size_t i = 0; i < data_volum_.size(); i++) {
        if (0 != data_volum_[i]->Destroy()) {
            return ERRORCODE(-1,
                    "failed in destroying data volum(%s->%s)",
                    data_volum_[i]->SourcePath().c_str(),
                    data_volum_[i]->TargetPath().c_str());
        }
    }

    if (0 != workspace_volum_->Destroy()) {
        return ERRORCODE(-1,
                "failed in destroying workspace volum");
    }

    return ERRORCODE_OK;
}

int VolumGroup::ExportEnv(std::map<std::string, std::string>& env)
{
    env["baidu_galaxy_container_workspace_path"] = workspace_volum_->Description()->dest_path();
    env["baidu_galaxy_container_workspace_abstargetpath"] = workspace_volum_->TargetPath();
    env["baidu_galaxy_container_workspace_abssourcepath"] = workspace_volum_->SourcePath();
    env["baidu_galaxy_container_workspace_datavolum_size"] = boost::lexical_cast<std::string>(data_volum_.size());
    return 0;
}

boost::shared_ptr<google::protobuf::Message> VolumGroup::Report()
{
    boost::shared_ptr<google::protobuf::Message> ret;
    return ret;
}

boost::shared_ptr<Volum> VolumGroup::Construct(boost::shared_ptr<baidu::galaxy::proto::VolumRequired> dp)
{
    assert(NULL != dp.get());
    assert(gc_index_ >= 0);
    boost::shared_ptr<Volum> volum = Volum::CreateVolum(dp);

    if (NULL == volum.get()) {
        return volum;
    }

    volum->SetDescription(dp);
    volum->SetContainerId(this->container_id_);
    volum->SetGcIndex(gc_index_);

    if (0 != volum->Construct()) {
        volum.reset();
    }

    return volum;
}

// FIX: a single class
int VolumGroup::MountRootfs()
{
    std::vector<std::string> vm;
    boost::split(vm, FLAGS_mount_templat, boost::is_any_of(","));

    std::string container_path = baidu::galaxy::path::ContainerRootPath(container_id_);

    for (size_t i = 0; i < vm.size(); i++) {
        if (vm[i].empty()) {
            continue;
        }

        boost::system::error_code ec;
        boost::filesystem::path path(container_path);
        path.append(vm[i]);

        if (!boost::filesystem::exists(path, ec) && !boost::filesystem::create_directories(path, ec)) {
            LOG(WARNING) << "create_directories failed: " << path.string() << ": " << ec.message();
            return -1;
        }

        if (boost::filesystem::is_directory(path, ec)) {
            LOG(INFO) << "create_directories sucessfully: " << path.string();
        }

        if ("/proc" == vm[i]) {
            baidu::galaxy::util::ErrorCode errc = MountProc(path.string());

            if (0 != errc.Code()) {
                LOG(WARNING) << "mount " << vm[i] << "for container " << container_id_ << " failed " << errc.Message();
                return -1;
            }

            LOG(INFO) << "mount successfully: " << vm[i] << " -> " << path.string();
        } else {
            baidu::galaxy::util::ErrorCode errc = MountDir(vm[i], path.string());

            if (0 != errc.Code()) {
                LOG(WARNING) << "mount " << vm[i] << "for container " << container_id_ << " failed " << errc.Message();
                return -1;
            }

            LOG(INFO) << "mount successfully: " << vm[i] << " -> " << path.string();
        }
    }

    return 0;
}

}
}
}
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
// Copyright( c ) 2016, Robert Kimball
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
//    contributors may be used to endorse or promote products derived from
//    this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//----------------------------------------------------------------------------

// DHCP Info https://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol
// DHCP Options http://www.faqs.org/rfcs/rfc1533.html

#include <stdio.h>
#include <string.h>
#include "ProtocolDHCP.h"
#include "ProtocolUDP.h"
#include "ProtocolIP.h"
#include "NetworkInterface.h"
#include "Utility.h"
#include "osTime.h"

extern AddressConfiguration Config;
int32_t ProtocolDHCP::PendingXID = -1;
static const uint32_t DHCP_MAGIC = 0x63825363;

const char* inet_ntoa( uint32_t addr )
{
   static char rc[ 20 ];
   sprintf( rc, "%d.%d.%d.%d",
      (addr >> 24) & 0xFF,
      (addr >> 16) & 0xFF,
      (addr >> 8) & 0xFF,
      (addr >> 0) & 0xFF
      );
   return rc;
}

uint8_t Unpack8( const uint8_t* p, size_t size )
{
   return *p;
}

uint16_t Unpack16( const uint8_t* p, size_t size )
{
   uint16_t rc = 0;
   for( int i = 0; i < size; i++ )
   {
      rc <<= 8;
      rc |= *p;
      p++;
   }
   return rc;
}

uint32_t Unpack32( const uint8_t* p, size_t size )
{
   uint32_t rc = 0;
   for( int i = 0; i < size; i++ )
   {
      rc <<= 8;
      rc |= *p;
      p++;
   }
   return rc;
}

void ProtocolDHCP::test()
{
   printf( "sending discover\n" );
   Discover();
   printf( "discover sent\n" );
}

void ProtocolDHCP::ProcessRx( DataBuffer* buffer )
{
   printf( "ProtocolDHCP::ProcessRx\n" );

   uint8_t op = Unpack8( &buffer->Packet[ 0 ], 1 );
   uint8_t htype = Unpack8( &buffer->Packet[ 1 ], 1 );
   uint8_t hlen = Unpack8( &buffer->Packet[ 2 ], 1 );
   uint8_t hops = Unpack8( &buffer->Packet[ 3 ], 1 );
   uint32_t xid = Unpack32( &buffer->Packet[ 4 ], 4 );
   uint16_t secs = Unpack16( &buffer->Packet[ 8 ], 2 );
   uint16_t flags = Unpack16( &buffer->Packet[ 10 ], 2 );
   uint32_t ciaddr = Unpack32( &buffer->Packet[ 12 ], 4 ); // (Client IP address)
   uint32_t yiaddr = Unpack32( &buffer->Packet[ 16 ], 4 ); // (Your IP address)
   uint32_t siaddr = Unpack32( &buffer->Packet[ 20 ], 4 ); // (Server IP address)
   uint32_t giaddr = Unpack32( &buffer->Packet[ 24 ], 4 ); // (Gateway IP address)

   //uint8_t chaddr[ 16 ]; // (Client hardware address)
   //uint8_t sname[ 64 ];
   //uint8_t file[ 128 ];

   uint32_t magic = Unpack32( &buffer->Packet[ 236 ], 4 );

   printf( "op = %d\n", op );
   printf( "htype = %d\n", htype );
   printf( "hlen = %d\n", hlen );
   printf( "hops = %d\n", hops );
   printf( "xid = 0x%0X\n", xid );
   printf( "secs = %d\n", secs );
   printf( "flags = %d\n", flags );
   printf( "ciaddr = %s\n", inet_ntoa( ciaddr ) ); // (Client IP address)
   printf( "yiaddr = %s\n", inet_ntoa( yiaddr ) ); // (Your IP address)
   printf( "siaddr = %s\n", inet_ntoa( siaddr ) ); // (Server IP address)
   printf( "giaddr = %s\n", inet_ntoa( giaddr ) ); // (Gateway IP address)
   if( xid == PendingXID )
   {
      printf( "*********** this is for me ************\n" );
   }
   printf( "magic = 0x%0X\n", magic );
}

//9.4.DHCP Message Type
//
//This option is used to convey the type of the DHCP message.The code
//for this option is 53, and its length is 1.  Legal values for this
//option are :
//
//Value   Message Type
//---- - ------------
//1     DHCPDISCOVER
//2     DHCPOFFER
//3     DHCPREQUEST
//4     DHCPDECLINE
//5     DHCPACK
//6     DHCPNAK
//7     DHCPRELEASE
//
//Code   Len  Type
//+ ---- - +---- - +---- - +
//| 53 | 1 | 1 - 7 |
//+---- - +---- - +---- - +

void ProtocolDHCP::Discover()
{
   DataBuffer* buffer = ProtocolUDP::GetTxBuffer();
   if( buffer )
   {
      DHCPDISCOVER* packet = (DHCPDISCOVER*)(buffer->Packet);
      for( int i = 0; i < sizeof( DHCPDISCOVER ); i++ ) buffer->Packet[ i ] = 0;
      PendingXID = (uint32_t)osTime::GetProcessorTime();

      packet->op = 0x01;
      packet->htype = 0x01;
      packet->hlen = 0x06;
      packet->hops = 0x00;
      packet->xid = hton32( PendingXID );
      packet->secs = hton16( 0x0000 );
      packet->flags = hton16( 0x8000 );
      packet->ciaddr = hton32( 0x00000000 ); // (Client IP address)
      packet->yiaddr = hton32( 0x00000000 ); // (Your IP address)
      packet->siaddr = hton32( 0x00000000 ); // (Server IP address)
      packet->giaddr = hton32( 0x00000000 ); // (Gateway IP address)

      for( int i = 0; i < 6; i++ )
      {
         packet->chaddr[ i ] = Config.Address.Hardware[ i ];
      }
      packet->magic = hton32( DHCP_MAGIC );

      buffer->Length = sizeof( DHCPDISCOVER );

      // Add options
      buffer->Packet[ buffer->Length++ ] = 53;
      buffer->Packet[ buffer->Length++ ] = 1;
      buffer->Packet[ buffer->Length++ ] = 1; // DHCP Discover

      // client id
      buffer->Packet[ buffer->Length++ ] = 61;
      buffer->Packet[ buffer->Length++ ] = 7; // length
      buffer->Packet[ buffer->Length++ ] = 1; // type is hardware address
      for( int i = 0; i < 6; i++ ) buffer->Packet[ buffer->Length++ ] = Config.Address.Hardware[ i ];

      // requested address
      buffer->Packet[ buffer->Length++ ] = 0x32;
      buffer->Packet[ buffer->Length++ ] = 0x04;
      buffer->Packet[ buffer->Length++ ] = 0xC0;
      buffer->Packet[ buffer->Length++ ] = 0xA8;
      buffer->Packet[ buffer->Length++ ] = 0x01;
      buffer->Packet[ buffer->Length++ ] = 0x03;

      // host name
      const char* name = "tinytcp";
      buffer->Packet[ buffer->Length++ ] = 12;
      buffer->Packet[ buffer->Length++ ] = strlen( name );
      for( int i = 0; i < strlen( name ); i++ ) buffer->Packet[ buffer->Length++ ] = name[ i ];

      // vendor class ident
      buffer->Packet[ buffer->Length++ ] = 0x3C;
      buffer->Packet[ buffer->Length++ ] = 0x08;
      buffer->Packet[ buffer->Length++ ] = 0x4D;
      buffer->Packet[ buffer->Length++ ] = 0x53;
      buffer->Packet[ buffer->Length++ ] = 0x46;
      buffer->Packet[ buffer->Length++ ] = 0x54;
      buffer->Packet[ buffer->Length++ ] = 0x20;
      buffer->Packet[ buffer->Length++ ] = 0x35;
      buffer->Packet[ buffer->Length++ ] = 0x2E;
      buffer->Packet[ buffer->Length++ ] = 0x30;

      // parameter request list
      buffer->Packet[ buffer->Length++ ] = 55;
      buffer->Packet[ buffer->Length++ ] = 13; // length
      buffer->Packet[ buffer->Length++ ] = 1; // subnet mask
      buffer->Packet[ buffer->Length++ ] = 3; // router
      buffer->Packet[ buffer->Length++ ] = 6; // dns
      buffer->Packet[ buffer->Length++ ] = 15; // domain name
      buffer->Packet[ buffer->Length++ ] = 31; // domain name
      buffer->Packet[ buffer->Length++ ] = 33; // domain name
      buffer->Packet[ buffer->Length++ ] = 43; // domain name
      buffer->Packet[ buffer->Length++ ] = 44; // domain name
      buffer->Packet[ buffer->Length++ ] = 46; // domain name
      buffer->Packet[ buffer->Length++ ] = 47; // domain name
      buffer->Packet[ buffer->Length++ ] = 121; // domain name
      buffer->Packet[ buffer->Length++ ] = 249; // domain name
      buffer->Packet[ buffer->Length++ ] = 252; // domain name

      buffer->Packet[ buffer->Length++ ] = 255;  // End options

      int pad = 8;
      for( int i = 0; i < pad; i++ ) buffer->Packet[ buffer->Length++ ] = 0;

      uint8_t sourceIP[] = { 0, 0, 0, 0 };
      uint8_t targetIP[] = { 255, 255, 255, 255 };
      ProtocolUDP::Transmit( buffer, targetIP, 67, sourceIP, 68 );
   }
}
<commit_msg>remove unused DHCP fields<commit_after>//----------------------------------------------------------------------------
// Copyright( c ) 2016, Robert Kimball
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
//    contributors may be used to endorse or promote products derived from
//    this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//----------------------------------------------------------------------------

// DHCP Info https://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol
// DHCP Options http://www.faqs.org/rfcs/rfc1533.html

#include <stdio.h>
#include <string.h>
#include "ProtocolDHCP.h"
#include "ProtocolUDP.h"
#include "ProtocolIP.h"
#include "NetworkInterface.h"
#include "Utility.h"
#include "osTime.h"

extern AddressConfiguration Config;
int32_t ProtocolDHCP::PendingXID = -1;
static const uint32_t DHCP_MAGIC = 0x63825363;

const char* inet_ntoa( uint32_t addr )
{
   static char rc[ 20 ];
   sprintf( rc, "%d.%d.%d.%d",
      (addr >> 24) & 0xFF,
      (addr >> 16) & 0xFF,
      (addr >> 8) & 0xFF,
      (addr >> 0) & 0xFF
      );
   return rc;
}

uint8_t Unpack8( const uint8_t* p, size_t size )
{
   return *p;
}

uint16_t Unpack16( const uint8_t* p, size_t size )
{
   uint16_t rc = 0;
   for( int i = 0; i < size; i++ )
   {
      rc <<= 8;
      rc |= *p;
      p++;
   }
   return rc;
}

uint32_t Unpack32( const uint8_t* p, size_t size )
{
   uint32_t rc = 0;
   for( int i = 0; i < size; i++ )
   {
      rc <<= 8;
      rc |= *p;
      p++;
   }
   return rc;
}

void ProtocolDHCP::test()
{
   printf( "sending discover\n" );
   Discover();
   printf( "discover sent\n" );
}

void ProtocolDHCP::ProcessRx( DataBuffer* buffer )
{
   printf( "ProtocolDHCP::ProcessRx\n" );

   uint8_t op = Unpack8( &buffer->Packet[ 0 ], 1 );
   uint8_t htype = Unpack8( &buffer->Packet[ 1 ], 1 );
   uint8_t hlen = Unpack8( &buffer->Packet[ 2 ], 1 );
   uint8_t hops = Unpack8( &buffer->Packet[ 3 ], 1 );
   uint32_t xid = Unpack32( &buffer->Packet[ 4 ], 4 );
   uint16_t secs = Unpack16( &buffer->Packet[ 8 ], 2 );
   uint16_t flags = Unpack16( &buffer->Packet[ 10 ], 2 );
   uint32_t ciaddr = Unpack32( &buffer->Packet[ 12 ], 4 ); // (Client IP address)
   uint32_t yiaddr = Unpack32( &buffer->Packet[ 16 ], 4 ); // (Your IP address)
   uint32_t siaddr = Unpack32( &buffer->Packet[ 20 ], 4 ); // (Server IP address)
   uint32_t giaddr = Unpack32( &buffer->Packet[ 24 ], 4 ); // (Gateway IP address)

   //uint8_t chaddr[ 16 ]; // (Client hardware address)
   //uint8_t sname[ 64 ];
   //uint8_t file[ 128 ];

   uint32_t magic = Unpack32( &buffer->Packet[ 236 ], 4 );

   printf( "op = %d\n", op );
   printf( "htype = %d\n", htype );
   printf( "hlen = %d\n", hlen );
   printf( "hops = %d\n", hops );
   printf( "xid = 0x%0X\n", xid );
   printf( "secs = %d\n", secs );
   printf( "flags = %d\n", flags );
   printf( "ciaddr = %s\n", inet_ntoa( ciaddr ) ); // (Client IP address)
   printf( "yiaddr = %s\n", inet_ntoa( yiaddr ) ); // (Your IP address)
   printf( "siaddr = %s\n", inet_ntoa( siaddr ) ); // (Server IP address)
   printf( "giaddr = %s\n", inet_ntoa( giaddr ) ); // (Gateway IP address)
   if( xid == PendingXID )
   {
      printf( "*********** this is for me ************\n" );
   }
   printf( "magic = 0x%0X\n", magic );
}

//9.4.DHCP Message Type
//
//This option is used to convey the type of the DHCP message.The code
//for this option is 53, and its length is 1.  Legal values for this
//option are :
//
//Value   Message Type
//---- - ------------
//1     DHCPDISCOVER
//2     DHCPOFFER
//3     DHCPREQUEST
//4     DHCPDECLINE
//5     DHCPACK
//6     DHCPNAK
//7     DHCPRELEASE
//
//Code   Len  Type
//+ ---- - +---- - +---- - +
//| 53 | 1 | 1 - 7 |
//+---- - +---- - +---- - +

void ProtocolDHCP::Discover()
{
   DataBuffer* buffer = ProtocolUDP::GetTxBuffer();
   if( buffer )
   {
      DHCPDISCOVER* packet = (DHCPDISCOVER*)(buffer->Packet);
      for( int i = 0; i < sizeof( DHCPDISCOVER ); i++ ) buffer->Packet[ i ] = 0;
      PendingXID = (uint32_t)osTime::GetProcessorTime();

      packet->op = 0x01;
      packet->htype = 0x01;
      packet->hlen = 0x06;
      packet->hops = 0x00;
      packet->xid = hton32( PendingXID );
      packet->secs = hton16( 0x0000 );
      packet->flags = hton16( 0x8000 );
      packet->ciaddr = hton32( 0x00000000 ); // (Client IP address)
      packet->yiaddr = hton32( 0x00000000 ); // (Your IP address)
      packet->siaddr = hton32( 0x00000000 ); // (Server IP address)
      packet->giaddr = hton32( 0x00000000 ); // (Gateway IP address)

      for( int i = 0; i < 6; i++ )
      {
         packet->chaddr[ i ] = Config.Address.Hardware[ i ];
      }
      packet->magic = hton32( DHCP_MAGIC );

      buffer->Length = sizeof( DHCPDISCOVER );

      // Add options
      buffer->Packet[ buffer->Length++ ] = 53;
      buffer->Packet[ buffer->Length++ ] = 1;
      buffer->Packet[ buffer->Length++ ] = 1; // DHCP Discover

      // client id
      buffer->Packet[ buffer->Length++ ] = 61;
      buffer->Packet[ buffer->Length++ ] = 7; // length
      buffer->Packet[ buffer->Length++ ] = 1; // type is hardware address
      for( int i = 0; i < 6; i++ ) buffer->Packet[ buffer->Length++ ] = Config.Address.Hardware[ i ];

      // host name
      const char* name = "tinytcp";
      buffer->Packet[ buffer->Length++ ] = 12;
      buffer->Packet[ buffer->Length++ ] = strlen( name );
      for( int i = 0; i < strlen( name ); i++ ) buffer->Packet[ buffer->Length++ ] = name[ i ];

      // parameter request list
      buffer->Packet[ buffer->Length++ ] = 55;
      buffer->Packet[ buffer->Length++ ] = 13; // length
      buffer->Packet[ buffer->Length++ ] = 1; // subnet mask
      buffer->Packet[ buffer->Length++ ] = 3; // router
      buffer->Packet[ buffer->Length++ ] = 6; // dns
      buffer->Packet[ buffer->Length++ ] = 15; // domain name

      buffer->Packet[ buffer->Length++ ] = 255;  // End options

      int pad = 8;
      for( int i = 0; i < pad; i++ ) buffer->Packet[ buffer->Length++ ] = 0;

      uint8_t sourceIP[] = { 0, 0, 0, 0 };
      uint8_t targetIP[] = { 255, 255, 255, 255 };
      ProtocolUDP::Transmit( buffer, targetIP, 67, sourceIP, 68 );
   }
}
<|endoftext|>


<commit_before>#ifndef MPACK_GROUPCONTROLLERS_HPP
#define MPACK_GROUPCONTROLLERS_HPP

#include "GroupController.hpp"
#include "PlayGroupController.hpp"
#include "VolumeGroupController.hpp"

#endif
<commit_msg>Updated GroupControllers.hpp<commit_after>#ifndef MPACK_GROUPCONTROLLERS_HPP
#define MPACK_GROUPCONTROLLERS_HPP

#include "GroupController.hpp"
#include "PlayGroupController.hpp"
#include "VolumeGroupController.hpp"
#include "StereoGroupController.hpp"

#endif
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016-2018 metaverse core developers (see MVS-AUTHORS)
 *
 * This file is part of metaverse.
 *
 * metaverse is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <metaverse/consensus/witness.hpp>
#include <metaverse/node/p2p_node.hpp>
#include <metaverse/blockchain/settings.hpp>
#include <mutex>

#define LOG_HEADER "witness"

namespace libbitcoin {
namespace consensus {

witness* witness::instance_ = nullptr;

witness::witness(p2p_node& node)
    : node_(node)
    , setting_(node_.chain_impl().chain_settings())
    , epoch_height_(0)
    , witness_list_()
    , candidate_list_()
    , mutex_()
{
}

witness::~witness()
{
}

void witness::init(p2p_node& node)
{
    static witness s_instance(node);
    instance_ = &s_instance;
}

witness& witness::create(p2p_node& node)
{
    static std::once_flag s_flag;
    std::call_once(s_flag, witness::init, node);
    return *instance_;
}

witness& witness::get()
{
    BITCOIN_ASSERT_MSG(instance_, "use witness::create() before witness::get()");
    return *instance_;
}

witness::iterator witness::finds(list& l, const witness_id& id)
{
    auto cmp = [&id](const witness_id& item){return id == item;};
    return std::find_if(std::begin(l), std::end(l), cmp);
}

witness::const_iterator witness::finds(const list& l, const witness_id& id)
{
    auto cmp = [&id](const witness_id& item){return id == item;};
    return std::find_if(std::begin(l), std::end(l), cmp);
}

bool witness::exists(const list& l, const witness_id& id)
{
    return finds(l, id) != l.end();
}

witness::list witness::get_witness_list() const
{
    shared_lock lock(mutex_);
    return witness_list_;
}

witness::list witness::get_candidate_list() const
{
    shared_lock lock(mutex_);
    return candidate_list_;
}

bool witness::is_witness(const witness_id& id) const
{
    shared_lock lock(mutex_);
    return (!id.empty()) && exists(witness_list_, id);
}

bool witness::register_witness(const witness_id& id)
{
    upgrade_lock lock(mutex_);

    if (exists(witness_list_, id) || exists(candidate_list_, id)) {
        log::debug(LOG_HEADER) << "In register_witness, " << id << " is already registered.";
        return false;
    }

    upgrade_to_unique_lock ulock(lock);
    candidate_list_.push_back(id);
    return true;
}

bool witness::unregister_witness(const witness_id& id)
{
    upgrade_lock lock(mutex_);

    auto witness_pos = finds(witness_list_, id);
    auto candidate_pos = finds(candidate_list_, id);

    if (witness_pos == witness_list_.end() && candidate_pos == candidate_list_.end()) {
        log::debug(LOG_HEADER) << "In unregister_witness, " << id << " is not registered.";
        return false;
    }

    upgrade_to_unique_lock ulock(lock);
    if (witness_pos != witness_list_.end()) {
        // clear data instead of remove, as a stub
        *witness_pos = witness_id();
    }
    if (candidate_pos != candidate_list_.end()) {
        candidate_list_.erase(candidate_pos);
    }
    return true;
}

// DPOS_TODO: add algorithm to generate the witness list of each epoch
bool witness::update_witness_list(uint64_t height)
{
    return true;
}

void witness::set_epoch_height(uint64_t block_height)
{
    unique_lock lock(mutex_);
    epoch_height_ = block_height;
}

uint32_t witness::get_slot_num(const witness_id& id) const
{
    shared_lock lock(mutex_);
    auto pos = finds(witness_list_, id);
    if (pos != witness_list_.end()) {
        return pos - witness_list_.cbegin();
    }
    return max_uint32;
}

bool witness::sign(endorsement& out, const ec_secret& secret, const chain::header& h)
{
    const auto sighash = h.hash();

    ec_signature signature;
    if (!bc::sign(signature, secret, sighash) || !bc::encode_signature(out, signature)) {
        return false;
    }

    out.push_back(h.number & 0xff);
    return true;
}

bool witness::verify_sign(const endorsement& out, const public_key_t& public_key, const chain::header& h)
{
    if (public_key.empty()) {
        return false;
    }

    if (out.back() != (h.number & 0xff)) {
        return false;
    }

    auto distinguished = out;
    distinguished.pop_back();

    ec_signature signature;

    if (!parse_signature(signature, distinguished, true)) {
        return false;
    }

    const auto sighash = h.hash();

    return bc::verify_signature(public_key, sighash, signature);
}

bool witness::verify_signer(const public_key_t& public_key, const chain::block& block, const chain::header& prev_header) const
{
    shared_lock lock(mutex_);
    auto witness_slot_num = get_slot_num(public_key);
    return verify_signer(witness_slot_num, block, prev_header);
}

bool witness::verify_signer(uint32_t witness_slot_num, const chain::block& block, const chain::header& prev_header) const
{
    if (witness_slot_num >= witess_number) {
        return false;
    }

    const auto& header = block.header;
    auto block_height = header.number;
    auto calced_slot_num = ((block_height - epoch_height_) % witess_number);
    if (calced_slot_num == witness_slot_num) {
        return true;
    }
    static uint32_t time_config{24}; // same as HeaderAux::calculateDifficulty
    if (header.timestamp > prev_header.timestamp + time_config*2) {
        return true;
    }
    return false;
}

} // consensus
} // libbitcoin
<commit_msg>fix std::call_once can not pass building<commit_after>/**
 * Copyright (c) 2016-2018 metaverse core developers (see MVS-AUTHORS)
 *
 * This file is part of metaverse.
 *
 * metaverse is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <metaverse/consensus/witness.hpp>
#include <metaverse/node/p2p_node.hpp>
#include <metaverse/blockchain/settings.hpp>

#define LOG_HEADER "witness"

namespace libbitcoin {
namespace consensus {

witness* witness::instance_ = nullptr;

witness::witness(p2p_node& node)
    : node_(node)
    , setting_(node_.chain_impl().chain_settings())
    , epoch_height_(0)
    , witness_list_()
    , candidate_list_()
    , mutex_()
{
}

witness::~witness()
{
}

void witness::init(p2p_node& node)
{
    static witness s_instance(node);
    instance_ = &s_instance;
}

witness& witness::create(p2p_node& node)
{
    static unique_mutex umutex;
    if (!instance_) {
        scoped_lock l(umutex);
        init(node);
    }
    return *instance_;
}

witness& witness::get()
{
    BITCOIN_ASSERT_MSG(instance_, "use witness::create() before witness::get()");
    return *instance_;
}

witness::iterator witness::finds(list& l, const witness_id& id)
{
    auto cmp = [&id](const witness_id& item){return id == item;};
    return std::find_if(std::begin(l), std::end(l), cmp);
}

witness::const_iterator witness::finds(const list& l, const witness_id& id)
{
    auto cmp = [&id](const witness_id& item){return id == item;};
    return std::find_if(std::begin(l), std::end(l), cmp);
}

bool witness::exists(const list& l, const witness_id& id)
{
    return finds(l, id) != l.end();
}

witness::list witness::get_witness_list() const
{
    shared_lock lock(mutex_);
    return witness_list_;
}

witness::list witness::get_candidate_list() const
{
    shared_lock lock(mutex_);
    return candidate_list_;
}

bool witness::is_witness(const witness_id& id) const
{
    shared_lock lock(mutex_);
    return (!id.empty()) && exists(witness_list_, id);
}

bool witness::register_witness(const witness_id& id)
{
    upgrade_lock lock(mutex_);

    if (exists(witness_list_, id) || exists(candidate_list_, id)) {
        log::debug(LOG_HEADER) << "In register_witness, " << id << " is already registered.";
        return false;
    }

    upgrade_to_unique_lock ulock(lock);
    candidate_list_.push_back(id);
    return true;
}

bool witness::unregister_witness(const witness_id& id)
{
    upgrade_lock lock(mutex_);

    auto witness_pos = finds(witness_list_, id);
    auto candidate_pos = finds(candidate_list_, id);

    if (witness_pos == witness_list_.end() && candidate_pos == candidate_list_.end()) {
        log::debug(LOG_HEADER) << "In unregister_witness, " << id << " is not registered.";
        return false;
    }

    upgrade_to_unique_lock ulock(lock);
    if (witness_pos != witness_list_.end()) {
        // clear data instead of remove, as a stub
        *witness_pos = witness_id();
    }
    if (candidate_pos != candidate_list_.end()) {
        candidate_list_.erase(candidate_pos);
    }
    return true;
}

// DPOS_TODO: add algorithm to generate the witness list of each epoch
bool witness::update_witness_list(uint64_t height)
{
    return true;
}

void witness::set_epoch_height(uint64_t block_height)
{
    unique_lock lock(mutex_);
    epoch_height_ = block_height;
}

uint32_t witness::get_slot_num(const witness_id& id) const
{
    shared_lock lock(mutex_);
    auto pos = finds(witness_list_, id);
    if (pos != witness_list_.end()) {
        return pos - witness_list_.cbegin();
    }
    return max_uint32;
}

bool witness::sign(endorsement& out, const ec_secret& secret, const chain::header& h)
{
    const auto sighash = h.hash();

    ec_signature signature;
    if (!bc::sign(signature, secret, sighash) || !bc::encode_signature(out, signature)) {
        return false;
    }

    out.push_back(h.number & 0xff);
    return true;
}

bool witness::verify_sign(const endorsement& out, const public_key_t& public_key, const chain::header& h)
{
    if (public_key.empty()) {
        return false;
    }

    if (out.back() != (h.number & 0xff)) {
        return false;
    }

    auto distinguished = out;
    distinguished.pop_back();

    ec_signature signature;

    if (!parse_signature(signature, distinguished, true)) {
        return false;
    }

    const auto sighash = h.hash();

    return bc::verify_signature(public_key, sighash, signature);
}

bool witness::verify_signer(const public_key_t& public_key, const chain::block& block, const chain::header& prev_header) const
{
    shared_lock lock(mutex_);
    auto witness_slot_num = get_slot_num(public_key);
    return verify_signer(witness_slot_num, block, prev_header);
}

bool witness::verify_signer(uint32_t witness_slot_num, const chain::block& block, const chain::header& prev_header) const
{
    if (witness_slot_num >= witess_number) {
        return false;
    }

    const auto& header = block.header;
    auto block_height = header.number;
    auto calced_slot_num = ((block_height - epoch_height_) % witess_number);
    if (calced_slot_num == witness_slot_num) {
        return true;
    }
    static uint32_t time_config{24}; // same as HeaderAux::calculateDifficulty
    if (header.timestamp > prev_header.timestamp + time_config*2) {
        return true;
    }
    return false;
}

} // consensus
} // libbitcoin
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 **/
#include "modules/planning/math/smoothing_spline/piecewise_linear_kernel.h"

#include "gtest/gtest.h"

namespace apollo {
namespace planning {

using Eigen::MatrixXd;

TEST(TestPiecewiseLinearKernel, add_regularization) {
  PiecewiseLinearKernel kernel(10, 0.1);

  kernel.AddRegularization(0.2);

  const auto mat = kernel.kernel_matrix();
  const auto offset = kernel.offset_matrix();

  std::cout << mat << std::endl;
  std::cout << offset << std::endl;

  MatrixXd mat_golden(10, 10);
  // clang-format off
  mat_golden <<
    0.2,   0,   0,   0,   0,   0,   0,   0,   0,   0,
      0, 0.2,   0,   0,   0,   0,   0,   0,   0,   0,
      0,   0, 0.2,   0,   0,   0,   0,   0,   0,   0,
      0,   0,   0, 0.2,   0,   0,   0,   0,   0,   0,
      0,   0,   0,   0, 0.2,   0,   0,   0,   0,   0,
      0,   0,   0,   0,   0, 0.2,   0,   0,   0,   0,
      0,   0,   0,   0,   0,   0, 0.2,   0,   0,   0,
      0,   0,   0,   0,   0,   0,   0, 0.2,   0,   0,
      0,   0,   0,   0,   0,   0,   0,   0, 0.2,   0,
      0,   0,   0,   0,   0,   0,   0,   0,   0, 0.2;
  // clang-format on
  EXPECT_EQ(mat, mat_golden);

  MatrixXd offset_golden(10, 1);
  offset_golden << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;
  EXPECT_EQ(offset, offset_golden);

  kernel.AddRegularization(0.3);
  mat_golden = MatrixXd::Identity(10, 10) * 0.5;
  EXPECT_EQ(kernel.kernel_matrix(), mat_golden);
}

TEST(TestPiecewiseLinearKernel, add_reference_line_kernel_matrix) {
  PiecewiseLinearKernel kernel(10, 0.1);

  std::vector<uint32_t> index_list;
  std::vector<double> pos_list;
  for (int i = 0; i < 10; ++i) {
    index_list.push_back(i);
    pos_list.push_back(i * 2);
  }

  kernel.AddReferenceLineKernelMatrix(index_list, pos_list, 10.0);

  const auto mat = kernel.kernel_matrix();
  const auto offset = kernel.offset_matrix();

  std::cout << mat << std::endl;
  std::cout << offset << std::endl;

  MatrixXd mat_golden = MatrixXd::Identity(10, 10) * 10.0;
  EXPECT_EQ(mat, mat_golden);

  MatrixXd offset_golden(10, 1);
  offset_golden << 0, -40, -80, -120, -160, -200, -240, -280, -320, -360;

  EXPECT_EQ(offset, offset_golden);
}

}  // namespace planning
}  // namespace apollo
<commit_msg>Planning: added TestPiecewiseLinearKernel - add_second_derivative_kernel_matrix. (#484)<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 **/
#include "modules/planning/math/smoothing_spline/piecewise_linear_kernel.h"

#include "gtest/gtest.h"

namespace apollo {
namespace planning {

using Eigen::MatrixXd;

TEST(TestPiecewiseLinearKernel, add_regularization) {
  PiecewiseLinearKernel kernel(10, 0.1);

  kernel.AddRegularization(0.2);

  const auto mat = kernel.kernel_matrix();
  const auto offset = kernel.offset_matrix();

  std::cout << mat << std::endl;
  std::cout << offset << std::endl;

  MatrixXd mat_golden(10, 10);
  // clang-format off
  mat_golden <<
    0.2,   0,   0,   0,   0,   0,   0,   0,   0,   0,
      0, 0.2,   0,   0,   0,   0,   0,   0,   0,   0,
      0,   0, 0.2,   0,   0,   0,   0,   0,   0,   0,
      0,   0,   0, 0.2,   0,   0,   0,   0,   0,   0,
      0,   0,   0,   0, 0.2,   0,   0,   0,   0,   0,
      0,   0,   0,   0,   0, 0.2,   0,   0,   0,   0,
      0,   0,   0,   0,   0,   0, 0.2,   0,   0,   0,
      0,   0,   0,   0,   0,   0,   0, 0.2,   0,   0,
      0,   0,   0,   0,   0,   0,   0,   0, 0.2,   0,
      0,   0,   0,   0,   0,   0,   0,   0,   0, 0.2;
  // clang-format on
  EXPECT_EQ(mat, mat_golden);

  MatrixXd offset_golden(10, 1);
  offset_golden << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;
  EXPECT_EQ(offset, offset_golden);

  kernel.AddRegularization(0.3);
  mat_golden = MatrixXd::Identity(10, 10) * 0.5;
  EXPECT_EQ(kernel.kernel_matrix(), mat_golden);
}

TEST(TestPiecewiseLinearKernel, add_reference_line_kernel_matrix) {
  PiecewiseLinearKernel kernel(10, 0.1);

  std::vector<uint32_t> index_list;
  std::vector<double> pos_list;
  for (int i = 0; i < 10; ++i) {
    index_list.push_back(i);
    pos_list.push_back(i * 2);
  }

  kernel.AddReferenceLineKernelMatrix(index_list, pos_list, 10.0);

  const auto mat = kernel.kernel_matrix();
  const auto offset = kernel.offset_matrix();

  std::cout << mat << std::endl;
  std::cout << offset << std::endl;

  MatrixXd mat_golden = MatrixXd::Identity(10, 10) * 10.0;
  EXPECT_EQ(mat, mat_golden);

  MatrixXd offset_golden(10, 1);
  offset_golden << 0, -40, -80, -120, -160, -200, -240, -280, -320, -360;

  EXPECT_EQ(offset, offset_golden);
}

TEST(TestPiecewiseLinearKernel, add_second_order_derivative_matrix) {
  PiecewiseLinearKernel kernel(10, 0.1);
  const double init_derivative = 5.0;

  kernel.AddSecondOrderDerivativeMatrix(init_derivative, 1.0);

  const auto mat = kernel.kernel_matrix() / (2.0 * 1.0 / std::pow(0.1, 4));
  const auto offset = kernel.offset_matrix();

  std::cout << mat << std::endl;
  std::cout << offset << std::endl;

  MatrixXd mat_golden(10, 10);
  // clang-format off
  mat_golden <<
      6, -4,  1,  0,  0,  0,  0,  0,  0,  0,
     -4,  6, -4,  1,  0,  0,  0,  0,  0,  0,
      1, -4,  6, -4,  1,  0,  0,  0,  0,  0,
      0,  1, -4,  6, -4,  1,  0,  0,  0,  0,
      0,  0,  1, -4,  6, -4,  1,  0,  0,  0,
      0,  0,  0,  1, -4,  6, -4,  1,  0,  0,
      0,  0,  0,  0,  1, -4,  6, -4,  1,  0,
      0,  0,  0,  0,  0,  1, -4,  6, -4,  1,
      0,  0,  0,  0,  0,  0,  1, -4,  5, -2,
      0,  0,  0,  0,  0,  0,  0,  1, -2,  1;
  // clang-format on
  EXPECT_EQ(mat, mat_golden);

  MatrixXd offset_golden = MatrixXd::Zero(10, 1);
  offset_golden(0, 0) = -10000.0;

  for (int i = 0; i < 10; ++i) {
    EXPECT_DOUBLE_EQ(offset(i, 0), offset_golden(i, 0));
  }
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstring>
#include <cassert>
const int shift = 32;
const unsigned long long BASE = (unsigned long long)1 << shift;
const int LEN = 10000000;

void add(unsigned dest[], unsigned src[]) {
	for (int i = LEN - 1; i >= 0; i--)
		if (dest[i] >= BASE - src[i]) {
			assert(i && "Oh carry overflow!");
			dest[i] = (long long)dest[i] + src[i] - BASE;
			dest[i - 1]++;
		} else {
			dest[i] += src[i];
		}
}

void minus(unsigned dest[], unsigned src[]) {
	bool borrow = false;
	for (int i = LEN - 1; i >= 0; i--)
		if (dest[i] < src[i] + (borrow? 1: 0)) {
			assert(i && "Oh borrow overflow!");
			dest[i] = (unsigned long long)dest[i] + BASE - src[i] - (borrow? 1: 0);
			borrow = true;
		} else {
			dest[i] = dest[i] - src[i] - (borrow? 1: 0);
			borrow = false;
		}
}

void multiply(unsigned dest[], unsigned num) {
	unsigned carry = 0;
	for (int i = LEN - 1; i >= 0; i--) {
		unsigned long long tmp = (unsigned long long)num * dest[i] + carry;
		assert((tmp & (BASE - 1)) < BASE && "multiply truncation");
		dest[i] = (tmp & (BASE - 1));
		carry = tmp >> shift;
		assert((i || !carry) && "Oh multiply overflow!");
	}
}

void divide(unsigned dest[], unsigned num) {
	unsigned long long s = 0;
	for (int i = 0; i < LEN; i++) {
		s <<= shift;
		s += dest[i];
		if (s >= num) {
			assert(s / num < BASE && "divide truncation");
			dest[i] = s / num;
			s %= num;
		} else {
			dest[i] = 0;
		}
	}
}

void test_multiply_divide() {
	unsigned *ptr = new unsigned[LEN];
	for (int i = 0; i < LEN; i++)
		ptr[i] = i;
	unsigned num = 123454321;
	multiply(ptr, num);
	divide(ptr, num);
	for (size_t i = 0; i < LEN; i++)
		assert(ptr[i] == i && "multiply or divide error.");
	delete[] ptr;
}

void test_add_minus() {
	unsigned *ptr = new unsigned[LEN], *ptr2 = new unsigned[LEN];
	for (size_t i = 0; i < LEN; i++) {
		ptr[i] = LEN - i;
		ptr2[i] = ptr[i] + 1;
	}
	ptr[0] = 1, ptr2[0] = 0;

	minus(ptr, ptr2);
	assert(ptr[0] == 0 && "ptr[0] minus error.");
	assert(ptr[LEN - 1] == BASE - 1 && "ptr[LEN - 1] minus error.");
	for (int i = 1; i < LEN - 1; i++)
		assert(ptr[i] == BASE - 2 && "substraction error.");

	add(ptr, ptr2);
	assert(ptr[0] == 1 && "ptr[0] add error.");
	for (size_t i = 1; i < LEN; i++)
		assert(ptr[i] == LEN - i && "addition error.");
	delete[] ptr;
	delete[] ptr2;
}

inline void print(unsigned num) {
	for (int pos = 28; pos >= 0; pos -= 4)
		printf("%01X", (num >> pos) & 0xF);
}

void test_print() {
	unsigned tmp = 180150013;
	print(tmp);
}

inline void output(unsigned array[]) {
	printf("3.\n");
	for (int i = 1; i < LEN; i++)
		print(array[i]);
	printf("\n");
}

void shift_right(unsigned sub[], int num) {
	for (int i = LEN - 1; i >= 0; i++) {
	}
}

void cal_sub_Pi(unsigned Pi[], unsigned k) {
	unsigned *sub = new unsigned[LEN];
	memset(sub, 0, sizeof(unsigned) * LEN);

	sub[0] = 4;
	delete[] sub;
}

int main(int argc, char *argv[]) {
	test_add_minus();
	test_multiply_divide();
	test_print();
	return 0;
}
<commit_msg>formula sum{ (-1)^(k-1) *  1/(2k-1) } (k = 1, 2, ... )<commit_after>#include <cstdio>
#include <cstring>
#include <cassert>
const int SHIFT = 32;
const unsigned long long BASE = (unsigned long long)1 << SHIFT;
const int LEN	=	1000;
const int LOOP	=	5000000;

void add(unsigned dest[], unsigned src[]) {
	for (int i = LEN - 1; i >= 0; i--)
		if (dest[i] >= BASE - src[i]) {
			assert(i && "Oh carry overflow!");
			dest[i] = (long long)dest[i] + src[i] - BASE;
			dest[i - 1]++;
		} else {
			dest[i] += src[i];
		}
}

void minus(unsigned dest[], unsigned src[]) {
	bool borrow = false;
	for (int i = LEN - 1; i >= 0; i--)
		if (dest[i] < src[i] + (borrow? 1: 0)) {
			assert(i && "Oh borrow overflow!");
			dest[i] = (unsigned long long)dest[i] + BASE - src[i] - (borrow? 1: 0);
			borrow = true;
		} else {
			dest[i] = dest[i] - src[i] - (borrow? 1: 0);
			borrow = false;
		}
}

void multiply(unsigned dest[], unsigned num) {
	unsigned carry = 0;
	for (int i = LEN - 1; i >= 0; i--) {
		unsigned long long tmp = (unsigned long long)num * dest[i] + carry;
		assert((tmp & (BASE - 1)) < BASE && "multiply truncation");
		dest[i] = (tmp & (BASE - 1));
		carry = tmp >> SHIFT;
		assert((i || !carry) && "Oh multiply overflow!");
	}
}

void divide(unsigned dest[], unsigned num) {
	unsigned long long s = 0;
	for (int i = 0; i < LEN; i++) {
		s <<= SHIFT;
		s += dest[i];
		if (s >= num) {
			assert(s / num < BASE && "divide truncation");
			dest[i] = s / num;
			s %= num;
		} else {
			dest[i] = 0;
		}
	}
}

void test_multiply_divide() {
	unsigned *ptr = new unsigned[LEN];
	for (int i = 0; i < LEN; i++)
		ptr[i] = i;
	unsigned num = 123454321;
	multiply(ptr, num);
	divide(ptr, num);
	for (size_t i = 0; i < LEN; i++)
		assert(ptr[i] == i && "multiply or divide error.");
	delete[] ptr;
}

void test_add_minus() {
	unsigned *ptr = new unsigned[LEN], *ptr2 = new unsigned[LEN];
	for (size_t i = 0; i < LEN; i++) {
		ptr[i] = LEN - i;
		ptr2[i] = ptr[i] + 1;
	}
	ptr[0] = 1, ptr2[0] = 0;

	minus(ptr, ptr2);
	assert(ptr[0] == 0 && "ptr[0] minus error.");
	assert(ptr[LEN - 1] == BASE - 1 && "ptr[LEN - 1] minus error.");
	for (int i = 1; i < LEN - 1; i++)
		assert(ptr[i] == BASE - 2 && "substraction error.");

	add(ptr, ptr2);
	assert(ptr[0] == 1 && "ptr[0] add error.");
	for (size_t i = 1; i < LEN; i++)
		assert(ptr[i] == LEN - i && "addition error.");
	delete[] ptr;
	delete[] ptr2;
}

inline void print(unsigned num) {
	for (int pos = SHIFT - 4; pos >= 0; pos -= 4)
		printf("%01X", (num >> pos) & 0xF);
}

void test_print() {
	unsigned tmp = 180150013;
	print(tmp);
}

inline void output(unsigned array[]) {
	printf("%d.\n", array[0]);
	unsigned digit = 0;
	for (int i = 1; i < LEN; i++)
		for (int pos = SHIFT - 4; pos >= 0; pos -= 4) {
			printf("%01X", (array[i] >> pos) & 0xF);
			if (++digit == 64) {
				printf("\n");
				digit = 0;
			}
		}
	printf("\n");
}

/*
void shift_right(unsigned sub[], int num) {
	memmove((void *)sub + num, sub, sizeof(unsigned) * LEN - num);
	memset(sub, 0, num);
}

void test_shift_right() {
	unsigned *sub = new unsigned[LEN];
	sub[0] = 0xF0;
	shift_right(sub, sizeof(unsigned) * (LEN - 1));
	assert(
	delete[] sub;
}
*/

void cal_Pi(unsigned Pi[]) {
	unsigned *sub = new unsigned[LEN];

	for (unsigned i = 1; i < LOOP; i++) {
		memset(sub, 0, sizeof(unsigned) * LEN);
		sub[0] = 4;
		divide(sub, 2 * i - 1);
		if (i % 2)
			add(Pi, sub);
		else
			minus(Pi, sub);
	}
	delete[] sub;
}

int main(int argc, char *argv[]) {
	/*
	test_add_minus();
	test_multiply_divide();
	test_print();
	*/
	unsigned *Pi = new unsigned[LEN];
	cal_Pi(Pi);
	output(Pi);
	delete[] Pi;
	return 0;
}
<|endoftext|>


<commit_before>/* vim:set ts=4 sw=4 sts=4 et: */

#include <set>
#include <stdexcept>
#include <igraph/cpp/edge.h>
#include <igraph/cpp/generators/line_graph.h>
#include <netctrl/model/liu.h>
#include <netctrl/model/switchboard.h>

namespace netctrl {

using namespace igraph;

SwitchboardControllabilityModel::~SwitchboardControllabilityModel() {
    clearControlPaths();
}

void SwitchboardControllabilityModel::calculate() {
    // Construct the line graph first
    Graph lg(line_graph(*m_pGraph));

    // Find the driver nodes in the line graph; these are the driver edges
    // in our model
    LiuControllabilityModel model(&lg);
    model.calculate();

    // Loop through the stems and buds of the line graph. The root of each
    // stem represents an edge in the original graph and its tail will
    // become a driver node.
    std::vector<ControlPath*> controlPaths = model.controlPaths();
    std::set<long int> driverNodeSet;

    for (std::vector<ControlPath*>::const_iterator it = controlPaths.begin();
            it != controlPaths.end(); it++) {
        ControlPath* path = *it;
        Stem* stem = dynamic_cast<Stem*>(path);
        if (stem != 0) {
            // Store the source vertex of the root of the stem
            driverNodeSet.insert(m_pGraph->edge(stem->root()).tail());
        }
    }

    m_driverNodes = Vector(driverNodeSet.begin(), driverNodeSet.end());
}

void SwitchboardControllabilityModel::clearControlPaths() {
    for (std::vector<ControlPath*>::const_iterator it = m_controlPaths.begin();
            it != m_controlPaths.end(); it++) {
        delete *it;
    }
}

std::vector<ControlPath*> SwitchboardControllabilityModel::controlPaths() const {
    return m_controlPaths;
}

igraph::Vector SwitchboardControllabilityModel::driverNodes() const {
    return m_driverNodes;
}

}        // end of namespaces

<commit_msg>fixed an edge case in the switchboard dynamics<commit_after>/* vim:set ts=4 sw=4 sts=4 et: */

#include <set>
#include <stdexcept>
#include <igraph/cpp/edge.h>
#include <igraph/cpp/generators/line_graph.h>
#include <netctrl/model/liu.h>
#include <netctrl/model/switchboard.h>

namespace netctrl {

using namespace igraph;

SwitchboardControllabilityModel::~SwitchboardControllabilityModel() {
    clearControlPaths();
}

void SwitchboardControllabilityModel::calculate() {
    // Construct the line graph first
    Graph lg(line_graph(*m_pGraph));

    // Find the driver nodes in the line graph; these are the driver edges
    // in our model
    LiuControllabilityModel model(&lg);
    model.calculate();

    // Loop through the stems and buds of the line graph. The root of each
    // stem represents an edge in the original graph and its tail will
    // become a driver node.
    std::vector<ControlPath*> controlPaths = model.controlPaths();
    std::set<long int> driverNodeSet;

    for (std::vector<ControlPath*>::const_iterator it = controlPaths.begin();
            it != controlPaths.end(); it++) {
        ControlPath* path = *it;
        Stem* stem = dynamic_cast<Stem*>(path);
        if (stem != 0) {
            // Store the source vertex of the root of the stem
            driverNodeSet.insert(m_pGraph->edge(stem->root()).tail());
        }
    }

    // Now, check the buds. Each bud that is not attached to a stem in the line
    // graph is problematic. For such buds, we have to iterate over its edges,
    // map the endpoints of the edges back to the original graph, and see if
    // any of these is already a driver node. If so, we are okay. If not, we
    // have to make one of the nodes a driver node.
    for (std::vector<ControlPath*>::const_iterator it = controlPaths.begin();
            it != controlPaths.end(); it++) {
        ControlPath* path = *it;
        Bud* bud = dynamic_cast<Bud*>(path);
        if (bud != 0 && bud->stem() == 0) {
            Vector::const_iterator it, end = bud->nodes().end();
            bool foundDriverNode = false;

            for (it = bud->nodes().begin(); it != end && !foundDriverNode; it++) {
                if (driverNodeSet.find(*it) != driverNodeSet.end())
                    foundDriverNode = true;
            }

            if (!foundDriverNode) {
                // TODO: better strategy; what if there is another node which
                // could control more than one bud? Is it possible?
                driverNodeSet.insert(bud->nodes().front());
            }
        }
    }

    m_driverNodes = Vector(driverNodeSet.begin(), driverNodeSet.end());
}

void SwitchboardControllabilityModel::clearControlPaths() {
    for (std::vector<ControlPath*>::const_iterator it = m_controlPaths.begin();
            it != m_controlPaths.end(); it++) {
        delete *it;
    }
}

std::vector<ControlPath*> SwitchboardControllabilityModel::controlPaths() const {
    return m_controlPaths;
}

igraph::Vector SwitchboardControllabilityModel::driverNodes() const {
    return m_driverNodes;
}

}        // end of namespaces

<|endoftext|>