text:
/************************************************************//**
  @file lsjt_scheme.h

  Defines relative and two-body state indexing in LSJT coupling scheme.
  Written for use in Moshinsky transformation.

  Indexing is in each case broken into a *subspace* (described by
  LSJTg labels and an Nmax trunction) and then indexed states within
  the subspace.

  Variant indexing schemes where the subspaces are further broken down
  by the number of oscillator quanta N are then provided, so that the
  Moshinsky transformation implementation can be more easily broken
  down by N blocks.

  See notes "Moshinsky xform for operators" (2015) for derivation
  of indexing scheme.

  Language: C++11

  Mark A. Caprio
  University of Notre Dame

  + 11/13/15 (mac): Created, styled after shell_indexing_nlj.
  + 11/21/15 (mac): Rename from shell_indexing_lsjt to indexing_lsjt.
    Extracted generic class properties to templates base classes in
    indexing_base.
  + 11/26/15 (mac): Update iteration schemes.
  + 6/8/16 (mac): Update for basis package and update conventions.
    - Rename to lsjt_scheme.h.
    - Rename quantum number N to Nr.
    - Rename SpuriousRelative to RelativeCM.
    - Replace RelativeCM *state* iteration constraint lr+S+T~1 in
      constructor with *subspace* constraint Ncm+S+T+g~1 in Validate.
    - Restrict TwoBody states to canonical ordering of orbitals.
    - Replace Print() methods with Str() methods.
  + 6/22/16 (mac): Make explicit typedefs for label types.
  + 6/27/16 (mac):
    - Add Jr_max cutoff on construction of relative basis.
    - Change relative-c.m. scheme from spectator (Nc,lc) to active (Nc,lc).
    - Add fixed-N subspaces in relative-c.m. basis for use with Moshinsky
      transform block structure.
    - Expand basis indexing comments.
    - Implement canonical ordering constraint on sectors.
    - Remove all-to-all sector constructors.
    - Rename Str() to DebugStr().
    - Rename labels on relative basis (e.g., J->Jr).
  + 6/30/16 (mac): Revert labels on relative basis (e.g., Jr->J).
  + 7/3/16 (mac): Add default constructors for RelativeLSJT basis.
  + 7/4/16 (mac): Add fixed-N subspaces in two-body basis for use with
    Moshinsky transform block structure.
  + 7/8/16 (mac): Add default constructors for TwoBodyLSJT basis.
  + 7/9/16 (mac):
    - Add debug strings for RelativeLSJT basis.
    - Add default constructors for remaining subspaces, spaces,
      and sectors.
  + 7/13/16 (mac): Fix relative enumeration.
  + 7/16/16 (mac):
    - Add debug strings for TwoBodyLSJT basis.
    - Move N to least significant subspace label in LSJTN bases.
  + 7/17/16 (mac):
    - Rename NLSJT to LSJTN.
    - Remove unnecessary complication of matching subspace Nmax
      to g.
    - Add one-body (square) truncation on two-body bases.
  + 7/19/16 (mac): Use enum Rank for truncation rank.
  + 7/1/17 (mac): Add n accessor to RelativeStateLSJT.
  + 05/09/19 (pjf): Use std::size_t for indices and sizes, to prevent
    integer overflow.
  + 05/27/19 (pjf): Update to initialize BaseSectors with spaces.
  + 07/03/21 (pjf): Call base class constructor for initializing labels.
  + 07/04/21 (pjf): Pass derived subspace class as template argument to
    BaseSubspace.
  + 06/03/22 (pjf): Add nr() and nc() accessors to RelativeCMStateLSJT.

****************************************************************/

#ifndef BASIS_LSJT_SCHEME_H_
#define BASIS_LSJT_SCHEME_H_

#include <cstddef>
#include <string>
#include <tuple>

#include "basis.h"
#include "many_body.h"

namespace basis {

  ////////////////////////////////////////////////////////////////
  // relative states in LSJT scheme
  ////////////////////////////////////////////////////////////////

  ////////////////////////////////////////////////////////////////
  //
  // Labeling
  //
  // subspace labels: (L,S,J,T,g)    P=(-)^g
  //
  //   L (int): orbital angular momentum of *relative* motion (=lr)
  //   S (int): total spin
  //   J (int): total angular momentum of *relative* motion (=Jr)
  //            (i.e., L coupled to S)
  //   T (int): isospin
  //   g (int): grade (=0,1) for the parity P of *relative*
  //            motion (=gr)
  //
  // state labels within subspace: (N)
  //
  //   N (int): oscillator quanta of relative motion (=Nr)
  //
  ////////////////////////////////////////////////////////////////
  //
  // Subspaces
  //
  // Within the full space, subspaces are ordered by:
  //   -- increasing L (L=0,1,...,Nmax)
  //   -- increasing S (S=0,1)
  //   -- increasing J
  //   -- [T forced by L+S+T~1]
  //   -- [g forced by g~L]
  // subject to:
  //   -- triangularity of (L,S,J)
  //   -- parity constraint L~g
  //   -- antisymmetry constraint L+S+T~1
  //
  // Subspaces are asserted to have nonzero dimension (as a sanity
  // check).
  //
  // Note that ordering of subspaces is lexicographic by (L,S,J).
  //
  // Truncation of the space is by the relative Nmax.
  //
  ////////////////////////////////////////////////////////////////
  //
  // States
  //
  // Within a subspace, the states are ordered by:
  //   -- increasing N
  // and subject to:
  //   -- oscillator branching constraints N>=L and N~L (or,
  //      equivalently, parity constraint N~g)
  //
  // This basis is for *identical* particle states, but the
  // antisymmetry constraint is already applied at the level of
  // selecting the subspace labels L+S+T~1.
  //
  ////////////////////////////////////////////////////////////////

  // declarations
  class RelativeSubspaceLSJT;
  class RelativeStateLSJT;
  class RelativeSpaceLSJT;

  // labels

  typedef std::tuple<int,int,int,int,int> RelativeSubspaceLSJTLabels;
  typedef std::tuple<int> RelativeStateLSJTLabels;

  // subspace

  class RelativeSubspaceLSJT
    : public BaseSubspace<RelativeSubspaceLSJT,RelativeSubspaceLSJTLabels,RelativeStateLSJT,RelativeStateLSJTLabels>
    {

      public:

      // constructor

      RelativeSubspaceLSJT() = default;
      // default constructor -- provided since required for certain
      // purposes by STL container classes (e.g., std::vector::resize)

      RelativeSubspaceLSJT(int L, int S, int J, int T, int g, int Nmax);
      // Set up indexing.

      // accessors

      int L() const {return std::get<0>(labels());}
      int S() const {return std::get<1>(labels());}
      int J() const {return std::get<2>(labels());}
      int T() const {return std::get<3>(labels());}
      int g() const {return std::get<4>(labels());}
      int Nmax() const {return Nmax_;}

      // diagnostic strings
      std::string LabelStr() const;
      // Provide string representation of subspace labels.
      std::string DebugStr() const;
      // Dump subspace contents.

      private:

      //validation
      bool ValidLabels() const;

      // truncation
      int Nmax_;

    };

  // state

  class RelativeStateLSJT
    : public BaseState<RelativeSubspaceLSJT>
  {

    public:

    // pass-through constructors

    RelativeStateLSJT(const SubspaceType& subspace, std::size_t index)
      // Construct state by index.
      : BaseState (subspace,index) {}

    RelativeStateLSJT(const SubspaceType& subspace, const StateLabelsType& state_labels)
      // Construct state by reverse lookup on labels.
      : BaseState (subspace,state_labels) {}

    // pass-through accessors
    int L() const {return subspace().L();}
    int S() const {return subspace().S();}
    int J() const {return subspace().J();}
    int T() const {return subspace().T();}
    int g() const {return subspace().g();}

    // state label accessors
    int N() const {return std::get<0>(labels());}

    // derived label
    //
    // radial number n can be recovered from N=2*n+L, but it also
    // happens to simply be state index w/in the subspace
    int n() const {return (N()-L())/2;}

  };

  // space

  class RelativeSpaceLSJT
    : public BaseSpace<RelativeSubspaceLSJT>
  {

    public:

    // constructor

    RelativeSpaceLSJT() = default;
    // default constructor -- provided since required for certain
    // purposes by STL container classes (e.g., std::vector::resize)

    RelativeSpaceLSJT(int Nmax, int Jmax);
    // Enumerate all relative LSJT subspaces of given dimension up to
    // a given relative oscillator cutoff and relative angular
    // momentum cutoff.
    //
    // The relative angular momentum cutoff is included in recognition
    // of the common practice of truncation by highest partial wave in
    // the representation of relative interations.
    //
    // Arguments:
    //   Nmax (int) : relative oscillator truncation on included subspaces
    //   Jmax (int) : relative angular momentum truncation on included
    //     subspaces (Jmax<=Nmax+1)

    // accessors
    int Nmax() const {return Nmax_;}
    int Jmax() const {return Jmax_;}

    // diagnostic string
    std::string DebugStr() const;

    private:
    // truncation
    int Nmax_, Jmax_;

  };

  // sectors

  class RelativeSectorsLSJT
    : public BaseSectors<RelativeSpaceLSJT>
  {

    public:

    // constructor

    RelativeSectorsLSJT() = default;
    // default constructor -- provided since required for certain
    // purposes by STL container classes (e.g., std::vector::resize)

    RelativeSectorsLSJT(
        const RelativeSpaceLSJT& space,
        basis::SectorDirection sector_direction = basis::SectorDirection::kCanonical
      );
    // Enumerate all sector pairs ("all-to-all" sector enumeration).
    //
    // Sectors are enumerated in lexicographical order by (bra)(ket).
    //
    // Note: This all-to-all constructor is implemented primarily for
    // the purpose of providing example code for all-to-all sector
    // enumeration.  It is not clear that there is immediate
    // application of all-to-all enumeration for this particular
    // basis.

    RelativeSectorsLSJT(
        const RelativeSpaceLSJT& space,
        int J0, int T0, int g0,
        basis::SectorDirection sector_direction = basis::SectorDirection::kCanonical
      );
    // Enumerate sector pairs connected by an operator of given
    // tensorial and parity character ("constrained" sector
    // enumeration).

  };

  ////////////////////////////////////////////////////////////////
  // relative-cm states in LSJT scheme
  ////////////////////////////////////////////////////////////////

  ////////////////////////////////////////////////////////////////
  //
  // Labeling
  //
  // subspace labels: (L,S,J,T,g)
  //
  //   L (int): orbital angular momentum
  //   S (int): total spin
  //   J (int): total angular momentum
  //   T (int): isospin
  //   g (int): grade (=0,1) for the parity P
  //
  // state labels within subspace: (Nr,lr,Nc,lc)
  //
  //   Nr (int): oscillator quanta of relative motion
  //   lr (int): orbital angular momentum of relative motion
  //   Nc (int): oscillator quanta of c.m. motion
  //   lc (int): orbital angular momentum of c.m. motion
  //
  ////////////////////////////////////////////////////////////////
  //
  // Subspaces
  //
  // Within the full space, subspaces are ordered by:
  //    -- increasing L (L=0,1,...,Nmax)
  //    -- increasing S (S=0,1)
  //    -- increasing J
  //    -- increasing T (T=0,1)
  //    -- increasing g (g=0,1)
  // subject to:
  //    -- triangularity of (L,S,J)
  //
  // Subspaces are pruned to those of nonzero dimension.
  //
  // Note that ordering of subspaces is lexicographic by (L,S,J,T,g).
  //
  // Truncation of the space is by the two-body Nmax.
  //
  ////////////////////////////////////////////////////////////////
  //
  // States
  //
  // Within a subspace, the states are ordered by:
  //   -- increasing N  (N=Nr+Nc)
  //   -- lexicographically increasing (Nr,lr)
  //   -- lexicographically increasing (Nc,lc)
  // and subject to:
  //   -- triangularity constraint on (lr,lc,L)
  //   -- parity constraint N~g
  //   -- antisymmetry constraint lr+S+T~1 (or, equivalentsly,
  //      Nr+S+T~1)
  //
  // This basis is for *identical* particle states, as enforced by the
  // antisymmetry constraint on Nr.
  //
  ////////////////////////////////////////////////////////////////

  // declarations
  class RelativeCMSubspaceLSJT;
  class RelativeCMStateLSJT;
  class RelativeCMSpaceLSJT;

  // labels

  typedef std::tuple<int,int,int,int,int> RelativeCMSubspaceLSJTLabels;
  typedef std::tuple<int,int,int,int> RelativeCMStateLSJTLabels;

  //subspace

  class RelativeCMSubspaceLSJT
    : public BaseSubspace<RelativeCMSubspaceLSJT,RelativeCMSubspaceLSJTLabels,RelativeCMStateLSJT,RelativeCMStateLSJTLabels>
    {

      public:

      // constructor

      RelativeCMSubspaceLSJT() = default;
      // default constructor -- provided since required for certain
      // purposes by STL container classes (e.g., std::vector::resize)

      RelativeCMSubspaceLSJT(int L, int S, int J, int T, int g, int Nmax);

      // accessors

      int L() const {return std::get<0>(labels());}
      int S() const {return std::get<1>(labels());}
      int J() const {return std::get<2>(labels());}
      int T() const {return std::get<3>(labels());}
      int g() const {return std::get<4>(labels());}
      int Nmax() const {return Nmax_;}

      // diagnostic strings
      std::string LabelStr() const;
      // Provide string representation of subspace labels.
      std::string DebugStr() const;
      // Dump subspace contents.

      private:

      //validation
      bool ValidLabels() const;

      // truncation
      int Nmax_;

    };

  // state

  class RelativeCMStateLSJT
    : public BaseState<RelativeCMSubspaceLSJT>
  {

    public:

    // pass-through constructors

    RelativeCMStateLSJT(const SubspaceType& subspace, std::size_t index)
      // Construct state by index.
      : BaseState (subspace, index) {}

    RelativeCMStateLSJT(const SubspaceType& subspace, const StateLabelsType& state_labels)
      // Construct state by reverse lookup on labels.
      : BaseState (subspace, state_labels) {}

    // pass-through accessors

    int L() const {return subspace().L();}
    int S() const {return subspace().S();}
    int J() const {return subspace().J();}
    int T() const {return subspace().T();}
    int g() const {return subspace().g();}

    // state label accessors
    int Nr() const {return std::get<0>(labels());}
    int lr() const {return std::get<1>(labels());}
    int nr() const {return (Nr()-lr())/2;}
    int Nc() const {return std::get<2>(labels());}
    int lc() const {return std::get<3>(labels());}
    int nc() const {return (Nc()-lc())/2;}
    int N() const {return  Nr()+Nc();}

  };

  // space

  class RelativeCMSpaceLSJT
    : public BaseSpace<RelativeCMSubspaceLSJT>
  {

    public:

    // constructor

    RelativeCMSpaceLSJT() = default;
    // default constructor -- provided since required for certain
    // purposes by STL container classes (e.g., std::vector::resize)

    RelativeCMSpaceLSJT(int Nmax);
    // Enumerate all subspaces up to a given Nmax cutoff.

    // accessors
    int Nmax() const {return Nmax_;}

    // diagnostic string
    std::string DebugStr() const;

    private:
    // truncation
    int Nmax_;

  };

  // sectors

  class RelativeCMSectorsLSJT
    : public BaseSectors<RelativeCMSpaceLSJT>
  {

    public:

    // constructor

    RelativeCMSectorsLSJT() = default;
    // default constructor -- provided since required for certain
    // purposes by STL container classes (e.g., std::vector::resize)

    RelativeCMSectorsLSJT(
        const RelativeCMSpaceLSJT& space,
        int J0, int T0, int g0,
        basis::SectorDirection sector_direction = basis::SectorDirection::kCanonical
      );
    // Enumerate sector pairs connected by an operator of given
    // tensorial and parity character ("constrained" sector
    // enumeration).

  };

  ////////////////////////////////////////////////////////////////
  // relative-cm states in LSJT scheme -- subspaced by N
  ////////////////////////////////////////////////////////////////

  ////////////////////////////////////////////////////////////////
  //
  // Labeling
  //
  // subspace labels: (L,S,J,T,g,N)  (MODIFICATION for subspacing by N)
  //
  // state labels within subspace: (Nr,lr,Nc,lc)
  //
  ////////////////////////////////////////////////////////////////
  //
  // Subspaces
  //
  // Within the full space, subspaces are ordered by:
  //    -- increasing L (L=0,1,...,Nmax)
  //    -- increasing S (S=0,1)
  //    -- increasing J
  //    -- increasing T (T=0,1)
  //    -- increasing g (g=0,1)
  //    -- increasing N (N=0,1,...,Nmax)  (MODIFICATION for subspacing by N)
  // subject to:
  //    -- triangularity of (L,S,J)
  //    -- parity constraint N~g  (MODIFICATION for subspacing by N)
  //
  // Subspaces are pruned to those of nonzero dimension.
  //
  // Note that ordering of subspaces is lexicographic by (L,S,J,T,g,N).  (MODIFICATION for subspacing by N)
  //
  // Truncation of the space is by the two-body Nmax.
  //
  ////////////////////////////////////////////////////////////////
  //
  // States
  //
  // Within a subspace, the states are ordered by:
  //   -- [increasing N  (N=Nr+Nc)]  (MODIFICATION for subspacing by N)
  //   -- lexicographically increasing (Nr,lr)
  //   -- lexicographically increasing (Nc,lc)
  // and subject to:
  //   -- triangularity constraint on (lr,lc,L)
  //   -- [parity constraint N~g]  (MODIFICATION for subspacing by N)
  //   -- antisymmetry constraint lr+S+T~1 (or, equivalentsly,
  //      Nr+S+T~1)
  //
  // This basis is for *identical* particle states (see discussion
  // above for non-N version).
  //
  ////////////////////////////////////////////////////////////////

  // Modification for subspacing by N is by lexical replacement LSJT
  // -> LSJTN plus specific mods as flagged by MODIFICATION comments
  // in code.

  // declarations
  class RelativeCMSubspaceLSJTN;
  class RelativeCMStateLSJTN;
  class RelativeCMSpaceLSJTN;

  // labels

  typedef std::tuple<int,int,int,int,int,int> RelativeCMSubspaceLSJTNLabels;  // (MODIFICATION for subspacing by N)
  typedef std::tuple<int,int,int,int> RelativeCMStateLSJTNLabels;

  //subspace

  class RelativeCMSubspaceLSJTN
    : public BaseSubspace<RelativeCMSubspaceLSJTN,RelativeCMSubspaceLSJTNLabels,RelativeCMStateLSJTN,RelativeCMStateLSJTNLabels>
    {

      public:

      // constructor

      RelativeCMSubspaceLSJTN() = default;
      // default constructor -- provided since required for certain
      // purposes by STL container classes (e.g., std::vector::resize)

      RelativeCMSubspaceLSJTN(int L, int S, int J, int T, int g, int N);  // (MODIFICATION for subspacing by N)

      // accessors

      int L() const {return std::get<0>(labels());}
      int S() const {return std::get<1>(labels());}
      int J() const {return std::get<2>(labels());}
      int T() const {return std::get<3>(labels());}
      int g() const {return std::get<4>(labels());}
      int N() const {return std::get<5>(labels());}  // (MODIFICATION for subspacing by N)

      // diagnostic strings
      std::string LabelStr() const;
      // Provide string representation of subspace labels.
      std::string DebugStr() const;
      // Dump subspace contents.

      private:

      //validation
      bool ValidLabels() const;

      private:
      // truncation
      int N_;  // (MODIFICATION for subspacing by N)

    };

  // state

  class RelativeCMStateLSJTN
    : public BaseState<RelativeCMSubspaceLSJTN>
  {

    public:

    // pass-through constructors

    RelativeCMStateLSJTN(const SubspaceType& subspace, std::size_t index)
      // Construct state by index.
      : BaseState (subspace, index) {}

    RelativeCMStateLSJTN(const SubspaceType& subspace, const StateLabelsType& state_labels)
      // Construct state by reverse lookup on labels.
      : BaseState (subspace, state_labels) {}

    // pass-through accessors

    int L() const {return subspace().L();}
    int S() const {return subspace().S();}
    int J() const {return subspace().J();}
    int T() const {return subspace().T();}
    int g() const {return subspace().g();}

    // state label accessors
    int Nr() const {return std::get<0>(labels());}
    int lr() const {return std::get<1>(labels());}
    int Nc() const {return std::get<2>(labels());}
    int lc() const {return std::get<3>(labels());}
    int N() const {return  Nr()+Nc();}

  };

  // space

  class RelativeCMSpaceLSJTN
    : public BaseSpace<RelativeCMSubspaceLSJTN>
  {

    public:

    // constructor

    RelativeCMSpaceLSJTN() = default;
    // default constructor -- provided since required for certain
    // purposes by STL container classes (e.g., std::vector::resize)

    RelativeCMSpaceLSJTN(int Nmax);
    // Enumerate all subspaces up to a given Nmax cutoff.

    // accessors
    int Nmax() const {return Nmax_;}

    // diagnostic string
    std::string DebugStr() const;

    private:
    // truncation
    int Nmax_;

  };

  // sectors

  class RelativeCMSectorsLSJTN
    : public BaseSectors<RelativeCMSpaceLSJTN>
  {

    public:

    // constructor

    RelativeCMSectorsLSJTN() = default;
    // default constructor -- provided since required for certain
    // purposes by STL container classes (e.g., std::vector::resize)

    RelativeCMSectorsLSJTN(
        const RelativeCMSpaceLSJTN& space,
        int J0, int T0, int g0,
        basis::SectorDirection sector_direction = basis::SectorDirection::kCanonical
      );
    // Enumerate sector pairs connected by an operator of given
    // tensorial and parity character ("constrained" sector
    // enumeration).

  };

  ////////////////////////////////////////////////////////////////
  // two-body states in LSJT scheme
  ////////////////////////////////////////////////////////////////

  ////////////////////////////////////////////////////////////////
  //
  // Labeling
  //
  // subspace labels: (L,S,J,T,g)
  //
  // state labels within subspace: (N1,l1,N2,l2)
  //
  ////////////////////////////////////////////////////////////////
  //
  // Subspaces
  //
  // Within the full space, subspaces are ordered by:
  //    -- increasing L (L=0,1,...,Nmax)
  //    -- increasing S (S=0,1)
  //    -- increasing J
  //    -- increasing T (T=0,1)
  //    -- increasing g (g=0,1)
  // subject to:
  //    -- triangularity of (L,S,J)
  //
  // Subspaces are pruned to those of nonzero dimension.
  //
  // Note that ordering of subspaces is lexicographic by (L,S,J,g).
  //
  // Truncation of the space is by the one-body N1max or two-body
  // N2max.
  //
  ////////////////////////////////////////////////////////////////
  //
  // States
  //
  // Within a subspace, the states are ordered by:
  //   -- increasing N (N~g)
  //   -- lexicographically increasing (N1,l1)
  //   -- lexicographically increasing (N2,l2)
  // and subject to:
  //   -- triangularity constraint on (l1,l2,L)
  //   -- parity constraint N~g
  //   -- antisymmetry constraint L+S+T~1 if (N1,l1)==(N2,l2)
  //
  //
  // This basis is for *identical* particle states:
  //   -- The labels are subject to the antisymmetry constraint
  //      (L+S+T~1) if the orbitals are identical.
  //   -- A canonical (lexicographic) ordering constraint is applied to the
  //      single-particle quantum numbers.  That is, when
  //      enumerating the basis, the states
  //
  //        |((N1,l1),(N2,l2))...>  and  |((N2,l2),(N1,l1))...>
  //
  //      would be redundant, and only the first (for (N1,l1)<=(N2,l2)) is
  //      retained.
  //
  // Comment: For some applications, it might be more convenient to
  // an overcomplete basis, in which the states
  //
  //   |(N1,l1)(N2,l2)...>  and  |(N2,l2)(N1,l1)...>
  //
  // are still counted separately in the basis.  That is, *no*
  // lexicographical ordering constraint (N1,l1)<=(N2,l2) on the two
  // single-particle states is imposed.  The basis is therefore
  // redundant.  This simplifies implementation of double contractions
  // over "particle 1" and "particle 2" indices as matrix
  // multiplication, without the calling code having to worry about
  // "swapping" single particle states within the two-body state and
  // applying the relevant phase (~L+S+T+g+1).
  //
  ////////////////////////////////////////////////////////////////

  // declarations
  class TwoBodySubspaceLSJT;
  class TwoBodyStateLSJT;
  class TwoBodySpaceLSJT;

  // labels

  typedef std::tuple<int,int,int,int,int> TwoBodySubspaceLSJTLabels;
  typedef std::tuple<int,int,int,int> TwoBodyStateLSJTLabels;

  //subspace

  class TwoBodySubspaceLSJT
    : public BaseSubspace<TwoBodySubspaceLSJT,TwoBodySubspaceLSJTLabels,TwoBodyStateLSJT,TwoBodyStateLSJTLabels>
    {

      public:

      // constructor

      TwoBodySubspaceLSJT() = default;
      // default constructor -- provided since required for certain
      // purposes by STL container classes (e.g., std::vector::resize)

      TwoBodySubspaceLSJT(
          int L, int S, int J, int T, int g,
          basis::Rank truncation_rank, int truncation_cutoff
        );
      // Set up indexing.

      // accessors

      int L() const {return std::get<0>(labels());}
      int S() const {return std::get<1>(labels());}
      int J() const {return std::get<2>(labels());}
      int T() const {return std::get<3>(labels());}
      int g() const {return std::get<4>(labels());}
      int N1max() const {return N1max_;}
      int N2max() const {return N2max_;}

      // diagnostic strings
      std::string LabelStr() const;
      // Provide string representation of subspace labels.
      std::string DebugStr() const;
      // Dump subspace contents.

      private:

      //validation
      bool ValidLabels() const;

      // truncation
      int N1max_, N2max_;
    };

  // state

  class TwoBodyStateLSJT
    : public BaseState<TwoBodySubspaceLSJT>
  {

    public:

    // pass-through constructors

    TwoBodyStateLSJT(const SubspaceType& subspace, std::size_t index)
      // Construct state by index.
      : BaseState (subspace, index) {}

    TwoBodyStateLSJT(const SubspaceType& subspace, const StateLabelsType& state_labels)
      // Construct state by reverse lookup on labels.
      : BaseState (subspace, state_labels) {}

    // pass-through accessors
    int L() const {return subspace().L();}
    int S() const {return subspace().S();}
    int J() const {return subspace().J();}
    int T() const {return subspace().T();}
    int g() const {return subspace().g();}

    // state label accessors
    int N1() const {return std::get<0>(labels());}
    int l1() const {return std::get<1>(labels());}
    int N2() const {return std::get<2>(labels());}
    int l2() const {return std::get<3>(labels());}

    int N() const {return N1()+N2();}

  };

  // space

  class TwoBodySpaceLSJT
    : public BaseSpace<TwoBodySubspaceLSJT>
  {

    public:

    // constructor

    TwoBodySpaceLSJT() = default;
    // default constructor -- provided since required for certain
    // purposes by STL container classes (e.g., std::vector::resize)

    TwoBodySpaceLSJT(basis::Rank truncation_rank, int truncation_cutoff);
    // Enumerate all subspaces up to a given Nmax cutoff.

    // accessors
    int N1max() const {return N1max_;}
    int N2max() const {return N2max_;}

    // diagnostic string
    std::string DebugStr() const;

    private:
    // truncation
    int N1max_, N2max_;

  };

  // sectors

  class TwoBodySectorsLSJT
    : public BaseSectors<TwoBodySpaceLSJT>
  {

    public:

    // constructor

    TwoBodySectorsLSJT() = default;
    // default constructor -- provided since required for certain
    // purposes by STL container classes (e.g., std::vector::resize)

    TwoBodySectorsLSJT(
        const TwoBodySpaceLSJT& space,
        int J0, int T0, int g0,
        basis::SectorDirection sector_direction = basis::SectorDirection::kCanonical
      );
    // Enumerate sector pairs connected by an operator of given
    // tensorial and parity character ("constrained" sector
    // enumeration).

  };

  ////////////////////////////////////////////////////////////////
  // two-body states in LSJT scheme -- subspaced by N
  ////////////////////////////////////////////////////////////////

  ////////////////////////////////////////////////////////////////
  //
  // Labeling
  //
  // subspace labels: (L,S,J,T,g,N)  (MODIFICATION for subspacing by N)
  //
  // state labels within subspace: (N1,l1,N2,l2)
  //
  ////////////////////////////////////////////////////////////////
  //
  // Subspaces
  //
  // Within the full space, subspaces are ordered by:
  //    -- increasing L (L=0,1,...,Nmax)
  //    -- increasing S (S=0,1)
  //    -- increasing J
  //    -- increasing T (T=0,1)
  //    -- increasing g (g=0,1)
  //    -- increasing N (N=0,1,...,Nmax)  (MODIFICATION for subspacing by N)
  // subject to:
  //    -- triangularity of (L,S,J)
  //    -- parity constraint N~g  (MODIFICATION for subspacing by N)
  //
  // Subspaces are pruned to those of nonzero dimension.
  //
  // Note that ordering of subspaces is lexicographic by (L,S,J,T,g,N).  (MODIFICATION for subspacing by N)
  //
  // Truncation of the space is by the one-body N1max or two-body
  // N2max.
  //
  ////////////////////////////////////////////////////////////////
  //
  // States
  //
  // Within a subspace, the states are ordered by:
  //   -- [increasing N  (N=N1+N2)]  (MODIFICATION for subspacing by N)
  //   -- lexicographically increasing (N1,l1)
  //   -- lexicographically increasing (N2,l2)
  // and subject to:
  //   -- triangularity constraint on (l1,l2,L)
  //   -- [parity constraint N~g]  (MODIFICATION for subspacing by N)
  //   -- antisymmetry constraint L+S+T~1 if (N1,l1)==(N2,l2)
  //
  //
  // This basis is for *identical* particle states (see discussion
  // above for non-N version).
  //
  ////////////////////////////////////////////////////////////////

  // Modification for subspacing by N is by lexical replacement LSJT
  // -> LSJTN plus specific mods as flagged by MODIFICATION comments
  // in code.

  // declarations
  class TwoBodySubspaceLSJTN;
  class TwoBodyStateLSJTN;
  class TwoBodySpaceLSJTN;

  // labels

  typedef std::tuple<int,int,int,int,int,int> TwoBodySubspaceLSJTNLabels;  // (MODIFICATION for subspacing by N)
  typedef std::tuple<int,int,int,int> TwoBodyStateLSJTNLabels;

  //subspace

  class TwoBodySubspaceLSJTN
    : public BaseSubspace<TwoBodySubspaceLSJTN,TwoBodySubspaceLSJTNLabels,TwoBodyStateLSJTN,TwoBodyStateLSJTNLabels>
    {

      public:

      // constructor

      TwoBodySubspaceLSJTN() = default;
      // default constructor -- provided since required for certain
      // purposes by STL container classes (e.g., std::vector::resize)

      TwoBodySubspaceLSJTN(
          int L, int S, int J, int T, int g, int N,  // (MODIFICATION for subspacing by N)
          basis::Rank truncation_rank, int truncation_cutoff
        );
      // Set up indexing.

      // accessors

      int L() const {return std::get<0>(labels());}
      int S() const {return std::get<1>(labels());}
      int J() const {return std::get<2>(labels());}
      int T() const {return std::get<3>(labels());}
      int g() const {return std::get<4>(labels());}
      int N() const {return std::get<5>(labels());}  // (MODIFICATION for subspacing by N)
      int N1max() const {return N1max_;}
      int N2max() const {return N2max_;}

      // diagnostic strings
      std::string LabelStr() const;
      // Provide string representation of subspace labels.
      std::string DebugStr() const;
      // Dump subspace contents.

      private:

      //validation
      bool ValidLabels() const;

      // truncation
      int N1max_, N2max_;
      int N_;  // (MODIFICATION for subspacing by N)
    };

  // state

  class TwoBodyStateLSJTN
    : public BaseState<TwoBodySubspaceLSJTN>
  {

    public:

    // pass-through constructors

    TwoBodyStateLSJTN(const SubspaceType& subspace, std::size_t index)
      // Construct state by index.
      : BaseState (subspace, index) {}

    TwoBodyStateLSJTN(const SubspaceType& subspace, const StateLabelsType& state_labels)
      // Construct state by reverse lookup on labels.
      : BaseState (subspace, state_labels) {}

    // pass-through accessors
    int L() const {return subspace().L();}
    int S() const {return subspace().S();}
    int J() const {return subspace().J();}
    int T() const {return subspace().T();}
    int g() const {return subspace().g();}

    // state label accessors
    int N1() const {return std::get<0>(labels());}
    int l1() const {return std::get<1>(labels());}
    int N2() const {return std::get<2>(labels());}
    int l2() const {return std::get<3>(labels());}

    int N() const {return N1()+N2();}

  };

  // space

  class TwoBodySpaceLSJTN
    : public BaseSpace<TwoBodySubspaceLSJTN>
  {

    public:

    // constructor

    TwoBodySpaceLSJTN() = default;
    // default constructor -- provided since required for certain
    // purposes by STL container classes (e.g., std::vector::resize)

    TwoBodySpaceLSJTN(basis::Rank truncation_rank, int truncation_cutoff);
    // Enumerate all subspaces up to a given Nmax cutoff.

    // accessors
    int N1max() const {return N1max_;}
    int N2max() const {return N2max_;}

    // diagnostic string
    std::string DebugStr() const;

    private:
    // truncation
    int N1max_, N2max_;

  };

  // sectors

  class TwoBodySectorsLSJTN
    : public BaseSectors<TwoBodySpaceLSJTN>
  {

    public:

    // constructor

    TwoBodySectorsLSJTN() = default;
    // default constructor -- provided since required for certain
    // purposes by STL container classes (e.g., std::vector::resize)

    TwoBodySectorsLSJTN(
        const TwoBodySpaceLSJTN& space,
        int J0, int T0, int g0,
        basis::SectorDirection sector_direction = basis::SectorDirection::kCanonical
      );
    // Enumerate sector pairs connected by an operator of given
    // tensorial and parity character ("constrained" sector
    // enumeration).

  };

  ////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////
} // namespace

#endif


text:
<!DOCTYPE html>
<script src="../../../resources/testharness.js"></script>
<script src="../../../resources/testharnessreport.js"></script>
<script>
var upgradeIds = [];
</script>
<x-a id="a1"></x-a>
<link rel="import" href="resources/import-block-upgrade-in-import-child.html">
<body>
<x-b id="b4"></x-b>
<x-a id="a5"></x-a>
<script>
test(function () {
    assert_array_equals(window.upgradeIds, ['a1', 'a2', 'a3', 'b0', 'b1', 'b2', 'a4', 'b3', 'b4', 'a5'],
                        'Elements in the master and imports should be upgraded by a definition in an import.');
}, 'upgrade in the master');
</script>
</body>

redpajama_set_name: RedPajamaGithub


text:
SET @iCategId = (SELECT `id` FROM `sys_options_categories` WHERE `name`='bx_unacon_general' LIMIT 1);

DELETE FROM `sys_options` WHERE `name`='bx_unacon_privacy';
INSERT INTO `sys_options` (`name`, `value`, `category_id`, `caption`, `type`, `check`, `check_error`, `order`, `extra`) VALUES
('bx_unacon_privacy', '3', @iCategId, '_sys_connect_option_privacy', 'select', '', '', 54, 'a:2:{s:6:"module";s:9:"bx_unacon";s:6:"method";s:18:"get_privacy_groups";}');


text:
.. _api:

API
===

.. currentmodule:: distributed

**Client**

The client connects to and submits computation to a Dask cluster (such as a :class:`distributed.LocalCluster`)

.. autosummary::
   Client

.. autoautosummary:: distributed.Client
   :methods:

.. currentmodule:: distributed

.. autosummary::
   worker_client
   get_worker
   get_client
   secede
   rejoin
   print
   warn
   Reschedule

.. currentmodule:: distributed.recreate_tasks

.. autosummary::
   ReplayTaskClient.recreate_task_locally
   ReplayTaskClient.recreate_error_locally

.. currentmodule:: distributed

**Future**

.. autosummary::
   Future

.. autoautosummary:: distributed.Future
   :methods:

**Synchronization**

.. currentmodule:: distributed

.. autosummary::
   Event
   Lock
   MultiLock
   Semaphore
   Queue
   Variable

**Other**

.. autosummary::
   as_completed
   distributed.diagnostics.progressbar.progress
   wait
   fire_and_forget
   futures_of
   get_task_stream
   get_task_metadata
   performance_report

**Utilities**

.. autosummary::
   distributed.utils.Log
   distributed.utils.Logs

Asynchronous methods
--------------------

Most methods and functions can be used equally well within a blocking or
asynchronous environment using Tornado coroutines.  If used within a Tornado
IOLoop then you should yield or await otherwise blocking operations
appropriately.

You must tell the client that you intend to use it within an asynchronous
environment by passing the ``asynchronous=True`` keyword

.. code-block:: python

   # blocking
   client = Client()
   future = client.submit(func, *args)  # immediate, no blocking/async difference
   result = client.gather(future)  # blocking

   # asynchronous Python 2/3
   client = yield Client(asynchronous=True)
   future = client.submit(func, *args)  # immediate, no blocking/async difference
   result = yield client.gather(future)  # non-blocking/asynchronous

   # asynchronous Python 3
   client = await Client(asynchronous=True)
   future = client.submit(func, *args)  # immediate, no blocking/async difference
   result = await client.gather(future)  # non-blocking/asynchronous

The asynchronous variants must be run within a Tornado coroutine.  See the
:doc:`Asynchronous <asynchronous>` documentation for more information.

Client
------

.. currentmodule:: distributed

.. autoclass:: Client
   :members:

.. autoclass:: distributed.recreate_tasks.ReplayTaskClient
   :members:

Future
------

.. autoclass:: Future
   :members:

Synchronization
---------------

.. autoclass:: Event
   :members:
.. autoclass:: Lock
   :members:
.. autoclass:: MultiLock
   :members:
.. autoclass:: Semaphore
   :members:
.. autoclass:: Queue
   :members:
.. autoclass:: Variable
   :members:

Cluster
-------

Classes relevant for cluster creation and management. Other libraries
(like `dask-jobqueue`_, `dask-gateway`_, `dask-kubernetes`_, `dask-yarn`_ etc.)
provide additional cluster objects.

.. _dask-jobqueue: https://jobqueue.dask.org/
.. _dask-gateway: https://gateway.dask.org/
.. _dask-kubernetes: https://kubernetes.dask.org/
.. _dask-yarn: https://yarn.dask.org/en/latest/

.. autosummary::
   LocalCluster
   SpecCluster

.. autoclass:: LocalCluster
   :members:

.. autoclass:: SpecCluster
   :members:

Other
-----

.. autoclass:: as_completed
   :members:

.. autofunction:: distributed.diagnostics.progressbar.progress
.. autofunction:: wait
.. autofunction:: fire_and_forget
.. autofunction:: futures_of

.. currentmodule:: distributed

.. autofunction:: distributed.worker_client
.. autofunction:: distributed.get_worker
.. autofunction:: distributed.get_client
.. autofunction:: distributed.secede
.. autofunction:: distributed.rejoin
.. autofunction:: distributed.print
.. autofunction:: distributed.warn
.. autoclass:: distributed.Reschedule
.. autoclass:: get_task_stream
.. autoclass:: get_task_metadata
.. autoclass:: performance_report

Utilities
---------

.. autoclass:: distributed.utils.Log
.. autoclass:: distributed.utils.Logs

Adaptive
--------

.. currentmodule:: distributed.deploy
.. autoclass:: Adaptive
   :members:


text:
{-# LANGUAGE QuasiQuotes, ScopedTypeVariables #-}
module Handler.EditTrip where

import Import
import Utils.Database
import Utils.Users
import Yesod.Form.Bootstrap3

import qualified Hasql as H
import qualified Data.Text as T

getEditTripR :: Int -> Handler Html
getEditTripR tripId = do
    req <- waiRequest
    restrictToAdmins req
    dbres <- liftIO $ do
        conn <- getDbConn
        H.session conn $ H.tx Nothing $ do
            (reasons :: [(Int,T.Text)]) <- H.listEx $ [H.stmt|
                    SELECT *
                    FROM reasons
                    ORDER BY reason ASC
                |]
            (Identity (reason :: Int)) <- H.singleEx $ [H.stmt|
                    SELECT reason_id
                    FROM trips
                    WHERE id = ?
                |] tripId
            return (reasons,reason)
    case dbres of
        Left err -> error $ show err
        Right (reasons,reason) -> do
            (widget, enctype) <- generateFormPost $ editTripForm reasons reason
            defaultLayout $ do
                setTitle $ "Edit Trip | Brandreth Guestbook"
                $(widgetFile "edittrip")

data TripReason = TripReason Int

editTripAForm :: [(Int,T.Text)] -> Int -> AForm Handler TripReason
editTripAForm reasons reason =
        TripReason <$> areq (selectFieldList sreasons) "Trip Reason"
                                                            (Just reason)
                   <*  bootstrapSubmit ("Submit" :: BootstrapSubmit Text)
    where sreasons = map (\(x,y) -> (y,x)) reasons

editTripForm :: [(Int,T.Text)]
             -> Int
             -> Html
             -> MForm Handler (FormResult TripReason, Widget)
editTripForm reasons reason =
            renderBootstrap3 BootstrapBasicForm $ editTripAForm reasons reason

postEditTripR :: Int -> Handler Html
postEditTripR tripId = do
    req <- waiRequest
    restrictToAdmins req
    dbres <- liftIO $ do
        conn <- getDbConn
        H.session conn $ H.tx Nothing $ do
            (reasons :: [(Int,T.Text)]) <- H.listEx $ [H.stmt|
                    SELECT *
                    FROM reasons
                    ORDER BY reason ASC
                |]
            (Identity (reason :: Int)) <- H.singleEx $ [H.stmt|
                    SELECT reason_id
                    FROM trips
                    WHERE id = ?
                |] tripId
            return (conn, reasons, reason)
    case dbres of
        Left err -> error $ show err
        Right (conn, reasons, reason) -> do
            ((result, _), _) <- runFormPost (editTripForm reasons reason)
            case result of
                FormSuccess (TripReason r) -> do
                    dbres' <- liftIO $ do
                        H.session conn $ H.tx Nothing $ do
                            H.unitEx $ [H.stmt|
                                    UPDATE "trips"
                                    SET reason_id = ?
                                    WHERE id = ?
                                |] r tripId
                    case dbres' of
                        Left err -> error $ show err
                        Right _ -> redirect $ TripR tripId
                FormMissing -> error $ "No form data sent!"
                FormFailure err -> error $ show err


text:
import {Packument, PackumentVersion, Repository} from '@npm/types';

class PackumentBuilder {
  versions: PackumentVersion[] = [];
  name: string;
  tag: string;
  constructor(name: string, tag = 'latest') {
    this.name = name;
    this.tag = tag;
  }
  addVersion(
    versionNumber: string,
    repository?: Repository,
    npmUser = 'soldair'
  ): PackumentBuilder {
    const version = {
      id: this.name,
      name: this.name,
      version: versionNumber,
      npmVersion: '6.11.3',
      nodeVersion: '10.10.0',
      maintainers: [],
      npmUser,
      repository,
      dist: {tarball: 'example.com', shasum: 'abc123'},
    };
    this.versions.push(version);
    return this;
  }
  packument(): Packument {
    const packument = {
      name: this.name,
      'dist-tags': {},
      maintainers: [],
      versions: {},
      time: {modified: '', created: ''},
      license: '',
    } as Packument;
    for (const version of this.versions) {
      packument.versions[version.version] = version;
      packument['dist-tags'][this.tag] = version.version;
    }
    return packument;
  }
}

export function createPackument(
  name: string,
  tag = 'latest'
): PackumentBuilder {
  return new PackumentBuilder(name, tag);
}


text:
package com.example.thread;

import java.util.LinkedList;

class Run1 implements Runnable {
	LinkedList<Email> emailList;

	public Run1(LinkedList<Email> emailList) {
		this.emailList = emailList;
	}

	@Override
	public void run() {
		Email email = null;
		while (true) {
			synchronized (emailList) {
				if (!emailList.isEmpty())
					email = emailList.removeFirst();
				else
					break;
			}
			System.out.println(Thread.currentThread().getName() + ":email--" + email.getUserName());
		}
	}
}

public class EmailTest1 {

	public static void main(String[] args) {
		LinkedList<Email> emailList = new LinkedList<Email>();// 假设list中有1W条数据
		for (int i = 0; i < 10000; i++) {
			emailList.add(new Email(String.valueOf(i)));
		}

		for (int i = 0; i < 4; i++) {
			new Thread(new Run1(emailList)).start();
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Merchello.Core.Models;
using Merchello.Core.Services;
using Merchello.Plugin.Shipping.UPS.Models;
using Umbraco.Core;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;

namespace Merchello.Plugin.Shipping.UPS
{
    public class UpsEvents : ApplicationEventHandler
    {
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication,
                                              ApplicationContext applicationContext)
        {
            base.ApplicationStarted(umbracoApplication, applicationContext);

            LogHelper.Info<UpsEvents>("Initializing UPS Shipping provider registration binding events");

            GatewayProviderService.Saving += delegate(IGatewayProviderService sender, SaveEventArgs<IGatewayProviderSettings> args)
            {
                var key = new Guid("AEB14625-B9DE-4DE8-9C92-99204D340342");
                var provider = args.SavedEntities.FirstOrDefault(x => key == x.Key && !x.HasIdentity);
                if (provider == null) return;

                provider.ExtendedData.SaveProcessorSettings(new UPSProcessorSettings());

            };
        }
    }
}


text:
@interface NDNativeTextElement : NDNativeElement

// Returns true if the view should send |textFieldShouldReturn:| message for the
// given key.
- (BOOL)isTextFieldReturnKey:(NSString *)key;

// Sends |textFieldShouldReturn:| message to the delegate. Just returns YES if
// the element doesn't support this message.
- (BOOL)shouldReturn;

// Tells the delegate it should change the text in range. Just returns YES if
// the element doesn't support checking changes.
- (BOOL)shouldChangeTextInRange:(NSRange)range
              replacementString:(NSString *)text;

// Sends |textViewDidChange:| message to the delegate. Does nothing if the
// element doesn't support this message.
- (void)didChange;

@end


text:
package org.mifos.framework.struts.tags;

import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.mifos.config.Localization;
import org.mifos.framework.security.util.UserContext;
import org.mifos.framework.util.helpers.Constants;

/**
 * Custom tag for input fields of type "img". The tag selects properties file
 * according to the attribute mentioned in the tag.
 */

public class MifosImageTag extends TagSupport {

    private static final long serialVersionUID = 1L;
    protected String moduleName = null;
    protected String id = null;
    private String path = null;

    public MifosImageTag() {
        super();
    }

    /** Used to set the id given in the JSP file */

    @Override
    public void setId(final String id) {
        this.id = id;
    }

    @Override
    public String getId() {
        return this.id;
    }

    /** Used to set the moduleName given in the JSP file */

    public void setModuleName(final String name) {
        this.moduleName = name;
    }

    public String getModuleName() {
        return this.moduleName;
    }

    /** Used to get the corresponding properties fileName using moduleName */

    public String getPropertiesFileName() {
        String moduleName = getModuleName();
        if (moduleName.contains(".")) {
            moduleName = moduleName.substring(moduleName.indexOf(".") + 1, moduleName.length());
        }
        return moduleName + "Images";
    }

    /**
     * Function to render the tag
     *
     * @throws JspException
     */
    @Override
    public int doStartTag() throws JspException {
        JspWriter out = pageContext.getOut();
        UserContext userContext = (UserContext) pageContext.getSession().getAttribute(Constants.USER_CONTEXT_KEY);
        Locale locale = userContext.getPreferredLocale();
        ResourceBundle resource = ResourceBundle.getBundle("org.mifos.application." + getModuleName()
                + ".util.resources." + getPropertiesFileName(), locale);
        path = resource.getString(getId());
        try {
            out.println(render());

        } catch (IOException e) {
            e.printStackTrace();
        }

        return SKIP_BODY;

    }

    public String render() {
        Locale locale = Localization.getInstance().getMainLocale();
        ResourceBundle resource = ResourceBundle.getBundle("org.mifos.application." + getModuleName()
                + ".util.resources." + getPropertiesFileName(), locale);
        path = resource.getString(getId());
        XmlBuilder html = new XmlBuilder();
        html.startTag("html");
        html.startTag("body");
        html.singleTag("img", "src", path);
        html.endTag("body");
        html.endTag("html");
        return html.toString();
    }
}


text:
import {RuntimeError, RuntimeErrorCode} from '../errors';
import {getDocument} from '../render3/interfaces/document';
import {SANITIZER} from '../render3/interfaces/view';
import {getLView} from '../render3/state';
import {renderStringify} from '../render3/util/stringify_utils';
import {TrustedHTML, TrustedScript, TrustedScriptURL} from '../util/security/trusted_type_defs';
import {trustedHTMLFromString, trustedScriptURLFromString} from '../util/security/trusted_types';
import {trustedHTMLFromStringBypass, trustedScriptFromStringBypass, trustedScriptURLFromStringBypass} from '../util/security/trusted_types_bypass';

import {allowSanitizationBypassAndThrow, BypassType, unwrapSafeValue} from './bypass';
import {_sanitizeHtml as _sanitizeHtml} from './html_sanitizer';
import {Sanitizer} from './sanitizer';
import {SecurityContext} from './security';
import {_sanitizeUrl as _sanitizeUrl} from './url_sanitizer';

/**
 * An `html` sanitizer which converts untrusted `html` **string** into trusted string by removing
 * dangerous content.
 *
 * This method parses the `html` and locates potentially dangerous content (such as urls and
 * javascript) and removes it.
 *
 * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustHtml}.
 *
 * @param unsafeHtml untrusted `html`, typically from the user.
 * @returns `html` string which is safe to display to user, because all of the dangerous javascript
 * and urls have been removed.
 *
 * @codeGenApi
 */
export function ɵɵsanitizeHtml(unsafeHtml: any): TrustedHTML|string {
  const sanitizer = getSanitizer();
  if (sanitizer) {
    return trustedHTMLFromStringBypass(sanitizer.sanitize(SecurityContext.HTML, unsafeHtml) || '');
  }
  if (allowSanitizationBypassAndThrow(unsafeHtml, BypassType.Html)) {
    return trustedHTMLFromStringBypass(unwrapSafeValue(unsafeHtml));
  }
  return _sanitizeHtml(getDocument(), renderStringify(unsafeHtml));
}

/**
 * A `style` sanitizer which converts untrusted `style` **string** into trusted string by removing
 * dangerous content.
 *
 * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustStyle}.
 *
 * @param unsafeStyle untrusted `style`, typically from the user.
 * @returns `style` string which is safe to bind to the `style` properties.
 *
 * @codeGenApi
 */
export function ɵɵsanitizeStyle(unsafeStyle: any): string {
  const sanitizer = getSanitizer();
  if (sanitizer) {
    return sanitizer.sanitize(SecurityContext.STYLE, unsafeStyle) || '';
  }
  if (allowSanitizationBypassAndThrow(unsafeStyle, BypassType.Style)) {
    return unwrapSafeValue(unsafeStyle);
  }
  return renderStringify(unsafeStyle);
}

/**
 * A `url` sanitizer which converts untrusted `url` **string** into trusted string by removing
 * dangerous
 * content.
 *
 * This method parses the `url` and locates potentially dangerous content (such as javascript) and
 * removes it.
 *
 * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustUrl}.
 *
 * @param unsafeUrl untrusted `url`, typically from the user.
 * @returns `url` string which is safe to bind to the `src` properties such as `<img src>`, because
 * all of the dangerous javascript has been removed.
 *
 * @codeGenApi
 */
export function ɵɵsanitizeUrl(unsafeUrl: any): string {
  const sanitizer = getSanitizer();
  if (sanitizer) {
    return sanitizer.sanitize(SecurityContext.URL, unsafeUrl) || '';
  }
  if (allowSanitizationBypassAndThrow(unsafeUrl, BypassType.Url)) {
    return unwrapSafeValue(unsafeUrl);
  }
  return _sanitizeUrl(renderStringify(unsafeUrl));
}

/**
 * A `url` sanitizer which only lets trusted `url`s through.
 *
 * This passes only `url`s marked trusted by calling {@link bypassSanitizationTrustResourceUrl}.
 *
 * @param unsafeResourceUrl untrusted `url`, typically from the user.
 * @returns `url` string which is safe to bind to the `src` properties such as `<img src>`, because
 * only trusted `url`s have been allowed to pass.
 *
 * @codeGenApi
 */
export function ɵɵsanitizeResourceUrl(unsafeResourceUrl: any): TrustedScriptURL|string {
  const sanitizer = getSanitizer();
  if (sanitizer) {
    return trustedScriptURLFromStringBypass(
        sanitizer.sanitize(SecurityContext.RESOURCE_URL, unsafeResourceUrl) || '');
  }
  if (allowSanitizationBypassAndThrow(unsafeResourceUrl, BypassType.ResourceUrl)) {
    return trustedScriptURLFromStringBypass(unwrapSafeValue(unsafeResourceUrl));
  }
  throw new RuntimeError(
      RuntimeErrorCode.UNSAFE_VALUE_IN_RESOURCE_URL,
      ngDevMode &&
          'unsafe value used in a resource URL context (see https://g.co/ng/security#xss)');
}

/**
 * A `script` sanitizer which only lets trusted javascript through.
 *
 * This passes only `script`s marked trusted by calling {@link
 * bypassSanitizationTrustScript}.
 *
 * @param unsafeScript untrusted `script`, typically from the user.
 * @returns `url` string which is safe to bind to the `<script>` element such as `<img src>`,
 * because only trusted `scripts` have been allowed to pass.
 *
 * @codeGenApi
 */
export function ɵɵsanitizeScript(unsafeScript: any): TrustedScript|string {
  const sanitizer = getSanitizer();
  if (sanitizer) {
    return trustedScriptFromStringBypass(
        sanitizer.sanitize(SecurityContext.SCRIPT, unsafeScript) || '');
  }
  if (allowSanitizationBypassAndThrow(unsafeScript, BypassType.Script)) {
    return trustedScriptFromStringBypass(unwrapSafeValue(unsafeScript));
  }
  throw new RuntimeError(
      RuntimeErrorCode.UNSAFE_VALUE_IN_SCRIPT,
      ngDevMode && 'unsafe value used in a script context');
}

/**
 * A template tag function for promoting the associated constant literal to a
 * TrustedHTML. Interpolation is explicitly not allowed.
 *
 * @param html constant template literal containing trusted HTML.
 * @returns TrustedHTML wrapping `html`.
 *
 * @security This is a security-sensitive function and should only be used to
 * convert constant values of attributes and properties found in
 * application-provided Angular templates to TrustedHTML.
 *
 * @codeGenApi
 */
export function ɵɵtrustConstantHtml(html: TemplateStringsArray): TrustedHTML|string {
  // The following runtime check ensures that the function was called as a
  // template tag (e.g. ɵɵtrustConstantHtml`content`), without any interpolation
  // (e.g. not ɵɵtrustConstantHtml`content ${variable}`). A TemplateStringsArray
  // is an array with a `raw` property that is also an array. The associated
  // template literal has no interpolation if and only if the length of the
  // TemplateStringsArray is 1.
  if (ngDevMode && (!Array.isArray(html) || !Array.isArray(html.raw) || html.length !== 1)) {
    throw new Error(`Unexpected interpolation in trusted HTML constant: ${html.join('?')}`);
  }
  return trustedHTMLFromString(html[0]);
}

/**
 * A template tag function for promoting the associated constant literal to a
 * TrustedScriptURL. Interpolation is explicitly not allowed.
 *
 * @param url constant template literal containing a trusted script URL.
 * @returns TrustedScriptURL wrapping `url`.
 *
 * @security This is a security-sensitive function and should only be used to
 * convert constant values of attributes and properties found in
 * application-provided Angular templates to TrustedScriptURL.
 *
 * @codeGenApi
 */
export function ɵɵtrustConstantResourceUrl(url: TemplateStringsArray): TrustedScriptURL|string {
  // The following runtime check ensures that the function was called as a
  // template tag (e.g. ɵɵtrustConstantResourceUrl`content`), without any
  // interpolation (e.g. not ɵɵtrustConstantResourceUrl`content ${variable}`). A
  // TemplateStringsArray is an array with a `raw` property that is also an
  // array. The associated template literal has no interpolation if and only if
  // the length of the TemplateStringsArray is 1.
  if (ngDevMode && (!Array.isArray(url) || !Array.isArray(url.raw) || url.length !== 1)) {
    throw new Error(`Unexpected interpolation in trusted URL constant: ${url.join('?')}`);
  }
  return trustedScriptURLFromString(url[0]);
}

/**
 * Detects which sanitizer to use for URL property, based on tag name and prop name.
 *
 * The rules are based on the RESOURCE_URL context config from
 * `packages/compiler/src/schema/dom_security_schema.ts`.
 * If tag and prop names don't match Resource URL schema, use URL sanitizer.
 */
export function getUrlSanitizer(tag: string, prop: string) {
  if ((prop === 'src' &&
       (tag === 'embed' || tag === 'frame' || tag === 'iframe' || tag === 'media' ||
        tag === 'script')) ||
      (prop === 'href' && (tag === 'base' || tag === 'link'))) {
    return ɵɵsanitizeResourceUrl;
  }
  return ɵɵsanitizeUrl;
}

/**
 * Sanitizes URL, selecting sanitizer function based on tag and property names.
 *
 * This function is used in case we can't define security context at compile time, when only prop
 * name is available. This happens when we generate host bindings for Directives/Components. The
 * host element is unknown at compile time, so we defer calculation of specific sanitizer to
 * runtime.
 *
 * @param unsafeUrl untrusted `url`, typically from the user.
 * @param tag target element tag name.
 * @param prop name of the property that contains the value.
 * @returns `url` string which is safe to bind.
 *
 * @codeGenApi
 */
export function ɵɵsanitizeUrlOrResourceUrl(unsafeUrl: any, tag: string, prop: string): any {
  return getUrlSanitizer(tag, prop)(unsafeUrl);
}

export function validateAgainstEventProperties(name: string) {
  if (name.toLowerCase().startsWith('on')) {
    const errorMessage =
        `Binding to event property '${name}' is disallowed for security reasons, ` +
        `please use (${name.slice(2)})=...` +
        `\nIf '${name}' is a directive input, make sure the directive is imported by the` +
        ` current module.`;
    throw new RuntimeError(RuntimeErrorCode.INVALID_EVENT_BINDING, errorMessage);
  }
}

export function validateAgainstEventAttributes(name: string) {
  if (name.toLowerCase().startsWith('on')) {
    const errorMessage =
        `Binding to event attribute '${name}' is disallowed for security reasons, ` +
        `please use (${name.slice(2)})=...`;
    throw new RuntimeError(RuntimeErrorCode.INVALID_EVENT_BINDING, errorMessage);
  }
}

function getSanitizer(): Sanitizer|null {
  const lView = getLView();
  return lView && lView[SANITIZER];
}


text:
Sequel.migration do
  change do
    create_table :reg_c481 do
      column :id, :Bignum, primary_key: true
      column :id_pai, :Bignum, index: true, null: false
      column :cst_pis, String, size: 2
      column :vl_item, BigDecimal, size: [18, 2]
      column :vl_bc_pis, BigDecimal, size: [18, 2]
      column :aliq_pis, BigDecimal, size: [18, 4]
      column :quant_bc_pis, BigDecimal, size: [18, 3]
      column :aliq_pis_quant, BigDecimal, size: [18, 4]
      column :vl_pis, BigDecimal, size: [18, 2]
      column :cod_item, String, size: 60
      column :cod_cta, String, size: 255
      column :cnpj_pai, String, size: 14, index: true
    end
  end
end


text:
package builder

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io/ioutil"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"time"

	s2iapi "github.com/openshift/source-to-image/pkg/api"
	"github.com/openshift/source-to-image/pkg/api/describe"
	"github.com/openshift/source-to-image/pkg/api/validation"
	s2ibuild "github.com/openshift/source-to-image/pkg/build"
	s2i "github.com/openshift/source-to-image/pkg/build/strategies"
	"github.com/openshift/source-to-image/pkg/docker"
	s2igit "github.com/openshift/source-to-image/pkg/scm/git"

	buildapi "github.com/openshift/origin/pkg/build/apis/build"
	"github.com/openshift/origin/pkg/build/builder/cmd/dockercfg"
	"github.com/openshift/origin/pkg/build/builder/timing"
	"github.com/openshift/origin/pkg/build/controller/strategy"
	"github.com/openshift/origin/pkg/build/util"
	"github.com/openshift/origin/pkg/client"
	"github.com/openshift/origin/pkg/generate/git"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// builderFactory is the internal interface to decouple S2I-specific code from Origin builder code
type builderFactory interface {
	// Create S2I Builder based on S2I configuration
	Builder(config *s2iapi.Config, overrides s2ibuild.Overrides) (s2ibuild.Builder, s2iapi.BuildInfo, error)
}

// validator is the interval interface to decouple S2I-specific code from Origin builder code
type validator interface {
	// Perform validation of S2I configuration, returns slice of validation errors
	ValidateConfig(config *s2iapi.Config) []validation.Error
}

// runtimeBuilderFactory is the default implementation of stiBuilderFactory
type runtimeBuilderFactory struct{}

// Builder delegates execution to S2I-specific code
func (_ runtimeBuilderFactory) Builder(config *s2iapi.Config, overrides s2ibuild.Overrides) (s2ibuild.Builder, s2iapi.BuildInfo, error) {
	client, err := docker.NewEngineAPIClient(config.DockerConfig)
	if err != nil {
		return nil, s2iapi.BuildInfo{}, err
	}
	builder, buildInfo, err := s2i.Strategy(client, config, overrides)
	return builder, buildInfo, err
}

// runtimeConfigValidator is the default implementation of stiConfigValidator
type runtimeConfigValidator struct{}

// ValidateConfig delegates execution to S2I-specific code
func (_ runtimeConfigValidator) ValidateConfig(config *s2iapi.Config) []validation.Error {
	return validation.ValidateConfig(config)
}

// S2IBuilder performs an STI build given the build object
type S2IBuilder struct {
	builder      builderFactory
	validator    validator
	gitClient    GitClient
	dockerClient DockerClient
	dockerSocket string
	build        *buildapi.Build
	client       client.BuildInterface
	cgLimits     *s2iapi.CGroupLimits
}

// NewS2IBuilder creates a new STIBuilder instance
func NewS2IBuilder(dockerClient DockerClient, dockerSocket string, buildsClient client.BuildInterface, build *buildapi.Build,
	gitClient GitClient, cgLimits *s2iapi.CGroupLimits) *S2IBuilder {
	// delegate to internal implementation passing default implementation of builderFactory and validator
	return newS2IBuilder(dockerClient, dockerSocket, buildsClient, build, gitClient, runtimeBuilderFactory{}, runtimeConfigValidator{}, cgLimits)
}

// newS2IBuilder is the internal factory function to create STIBuilder based on parameters. Used for testing.
func newS2IBuilder(dockerClient DockerClient, dockerSocket string, buildsClient client.BuildInterface, build *buildapi.Build,
	gitClient GitClient, builder builderFactory, validator validator, cgLimits *s2iapi.CGroupLimits) *S2IBuilder {
	// just create instance
	return &S2IBuilder{
		builder:      builder,
		validator:    validator,
		gitClient:    gitClient,
		dockerClient: dockerClient,
		dockerSocket: dockerSocket,
		build:        build,
		client:       buildsClient,
		cgLimits:     cgLimits,
	}
}

// Build executes STI build based on configured builder, S2I builder factory
// and S2I config validator
func (s *S2IBuilder) Build() error {

	var err error
	ctx := timing.NewContext(context.Background())
	defer func() {
		s.build.Status.Stages = buildapi.AppendStageAndStepInfo(s.build.Status.Stages, timing.GetStages(ctx))
		handleBuildStatusUpdate(s.build, s.client, nil)
	}()

	if s.build.Spec.Strategy.SourceStrategy == nil {
		return errors.New("the source to image builder must be used with the source strategy")
	}

	buildDir, err := ioutil.TempDir("", "s2i-build")
	if err != nil {
		return err
	}
	srcDir := filepath.Join(buildDir, s2iapi.Source)
	if err = os.MkdirAll(srcDir, os.ModePerm); err != nil {
		return err
	}

	var push bool
	// if there is no output target, set one up so the docker build logic
	// (which requires a tag) will still work, but we won't push it at the end.
	if s.build.Spec.Output.To == nil || len(s.build.Spec.Output.To.Name) == 0 {
		s.build.Status.OutputDockerImageReference = s.build.Name
	} else {
		push = true
	}
	pushTag := s.build.Status.OutputDockerImageReference

	// fetch source
	sourceInfo, err := fetchSource(ctx, s.dockerClient, srcDir, s.build, initialURLCheckTimeout, os.Stdin, s.gitClient)

	if err != nil {
		switch err.(type) {
		case contextDirNotFoundError:
			s.build.Status.Phase = buildapi.BuildPhaseFailed
			s.build.Status.Reason = buildapi.StatusReasonInvalidContextDirectory
			s.build.Status.Message = buildapi.StatusMessageInvalidContextDirectory
		default:
			s.build.Status.Phase = buildapi.BuildPhaseFailed
			s.build.Status.Reason = buildapi.StatusReasonFetchSourceFailed
			s.build.Status.Message = buildapi.StatusMessageFetchSourceFailed
		}
		handleBuildStatusUpdate(s.build, s.client, nil)
		return err
	}

	contextDir := ""
	if len(s.build.Spec.Source.ContextDir) > 0 {
		contextDir = filepath.Clean(s.build.Spec.Source.ContextDir)
		if contextDir == "." || contextDir == "/" {
			contextDir = ""
		}
		if len(contextDir) > 0 {
			// if we're building out of a context dir, we need to use a different working
			// directory from where we put the source code because s2i is going to copy
			// from the context dir to the workdir, and if the workdir is a parent of the
			// context dir, we end up with a directory that contains 2 copies of the
			// input source code.
			buildDir, err = ioutil.TempDir("", "s2i-build-context")
		}
		if sourceInfo != nil {
			sourceInfo.ContextDir = s.build.Spec.Source.ContextDir
		}
	}

	var s2iSourceInfo *s2igit.SourceInfo
	if sourceInfo != nil {
		s2iSourceInfo = &sourceInfo.SourceInfo
		revision := updateBuildRevision(s.build, sourceInfo)
		handleBuildStatusUpdate(s.build, s.client, revision)
	}

	injections := s2iapi.VolumeList{}
	for _, s := range s.build.Spec.Source.Secrets {
		glog.V(3).Infof("Injecting secret %q into a build into %q", s.Secret.Name, filepath.Clean(s.DestinationDir))
		secretSourcePath := filepath.Join(strategy.SecretBuildSourceBaseMountPath, s.Secret.Name)
		injections = append(injections, s2iapi.VolumeSpec{
			Source:      secretSourcePath,
			Destination: s.DestinationDir,
		})
	}

	buildTag := randomBuildTag(s.build.Namespace, s.build.Name)
	scriptDownloadProxyConfig, err := scriptProxyConfig(s.build)
	if err != nil {
		return err
	}
	if scriptDownloadProxyConfig != nil {
		glog.V(0).Infof("Using HTTP proxy %v and HTTPS proxy %v for script download",
			util.SafeForLoggingURL(scriptDownloadProxyConfig.HTTPProxy),
			util.SafeForLoggingURL(scriptDownloadProxyConfig.HTTPSProxy),
		)
	}

	var incremental bool
	if s.build.Spec.Strategy.SourceStrategy.Incremental != nil {
		incremental = *s.build.Spec.Strategy.SourceStrategy.Incremental
	}
	config := &s2iapi.Config{
		// Save some processing time by not cleaning up (the container will go away anyway)
		PreserveWorkingDir: true,
		WorkingDir:         buildDir,
		DockerConfig:       &s2iapi.DockerConfig{Endpoint: s.dockerSocket},
		DockerCfgPath:      os.Getenv(dockercfg.PullAuthType),
		LabelNamespace:     buildapi.DefaultDockerLabelNamespace,

		ScriptsURL: s.build.Spec.Strategy.SourceStrategy.Scripts,

		BuilderImage:       s.build.Spec.Strategy.SourceStrategy.From.Name,
		Incremental:        incremental,
		IncrementalFromTag: pushTag,

		Environment:       buildEnvVars(s.build, sourceInfo),
		Labels:            buildLabels(s.build),
		DockerNetworkMode: getDockerNetworkMode(),

		Source:     &s2igit.URL{URL: url.URL{Path: srcDir}, Type: s2igit.URLTypeLocal},
		ContextDir: contextDir,
		SourceInfo: s2iSourceInfo,
		ForceCopy:  true,
		Injections: injections,

		Tag: buildTag,

		CGroupLimits:              s.cgLimits,
		ScriptDownloadProxyConfig: scriptDownloadProxyConfig,
		BlockOnBuild:              true,
	}

	if s.build.Spec.Strategy.SourceStrategy.ForcePull {
		glog.V(4).Infof("With force pull true, setting policies to %s", s2iapi.PullAlways)
		config.BuilderPullPolicy = s2iapi.PullAlways
		config.RuntimeImagePullPolicy = s2iapi.PullAlways
	} else {
		glog.V(4).Infof("With force pull false, setting policies to %s", s2iapi.PullIfNotPresent)
		config.BuilderPullPolicy = s2iapi.PullIfNotPresent
		config.RuntimeImagePullPolicy = s2iapi.PullIfNotPresent
	}
	config.PreviousImagePullPolicy = s2iapi.PullAlways

	allowedUIDs := os.Getenv(buildapi.AllowedUIDs)
	glog.V(4).Infof("The value of %s is [%s]", buildapi.AllowedUIDs, allowedUIDs)
	if len(allowedUIDs) > 0 {
		err = config.AllowedUIDs.Set(allowedUIDs)
		if err != nil {
			return err
		}
	}
	dropCaps := os.Getenv(buildapi.DropCapabilities)
	glog.V(4).Infof("The value of %s is [%s]", buildapi.DropCapabilities, dropCaps)
	if len(dropCaps) > 0 {
		config.DropCapabilities = strings.Split(dropCaps, ",")
	}

	if s.build.Spec.Strategy.SourceStrategy.RuntimeImage != nil {
		runtimeImageName := s.build.Spec.Strategy.SourceStrategy.RuntimeImage.Name
		config.RuntimeImage = runtimeImageName
		t, _ := dockercfg.NewHelper().GetDockerAuth(runtimeImageName, dockercfg.PullAuthType)
		config.RuntimeAuthentication = s2iapi.AuthConfig{Username: t.Username, Password: t.Password, Email: t.Email, ServerAddress: t.ServerAddress}
		config.RuntimeArtifacts = copyToVolumeList(s.build.Spec.Strategy.SourceStrategy.RuntimeArtifacts)
	}
	// If DockerCfgPath is provided in buildapi.Config, then attempt to read the
	// dockercfg file and get the authentication for pulling the builder image.
	t, _ := dockercfg.NewHelper().GetDockerAuth(config.BuilderImage, dockercfg.PullAuthType)
	config.PullAuthentication = s2iapi.AuthConfig{Username: t.Username, Password: t.Password, Email: t.Email, ServerAddress: t.ServerAddress}
	t, _ = dockercfg.NewHelper().GetDockerAuth(pushTag, dockercfg.PushAuthType)
	config.IncrementalAuthentication = s2iapi.AuthConfig{Username: t.Username, Password: t.Password, Email: t.Email, ServerAddress: t.ServerAddress}

	if errs := s.validator.ValidateConfig(config); len(errs) != 0 {
		var buffer bytes.Buffer
		for _, ve := range errs {
			buffer.WriteString(ve.Error())
			buffer.WriteString(", ")
		}
		return errors.New(buffer.String())
	}

	client, err := docker.NewEngineAPIClient(config.DockerConfig)
	if err != nil {
		return err
	}
	if glog.Is(4) {
		redactedConfig := util.SafeForLoggingS2IConfig(config)
		glog.V(4).Infof("Creating a new S2I builder with config: %#v\n", describe.Config(client, redactedConfig))
	}
	builder, buildInfo, err := s.builder.Builder(config, s2ibuild.Overrides{Downloader: nil})
	if err != nil {
		s.build.Status.Phase = buildapi.BuildPhaseFailed
		s.build.Status.Reason, s.build.Status.Message = convertS2IFailureType(
			buildInfo.FailureReason.Reason,
			buildInfo.FailureReason.Message,
		)
		handleBuildStatusUpdate(s.build, s.client, nil)
		return err
	}

	glog.V(4).Infof("Starting S2I build from %s/%s BuildConfig ...", s.build.Namespace, s.build.Name)
	startTime := metav1.Now()
	result, err := builder.Build(config)

	for _, stage := range result.BuildInfo.Stages {
		for _, step := range stage.Steps {
			timing.RecordNewStep(ctx, buildapi.StageName(stage.Name), buildapi.StepName(step.Name), metav1.NewTime(step.StartTime), metav1.NewTime(step.StartTime.Add(time.Duration(step.DurationMilliseconds)*time.Millisecond)))
		}
	}

	if err != nil {
		s.build.Status.Phase = buildapi.BuildPhaseFailed
		s.build.Status.Reason, s.build.Status.Message = convertS2IFailureType(
			result.BuildInfo.FailureReason.Reason,
			result.BuildInfo.FailureReason.Message,
		)

		handleBuildStatusUpdate(s.build, s.client, nil)
		return err
	}

	cName := containerName("s2i", s.build.Name, s.build.Namespace, "post-commit")
	startTime = metav1.Now()
	err = execPostCommitHook(s.dockerClient, s.build.Spec.PostCommit, buildTag, cName)

	timing.RecordNewStep(ctx, buildapi.StagePostCommit, buildapi.StepExecPostCommitHook, startTime, metav1.Now())

	if err != nil {
		s.build.Status.Phase = buildapi.BuildPhaseFailed
		s.build.Status.Reason = buildapi.StatusReasonPostCommitHookFailed
		s.build.Status.Message = buildapi.StatusMessagePostCommitHookFailed
		handleBuildStatusUpdate(s.build, s.client, nil)
		return err
	}

	if push {
		if err = tagImage(s.dockerClient, buildTag, pushTag); err != nil {
			return err
		}
	}

	if err = removeImage(s.dockerClient, buildTag); err != nil {
		glog.V(0).Infof("warning: Failed to remove temporary build tag %v: %v", buildTag, err)
	}

	if push {
		// Get the Docker push authentication
		pushAuthConfig, authPresent := dockercfg.NewHelper().GetDockerAuth(
			pushTag,
			dockercfg.PushAuthType,
		)
		if authPresent {
			glog.V(3).Infof("Using provided push secret for pushing %s image", pushTag)
		} else {
			glog.V(3).Infof("No push secret provided")
		}
		glog.V(0).Infof("\nPushing image %s ...", pushTag)
		startTime = metav1.Now()
		digest, err := pushImage(s.dockerClient, pushTag, pushAuthConfig)

		timing.RecordNewStep(ctx, buildapi.StagePushImage, buildapi.StepPushImage, startTime, metav1.Now())

		if err != nil {
			s.build.Status.Phase = buildapi.BuildPhaseFailed
			s.build.Status.Reason = buildapi.StatusReasonPushImageToRegistryFailed
			s.build.Status.Message = buildapi.StatusMessagePushImageToRegistryFailed
			handleBuildStatusUpdate(s.build, s.client, nil)
			return reportPushFailure(err, authPresent, pushAuthConfig)
		}

		if len(digest) > 0 {
			s.build.Status.Output.To = &buildapi.BuildStatusOutputTo{
				ImageDigest: digest,
			}
			handleBuildStatusUpdate(s.build, s.client, nil)
		}
		glog.V(0).Infof("Push successful")
	}
	return nil
}

type downloader struct {
	sourceInfo *s2igit.SourceInfo
}

// Download no-ops (because we already downloaded the source to the right location)
// and returns the previously computed sourceInfo for the source.
func (d *downloader) Download(config *s2iapi.Config) (*s2igit.SourceInfo, error) {
	config.WorkingSourceDir = config.Source.LocalPath()

	return d.sourceInfo, nil
}

// buildEnvVars returns a map with build metadata to be inserted into Docker
// images produced by build. It transforms the output from buildInfo into the
// input format expected by s2iapi.Config.Environment.
// Note that using a map has at least two downsides:
// 1. The order of metadata KeyValue pairs is lost;
// 2. In case of repeated Keys, the last Value takes precedence right here,
//    instead of deferring what to do with repeated environment variables to the
//    Docker runtime.
func buildEnvVars(build *buildapi.Build, sourceInfo *git.SourceInfo) s2iapi.EnvironmentList {
	bi := buildInfo(build, sourceInfo)
	envVars := &s2iapi.EnvironmentList{}
	for _, item := range bi {
		envVars.Set(fmt.Sprintf("%s=%s", item.Key, item.Value))
	}
	return *envVars
}

func buildLabels(build *buildapi.Build) map[string]string {
	labels := make(map[string]string)
	addBuildLabels(labels, build)
	for _, lbl := range build.Spec.Output.ImageLabels {
		labels[lbl.Name] = lbl.Value
	}
	return labels
}

// scriptProxyConfig determines a proxy configuration for downloading
// scripts from a URL. For now, it uses environment variables passed in
// the strategy's environment. There is no preference given to either lowercase
// or uppercase form of the variable.
func scriptProxyConfig(build *buildapi.Build) (*s2iapi.ProxyConfig, error) {
	httpProxy := ""
	httpsProxy := ""
	for _, env := range build.Spec.Strategy.SourceStrategy.Env {
		switch env.Name {
		case "HTTP_PROXY", "http_proxy":
			httpProxy = env.Value
		case "HTTPS_PROXY", "https_proxy":
			httpsProxy = env.Value
		}
	}
	if len(httpProxy) == 0 && len(httpsProxy) == 0 {
		return nil, nil
	}
	config := &s2iapi.ProxyConfig{}
	if len(httpProxy) > 0 {
		proxyURL, err := util.ParseProxyURL(httpProxy)
		if err != nil {
			return nil, err
		}
		config.HTTPProxy = proxyURL
	}
	if len(httpsProxy) > 0 {
		proxyURL, err := util.ParseProxyURL(httpsProxy)
		if err != nil {
			return nil, err
		}
		config.HTTPSProxy = proxyURL
	}
	return config, nil
}

// copyToVolumeList copies the artifacts set in the build config to the
// VolumeList struct in the s2iapi.Config
func copyToVolumeList(artifactsMapping []buildapi.ImageSourcePath) (volumeList s2iapi.VolumeList) {
	for _, mappedPath := range artifactsMapping {
		volumeList = append(volumeList, s2iapi.VolumeSpec{
			Source:      mappedPath.SourcePath,
			Destination: mappedPath.DestinationDir,
		})
	}
	return
}

func convertS2IFailureType(reason s2iapi.StepFailureReason, message s2iapi.StepFailureMessage) (buildapi.StatusReason, string) {
	return buildapi.StatusReason(reason), fmt.Sprintf("%s", message)
}


text:
function [newPos] = setMotionAKD(Position,Traverse)
%SETMOTIONAKD Set a position on the AKD drive
% setMotionAKD(Position,Traverse) takes a position in mm and constructs a
% motion task on the specified AKD drive. The position input can have a
% maximum accuracy of 3 decimals.
%
% The "Set motion task control" section defines whether the position input
% is either relative or absolute. This is currently set to absolute.
%
% Example:
%     setMotionAKD(1000.032,TyM) sets the motion task to an absolute
%     position of 1000.032 mm for the y-axis of the traverse.
%
% The "Set motion task number" section appends the motion task with a
% number (currently set to 12) which will be overwritten every time this
% function is executed. When this function is executed, the resulting
% motion task will be visible in the Kollmorgen workbench under the
% corresponding number.
%
% See also moveAKD

% Copyright (c) 2015, Erwin Hamminga and The University of Adelaide

% Thanks Kees Stroeken, author of ModBusYaskawa
% <http://www.mathworks.com/matlabcentral/fileexchange/44662>
% for the inspiration to construct this function.
%% Define constants
tcpip_pipe=Traverse;
ProtID = uint16(0);     % 16-bit Protocol ID (0 for ModBus)
UnitID = uint8(0);      % 8-bit Unit ID (0) unit identifier (previous 'device address'). The device is accessed directly via IP address, therefore this parameter
                        % has no function and may be set to 0xFF. Exception: If the communication is performed via gateway the device
                        % address must be set as before.
pos = Position*1000;

%% Set motion task control (MT.CNTL)
% define message values
transID = uint16(1);    % 16b Transaction Identifier
nBytes = uint16(11);     % 16-bit Number of 8-bit blocks of data to be sent (6)

FunCod = uint8(16);      % 8-bit Function code: read (3) or write (16)
Index = uint16(532);    % 16-bit Start address of the register (588)
nRegisters = uint16(2); % 16-bit Number of registers (4)
DataSize = int8(4);
MT.CNTL = uint32(0); % relative pos(7) or absolute pos(0)

% transfer actual message (order is important)
fwrite(tcpip_pipe, transID,'int16');
fwrite(tcpip_pipe, ProtID,'int16');
fwrite(tcpip_pipe, nBytes,'int16');
fwrite(tcpip_pipe, UnitID,'int8');
fwrite(tcpip_pipe, FunCod,'int8');
fwrite(tcpip_pipe, Index,'int16');
fwrite(tcpip_pipe, nRegisters,'int16');
fwrite(tcpip_pipe, DataSize,'int8');
fwrite(tcpip_pipe, MT.CNTL,'int32');

while ~tcpip_pipe.BytesAvailable,end
tcpip_pipe.BytesAvailable;
res=uint8(fread(tcpip_pipe,tcpip_pipe.BytesAvailable)); %the result is produced in 8 bit integers, hence the "uint8"

% a pair of 8-bit integers needs to be combined into one 16-bit integer.
% This is done using typecast. The Swapbytes function is used to format
% the output from little-endian to big-endian.
res_proc=swapbytes(typecast(res(length(res)-(nRegisters*2-1):length(res)),'int32'));

%% Set motion task number (MT.NUM)
% define message values
transID = uint16(transID+1);    % 16b Transaction Identifier
nBytes = uint16(11);     % 16-bit Number of 8-bit blocks of data to be sent (6)
FunCod = uint8(16);      % 8-bit Function code: read (3) or write (16)
Index = uint16(548);    % 16-bit Start address of the register (588)
nRegisters = uint16(2); % 16-bit Number of registers (4)
DataSize = int8(4);
MT.NUM = uint32(12);

% transfer actual message (order is important)
fwrite(tcpip_pipe, transID,'int16');
fwrite(tcpip_pipe, ProtID,'int16');
fwrite(tcpip_pipe, nBytes,'int16');
fwrite(tcpip_pipe, UnitID,'int8');
fwrite(tcpip_pipe, FunCod,'int8');
fwrite(tcpip_pipe, Index,'int16');
fwrite(tcpip_pipe, nRegisters,'int16');
fwrite(tcpip_pipe, DataSize,'int8');
fwrite(tcpip_pipe, MT.NUM,'int32');

while ~tcpip_pipe.BytesAvailable,end
tcpip_pipe.BytesAvailable;
res=uint8(fread(tcpip_pipe,tcpip_pipe.BytesAvailable)); %the result is produced in 8 bit integers, hence the "uint8"

% a pair of 8-bit integers needs to be combined into one 16-bit integer.
% This is done using typecast. The Swapbytes function is used to format
% the output from little-endian to big-endian.
res_proc=swapbytes(typecast(res(length(res)-(nRegisters*2-1):length(res)),'int32'));

%% Set motion task velocity (MT.V) might try 64-bit
% define message values
transID = uint16(transID+1);    % 16b Transaction Identifier
nBytes = uint16(11);     % 16-bit Number of 8-bit blocks of data to be sent (6)
FunCod = uint8(16);      % 8-bit Function code: read (3) or write (16)
Index = uint16(566);    % 16-bit Start address of the register (588)
nRegisters = uint16(2); % 16-bit Number of registers (4)
DataSize = int8(4);
MT.V = 100000;  % actual velocity in rpm: MT.V/1000 with 3 dec. accuracy.

% transfer actual message (order is important)
fwrite(tcpip_pipe, transID,'int16');
fwrite(tcpip_pipe, ProtID,'int16');
fwrite(tcpip_pipe, nBytes,'int16');
fwrite(tcpip_pipe, UnitID,'int8');
fwrite(tcpip_pipe, FunCod,'int8');
fwrite(tcpip_pipe, Index,'int16');
fwrite(tcpip_pipe, nRegisters,'int16');
fwrite(tcpip_pipe, DataSize,'int8');
fwrite(tcpip_pipe, MT.V,'int32');

while ~tcpip_pipe.BytesAvailable,end
tcpip_pipe.BytesAvailable;
res=uint8(fread(tcpip_pipe,tcpip_pipe.BytesAvailable)); %the result is produced in 8 bit integers, hence the "uint8"

% a pair of 8-bit integers needs to be combined into one 16-bit integer.
% This is done using typecast. The Swapbytes function is used to format
% the output from little-endian to big-endian.
res_proc=swapbytes(typecast(res(length(res)-(nRegisters*2-1):length(res)),'int32'));

%% Set motion task acceleration (MT.ACC)
% define message values
transID = uint16(transID+1);    % 16b Transaction Identifier
nBytes = uint16(15);     % 16-bit Number of 8-bit blocks of data to be sent (6)
FunCod = uint8(16);      % 8-bit Function code: read (3) or write (16)
Index = uint16(526);    % 16-bit Start address of the register (588)
nRegisters = uint16(4); % 16-bit Number of registers (4)
DataSize = int8(8);
MT.ACC = 10000000; %rpm/s, is read as MT.ACC/1000 with 3 dec. accuracy

% transfer actual message (order is important)
fwrite(tcpip_pipe, transID,'int16');
fwrite(tcpip_pipe, ProtID,'int16');
fwrite(tcpip_pipe, nBytes,'int16');
fwrite(tcpip_pipe, UnitID,'int8');
fwrite(tcpip_pipe, FunCod,'int8');
fwrite(tcpip_pipe, Index,'int16');
fwrite(tcpip_pipe, nRegisters,'int16');
fwrite(tcpip_pipe, DataSize,'int8');
fwrite(tcpip_pipe, 0,'uint16')
fwrite(tcpip_pipe, 0,'uint16')
fwrite(tcpip_pipe, MT.ACC,'uint32');

while ~tcpip_pipe.BytesAvailable,end
tcpip_pipe.BytesAvailable;
res=uint8(fread(tcpip_pipe,tcpip_pipe.BytesAvailable)); %the result is produced in 8 bit integers, hence the "uint8"

% a pair of 8-bit integers needs to be combined into one 16-bit integer.
% This is done using typecast. The Swapbytes function is used to format
% the output from little-endian to big-endian.
res_proc=swapbytes(typecast(res(length(res)-(nRegisters*2-1):length(res)),'int32'));

%% Set motion task deceleration (MT.DEC)
% define message values
transID = uint16(transID+1);    % 16b Transaction Identifier
nBytes = uint16(15);     % 16-bit Number of 8-bit blocks of data to be sent (6)
FunCod = uint8(16);      % 8-bit Function code: read (3) or write (16)
Index = uint16(536);    % 16-bit Start address of the register (588)
nRegisters = uint16(4); % 16-bit Number of registers (4)
DataSize = int8(8);
MT.DEC = uint32(10000000); % rpm/s, is read as MT.DEC/1000 with 3 dec. accuracy

% transfer actual message (order is important)
fwrite(tcpip_pipe, transID,'int16');
fwrite(tcpip_pipe, ProtID,'int16');
fwrite(tcpip_pipe, nBytes,'int16');
fwrite(tcpip_pipe, UnitID,'int8');
fwrite(tcpip_pipe, FunCod,'int8');
fwrite(tcpip_pipe, Index,'int16');
fwrite(tcpip_pipe, nRegisters,'int16');
fwrite(tcpip_pipe, DataSize,'int8');
fwrite(tcpip_pipe, 0,'uint16')
fwrite(tcpip_pipe, 0,'uint16')
fwrite(tcpip_pipe, MT.DEC,'uint32');

while ~tcpip_pipe.BytesAvailable,end
tcpip_pipe.BytesAvailable;
res=uint8(fread(tcpip_pipe,tcpip_pipe.BytesAvailable)); %the result is produced in 8 bit integers, hence the "uint8"

% a pair of 8-bit integers needs to be combined into one 16-bit integer.
% This is done using typecast. The Swapbytes function is used to format
% the output from little-endian to big-endian.
res_proc=swapbytes(typecast(res(length(res)-(nRegisters*2-1):length(res)),'int32'));

%% Set motion task position (MT.P)
% define message values
transID = uint16(transID+1);    % 16b Transaction Identifier
FunCod = uint8(16);      % 8-bit Function code: read (3)
Index = uint16(550);    % 16-bit Start address of the register (588)
nRegisters = uint16(4); % 16-bit Number of registers (4)
MT.P = pos; % abs or rel depending on MT.CNTL setting. Actual pos: MT.P/1000 with 3 dec. accuracy
DataSize = uint8(8);
nBytes = uint16(15);

% transfer actual message (order is important)
fwrite(tcpip_pipe, transID,'uint16');
fwrite(tcpip_pipe, ProtID,'uint16');
fwrite(tcpip_pipe, nBytes,'uint16');
fwrite(tcpip_pipe, UnitID,'uint8');
fwrite(tcpip_pipe, FunCod,'uint8');
fwrite(tcpip_pipe, Index,'uint16');
fwrite(tcpip_pipe, nRegisters,'uint16');
fwrite(tcpip_pipe, DataSize,'uint8');
fwrite(tcpip_pipe, 0,'uint16')
fwrite(tcpip_pipe, 0,'uint16')
fwrite(tcpip_pipe, MT.P,'uint32');

while ~tcpip_pipe.BytesAvailable,end
tcpip_pipe.BytesAvailable;
res=uint8(fread(tcpip_pipe,tcpip_pipe.BytesAvailable)); %the result is produced in 8 bit integers, hence the "uint8"

% a pair of 8-bit integers needs to be combined into one 16-bit integer.
% This is done using typecast. The Swapbytes function is used to format
% the output from little-endian to big-endian.
res_proc=swapbytes(typecast(res(length(res)-(nRegisters*2-1):length(res)),'int32'));

%% Set motion task confirmation (MT.SET)
% define message values
transID = uint16(transID+1);    % 16b Transaction Identifier
nBytes = uint16(11);     % 16-bit Number of 8-bit blocks of data to be sent (6)
FunCod = uint8(16);      % 8-bit Function code: read (3) or write (16)
Index = uint16(554);    % 16-bit Start address of the register (588)
nRegisters = uint16(2); % 16-bit Number of registers (4)
DataSize = int8(4);
MT.SET = uint32(1); %set

% transfer actual message (order is important)
fwrite(tcpip_pipe, transID,'int16');
fwrite(tcpip_pipe, ProtID,'int16');
fwrite(tcpip_pipe, nBytes,'int16');
fwrite(tcpip_pipe, UnitID,'int8');
fwrite(tcpip_pipe, FunCod,'int8');
fwrite(tcpip_pipe, Index,'int16');
fwrite(tcpip_pipe, nRegisters,'int16');
fwrite(tcpip_pipe, DataSize,'int8');
fwrite(tcpip_pipe, MT.SET,'int32');

while ~tcpip_pipe.BytesAvailable,end
tcpip_pipe.BytesAvailable;
res=uint8(fread(tcpip_pipe,tcpip_pipe.BytesAvailable)); %the result is produced in 8 bit integers, hence the "uint8"

% a pair of 8-bit integers needs to be combined into one 16-bit integer.
% This is done using typecast. The Swapbytes function is used to format
% the output from little-endian to big-endian.
res_proc=swapbytes(typecast(res(length(res)-(nRegisters*2-1):length(res)),'int32'));

%% display feedback
if MT.CNTL==0
    motionTaskCtrl='absolute';
else
    motionTaskCtrl='relative';
end
disp(['Motion task position set to ',num2str(Position),' mm ',motionTaskCtrl]);


text:
% Copyright 2013 The MathWorks, Inc.

classdef FooTest < TestCase
    methods
        function object = FooTest(name)
            object = object@TestCase(name);
        end
        function test_sanity(object)
            assertEqual(0, 0)
        end
    end
end


text:
/**
 *
 */
export interface IFilter {
    transform?(expression: string, request: Express.Request, response: Express.Response): any;
}


text:
class G4Run;

/// Run action class
///
/// It accumulates statistic and computes dispersion of the energy deposit
/// and track lengths of charged particles with use of analysis tools:
/// H1D histograms are created in BeginOfRunAction() for the following
/// physics quantities:
/// - Edep in absorber
/// - Edep in gap
/// - Track length in absorber
/// - Track length in gap
/// The same values are also saved in the ntuple.
/// The histograms and ntuple are saved in the output file in a format
/// accoring to a selected technology in B4Analysis.hh.
///
/// In EndOfRunAction(), the accumulated statistic and computed
/// dispersion is printed.
///

class RunAction : public G4UserRunAction
{
public:
    RunAction();
    virtual ~RunAction();

    virtual void BeginOfRunAction(const G4Run*);
    virtual void   EndOfRunAction(const G4Run*);

    //--------------------------------------------------------------------------------
    //      Initial Simulated Particles
    std::vector<double>   iSimulatedParticle_T; // MeV

    void SetInitialParticleKineticEnergy(std::vector<double> vec) {iSimulatedParticle_T = vec;};

    //--------------------------------------------------------------------------------
    //      Detectable energy

    std::vector<double>   detectableEnergy; // MeV

    void SetDetectableEnergy(std::vector<double> vec) {detectableEnergy = vec;};

    //--------------------------------------------------------------------------------
    //      CAKE
    std::vector<int>    CAKE_detNr;
    std::vector<int>    CAKE_ringNr;
    std::vector<int>    CAKE_sectorNr;
    std::vector<double> CAKE_hitRadius;

    void SetCAKE_detNr(std::vector<int> vec)     {CAKE_detNr = vec;};
    void SetCAKE_ringNr(std::vector<int> vec)    {CAKE_ringNr = vec;};
    void SetCAKE_sectorNr(std::vector<int> vec)  {CAKE_sectorNr = vec;};
    void SetCAKE_hitRadius(std::vector<double> vec)  {CAKE_hitRadius = vec;};

    //--------------------------------------------------------------------------------
    //      Reaction variables
    std::vector<int>    nReactionProducts;
    std::vector<int>    reaction_Z;
    std::vector<double> reaction_A;
    std::vector<double> reaction_P;
    std::vector<double> reaction_T;
    std::vector<double> reaction_Ex;

    void SetNReactionProducts(int n)
    {
        nReactionProducts.clear();
        nReactionProducts.push_back(n);
    };

    void SetReaction_Z(std::vector<int> vec)    {reaction_Z = vec;};
    void SetReaction_A(std::vector<double> vec) {reaction_A = vec;};
    void SetReaction_P(std::vector<double> vec) {reaction_P = vec;};
    void SetReaction_T(std::vector<double> vec) {reaction_T = vec;};
    void SetReaction_Ex(std::vector<double> vec) {reaction_Ex = vec;};

    std::vector<double> reaction_theta_LAB;
    std::vector<double> reaction_phi_LAB;
    std::vector<double> reaction_theta_reactionCOM;
    std::vector<double> reaction_phi_reactionCOM;

    void SetReaction_theta_LAB(std::vector<double> vec)         {reaction_theta_LAB = vec;};
    void SetReaction_phi_LAB(std::vector<double> vec)           {reaction_phi_LAB = vec;};
    void SetReaction_theta_reactionCOM(std::vector<double> vec) {reaction_theta_reactionCOM = vec;};
    void SetReaction_phi_reactionCOM(std::vector<double> vec)   {reaction_phi_reactionCOM = vec;};

    //--------------------------------------------------------------------------------
    //      Decay variables
    std::vector<int>    nDecayProducts;
    std::vector<int>    decay_Z;
    std::vector<double> decay_A;
    std::vector<double> decay_P;
    std::vector<double> decay_T;

    void SetNDecayProducts(int n)
    {
        nDecayProducts.clear();
        nDecayProducts.push_back(n);
    };

    void SetDecay_Z(std::vector<int> vec)       {decay_Z = vec;};
    void SetDecay_A(std::vector<double> vec)    {decay_A = vec;};
    void SetDecay_P(std::vector<double> vec)    {decay_P = vec;};
    void SetDecay_T(std::vector<double> vec)    {decay_T = vec;};

    std::vector<double> decay_theta_LAB;
    std::vector<double> decay_phi_LAB;
    std::vector<double> decay_theta_reactionCOM;
    std::vector<double> decay_phi_reactionCOM;
    std::vector<double> decay_theta_recoilCOM;
    std::vector<double> decay_phi_recoilCOM;

    void SetDecay_theta_LAB(std::vector<double> vec)            {decay_theta_LAB = vec;};
    void SetDecay_phi_LAB(std::vector<double> vec)              {decay_phi_LAB = vec;};
    void SetDecay_theta_recoilCOM(std::vector<double> vec)      {decay_theta_recoilCOM = vec;};
    void SetDecay_phi_recoilCOM(std::vector<double> vec)        {decay_phi_recoilCOM = vec;};
    void SetDecay_theta_reactionCOM(std::vector<double> vec)    {decay_theta_reactionCOM = vec;};
    void SetDecay_phi_reactionCOM(std::vector<double> vec)      {decay_phi_reactionCOM = vec;};

    //--------------------------------------------------------------------------------
    //      CLOVER detectors
    std::vector<int>    CLOVER_eventFold;
    std::vector<int>    CLOVER_iD;
    std::vector<int>    CLOVER_nCrystalsTriggered;
    std::vector<double> CLOVER_energyPerCrystal;
    std::vector<double> CLOVER_energy;
    std::vector<double> CLOVER_initialEnergy;
    std::vector<double> CLOVER_initialEnergy_COM;
    std::vector<double> CLOVER_detectorTheta;
    std::vector<double> CLOVER_detectorPhi;
    std::vector<int>    CLOVER_CrystalReflectionIndex;
    std::vector<double> CLOVER_initialInteractionTheta;
    std::vector<double> CLOVER_initialInteractionPhi;
    std::vector<double> CLOVER_initialParticleTheta;
    std::vector<double> CLOVER_initialParticlePhi;

    std::vector<int>    CLOVER_BGOCrystalsTriggered;

    void SetCLOVER_EventFold(int n)
    {
        CLOVER_eventFold.clear();
        CLOVER_eventFold.push_back(n);
    };

    void SetCLOVER_IDs(std::vector<int> vec) {CLOVER_iD = vec;};
    void SetCLOVER_NCrystalsTriggered(std::vector<int> vec) {CLOVER_nCrystalsTriggered = vec;};
    void SetCLOVER_EnergiesPerCrystal(std::vector<double> vec) {CLOVER_energyPerCrystal = vec;};
    void SetCLOVER_Energies(std::vector<double> vec) {CLOVER_energy = vec;};
    void SetCLOVER_InitialEnergies(std::vector<double> vec) {CLOVER_initialEnergy = vec;};
    void SetCLOVER_InitialEnergiesCOM(std::vector<double> vec) {CLOVER_initialEnergy_COM = vec;};
    void SetCLOVER_DetectorThetas(std::vector<double> vec) {CLOVER_detectorTheta = vec;};
    void SetCLOVER_DetectorPhis(std::vector<double> vec) {CLOVER_detectorPhi = vec;};
    void SetCLOVER_CrystalReflectionIndices(std::vector<int> vec) {CLOVER_CrystalReflectionIndex = vec;};
    void SetCLOVER_InitialInteractionThetas(std::vector<double> vec) {CLOVER_initialInteractionTheta = vec;};
    void SetCLOVER_InitialInteractionPhis(std::vector<double> vec) {CLOVER_initialInteractionPhi = vec;};
    void SetCLOVER_InitialParticleThetas(std::vector<double> vec) {CLOVER_initialParticleTheta = vec;};
    void SetCLOVER_InitialParticlePhis(std::vector<double> vec) {CLOVER_initialParticlePhi = vec;};

    void SetCLOVER_BGOCrystalsTriggered(std::vector<int> vec) {CLOVER_BGOCrystalsTriggered = vec;};

    //--------------------------------------------------------------------------------
    //      LaBr3Ce detectors
    std::vector<int>    laBr3Ce_eventFold;
    std::vector<int>    laBr3Ce_iD;
    std::vector<double> laBr3Ce_energy;
    std::vector<double> laBr3Ce_detectorTheta;
    std::vector<double> laBr3Ce_detectorPhi;
    std::vector<double> laBr3Ce_theta;
    std::vector<double> laBr3Ce_phi;
    std::vector<double> laBr3Ce_xPos;
    std::vector<double> laBr3Ce_yPos;
    std::vector<double> laBr3Ce_zPos;

    void SetLaBr3Ce_EventFold(int n)
    {
        laBr3Ce_eventFold.clear();
        laBr3Ce_eventFold.push_back(n);
    };

    void SetLaBr3Ce_IDs(std::vector<int> vec) {laBr3Ce_iD = vec;};
    void SetLaBr3Ce_Energies(std::vector<double> vec) {laBr3Ce_energy = vec;};
    void SetLaBr3Ce_Thetas(std::vector<double> vec) {laBr3Ce_theta = vec;};
    void SetLaBr3Ce_Phis(std::vector<double> vec) {laBr3Ce_phi = vec;};
    void SetLaBr3Ce_DetectorThetas(std::vector<double> vec) {laBr3Ce_detectorTheta = vec;};
    void SetLaBr3Ce_DetectorPhis(std::vector<double> vec) {laBr3Ce_detectorPhi = vec;};
    void SetLaBr3Ce_xPos(std::vector<double> vec) {laBr3Ce_xPos = vec;};
    void SetLaBr3Ce_yPos(std::vector<double> vec) {laBr3Ce_yPos = vec;};
    void SetLaBr3Ce_zPos(std::vector<double> vec) {laBr3Ce_zPos = vec;};

};

//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......

#endif


text:
package version

var VERSION = ""


text:
```js
var homepage = require('{%= name %}');

homepage({homepage: 'https://github.com/foo/bar'});
//=> 'https://github.com/foo/bar'

homepage({repository: 'foo/bar'});
//=> 'https://github.com/foo/bar'

homepage({repository: {url: 'git://gitub.com/foo/bar.git'}});
//=> 'https://github.com/foo/bar'
```


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycologia 94(1): 167 (2002)

#### Original name
Trichoderma aggressivum f. europaeum Samuels & W. Gams, 2002

### Remarks
null