<commit_before>/* eslint-env browser */

window.mathquill4quill = function(dependencies) {
  dependencies = dependencies || {};

  var Quill = dependencies.Quill || window.Quill;
  var MathQuill = dependencies.MathQuill || window.MathQuill;
  var katex = dependencies.katex || window.katex;

  function insertAfter(newNode, referenceNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
  }

  function areAllDependenciesMet(quill) {
    if (!Quill) {
      console.log("Quill.js not loaded"); // eslint-disable-line no-console
      return false;
    }

    if (!MathQuill) {
      console.log("MathQuill.js not loaded"); // eslint-disable-line no-console
      return false;
    }

    if (!katex) {
      console.log("katex.js not loaded"); // eslint-disable-line no-console
      return false;
    }

    if (!quill.options.modules.formula) {
      console.log("Formula module not enabled"); // eslint-disable-line no-console
      return false;
    }

    return true;
  }

  function applyInputStyles(mqInput) {
    mqInput.style.border = "1px solid #ccc";
    mqInput.style.fontSize = "13px";
    mqInput.style.minHeight = "26px";
    mqInput.style.margin = "0px";
    mqInput.style.padding = "3px 5px";
    mqInput.style.width = "170px";
  }

  function applyOperatorButtonStyles(button) {
    button.style.margin = "5px";
    button.style.width = "50px";
    button.style.height = "50px";
    button.style.backgroundColor = "#ffffff";
    button.style.borderColor = "#000000";
    button.style.borderRadius = "7px";
    button.style.borderWidth = "2px";
  }

  function createOperatorButton(displayOperator, operator, mqField) {
    var button = document.createElement("button");
    katex.render(displayOperator, button, {
      throwOnError: false
    });
    button.onclick = function() {
      mqField.cmd(operator);
      mqField.focus();
    };
    applyOperatorButtonStyles(button);
    return button;
  }

  function createOperatorButtons(operators, tooltip, mqField) {
    var container = document.createElement("div");
    operators.forEach(function(element) {
      container.appendChild(
        createOperatorButton(element[0], element[1], mqField)
      );
    });

    if (operators.length > 0) {
      tooltip.appendChild(container);
    }

    return {
      display: function(show) {
        if (show) {
          container.style.display = "flex";
          container.style.alignItems = "center";
        } else {
          container.style.display = "none";
        }
      }
    };
  }

  function enableMathQuillFormulaAuthoring(quill, options) {
    if (!areAllDependenciesMet(quill)) {
      return;
    }

    options = options || {};
    options.operators = options.operators || [];

    var tooltip = quill.container.getElementsByClassName("ql-tooltip")[0];
    var latexInput = tooltip.getElementsByTagName("input")[0];
    var formulaButton = document.getElementsByClassName("ql-formula")[0];

    // replace LaTeX formula input with MathQuill input
    var mqInput = document.createElement("span");
    applyInputStyles(mqInput);
    insertAfter(mqInput, latexInput);
    latexInput.setAttribute(
      "style",
      "visibility:hidden;padding:0px;border:0px;width:0px;"
    );

    // synchronize MathQuill input and LaTeX formula input
    var mqField = MathQuill.getInterface(2).MathField(mqInput, {
      handlers: {
        edit: function() {
          latexInput.value = mqField.latex();
        }
      }
    });

    var operatorButtons = createOperatorButtons(
      options.operators,
      tooltip,
      mqField
    );

    var observer = new MutationObserver(function() {
      var isFormula = tooltip.attributes["data-mode"].value === "formula";

      // hide operator buttons on non-formula tooltips
      operatorButtons.display(isFormula);

      // hide math on non-formula tooltips
      if (!isFormula) {
        mqField.latex("");
      }
    });

    observer.observe(tooltip, {
      attributes: true,
      attributeFilter: ["data-mode"]
    });

    formulaButton.onclick = function() {
      // set focus to formula editor when it is opened
      window.setTimeout(function() {
        mqField.focus();
      }, 1);
    };
  }

  return enableMathQuillFormulaAuthoring;
};

// for backwards compatibility with prototype-based API
if (window.Quill) {
  window.Quill.prototype.enableMathQuillFormulaAuthoring = function(options) {
    window.mathquill4quill()(this, options);
  };
}
<commit_msg>Encapsulate all operator button functions<commit_after>/* eslint-env browser */

window.mathquill4quill = function(dependencies) {
  dependencies = dependencies || {};

  var Quill = dependencies.Quill || window.Quill;
  var MathQuill = dependencies.MathQuill || window.MathQuill;
  var katex = dependencies.katex || window.katex;

  function insertAfter(newNode, referenceNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
  }

  function areAllDependenciesMet(quill) {
    if (!Quill) {
      console.log("Quill.js not loaded"); // eslint-disable-line no-console
      return false;
    }

    if (!MathQuill) {
      console.log("MathQuill.js not loaded"); // eslint-disable-line no-console
      return false;
    }

    if (!katex) {
      console.log("katex.js not loaded"); // eslint-disable-line no-console
      return false;
    }

    if (!quill.options.modules.formula) {
      console.log("Formula module not enabled"); // eslint-disable-line no-console
      return false;
    }

    return true;
  }

  function applyInputStyles(mqInput) {
    mqInput.style.border = "1px solid #ccc";
    mqInput.style.fontSize = "13px";
    mqInput.style.minHeight = "26px";
    mqInput.style.margin = "0px";
    mqInput.style.padding = "3px 5px";
    mqInput.style.width = "170px";
  }

  function createOperatorButtons(operators, tooltip, mqField) {
    function applyOperatorButtonStyles(button) {
      button.style.margin = "5px";
      button.style.width = "50px";
      button.style.height = "50px";
      button.style.backgroundColor = "#ffffff";
      button.style.borderColor = "#000000";
      button.style.borderRadius = "7px";
      button.style.borderWidth = "2px";
    }

    function createOperatorButton(element) {
      var displayOperator = element[0];
      var operator = element[1];

      var button = document.createElement("button");
      katex.render(displayOperator, button, {
        throwOnError: false
      });
      button.onclick = function() {
        mqField.cmd(operator);
        mqField.focus();
      };
      applyOperatorButtonStyles(button);
      return button;
    }

    var container = document.createElement("div");
    operators.forEach(function(element) {
      container.appendChild(createOperatorButton(element));
    });

    if (operators.length > 0) {
      tooltip.appendChild(container);
    }

    return {
      display: function(show) {
        if (show) {
          container.style.display = "flex";
          container.style.alignItems = "center";
        } else {
          container.style.display = "none";
        }
      }
    };
  }

  function enableMathQuillFormulaAuthoring(quill, options) {
    if (!areAllDependenciesMet(quill)) {
      return;
    }

    options = options || {};
    options.operators = options.operators || [];

    var tooltip = quill.container.getElementsByClassName("ql-tooltip")[0];
    var latexInput = tooltip.getElementsByTagName("input")[0];
    var formulaButton = document.getElementsByClassName("ql-formula")[0];

    // replace LaTeX formula input with MathQuill input
    var mqInput = document.createElement("span");
    applyInputStyles(mqInput);
    insertAfter(mqInput, latexInput);
    latexInput.setAttribute(
      "style",
      "visibility:hidden;padding:0px;border:0px;width:0px;"
    );

    // synchronize MathQuill input and LaTeX formula input
    var mqField = MathQuill.getInterface(2).MathField(mqInput, {
      handlers: {
        edit: function() {
          latexInput.value = mqField.latex();
        }
      }
    });

    var operatorButtons = createOperatorButtons(
      options.operators,
      tooltip,
      mqField
    );

    var observer = new MutationObserver(function() {
      var isFormula = tooltip.attributes["data-mode"].value === "formula";

      // hide operator buttons on non-formula tooltips
      operatorButtons.display(isFormula);

      // hide math on non-formula tooltips
      if (!isFormula) {
        mqField.latex("");
      }
    });

    observer.observe(tooltip, {
      attributes: true,
      attributeFilter: ["data-mode"]
    });

    formulaButton.onclick = function() {
      // set focus to formula editor when it is opened
      window.setTimeout(function() {
        mqField.focus();
      }, 1);
    };
  }

  return enableMathQuillFormulaAuthoring;
};

// for backwards compatibility with prototype-based API
if (window.Quill) {
  window.Quill.prototype.enableMathQuillFormulaAuthoring = function(options) {
    window.mathquill4quill()(this, options);
  };
}
<|endoftext|>


<commit_before>import { describe, beforeEach, it } from 'mocha';
import { expect } from 'chai';
import d3 from 'd3';

import { frequencies } from '../../lib/data';

const submission = global.submission;

const barWidth = 960 / 26;
const heightScale = d3.scale.linear()
    .domain([0, d3.max(frequencies, d => d.value)])
    .range([500, 0]);

describe('Part 3: Encoding ordinal data', () => {
    beforeEach('', () => {
        d3.select('.chart').remove();
        d3.select('body').append('svg').attr('class', 'chart');
    });

    it('should export a function', () => {
        expect(submission).to.be.a('function');
    });

    it('should have a container <svg> with a "chart" class inside the body', () => {
        submission(frequencies);
        expect(d3.select('body > svg.chart').size()).to.be.above(0);
    });

    it('should dimensions the container properly', () => {
        submission(frequencies);
        expect(parseInt(d3.select('.chart').attr('width'), 10)).to.equal(960);
        expect(parseInt(d3.select('.chart').attr('height'), 10)).to.equal(500);
    });

    it('should have 26 <g> bars inside the container .chart', () => {
        submission(frequencies);
        expect(d3.selectAll('.chart > g').size()).to.equal(26);
    });

    it('each bar should contain a <rect> and a <text>', () => {
        submission(frequencies);
        const bars = d3.selectAll('.chart > g')[0];

        bars.forEach((elt) => {
            expect(d3.select(elt).select('rect').size()).to.be.above(0);
            expect(d3.select(elt).select('text').size()).to.be.above(0);
        });
    });

    it('each bar should have a width that is not fixed', () => {
        submission(frequencies);
        const rects = d3.selectAll('rect')[0];

        rects.forEach((elt) => {
            const width = parseInt(elt.getAttribute('width'), 10);

            expect(width).to.not.equal(19);
        });
    });

    it('each bar should be positioned with a translate transform, according to its order', () => {
        submission(frequencies);
        const bars = d3.selectAll('.chart > g')[0];

        bars.forEach((elt, i) => {
            const transform = elt.getAttribute('transform');
            const positionX = parseFloat(transform.split('translate(')[1].split(',0)')[0]);

            expect(transform).to.be.a('string');
            expect(transform).to.contain('translate');
            expect(positionX).to.be.closeTo(i * barWidth, 0.05);
        });
    });

    it('each <text> should have the right value, according to its bound data', () => {
        submission(frequencies);
        const bars = d3.selectAll('.chart > g');

        bars.each((d, i) => {
            const bar = d3.select(bars[0][i]);
            const value = parseFloat(bar.text());

            expect(value).to.be.a('number');
            expect(value).to.equal(d.value);
        });
    });

    it('each <text> should be at the right position according to its bound data', () => {
        submission(frequencies);
        const bars = d3.selectAll('.chart > g');

        bars.each((d, i) => {
            const bar = d3.select(bars[0][i]);
            const text = bar.select('text');
            const x = parseFloat(text.attr('x'));
            const y = parseFloat(text.attr('y'));

            expect(x).to.equal(barWidth / 2);
            expect(y).to.be.closeTo(heightScale(d.value), 3);
        });
    });

    it('each <rect> should be of the right dimensions according to its bound data', () => {
        submission(frequencies);
        const bars = d3.selectAll('.chart > g');

        bars.each((d, i) => {
            const bar = d3.select(bars[0][i]);
            const rect = bar.select('rect');
            const width = parseFloat(rect.attr('width'));
            const height = parseFloat(rect.attr('height'));

            expect(width).to.be.closeTo(barWidth, 1);
            expect(height).to.be.closeTo(500 - heightScale(d.value), 5);
        });
    });
});
<commit_msg>Update tests for latest exercise<commit_after>import { describe, beforeEach, it } from 'mocha';
import { expect } from 'chai';
import d3 from 'd3';

import { frequencies } from '../../lib/data';

const submission = global.submission;

const heightScale = d3.scale.linear()
    .domain([0, d3.max(frequencies, d => d.value)])
    .range([500, 0]);

const widthScale = d3.scale.ordinal()
    .domain(frequencies.map(d => d.letter))
    .rangeRoundBands([0, 960], 0.1);

describe('Part 3: Encoding ordinal data', () => {
    beforeEach('', () => {
        d3.select('.chart').remove();
        d3.select('body').append('svg').attr('class', 'chart');
    });

    it('should export a function', () => {
        expect(submission).to.be.a('function');
    });

    it('should have a container <svg> with a "chart" class inside the body', () => {
        submission(frequencies);
        expect(d3.select('body > svg.chart').size()).to.be.above(0);
    });

    it('should dimensions the container properly', () => {
        submission(frequencies);
        expect(parseInt(d3.select('.chart').attr('width'), 10)).to.equal(960);
        expect(parseInt(d3.select('.chart').attr('height'), 10)).to.equal(500);
    });

    it('should have 26 <g> bars inside the container .chart', () => {
        submission(frequencies);
        expect(d3.selectAll('.chart > g').size()).to.equal(26);
    });

    it('each bar should contain a <rect> and a <text>', () => {
        submission(frequencies);
        const bars = d3.selectAll('.chart > g')[0];

        bars.forEach((elt) => {
            expect(d3.select(elt).select('rect').size()).to.be.above(0);
            expect(d3.select(elt).select('text').size()).to.be.above(0);
        });
    });

    it('each bar should have a width that is not fixed', () => {
        submission(frequencies);
        const rects = d3.selectAll('rect')[0];

        rects.forEach((elt) => {
            const width = parseInt(elt.getAttribute('width'), 10);

            expect(width).to.not.equal(19);
        });
    });

    it('each bar should be positioned with a translate transform, according an ordinal scale', () => {
        submission(frequencies);
        const bars = d3.selectAll('.chart > g');

        bars.each((d, i) => {
            const bar = d3.select(bars[0][i]);
            const transform = bar.attr('transform');
            const positionX = parseFloat(transform.split('translate(')[1].split(',0)')[0]);

            expect(transform).to.be.a('string');
            expect(transform).to.contain('translate');
            expect(positionX).to.be.closeTo(widthScale(d.letter), 1 + 0.05);
        });
    });

    it('each <text> should have the right value, according to its bound data', () => {
        submission(frequencies);
        const bars = d3.selectAll('.chart > g');

        bars.each((d, i) => {
            const bar = d3.select(bars[0][i]);
            const value = parseFloat(bar.text());

            expect(value).to.be.a('number');
            expect(value).to.equal(d.value);
        });
    });

    it('each <text> should be at the right position according to the scale\'s range band', () => {
        submission(frequencies);
        const bars = d3.selectAll('.chart > g');

        bars.each((d, i) => {
            const bar = d3.select(bars[0][i]);
            const text = bar.select('text');
            const x = parseFloat(text.attr('x'));
            const y = parseFloat(text.attr('y'));

            expect(x).to.be.closeTo(widthScale.rangeBand() / 2, 1);
            expect(y).to.be.closeTo(heightScale(d.value), 3);
        });
    });

    it('each <rect> should be of the right dimensions according to its bound data and the scale', () => {
        submission(frequencies);
        const bars = d3.selectAll('.chart > g');

        bars.each((d, i) => {
            const bar = d3.select(bars[0][i]);
            const rect = bar.select('rect');
            const width = parseFloat(rect.attr('width'));
            const height = parseFloat(rect.attr('height'));

            expect(width).to.be.closeTo(widthScale.rangeBand(), 1);
            expect(height).to.be.closeTo(500 - heightScale(d.value), 5);
        });
    });
});
<|endoftext|>


<commit_before>module.exports = {
  randomNormal: function() {
    var result;
    if ("randomNormalCache" in this) {
      result = this.randomNormalCache;
      delete this.randomNormalCache;
    }
    else {
      var x1, x2, w;
      do {
        x1 = 2.0 * Math.random() - 1.0;
        x2 = 2.0 * Math.random() - 1.0;
        w = x1 * x1 + x2 * x2;
      } while (w >= 1.0);
      w = Math.sqrt( (-2.0 * Math.log(w)) / w );
      result = x1 * w;
      this.randomNormalCache = x2 * w;
    }
    return result;
  },

  randomCovariance: function (n) {
    var N = [];
    for (var i=0; i<n; ++i)
      N.push(this.randomNormal());
    var M = [];
    for (var i=0; i<n; ++i) {
      M[i] = [];
      for (var j=0; j<n; ++j)
        M[i][j] = N[i] * N[j];
    }
    return M;
  },

  randomCorrelation: function (n) {
    var M = this.randomCovariance(n);

    var s = [];
    for (var i=0; i<n; ++i)
      s.push(1.0/Math.sqrt(M[i][i]));

    for (var i=0; i<n; ++i)
      for (var j=0; j<n; ++j)
        M[i][j] *= s[i] * s[j];
    return M;
  },

  cholesky: function (A) {
    var n = A.length;

    var L = [];
    for (var i=0; i<n; ++i) {
      L[i] = [];
      for (var j=0; j<n; ++j)
        L[i].push(0.0);
    }

    for (var i=0; i<n; ++i) {
      for (var j=0; j<(i+1); ++j ) {
        var s = 0.0;
        for (var k=0; k<j; ++k)
          s += L[i][k] * L[j][k];
        if (i == j)
          L[i][j] = Math.sqrt(A[i][i]-s);
        else
          L[i][j] = 1.0/L[j][j]*(A[i][j]-s);
      }
    }
    return L;
  }
};
<commit_msg>Generation of random correlation matrices<commit_after>module.exports = {
  randomNormal: function() {
    var result;
    if ("randomNormalCache" in this) {
      result = this.randomNormalCache;
      delete this.randomNormalCache;
    }
    else {
      var x1, x2, w;
      do {
        x1 = 2.0 * Math.random() - 1.0;
        x2 = 2.0 * Math.random() - 1.0;
        w = x1 * x1 + x2 * x2;
      } while (w >= 1.0);
      w = Math.sqrt( (-2.0 * Math.log(w)) / w );
      result = x1 * w;
      this.randomNormalCache = x2 * w;
    }
    return result;
  },

  mat: {
    zero: function (rows, cols) {
      var M = [];
      for (var i=0; i<rows; ++i) {
        M[i] = [];
        for (var j=0; j<cols; ++j)
          M[i][j] = 0.0;
      }
      return M;
    },

    mul: function (M, N) {
      var R = [];
      for (var i=0; i<M.length; ++i) {
        if (M[i].length != N.length)
          throw "bad matricies";
        R[i] = [];
        for (var j=0; j<N[0].length; ++j) {
          var sum = 0;
          for (var k=0; k<N.length; ++k)
            sum += M[i][k] * N[k][j];
          R[i][j] = sum;
        }
      }
      return R;
    },

    trans: function (M) {
      var R = [];
      for (var i=0; i<M[0].length; ++i) {
        R[i] = [];
        for (var j=0; j<M.length; ++j) {
          R[i][j] = M[j][i];
        }
      }
      return R;
    }
  },

  randomCorrelation: function (n) {
    var T = [];

    // Generate n uniform random columns
    for (var i=0; i<n; ++i) {
      T[i] = [];
      for (var j=0; j<n; ++j) {
        T[i][j] = this.randomNormal();
      }
    }

    // Normalize the columns
    for (var j=0; j<n; ++j) {
      var sqSum = 0;
      for (var i=0; i<n; ++i)
        sqSum += T[i][j] * T[i][j];
      var norm = Math.sqrt(sqSum);
      for (var i=0; i<n; ++i)
        T[i][j] /= norm;
    }

    // result is T'*T
    return this.mat.mul(this.mat.trans(T), T);
  },

  cholesky: function (A) {
    var n = A.length;

    var L = this.mat.zero(n, n);
    for (var i=0; i<n; ++i) {
      for (var j=0; j<(i+1); ++j ) {
        var s = 0.0;
        for (var k=0; k<j; ++k)
          s += L[i][k] * L[j][k];
        if (i == j)
          L[i][i] = Math.sqrt(A[i][i]-s);
        else
          L[i][j] = 1.0/L[j][j]*(A[i][j]-s);
      }
    }
    return this.mat.trans(L);
  }
};
<|endoftext|>


<commit_before>$('#song_content').on('mouseover', '.chord', function() {
    $(this).children('img').css('visibility', 'visible');
})

$('#song_content').on('mouseout', '.chord', function() {
    $(this).children('img').css('visibility', 'hidden');
})

$('#hide_chords').click(function() {
    $('.chordline').toggle();
    $('#hide_chords').text(
        $('#hide_chords').text() == 'Hide chords' ? 'Show chords' : 'Hide chords');
})

$('#semiton_change').change(function() {
    var semitonsMove = parseInt($(this).find(':selected').text(), 10);
    $('.chord').each(function() {
        //changeSemiton($(this), semitonsMove);
        $(this).text(changeSemiton($(this).attr('origchord'), semitonsMove));
    });
})

/**
 * Return the given chord, changed by semitonsMove semitons.
 *
 * @param {String} chord a string representing a chord, eg. "A#5"
 * @param {Number} semitonsMove an integer from -5 to 6
 * @return {String} the changed chord
 */
function changeSemiton(chord, semitonsMove) {
    var semitons = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
    var regex = /([A-G][#b]?)((maj|m|aug|dim|sus)?[245679]?)/;

    var match = regex.exec(chord);
    var origSemiton = match[1];
    var restChord = match[2];

    var index = semitons.indexOf(origSemiton) + semitonsMove;
    if (index >= semitons.length)
        index = index % semitons.length;
    else if (index < 0)
        index = semitons.length + index;

    return semitons[index] + restChord;
}

/**
 * Each chord must be enclosed in a span tag of class "chord", and an
 * appropriate image must be assigned to it. Additionally, each line of
 * song content containing chords should be enclosed in div tags of class
 * "chordline"".
 */
function parseSong() {
    var content = $("#song_content");
    var result = content.html().replace(
        /([A-G][#b]?(maj|m|aug|dim|sus)?[245679]?)/g,
        '$1'
    );

    var lines = result.split('\n');
    var newlines = "";

    for (i = 0; i < lines.length; i++) {
        if (lines[i].indexOf('') != -1)
            newlines += '
' + lines[i] + '
';
        else
            newlines += lines[i] + "\n";
    }
    content.html(newlines);
}

/**
 * Fills the semiton_change select object, with the values from -5 to 6
 * followed by the base chord of the song at the specific semiton.
 *
 * eg. -1 (D), 0 (D#), +1 (E)
 */
function fillSemitonChange() {
    var songBase = $('.chord').first().attr('origchord');
    for (i = 6; i >= -5; i--) {
        if (i != 0) {
            $('#semiton_change')
                .append($('<option></option>')
                .text((i>0 ? '+' : '') + i + ' (' + changeSemiton(songBase, i) + ')'));
        } else {
            $('#semiton_change')
                .append($('<option></option>')
                .attr('selected', 'selected')
                .text(i + ' (' + changeSemiton(songBase, i) + ')'));
        }
    }
}

$().ready(function() {
    parseSong();
    fillSemitonChange();
});
<commit_msg>fix a bug with show/hide chords<commit_after>$('#song_content').on('mouseover', '.chord', function() {
    $(this).children('img').css('visibility', 'visible');
})

$('#song_content').on('mouseout', '.chord', function() {
    $(this).children('img').css('visibility', 'hidden');
})

$('#hide_chords').click(function() {
    $('.chordline').toggle();
    $('#hide_chords').text(
        $('#hide_chords').text() == 'Hide chords' ? 'Show chords' : 'Hide chords');
})

$('#semiton_change').change(function() {
    var semitonsMove = parseInt($(this).find(':selected').text(), 10);
    $('.chord').each(function() {
        //changeSemiton($(this), semitonsMove);
        $(this).text(changeSemiton($(this).attr('origchord'), semitonsMove));
    });
})

/**
 * Return the given chord, changed by semitonsMove semitons.
 *
 * @param {String} chord a string representing a chord, eg. "A#5"
 * @param {Number} semitonsMove an integer from -5 to 6
 * @return {String} the changed chord
 */
function changeSemiton(chord, semitonsMove) {
    var semitons = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
    var regex = /([A-G][#b]?)((maj|m|aug|dim|sus)?[245679]?)/;

    var match = regex.exec(chord);
    var origSemiton = match[1];
    var restChord = match[2];

    var index = semitons.indexOf(origSemiton) + semitonsMove;
    if (index >= semitons.length)
        index = index % semitons.length;
    else if (index < 0)
        index = semitons.length + index;

    return semitons[index] + restChord;
}

/**
 * Each chord must be enclosed in a span tag of class "chord", and an
 * appropriate image must be assigned to it. Additionally, each line of
 * song content containing chords should be enclosed in div tags of class
 * "chordline"".
 */
function parseSong() {
    var content = $("#song_content");
    var result = content.html().replace(
        /([A-G][#b]?(maj|m|aug|dim|sus)?[245679]?)/g,
        '$1'
    );

    var lines = result.split('\n');
    var newlines = "";

    for (i = 0; i < lines.length; i++) {
        if (lines[i].indexOf('= -5; i--) {
        if (i != 0) {
            $('#semiton_change')
                .append($('<option></option>')
                .text((i>0 ? '+' : '') + i + ' (' + changeSemiton(songBase, i) + ')'));
        } else {
            $('#semiton_change')
                .append($('<option></option>')
                .attr('selected', 'selected')
                .text(i + ' (' + changeSemiton(songBase, i) + ')'));
        }
    }
}

$().ready(function() {
    parseSong();
    fillSemitonChange();
});
<|endoftext|>


<commit_before><commit_msg>add tool symbol on dataset<commit_after><|endoftext|>


<commit_before>import * as math from '../../../math';

let CRp = {};

CRp.drawElement = function( context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity ){
  let r = this;

  if( ele.isNode() ){
    r.drawNode( context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity );
  } else {
    r.drawEdge( context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity );
  }
};

CRp.drawElementOverlay = function( context, ele ){
  let r = this;

  if( ele.isNode() ){
    r.drawNodeOverlay( context, ele );
  } else {
    r.drawEdgeOverlay( context, ele );
  }
};

CRp.drawCachedElementPortion = function( context, ele, eleTxrCache, pxRatio, lvl, reason, getRotation ){
  let r = this;
  let bb = eleTxrCache.getBoundingBox(ele);

  if( bb.w === 0 || bb.h === 0 ){ return; } // ignore zero size case

  let eleCache = eleTxrCache.getElement( ele, bb, pxRatio, lvl, reason );

  if( eleCache != null ){
    let opacity = ele.pstyle('opacity').pfValue;

    if( opacity === 0 ){ return; }

    let theta = getRotation(r, ele);
    let { x1, y1, w, h } = bb;
    let x, y, sx, sy, smooth;

    if( theta !== 0 ){
      let rotPt = eleTxrCache.getRotationPoint(ele);

      sx = rotPt.x;
      sy = rotPt.y;

      context.translate(sx, sy);
      context.rotate(theta);

      smooth = r.getImgSmoothing(context);

      if( !smooth ){ r.setImgSmoothing(context, true); }

      let off = eleTxrCache.getRotationOffset(ele);

      x = off.x;
      y = off.y;
    } else {
      x = x1;
      y = y1;
    }

    let oldGlobalAlpha;

    if( opacity !== 1 ){
      oldGlobalAlpha = context.globalAlpha;
      context.globalAlpha = oldGlobalAlpha * opacity;
    }

    context.drawImage( eleCache.texture.canvas, eleCache.x, 0, eleCache.width, eleCache.height, x, y, w, h );

    if( opacity !== 1 ){
      context.globalAlpha = oldGlobalAlpha;
    }

    if( theta !== 0 ){
      context.rotate(-theta);
      context.translate(-sx, -sy);

      if( !smooth ){ r.setImgSmoothing(context, false); }
    }
  } else {
    eleTxrCache.drawElement( context, ele ); // direct draw fallback
  }
};

const getZeroRotation = () => 0;
const getLabelRotation = (r, ele) => r.getTextAngle(ele, null);
const getSourceLabelRotation = (r, ele) => r.getTextAngle(ele, 'source');
const getTargetLabelRotation = (r, ele) => r.getTextAngle(ele, 'target');

CRp.drawCachedElement = function( context, ele, pxRatio, extent, lvl, requestHighQuality ){
  let r = this;
  let { eleTxrCache, lblTxrCache, slbTxrCache, tlbTxrCache } = r.data;

  let bb = ele.boundingBox();
  let reason = requestHighQuality === true ? eleTxrCache.reasons.highQuality : null;

  if( bb.w === 0 || bb.h === 0 || !ele.visible() ){ return; }

  if( !extent || math.boundingBoxesIntersect( bb, extent ) ){
    r.drawCachedElementPortion( context, ele, eleTxrCache, pxRatio, lvl, reason, getZeroRotation );
    r.drawCachedElementPortion( context, ele, lblTxrCache, pxRatio, lvl, reason, getLabelRotation );

    if( ele.isEdge() ){
      r.drawCachedElementPortion( context, ele, slbTxrCache, pxRatio, lvl, reason, getSourceLabelRotation );
      r.drawCachedElementPortion( context, ele, tlbTxrCache, pxRatio, lvl, reason, getTargetLabelRotation );
    }

    r.drawElementOverlay( context, ele );
  }
};

CRp.drawElements = function( context, eles ){
  let r = this;

  for( let i = 0; i < eles.length; i++ ){
    let ele = eles[ i ];

    r.drawElement( context, ele );
  }
};

CRp.drawCachedElements = function( context, eles, pxRatio, extent ){
  let r = this;

  for( let i = 0; i < eles.length; i++ ){
    let ele = eles[ i ];

    r.drawCachedElement( context, ele, pxRatio, extent );
  }
};

CRp.drawCachedNodes = function( context, eles, pxRatio, extent ){
  let r = this;

  for( let i = 0; i < eles.length; i++ ){
    let ele = eles[ i ];

    if( !ele.isNode() ){ continue; }

    r.drawCachedElement( context, ele, pxRatio, extent );
  }
};

CRp.drawLayeredElements = function( context, eles, pxRatio, extent ){
  let r = this;

  let layers = r.data.lyrTxrCache.getLayers( eles, pxRatio );

  if( layers ){
    for( let i = 0; i < layers.length; i++ ){
      let layer = layers[i];
      let bb = layer.bb;

      if( bb.w === 0 || bb.h === 0 ){ continue; }

      context.drawImage( layer.canvas, bb.x1, bb.y1, bb.w, bb.h );
    }
  } else { // fall back on plain caching if no layers
    r.drawCachedElements( context, eles, pxRatio, extent );
  }
};

if( process.env.NODE_ENV !== 'production' ){
  CRp.drawDebugPoints = function( context, eles ){
    let draw = function( x, y, color ){
      context.fillStyle = color;
      context.fillRect( x - 1, y - 1, 3, 3 );
    };

    for( let i = 0; i < eles.length; i++ ){
      let ele = eles[i];
      let rs = ele._private.rscratch;

      if( ele.isNode() ){
        let p = ele.position();

        draw( p.x, p.y, 'magenta' );
      } else {
        let pts = rs.allpts;

        for( let j = 0; j + 1 < pts.length; j += 2 ){
          let x = pts[ j ];
          let y = pts[ j + 1 ];

          draw( x, y, 'cyan' );
        }

        draw( rs.midX, rs.midY, 'yellow' );
      }
    }
  };
}

export default CRp;
<commit_msg>The element texture cache should use the `effectiveOpacity()` rather than the raw style value<commit_after>import * as math from '../../../math';

let CRp = {};

CRp.drawElement = function( context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity ){
  let r = this;

  if( ele.isNode() ){
    r.drawNode( context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity );
  } else {
    r.drawEdge( context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity );
  }
};

CRp.drawElementOverlay = function( context, ele ){
  let r = this;

  if( ele.isNode() ){
    r.drawNodeOverlay( context, ele );
  } else {
    r.drawEdgeOverlay( context, ele );
  }
};

CRp.drawCachedElementPortion = function( context, ele, eleTxrCache, pxRatio, lvl, reason, getRotation ){
  let r = this;
  let bb = eleTxrCache.getBoundingBox(ele);

  if( bb.w === 0 || bb.h === 0 ){ return; } // ignore zero size case

  let eleCache = eleTxrCache.getElement( ele, bb, pxRatio, lvl, reason );

  if( eleCache != null ){
    let opacity = ele.effectiveOpacity();

    if( opacity === 0 ){ return; }

    let theta = getRotation(r, ele);
    let { x1, y1, w, h } = bb;
    let x, y, sx, sy, smooth;

    if( theta !== 0 ){
      let rotPt = eleTxrCache.getRotationPoint(ele);

      sx = rotPt.x;
      sy = rotPt.y;

      context.translate(sx, sy);
      context.rotate(theta);

      smooth = r.getImgSmoothing(context);

      if( !smooth ){ r.setImgSmoothing(context, true); }

      let off = eleTxrCache.getRotationOffset(ele);

      x = off.x;
      y = off.y;
    } else {
      x = x1;
      y = y1;
    }

    let oldGlobalAlpha;

    if( opacity !== 1 ){
      oldGlobalAlpha = context.globalAlpha;
      context.globalAlpha = oldGlobalAlpha * opacity;
    }

    context.drawImage( eleCache.texture.canvas, eleCache.x, 0, eleCache.width, eleCache.height, x, y, w, h );

    if( opacity !== 1 ){
      context.globalAlpha = oldGlobalAlpha;
    }

    if( theta !== 0 ){
      context.rotate(-theta);
      context.translate(-sx, -sy);

      if( !smooth ){ r.setImgSmoothing(context, false); }
    }
  } else {
    eleTxrCache.drawElement( context, ele ); // direct draw fallback
  }
};

const getZeroRotation = () => 0;
const getLabelRotation = (r, ele) => r.getTextAngle(ele, null);
const getSourceLabelRotation = (r, ele) => r.getTextAngle(ele, 'source');
const getTargetLabelRotation = (r, ele) => r.getTextAngle(ele, 'target');

CRp.drawCachedElement = function( context, ele, pxRatio, extent, lvl, requestHighQuality ){
  let r = this;
  let { eleTxrCache, lblTxrCache, slbTxrCache, tlbTxrCache } = r.data;

  let bb = ele.boundingBox();
  let reason = requestHighQuality === true ? eleTxrCache.reasons.highQuality : null;

  if( bb.w === 0 || bb.h === 0 || !ele.visible() ){ return; }

  if( !extent || math.boundingBoxesIntersect( bb, extent ) ){
    r.drawCachedElementPortion( context, ele, eleTxrCache, pxRatio, lvl, reason, getZeroRotation );
    r.drawCachedElementPortion( context, ele, lblTxrCache, pxRatio, lvl, reason, getLabelRotation );

    if( ele.isEdge() ){
      r.drawCachedElementPortion( context, ele, slbTxrCache, pxRatio, lvl, reason, getSourceLabelRotation );
      r.drawCachedElementPortion( context, ele, tlbTxrCache, pxRatio, lvl, reason, getTargetLabelRotation );
    }

    r.drawElementOverlay( context, ele );
  }
};

CRp.drawElements = function( context, eles ){
  let r = this;

  for( let i = 0; i < eles.length; i++ ){
    let ele = eles[ i ];

    r.drawElement( context, ele );
  }
};

CRp.drawCachedElements = function( context, eles, pxRatio, extent ){
  let r = this;

  for( let i = 0; i < eles.length; i++ ){
    let ele = eles[ i ];

    r.drawCachedElement( context, ele, pxRatio, extent );
  }
};

CRp.drawCachedNodes = function( context, eles, pxRatio, extent ){
  let r = this;

  for( let i = 0; i < eles.length; i++ ){
    let ele = eles[ i ];

    if( !ele.isNode() ){ continue; }

    r.drawCachedElement( context, ele, pxRatio, extent );
  }
};

CRp.drawLayeredElements = function( context, eles, pxRatio, extent ){
  let r = this;

  let layers = r.data.lyrTxrCache.getLayers( eles, pxRatio );

  if( layers ){
    for( let i = 0; i < layers.length; i++ ){
      let layer = layers[i];
      let bb = layer.bb;

      if( bb.w === 0 || bb.h === 0 ){ continue; }

      context.drawImage( layer.canvas, bb.x1, bb.y1, bb.w, bb.h );
    }
  } else { // fall back on plain caching if no layers
    r.drawCachedElements( context, eles, pxRatio, extent );
  }
};

if( process.env.NODE_ENV !== 'production' ){
  CRp.drawDebugPoints = function( context, eles ){
    let draw = function( x, y, color ){
      context.fillStyle = color;
      context.fillRect( x - 1, y - 1, 3, 3 );
    };

    for( let i = 0; i < eles.length; i++ ){
      let ele = eles[i];
      let rs = ele._private.rscratch;

      if( ele.isNode() ){
        let p = ele.position();

        draw( p.x, p.y, 'magenta' );
      } else {
        let pts = rs.allpts;

        for( let j = 0; j + 1 < pts.length; j += 2 ){
          let x = pts[ j ];
          let y = pts[ j + 1 ];

          draw( x, y, 'cyan' );
        }

        draw( rs.midX, rs.midY, 'yellow' );
      }
    }
  };
}

export default CRp;
<|endoftext|>


<commit_before>export default which =>
  [
    { label: "None detected.", value: "None detected." },
    {
      label: "Specify",
      value: "Please specify what you wish to scan for."
    },
    {
      label: "Does not compute",
      value: "The scan does not compute - Please restate or rephrase."
    },
    {
      label: "Unknown",
      value: "Request is unknown or ambiguous. Please restate or clarify."
    },
    {
      label: "Omni course",
      value: "omnicourse"
    },
    {
      label: "Eta",
      value:
        "At current speed this vessel will reach its destination in **minutes, **seconds."
    },
    {
      label: "Destination",
      value: "Now approaching destination. Recommend slowing to Full Stop."
    },
    { label: "Detected.", value: "Detected." },
    {
      label: "None in range",
      value: "None detected within sensor range."
    },
    {
      label: "External sensors offline",
      value: "Unable to complete scan. External sensors are offline."
    },
    { label: "Invalid", value: "Invalid search query." },
    {
      label: "No probe",
      value: "Unable to complete scan.  No probe has been launched."
    },
    {
      label: "Ship not in range",
      value: "Unable to complete scan. Ship is not within range."
    },
    {
      label: "Radiation from nebula",
      value:
        "Radiation from the nebula is interferring with sensors.  Unable to complete scan."
    },
    {
      label: "Scanning...",
      value: "Scanning... Results will be displayed on the main view screen."
    },
    {
      label: "Sensors damaged",
      value: "Sensor systems have been damaged.  Unable to complete scan."
    },
    {
      label: "Which contact.",
      value: "Please specify which contact you wish to scan."
    },
    {
      label: "Thruster Dodge",
      value: "thrusterdodge"
    },
    {
      label: "Undocking Instructions",
      value:
        "This vessel is currently docked. The Boarding Ramps and the Docking Clamps must be retracted before the Thrusters can be used to undock."
    },
    {
      label: "Undocking Completed",
      value:
        "This vessel has successfully undocked. It is recommended to calculate a course to our destination."
    },
    {
      label: "Asteroids",
      value:
        "Asteroids detected in the area. It is recommended that Thrusters be used to dodge asteroids. The weapon systems can be used to destroy incoming projectiles before impact."
    },
    {
      label: "On Course",
      value:
        "Now on course "
    },
    which && {
      label: `Use ${which === "internal" ? "External" : "Internal"}`,
      value: `Unable to complete scan. Recommend using ${
        which === "internal" ? "External" : "Internal"
      } Sensors.`
    }
  ].filter(Boolean);
<commit_msg>Sensors fix (#2079)<commit_after>export default which =>
  [
    { label: "None detected.", value: "None detected." },
    {
      label: "Specify",
      value: "Please specify what you wish to scan for."
    },
    {
      label: "Does not compute",
      value: "The scan does not compute - Please restate or rephrase."
    },
    {
      label: "Unknown",
      value: "Request is unknown or ambiguous. Please restate or clarify."
    },
    {
      label: "Omni course",
      value: "omnicourse"
    },
    {
      label: "Eta",
      value:
        "At current speed this vessel will reach its destination in **minutes, **seconds."
    },
    {
      label: "Destination",
      value: "Now approaching destination. Recommend slowing to Full Stop."
    },
    { label: "Detected.", value: "Detected." },
    {
      label: "None in range",
      value: "None detected within sensor range."
    },
    {
      label: "External sensors offline",
      value: "Unable to complete scan. External sensors are offline."
    },
    { label: "Invalid", value: "Invalid search query." },
    {
      label: "No probe",
      value: "Unable to complete scan.  No probe has been launched."
    },
    {
      label: "Ship not in range",
      value: "Unable to complete scan. Ship is not within range."
    },
    {
      label: "Radiation interference",
      value:
        "Radiation is interfering with sensors.  Unable to complete scan."
    },
    {
      label: "Scanning...",
      value: "Scanning... Results will be displayed on the main view screen."
    },
    {
      label: "Sensors damaged",
      value: "Sensor systems have been damaged.  Unable to complete scan."
    },
    {
      label: "Which contact.",
      value: "Please specify which contact you wish to scan."
    },
    {
      label: "Thruster Dodge",
      value: "thrusterdodge"
    },
    {
      label: "Undocking Instructions",
      value:
        "This vessel is currently docked. The Boarding Ramps and the Docking Clamps must be retracted before the Thrusters can be used to undock."
    },
    {
      label: "Undocking Completed",
      value:
        "This vessel has successfully undocked. It is recommended to calculate a course to our destination."
    },
    {
      label: "Asteroids",
      value:
        "Asteroids detected in the area. It is recommended that Thrusters be used to dodge asteroids. The weapon systems can be used to destroy incoming projectiles before impact."
    },
    {
      label: "On Course",
      value:
        "Now on course "
    },
    which && {
      label: `Use ${which === "internal" ? "External" : "Internal"}`,
      value: `Unable to complete scan. Recommend using ${
        which === "internal" ? "External" : "Internal"
      } Sensors.`
    }
  ].filter(Boolean);
<|endoftext|>


<commit_before>/* -*- Mode: java; tab-width: 2; c-tab-always-indent: t; indent-tabs-mode: t; c-basic-offset: 2 -*- */

function onSearchFormSubmit() {
  var searchValue = $("searchValue");

  var url = (UserFolderURL
						 + "usersSearch?search=" + escape(searchValue.value));
  if (document.userFoldersRequest) {
		document.userFoldersRequest.aborted = true;
		document.userFoldersRequest.abort();
  }
  document.userFoldersRequest
		= triggerAjaxRequest(url, usersSearchCallback);

  return false;
}

function usersSearchCallback(http) {
  document.userFoldersRequest = null;
  var div = $("folders");
  if (http.status == 200) {
    var response = http.responseText;
		buildUsersTree(div, http.responseText)
  }
  else if (http.status == 404)
    div.update();
}

function addUserLineToTree(tree, parent, line) {
	var icon = ResourcesURL + '/busy.gif';

	var userInfos = line.split(":");
	var email = userInfos[1] + " <" + userInfos[2] + ">";
	if (!userInfos[3].empty())
		email += ", " + userInfos[3]; // extra contact info
	tree.add(parent, 0, email, 0, '#', userInfos[0], 'person',
					 '', '',
					 ResourcesURL + '/abcard.gif',
					 ResourcesURL + '/abcard.gif');
	if (window.opener.userFolderType != "user") {
		tree.add(parent + 1, parent, labels["Please wait..."], 0, '#', null,
						 null, '', '', icon, icon);
	}
}

function buildUsersTree(treeDiv, response) {
	d = new dTree("d");
	d.config.folderLlinks = true;
	d.config.hideRoot = true;
	d.icon.root = ResourcesURL + '/tbtv_account_17x17.gif';
	d.icon.folder = ResourcesURL + '/tbtv_leaf_corner_17x17.png';
	d.icon.folderOpen = ResourcesURL + '/tbtv_leaf_corner_17x17.png';
	d.icon.node = ResourcesURL + '/tbtv_leaf_corner_17x17.png';
	d.icon.line = ResourcesURL + '/tbtv_line_17x17.gif';
	d.icon.join = ResourcesURL + '/tbtv_junction_17x17.gif';
	d.icon.joinBottom = ResourcesURL + '/tbtv_corner_17x17.gif';
	d.icon.plus = ResourcesURL + '/tbtv_plus_17x17.gif';
	d.icon.plusBottom = ResourcesURL + '/tbtv_corner_plus_17x17.gif';
	d.icon.minus = ResourcesURL + '/tbtv_minus_17x17.gif';
	d.icon.minusBottom = ResourcesURL + '/tbtv_corner_minus_17x17.gif';
	d.icon.nlPlus = ResourcesURL + '/tbtv_corner_plus_17x17.gif';
	d.icon.nlMinus = ResourcesURL + '/tbtv_corner_minus_17x17.gif';
	d.icon.empty = ResourcesURL + '/empty.gif';
	d.add(0, -1, '');

	var isUserDialog = (window.opener.userFolderType == "user");
	var multiplier = ((isUserDialog) ? 1 : 2);

	if (response.length) {
		var lines = response.split("\n");
		for (var i = 0; i < lines.length; i++) {
			if (lines[i].length > 0)
				addUserLineToTree(d, 1 + i * multiplier, lines[i]);
		}

		treeDiv.update(d);
		treeDiv.clean = false;

		for (var i = 0; i < lines.length - 1; i++) {
			if (lines[i].length > 0) {
				if (!isUserDialog) {
					var toggle = $("tgd" + (1 + i * 2));
					toggle.observe ("click", onUserNodeToggle);
				}
				var sd = $("sd" + (1 + i * multiplier));
				sd.observe("click", onTreeItemClick);
			}
		}
	}
}

function onUserNodeToggle(event) {
	this.stopObserving("click", onUserNodeToggle);

	var person = this.parentNode.getAttribute("dataname");
	var url = (UserFolderURL + "foldersSearch"
						 + "?user=" + escape(person)
						 + "&type=" + window.opener.userFolderType);
	var nodeId = this.getAttribute("id").substr(3);
	triggerAjaxRequest(url, foldersSearchCallback,
										 { nodeId: nodeId, user: person });
}

function onTreeItemClick(event) {
	preventDefault(event);

	var topNode = $("d");
	if (topNode.selectedEntry)
		topNode.selectedEntry.deselect();
	this.selectElement();
	topNode.selectedEntry = this;

	if (window.opener.userFolderType == "user")
		$("addButton").disabled = false;
	else {
		var dataname = this.parentNode.getAttribute("dataname");
		if (!dataname)
			dataname = "";
		$("addButton").disabled = (dataname.indexOf(":") == -1);
	};
}

function foldersSearchCallback(http) {
  if (http.status == 200) {
    var response = http.responseText;
 		var nodeId = parseInt(http.callbackData["nodeId"]);

		var dd = $("dd" + (nodeId + 2));
		var indentValue = (dd ? 1 : 0);
		d.aIndent.push(indentValue);

		var dd = $("dd" + nodeId);
		if (response.length) {
			var str = '';
			var folders = response.split(";");
			var user = http.callbackData["user"];

			for (var i = 1; i < folders.length - 1; i++)
				str += addFolderBranchToTree (d, user, folders[i], nodeId, i, false);
			str += addFolderBranchToTree (d, user, folders[folders.length-1], nodeId,
																		(folders.length - 1), true);
			dd.update(str);
			for (var i = 1; i < folders.length; i++) {
				var sd = $("sd" + (nodeId + i));
				sd.observe("click", onTreeItemClick);
			}
		}
		else {
			dd.update(addFolderNotFoundNode (d, nodeId));
			var sd = $("sd" + (nodeId + 1));
			sd.observe("click", onTreeItemClick);
		}

		d.aIndent.pop();
  }
}

function addFolderBranchToTree(tree, user, folder, nodeId, subId, isLast) {
	var folderInfos = folder.split(":");
	var icon = ResourcesURL + '/';
	if (folderInfos[2] == 'Contact')
		icon += 'tb-mail-addressbook-flat-16x16.png';
	else
		icon += 'calendar-folder-16x16.png';
	var folderId = user + ":" + folderInfos[1];
	var name = folderInfos[0]; // name has the format "Folername (Firstname Lastname <email>)"
	var pos = name.lastIndexOf(' (');
	if (pos > -1)
		name = name.substring(0, pos); // strip the part with fullname and email
	var node = new Node(subId, nodeId, name, 0, '#', folderId,
											folderInfos[2] + '-folder', '', '', icon, icon);
	node._ls = isLast;
	var content = tree.node(node, (nodeId + subId));

	return content;
}

function addFolderNotFoundNode (tree, nodeId) {
	var icon = ResourcesURL + '/icon_unread.gif';
	var node = new Node(1, nodeId, labels["No possible subscription"], 0, '#',
											null, null, '', '', icon, icon);
	node._ls = true;
	return tree.node(node, (nodeId + 1));
}

function onConfirmFolderSelection(event) {
  var topNode = $("d");
  if (topNode && topNode.selectedEntry) {
    var node = topNode.selectedEntry.parentNode;
    var folder = node.getAttribute("dataname");

    var folderName;
    if (window.opener.userFolderType == "user") {
			var span = $(topNode.selectedEntry).down("SPAN.nodeName");
			var email = (span.innerHTML
									 .replace("<", "<", "g")
									 .replace(">", ">", "g"));
      folderName = email;
    }
    else {
			var resource = $(topNode.selectedEntry).down("SPAN.nodeName");
			var user = $(node.parentNode.previousSibling).down("SPAN.nodeName");
			var email = (user.innerHTML
									 .replace("<", "<", "g")
									 .replace(">", ">", "g"));
			folderName = resource.innerHTML + ' (' + email + ')';
    }
		folderName = folderName.replace(/>,.*(\))?$/, ">)$1", "g");

    var data = { folderName: folderName, folder: folder, window: window };
    if (parent$(accessToSubscribedFolder(folder)))
      window.alert(clabels["You have already subscribed to that folder!"]);
    else
      window.opener.subscribeToFolder(window.opener.userFolderCallback, data);
  }
}

function onFolderSearchKeyDown(event) {
  var div = $("folders");
  if (!div.clean
			&& (event.keyCode == 8
					|| event.keyCode >31)) {
    div.update();
    div.clean = true;
		$("addButton").disabled = true;
  }
}

function initUserFoldersWindow() {
  var searchValue = $("searchValue");
  searchValue.observe("keydown", onFolderSearchKeyDown);
  var addButton = $("addButton");
  addButton.observe("click", onConfirmFolderSelection);
  searchValue.focus();
}

document.observe("dom:loaded", initUserFoldersWindow);
<commit_msg><commit_after>/* -*- Mode: java; tab-width: 2; c-tab-always-indent: t; indent-tabs-mode: t; c-basic-offset: 2 -*- */

function onSearchFormSubmit() {
  var searchValue = $("searchValue");

  var url = (UserFolderURL
						 + "usersSearch?search=" + escape(searchValue.value));
  if (document.userFoldersRequest) {
		document.userFoldersRequest.aborted = true;
		document.userFoldersRequest.abort();
  }
  document.userFoldersRequest
		= triggerAjaxRequest(url, usersSearchCallback);

  return false;
}

function usersSearchCallback(http) {
  document.userFoldersRequest = null;
  var div = $("folders");
  if (http.status == 200) {
    var response = http.responseText;
		buildUsersTree(div, http.responseText)
  }
  else if (http.status == 404)
    div.update();
}

function addUserLineToTree(tree, parent, line) {
	var icon = ResourcesURL + '/busy.gif';

	var userInfos = line.split(":");
	var email = userInfos[1] + " <" + userInfos[2] + ">";
	if (userInfos[3] && !userInfos[3].empty())
		email += ", " + userInfos[3]; // extra contact info
	tree.add(parent, 0, email, 0, '#', userInfos[0], 'person',
					 '', '',
					 ResourcesURL + '/abcard.gif',
					 ResourcesURL + '/abcard.gif');
	if (window.opener.userFolderType != "user") {
		tree.add(parent + 1, parent, labels["Please wait..."], 0, '#', null,
						 null, '', '', icon, icon);
	}
}

function buildUsersTree(treeDiv, response) {
	d = new dTree("d");
	d.config.folderLlinks = true;
	d.config.hideRoot = true;
	d.icon.root = ResourcesURL + '/tbtv_account_17x17.gif';
	d.icon.folder = ResourcesURL + '/tbtv_leaf_corner_17x17.png';
	d.icon.folderOpen = ResourcesURL + '/tbtv_leaf_corner_17x17.png';
	d.icon.node = ResourcesURL + '/tbtv_leaf_corner_17x17.png';
	d.icon.line = ResourcesURL + '/tbtv_line_17x17.gif';
	d.icon.join = ResourcesURL + '/tbtv_junction_17x17.gif';
	d.icon.joinBottom = ResourcesURL + '/tbtv_corner_17x17.gif';
	d.icon.plus = ResourcesURL + '/tbtv_plus_17x17.gif';
	d.icon.plusBottom = ResourcesURL + '/tbtv_corner_plus_17x17.gif';
	d.icon.minus = ResourcesURL + '/tbtv_minus_17x17.gif';
	d.icon.minusBottom = ResourcesURL + '/tbtv_corner_minus_17x17.gif';
	d.icon.nlPlus = ResourcesURL + '/tbtv_corner_plus_17x17.gif';
	d.icon.nlMinus = ResourcesURL + '/tbtv_corner_minus_17x17.gif';
	d.icon.empty = ResourcesURL + '/empty.gif';
	d.add(0, -1, '');

	var isUserDialog = (window.opener.userFolderType == "user");
	var multiplier = ((isUserDialog) ? 1 : 2);

	if (response.length) {
		var lines = response.split("\n");
		for (var i = 0; i < lines.length; i++) {
			if (lines[i].length > 0)
				addUserLineToTree(d, 1 + i * multiplier, lines[i]);
		}

		treeDiv.update(d);
		treeDiv.clean = false;

		for (var i = 0; i < lines.length - 1; i++) {
			if (lines[i].length > 0) {
				if (!isUserDialog) {
					var toggle = $("tgd" + (1 + i * 2));
					toggle.observe ("click", onUserNodeToggle);
				}
				var sd = $("sd" + (1 + i * multiplier));
				sd.observe("click", onTreeItemClick);
			}
		}
	}
}

function onUserNodeToggle(event) {
	this.stopObserving("click", onUserNodeToggle);

	var person = this.parentNode.getAttribute("dataname");
	var url = (UserFolderURL + "foldersSearch"
						 + "?user=" + escape(person)
						 + "&type=" + window.opener.userFolderType);
	var nodeId = this.getAttribute("id").substr(3);
	triggerAjaxRequest(url, foldersSearchCallback,
										 { nodeId: nodeId, user: person });
}

function onTreeItemClick(event) {
	preventDefault(event);

	var topNode = $("d");
	if (topNode.selectedEntry)
		topNode.selectedEntry.deselect();
	this.selectElement();
	topNode.selectedEntry = this;

	if (window.opener.userFolderType == "user")
		$("addButton").disabled = false;
	else {
		var dataname = this.parentNode.getAttribute("dataname");
		if (!dataname)
			dataname = "";
		$("addButton").disabled = (dataname.indexOf(":") == -1);
	};
}

function foldersSearchCallback(http) {
  if (http.status == 200) {
    var response = http.responseText;
 		var nodeId = parseInt(http.callbackData["nodeId"]);

		var dd = $("dd" + (nodeId + 2));
		var indentValue = (dd ? 1 : 0);
		d.aIndent.push(indentValue);

		var dd = $("dd" + nodeId);
		if (response.length) {
			var str = '';
			var folders = response.split(";");
			var user = http.callbackData["user"];

			for (var i = 1; i < folders.length - 1; i++)
				str += addFolderBranchToTree (d, user, folders[i], nodeId, i, false);
			str += addFolderBranchToTree (d, user, folders[folders.length-1], nodeId,
																		(folders.length - 1), true);
			dd.update(str);
			for (var i = 1; i < folders.length; i++) {
				var sd = $("sd" + (nodeId + i));
				sd.observe("click", onTreeItemClick);
			}
		}
		else {
			dd.update(addFolderNotFoundNode (d, nodeId));
			var sd = $("sd" + (nodeId + 1));
			sd.observe("click", onTreeItemClick);
		}

		d.aIndent.pop();
  }
}

function addFolderBranchToTree(tree, user, folder, nodeId, subId, isLast) {
	var folderInfos = folder.split(":");
	var icon = ResourcesURL + '/';
	if (folderInfos[2] == 'Contact')
		icon += 'tb-mail-addressbook-flat-16x16.png';
	else
		icon += 'calendar-folder-16x16.png';
	var folderId = user + ":" + folderInfos[1];
	var name = folderInfos[0]; // name has the format "Folername (Firstname Lastname <email>)"
	var pos = name.lastIndexOf(' (');
	if (pos > -1)
		name = name.substring(0, pos); // strip the part with fullname and email
	var node = new Node(subId, nodeId, name, 0, '#', folderId,
											folderInfos[2] + '-folder', '', '', icon, icon);
	node._ls = isLast;
	var content = tree.node(node, (nodeId + subId));

	return content;
}

function addFolderNotFoundNode (tree, nodeId) {
	var icon = ResourcesURL + '/icon_unread.gif';
	var node = new Node(1, nodeId, labels["No possible subscription"], 0, '#',
											null, null, '', '', icon, icon);
	node._ls = true;
	return tree.node(node, (nodeId + 1));
}

function onConfirmFolderSelection(event) {
  var topNode = $("d");
  if (topNode && topNode.selectedEntry) {
    var node = topNode.selectedEntry.parentNode;
    var folder = node.getAttribute("dataname");

    var folderName;
    if (window.opener.userFolderType == "user") {
			var span = $(topNode.selectedEntry).down("SPAN.nodeName");
			var email = (span.innerHTML
									 .replace("<", "<", "g")
									 .replace(">", ">", "g"));
      folderName = email;
    }
    else {
			var resource = $(topNode.selectedEntry).down("SPAN.nodeName");
			var user = $(node.parentNode.previousSibling).down("SPAN.nodeName");
			var email = (user.innerHTML
									 .replace("<", "<", "g")
									 .replace(">", ">", "g"));
			folderName = resource.innerHTML + ' (' + email + ')';
    }
		folderName = folderName.replace(/>,.*(\))?$/, ">)$1", "g");

    var data = { folderName: folderName, folder: folder, window: window };
    if (parent$(accessToSubscribedFolder(folder)))
      window.alert(clabels["You have already subscribed to that folder!"]);
    else
      window.opener.subscribeToFolder(window.opener.userFolderCallback, data);
  }
}

function onFolderSearchKeyDown(event) {
  var div = $("folders");
  if (!div.clean
			&& (event.keyCode == 8
					|| event.keyCode >31)) {
    div.update();
    div.clean = true;
		$("addButton").disabled = true;
  }
}

function initUserFoldersWindow() {
  var searchValue = $("searchValue");
  searchValue.observe("keydown", onFolderSearchKeyDown);
  var addButton = $("addButton");
  addButton.observe("click", onConfirmFolderSelection);
  searchValue.focus();
}

document.observe("dom:loaded", initUserFoldersWindow);
<|endoftext|>


<commit_before>export default which =>
  [
    { label: "None detected.", value: "None detected." },
    {
      label: "Specify",
      value: "Please specify what you wish to scan for."
    },
    {
      label: "Does not compute",
      value: "The scan does not compute - Please restate or rephrase."
    },
    {
      label: "Unknown",
      value: "Request is unknown or ambiguous. Please restate or clarify."
    },
    {
      label: "Omni course",
      value: "omnicourse"
    },
    {
      label: "Eta",
      value:
        "At current speed this vessel will reach its destination in **minutes, **seconds."
    },
    {
      label: "Destination",
      value: "Now approaching destination. Recommend slowing to Full Stop."
    },
    { label: "Detected.", value: "Detected." },
    {
      label: "None in range",
      value: "None detected within sensor range."
    },
    {
      label: "External sensors offline",
      value: "Unable to complete scan. External sensors are offline."
    },
    { label: "Invalid", value: "Invalid search query." },
    {
      label: "No probe",
      value: "Unable to complete scan.  No probe has been launched."
    },
    {
      label: "Not in range",
      value: "Unable to complete scan. USS ***** is not within range."
    },
    {
      label: "Radiation from nebula",
      value:
        "Radiation from the nebula is interferring with sensors.  Unable to complete scan."
    },
    {
      label: "Scanning...",
      value: "Scanning... Results will be displayed on the main view screen."
    },
    {
      label: "Sensors damaged",
      value: "Sensor systems have been damaged.  Unable to complete scan."
    },
    {
      label: "Which contact.",
      value: "Please specify which contact you wish to scan."
    },
    {
      label: "Thruster Dodge",
      value: "thrusterdodge"
    },
    {
      label: "Undocking Instructions",
      value:
        "This vessel is currently docked. The Boarding Ramps and the Docking Clamps must be retracted before the Thrusters can be used to undock."
    },
    {
      label: "Undocking Completed",
      value:
        "This vessel has successfully undocked. It is recommended to calculate a course to our destination."
    },
    {
      label: "Asteroids",
      value:
        "Asteroids detected in the area. It is recommended that Thrusters be used to dodge asteroids. The weapon systems can be used to destroy incoming projectiles before impact."
    },
    which && {
      label: `Use ${which === "internal" ? "External" : "Internal"}`,
      value: `Unable to complete scan. Recommend using ${
        which === "internal" ? "External" : "Internal"
      } Sensors.`
    }
  ].filter(Boolean);
<commit_msg>Added course set to scanning presets<commit_after>export default which =>
  [
    { label: "None detected.", value: "None detected." },
    {
      label: "Specify",
      value: "Please specify what you wish to scan for."
    },
    {
      label: "Does not compute",
      value: "The scan does not compute - Please restate or rephrase."
    },
    {
      label: "Unknown",
      value: "Request is unknown or ambiguous. Please restate or clarify."
    },
    {
      label: "Omni course",
      value: "omnicourse"
    },
    {
      label: "Eta",
      value:
        "At current speed this vessel will reach its destination in **minutes, **seconds."
    },
    {
      label: "Destination",
      value: "Now approaching destination. Recommend slowing to Full Stop."
    },
    { label: "Detected.", value: "Detected." },
    {
      label: "None in range",
      value: "None detected within sensor range."
    },
    {
      label: "External sensors offline",
      value: "Unable to complete scan. External sensors are offline."
    },
    { label: "Invalid", value: "Invalid search query." },
    {
      label: "No probe",
      value: "Unable to complete scan.  No probe has been launched."
    },
    {
      label: "Not in range",
      value: "Unable to complete scan. USS ***** is not within range."
    },
    {
      label: "Radiation from nebula",
      value:
        "Radiation from the nebula is interferring with sensors.  Unable to complete scan."
    },
    {
      label: "Scanning...",
      value: "Scanning... Results will be displayed on the main view screen."
    },
    {
      label: "Sensors damaged",
      value: "Sensor systems have been damaged.  Unable to complete scan."
    },
    {
      label: "Which contact.",
      value: "Please specify which contact you wish to scan."
    },
    {
      label: "Thruster Dodge",
      value: "thrusterdodge"
    },
    {
      label: "Undocking Instructions",
      value:
        "This vessel is currently docked. The Boarding Ramps and the Docking Clamps must be retracted before the Thrusters can be used to undock."
    },
    {
      label: "Undocking Completed",
      value:
        "This vessel has successfully undocked. It is recommended to calculate a course to our destination."
    },
    {
      label: "Asteroids",
      value:
        "Asteroids detected in the area. It is recommended that Thrusters be used to dodge asteroids. The weapon systems can be used to destroy incoming projectiles before impact."
    },
    {
      label: "On Course",
      value:
        "Now on course "
    },
    which && {
      label: `Use ${which === "internal" ? "External" : "Internal"}`,
      value: `Unable to complete scan. Recommend using ${
        which === "internal" ? "External" : "Internal"
      } Sensors.`
    }
  ].filter(Boolean);
<|endoftext|>


<commit_before>var DataTable = require("toolkit-dir/DataTable");
var helpers = require("helpers");

QUnit.module("DataTable");
QUnit.test("rendering", function (assert) {
  assert.equal(helpers.getRenderedText(DataTable, {
    headers: ["foo", "bar"],
    rows: [[1,2], [3,4]],
    globalActions: [{
      label: "New",
      callback: function() {}
    }],
    rowActions: [{
      label: "Remove",
      callback: function() {}
    }]
  }), "New foobar Actions 12 Remove34 Remove");
});
<commit_msg>Fix jstests<commit_after>var DataTable = require("toolkit-dir/DataTable");
var helpers = require("helpers");

QUnit.module("DataTable");
QUnit.test("rendering", function (assert) {
  assert.equal(helpers.getRenderedText(DataTable, {
    headers: ["foo", "bar"],
    rows: [[1,2], [3,4]],
    rowActions: [{
      label: "Remove",
      callback: function() {}
    }]
  }), "foobar Actions 12 Remove34 Remove");
});
<|endoftext|>


<commit_before>console.log("Hello");

var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });

function preload() {
  game.load.image('ghost', '/ghost.png');
  game.load.image('person', '/person.png')
}

var person;
var ghost1; var ghost2; var ghost3; var ghost4;
var ghosts;
var key1; var key2; var key3; var key4;
var walls;

function create() {

    game.physics.startSystem(Phaser.Physics.ARCADE);

    platforms = game.add.group();

    platforms.enableBody = true;

     var ledge = platforms.create(400, 400, 'platform');
    ledge.body.immovable = true;

    for (var i=0; i < 25; i++) {

      //top border
      ledge = platforms.create(0+i*32, 0, 'platform');
      ledge.body.immovable = true;

      //left border
      ledge = platforms.create(0, 25+i*20, 'platform');
      ledge.scale.setTo(1.5, 0.75);
      ledge.body.immovable = true;

       //right border
      ledge = platforms.create(750, 30+i*20, 'platform');
      ledge.scale.setTo(1.5, 0.75);
      ledge.body.immovable = true;

    }

    for (var i=0; i < 2; i++) {
       //top right box (near border)
      ledge = platforms.create(i*50+600, 100, 'platform');
      ledge.scale.setTo(1.5, 0.75);
      ledge.body.immovable = true;

       //top left box (near border)
      ledge = platforms.create(i*50+100, 100, 'platform');
      ledge.scale.setTo(1.5, 0.75);
      ledge.body.immovable = true;

      //bottom right box
      ledge = platforms.create(i*50+600, 400, 'platform');
      ledge.scale.setTo(1.5, 0.75);
      ledge.body.immovable = true;

      //bottom left box
      ledge = platforms.create(i*50+100, 400, 'platform');
      ledge.scale.setTo(1.5, 0.75);
      ledge.body.immovable = true;

       //center box
      ledge = platforms.create(i*50+350, 250, 'platform')
      ledge.scale.setTo(1.5, 0.75);
      ledge.body.immovable = true;

      ledge = platforms.create(i*50+350, 275, 'platform')
      ledge.scale.setTo(1.5, 0.75);
      ledge.body.immovable = true;
    }

    //inner borders
    for (var i=0; i < 12; i++) {
      //top right border
      ledge = platforms.create(650, i*25+100, 'platform');
      ledge.scale.setTo(1.5, 0.75);
      ledge.body.immovable = true;

      ledge = platforms.create(100, i*25+100, 'platform');
      ledge.scale.setTo(1.5, 0.75);
      ledge.body.immovable = true;

    }

    // Create person.

    person = game.add.sprite(1, game.world.height - 150, 'person');
    person.scale.setTo(0.5, 0.5);
    person.anchor.setTo(0.5, 0.5);

    // Create ghosts.

    ghost1 = game.add.sprite(100, game.world.height - 150, 'ghost');
    ghost1.anchor.setTo(0.5, 0.5);
    ghost1.scale.setTo(2,2);

    ghost2 = game.add.sprite(200, game.world.height - 150, 'ghost');
    ghost2.anchor.setTo(0.5, 0.5);
    ghost2.scale.setTo(2,2);

    ghosts = [ghost1, ghost2];

    //  Enable physics for sprites, make world boundaries.

    game.physics.arcade.enable([person, ghost1, ghost2]);
    person.body.collideWorldBounds = true;
    ghost1.body.collideWorldBounds = true;
    ghost2.body.collideWorldBounds = true;

    // Create hotkeys.

    key1 = game.input.keyboard.addKey(Phaser.Keyboard.ONE);
    key2 = game.input.keyboard.addKey(Phaser.Keyboard.TWO);
    key3 = game.input.keyboard.addKey(Phaser.Keyboard.THREE);
    key4 = game.input.keyboard.addKey(Phaser.Keyboard.FOUR);

    key1.onDown.add(function() { makeActive(1), makeInactive(1) } );
    key2.onDown.add(function() { makeActive(2), makeInactive(2) } );
    key3.onDown.add(function() { makeActive(3) } );
    key4.onDown.add(function() { makeActive(4) } );
}

function update() {

  if (person.body.enable == true) {
    if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) {
      person.x -= 4;
    }
    else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) {
      person.x += 4;
    }
    if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) {
      person.y -= 4;
    }
    else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) {
      person.y +=4;
    }
  }

  ghosts.forEach(function(item) {
      if (item.body.enable == true) {
        if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) {
          item.x -= 4;
        }
        else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) {
          item.x += 4;
        }
        if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) {
          item.y -= 4;
        }
        else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) {
          item.y +=4;
        }
      }
  });

}

function makeActive(hotkey) {
  ghosts[(hotkey - 1)].body.enable = true;
};

function makeInactive(hotkey) {
  for (var i = 1; i < 3; i++) {
    if (i != (hotkey - 1)) {
      ghosts[i].body.enable = false;
    }
  }

};<commit_msg>fixing collision<commit_after>console.log("Hello");

var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });

function preload() {
  game.load.image('ghost', '/ghost.png');
  game.load.image('person', '/person.png')
}

var person;
var ghost1; var ghost2; var ghost3; var ghost4;
var ghosts;
var key1; var key2; var key3; var key4;
var walls;

function create() {

    game.physics.startSystem(Phaser.Physics.ARCADE);

    walls = game.add.group();

    walls.enableBody = true;

    for (var i=0; i < 25; i++) {

      //top border
      ledge = walls.create(0+i*32, 0, 'platform');
      ledge.body.immovable = true;

      //left border
      ledge = walls.create(0, 25+i*20, 'platform');
      ledge.scale.setTo(1.5, 0.75);
      ledge.body.immovable = true;

       //right border
      ledge = walls.create(750, 30+i*20, 'platform');
      ledge.scale.setTo(1.5, 0.75);
      ledge.body.immovable = true;

    }

    for (var i=0; i < 2; i++) {
       //top right box (near border)
      ledge2 = walls.create(i*50+600, 100, 'platform');
      ledge2.scale.setTo(1.5, 0.75);
      ledge2.body.immovable = true;

       //top left box (near border)
      ledge3 = walls.create(i*50+100, 100, 'platform');
      ledge3.scale.setTo(1.5, 0.75);
      ledge3.body.immovable = true;

      //bottom right box
      ledge4 = walls.create(i*50+600, 400, 'platform');
      ledge4.scale.setTo(1.5, 0.75);
      ledge4.body.immovable = true;

      //bottom left box
      ledge5 = walls.create(i*50+100, 400, 'platform');
      ledge5.scale.setTo(1.5, 0.75);
      ledge5.body.immovable = true;

       //center box
      ledge6 = walls.create(i*50+350, 250, 'platform')
      ledge6.scale.setTo(1.5, 0.75);
      ledge6.body.immovable = true;

      ledge7 = walls.create(i*50+350, 275, 'platform')
      ledge7.scale.setTo(1.5, 0.75);
      ledge7.body.immovable = true;

    }

    //inner borders
    for (var i=0; i < 12; i++) {
      //top right border
      ledge8 = walls.create(650, i*25+100, 'platform');
      ledge8.scale.setTo(1.5, 0.75);
      ledge8.body.immovable = true;

      ledge9 = walls.create(100, i*25+100, 'platform');
      ledge9.scale.setTo(1.5, 0.75);
      ledge9.body.immovable = true;

    }

    // Create person.

    person = game.add.sprite(1, game.world.height - 150, 'person');
    person.scale.setTo(0.5, 0.5);
    person.anchor.setTo(0.5, 0.5);

    // Create ghosts.

    ghost1 = game.add.sprite(100, game.world.height - 150, 'ghost');
    ghost1.anchor.setTo(0.5, 0.5);
    ghost1.scale.setTo(2,2);

    ghost2 = game.add.sprite(200, game.world.height - 150, 'ghost');
    ghost2.anchor.setTo(0.5, 0.5);
    ghost2.scale.setTo(2,2)

    ghost3 = game.add.sprite(300, game.world.height - 150, 'ghost');
    ghost3.anchor.setTo(0.5, 0.5);
    ghost3.scale.setTo(2,2)

    ghost4 = game.add.sprite(400, game.world.height - 150, 'ghost');
    ghost4.anchor.setTo(0.5, 0.5);
    ghost4.scale.setTo(2,2)

    ghosts = [ghost1, ghost2, ghost3, ghost4];

    //  Enable physics for sprites, make world boundaries.
    game.physics.arcade.enable([person, ghost1, ghost2, ghost3, ghost4]);

    person.body.collideWorldBounds = true;
    ghost1.body.collideWorldBounds = true;
    ghost2.body.collideWorldBounds = true;
    ghost3.body.collideWorldBounds = true;
    ghost4.body.collideWorldBounds = true;

    // Make ghosts inactive by default.

    ghosts.forEach(function(item) { item.body.enable = false; });

    // Create hotkeys.

    key1 = game.input.keyboard.addKey(Phaser.Keyboard.ONE);
    key2 = game.input.keyboard.addKey(Phaser.Keyboard.TWO);
    key3 = game.input.keyboard.addKey(Phaser.Keyboard.THREE);
    key4 = game.input.keyboard.addKey(Phaser.Keyboard.FOUR);

    key1.onDown.add(function() { makeActive(1), makeInactive([2, 3, 4])} );
    key2.onDown.add(function() { makeActive(2), makeInactive([1, 3, 4])} );
    key3.onDown.add(function() { makeActive(3), makeInactive([1, 2, 4])} );
    key4.onDown.add(function() { makeActive(4), makeInactive([1, 2, 3])} );
}

function update() {
  game.physics.arcade.collide(person, walls);
  game.physics.arcade.collide(ghost1, walls);
  game.physics.arcade.collide(ghost2, walls);
  game.physics.arcade.collide(ghost3, walls);
  game.physics.arcade.collide(ghost4, walls);

  game.physics.arcade.overlap(person, ghost1, collectStar, null, this);

  if (person.body.enable == true) {
    if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) {
      person.x -= 4;
    }
    else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) {
      person.x += 4;
    }
    if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) {
      person.y -= 4;
    }
    else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) {
      person.y +=4;
    }
  }

  ghosts.forEach(function(item) {
      if (item.body.enable == true) {
        if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) {
          item.x -= 4;
        }
        else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) {
          item.x += 4;
        }
        if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) {
          item.y -= 4;
        }
        else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) {
          item.y +=4;
        }
      }
  });

}

function makeActive(hotkey) {
  ghosts[(hotkey - 1)].body.enable = true;
};

function makeInactive(hotkeys) {
  hotkeys.forEach(function(item) {
    ghosts[(item - 1)].body.enable = false;
  })
};

function collectStar (person, ghost1) {
  // Removes the star from the screen
  ghost1.kill();
};
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var webpack = require('webpack');
var functions = require('postcss-functions');
var StatsPlugin = require('stats-webpack-plugin');

var ExtractTextPlugin = require("extract-text-webpack-plugin");

var autoprefixer = require('autoprefixer');
var CompressionPlugin = require("compression-webpack-plugin");

var host = process.env.HOST || 'localhost'
var devServerPort = 3808;

var production = process.env.NODE_ENV === 'production';

const extractSass = new ExtractTextPlugin({
    filename: "[name].[contenthash].css",
    disable: !production
});

var sassExtractor = () => {
  return extractSass.extract({
    use: [{
      loader: "style-loader"
    }, {
      loader: "css-loader",
      options: {
        sourceMap: true
      }
    }, {
      loader: "sass-loader",
      options: {
        sourceMap: true
      }
    }],
    fallback: "style-loader"
  })
}

var config = {
  entry: {
    // Sources are expected to live in $app_root/webpack
    vendor: [
      'babel-polyfill',
    ],
    application: 'application.es6'
  },

  module: {
      rules: [
          { test: /\.es6/, use: "babel-loader" },
          { test: /\.(jpe?g|png|gif)$/i, use: "file-loader" },
          {
            test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/,
            use: production ? 'file-loader' : 'url-loader'
          },
          { test: /\.sass$/, use: sassExtractor() },
          { test: /\.scss$/, use: sassExtractor() },
          { test: /\.css$/, use: sassExtractor() }
      ]
  },

  output: {
    // Build assets directly in to public/webpack/, let webpack know
    // that all webpacked assets start with webpack/

    // must match config.webpack.output_dir
    path: path.join(__dirname, '..', 'public', 'webpack'),
    publicPath: '/webpack/',

    filename: production ? '[name]-[chunkhash].js' : '[name].js'
  },

  resolve: {
    modules: [path.resolve(__dirname, "webpack"), path.resolve(__dirname, "node_modules")],
    extensions: [".js", ".es6", ".css", ".sass", ".scss"],
  },

  plugins: [
    extractSass,
    new StatsPlugin('manifest.json', {
      chunkModules: false,
      source: false,
      chunks: false,
      modules: false,
      assets: true
    })
  ]
};

if (production) {
  config.plugins.push(
    new webpack.optimize.CommonsChunkPlugin({name: 'vendor', filename: 'vendor-[chunkhash].js'}),
    new webpack.optimize.UglifyJsPlugin({
      compressor: { warnings: false },
      sourceMap: false
    }),
    new webpack.DefinePlugin({ // <--key to reduce React's size
      'process.env': { NODE_ENV: JSON.stringify('production') }
    }),
    new CompressionPlugin({
        asset: "[path].gz",
        algorithm: "gzip",
        test: /\.js$|\.css$/,
        threshold: 4096,
        minRatio: 0.8
    })
  );
} else {
  config.plugins.push(
    new webpack.optimize.CommonsChunkPlugin({name: 'vendor', filename: 'vendor.js'}),
    new webpack.NamedModulesPlugin()
  )

  config.devServer = {
    port: devServerPort,
    headers: { 'Access-Control-Allow-Origin': '*' },
  };
  config.output.publicPath = 'http://' + host + ':' + devServerPort + '/webpack/';
  config.devtool = 'source-map';
}

module.exports = config;
<commit_msg>update example<commit_after>'use strict';

var path = require('path');
var webpack = require('webpack');
var functions = require('postcss-functions');
var StatsPlugin = require('stats-webpack-plugin');

var ExtractTextPlugin = require("extract-text-webpack-plugin");

var autoprefixer = require('autoprefixer');
var CompressionPlugin = require("compression-webpack-plugin");

var host = process.env.HOST || 'localhost'
var devServerPort = 3808;

var production = process.env.NODE_ENV === 'production';

const extractSass = new ExtractTextPlugin({
    filename: "[name].[contenthash].css",
    disable: !production
});

var sassExtractor = () => {
  return extractSass.extract({
    use: [{
      loader: "style-loader"
    }, {
      loader: "css-loader",
      options: {
        sourceMap: true
      }
    }, {
      loader: "sass-loader",
      options: {
        sourceMap: true
      }
    }],
    fallback: "style-loader"
  })
}

var config = {
  entry: {
    // Sources are expected to live in $app_root/webpack
    vendor: [
      'babel-polyfill',
    ],
    application: 'application.es6'
  },

  module: {
      rules: [
          { test: /\.es6/, use: "babel-loader" },
          { test: /\.(jpe?g|png|gif)$/i, use: "file-loader" },
          {
            test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/,
            use: production ? 'file-loader' : 'url-loader'
          },
          { test: /\.sass$/, use: sassExtractor() },
          { test: /\.scss$/, use: sassExtractor() },
          { test: /\.css$/, use: sassExtractor() }
      ]
  },

  output: {
    // Build assets directly in to public/webpack/, let webpack know
    // that all webpacked assets start with webpack/

    // must match config.webpack.output_dir
    path: path.join(__dirname, 'public', 'webpack'),
    publicPath: '/webpack/',

    filename: production ? '[name]-[chunkhash].js' : '[name].js'
  },

  resolve: {
    modules: [path.resolve(__dirname, "webpack"), path.resolve(__dirname, "node_modules")],
    extensions: [".js", ".es6", ".css", ".sass", ".scss"],
  },

  plugins: [
    extractSass,
    new StatsPlugin('manifest.json', {
      chunkModules: false,
      source: false,
      chunks: false,
      modules: false,
      assets: true
    })
  ]
};

if (production) {
  config.plugins.push(
    new webpack.optimize.CommonsChunkPlugin({name: 'vendor', filename: 'vendor-[chunkhash].js'}),
    new webpack.optimize.UglifyJsPlugin({
      compressor: { warnings: false },
      sourceMap: false
    }),
    new webpack.DefinePlugin({ // <--key to reduce React's size
      'process.env': { NODE_ENV: JSON.stringify('production') }
    }),
    new CompressionPlugin({
        asset: "[path].gz",
        algorithm: "gzip",
        test: /\.js$|\.css$/,
        threshold: 4096,
        minRatio: 0.8
    })
  );
} else {
  config.plugins.push(
    new webpack.optimize.CommonsChunkPlugin({name: 'vendor', filename: 'vendor.js'}),
    new webpack.NamedModulesPlugin()
  )

  config.devServer = {
    port: devServerPort,
    headers: { 'Access-Control-Allow-Origin': '*' },
  };
  config.output.publicPath = 'http://' + host + ':' + devServerPort + '/webpack/';
  config.devtool = 'source-map';
}

module.exports = config;
<|endoftext|>


<commit_before>Template.DocumentEditorModal.onCreated(function () {

});

Template.DocumentEditorModal.helpers({
  connection() {
    var ModalParams = Session.get('DocumentEditorModal');
    if (!ModalParams) return false;
    return Connections.findOne(ModalParams.connectionId);
  },
  database() {
    var ModalParams = Session.get('DocumentEditorModal');
    if (!ModalParams) return false;
    return Connections.findOne(ModalParams.databaseId);
  },
  collection() {
    var ModalParams = Session.get('DocumentEditorModal');
    if (!ModalParams) return false;
    return Connections.findOne(ModalParams.collectionId);
  },
  json() {
  },
  config() {
    var ModalParams = Session.get('DocumentEditorModal');
    if (!ModalParams) return false;
    var jsonData = JSON.stringify(ModalParams.document, null, '\t');

    return function (editor) {
      // Set some reasonable options on the editor
      editor.setValue(jsonData)
      editor.setTheme('ace/theme/monokai')
      editor.getSession().setMode('ace/mode/json')
      editor.setShowPrintMargin(false)
      editor.getSession().setUseWrapMode(true)
    }
  }
});
Template.DocumentEditorModal.events({
  'click #save-changes': function (e, t) {
    e.preventDefault();
    var data = ace.edit("editor").getValue();
    try {
      data = JSON.parse(data);
    }

    catch(error) {
      showFlashMessage({message: 'Invalid JSON format!'});
      return false;
    }
    var ModalParams = Session.get('DocumentEditorModal');
    Meteor.call('updateDocument', ModalParams.collectionId, ModalParams.documentId, data)
    $('#DocumentEditorModal').modal('hide');
  }
});
<commit_msg>JSON Edit tweak<commit_after>Template.DocumentEditorModal.onCreated(function () {

});

Template.DocumentEditorModal.helpers({
  connection() {
    var ModalParams = Session.get('DocumentEditorModal');
    if (!ModalParams) return false;
    return Connections.findOne(ModalParams.connectionId);
  },
  database() {
    var ModalParams = Session.get('DocumentEditorModal');
    if (!ModalParams) return false;
    return Connections.findOne(ModalParams.databaseId);
  },
  collection() {
    var ModalParams = Session.get('DocumentEditorModal');
    if (!ModalParams) return false;
    return Connections.findOne(ModalParams.collectionId);
  },
  json() {
  },
  config() {
    var ModalParams = Session.get('DocumentEditorModal');
    if (!ModalParams) return false;
    var jsonData = JSON.stringify(ModalParams.document, null, '\t');

    return function (editor) {
      // Set some reasonable options on the editor
      editor.setValue(jsonData)
      editor.setTheme('ace/theme/monokai')
      editor.getSession().setMode('ace/mode/json')
      editor.setShowPrintMargin(false)
      editor.getSession().setUseWrapMode(true)
      editor.gotoLine(1, 1)
      editor.focus()
    }
  }
});
Template.DocumentEditorModal.events({
  'click #save-changes': function (e, t) {
    e.preventDefault();
    var data = ace.edit("editor").getValue();
    try {
      data = JSON.parse(data);
    }

    catch(error) {
      showFlashMessage({message: 'Invalid JSON format!'});
      return false;
    }
    var ModalParams = Session.get('DocumentEditorModal');
    Meteor.call('updateDocument', ModalParams.collectionId, ModalParams.documentId, data)
    $('#DocumentEditorModal').modal('hide');
  }
});
<|endoftext|>