<commit_before>/*
 * Changes to this file committed after and not including commit-id: ccc0d2c5f9a5ac661e60e6eaf138de7889928b8b
 * are released under the following license:
 *
 * This file is part of Hopsworks
 * Copyright (C) 2018, Logical Clocks AB. All rights reserved
 *
 * Hopsworks is free software: you can redistribute it and/or modify it under the terms of
 * the GNU Affero General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * Hopsworks 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with this program.
 * If not, see <https://www.gnu.org/licenses/>.
 *
 * Changes to this file committed before and including commit-id: ccc0d2c5f9a5ac661e60e6eaf138de7889928b8b
 * are released under the following license:
 *
 * Copyright (C) 2013 - 2018, Logical Clocks AB and RISE SICS AB. All rights reserved
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
 * software and associated documentation files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software, and to permit
 * persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR  OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

'use strict';

angular.module('hopsWorksApp')
        .factory('TourService', ['$timeout',
            function ($timeout) {

                var tourService = this;

                tourService.kafkaSchemaName = "DemoAvroSchema";
                tourService.kafkaTopicName = "DemoKafkaTopic";
                tourService.kafkaProjectPrefix = "demo_kafka";
                tourService.sparkProjectPrefix = "demo_spark";
                tourService.deepLearningProjectPrefix = "demo_deep_learning";
                tourService.featurestoreProjectPrefix = "demo_featurestore";
                tourService.featurestoreTourJobName = "featurestore_tour_job";
                tourService.deepLearningRunTip = "";
                tourService.informAndTips = true;
                tourService.tipsOnly = false;
                tourService.informOnly = false;
                tourService.showNothing = false;
                tourService.currentProjectName = '';

                tourService.toursInfoStep = 0;
                tourService.currentStep_TourOne = -1;
                tourService.currentStep_TourTwo = -1;
                tourService.currentStep_TourThree = -1;
                tourService.currentStep_TourFour = -1;
                tourService.currentStep_TourFive = -1;
                tourService.currentStep_TourSix = -1;
                tourService.currentStep_TourSeven = -1;
                tourService.currentStep_TourEight = -1;
                tourService.currentStep_TourNine = -1;
                tourService.alive_TourOne = 15;
                tourService.createdJobName = null;
                tourService.activeTour = null;
                tourService.kafkaJobCreationState = "producer";
                tourService.counter = 0;

                tourService.getDeepLearningJobTip = function(){
                  if(tourService.activeTour === "deep_learning"){
                    tourService.deepLearningRunTip = "An inference job was created for you! Go on and run it after the model is finished.";
                  }
                  return tourService.deepLearningRunTip;
                };

                tourService.setActiveTour = function (tourName) {
                    tourService.activeTour = tourName;
                };

                tourService.setInformAndTipsState = function () {
                  tourService.informAndTips = true;
                  tourService.tipsOnly = false;
                  tourService.informOnly = false;
                  tourService.showNothing = false;
                };

                tourService.setTipsOnlyState = function () {
                  tourService.informAndTips = false;
                  tourService.tipsOnly = true;
                  tourService.informOnly = false;
                  tourService.showNothing = false;
                };

                tourService.setInformOnly = function () {
                  tourService.informAndTips = false;
                  tourService.tipsOnly = false;
                  tourService.informOnly = true;
                  tourService.showNothing = false;
                };

                tourService.setShowNothingState = function () {
                  tourService.informAndTips = false;
                  tourService.tipsOnly = false;
                  tourService.informOnly = false;
                  tourService.showNothing = true;
                };

                tourService.setDefaultTourState = function () {
                  tourService.informAndTips = true;
                  tourService.tipsOnly = false;
                  tourService.informOnly = false;
                  tourService.showNothing = false;
                };

                tourService.printDebug = function () {
                  console.log("Counter: " + tourService.counter);
                  tourService.counter++;
                  console.log(">> kafka state: " + tourService
                  .kafkaJobCreationState);
                  console.log(">> TourSix: " + tourService.currentStep_TourSix);
                  console.log(">> TourSeven: " + tourService
                  .currentStep_TourSeven);

                  return true;
                };

                tourService.getKafkaGuideJarPath = function (projectName, filename) {
                  return "hdfs:///Projects/" + projectName +
                   "/TestJob/" + filename;
                };

                tourService.resetTours = function () {

                    tourService.toursInfoStep = 0;
                    tourService.currentStep_TourOne = -1;
                    tourService.alive_TourOne = 15;
                    tourService.currentStep_TourTwo = -1;
                    tourService.currentStep_TourThree = -1;
                    tourService.currentStep_TourFour = -1;
                    tourService.currentStep_TourFive = -1;
                    tourService.currentStep_TourSix = -1;
                    tourService.currentStep_TourSeven = -1;
                    tourService.currentStep_TourEight = -1;
                    tourService.currentStep_TourNine = -1;
                    tourService.createdJobName = null;
                };

                tourService.KillTourOneSoon = function ()
                {
                    $timeout(function () {
                        tourService.alive_TourOne--;
                    }, 1000).then(function () {
                        if (tourService.alive_TourOne === 0)
                        {
                            tourService.currentStep_TourOne = -1;
                            tourService.alive_TourOne = 15;
                        } else
                        {
                            tourService.KillTourOneSoon();
                        }
                    });
                };
                return tourService;
            }
        ]);
<commit_msg>[HOPSWORKS-1014] append  - Fix kafka tour jar path (#243)<commit_after>/*
 * Changes to this file committed after and not including commit-id: ccc0d2c5f9a5ac661e60e6eaf138de7889928b8b
 * are released under the following license:
 *
 * This file is part of Hopsworks
 * Copyright (C) 2018, Logical Clocks AB. All rights reserved
 *
 * Hopsworks is free software: you can redistribute it and/or modify it under the terms of
 * the GNU Affero General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * Hopsworks 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with this program.
 * If not, see <https://www.gnu.org/licenses/>.
 *
 * Changes to this file committed before and including commit-id: ccc0d2c5f9a5ac661e60e6eaf138de7889928b8b
 * are released under the following license:
 *
 * Copyright (C) 2013 - 2018, Logical Clocks AB and RISE SICS AB. All rights reserved
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
 * software and associated documentation files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software, and to permit
 * persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR  OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

'use strict';

angular.module('hopsWorksApp')
        .factory('TourService', ['$timeout',
            function ($timeout) {

                var tourService = this;

                tourService.kafkaSchemaName = "DemoAvroSchema";
                tourService.kafkaTopicName = "DemoKafkaTopic";
                tourService.kafkaProjectPrefix = "demo_kafka";
                tourService.sparkProjectPrefix = "demo_spark";
                tourService.deepLearningProjectPrefix = "demo_deep_learning";
                tourService.featurestoreProjectPrefix = "demo_featurestore";
                tourService.featurestoreTourJobName = "featurestore_tour_job";
                tourService.deepLearningRunTip = "";
                tourService.informAndTips = true;
                tourService.tipsOnly = false;
                tourService.informOnly = false;
                tourService.showNothing = false;
                tourService.currentProjectName = '';

                tourService.toursInfoStep = 0;
                tourService.currentStep_TourOne = -1;
                tourService.currentStep_TourTwo = -1;
                tourService.currentStep_TourThree = -1;
                tourService.currentStep_TourFour = -1;
                tourService.currentStep_TourFive = -1;
                tourService.currentStep_TourSix = -1;
                tourService.currentStep_TourSeven = -1;
                tourService.currentStep_TourEight = -1;
                tourService.currentStep_TourNine = -1;
                tourService.alive_TourOne = 15;
                tourService.createdJobName = null;
                tourService.activeTour = null;
                tourService.kafkaJobCreationState = "producer";
                tourService.counter = 0;

                tourService.getDeepLearningJobTip = function(){
                  if(tourService.activeTour === "deep_learning"){
                    tourService.deepLearningRunTip = "An inference job was created for you! Go on and run it after the model is finished.";
                  }
                  return tourService.deepLearningRunTip;
                };

                tourService.setActiveTour = function (tourName) {
                    tourService.activeTour = tourName;
                };

                tourService.setInformAndTipsState = function () {
                  tourService.informAndTips = true;
                  tourService.tipsOnly = false;
                  tourService.informOnly = false;
                  tourService.showNothing = false;
                };

                tourService.setTipsOnlyState = function () {
                  tourService.informAndTips = false;
                  tourService.tipsOnly = true;
                  tourService.informOnly = false;
                  tourService.showNothing = false;
                };

                tourService.setInformOnly = function () {
                  tourService.informAndTips = false;
                  tourService.tipsOnly = false;
                  tourService.informOnly = true;
                  tourService.showNothing = false;
                };

                tourService.setShowNothingState = function () {
                  tourService.informAndTips = false;
                  tourService.tipsOnly = false;
                  tourService.informOnly = false;
                  tourService.showNothing = true;
                };

                tourService.setDefaultTourState = function () {
                  tourService.informAndTips = true;
                  tourService.tipsOnly = false;
                  tourService.informOnly = false;
                  tourService.showNothing = false;
                };

                tourService.printDebug = function () {
                  console.log("Counter: " + tourService.counter);
                  tourService.counter++;
                  console.log(">> kafka state: " + tourService
                  .kafkaJobCreationState);
                  console.log(">> TourSix: " + tourService.currentStep_TourSix);
                  console.log(">> TourSeven: " + tourService
                  .currentStep_TourSeven);

                  return true;
                };

                tourService.getKafkaGuideJarPath = function (projectName, filename) {
                  return "Projects/" + projectName + "/TestJob/" + filename;
                };

                tourService.resetTours = function () {

                    tourService.toursInfoStep = 0;
                    tourService.currentStep_TourOne = -1;
                    tourService.alive_TourOne = 15;
                    tourService.currentStep_TourTwo = -1;
                    tourService.currentStep_TourThree = -1;
                    tourService.currentStep_TourFour = -1;
                    tourService.currentStep_TourFive = -1;
                    tourService.currentStep_TourSix = -1;
                    tourService.currentStep_TourSeven = -1;
                    tourService.currentStep_TourEight = -1;
                    tourService.currentStep_TourNine = -1;
                    tourService.createdJobName = null;
                };

                tourService.KillTourOneSoon = function ()
                {
                    $timeout(function () {
                        tourService.alive_TourOne--;
                    }, 1000).then(function () {
                        if (tourService.alive_TourOne === 0)
                        {
                            tourService.currentStep_TourOne = -1;
                            tourService.alive_TourOne = 15;
                        } else
                        {
                            tourService.KillTourOneSoon();
                        }
                    });
                };
                return tourService;
            }
        ]);
<|endoftext|>


<commit_before>import { typeOf } from '../arithmetic/base';
import { affineTransformations } from './types';

const V = affineTransformations;

const modZ = q => V.minus(q, V.floor(q));

const checkInteger = x => {
  if (!V.isInteger(x))
    throw new Error(`expected an integer, got ${x}`);
};

const checkShiftCoordinate = x => {
  if (!V.isRational(x))
    throw new Error(`expected a rational number, got ${x}`);
  if (!V.eq(x, modZ(x)))
    throw new Error(`expected a number in [0,1), got ${x}`);
};

const checkLinearPartOfOperator = (M, d) => {
  const [n, m] = V.shape(M);

  if (n != d || m != d)
    throw new Error(`expected a ${d}x${d} matrix, got ${M}`);

  M.forEach(row => row.forEach(checkInteger));

  const det = V.determinant(M);

  if (V.abs(det) != 1)
    throw new Error(
      `expected a unimodular matrix, got ${M} with determinant ${det}`
    );
};

const checkTranslationalPartOfOperator = (s, d) => {
  if (s.length != d)
    throw new Error(`expected a ${d}-dimensional vector, got ${s}`);

  s.forEach(checkShiftCoordinate);
};

const checkOperatorType = op => {
  const t = typeOf(op);

  if (t != 'Matrix' && t != 'AffineTransformation')
    throw new Error(`expected a Matrix or AffineTransformation, got ${op}`);
};

const checkOperator = (op, d) => {
  checkOperatorType(op);

  if (typeOf(op) == 'Matrix')
    checkLinearPartOfOperator(op, d);
  else {
    checkLinearPartOfOperator(op.linear, d);
    checkTranslationalPartOfOperator(op.shift, d);
  }
};

const operatorDimension = op =>
  (typeOf(op) == 'Matrix' ? op : op.linear).length;

const checkOperatorList = ops => {
  if (!ops.length)
    return;

  ops.forEach(checkOperatorType);

  const d = operatorDimension(ops[0]);
  ops.forEach(op => checkOperator(op, d));
};

const opModZ = op => {
  if (typeOf(op) == 'Matrix')
    return op;
  else
    return V.affineTransformation(op.linear, op.shift.map(modZ));
};

const fullOperatorList = gens => {
  const seen = {};
  gens.forEach(g => seen[g] = true);

  const ops = gens.slice();

  for (let i = 0; i < ops.length; ++i) {
    const A = ops[i];
    gens.forEach(B => {
      const AB = opModZ(V.times(A, V.inverse(B)));
      if (!seen[AB]) {
        ops.push(AB);
        seen[AB] = true;
      }
    });
  }

  return ops;
};

const checkGroup = ops => {
  const seen = {};
  ops.forEach(op => seen[op] = true);

  ops.forEach(A => {
    ops.forEach(B => {
      if (!seen[opModZ(V.times(A, V.inverse(B)))])
        throw new Error('operators do not form a group');
    })
  });
};

if (require.main == module) {
  Array.prototype.toString = function() {
    return '[ ' + this.map(x => x.toString()).join(', ') + ' ]';
  };

  const check = (op, d) => {
    try {
      if (d == null) {
        checkOperatorList(op);
        checkGroup(op);
        console.log(`Operator list ${op} is okay`);
      }
      else {
        checkOperator(op, d);
        console.log(`Operator ${op} is okay`);
      }
    } catch(ex) {
      console.log(ex);
    }
  };

  const M = [[1,1,0],[0,1,5],[0,0,-1]];

  check(M, 3);
  check(V.affineTransformation(M, V.div([1,2,3], 3)), 3);

  check([1,1,0], 3);
  check([[1,1,0],[0,1,5]], 3);
  check([[1,1,0],[0,1,5],[0,0.2,1]], 3);
  check([[1,1,0],[0,1,5],[0,0,-2]], 3);
  check(V.affineTransformation(M, [V.div(5,3),0,1]), 3);

  check([ [[1,1],[3,4]], [[1,0],[1,1],[1,3]] ]);
  const ops = [
    [[-1,0],[0,1]],
    V.affineTransformation([[1,0],[0,1]], V.div([1,1], 2))
  ];
  check(ops);
  check(fullOperatorList(ops));
}
<commit_msg>add primitive cell computation for spacegroups<commit_after>import { typeOf } from '../arithmetic/base';
import { rationalMethods, rationals } from '../arithmetic/types';
import * as mats from '../arithmetic/matrices';

import { affineTransformations } from './types';

const X = rationalMethods.register(
  mats.methods(rationals, ['Integer', 'LongInt', 'Fraction'], false)
).ops();

const V = affineTransformations;

const modZ = q => V.minus(q, V.floor(q));

const isIdentity = M => {
  for (let i = 0; i < M.length; ++i) {
    const row = M[i];
    for (let j = 0; j < row.length; ++j) {
      if (V.ne(row[j], 0 + (i == j)))
        return false;
    }
  }

  return true;
};

const checkInteger = x => {
  if (!V.isInteger(x))
    throw new Error(`expected an integer, got ${x}`);
};

const checkShiftCoordinate = x => {
  if (!V.isRational(x))
    throw new Error(`expected a rational number, got ${x}`);
  if (!V.eq(x, modZ(x)))
    throw new Error(`expected a number in [0,1), got ${x}`);
};

const checkLinearPartOfOperator = (M, d) => {
  const [n, m] = V.shape(M);

  if (n != d || m != d)
    throw new Error(`expected a ${d}x${d} matrix, got ${M}`);

  M.forEach(row => row.forEach(checkInteger));

  const det = V.determinant(M);

  if (V.abs(det) != 1)
    throw new Error(
      `expected a unimodular matrix, got ${M} with determinant ${det}`
    );
};

const checkTranslationalPartOfOperator = (s, d) => {
  if (s.length != d)
    throw new Error(`expected a ${d}-dimensional vector, got ${s}`);

  s.forEach(checkShiftCoordinate);
};

const checkOperatorType = op => {
  const t = typeOf(op);

  if (t != 'Matrix' && t != 'AffineTransformation')
    throw new Error(`expected a Matrix or AffineTransformation, got ${op}`);
};

const checkOperator = (op, d) => {
  checkOperatorType(op);

  if (typeOf(op) == 'Matrix')
    checkLinearPartOfOperator(op, d);
  else {
    checkLinearPartOfOperator(op.linear, d);
    checkTranslationalPartOfOperator(op.shift, d);
  }
};

const operatorDimension = op =>
  (typeOf(op) == 'Matrix' ? op : op.linear).length;

const checkOperatorList = ops => {
  if (!ops.length)
    return;

  ops.forEach(checkOperatorType);

  const d = operatorDimension(ops[0]);
  ops.forEach(op => checkOperator(op, d));
};

const opModZ = op => {
  if (typeOf(op) == 'Matrix')
    return op;
  else
    return V.affineTransformation(op.linear, op.shift.map(modZ));
};

const fullOperatorList = gens => {
  const seen = {};
  gens.forEach(g => seen[g] = true);

  const ops = gens.slice();

  for (let i = 0; i < ops.length; ++i) {
    const A = ops[i];
    gens.forEach(B => {
      const AB = opModZ(V.times(A, V.inverse(B)));
      if (!seen[AB]) {
        ops.push(AB);
        seen[AB] = true;
      }
    });
  }

  return ops;
};

const checkGroup = ops => {
  const seen = {};
  ops.forEach(op => seen[op] = true);

  ops.forEach(A => {
    ops.forEach(B => {
      if (!seen[opModZ(V.times(A, V.inverse(B)))])
        throw new Error('operators do not form a group');
    })
  });
};

const primitiveCell = ops => {
  const d  = operatorDimension(ops[0]);
  const vs = ops
    .filter(op => typeOf(op) == 'AffineTransformation')
    .filter(op => isIdentity(op.linear))
    .map(op => op.shift);

  const B = V.identityMatrix(d).concat(vs);

  return X.triangulation(B).R.slice(0, d);
};

if (require.main == module) {
  Array.prototype.toString = function() {
    return '[ ' + this.map(x => x.toString()).join(', ') + ' ]';
  };

  const check = (op, d) => {
    try {
      if (d == null) {
        checkOperatorList(op);
        checkGroup(op);
        console.log(`Operator list ${op} is okay`);
      }
      else {
        checkOperator(op, d);
        console.log(`Operator ${op} is okay`);
      }
    } catch(ex) {
      console.log(ex);
    }
  };

  const M = [[1,1,0],[0,1,5],[0,0,-1]];

  check(M, 3);
  check(V.affineTransformation(M, V.div([1,2,3], 3)), 3);

  check([1,1,0], 3);
  check([[1,1,0],[0,1,5]], 3);
  check([[1,1,0],[0,1,5],[0,0.2,1]], 3);
  check([[1,1,0],[0,1,5],[0,0,-2]], 3);
  check(V.affineTransformation(M, [V.div(5,3),0,1]), 3);

  check([ [[1,1],[3,4]], [[1,0],[1,1],[1,3]] ]);
  const ops = [
    [[-1,0],[0,1]],
    V.affineTransformation([[1,0],[0,1]], V.div([1,1], 2))
  ];
  check(ops);
  check(fullOperatorList(ops));

  console.log(isIdentity([[1,0,0],[0,1,0],[0,0,1]]));
  console.log(isIdentity([[1,0,0],[0,1,-1],[0,0,1]]));
  console.log(`${primitiveCell(fullOperatorList(ops))}`);
}
<|endoftext|>


<commit_before>'use strict';

Chart.defaults.global.defaultFontSize = 8;
Chart.defaults.global.animation.duration = 500;
Chart.defaults.global.legend.display = false;
Chart.defaults.global.elements.line.backgroundColor = "rgba(0,0,0,0)";
Chart.defaults.global.elements.line.borderColor = "rgba(0,0,0,0.9)";
Chart.defaults.global.elements.line.borderWidth = 2;

var socket = io(location.protocol + '//' + location.hostname + ':' + location.port);
var defaultSpan = 0;
var spans = [];

var defaultDataset = {
  label: '',
  data: [],
  lineTension: 0.2,
  pointRadius: 0
};

var defaultOptions = {
  scales: {
    yAxes: [{
      ticks: {
        beginAtZero: true
      }
    }],
    xAxes: [{
      type: 'time',
      time: {
        unitStepSize: 30
      },
      gridLines: {
        display: false
      }
    }]
  },
  tooltips: {
    enabled: false
  },
  responsive: true,
  maintainAspectRatio: false,
  animation: false
};

var createChart = function (ctx, dataset) {
  return new Chart(ctx, {
    type: 'line',
    data: {
      labels: [],
      datasets: dataset
    },
    options: defaultOptions
  });
};

var addTimestamp = function(point) {
  return point.timestamp;
};

var cpuDataset = [Object.create(defaultDataset)];
var memDataset = [Object.create(defaultDataset)];
var loadDataset = [Object.create(defaultDataset)];
var responseTimeDataset = [Object.create(defaultDataset)];
var rpsDataset = [Object.create(defaultDataset)];

var cpuStat = document.getElementById('cpuStat');
var memStat = document.getElementById('memStat');
var loadStat = document.getElementById('loadStat');
var responseTimeStat = document.getElementById('responseTimeStat');
var rpsStat = document.getElementById('rpsStat');

var cpuChartCtx = document.getElementById("cpuChart");
var memChartCtx = document.getElementById("memChart");
var loadChartCtx = document.getElementById("loadChart");
var responseTimeChartCtx = document.getElementById("responseTimeChart");
var rpsChartCtx = document.getElementById("rpsChart");

var cpuChart = createChart(cpuChartCtx, cpuDataset);
var memChart = createChart(memChartCtx, memDataset);
var loadChart = createChart(loadChartCtx, loadDataset);
var responseTimeChart = createChart(responseTimeChartCtx, responseTimeDataset);
var rpsChart = createChart(rpsChartCtx, rpsDataset);

var charts = [cpuChart, memChart, loadChart, responseTimeChart, rpsChart];

var onSpanChange = function (e) {
  e.target.classList.add('active');
  defaultSpan = parseInt(e.target.id);

  var otherSpans = document.getElementsByTagName('span');
  for (var i = 0; i < otherSpans.length; i++) {
    if (otherSpans[i] !== e.target) otherSpans[i].classList.remove('active');
  }

  socket.emit('change');
};

socket.on('start', function (data) {
  // Remove last element of Array because it contains malformed responses data.
  // To keep consistency we also remove os data.
  data[defaultSpan].responses.pop();
  data[defaultSpan].os.pop();

  cpuStat.textContent = data[defaultSpan].os[data[defaultSpan].os.length - 1].cpu.toFixed(1) + '%';
  cpuChart.data.datasets[0].data = data[defaultSpan].os.map(function (point) {
    return point.cpu;
  });
  cpuChart.data.labels = data[defaultSpan].os.map(addTimestamp);

  memStat.textContent = data[defaultSpan].os[data[defaultSpan].os.length - 1].memory.toFixed(1) + 'MB';
  memChart.data.datasets[0].data = data[defaultSpan].os.map(function (point) {
    return point.memory;
  });
  memChart.data.labels = data[defaultSpan].os.map(addTimestamp);

  loadStat.textContent = data[defaultSpan].os[data[defaultSpan].os.length - 1].load[defaultSpan].toFixed(2);
  loadChart.data.datasets[0].data = data[defaultSpan].os.map(function (point) {
    return point.load[0];
  });
  loadChart.data.labels = data[defaultSpan].os.map(addTimestamp);

  responseTimeStat.textContent = data[defaultSpan].responses[data[defaultSpan].responses.length - 1].mean.toFixed(2) + 'ms';
  responseTimeChart.data.datasets[0].data = data[defaultSpan].responses.map(function (point) {
    return point.mean;
  });
  responseTimeChart.data.labels = data[defaultSpan].responses.map(addTimestamp);

  if (data[defaultSpan].responses.length >= 2) {
    var deltaTime = data[defaultSpan].responses[data[defaultSpan].responses.length - 1].timestamp - data[defaultSpan].responses[data[defaultSpan].responses.length - 2].timestamp;
    rpsStat.textContent = (data[defaultSpan].responses[data[defaultSpan].responses.length - 1].count / deltaTime * 1000).toFixed(2);
    rpsChart.data.datasets[0].data = data[defaultSpan].responses.map(function (point) {
      return point.count / deltaTime * 1000;
    });
    rpsChart.data.labels = data[defaultSpan].responses.map(addTimestamp);
  }

  charts.forEach(function(chart) {
    chart.update();
  });

  var spanControls = document.getElementById('span-controls');
  if (data.length !== spans.length) {
    data.forEach(function (span, index) {
      spans.push({
        retention: span.retention,
        interval: span.interval
      });

      var spanNode = document.createElement('span');
      var textNode = document.createTextNode((span.retention * span.interval) / 60 + "M");
      spanNode.appendChild(textNode);
      spanNode.setAttribute('id', index);
      spanNode.onclick = onSpanChange;
      spanControls.appendChild(spanNode);
    });
    document.getElementsByTagName('span')[0].classList.add('active');
  }
});

socket.on('stats', function (data) {
  if (data.retention === spans[defaultSpan].retention && data.interval === spans[defaultSpan].interval) {
    cpuStat.textContent = data.os.cpu.toFixed(1) + '%';
    cpuChart.data.datasets[0].data.push(data.os.cpu);
    cpuChart.data.labels.push(data.os.timestamp);

    memStat.textContent = data.os.memory.toFixed(1) + 'MB';
    memChart.data.datasets[0].data.push(data.os.memory);
    memChart.data.labels.push(data.os.timestamp);

    loadStat.textContent = data.os.load[0].toFixed(2);
    loadChart.data.datasets[0].data.push(data.os.load[0]);
    loadChart.data.labels.push(data.os.timestamp);

    responseTimeStat.textContent = data.responses.mean.toFixed(2) + 'ms';
    responseTimeChart.data.datasets[0].data.push(data.responses.mean);
    responseTimeChart.data.labels.push(data.responses.timestamp);

    var deltaTime = data.responses.timestamp - rpsChart.data.labels[rpsChart.data.labels.length - 1];
    rpsStat.textContent = (data.responses.count / deltaTime * 1000).toFixed(2);
    rpsChart.data.datasets[0].data.push(data.responses.count / deltaTime * 1000);
    rpsChart.data.labels.push(data.responses.timestamp);

    charts.forEach(function (chart) {
      if (spans[defaultSpan].retention < chart.data.labels.length) {
        chart.data.datasets[0].data.shift();
        chart.data.labels.shift();
      }

      chart.update();
    });
  }
});
<commit_msg>Update app.js to the latest version of RafalWilinski/express-status-monitor<commit_after>'use strict';

Chart.defaults.global.defaultFontSize = 8;
Chart.defaults.global.animation.duration = 500;
Chart.defaults.global.legend.display = false;
Chart.defaults.global.elements.line.backgroundColor = "rgba(0,0,0,0)";
Chart.defaults.global.elements.line.borderColor = "rgba(0,0,0,0.9)";
Chart.defaults.global.elements.line.borderWidth = 2;

var socket = io(location.protocol + '//' + location.hostname + ':' + location.port);
var defaultSpan = 0;
var spans = [];
var statusCodesColors = ['#75D701', '#47b8e0', '#ffc952', '#E53A40'];

var defaultDataset = {
  label: '',
  data: [],
  lineTension: 0.2,
  pointRadius: 0
};

var defaultOptions = {
  scales: {
    yAxes: [{
      ticks: {
        beginAtZero: true
      }
    }],
    xAxes: [{
      type: 'time',
      time: {
        unitStepSize: 30
      },
      gridLines: {
        display: false
      }
    }]
  },
  tooltips: {
    enabled: false
  },
  responsive: true,
  maintainAspectRatio: false,
  animation: false
};

var createChart = function (ctx, dataset) {
  return new Chart(ctx, {
    type: 'line',
    data: {
      labels: [],
      datasets: dataset,
    },
    options: defaultOptions
  });
};

var addTimestamp = function (point) {
  return point.timestamp;
};

var cpuDataset = [Object.create(defaultDataset)];
var memDataset = [Object.create(defaultDataset)];
var loadDataset = [Object.create(defaultDataset)];
var responseTimeDataset = [Object.create(defaultDataset)];
var rpsDataset = [Object.create(defaultDataset)];
var statusCodesDataset = [Object.create(defaultDataset)];

var cpuStat = document.getElementById('cpuStat');
var memStat = document.getElementById('memStat');
var loadStat = document.getElementById('loadStat');
var responseTimeStat = document.getElementById('responseTimeStat');
var rpsStat = document.getElementById('rpsStat');

var cpuChartCtx = document.getElementById("cpuChart");
var memChartCtx = document.getElementById("memChart");
var loadChartCtx = document.getElementById("loadChart");
var responseTimeChartCtx = document.getElementById("responseTimeChart");
var rpsChartCtx = document.getElementById("rpsChart");
var statusCodesChartCtx = document.getElementById("statusCodesChart");

var cpuChart = createChart(cpuChartCtx, cpuDataset);
var memChart = createChart(memChartCtx, memDataset);
var loadChart = createChart(loadChartCtx, loadDataset);
var responseTimeChart = createChart(responseTimeChartCtx, responseTimeDataset);
var rpsChart = createChart(rpsChartCtx, rpsDataset);
var statusCodesChart = new Chart(statusCodesChartCtx, {
  type: 'line',
  data: {
    labels: [],
    datasets: [
      Object.create(defaultDataset),
      Object.create(defaultDataset),
      Object.create(defaultDataset),
      Object.create(defaultDataset)
    ]
  },
  options: defaultOptions
});

statusCodesChart.data.datasets.forEach(function(dataset, index) {
  dataset.borderColor = statusCodesColors[index];
});

var charts = [cpuChart, memChart, loadChart, responseTimeChart, rpsChart, statusCodesChart];

var onSpanChange = function (e) {
  e.target.classList.add('active');
  defaultSpan = parseInt(e.target.id);

  var otherSpans = document.getElementsByTagName('span');
  for (var i = 0; i < otherSpans.length; i++) {
    if (otherSpans[i] !== e.target) otherSpans[i].classList.remove('active');
  }

  socket.emit('change');
};

socket.on('start', function (data) {
  // Remove last element of Array because it contains malformed responses data.
  // To keep consistency we also remove os data.
  data[defaultSpan].responses.pop();
  data[defaultSpan].os.pop();

  var lastOsMetric = data[defaultSpan].os[data[defaultSpan].os.length - 1];

  cpuStat.textContent = '0.0%';
  if (lastOsMetric) {
    cpuStat.textContent = lastOsMetric.cpu.toFixed(1) + '%';
  }

  cpuChart.data.datasets[0].data = data[defaultSpan].os.map(function (point) {
    return point.cpu;
  });
  cpuChart.data.labels = data[defaultSpan].os.map(addTimestamp);

  memStat.textContent = '0.0MB';
  if (lastOsMetric) {
    memStat.textContent = lastOsMetric.memory.toFixed(1) + 'MB';
  }

  memChart.data.datasets[0].data = data[defaultSpan].os.map(function (point) {
    return point.memory;
  });
  memChart.data.labels = data[defaultSpan].os.map(addTimestamp);

  loadStat.textContent = '0.00';
  if (lastOsMetric) {
    loadStat.textContent = lastOsMetric.load[defaultSpan].toFixed(2);
  }

  loadChart.data.datasets[0].data = data[defaultSpan].os.map(function (point) {
    return point.load[0];
  });
  loadChart.data.labels = data[defaultSpan].os.map(addTimestamp);

  var lastResponseMetric = data[defaultSpan].responses[data[defaultSpan].responses.length - 1];

  responseTimeStat.textContent = '0.00ms';
  if (lastResponseMetric) {
    responseTimeStat.textContent = lastResponseMetric.mean.toFixed(2) + 'ms';
  }

  responseTimeChart.data.datasets[0].data = data[defaultSpan].responses.map(function (point) {
    return point.mean;
  });
  responseTimeChart.data.labels = data[defaultSpan].responses.map(addTimestamp);

  for(var i = 0; i < 4; i++) {
    statusCodesChart.data.datasets[i].data = data[defaultSpan].responses.map(function (point) {
      return point[i+2];
    });
  }
  statusCodesChart.data.labels = data[defaultSpan].responses.map(addTimestamp);

  if (data[defaultSpan].responses.length >= 2) {
    var deltaTime = lastResponseMetric.timestamp - data[defaultSpan].responses[data[defaultSpan].responses.length - 2].timestamp;
    if (deltaTime < 1) deltaTime = 1000;
    rpsStat.textContent = (lastResponseMetric.count / deltaTime * 1000).toFixed(2);
    rpsChart.data.datasets[0].data = data[defaultSpan].responses.map(function (point) {
      return point.count / deltaTime * 1000;
    });
    rpsChart.data.labels = data[defaultSpan].responses.map(addTimestamp);
  }

  charts.forEach(function (chart) {
    chart.update();
  });

  var spanControls = document.getElementById('span-controls');
  if (data.length !== spans.length) {
    data.forEach(function (span, index) {
      spans.push({
        retention: span.retention,
        interval: span.interval
      });

      var spanNode = document.createElement('span');
      var textNode = document.createTextNode((span.retention * span.interval) / 60 + "M");
      spanNode.appendChild(textNode);
      spanNode.setAttribute('id', index);
      spanNode.onclick = onSpanChange;
      spanControls.appendChild(spanNode);
    });
    document.getElementsByTagName('span')[0].classList.add('active');
  }
});

socket.on('stats', function (data) {
  if (data.retention === spans[defaultSpan].retention && data.interval === spans[defaultSpan].interval) {
    var os = data.os;
    var responses = data.responses;

    cpuStat.textContent = '0.0%';
    if (os) {
      cpuStat.textContent = os.cpu.toFixed(1) + '%';
      cpuChart.data.datasets[0].data.push(os.cpu);
      cpuChart.data.labels.push(os.timestamp);
    }

    memStat.textContent = '0.0MB';
    if (os) {
      memStat.textContent = os.memory.toFixed(1) + 'MB';
      memChart.data.datasets[0].data.push(os.memory);
      memChart.data.labels.push(os.timestamp);
    }

    loadStat.textContent = '0';
    if (os) {
      loadStat.textContent = os.load[0].toFixed(2);
      loadChart.data.datasets[0].data.push(os.load[0]);
      loadChart.data.labels.push(os.timestamp);
    }

    responseTimeStat.textContent = '0.00ms';
    if (responses) {
      responseTimeStat.textContent = responses.mean.toFixed(2) + 'ms';
      responseTimeChart.data.datasets[0].data.push(responses.mean);
      responseTimeChart.data.labels.push(responses.timestamp);
    }

    if (responses) {
      var deltaTime = responses.timestamp - rpsChart.data.labels[rpsChart.data.labels.length - 1];
      if (deltaTime < 1) deltaTime = 1000;
      rpsStat.textContent = (responses.count / deltaTime * 1000).toFixed(2);
      rpsChart.data.datasets[0].data.push(responses.count / deltaTime * 1000);
      rpsChart.data.labels.push(responses.timestamp);
    }

    if (responses) {
       for(var i = 0; i < 4; i++) {
        statusCodesChart.data.datasets[i].data.push(data.responses[i+2]);
      }
      statusCodesChart.data.labels.push(data.responses.timestamp);
    }

    charts.forEach(function (chart) {
      if (spans[defaultSpan].retention < chart.data.labels.length) {
        chart.data.datasets.forEach(function(dataset) {
          dataset.data.shift();
        });

        chart.data.labels.shift();
      }
      chart.update();
    });
  }
});
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import NodeGroup from './NodeGroup'
import { easeLinear } from 'd3-ease'

const COLORS = ['#a63603', '#feedde','#fdbe85','#fd8d3c','#e6550d']

const Arcs = props => {
  const {
    path,
    arcs,
    arcTween,
    duration,
    setActiveNode,
  } = props

  return (
    <NodeGroup
      data={arcs}
      keyAccessor={d => d.filePath}

      start={d => ({
        opacity: 0.6,
        d: path(d)
      })}

      update={d => {
        if (d.noTransition) {
          return {
            opacity: 0.6,
            d: path(d)
          }
        }

        return {
          opacity: d.angle === 0 ? [1e-6] : 0.6,
          d: arcTween(d),
          timing: { duration, ease: easeLinear }
        }
      }}
    >
      <path
        d={s => s.d}
        style="cursor: pointer;"
        fill={(s, d) => COLORS[d.depth]}
        onClick={(s, d) => {
          return () => setActiveNode(d)
        }}
      />
    </NodeGroup>
  )
}

Arcs.propTypes = {
  path: PropTypes.func.isRequired,
  arcs: PropTypes.array.isRequired,
  arcTween: PropTypes.func.isRequired,
  duration: PropTypes.number.isRequired,
  setActiveNode: PropTypes.func.isRequired
}

export default Arcs
<commit_msg>remove opacity<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import NodeGroup from './NodeGroup'
import { easeLinear } from 'd3-ease'

const COLORS = ['#a63603', '#feedde','#fdbe85','#fd8d3c','#e6550d']

const Arcs = props => {
  const {
    path,
    arcs,
    arcTween,
    duration,
    setActiveNode,
  } = props

  return (
    <NodeGroup
      data={arcs}
      keyAccessor={d => d.filePath}

      start={d => ({
        d: path(d)
      })}

      update={d => {
        if (d.noTransition) {
          return {
            d: path(d)
          }
        }

        return {
          d: arcTween(d),
          timing: { duration, ease: easeLinear }
        }
      }}
    >
      <path
        d={s => s.d}
        style="cursor: pointer;"
        fill={(s, d) => COLORS[d.depth]}
        onClick={(s, d) => {
          return () => setActiveNode(d)
        }}
      />
    </NodeGroup>
  )
}

Arcs.propTypes = {
  path: PropTypes.func.isRequired,
  arcs: PropTypes.array.isRequired,
  arcTween: PropTypes.func.isRequired,
  duration: PropTypes.number.isRequired,
  setActiveNode: PropTypes.func.isRequired
}

export default Arcs
<|endoftext|>


<commit_before>
/**
 * Client UI root object.
 */
GuacUI.Client = {

    /**
     * Collection of all Guacamole client UI states.
     */
    "states": {

        /**
         * The normal default Guacamole client UI mode
         */
        "FULL_INTERACTIVE" : 0,

        /**
         * Same as FULL_INTERACTIVE except with visible on-screen keyboard.
         */
        "OSK"              : 1,

        /**
         * No on-screen keyboard, but a visible magnifier.
         */
        "MAGNIFIER"        : 2,

        /**
         * Arrows and a draggable view.
         */
        "PAN"              : 3,

        /**
         * Same as PAN, but with visible native OSK.
         */
        "PAN_TYPING"       : 4
    },

    /* Constants */

    "LONG_PRESS_DETECT_TIMEOUT"     : 800, /* milliseconds */
    "LONG_PRESS_MOVEMENT_THRESHOLD" : 10,  /* pixels */
    "KEYBOARD_AUTO_RESIZE_INTERVAL" : 30,  /* milliseconds */

    /* UI Components */

    "viewport"    : document.getElementById("viewportClone"),
    "display"     : document.getElementById("display"),
    "logo"        : document.getElementById("status-logo"),

    "buttons": {
        "reconnect" : document.getElementById("reconnect")
    },

    "containers": {
        "state"     : document.getElementById("statusDialog"),
        "keyboard"  : document.getElementById("keyboardContainer")
    },

    "state"        : document.getElementById("statusText"),
    "client"       : null,
    "sessionState" : new GuacamoleSessionState(),

    /* Expected Input Rectangle */

    "expected_input_x" : 0,
    "expected_input_y" : 0,
    "expected_input_width" : 1,
    "expected_input_height" : 1

};

/**
 * Component which displays a magnified (100% zoomed) client display.
 *
 * @constructor
 * @augments GuacUI.DraggableComponent
 */
GuacUI.Client.Magnifier = function() {

    /**
     * Reference to this magnifier.
     * @private
     */
    var guac_magnifier = this;

    /**
     * Large background div which will block touch events from reaching the
     * client while also providing a click target to deactivate the
     * magnifier.
     * @private
     */
    var magnifier_background = GuacUI.createElement("div", "magnifier-background");

    /**
     * Container div for the magnifier, providing a clipping rectangle.
     * @private
     */
    var magnifier = GuacUI.createChildElement(magnifier_background,
        "div", "magnifier");

    /**
     * Canvas which will contain the static image copy of the display at time
     * of show.
     * @private
     */
    var magnifier_display = GuacUI.createChildElement(magnifier, "canvas");

    /**
     * Context of magnifier display.
     * @private
     */
    var magnifier_context = magnifier_display.getContext("2d");

    /*
     * This component is draggable.
     */
    GuacUI.DraggableComponent.apply(this, [magnifier]);

    // Ensure transformations on display originate at 0,0
    magnifier.style.transformOrigin =
    magnifier.style.webkitTransformOrigin =
    magnifier.style.MozTransformOrigin =
    magnifier.style.OTransformOrigin =
    magnifier.style.msTransformOrigin =
        "0 0";

    /*
     * Reposition magnifier display relative to own position on screen.
     */

    this.onmove = function(x, y) {

        var width = magnifier.offsetWidth;
        var height = magnifier.offsetHeight;

        // Update contents relative to new position
        var clip_x = x
            / (window.innerWidth - width) * (GuacamoleUI.client.getWidth() - width);
        var clip_y = y
            / (window.innerHeight - height) * (GuacamoleUI.client.getHeight() - height);

        magnifier_display.style.WebkitTransform =
        magnifier_display.style.MozTransform =
        magnifier_display.style.OTransform =
        magnifier_display.style.msTransform =
        magnifier_display.style.transform = "translate("
            + (-clip_x) + "px, " + (-clip_y) + "px)";

        /* Update expected input rectangle */
        GuacUI.Client.expected_input_x = clip_x;
        GuacUI.Client.expected_input_y = clip_y;
        GuacUI.Client.expected_input_width  = width;
        GuacUI.Client.expected_input_height = height;

    };

    /*
     * Copy display and add self to body on show.
     */

    this.show = function() {

        // Copy displayed image
        magnifier_display.width = GuacamoleUI.client.getWidth();
        magnifier_display.height = GuacamoleUI.client.getHeight();
        magnifier_context.drawImage(GuacamoleUI.client.flatten(), 0, 0);

        // Show magnifier container
        document.body.appendChild(magnifier_background);

    };

    /*
     * Remove self from body on hide.
     */

    this.hide = function() {

        // Hide magnifier container
        document.body.removeChild(magnifier_background);

    };

    /*
     * If the user clicks on the background, switch to INTERACTIVE mode.
     */

    magnifier_background.addEventListener("click", function() {
        GuacUI.StateManager.setState(GuacUI.Client.states.INTERACTIVE);
    }, true);

    /*
     * If the user clicks on the magnifier, switch to PAN_TYPING mode.
     */

    magnifier.addEventListener("click", function(e) {
        GuacUI.StateManager.setState(GuacUI.Client.states.PAN_TYPING);
        e.stopPropagation();
    }, true);

};

/*
 * We inherit from GuacUI.DraggableComponent.
 */
GuacUI.Client.Magnifier.prototype = new GuacUI.DraggableComponent();

GuacUI.StateManager.registerComponent(
    new GuacUI.Client.Magnifier(),
    GuacUI.Client.states.MAGNIFIER
);

/**
 * Zoomed Display, a pseudo-component.
 *
 * @constructor
 * @augments GuacUI.Component
 */
GuacUI.Client.ZoomedDisplay = function() {

    var old_scale = null;

    this.show = function() {
        old_scale = GuacamoleUI.client.getScale();
        GuacamoleUI.client.scale(1.0);
    };

    this.hide = function() {
        GuacamoleUI.client.scale(old_scale);
    };

};

GuacUI.Client.ZoomedDisplay.prototype = new GuacUI.Component();

/*
 * Zoom the main display during PAN and PAN_TYPING modes.
 */

GuacUI.StateManager.registerComponent(
    new GuacUI.Client.ZoomedDisplay(),
    GuacUI.Client.states.PAN,
    GuacUI.Client.states.PAN_TYPING
);

/**
 * Pan overlay UI. This component functions to receive touch events and
 * translate them into scrolling of the main UI.
 *
 * @constructor
 * @augments GuacUI.Component
 */
GuacUI.Client.PanOverlay = function() {

    /**
     * Overlay which will provide the means of scrolling the screen.
     */
    var pan_overlay = GuacUI.createElement("div", "pan-overlay");

    /*
     * Add arrows
     */

    GuacUI.createChildElement(pan_overlay, "div", "indicator up");
    GuacUI.createChildElement(pan_overlay, "div", "indicator down");
    GuacUI.createChildElement(pan_overlay, "div", "indicator right");
    GuacUI.createChildElement(pan_overlay, "div", "indicator left");

    this.show = function() {
        document.body.appendChild(pan_overlay);
    };

    this.hide = function() {
        document.body.removeChild(pan_overlay);
    };

    /*
     * Transition to PAN_TYPING when the user taps on the overlay.
     */

    pan_overlay.addEventListener("click", function(e) {
        GuacUI.StateManager.setState(GuacUI.Client.states.PAN_TYPING);
        e.stopPropagation();
    }, true);

};

GuacUI.Client.PanOverlay.prototype = new GuacUI.Component();

/*
 * Show the pan overlay during PAN or PAN_TYPING modes.
 */

GuacUI.StateManager.registerComponent(
    new GuacUI.Client.PanOverlay(),
    GuacUI.Client.states.PAN,
    GuacUI.Client.states.PAN_TYPING
);

/**
 * Native Keyboard. This component uses a hidden textarea field to show the
 * platforms native on-screen keyboard (if any) or otherwise enable typing,
 * should the platform require a text field with focus for keyboard events to
 * register.
 *
 * @constructor
 * @augments GuacUI.Component
 */
GuacUI.Client.NativeKeyboard = function() {

    /**
     * Event target. This is a hidden textarea element which will receive
     * key events.
     * @private
     */
    var eventTarget = GuacUI.createElement("textarea", "event-target");
    eventTarget.setAttribute("autocorrect", "off");
    eventTarget.setAttribute("autocapitalize", "off");

    this.show = function() {

        // Move to location of expected input
        eventTarget.style.left   = GuacUI.Client.expected_input_x + "px";
        eventTarget.style.top    = GuacUI.Client.expected_input_y + "px";
        eventTarget.style.width  = GuacUI.Client.expected_input_width + "px";
        eventTarget.style.height = GuacUI.Client.expected_input_height + "px";

        // Show and focus target
        document.body.appendChild(eventTarget);
        eventTarget.focus();

    };

    this.hide = function() {

        // Hide and blur target
        eventTarget.blur();
        document.body.removeChild(eventTarget);

    };

    /*
     * Automatically switch to INTERACTIVE mode after target loses focus
     */

    eventTarget.addEventListener("blur", function() {
        GuacUI.StateManager.setState(GuacUI.Client.states.INTERACTIVE);
    }, false);

};

GuacUI.Client.NativeKeyboard.prototype = new GuacUI.Component();

/*
 * Show native keyboard during PAN_TYPING mode only.
 */

GuacUI.StateManager.registerComponent(
    new GuacUI.Client.NativeKeyboard(),
    GuacUI.Client.states.PAN_TYPING
);

/**
 * On-screen Keyboard. This component provides a clickable/touchable keyboard
 * which sends key events to the Guacamole client.
 *
 * @constructor
 * @augments GuacUI.Component
 */
GuacUI.Client.OnScreenKeyboard = function() {

    /**
     * Event target. This is a hidden textarea element which will receive
     * key events.
     * @private
     */
    var keyboard_container = GuacUI.createElement("div", "keyboard-container");

    var keyboard_resize_interval = null;

    // On-screen keyboard
    var keyboard = new Guacamole.OnScreenKeyboard("layouts/en-us-qwerty.xml");
    keyboard_container.appendChild(keyboard.getElement());

    var last_keyboard_width = 0;

    // Function for automatically updating keyboard size
    function updateKeyboardSize() {
        var currentSize = keyboard.getElement().offsetWidth;
        if (last_keyboard_width != currentSize) {
            keyboard.resize(currentSize);
            last_keyboard_width = currentSize;
        }
    }

    keyboard.onkeydown = function(keysym) {
        GuacamoleUI.client.sendKeyEvent(1, keysym);
    };

    keyboard.onkeyup = function(keysym) {
        GuacamoleUI.client.sendKeyEvent(0, keysym);
    };

    this.show = function() {

        // Show keyboard
        document.body.appendChild(keyboard_container);

        // Start periodic update of keyboard size
        keyboard_resize_interval = window.setInterval(
            updateKeyboardSize,
            GuacUI.Client.KEYBOARD_AUTO_RESIZE_INTERVAL);

        // Resize on window resize
        window.addEventListener("resize", updateKeyboardSize, true);

        // Initialize size
        updateKeyboardSize();

    };

    this.hide = function() {

        // Hide keyboard
        document.body.removeChild(keyboard_container);
        window.clearInterval(keyboard_resize_interval);
        window.removeEventListener("resize", updateKeyboardSize, true);

    };

};

GuacUI.Client.OnScreenKeyboard.prototype = new GuacUI.Component();

/*
 * Show on-screen keyboard during OSK mode only.
 */

GuacUI.StateManager.registerComponent(
    new GuacUI.Client.OnScreenKeyboard(),
    GuacUI.Client.states.OSK
);

/*
 * Set initial state
 */

GuacUI.StateManager.setState(GuacUI.Client.states.INTERACTIVE);
<commit_msg>Fix typo in INTERACTIVE naming.<commit_after>
/**
 * Client UI root object.
 */
GuacUI.Client = {

    /**
     * Collection of all Guacamole client UI states.
     */
    "states": {

        /**
         * The normal default Guacamole client UI mode
         */
        "INTERACTIVE" : 0,

        /**
         * Same as INTERACTIVE except with visible on-screen keyboard.
         */
        "OSK"              : 1,

        /**
         * No on-screen keyboard, but a visible magnifier.
         */
        "MAGNIFIER"        : 2,

        /**
         * Arrows and a draggable view.
         */
        "PAN"              : 3,

        /**
         * Same as PAN, but with visible native OSK.
         */
        "PAN_TYPING"       : 4
    },

    /* Constants */

    "LONG_PRESS_DETECT_TIMEOUT"     : 800, /* milliseconds */
    "LONG_PRESS_MOVEMENT_THRESHOLD" : 10,  /* pixels */
    "KEYBOARD_AUTO_RESIZE_INTERVAL" : 30,  /* milliseconds */

    /* UI Components */

    "viewport"    : document.getElementById("viewportClone"),
    "display"     : document.getElementById("display"),
    "logo"        : document.getElementById("status-logo"),

    "buttons": {
        "reconnect" : document.getElementById("reconnect")
    },

    "containers": {
        "state"     : document.getElementById("statusDialog"),
        "keyboard"  : document.getElementById("keyboardContainer")
    },

    "state"        : document.getElementById("statusText"),
    "client"       : null,
    "sessionState" : new GuacamoleSessionState(),

    /* Expected Input Rectangle */

    "expected_input_x" : 0,
    "expected_input_y" : 0,
    "expected_input_width" : 1,
    "expected_input_height" : 1

};

/**
 * Component which displays a magnified (100% zoomed) client display.
 *
 * @constructor
 * @augments GuacUI.DraggableComponent
 */
GuacUI.Client.Magnifier = function() {

    /**
     * Reference to this magnifier.
     * @private
     */
    var guac_magnifier = this;

    /**
     * Large background div which will block touch events from reaching the
     * client while also providing a click target to deactivate the
     * magnifier.
     * @private
     */
    var magnifier_background = GuacUI.createElement("div", "magnifier-background");

    /**
     * Container div for the magnifier, providing a clipping rectangle.
     * @private
     */
    var magnifier = GuacUI.createChildElement(magnifier_background,
        "div", "magnifier");

    /**
     * Canvas which will contain the static image copy of the display at time
     * of show.
     * @private
     */
    var magnifier_display = GuacUI.createChildElement(magnifier, "canvas");

    /**
     * Context of magnifier display.
     * @private
     */
    var magnifier_context = magnifier_display.getContext("2d");

    /*
     * This component is draggable.
     */
    GuacUI.DraggableComponent.apply(this, [magnifier]);

    // Ensure transformations on display originate at 0,0
    magnifier.style.transformOrigin =
    magnifier.style.webkitTransformOrigin =
    magnifier.style.MozTransformOrigin =
    magnifier.style.OTransformOrigin =
    magnifier.style.msTransformOrigin =
        "0 0";

    /*
     * Reposition magnifier display relative to own position on screen.
     */

    this.onmove = function(x, y) {

        var width = magnifier.offsetWidth;
        var height = magnifier.offsetHeight;

        // Update contents relative to new position
        var clip_x = x
            / (window.innerWidth - width) * (GuacamoleUI.client.getWidth() - width);
        var clip_y = y
            / (window.innerHeight - height) * (GuacamoleUI.client.getHeight() - height);

        magnifier_display.style.WebkitTransform =
        magnifier_display.style.MozTransform =
        magnifier_display.style.OTransform =
        magnifier_display.style.msTransform =
        magnifier_display.style.transform = "translate("
            + (-clip_x) + "px, " + (-clip_y) + "px)";

        /* Update expected input rectangle */
        GuacUI.Client.expected_input_x = clip_x;
        GuacUI.Client.expected_input_y = clip_y;
        GuacUI.Client.expected_input_width  = width;
        GuacUI.Client.expected_input_height = height;

    };

    /*
     * Copy display and add self to body on show.
     */

    this.show = function() {

        // Copy displayed image
        magnifier_display.width = GuacamoleUI.client.getWidth();
        magnifier_display.height = GuacamoleUI.client.getHeight();
        magnifier_context.drawImage(GuacamoleUI.client.flatten(), 0, 0);

        // Show magnifier container
        document.body.appendChild(magnifier_background);

    };

    /*
     * Remove self from body on hide.
     */

    this.hide = function() {

        // Hide magnifier container
        document.body.removeChild(magnifier_background);

    };

    /*
     * If the user clicks on the background, switch to INTERACTIVE mode.
     */

    magnifier_background.addEventListener("click", function() {
        GuacUI.StateManager.setState(GuacUI.Client.states.INTERACTIVE);
    }, true);

    /*
     * If the user clicks on the magnifier, switch to PAN_TYPING mode.
     */

    magnifier.addEventListener("click", function(e) {
        GuacUI.StateManager.setState(GuacUI.Client.states.PAN_TYPING);
        e.stopPropagation();
    }, true);

};

/*
 * We inherit from GuacUI.DraggableComponent.
 */
GuacUI.Client.Magnifier.prototype = new GuacUI.DraggableComponent();

GuacUI.StateManager.registerComponent(
    new GuacUI.Client.Magnifier(),
    GuacUI.Client.states.MAGNIFIER
);

/**
 * Zoomed Display, a pseudo-component.
 *
 * @constructor
 * @augments GuacUI.Component
 */
GuacUI.Client.ZoomedDisplay = function() {

    var old_scale = null;

    this.show = function() {
        old_scale = GuacamoleUI.client.getScale();
        GuacamoleUI.client.scale(1.0);
    };

    this.hide = function() {
        GuacamoleUI.client.scale(old_scale);
    };

};

GuacUI.Client.ZoomedDisplay.prototype = new GuacUI.Component();

/*
 * Zoom the main display during PAN and PAN_TYPING modes.
 */

GuacUI.StateManager.registerComponent(
    new GuacUI.Client.ZoomedDisplay(),
    GuacUI.Client.states.PAN,
    GuacUI.Client.states.PAN_TYPING
);

/**
 * Pan overlay UI. This component functions to receive touch events and
 * translate them into scrolling of the main UI.
 *
 * @constructor
 * @augments GuacUI.Component
 */
GuacUI.Client.PanOverlay = function() {

    /**
     * Overlay which will provide the means of scrolling the screen.
     */
    var pan_overlay = GuacUI.createElement("div", "pan-overlay");

    /*
     * Add arrows
     */

    GuacUI.createChildElement(pan_overlay, "div", "indicator up");
    GuacUI.createChildElement(pan_overlay, "div", "indicator down");
    GuacUI.createChildElement(pan_overlay, "div", "indicator right");
    GuacUI.createChildElement(pan_overlay, "div", "indicator left");

    this.show = function() {
        document.body.appendChild(pan_overlay);
    };

    this.hide = function() {
        document.body.removeChild(pan_overlay);
    };

    /*
     * Transition to PAN_TYPING when the user taps on the overlay.
     */

    pan_overlay.addEventListener("click", function(e) {
        GuacUI.StateManager.setState(GuacUI.Client.states.PAN_TYPING);
        e.stopPropagation();
    }, true);

};

GuacUI.Client.PanOverlay.prototype = new GuacUI.Component();

/*
 * Show the pan overlay during PAN or PAN_TYPING modes.
 */

GuacUI.StateManager.registerComponent(
    new GuacUI.Client.PanOverlay(),
    GuacUI.Client.states.PAN,
    GuacUI.Client.states.PAN_TYPING
);

/**
 * Native Keyboard. This component uses a hidden textarea field to show the
 * platforms native on-screen keyboard (if any) or otherwise enable typing,
 * should the platform require a text field with focus for keyboard events to
 * register.
 *
 * @constructor
 * @augments GuacUI.Component
 */
GuacUI.Client.NativeKeyboard = function() {

    /**
     * Event target. This is a hidden textarea element which will receive
     * key events.
     * @private
     */
    var eventTarget = GuacUI.createElement("textarea", "event-target");
    eventTarget.setAttribute("autocorrect", "off");
    eventTarget.setAttribute("autocapitalize", "off");

    this.show = function() {

        // Move to location of expected input
        eventTarget.style.left   = GuacUI.Client.expected_input_x + "px";
        eventTarget.style.top    = GuacUI.Client.expected_input_y + "px";
        eventTarget.style.width  = GuacUI.Client.expected_input_width + "px";
        eventTarget.style.height = GuacUI.Client.expected_input_height + "px";

        // Show and focus target
        document.body.appendChild(eventTarget);
        eventTarget.focus();

    };

    this.hide = function() {

        // Hide and blur target
        eventTarget.blur();
        document.body.removeChild(eventTarget);

    };

    /*
     * Automatically switch to INTERACTIVE mode after target loses focus
     */

    eventTarget.addEventListener("blur", function() {
        GuacUI.StateManager.setState(GuacUI.Client.states.INTERACTIVE);
    }, false);

};

GuacUI.Client.NativeKeyboard.prototype = new GuacUI.Component();

/*
 * Show native keyboard during PAN_TYPING mode only.
 */

GuacUI.StateManager.registerComponent(
    new GuacUI.Client.NativeKeyboard(),
    GuacUI.Client.states.PAN_TYPING
);

/**
 * On-screen Keyboard. This component provides a clickable/touchable keyboard
 * which sends key events to the Guacamole client.
 *
 * @constructor
 * @augments GuacUI.Component
 */
GuacUI.Client.OnScreenKeyboard = function() {

    /**
     * Event target. This is a hidden textarea element which will receive
     * key events.
     * @private
     */
    var keyboard_container = GuacUI.createElement("div", "keyboard-container");

    var keyboard_resize_interval = null;

    // On-screen keyboard
    var keyboard = new Guacamole.OnScreenKeyboard("layouts/en-us-qwerty.xml");
    keyboard_container.appendChild(keyboard.getElement());

    var last_keyboard_width = 0;

    // Function for automatically updating keyboard size
    function updateKeyboardSize() {
        var currentSize = keyboard.getElement().offsetWidth;
        if (last_keyboard_width != currentSize) {
            keyboard.resize(currentSize);
            last_keyboard_width = currentSize;
        }
    }

    keyboard.onkeydown = function(keysym) {
        GuacamoleUI.client.sendKeyEvent(1, keysym);
    };

    keyboard.onkeyup = function(keysym) {
        GuacamoleUI.client.sendKeyEvent(0, keysym);
    };

    this.show = function() {

        // Show keyboard
        document.body.appendChild(keyboard_container);

        // Start periodic update of keyboard size
        keyboard_resize_interval = window.setInterval(
            updateKeyboardSize,
            GuacUI.Client.KEYBOARD_AUTO_RESIZE_INTERVAL);

        // Resize on window resize
        window.addEventListener("resize", updateKeyboardSize, true);

        // Initialize size
        updateKeyboardSize();

    };

    this.hide = function() {

        // Hide keyboard
        document.body.removeChild(keyboard_container);
        window.clearInterval(keyboard_resize_interval);
        window.removeEventListener("resize", updateKeyboardSize, true);

    };

};

GuacUI.Client.OnScreenKeyboard.prototype = new GuacUI.Component();

/*
 * Show on-screen keyboard during OSK mode only.
 */

GuacUI.StateManager.registerComponent(
    new GuacUI.Client.OnScreenKeyboard(),
    GuacUI.Client.states.OSK
);

/*
 * Set initial state
 */

GuacUI.StateManager.setState(GuacUI.Client.states.INTERACTIVE);
<|endoftext|>


<commit_before>(function () {

  var directive = function () {
    return {
      restrict: "EA",
      bindToController: {
        stepIndex: '@'
      },
      require:['thinkbigVisualQueryTransform','^thinkbigStepper'],
      scope: {},
      controllerAs: 'vm',
      templateUrl: 'js/visual-query/visual-query-transform.html',
      controller: "VisualQueryTransformController",
      link: function ($scope, element, attrs, controllers) {
        var thisController = controllers[0];
        var stepperController = controllers[1];
        //store a reference to the stepper if needed
        thisController.stepperController = stepperController;
      }

    };
  }

  var controller =  function($scope,$log, $http,$mdToast,RestUrlService, VisualQueryService,  HiveService, TableDataFunctions,SideNavService, SparkShellService) {

    var self = this;
    //The model passed in from the previous step
    this.model = VisualQueryService.model;
    //Flag to determine if we can move on to the next step
    this.isValid = true;
    //The SQL String from the previous step
    this.sql = this.model.visualQuerySql;
    //The sql model passed over from the previous step
    this.sqlModel = this.model.visualQueryModel;
    //The array of columns with their respective Table, schema and alias passed over from the previous step
    //{column:'name', alias:'alias',tableName:'table name',tableColumn:'alias_name',dataType:'dataType'}
    this.selectedColumnsAndTables = this.model.selectedColumnsAndTables;
    //The query result transformed to the ag-grid model  (@see HiveService.transformToAgGrid
    this.tableData = {columns:[],rows:[]}
    //Function History
    this.functionHistory = [];

    //The current formula string
    this.currentFormula = '';

    //flag to indicate if the Hive data is available
    this.hiveDataLoaded = false;
    //flag to indicate codemirror is ready
    this.codemirroLoaded = false;
    //the codemirror editor
    this.codemirrorEditor = null;
    //the tern server reference
    this.ternServer = null;

    //Function Command Holder
    //@see TableDataFunctions.js
    this.functionCommandHolder =null;

    //Flag to show/hide function history panel
    this.isShowFunctionHistory = false;

    //Setup initial grid options
    this.gridOptions = {
      columnDefs: [],
      data: null,
      enableColumnResizing: true,
      enableGridMenu: true,
      flatEntityAccess: true
    };

    this.sparkShellService = new SparkShellService(this.sql);

    //Code Mirror options.  Tern Server requires it be in javascript mode
    this.codemirrorOptions = {
      lineWrapping : false,
      indentWithTabs: false,
      smartIndent: false,
      lineNumbers: false,
      matchBrackets : false,
      autofocus: true,
      mode: 'javascript',
      scrollbarStyle:null
    }

    /**
     * Show and hide the Funciton History
     */
    this.toggleFunctionHistory = function() {
      if(self.isShowFunctionHistory){
        self.isShowFunctionHistory = false;
      }
      else {
        self.isShowFunctionHistory = true;
      }
    }

    //Callback when Codemirror has been loaded (reference is in the html page at: ui-codemirror="{ onLoad : vm.codemirrorLoaded }"
    this.codemirrorLoaded = function(_editor) {
      //assign the editor to a variable on this object for future reference
      self.codemirrorEditor = _editor;
      //Set the width,heightof the editor
      //Code mirror needs an explicit width/height
      _editor.setSize(700, 25);

      //disable users ability to add new lines.  The Formula bar is only 1 line
      _editor.on("beforeChange", function(instance, change) {
        var newtext = change.text.join("").replace(/\n/g, ""); // remove ALL \n !
        change.update(change.from, change.to, [newtext]);
        return true;
      });

      //hide the scrollbar
      _editor.on("change", function(instance, change) {
        //$(".CodeMirror-hscrollbar").css('display', 'none');
      });
      //set the flag to be loaded and then call out to update Autocomplete options
      self.codemirroLoaded = true;
      self.updateCodeMirrorAutoComplete();
    };

    /**
     * return the columns from the previous step into tern defs for usage with Ctl+Space (Columns.columnName)
     * @returns {{Columns: {!type: string, !doc: string}}}
     */
    function transformColumnsAndTablesToFormulaBar(){
      var Columns = {"Columns":{
        "!type": "fn()",
        "!doc": "Avaliable Columns ",
      }
      };

      angular.forEach(self.tableData.queryResultColumns,function(item){
        Columns.Columns[item.displayName] = {   "!type": item.dataType, "!doc": "Database Column: "+item.field};
      });
      return Columns;
    }

    /**
     * turn a column into a tern def.
     * This is called for each new command/formula a user creates.
     * New columns will be marked as 'derived' with the type of String
     * TODO update this function to take a dataType or be able to lookup the datatypes associated with newly created columns
     * @param columnName
     * @returns {*}
     */
    function toTernDef(columnName){
      //attempt to see if the incoming columnName is one that was from the original query.
      //if so we can get the dataType and table it came from and add it to the tern def '!doc'
      var initialColumn = _.find(self.tableData.queryResultColumns,function(item){
        return item.displayName == columnName;
      })
      if(initialColumn != null && initialColumn != undefined){
        return {"!type": initialColumn.dataType, "!doc": "Database Column: "+initialColumn.field};
      }
      else {
        //default type to String
        //TODO revisit to assign correct datatype if can be done.
        return {"!type": "string", "!doc": "derived Column: "+columnName};
      }

    }

    /**
     * Called after a formula is created and applied to the table
     * in order to update the autocomplete (Ctl+Space) for the column names.
     *
     * This will update the column list and tell the tern server to refresh
     * @param columns
     */
    function updateTernColumnDefs(columns){
      var defs = self.ternServer.options.defs;

      var Columns = {"Columns":{
        "!type": "fn()",
        "!doc": "Avaliable Columns ",
      }
      };

      angular.forEach(columns,function(field){
        Columns.Columns[field.field] = toTernDef(field.field);
      })
      delete defs[0].Columns;
      angular.extend(defs[0],Columns);
      self.ternServer.updateDefs(defs);
    }

    /**
     * Creates a Tern server.
     */
    function createTernServer ()
    {
      $http.get('js/vendor/tern/defs/tableFunctions.json').success(function (code) {
        self.sparkShellService.setFunctionDefs(code);

        // angular.extend(code, self.sparkShellService.getColumnDefs());
        self.ternServer = new CodeMirror.TernServer({defs: [code]});
        self.ternServer.server.addDefs(self.sparkShellService.getColumnDefs());

        var _editor = self.codemirrorEditor;
        _editor.setOption("extraKeys", {
          "Ctrl-Space": function (cm) {
            self.ternServer.complete(cm);
          },
          "Ctrl-I": function (cm) {
            self.ternServer.showType(cm);
          },
          "Ctrl-O": function (cm) {
            self.ternServer.showDocs(cm);
          },
          "Alt-.": function (cm) {
            self.ternServer.jumpToDef(cm);
          },
          "Alt-,": function (cm) {
            self.ternServer.jumpBack(cm);
          },
          "Ctrl-Q": function (cm) {
            self.ternServer.rename(cm);
          },
          "Ctrl-.": function (cm) {
            self.ternServer.selectName(cm);
          }
        });
        _editor.on("blur", function () {
          self.ternServer.hideDoc();
        });
        _editor.on("cursorActivity", self.showHint);
        _editor.on("focus", self.showHint);
      });
    }

    /**
     * Setup the CodeMirror and Tern Server autocomplete
     * This will only execute when both Hive and Code Mirror are fully initialized
     */
    this.updateCodeMirrorAutoComplete = function() {
      if (self.codemirroLoaded && self.hiveDataLoaded) {
        if (self.ternServer === null) {
          createTernServer();
        }
        else {
          var defs = self.sparkShellService.getColumnDefs();
          self.ternServer.server.deleteDefs(defs["!name"]);
          self.ternServer.server.addDefs(defs);
        }
      }
    };

    /**
     * Makes an asynchronous request to get the list of completions available at the cursor.
     * When a completion is picked by the user, the function call is completed so that the
     * function argument hints can be displayed. If the only
     *
     * @param {CodeMirror|CodeMirror.Doc} cm the code mirror instance
     * @param {Function} callback the callback function
     */
    this.getHint = function (cm, callback)
    {
      self.ternServer.getHint(cm, function (data) {
        // Complete function calls so arg hints can be displayed
        CodeMirror.on(data, "pick", function (completion) {
          if (completion.data.type.substr(0, 3) === "fn(") {
            var cursor = cm.getCursor();
            cm.replaceRange("(", cursor, cursor, "complete");
          }
        });

        // Display hints
        callback(data);
      });
    };
    this.getHint.async = true;

    /**
     * Shows either argument hints or identifier hints depending on the context.
     *
     * @param {CodeMirror|CodeMirror.Doc} cm the code mirror instance
     */
    this.showHint = function (cm)
    {
      // Show args if in a function
      var cursor = cm.getCursor();
      var token = cm.getTokenAt(cursor);
      var lexer = token.state.lexical;

      if (lexer.info === "call" && token.type !== "variable") {
        self.ternServer.updateArgHints(cm);
      }
      else {
        self.ternServer.hideDoc();
      }

      // Show completions if available
      if (cursor.ch === 0 || token.type === "variable"
          || (token.string === "." && lexer.type === "stat")) {
        cm.showHint({
          completeSingle: false,
          hint: self.getHint
        });
      }
    };

    /**
     * Query Hive using the query from the previous step
     * Set the Grids rows and columns
     * @returns {*}
     */
    this.query = function(){
      //flag to indicate query is running
      this.executingQuery = true;

      return self.sparkShellService.transform().then(function (response) {
        //mark the query as finished
        self.executingQuery = false;
        //transform the result to the agGrid model
        var result = HiveService.transformQueryResultsToUiGridModel({data: response.data.results});
        //store the result for use in the commands
        self.tableData = result;
        //update the ag-grid
        self.gridOptions.columnDefs =result.columns;
        self.gridOptions.data =result.rows;
        //mark the flag to indicate Hive is loaded
        self.hiveDataLoaded = true;
        self.updateCodeMirrorAutoComplete();

        //Initialize the Command function holder
        self.functionCommandHolder = TableDataFunctions.newCommandHolder({rows:result.rows,columns:result.columns});

      });

    }

    function updateGrid(tableData) {
      self.gridOptions.columnDefs = tableData.columns;
      self.gridOptions.data = tableData.rows;
      updateTernColumnDefs(tableData.columns)
    }

    /**
     * Called when the user clicks Add on the function bar
     */
    this.onAddFunction = function(){
      var tableData = self.functionCommandHolder.executeStr(self.currentFormula);
      if(tableData != null && tableData != undefined) {
        updateGrid(tableData);
        self.functionHistory.push(self.currentFormula);

        self.ternServer.server.addFile("[doc]", self.currentFormula);
        var file = self.ternServer.server.findFile("[doc]");
        self.sparkShellService.push(file.ast);
        self.query();
      }
    }

    //reference to the last command that was undone
    var lastUndo = '';

    this.onUndo = function(){
      var tableData = self.functionCommandHolder.undo();
      updateGrid(tableData);
      lastUndo =  self.functionHistory.pop();
    }
    this.onRedo = function(){
      var tableData =   self.functionCommandHolder.redo();
      updateGrid(tableData);
      self.functionHistory.push(lastUndo);
    }

    this.canUndo = function(){
      if(self.functionCommandHolder){
        return   self.functionCommandHolder.canUndo();
      }
      else {
        return false;
      }
    }
    this.canRedo = function(){
      if(self.functionCommandHolder){
        return   self.functionCommandHolder.canRedo();
      }
      else {
        return false;
      }
    }

    //Hide the left side nav bar
    SideNavService.hideSideNav();

    this.query();

    $scope.$on('$destroy',function(){
      //clean up code here
    });

  };

  angular.module(MODULE_FEED_MGR).controller('VisualQueryTransformController', controller);

  angular.module(MODULE_FEED_MGR)
      .directive('thinkbigVisualQueryTransform', directive);

})();
<commit_msg>Code cleanup.<commit_after>(function() {

  var directive = function() {
    return {
      restrict: "EA",
      bindToController: {
        stepIndex: '@'
      },
      require: ['thinkbigVisualQueryTransform', '^thinkbigStepper'],
      scope: {},
      controllerAs: 'vm',
      templateUrl: 'js/visual-query/visual-query-transform.html',
      controller: "VisualQueryTransformController",
      link: function($scope, element, attrs, controllers) {
        var thisController = controllers[0];
        var stepperController = controllers[1];
        //store a reference to the stepper if needed
        thisController.stepperController = stepperController;
      }

    };
  };

  var controller = function($scope, $log, $http, $mdToast, NifiService, VisualQueryService, HiveService, TableDataFunctions,
                            SideNavService, SparkShellService) {

    var self = this;
    //The model passed in from the previous step
    this.model = VisualQueryService.model;
    //Flag to determine if we can move on to the next step
    this.isValid = true;
    //The SQL String from the previous step
    this.sql = this.model.visualQuerySql;
    //The sql model passed over from the previous step
    this.sqlModel = this.model.visualQueryModel;
    //The array of columns with their respective Table, schema and alias passed over from the previous step
    //{column:'name', alias:'alias',tableName:'table name',tableColumn:'alias_name',dataType:'dataType'}
    this.selectedColumnsAndTables = this.model.selectedColumnsAndTables;
    //The query result transformed to the ag-grid model  (@see HiveService.transformToAgGrid
    this.tableData = {columns: [], rows: []};
    //Function History
    this.functionHistory = [];

    //The current formula string
    this.currentFormula = '';

    //flag to indicate if the Hive data is available
    this.hiveDataLoaded = false;
    //flag to indicate codemirror is ready
    this.codemirroLoaded = false;
    //the codemirror editor
    this.codemirrorEditor = null;
    //the tern server reference
    this.ternServer = null;

    //Function Command Holder
    //@see TableDataFunctions.js
    this.functionCommandHolder = null;

    //Flag to show/hide function history panel
    this.isShowFunctionHistory = false;

    //Setup initial grid options
    this.gridOptions = {
      columnDefs: [],
      data: null,
      enableColumnResizing: true,
      enableGridMenu: true,
      flatEntityAccess: true
    };

    // Translates expressions into Spark code
    this.sparkShellService = new SparkShellService(this.sql);

    //Code Mirror options.  Tern Server requires it be in javascript mode
    this.codemirrorOptions = {
      lineWrapping: false,
      indentWithTabs: false,
      smartIndent: false,
      lineNumbers: false,
      matchBrackets: false,
      autofocus: true,
      mode: 'javascript',
      scrollbarStyle: null
    };

    /**
     * Show and hide the Funciton History
     */
    this.toggleFunctionHistory = function() {
      self.isShowFunctionHistory = !self.isShowFunctionHistory;
    };

    //Callback when Codemirror has been loaded (reference is in the html page at:
    // ui-codemirror="{ onLoad : vm.codemirrorLoaded }"
    this.codemirrorLoaded = function(_editor) {
      //assign the editor to a variable on this object for future reference
      self.codemirrorEditor = _editor;
      //Set the width,height of the editor. Code mirror needs an explicit width/height
      _editor.setSize(700, 25);

      //disable users ability to add new lines.  The Formula bar is only 1 line
      _editor.on("beforeChange", function(instance, change) {
        var newtext = change.text.join("").replace(/\n/g, ""); // remove ALL \n !
        change.update(change.from, change.to, [newtext]);
        return true;
      });

      //hide the scrollbar
      _editor.on("change", function(instance, change) {
        //$(".CodeMirror-hscrollbar").css('display', 'none');
      });
      //set the flag to be loaded and then call out to update Autocomplete options
      self.codemirroLoaded = true;
      self.updateCodeMirrorAutoComplete();
    };

    /**
     * Creates a Tern server.
     */
    function createTernServer() {
      $http.get('js/vendor/tern/defs/tableFunctions.json').success(function(code) {
        self.sparkShellService.setFunctionDefs(code);

        self.ternServer = new CodeMirror.TernServer({defs: [code]});
        self.ternServer.server.addDefs(self.sparkShellService.getColumnDefs());

        var _editor = self.codemirrorEditor;
        _editor.setOption("extraKeys", {
          "Ctrl-Space": function(cm) {
            self.ternServer.complete(cm);
          },
          "Ctrl-I": function(cm) {
            self.ternServer.showType(cm);
          },
          "Ctrl-O": function(cm) {
            self.ternServer.showDocs(cm);
          },
          "Alt-.": function(cm) {
            self.ternServer.jumpToDef(cm);
          },
          "Alt-,": function(cm) {
            self.ternServer.jumpBack(cm);
          },
          "Ctrl-Q": function(cm) {
            self.ternServer.rename(cm);
          },
          "Ctrl-.": function(cm) {
            self.ternServer.selectName(cm);
          }
        });
        _editor.on("blur", function() {
          self.ternServer.hideDoc();
        });
        _editor.on("cursorActivity", self.showHint);
        _editor.on("focus", self.showHint);
      });
    }

    /**
     * Setup the CodeMirror and Tern Server autocomplete. This will only execute when both Hive and Code Mirror are fully
     * initialized.
     */
    this.updateCodeMirrorAutoComplete = function() {
      if (self.codemirroLoaded && self.hiveDataLoaded) {
        if (self.ternServer === null) {
          createTernServer();
        } else {
          var defs = self.sparkShellService.getColumnDefs();
          self.ternServer.server.deleteDefs(defs["!name"]);
          self.ternServer.server.addDefs(defs);
        }
      }
    };

    /**
     * Makes an asynchronous request to get the list of completions available at the cursor.
     *
     * @param {CodeMirror|CodeMirror.Doc} cm the code mirror instance
     * @param {Function} callback the callback function
     */
    this.getHint = function(cm, callback) {
      self.ternServer.getHint(cm, function(data) {
        // Complete function calls so arg hints can be displayed
        CodeMirror.on(data, "pick", function(completion) {
          if (completion.data.type.substr(0, 3) === "fn(") {
            var cursor = cm.getCursor();
            cm.replaceRange("(", cursor, cursor, "complete");
          }
        });

        // Display hints
        callback(data);
      });
    };
    this.getHint.async = true;

    /**
     * Shows either argument hints or identifier hints depending on the context.
     *
     * @param {CodeMirror|CodeMirror.Doc} cm the code mirror instance
     */
    this.showHint = function(cm) {
      // Show args if in a function
      var cursor = cm.getCursor();
      var token = cm.getTokenAt(cursor);
      var lexer = token.state.lexical;

      if (lexer.info === "call" && token.type !== "variable") {
        self.ternServer.updateArgHints(cm);
      } else {
        self.ternServer.hideDoc();
      }

      // Show completions if available
      if (cursor.ch === 0 || token.type === "variable" || (token.string === "." && lexer.type === "stat")) {
        cm.showHint({
          completeSingle: false,
          hint: self.getHint
        });
      }
    };

    /**
     * Query Hive using the query from the previous step. Set the Grids rows and columns
     */
    this.query = function() {
      //flag to indicate query is running
      this.executingQuery = true;

      return self.sparkShellService.transform().then(function(response) {
        //mark the query as finished
        self.executingQuery = false;
        //transform the result to the agGrid model
        var result = HiveService.transformQueryResultsToUiGridModel({data: response.data.results});
        //store the result for use in the commands
        self.tableData = result;
        //update the ag-grid
        self.gridOptions.columnDefs = result.columns;
        self.gridOptions.data = result.rows;
        //mark the flag to indicate Hive is loaded
        self.hiveDataLoaded = true;
        self.updateCodeMirrorAutoComplete();

        //Initialize the Command function holder
        self.functionCommandHolder = TableDataFunctions.newCommandHolder({rows: result.rows, columns: result.columns});
      });
    };

    function updateGrid(tableData) {
      self.gridOptions.columnDefs = tableData.columns;
      self.gridOptions.data = tableData.rows;
    }

    /**
     * Called when the user clicks Add on the function bar
     */
    this.onAddFunction = function() {
      var tableData = self.functionCommandHolder.executeStr(self.currentFormula);
      if (tableData != null && tableData != undefined) {
        updateGrid(tableData);
        self.functionHistory.push(self.currentFormula);

        self.ternServer.server.addFile("[doc]", self.currentFormula);
        var file = self.ternServer.server.findFile("[doc]");
        self.sparkShellService.push(file.ast);
        self.query();
      }
    };

    //reference to the last command that was undone
    var lastUndo = '';

    this.onUndo = function() {
      var tableData = self.functionCommandHolder.undo();
      updateGrid(tableData);
      lastUndo = self.functionHistory.pop();
    };
    this.onRedo = function() {
      var tableData = self.functionCommandHolder.redo();
      updateGrid(tableData);
      self.functionHistory.push(lastUndo);
    };

    this.canUndo = function() {
      if (self.functionCommandHolder) {
        return self.functionCommandHolder.canUndo();
      } else {
        return false;
      }
    };
    this.canRedo = function() {
      if (self.functionCommandHolder) {
        return self.functionCommandHolder.canRedo();
      } else {
        return false;
      }
    };

    //Hide the left side nav bar
    SideNavService.hideSideNav();

    this.query();

    $scope.$on('$destroy', function() {
      //clean up code here
    });
  };

  angular.module(MODULE_FEED_MGR).controller('VisualQueryTransformController', controller);
  angular.module(MODULE_FEED_MGR)
      .directive('thinkbigVisualQueryTransform', directive);
})();
<|endoftext|>


<commit_before>'use strict';

let cli = require('heroku-cli-util');

module.exports = {
  topic: 'pipelines',
  command: 'list',
  description: 'list pipelines',
  default: true,
  help: 'list pipelines you have access to',
  needsAuth: true,
  run: cli.command(function* (context, heroku) {
    let pipelines = yield heroku.request({
      method: 'GET',
      path: "/pipelines",
      headers: { 'Accept': 'application/vnd.heroku+json; version=3.pipelines' }
    }); // heroku.pipelines().list();
    cli.hush(pipelines);
    for (var pipeline in pipelines) {
      cli.log(`${pipelines[pipeline].name}`);
    }
  })
};
<commit_msg>Remove extraneous hush<commit_after>'use strict';

let cli = require('heroku-cli-util');

module.exports = {
  topic: 'pipelines',
  command: 'list',
  description: 'list pipelines',
  default: true,
  help: 'list pipelines you have access to',
  needsAuth: true,
  run: cli.command(function* (context, heroku) {
    let pipelines = yield heroku.request({
      method: 'GET',
      path: "/pipelines",
      headers: { 'Accept': 'application/vnd.heroku+json; version=3.pipelines' }
    }); // heroku.pipelines().list();
    for (var pipeline in pipelines) {
      cli.log(`${pipelines[pipeline].name}`);
    }
  })
};
<|endoftext|>


<commit_before>/*
 eslint no-param-reassign: ["error", { "props": true, "ignorePropertyModificationsFor": ["state"] }]
 */

import Vue from 'vue';

const search = {
  namespaced: true,
  state: {
    processing: false,
    results: null,
    errors: null,
    searchParameters: {
      page: 1,
    },
    language: null,
  },
  mutations: {
    updateResults(state, results, errors) {
      state.results = results;
      state.errors = errors;
    },
    updateSearchParameters(state, changedParameters) {
      state.searchParameters = Object.assign(state.searchParameters, changedParameters);
    },
    startProcessing(state) {
      state.processing = true;
    },
    endProcessing(state) {
      state.processing = false;
    },
    setPage(state, page) {
      state.searchParameters.page = page;
    },
    previousPage(state) {
      state.searchParameters.page -= 1;
    },
    nextPage(state) {
      state.searchParameters.page += 1;
    },
    setLanguage(state, language) {
      state.language = language;
    },
    setPublicationYears(state, yearList) {
      state.searchParameters.publication_year = yearList;
    },
    setDataSets(state, dataSetList) {
      state.searchParameters.dataset = dataSetList;
    },
    setLatestOnly(state, truthValue) {
      if (truthValue) {
        state.searchParameters.is_latest = truthValue;
      } else {
        delete state.searchParameters.is_latest;
      }
    },
    reset(state) {
      state.processing = false;
      state.results = null;
      state.errors = null;
      state.searchParameters = {
        page: 1,
      };
    },
  },
  actions: {
    search({ state, commit, getters }) {
      const defaultSearchParameters = {
        page_size: getters.pageSize,
        language: getters.getUserLanguage,
      };
      const queryParameters = Object.assign(
        state.searchParameters,
        defaultSearchParameters,
      );
      if (!queryParameters.search) {
        return;
      }
      commit('updateResults', null, null);
      const loadingTimer = setTimeout(() => commit('startProcessing'), 150);
      Vue.http.get('/api/search/{?publication_year,dataset}', { params: queryParameters }, {
        before(request) {
          if (this.previousRequest) {
            this.previousRequest.abort();
          }
          this.previousRequest = request;
        },
      }).then((response) => {
        commit('updateResults', response.body, null);
      }, (response) => {
        commit('updateResults', null, response.body.detail);
      }).then(() => {
        clearTimeout(loadingTimer);
        commit('endProcessing');
      });
    },
  },
  getters: {
    pageSize() {
      // return default size
      return 10;
    },
    maxPage(state, getters) {
      return Math.floor(state.results.count / getters.pageSize);
    },
    hasNextPage(state, getters) {
      return (state.searchParameters.page) < getters.maxPage;
    },
    hasPreviousPage(state) {
      return state.searchParameters.page > 1;
    },
    currentPage(state) {
      return state.searchParameters.page;
    },
    resultsTotal(state) {
      return state.results.count;
    },
    showingResultsFromToText(state, getters) {
      const totalResults = getters.resultsTotal;
      const previousPage = getters.currentPage - 1;
      const itemsPerPage = getters.pageSize;
      const itemsNumberStart = (previousPage * itemsPerPage) + 1;
      let itemsNumberEnd = getters.pageSize * getters.currentPage;
      if (!getters.hasNextPage) {
        itemsNumberEnd = totalResults;
      }
      return `Showing ${itemsNumberStart}-${itemsNumberEnd} of
      total ${totalResults} results.`;
    },
    getUserLanguage(state, getters) {
      return state.language || getters.getDefaultUserLanguage;
    },
    getDefaultUserLanguage() {
      let userLanguage;
      if (navigator.languages) {
        userLanguage = navigator.languages[0];
      } else {
        userLanguage = navigator.language || navigator.userLanguage;
      }
      if (userLanguage.includes('en')) {
        userLanguage = 'en';
      }
      if (userLanguage.includes('de')) {
        userLanguage = 'de';
      }
      if (userLanguage.includes('fr')) {
        userLanguage = 'fr';
      }
      return userLanguage || 'en';
    },
    getChoices(state) {
      return state.results.result_choices;
    },
  },
};
export { search as default };
<commit_msg>off by one pagination corrected<commit_after>/*
 eslint no-param-reassign: ["error", { "props": true, "ignorePropertyModificationsFor": ["state"] }]
 */

import Vue from 'vue';

const search = {
  namespaced: true,
  state: {
    processing: false,
    results: null,
    errors: null,
    searchParameters: {
      page: 1,
    },
    language: null,
  },
  mutations: {
    updateResults(state, results, errors) {
      state.results = results;
      state.errors = errors;
    },
    updateSearchParameters(state, changedParameters) {
      state.searchParameters = Object.assign(state.searchParameters, changedParameters);
    },
    startProcessing(state) {
      state.processing = true;
    },
    endProcessing(state) {
      state.processing = false;
    },
    setPage(state, page) {
      state.searchParameters.page = page;
    },
    previousPage(state) {
      state.searchParameters.page -= 1;
    },
    nextPage(state) {
      state.searchParameters.page += 1;
    },
    setLanguage(state, language) {
      state.language = language;
    },
    setPublicationYears(state, yearList) {
      state.searchParameters.publication_year = yearList;
    },
    setDataSets(state, dataSetList) {
      state.searchParameters.dataset = dataSetList;
    },
    setLatestOnly(state, truthValue) {
      if (truthValue) {
        state.searchParameters.is_latest = truthValue;
      } else {
        delete state.searchParameters.is_latest;
      }
    },
    reset(state) {
      state.processing = false;
      state.results = null;
      state.errors = null;
      state.searchParameters = {
        page: 1,
      };
    },
  },
  actions: {
    search({ state, commit, getters }) {
      const defaultSearchParameters = {
        page_size: getters.pageSize,
        language: getters.getUserLanguage,
      };
      const queryParameters = Object.assign(
        state.searchParameters,
        defaultSearchParameters,
      );
      if (!queryParameters.search) {
        return;
      }
      commit('updateResults', null, null);
      const loadingTimer = setTimeout(() => commit('startProcessing'), 150);
      Vue.http.get('/api/search/{?publication_year,dataset}', { params: queryParameters }, {
        before(request) {
          if (this.previousRequest) {
            this.previousRequest.abort();
          }
          this.previousRequest = request;
        },
      }).then((response) => {
        commit('updateResults', response.body, null);
      }, (response) => {
        commit('updateResults', null, response.body.detail);
      }).then(() => {
        clearTimeout(loadingTimer);
        commit('endProcessing');
      });
    },
  },
  getters: {
    pageSize() {
      // return default size
      return 10;
    },
    maxPage(state, getters) {
      return Math.ceil(state.results.count / getters.pageSize);
    },
    hasNextPage(state, getters) {
      return (state.searchParameters.page) < getters.maxPage;
    },
    hasPreviousPage(state) {
      return state.searchParameters.page > 1;
    },
    currentPage(state) {
      return state.searchParameters.page;
    },
    resultsTotal(state) {
      return state.results.count;
    },
    showingResultsFromToText(state, getters) {
      const totalResults = getters.resultsTotal;
      const previousPage = getters.currentPage - 1;
      const itemsPerPage = getters.pageSize;
      const itemsNumberStart = (previousPage * itemsPerPage) + 1;
      let itemsNumberEnd = getters.pageSize * getters.currentPage;
      if (!getters.hasNextPage) {
        itemsNumberEnd = totalResults;
      }
      return `Showing ${itemsNumberStart}-${itemsNumberEnd} of
      total ${totalResults} results.`;
    },
    getUserLanguage(state, getters) {
      return state.language || getters.getDefaultUserLanguage;
    },
    getDefaultUserLanguage() {
      let userLanguage;
      if (navigator.languages) {
        userLanguage = navigator.languages[0];
      } else {
        userLanguage = navigator.language || navigator.userLanguage;
      }
      if (userLanguage.includes('en')) {
        userLanguage = 'en';
      }
      if (userLanguage.includes('de')) {
        userLanguage = 'de';
      }
      if (userLanguage.includes('fr')) {
        userLanguage = 'fr';
      }
      return userLanguage || 'en';
    },
    getChoices(state) {
      return state.results.result_choices;
    },
  },
};
export { search as default };
<|endoftext|>