text:
using Orders::FireAt;

BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE

#if BOOST_VERSION == 102800
extern PyObject * to_python( Unit *x );
#endif

BOOST_PYTHON_END_CONVERSION_NAMESPACE
bool useAfterburner()
{
    static bool useafterburner = XMLSupport::parse_bool( vs_config->getVariable( "AI", "use_afterburner", "true" ) );
    return useafterburner;
}
bool useAfterburnerToRun()
{
    static bool useafterburner = XMLSupport::parse_bool( vs_config->getVariable( "AI", "use_afterburner_to_run", "true" ) );
    return useafterburner;
}
bool useAfterburnerToFollow()
{
    static bool useafterburner = XMLSupport::parse_bool( vs_config->getVariable( "AI", "use_afterburner_to_follow", "true" ) );
    return useafterburner;
}
void AddOrd( Order *aisc, Unit *un, Order *ord )
{
    ord->SetParent( un );
    aisc->EnqueueOrder( ord );
}
void ReplaceOrd( Order *aisc, Unit *un, Order *ord )
{
    ord->SetParent( un );
    aisc->ReplaceOrder( ord );
}
static Order *lastOrder = NULL;
void FireAt::AddReplaceLastOrder( bool replace )
{
    if (lastOrder) {
        if (replace)
            ReplaceOrd( this, parent, lastOrder );
        else
            AddOrd( this, parent, lastOrder );
        lastOrder = NULL;
    }
}
void FireAt::ExecuteLastScriptFor( float time )
{
    if (lastOrder)
        lastOrder = new ExecuteFor( lastOrder, time );
}
void FireAt::FaceTarget( bool end )
{
    lastOrder = new Orders::FaceTarget( end, 4 );
}
void FireAt::FaceTargetITTS( bool end )
{
    lastOrder = new Orders::FaceTargetITTS( end, 4 );
}
void FireAt::MatchLinearVelocity( bool terminate, Vector vec, bool afterburn, bool local )
{
    afterburn = afterburn && useAfterburner();
    lastOrder = new Orders::MatchLinearVelocity( parent->ClampVelocity( vec, afterburn ), local, afterburn, terminate );
}
void FireAt::MatchAngularVelocity( bool terminate, Vector vec, bool local )
{
    lastOrder = new Orders::MatchAngularVelocity( parent->ClampAngVel( vec ), local, terminate );
}
void FireAt::ChangeHeading( QVector vec )
{
    lastOrder = new Orders::ChangeHeading( vec, 3 );
}
void FireAt::ChangeLocalDirection( Vector vec )
{
    lastOrder = new Orders::ChangeHeading( ( ( parent->Position().Cast() )+parent->ToWorldCoordinates( vec ) ).Cast(), 3 );
}
void FireAt::MoveTo( QVector vec, bool afterburn )
{
    afterburn = afterburn && useAfterburner();
    lastOrder = new Orders::MoveTo( vec, afterburn, 3 );
}
void FireAt::MatchVelocity( bool terminate, Vector vec, Vector angvel, bool afterburn, bool local )
{
    afterburn = afterburn && useAfterburner();
    lastOrder = new Orders::MatchVelocity( parent->ClampVelocity( vec, afterburn ), parent->ClampAngVel(
                                               angvel ), local, afterburn, terminate );
}
void FireAt::Cloak( bool enable, float seconds )
{
    lastOrder = new CloakFor( enable, seconds );
}
void FireAt::FormUp( QVector pos )
{
    lastOrder = new Orders::FormUp( pos );
}
void FireAt::FormUpToOwner( QVector pos )
{
    lastOrder = new Orders::FormUpToOwner( pos );
}
void FireAt::FaceDirection( float distToMatchFacing, bool finish )
{
    lastOrder = new Orders::FaceDirection( distToMatchFacing, finish, 3 );
}
void FireAt::XMLScript( string script )
{
    lastOrder = new AIScript( script.c_str() );
}
void FireAt::LastPythonScript()
{
    lastOrder = PythonAI< Orders::FireAt >::LastPythonClass();
}

class EvadeLeftRightC : public FlyByWire
{
    bool   updown;
    Vector facing;
    bool   dir;
public: EvadeLeftRightC( bool updown )
    {
        this->updown = updown;
        facing = Vector( 0, 0, 0 );
        desired_ang_velocity = Vector( 0, 0, 0 );
        dir    = (rand() < RAND_MAX/2);
    }
    void SetOppositeDir()
    {
        dir = !dir;
        SetDesiredAngularVelocity( Vector( 0.0f, 0.0f, 0.0f ), true );
        if (updown)
            Up( dir ? 1.0f : -1.0f );
        else
            Right( dir ? 1.0f : -1.0f );
        Vector P = Vector( 0, 0, 0 ), Q = Vector( 0, 0, 0 );
        parent->GetOrientation( P, Q, facing );
    }
    virtual void SetParent( Unit *parent1 )
    {
        FlyByWire::SetParent( parent1 );
        SetOppositeDir();
    }
    void Execute()
    {
        FlyByWire::Execute();
        Vector P, Q, R;
        parent->GetOrientation( P, Q, R );
        static float ang = cos( XMLSupport::parse_float( vs_config->getVariable( "AI", "evasion_angle", "45" ) ) );
        if ( R.Dot( facing ) < ang
            || (desired_ang_velocity.i == 0 && desired_ang_velocity.j == 0 && desired_ang_velocity.k == 0) )
            SetOppositeDir();
    }
};

//these can be used in the XML scripts if they are allowed to be called

//these can be used in the XML scripts if they are allowed to be called

void AfterburnTurnTowards( Order *aisc, Unit *un )
{
    Vector vec( 0, 0, 10000 );
    bool   afterburn = useAfterburnerToFollow();
    Order *ord = new Orders::MatchLinearVelocity( un->ClampVelocity( vec, afterburn ), true, afterburn, false );
    AddOrd( aisc, un, ord );
    ord = ( new Orders::FaceTarget( false, 3 ) );
    AddOrd( aisc, un, ord );
}
void AfterburnTurnTowardsITTS( Order *aisc, Unit *un )
{
    Vector vec( 0, 0, 10000 );

    bool   afterburn = useAfterburnerToFollow();
    Order *ord = new Orders::MatchLinearVelocity( un->ClampVelocity( vec, afterburn ), true, afterburn, false );
    AddOrd( aisc, un, ord );
    ord = ( new Orders::FaceTargetITTS( false, 3 ) );
    AddOrd( aisc, un, ord );
}

void BarrelRoll( Order *aisc, Unit *un )
{
    FlyByWire *broll = new FlyByWire;
    AddOrd( aisc, un, broll );
    broll->RollRight( rand() > RAND_MAX/2 ? 1 : -1 );
    float per;
    if (rand() < RAND_MAX/2) {
        per = ( (float) rand() )/RAND_MAX;
        if (per < .5)
            per -= 1;
        broll->Up( per );
    } else {
        per = ( (float) rand() )/RAND_MAX;
        if (per < .5)
            per -= 1;
        broll->Right( per );
    }
    bool afterburn = useAfterburner();
    broll->MatchSpeed( Vector( 0, 0, afterburn ? un->GetComputerData().max_ab_speed() : un->GetComputerData().max_speed() ) );
    broll->Afterburn( afterburn );
}

static void EvadeWavy( Order *aisc, Unit *un, bool updown, bool ab )
{
    EvadeLeftRightC *broll = NULL;
    broll = new EvadeLeftRightC( updown );
    AddOrd( aisc, un, broll );
    bool afterburn = ab && useAfterburner();
    broll->MatchSpeed( Vector( 0, 0, afterburn ? un->GetComputerData().max_ab_speed() : un->GetComputerData().max_speed() ) );
    broll->Afterburn( afterburn );
}
void AfterburnEvadeLeftRight( Order *aisc, Unit *un )
{
    EvadeWavy( aisc, un, false, true );
}
void AfterburnEvadeUpDown( Order *aisc, Unit *un )
{
    EvadeWavy( aisc, un, true, true );
}
void EvadeLeftRight( Order *aisc, Unit *un )
{
    EvadeWavy( aisc, un, false, false );
}
void EvadeUpDown( Order *aisc, Unit *un )
{
    EvadeWavy( aisc, un, true, false );
}

namespace Orders
{
class LoopAround : public Orders::FaceTargetITTS
{
    Orders::MatchLinearVelocity m;
    float  qq;
    float  pp;
    Vector rr;    //place to go for @ end1111
    bool   afterburn;
    bool   aggressive;
    bool   force_afterburn;
public:
    void SetParent( Unit *parent1 )
    {
        FaceTargetITTS::SetParent( parent1 );
        m.SetParent( parent1 );
    }
    LoopAround( bool aggressive, bool afterburn, bool force_afterburn, int seed ) : FaceTargetITTS( false, 3 )
        , m( Vector( 0, 0, 1000 ), true, afterburn, false )
    {
        VSRandom vsr( seed );
        this->aggressive = aggressive;
        this->afterburn  = afterburn;
        this->force_afterburn = force_afterburn;

        static float loopdis  = XMLSupport::parse_float( vs_config->getVariable( "AI", "loop_around_distance", "1" ) );
        qq = pp = 0;
        static float loopdisd =
            XMLSupport::parse_float( vs_config->getVariable( "AI", "loop_around_destination_distance", "20.0" ) );
        static float loopdisv =
            XMLSupport::parse_float( vs_config->getVariable( "AI", "loop_around_destination_vertical", "4.0" ) );
        static float loopdisl = XMLSupport::parse_float( vs_config->getVariable( "AI", "loop_around_destination_lateral", "4.0" ) );
        rr.Set( loopdisl*vsr.uniformInc( -1, 1 ), loopdisv*vsr.uniformInc( -1, 1 ), 1.0+loopdisd*vsr.uniformInc( 0, 1 ) );
        if (vsr.rand() < VS_RAND_MAX/2) {
            qq   = vsr.uniformInc( -1, 1 );
            rr.j = qq;
            if (qq > 0)
                qq += loopdis;
            if (qq < 0)
                qq -= loopdis;
        } else {
            pp   = vsr.uniformInc( -1, 1 );
            rr.i = pp;
            if (pp > 0)
                pp += loopdis;
            if (pp < 0)
                pp -= loopdis;
        }
    }
    void Execute()
    {
        Unit *targ = parent->Target();
        if (targ) {
            Vector relloc    = parent->Position()-targ->Position();
            Vector r = targ->cumulative_transformation_matrix.getR();
            bool   afterburn = useAfterburner() && this->afterburn;
            bool   ab_needed = force_afterburn || targ->GetVelocity().MagnitudeSquared() > parent->GetComputerData().max_speed();
            m.SetDesiredVelocity( Vector( 0, 0, afterburn
                                         && ab_needed ? parent->GetComputerData().max_ab_speed() : parent->GetComputerData().
                                         max_speed() ), true );
            float spseed, grange = 0, mrange = 0;
            parent->getAverageGunSpeed( spseed, grange, mrange );
            if (r.Dot( relloc ) < 0) {
                static float gun_range_pct =
                    XMLSupport::parse_float( vs_config->getVariable( "AI", "gun_range_percent_ok", ".66" ) );
                FaceTargetITTS::Execute();
                float dist = UnitUtil::getDistance( parent, targ );
                if ( dist < grange*gun_range_pct || (grange == 0 && dist < mrange) ) {
                    static float velocity_adjustment_pct =
                        XMLSupport::parse_float( vs_config->getVariable( "AI", "loop_around_pursuit_velocity_percent", ".9" ) );
                    m.SetDesiredVelocity( Vector( 0, 0, targ->cumulative_velocity.Magnitude()*velocity_adjustment_pct ), true );
                }
                m.SetAfterburn( afterburn && ab_needed );
                m.Execute();
            } else {
                done = false;
                if (afterburn)
                    m.SetAfterburn( ab_needed );
                else
                    m.SetAfterburn( 0 );
                Vector scala =
                    targ->cumulative_transformation_matrix.getQ().Scale( qq
                                                                        *( parent->rSize()
                                                                          +targ->rSize() ) )
                    +targ->cumulative_transformation_matrix.getP().Scale( pp*( parent->rSize()+targ->rSize() ) );
                QVector dest = targ->Position()+scala;
                SetDest( dest );
                ChangeHeading::Execute();
                m.Execute();
            }
        }
    }
};

class LoopAroundAgro : public Orders::FaceTargetITTS
{
    Orders::MoveToParent m;
    float  qq;
    float  pp;
    Vector rr;    //place to go for @ end
    bool   aggressive;
    bool   afterburn;
    bool   force_afterburn;
public: LoopAroundAgro( bool aggressive, bool afterburn, bool force_afterburn, int seed ) : FaceTargetITTS( false, 3 )
        , m( false, 2, false )
    {
        VSRandom vsr( seed );
        this->afterburn  = afterburn;
        this->force_afterburn = force_afterburn;
        this->aggressive = aggressive;
        static float loopdis  = XMLSupport::parse_float( vs_config->getVariable( "AI", "loop_around_distance", "1" ) );
        qq = pp = 0;
        static float loopdisd =
            XMLSupport::parse_float( vs_config->getVariable( "AI", "loop_around_destination_distance", "20.0" ) );
        static float loopdisv =
            XMLSupport::parse_float( vs_config->getVariable( "AI", "loop_around_destination_vertical", "4.0" ) );
        static float loopdisl = XMLSupport::parse_float( vs_config->getVariable( "AI", "loop_around_destination_lateral", "4.0" ) );
        rr.Set( loopdisl*vsr.uniformInc( -1, 1 ), loopdisv*vsr.uniformInc( -1, 1 ), 1.0+loopdisd*vsr.uniformInc( 0, 1 ) );
        if (vsr.rand() < VS_RAND_MAX/2) {
            qq   = vsr.uniformInc( -1, 1 );
            rr.j = qq;
            if (qq > 0)
                qq += loopdis;
            if (qq < 0)
                qq -= loopdis;
        } else {
            pp   = vsr.uniformInc( -1, 1 );
            rr.i = pp;
            if (pp > 0)
                pp += loopdis;
            if (pp < 0)
                pp -= loopdis;
        }
    }
    void Execute()
    {
        Unit *targ = parent->Target();
        if (targ) {
            Vector relloc    = parent->Position()-targ->Position();
            Vector r = targ->cumulative_transformation_matrix.getR();
            bool   afterburn = useAfterburner() && this->afterburn;
            bool   ab_needed = force_afterburn || targ->GetVelocity().MagnitudeSquared() > parent->GetComputerData().max_speed();
            if (r.Dot( relloc ) < 0) {
                FaceTargetITTS::Execute();
                m.SetAfterburn( afterburn && ab_needed );
                m.Execute( parent, targ->Position()-r.Scale(
                              rr.k*parent->rSize()
                              +targ->rSize() )+targ->cumulative_transformation_matrix.getP()
                          *( rr.i*parent->rSize() )+targ->cumulative_transformation_matrix.getQ()*( rr.j*parent->rSize() ) );
            } else {
                done = false;
                if (afterburn)
                    m.SetAfterburn( ab_needed );
                else
                    m.SetAfterburn( 0 );
                Vector scala =
                    targ->cumulative_transformation_matrix.getQ().Scale( qq
                                                                        *( parent->rSize()
                                                                          +targ->rSize() ) )
                    +targ->cumulative_transformation_matrix.getP().Scale( pp*( parent->rSize()+targ->rSize() ) );
                QVector dest = targ->Position()+scala;
                if (aggressive) {
                    FaceTargetITTS::Execute();
                } else {
                    SetDest( dest );
                    ChangeHeading::Execute();
                }
                m.Execute( parent, dest+scala );
            }
        }
    }
};

class FacePerpendicular : public Orders::FaceTargetITTS
{
    Orders::MatchLinearVelocity m;
    float  qq;
    float  pp;
    Vector rr;    //place to go for @ end1111
    bool   afterburn;
    bool   aggressive;
    bool   force_afterburn;
public:
    void SetParent( Unit *parent1 )
    {
        FaceTargetITTS::SetParent( parent1 );
        m.SetParent( parent1 );
    }
    FacePerpendicular( bool aggressive, bool afterburn, bool force_afterburn, int seed ) : FaceTargetITTS( false, 3 )
        , m( Vector( 0, 0, 1000 ), true, afterburn, false )
    {
        this->aggressive = aggressive;
        VSRandom vsr( seed );
        this->afterburn  = afterburn;
        this->force_afterburn = force_afterburn;

        static float loopdis  = XMLSupport::parse_float( vs_config->getVariable( "AI", "loop_around_distance", "1" ) );
        qq = pp = 0;
        static float loopdisd =
            XMLSupport::parse_float( vs_config->getVariable( "AI", "loop_around_destination_distance", "20.0" ) );
        static float loopdisv =
            XMLSupport::parse_float( vs_config->getVariable( "AI", "loop_around_destination_vertical", "4.0" ) );
        static float loopdisl = XMLSupport::parse_float( vs_config->getVariable( "AI", "loop_around_destination_lateral", "4.0" ) );
        rr.Set( loopdisl*vsr.uniformInc( -1, 1 ), loopdisv*vsr.uniformInc( -1, 1 ), 1.0+loopdisd*vsr.uniformInc( 0, 1 ) );
        if (vsr.rand() < VS_RAND_MAX/2) {
            qq   = vsr.uniformInc( -1, 1 );
            rr.j = qq;
            if (qq > 0)
                qq += loopdis;
            if (qq < 0)
                qq -= loopdis;
        } else {
            pp   = vsr.uniformInc( -1, 1 );
            rr.i = pp;
            if (pp > 0)
                pp += loopdis;
            if (pp < 0)
                pp -= loopdis;
        }
    }
    void Execute()
    {
        static float gun_range_pct = XMLSupport::parse_float( vs_config->getVariable( "AI", "gun_range_percent_ok", ".66" ) );
        Unit *targ = parent->Target();
        if (targ) {
            Vector relloc    = parent->Position()-targ->Position();
            Vector r = targ->cumulative_transformation_matrix.getR();
            bool   afterburn = useAfterburner() && this->afterburn;
            bool   ab_needed = force_afterburn || targ->GetVelocity().MagnitudeSquared() > parent->GetComputerData().max_speed();
            m.SetDesiredVelocity( Vector( 0, 0, afterburn
                                         && ab_needed ? parent->GetComputerData().max_ab_speed() : parent->GetComputerData().
                                         max_speed() ), true );
            float speed, grange = 0, mrange = 0;
            parent->getAverageGunSpeed( speed, grange, mrange );
            if (r.Dot( relloc ) < 0) {
                FaceTargetITTS::Execute();
                float dist = UnitUtil::getDistance( parent, targ );
                if ( dist < grange*gun_range_pct || (grange == 0 && dist < mrange) ) {
                    static float velocity_adjustment_pct =
                        XMLSupport::parse_float( vs_config->getVariable( "AI", "loop_around_pursuit_velocity_percent", ".9" ) );
                    m.SetDesiredVelocity( Vector( 0, 0, targ->cumulative_velocity.Magnitude()*velocity_adjustment_pct ), true );
                }
                m.SetAfterburn( afterburn && ab_needed );
                m.Execute();
            } else {
                done = false;
                if (afterburn)
                    m.SetAfterburn( ab_needed );
                else
                    m.SetAfterburn( 0 );
                Vector  scala = targ->cumulative_transformation_matrix.getR().Cross(
                    aggressive ? parent->cumulative_transformation_matrix.getQ() : Vector( .01, .99,
                                                                                -.001 ) )*parent->rSize()*100.;
                QVector dest  = parent->Position()+scala;
                SetDest( dest );
                ChangeHeading::Execute();
                m.Execute();
            }
        }
    }
};
}
void LoopAround( Order *aisc, Unit *un )
{
    Order *broll = new Orders::LoopAround( false, true, false, (int) (size_t) un );
    AddOrd( aisc, un, broll );
}
void AggressiveLoopAround( Order *aisc, Unit *un )
{
    Order *broll = new Orders::LoopAroundAgro( true, true, false, (int) (size_t) un );
    AddOrd( aisc, un, broll );
}
void RollLeft( Order *aisc, Unit *un )
{
    if (un->aistate)
        AddOrd( un->aistate, un, new Orders::ExecuteFor( new Orders::MatchRoll( un->GetComputerData().max_roll_right, false ), 1.0f ) );
}
void RollRight( Order *aisc, Unit *un )
{
    if (un->aistate)
        AddOrd( un->aistate, un, new Orders::ExecuteFor( new Orders::MatchRoll( -un->GetComputerData().max_roll_left, false ), 1.0f ) );
}
void RollLeftHard( Order *aisc, Unit *un )
{
    static float durvar = XMLSupport::parse_float( vs_config->getVariable( "AI", "roll_order_duration", "5.0" ) );
    if (un->aistate)
        AddOrd( un->aistate, un, new Orders::ExecuteFor( new Orders::MatchRoll( un->GetComputerData().max_roll_right, false ), durvar ) );
}
void RollRightHard( Order *aisc, Unit *un )
{
    static float durvar = XMLSupport::parse_float( vs_config->getVariable( "AI", "roll_order_duration", "5.0" ) );
    if (un->aistate)
        AddOrd( un->aistate, un, new Orders::ExecuteFor( new Orders::MatchRoll( -un->GetComputerData().max_roll_left, false ), durvar ) );
}
void LoopAroundFast( Order *aisc, Unit *un )
{
    Order *broll = new Orders::LoopAround( false, true, true, (int) (size_t) un );
    AddOrd( aisc, un, broll );
}

void FacePerpendicularFast( Order *aisc, Unit *un )
{
    Order *broll = new Orders::FacePerpendicular( false, true, true, (int) (size_t) un );
    AddOrd( aisc, un, broll );
}
void FacePerpendicular( Order *aisc, Unit *un )
{
    Order *broll = new Orders::FacePerpendicular( false, true, false, (int) (size_t) un );
    AddOrd( aisc, un, broll );
}
void FacePerpendicularSlow( Order *aisc, Unit *un )
{
    Order *broll = new Orders::FacePerpendicular( false, false, false, (int) (size_t) un );
    AddOrd( aisc, un, broll );
}

void RollFacePerpendicularFast( Order *aisc, Unit *un )
{
    Order *broll = new Orders::FacePerpendicular( true, true, true, (int) (size_t) un );
    AddOrd( aisc, un, broll );
}
void RollFacePerpendicular( Order *aisc, Unit *un )
{
    Order *broll = new Orders::FacePerpendicular( true, true, false, (int) (size_t) un );
    AddOrd( aisc, un, broll );
}
void RollFacePerpendicularSlow( Order *aisc, Unit *un )
{
    Order *broll = new Orders::FacePerpendicular( true, false, false, (int) (size_t) un );
    AddOrd( aisc, un, broll );
}

void AggressiveLoopAroundFast( Order *aisc, Unit *un )
{
    Order *broll = new Orders::LoopAroundAgro( true, true, true, (int) (size_t) un );
    AddOrd( aisc, un, broll );
}
void LoopAroundSlow( Order *aisc, Unit *un )
{
    Order *broll = new Orders::LoopAround( false, false, false, (int) (size_t) un );
    AddOrd( aisc, un, broll );
}

void SelfDestruct( Order *aisc, Unit *un )
{
    un->armor.frontrighttop    = -1;
    un->armor.backrighttop     = -1;
    un->armor.frontlefttop     = -1;
    un->armor.backlefttop      = -1;
    un->armor.frontrightbottom = -1;
    un->armor.backrightbottom  = -1;
    un->armor.frontleftbottom  = -1;
    un->armor.backleftbottom   = -1;
    un->hull = -1;     //hull goes to zero but no kill, same for armor. strangely enough, all of them together work.
    un->Split( rand()%3+1 );
    un->Explode( true, 0 );     //displays explosion, unit continues
    un->RemoveFromSystem();      //has no effect
}

void AggressiveLoopAroundSlow( Order *aisc, Unit *un )
{
    Order *broll = new Orders::LoopAroundAgro( true, false, false, (int) (size_t) un );
    AddOrd( aisc, un, broll );
}
#if 0
void Evade( Order *aisc, Unit *un )
{
    QVector v( un->Position() );
    QVector u( v );
    Unit   *targ = un->Target();
    if (targ)
        u = targ->Position();
    Order  *ord  = new Orders::ChangeHeading( ( 200*(v-u) )+v, 3 );
    AddOrd( aisc, un, ord );
    bool    afterburn = useAfterburner();
    ord = new Orders::MatchLinearVelocity( un->ClampVelocity( Vector( -10000, 0, 10000 ), afterburn ), false, afterburn, true );
    AddOrd( aisc, un, ord );
    ord = new Orders::FaceTargetITTS( false, 3 );
    AddOrd( aisc, un, ord );
    ord = new Orders::MatchLinearVelocity( un->ClampVelocity( Vector( 10000, 0, 10000 ), afterburn ), false, afterburn, true );
    AddOrd( aisc, un, ord );
}
#endif
void MoveTo( Order *aisc, Unit *un )
{
    QVector Targ( un->Position() );
    Unit   *untarg = un->Target();
    if (untarg)
        Targ = untarg->Position();
    Order  *ord    = new Orders::MoveTo( Targ, false, 3 );
    AddOrd( aisc, un, ord );
}

void KickstopBase( Order *aisc, Unit *un, bool match )
{
    Vector vec( 0, 0, 0 );
    if ( match && un->Target() )
        vec = un->Target()->GetVelocity();
    Order *ord = new Orders::MatchLinearVelocity( un->ClampVelocity( vec, false ), true, false, true );
    AddOrd( aisc, un, ord );
    ord = ( new Orders::FaceTargetITTS( false, 3 ) );
    AddOrd( aisc, un, ord );
}
void Kickstop( Order *aisc, Unit *un )
{
    KickstopBase( aisc, un, false );
}

void CoastToStop( Order *aisc, Unit *un )
{
    Vector vec( 0, 0, 0 );
    vec   = un->GetVelocity();

    vec.i = vec.i*0.1;
    vec.j = vec.j*0.1;
    vec.k = vec.k*0.1;

    Order *ord = new Orders::ExecuteFor( new Orders::MatchLinearVelocity( un->ClampVelocity( vec, false ), true, false, true ), 1 );
    AddOrd( aisc, un, ord );
}

void DoNothing( Order *aisc, Unit *un )
{
    Vector vec( 0, 0, 0 );
    vec = un->GetVelocity();

    Order *ord = new Orders::ExecuteFor( new Orders::MatchLinearVelocity( vec, true, false, true ), 1 );
    AddOrd( aisc, un, ord );
}

void MatchVelocity( Order *aisc, Unit *un )
{
    KickstopBase( aisc, un, true );
}

static Vector VectorThrustHelper( Order *aisc, Unit *un, bool ab = false )
{
    Vector vec( 0, 0, 0 );
    Vector retval( 0, 0, 0 );
    if ( un->Target() ) {
        Vector tpos   = un->Target()->Position().Cast();
        Vector relpos = tpos-un->Position().Cast();
        CrossProduct( relpos, Vector( 1, 0, 0 ), vec );
        retval += tpos;
    }
    Order *ord = new Orders::MatchLinearVelocity( un->ClampVelocity( vec, ab ), false, ab, true );
    AddOrd( aisc, un, ord );
    return retval;
}
void VeerAway( Order *aisc, Unit *un )
{
    VectorThrustHelper( aisc, un );
    Order *ord = ( new Orders::FaceTarget( false, 3 ) );
    AddOrd( aisc, un, ord );
}
void VeerAwayITTS( Order *aisc, Unit *un )
{
    VectorThrustHelper( aisc, un );
    Order *ord = ( new Orders::FaceTargetITTS( false, 3 ) );
    AddOrd( aisc, un, ord );
}
void VeerAndVectorAway( Order *aisc, Unit *un )
{
    Vector retval = VectorThrustHelper( aisc, un );
    Order *ord    = new Orders::ChangeHeading( retval, 3, 1 );
    AddOrd( aisc, un, ord );
}
void AfterburnVeerAndVectorAway( Order *aisc, Unit *un )
{
    Vector retval = VectorThrustHelper( aisc, un, true );
    Order *ord    = new Orders::ChangeHeading( retval, 3, 1 );
    AddOrd( aisc, un, ord );
}
void AfterburnVeerAndTurnAway( Order *aisc, Unit *un )
{
    Vector vec  = Vector( 0, 0, 1 );
    bool   ab   = true;
    Vector tpos = un->Position().Cast();
    if ( un->Target() ) {
        tpos = un->Target()->Position().Cast();
        Vector relpos = tpos-un->Position().Cast();
        CrossProduct( relpos, Vector( 1, 0, 0 ), vec );
    }
    Order *ord = new Orders::ExecuteFor( new Orders::MatchLinearVelocity( Vector( 0, 0, 0 ), true, ab, true ), .5 );

    AddOrd( aisc, un, ord );
    ord = new Orders::MatchLinearVelocity( un->ClampVelocity( Vector( 0, 0, 100000 ), ab ), true, ab, true );
    aisc->EnqueueOrder( ord );
    ord = new Orders::ChangeHeading( tpos+vec, 3, 1 );
    AddOrd( aisc, un, ord );
}
static void SetupVAndTargetV( QVector &targetv, QVector &targetpos, Unit *un )
{
    Unit *targ;
    if ( ( targ = un->Target() ) ) {
        targetv   = targ->GetVelocity().Cast();
        targetpos = targ->Position();
    }
}

void SheltonSlide( Order *aisc, Unit *un )
{
    QVector def( un->Position()+QVector( 1, 0, 0 ) );
    QVector targetv( def );
    QVector targetpos( def );
    SetupVAndTargetV( targetpos, targetv, un );
    QVector difference = targetpos-un->Position();
    QVector perp = targetv.Cross( -difference );
    perp.Normalize();
    perp = perp*( targetv.Dot( difference* -1./( difference.Magnitude() ) ) );
    perp = (perp+difference)*10000.;

    bool   afterburn = useAfterburner();
    Order *ord = new Orders::MatchLinearVelocity( un->ClampVelocity( perp.Cast(), afterburn ), false, afterburn, true );
    AddOrd( aisc, un, ord );
    ord = ( new Orders::FaceTargetITTS( false, 3 ) );
    AddOrd( aisc, un, ord );
}

void AfterburnerSlide( Order *aisc, Unit *un )
{
    QVector def = un->Position()+QVector( 1, 0, 0 );
    QVector targetv( def );
    QVector targetpos( def );
    SetupVAndTargetV( targetpos, targetv, un );

    QVector difference = targetpos-un->Position();
    QVector perp = targetv.Cross( -difference );
    perp.Normalize();
    perp = perp*( targetv.Dot( difference* -1./( difference.Magnitude() ) ) );
    perp = (perp+difference)*1000;
    bool   afterburn = useAfterburner();
    Order *ord = new Orders::MatchLinearVelocity( un->ClampVelocity( perp.Cast(), afterburn ), false, afterburn, true );
    AddOrd( aisc, un, ord );
    ord = new Orders::ExecuteFor( new Orders::ChangeHeading( perp+un->Position(), 3 ), 1.5 );
    AddOrd( aisc, un, ord );
    ord = ( new Orders::FaceTargetITTS( false, 3 ) );
    AddOrd( aisc, un, ord );
}
void SkilledABSlide( Order *aisc, Unit *un )
{
    QVector def = un->Position()+QVector( 1, 0, 0 );
    QVector targetv( def );
    QVector targetpos( def );
    SetupVAndTargetV( targetpos, targetv, un );

    QVector difference  = targetpos-un->Position();
    QVector ndifference = difference;
    ndifference.Normalize();
    QVector Perp;
    ScaledCrossProduct( ndifference, targetv, Perp );
    Perp = Perp+.5*ndifference;
    Perp = Perp*10000;

    bool   afterburn = useAfterburner();

    Order *ord = new Orders::MatchLinearVelocity( un->ClampVelocity( Perp.Cast(), afterburn ), false, afterburn, true );
    AddOrd( aisc, un, ord );
    ord = new Orders::ExecuteFor( new Orders::ChangeHeading( Perp+un->Position(), 3 ), .5 );
    AddOrd( aisc, un, ord );
    ord = ( new Orders::FaceTargetITTS( false, 3 ) );
    AddOrd( aisc, un, ord );
}
void Stop( Order *aisc, Unit *un )
{
    Vector vec( 0, 0, 0000 );
    Order *ord = new Orders::MatchLinearVelocity( un->ClampVelocity( vec, false ), true, false, false );
    AddOrd( aisc, un, ord );     //<!-- should we fini? -->
}
void AfterburnTurnAway( Order *aisc, Unit *un )
{
    QVector v( un->Position() );
    QVector u( v );
    Unit   *targ = un->Target();
    if (targ)
        u = targ->Position();
    bool    afterburn = useAfterburner() || useAfterburnerToRun();
    Order  *ord = new Orders::MatchLinearVelocity( un->ClampVelocity( 200*(v-u).Cast(), afterburn ), false, afterburn, false );
    AddOrd( aisc, un, ord );
    ord = new Orders::ChangeHeading( ( 200*(v-u) )+v, 3 );
    AddOrd( aisc, un, ord );
}
void TurnAway( Order *aisc, Unit *un )
{
    QVector v( un->Position() );
    QVector u( v );
    Unit   *targ = un->Target();
    if (targ)
        u = targ->Position();
    bool    afterburn = false;
    Order  *ord = new Orders::MatchLinearVelocity( un->ClampVelocity( 200*(v-u).Cast(), afterburn ), false, afterburn, false );
    AddOrd( aisc, un, ord );
    ord = new Orders::ChangeHeading( ( 200*(v-u) )+v, 3 );
    AddOrd( aisc, un, ord );
}
void TurnTowards( Order *aisc, Unit *un )
{
    Vector vec( 0, 0, 10000 );
    Order *ord = new Orders::MatchLinearVelocity( un->ClampVelocity( vec, false ), true, false, false );
    AddOrd( aisc, un, ord );

    ord = new Orders::FaceTarget( 0, 3 );
    AddOrd( aisc, un, ord );
}
void FlyStraight( Order *aisc, Unit *un )
{
    Vector vec( 0, 0, 10000 );
    Order *ord = new Orders::MatchVelocity( un->ClampVelocity( vec, false ), Vector( 0, 0, 0 ), true, false, false );
    AddOrd( aisc, un, ord );
    ord = new Orders::MatchAngularVelocity( Vector( 0, 0, 0 ), 1, false );
    AddOrd( aisc, un, ord );
}
void FlyStraightAfterburner( Order *aisc, Unit *un )
{
    Vector vec( 0, 0, 10000 );
    bool   afterburn = useAfterburner();
    Order *ord = new Orders::MatchVelocity( un->ClampVelocity( vec, afterburn ), Vector( 0, 0, 0 ), true, afterburn, false );
    AddOrd( aisc, un, ord );
    ord = new Orders::MatchAngularVelocity( Vector( 0, 0, 0 ), 1, false );
    AddOrd( aisc, un, ord );
}

//spiritplumber was here and added some orders, mostly for carriers and their spawn (eep, can carriers have kids?)

void Takeoff( Order *aisc, Unit *un )
{
    Vector vec( 0, 0, 10000 );
    static bool firsttime = true;
    Order *ord;
    if (firsttime) {
        un->UnFire();
        ord = new Orders::MatchVelocity( un->ClampVelocity( vec, true ), Vector( 0, 0, 0 ), true, true, false );
        AddOrd( aisc, un, ord );
        ord = new Orders::MatchAngularVelocity( Vector( 0, 0, 0 ), 1, false );
        AddOrd( aisc, un, ord );
        ord = new Orders::ExecuteFor( new Orders::MatchVelocity( un->ClampVelocity( vec, true ), Vector( 0,
                                                                                0,
                                                                                0 ), true, true, false ), 1.5f );
        AddOrd( aisc, un, ord );
        ord = new Orders::ExecuteFor( new Orders::MatchAngularVelocity( Vector( 0, 0, 0 ), 1, false ), 1.5f );
        AddOrd( aisc, un, ord );
        ord = new Orders::MatchLinearVelocity( un->ClampVelocity( vec, false ), true, false, false );
        AddOrd( aisc, un, ord );
        ord = ( new Orders::FaceTargetITTS( 0, 3 ) );
        AddOrd( aisc, un, ord );
        un->UnFire();
        firsttime = false;
    } else {
        firsttime = false;
        ord = new Orders::MatchLinearVelocity( un->ClampVelocity( vec, false ), true, false, false );
        AddOrd( aisc, un, ord );
        ord = ( new Orders::FaceTargetITTS( 0, 3 ) );
        AddOrd( aisc, un, ord );
    }
    ord = new Orders::MatchLinearVelocity( un->ClampVelocity( vec, false ), true, false, false );
    AddOrd( aisc, un, ord );
    ord = ( new Orders::FaceTargetITTS( 0, 3 ) );
    AddOrd( aisc, un, ord );
    un->SelectAllWeapon( false );
    un->Fire( (weapon_info::LIGHT || weapon_info::MEDIUM), false );
    TurnTowards( aisc, un );
}

void TakeoffEveryZig( Order *aisc, Unit *un )
{
    Vector vec( 0, 0, 10000 );

    Order *ord;
    un->UnFire();
    un->Fire( weapon_info::CAPSHIPHEAVY, false );
    un->UnFire();
    ord = new Orders::MatchVelocity( un->ClampVelocity( vec, true ), Vector( 0, 0, 0 ), true, true, false );
    AddOrd( aisc, un, ord );
    ord = new Orders::MatchAngularVelocity( Vector( 0, 0, 0 ), 1, false );
    AddOrd( aisc, un, ord );
    ord = new Orders::ExecuteFor( new Orders::MatchAngularVelocity( Vector( 0, 0, 0 ), 1, false ), 3.4f );
    AddOrd( aisc, un, ord );
    ord = new Orders::ExecuteFor( new Orders::MatchVelocity( un->ClampVelocity( vec, true ), Vector( 0,
                                                                                0,
                                                                                0 ), true, true, false ), 0.1f );
    AddOrd( aisc, un, ord );
    ord = new Orders::ExecuteFor( new Orders::FaceTarget( 0, 3 ), 1.0f );
    AddOrd( aisc, un, ord );
    ord = new Orders::MatchVelocity( un->ClampVelocity( vec, true ), Vector( 0, 0, 0 ), true, true, false );
    AddOrd( aisc, un, ord );
    ord = new Orders::MatchAngularVelocity( Vector( 0, 0, 0 ), 1, false );
    AddOrd( aisc, un, ord );
    un->Fire( weapon_info::CAPSHIPHEAVY, false );     //doesn't have time to happen anyway
    un->SelectAllWeapon( false );
}

void CloakForScript( Order *aisc, Unit *un )
{
    Vector vec( 0, 0, 10000 );
    Order *ord = new Orders::MatchLinearVelocity( un->ClampVelocity( vec, false ), true, false, false );
    AddOrd( aisc, un, ord );
    ord = ( new Orders::FaceTargetITTS( 0, 3 ) );
    AddOrd( aisc, un, ord );
    ord = new Orders::ExecuteFor( new CloakFor( 1, 8 ), 32 );
    AddOrd( aisc, un, ord );
}
void TurnTowardsITTS( Order *aisc, Unit *un )
{
    Vector vec( 0, 0, 10000 );
    Order *ord = new Orders::MatchLinearVelocity( un->ClampVelocity( vec, false ), true, false, false );
    AddOrd( aisc, un, ord );
    ord = ( new Orders::FaceTargetITTS( 0, 3 ) );
    AddOrd( aisc, un, ord );
}

void DropCargo( Order *aisc, Unit *un )
{
    if (un->numCargo() > 0) {
        int dropcount = un->numCargo();

        {
            for (int i = 0; i < dropcount; i++)
                un->EjectCargo( 0 );
        }
        Stop( aisc, un );
    } else {
        TurnAway( aisc, un );
    }
}

void DropHalfCargo( Order *aisc, Unit *un )
{
    if (un->numCargo() > 0) {
        int dropcount = (un->numCargo()/2)+1;

        {
            for (int i = 0; i < dropcount; i++)
                un->EjectCargo( 0 );
        }
        Stop( aisc, un );
    } else {
        TurnAway( aisc, un );
    }
}

void DropOneCargo( Order *aisc, Unit *un )
{
    if (un->numCargo() > 0) {
        un->EjectCargo( 0 );
        Stop( aisc, un );
    } else {
        TurnAway( aisc, un );
    }
}


text:
/*	$NetBSD: lms.c,v 1.37 1999/01/23 15:03:50 drochner Exp $	*/

/*-
 * Copyright (c) 1993, 1994 Charles M. Hannum.
 * Copyright (c) 1992, 1993 Erik Forsberg.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
 * NO EVENT SHALL I BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/ioctl.h>
#include <sys/device.h>

#include <machine/bus.h>
#include <machine/intr.h>

#include <dev/isa/isavar.h>

#include <dev/wscons/wsconsio.h>
#include <dev/wscons/wsmousevar.h>

#define	LMS_DATA	0       /* offset for data port, read-only */
#define	LMS_SIGN	1       /* offset for signature port, read-write */
#define	LMS_INTR	2       /* offset for interrupt port, read-only */
#define	LMS_CNTRL	2       /* offset for control port, write-only */
#define	LMS_CONFIG	3	/* for configuration port, read-write */
#define	LMS_NPORTS	4

struct lms_softc {		/* driver status information */
	struct device sc_dev;
	void *sc_ih;

	bus_space_tag_t sc_iot;		/* bus i/o space identifier */
	bus_space_handle_t sc_ioh;	/* bus i/o handle */

	int sc_enabled; /* device is open */
	int oldbuttons;	/* mouse button status */

	struct device *sc_wsmousedev;
};

int lmsprobe __P((struct device *, struct cfdata *, void *));
void lmsattach __P((struct device *, struct device *, void *));
int lmsintr __P((void *));

struct cfattach lms_ca = {
	sizeof(struct lms_softc), lmsprobe, lmsattach
};

int	lms_enable __P((void *));
int	lms_ioctl __P((void *, u_long, caddr_t, int, struct proc *));
void	lms_disable __P((void *));

const struct wsmouse_accessops lms_accessops = {
	lms_enable,
	lms_ioctl,
	lms_disable,
};

int
lmsprobe(parent, match, aux)
	struct device *parent;
	struct cfdata *match;
	void *aux;
{
	struct isa_attach_args *ia = aux;
	bus_space_tag_t iot = ia->ia_iot;
	bus_space_handle_t ioh;
	int rv;

	/* Disallow wildcarded i/o base. */
	if (ia->ia_iobase == ISACF_PORT_DEFAULT)
		return 0;

	/* Map the i/o space. */
	if (bus_space_map(iot, ia->ia_iobase, LMS_NPORTS, 0, &ioh))
		return 0;

	rv = 0;

	/* Configure and check for port present. */
	bus_space_write_1(iot, ioh, LMS_CONFIG, 0x91);
	delay(10);
	bus_space_write_1(iot, ioh, LMS_SIGN, 0x0c);
	delay(10);
	if (bus_space_read_1(iot, ioh, LMS_SIGN) != 0x0c)
		goto out;
	bus_space_write_1(iot, ioh, LMS_SIGN, 0x50);
	delay(10);
	if (bus_space_read_1(iot, ioh, LMS_SIGN) != 0x50)
		goto out;

	/* Disable interrupts. */
	bus_space_write_1(iot, ioh, LMS_CNTRL, 0x10);

	rv = 1;
	ia->ia_iosize = LMS_NPORTS;
	ia->ia_msize = 0;

out:
	bus_space_unmap(iot, ioh, LMS_NPORTS);
	return rv;
}

void
lmsattach(parent, self, aux)
	struct device *parent, *self;
	void *aux;
{
	struct lms_softc *sc = (void *)self;
	struct isa_attach_args *ia = aux;
	bus_space_tag_t iot = ia->ia_iot;
	bus_space_handle_t ioh;
	struct wsmousedev_attach_args a;

	printf("\n");

	if (bus_space_map(iot, ia->ia_iobase, LMS_NPORTS, 0, &ioh)) {
		printf("%s: can't map i/o space\n", sc->sc_dev.dv_xname);
		return;
	}

	/* Other initialization was done by lmsprobe. */
	sc->sc_iot = iot;
	sc->sc_ioh = ioh;
	sc->sc_enabled = 0;

	sc->sc_ih = isa_intr_establish(ia->ia_ic, ia->ia_irq, IST_PULSE,
	    IPL_TTY, lmsintr, sc);

	a.accessops = &lms_accessops;
	a.accesscookie = sc;

	/*
	 * Attach the wsmouse, saving a handle to it.
	 * Note that we don't need to check this pointer against NULL
	 * here or in psmintr, because if this fails lms_enable() will
	 * never be called, so lmsintr() will never be called.
	 */
	sc->sc_wsmousedev = config_found(self, &a, wsmousedevprint);
}

int
lms_enable(v)
	void *v;
{
	struct lms_softc *sc = v;

	if (sc->sc_enabled)
		return EBUSY;

	sc->sc_enabled = 1;
	sc->oldbuttons = 0;

	/* Enable interrupts. */
	bus_space_write_1(sc->sc_iot, sc->sc_ioh, LMS_CNTRL, 0);

	return 0;
}

void
lms_disable(v)
	void *v;
{
	struct lms_softc *sc = v;

	/* Disable interrupts. */
	bus_space_write_1(sc->sc_iot, sc->sc_ioh, LMS_CNTRL, 0x10);

	sc->sc_enabled = 0;
}

int
lms_ioctl(v, cmd, data, flag, p)
	void *v;
	u_long cmd;
	caddr_t data;
	int flag;
	struct proc *p;
{
#if 0
	struct lms_softc *sc = v;
#endif

	switch (cmd) {
	case WSMOUSEIO_GTYPE:
		*(u_int *)data = WSMOUSE_TYPE_LMS;
		return (0);
	}
	return (-1);
}

int
lmsintr(arg)
	void *arg;
{
	struct lms_softc *sc = arg;
	bus_space_tag_t iot = sc->sc_iot;
	bus_space_handle_t ioh = sc->sc_ioh;
	u_char hi, lo;
	signed char dx, dy;
	u_int buttons;
	int changed;

	if (!sc->sc_enabled)
		/* Interrupts are not expected. */
		return 0;

	bus_space_write_1(iot, ioh, LMS_CNTRL, 0xab);
	hi = bus_space_read_1(iot, ioh, LMS_DATA);
	bus_space_write_1(iot, ioh, LMS_CNTRL, 0x90);
	lo = bus_space_read_1(iot, ioh, LMS_DATA);
	dx = ((hi & 0x0f) << 4) | (lo & 0x0f);
	/* Bounding at -127 avoids a bug in XFree86. */
	dx = (dx == -128) ? -127 : dx;

	bus_space_write_1(iot, ioh, LMS_CNTRL, 0xf0);
	hi = bus_space_read_1(iot, ioh, LMS_DATA);
	bus_space_write_1(iot, ioh, LMS_CNTRL, 0xd0);
	lo = bus_space_read_1(iot, ioh, LMS_DATA);
	dy = ((hi & 0x0f) << 4) | (lo & 0x0f);
	dy = (dy == -128) ? 127 : -dy;

	bus_space_write_1(iot, ioh, LMS_CNTRL, 0);

	buttons = ((hi & 0x80) ? 0 : 0x1) |
		((hi & 0x40) ? 0 : 0x2) |
		((hi & 0x20) ? 0 : 0x4);
	changed = (buttons ^ sc->oldbuttons);
	sc->oldbuttons = buttons;

	if (dx || dy || changed)
		wsmouse_input(sc->sc_wsmousedev,
			      buttons, dx, dy, 0);

	return -1;
}

redpajama_set_name: RedPajamaGithub


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('tracking', '0005_device_hidden'),
    ]

    operations = [
        migrations.AlterField(
            model_name='device',
            name='hidden',
            field=models.BooleanField(default=True, verbose_name='Hidden/private use'),
        ),
        migrations.AlterField(
            model_name='device',
            name='source_device_type',
            field=models.CharField(choices=[('tracplus', 'TracPlus'), ('iriditrak', 'Iriditrak'), ('dplus', 'DPlus'), ('spot', 'Spot'), ('dfes', 'DFES'), ('mp70', 'MP70'), ('fleetcare', 'fleetcare'), ('other', 'Other')], default='other', max_length=32),
        ),
        migrations.AlterField(
            model_name='loggedpoint',
            name='source_device_type',
            field=models.CharField(choices=[('tracplus', 'TracPlus'), ('iriditrak', 'Iriditrak'), ('dplus', 'DPlus'), ('spot', 'Spot'), ('dfes', 'DFES'), ('mp70', 'MP70'), ('fleetcare', 'fleetcare'), ('other', 'Other')], default='other', max_length=32),
        ),
    ]


text:
{% if doc.usageNotes %}

Usage Notes

  {$ doc.usageNotes | marked $}

{% endif %}


text:
]]

local parent, ns = ...
local oUF = ns.oUF

local _PATTERN = '%[..-%]+'

local _ENV = {
	Hex = function(r, g, b)
		if type(r) == "table" then
			if r.r then r, g, b = r.r, r.g, r.b else r, g, b = unpack(r) end
		end
		return string.format("|cff%02x%02x%02x", r*255, g*255, b*255)
	end,
	ColorGradient = oUF.ColorGradient,
}
local _PROXY = setmetatable(_ENV, {__index = _G})

local tagStrings = {
	["creature"] = [[function(u)
		return UnitCreatureFamily(u) or UnitCreatureType(u)
	end]],

	["dead"] = [[function(u)
		if(UnitIsDead(u)) then
			return 'Dead'
		elseif(UnitIsGhost(u)) then
			return 'Ghost'
		end
	end]],

	["difficulty"] = [[function(u)
		if UnitCanAttack("player", u) then
			local l = UnitLevel(u)
			return Hex(GetQuestDifficultyColor((l > 0) and l or 99))
		end
	end]],

	["leader"] = [[function(u)
		if(UnitIsGroupLeader(u)) then
			return 'L'
		end
	end]],

	["leaderlong"]  = [[function(u)
		if(UnitIsGroupLeader(u)) then
			return 'Leader'
		end
	end]],

	["level"] = [[function(u)
		local l = UnitLevel(u)
		if(UnitIsWildBattlePet(u) or UnitIsBattlePetCompanion(u)) then
			l = UnitBattlePetLevel(u)
		end

		if(l > 0) then
			return l
		else
			return '??'
		end
	end]],

	["missinghp"] = [[function(u)
		local current = UnitHealthMax(u) - UnitHealth(u)
		if(current > 0) then
			return current
		end
	end]],

	["missingpp"] = [[function(u)
		local current = UnitPowerMax(u) - UnitPower(u)
		if(current > 0) then
			return current
		end
	end]],

	["name"] = [[function(u, r)
		return UnitName(r or u)
	end]],

	["offline"] = [[function(u)
		if(not UnitIsConnected(u)) then
			return 'Offline'
		end
	end]],

	["perhp"] = [[function(u)
		local m = UnitHealthMax(u)
		if(m == 0) then
			return 0
		else
			return math.floor(UnitHealth(u)/m*100+.5)
		end
	end]],

	["perpp"] = [[function(u)
		local m = UnitPowerMax(u)
		if(m == 0) then
			return 0
		else
			return math.floor(UnitPower(u)/m*100+.5)
		end
	end]],

	["plus"] = [[function(u)
		local c = UnitClassification(u)
		if(c == 'elite' or c == 'rareelite') then
			return '+'
		end
	end]],

	["pvp"] = [[function(u)
		if(UnitIsPVP(u)) then
			return 'PvP'
		end
	end]],

	["raidcolor"] = [[function(u)
		local _, x = UnitClass(u)
		if(x) then
			return Hex(_COLORS.class[x])
		end
	end]],

	["rare"] = [[function(u)
		local c = UnitClassification(u)
		if(c == 'rare' or c == 'rareelite') then
			return 'Rare'
		end
	end]],

	["resting"] = [[function(u)
		if(u == 'player' and IsResting()) then
			return 'zzz'
		end
	end]],

	["sex"] = [[function(u)
		local s = UnitSex(u)
		if(s == 2) then
			return 'Male'
		elseif(s == 3) then
			return 'Female'
		end
	end]],

	["smartclass"] = [[function(u)
		if(UnitIsPlayer(u)) then
			return _TAGS['class'](u)
		end

		return _TAGS['creature'](u)
	end]],

	["status"] = [[function(u)
		if(UnitIsDead(u)) then
			return 'Dead'
		elseif(UnitIsGhost(u)) then
			return 'Ghost'
		elseif(not UnitIsConnected(u)) then
			return 'Offline'
		else
			return _TAGS['resting'](u)
		end
	end]],

	["threat"] = [[function(u)
		local s = UnitThreatSituation(u)
		if(s == 1) then
			return '++'
		elseif(s == 2) then
			return '--'
		elseif(s == 3) then
			return 'Aggro'
		end
	end]],

	["threatcolor"] = [[function(u)
		return Hex(GetThreatStatusColor(UnitThreatSituation(u)))
	end]],

	["cpoints"] = [[function(u)
		local cp
		if(UnitHasVehicleUI'player') then
			cp = GetComboPoints('vehicle', 'target')
		else
			cp = GetComboPoints('player', 'target')
		end

		if(cp > 0) then
			return cp
		end
	end]],

	['smartlevel'] = [[function(u)
		local c = UnitClassification(u)
		if(c == 'worldboss') then
			return 'Boss'
		else
			local plus = _TAGS['plus'](u)
			local level = _TAGS['level'](u)
			if(plus) then
				return level .. plus
			else
				return level
			end
		end
	end]],

	["classification"] = [[function(u)
		local c = UnitClassification(u)
		if(c == 'rare') then
			return 'Rare'
		elseif(c == 'rareelite') then
			return 'Rare Elite'
		elseif(c == 'elite') then
			return 'Elite'
		elseif(c == 'worldboss') then
			return 'Boss'
		elseif(c == 'minus') then
			return 'Affix'
		end
	end]],

	["shortclassification"] = [[function(u)
		local c = UnitClassification(u)
		if(c == 'rare') then
			return 'R'
		elseif(c == 'rareelite') then
			return 'R+'
		elseif(c == 'elite') then
			return '+'
		elseif(c == 'worldboss') then
			return 'B'
		elseif(c == 'minus') then
			return '-'
		end
	end]],

	["group"] = [[function(unit)
		local name, server = UnitName(unit)
		if(server and server ~= "") then
			name = string.format("%s-%s", name, server)
		end

		for i=1, GetNumGroupMembers() do
			local raidName, _, group = GetRaidRosterInfo(i)
			if( raidName == name ) then
				return group
			end
		end
	end]],

	["deficit:name"] = [[function(u)
		local missinghp = _TAGS['missinghp'](u)
		if(missinghp) then
			return '-' .. missinghp
		else
			return _TAGS['name'](u)
		end
	end]],

	['pereclipse'] = [[function(u)
		local m = UnitPowerMax('player', SPELL_POWER_ECLIPSE)
		if(m == 0) then
			return 0
		else
			return math.abs(UnitPower('player', SPELL_POWER_ECLIPSE)/m*100)
		end
	end]],

	['curmana'] = [[function(unit)
		return UnitPower(unit, SPELL_POWER_MANA)
	end]],

	['maxmana'] = [[function(unit)
		return UnitPowerMax(unit, SPELL_POWER_MANA)
	end]],

	['soulshards'] = [[function()
		local num = UnitPower('player', SPELL_POWER_SOUL_SHARDS)
		if(num > 0) then
			return num
		end
	end]],

	['holypower'] = [[function()
		local num = UnitPower('player', SPELL_POWER_HOLY_POWER)
		if(num > 0) then
			return num
		end
	end]],

	['chi'] = [[function()
		local num = UnitPower('player', SPELL_POWER_CHI)
		if(num > 0) then
			return num
		end
	end]],

	['shadoworbs'] = [[function()
		local num = UnitPower('player', SPELL_POWER_SHADOW_ORBS)
		if(num > 0) then
			return num
		end
	end]],

	['affix'] = [[function(u)
		local c = UnitClassification(u)
		if(c == 'minus') then
			return 'Affix'
		end
	end]],
}

local tags = setmetatable(
	{
		curhp = UnitHealth,
		curpp = UnitPower,
		maxhp = UnitHealthMax,
		maxpp = UnitPowerMax,
		class = UnitClass,
		faction = UnitFactionGroup,
		race = UnitRace,
	},

	{
		__index = function(self, key)
			local tagFunc = tagStrings[key]
			if(tagFunc) then
				local func, err = loadstring('return ' .. tagFunc)
				if(func) then
					func = func()

					-- Want to trigger __newindex, so no rawset.
					self[key] = func
					tagStrings[key] = nil

					return func
				else
					error(err, 3)
				end
			end
		end,
		__newindex = function(self, key, val)
			if(type(val) == 'string') then
				tagStrings[key] = val
			elseif(type(val) == 'function') then
				-- So we don't clash with any custom envs.
				if(getfenv(val) == _G) then
					setfenv(val, _PROXY)
				end

				rawset(self, key, val)
			end
		end,
	}
)

_ENV._TAGS = tags

local tagEvents = {
	["curhp"]               = "UNIT_HEALTH",
	["dead"]                = "UNIT_HEALTH",
	["leader"]              = "PARTY_LEADER_CHANGED",
	["leaderlong"]          = "PARTY_LEADER_CHANGED",
	["level"]               = "UNIT_LEVEL PLAYER_LEVEL_UP",
	["maxhp"]               = "UNIT_MAXHEALTH",
	["missinghp"]           = "UNIT_HEALTH UNIT_MAXHEALTH",
	["name"]                = "UNIT_NAME_UPDATE",
	["perhp"]               = "UNIT_HEALTH UNIT_MAXHEALTH",
	["pvp"]                 = "UNIT_FACTION",
	["resting"]             = "PLAYER_UPDATE_RESTING",
	["smartlevel"]          = "UNIT_LEVEL PLAYER_LEVEL_UP UNIT_CLASSIFICATION_CHANGED",
	["threat"]              = "UNIT_THREAT_SITUATION_UPDATE",
	["threatcolor"]         = "UNIT_THREAT_SITUATION_UPDATE",
	['cpoints']             = 'UNIT_COMBO_POINTS PLAYER_TARGET_CHANGED',
	['affix']				= 'UNIT_CLASSIFICATION_CHANGED',
	['plus']				= 'UNIT_CLASSIFICATION_CHANGED',
	['rare']                = 'UNIT_CLASSIFICATION_CHANGED',
	['classification']      = 'UNIT_CLASSIFICATION_CHANGED',
	['shortclassification'] = 'UNIT_CLASSIFICATION_CHANGED',
	["group"]               = "GROUP_ROSTER_UPDATE",
	["curpp"]               = 'UNIT_POWER',
	["maxpp"]               = 'UNIT_MAXPOWER',
	["missingpp"]           = 'UNIT_MAXPOWER UNIT_POWER',
	["perpp"]               = 'UNIT_MAXPOWER UNIT_POWER',
	["offline"]             = "UNIT_HEALTH UNIT_CONNECTION",
	["status"]              = "UNIT_HEALTH PLAYER_UPDATE_RESTING UNIT_CONNECTION",
	["pereclipse"]          = 'UNIT_POWER',
	['curmana']             = 'UNIT_POWER UNIT_MAXPOWER',
	['maxmana']             = 'UNIT_POWER UNIT_MAXPOWER',
	['soulshards']          = 'UNIT_POWER',
	['holypower']           = 'UNIT_POWER',
	['chi']                 = 'UNIT_POWER',
	['shadoworbs']          = 'UNIT_POWER',
}

local unitlessEvents = {
	PLAYER_LEVEL_UP = true,
	PLAYER_UPDATE_RESTING = true,
	PLAYER_TARGET_CHANGED = true,

	PARTY_LEADER_CHANGED = true,

	GROUP_ROSTER_UPDATE = true,

	UNIT_COMBO_POINTS = true
}

local events = {}
local frame = CreateFrame"Frame"
frame:SetScript('OnEvent', function(self, event, unit)
	local strings = events[event]
	if(strings) then
		for k, fontstring in next, strings do
			if(fontstring:IsVisible() and (unitlessEvents[event] or fontstring.parent.unit == unit)) then
				fontstring:UpdateTag()
			end
		end
	end
end)

local OnUpdates = {}
local eventlessUnits = {}

local createOnUpdate = function(timer)
	local OnUpdate = OnUpdates[timer]

	if(not OnUpdate) then
		local total = timer
		local frame = CreateFrame'Frame'
		local strings = eventlessUnits[timer]

		frame:SetScript('OnUpdate', function(self, elapsed)
			if(total >= timer) then
				for k, fs in next, strings do
					if(fs.parent:IsShown() and UnitExists(fs.parent.unit)) then
						fs:UpdateTag()
					end
				end

				total = 0
			end

			total = total + elapsed
		end)

		OnUpdates[timer] = frame
	end
end

local OnShow = function(self)
	for _, fs in next, self.__tags do
		fs:UpdateTag()
	end
end

local getTagName = function(tag)
	local s = (tag:match('>+()') or 2)
	local e = tag:match('.*()<+')
	e = (e and e - 1) or -2

	return tag:sub(s, e), s, e
end

local RegisterEvent = function(fontstr, event)
	if(not events[event]) then events[event] = {} end

	frame:RegisterEvent(event)
	table.insert(events[event], fontstr)
end

local RegisterEvents = function(fontstr, tagstr)
	for tag in tagstr:gmatch(_PATTERN) do
		tag = getTagName(tag)
		local tagevents = tagEvents[tag]
		if(tagevents) then
			for event in tagevents:gmatch'%S+' do
				RegisterEvent(fontstr, event)
			end
		end
	end
end

local UnregisterEvents = function(fontstr)
	for event, data in pairs(events) do
		for k, tagfsstr in pairs(data) do
			if(tagfsstr == fontstr) then
				if(#data == 1) then
					frame:UnregisterEvent(event)
				end

				table.remove(data, k)
			end
		end
	end
end

local tagPool = {}
local funcPool = {}
local tmp = {}

local Tag = function(self, fs, tagstr)
	if(not fs or not tagstr) then return end

	if(not self.__tags) then
		self.__tags = {}
		table.insert(self.__elements, OnShow)
	else
		-- Since people ignore everything that's good practice - unregister the tag
		-- if it already exists.
		for _, tag in pairs(self.__tags) do
			if(fs == tag) then
				-- We don't need to remove it from the __tags table as Untag handles
				-- that for us.
				self:Untag(fs)
			end
		end
	end

	fs.parent = self

	local func = tagPool[tagstr]
	if(not func) then
		local format, numTags = tagstr:gsub('%%', '%%%%'):gsub(_PATTERN, '%%s')
		local args = {}

		for bracket in tagstr:gmatch(_PATTERN) do
			local tagFunc = funcPool[bracket] or tags[bracket:sub(2, -2)]
			if(not tagFunc) then
				local tagName, s, e = getTagName(bracket)

				local tag = tags[tagName]
				if(tag) then
					s = s - 2
					e = e + 2

					if(s ~= 0 and e ~= 0) then
						local pre = bracket:sub(2, s)
						local ap = bracket:sub(e, -2)

						tagFunc = function(u,r)
							local str = tag(u,r)
							if(str) then
								return pre..str..ap
							end
						end
					elseif(s ~= 0) then
						local pre = bracket:sub(2, s)

						tagFunc = function(u,r)
							local str = tag(u,r)
							if(str) then
								return pre..str
							end
						end
					elseif(e ~= 0) then
						local ap = bracket:sub(e, -2)

						tagFunc = function(u,r)
							local str = tag(u,r)
							if(str) then
								return str..ap
							end
						end
					end

					funcPool[bracket] = tagFunc
				end
			end

			if(tagFunc) then
				table.insert(args, tagFunc)
			else
				return error(('Attempted to use invalid tag %s.'):format(bracket), 3)
			end
		end

		if(numTags == 1) then
			func = function(self)
				local parent = self.parent
				local realUnit
				if(self.overrideUnit) then
					realUnit = parent.realUnit
				end

				_ENV._COLORS = parent.colors
				return self:SetFormattedText(
					format,
					args[1](parent.unit, realUnit) or ''
				)
			end
		elseif(numTags == 2) then
			func = function(self)
				local parent = self.parent
				local unit = parent.unit
				local realUnit
				if(self.overrideUnit) then
					realUnit = parent.realUnit
				end

				_ENV._COLORS = parent.colors
				return self:SetFormattedText(
					format,
					args[1](unit, realUnit) or '',
					args[2](unit, realUnit) or ''
				)
			end
		elseif(numTags == 3) then
			func = function(self)
				local parent = self.parent
				local unit = parent.unit
				local realUnit
				if(self.overrideUnit) then
					realUnit = parent.realUnit
				end

				_ENV._COLORS = parent.colors
				return self:SetFormattedText(
					format,
					args[1](unit, realUnit) or '',
					args[2](unit, realUnit) or '',
					args[3](unit, realUnit) or ''
				)
			end
		else
			func = function(self)
				local parent = self.parent
				local unit = parent.unit
				local realUnit
				if(self.overrideUnit) then
					realUnit = parent.realUnit
				end

				_ENV._COLORS = parent.colors
				for i, func in next, args do
					tmp[i] = func(unit, realUnit) or ''
				end

				-- We do 1, numTags because tmp can hold several unneeded variables.
				return self:SetFormattedText(format, unpack(tmp, 1, numTags))
			end
		end

		tagPool[tagstr] = func
	end
	fs.UpdateTag = func

	local unit = self.unit
	if((unit and unit:match'%w+target') or fs.frequentUpdates) then
		local timer
		if(type(fs.frequentUpdates) == 'number') then
			timer = fs.frequentUpdates
		else
			timer = .5
		end

		if(not eventlessUnits[timer]) then eventlessUnits[timer] = {} end
		table.insert(eventlessUnits[timer], fs)

		createOnUpdate(timer)
	else
		RegisterEvents(fs, tagstr)
	end

	table.insert(self.__tags, fs)
end

local Untag = function(self, fs)
	if(not fs) then return end

	UnregisterEvents(fs)
	for _, timers in next, eventlessUnits do
		for k, fontstr in next, timers do
			if(fs == fontstr) then
				table.remove(timers, k)
			end
		end
	end

	for k, fontstr in next, self.__tags do
		if(fontstr == fs) then
			table.remove(self.__tags, k)
		end
	end

	fs.UpdateTag = nil
end

oUF.Tags = {
	Methods = tags,
	Events = tagEvents,
	SharedEvents = unitlessEvents,

}
oUF:RegisterMetaFunction('Tag', Tag)
oUF:RegisterMetaFunction('Untag', Untag)


text:
layout: page
title: Peck - Goodwin Wedding
date: 2016-05-24
author: Terry Meza
tags: weekly links, java
status: published
summary: Sed at augue in est auctor condimentum vel nec orci.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 01/25/2018
  endDate: 01/27/2018
  ctyhocn: MGCHXHX
  groupCode: PGW
published: true
---
Integer purus magna, posuere vitae rutrum nec, imperdiet sit amet sapien. In laoreet quam sit amet porta posuere. Aliquam erat volutpat. Aliquam vel vestibulum dui, eget mollis nulla. Ut blandit, orci ac sodales maximus, dolor diam cursus mauris, ac blandit lorem mauris tincidunt ligula. Ut quis nisl erat. Vivamus ut fringilla justo. Nam porta dictum lacus at elementum. Donec non finibus arcu. Aliquam suscipit sem mi, sed faucibus mauris accumsan in. Aliquam tempus, justo sed vulputate vestibulum, nisl arcu vulputate enim, at semper enim velit a enim. Nullam faucibus quis justo quis venenatis. Mauris vehicula volutpat tristique.
Phasellus aliquam urna tortor, sit amet fringilla urna hendrerit a. Morbi congue, urna id vestibulum semper, quam ante porttitor neque, sit amet venenatis ligula magna eget tortor. Ut viverra aliquet tortor quis feugiat. Maecenas accumsan libero eu diam rhoncus dictum vel et elit. Mauris a sem sit amet ex feugiat condimentum. Ut eget dignissim ante. Nulla a venenatis ipsum, eget finibus velit. Praesent consectetur nec velit et congue. Mauris pretium vitae nisi et feugiat.

1 Mauris iaculis est nec semper auctor
1 Aliquam scelerisque sapien eget enim porta luctus.

Pellentesque non leo in massa rhoncus pharetra. Proin quis nisi leo. Pellentesque vulputate pulvinar nisi, sed ultricies arcu. Proin pharetra sed nisi quis porta. Phasellus nec ipsum diam. Nam in urna id nisi bibendum egestas. Vestibulum augue enim, viverra et sollicitudin sit amet, facilisis pharetra nunc. Aenean maximus libero at lorem rutrum, ut porta erat vulputate. Nunc in leo a ligula vulputate vestibulum. Sed sodales dolor ac lacinia placerat. Nunc posuere lacinia odio. Proin consectetur at ligula vitae pulvinar. Duis at augue dictum, vehicula risus eget, venenatis tortor. Sed posuere vel justo nec fringilla. Donec sodales tristique imperdiet.


text:
Zeal Optics Wedstrijd

Applicatie

Het is een applicatie voor een wedstrijd van Zeal Optic.
Men kan hier een waanzinnige ski-bril met ingebouwde HD camera winnen.
In deze applicatie moet je je registreren om deel te nemen.
Daarna kunt je een photo van je ski vakantie uploadden.
Iedereen mag maar een keer aan deel nemen.
Iedereen mag ook maar een keer voor een photo stemmen (een stem per photo).
Drie photos met de meeste stemmen winnen.
Elke periode zijn er dus drie winnaars die op de front-pagina komen te staan.
Applicatie kan de winnaars naar de verantwoordelijke via mail versturen als de cron jobs ingesteld zijn.
Applicatie kan ook een lijst van mensen die deel hebben genomen, dus een excel document opmaken en elke nacht naar de verantwoordelijke via mail versturen.
Er is een administratieve gedeelte voorzien. Daarvoor moet men inloggen.
Als admin kan je de periodes van de wedstrijd aanpassen of meer periodes toevoegen.

Installatie

Server requirements:
•	PHP >= 5.5.9
•	OpenSSL PHP Extension
•	PDO PHP Extension
•	Mbstring PHP Extension
•	Tokenizer PHP Extension

Om sommige zaken automatisch te kunnen generen hebben we ook composer nodig:

Composer installeren:

- curl -sS https://getcomposer.org/installer | php
- mv composer.phar /usr/local/bin/composer
- echo 'export PATH="$PATH:~/.composer/vendor/bin"' >> ~/.bashrc
- source ~/.bashrc

Installatie van de applicatie

    download repository in /var/www of in je gewenste pad /var/www/your_path:
            git clone https://github.com/JolitaGrazyte/webdev_examen.git

    - site directory root voor apache site configuratie file is nu:
            /var/www/your_path/webdev_examen/public

    als je applicatie in een andere directory wilt:

    verplaats alle files van  webdev_examen map naar je gewenste pad
        bv.: /var/www/your_path/public

    ga naar applicatie root (zoals nu naar  /var/www/your_path/webdev_examen/ )

    applicatie heeft een .env file nodig

        - daarom kopieer .env.toReplace  file en verander de gegevens voor databank:
        mv .env.toReplace .env  of cp .env.toReplace .env

        pas de volgende aan in .env  file:

            DB_DATABASE=YOUR_DB_NAME # must be changed
            DB_USERNAME=YOUR_DB_USER # must be changed
            DB_PASSWORD=YOUR_DB_PASSWORD # must be changed

    verder run de volgende commandos:

        composer install of sudo composer install
        chmod -R 777 storage of sudo chmod -R 777 storage
        chmod -R 777 bootstrap/cache of sudo chmod -R 777 bootstrap/cache

    in de root of de application run volgende commandos:

        php artisan migrate (om databank tabellen automatisch aan te maken)
        almost ready to use! :-)

    Om applicatie  te kunnen testen met 'fake' data run volgende commandos:
            php artisan db:seed

    Om proper opnieuw te beginnen:
        php artisan migrate:rollback
        php artisan migrate
        seed alleen maar admin account:
        php artisan db:seed --class=SeedOnlyAdmin

Nu kunt je inloggen naar administratieve gedeelte met volgende gegevens:
    username: admin
    password: test

In administratieve gedeelte kunt je periodes toevoegen.
Je kunt ook je email adres en password veranderen.

Als je wilt alleen periodes automatisch aanmaken, kunt je de volgende commando runnen:

    php artisan db:seed --class=PeriodsSeeder

Nu is het klaar om te gebruiken.

Om een email met de winnaars en de mensen die hebben meegedaan te kunnen ontvangen dan moet je nog cron installeren.
    Run commando:  crontab -e
    Zet de volgende lijn in je crontab:
    * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

Administratieve gedeelte i bereikbaar via  http://je-site-naam/admin.


text:
<?php defined('BX_DOL') or die('hack attempt');

/**
 * Database queries for category objects.
 * @see BxDolCategory
 */
class BxDolCategoryQuery extends BxDolDb
{
    protected $_aObject;

    public function __construct($aObject)
    {
        parent::__construct();
        $this->_aObject = $aObject;
    }

    static public function getCategoryObject ($sObject)
    {
        $oDb = BxDolDb::getInstance();
        $sQuery = $oDb->prepare("SELECT * FROM `sys_objects_category` WHERE `object` = ?", $sObject);
        $aObject = $oDb->getRow($sQuery);
        if (!$aObject || !is_array($aObject))
            return false;

        return $aObject;
    }

    static public function getCategoryObjectByFormAndList ($sObjectForm, $sListName)
    {
        $oDb = BxDolDb::getInstance();
        $sQuery = $oDb->prepare("SELECT * FROM `sys_objects_category` WHERE `form_object` = ? AND `list_name` = ?", $sObjectForm, $sListName);
        $aObject = $oDb->getRow($sQuery);
        if (!$aObject || !is_array($aObject))
            return false;

        return $aObject;
    }

    static public function getItemsNumInCategory ($aObject, $sCategoryValue, $bPublicOnly = true)
    {
        $oDb = BxDolDb::getInstance();
        $sWhere = '';
        // TODO: in the future add 'module' field to categories object
        if ($bPublicOnly && ($oModule = BxDolModule::getInstance($aObject['search_object'])) && isset($oModule->_oConfig->CNF)) {
            $CNF = &$oModule->_oConfig->CNF;

            if(isset($CNF['FIELD_ALLOW_VIEW_TO'])) {
                bx_import('BxDolPrivacy');
                $a = isLogged() ? array(BX_DOL_PG_ALL, BX_DOL_PG_MEMBERS) : array(BX_DOL_PG_ALL);
                $sWhere .= ' AND `' . $aObject['table'] . '`.`' . $CNF['FIELD_ALLOW_VIEW_TO'] . '` IN(' . $oDb->implode_escape($a) . ') ';
            }

            if(isset($CNF['FIELD_STATUS']))
                $sWhere .= ' AND `' . $aObject['table'] . '`.`' . $CNF['FIELD_STATUS'] . '` = \'active\' ';

            if(isset($CNF['FIELD_STATUS_ADMIN']))
                $sWhere .= ' AND `' . $aObject['table'] . '`.`' . $CNF['FIELD_STATUS_ADMIN'] . '` = \'active\' ';
        }
        return $oDb->getOne("SELECT COUNT(*) FROM `" . $aObject['table'] . "` " . $aObject['join'] . " WHERE `" . $aObject['field'] . "` = :cat " . $aObject['where'] . $sWhere, array('cat' => $sCategoryValue));
    }
}

/** @} */


text:
// Ŭnicode please
#include "device.h"
#include "globals.h"
#include <conio.h>
#include <Windows.h>
#include <ctime>

#include "level.h"
#include "snake.h"

const char *WALL_HORIZONTAL = "─";
const char *WALL_VERTICAL = "│";
const char *WALL_TOP_LEFT = "┌";
const char *WALL_TOP_RIGHT = "┐";
const char *WALL_BOTTOM_LEFT = "└";
const char *WALL_BOTTOM_RIGHT = "┘";

const char *HEAD = "@";
const char *TAIL = "■";
const char *APPLE = "♡";
const char *EMPTY = "  ";

Renderer::Renderer()
{
	std::fill(prev_buffer_.begin(), prev_buffer_.end(), ' ');
	int buffer_width = BOARD_WIDTH + 2;
	int buffer_height = HEIGHT;
	for (int y = 0; y < buffer_height; ++y) {
		int newline_idx = toCoord(y, buffer_width);
		prev_buffer_[newline_idx] = '\0';
	}

	//fillBorder(&prev_buffer_);
}

int Renderer::toCoord(int y, int x) const
{
	return (y * WIDTH_WITH_NEWLINE) + (x * 2);
}

void Renderer::fillBorder(framebuffer_t *buffer)
{
	int buffer_width = BOARD_WIDTH + 2;
	int buffer_height = HEIGHT;

	// reset buffer
	std::fill(buffer->begin(), buffer->end(), ' ');
	for (int y = 0; y < buffer_height; ++y) {
		if (y == 0 || y == (buffer_height - 1)) {
			for (int x = 0; x < buffer_width; ++x) {
				int idx = toCoord(y, x);
				memcpy(buffer->data() + idx, WALL_HORIZONTAL, 2);
			}
		}
		int left_wall_idx = toCoord(y, 0);
		int right_wall_idx = toCoord(y, buffer_width - 1);
		memcpy(buffer->data() + left_wall_idx, WALL_VERTICAL, 2);
		memcpy(buffer->data() + right_wall_idx, WALL_VERTICAL, 2);

		if (y == 0) {
			int left_idx = toCoord(y, 0);
			int right_idx = toCoord(y, buffer_width - 1);
			memcpy(buffer->data() + left_idx, WALL_TOP_LEFT, 2);
			memcpy(buffer->data() + right_idx, WALL_TOP_RIGHT, 2);
		}
		if (y == (HEIGHT - 1)) {
			int left_idx = toCoord(y, 0);
			int right_idx = toCoord(y, buffer_width - 1);
			memcpy(buffer->data() + left_idx, WALL_BOTTOM_LEFT, 2);
			memcpy(buffer->data() + right_idx, WALL_BOTTOM_RIGHT, 2);
		}

		int newline_idx = toCoord(y, buffer_width);
		(*buffer)[newline_idx] = '\0';
	}
}

void Renderer::fillLevel(const Level &lv, framebuffer_t *buffer)
{
	Position apple_pos = Position::decode(lv.apple_pos());
	int idx = toCoord(apple_pos.y + 1, apple_pos.x + 1);
	memcpy(buffer->data() + idx, APPLE, 2);
}

void Renderer::fillSnake(const Snake &snake, framebuffer_t *buffer)
{
	position_t head_pos = snake.getHead();
	Position pos = Position::decode(head_pos);
	int head_idx = toCoord(pos.y + 1, pos.x + 1);
	memcpy(buffer->data() + head_idx, HEAD, 2);

	auto tail = snake.getTail();
	for (auto tail_pos : tail) {
		Position pos = Position::decode(tail_pos);
		int tail_idx = toCoord(pos.y + 1, pos.x + 1);
		memcpy(buffer->data() + tail_idx, TAIL, 2);
	}
}
void Renderer::renderBuffer(const framebuffer_t &buffer) const
{
	for (int y = 0; y < HEIGHT; ++y) {
		int idx = toCoord(y, 0);
		const unsigned char *ptr = buffer.data() + idx;
		printf("%s\n", ptr);
	}
}

void Renderer::render(const Level &lv, const Snake &snake)
{
	gotoxy(1, 1);
	printf("%c=Left / %c = Right / %c=Reset / %c=Quit\n",
		KEY_TURN_LEFT, KEY_TURN_RIGHT, KEY_RESET, KEY_QUIT);

	gotoxy(2, 1);
	printf("Turn = %d, Score = %d / HighScore = %d\n", snake.age(), snake.score(), Snake::getHighScore());

	framebuffer_t curr_buffer;
	fillBorder(&curr_buffer);
	fillLevel(lv, &curr_buffer);
	fillSnake(snake, &curr_buffer);

	// prev와 curr의 차이를 찾아서 변경지점만 렌더링
	for (int y = 0; y < HEIGHT; ++y) {
		for(int x = 0; x < BOARD_WIDTH + 2; ++x) {
			int coord = toCoord(y, x);
			unsigned char curr = curr_buffer[coord];
			unsigned char prev = prev_buffer_[coord];
			if (curr != prev) {
				unsigned char buffer[3];
				memcpy(buffer, curr_buffer.data() + coord, 2);
				buffer[2] = '\0';

				gotoxy(y + 3, x * 2 + 1);
				printf("%s", buffer);
			}
		}
	}

	//renderBuffer(prev_buffer_);
	std::copy(curr_buffer.begin(), curr_buffer.end(), prev_buffer_.begin());

	if (snake.running() == false) {
		gotoxy(HEIGHT + 3, 1);
		printf("Game Over. Score=%d, Restart=%c\n", snake.score(), KEY_RESET);
	}
}

void Renderer::clear()
{
	system("cls");
}

void Renderer::gotoxy(int y, int x)
{
	COORD pos = { x - 1, y - 1 };
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}

////////////////////////
Event GameDevice::getKeyEvent()
{
	if (kbhit()) {
		int c = getch();
		switch (c) {
		case KEY_TURN_LEFT:
			return Event(EVT_TURN_LEFT);
		case KEY_TURN_RIGHT:
			return Event(EVT_TURN_RIGHT);
		case KEY_QUIT:
			return Event(EVT_GAME_QUIT);
		case KEY_RESET:
			return Event(EVT_GAME_RESET);
		}
	}

	Event evt;
	return evt;
}
void GameDevice::sleep(int ms)
{
	Sleep(ms);
}

GameDevice &GameDevice::getInstance()
{
	static GameDevice ctx;
	return ctx;
}

void GameDevice::setUp()
{
	srand((unsigned int)time(NULL));
}

void GameDevice::cleanUp()
{

}


text:
(function(root, mod) {
  if (typeof exports == "object" && typeof module == "object") return mod(exports); // CommonJS
    if (typeof define == "function" && define.amd) return define(["exports"], mod); // AMD
      mod(root.JSTester || (root.JSTester = {})); // Plain browser env
    })(this, function(exports) {
      "use strict";
      var acorn = require('acorn');
      var walk = require('acorn/util/walk');

      var validNodeTypes = {
        // basic
        "Printable": true,
        "Node": true,
        "SourceLocation": true,
        "Position": true,
        "Program": true,
        "Function": true,
        "BlockStatement": true,
        "ExpressionStatement": true,
        "IfStatement": true,
        "LabeledStatement": true,
        "BreakStatement": true,
        "ContinueStatement": true,
        "WithStatement": true,
        "SwitchStatement": true,
        "ReturnStatement": true,
        "ThrowStatement": true,
        "TryStatement": true,
        "CatchClause": true,
        "WhileStatement": true,
        "DoWhileStatement": true,
        "ForStatement": true,
        "ForInStatement": true,
        "FunctionDeclaration": true,
        "FunctionExpression": true,
        "VariableDeclaration": true,
        "VariableDeclarator": true,
        "ArrayExpression": true,
        "ObjectExpression": true,
        "Property": true,
        "SequenceExpression": true,
        "UnaryExpression": true,
        "BinaryExpression": true,
        "AssignmentExpression": true,
        "UpdateExpression": true,
        "LogicalExpression": true,
        "ConditionalExpression": true,
        "NewExpression": true,
        "CallExpression": true,
        "MemberExpression": true,
        "ObjectPattern": true,
        "PropertyPattern": true,
        "ArrayPattern": true,
        "SwitchCase": true,
        "Identifier": true,
        "Literal": true,
        "Block": true,
        "Line": true,

        // ES6
        "ArrowFunctionExpression": true,
        "YieldExpression": true,
        "GeneratorExpression": true,
        "ComprehensionExpression": true,
        "ComprehensionBlock": true,
        "ModuleSpecifier": true,
        "MethodDefinition": true,
        "SpreadElement": true,
        "SpreadElementPattern": true,
        "ClassProperty": true,
        "ClassBody": true,
        "ClassDeclaration": true,
        "ClassExpression": true,
        "ClassImplements": true,
        "NamedSpecifier": true,
        "ExportSpecifier": true,
        "ExportBatchSpecifier": true,
        "ImportSpecifier": true,
        "ImportNamespaceSpecifier": true,
        "ImportDefaultSpecifier": true,
        "ExportDeclaration": true,
        "ImportDeclaration": true,
        "TaggedTemplateExpression": true,
        "TemplateLiteral": true,
        "TemplateElement": true,
      };
      exports.validNodeTypes = validNodeTypes;

      var validOptions = ["whiteList", "blackList", "structure"];
      exports.validOptions = validOptions;

      var test = function(input, opts) {
        if (!opts) {
          return {success: false, error: "options is not specified"};
        }
        var options = {};
        // validate options
        exports.validOptions.forEach(function(optionKey) {
          if (has(opts, optionKey) && Array.isArray(opts[optionKey])) {
            // validate node types
            var optionValue = opts[optionKey],
            validatedOptionValue = optionValue.reduce(function(acc, nodeType) {
              if (has(exports.validNodeTypes, nodeType)) {
                acc.push(nodeType);
              } else {
                console.log("Node type \""+nodeType+"\" is invalid.");
              }
              return acc;
            }, []);
            if (validatedOptionValue.length > 0) {
              options[optionKey] = validatedOptionValue;
            }
          }
        });

        if (Object.keys(options).length === 0) {
          return {success: false, error: "options is empty or no valid options"};
        }

        options.whiteList = has(options, "whiteList") ? unique(options.whiteList) : [];
        options.blackList = has(options, "blackList") ? unique(options.blackList) : [];
        options.structure = has(options, "structure") ? options.structure : [];

        if (options.whiteList.union(options.blackList).length>0) {
          return {success: false, error: "white list and black list are conflicting"};
        }

        // console.log("options: "+JSON.stringify(options));

        try {
          var parsed = acorn.parse(input, {});
        } catch (err) {
          return {success: false, error: "parserError: "+err};
        }

        // test white and black list
        var listsTestResults = function(whiteList, blackList) {
          var visitors = {};

          var whiteListOutput = [],
          whiteListNodeHandler = simpleWalkNodeHandler(whiteList, whiteListOutput);
          whiteList.forEach(function (nodeType) {
            visitors[nodeType] = whiteListNodeHandler;
          });

          var blackListOutput = [],
          blackListNodeHandler = simpleWalkNodeHandler(blackList, blackListOutput);
          blackList.forEach(function (nodeType) {
            visitors[nodeType] = blackListNodeHandler;
          });

          walk.simple(parsed, visitors);

          var missingInWihteList = whiteList.reduce(function(acc, nodeType) {
            if (!whiteListOutput.contains(nodeType)) {
              acc.push(nodeType);
            }
            return acc;
          }, []);
          return {
            "missingFromWhiteList": missingInWihteList,
            "presentInblackList": blackListOutput,
          };
        }(options.whiteList, options.blackList);

        // test structure
        var structureTestResults = function(structure) {
          var visitors = {}, successful = false, maxJ = 0;
          var structureNodeHandler = function(node, state) {
            if (successful) {
              return;
            }
            var j = 0;
            state.forEach(function(node) {
              if (node.type === structure[j]) {
                j++;
                maxJ = Math.max(maxJ, j);
              }
              if (j === structure.length) {
                successful = true;
                return;
              }
            });
          };

          structure.forEach(function (nodeType) {
            visitors[nodeType] = structureNodeHandler;
          });

          walk.ancestor(parsed, visitors);

          var missing = successful ? [] : structure.slice(maxJ, structure.length);
          return {
            missingFromStructure: missing,
          };
        }(options.structure);

        var failed = {};
        if (listsTestResults.missingFromWhiteList.length !== 0) {
          failed.whiteList = listsTestResults.missingFromWhiteList;
        }
        if (listsTestResults.presentInblackList.length !== 0) {
          failed.blackList = listsTestResults.presentInblackList;
        }
        if (structureTestResults.missingFromStructure.length !== 0) {
          failed.structure = structureTestResults.missingFromStructure;
        }

        var ret = {};
        if (Object.keys(failed).length === 0) {
          ret.success = true;
        } else {
          ret.success = false;
          ret.failed = failed;
        }
        // console.log("failed "+failed);
        return ret;
      };

      exports.test = test;

      var simpleWalkNodeHandler = function(inputArray, outputArray) {
        var isOutputArrayFull = false;
        return function(node, scope) {
          if (isOutputArrayFull) {
            return;
          }
          var nodeName = node.type;
          if (!outputArray.contains(nodeName)) {
            if (outputArray.push(nodeName) === inputArray.length) {
              isOutputArrayFull = true;
            }
          }
        };
      };

      Array.prototype.contains = function (v) {
        return this.indexOf(v) > -1;
      };

      Array.prototype.union = function (other) {
        var union = [], self = this.slice(0);
        other.forEach(function(v) {
          if (self.contains(v)) {
            union.push(v);
          }
        });
        return union;
      };

      function has(obj, propName) {
        return Object.prototype.hasOwnProperty.call(obj, propName);
      }

      function unique(a) {
        return a.sort().filter(function(item, pos) {
          return !pos || item != a[pos - 1];
        });
      }

});


text:
package org.andengine.opengl.texture.compressed.pvr;

import org.andengine.opengl.texture.ITextureStateListener;
import org.andengine.opengl.texture.TextureManager;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.compressed.pvr.pixelbufferstrategy.IPVRTexturePixelBufferStrategy;
import org.andengine.util.StreamUtils;
import org.andengine.util.adt.array.ArrayUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

/**
 * (c) 2010 Nicolas Gramlich
 * (c) 2011 Zynga Inc.
 *
 * @author Nicolas Gramlich
 * @since 14:17:23 - 27.07.2011
 */
public abstract class PVRCCZTexture extends PVRTexture {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	private CCZHeader mCCZHeader;

	// ===========================================================
	// Constructors
	// ===========================================================

	public PVRCCZTexture(final TextureManager pTextureManager, final PVRTextureFormat pPVRTextureFormat) throws IllegalArgumentException, IOException {
		super(pTextureManager, pPVRTextureFormat);
	}

	public PVRCCZTexture(final TextureManager pTextureManager, final PVRTextureFormat pPVRTextureFormat, final IPVRTexturePixelBufferStrategy pPVRTexturePixelBufferStrategy) throws IllegalArgumentException, IOException {
		super(pTextureManager, pPVRTextureFormat, pPVRTexturePixelBufferStrategy);
	}

	public PVRCCZTexture(final TextureManager pTextureManager, final PVRTextureFormat pPVRTextureFormat, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException {
		super(pTextureManager, pPVRTextureFormat, pTextureStateListener);
	}

	public PVRCCZTexture(final TextureManager pTextureManager, final PVRTextureFormat pPVRTextureFormat, final IPVRTexturePixelBufferStrategy pPVRTexturePixelBufferStrategy, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException {
		super(pTextureManager, pPVRTextureFormat, pPVRTexturePixelBufferStrategy, pTextureStateListener);
	}

	public PVRCCZTexture(final TextureManager pTextureManager, final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException, IOException {
		super(pTextureManager, pPVRTextureFormat, pTextureOptions);
	}

	public PVRCCZTexture(final TextureManager pTextureManager, final PVRTextureFormat pPVRTextureFormat, final IPVRTexturePixelBufferStrategy pPVRTexturePixelBufferStrategy, final TextureOptions pTextureOptions) throws IllegalArgumentException, IOException {
		super(pTextureManager, pPVRTextureFormat, pPVRTexturePixelBufferStrategy, pTextureOptions);
	}

	public PVRCCZTexture(final TextureManager pTextureManager, final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException {
		super(pTextureManager, pPVRTextureFormat, pTextureOptions, pTextureStateListener);
	}

	public PVRCCZTexture(final TextureManager pTextureManager, final PVRTextureFormat pPVRTextureFormat, final IPVRTexturePixelBufferStrategy pPVRTexturePixelBufferStrategy, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException {
		super(pTextureManager, pPVRTextureFormat, pPVRTexturePixelBufferStrategy, pTextureOptions, pTextureStateListener);
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	public final InflaterInputStream getInputStream() throws IOException {
		final InputStream inputStream = this.onGetInputStream();

		this.mCCZHeader = new CCZHeader(StreamUtils.streamToBytes(inputStream, CCZHeader.SIZE));

		return this.mCCZHeader.getCCZCompressionFormat().wrap(inputStream);
	}

	@Override
	public ByteBuffer getPVRTextureBuffer() throws IOException {
		final InputStream inputStream = this.getInputStream();
		try {
			final byte[] data = new byte[this.mCCZHeader.getUncompressedSize()];
			StreamUtils.copy(inputStream, data);
			return ByteBuffer.wrap(data);
		} finally {
			StreamUtils.close(inputStream);
		}
	}

	// ===========================================================
	// Methods
	// ===========================================================

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================

	public static class CCZHeader {
		// ===========================================================
		// Constants
		// ===========================================================

		static final byte[] MAGIC_IDENTIFIER = {
			(byte)'C',
			(byte)'C',
			(byte)'Z',
			(byte)'!'
		};

		public static final int SIZE = 16;

		// ===========================================================
		// Fields
		// ===========================================================

		private final ByteBuffer mDataByteBuffer;
		private final CCZCompressionFormat mCCZCompressionFormat;

		// ===========================================================
		// Constructors
		// ===========================================================

		public CCZHeader(final byte[] pData) {
			this.mDataByteBuffer = ByteBuffer.wrap(pData);
			this.mDataByteBuffer.rewind();
			this.mDataByteBuffer.order(ByteOrder.BIG_ENDIAN);

			/* Check magic bytes. */
			if (!ArrayUtils.equals(pData, 0, CCZHeader.MAGIC_IDENTIFIER, 0, CCZHeader.MAGIC_IDENTIFIER.length)) {
				throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!");
			}

			// TODO Check the version?

			this.mCCZCompressionFormat = CCZCompressionFormat.fromID(this.getCCZCompressionFormatID());
		}

		// ===========================================================
		// Getter & Setter
		// ===========================================================

		private short getCCZCompressionFormatID() {
			return this.mDataByteBuffer.getShort(4);
		}

		public CCZCompressionFormat getCCZCompressionFormat() {
			return this.mCCZCompressionFormat;
		}

		public short getVersion() {
			return this.mDataByteBuffer.getShort(6);
		}

		public int getUserdata() {
			return this.mDataByteBuffer.getInt(8);
		}

		public int getUncompressedSize() {
			return this.mDataByteBuffer.getInt(12);
		}

		// ===========================================================
		// Methods for/from SuperClass/Interfaces
		// ===========================================================

		// ===========================================================
		// Methods
		// ===========================================================

		// ===========================================================
		// Inner and Anonymous Classes
		// ===========================================================
	}

	public static enum CCZCompressionFormat {
		// ===========================================================
		// Elements
		// ===========================================================

		ZLIB((short)0),
		BZIP2((short)1),
		GZIP((short)2),
		NONE((short)3);

		// ===========================================================
		// Constants
		// ===========================================================

		// ===========================================================
		// Fields
		// ===========================================================

		private final short mID;

		// ===========================================================
		// Constructors
		// ===========================================================

		private CCZCompressionFormat(final short pID) {
			this.mID = pID;
		}

		public InflaterInputStream wrap(final InputStream pInputStream) throws IOException {
			switch (this) {
				case GZIP:
					return new GZIPInputStream(pInputStream);
				case ZLIB:
					return new InflaterInputStream(pInputStream, new Inflater());
				case NONE:
				case BZIP2:
				default:
					throw new IllegalArgumentException("Unexpected " + CCZCompressionFormat.class.getSimpleName() + ": '" + this + "'.");
			}
		}

		public static CCZCompressionFormat fromID(final short pID) {
			final CCZCompressionFormat[] cczCompressionFormats = CCZCompressionFormat.values();
			final int cczCompressionFormatCount = cczCompressionFormats.length;
			for (int i = 0; i < cczCompressionFormatCount; i++) {
				final CCZCompressionFormat cczCompressionFormat = cczCompressionFormats[i];
				if (cczCompressionFormat.mID == pID) {
					return cczCompressionFormat;
				}
			}
			throw new IllegalArgumentException("Unexpected " + CCZCompressionFormat.class.getSimpleName() + "-ID: '" + pID + "'.");
		}

		// ===========================================================
		// Getter & Setter
		// ===========================================================

		// ===========================================================
		// Methods for/from SuperClass/Interfaces
		// ===========================================================

		// ===========================================================
		// Methods
		// ===========================================================

		// ===========================================================
		// Inner and Anonymous Classes
		// ===========================================================
	}
}


text:
import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { SuggestModel } from 'vs/editor/contrib/suggest/suggestModel';

export class OvertypingCapturer implements IDisposable {

	private static readonly _maxSelectionLength = 51200;
	private readonly _disposables = new DisposableStore();

	private _lastOvertyped: { value: string; multiline: boolean }[] = [];
	private _empty: boolean = true;

	constructor(editor: ICodeEditor, suggestModel: SuggestModel) {

		this._disposables.add(editor.onWillType(() => {
			if (!this._empty) {
				return;
			}
			if (!editor.hasModel()) {
				return;
			}

			const selections = editor.getSelections();
			const selectionsLength = selections.length;

			// Check if it will overtype any selections
			let willOvertype = false;
			for (let i = 0; i < selectionsLength; i++) {
				if (!selections[i].isEmpty()) {
					willOvertype = true;
					break;
				}
			}
			if (!willOvertype) {
				return;
			}

			this._lastOvertyped = [];
			const model = editor.getModel();
			for (let i = 0; i < selectionsLength; i++) {
				const selection = selections[i];
				// Check for overtyping capturer restrictions
				if (model.getValueLengthInRange(selection) > OvertypingCapturer._maxSelectionLength) {
					return;
				}
				this._lastOvertyped[i] = { value: model.getValueInRange(selection), multiline: selection.startLineNumber !== selection.endLineNumber };
			}
			this._empty = false;
		}));

		this._disposables.add(suggestModel.onDidCancel(e => {
			if (!this._empty && !e.retrigger) {
				this._empty = true;
			}
		}));
	}

	getLastOvertypedInfo(idx: number): { value: string; multiline: boolean } | undefined {
		if (!this._empty && idx >= 0 && idx < this._lastOvertyped.length) {
			return this._lastOvertyped[idx];
		}
		return undefined;
	}

	dispose() {
		this._disposables.dispose();
	}
}