text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef EIGEN_BINARY_FUNCTORS_H
#define EIGEN_BINARY_FUNCTORS_H

namespace Eigen {

namespace internal {

//---------- associative binary functors ----------

template<typename Arg1, typename Arg2>
struct binary_op_base
{
  typedef Arg1 first_argument_type;
  typedef Arg2 second_argument_type;
};

/** \internal
  * \brief Template functor to compute the sum of two scalars
  *
  * \sa class CwiseBinaryOp, MatrixBase::operator+, class VectorwiseOp, DenseBase::sum()
  */
template<typename LhsScalar,typename RhsScalar>
struct scalar_sum_op : binary_op_base<LhsScalar,RhsScalar>
{
  typedef typename ScalarBinaryOpTraits<LhsScalar,RhsScalar,scalar_sum_op>::ReturnType result_type;
#ifndef EIGEN_SCALAR_BINARY_OP_PLUGIN
  EIGEN_EMPTY_STRUCT_CTOR(scalar_sum_op)
#else
  scalar_sum_op() {
    EIGEN_SCALAR_BINARY_OP_PLUGIN
  }
#endif
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const result_type operator() (const LhsScalar& a, const RhsScalar& b) const { return a + b; }
  template<typename Packet>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a, const Packet& b) const
  { return internal::padd(a,b); }
  template<typename Packet>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const result_type predux(const Packet& a) const
  { return internal::predux(a); }
};
template<typename LhsScalar,typename RhsScalar>
struct functor_traits<scalar_sum_op<LhsScalar,RhsScalar> > {
  enum {
    Cost = (NumTraits<LhsScalar>::AddCost+NumTraits<RhsScalar>::AddCost)/2, // rough estimate!
    PacketAccess = is_same<LhsScalar,RhsScalar>::value && packet_traits<LhsScalar>::HasAdd && packet_traits<RhsScalar>::HasAdd
    // TODO vectorize mixed sum
  };
};

/** \internal
  * \brief Template specialization to deprecate the summation of boolean expressions.
  * This is required to solve Bug 426.
  * \sa DenseBase::count(), DenseBase::any(), ArrayBase::cast(), MatrixBase::cast()
  */
template<> struct scalar_sum_op<bool,bool> : scalar_sum_op<int,int> {
  EIGEN_DEPRECATED
  scalar_sum_op() {}
};

/** \internal
  * \brief Template functor to compute the product of two scalars
  *
  * \sa class CwiseBinaryOp, Cwise::operator*(), class VectorwiseOp, MatrixBase::redux()
  */
template<typename LhsScalar,typename RhsScalar>
struct scalar_product_op  : binary_op_base<LhsScalar,RhsScalar>
{
  typedef typename ScalarBinaryOpTraits<LhsScalar,RhsScalar,scalar_product_op>::ReturnType result_type;
#ifndef EIGEN_SCALAR_BINARY_OP_PLUGIN
  EIGEN_EMPTY_STRUCT_CTOR(scalar_product_op)
#else
  scalar_product_op() {
    EIGEN_SCALAR_BINARY_OP_PLUGIN
  }
#endif
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const result_type operator() (const LhsScalar& a, const RhsScalar& b) const { return a * b; }
  template<typename Packet>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a, const Packet& b) const
  { return internal::pmul(a,b); }
  template<typename Packet>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const result_type predux(const Packet& a) const
  { return internal::predux_mul(a); }
};
template<typename LhsScalar,typename RhsScalar>
struct functor_traits<scalar_product_op<LhsScalar,RhsScalar> > {
  enum {
    Cost = (NumTraits<LhsScalar>::MulCost + NumTraits<RhsScalar>::MulCost)/2, // rough estimate!
    PacketAccess = is_same<LhsScalar,RhsScalar>::value && packet_traits<LhsScalar>::HasMul && packet_traits<RhsScalar>::HasMul
    // TODO vectorize mixed product
  };
};

/** \internal
  * \brief Template functor to compute the conjugate product of two scalars
  *
  * This is a short cut for conj(x) * y which is needed for optimization purpose; in Eigen2 support mode, this becomes x * conj(y)
  */
template<typename LhsScalar,typename RhsScalar>
struct scalar_conj_product_op  : binary_op_base<LhsScalar,RhsScalar>
{

  enum {
    Conj = NumTraits<LhsScalar>::IsComplex
  };

  typedef typename ScalarBinaryOpTraits<LhsScalar,RhsScalar,scalar_conj_product_op>::ReturnType result_type;

  EIGEN_EMPTY_STRUCT_CTOR(scalar_conj_product_op)
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const result_type operator() (const LhsScalar& a, const RhsScalar& b) const
  { return conj_helper<LhsScalar,RhsScalar,Conj,false>().pmul(a,b); }

  template<typename Packet>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a, const Packet& b) const
  { return conj_helper<Packet,Packet,Conj,false>().pmul(a,b); }
};
template<typename LhsScalar,typename RhsScalar>
struct functor_traits<scalar_conj_product_op<LhsScalar,RhsScalar> > {
  enum {
    Cost = NumTraits<LhsScalar>::MulCost,
    PacketAccess = internal::is_same<LhsScalar, RhsScalar>::value && packet_traits<LhsScalar>::HasMul
  };
};

/** \internal
  * \brief Template functor to compute the min of two scalars
  *
  * \sa class CwiseBinaryOp, MatrixBase::cwiseMin, class VectorwiseOp, MatrixBase::minCoeff()
  */
template<typename LhsScalar,typename RhsScalar>
struct scalar_min_op : binary_op_base<LhsScalar,RhsScalar>
{
  typedef typename ScalarBinaryOpTraits<LhsScalar,RhsScalar,scalar_min_op>::ReturnType result_type;
  EIGEN_EMPTY_STRUCT_CTOR(scalar_min_op)
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const result_type operator() (const LhsScalar& a, const RhsScalar& b) const { return numext::mini(a, b); }
  template<typename Packet>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a, const Packet& b) const
  { return internal::pmin(a,b); }
  template<typename Packet>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const result_type predux(const Packet& a) const
  { return internal::predux_min(a); }
};
template<typename LhsScalar,typename RhsScalar>
struct functor_traits<scalar_min_op<LhsScalar,RhsScalar> > {
  enum {
    Cost = (NumTraits<LhsScalar>::AddCost+NumTraits<RhsScalar>::AddCost)/2,
    PacketAccess = internal::is_same<LhsScalar, RhsScalar>::value && packet_traits<LhsScalar>::HasMin
  };
};

/** \internal
  * \brief Template functor to compute the max of two scalars
  *
  * \sa class CwiseBinaryOp, MatrixBase::cwiseMax, class VectorwiseOp, MatrixBase::maxCoeff()
  */
template<typename LhsScalar,typename RhsScalar>
struct scalar_max_op  : binary_op_base<LhsScalar,RhsScalar>
{
  typedef typename ScalarBinaryOpTraits<LhsScalar,RhsScalar,scalar_max_op>::ReturnType result_type;
  EIGEN_EMPTY_STRUCT_CTOR(scalar_max_op)
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const result_type operator() (const LhsScalar& a, const RhsScalar& b) const { return numext::maxi(a, b); }
  template<typename Packet>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a, const Packet& b) const
  { return internal::pmax(a,b); }
  template<typename Packet>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const result_type predux(const Packet& a) const
  { return internal::predux_max(a); }
};
template<typename LhsScalar,typename RhsScalar>
struct functor_traits<scalar_max_op<LhsScalar,RhsScalar> > {
  enum {
    Cost = (NumTraits<LhsScalar>::AddCost+NumTraits<RhsScalar>::AddCost)/2,
    PacketAccess = internal::is_same<LhsScalar, RhsScalar>::value && packet_traits<LhsScalar>::HasMax
  };
};

/** \internal
  * \brief Template functors for comparison of two scalars
  * \todo Implement packet-comparisons
  */
template<typename LhsScalar, typename RhsScalar, ComparisonName cmp> struct scalar_cmp_op;

template<typename LhsScalar, typename RhsScalar, ComparisonName cmp>
struct functor_traits<scalar_cmp_op<LhsScalar,RhsScalar, cmp> > {
  enum {
    Cost = (NumTraits<LhsScalar>::AddCost+NumTraits<RhsScalar>::AddCost)/2,
    PacketAccess = false
  };
};

template<ComparisonName Cmp, typename LhsScalar, typename RhsScalar>
struct result_of<scalar_cmp_op<LhsScalar, RhsScalar, Cmp>(LhsScalar,RhsScalar)> {
  typedef bool type;
};

template<typename LhsScalar, typename RhsScalar>
struct scalar_cmp_op<LhsScalar,RhsScalar, cmp_EQ> : binary_op_base<LhsScalar,RhsScalar>
{
  typedef bool result_type;
  EIGEN_EMPTY_STRUCT_CTOR(scalar_cmp_op)
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool operator()(const LhsScalar& a, const RhsScalar& b) const {return a==b;}
};
template<typename LhsScalar, typename RhsScalar>
struct scalar_cmp_op<LhsScalar,RhsScalar, cmp_LT> : binary_op_base<LhsScalar,RhsScalar>
{
  typedef bool result_type;
  EIGEN_EMPTY_STRUCT_CTOR(scalar_cmp_op)
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool operator()(const LhsScalar& a, const RhsScalar& b) const {return a<b;}
};
template<typename LhsScalar, typename RhsScalar>
struct scalar_cmp_op<LhsScalar,RhsScalar, cmp_LE> : binary_op_base<LhsScalar,RhsScalar>
{
  typedef bool result_type;
  EIGEN_EMPTY_STRUCT_CTOR(scalar_cmp_op)
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool operator()(const LhsScalar& a, const RhsScalar& b) const {return a<=b;}
};
template<typename LhsScalar, typename RhsScalar>
struct scalar_cmp_op<LhsScalar,RhsScalar, cmp_GT> : binary_op_base<LhsScalar,RhsScalar>
{
  typedef bool result_type;
  EIGEN_EMPTY_STRUCT_CTOR(scalar_cmp_op)
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool operator()(const LhsScalar& a, const RhsScalar& b) const {return a>b;}
};
template<typename LhsScalar, typename RhsScalar>
struct scalar_cmp_op<LhsScalar,RhsScalar, cmp_GE> : binary_op_base<LhsScalar,RhsScalar>
{
  typedef bool result_type;
  EIGEN_EMPTY_STRUCT_CTOR(scalar_cmp_op)
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool operator()(const LhsScalar& a, const RhsScalar& b) const {return a>=b;}
};
template<typename LhsScalar, typename RhsScalar>
struct scalar_cmp_op<LhsScalar,RhsScalar, cmp_UNORD> : binary_op_base<LhsScalar,RhsScalar>
{
  typedef bool result_type;
  EIGEN_EMPTY_STRUCT_CTOR(scalar_cmp_op)
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool operator()(const LhsScalar& a, const RhsScalar& b) const {return !(a<=b || b<=a);}
};
template<typename LhsScalar, typename RhsScalar>
struct scalar_cmp_op<LhsScalar,RhsScalar, cmp_NEQ> : binary_op_base<LhsScalar,RhsScalar>
{
  typedef bool result_type;
  EIGEN_EMPTY_STRUCT_CTOR(scalar_cmp_op)
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool operator()(const LhsScalar& a, const RhsScalar& b) const {return a!=b;}
};

/** \internal
  * \brief Template functor to compute the hypot of two scalars
  *
  * \sa MatrixBase::stableNorm(), class Redux
  */
template<typename Scalar>
struct scalar_hypot_op<Scalar,Scalar> : binary_op_base<Scalar,Scalar>
{
  EIGEN_EMPTY_STRUCT_CTOR(scalar_hypot_op)
//   typedef typename NumTraits<Scalar>::Real result_type;
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& _x, const Scalar& _y) const
  {
    using std::sqrt;
    Scalar p, qp;
    if(_x>_y)
    {
      p = _x;
      qp = _y / p;
    }
    else
    {
      p = _y;
      qp = _x / p;
    }
    return p * sqrt(Scalar(1) + qp*qp);
  }
};
template<typename Scalar>
struct functor_traits<scalar_hypot_op<Scalar,Scalar> > {
  enum
  {
    Cost = 3 * NumTraits<Scalar>::AddCost +
           2 * NumTraits<Scalar>::MulCost +
           2 * NumTraits<Scalar>::template Div<false>::Cost,
    PacketAccess = false
  };
};

/** \internal
  * \brief Template functor to compute the pow of two scalars
  */
template<typename Scalar, typename Exponent>
struct scalar_pow_op  : binary_op_base<Scalar,Exponent>
{
  typedef typename ScalarBinaryOpTraits<Scalar,Exponent,scalar_pow_op>::ReturnType result_type;
#ifndef EIGEN_SCALAR_BINARY_OP_PLUGIN
  EIGEN_EMPTY_STRUCT_CTOR(scalar_pow_op)
#else
  scalar_pow_op() {
    typedef Scalar LhsScalar;
    typedef Exponent RhsScalar;
    EIGEN_SCALAR_BINARY_OP_PLUGIN
  }
#endif
  EIGEN_DEVICE_FUNC
  inline result_type operator() (const Scalar& a, const Exponent& b) const { return numext::pow(a, b); }
};
template<typename Scalar, typename Exponent>
struct functor_traits<scalar_pow_op<Scalar,Exponent> > {
  enum { Cost = 5 * NumTraits<Scalar>::MulCost, PacketAccess = false };
};

//---------- non associative binary functors ----------

/** \internal
  * \brief Template functor to compute the difference of two scalars
  *
  * \sa class CwiseBinaryOp, MatrixBase::operator-
  */
template<typename LhsScalar,typename RhsScalar>
struct scalar_difference_op : binary_op_base<LhsScalar,RhsScalar>
{
  typedef typename ScalarBinaryOpTraits<LhsScalar,RhsScalar,scalar_difference_op>::ReturnType result_type;
#ifndef EIGEN_SCALAR_BINARY_OP_PLUGIN
  EIGEN_EMPTY_STRUCT_CTOR(scalar_difference_op)
#else
  scalar_difference_op() {
    EIGEN_SCALAR_BINARY_OP_PLUGIN
  }
#endif
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const result_type operator() (const LhsScalar& a, const RhsScalar& b) const { return a - b; }
  template<typename Packet>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a, const Packet& b) const
  { return internal::psub(a,b); }
};
template<typename LhsScalar,typename RhsScalar>
struct functor_traits<scalar_difference_op<LhsScalar,RhsScalar> > {
  enum {
    Cost = (NumTraits<LhsScalar>::AddCost+NumTraits<RhsScalar>::AddCost)/2,
    PacketAccess = is_same<LhsScalar,RhsScalar>::value && packet_traits<LhsScalar>::HasSub && packet_traits<RhsScalar>::HasSub
  };
};

/** \internal
  * \brief Template functor to compute the quotient of two scalars
  *
  * \sa class CwiseBinaryOp, Cwise::operator/()
  */
template<typename LhsScalar,typename RhsScalar>
struct scalar_quotient_op  : binary_op_base<LhsScalar,RhsScalar>
{
  typedef typename ScalarBinaryOpTraits<LhsScalar,RhsScalar,scalar_quotient_op>::ReturnType result_type;
#ifndef EIGEN_SCALAR_BINARY_OP_PLUGIN
  EIGEN_EMPTY_STRUCT_CTOR(scalar_quotient_op)
#else
  scalar_quotient_op() {
    EIGEN_SCALAR_BINARY_OP_PLUGIN
  }
#endif
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const result_type operator() (const LhsScalar& a, const RhsScalar& b) const { return a / b; }
  template<typename Packet>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a, const Packet& b) const
  { return internal::pdiv(a,b); }
};
template<typename LhsScalar,typename RhsScalar>
struct functor_traits<scalar_quotient_op<LhsScalar,RhsScalar> > {
  typedef typename scalar_quotient_op<LhsScalar,RhsScalar>::result_type result_type;
  enum {
    PacketAccess = is_same<LhsScalar,RhsScalar>::value && packet_traits<LhsScalar>::HasDiv && packet_traits<RhsScalar>::HasDiv,
    Cost = NumTraits<result_type>::template Div<PacketAccess>::Cost
  };
};

/** \internal
  * \brief Template functor to compute the and of two booleans
  *
  * \sa class CwiseBinaryOp, ArrayBase::operator&&
  */
struct scalar_boolean_and_op {
  EIGEN_EMPTY_STRUCT_CTOR(scalar_boolean_and_op)
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool operator() (const bool& a, const bool& b) const { return a && b; }
};
template<> struct functor_traits<scalar_boolean_and_op> {
  enum {
    Cost = NumTraits<bool>::AddCost,
    PacketAccess = false
  };
};

/** \internal
  * \brief Template functor to compute the or of two booleans
  *
  * \sa class CwiseBinaryOp, ArrayBase::operator||
  */
struct scalar_boolean_or_op {
  EIGEN_EMPTY_STRUCT_CTOR(scalar_boolean_or_op)
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool operator() (const bool& a, const bool& b) const { return a || b; }
};
template<> struct functor_traits<scalar_boolean_or_op> {
  enum {
    Cost = NumTraits<bool>::AddCost,
    PacketAccess = false
  };
};

/** \internal
 * \brief Template functor to compute the xor of two booleans
 *
 * \sa class CwiseBinaryOp, ArrayBase::operator^
 */
struct scalar_boolean_xor_op {
  EIGEN_EMPTY_STRUCT_CTOR(scalar_boolean_xor_op)
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool operator() (const bool& a, const bool& b) const { return a ^ b; }
};
template<> struct functor_traits<scalar_boolean_xor_op> {
  enum {
    Cost = NumTraits<bool>::AddCost,
    PacketAccess = false
  };
};

/** \internal
  * \brief Template functor to compute the incomplete gamma function igamma(a, x)
  *
  * \sa class CwiseBinaryOp, Cwise::igamma
  */
template<typename Scalar> struct scalar_igamma_op : binary_op_base<Scalar,Scalar>
{
  EIGEN_EMPTY_STRUCT_CTOR(scalar_igamma_op)
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& a, const Scalar& x) const {
    using numext::igamma; return igamma(a, x);
  }
  template<typename Packet>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a, const Packet& x) const {
    return internal::pigamma(a, x);
  }
};
template<typename Scalar>
struct functor_traits<scalar_igamma_op<Scalar> > {
  enum {
    // Guesstimate
    Cost = 20 * NumTraits<Scalar>::MulCost + 10 * NumTraits<Scalar>::AddCost,
    PacketAccess = packet_traits<Scalar>::HasIGamma
  };
};

/** \internal
  * \brief Template functor to compute the complementary incomplete gamma function igammac(a, x)
  *
  * \sa class CwiseBinaryOp, Cwise::igammac
  */
template<typename Scalar> struct scalar_igammac_op : binary_op_base<Scalar,Scalar>
{
  EIGEN_EMPTY_STRUCT_CTOR(scalar_igammac_op)
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& a, const Scalar& x) const {
    using numext::igammac; return igammac(a, x);
  }
  template<typename Packet>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a, const Packet& x) const
  {
    return internal::pigammac(a, x);
  }
};
template<typename Scalar>
struct functor_traits<scalar_igammac_op<Scalar> > {
  enum {
    // Guesstimate
    Cost = 20 * NumTraits<Scalar>::MulCost + 10 * NumTraits<Scalar>::AddCost,
    PacketAccess = packet_traits<Scalar>::HasIGammac
  };
};

//---------- binary functors bound to a constant, thus appearing as a unary functor ----------

// The following two classes permits to turn any binary functor into a unary one with one argument bound to a constant value.
// They are analogues to std::binder1st/binder2nd but with the following differences:
//  - they are compatible with packetOp
//  - they are portable across C++ versions (the std::binder* are deprecated in C++11)
template<typename BinaryOp> struct bind1st_op : BinaryOp {

  typedef typename BinaryOp::first_argument_type  first_argument_type;
  typedef typename BinaryOp::second_argument_type second_argument_type;
  typedef typename BinaryOp::result_type          result_type;

  bind1st_op(const first_argument_type &val) : m_value(val) {}

  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const result_type operator() (const second_argument_type& b) const { return BinaryOp::operator()(m_value,b); }

  template<typename Packet>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& b) const
  { return BinaryOp::packetOp(internal::pset1<Packet>(m_value), b); }

  first_argument_type m_value;
};
template<typename BinaryOp> struct functor_traits<bind1st_op<BinaryOp> > : functor_traits<BinaryOp> {};

template<typename BinaryOp> struct bind2nd_op : BinaryOp {

  typedef typename BinaryOp::first_argument_type  first_argument_type;
  typedef typename BinaryOp::second_argument_type second_argument_type;
  typedef typename BinaryOp::result_type          result_type;

  bind2nd_op(const second_argument_type &val) : m_value(val) {}

  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const result_type operator() (const first_argument_type& a) const { return BinaryOp::operator()(a,m_value); }

  template<typename Packet>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a) const
  { return BinaryOp::packetOp(a,internal::pset1<Packet>(m_value)); }

  second_argument_type m_value;
};
template<typename BinaryOp> struct functor_traits<bind2nd_op<BinaryOp> > : functor_traits<BinaryOp> {};

} // end namespace internal

} // end namespace Eigen

#endif // EIGEN_BINARY_FUNCTORS_H


text:
package tccrouter.ring.gui.animationstate;

import java.awt.Toolkit;

import javax.swing.ImageIcon;

import tccrouter.ring.gui.context.UIOperation;
import tccrouter.ring.gui.context.UIState;

/**
 *
 */
public class StepBackwardUIOperation extends UIOperation {

	/**
	 * @param state
	 * @param type
	 */
	public StepBackwardUIOperation(UIState state, boolean enabled) {
		super(state,UIOperation.ACTION_TYPE,enabled,true);
	}

	/**
	 * @see ring.gui.context.UIOperation#execute()
	 */
	public void execute() {
		AnimationUIState animationState = (AnimationUIState) state;

		animationState.stepBackward();

	}

	/**
	 * @see ring.gui.context.UIOperation#getName()
	 */
	public String getName() {
		return null;
	}

	/**
	 * @see ring.gui.context.UIOperation#getIcon()
	 */
	public ImageIcon getIcon() {
		return new ImageIcon(Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource("images/StepBack.gif")));
	}

}

redpajama_set_name: RedPajamaGithub


text:
package com.androidbase.binding.properties;

import com.androidbase.binding.enums.Bindings;
import com.androidbase.interfaces.ICopiable;
import com.androidbase.log.Log;

public class ObjectProperty extends PropertyBinding<Object> {

	// region Properties

	protected String tag = "ObjectProperty";

	// endregion

	// region Constructors

	public ObjectProperty(Object object, String propertyName) {
		super(object, propertyName);
	}

	public ObjectProperty(Object object, String propertyName, Bindings binding) {
		super(object, propertyName, binding);
	}

	// endregion

	// region Overrides

	@Override
	public void setValue(Object value) {

		try {
			Object fieldObject = getValue();

			if (fieldObject instanceof ICopiable) {
				((ICopiable) fieldObject).copy(value);
			} else {

				super.setValue(value);
			}

		} catch (Exception ex) {
			Log.e(tag, ex);
		}
	}

	@Override
	public void setValueWithouthRaise(Object value) {
		try {
			Object fieldObject = getValue();

			if (fieldObject instanceof ICopiable) {
				((ICopiable) fieldObject).copy(value);
			} else {

				super.setValueWithouthRaise(value);
			}

		} catch (Exception ex) {
			Log.e(tag, ex);
		}
	}

	// endregion

}


text:
//
//  NBMRequest.h
//  Copyright (c) 2016 Telecom Italia S.p.A. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import <Foundation/Foundation.h>
#import "NBMMessage.h"

/**
 *  Represents a JSON-RPC 2.0 request.
 */
@interface NBMRequest : NSObject  <NBMMessage>

/**
 *  The request identifier which is echoed back to the client with the response.
 */
@property (nonatomic, readonly) NSNumber *requestId;
/**
 *  The name of the requested method.
 */
@property (nonatomic, copy, readonly) NSString *method;
/**
 *  The parameters encoded into the request, these are an `NSDictionary` or `NSArray.
 */
@property (nonatomic, readonly) id parameters;

/**
 *  Creates and initializes a JSON-RPC 2.0 request with the specified method
 *
 *  @param method The name of the requested method. Must not be `nil`.
 *
 *  @return An initialized JSON-RPC request.
 */
+ (instancetype)requestWithMethod:(NSString *)method;

/**
 *  Creates and initializes a JSON-RPC 2.0 request with the specified method and parameters (named or positional).
 *
 *  @param method     The name of the requested method. Must not be `nil`.
 *  @param parameters The parameters to encode into the request. Must be either an `NSDictionary` or `NSArray`.
 *
 *  @return An initialized JSON-RPC request.
 */
+ (instancetype)requestWithMethod:(NSString *)method
                       parameters:(id)parameters;

@end


text:
import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import { join, sep, normalize } from 'path';
import * as slash from 'slash';

import Config from '../../config';
import { TemplateLocalsBuilder } from '../../utils';

const plugins = <any>gulpLoadPlugins();

/**
 * Executes the build process, injecting the JavaScript and CSS dependencies into the `index.html` for the production
 * environment.
 */
export = () => {
  return gulp
    .src(join(Config.APP_SRC, 'index.html'))
    .pipe(injectJs())
    .pipe(injectCss())
    .pipe(
      plugins.template(
        new TemplateLocalsBuilder().withoutStringifiedEnvConfig().build(),
        Config.TEMPLATE_CONFIG
      )
    )
    .pipe(gulp.dest(Config.APP_DEST));
};

/**
 * Injects the given file array and transforms the path of the files.
 * @param {Array<string>} files - The files to be injected.
 */
function inject(...files: Array<string>) {
  return plugins.inject(gulp.src(files, { read: false }), {
    files,
    transform: transformPath()
  });
}

/**
 * Injects the bundled JavaScript shims and application bundles for the production environment.
 */
function injectJs() {
  return inject(
    join(Config.JS_DEST, Config.JS_PROD_SHIMS_BUNDLE),
    join(Config.JS_DEST, Config.JS_PROD_APP_BUNDLE)
  );
}

/**
 * Injects the bundled CSS files for the production environment.
 */
function injectCss() {
  return inject(join(Config.CSS_DEST, `${Config.CSS_BUNDLE_NAME}.css`));
}

/**
 * Transform the path of a dependency to its location within the `dist` directory according to the applications
 * environment.
 */
function transformPath() {
  return function(filepath: string) {
    let path: Array<string> = normalize(filepath).split(sep);
    let slice_after = path.indexOf(Config.APP_DEST);
    if (slice_after > -1) {
      slice_after++;
    } else {
      slice_after = 3;
    }
    arguments[0] =
      Config.APP_BASE + path.slice(slice_after, path.length).join(sep);
    const queryString = Config.QUERY_STRING_GENERATOR();
    if (queryString) {
      arguments[0] += `?${queryString}`;
    }
    return slash(
      plugins.inject.transform.apply(plugins.inject.transform, arguments)
    );
  };
}


text:
	#error "include 'stdafx.h' before including this file for PCH"
#endif

#include "resource.h"		// main symbols

namespace FileSearch {

// CFileSearchApp:
// See FileSearch.cpp for the implementation of this class
//

class CFileSearchApp : public CWinApp {
public:
    CFileSearchApp();

    // Overrides
public:
    virtual BOOL InitInstance();

    // Implementation

    DECLARE_MESSAGE_MAP()
};

extern CFileSearchApp theApp;
}


text:
<?php
/* This function is called on login. It redirects the User to the question he was answering last */
require_once("models/config.php");
  global $loggedInUser,$db,$db_table_prefix;
          $query="SELECT score FROM `".$db_table_prefix."Users` WHERE User_ID = '".$db->sql_escape($loggedInUser->user_id)."'";
          $result=mysql_query($query) or die(mysql_error);
          $row_a = mysql_fetch_array($result);
          extract($row_a);
                                                switch($score){
                                                       case "0":header('location:level1.php'); break;
                                                       case "1":header('location:level2.php'); break;
                                                       case "2":header('location:level3.php'); break;
                                                       case "3":header('location:level4.php'); break;
                                                       case "4":header('location:level5.php'); break;
                                                       default:header('location:login.php');break;
                                                       }
						die();
?>


text:
#include "rxsrvice.h"
#pragma pack (push, 8)

class AcRxClass;
class AcRxDictionary;

class AcRxKernel : public AcRxService
{
public:
    ACRX_DECLARE_MEMBERS(AcRxKernel);
    AcRxKernel();
    virtual ~AcRxKernel();

    virtual
    AcRxDictionary* newAcRxDictionary(Adesk::Boolean sorted = Adesk::kTrue,
                                      Adesk::Boolean ignoreCase
                                                           = Adesk::kFalse) = 0;

    virtual
    AcRxDictionary* newAcRxDictionary(unsigned long length,
                                      Adesk::Boolean delObjects,
                                      Adesk::Boolean sorted = Adesk::kTrue,
                                      Adesk::Boolean ignoreCase
                                                           = Adesk::kFalse) = 0;

    virtual
    AcRxDictionary* newAcRxDictionary(const AcRxClass * filter) = 0;
};

#define acrxKernel \
    AcRxKernel::cast(AcRxDictionary::cast(\
    acrxSysRegistry()->at(ACRX_SERVICE_DICTIONARY))->at(ACRX_KERNEL_SERVICES))

#pragma pack (pop)
#endif


text:
using System.Diagnostics;

namespace NanoByte.Common.Native;

/// <summary>
/// Extension methods for <see cref="IProcessLauncher"/>.
/// </summary>
public static class ProcessLauncherExtensions
{
    /// <summary>
    /// Runs the sub process, captures its stdout and stderr output and waits for it to exit.
    /// </summary>
    /// <param name="processLauncher">The sub process.</param>
    /// <param name="arguments">Command-line arguments to launch the process with.</param>
    /// <returns>The process' complete stdout output.</returns>
    /// <exception cref="IOException">There was a problem launching the executable.</exception>
    /// <exception cref="FileNotFoundException">The executable file could not be found.</exception>
    /// <exception cref="NotAdminException">The target process requires elevation.</exception>
    /// <exception cref="ExitCodeException">The process exited with a non-zero <see cref="Process.ExitCode"/>.</exception>
    public static string RunAndCapture(this IProcessLauncher processLauncher, params string[] arguments)
        => processLauncher.RunAndCapture(null, arguments);

    /// <summary>
    /// Runs the sub process, captures its stdout and stderr output and waits for it to exit.
    /// </summary>
    /// <param name="processLauncher">The sub process.</param>
    /// <param name="stdinData">Data to the process' stdin right after startup.</param>
    /// <param name="arguments">Command-line arguments to launch the process with.</param>
    /// <returns>The process' complete stdout output.</returns>
    /// <exception cref="IOException">There was a problem launching the executable.</exception>
    /// <exception cref="FileNotFoundException">The executable file could not be found.</exception>
    /// <exception cref="NotAdminException">The target process requires elevation.</exception>
    /// <exception cref="ExitCodeException">The process exited with a non-zero <see cref="Process.ExitCode"/>.</exception>
    public static string RunAndCapture(this IProcessLauncher processLauncher, ArraySegment<byte> stdinData, params string[] arguments)
        => processLauncher.RunAndCapture(writer =>
        {
            writer.BaseStream.Write(stdinData.Array!, stdinData.Offset, stdinData.Count);
            writer.BaseStream.Flush();
        }, arguments);
}


text:
(function() {var implementors = {};
implementors["interval_set"] = ["impl Ord for Interval",];

            if (window.register_implementors) {
                window.register_implementors(implementors);
            } else {
                window.pending_implementors = implementors;
            }

})()


text:
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var passport = require('passport');
var jwt = require('express-jwt');
var nodemailer = require('nodemailer');

/*import mongoose model*/
var User = mongoose.model('User');
var auth = jwt({secret: 'SECRET', userProperty: 'payload'});

/* GET home page. */
router.get('/',function(req, res, next) {
  res.render('index');
});

router.param('user', function(req, res, next, id) {
  var query = User.findById(id);
  query.exec(function (err, chat){
    if (err) { return next(err); }
    if (!user) { return next(new Error("can't find user")); }

    req.user = user;
    return next();

  });
});

router.get('/register/:id',function(req,res,next){
  User.findByIdAndUpdate(req.params.id, {isValid : true},function(err){
     if(err){ return next(err); }

   });
});

router.post('/register', function(req, res, next){
  if(!req.body.username || !req.body.password || !req.body.nickname || !req.body.name){
    return res.status(400).json({message: 'Please fill out all fields'});
  }

  var user = new User();

  user.username = req.body.username;
  user.nickname = req.body.nickname;
  user.name = req.body.name;
  user.setPassword(req.body.password)

  var transport = nodemailer.createTransport('SMTP', {
    survice : "gmail",
    auth:{
      user : "bcsdtest2016@gmail.com",
      pass : "as123654"
    }
  });

  var msg = {
    text : "click the link for BCSD verification \n"+"http://localhost:3000/#/register/"+user._id,
    from : "BCSDLab@bcsdlab.com",
    subject : "BCSD email verification",
    to : user.username+"@koreatech.ac.kr"
  };

  transport.sendMail(msg, function(err){
    if(err){
      console.log('Sending to' + msg.to + 'failed' +err);
    }

    console.log('Sent to'+msg.to);
    msg.transport.close();
  });

  user.save(function (err){
    if(err){ return next(err); }
    res.render('index');
  });
});

router.post('/login', function(req, res, next){
  if(!req.body.username || !req.body.password){
    return res.status(400).json({message: 'Please fill out all fields'});
  }

  var idValid;

  function getValid(callback){
    User.findOne({username : req.body.username},'isValid',function(err, user){
      idValid =  user.isValid;
      callback();
     });

   }
  getValid(function(){
     console.log(idValid);
      if(!idValid){
        return res.status(400).json({message : 'Please check the email'});
      }
      console.log('calling passport');
      passport.authenticate('local', function(err, user, info){
        if(err){ return next(err); }
          if(user){
            return res.json({token: user.generateJWT()});
          } else {
            return res.status(401).json(info);
          }
        })(req, res, next);
    });

});

router.get('/users', function(req, res, next) {
  User.find(function(err, users) {
    if(err) return next(err);
    return res.json(users);
  });
});

module.exports = router;


text:
package org.apache.spark.sql.execution.datasources.orc

import java.util.Locale

import scala.collection.JavaConverters._

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FileStatus, Path}
import org.apache.orc.{OrcFile, Reader, TypeDescription}

import org.apache.spark.SparkException
import org.apache.spark.deploy.SparkHadoopUtil
import org.apache.spark.internal.Logging
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.catalyst.analysis.caseSensitiveResolution
import org.apache.spark.sql.catalyst.parser.CatalystSqlParser
import org.apache.spark.sql.types._

object OrcUtils extends Logging {

  // The extensions for ORC compression codecs
  val extensionsForCompressionCodecNames = Map(
    "NONE" -> "",
    "SNAPPY" -> ".snappy",
    "ZLIB" -> ".zlib",
    "LZO" -> ".lzo")

  def listOrcFiles(pathStr: String, conf: Configuration): Seq[Path] = {
    val origPath = new Path(pathStr)
    val fs = origPath.getFileSystem(conf)
    val paths = SparkHadoopUtil.get.listLeafStatuses(fs, origPath)
      .filterNot(_.isDirectory)
      .map(_.getPath)
      .filterNot(_.getName.startsWith("_"))
      .filterNot(_.getName.startsWith("."))
    paths
  }

  def readSchema(file: Path, conf: Configuration, ignoreCorruptFiles: Boolean)
      : Option[TypeDescription] = {
    val fs = file.getFileSystem(conf)
    val readerOptions = OrcFile.readerOptions(conf).filesystem(fs)
    try {
      val reader = OrcFile.createReader(file, readerOptions)
      val schema = reader.getSchema
      if (schema.getFieldNames.size == 0) {
        None
      } else {
        Some(schema)
      }
    } catch {
      case e: org.apache.orc.FileFormatException =>
        if (ignoreCorruptFiles) {
          logWarning(s"Skipped the footer in the corrupted file: $file", e)
          None
        } else {
          throw new SparkException(s"Could not read footer for file: $file", e)
        }
    }
  }

  def readSchema(sparkSession: SparkSession, files: Seq[FileStatus])
      : Option[StructType] = {
    val ignoreCorruptFiles = sparkSession.sessionState.conf.ignoreCorruptFiles
    val conf = sparkSession.sessionState.newHadoopConf()
    // TODO: We need to support merge schema. Please see SPARK-11412.
    files.toIterator.map(file => readSchema(file.getPath, conf, ignoreCorruptFiles)).collectFirst {
      case Some(schema) =>
        logDebug(s"Reading schema from file $files, got Hive schema string: $schema")
        CatalystSqlParser.parseDataType(schema.toString).asInstanceOf[StructType]
    }
  }

  /**
   * Returns the requested column ids from the given ORC file. Column id can be -1, which means the
   * requested column doesn't exist in the ORC file. Returns None if the given ORC file is empty.
   */
  def requestedColumnIds(
      isCaseSensitive: Boolean,
      dataSchema: StructType,
      requiredSchema: StructType,
      reader: Reader,
      conf: Configuration): Option[Array[Int]] = {
    val orcFieldNames = reader.getSchema.getFieldNames.asScala
    if (orcFieldNames.isEmpty) {
      // SPARK-8501: Some old empty ORC files always have an empty schema stored in their footer.
      None
    } else {
      if (orcFieldNames.forall(_.startsWith("_col"))) {
        // This is a ORC file written by Hive, no field names in the physical schema, assume the
        // physical schema maps to the data scheme by index.
        assert(orcFieldNames.length <= dataSchema.length, "The given data schema " +
          s"${dataSchema.catalogString} has less fields than the actual ORC physical schema, " +
          "no idea which columns were dropped, fail to read.")
        Some(requiredSchema.fieldNames.map { name =>
          val index = dataSchema.fieldIndex(name)
          if (index < orcFieldNames.length) {
            index
          } else {
            -1
          }
        })
      } else {
        if (isCaseSensitive) {
          Some(requiredSchema.fieldNames.map { name =>
            orcFieldNames.indexWhere(caseSensitiveResolution(_, name))
          })
        } else {
          // Do case-insensitive resolution only if in case-insensitive mode
          val caseInsensitiveOrcFieldMap =
            orcFieldNames.zipWithIndex.groupBy(_._1.toLowerCase(Locale.ROOT))
          Some(requiredSchema.fieldNames.map { requiredFieldName =>
            caseInsensitiveOrcFieldMap
              .get(requiredFieldName.toLowerCase(Locale.ROOT))
              .map { matchedOrcFields =>
                if (matchedOrcFields.size > 1) {
                  // Need to fail if there is ambiguity, i.e. more than one field is matched.
                  val matchedOrcFieldsString = matchedOrcFields.map(_._1).mkString("[", ", ", "]")
                  throw new RuntimeException(s"""Found duplicate field(s) "$requiredFieldName": """
                    + s"$matchedOrcFieldsString in case-insensitive mode")
                } else {
                  matchedOrcFields.head._2
                }
              }.getOrElse(-1)
          })
        }
      }
    }
  }
}


text:
package com.arnaugarcia.realstatecamp.web.rest;

import com.arnaugarcia.realstatecamp.service.MailService;
import com.arnaugarcia.realstatecamp.web.rest.util.HeaderUtil;
import com.codahale.metrics.annotation.Timed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.inject.Inject;
import java.net.URISyntaxException;

/**
 * REST controller for managing Contact.
 */
@RestController
@RequestMapping("/api")
public class ContactResource {

    private final Logger log = LoggerFactory.getLogger(ContactResource.class);

    @Inject
    private MailService mailService;

    /**
     * POST  /contacts : Create a new contact.
     *
     * @return the ResponseEntity with status 201 (Created) and with body the new contact, or with status 400 (Bad Request) if the contact has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/contact")
    @Timed
    public ResponseEntity<Void> createContact(@RequestParam("to") String to, @RequestParam("subject") String subject, @RequestParam("content") String content) throws URISyntaxException {

        try {
            mailService.sendEmail(to,subject,content,false,false);
            return new ResponseEntity<>(HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("contact", "errorEnvioMail", e.getMessage())).body(null);
        }

    }

}


text:
'use strict';

var assert = require('assert');
var should = require('should');
var Template = require('..');
var template = new Template();

describe('template process', function () {
  beforeEach(function() {
    template.clear();
    template.omit('abcdefghijklmnopqrstuvwxyz'.split(''));
  });

  describe('.process()', function () {
    it('should resolve template strings in config values', function () {
      var store = template.process({a: '<%= b %>', b: 'c'});
      store.a.should.equal('c')
    });

    it('should process the cache when no arguments are passed', function () {
      template.data({a: '${b}', b: '${c}', c: 'DONE'});
      template.get('data.a').should.equal('${b}');

      template.get('data.b').should.equal('${c}');
      template.get('data.c').should.equal('DONE');

      template.process();

      template.get('data.a').should.equal('DONE');
      template.get('data.b').should.equal('DONE');
      template.get('data.c').should.equal('DONE');
    });

    it('should resolve es6 template strings in config values', function () {
      var store = template.process({a: '${b}', b: 'c'});
      store.a.should.equal('c');
    });

    it('should recursively resolve template strings.', function () {
      var store = template.process({
        a: '${b}',
        b: '${c}',
        c: '${d}',
        d: '${e.f.g}',
        e: {f:{g:'h'}}});
      store.a.should.equal('h');
    });

    describe('when functions are defined on the config', function() {
      it('should used them on config templates', function() {
        template.set({
          upper: function (str) {
            return str.toUpperCase();
          }
        });

        template.set({fez: 'bang', pop: 'boom-pow!'});
        template.set({whistle: '<%= upper(fez) %>-<%= upper(pop) %>'});
        template.get('whistle').should.equal('<%= upper(fez) %>-<%= upper(pop) %>');

        var a = template.process(template.get('whistle'), template.get());
        a.should.equal('BANG-BOOM-POW!');

        var b = template.process(template.get(), template.get());
        b.whistle.should.equal('BANG-BOOM-POW!');
      });
    });
  });
});


text:
require 'image_optim/worker'

class ImageOptim
  class Worker
    # https://github.com/svg/svgo
    class Svgo < Worker
      def optimize(src, dst)
        args = %W[
          --input #{src}
          --output #{dst}
        ]
        execute(:svgo, *args) && optimized?(src, dst)
      end
    end
  end
end


text:
name             'cmd-executor'
maintainer       'YOUR_COMPANY_NAME'
maintainer_email 'YOUR_EMAIL'
license          'All rights reserved'
description      'Installs/Configures cmd-executor'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '0.1.0'


text:
using UnityEngine;
using UnityPureMVC.Patterns;

namespace lizzard.Examples02
{
    public class PlayerProxy : Proxy
    {
        private GameObject _playerPrefab;

        private GameObject _player;

        public PlayerProxy(string proxyName, object data = null) : base(proxyName, data)
        {
            LoadPlayerPrefab("Player02");
        }

        private void LoadPlayerPrefab(string name)
        {
            _playerPrefab = Resources.Load<GameObject>(name);
        }

        public GameObject GetPlayerPrefab()
        {
            return _playerPrefab;
        }

        public void AddPlayer(GameObject player)
        {
            _player = player;
        }

        public GameObject GetPlayer()
        {
            return _player;
        }
    }
}


text:
<?xml version="1.0" ?>
<INPUT>

	<MEDALS>
		<MEDAL Id="1" MEDAL_THRESHOLD="52000" TYPE="Gold"/>
		<MEDAL Id="2" MEDAL_THRESHOLD="79000" TYPE="Silver"/>
		<MEDAL Id="3" MEDAL_THRESHOLD="102000" TYPE="Bronze"/>

	</MEDALS>

	<SpeedSettings Default="18" Max="150" Min="0"/>

	<PenaltySettings SpeedLost="0.1" TimeLost="15"/>

	<PROBLEM_SET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="Fraction">
				<ContentSettings denominator="4" numerator="2" whole="1"/>
			</TARGET>
			<QUESTION INDEX="1">
				<Content TYPE="String">
					<ContentSettings string="0.5"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
			<QUESTION INDEX="2">
				<Content TYPE="String">
					<ContentSettings string="1"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1.75"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="3">
				<Content TYPE="String">
					<ContentSettings string="2"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="2.25"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="Fraction">
				<ContentSettings denominator="10" numerator="7"/>
			</TARGET>
			<QUESTION INDEX="4">
				<Content TYPE="String">
					<ContentSettings string="0.3"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.8"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="5">
				<Content TYPE="String">
					<ContentSettings string="0.8"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1.1"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="6">
				<Content TYPE="String">
					<ContentSettings string="0.8"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="Fraction">
				<ContentSettings denominator="10" numerator="2"/>
			</TARGET>
			<QUESTION INDEX="7">
				<Content TYPE="String">
					<ContentSettings string="0"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.1"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
			<QUESTION INDEX="8">
				<Content TYPE="String">
					<ContentSettings string="0.8"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="9">
				<Content TYPE="String">
					<ContentSettings string="0.1"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.6"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="Fraction">
				<ContentSettings denominator="100" numerator="15" whole="1"/>
			</TARGET>
			<QUESTION INDEX="10">
				<Content TYPE="String">
					<ContentSettings string="0.97"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1.99"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="11">
				<Content TYPE="String">
					<ContentSettings string="0.91"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1.56"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="12">
				<Content TYPE="String">
					<ContentSettings string="1.95"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1.98"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="Fraction">
				<ContentSettings denominator="12" numerator="10"/>
			</TARGET>
			<QUESTION INDEX="13">
				<Content TYPE="String">
					<ContentSettings string="0.916"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1.083"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="14">
				<Content TYPE="String">
					<ContentSettings string="1"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1.083"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="15">
				<Content TYPE="String">
					<ContentSettings string="0.166"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.5"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="Fraction">
				<ContentSettings denominator="100" numerator="73"/>
			</TARGET>
			<QUESTION INDEX="16">
				<Content TYPE="String">
					<ContentSettings string="0.09"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.8"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="17">
				<Content TYPE="String">
					<ContentSettings string="0"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.46"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
			<QUESTION INDEX="18">
				<Content TYPE="String">
					<ContentSettings string="0.02"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.78"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
		</PROBLEM_SUBSET>

	</PROBLEM_SET>

</INPUT>


text:
package org.springframework.context.event;

import junit.framework.TestCase;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.Lifecycle;
import org.springframework.context.support.StaticApplicationContext;

/**
 * @author Mark Fisher
 * @author Juergen Hoeller
 */
public class LifecycleEventTests extends TestCase {

	public void testContextStartedEvent() {
		StaticApplicationContext context = new StaticApplicationContext();
		context.registerSingleton("lifecycle", LifecycleTestBean.class);
		context.registerSingleton("listener", LifecycleListener.class);
		context.refresh();
		LifecycleTestBean lifecycleBean = (LifecycleTestBean) context.getBean("lifecycle");
		LifecycleListener listener = (LifecycleListener) context.getBean("listener");
		assertFalse(lifecycleBean.isRunning());
		assertEquals(0, listener.getStartedCount());
		context.start();
		assertTrue(lifecycleBean.isRunning());
		assertEquals(1, listener.getStartedCount());
		assertSame(context, listener.getApplicationContext());
	}

	public void testContextStoppedEvent() {
		StaticApplicationContext context = new StaticApplicationContext();
		context.registerSingleton("lifecycle", LifecycleTestBean.class);
		context.registerSingleton("listener", LifecycleListener.class);
		context.refresh();
		LifecycleTestBean lifecycleBean = (LifecycleTestBean) context.getBean("lifecycle");
		LifecycleListener listener = (LifecycleListener) context.getBean("listener");
		assertFalse(lifecycleBean.isRunning());
		context.start();
		assertTrue(lifecycleBean.isRunning());
		assertEquals(0, listener.getStoppedCount());
		context.stop();
		assertFalse(lifecycleBean.isRunning());
		assertEquals(1, listener.getStoppedCount());
		assertSame(context, listener.getApplicationContext());
	}

	private static class LifecycleListener implements ApplicationListener<ApplicationEvent> {

		private ApplicationContext context;

		private int startedCount;

		private int stoppedCount;

		@Override
		public void onApplicationEvent(ApplicationEvent event) {
			if (event instanceof ContextStartedEvent) {
				this.context = ((ContextStartedEvent) event).getApplicationContext();
				this.startedCount++;
			}
			else if (event instanceof ContextStoppedEvent) {
				this.context = ((ContextStoppedEvent) event).getApplicationContext();
				this.stoppedCount++;
			}
		}

		public ApplicationContext getApplicationContext() {
			return this.context;
		}

		public int getStartedCount() {
			return this.startedCount;
		}

		public int getStoppedCount() {
			return this.stoppedCount;
		}
	}

	private static class LifecycleTestBean implements Lifecycle {

		private boolean running;

		@Override
		public boolean isRunning() {
			return this.running;
		}

		@Override
		public void start() {
			this.running = true;
		}

		@Override
		public void stop() {
			this.running = false;
		}
	}

}


text:
package main.java.engine.util.leapmotion.keybinderutils;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.*;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import main.java.engine.util.leapmotion.gamecontroller.LeapGameController;

/**
 *
 * Credited to Dennis and Sam's keybinder utility.
 *
 */
@SuppressWarnings("serial")
public class KeybindUtility extends JPanel {
	private static final String WAIT_STATUS = "    Click Set to Bind, Click Clear to Delete Binding   ";
	private static final String CHANGE_STATUS = "    Press the Key or Double Click to Bind an Action    ";
	private static final String BOUND_STATUS = "   Key Already Bound.  Please Press Another Key  ";

	private JLabel statusLabel = new JLabel(WAIT_STATUS);
	private List<String> commandList;
	private TabManager parentFrame;
	private String gameObject;

	//protected Map<Integer, String> keyBindings = new HashMap<Integer, String>();

	/**
	 * A utility class to easily swap meaningful key inputs for the editor as
	 * well as for the game being created.
	 */
	public KeybindUtility(String object, List<String> commands, TabManager manager) {
		gameObject = object;
		commandList = commands;
		parentFrame = manager;
		initialize();
	}

	/**
	 * Creates the GUI for the Keybind Utility to let the user easily map the
	 * keyboard inputs
	 */
	private void initialize() {
		JComponent shell = new JPanel();
		shell.setLayout(new BoxLayout(shell, BoxLayout.Y_AXIS));
		createBindingPanels(shell);
		add(shell);
		setVisible(true);
	}

	/**
	 * Generates a constantly present key listener that will update a KeyEvent
	 * buffer variable with the most recently released key.
	 */
	private void generateButtonListener(final JLabel label,
			final String command, final JButton button) {
		button.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {
				// Do nothing - must be present for interface
			}

			public void keyReleased(KeyEvent e) {
				boolean alreadyBound = false;

				for (String event : parentFrame.keyBindings.keySet()) {
					if (event.equals(e.getKeyCode())) {
						alreadyBound = true;
					}
				}
				if (alreadyBound) {
					statusLabel.setText(BOUND_STATUS);
				} else {
					parentFrame.keyBindings.put(command, e.getKeyCode());
					label.setText(KeyEvent.getKeyText(e.getKeyCode())
							+ "        ");
					statusLabel.setText(WAIT_STATUS);
					alreadyBound = false;
				}
			}

			public void keyTyped(KeyEvent e) {
				// Do nothing - must be present for interface
			}
		});

		button.addMouseListener( new MouseListener() {

                    @Override
                    public void mouseReleased (MouseEvent e) {
                    }

                    @Override
                    public void mousePressed (MouseEvent e) {
                    }

                    @Override
                    public void mouseExited (MouseEvent e) {
                    }

                    @Override
                    public void mouseEntered (MouseEvent e) {
                    }

                    @Override
                    public void mouseClicked (MouseEvent e) {
                        if(e.getClickCount() < 2) {
                            //disallow single click to register mouse binding
                            return;
                        }
                        if (SwingUtilities.isLeftMouseButton(e)){
                            parentFrame.keyBindings.put(command, KeyEvent.BUTTON1_DOWN_MASK);
                            label.setText(LeapGameController.LEFT_CLICK);
                        } else {
                            parentFrame.keyBindings.put(command, KeyEvent.BUTTON2_DOWN_MASK);
                            label.setText(LeapGameController.RIGHT_CLICK);
                        }
                        statusLabel.setText(WAIT_STATUS);
                    }
                });

	}

	/**
	 * Generates the GUI panels for the key-binding interface. This GUI is
	 * composed of individual panels that all hold the labels for the associated
	 * command, keybinding, and set and clear buttons to set a new binding or
	 * clear an existing one.
	 *
	 * @param framePanel
	 *            The panel that will hold all of the individual component
	 *            panels
	 */
	private void createBindingPanels(final JComponent framePanel) {
		for (final String command : commandList) {
			JPanel componentPanel = new JPanel();
			componentPanel.setLayout(new BoxLayout(componentPanel,
					BoxLayout.X_AXIS));
			JLabel commandLabel = new JLabel(command + "    ");
			JLabel binding = new JLabel("<>      ");
			JButton setButton = new JButton("Set");
			createSetListener(setButton, binding, command);
			JButton clearButton = new JButton("Clear");
			createClearListener(clearButton, binding, command);
			componentPanel.add(commandLabel);
			componentPanel.add(binding);
			componentPanel.add(setButton);
			componentPanel.add(clearButton);
			framePanel.add(componentPanel);
		}
		statusLabel.setAlignmentX(CENTER_ALIGNMENT);
		framePanel.add(statusLabel);

	}

	/**
	 * Creates a listener for a particular panel's CLEAR button
	 *
	 * @param clearButton
	 * @param binding
	 *            The label that describes the bound key event
	 * @param command
	 *            The label that describes the method the panel controls
	 */
	private void createClearListener(JButton clearButton, final JLabel binding,
			final String command) {
		clearButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				String keyToRemove = "";
				binding.setText("<>      ");
				for(String key : parentFrame.keyBindings.keySet()) {
					if(key.startsWith(command)) {
						keyToRemove = key;
					}
				}
				if(!keyToRemove.equals("")) {
					parentFrame.keyBindings.remove(keyToRemove);
				}
				statusLabel.setText(WAIT_STATUS);
			}

		});

	}

	/**
	 * Creates a listener for a particular panel's CLEAR button
	 *
	 * @param setButton
	 * @param binding
	 *            The label that describes the bound key event
	 * @param command
	 *            The label that describes the method the panel controls
	 */
	private void createSetListener(final JButton setButton,
			final JLabel binding, final String command) {
		generateButtonListener(binding, command, setButton);
		setButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				statusLabel.setText(CHANGE_STATUS);
			}

		});
	}
}


text:
set -e

WORKSPACE=$(git rev-parse --show-toplevel)
BASENAME=$(basename "$WORKSPACE")
WEBREPO="git@github.com:eclipse-iceoryx/iceoryx-web.git"
TYPE=${1:-local} #`local` starts a local webserver to inspect the results, `publish` pushes the generated doc to iceoryx_web
VERSION=$2
BRANCH=$3

if [ "$BASENAME" != "iceoryx" ]; then
    echo "Git folder must be named iceoryx!"
    exit 1
fi

cd "$WORKSPACE"

git checkout "$BRANCH"

# Generate doxygen
cmake -Bbuild -Hiceoryx_meta -DBUILD_DOC=ON
cd "$WORKSPACE"/build
make -j8 doxygen_iceoryx_posh doxygen_iceoryx_hoofs doxygen_iceoryx_binding_c doxygen_iceoryx_introspection

cd "$WORKSPACE"

PACKAGES="hoofs posh c-binding introspection"

# Generate doxybook2 config files, to have correct links in doxygen docu
mkdir -p "$WORKSPACE"/tools/website/generated/

for PACKAGE in ${PACKAGES}  ; do
    FILE=$WORKSPACE/tools/website/generated/doxybook2-$PACKAGE.json
    rm -f "$FILE"
    echo "{" >> "$FILE"
    if [ "$TYPE" == "local" ]; then
        echo "\"baseUrl\": \"/API-reference/$PACKAGE/\","  >> "$FILE"
    else
        echo "\"baseUrl\": \"/$VERSION/API-reference/$PACKAGE/\","  >> "$FILE"
    fi
    echo "\"indexInFolders\": false,"  >> "$FILE"
    echo "\"linkSuffix\": \"/\","  >> "$FILE"
    echo "\"mainPageInRoot\": false"  >> "$FILE"
    echo "}"  >> "$FILE"
done

BUILD_FOLDER="$WORKSPACE"/build/doc
DOC_FOLDER="$WORKSPACE"/doc/website/API-reference
CONFIG_FOLDER="$WORKSPACE"/tools/website/generated/

# Generate markdown from doxygen
mkdir -p "$DOC_FOLDER"/hoofs
doxybook2 --input $BUILD_FOLDER/iceoryx_hoofs/xml/ --output $DOC_FOLDER/hoofs --config $CONFIG_FOLDER/doxybook2-hoofs.json

mkdir -p "$DOC_FOLDER"/posh
doxybook2 --input $BUILD_FOLDER/iceoryx_posh/xml/ --output $DOC_FOLDER/posh --config $CONFIG_FOLDER/doxybook2-posh.json

mkdir -p "$DOC_FOLDER"/c-binding
doxybook2 --input $BUILD_FOLDER/iceoryx_binding_c/xml/ --output $DOC_FOLDER/c-binding --config $CONFIG_FOLDER/doxybook2-c-binding.json

mkdir -p "$DOC_FOLDER"/introspection
doxybook2 --input $BUILD_FOLDER/iceoryx_introspection/xml/ --output $DOC_FOLDER/introspection --config $CONFIG_FOLDER/doxybook2-introspection.json

# Remove index files

FILES="index_classes.md index_examples.md index_files.md index_modules.md index_namespaces.md index_pages.md index_groups.md"

for PACKAGE in ${PACKAGES}  ; do
    for FILE in ${FILES}  ; do
        rm -f "$WORKSPACE"/doc/website/API-reference/"$PACKAGE"/"$FILE"
    done
done

if [ "$TYPE" == "local" ]; then
    echo "starting local webserver"
    mkdocs serve --config-file ../iceoryx/mkdocs.yml
fi

if [ "$TYPE" == "publish" ]; then
    # Generate HTML and push to GitHub pages
    if [ ! -d "$WORKSPACE/../iceoryx-web" ]; then
        cd "$WORKSPACE"/../
        git clone $WEBREPO
    fi
    cd "$WORKSPACE"/../iceoryx-web
    mike deploy --branch main --config-file ../iceoryx/mkdocs.yml --push --update-aliases "$VERSION" latest
fi


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/layoutBackground">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_margin="@dimen/table_title_margin"
        android:text="@string/weapon_title"
        android:textColor="@color/colorText"
        android:textSize="@dimen/table_title_text_size"
        android:textStyle="bold"
        android:id="@+id/weaponTableTitle" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/weaponTableTitle"
        android:layout_margin="@dimen/effects_margin"
        android:text="@string/weapon_effect1"
        android:textColor="@color/colorText"
        android:gravity="center"
        android:id="@+id/weaponEffect1" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_below="@+id/weaponEffect1"
        android:layout_alignParentStart="true"
        android:id="@+id/weaponEffect1LinearLayout"
        android:baselineAligned="false">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/effects_img_margin"
                android:layout_centerHorizontal="true"
                android:id="@+id/weaponEffect1Img1"
                android:src="@drawable/blessed_thistle"
                android:contentDescription="@string/blessed_thistle" />

            <TextView
                android:layout_width="@dimen/reagents_labels"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="@string/blessed_thistle"
                android:textColor="@color/colorText"
                android:id="@+id/weaponEffect1Txt1"
                android:layout_marginLeft="@dimen/effects_txt_margin"
                android:layout_marginRight="@dimen/effects_txt_margin"
                android:layout_centerHorizontal="true"
                android:layout_below="@+id/weaponEffect1Img1" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_weight="1">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_margin="@dimen/effects_img_margin"
                android:id="@+id/weaponEffect1Img2"
                android:src="@drawable/dragonthorn"
                android:contentDescription="@string/dragonthorn" />

            <TextView
                android:layout_width="@dimen/reagents_labels"
                android:layout_height="wrap_content"
                android:text="@string/dragonthorn"
                android:textColor="@color/colorText"
                android:id="@+id/weaponEffect1Txt2"
                android:layout_centerHorizontal="true"
                android:layout_marginLeft="@dimen/effects_txt_margin"
                android:layout_marginRight="@dimen/effects_txt_margin"
                android:layout_below="@+id/weaponEffect1Img2"
                android:gravity="center" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="@dimen/customPadding">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_margin="@dimen/effects_img_margin"
                android:id="@+id/weaponEffect1Img3"
                android:src="@drawable/water_hyacinth"
                android:contentDescription="@string/water_hyacinth" />

            <TextView
                android:layout_width="@dimen/reagents_labels"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:gravity="center"
                android:text="@string/water_hyacinth"
                android:textColor="@color/colorText"
                android:id="@+id/weaponEffect1Txt3"
                android:layout_marginLeft="@dimen/effects_txt_margin"
                android:layout_marginRight="@dimen/effects_txt_margin"
                android:layout_below="@+id/weaponEffect1Img3" />
        </RelativeLayout>

    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_below="@+id/weaponEffect1LinearLayout"
        android:id="@+id/OR_weapon_1"
        android:text="@string/or"
        android:textColor="@color/colorText"
        android:textSize="20sp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_below="@+id/OR_weapon_1"
        android:layout_alignParentStart="true"
        android:id="@+id/weaponEffect1LinearLayout2"
        android:baselineAligned="false">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/effects_img_margin"
                android:layout_centerHorizontal="true"
                android:id="@+id/weaponEffect1Img4"
                android:src="@drawable/blessed_thistle"
                android:contentDescription="@string/blessed_thistle" />

            <TextView
                android:layout_width="@dimen/reagents_labels"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="@string/blessed_thistle"
                android:textColor="@color/colorText"
                android:id="@+id/weaponEffect1Txt4"
                android:layout_marginLeft="@dimen/effects_txt_margin"
                android:layout_marginRight="@dimen/effects_txt_margin"
                android:layout_centerHorizontal="true"
                android:layout_below="@+id/weaponEffect1Img4" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_weight="1">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_margin="@dimen/effects_img_margin"
                android:id="@+id/weaponEffect1Img5"
                android:src="@drawable/dragonthorn"
                android:contentDescription="@string/dragonthorn" />

            <TextView
                android:layout_width="@dimen/reagents_labels"
                android:layout_height="wrap_content"
                android:text="@string/dragonthorn"
                android:textColor="@color/colorText"
                android:id="@+id/weaponEffect1Txt5"
                android:layout_centerHorizontal="true"
                android:layout_marginLeft="@dimen/effects_txt_margin"
                android:layout_marginRight="@dimen/effects_txt_margin"
                android:layout_below="@+id/weaponEffect1Img5"
                android:gravity="center" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="@dimen/customPadding">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_margin="@dimen/effects_img_margin"
                android:id="@+id/weaponEffect1Img6"
                android:src="@drawable/wormwood"
                android:contentDescription="@string/wormwood" />

            <TextView
                android:layout_width="@dimen/reagents_labels"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:gravity="center"
                android:text="@string/wormwood"
                android:textColor="@color/colorText"
                android:id="@+id/weaponEffect1Txt6"
                android:layout_marginLeft="@dimen/effects_txt_margin"
                android:layout_marginRight="@dimen/effects_txt_margin"
                android:layout_below="@+id/weaponEffect1Img6" />
        </RelativeLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:id="@+id/weaponLine1"
        android:background="@color/colorText"
        android:orientation="vertical"
        android:layout_below="@+id/weaponEffect1LinearLayout2"></LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/weaponLine1"
        android:layout_margin="@dimen/effects_margin"
        android:text="@string/weapon_effect2"
        android:textColor="@color/colorText"
        android:gravity="center"
        android:id="@+id/weaponEffect2" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_below="@+id/weaponEffect2"
        android:layout_alignParentStart="true"
        android:id="@+id/weaponEffect2LinearLayout"
        android:baselineAligned="false">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/effects_img_margin"
                android:layout_centerHorizontal="true"
                android:id="@+id/weaponEffect2Img1"
                android:src="@drawable/columbine"
                android:contentDescription="@string/columbine" />

            <TextView
                android:layout_width="@dimen/reagents_labels"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="@string/columbine"
                android:textColor="@color/colorText"
                android:id="@+id/weaponEffect2Txt1"
                android:layout_marginLeft="@dimen/effects_txt_margin"
                android:layout_marginRight="@dimen/effects_txt_margin"
                android:layout_centerHorizontal="true"
                android:layout_below="@+id/weaponEffect2Img1" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_weight="1">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_margin="@dimen/effects_img_margin"
                android:id="@+id/weaponEffect2Img2"
                android:src="@drawable/dragonthorn"
                android:contentDescription="@string/dragonthorn" />

            <TextView
                android:layout_width="@dimen/reagents_labels"
                android:layout_height="wrap_content"
                android:text="@string/dragonthorn"
                android:textColor="@color/colorText"
                android:id="@+id/weaponEffect2Txt2"
                android:layout_centerHorizontal="true"
                android:layout_marginLeft="@dimen/effects_txt_margin"
                android:layout_marginRight="@dimen/effects_txt_margin"
                android:layout_below="@+id/weaponEffect2Img2"
                android:gravity="center" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="@dimen/customPadding">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_margin="@dimen/effects_img_margin"
                android:id="@+id/weaponEffect2Img3"
                android:src="@drawable/water_hyacinth"
                android:contentDescription="@string/water_hyacinth" />

            <TextView
                android:layout_width="@dimen/reagents_labels"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:gravity="center"
                android:text="@string/water_hyacinth"
                android:textColor="@color/colorText"
                android:id="@+id/weaponEffect2Txt3"
                android:layout_marginLeft="@dimen/effects_txt_margin"
                android:layout_marginRight="@dimen/effects_txt_margin"
                android:layout_below="@+id/weaponEffect2Img3" />
        </RelativeLayout>

    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_below="@+id/weaponEffect2LinearLayout"
        android:id="@+id/OR_weapon_2"
        android:text="@string/or"
        android:textColor="@color/colorText"
        android:textSize="20sp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_below="@+id/OR_weapon_2"
        android:layout_alignParentStart="true"
        android:id="@+id/weaponEffect2LinearLayout2"
        android:baselineAligned="false">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/effects_img_margin"
                android:layout_centerHorizontal="true"
                android:id="@+id/weaponEffect2Img4"
                android:src="@drawable/dragonthorn"
                android:contentDescription="@string/dragonthorn" />

            <TextView
                android:layout_width="@dimen/reagents_labels"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="@string/dragonthorn"
                android:textColor="@color/colorText"
                android:id="@+id/weaponEffect2Txt4"
                android:layout_marginLeft="@dimen/effects_txt_margin"
                android:layout_marginRight="@dimen/effects_txt_margin"
                android:layout_centerHorizontal="true"
                android:layout_below="@+id/weaponEffect2Img4" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_weight="1">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_margin="@dimen/effects_img_margin"
                android:id="@+id/weaponEffect2Img5"
                android:src="@drawable/mountain_flower"
                android:contentDescription="@string/mountain_flower" />

            <TextView
                android:layout_width="@dimen/reagents_labels"
                android:layout_height="wrap_content"
                android:text="@string/mountain_flower"
                android:textColor="@color/colorText"
                android:id="@+id/weaponEffect2Txt5"
                android:layout_centerHorizontal="true"
                android:layout_marginLeft="@dimen/effects_txt_margin"
                android:layout_marginRight="@dimen/effects_txt_margin"
                android:layout_below="@+id/weaponEffect2Img5"
                android:gravity="center" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="@dimen/customPadding">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_margin="@dimen/effects_img_margin"
                android:id="@+id/weaponEffect2Img6"
                android:src="@drawable/water_hyacinth"
                android:contentDescription="@string/water_hyacinth" />

            <TextView
                android:layout_width="@dimen/reagents_labels"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:gravity="center"
                android:text="@string/water_hyacinth"
                android:textColor="@color/colorText"
                android:id="@+id/weaponEffect2Txt6"
                android:layout_marginLeft="@dimen/effects_txt_margin"
                android:layout_marginRight="@dimen/effects_txt_margin"
                android:layout_below="@+id/weaponEffect2Img6" />
        </RelativeLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:id="@+id/weaponLine2"
        android:background="@color/colorText"
        android:orientation="vertical"
        android:layout_below="@+id/weaponEffect2LinearLayout2"></LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/weaponLine2"
        android:layout_margin="@dimen/effects_margin"
        android:text="@string/weapon_effect3"
        android:textColor="@color/colorText"
        android:gravity="center"
        android:id="@+id/weaponEffect3" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_below="@+id/weaponEffect3"
        android:layout_alignParentStart="true"
        android:id="@+id/weaponEffect3LinearLayout"
        android:baselineAligned="false">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/effects_img_margin"
                android:layout_centerHorizontal="true"
                android:id="@+id/weaponEffect3Img1"
                android:src="@drawable/blessed_thistle"
                android:contentDescription="@string/blessed_thistle" />

            <TextView
                android:layout_width="@dimen/reagents_labels"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="@string/blessed_thistle"
                android:textColor="@color/colorText"
                android:id="@+id/weaponEffect3Txt1"
                android:layout_marginLeft="@dimen/effects_txt_margin"
                android:layout_marginRight="@dimen/effects_txt_margin"
                android:layout_centerHorizontal="true"
                android:layout_below="@+id/weaponEffect3Img1" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_weight="1">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_margin="@dimen/effects_img_margin"
                android:id="@+id/weaponEffect3Img2"
                android:src="@drawable/dragonthorn"
                android:contentDescription="@string/dragonthorn" />

            <TextView
                android:layout_width="@dimen/reagents_labels"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="@string/dragonthorn"
                android:textColor="@color/colorText"
                android:id="@+id/weaponEffect3Txt2"
                android:layout_centerHorizontal="true"
                android:layout_marginLeft="@dimen/effects_txt_margin"
                android:layout_marginRight="@dimen/effects_txt_margin"
                android:layout_below="@+id/weaponEffect3Img2" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="@dimen/customPadding">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_margin="@dimen/effects_img_margin"
                android:id="@+id/weaponEffect3Img3"
                android:src="@drawable/namiras_rot"
                android:contentDescription="@string/namiras_rot" />

            <TextView
                android:layout_width="@dimen/reagents_labels"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:gravity="center"
                android:text="@string/namiras_rot"
                android:textColor="@color/colorText"
                android:id="@+id/weaponEffect3Txt3"
                android:layout_marginLeft="@dimen/effects_txt_margin"
                android:layout_marginRight="@dimen/effects_txt_margin"
                android:layout_below="@+id/weaponEffect3Img3" />
        </RelativeLayout>

    </LinearLayout>

</RelativeLayout>


text:
package org.apache.hadoop.yarn.server.nodemanager;

import java.io.IOException;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.*;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.UnsupportedFileSystemException;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor;
import org.apache.hadoop.yarn.service.AbstractService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

public class DeletionService extends AbstractService {
  static final Log LOG = LogFactory.getLog(DeletionService.class);
  private int debugDelay;
  private final ContainerExecutor exec;
  private ScheduledThreadPoolExecutor sched;
  private final FileContext lfs = getLfs();
  static final FileContext getLfs() {
    try {
      return FileContext.getLocalFSFileContext();
    } catch (UnsupportedFileSystemException e) {
      throw new RuntimeException(e);
    }
  }

  public DeletionService(ContainerExecutor exec) {
    super(DeletionService.class.getName());
    this.exec = exec;
    this.debugDelay = 0;
  }

  /**
   *
  /**
   * Delete the path(s) as this user.
   * @param user The user to delete as, or the JVM user if null
   * @param subDir the sub directory name
   * @param baseDirs the base directories which contains the subDir's
   */
  public void delete(String user, Path subDir, Path... baseDirs) {
    // TODO if parent owned by NM, rename within parent inline
    sched.schedule(new FileDeletion(user, subDir, baseDirs),
        debugDelay, TimeUnit.SECONDS);
  }

  @Override
  public void init(Configuration conf) {
    ThreadFactory tf = new ThreadFactoryBuilder()
      .setNameFormat("DeletionService #%d")
      .build();
    if (conf != null) {
      sched = new ScheduledThreadPoolExecutor(
          conf.getInt(YarnConfiguration.NM_DELETE_THREAD_COUNT, YarnConfiguration.DEFAULT_NM_DELETE_THREAD_COUNT),
          tf);
      debugDelay = conf.getInt(YarnConfiguration.DEBUG_NM_DELETE_DELAY_SEC, 0);
    } else {
      sched = new ScheduledThreadPoolExecutor(YarnConfiguration.DEFAULT_NM_DELETE_THREAD_COUNT,
          tf);
    }
    sched.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    sched.setKeepAliveTime(60L, SECONDS);
    super.init(conf);
  }

  @Override
  public void stop() {
    sched.shutdown();
    boolean terminated = false;
    try {
      terminated = sched.awaitTermination(10, SECONDS);
    } catch (InterruptedException e) {
    }
    if (terminated != true) {
      sched.shutdownNow();
    }
    super.stop();
  }

  /**
   * Determine if the service has completely stopped.
   * Used only by unit tests
   * @return true if service has completely stopped
   */
  @Private
  public boolean isTerminated() {
    return getServiceState() == STATE.STOPPED && sched.isTerminated();
  }

  private class FileDeletion implements Runnable {
    final String user;
    final Path subDir;
    final Path[] baseDirs;
    FileDeletion(String user, Path subDir, Path[] baseDirs) {
      this.user = user;
      this.subDir = subDir;
      this.baseDirs = baseDirs;
    }
    @Override
    public void run() {
      if (null == user) {
        if (baseDirs == null || baseDirs.length == 0) {
          LOG.debug("NM deleting absolute path : " + subDir);
          try {
            lfs.delete(subDir, true);
          } catch (IOException e) {
            LOG.warn("Failed to delete " + subDir);
          }
          return;
        }
        for (Path baseDir : baseDirs) {
          Path del = subDir == null? baseDir : new Path(baseDir, subDir);
          LOG.debug("NM deleting path : " + del);
          try {
            lfs.delete(del, true);
          } catch (IOException e) {
            LOG.warn("Failed to delete " + subDir);
          }
        }
      } else {
        try {
          LOG.debug("Deleting path: [" + subDir + "] as user: [" + user + "]");
          exec.deleteAsUser(user, subDir, baseDirs);
        } catch (IOException e) {
          LOG.warn("Failed to delete as user " + user, e);
        } catch (InterruptedException e) {
          LOG.warn("Failed to delete as user " + user, e);
        }
      }
    }
  }
}


text:
"use strict";

import React from 'react';
import {Router, Route, Link, IndexRoute} from 'react-router';
import HomePage from '../../HomePage';
import LoginPage from '../../LoginPage';
import NavLoggedInItems from './NavLoggedInItems';
import NavNotLoggedInItems from './NavNotLoggedInItems';

import LeftNav from 'material-ui/lib/left-nav';
import MenuItem from 'material-ui/lib/menus/menu-item';
import RaisedButton from 'material-ui/lib/raised-button';

import UserStore from '../../../stores/UserStore'

export default class Nav extends React.Component {
    componentWillMount() {
        this.state = {
            navopen: false
        }
    };

    handleToggle = () => {
        this.setState({navopen: !this.state.navopen});
    };

    render() {
        let NavItems;
        if (this.props.user) {
            NavItems = <NavLoggedInItems user={this.props.user}/>
        } else {
            NavItems = <NavNotLoggedInItems/>
        }
        return (
            <nav>
                <LeftNav open={this.state.navopen} style={{zIndex:9999}} overlayStyle={{zIndex:999}} className="navRoot" overlayClassName="navRootOverlay" docked={false} onRequestChange={navopen => this.setState({navopen})}>
                <button className="navTrigger" onClick={this.handleToggle}><i className="fa fa-bars"></i></button>
                  {NavItems}
                </LeftNav>

            </nav>
        )
    }
}


text:
<?php

/**
 * Ce fichier est une partie de l'application Pablo.
 *
 * @author Thomas Decraux <thomasdecraux@gmail.com>
 * @version <0.1.0>
 */

namespace Pablo\PeopleBundle\Controller;

use Pablo\PeopleBundle\Entity\Adresse;
use Pablo\PeopleBundle\Entity\Personne;
use Pablo\PeopleBundle\Entity\Employe;
use Pablo\PeopleBundle\Form\AdresseType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

/**
 * Class AdresseController
 * @package Pablo\PeopleBundle\Controller
 */
class AdresseController extends Controller
{
    /**
     * Affiche la liste des personnes et employés avec leur(s) adresse(s)
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function listAction()
    {
        $em = $this->getDoctrine()->getManager();
        $adresses = $em->getRepository('PabloPeopleBundle:Adresse')->findAll();

        return $this->render('PabloPeopleBundle:Adresse:list.html.twig', array(
            'adresses' => $adresses,
        ));
    }

    /**
     * Affiche le formulaire d'ajout d'une nouvelle adresse
     *
     * @param $id
     * @param Personne $personne
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function addAction($id, Personne $personne)
    {
        $adresse = new Adresse();
        $adresse->setPersonne($personne);

        $form = $this->createForm(new AdresseType(), $adresse);

        if ($adresse->getPersonne() instanceof Employe) {
            $url = $this->generateUrl('pablo_employe_show', array('id' => $adresse->getPersonne()->getId())) . '#adresses';
        } else {
            $url = $this->generateUrl('pablo_personne_show', array('id' => $adresse->getPersonne()->getId())) . '#adresses';
        }

        return $this->render('PabloPeopleBundle:Adresse:create.html.twig', array(
            'adresse' => $adresse,
            'form' => $form->createView(),
            'url' => $url,
        ));
    }

    /**
     * Valide le formulaire et enregistre la nouvelle adresse
     * Redirige vers la fiche de la personne ou de l'employé.
     *
     * @param $id
     * @param Personne $personne
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function createAction($id, Personne $personne)
    {
        $adresse = new Adresse();
        $adresse->setPersonne($personne);

        $form = $this->createForm(new AdresseType(), $adresse);
        $form->handleRequest($this->getRequest());

        if ($adresse->getPersonne() instanceof Employe) {
            $url = $this->generateUrl('pablo_employe_show', array('id' => $adresse->getPersonne()->getId())) . '#adresses';
        } else {
            $url = $this->generateUrl('pablo_personne_show', array('id' => $adresse->getPersonne()->getId())) . '#adresses';
        }

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($adresse);
            $em->flush();

            $this->get('session')->getFlashBag()->add('notice', array(
                'type' => 'success',
                'content' => 'L\'adresse a été enregistrée.'
            ));

            return $this->redirect($url);
        }

        return $this->render('PabloPeopleBundle:Adresse:create.html.twig', array(
            'adresse' => $adresse,
            'form' => $form->createView(),
            'url' => $url,
        ));
    }

    /**
     * Affiche le formulaire d'édition d'une adresse exitante
     *
     * @param $id
     * @param Adresse $adresse
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function editAction($id, Adresse $adresse)
    {
        $form = $this->createForm(new AdresseType(), $adresse);

        if ($adresse->getPersonne() instanceof Employe) {
            $url = $this->generateUrl('pablo_employe_show', array('id' => $adresse->getPersonne()->getId())) . '#adresses';
        } else {
            $url = $this->generateUrl('pablo_personne_show', array('id' => $adresse->getPersonne()->getId())) . '#adresses';
        }

        return $this->render('PabloPeopleBundle:Adresse:edit.html.twig', array(
            'adresse' => $adresse,
            'form' => $form->createView(),
            'url' => $url,
        ));
    }

    /**
     * Valide le formulaire et enregistre l'adresse modifiée
     * Redirige vers la fiche de la personne ou de l'employé.
     *
     * @param $id
     * @param \Pablo\PeopleBundle\Entity\Adresse $adresse
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function updateAction($id, Adresse $adresse)
    {
        $form = $this->createForm(new AdresseType(), $adresse);
        $form->handleRequest($this->getRequest());

        if ($adresse->getPersonne() instanceof Employe) {
            $url = $this->generateUrl('pablo_employe_show', array('id' => $adresse->getPersonne()->getId())) . '#adresses';
        } else {
            $url = $this->generateUrl('pablo_personne_show', array('id' => $adresse->getPersonne()->getId())) . '#adresses';
        }

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->flush();

            $this->get('session')->getFlashBag()->add('notice', array(
                'type' => 'success',
                'content' => 'L\'adresse a été modifiée.'
            ));

            return $this->redirect($url);
        }

        return $this->render('PabloPeopleBundle:Adresse:edit.html.twig', array(
            'adresse' => $adresse,
            'form' => $form->createView(),
            'url' => $url,
        ));
    }

    /**
     * Efface une adresse
     * Redirige vers la fiche de la personne ou de l'employé.
     *
     * @param $id
     * @param Adresse $adresse
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function deleteAction($id, Adresse $adresse)
    {
        $em = $this->getDoctrine()->getManager();
        $em->remove($adresse);
        $em->flush();

        $this->get('session')->getFlashBag()->add('notice', array(
            'type' => null,
            'content' => 'L\'adresse a été supprimée.'
        ));

        if ($adresse->getPersonne() instanceof Employe) {
            $url = $this->generateUrl('pablo_employe_show', array('id' => $adresse->getPersonne()->getId())) . '#adresses';
        } else {
            $url = $this->generateUrl('pablo_personne_show', array('id' => $adresse->getPersonne()->getId())) . '#adresses';
        }

        return $this->redirect($url);
    }
}