text:
// **********************************
//    Classes and methods for PCA
// **********************************
//    written using ES6

'strict mode';

/**
 * Class for storing and visualising liner decomposition results
 */
class LDecomp {
   /**
    *
    * @param {Dataset} scores Dataset with scores
    * @param {Dataset} T2  Dataset with T2 residuals
    * @param {Dataset} Q  Dataset with Q residuals
    * @param {Dataset} variance
    * @param {string} info
    */
   constructor (scores, T2, Q, variance, info) {
      this.scores = scores;
      this.T2 = T2;
      this.Q = Q;
      this.variance = variance;
      this.ncomp = scores.nVar;
      this.info = info;
   }

   plotScores (id, comp, param) {
      if (!comp) {
         if (this.scores.nVar > 1) {
            comp = ['Comp 1', 'Comp 2'];
         } else {
            comp = ['Comp 1'];
         }
      }
      return this.scores.subset(comp).plot(id, param);
   }

   plotResiduals (id, ncomp = 1, param = {}) {
      const plotData = new Dataset(
         [this.T2.values[ncomp - 1], this.Q.values[ncomp - 1]],
         ['Hotteling T2 residuals', 'Squared orthogonal distance'],
         this.T2.objNames,
         'Residuals'
      );

      return plotData.plot(id, param);
   }

   plotVariance (id, variance = 'Individual', param = {}) {
      if (!param.type || param.type == 'p') {
         param.type = 'h';
      }

      let plotData = this.variance.subset([variance]);
      plotData.name = variance + ' explained variance';
      plotData.varNames[0] = 'Variance, %';
      plotData.varAxisValues = plotData.varNames;
      return plotData.plot(id, param);
   }
}

class PCARes extends LDecomp {
   constructor(scores, T2, Q, variance, info) {
      super(scores, T2, Q, variance, info);
   }
}

/**
 * Class for a PCA (and similar) model
 * @param {Numeric} ncomp - number of components
 */
class PCAModel {

   constructor () {
      // what can be changed in the model
      this.options = {
         methods: { 'PCA': 0 },
         autoscale: { 'none': 0, 'center only': 1, 'scale only': 2, 'center + scale': 3 },
      };

      // currently selected parameters
      this.param = {
         ncomp: 1,               // number of components to compute
         method: 0,                 // choice for method
         autoscale: 3,              // choice for autoscaling
      };

      /* values using for scale and center of data */
      this.centerValues = null;
      this.scaleValues = null;
      this.tnorm = null;
   }

   /**
    * Compute loadings using the selected method
    * @param {Array} data Numeric 2D array with data after preprocessing
    */
   calibrate (data, ncomp) {
      // generate vector with mean values for centering (or null if no centering is needed)
      if (this.param.autoscale == 1 || this.param.autoscale == 3) {
         this.centerValues = rowMean(data.values);
      } else {
         this.centerValues = null;
      }

      // generate vector with std values for scaling (or null if no scaling is needed)
      if (this.param.autoscale == 2 || this.param.autoscale == 3) {
         this.scaleValues = rowSd(data.values);
      } else {
         this.scaleValues = null;
      }

      // define number of components and number of selected components
      if (ncomp > 0) {
         this.param.ncomp = Math.min(data.nObj - 1, data.nVar, 20, ncomp);
      }

      // autoscale the data values
      let values = autoscale(data.values, this.centerValues, this.scaleValues);

      // get the loadings
      let loadings = null;
      switch (this.param.method) {
         case 0:
            loadings = PCAModel.nipals(values, this.param.ncomp);
            break;
         case 1:
            loadings = PCAModel.ica(values, this.param.ncomp);
            break;
      }

      // convert loading values to Dataset object
      this.loadings = new Dataset(
         loadings,
         paste('Comp', seq(1, this.param.ncomp)),
         data.varNames,
         'Loadings',
         '',
         'Loadings',
         seq(1, this.ncomp),
         data.varAxisName,
         data.varAxisValues
      );

      // calculate PCA resilts for calibration set
      this.tnorm = null;
      this.calres = this.predict(data);
   }

   /**
    * Applies PCA model to a new dataset
    * @param {Dataset} newData A new set of values as Dataset object
    */
   predict (newData) {

      if (this.loadings == null) {
         return undefined;
      }

      // autoscale the new values using values calculated for calibration set
      let values = autoscale(newData.values, this.centerValues, this.scaleValues);

      // compute the scores and create a Dataset object
      let scores = numeric.dot(this.loadings.values, values);
      if (this.ncomp == 1) scores = [scores];

      scores = new Dataset(
         scores,
         this.loadings.varNames,
         newData.objNames,
         'Scores',
         '',
         'Components',
         seq(1, this.ncomp),
         newData.objAxisName,
         newData.objAxisValues
      );

      // compute vector with singular values for normalization of scores (for T2 residuals)
      // do it only once, when model is applied to calibration set
      if (this.tnorm == null) {
         this.tnorm = numeric.sqrt(numeric.div(rowSum(numeric.pow(scores.values, 2)), (scores.nObj - 1)));
      }

      // normalize the scores and prepare arrays for residual distances and cumulative explained variance
      var scoresn = autoscale(scores.values, false, this.tnorm);
      var T2 = Array(this.param.ncomp);
      var Q = Array(this.param.ncomp);
      var cumexpvar = Array(this.param.ncomp);
      var fullvar = numeric.sum(numeric.pow(values, 2));

      // calculate residual distanced and explained variance for each number of components
      for (var i = 1; i <= this.param.ncomp; i++) {
         var TPT = numeric.dot(numeric.transpose(this.loadings.values.slice(0, i)), scores.values.slice(0, i));
         var E = numeric.add(values, numeric.neg(TPT));
         Q[i - 1] = rowSum(numeric.transpose(numeric.pow(E, 2)));
         T2[i - 1] = rowSum(numeric.transpose(numeric.pow(scoresn.slice(0, i), 2)));
         cumexpvar[i - 1] = numeric.sum(numeric.pow(TPT, 2)) / fullvar * 100;
      }

      // compute explained variance for each component individually
      let expvar = numeric.add(cumexpvar, numeric.neg([0].concat(cumexpvar.slice(0, cumexpvar.length - 1))));
      cumexpvar = cumexpvar.map((x) => round(x * 100)/100);
      expvar = expvar.map((x) => round(x * 100)/100);

      // create PCAResults object and return
      return new PCARes(
         scores,
         new Dataset(
            T2,
            scores.varNames,
            scores.objNames,
            'Hotteling T2 residuals',
            '',
            scores.varAxisName,
            scores.varAxisValues,
            newData.objAxisName,
            newData.objAxisValues
         ),
         new Dataset(
            Q,
            scores.varNames,
            scores.objNames,
            'Squared orthogonal distance',
            '',
            scores.varAxisName,
            scores.varAxisValues,
            newData.objAxisName,
            newData.objAxisValues
         ),
         new Dataset(
            [expvar, cumexpvar],
            ['Individual', 'Cumulative'],
            scores.varNames,
            'Explained variance',
            '',
            null,
            null,
            'Components',
            seq(1, this.ncomp)
         ),
         'Calibration results'
      );
   }

   /**
    * Creates a plot for loadings using Plotly
    * @param {HTMLDomObject} id ID of DOM object (div) to show the plot in
    * @param {Numeric[]} comp Which components to make the plot for (one value or an array)
    * @param {Character} type Type of plot ('p', 'l', 'h')
    * @param {Object} param JSON object with plot parameters (see Dataset.plot() method for details)
    */
   plotLoadings (id, comp, param = {}) {
      if (!comp) {
         if (this.param.ncomp > 1) {
            comp = ['Comp 1', 'Comp 2'];
         } else {
            comp = ['Comp 1'];
         }
      }

      if (param.type == undefined) {
         if (comp.length > 1) {
            param.type = 'p';
         } else {
            param.type = 'h';
         }
      }

      // subset loadings for the given number of components
      let subset = this.loadings.subset(comp);

      // add percent of explained variance to the name for each component
      for (let i = 0; i < comp.length; i++) {
         subset.varNames[i] = subset.varNames[i] + ' (' + this.calres.variance.subset([0], comp[i]).values[0][0].toFixed(1) + '%)';
      }

      // show the plot
      let plot = subset.plot(id, modelPlotParam.calres(param));

      // for scatter plot adjust the axes limits
      /*
      if (param.type == 'p') {
         Plotly.relayout(plot, { "xaxis.range": [-1.2, 1.2], "yaxis.range": [-1.2, 1.2] });
      } else {
         Plotly.relayout(plot, { "yaxis.range": [-1.2, 1.2] });
      }
      */

      // for line plot add a siluette with preprocessed values
      if (param.type != 'p' && this.centerValues != null) {
         let prepValues = this.centerValues;
         if (this.scaleValues != null) {
            prepValues = numeric.div(prepValues, this.scaleValues);
         }
         const axsRange = plot.layout.yaxis.range;
         const axsDiff = axsRange[1] - axsRange[0];
         const valRange = [Math.min(...prepValues), Math.max(...prepValues)];
         const valDiff = valRange[1] - valRange[0];
         const newVal = numeric.add(numeric.dot(axsDiff/valDiff, numeric.add(prepValues, -valRange[0])), axsRange[0]);

         let meanTrace = {
            type: 'scatter',
            mode: 'lines',
            hoverinfo: 'none',
            x: this.loadings.objAxisValues,
            y: newVal,
            line: {
               color: "#e0e0e0",
               width: 2,
            }
         };

         if (param.type == 'h') {
            Plotly.addTraces(plot, [meanTrace]);
         } else {
            Plotly.addTraces(plot, [meanTrace], 0);
         }
      }
      return plot;
   }

   /**
    * Creates a plot for scores using Plotly
    * @param {HTMLDomObject} id ID of DOM object (div) to show the plot in
    * @param {Numeric[]} comp Which components to make the plot for (one value or an array)
    * @param {Character} type Type of plot ('p', 'l', 'h')
    * @param {Object} param JSON object with plot parameters (see Dataset.plot() method for details)
    */
   plotScores (id, comp, param = {}) {
      let plot = this.calres.plotScores(id, comp, modelPlotParam.calres(param));
      return plot;
   }

   /**
    * Creates a plot for scores using Plotly
    * @param {HTMLDomObject} id ID of DOM object (div) to show the plot in
    * @param {Numeric} ncomp Which component to make the plot for (one value)
    * @param {Object} param JSON object with plot parameters (see Dataset.plot() method for details)
    */
   plotResiduals (id, ncomp = 1, param = {}) {

      let plot = this.calres.plotResiduals(id, ncomp, modelPlotParam.calres(param));

      if (this.cvres != null) {
         Plotly.addTraces(plot, this.cvres.plotResiduals(null, ncomp, modelPlotParam.cvres(param)));
         Plotly.relayout(plot, { showlegend: false });
      }

      Plotly.relayout(plot, { 'xaxis.range': [0, plot.layout.xaxis.range[1]], 'yaxis.range': [0, plot.layout.yaxis.range[1]]});
      return plot;
   }

   /**
    * Creates a plot for variance using Plotly
    * @param {HTMLDomObject} id ID of DOM object (div) to show the plot in
    * @param {Numeric} variance Which variance to make the plot for ('expvar' or 'cumexpvar')
    * @param {Object} param JSON object with plot parameters (see Dataset.plot() method for details)
    */
    plotVariance (id, variance = 'Expvar', param = {}) {
      let plot = this.calres.plotVariance(id, variance, modelPlotParam.calres(param));

      if (this.cvres != null) {
         Plotly.addTraces(plot, this.cvres.plotResiduals(null, variance, modelPlotParam.cvres(param)));
         Plotly.relayout(plot, { showlegend: false });
      }

      return plot;
   }

   /**
    * Static methods for compiting PCA loadings using SVD
    * @param {Array} values Numeric 2D array with data after preprocessing
    */
   static svd (values) {
      let loadings = numeric.svd(numeric.transpose(values)).V;
      loadings = loadings.slice(0, this.param.ncomp);
      return loadings;
   }

   /**
    * Static method for computing PCA loadings using NIPALS
    * @param {Array} values Numeric 2D array with data after preprocessing
    */
   static nipals (values, ncomp, tolerance = 0.00001) {

      let loadings = Array(ncomp);
      let E = values;

      for (var i = 0; i < ncomp; i++) {
         var sd = rowSd(E);
         var ind = sd.indexOf(Math.max.apply(null, sd));
         var t = E[ind];
         var tau = 99999;
         var th = 9999;

         n = 1;
         var p = null;
         while (th > tolerance && n < 100 && th) {
            p = numeric.div(numeric.dot(E, t), numeric.dot(t, t));
            p = numeric.div(p, Math.sqrt(numeric.dot(p, p)));

            t = numeric.dot(p, E);
            t = numeric.div(t, numeric.dot(p, p));

            var tauNew = numeric.dot(t, t);
            th = Math.abs(tau - tauNew);
            tau = tauNew;
            n++;
         }
         E = numeric.add(E, numeric.neg(numeric.dot(numeric.transpose([p]), [t])));
         loadings[i] = p;
      }

      return loadings;
   }
}

/**
 * Interactive 3D application for PCA
 */
class PCA3DApp {
   constructor(data = people, varset = { X1: 'Height', X2: 'IQ', X3: 'Weight' }) {
      this.data = data;             // dataset
      this.varset = varset;         // selected variables (X1, X2, X3)
      this.model = new PCAModel();  // current PCA model
      this.ncomp = 2;               // number of componenta

      // index and values for selected data point (object)
      this.selection = {
         n: 0,
         X1: this.data.subset(varset.X1).values[0][0],
         X2: this.data.subset(varset.X2).values[0][0],
         X3: this.data.subset(varset.X3).values[0][0],
      };

      // define main DOM elements
      this.gui = {
         dom: {
            tablePane: document.getElementById('tablePane'),
            helpPane: document.getElementById('helpDialog'),
            plotPane: document.getElementById('mainPlotPane'),
            infoPane: document.getElementById('infoPane'),
            dataSettingsPane: document.getElementById('dataSettingsPane'),
            varsetSettingsPane: document.getElementById('varsetSettingsPane'),
            selectedObjectSettingsPane: document.getElementById('selectedObjectSettingsPane'),
         },
         settings: {
            selectedObject: null,
            model: null
         }
      };

      // process keypress events for showing help and table
      window.addEventListener("keydown", (e) => {
         const elHelp = this.gui.dom.helpPane;
         const elMat = this.gui.dom.tablePane;
         const elPlot = this.gui.dom.plotPane;
         switch (e.key) {
            case 'ArrowUp':
               // select object from next row
               this.select('--');
               break;
            case 'ArrowDown':
               // select object from previous row
               this.select('++');
               break;
            case 'h':
               // show/hide window with help text
               elHelp.style.display = (elHelp.style.display == 'none' || !elHelp.style.display) ? 'block' : 'none';
               break;
            case 't':
               // show/hide window with numeric data
               if (elMat.style.display == 'none' || !elMat.style.display) {
                  elPlot.style.display = 'none';
                  elMat.style.display = 'block';
               } else {
                  elPlot.style.display = 'block';
                  elMat.style.display = 'none';
                  resizePlot(elPlot);
               }
               break;
         }
      });

      // setup panel with options for dataset and visualisation
      let el1 = this.gui.dom.dataSettingsPane;
      if (el1) {
         this.gui.settings.model = new dat.GUI({ autoplace: false, width: '100%' });
         this.gui.settings.model
            .add(this.model.param, 'autoscale', this.model.options.autoscale)
            .onChange(() => {
               this.updateAll();
            });
         this.gui.settings.model
            .add(this, 'ncomp', [1, 2])
            .name('number of PCs')
            .onChange((value) => {
               this.updateAll();
            });
         el1.appendChild(this.gui.settings.model.domElement);
      }

      // set up control panel for selecting variables
      let el2 = this.gui.dom.varsetSettingsPane;
      if (el2) {
         this.gui.settings.varset = new dat.GUI({ autoplace: false, width: '100%' });
         this.gui.settings.varset
            .add(this.varset, 'X1', this.data.varNames)
            .onFinishChange(() => {
               this.updateVarset(0);
            });
         this.gui.settings.varset
            .add(this.varset, 'X2', this.data.varNames)
            .onFinishChange(() => {
               this.updateVarset(1);
            });
         this.gui.settings.varset
            .add(this.varset, 'X3', this.data.varNames)
            .onFinishChange(() => {
               this.updateVarset(2);
            });
         el2.appendChild(this.gui.settings.varset.domElement);
      }

      // set up and show settings pane for selected object
      let el3 = this.gui.dom.selectedObjectSettingsPane;
      if (el3) {
         const subset = this.data.subset(Object.values(this.varset));
         const mn = rowMin(subset.values);
         const mx = rowMax(subset.values);
         const df = numeric.div(numeric.add(mx, numeric.neg(mn)), 10);
         this.gui.settings.selectedObject = new dat.GUI({ autoplace: false, width: '100%' });
         this.gui.settings.selectedObject
            .add(this.selection, 'X1', mn[0] - df[0], mx[0] + df[0])
            .name(this.varset.X1)
            .listen()
            .onFinishChange(() => {
               this.updateAll('X1');
            });
         this.gui.settings.selectedObject
            .add(this.selection, 'X2', mn[1] - df[1], mx[1] + df[1])
            .name(this.varset.X2)
            .listen()
            .onFinishChange(() => {
               this.updateAll('X2');
            });
         this.gui.settings.selectedObject
            .add(this.selection, 'X3', mn[2] - df[2], mx[2] + df[2])
            .name(this.varset.X3)
            .listen()
            .onFinishChange(() => {
               this.updateAll('X3');
            });
         el3.appendChild(this.gui.settings.selectedObject.domElement);
      }

      this.computePlotData();
      this.plot();
      this.updateInfo();
      this.select(0);
   }

   /**
    * Updates control elements when variables are changed
    * @param {Numeric} varNum which variable is changed (X1, X2 or X3)
    * @param {*} value new value for the variable
   */
   updateVarset(varNum, value) {
      if (varNum < 0 || varNum > 2) return undefined;

      // get name and values for the selected variable
      const varName = Object.keys(this.varset)[varNum];
      const varValues = this.data.subset(this.varset[varName]).values[0];

      // change varable value for selected object
      this.selection[varName] = varValues[this.selection.n];

      // change limits for the selected variable
      if (this.gui.settings.selectedObject.__controllers[varNum]) {

         // calculate limits for the variable
         const mn = Math.min(...varValues);
         const mx = Math.max(...varValues);
         const df = (mx - mn) / 10;

         // change properties of DAT.GUI element for selected object and variable
         this.gui.settings.selectedObject.__controllers[varNum].name(this.varset[varName]);
         this.gui.settings.selectedObject.__controllers[varNum].__min = mn - df;
         this.gui.settings.selectedObject.__controllers[varNum].__max = mx + df;
         this.gui.settings.selectedObject.__controllers[varNum].updateDisplay();
         this.updateAll();
      }
   }

   /**
    * Updates table with numerical values
    */
   updateTable(ind = [], coeffs = null) {
      var obj = this.gui.dom.tablePane.childNodes[0];
      if (obj) {
         const n = this.selection.n;

         // data set for original values
         let dataRaw = this.data.subset(Object.values(this.varset));
         dataRaw = dataRaw.rbind(dataRaw.mean());
         dataRaw.varNames = ['X1', 'X2', 'X3'];

         // dataset for scaled values
         let dataScaled = new Dataset(this.values, ["X1'", "X2'", "X3'"]);
         dataScaled = dataScaled.rbind(dataScaled.mean());

         // dataset for residual distances
         let dist = new Dataset(
            [
               this.model.calres.T2.subset(this.ncomp - 1).values[0],
               this.model.calres.Q.subset(this.ncomp - 1).values[0],
            ],
            ["T2", "Q"]
         );
         dist = dist.rbind(dist.mean());

         // dataset for projections
         let proj = new Dataset(
            this.projections,
            ['X1', 'X2', 'X3']
         );
         proj = proj.rbind(proj.mean());

         // dataset for redisuals
         let res = new Dataset(
            numeric.add(this.values, numeric.neg(this.projections)),
            ['X1', 'X2', 'X3']
         );
         res = res.rbind(res.mean());

         // dataset for scores
         let scores = this.model.calres.scores.rbind(this.model.calres.scores.mean());

         obj.innerHTML = '' +
            '

X, raw
' + dataRaw.asTable({ showObjNames: true, current: n }) + '
' +
            '

X, autoscaled
' + dataScaled.asTable({ showObjNames: false, dec: 1, current: n }) + '
' +
            "

TP'
" + proj.asTable({ showObjNames: false, dec: 1, current: n }) + '
' +
            '

E
' + res.asTable({ showObjNames: false, dec: 2, current: n }) + '
' +
            '

Scores
' + scores.asTable({ showObjNames: false, dec: 1, current: n }) + '
' +
            '

Distances
' + dist.asTable({ showObjNames: false, current: n }) + '
';
      }
   }

   /**
    * Shows info about the model and variables mean values
    */
    updateInfo() {
      var obj = this.gui.dom.infoPane;
      if (obj) {
         obj.innerHTML = '' +
         '
' +
         this.model.loadings.asTable({showObjNames: true, dec: 3}) +
         '
';
      }
   }

   /**
    * Updates plots if values or parameters have been changed
    * @param {boolean} variableChanged name of variable that has been changed for selected object
    */
   updateAll(variableChanged) {

      // number of current selected object
      const nObj = this.selection.n;

      // update dataset if values for selected object were changed
      if (variableChanged) {
         let nVar = this.data.varNames.indexOf(this.varset[variableChanged]);
         this.data.values[nVar][nObj] = this.selection[variableChanged];
      }

      // recompute the model and PC plane
      this.computePlotData();

      // prepare plot trace for the updated data and model
      const updatePlots = {
         x: [
            this.values[0],
            this.projections[0],
            this.plane[0],
            [this.plane[0][1], this.plane[0][7]],
            [this.plane[0][3], this.plane[0][5]]
         ],
         y: [
            this.values[1],
            this.projections[1],
            this.plane[1],
            [this.plane[1][1], this.plane[1][7]],
            [this.plane[1][3], this.plane[1][5]]
         ],
         z: [
            this.values[2],
            this.projections[2],
            this.plane[2],
            [this.plane[2][1], this.plane[2][7]],
            [this.plane[2][3], this.plane[2][5]]
         ],
      };

      // update names for axes
      var updateLayout = {
         scene: {
            xaxis: { title: this.varset.X1 },
            yaxis: { title: this.varset.X2 },
            zaxis: { title: this.varset.X3 },
         }
      };

      // show the updated plots (both for 3D and model)
      if (this.gui.dom.plotPane != null) {
         Plotly.restyle(this.gui.dom.plotPane, updatePlots, [0, 1, 2, 3, 4]);
         Plotly.relayout(this.gui.dom.plotPane, updateLayout);

         this.updateInfo();
         this.select(nObj);
      }
   }

   /**
    * Computes model and data for 3D plot
    */
   computePlotData() {
      // calibrate PCA model and compute coordinates of projected points
      let data =  this.data.subset(Object.values(this.varset));
      this.model.calibrate(data, this.ncomp);
      this.values = autoscale(data.values, this.model.centerValues, this.model.scaleValues);
      this.projections = numeric.dot(numeric.transpose(this.model.loadings.values), this.model.calres.scores.values);

      // compute evenly spread coordinates to show PC space as a plane
      const n = 10;
      const maxScores = rowMax(numeric.abs(this.model.calres.scores.values));
      const pc1Scores = [-maxScores[0], 0, maxScores[0], -maxScores[0], 0, maxScores[0], -maxScores[0], 0, maxScores[0]];
      const pc2Scores = [-maxScores[1], -maxScores[1], -maxScores[1], 0, 0, 0, maxScores[1], maxScores[1], maxScores[1]];
      this.plane = numeric.transpose(numeric.dot(numeric.transpose([pc1Scores, pc2Scores]), this.model.loadings.values));
   }

   /**
    * Method called when a new object is selected
    */
   select(value) {
      var n = this.selection.n;
      if (typeof (value) == 'string') {
         if (value == '++') {
            n = n + 1;
            if (n >= this.data.nObj) {
               n = 0;
            }
         } else if (value == '--') {
            n = n - 1;
            if (n < 0) {
               n = this.data.nObj;
            }
         }
      } else {
         n = value;
      }

      if (n == null || n < 0 || n >= this.data.nObj) {
         n = 0;
      }

      const subset = this.data.subset(Object.values(this.varset));
      this.selection.n = n;
      this.selection.X1 = subset.values[0][n];
      this.selection.X2 = subset.values[1][n];
      this.selection.X3 = subset.values[2][n];

      var update = {
         x: [[this.values[0][n]], [this.projections[0][n]], [this.values[0][n], this.projections[0][n]]],
         y: [[this.values[1][n]], [this.projections[1][n]], [this.values[1][n], this.projections[1][n]]],
         z: [[this.values[2][n]], [this.projections[2][n]], [this.values[2][n], this.projections[2][n]]],
      };

      Plotly.restyle(this.gui.dom.plotPane, update, null, [5, 6, 7]);
      this.plotModel();
      this.updateTable();
   }

   /**
    * Resizes plots if splitters have been moved
    */
   resizePlots() {
      window.dispatchEvent(new Event('resize'));
   }

   /**
    * Create a 3D plot with data and PCA model
    */
   plot() {
      const layout = {
         autorange: true,
         showlegend: false,
         hovermode: 'closest',
         title: '',
         margin: { l: 30, r: 30, b: 30, t: 0 },
         scene: {
            xaxis: { title: this.varset.X1 },
            yaxis: { title: this.varset.X2 },
            zaxis: { title: this.varset.X3 },
         }
      };

      const dataTrace = {
         opacity: 0.75,
         size: 0.5,
         hoverinfo: 'text',
         text: this.data.objNames,
         type: 'scatter3d',
         x: this.values[0],
         y: this.values[1],
         z: this.values[2],
         mode: 'markers',
         marker: {
            size: 6,
            color: 'dodgerblue'
         }
      };

      const projectionsTrace = {
         opacity: 1,
         size: 0.5,
         type: 'scatter3d',
         hoverinfo: 'text',
         text: this.data.objNames,
         x: this.projections[0],
         y: this.projections[1],
         z: this.projections[2],
         mode: 'markers',
         marker: {
            size: 4,
            color: 'dodgerblue'
         }
      };

      const modelPlaneTrace = {
         x: this.plane[0],
         y: this.plane[1],
         z: this.plane[2],
         hoverinfo: 'none',
         opacity: 0.25,
         type: 'mesh3d',
         color: 'yellow',
      };

      var modelPC1Trace = {
         x: [this.plane[0][1], this.plane[0][7]],
         y: [this.plane[1][1], this.plane[1][7]],
         z: [this.plane[2][1], this.plane[2][7]],
         hoverinfo: 'none',
         type: 'scatter3d',
         mode: 'lines',
         marker: {
            color: 'orange',
         },
         opacity: 0.75
      };

      var modelPC2Trace = {
         x: [this.plane[0][3], this.plane[0][5]],
         y: [this.plane[1][3], this.plane[1][5]],
         z: [this.plane[2][3], this.plane[2][5]],
         hoverinfo: 'none',
         type: 'scatter3d',
         mode: 'lines',
         marker: {
            color: 'orange',
         },
         opacity: 0.75
      };

      const selDataTrace = {
         opacity: 1,
         size: 0.5,
         type: 'scatter3d',
         hoverinfo: 'text',
         text: this.data.objNames,
         x: this.values[0][0],
         y: this.values[1][0],
         z: this.values[2][0],
         mode: 'markers',
         marker: {
            size: 8,
            color: '#1564b2'
         }
      };

      const selProjectionsTrace = {
         opacity: 1,
         size: 0.5,
         type: 'scatter3d',
         hoverinfo: 'text',
         text: this.data.objNames,
         x: this.projections[0][0],
         y: this.projections[1][0],
         z: this.projections[2][0],
         mode: 'markers',
         marker: {
            size: 6,
            color: '#1564b2'
         }
      };

      const selDistanceTrace = {
         x: [this.values[0][0], this.projections[0][0]],
         y: [this.values[1][0], this.projections[1][0]],
         z: [this.values[2][0], this.projections[2][0]],
         hoverinfo: 'text',
         text: ['orthogonal residual distance'],
         type: 'scatter3d',
         mode: 'lines',
         marker: {
            color: '#1564b2',
         },
         opacity: 0.9
      };

      Plotly.newPlot(
         this.gui.dom.plotPane,
         [
            dataTrace, projectionsTrace,
            modelPlaneTrace, modelPC1Trace, modelPC2Trace,
            selDataTrace, selProjectionsTrace, selDistanceTrace,
         ],
         layout,
         { displayModeBar: false }
      );

      // this option is off as it makes rotation of 3D plot more tricky
      // the use of setTimeout is a workaround for an plotly issue reported in
      // https://github.com/plotly/plotly.js/issues/1025
      /*
      this.gui.dom.plotPane.on('plotly_click', (data) => {
         setTimeout(function(obj, n) { obj.select(n); }, 100, this, data.points[0].pointNumber);
      });
      */

      if (this.gui.dom.plotPane != null) {
         var plotPane = this.gui.dom.plotPane;
         window.addEventListener('resize', function () { resizePlot(plotPane); });
      }

   }

   /**
    * show 2D plots for current MLR model
    */
   plotModel() {
      let nObj = this.selection.n;
      let p1 = this.model.plotScores(
         document.getElementById('scoresPlot'), null,
         { showLabels: true, markerSize: 6, current: nObj }
      );
      p1.on('plotly_click', (data) => {
         this.select(data.points[0].pointNumber);
      });

      let p2 = this.model.plotResiduals(
         document.getElementById('residualsPlot'), this.model.param.ncomp,
         { showLabels: true, markerSize: 6, current: nObj }
      );
      p2.on('plotly_click', (data) => {
         this.select(data.points[0].pointNumber);
      });

      this.model.plotLoadings(
         document.getElementById('loadingsPlot'), null,
         { showLabels: true, markerSize: 6 }
      );
   }
}

/** Class for PCA app */
class PCAAppPlot extends MDAAppPlot {
   constructor (parent, plotPane, settingsPane, data = 'scores') {
      super(parent, plotPane, settingsPane, ['scores', 'loadings', 'residuals', 'variance']);
      this.parent = parent;
      this.param.data = data;
      this.param.resncomp = 1;
      this.setDefaultSettings();
      this.update();
   }

   setDefaultSettings() {
      switch (this.param.data) {
         case 'scores':
            this.param.type = 'p';
            break;
         case 'loadings':
            this.param.type = 'p';
            this.param.colorby = 'none';
            break;
         case 'residuals':
           this.param.type = 'p';
           this.param.colorby = 'none';
           break;
         case 'variance':
            this.param.type = 'h';
            break;
      }
   }

   updateSettings() {
      super.updateSettings();
      switch (this.param.data) {
         case 'scores':
            this.setScoresPlotSettings();
            break;
         case 'loadings':
            this.setLoadingsPlotSettings();
            break;
         case 'residuals':
            this.setResidualsPlotSettings();
            break;
         case 'variance':
            this.setVariancePlotSettings();
            break;
      }
   }

   plot() {
      // get values for color by option
      let param = Object.assign({}, this.param, {});
      param.colorby = 'none';
      if (this.param.colorby != 'none') {
         if (this.param.colorby == this.parent.dataset().objAxisName) {
            param.colorby = this.parent.dataset().objAxisValues;
         } else {
            param.colorby = this.parent.dataset().subset(this.param.colorby).values[0];
         }
      }

      // create plot
      let comp = [param.xaxis, param.yaxis];
      switch (this.param.data) {
         case 'scores':
            if (param.xaxis == 'Objects') {
               comp = [param.yaxis];
            }
            this.parent.model.plotScores(this.plotPane, comp, param);
            super.plot();
            break;
         case 'loadings':
            if (param.xaxis == 'Variables') {
               comp = [param.yaxis];
            }
            this.parent.model.plotLoadings(this.plotPane, comp, param);
            super.plot();
            break;
         case 'residuals':
            this.parent.model.plotResiduals(this.plotPane, param.ncomp, param);
            super.plot();
            break;
         case 'variance':
            this.parent.model.plotVariance(this.plotPane, param.variance, param);
            super.plot();
            break;
      }
   }
}

class PCAApp extends MDAApp {
   constructor(datasets, parent = null) {
      super(datasets, parent);
      this.nCompMax = 2;
      this.model = new PCAModel();
      this.model.param.ncomp = 2;

      let el2 = this.gui.modelSettingsPane;
      if (el2) {
         this.settings.model = new dat.GUI({ autoplace: false, width: '100%' });
         this.settings.model
            .add(this.model.param, 'ncomp').min(1).max(this.nCompMax).step(1)
            .name('number of PCs')
            .listen()
            .onFinishChange(() => {
               this.updateAll();
            });
         this.settings.model
            .add(this.model.param, 'autoscale', this.model.options.autoscale)
            .listen()
            .onFinishChange(() => {
               this.updateAll();
            });
         el2.appendChild(this.settings.model.domElement);
      }

      this.selectDataset();
   }

   selectDataset() {
      // set maximum number of components
      this.nCompMax = Math.min(this.dataset().nObj - 1, this.dataset().nVar, 10);

      // change limits for the number of components settings element
      if (this.settings.model.__controllers[0]) {
         this.settings.model.__controllers[0].__min = 1;
         this.settings.model.__controllers[0].__max = this.nCompMax;
         this.settings.model.__controllers[0].updateDisplay();
      }

      super.selectDataset();
   }

   createPlots() {
      this.plots[0] = new PCAAppPlot(this, this.gui.plot1Pane, this.gui.plot1SettingsPane, 'scores');
      this.plots[1] = new PCAAppPlot(this, this.gui.plot2Pane, this.gui.plot2SettingsPane, 'residuals');
      this.plots[2] = new PCAAppPlot(this, this.gui.plot3Pane, this.gui.plot3SettingsPane, 'loadings');
      this.plots[3] = new PCAAppPlot(this, this.gui.plot4Pane, this.gui.plot4SettingsPane, 'variance');
   }
}


text:
package edu.fudan.weixin.model.message;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客服图文消息
 * @author wking
 *
 */
public class NewsJSONMessageBuilder extends JSONMessageBuilder implements NewsMessageBuilder{

	private List<Map<String,String>> articles;

	public TextMessageBuilder toXMLMessageBuilder()
	{
		NewsXMLMessageBuilder builder=new NewsXMLMessageBuilder();
		for(Map<String,String> news:articles)
		{
			builder.addArticle(news.get("title"), news.get("description"), news.get("url"), news.get("picurl"));
		}
		builder.setContent(null);
		return builder;
	}

	public NewsJSONMessageBuilder() {
		super();
		set("msgtype","news");
		articles=new ArrayList<Map<String,String>>();
	}
	/**
	 *
	 * @param news
	 */
	public void setContent(Object news)
	{

		//set("msgtype","news");
		if(news!=null)
			message.put("news", news);
		else
		{
			Map<String,Object> entry=new HashMap<String,Object>();
			entry.put("articles", articles);
			message.put("news", entry);
		}

	}

	public void addArticle(String title,String description, String url, String picurl)
	{
		Map<String,String> article=new HashMap<String,String>();
		article.put("title",title);
		article.put("description", description);
		article.put("url", url);
		article.put("picurl",picurl);
		articles.add(article);
	}
	@Override
	public int getCount() {
		return articles.size();
	}

}

redpajama_set_name: RedPajamaGithub


text:
class TexDistro
  def self.run_command(path, command, config)
    log_file = 'input.log'

    Process.waitpid(
        fork do
          begin
            if config[:dockerImage].blank?
              Dir.chdir path
            end
            # Passenger 4.0.x redirects STDOUT to STDER
            # more info: https://github.com/jacott/rails-latex/issues/29
            if defined?(::PhusionPassenger)
              STDERR.reopen(log_file, 'a')
            else
              STDOUT.reopen(log_file, 'a')
              STDERR.reopen(STDOUT)
            end

            if config[:dockerImage].present?
              picturesPath =  ''
              if config[:appPath].present?
                appPath = File.join(config[:appPath], 'public/uploads')
                picturesPath = " -v #{appPath}:#{appPath}"
              end
              exec "docker run --rm -i --user=\"$(id -un):$(id -gn)\" --net=none #{picturesPath} -v #{path}:/data #{config[:dockerImage]} /bin/bash -c \"source /etc/environment && #{command}\""
            else
              exec command
            end
          rescue
            File.open(log_file, 'a') { |io| io.write("#{$!.message}:\n#{$!.backtrace.join("\n")}\n") }
          ensure
            Process.exit! 1
          end
        end)
  end

  def self.command
    raise 'You forgot to define #command for your TexDistro class'
  end

  def self.pdf_command
    raise 'You forgot to define #pdf_command for your TexDistro class'
  end

  def self.default_arguments
    raise 'You forgot to define #default_arguments for your TexDistro class'
  end

  def self.build_command(arguments, filename)
    raise 'You forgot to define #build_command for your TexDistro class'
  end
end


text:
TitleScreen::TitleScreen(sf::RenderWindow& window) {
    _gui.setWindow(window);

    auto resourceHandler = Locator<ResourceHandler>::get();
    auto settings = Locator<Settings>::get();

    // Pulls the window dimensions from the window
    auto windowWidth = tgui::bindWidth(_gui);
    auto windowHeight = tgui::bindHeight(_gui);

    // Gets the default theme from the ResourceCache
    auto theme = resourceHandler->get<tgui::Theme>(THEME_DEFAULT);

    // Background image
    auto background = tgui::Picture::create();
    background->setTexture(BACKGROUNDS_DIR + settings->getBackground());
    _gui.add(background);

    // Loads the font for the title
    auto titleFont = resourceHandler->emplace<sf::Font>(TITLE_FONT);
    titleFont->loadFromFile(FONTS_DIR + settings->getFont());

    // "Bubble Warrior" text component
    tgui::Label::Ptr lblTitle1 = theme->load("Label");
    lblTitle1->setFont(*titleFont);
    lblTitle1->setTextSize(72);
    lblTitle1->setTextColor(sf::Color::Black);
    lblTitle1->setHorizontalAlignment(tgui::Label::HorizontalAlignment::Center);
    lblTitle1->setSize(windowWidth, 500);
    lblTitle1->setPosition(0, windowHeight / 6);
    lblTitle1->setText("Bubble Warrior");
    _gui.add(lblTitle1);

    // "Adventures" text component
    tgui::Label::Ptr lblTitle2 = theme->load("Label");
    lblTitle2->setFont(*titleFont);
    lblTitle2->setTextSize(72);
    lblTitle2->setTextColor(sf::Color(0x001b0bff));
    lblTitle2->setHorizontalAlignment(tgui::Label::HorizontalAlignment::Center);
    lblTitle2->setSize(windowWidth, 500);
    lblTitle2->setPosition(0, windowHeight * 7 / 20);
    lblTitle2->setText("Adventures");
    _gui.add(lblTitle2);

    // Button constants
    constexpr unsigned BUTTON_HEIGHT = 50,
                       BUTTON_PADDING = 40;

    // Play button
    tgui::Button::Ptr btnPlay = theme->load("Button");
    btnPlay->setSize(windowWidth / 2 - BUTTON_PADDING, BUTTON_HEIGHT);
    btnPlay->setPosition(BUTTON_PADDING, windowHeight * 3 / 5);
    btnPlay->setText("Play");
    btnPlay->connect("pressed", [&] {
        auto stateHandler = Locator<StateHandler>::get();
        if (stateHandler->size() == 1)
            stateHandler->change<PlayScreen>(std::ref(window));
        else
            stateHandler->pop();
    });
    _gui.add(btnPlay);

    // Settings button
    tgui::Button::Ptr btnSettings = theme->load("Button");
    btnSettings->setSize(windowWidth / 2 - BUTTON_PADDING * 2, BUTTON_HEIGHT);
    btnSettings->setPosition(windowWidth / 2 + BUTTON_PADDING,
        windowHeight * 3 / 5);
    btnSettings->setText("Settings");
    _gui.add(btnSettings);

    // Credits button
    tgui::Button::Ptr btnCredits = theme->load("Button");
    btnCredits->setSize(windowWidth / 2 - BUTTON_PADDING, BUTTON_HEIGHT);
    btnCredits->setPosition(BUTTON_PADDING,
        windowHeight * 3 / 5 + BUTTON_HEIGHT + BUTTON_PADDING);
    btnCredits->setText("Credits");
    btnCredits->connect("pressed", [&] {
        Locator<StateHandler>::get()->push<CreditsScreen>(std::ref(window));
    });
    _gui.add(btnCredits);

    // Exit confirmation
    tgui::MessageBox::Ptr msgboxExit = theme->load("MessageBox");

    // Exit button
    tgui::Button::Ptr btnExit = theme->load("Button");
    btnExit->setSize(windowWidth / 2 - BUTTON_PADDING * 2, BUTTON_HEIGHT);
    btnExit->setPosition(windowWidth / 2 + BUTTON_PADDING,
        windowHeight * 3 / 5 + BUTTON_HEIGHT + BUTTON_PADDING);
    btnExit->setText("Exit");
    btnExit->connect("pressed", [=] {
        btnPlay->disable();
        btnSettings->disable();
        btnCredits->disable();
        btnExit->disable();
        auto msgboxExitOffset = msgboxExit->getSizeLayout() / 2;
        msgboxExit->setPosition(windowWidth / 2 - msgboxExitOffset.x,
            windowHeight / 2 - msgboxExitOffset.y);
        msgboxExit->show();
    });
    _gui.add(btnExit);

    // Exit confirmation continued
    msgboxExit->setTitle("Exit Confirmation");
    msgboxExit->setText("Are you sure you want to exit?");
    msgboxExit->addButton("Yes");
    msgboxExit->addButton("No");
    msgboxExit->hide();
    msgboxExit->connect("buttonpressed", [=, &window](const std::string& text) {
        if (text == "Yes")
            window.close();
        else if (text == "No") {
            btnPlay->enable();
            btnSettings->enable();
            btnCredits->enable();
            btnExit->enable();
        }
        msgboxExit->hide();
    });
    msgboxExit->connect("closed", [=] {
        btnPlay->enable();
        btnSettings->enable();
        btnCredits->enable();
        btnExit->enable();
        msgboxExit->hide();
    });
    _gui.add(msgboxExit);
}

void TitleScreen::handleEvent(sf::Event& e) {
    _gui.handleEvent(e);
}

void TitleScreen::update(float delta) {}

void TitleScreen::draw(sf::RenderWindow& window) {
    _gui.draw();
}


text:
/// <reference path="angular.d.ts" />

// issue: https://github.com/borisyankov/DefinitelyTyped/issues/369
https://github.com/witoldsz/angular-http-auth/blob/master/src/angular-http-auth.js
/**
 * @license HTTP Auth Interceptor Module for AngularJS
 * (c) 2012 Witold Szczerba
 * License: MIT
 */
angular.module('http-auth-interceptor', [])

  .provider('authService', function () {
      /**
       * Holds all the requests which failed due to 401 response,
       * so they can be re-requested in future, once login is completed.
       */
      var buffer = [];

      /**
       * Required by HTTP interceptor.
       * Function is attached to provider to be invisible for regular users of this service.
       */
      this.pushToBuffer = function (config: ng.IRequestConfig, deferred: ng.IDeferred) {
          buffer.push({
              config: config,
              deferred: deferred
          });
      }

      this.$get = ['$rootScope', '$injector', <any>function ($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) {
          var $http: ng.IHttpService; //initialized later because of circular dependency problem
          function retry(config: ng.IRequestConfig, deferred: ng.IDeferred) {
              $http = $http || $injector.get('$http');
              $http(config).then(function (response) {
                  deferred.resolve(response);
              });
          }
          function retryAll() {
              for (var i = 0; i < buffer.length; ++i) {
                  retry(buffer[i].config, buffer[i].deferred);
              }
              buffer = [];
          }

          return {
              loginConfirmed: function () {
                  $rootScope.$broadcast('event:auth-loginConfirmed');
                  retryAll();
              }
          }
      }]
  })

  /**
   * $http interceptor.
   * On 401 response - it stores the request and broadcasts 'event:angular-auth-loginRequired'.
   */
  .config(['$httpProvider', 'authServiceProvider', <any>function ($httpProvider: ng.IHttpProvider, authServiceProvider) {

      var interceptor = ['$rootScope', '$q', <any>function ($rootScope: ng.IScope, $q: ng.IQService) {
          function success(response: ng.IHttpPromiseCallbackArg) {
              return response;
          }

          function error(response: ng.IHttpPromiseCallbackArg) {
              if (response.status === 401) {
                  var deferred = $q.defer();
                  authServiceProvider.pushToBuffer(response.config, deferred);
                  $rootScope.$broadcast('event:auth-loginRequired');
                  return deferred.promise;
              }
              // otherwise
              return $q.reject(response);
          }

          return function (promise: ng.IHttpPromise) {
              return promise.then(success, error);
          }

      }];
      $httpProvider.responseInterceptors.push(interceptor);
  }]);

module HttpAndRegularPromiseTests {
  interface Person {
    firstName: string;
    lastName:  string;
  }

  interface ExpectedResponse extends Person {}

  interface SomeControllerScope extends ng.IScope {
    person:    Person;
    theAnswer: number;
    letters:   string[];
  }

  interface OurApiPromiseCallbackArg extends ng.IHttpPromiseCallbackArg {
    data?: ExpectedResponse;
  }

  var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => {
    $http.get("http://somewhere/some/resource")
    .success((data: ExpectedResponse) => {
      $scope.person = data;
    });

    $http.get("http://somewhere/some/resource")
    .then((response: ng.IHttpPromiseCallbackArg) => {
      // typing lost, so something like
      // var i: number = response.data
      // would type check
      $scope.person = response.data;
    });

    $http.get("http://somewhere/some/resource")
    .then((response: OurApiPromiseCallbackArg) => {
      // typing lost, so something like
      // var i: number = response.data
      // would NOT type check
      $scope.person = response.data;
    });

    var aPromise: ng.IPromise = $q.when({firstName: "Jack", lastName: "Sparrow"});
    aPromise.then((person: Person) => {
      $scope.person = person;
    });

    var bPromise: ng.IPromise = $q.when(42);
    bPromise.then((answer: number) => {
      $scope.theAnswer = answer;
    });

    var cPromise: ng.IPromise = $q.when(["a", "b", "c"]);
    cPromise.then((letters: string[]) => {
      $scope.letters = letters;
    });
  }

  // Test that we can pass around a type-checked success/error Promise Callback
  var anotherController: Function = ($scope: SomeControllerScope, $http:
      ng.IHttpService, $q: ng.IQService) => {

    var buildFooData: Function = () => 42;

    var doFoo: Function = (callback: ng.IHttpPromiseCallback) => {
      $http.get('/foo', buildFooData())
        .success(callback);
    }

    doFoo((data) => console.log(data));
  }
}

// Test for AngularJS Syntac

module My.Namespace {
    export var x; // need to export something for module to kick in
}

// IModule Registering Test
var mod = angular.module('tests',[]);
mod.controller('name', function($scope : ng.IScope) {})
mod.controller('name', ['$scope', <any>function($scope : ng.IScope) {}])
mod.controller(My.Namespace);
mod.directive('name', <any>function ($scope: ng.IScope) {})
mod.directive('name', ['$scope', <any>function($scope : ng.IScope) {}])
mod.directive(My.Namespace);
mod.factory('name', function($scope : ng.IScope) {})
mod.factory('name', ['$scope', <any>function($scope : ng.IScope) {}])
mod.factory(My.Namespace);
mod.filter('name', function($scope : ng.IScope) {})
mod.filter('name', ['$scope', <any>function($scope : ng.IScope) {}])
mod.filter(My.Namespace);
mod.provider('name', function($scope : ng.IScope) {})
mod.provider('name', ['$scope', <any>function($scope : ng.IScope) {}])
mod.provider(My.Namespace);
mod.service('name', function($scope : ng.IScope) {})
mod.service('name', ['$scope', <any>function($scope : ng.IScope) {}])
mod.service(My.Namespace);
mod.constant('name', 23);
mod.constant('name', "23");
mod.constant(My.Namespace);
mod.value('name', 23);
mod.value('name', "23");
mod.value(My.Namespace);


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { CabezaComponent } from './cabeza.component';

describe('CabezaComponent', () => {
  let component: CabezaComponent;
  let fixture: ComponentFixture<CabezaComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CabezaComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CabezaComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});


text:
/**
 * Provides classes for spelling.
 *
 * @author  Justin Basilico
 * @since   3.0
 */
@gov.sandia.cognition.annotation.Documentation
package gov.sandia.cognition.text.spelling;


text:
"""
Copyright 2013 Jérémie BOUTOILLE

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""

from struct import unpack, pack
from viper.modules.pymacho.MachOLoadCommand import MachOLoadCommand
from viper.modules.pymacho.Constants import *
from viper.modules.pymacho.Utils import green

class MachODYLDInfoCommand(MachOLoadCommand):

    rebase_off = 0
    rebase_size = 0
    bind_off = 0
    bind_size = 0
    weak_bind_off = 0
    weak_bind_size = 0
    lazy_bind_off = 0
    lazy_bind_size = 0
    export_off = 0
    export_size = 0

    def __init__(self, macho_file=None, cmd=0):
        self.cmd = cmd
        if macho_file is not None:
            self.parse(macho_file)

    def parse(self, macho_file):
        self.rebase_off, self.rebase_size, self.bind_off, self.bind_size = unpack('<IIII', macho_file.read(4*4))
        self.weak_bind_off, self.weak_bind_size, self.lazy_bind_off, self.lazy_bind_size = unpack('<IIII', macho_file.read(4*4))
        self.export_off, self.export_size = unpack('<II', macho_file.read(2*4))

    def write(self, macho_file):
        before = macho_file.tell()
        macho_file.write(pack('<I', self.cmd))
        macho_file.write(pack('<I', 0x0)) # cmdsize
        macho_file.write(pack('<IIII', self.rebase_off, self.rebase_size, self.bind_off, self.bind_size))
        macho_file.write(pack('<IIII', self.weak_bind_off, self.weak_bind_size, self.lazy_bind_off, self.lazy_bind_size))
        macho_file.write(pack('<II', self.export_off, self.export_size))
        after = macho_file.tell()
        macho_file.seek(before+4)
        macho_file.write(pack('<I', after-before))
        macho_file.seek(after)

    def display(self, before=''):
        print before + green("[+]")+" %s" % ("LC_DYLD_INFO_ONLY" if self.cmd == LC_DYLD_INFO_ONLY else "LC_DYLD_INFO")
        print before + "\t- rebase_off : 0x%x" % self.rebase_off
        print before + "\t- rebase_size : %d (0x%x)" % (self.rebase_size, self.rebase_size)
        print before + "\t- bind_off : 0x%x" % self.bind_off
        print before + "\t- bind_size : %d (0x%x)" % (self.bind_size, self.bind_size)
        print before + "\t- weak_bind_off : 0x%x" % self.weak_bind_off
        print before + "\t- weak_bind_size : %d (0x%x)" % (self.weak_bind_size, self.weak_bind_size)
        print before + "\t- lazy_bind_off : 0x%x" % self.lazy_bind_off
        print before + "\t- lazy_bind_size : %d (0x%x)" % (self.lazy_bind_size, self.lazy_bind_size)
        print before + "\t- export_off : 0x%x" % self.export_off
        print before + "\t- export_size : %d (0x%x)" % (self.export_size, self.export_size)


text:
<?php
require_once "Loader.php";

class Feature_LoggerTest extends PHPUnit_Framework_TestCase {

    // Test cases borrowed from AB2_Logger_GALoggerTest

    function testNoLogging() {
        $this->assertEquals('', Feature_Logger::getGAJavascript(array()));
    }

    function testLogOne() {
        $selections = array();
        $selections[] = array('TEST_key1', 'TEST_var1', 123);
        $js = Feature_Logger::getGAJavascript($selections);
        $this->assertEquals("Etsy.GA.track(['_setCustomVar', 2, 'AB', 'TEST_key1.TEST_var1', 3]);", $js);
    }

    function testLogTwo() {
        $selections = array();
        $selections[] = array('TEST_key1', 'TEST_var1', 123);
        $selections[] = array('foo', 'bar', 123);
        $js = Feature_Logger::getGAJavascript($selections);
        $this->assertEquals("Etsy.GA.track(['_setCustomVar', 2, 'AB', 'TEST_key1.TEST_var1..foo.bar', 3]);", $js);
    }

    function testTooLong() {
        $selections = array();
        $pairs = array();
        foreach (array('a', 'b', 'c', 'd', 'e') as $x) {
            $selections[] = array($x, 'xxxxxxxxxx', 123);
            $pairs[] = "$x.xxxxxxxxxx";
        }
        // This one should not be included in the Javascript because
        // we already have 12*5=60 chars and this pair would add three
        // more pushing us over the limit of 62.
        $selections[] = array('f', 'x', 123);
        $value = implode('..', $pairs);
        $js = Feature_Logger::getGAJavascript($selections);
        $this->assertEquals("Etsy.GA.track(['_setCustomVar', 2, 'AB', '$value', 3]);", $js);
    }
}


text:
package com.incomb.server.indexing.conf.fields;

import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;

/**
 * Wraps a {@link String} into a {@link TextField}.
 * The value can be stored and will be tokenized. That means that only if the
 * user searches for a single part of value the document will be found.
 * @see StringIndexFieldConf
 */
public class TextIndexFieldConf extends AStoreableIndexFieldConf<String> {

	/**
	 * Creates a new instance.
	 * @param name the name of the field
	 * @param store true if the value should be stored
	 */
	public TextIndexFieldConf(final String name, final boolean store) {
		super(name, store);
	}

	/**
	 * {@inheritDoc}
	 * @see TextIndexFieldConf
	 */
	@Override
	public Field buildField(final String content) {
		return new TextField(getName(), content, isStored());
	}
}


text:
{% load xforms_extras %}
{% if module %}

    >

        {{ module.name|html_trans:langs|safe }}

{% endif %}


text:
"""Find the path to xgboost dynamic library files."""

import os
import platform
import sys
from typing import List

class XGBoostLibraryNotFound(Exception):
    """Error thrown by when xgboost is not found"""

def find_lib_path() -> List[str]:
    """Find the path to xgboost dynamic library files.

    Returns
    -------
    lib_path
       List of all found library path to xgboost
    """
    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
    dll_path = [
        # normal, after installation `lib` is copied into Python package tree.
        os.path.join(curr_path, 'lib'),
        # editable installation, no copying is performed.
        os.path.join(curr_path, os.path.pardir, os.path.pardir, 'lib'),
        # use libxgboost from a system prefix, if available.  This should be the last
        # option.
        os.path.join(sys.prefix, 'lib'),
    ]

    if sys.platform == 'win32':
        if platform.architecture()[0] == '64bit':
            dll_path.append(
                os.path.join(curr_path, '../../windows/x64/Release/'))
            # hack for pip installation when copy all parent source
            # directory here
            dll_path.append(os.path.join(curr_path, './windows/x64/Release/'))
        else:
            dll_path.append(os.path.join(curr_path, '../../windows/Release/'))
            # hack for pip installation when copy all parent source
            # directory here
            dll_path.append(os.path.join(curr_path, './windows/Release/'))
        dll_path = [os.path.join(p, 'xgboost.dll') for p in dll_path]
    elif sys.platform.startswith(('linux', 'freebsd', 'emscripten')):
        dll_path = [os.path.join(p, 'libxgboost.so') for p in dll_path]
    elif sys.platform == 'darwin':
        dll_path = [os.path.join(p, 'libxgboost.dylib') for p in dll_path]
    elif sys.platform == 'cygwin':
        dll_path = [os.path.join(p, 'cygxgboost.dll') for p in dll_path]
    if platform.system() == 'OS400':
        dll_path = [os.path.join(p, 'libxgboost.so') for p in dll_path]

    lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)]

    # XGBOOST_BUILD_DOC is defined by sphinx conf.
    if not lib_path and not os.environ.get('XGBOOST_BUILD_DOC', False):
        link = 'https://xgboost.readthedocs.io/en/latest/build.html'
        msg = 'Cannot find XGBoost Library in the candidate path.  ' + \
            'List of candidates:\n- ' + ('\n- '.join(dll_path)) + \
            '\nXGBoost Python package path: ' + curr_path + \
            '\nsys.prefix: ' + sys.prefix + \
            '\nSee: ' + link + ' for installing XGBoost.'
        raise XGBoostLibraryNotFound(msg)
    return lib_path


text:
namespace app { namespace Uno { namespace IO { struct Stream; } } }

namespace app {
namespace Fuse {
namespace Reactive {

struct JSFileSource;

struct JSFileSource__uType : ::app::Uno::UX::FileSource__uType
{
};

JSFileSource__uType* JSFileSource__typeof();

void JSFileSource___ObjInit_1(JSFileSource* __this, ::uString* path);
JSFileSource* JSFileSource__New_1(::uStatic* __this, ::uString* path);
::app::Uno::IO::Stream* JSFileSource__OpenRead(JSFileSource* __this);

struct JSFileSource : ::app::Uno::UX::FileSource
{
    ::uStrong< ::uString*> _path;

    void _ObjInit_1(::uString* path) { JSFileSource___ObjInit_1(this, path); }
};

}}}

#endif


text:
package info.rmapproject.api;

import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.annotation.Transactional;

/**
 * Tests for ResponseManager.
 * @author khanson
 */
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles({"default", "inmemory-triplestore", "inmemory-idservice", "inmemory-db", "embedded-solr", "mock-kafka"})
@ContextConfiguration("classpath:/beans.xml")
@Transactional
public abstract class ApiTestAbstractIT {

}


text:
'use strict';

/**
 * @ngdoc function
 * @name healthAnalyticsSiteApp.controller:AboutCtrl
 * @description
 * # AboutCtrl
 * Controller of the healthAnalyticsSiteApp
 */
angular.module('healthAnalyticsSiteApp')
  .controller('AboutCtrl', function () {
    this.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];
  });


text:
/*
*/
#ifdef Consequences1
/*
*/
class Composition {
  public:
    void Repair();
    void ComposeWithSimpleCompositor();
    void ComposeWithTeXCompositor();
    int _breakingStrategy;
};
const int SimpleStrategy = 1;
const int TeXStrategy = 2;
/*
*/
void Composition::Repair () {
    switch (_breakingStrategy) {
    case SimpleStrategy:
        ComposeWithSimpleCompositor();
        break;
    case TeXStrategy:
        ComposeWithTeXCompositor();
        break;
    // ...
    }
    // merge results with existing composition, if necessary
}
/*
*/
#endif
/*
*/
#ifdef Consequences2
class Compositor {
    public:
    void Compose();
};
class Composition {
  public:
    void Repair();
    Compositor* _compositor;
};
/*
*/
void Composition::Repair () {
    _compositor->Compose();
    // merge results with existing composition, if necessary
}
/*
*/
#endif
/*
*/
#ifdef Implementation
/*
*/
template <class AStrategy>
class Context {
    void Operation() { theStrategy.DoAlgorithm(); }
    // ...
private:
    AStrategy theStrategy;
};
/*
*/
class MyStrategy {
public:
    void DoAlgorithm();
};

Context<MyStrategy> aContext;
/*
*/
#endif
/*
*/
#ifdef SampleCode
#include "Geom.H"
/*
*/
class Compositor;
class Component;
/*
*/
class Composition {
public:
    Composition(Compositor*);
    void Repair();
private:
    Compositor* _compositor;
    Component* _components;    // the list of components
    int _componentCount;       // the number of components
    int _lineWidth;            // the Composition's line width
    int* _lineBreaks;          // the position of linebreaks
                               // in components
    int _lineCount;            // the number of lines
};
/*
*/
class Compositor {
public:
    virtual int Compose(
        Coord natural[], Coord stretch[], Coord shrink[],
        int componentCount, int lineWidth, int breaks[]
    ) = 0;
protected:
    Compositor();
};
/*
*/
Coord coords[] = {
    1,2,3
};
int b[] = {
    1,2,2
};
/*
*/
void Composition::Repair () {
    Coord* natural;
    Coord* stretchability;
    Coord* shrinkability;
    int componentCount;
    int* breaks;

    // prepare the arrays with the desired component sizes
    // ...
/*
*/
    // kills comiler warnings
    natural = coords;
    stretchability = coords;
    shrinkability = coords;
    componentCount = 1;
    breaks = b;
/*
*/
    // determine where the breaks are:
    int breakCount;
    breakCount = _compositor->Compose(
        natural, stretchability, shrinkability,
        componentCount, _lineWidth, breaks
    );
/*
*/
    // lay out components according to breaks
    // ...
}
/*
*/
class SimpleCompositor : public Compositor {
public:
    SimpleCompositor();

    virtual int Compose(
        Coord natural[], Coord stretch[], Coord shrink[],
        int componentCount, int lineWidth, int breaks[]
    );
    // ...
};
/*
*/
class TeXCompositor : public Compositor {
public:
    TeXCompositor();

    virtual int Compose(
        Coord natural[], Coord stretch[], Coord shrink[],
        int componentCount, int lineWidth, int breaks[]
    );
    // ...
};
/*
*/
class ArrayCompositor : public Compositor {
public:
    ArrayCompositor(int interval);

    virtual int Compose(
        Coord natural[], Coord stretch[], Coord shrink[],
        int componentCount, int lineWidth, int breaks[]
    );
    // ...
};
/*
*/
Composition* quick = new Composition(new SimpleCompositor);
Composition* slick = new Composition(new TeXCompositor);
Composition* iconic = new Composition(new ArrayCompositor(100));
/*
*/
#endif
/*
*/


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.contracts.commerceruntime.products;

import org.joda.time.DateTime;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.joda.time.DateTime;
import com.mozu.api.contracts.commerceruntime.commerce.PackageMeasurements;

/**
 *	Properties of a component product in a product bundle. A product bundle can represent either a collection of multiple products sold as a single entity, or a collection of the same product sold as a package. For example, a 10-pack of socks or multiple parts and devices in a technology bundle for a computer.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class BundledProduct implements Serializable
{
	// Default Serial Version UID
	private static final long serialVersionUID = 1L;

	/**
	 * Allocation ID associated with this product on this order.
	 */
	protected DateTime allocationExpiration;

	public DateTime getAllocationExpiration() {
		return this.allocationExpiration;
	}

	public void setAllocationExpiration(DateTime allocationExpiration) {
		this.allocationExpiration = allocationExpiration;
	}

	/**
	 * Allocation ID associated with this product on this order.
	 */
	protected Integer allocationId;

	public Integer getAllocationId() {
		return this.allocationId;
	}

	public void setAllocationId(Integer allocationId) {
		this.allocationId = allocationId;
	}

	/**
	 * The credit value of the product or bundled product. When the `goodsType `is `DigitalCredit`, this value is populated to indicate the value of the credit. This is used to create store credit in the fulfillment of gift cards.
	 */
	protected Double creditValue;

	public Double getCreditValue() {
		return this.creditValue;
	}

	public void setCreditValue(Double creditValue) {
		this.creditValue = creditValue;
	}

	/**
	 * The localized description in text for the object, displayed per the locale code. For example, descriptions are used for product descriptions, attributes, and pre-authorization transaction types.
	 */
	protected String description;

	public String getDescription() {
		return this.description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	/**
	 * Fulfillment status of the product.
	 */
	protected String fulfillmentStatus;

	public String getFulfillmentStatus() {
		return this.fulfillmentStatus;
	}

	public void setFulfillmentStatus(String fulfillmentStatus) {
		this.fulfillmentStatus = fulfillmentStatus;
	}

	/**
	 * The type of goods in a bundled product. A bundled product is composed of products associated to sell together. Possible values include "Physical" and "DigitalCredit". This comes from the `productType `of the product. Products are defaulted to a Physical `goodsType`. Gift cards have a `goodsType `of DigitalCredit.
	 */
	protected String goodsType;

	public String getGoodsType() {
		return this.goodsType;
	}

	public void setGoodsType(String goodsType) {
		this.goodsType = goodsType;
	}

	/**
	 * Indicates if the product must be shipped alone in a container. This is used for products and products within a bundle. If true, this product cannot be shipped in a package with other items and must ship in a package by itself.
	 */
	protected Boolean isPackagedStandAlone;

	public Boolean getIsPackagedStandAlone() {
		return this.isPackagedStandAlone;
	}

	public void setIsPackagedStandAlone(Boolean isPackagedStandAlone) {
		this.isPackagedStandAlone = isPackagedStandAlone;
	}

	/**
	 * The display name of the source product property. For a product field it will be the display name of the field. For a product attribute it will be the Attribute Name.
	 */
	protected String name;

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	/**
	 * The fully qualified name of the attribute, which is a user defined attribute identifier.
	 */
	protected String optionAttributeFQN;

	public String getOptionAttributeFQN() {
		return this.optionAttributeFQN;
	}

	public void setOptionAttributeFQN(String optionAttributeFQN) {
		this.optionAttributeFQN = optionAttributeFQN;
	}

	/**
	 * The value of the option attribute. These values are associated and used by product bundles and options.
	 */
	protected Object optionValue;

	public Object getOptionValue() {
		return this.optionValue;
	}

	public void setOptionValue(Object optionValue) {
		this.optionValue = optionValue;
	}

	/**
	 * Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only.
	 */
	protected String productCode;

	public String getProductCode() {
		return this.productCode;
	}

	public void setProductCode(String productCode) {
		this.productCode = productCode;
	}

	/**
	 * Unique identifier of the product reservation associated with the component product in a product bundle or item in a cart/order. System-supplied and read only.
	 */
	protected Integer productReservationId;

	public Integer getProductReservationId() {
		return this.productReservationId;
	}

	public void setProductReservationId(Integer productReservationId) {
		this.productReservationId = productReservationId;
	}

	/**
	 * The specified quantity of objects and items. This property is used for numerous object types including products, options, components within a product bundle, cart and order items, returned items, shipping line items, items in a digital product. and items associated with types and reservations.
	 */
	protected Integer quantity;

	public Integer getQuantity() {
		return this.quantity;
	}

	public void setQuantity(Integer quantity) {
		this.quantity = quantity;
	}

	/**
	 * Dimensions of the packaged product.
	 */
	protected PackageMeasurements measurements;

	public PackageMeasurements getMeasurements() {
		return this.measurements;
	}

	public void setMeasurements(PackageMeasurements measurements) {
		this.measurements = measurements;
	}

}


text:
package com.ts.service.Report.InHospitalRep.AntiDrugRep.Impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.ts.dao.DAO;
import com.ts.entity.Page;
import com.ts.service.Report.InHospitalRep.AntiDrugRep.IAntiDrugUseService;
import com.ts.util.PageData;

/**
 * 抗菌药物分级管理报表
 * @author autumn
 *
 */
@Service("antiDrugUseServiceBean")
public class AntiDrugUseServiceBean implements IAntiDrugUseService
{

    @Resource(name="daoSupportPH")
    private DAO daoPH ;

    @Override
    public List<PageData> DRANO013(Page page) throws Exception
    {
        List<PageData> listpd = null;
        if("zl".equals(page.getPd().getString("useType")))
        {
            listpd = (List<PageData>) daoPH.findForList("antiDrugUse.findAntiDrugUseZLPage", page);
        }
        else
        {
            listpd = (List<PageData>) daoPH.findForList("antiDrugUse.findAntiDrugUseYFPage", page);
        }
        return listpd;
    }

    @Override
    public PageData DRANO013Sum(PageData pd) throws Exception
    {
        PageData entity = null;
        if("zl".equals(pd.getString("useType")))
        {
            entity = (PageData) daoPH.findForObject("antiDrugUse.findAntiDrugUseZLSum", pd);
        }else
        {
            entity = (PageData) daoPH.findForObject("antiDrugUse.findAntiDrugUseYFSum", pd);
        }
        return entity;
    }

    @Override
    public List<PageData> DRANO014(Page page) throws Exception
    {
        List<PageData> listpd = null;
        if("zl".equals(page.getPd().getString("useType")))
        {
            listpd = (List<PageData>) daoPH.findForList("antiDrugUse.findAntiDrugUsePatZLPage", page);
        }
        else
        {
            listpd = (List<PageData>) daoPH.findForList("antiDrugUse.findAntiDrugUsePatYFPage", page);
        }
        return listpd;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

namespace KindergartentManagerment.Models
{
    public class DD_LoaiSuatAn
    {
        [Key]
        public int DDLoaiSuatAnID { get; set; }

        [Required]
        [StringLength(50, ErrorMessage = "Ten loai suat an cannot be longer than 50 characters.")]
        public string TenLoaiSuatAn { get; set; }
        public string GhiChu { get; set; }
        public string Record_Status { get; set; }
        public string Maker_ID { get; set; }
        public Nullable<System.DateTime> Create_DT { get; set; }
        public string Auth_Status { get; set; }
        public string Checker_ID { get; set; }
        public Nullable<System.DateTime> Approve_DT { get; set; }
    }
}


text:
(function(draw_simulator, $) {
  var deck = null, initial_size = 0, draw_count = 0, container = null;

  draw_simulator.reset = function() {
    if(container) container.empty();
    deck = null;
    initial_size = draw_count = 0;
    update_odds();
    check_draw_type();
    $('#draw-simulator-clear').attr('disabled', true);
  };
  draw_simulator.init = function() {
    container = $('#table-draw-simulator-content');
    deck = [];
    check_draw_type();
    NRDB.data.cards.find({indeck:{'$gt':0},type_code:{'$ne':'identity'}}).forEach(function (card) {
      for(var ex = 0; ex < card.indeck; ex++) {
        deck.push(card);
      }
    });
    initial_size = deck.length;
  };

  function update_odds() {
    for(var i=1; i<=3; i++) {
      var odd = hypergeometric.get_cumul(1, initial_size, i, draw_count);
      $('#draw-simulator-odds-'+i).text(Math.round(100*odd));
    }
  }

  function check_draw_type() {
    identity = NRDB.data.cards.find({indeck:{'$gt':0},type_code:{'$eq':'identity'}}).pop();
    var special_button = $("#draw-simulator-special");
    var special_draw = false;
    switch (identity.code) {
      case "02083":
        special_draw = true;
        special_button.attr("data-draw-type", "andy");
        break;
      case "07029": // MaxX
        special_draw = true;
        special_button.attr("data-draw-type", "maxx");
        break;
      default:
        special_button.hide();
    }
    if (special_draw) {
      special_button.text(identity.title.split(":")[0]).attr("disabled",false).show();
    }
  }

  function do_draw(draw, draw_type) {
    for(var pick = 0; pick < draw && deck.length > 0; pick++) {
      var rand = Math.floor(Math.random() * deck.length);
      var spliced = deck.splice(rand, 1);
      var card = spliced[0];
      var card_element;
      if(card.imageUrl) {
        card_element = $('');
      } else {
        card_element = $('

'+card.title+'

');
      }
      switch (draw_type) {
        case "maxx":
          if ((pick + 1) % 3 != 0) {
            card_element.addClass("trashed");
          }
          break;
      }
      if ($("#draw-simulator-special").attr("data-draw-type") == "andy") {
        $("#draw-simulator-special").attr("disabled",true);
      }
      container.append(card_element);
      draw_count++;
    }
    update_odds();
  }

  draw_simulator.handle_click = function(event) {

    event.preventDefault();
    var draw_type = false;
    var id = $(this).attr('id');
    var command = id.substr(15);
    $('#draw-simulator-clear').attr('disabled', false);
    if(command === 'clear') {
      draw_simulator.reset();
      return;
    }
    if(event.shiftKey) {
      draw_simulator.reset();
    }
    if(deck === null) {
      draw_simulator.init();
    }
    var draw;
    if(command === 'all') {
      draw = deck.length;
    } else if(command === 'special') {
      draw_type = $(this).attr('data-draw-type');
      switch (draw_type) {
        case "maxx":
          draw = 3;
          break;
        case "andy":
          draw = 9;
          $(this).attr("disabled", true);
          break;
      }
    } else {
      draw = parseInt(command, 10);
    }
    if(isNaN(draw)) return;
    do_draw(draw, draw_type);

  };

  draw_simulator.toggle_opacity = function(event) {
    $(this).css('opacity', 1.5 - parseFloat($(this).css('opacity')));
  };

  $(function () {
    $('#table-draw-simulator').on({click: draw_simulator.handle_click}, 'button.btn');
    $('#table-draw-simulator').on({click: draw_simulator.toggle_opacity}, 'img.card-image, div.card-proxy');
  });
})(NRDB.draw_simulator = {}, jQuery);


text:
package com.badlogic.gdx.physics.box2d;

import com.badlogic.gdx.math.Vector2;

/**
 * Callback class for ray casts.
 * @see World#rayCast(RayCastCallback, Vector2, Vector2)
 * @author mzechner
 *
 */

public interface RayCastCallback {

	/** Called for each fixture found in the query. You control how the ray cast
		 proceeds by returning a float:
		 return -1: ignore this fixture and continue
		 return 0: terminate the ray cast
		 return fraction: clip the ray to this point
		 return 1: don't clip the ray and continue
		 @param fixture the fixture hit by the ray
		 @param point the point of initial intersection
		 @param normal the normal vector at the point of intersection
		 @return -1 to filter, 0 to terminate, fraction to clip the ray for
		 closest hit, 1 to continue
	 **/
	public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction);
}


text: require 'gov_kit'


text:
$(function() {
    "use strict";

    // Obtener los elementos del DOM
    var content = $('#content');
    var input = document.getElementById('input');
    var span = document.getElementById('status');
    var countMessage = 0;

    // Mi color asignado por el servidor
    var myColor = false;
    // Mi nick
    var myName = false;

    // Comprobar la disponibilidad de Web Socket en el navegador

    if (!Modernizr.websockets) {
        return false;
    }

    window.WebSocket = window.WebSocket || window.MozWebSocket;

    // Abrir la conexion con ws://www.arkaitzgarro.com:1337
    // 1. Al abrir la conexión, solicitar el nick.
    var socket = new WebSocket('ws://www.arkaitzgarro.com:1337');
    console.log(socket);
    // 2. Controlar posibles errores del servidor.
    var openMessage = function(e) {
        if (this.readyState === 1) {
            input.disabled = false;

        }
        console.log("Welcome - status " + this.readyState);
    };
    var errorMessage = function(e) {

        console.log("error message " + this.readyState);
    };
    var closeMessage = function(e) {

        console.log("Disconnected - status " + this.readyState);
    };
    socket.addEventListener('open', openMessage, false);
    socket.addEventListener('error', errorMessage, false);
    socket.addEventListener('close', closeMessage, false);

    // socket.onopen  = function(e){ log("Welcome - status "+this.readyState); };
    // socket.onclose = function(e){ log("Disconnected - status "+this.readyState); };
    // 3. Escucar los mensajes del servidor, y mostrarlos en el elemento "content"
    console.log(myColor);

    socket.onmessage = function(event) {
        var info;
        try {
            info = JSON.parse(event.data);
            console.log(info);
        } catch (ex) {
            console.log("error with json message." + e.data);
        }
        if (info) {
            switch (info.type) {
                case "color":
                    console.log("color: " + info);
                    myColor = info.data;
                    span.style.color = myColor;
                    span.innerText=myName+":";
                    break;

                case "history":
                    console.log("history: " + info);
                    for (var i = info.data.length - 1; i >= 0; i--) {
                        addMessage(info.data[i].author, info.data[i].text, info.data[i].color, new Date(info.data[i].time));
                    }
                    break;
                default:
                    console.log("message: " + info);
                    addMessage(info.data.author, info.data.text, info.data.color, new Date(info.data.time));
                    break;
            }
        }

        // if (data.action == 'joined') {
        //     initiliseChat();
        // } else {
        //     showNewMessage(data.who, data.text);
        // }
    };
    // 4. La estructura del objeto enviado por el servidor es la siguiente:
    //      {

    //          // Contiene el tipo de mensaje recibido
    //          type : @string in ['color', 'history', 'message'],
    //          // Contiene los datos según el tipo de mensaje recibido
    //          data: @Object {author, text, color, time}
    //      }
    // 5. Enviar un mensaje al pulsar enter. El mensaje enviado es únicamente la cadena de caracteres.

    var sendMessage = function(e) {
        if (e.keyCode === 13) {
            var inputMessage = input.value;

            if (inputMessage) {
                if (!myName) {
                    myName = inputMessage;
                }
                socket.send(inputMessage);
                console.log(inputMessage);
                input.value = "";
            }

        }
    };
    input.addEventListener('keydown', sendMessage, false);

    /**
     * Añadir el mensaje a la ventana de chat
     */
    function addMessage(author, message, color, dt) {
        content.prepend('
' + author + ' @ ' + (dt.getHours() < 10 ? '0' + dt.getHours() : dt.getHours()) + ':' + (dt.getMinutes() < 10 ? '0' + dt.getMinutes() : dt.getMinutes()) + ': ' + message + '
');
    }
});


text:
angular.module('gs.services',[])
.factory("StoriesResouce", function($resource) {
  return $resource("http://www.reddit.com/r/:subreddit/.json?limit=:limit");
})
.factory("CommentResource", function($resource) {
  return $resource("http://www.reddit.com/r/:subreddit/comments/:permalink/:story/.json?limit=:limit");
})
.factory("CommentService", function() {
	//Use this to pass data between views / controllers
	//Service variables will persist
	var commentURL = '';
	var storyTitle = '';

	return {
		setCommentURL:function (data) {
			commentURL =  data;
			//console.log(data);
		},
		getCommentURL:function () {
			return commentURL;
		},
		setStoryTitle:function (data) {
			storyTitle =  data;
			//console.log(data);
		},
		getStoryTitle:function () {
			return storyTitle;
		}
	};

});


text:
An utility to properly create a bundle for Cocoa applications.

It uses `otool` application to analyze needed dependencies
from the application itself and its dependencies recursively.

It will copy all needed files to `bundle/Frameworks` folder
and change needed links using `install_name_tool -change` command.


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Text.RegularExpressions;
using Mono.Options;
using ReferenceChecker.Gac;

namespace ReferenceChecker
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            var directory = string.Empty;
            var verbose = false;
            var help = false;
            var output = string.Empty;
            var exceptions = string.Empty;
            var assembliesToIgnore = string.Empty;
            var expectedRoots = string.Empty;
            var dontCheckAssemblyVersion = false;

            var options = new OptionSet
                {
                    {"d|directory=","The directory to check runtime dependencies for.", v => directory = v},
                    {"v|verbose", "Verbose logging",v => verbose = v != null},
                    {"n|noassemblyversioncheck", "Don't check the assembly version when checking existence.",v => dontCheckAssemblyVersion = v != null},
                    {"h|?|help", "Show help.", v => help = v != null},
                    {"o|output=","File to output DGML graph of references to.", v => output = v},
                    {"e|exceptions=", "A semi-colon delimited list of exclusions (accepts wildcards)",v => exceptions = v},
                    {"i|ignore=","List of wildards matching assemblies to ignore when graphing", v => assembliesToIgnore = v},
                    {"r|roots=", "A semi-colon delimited list of expected roots.",v => expectedRoots = v},
                };

            var extra = options.Parse(args);

            if (extra.Any() || help)
            {
                OutputHelpAndExit(options);
            }

            if (!Directory.Exists(directory))
            {
                Console.WriteLine("Directory does not exist.");
                OutputHelpAndExit(options);
            }
            if (string.IsNullOrEmpty(directory))
            {
                Console.WriteLine("Please provide a directory.");
                OutputHelpAndExit(options);
            }

            var exclusions = WildcardListFromString(exceptions);
            var ignoreWildcards = WildcardListFromString(assembliesToIgnore);
            var rootsList = expectedRoots.Split(';').Where(r => !string.IsNullOrEmpty(r)).ToList();

            var files = new ConcurrentBag<string>(Directory.GetFiles(directory, "*.dll").Concat(Directory.GetFiles(directory, "*.exe")));

            var grapher = new AssemblyReferenceGrapher(new FileSystem(), new GacResolver());
            var graph = grapher.GenerateAssemblyReferenceGraph(exclusions, ignoreWildcards, files, verbose, !dontCheckAssemblyVersion);

            var roots = graph.Vertices.Where(v => graph.InDegree(v) == 0).ToList();
            var missingButExcluded = graph.Vertices.Where(m => m.Excluded && !m.Exists);
            var failures = graph.Vertices.Where(m => !m.Exists && !m.Excluded);

            OutputList(roots, "Roots...", a => a.AssemblyName.FullName, a => a.AssemblyName.ToString());
            OutputList(missingButExcluded, "Missing but excluded...", a => a.AssemblyName.FullName, a => a.AssemblyName.ToString());
            var exitCode = OutputList(failures, "Missing...", a => a.AssemblyName.FullName, a => a.AssemblyName.ToString());

            if (rootsList.Any())
            {
                var missingRoots = rootsList.Where(er => !roots.Any(r => r.AssemblyName.Name.Equals(er,StringComparison.OrdinalIgnoreCase))).ToList();
                var additionalRoots = roots.Where(r => !rootsList.Any(er => er.Equals(r.AssemblyName.Name, StringComparison.OrdinalIgnoreCase))).ToList();
                exitCode = exitCode + OutputList(missingRoots, "Missing Roots...", a => a, a => a);
                exitCode = exitCode + OutputList(additionalRoots, "Additonal Roots...", a => a.AssemblyName.FullName, a => a.AssemblyName.ToString());
            }

            if (!string.IsNullOrEmpty(output))
            {
                AssemblyReferenceGrapher.OutputToDgml(output, graph);
            }

            Environment.Exit(exitCode);
        }

        private static int OutputList<T>(IEnumerable<T> list, string heading, Func<T,string> orderBy, Func<T,string> outputString)
        {
            var returnCode = 0;
            var assemblyVertices = list as T[] ?? list.ToArray();
            if (assemblyVertices.Any())
            {
                Console.WriteLine();
                Console.WriteLine(heading);
                assemblyVertices.OrderByDescending(orderBy).ToList().ForEach(m => Console.WriteLine("\t" + outputString(m)));
                returnCode = assemblyVertices.Count();
            }
            return returnCode;
        }

        private static IEnumerable<Regex> WildcardListFromString(string exceptions)
        {
            if (string.IsNullOrEmpty(exceptions))
                return new List<Regex>();
            var wildcards = exceptions.Split(';').Select(s => s.ToLowerInvariant());
            return new List<Regex>(wildcards.Select(w => new Wildcard(w)));
        }

        private static void OutputHelpAndExit(OptionSet options)
        {
            options.WriteOptionDescriptions(Console.Out);
            Environment.Exit(1);
        }
    }
}


text:
var assert = require('assert');
var Rpc = require('..');
var VirtualLink = require('node-network/test/links/VirtualLink');

describe('RouteTable Functions', function() {
	describe('request', function() {

		var node1, node2;

		// Set up
		before(function(done){
			node1 = Rpc({
				dnsDb: {
					public: true,
					apiPath: '/api/dns'
				},
				dnsClient: {},
				network: {
					address: 'node1'
				}
			});

			node1.dnsClient._id = 'node1';
			node1.dnsClient._dnsDb._id = 'node1';

			node2 = Rpc({
				dnsClient: {
					dnsServer: 'node1'
				}
			});

			node2.dnsClient._id = 'node2';
			node2.dnsClient._dnsDb._id = 'node2';

			var link_1_2 = VirtualLink();

			node1.addConnection(link_1_2.connection1);
			node2.addConnection(link_1_2.connection2);

			link_1_2.connection1.connect();
			link_1_2.connection2.connect();

			node2.on('connect', function() {
				done();
			});

		});

		it('Insert route into route table', function(done) {

			node1.dnsClient.addToGroup(node1.address, 'mygroup', function(error, result) {

			});

			node1.router.use(function(request, respond, next) {
				respond(null, 'ok');
			});

			node2.request('mygroup', '/test', {}, {groupSubscribe: true}, function(error, response) {

				setTimeout(function() {

					node2.dnsClient.addToGroup(node2.address, 'mygroup', function(error, result) {

						console.log(node2.dnsDb.groupAddresses('mygroup', function(error, addresses) {
							console.log(node1.dnsDb == node2.dnsDb);
							console.log(error, addresses);
						}));
						console.log("ADDED-2", error, result);
					});

				}, 1000);

				//console.log(error, response);
				/*
				if(error)
					throw new Error(error);
				else if(response == 'ok')
					done();
				else
					throw new Error('wrong response');
				*/
			});
		});
	});

});


text:
(function() {
    'use strict';

    angular
        .module('gatewayApp')
        .controller('UserManagementDialogController',UserManagementDialogController);

    UserManagementDialogController.$inject = ['$stateParams', '$uibModalInstance', 'entity', 'User', 'JhiLanguageService'];

    function UserManagementDialogController ($stateParams, $uibModalInstance, entity, User, JhiLanguageService) {
        var vm = this;

        vm.authorities = ['ROLE_USER', 'ROLE_ADMIN'];
        vm.clear = clear;
        vm.languages = null;
        vm.save = save;
        vm.user = entity;

        JhiLanguageService.getAll().then(function (languages) {
            vm.languages = languages;
        });

        function clear () {
            $uibModalInstance.dismiss('cancel');
        }

        function onSaveSuccess (result) {
            vm.isSaving = false;
            $uibModalInstance.close(result);
        }

        function onSaveError () {
            vm.isSaving = false;
        }

        function save () {
            vm.isSaving = true;
            if (vm.user.id !== null) {
                User.update(vm.user, onSaveSuccess, onSaveError);
            } else {
                User.save(vm.user, onSaveSuccess, onSaveError);
            }
        }
    }
})();