text:
/* ----------------------------------------------------------------------- *//**
 *
 * @file linear_crf.cpp
 *
 * @brief Linear-chain Conditional Random Field functions
 *
 * We implement limited-memory BFGS method.
 *
 *//* ----------------------------------------------------------------------- */
#include <iostream>
#include <dbconnector/dbconnector.hpp>
#include <modules/shared/HandleTraits.hpp>
#include "linear_crf.hpp"
namespace madlib {

// Use Eigen
using namespace dbal::eigen_integration;

namespace modules {

// Import names from other MADlib modules
using dbal::NoSolutionFoundException;

namespace crf {

// Internal functions
AnyType stateToResult(const Allocator &inAllocator,
                      const HandleMap<const ColumnVector,
                      TransparentHandle<double> > &incoef,
                      double loglikelihood, const uint32_t &iterations);

/**
 * @brief Inter- and intra-iteration state for lbfgs method for
 * linear-chain conditional random field
 *
 * TransitionState encapsualtes the transition state during the
 * linear-chain crf aggregate function. To the database, the state is
 * exposed as a single DOUBLE PRECISION array, to the C++ code it is a proper
 * object containing scalars and vectors.
 *
 * Note: We assume that the DOUBLE PRECISION array is initialized by the
 * database with length at least 58, and all elemenets are 0.
 */
template <class Handle>
class LinCrfLBFGSTransitionState {
    template <class OtherHandle>
    friend class LinCrfLBFGSTransitionState;

public:
    LinCrfLBFGSTransitionState(const AnyType &inArray)
        : mStorage(inArray.getAs<Handle>()) {

        rebind(static_cast<uint32_t>(mStorage[1]));
    }

    /**
     * @brief Convert to backend representation
     *
     * We define this function so that we can use State in the
     * argument list and as a return type.
     */
    inline operator AnyType() const {
        return mStorage;
    }

    /**
     * @brief Initialize the lbfgs state.
     *
     * This function is only called for the first row.
     */
    inline void initialize(const Allocator &inAllocator, uint32_t inWidthOfX,
                            uint32_t tagSize) {
        mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,
        dbal::DoZero, dbal::ThrowBadAlloc>(arraySize(inWidthOfX));
        rebind(inWidthOfX);
        num_features = inWidthOfX;
        num_labels =  tagSize;
        if(iteration == 0)
            diag.fill(1);
    }

    /**
     * @brief We need to support assigning the previous state
     */
    template <class OtherHandle>
    LinCrfLBFGSTransitionState &operator=(
        const LinCrfLBFGSTransitionState<OtherHandle> &inOtherState) {

        for (size_t i = 0; i < mStorage.size(); i++)
            mStorage[i] = inOtherState.mStorage[i];
        return *this;
    }

    /**
     * @brief Merge with another State object by copying the intra-iteration
     * fields
     */
    template <class OtherHandle>
    LinCrfLBFGSTransitionState &operator+=(
        const LinCrfLBFGSTransitionState<OtherHandle> &inOtherState) {
        if (mStorage.size() != inOtherState.mStorage.size())
            throw std::logic_error("Internal error: Incompatible transition "
                                   "states");
        numRows += inOtherState.numRows;
        grad += inOtherState.grad;
        loglikelihood += inOtherState.loglikelihood;
        return *this;
    }

    /**
     * @brief Reset the inter-iteration fields.
     */
    inline void reset() {
        numRows = 0;
        grad.fill(0);
        loglikelihood = 0;
    }

    static const int m=7;// The number of corrections used in the LBFGS update.

private:
    static inline uint32_t arraySize(const uint32_t num_features) {
        return 52 + 3 * num_features + num_features*(2*m+1)+2*m;
    }

    void rebind(uint32_t inWidthOfFeature) {
        iteration.rebind(&mStorage[0]);
        num_features.rebind(&mStorage[1]);
        num_labels.rebind(&mStorage[2]);
        coef.rebind(&mStorage[3], inWidthOfFeature);
        diag.rebind(&mStorage[3 + inWidthOfFeature], inWidthOfFeature);
        grad.rebind(&mStorage[3 + 2 * inWidthOfFeature], inWidthOfFeature);
        ws.rebind(&mStorage[3 + 3 * inWidthOfFeature],
                                    inWidthOfFeature*(2*m+1)+2*m);
        numRows.rebind(&mStorage[3 + 3 * inWidthOfFeature +
                                    inWidthOfFeature*(2*m+1)+2*m]);
        loglikelihood.rebind(&mStorage[4 + 3 * inWidthOfFeature +
                                    inWidthOfFeature*(2*m+1)+2*m]);
        lbfgs_state.rebind(&mStorage[5 + 3 * inWidthOfFeature +
                                    inWidthOfFeature*(2*m+1)+2*m], 21);
        mcsrch_state.rebind(&mStorage[26 + 3 * inWidthOfFeature +
                                    inWidthOfFeature*(2*m+1)+2*m], 25);
    }
    Handle mStorage;

public:
    typename HandleTraits<Handle>::ReferenceToUInt32 iteration;
    typename HandleTraits<Handle>::ReferenceToUInt32 num_features;
    typename HandleTraits<Handle>::ReferenceToUInt32 num_labels;
    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap coef;
    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap diag;
    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap grad;
    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap ws;

    typename HandleTraits<Handle>::ReferenceToUInt64 numRows;
    typename HandleTraits<Handle>::ReferenceToDouble loglikelihood;

    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap lbfgs_state;
    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap mcsrch_state;
};

/** This class contains code for the limited-memory Broyden-Fletcher-Goldfarb-Shanno
 * (LBFGS) algorithm for large-scale multidimensional unconstrained minimization problems.
 * This following class is a translation of Fortran code written by Jorge Nocedal.
 */
class LBFGS {
public:
    // shared variable in lbfgs
    double stp1, ftol, stp, sq, yr, beta;
    // iflag A return with iflag < 0 indicates an error,
    // and iflag = 0 indicates that the routine has
    // terminated without detecting errors. On a return with
    // iflag = 1, the user must evaluate the function
    // f and gradient g. On a return with
    // iflag is negative , lbfgs failed

    int  iflag, iter, nfun, point, ispt, iypt, maxfev, info, bound, npt, cp, nfev, inmc, iycn, iscn;
    // shared varibles in mcscrch
    int infoc;
    double dg, dgm, dginit, dgtest, dgx, dgxm, dgy, dgym, finit, ftest1, fm, fx, fxm, fy, fym, p5, p66, stx, sty, stmin, stmax, width, width1, xtrapf;
    bool brackt, stage1, finish;

    ColumnVector w;//
    ColumnVector x;// solution vector
    ColumnVector diag;

    LBFGS(LinCrfLBFGSTransitionState<MutableArrayHandle<double> >&);
    void save_state(LinCrfLBFGSTransitionState<MutableArrayHandle<double> > &state);
    void mcstep (double&, double& , double&, double&, double& , double&, double&, double, double, bool&, double, double, int&);
    void mcsrch (int, Eigen::VectorXd&, double, Eigen::VectorXd&, const Eigen::VectorXd&, double&, double, double, int, int&, int&, Eigen::VectorXd&);
    void lbfgs(int, int, double, Eigen::VectorXd, double, double);
};

/**
 *@brief initialize state of current lbfgs iteration with the state of last iteration
 */
LBFGS::LBFGS(LinCrfLBFGSTransitionState<MutableArrayHandle<double> >& state) {
    w = state.ws;
    diag = state.diag;
    x = state.coef;

    stp1 = state.lbfgs_state(0);
    ftol = state.lbfgs_state(1);
    stp = state.lbfgs_state(2);
    sq = state.lbfgs_state(3);
    yr = state.lbfgs_state(4);
    beta = state.lbfgs_state(5);
    iflag = static_cast<int>(state.lbfgs_state(6));
    iter = static_cast<int>(state.lbfgs_state(7));
    nfun = static_cast<int>(state.lbfgs_state(8));
    point = static_cast<int>(state.lbfgs_state(9));
    ispt = static_cast<int>(state.lbfgs_state(10));
    iypt = static_cast<int>(state.lbfgs_state(11));
    maxfev = static_cast<int>(state.lbfgs_state(12));
    info = static_cast<int>(state.lbfgs_state(13));
    bound = static_cast<int>(state.lbfgs_state(14));
    npt = static_cast<int>(state.lbfgs_state(15));
    cp = static_cast<int>(state.lbfgs_state(16));
    nfev = static_cast<int>(state.lbfgs_state(17));
    inmc = static_cast<int>(state.lbfgs_state(18));
    iycn = static_cast<int>(state.lbfgs_state(19));
    iscn = static_cast<int>(state.lbfgs_state(20));

    infoc = static_cast<int>(state.mcsrch_state(0));
    dg = state.mcsrch_state(1);
    dgm = state.mcsrch_state(2);
    dginit = state.mcsrch_state(3);
    dgtest = state.mcsrch_state(4);
    dgx = state.mcsrch_state(5);
    dgxm = state.mcsrch_state(6);
    dgy = state.mcsrch_state(7);
    dgym = state.mcsrch_state(8);
    finit = state.mcsrch_state(9);
    ftest1 = state.mcsrch_state(10);
    fm = state.mcsrch_state(11);
    fx = state.mcsrch_state(12);
    fxm = state.mcsrch_state(13);
    fy = state.mcsrch_state(14);
    fym = state.mcsrch_state(15);
    stx = state.mcsrch_state(16);
    sty = state.mcsrch_state(17);
    stmin = state.mcsrch_state(18);
    stmax = state.mcsrch_state(19);
    width = state.mcsrch_state(20);
    width1 = state.mcsrch_state(21);
    brackt = (state.mcsrch_state(22) == 1.0 ? true: false);
    stage1 = (state.mcsrch_state(23) == 1.0 ? true: false);
    finish = (state.mcsrch_state(24) == 1.0 ? true: false);
}

/**
 *@brief save current lbfgs state for the next lbfgs iteration
 */
void LBFGS::save_state(LinCrfLBFGSTransitionState<MutableArrayHandle<double> > &state) {
    state.ws = w ;
    state.diag = diag ;
    state.coef = x ;

    state.lbfgs_state(0) = stp1;
    state.lbfgs_state(1) = ftol;
    state.lbfgs_state(2) = stp;
    state.lbfgs_state(3) = sq;
    state.lbfgs_state(4) = yr;
    state.lbfgs_state(5) = beta;
    state.lbfgs_state(6) = iflag;
    state.lbfgs_state(7) = iter;
    state.lbfgs_state(8) = nfun;
    state.lbfgs_state(9) = point;
    state.lbfgs_state(10) = ispt;
    state.lbfgs_state(11) = iypt;
    state.lbfgs_state(12) = maxfev;
    state.lbfgs_state(13) = info;
    state.lbfgs_state(14) = bound;
    state.lbfgs_state(15) = npt;
    state.lbfgs_state(16) = cp;
    state.lbfgs_state(17) = nfev;
    state.lbfgs_state(18) = inmc;
    state.lbfgs_state(19) = iycn;
    state.lbfgs_state(20) = iscn;

    state.mcsrch_state(0) = infoc;
    state.mcsrch_state(1) =  dg;
    state.mcsrch_state(2) = dgm;
    state.mcsrch_state(3) = dginit;
    state.mcsrch_state(4) = dgtest;
    state.mcsrch_state(5) = dgx;
    state.mcsrch_state(6) = dgxm;
    state.mcsrch_state(7) = dgy;
    state.mcsrch_state(8) = dgym;
    state.mcsrch_state(9) = finit;
    state.mcsrch_state(10) = ftest1;
    state.mcsrch_state(11) = fm;
    state.mcsrch_state(12) = fx;
    state.mcsrch_state(13) = fxm;
    state.mcsrch_state(14) = fy;
    state.mcsrch_state(15) = fym;
    state.mcsrch_state(16) = stx;
    state.mcsrch_state(17) = sty;
    state.mcsrch_state(18) = stmin;
    state.mcsrch_state(19) = stmax;
    state.mcsrch_state(20) = width;
    state.mcsrch_state(21) = width1;
    state.mcsrch_state(22) = (brackt == true ? 1.0 : 0.0);
    state.mcsrch_state(23) = (stage1 == true ? 1.0 : 0.0);
    state.mcsrch_state(24) = (finish == true ? 1.0 : 0.0);
}
void LBFGS::mcstep(double& stx, double& fx, double& dx,
                   double& sty, double& fy, double& dy,
                   double& stp, double fp, double dp, bool& brackt,
                   double stmin, double stmax, int& info)
{
    bool bound;
    double gamma, p, q, r, sgnd, stpc, stpf, stpq, theta, s;

    info = 0;

    if ((brackt && ((stp <= std::min(stx, sty)) || (stp >= std::max(stx, sty)))) ||
            (dx * (stp - stx) >= 0) || (stmax < stmin)) {
        return;
    }

    sgnd = dp*(dx/fabs(dx));
    if (fp > fx) {
        info = 1;
        bound = true;
        theta = 3.0 * (fx - fp) / (stp - stx) + dx + dp;
        s = std::max(fabs(theta), std::max(fabs(dx), fabs(dp)));
        gamma = s * sqrt((theta / s) * (theta / s) - (dx / s) * (dp / s));
        if (stp < stx) {
            gamma = -gamma;
        }
        p = gamma - dx + theta;
        q = gamma - dx + gamma + dp;
        r = p / q;
        stpc = stx + r * (stp - stx);
        stpq = stx + dx/((fx - fp)/(stp - stx) + dx)/2 * (stp - stx);
        if (fabs(stpc - stx) < fabs(stpq - stx)) {
            stpf = stpc;
        } else {
            stpf = stpc + (stpq - stpc)/2;
        }
        brackt = true;

    } else if (sgnd < 0.0) {
        info = 2;
        bound = false;
        theta = 3.0 * (fx - fp) / (stp - stx) + dx + dp;
        s = std::max(fabs(theta), std::max(fabs(dx), fabs(dp)));
        gamma = s * sqrt((theta / s) * (theta / s) - (dx / s) * (dp / s));
        if (stp > stx) {
            gamma = -gamma;
        }
        p = gamma - dp + theta;
        q = gamma - dp + gamma + dx;
        r = p / q;
        stpc = stp + r * (stx - stp);
        stpq = stp + dp / (dp - dx) * (stx - stp);
        stpf = (fabs(stpc - stp) > fabs(stpq - stp)) ? stpc : stpq;
        brackt = true;

    } else if (fabs(dp) < fabs(dx)) {
        info = 3;
        bound = true;
        theta = 3.0 * (fx - fp) / (stp - stx) + dx + dp;
        s = std::max(fabs(theta), std::max(fabs(dx), fabs(dp)));
        gamma = s * sqrt(std::max(0.0, (theta/s)*(theta/s) - (dx/s)*(dp/s)));
        if (stp > stx) {
            gamma = -gamma;
        }
        p = gamma - dp + theta;
        q = gamma + (dx - dp) + gamma;
        r = p / q;
        if ((r < 0.0) && (gamma != 0.0)) {
            stpc = stp + r * (stx - stp);
        } else {
            stpc = (stp > stx) ? stmax : stmin;
        }

        stpq = stp + dp / (dp - dx) * (stx - stp);
        if (brackt) {
            stpf = (fabs(stp - stpc) < fabs(stp - stpq)) ? stpc : stpq;
        } else {
            stpf = (fabs(stp - stpc) > fabs(stp - stpq)) ? stpc : stpq;
        }

    } else {
        info = 4;
        bound = false;
        if (brackt) {
            theta = 3.0 * (fp - fy) / (sty - stp) + dy + dp;
            s = std::max(fabs(theta), std::max(fabs(dy), fabs(dp)));
            gamma = s * sqrt((theta/s)*(theta/s) - (dy/s)*(dp/s));
            if (stp > sty) {
                gamma = -gamma;
            }
            p = gamma - dp + theta;
            q = gamma - dp + gamma + dy;
            r = p / q;
            stpc = stp + r * (sty - stp);
            stpf = stpc;
        } else {
            stpf = (stp > stx) ? stmax : stmin;
        }
    }

    if (fp > fx) {
        sty = stp;
        fy = fp;
        dy = dp;
    } else {
        if (sgnd < 0.0) {
            sty = stx;
            fy = fx;
            dy = dx;
        }
        stx = stp;
        fx = fp;
        dx = dp;
    }

    stp = std::max(stmin, std::min(stmax, stpf));
    if (brackt && bound) {
        if (sty > stx) {
            stp = std::min(stx + 0.66*(sty - stx), stp);
        } else {
            stp = std::max(stx + 0.66*(sty - stx), stp);
        }
    }

    return;
}

void LBFGS::mcsrch(int n, Eigen::VectorXd& x, double f, Eigen::VectorXd& g,
                    const Eigen::VectorXd& s, double& stp, double ftol,
                    double xtol, int maxfev, int& info, int& nfev,
                    Eigen::VectorXd& wa)
{
    double stpmin = 1e-20;
    double stpmax = 1e20;
    double p5 = 0.5;
    double p66 = 0.66;
    double xtrapf = 4.0;
    double gtol = 0.9;

    if(info != -1) {
        infoc = 1;
        if (n <= 0 || stp <= 0 || ftol < 0 || gtol < 0 || xtol < 0 ||
                    stpmin < 0 || stpmax < stpmin || maxfev <= 0 )
            return;

        dginit = g.dot(s);
        if (dginit >= 0.0) {
            std::cout << "The search direction is not a descent direction."
                      << std::endl;
            return;
        }

        brackt = false;
        stage1 = true;
        nfev = 0;
        finit = f;
        dgtest = ftol * dginit;
        width = stpmax - stpmin;
        width1 = width/p5;

        wa = x;

        stx = 0.0;
        fx = finit;
        dgx = dginit;
        sty = 0.0;
        fy = finit;
        dgy = dginit;
    }

    while(true)
    {
        if(info != -1)
        {
            if (brackt) {
                if (stx < sty) {
                    stmin = stx;
                    stmax = sty;
                } else {
                    stmin = sty;
                    stmax = stx;
                }
            } else {
                stmin = stx;
                stmax = stp + xtrapf * (stp - stx);
            }

            stp = std::max(stpmin, std::min(stpmax, stp));

            if ((brackt && ((stp <= stmin) || (stp >= stmax))) ||
                    (nfev == maxfev - 1) ||
                    (!infoc) || (brackt && ((stmax - stmin) <= xtol * stmax))) {
                stp = stx;
            }

            x = wa + stp * s;

            info = -1;
            return;
        }
        info = 0;
        nfev= nfev + 1;
        dg = g.dot(s);
        ftest1 = finit + stp * dgtest;

        if ((brackt && ((stp <= stmin) || (stp >= stmax))) || (!infoc)) {
            info = 6;
        }
        if ((stp == stpmax) && (f <= ftest1) && (dg <= dgtest)) {
            info = 5;
        }
        if ((stp == stpmin) && ((f >= ftest1) || (dg >= dgtest))) {
            info = 4;
        }
        if (nfev >= maxfev) {
            info = 3;
        }
        if (brackt && (stmax - stmin <= xtol * stmax)) {
            info = 2;
        }
        if ((f <= ftest1) && (fabs(dg) <= -gtol * dginit)) {
            info = 1;
        }
        if (info !=0 )
            return ;

        if ( stage1 && f <= ftest1 && dg >= std::min(ftol , gtol) * dginit )
            stage1 = false;

        if (stage1 && f <= fx && f > ftest1) {
            fm = f - stp * dgtest;
            fxm = fx - stx * dgtest;
            fym = fy - sty * dgtest;
            dgm = dg - dgtest;
            dgxm = dgx - dgtest;
            dgym = dgy - dgtest;
            mcstep(stx, fxm, dgxm, sty, fym, dgym, stp, fm, dgm, brackt,
                    stmin, stmax, infoc);
            fx = fxm + stx * dgtest;
            fy = fym + sty * dgtest;
            dgx = dgxm + dgtest;
            dgy = dgym + dgtest;
        } else {
            mcstep(stx, fx, dgx, sty, fy, dgy, stp, f, dg, brackt, stmin,
                    stmax, infoc);
        }

        if (brackt) {
            if (fabs(sty - stx) >= p66 * width1) {
                stp = stx + p5 * (sty - stx);
            }
            width1 = width;
            width = fabs(sty - stx);
        }
    }
}

void LBFGS::lbfgs(int n, int m, double f, Eigen::VectorXd g, double eps,
                    double xtol)
{
    bool execute_entire_while_loop = false;
    if(iflag == 0) {
        iter=0;
        if ( n <= 0 || m <= 0 )
        {
            iflag= -3;
        }

        nfun= 1;
        point = 0;
        finish = false;
        ispt = n + 2*m;
        iypt = ispt + n*m;
        npt = 0;
        w.segment(ispt, n) = (-g).cwiseProduct(diag);

        stp1 = 1.0 / g.norm();
        ftol= 0.0001;
        maxfev= 20;
        execute_entire_while_loop = true;
    }
    while(true) {
        if(execute_entire_while_loop) {
            iter++;
            info = 0;
            bound=iter-1;
            if (iter!=1) {
                if (iter > m) bound = m;
                double ys = w.segment(iypt + npt, n).dot(w.segment(ispt + npt, n));
                double yy = w.segment(iypt + npt, n).squaredNorm();
                diag.setConstant(ys / yy);
                cp = point;
                if (point ==0 ) cp =m;
                w[n + cp-1] = 1.0 / ys;
                w.head(n) = -g;
                cp = point;
                for (int i = 0; i < bound; i++) {
                    cp -= 1;
                    if (cp == -1) {
                        cp = m - 1;
                    }
                    sq = w.segment(ispt + cp *n,n).dot(w.head(n));
                    inmc = n + m + cp;
                    iycn = iypt + cp * n;
                    w[inmc] = sq * w[n + cp];
                    w.head(n) -= w[inmc] * w.segment(iycn, n);
                }
                w.head(n)=w.head(n).cwiseProduct(diag);

                for (int i = 0; i < bound; i++) {
                    yr = w.segment(iypt + cp * n, n).dot(w.head(n));
                    inmc = n + m + cp;
                    beta = w[inmc] - w[n + cp] * yr;
                    iscn = ispt + cp * n;
                    w.head(n) += beta * w.segment(iscn, n);
                    cp += 1;
                    if (cp == m) {
                        cp = 0;
                    }
                }
                w.segment(ispt + point * n, n) = w.head(n);
            }
            nfev = 0;
            stp = (iter == 1) ? stp1 : 1.0;
            w.head(n) = g;
        }
        mcsrch(n, x, f, g, w.segment(ispt + point * n, n), stp, ftol,
                xtol, maxfev, info, nfev, diag);
        if(info == -1) {
            iflag = 1;
            return;
        } else {
            iflag = -1;
        }
        nfun = nfun + nfev;
        npt = point * n;
        w.segment(ispt + npt,n) *=stp;
        w.segment(iypt + npt,n) =g - w.head(n);
        point = point + 1;
        if (point == m) {
            point = 0;
        }
        if(g.norm()/std::max(1.0,x.norm())<=eps) {
            finish = true;
        }
        if (finish) {
            iflag = 0;
            return;
        }
        execute_entire_while_loop = true;
    }
}

/**
 *@brief compute exponential of Mi and Vi
 */
void compute_exp_Mi(int num_labels, Eigen::MatrixXd &Mi, Eigen::VectorXd &Vi) {
    // take exponential operator
    for (int m = 0; m < num_labels; m++) {
        Vi(m) = std::exp(Vi(m));
        for (int n = 0; n < num_labels; n++) {
            Mi(m, n) = std::exp(Mi(m, n));
        }
    }
}

Eigen::VectorXd mult(Eigen::MatrixXd Mi, Eigen::VectorXd Vi, bool trans,
                     int num_label)
{
    int i=0,j=0,r=0,c=0;
    Eigen::VectorXd z(num_label);
    z.fill(0);
    for (i = 0; i < num_label; i++ )
    {
        for (j=0; j< num_label; j++) {
            r= i;
            c=j;
            if(trans) {
                r= j;
                c=i;
            }
            z(r)+=Mi(i,j)*Vi(c);
        }
    }
    return z;
}

/**
 *@brief compute loglikelihood and gradient using forward-backward algorithm
 */
void validate_label(int label_id, int num_labels)
{
    if ((label_id < 0) || (label_id >= num_labels))
        throw std::runtime_error("Out of bound label ids found in feature table.");
}

void compute_logli_gradient(LinCrfLBFGSTransitionState<MutableArrayHandle<double> >& state,
                            MappedColumnVector& sparse_r,
                            MappedColumnVector& dense_m,
                            MappedColumnVector& sparse_m) {
    int r_size = static_cast<int>(sparse_r.size());
    int sparse_m_size = static_cast<int>(sparse_m.size());
    int seq_len = static_cast<int>(sparse_r(r_size-2)) + 1;

    Eigen::MatrixXd betas(static_cast<uint32_t>(state.num_labels), seq_len);
    Eigen::VectorXd scale(seq_len);
    Eigen::MatrixXd Mi(static_cast<uint32_t>(state.num_labels),
                                    static_cast<uint32_t>(state.num_labels));
    Eigen::VectorXd Vi(state.num_labels);
    Eigen::VectorXd alpha(state.num_labels);
    Eigen::VectorXd next_alpha(state.num_labels);
    Eigen::VectorXd temp(state.num_labels);
    Eigen::VectorXd ExpF(state.num_features);
    betas.fill(0);
    scale.fill(0);
    alpha.fill(1);
    next_alpha.fill(0);
    temp.fill(0);
    ExpF.fill(0);

    // compute beta values in a backward fashion
    // also scale beta-values to 1 to avoid numerical problems
    scale(seq_len - 1) = state.num_labels;
    betas.col(seq_len - 1).fill(1.0 / scale(seq_len - 1));

    int index = r_size-1;
    for (int i = seq_len - 1; i > 0; i--) {
        Mi.fill(0);
        Vi.fill(0);
        // examine all features at position "pos"
        //(prev_labe, curr_label, f_index, start_pos, exist)
        while (index-4>=0 && sparse_r(index-1) == i) {
            int curr_label =  static_cast<int>(sparse_r(index-3));
            validate_label(curr_label, state.num_labels);
            int f_index =  static_cast<int>(sparse_r(index-2));
            Vi(curr_label) += state.coef(f_index);
            index-=5;
        }
        //(f_index, prev_label, curr_label)
        for(int n=0; n+2<sparse_m_size ; n+=3) {
            int prev_label = static_cast<int>(sparse_m(n+1));
            int curr_label = static_cast<int>(sparse_m(n+2));
            validate_label(prev_label, state.num_labels);
            validate_label(curr_label, state.num_labels);
            Mi(prev_label, curr_label) += state.coef(static_cast<int>(sparse_m(n)));
        }

        compute_exp_Mi(state.num_labels, Mi, Vi);

        temp=betas.col(i);
        temp=temp.cwiseProduct(Vi);
        betas.col(i -1) = mult(Mi,temp,false,state.num_labels);
        // scale for the next (backward) beta values
        scale(i - 1)=betas.col(i-1).sum();
        betas.col(i - 1)*=(1.0 / scale(i - 1));
    } // end of beta values computation

    index = 0;
    // start to compute the log-likelihood of the current sequence
    for (int j = 0; j < seq_len; j++) {
        Mi.fill(0);
        Vi.fill(0);
        // examine all features at position "pos"
        int ori_index = index;

        while (((index+4) <= (r_size-1)) && sparse_r(index+3) == j) {
            int curr_label =  static_cast<int>(sparse_r(index+1));
            int f_index =  static_cast<int>(sparse_r(index+2));
            Vi(curr_label) += state.coef(f_index);
            index+=5;
        }
        if(j>=1) {
            for(int n=0; n+2<sparse_m_size ; n+=3) {
                int prev_label = static_cast<int>(sparse_m(n+1));
                int curr_label = static_cast<int>(sparse_m(n+2));
                Mi(prev_label, curr_label) += state.coef(static_cast<int>(sparse_m(n)));
            }
        }

        compute_exp_Mi(state.num_labels, Mi, Vi);

        if(j>0) {
            temp = alpha;
            next_alpha=mult(Mi,temp,true,state.num_labels);
            next_alpha=next_alpha.cwiseProduct(Vi);
        } else {
            next_alpha=Vi;
        }

        index = ori_index;
        while (((index+4) <= (r_size-1)) && sparse_r(index+3) == j) {
            int curr_label =  (int)sparse_r(index+1);
            int f_index =  (int)sparse_r(index+2);
            int exist = (int)sparse_r(index+4);
            if (exist == 1) {
                state.grad(f_index) += 1;
                state.loglikelihood += state.coef(f_index);
            }
            ExpF(f_index) += next_alpha(curr_label) * betas(curr_label,j);

            index+=5;
        }
        // Edge feature
        if(j>=1) {
            int f_index = (int)dense_m((j-1)*5+2);
            state.grad(f_index) += 1;
            state.loglikelihood += state.coef(f_index);
            //(f_index, prev_label, curr_label)
            for(int n=0; n+2<sparse_m_size ; n+=3) {
                int f_index = (int)sparse_m(n);
                int prev_label = static_cast<int>(sparse_m(n+1));
                int curr_label = static_cast<int>(sparse_m(n+2));
                ExpF(f_index) += alpha[prev_label] * Vi(curr_label) * Mi(prev_label,curr_label) * betas(curr_label, j);
            }
        }

        alpha = next_alpha;
        alpha*=(1.0 / scale(j));
    }

    // Zx = sum(alpha_i_n) where i = 1..num_labels, n = seq_len
    double Zx = alpha.sum();
    state.loglikelihood -= std::log(Zx);

    // re-correct the value of seq_logli because Zx was computed from
    // scaled alpha values
    for (int k = 0; k < seq_len; k++) {
        state.loglikelihood -= std::log(scale(k));
    }
    // update the gradient vector
    for (size_t k = 0; k < state.num_features; k++) {
        state.grad(k) -= ExpF(k) / Zx;
    }
}

/**
 * @brief Compute the log likelihood and gradient vector for each tuple
 */
AnyType
lincrf_lbfgs_step_transition::run(AnyType &args) {
    LinCrfLBFGSTransitionState<MutableArrayHandle<double> > state = args[0];
    MappedColumnVector sparse_r = args[1].getAs<MappedColumnVector>();
    MappedColumnVector dense_m = args[2].getAs<MappedColumnVector>();
    MappedColumnVector sparse_m = args[3].getAs<MappedColumnVector>();
    if (state.numRows == 0) {
        state.initialize(*this, static_cast<uint32_t>(args[4].getAs<double>()), static_cast<uint32_t>(args[5].getAs<double>()));
        if (!args[6].isNull()) {
            LinCrfLBFGSTransitionState<ArrayHandle<double> > previousState = args[6];
            state = previousState;
            state.reset();
        }
    }
    state.numRows++;
    compute_logli_gradient(state, sparse_r, dense_m, sparse_m);
    return state;
}

/**
 * @brief Perform the perliminary aggregation function: Merge transition states
 */
AnyType
lincrf_lbfgs_step_merge_states::run(AnyType &args) {
    LinCrfLBFGSTransitionState<MutableArrayHandle<double> > stateLeft = args[0];
    LinCrfLBFGSTransitionState<ArrayHandle<double> > stateRight = args[1];

    // We first handle the trivial case where this function is called with one
    // of the states being the initial state
    if (stateLeft.numRows == 0)
        return stateRight;
    else if (stateRight.numRows == 0)
        return stateLeft;

    // Merge states together and return
    stateLeft += stateRight;
    return stateLeft;
}

/**
 * @brief Perform the licrf_lbfgs final step
 */
AnyType
lincrf_lbfgs_step_final::run(AnyType &args) {
// We request a mutable object. Depending on the backend, this might perform
    // a deep copy.
    LinCrfLBFGSTransitionState<MutableArrayHandle<double> > state = args[0];

    // Aggregates that haven't seen any data just return Null.
    if (state.numRows == 0)
        return Null();

    // To avoid overfitting, penalize the likelihood with a spherical Gaussian
    // weight prior
    double sigma_square = 100;
    state.loglikelihood -= (state.coef.dot(state.coef)/(2 * sigma_square));
    state.grad -= state.coef/sigma_square;

    // the lbfgs minimize function, we want to maximize loglikelihood
    state.loglikelihood = state.loglikelihood * -1;
    state.grad = -state.grad;

    double eps = 0.001; //accuracy of the solution to be found
    double xtol = 1.0e-16; //an estimate of the machine precision

    assert((state.m > 0) && (state.m <= state.num_features) && (eps >= 0.0));
    LBFGS instance(state);// initialize the lbfgs with state of last iteration
    instance.lbfgs(state.num_features, state.m, state.loglikelihood, state.grad, eps, xtol);// lbfgs optimization
    instance.save_state(state);//save current state for the next iteration of lbfgs
    switch(instance.iflag)
    {
    case -1:
        throw std::logic_error("The line search rountine mcsch failed");
        break;
    case -2:
        throw std::logic_error("The i-th diagonal element of the diagonal inverse Hessian"
                               "approximation, given in DIAG, is not positive");
        break;
    case -3:
        throw std::logic_error("Improper input parameters for LBFGS n or m are not positive");
        break;
    }

    if(!state.coef.is_finite())
        throw NoSolutionFoundException("Over- or underflow in "
                                       "L-BFGS step, while updating coefficients. Input data "
                                       "is likely of poor numerical condition.");

    state.iteration++;
    return state;
}

/**
 * @brief Return iflag which indicates whether L-BFGS converge or not
 */
AnyType
internal_lincrf_lbfgs_converge::run(AnyType &args) {
    LinCrfLBFGSTransitionState<ArrayHandle<double> > state = args[0];
    return state.lbfgs_state(6);
}

/**
 * @brief Return the coefficients and diagnostic statistics of the state
 */
AnyType
internal_lincrf_lbfgs_result::run(AnyType &args) {
    LinCrfLBFGSTransitionState<ArrayHandle<double> > state = args[0];
    return stateToResult(*this, state.coef, state.loglikelihood, state.iteration);
}

/**
 * @brief Return the results for the L-BFGS method.
 */
AnyType stateToResult(
    const Allocator &inAllocator,
    const HandleMap<const ColumnVector, TransparentHandle<double> > &incoef,
    double loglikelihood, const uint32_t &iterations) {
    // FIXME: We currently need to copy the coefficient to a native array
    // This should be transparent to user code
    MutableNativeColumnVector coef(
        inAllocator.allocateArray<double>(incoef.size()));
    coef = incoef;

    // Return all coefficients, loglikelihood in a tuple
    AnyType tuple;
    tuple << coef << loglikelihood << iterations;
    return tuple;
}

} // namespace crf

} // namespace modules

} // namespace madlib


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

#include "math/mSplinePatch.h"

//******************************************************************************
// Spline control points
//******************************************************************************
SplCtrlPts::SplCtrlPts()
{
}

//------------------------------------------------------------------------------
// Destructor
//------------------------------------------------------------------------------
SplCtrlPts::~SplCtrlPts()
{
}

//------------------------------------------------------------------------------
// Get point
//------------------------------------------------------------------------------
const Point3F * SplCtrlPts::getPoint( U32 pointNum )
{
   return &mPoints[pointNum];
}

//------------------------------------------------------------------------------
// Set point
//------------------------------------------------------------------------------
void SplCtrlPts::setPoint( Point3F &point, U32 pointNum )
{
   mPoints[pointNum] = point;
}

//------------------------------------------------------------------------------
// Add point
//------------------------------------------------------------------------------
void SplCtrlPts::addPoint( Point3F &point )
{
   mPoints.push_back( point );
}

//------------------------------------------------------------------------------
// Submit control points
//------------------------------------------------------------------------------
void SplCtrlPts::submitPoints( Point3F *pts, U32 num )
{
   mPoints.clear();

   for( int i=0; i<num; i++ )
   {
      mPoints.push_back( pts[i] );
   }
}

//******************************************************************************
// Spline patch  - base class
//******************************************************************************
SplinePatch::SplinePatch()
{
   mNumReqControlPoints = 0;
}

//------------------------------------------------------------------------------
// This method is the only way to modify control points once they have been
// submitted to the patch.  This was done to make sure the patch has a chance
// to re-calc any pre-calculated data it may be using from the submitted control
// points.
//------------------------------------------------------------------------------
void SplinePatch::setControlPoint( Point3F &point, int index )
{
   mControlPoints.setPoint( point, index );
}

//------------------------------------------------------------------------------
// Calc point on spline using already submitted points
//------------------------------------------------------------------------------
void SplinePatch::calc( F32 /*t*/, Point3F &result )
{
   result.x = result.y = result.z = 0.0f;
}

//------------------------------------------------------------------------------
// Calc point on spline using passed-in points
//------------------------------------------------------------------------------
void SplinePatch::calc( Point3F * /*points*/, F32 /*t*/, Point3F &result )
{
   result.x = result.y = result.z = 0.0f;
}

redpajama_set_name: RedPajamaGithub


text:
const vertTemplate = [
    'attribute vec2 aVertexPosition;',
    'attribute vec2 aTextureCoord;',

    'uniform float strength;',
    'uniform mat3 projectionMatrix;',

    'varying vec2 vBlurTexCoords[%size%];',

    'void main(void)',
    '{',
    'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);',
    '%blur%',
    '}',
].join('\n');

export default function generateVertBlurSource(kernelSize, x)
{
    const halfLength = Math.ceil(kernelSize / 2);

    let vertSource = vertTemplate;

    let blurLoop = '';
    let template;
    // let value;

    if (x)
    {
        template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);';
    }
    else
    {
        template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);';
    }

    for (let i = 0; i < kernelSize; i++)
    {
        let blur = template.replace('%index%', i);

        // value = i;

        // if(i >= halfLength)
        // {
        //     value = kernelSize - i - 1;
        // }

        blur = blur.replace('%sampleIndex%', `${i - (halfLength - 1)}.0`);

        blurLoop += blur;
        blurLoop += '\n';
    }

    vertSource = vertSource.replace('%blur%', blurLoop);
    vertSource = vertSource.replace('%size%', kernelSize);

    return vertSource;
}


text:
namespace arangodb {
class UpgradeFeature final : public application_features::ApplicationFeature {
 public:
  UpgradeFeature(application_features::ApplicationServer* server, int* result,
                 std::vector<std::string> const& nonServerFeatures);

 public:
  void collectOptions(std::shared_ptr<options::ProgramOptions>) override final;
  void validateOptions(std::shared_ptr<options::ProgramOptions>) override final;
  void start() override final;

 private:
  bool _upgrade;
  bool _upgradeCheck;

 private:
  void upgradeDatabase();

 private:
  int* _result;
  std::vector<std::string> _nonServerFeatures;
};
}

#endif


text:
package infovis.data;

import java.util.Calendar;
import java.util.Comparator;

/**
 * A bus time consists of an hour and a minute.
 *
 * @author Joschi <josua.krause@googlemail.com>
 */
public final class BusTime implements Comparable<BusTime> {

  /** Midnight. */
  public static final BusTime MIDNIGHT = new BusTime(0);

  /** Bus time for 12:00 AM. */
  public static final BusTime NOON = new BusTime(12, 0);

  /** The number of hours per day. */
  public static final int HOURS_PER_DAY = 24;

  /** The number of minutes in an hour. */
  public static final int MINUTES_PER_HOUR = 60;

  /** The number of seconds in one minute. */
  public static final int SECONDS_PER_MINUTE = 60;

  /** The number of milliseconds in one second. */
  public static final int MILLISECONDS_PER_SECOND = 1000;

  /** The number of seconds in one day. */
  private static final int SECONDS_PER_DAY =
      HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE;

  /** Number of seconds since midnight. */
  private final int seconds;

  /**
   * Creates a new bus time.
   *
   * @param hour The hour ranging from 0 to 23.
   * @param minute The minute ranging from 0 to 59.
   */
  public BusTime(final int hour, final int minute) {
    this(hour, minute, 0);
  }

  /**
   * Creates a new bus time.
   *
   * @param hour The hour ranging from 0 to 23.
   * @param minute The minute ranging from 0 to 59.
   * @param second The second ranging from 0 to 59.
   */
  public BusTime(final int hour, final int minute, final int second) {
    this((checkRange("hour", hour, HOURS_PER_DAY) * MINUTES_PER_HOUR
        + checkRange("minute", minute, MINUTES_PER_HOUR)) * SECONDS_PER_MINUTE
        + checkRange("second", second, SECONDS_PER_MINUTE));
  }

  /**
   * Private constructor taking the number of seconds since midnight.
   *
   * @param secondsSinceMidnight seconds since midnight
   */
  private BusTime(final int secondsSinceMidnight) {
    seconds = checkRange("seconds since midnight", secondsSinceMidnight, SECONDS_PER_DAY);
  }

  /**
   * Checks if the given value lies within the range {@code [0,max)}.
   *
   * @param desc description of the value
   * @param val the value
   * @param max exclusive upper bound
   * @return the value for convenience
   * @throws IllegalArgumentException if the value lies outside the range
   */
  private static int checkRange(final String desc, final int val, final int max) {
    if(0 <= val && val < max) return val;
    throw new IllegalArgumentException(desc + " out of range: " + val);
  }

  /**
   * Getter.
   *
   * @return The hour.
   */
  public int getHour() {
    return seconds / (SECONDS_PER_MINUTE * MINUTES_PER_HOUR);
  }

  /**
   * Getter.
   *
   * @return The minute.
   */
  public int getMinute() {
    return (seconds / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR;
  }

  /**
   * Getter.
   *
   * @return The second.
   */
  public int getSecond() {
    return seconds % SECONDS_PER_MINUTE;
  }

  /**
   * Calculates the time until the given end. This method always returns
   * positive values even when the end time is before this time. The values are
   * wrapped around 24 hours.
   *
   * @param end The end time.
   * @return The time until the end in seconds.
   */
  public int secondsTo(final BusTime end) {
    return (end.seconds - seconds + SECONDS_PER_DAY) % SECONDS_PER_DAY;
  }

  /**
   * Getter.
   *
   * @return The seconds from midnight.
   */
  public int secondsFromMidnight() {
    return seconds;
  }

  /**
   * Calculates the time until the given end. This method always returns
   * positive values even when the end time is before this time. The values are
   * wrapped around 24 hours.
   *
   * @param end The end time.
   * @return The time until the end in minutes.
   */
  public int minutesTo(final BusTime end) {
    return (secondsTo(end) + SECONDS_PER_MINUTE - 1) / SECONDS_PER_MINUTE;
  }

  /**
   * Getter.
   *
   * @param min minutes
   * @param seconds seconds
   * @return The time that is the given amount of time later.
   */
  public BusTime later(final int min, final int seconds) {
    final int newSecs = this.seconds + min * SECONDS_PER_MINUTE + seconds;
    return new BusTime(((newSecs % SECONDS_PER_DAY) + SECONDS_PER_DAY) % SECONDS_PER_DAY);
  }

  /**
   * Creates a comparator that assumes this {@link BusTime} as lowest possible
   * value. Meaning the {@link BusTime} one minute before this is considered the
   * largest value. The times wrap around 24 hours.
   *
   * @return The comparator.
   */
  public Comparator<BusTime> createRelativeComparator() {
    return new Comparator<BusTime>() {

      @Override
      public int compare(final BusTime o1, final BusTime o2) {
        return BusTime.this.secondsTo(o1) - BusTime.this.secondsTo(o2);
      }

    };
  }

  @Override
  public int compareTo(final BusTime o) {
    return seconds - o.seconds;
  }

  @Override
  public boolean equals(final Object obj) {
    return obj instanceof BusTime && seconds == ((BusTime) obj).seconds;
  }

  @Override
  public int hashCode() {
    return seconds;
  }

  /**
   * Whether the given time represents a blink second, ie a second when the
   * colon is not printed.
   *
   * @return Whether it is a blink second.
   */
  public boolean isBlinkSecond() {
    return seconds % 2 != 0;
  }

  @Override
  public String toString() {
    return String.format("%s[%dh, %dmin, %dsec]", getClass().getSimpleName(),
        getHour(), getMinute(), getSecond());
  }

  /**
   * Getter.
   *
   * @return A pretty representation.
   */
  public String pretty() {
    return pretty(false);
  }

  /**
   * Getter.
   *
   * @param blink Whether the colon should not be printed
   * @return A pretty representation.
   */
  public String pretty(final boolean blink) {
    final String min = "0" + getMinute();
    return getHour() + (blink ? " " : ":") + min.substring(min.length() - 2) + "h";
  }

  /**
   * Converts minutes into a readable string.
   *
   * @param minutes The minutes.
   * @return The string.
   */
  public static String minutesToString(final int minutes) {
    final int min = Math.abs(minutes);
    final int h = min / MINUTES_PER_HOUR;
    final int m = min % MINUTES_PER_HOUR;
    return (minutes < 0 ? "-" : "") + (h > 0 ? h + " h" : "")
        + (m > 0 ? (h > 0 ? " " : "") + m + " min" : (h > 0 ? "" : "0 min"));
  }

  /**
   * Calculates the bus time for the given calendar object.
   *
   * @param calendar The time to convert.
   * @return The converted time.
   */
  public static BusTime fromCalendar(final Calendar calendar) {
    return new BusTime(calendar.get(Calendar.HOUR_OF_DAY),
        calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
  }

  /**
   * Getter.
   *
   * @return The current time.
   */
  public static BusTime now() {
    return fromCalendar(Calendar.getInstance());
  }

}


text:
package service;

public interface NewService {

	int new1();
	int new2();
}


text:
[kakao](../../index.md) / [com.agoda.kakao](../index.md) / [PositionMatcher](index.md) / [describeTo](./describe-to.md)

# describeTo

`fun describeTo(desc: Description): `[`Unit`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html)


text:
package com.vaenow.appupdate.android;

import android.app.Activity;
import android.Manifest;
import android.os.Build;
import android.net.Uri;
import android.provider.Settings;
import android.content.Intent;
import android.content.pm.PackageManager;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.BuildHelper;

import org.json.JSONArray;
import org.json.JSONException;

/**
 * Created by LuoWen on 2015/10/27.
 */
public class CheckAppUpdate extends CordovaPlugin {
    public static final String TAG = "CheckAppUpdate";

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("checkAppUpdate")) {
            getUpdateManager().options(args, callbackContext);
            if (verifyInstallPermission() && verifyOtherPermissions())
                getUpdateManager().checkUpdate();
            return true;
        }

        callbackContext.error(Utils.makeJSON(Constants.NO_SUCH_METHOD, "No such method: " + action));
        return false;
    }

    //////////
    // Update Manager
    //////////

    // UpdateManager singleton
    private UpdateManager updateManager = null;

    // Generate or retrieve the UpdateManager singleton
    public UpdateManager getUpdateManager() {
        if (updateManager == null)
            updateManager = new UpdateManager(cordova.getActivity(), cordova);

        return updateManager;
    }

    //////////
    // Permissions
    //////////

    private static final int INSTALL_PERMISSION_REQUEST_CODE = 0;
    private static final int UNKNOWN_SOURCES_PERMISSION_REQUEST_CODE = 1;
    private static final int OTHER_PERMISSIONS_REQUEST_CODE = 2;

    // Other necessary permissions for this plugin.
    private static String[] OTHER_PERMISSIONS = {
            Manifest.permission.INTERNET,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    // Prompt user for install permission if we don't already have it.
    public boolean verifyInstallPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (!cordova.getActivity().getPackageManager().canRequestPackageInstalls()) {
                String applicationId = (String) BuildHelper.getBuildConfigValue(cordova.getActivity(), "APPLICATION_ID");
                Uri packageUri = Uri.parse("package:" + applicationId);
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
                    .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    .setData(packageUri);
                cordova.setActivityResultCallback(this);
                cordova.getActivity().startActivityForResult(intent, INSTALL_PERMISSION_REQUEST_CODE);
                return false;
            }
        }
        else {
            try {
                if (Settings.Secure.getInt(cordova.getActivity().getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS) != 1) {
                    Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
                    cordova.setActivityResultCallback(this);
                    cordova.getActivity().startActivityForResult(intent, UNKNOWN_SOURCES_PERMISSION_REQUEST_CODE);
                    return false;
                }
            }
            catch (Settings.SettingNotFoundException e) {}
        }

        return true;
    }

    // Prompt user for all other permissions if we don't already have them all.
    public boolean verifyOtherPermissions() {
        boolean hasOtherPermissions = true;
        for (String permission:OTHER_PERMISSIONS)
            hasOtherPermissions = hasOtherPermissions && cordova.hasPermission(permission);

        if (!hasOtherPermissions) {
            cordova.requestPermissions(this, OTHER_PERMISSIONS_REQUEST_CODE, OTHER_PERMISSIONS);
            return false;
        }

        return true;
    }

    // React to user's response to our request for install permission.
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == INSTALL_PERMISSION_REQUEST_CODE) {
            if (!cordova.getActivity().getPackageManager().canRequestPackageInstalls()) {
                getUpdateManager().permissionDenied("Permission Denied: " + Manifest.permission.REQUEST_INSTALL_PACKAGES);
                return;
            }

            if (verifyOtherPermissions())
                getUpdateManager().checkUpdate();
        }
        else if (requestCode == UNKNOWN_SOURCES_PERMISSION_REQUEST_CODE) {
            try {
                if (Settings.Secure.getInt(cordova.getActivity().getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS) != 1) {
                    getUpdateManager().permissionDenied("Permission Denied: " + Settings.Secure.INSTALL_NON_MARKET_APPS);
                    return;
                }
            }
            catch (Settings.SettingNotFoundException e) {}

            if (verifyOtherPermissions())
                getUpdateManager().checkUpdate();
        }
    }

    // React to user's response to our request for other permissions.
    @Override
    public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == OTHER_PERMISSIONS_REQUEST_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    getUpdateManager().permissionDenied("Permission Denied: " + permissions[i]);
                    return;
                }
            }

            getUpdateManager().checkUpdate();
        }
    }
}


text:
import { ReactiveFormsModule } from '@angular/forms';

import { EffectsModule } from '@ngrx/effects';
import { StoreRouterConnectingModule } from '@ngrx/router-store';
import { StoreModule, MetaReducer } from '@ngrx/store';

import { MaterialModule } from './material.module';
import { TransferHttpModule } from '../modules/transfer-http/transfer-http.module';

import { DEV_REDUCERS, syncReducers, resetOnLogout, AppState } from './reducers';
import { RouterEffects } from './effects/router';
import { UserEffects } from './user/user.effects';

export const metaReducers: MetaReducer<AppState>[] = ENV === 'development' ?
  [...DEV_REDUCERS, resetOnLogout] : [resetOnLogout];

export const APP_IMPORTS = [
  EffectsModule.forRoot([
    RouterEffects,
    UserEffects
  ]),
  MaterialModule,
  ReactiveFormsModule,
  StoreModule.forRoot(syncReducers, { metaReducers }),
  StoreRouterConnectingModule.forRoot({
    stateKey: 'router' // name of reducer key
  }),
  TransferHttpModule
];


text:
package com.gorka.lige.labs;
import java.util.*;

public class Departamento
{
    //----------------------------------------------------------------------------
    // Propiedades
    //----------------------------------------------------------------------------
    private int id;
    private String nombre;
    private LinkedList<String> profesores;
    private LinkedList<String> asignaturas;

    //----------------------------------------------------------------------------
    // Constructores
    //----------------------------------------------------------------------------
    public Departamento ()
    {
        this.id          = 0;
        this.nombre      = "";
        this.profesores  = new LinkedList<String>();
        this.asignaturas = new LinkedList<String>();
    }

    public Departamento (int id, String nombre, LinkedList<String> profesores,
                         LinkedList<String> asignaturas)
    {
        this.id          = id;
        this.nombre      = nombre;
        this.profesores  = profesores;
        this.asignaturas = asignaturas;
    }

    //----------------------------------------------------------------------------
    // Métodos
    //----------------------------------------------------------------------------
    public int getID ()
    {
        return this.id;
    }

    public String getNombre ()
    {
        return this.nombre;
    }

    public LinkedList<String> getProfesores ()
    {
        return this.profesores;
    }

    public LinkedList<String> getAsignaturas ()
    {
        return this.asignaturas;
    }

    public void setID (int id)
    {
        this.id = id;
    }

    public void mostrarProfesores ()
    {
        System.out.println("+ Lista de profesores del departamento:");

        for(String profesor : this.profesores)
        {
            System.out.println("\t" + profesor);
        }
    }

    public void mostrarAsignaturas ()
    {
        System.out.println("+ Lista de asignaturas del departamento:");

        for(String asignatura : this.asignaturas)
        {
            System.out.println("\t" + asignatura);
        }
    }

    public void mostrarProfesores (String separacion)
    {
        System.out.println(separacion + "+ Lista de profesores del departamento:");

        for(String profesor : this.profesores)
        {
            System.out.println(separacion + "\t" + profesor);
        }
    }

    public void mostrarAsignaturas (String separacion)
    {
        System.out.println(separacion + "+ Lista de asignaturas del departamento:");

        for(String asignatura : this.asignaturas)
        {
            System.out.println(separacion + "\t" + asignatura);
        }
    }
}


text:
package com.abdallaadelessa.rtl.lib;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;

import com.sun.org.apache.xerces.internal.impl.xs.opti.NodeImpl;

/**
 *
 * @author Abdalla
 *
 */
public class RTLConvertor {
	private static final String XML_EXTENSION = ".xml";
	private static final String RADIO_GROUP = "RadioGroup";
	private static final String PERCENT_FRAME_LAYOUT = "android.support.percent.PercentFrameLayout";
	private static final String TEXT_VIEW = "TextView";
	private static final String EDIT_TEXT = "EditText";
	private static final String CENTER_HORIZONTAL = "center_horizontal";
	private static final String CENTER = "center";
	private static final String FRAME_LAYOUT = "FrameLayout";
	private static final String HORIZONTAL = "horizontal";
	private static final String ANDROID_ORIENTATION = "android:orientation";
	private static final String ANDROID_GRAVITY = "android:gravity";
	private static final String ANDROID_LAYOUT_GRAVITY = "android:layout_gravity";
	private static final String LINEAR_LAYOUT = "LinearLayout";
	private static final String GRAVITY = "gravity";
	private static final String UTF8 = "UTF8";
	// ---->
	public static final int MODE_RTL = 0;
	public static final int MODE_LTR = 1;
	private static int mode = MODE_RTL;
	private static boolean reverseLinearLayout = false;
	private static Set<String> textViewClassNames = new HashSet<>();
	private static Set<String> frameClassNames = new HashSet<>();
	private static Set<String> linearLayoutClassNames = new HashSet<>();
	private static final Map<String, String> RTL_ATTR_MAP = new HashMap<>();
	private static final Map<String, String> RTL_GRAVITY_MAP = new HashMap<>();
	static {
		RTL_ATTR_MAP.put("layout_toRightOf", "layout_toLeftOf");
		RTL_ATTR_MAP.put("layout_toLeftOf", "layout_toRightOf");
		RTL_ATTR_MAP.put("layout_alignLeft", "layout_alignRight");
		RTL_ATTR_MAP.put("layout_alignRight", "layout_alignLeft");
		RTL_ATTR_MAP.put("layout_marginRight", "layout_marginLeft");
		RTL_ATTR_MAP.put("layout_marginLeft", "layout_marginRight");
		RTL_ATTR_MAP.put("layout_toEndOf", "layout_toStartOf");
		RTL_ATTR_MAP.put("layout_toStartOf", "layout_toEndOf");
		RTL_ATTR_MAP.put("layout_alignStart", "layout_alignEnd");
		RTL_ATTR_MAP.put("layout_alignEnd", "layout_alignStart");
		RTL_ATTR_MAP.put("layout_marginEnd", "layout_marginStart");
		RTL_ATTR_MAP.put("layout_marginStart", "layout_marginEnd");
		RTL_ATTR_MAP.put("layout_alignParentRight", "layout_alignParentLeft");
		RTL_ATTR_MAP.put("layout_alignParentLeft", "layout_alignParentRight");
		RTL_ATTR_MAP.put("layout_alignParentEnd", "layout_alignParentStart");
		RTL_ATTR_MAP.put("layout_alignParentStart", "layout_alignParentEnd");
		RTL_ATTR_MAP.put("paddingLeft", "paddingRight");
		RTL_ATTR_MAP.put("paddingRight", "paddingLeft");
		RTL_ATTR_MAP.put("paddingStart", "paddingEnd");
		RTL_ATTR_MAP.put("paddingEnd", "paddingStart");
		RTL_ATTR_MAP.put("layout_marginEndPercent", "layout_marginStartPercent");
		RTL_ATTR_MAP.put("layout_marginRightPercent", "layout_marginLeftPercent");
		RTL_ATTR_MAP.put("layout_marginStartPercent", "layout_marginEndPercent");
		RTL_ATTR_MAP.put("layout_marginLeftPercent", "layout_marginRightPercent");
		RTL_GRAVITY_MAP.put("left", "right");
		RTL_GRAVITY_MAP.put("right", "left");
		RTL_GRAVITY_MAP.put("start", "end");
		RTL_GRAVITY_MAP.put("end", "start");
		RTL_ATTR_MAP.putAll(RTL_GRAVITY_MAP);
		// ---->
		textViewClassNames.add(TEXT_VIEW);
		textViewClassNames.add(EDIT_TEXT);
		frameClassNames.add(FRAME_LAYOUT);
		frameClassNames.add(PERCENT_FRAME_LAYOUT);
		linearLayoutClassNames.add(LINEAR_LAYOUT);
		linearLayoutClassNames.add(RADIO_GROUP);
	}

	// ------------------------>

	public static void setMode(int mode) {
		RTLConvertor.mode = mode;
	}

	public static void setReverseLinearLayout(boolean reverseLinearLayout) {
		RTLConvertor.reverseLinearLayout = reverseLinearLayout;
	}

	public static void addTextViewClass(String fullClassName) {
		if (!Helper.isStringEmpty(fullClassName)) {
			textViewClassNames.add(fullClassName);
		}
	}

	public static void addFrameLayoutClass(String fullClassName) {
		if (!Helper.isStringEmpty(fullClassName)) {
			frameClassNames.add(fullClassName);
		}
	}

	public static void addLinearLayoutClass(String fullClassName) {
		if (!Helper.isStringEmpty(fullClassName)) {
			linearLayoutClassNames.add(fullClassName);
		}
	}

	// ------------------------>

	public static String convertXmlFiles(File srcDir, File destDir) throws Exception {
		if (srcDir != null) {
			File[] listFiles = srcDir.listFiles(new FilenameFilter() {
				public boolean accept(File dir, String name) {
					return name.toLowerCase().endsWith(XML_EXTENSION);
				}
			});
			for (File file : listFiles) {
				convertXmlFile(file, Helper.getDestFile(file, destDir));
			}
		}
		return destDir != null ? destDir.getPath() : null;
	}

	public static String convertXmlFile(File srcFile, File destFile) throws Exception {
		BufferedReader br = null;
		BufferedWriter out = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(srcFile)));
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFile, false), UTF8));
			String strLine;
			while ((strLine = br.readLine()) != null) {
				out.write(convertXmlLine(strLine));
				out.newLine();
			}
		} finally {
			try {
				if (br != null) {
					br.close();
				}
			} catch (Exception e) {
				Helper.logError(e);
			}
			try {
				if (out != null) {
					out.close();
				}
			} catch (Exception e) {
				Helper.logError(e);
			}
		}
		updateXmlProperties(destFile, destFile);
		return destFile != null ? destFile.getPath() : null;
	}

	private static String convertXmlLine(String line) {
		String usedLine = line;
		String convertedLine = line;
		if (!Helper.isStringEmpty(line)) {
			int previousCuts = 0;
			Matcher matcher = Pattern.compile("android:(.*?)=\"(.*?)\"").matcher(line);
			while (matcher.find()) {
				String group = matcher.group();
				String attrName = matcher.group(1);
				String attrValue = matcher.group(2);
				String convertedAttrName = convertXmlAttrName(attrName);
				String convertedAttrValue = convertXmlAttrValue(attrName, attrValue);
				int start = usedLine.indexOf(group) + previousCuts;
				int end = (start + group.length());
				String part1 = convertedLine.substring(0, start);
				String part2 = convertedLine.substring(end);
				String convertedAttr = String.format("android:%s=\"%s\"", convertedAttrName, convertedAttrValue);
				convertedLine = part1 + convertedAttr + part2;
				previousCuts = (part1 + convertedAttr).length();
				usedLine = part2;
			}
		}
		return convertedLine;
	}

	// ------------------------>

	private static void updateXmlProperties(File srcFile, File destFile) throws Exception {
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(srcFile);
		for (String className : linearLayoutClassNames) {
			updateLinearLayout(doc, className);
		}
		for (String className : frameClassNames) {
			updateFrameLayout(doc, className);
		}
		for (String className : textViewClassNames) {
			updateNodeListGravity(doc.getElementsByTagName(className));
		}
		printXmlDocument(doc, destFile);
	}

	private static void updateLinearLayout(Document doc, String linearLayoutClassName) {
		NodeList nodes = doc.getElementsByTagName(linearLayoutClassName);
		if (nodes != null && nodes.getLength() > 0) {
			for (int i = 0; i < nodes.getLength(); i++) {
				Node item = nodes.item(i);
				NamedNodeMap attr = item.getAttributes();
				// Check Orientation
				Node orientationAttr = attr.getNamedItem(ANDROID_ORIENTATION);
				if (orientationAttr == null
						|| orientationAttr.getTextContent().equalsIgnoreCase(HORIZONTAL) && reverseLinearLayout) {
					reverseChildren(item);
				}
				// Add Gravity Support
				addDirectionGravitySupport(ANDROID_GRAVITY, item);
			}
		}
	}

	private static void updateFrameLayout(Document doc, String frameLayoutClassName) {
		NodeList nodes = doc.getElementsByTagName(frameLayoutClassName);
		if (nodes != null && nodes.getLength() > 0) {
			for (int i = 0; i < nodes.getLength(); i++) {
				Node item = nodes.item(i);
				// Add Layout Gravity Support to children
				if (item != null && item.getChildNodes() != null && item.getChildNodes().getLength() > 0) {
					for (int j = 0; j < item.getChildNodes().getLength(); j++) {
						Node childItem = item.getChildNodes().item(j);
						addDirectionGravitySupport(ANDROID_LAYOUT_GRAVITY, childItem);
					}
				}
			}
		}
	}

	private static void updateNodeListGravity(NodeList nodes) {
		if (nodes != null && nodes.getLength() > 0) {
			for (int i = 0; i < nodes.getLength(); i++) {
				Node item = nodes.item(i);
				addDirectionGravitySupport(ANDROID_GRAVITY, item);
			}
		}
	}

	private static void addDirectionGravitySupport(String attrName, Node item) {
		if (item != null && item.getNodeType() == Node.ELEMENT_NODE) {
			Node GravityAttr = item.getAttributes() != null ? item.getAttributes().getNamedItem(attrName) : null;
			if (GravityAttr == null) {
				((Element) item).setAttribute(attrName, mode == MODE_RTL ? "right|end" : "left|start");
			} else {
				List<String> gravityArray = new ArrayList<>(
						Arrays.asList(getGravityArray(GravityAttr.getTextContent())));
				if (gravityArray != null && !gravityArray.contains(CENTER)
						&& !gravityArray.contains(CENTER_HORIZONTAL)) {
					boolean containsRightOrLeftGravity = false;
					for (String gravity : gravityArray) {
						if (RTL_GRAVITY_MAP.keySet().contains(gravity)) {
							containsRightOrLeftGravity = true;
						}
					}
					if (!containsRightOrLeftGravity) {
						gravityArray.add(mode == MODE_RTL ? "left" : "right");
						gravityArray.add(mode == MODE_RTL ? "start" : "end");
						((Element) item).setAttribute(attrName,
								convertGravityArrayToString(gravityArray.toArray(new String[gravityArray.size()])));
					}
				}
			}
		}
	}

	private static void reverseChildren(Node parent) {
		NodeList children = parent.getChildNodes();
		if (children.getLength() == 0) {
			return;
		}
		List<Node> nodes = new ArrayList<Node>();
		for (int i = 0; i < children.getLength(); i++) {
			Node n = children.item(i);
			nodes.add(n);
		}
		Collections.reverse(nodes);
		for (Node n : nodes) {
			parent.appendChild(n);
		}
	}

	private static void printXmlDocument(Document document, File destPath)
			throws TransformerFactoryConfigurationError, TransformerException {
		Transformer transformer = TransformerFactory.newInstance().newTransformer();
		Result output = new StreamResult(destPath);
		Source input = new DOMSource(document);
		transformer.transform(input, output);
	}

	// ------------------------>

	private static String convertXmlAttrName(String attrName) {
		return RTL_ATTR_MAP.containsKey(attrName) ? RTL_ATTR_MAP.get(attrName) : attrName;
	}

	private static String convertXmlAttrValue(String attrName, String attrValue) {
		String convertedAttrValue = attrValue;
		if (!Helper.isStringEmpty(attrName) && !Helper.isStringEmpty(attrValue) && attrName.contains(GRAVITY)) {
			convertedAttrValue = convertGravityArrayToString(getGravityArray(attrValue));
		}
		return convertedAttrValue;
	}

	private static String convertGravityArrayToString(String[] gravityArray) {
		String convertedAttrValue = "";
		if (gravityArray != null) {
			for (String gravity : gravityArray) {
				convertedAttrValue += (!Helper.isStringEmpty(convertedAttrValue) ? "|" : "")
						+ (RTL_ATTR_MAP.containsKey(gravity) ? RTL_ATTR_MAP.get(gravity) : gravity);
			}
		}
		return convertedAttrValue;
	}

	private static String[] getGravityArray(String attrValue) {
		String[] gravityArray = { attrValue };
		if (attrValue.contains("|")) {
			gravityArray = attrValue.split("\\|");
		}
		return gravityArray;
	}

	// ------------------------>

}


text:
package de.iritgo.aktario.core.gui;

import de.iritgo.aktario.core.base.BaseObject;
import de.iritgo.aktario.core.iobject.IObject;
import de.iritgo.aktario.framework.IritgoEngine;
import de.iritgo.aktario.framework.client.Client;
import de.iritgo.aktario.framework.client.command.ShowWindow;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * A desktop manager handles virtual desktops.
 */
public abstract class IDesktopManager extends BaseObject
{
	/**
	 * Used to temporarily store display information.
	 */
	public class DisplayItem
	{
		/** Gui pane id. */
		public String guiPaneId;

		/** Id of the desktop of this display. */
		public String desktopId;

		/** Id of the IObject displayed in the gui pane. */
		public long iObjectUniqueId;

		/** Id of the IObject displayed in the gui pane. */
		public String iObjectTypeId;

		/** The properties of the gui pane. */
		public Properties properties;

		/** The current onScreen uniqueId of the guipane. */
		protected String onScreenUniqueId;

		/**
		 * Create a new DisplayItem.
		 *
		 * @param guiPaneId Gui pane id.
		 * @param desktopId Id of the desktop of this display.
		 * @param iObject IObject displayed in the gui pane.
		 */
		public DisplayItem(String guiPaneId, String onScreenUniqueId, String desktopId, IObject iObject,
						Properties properties)
		{
			this.guiPaneId = guiPaneId;
			this.desktopId = desktopId;
			this.properties = properties;
			this.onScreenUniqueId = onScreenUniqueId;

			if (iObject != null)
			{
				this.iObjectUniqueId = iObject.getUniqueId();
				this.iObjectTypeId = iObject.getTypeId();
			}
		}
	}

	/** The desktop frame. */
	protected IDesktopFrame desktopFrame;

	/** All displays on all desktops. */
	protected List displays;

	/** Mapping from display ids to displays. */
	protected Map displayById;

	/** Used to temporarily store displays. */
	private List savedDisplays;

	/** All active displays. */
	private IDisplay activeDisplay;

	/**
	 * Create a new IDesktopManager.
	 */
	public IDesktopManager()
	{
		displays = new LinkedList();
		displayById = new HashMap();
	}

	/**
	 * Add an IDisplay to the IDesktopManager.
	 *
	 * @param display The IDisplay to add.
	 */
	public void addDisplay(IDisplay display)
	{
		addDisplay(display, null);
	}

	/**
	 * Add an IDisplay to the IDesktopManager.
	 *
	 * @param display The IDisplay to add.
	 * @param desktopId The id of the desktop on which to open the display.
	 */
	public void addDisplay(IDisplay display, String desktopId)
	{
		displays.add(display);
		displayById.put(display.getOnScreenUniqueId(), display);
		addImpl(display, desktopId);
	}

	/**
	 * Get a Iterator over all Displays
	 *
	 * @return Iterator Iterator for all Displays
	 */
	public Iterator getDisplayIterator()
	{
		return displays.iterator();
	}

	/**
	 * Remove a display.
	 *
	 * @param display The display to remove.
	 */
	public void removeDisplay(IDisplay display)
	{
		if (display != null)
		{
			displays.remove(display);
			displayById.remove(display.getOnScreenUniqueId());
		}
	}

	/**
	 * Get a display by id.
	 *
	 * @param onScreenUniqueId The id of the display to retrieve.
	 * @return The display or null if no display was found.
	 */
	public IDisplay getDisplay(String onScreenUniqueId)
	{
		return (IDisplay) displayById.get(onScreenUniqueId);
	}

	/**
	 * Get a display by id.
	 *
	 * @param onScreenUniqueId The id of the display to retrieve.
	 * @return The display or null if no display was found.
	 */
	public IDisplay waitForDisplay(String onScreenUniqueId)
	{
		IDisplay display = null;

		while (display == null)
		{
			display = (IDisplay) Client.instance().getClientGUI().getDesktopManager().getDisplay(onScreenUniqueId);

			if (display == null)
			{
				try
				{
					Thread.sleep(100);
				}
				catch (InterruptedException x)
				{
				}
			}
		}

		return display;
	}

	/**
	 * Close all displays.
	 */
	public void closeAllDisplays()
	{
		List tmpDisplays = new LinkedList(displays);

		for (Iterator i = tmpDisplays.iterator(); i.hasNext();)
		{
			((IDisplay) i.next()).close();
		}
	}

	/**
	 * Close all displays on a specified pane.
	 *
	 * @param desktopId The id of the desktop.
	 */
	public void closeAllDisplays(String desktopId)
	{
		List tmpDisplays = new LinkedList(displays);

		for (Iterator i = tmpDisplays.iterator(); i.hasNext();)
		{
			IDisplay display = (IDisplay) i.next();

			if (display.getDesktopId().equals(desktopId))
			{
				display.close();
			}
		}
	}

	/**
	 * Temporarily save all currently visible displays.
	 */
	public void saveVisibleDisplays()
	{
		savedDisplays = new LinkedList();

		for (Iterator i = displays.iterator(); i.hasNext();)
		{
			IDisplay display = (IDisplay) i.next();

			if (display.getDesktopId() == null)
			{
				continue;
			}

			IObject businessObject = display.getGUIPane().getObject();

			savedDisplays.add(new DisplayItem(display.getGUIPane().getTypeId(), display.getGUIPane()
							.getOnScreenUniqueId(), display.getDesktopId(), businessObject, display.getGUIPane()
							.getProperties()));
		}
	}

	/**
	 * Redisplay all saved displays.
	 */
	public void showSavedDisplays()
	{
		ShowWindow show = null;

		for (Iterator i = savedDisplays.iterator(); i.hasNext();)
		{
			DisplayItem entry = (DisplayItem) i.next();

			GUIPane guiPane = GUIPaneRegistry.instance().create(entry.guiPaneId);

			if ((guiPane != null) && (entry.iObjectUniqueId != 0))
			{
				show = new ShowWindow(entry.guiPaneId, entry.onScreenUniqueId, entry.iObjectUniqueId,
								entry.iObjectTypeId, entry.desktopId);
			}
			else
			{
				show = new ShowWindow(entry.guiPaneId, entry.onScreenUniqueId, null, null, entry.desktopId);
			}

			show.setProperties(entry.properties);

			IritgoEngine.instance().getAsyncCommandProcessor().perform(show);
		}
	}

	/**
	 * Set the desktop frame.
	 *
	 * @param desktopFrame The desktop frame.
	 */
	public void setDesktopFrame(IDesktopFrame desktopFrame)
	{
		this.desktopFrame = desktopFrame;
	}

	/**
	 * Get the desktop frame.
	 *
	 * @return The desktop frame.
	 */
	public IDesktopFrame getDesktopFrame()
	{
		return desktopFrame;
	}

	/**
	 * Get the currently active display.
	 *
	 * @return The active display or null if no display is currently shown.
	 */
	public IDisplay getActiveDisplay()
	{
		return activeDisplay;
	}

	/**
	 * Set the currently active display.
	 *
	 * @param activeDisplay The active display.
	 */
	public void setActiveDisplay(IDisplay activeDisplay)
	{
		this.activeDisplay = activeDisplay;
	}

	/**
	 * Activate a display.
	 *
	 * @param activeDisplay The display to activate.
	 */
	public void activateDisplay(IDisplay activeDisplay)
	{
	}

	/**
	 * Add an IDisplay.
	 *
	 * @param display The IDisplay to add.
	 * @param desktopId The id of the desktop on which to open the display.
	 */
	public abstract void addImpl(IDisplay display, String desktopId);
}


text:
require_relative "spec_helper"

describe Day2  do

  describe Day2::PresentCollection do

    describe "#wrapping_paper_required" do
      it "handles scenario 1" do
        input = "2x3x4\n1x1x10"
        expected = 101
        actual = Day2::PresentCollection.new(input).wrapping_paper_required
        actual.must_equal expected
      end

      it "handles scenario 2" do
        input = "2x3x4\n1x1x10\n2x3x4\n1x1x10"
        expected = 202
        actual = Day2::PresentCollection.new(input).wrapping_paper_required
        actual.must_equal expected
      end
    end

    describe "#ribbon_required" do
      it "handles scenario 1" do
        input = "2x3x4\n1x1x10"
        expected = 48
        actual = Day2::PresentCollection.new(input).ribbon_required
        actual.must_equal expected
      end

      it "handles scenario 2" do
        input = "2x3x4\n1x1x10\n2x3x4\n1x1x10"
        expected = 96
        actual = Day2::PresentCollection.new(input).ribbon_required
        actual.must_equal expected
      end
    end
  end

  describe Day2::Present do

    let(:zero_present){ Day2::Present.new(0, 0, 0) }
    let(:rectangle1){ Day2::Present.new(2, 3, 4) }
    let(:rectangle2){ Day2::Present.new(1, 1, 10) }

    describe "#wrapping_paper_required" do
      it "handles zeros" do
        expected = 0
        actual = zero_present.wrapping_paper_required
        actual.must_equal expected
      end

      it "handles rectangle1" do
        expected = 58
        actual = rectangle1.wrapping_paper_required
        actual.must_equal expected
      end

      it "handles rectangle2" do
        expected = 43
        actual = rectangle2.wrapping_paper_required
        actual.must_equal expected
      end
    end

    describe "#ribbon_required" do
      it "handles zeroes present" do
        expected = 0
        actual = zero_present.ribbon_required
        actual.must_equal expected
      end

      it "handles rectangle1" do
        expected = 34
        actual = rectangle1.ribbon_required
        actual.must_equal expected
      end

      it "handles rectangle2" do
        expected = 14
        actual = rectangle2.ribbon_required
        actual.must_equal expected
      end
    end

    describe "#volume" do
      it "handles zeros" do
        expected = 0
        actual = zero_present.volume
        actual.must_equal expected
      end

      it "handles rectangle1" do
        expected = 24
        actual = rectangle1.volume
        actual.must_equal expected
      end

      it "handles rectangle2" do
        expected = 10
        actual = rectangle2.volume
        actual.must_equal expected
      end
    end
  end
end


text:
Halaman ini menjelaskan tentang akun di cecunguk.blankonlinux.or.id.

## Fasilitas
* Shell via SSH
* Hosting web pada alamat http://cecunguk.blankonlinux.or.id/~namapengguna

## Batasan
* Otentikasi SSH tidak mengizinkan penggunaan sandi, tapi hanya menggunakan kunci publik SSH

## Persyaratan
* Calon pengguna harus punya akun Launchpad
* Kunci SSH sudah masuk ke Launchpad

## Proses pembuatan akun
* Buat akun dengan adduser

`# adduser namapengguna`

* Pasang kunci SSH

`# ~irgsh/utils/update-ssh.sh namapengguna namapengguna-di-launchpad`

* akun siap digunakan

## Proses pembaruan kunci SSH

* Lakukan

`# ~irgsh/utils/update-ssh.sh namapengguna namapengguna-di-launchpad`

* Kunci SSH yang sudah ada akan diganti dengan kunci baru dari Launchpad

## Proses pembaruan kunci SSH yang sudah ada sebelumnya
* tambahkan "1" pada akhir perintah update-ssh.sh

`# ~irgsh/utils/update-ssh.sh namapengguna namapengguna-di-launchpad 1`

## Menggunakan hosting web
* Masukkan semua berkas yang hendak diakses dari web pada direktori www


text:
A project by Francesca PALMIOTTO and Dario NISI for an academic assignment of the course "Mathematical Models" ("Modelli matematici") at "Scuola Superiore degli Studi di Torino".

## Objective
The purpose of this project is to assign seats to the parties that joined the past Italian elections. applying game theoretical methodologies.
This data will be later compared to the actual electoral results in order to highlight differences from the governance and equity points of view.

## Reference
Once ultimated, the paper Francesca is writing will be published in this repository. You will find there usefull information concerning this topics.

## How to use
Once you clone the project you can run from the root directory of the project:
`python minimaxelections.py <elections-result-file>`
You can find to two examples files (`2008_elections.csv` and `2013_elections.csv`) you can use as an example to build your own elections files to evaluate.
The program will produce a file in the same format containing the seats assignment (in `output.csv`)


text:
package org.ovirt.engine.ui.userportal.section.main.view.popup.vm;

import org.ovirt.engine.ui.common.idhandler.ElementIdHandler;
import org.ovirt.engine.ui.common.view.popup.AbstractModelBoundWidgetPopupView;
import org.ovirt.engine.ui.common.widget.uicommon.popup.vm.VmSnapshotPreviewPopupWidget;
import org.ovirt.engine.ui.uicommonweb.models.vms.SnapshotModel;
import org.ovirt.engine.ui.userportal.ApplicationConstants;
import org.ovirt.engine.ui.userportal.ApplicationMessages;
import org.ovirt.engine.ui.userportal.ApplicationResources;
import org.ovirt.engine.ui.userportal.section.main.presenter.popup.vm.VmSnapshotPreviewPopupPresenterWidget;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;

public class VmSnapshotPreviewPopupView extends AbstractModelBoundWidgetPopupView<SnapshotModel> implements VmSnapshotPreviewPopupPresenterWidget.ViewDef {

    interface ViewIdHandler extends ElementIdHandler<VmSnapshotPreviewPopupView> {
        ViewIdHandler idHandler = GWT.create(ViewIdHandler.class);
    }

    @Inject
    public VmSnapshotPreviewPopupView(EventBus eventBus, ApplicationResources resources, ApplicationConstants constants, ApplicationMessages messages) {
        super(eventBus, resources, new VmSnapshotPreviewPopupWidget(constants, messages), "750px", "450px"); //$NON-NLS-1$ //$NON-NLS-2$
        ViewIdHandler.idHandler.generateAndSetIds(this);
    }
}


text:
import * as utils from '../utils';
import helper from './helper';
import iScroll from 'iscroll';
import session from '../session';
import i18n from '../i18n';
import backbutton from '../backbutton';
import * as xhr from '../xhr';
import newGameForm from './newGameForm';
import gameApi from '../lichess/game';
import challengesApi from '../lichess/challenges';
import m from 'mithril';
import ViewOnlyBoard from './shared/ViewOnlyBoard';

var scroller = null;

const gamesMenu = {};

gamesMenu.isOpen = false;

gamesMenu.open = function() {
  helper.analyticsTrackView('Games Menu');
  backbutton.stack.push(gamesMenu.close);
  gamesMenu.isOpen = true;
  setTimeout(function() {
    if (scroller) scroller.goToPage(1, 0);
  }, 400);
  if (utils.hasNetwork() && session.isConnected()) session.refresh();
};

gamesMenu.close = function(fromBB) {
  if (fromBB !== 'backbutton' && gamesMenu.isOpen) backbutton.stack.pop();
  gamesMenu.isOpen = false;
};

gamesMenu.lastJoined = null;

function joinGame(g) {
  gamesMenu.lastJoined = g;
  gamesMenu.close();
  m.route('/game/' + g.fullId);
}

function acceptChallenge(id) {
  return xhr.joinChallenge(id)
  .then(data =>
    m.route('/game' + data.url.round)
  )
  .then(() => challengesApi.remove(id))
  .then(gamesMenu.close);
}

function declineChallenge(id) {
  return xhr.declineChallenge(id).then(() =>
    challengesApi.remove(id)
  );
}

function cardDims() {
  const vp = helper.viewportDim();

  // if we're here it's a phone
  if (helper.isPortrait()) {
    let width = vp.vw * 85 / 100;
    let margin = vp.vw * 2.5 / 100;
    return {
      w: width + margin * 2,
      h: width + 145,
      innerW: width,
      margin: margin
    };
  } else {
    let width = 150;
    let margin = 10;
    return {
      w: width + margin * 2,
      h: width + 70,
      innerW: width,
      margin: margin
    };
  }
}

function renderViewOnlyBoard(cDim, fen, lastMove, orientation, variant) {
  const style = cDim ? { height: cDim.innerW + 'px' } : {};
  return (

      {m.component(ViewOnlyBoard, { fen, lastMove, orientation, variant })}

  );
}

function timeLeft(g) {
  if (!g.isMyTurn) return i18n('waitingForOpponent');
  if (!g.secondsLeft) return i18n('yourTurn');
  var time = window.moment().add(g.secondsLeft, 'seconds');
  return m('time', {
    datetime: time.format()
  }, time.fromNow());
}

function renderGame(g, cDim, cardStyle) {
  const icon = g.opponent.ai ? ':' : utils.gameIcon(g.perf);
  const cardClass = [
    'card',
    'standard',
    g.color
  ].join(' ');
  const timeClass = [
    'timeIndication',
    g.isMyTurn ? 'myTurn' : 'opponentTurn'
  ].join(' ');
  const config = helper.isWideScreen() ?
    helper.ontouchY(() => joinGame(g)) :
    helper.ontouchX(() => joinGame(g));

  return (

      {renderViewOnlyBoard(cDim, g.fen, g.lastMove, g.color, g.variant)}

{utils.playerName(g.opponent, false)}

            {g.variant.name}
            {timeLeft(g)}

  );
}

function renderChallenge(c, cDim, cardStyle) {
  const icon = utils.gameIcon(c.game.perf);
  const mode = c.game.rated ? i18n('rated') : i18n('casual');
  const timeAndMode = gameApi.time(c) + ', ' + mode;
  const challenger = c.player.user ? c.player : c.opponent;

  return (

      {renderViewOnlyBoard(cDim, c.game.fen, c.game.lastMove, null, c.game.variant)}

{i18n('playerisInvitingYou', utils.playerName(challenger, true))}

            {i18n('toATypeGame', c.game.variant.name)}
            {timeAndMode}

          <button config={helper.ontouchX(utils.f(acceptChallenge, c.game.id))}>
            {i18n('accept')}
          </button>
          <button config={helper.ontouchX(
            helper.fadesOut(declineChallenge.bind(undefined, c.game.id), '.card')
          )}>
            {i18n('decline')}
          </button>

  );
}

function renderAllGames(cDim) {
  const nowPlaying = session.nowPlaying();
  const challenges = challengesApi.list();
  const cardStyle = cDim ? {
    width: (cDim.w - cDim.margin * 2) + 'px',
    height: cDim.h + 'px',
    marginLeft: cDim.margin + 'px',
    marginRight: cDim.margin + 'px'
  } : {};
  const nbCards = challenges.length + nowPlaying.length + 1;
  let wrapperStyle, wrapperWidth;
  if (cDim) {
    // scroller wrapper width
    // calcul is:
    // ((cardWidth + visible part of adjacent card) * nb of cards) +
    //   wrapper's marginLeft
    wrapperWidth = ((cDim.w + cDim.margin * 2) * nbCards) +
      (cDim.margin * 2);
    wrapperStyle = helper.isWideScreen() ? {} : {
      width: wrapperWidth + 'px',
      marginLeft: (cDim.margin * 3) + 'px'
    };
  } else {
    wrapperStyle = {};
  }

  const challengesDom = challenges.map(c => renderChallenge(c, cDim, cardStyle));

  const allCards = challengesDom.concat(nowPlaying.map(g => renderGame(g, cDim, cardStyle)));

  if (!helper.isWideScreen()) {
    const newGameCard = (

 { gamesMenu.close(); newGameForm.open(); })}
      >
        {renderViewOnlyBoard(cDim)}

{i18n('createAGame')}

{i18n('newOpponent')}

    );

    allCards.unshift(newGameCard);
  }

  return (

      {allCards}

  );
}

gamesMenu.view = function() {
  if (!gamesMenu.isOpen) return (

  );

  const vh = helper.viewportDim().vh;
  const cDim = cardDims();
  const wrapperStyle = helper.isWideScreen() ? {} : { top: ((vh - cDim.h) / 2) + 'px' };
  const wrapperConfig =
  helper.isWideScreen() ? utils.noop : function(el, isUpdate, context) {
    if (!isUpdate) {
      scroller = new iScroll(el, {
        scrollX: true,
        scrollY: false,
        momentum: false,
        snap: '.card',
        snapSpeed: 400,
        preventDefaultException: {
          tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT|LABEL)$/
        }
      });

      context.onunload = function() {
        if (scroller) {
          scroller.destroy();
          scroller = null;
        }
      };
    }
    // see https://github.com/cubiq/iscroll/issues/412
    scroller.options.snap = el.querySelectorAll('.card');
    scroller.refresh();
  };
  const wrapperClass = helper.isWideScreen() ? 'overlay_popup' : '';

  return (

        {helper.isWideScreen() ? (

            {i18n('nbGamesInPlay', session.nowPlaying().length)}

        ) : null
        }
        {helper.isWideScreen() ? (

            {renderAllGames(null)}

          ) : renderAllGames(cDim)
        }

  );
};

module.exports = gamesMenu;


text:
#import <UIKit/UIKit.h>
#import "MGTwitterEngine.h"
#import "SBGeolocationController.h"
#import "SBCharacterCountView.h"
#import "SBPostingTitleView.h"
#import "SBBitlyHelper.h"

@class SBTweet;
@class SBAddressBookViewController;
@class SBLocationView;

@interface SBPostingViewController : UIViewController <MGTwitterEngineDelegate, MKReverseGeocoderDelegate, UIActionSheetDelegate, SBBitlyHelperDelegate, SBGeolocationControllerDelegate>
{
@private
  SBPostingTitleView *titleView;

  UIBarButtonItem *closeButton;
  UIBarButtonItem *postButton;
  UITextView *tweetTextView;

  // Bottom Toolbar
  UIToolbar *keyboardToolbar;
  UIBarButtonItem *deleteButton;
  UIBarButtonItem *addGeoDataButton;
  UIBarButtonItem *removeGeoDataButton;
	UIBarButtonItem *postPictureButton;
  SBCharacterCountView *characterCountView;
  UIBarButtonItem *characterCountButton;
  UIBarButtonItem *activityButton;

  // Geolocation Stuff
  BOOL locationViewVisible;
  SBLocationView *locationView;
  SBGeolocationController *locationController;
  MKReverseGeocoder *geoCoder;
  CLLocation *currentLocation;
  NSString *currentLocationString;

  UIViewController *logicalParentViewController;
  SBAddressBookViewController *addressBookViewController;
  MGTwitterEngine *twitter;
  NSOperationQueue *queue;

  SBTweet *inReplyToStatus;
  NSRange cursorSelectionRange;
  BOOL keyboardAlreadyResized;
}

@property (nonatomic, retain) IBOutlet UIBarButtonItem *closeButton;
@property (nonatomic, retain) IBOutlet UIBarButtonItem *postButton;
@property (nonatomic, retain) IBOutlet UITextView *tweetTextView;
@property (nonatomic, retain) IBOutlet UIToolbar *keyboardToolbar;
@property (nonatomic, retain) IBOutlet UIBarButtonItem *addGeoDataButton;
@property (nonatomic, retain) IBOutlet UIBarButtonItem *removeGeoDataButton;
@property (nonatomic, retain) IBOutlet UIBarButtonItem *postPictureButton;
@property (nonatomic, retain) IBOutlet UIBarButtonItem *deleteButton;
@property (nonatomic, retain) IBOutlet SBCharacterCountView *characterCountView;
@property (nonatomic, retain) IBOutlet UIBarButtonItem *characterCountButton;
@property (nonatomic, retain) UIBarButtonItem *activityButton;
@property (nonatomic, retain) SBPostingTitleView *titleView;
@property (nonatomic, retain) UIViewController *logicalParentViewController;
@property (nonatomic, retain) SBAddressBookViewController *addressBookViewController;
@property (nonatomic, retain) SBTweet *inReplyToStatus;
@property (nonatomic, retain) MKReverseGeocoder *geoCoder;
@property (nonatomic, retain) CLLocation *currentLocation;
@property (nonatomic, retain) SBLocationView *locationView;
@property (nonatomic, copy) NSString *currentLocationString;

- (IBAction)post:(id)sender;
- (IBAction)close:(id)sender;
- (IBAction)clearTweet:(id)sender;
- (IBAction)shrinkURLs:(id)sender;
- (IBAction)showAddressBook:(id)sender;
- (IBAction)attachGeocoordinates:(id)sender;
- (IBAction)removeGeocoordinates:(id)sender;
- (IBAction)postPicture:(id) sender;

- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;

@end


text:
using System.Data.Entity;

using Dealership.Models;
using Dealership.Repository.Contracts;

namespace Dealership.Repository
{
    public class EFWorkUnit : IWorkUnit
    {
        private readonly DbContext dbContext;

        public EFWorkUnit(DbContext dbContext)
        {
            this.dbContext = dbContext;
        }

        public void Save()
        {
            this.dbContext.SaveChanges();
        }

        public IRepository<City> CitiesRepository =>
            new EFDealershipRepository<City>(this.dbContext);

        public IRepository<Dealer> DealersRepository =>
            new EFDealershipRepository<Dealer>(this.dbContext);

        public IRepository<Manufacturer> ManufacturersRepository =>
            new EFDealershipRepository<Manufacturer>(this.dbContext);

        public IRepository<Car> CarsRepository =>
            new EFDealershipRepository<Car>(this.dbContext);
    }
}


text:
package org.neo4j.graphdb;

/**
 * This exception is thrown from the {@link GraphDatabaseService#execute(String, java.util.Map) execute method}
 * when there is an error during the execution of a query.
 */
public class QueryExecutionException extends RuntimeException
{
    private final String statusCode;

    public QueryExecutionException( String message, Throwable cause, String statusCode )
    {
        super( message, cause );
        this.statusCode = statusCode;
    }

    /**
     * The Neo4j error status code.
     *
     * @return the Neo4j error status code.
     */
    public String getStatusCode()
    {
        return statusCode;
    }
}


text:
package fr.qp1c.ebdj.liseuse.synchronisation.ws;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import fr.qp1c.ebdj.liseuse.commun.bean.exception.BdjException;
import fr.qp1c.ebdj.liseuse.commun.bean.synchro.Anomalie;
import fr.qp1c.ebdj.liseuse.commun.bean.synchro.Lecture;
import fr.qp1c.ebdj.liseuse.commun.exchange.correction.CorrectionQuestionBdjDistanteDemande;
import fr.qp1c.ebdj.liseuse.commun.exchange.correction.CorrectionQuestionJDBdjDistante;
import fr.qp1c.ebdj.liseuse.commun.exchange.question.QuestionJDBdjDistante;
import fr.qp1c.ebdj.liseuse.commun.exchange.question.QuestionSynchroBdjDistanteDemande;

public class SynchroJDWSHelper extends SynchroWSHelper {

	/**
	 * Default logger.
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(SynchroJDWSHelper.class);

	public SynchroJDWSHelper() {
		super();
	}

	public List<QuestionJDBdjDistante> synchroniserQuestionsJD(Long referenceMaxExistante) throws BdjException {
		List<QuestionJDBdjDistante> questions = new ArrayList<>();

		try {

			ObjectMapper mapper = new ObjectMapper();

			String urlToCall = urlCockpitRest + "/synchroniser/liseuse/jd/questions";

			QuestionSynchroBdjDistanteDemande questionSynchroBdjDistanteDemande = new QuestionSynchroBdjDistanteDemande();
			questionSynchroBdjDistanteDemande.setAuthentificationBdj(authentificationBdj);
			questionSynchroBdjDistanteDemande.setReference(referenceMaxExistante);

			String request = mapper.writeValueAsString(questionSynchroBdjDistanteDemande);

			String response = post(urlToCall, request);

			LOGGER.info(response);

			questions = mapper.readValue(response, new TypeReference<List<QuestionJDBdjDistante>>() {
			});

		} catch (Exception e) {
			LOGGER.error("Exception : an exception has occured : ", e.getMessage());
			throw new BdjException(e, "SYNCHRO_JD_01");
		}

		return questions;
	}

	public List<CorrectionQuestionJDBdjDistante> synchroniserCorrectionsJD(Long indexReprise) throws BdjException {

		List<CorrectionQuestionJDBdjDistante> corrections = new ArrayList<>();

		try {

			ObjectMapper mapper = new ObjectMapper();

			String urlToCall = urlCockpitRest + "/synchroniser/liseuse/jd/corrections";

			CorrectionQuestionBdjDistanteDemande correctionQuestionSynchroBdjDistanteDemande = new CorrectionQuestionBdjDistanteDemande();
			correctionQuestionSynchroBdjDistanteDemande.setAuthentificationBdj(authentificationBdj);
			correctionQuestionSynchroBdjDistanteDemande.setIndex(indexReprise);

			String request = mapper.writeValueAsString(correctionQuestionSynchroBdjDistanteDemande);

			String response = post(urlToCall, request);

			corrections = mapper.readValue(response, new TypeReference<List<CorrectionQuestionJDBdjDistante>>() {
			});

		} catch (Exception e) {
			LOGGER.error("Exception : an exception has occured : ", e.getMessage());
			throw new BdjException(e, "SYNCHRO_JD_02");
		}

		return corrections;
	}

	public void synchroniserLecturesJD(List<Lecture> lectures) throws BdjException {

		String urlToCall = urlCockpitRest + "/synchroniser/liseuse/jd/lectures";

		synchroniserLectures(urlToCall, lectures);
	}

	public void synchroniserAnomaliesJD(List<Anomalie> anomalies) throws BdjException {

		String urlToCall = urlCockpitRest + "/synchroniser/liseuse/jd/anomalies";

		synchroniserAnomalies(urlToCall, anomalies);
	}
}