<commit_before>import Component from '@ember/component'
import { computed } from '@ember/object'
import { isNone } from '@ember/utils'
import { observer } from '@ember/object'

export default Component.extend({
  tagName: 'div',
  classNames: ['easy-datatable-container'],
  classNameBindings: ['isFullScreen:full-screen'],

  selectedCellPosition: null,
  previouslySelectedCell : null,

  editAfterInsertion: false,
  showEditorForSelectedCell: false,
  addNewRowLabel: 'Add new row',
  showAddFirstRow: false,
  showAddLastRow: false,
  isFullScreen: false,
  tableClasses: '',
  showToolBar: false,
  showDuplicateRow: false,

  init() {
    this._super(...arguments)
    this.set('selectedCellPosition', {})
  },
  actions: {
    navigate: function (direction) {
      this.send(direction);
    },

    navigateLeft: function () {
      this.set('selectedCellPosition', this.computeNavigateLeftPosition());
    },

    navigateUp: function () {
      this.set('selectedCellPosition', this.computeNavigateUpPosition());
    },

    navigateRight: function () {
      this.set('selectedCellPosition', this.computeNavigateRightPosition());
    },

    navigateDown: function () {
      this.set('selectedCellPosition', this.computeNavigateDownPosition());
    },

    addFirstRow: function () {
      var index = this.get('table').getIndexForFirstInsertableRow();
      this.insertRowAt(index, {row: index, column: 0});
    },

    addLastRow: function () {
      var index = this.get('table').getIndexForLastInsertableRow();
      this.insertRowAt(index, {row: index, column: 0});
    },

    insertRowAfter: function (index) {
      if (this.get('table').rowCanBeInserted(index)) {
        this.insertRowAt(index, this.computeNavigateDownPosition);
      }
    },

    manipulate: function (label, index) {
      this.send(label, index);
    },

    removeRow: function (index) {
      if (this.get('table').rowCanBeRemoved(index)) {
        this.get('table').removeRow(index);

        if (this.get('selectedCellPosition.row') === this.get('table.body.length')) {
          this.send('navigateUp');
        } else {
          this.notifyPropertyChange('selectedCellPosition');
        }
      }
    },

    addFirstColumn: function () {
      var index = this.get('table').getIndexForFirstInsertableColumn();
      this.insertColumnAt(index, {row: -1, column: index});
    },

    addLastColumn: function () {
      var index = this.get('table').getIndexForLastInsertableColumn();
      this.insertColumnAt(index, {row: -1, column: index});
    },

    insertColumnAfter: function (index) {
      if (this.get('table').columnCanBeInserted(index)) {
        this.insertColumnAt(index, this.computeNavigateRightPosition);
      }
    },

    removeColumn: function (index) {
      if (this.get('table').columnCanBeRemoved(index)) {
        this.get('table').removeColumn(index);
        this.notifyPropertyChange('selectedCellPosition');
      }
    },

    moveRowUp: function (index) {
      if (this.get('table').rowCanMoveUp(index)) {
        this.get('table').moveRow(index, index - 1);
        this.send('navigateUp');
      }
    },

    moveRowDown: function (index) {
      if (this.get('table').rowCanMoveDown(index)) {
        this.get('table').moveRow(index, index + 1);
        this.send('navigateDown');
      }
    },

    duplicateRow : function (index) {
      if (this.get('table').rowCanBeInserted(index+1)) {
        this.insertRowAt(index+1, {row: index+1, column: 0});
        this.get('table').populateClonedRowCells(index);
      }
    },

    moveColumnLeft: function (index) {
      if (this.get('table').columnCanMoveLeft(index)) {
        this.get('table').moveColumn(index, index - 1);
        this.send('navigateLeft');
      }
    },

    moveColumnRight: function (index) {
      if (this.get('table').columnCanMoveRight(index)) {
        this.get('table').moveColumn(index, index + 1);
        this.send('navigateRight');
      }
    }
  },

  insertRowAt: function (index, nextPosition) {
    if (isNone(index)) {
      return;
    }

    this.get('table').insertRow(index);

    if (typeof(nextPosition) === 'function') {
      nextPosition = nextPosition.apply(this);
    }

    this.set('selectedCellPosition', nextPosition);
    if (this.get('editAfterInsertion')) {
      this.navigateToFirstEditableCellInRow();
      this.set('showEditorForSelectedCell', true);
    }
  },

  firstEditableCellIndexInColumn: function (columnIndex) {
    var index;

    if (this.get('table.headers.cells')[columnIndex].get('isEditable')) {
      return -1;
    }
    for (index = 0; index < this.get('table.body.length'); index++) {
      if (this.get('table.body')[index].get('cells')[columnIndex].get('isEditable')) {
        return index;
      }
    }
  },

  navigateToFirstEditableCellInColumn: function () {
    var columnIndex = this.get('selectedCellPosition.column'),
       rowIndex = this.firstEditableCellIndexInColumn(columnIndex);

    if (!isNone(rowIndex)) {
      this.set('selectedCellPosition', {row: rowIndex, column: columnIndex});
    }
  },

  firstEditableCellIndexInRow: function (rowIndex) {
    var index, row = this.get('table.body')[rowIndex].get('cells');

    for (index = 0; index < row.length; index++) {
      if (row[index].get('isEditable')) {
        return index;
      }
    }
  },

  navigateToFirstEditableCellInRow: function () {
    var rowIndex = this.get('selectedCellPosition.row'),
      columnIndex = this.firstEditableCellIndexInRow(rowIndex);

    if (!isNone(columnIndex)) {
      this.set('selectedCellPosition', {row: rowIndex, column: columnIndex});
    }
  },

  highlightedColumn: computed('selectedCellPosition', function () {
    var position = this.get('selectedCellPosition');
    if (isNone(position) || position.row !== -1) {
      return;
    }
    return position.column;
  }),

  highlightedRow: computed('selectedCellPosition', function () {
    var position = this.get('selectedCellPosition'),
      cell = this.get('selectedCell');

    if (isNone(cell) || !cell.get('isHeader') || position.row < 0) {
      return;
    }
    return position.row;
  }),

  fixPosition: function (position) {
    if (!this.isRowValid(position)) {
      position = this.fixRowPosition(position);
    } else if (!(this.isColumnValid(position))) {
      position = this.fixColumnPosition(position);
    }

    if (!this.isRowValid(position) || !this.isColumnValid(position)) {
      position.row = null;
      position.column = null;
    }

    return position;
  },

  isRowValid: function (position) {
    var rowCount = this.get('table.body.length');
    return position.row >= -1 && position.row < rowCount;
  },

  isColumnValid: function (position) {
    var columnCount = this.get('table.headers.cells.length');
    return position.column >= 0 && position.column < columnCount;
  },

  fixRowPosition: function (position) {
    var rowCount = this.get('table.body.length');

    if (position.row < - 1) {
      position.row = rowCount - 1;
      position.column -= 1;
    }

    if (position.row >= rowCount) {
      position.row = -1;
      position.column += 1;
    }
    return position;
  },

  fixColumnPosition: function (position) {
    var columnCount = this.get('table.body.firstObject.cells.length');

    if (position.column < 0) {
      position.column = columnCount - 1;
      position.row -= 1;
    }

    if (position.column >= columnCount) {
      position.column = 0;
      position.row += 1;
    }

    return position;
  },

  computeNavigateUpPosition: function () {
    var current = this.get('selectedCellPosition');
    return this.fixPosition(this.giveValidRowPosition(current, current.row - 1));
  },

  computeNavigateDownPosition: function () {
    var current = this.get('selectedCellPosition');
    return this.fixPosition(this.giveValidRowPosition(current, current.row + 1));
  },

  giveValidRowPosition: function (current, new_row) {
    var new_position = {row: new_row, column: current.column};
    if (!this.isRowValid(new_position)) {
      new_position = {row: current.row, column: current.column};
    }
    return new_position;
  },

  computeNavigateRightPosition: function () {
    var current = this.get('selectedCellPosition');
    return this.fixPosition({row: current.row, column: current.column + 1});
  },

  computeNavigateLeftPosition: function () {
    var current = this.get('selectedCellPosition');
    return this.fixPosition({row: current.row, column: current.column - 1});
  },

  insertColumnAt: function (index, nextPosition) {
    if (isNone(index)) {
      return;
    }

    this.get('table').insertColumn(index);
    if (typeof(nextPosition) === 'function') {
      nextPosition = nextPosition.apply(this);
    }

    this.set('selectedCellPosition', nextPosition);
    if (this.get('editAfterInsertion')) {
      this.navigateToFirstEditableCellInColumn();
      this.set('showEditorForSelectedCell', true);
    }
  },

  selectedCell: computed('selectedCellPosition', function () {
    var position = this.get('selectedCellPosition');
    if (isNone(position) || isNone(position.row) || isNone(position.column)) {
      return;
    }
    if (position.row === -1) {
      return this.get('table.headers.cells')[position.column];
    }
    return this.get('table.body')[position.row].get('cells')[position.column];
  }),

	updateSelection: observer('selectedCell', function () {
    var previous = this.get('previouslySelectedCell'),
      cell = this.get('selectedCell');

    if (!isNone(previous)  && !previous.get('isDestroying')) {
      previous.set('isSelected', false);
    }

    if (isNone(cell)) {
      this.set('previouslySelectedCell', null);
    } else {
      cell.set('isSelected', true);
      this.set('previouslySelectedCell', cell);
    }
  })
});
<commit_msg>Fix selectedCellPosition if the position row is superior to table rows length<commit_after>import Component from '@ember/component'
import { computed } from '@ember/object'
import { isNone } from '@ember/utils'
import { observer } from '@ember/object'

export default Component.extend({
  tagName: 'div',
  classNames: ['easy-datatable-container'],
  classNameBindings: ['isFullScreen:full-screen'],

  selectedCellPosition: null,
  previouslySelectedCell : null,

  editAfterInsertion: false,
  showEditorForSelectedCell: false,
  addNewRowLabel: 'Add new row',
  showAddFirstRow: false,
  showAddLastRow: false,
  isFullScreen: false,
  tableClasses: '',
  showToolBar: false,
  showDuplicateRow: false,

  init() {
    this._super(...arguments)
    this.set('selectedCellPosition', {})
  },
  actions: {
    navigate: function (direction) {
      this.send(direction);
    },

    navigateLeft: function () {
      this.set('selectedCellPosition', this.computeNavigateLeftPosition());
    },

    navigateUp: function () {
      this.set('selectedCellPosition', this.computeNavigateUpPosition());
    },

    navigateRight: function () {
      this.set('selectedCellPosition', this.computeNavigateRightPosition());
    },

    navigateDown: function () {
      this.set('selectedCellPosition', this.computeNavigateDownPosition());
    },

    addFirstRow: function () {
      var index = this.get('table').getIndexForFirstInsertableRow();
      this.insertRowAt(index, {row: index, column: 0});
    },

    addLastRow: function () {
      var index = this.get('table').getIndexForLastInsertableRow();
      this.insertRowAt(index, {row: index, column: 0});
    },

    insertRowAfter: function (index) {
      if (this.get('table').rowCanBeInserted(index)) {
        this.insertRowAt(index, this.computeNavigateDownPosition);
      }
    },

    manipulate: function (label, index) {
      this.send(label, index);
    },

    removeRow: function (index) {
      if (this.get('table').rowCanBeRemoved(index)) {
        this.get('table').removeRow(index);

        if (this.get('selectedCellPosition.row') === this.get('table.body.length')) {
          this.send('navigateUp');
        } else {
          this.notifyPropertyChange('selectedCellPosition');
        }
      }
    },

    addFirstColumn: function () {
      var index = this.get('table').getIndexForFirstInsertableColumn();
      this.insertColumnAt(index, {row: -1, column: index});
    },

    addLastColumn: function () {
      var index = this.get('table').getIndexForLastInsertableColumn();
      this.insertColumnAt(index, {row: -1, column: index});
    },

    insertColumnAfter: function (index) {
      if (this.get('table').columnCanBeInserted(index)) {
        this.insertColumnAt(index, this.computeNavigateRightPosition);
      }
    },

    removeColumn: function (index) {
      if (this.get('table').columnCanBeRemoved(index)) {
        this.get('table').removeColumn(index);
        this.notifyPropertyChange('selectedCellPosition');
      }
    },

    moveRowUp: function (index) {
      if (this.get('table').rowCanMoveUp(index)) {
        this.get('table').moveRow(index, index - 1);
        this.send('navigateUp');
      }
    },

    moveRowDown: function (index) {
      if (this.get('table').rowCanMoveDown(index)) {
        this.get('table').moveRow(index, index + 1);
        this.send('navigateDown');
      }
    },

    duplicateRow : function (index) {
      if (this.get('table').rowCanBeInserted(index+1)) {
        this.insertRowAt(index+1, {row: index+1, column: 0});
        this.get('table').populateClonedRowCells(index);
      }
    },

    moveColumnLeft: function (index) {
      if (this.get('table').columnCanMoveLeft(index)) {
        this.get('table').moveColumn(index, index - 1);
        this.send('navigateLeft');
      }
    },

    moveColumnRight: function (index) {
      if (this.get('table').columnCanMoveRight(index)) {
        this.get('table').moveColumn(index, index + 1);
        this.send('navigateRight');
      }
    }
  },

  insertRowAt: function (index, nextPosition) {
    if (isNone(index)) {
      return;
    }

    this.get('table').insertRow(index);

    if (typeof(nextPosition) === 'function') {
      nextPosition = nextPosition.apply(this);
    }

    this.set('selectedCellPosition', nextPosition);
    if (this.get('editAfterInsertion')) {
      this.navigateToFirstEditableCellInRow();
      this.set('showEditorForSelectedCell', true);
    }
  },

  firstEditableCellIndexInColumn: function (columnIndex) {
    var index;

    if (this.get('table.headers.cells')[columnIndex].get('isEditable')) {
      return -1;
    }
    for (index = 0; index < this.get('table.body.length'); index++) {
      if (this.get('table.body')[index].get('cells')[columnIndex].get('isEditable')) {
        return index;
      }
    }
  },

  navigateToFirstEditableCellInColumn: function () {
    var columnIndex = this.get('selectedCellPosition.column'),
       rowIndex = this.firstEditableCellIndexInColumn(columnIndex);

    if (!isNone(rowIndex)) {
      this.set('selectedCellPosition', {row: rowIndex, column: columnIndex});
    }
  },

  firstEditableCellIndexInRow: function (rowIndex) {
    var index, row = this.get('table.body')[rowIndex].get('cells');

    for (index = 0; index < row.length; index++) {
      if (row[index].get('isEditable')) {
        return index;
      }
    }
  },

  navigateToFirstEditableCellInRow: function () {
    var rowIndex = this.get('selectedCellPosition.row'),
      columnIndex = this.firstEditableCellIndexInRow(rowIndex);

    if (!isNone(columnIndex)) {
      this.set('selectedCellPosition', {row: rowIndex, column: columnIndex});
    }
  },

  highlightedColumn: computed('selectedCellPosition', function () {
    var position = this.get('selectedCellPosition');
    if (isNone(position) || position.row !== -1) {
      return;
    }
    return position.column;
  }),

  highlightedRow: computed('selectedCellPosition', function () {
    var position = this.get('selectedCellPosition'),
      cell = this.get('selectedCell');

    if (isNone(cell) || !cell.get('isHeader') || position.row < 0) {
      return;
    }
    return position.row;
  }),

  fixPosition: function (position) {
    if (!this.isRowValid(position)) {
      position = this.fixRowPosition(position);
    } else if (!(this.isColumnValid(position))) {
      position = this.fixColumnPosition(position);
    }

    if (!this.isRowValid(position) || !this.isColumnValid(position)) {
      position.row = null;
      position.column = null;
    }

    return position;
  },

  isRowValid: function (position) {
    var rowCount = this.get('table.body.length');
    return position.row >= -1 && position.row < rowCount;
  },

  isColumnValid: function (position) {
    var columnCount = this.get('table.headers.cells.length');
    return position.column >= 0 && position.column < columnCount;
  },

  fixRowPosition: function (position) {
    var rowCount = this.get('table.body.length');

    if (position.row < - 1) {
      position.row = rowCount - 1;
      position.column -= 1;
    }

    if (position.row >= rowCount) {
      position.row = -1;
      position.column += 1;
    }
    return position;
  },

  fixColumnPosition: function (position) {
    var columnCount = this.get('table.body.firstObject.cells.length');

    if (position.column < 0) {
      position.column = columnCount - 1;
      position.row -= 1;
    }

    if (position.column >= columnCount) {
      position.column = 0;
      position.row += 1;
    }

    return position;
  },

  computeNavigateUpPosition: function () {
    var current = this.get('selectedCellPosition');
    return this.fixPosition(this.giveValidRowPosition(current, current.row - 1));
  },

  computeNavigateDownPosition: function () {
    var current = this.get('selectedCellPosition');
    return this.fixPosition(this.giveValidRowPosition(current, current.row + 1));
  },

  giveValidRowPosition: function (current, new_row) {
    var new_position = {row: new_row, column: current.column};
    if (!this.isRowValid(new_position)) {
      new_position = {row: current.row, column: current.column};
    }
    return new_position;
  },

  computeNavigateRightPosition: function () {
    var current = this.get('selectedCellPosition');
    return this.fixPosition({row: current.row, column: current.column + 1});
  },

  computeNavigateLeftPosition: function () {
    var current = this.get('selectedCellPosition');
    return this.fixPosition({row: current.row, column: current.column - 1});
  },

  insertColumnAt: function (index, nextPosition) {
    if (isNone(index)) {
      return;
    }

    this.get('table').insertColumn(index);
    if (typeof(nextPosition) === 'function') {
      nextPosition = nextPosition.apply(this);
    }

    this.set('selectedCellPosition', nextPosition);
    if (this.get('editAfterInsertion')) {
      this.navigateToFirstEditableCellInColumn();
      this.set('showEditorForSelectedCell', true);
    }
  },

  selectedCell: computed('selectedCellPosition', function () {
    var position = this.get('selectedCellPosition');
    if (isNone(position) || isNone(position.row) || isNone(position.column)) {
      return;
    }
    if (position.row === -1) {
      return this.get('table.headers.cells')[position.column];
    }
    if (position.row >= this.get('table.body').length) {
      this.fixPosition({row: this.get('table.body').length - 1, column: position.column});
      position = this.get('selectedCellPosition')
    }
    return this.get('table.body')[position.row].get('cells')[position.column];
  }),

	updateSelection: observer('selectedCell', function () {
    var previous = this.get('previouslySelectedCell'),
      cell = this.get('selectedCell');

    if (!isNone(previous)  && !previous.get('isDestroying')) {
      previous.set('isSelected', false);
    }

    if (isNone(cell)) {
      this.set('previouslySelectedCell', null);
    } else {
      cell.set('isSelected', true);
      this.set('previouslySelectedCell', cell);
    }
  })
});
<|endoftext|>


<commit_before>/*
 * grunt-generate-sprite
 */

module.exports = function(grunt) {

    grunt.registerMultiTask('sprite', 'Generate CSS Sprite', function() {
        var done = this.async();
        var starttime = (new Date()).getTime();

        var options = this.data.options;

        // Run some sync stuff.
        grunt.log.writeln('Generating CSS Sprite...');

        // Catch if required fields are not provided.
        if ( !options.iconDirectoryPath ) {
            grunt.fail.warn('No path provided for CSS Sprite to scan.');
        }
        if ( !options.resultImageName ) {
            grunt.fail.warn('You must specify a filename for CSS Sprite sprite output.');
        }
        if ( !options.resultCSSName ) {
            grunt.fail.warn('You must specify a filename for CSS Sprite css output.');
        }
        if ( !options.spritePathInCSS ) {
            grunt.fail.warn('You must specify a path to the sprite from CSS.');
        }

        var fs = require('fs'),
            gm = require('gm'),
            async = require('async'),
            HOVERPOSTFIX = "_hover",
            COMBINEDPOSTFIX = "_combined",
            tmpDirectory = Math.random().toString(36).substring(7);

        var iconDirectoryPath = options.iconDirectoryPath,
            resultImageName = options.resultImageName,
            resultCSSName = options.resultCSSName,
            spritePathInCSS = options.spritePathInCSS;

        // add missing / to icon directory path
        if (iconDirectoryPath.lastIndexOf("/") !== iconDirectoryPath.length-1) {
            iconDirectoryPath += "/";
        }

        // verify the sprite path in css includes the sprite name
        if (spritePathInCSS.indexOf(resultImageName) === -1) {
            // add missing / to sprite path
            if (spritePathInCSS.lastIndexOf("/") !== spritePathInCSS.length-1) {
                spritePathInCSS += "/";
            }
            spritePathInCSS += resultImageName.substring(resultImageName.lastIndexOf("/")+1);
        }

        function readIconDirectory() {
            var files = fs.readdir(iconDirectoryPath, function (err, files) {
                if (!err) {
                    filterHoverIcons(files);
                } else {
                    console.log('Directory could not be read.', err);
                    process.exit(0);
                }
            });
        }

        function filterHoverIcons(files) {
            var hoverIcons = [],
                icons = [],
                current,
                next,
                outputDirectory = tmpDirectory + "/";
            for(var i = 0, j = 1, ilen = files.length; i < ilen; i++, j++) {
                current = files[i];
                next = files[j];
                if (next && (next.indexOf(HOVERPOSTFIX) > 0)) {
                    // separate images with _hover images to separate array
                    hoverIcons.push(next);
                    // add the future generated combined icon
                    icons.push(outputDirectory + next.replace(HOVERPOSTFIX, COMBINEDPOSTFIX));
                } else if (current.indexOf(HOVERPOSTFIX) > 0) {
                    // skip _hover images as these have already been handled
                } else {
                    icons.push(iconDirectoryPath + current);
                }
            }
            generateHoverIcons(hoverIcons, function() {
                readIconData(icons, function() {
                    cleanUp(hoverIcons);
                });
            });
        }

        function generateHoverIcons(files, next) {
            var combined,
                current,
                original,
                outputDirectory = tmpDirectory + "/";
            async.map(files, function (icon, callback) {
                var current = iconDirectoryPath + icon,
                    original = current.replace(HOVERPOSTFIX, ""),
                    combined = outputDirectory + icon.replace(HOVERPOSTFIX, COMBINEDPOSTFIX);

                // appends another.jpg to img.png from top-to-bottom
                gm(original).append(current, false).write(combined, callback);
            }, function (err, results) {
                if (!err && results) {
                    next();
                } else {
                    console.log("generateHoverIcons didn't work. Error", err);
                }
            });
        }

        function readIconData(icons, next) {
            async.map(icons, function (icon, callback) {
                gm(icon).size(callback);
            }, function (err, results) {
                if (!err) {
                    for(var i = 0, ilen = results.length; i < ilen; i++) {
                        results[i].file = icons[i];
                    }
                    writeSpriteImage(results, next);
                } else {
                    console.log("readIconData didn't work.");
                    next();
                }
            });
        }

        function writeSpriteImage(iconImages, next) {
            var sprite = null,
                offsetX = 0;

            for(var i = 0, ilen = iconImages.length; i < ilen; i++) {
                var currentIcon = iconImages[i].file;

                // calculate offset for sprite
                iconImages[i].offsetX = offsetX;
                // Note negative on purpose
                offsetX -= iconImages[i].width;
                if (currentIcon.indexOf(iconDirectoryPath) == 0) {
                    iconImages[i].offsetY = 0;
                } else {
                    // the icon has a hover state
                    // Note negative on purpose
                    iconImages[i].offsetY = -(iconImages[i].height/2);
                }

                if (sprite === null) {
                    sprite = gm(currentIcon);
                } else {
                    // appends another.jpg to img.png from left-to-right
                    sprite.append(currentIcon, true);
                }
            }

            // create parent folder as there the parent folder should not exist
            fs.mkdir(resultImageName.substring(0, resultImageName.lastIndexOf("/")), 0755, function (err) {
                if (!err || (err && err.code === 'EEXIST')){
                    // write sprite if directory has been created or exists
                    sprite.write(resultImageName, function (err) {
                        if (!err) {
                            writeSpriteCSS(iconImages, next);
                        } else {
                            console.log("writeSpriteImage didn't work. Error", err);
                        }
                    });
                } else {
                    console.log("writeSpriteImage create folder didn't work. Error", err);
                }
            });
        }

        function writeSpriteCSS(iconImages, next) {
            var file,
                className,
                css = "";

            for(var i = 0, ilen = iconImages.length; i < ilen; i++) {
                icon = iconImages[i],
                file = icon.file,
                className = file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf(".")).replace(COMBINEDPOSTFIX, "");

                if (file.indexOf(iconDirectoryPath) != 0) {
                    // generate CSS style declarations
                    css += generateCSS(className, icon.width, icon.height/2, icon.offsetX, 0);

                    // add hover style
                    css += generateCSS(className + ":hover", icon.width, icon.height/2, icon.offsetX, icon.offsetY);
                } else {
                    // generate CSS style declarations
                    css += generateCSS(className, icon.width, icon.height, icon.offsetX, 0);
                }
            }

            // write CSS
            fs.writeFile(resultCSSName, css, function(err) {
                if (!err) {
                    next();
                } else {
                    console.log("writeSpriteCSS didn't work. ", err);
                    console.log("You probably need to manually remove the temporary directory ", tmpDirectory);
                }
            });
        }

        function generateCSS(className, width, height, offsetX, offsetY) {
            var spriteBackgroundImage = "    background-image: url('" + spritePathInCSS + "') !important;\n",
                backgroundRepeat = "    background-repeat: no-repeat !important;\n",
                css = "";

            css += "." + className + " {\n";
            css += "    width: " + width + "px;\n";
            css += "    height: " + height + "px;\n";
            css += spriteBackgroundImage;
            css += backgroundRepeat;
            css += "    background-position: " + offsetX + "px " + offsetY + "px !important;\n";
            css += "}\n\n";

            return css;
        }

        function cleanUp(files) {
            async.map(files, function (icon, callback) {
                var outputDirectory = tmpDirectory + "/",
                    combined = outputDirectory + icon.replace(HOVERPOSTFIX, COMBINEDPOSTFIX);

                fs.unlink(combined, callback);
            }, function (err, results) {
                if (!err && results) {
                    fs.rmdir(tmpDirectory, function(err, result) {
                        if (!err) {
                            var endtime = (new Date()).getTime();
                            grunt.log.writeln('CSS Sprite completed in ' + ((endtime - starttime) / 1000) + ' seconds');
                            done();
                        } else {
                            console.log("cleanUp didn't work. ", err);
                            console.log("You probably need to manually remove the temporary directory ", tmpDirectory);
                        }
                    });
                } else {
                    console.log("generateHoverIcons didn't work. Error", err);
                }
            });
        }

        // remove sprite if exists and then create temporary directory where generated sprite stuff goes
        fs.unlink(resultImageName, function (err, result) {
            fs.mkdir(tmpDirectory, 0755, readIconDirectory);
        });
    });

};
<commit_msg>AH-667 Filters resultImageName from the read icons to avoid accidental recursion<commit_after>/*
 * grunt-generate-sprite
 */

module.exports = function(grunt) {

    grunt.registerMultiTask('sprite', 'Generate CSS Sprite', function() {
        var done = this.async();
        var starttime = (new Date()).getTime();

        var options = this.data.options;

        // Run some sync stuff.
        grunt.log.writeln('Generating CSS Sprite...');

        // Catch if required fields are not provided.
        if ( !options.iconDirectoryPath ) {
            grunt.fail.warn('No path provided for CSS Sprite to scan.');
        }
        if ( !options.resultImageName ) {
            grunt.fail.warn('You must specify a filename for CSS Sprite sprite output.');
        }
        if ( !options.resultCSSName ) {
            grunt.fail.warn('You must specify a filename for CSS Sprite css output.');
        }
        if ( !options.spritePathInCSS ) {
            grunt.fail.warn('You must specify a path to the sprite from CSS.');
        }

        var fs = require('fs'),
            gm = require('gm'),
            async = require('async'),
            HOVERPOSTFIX = "_hover",
            COMBINEDPOSTFIX = "_combined",
            tmpDirectory = Math.random().toString(36).substring(7);

        var iconDirectoryPath = options.iconDirectoryPath,
            resultImageName = options.resultImageName,
            resultCSSName = options.resultCSSName,
            spritePathInCSS = options.spritePathInCSS;

        // add missing / to icon directory path
        if (iconDirectoryPath.lastIndexOf("/") !== iconDirectoryPath.length-1) {
            iconDirectoryPath += "/";
        }

        // verify the sprite path in css includes the sprite name
        if (spritePathInCSS.indexOf(resultImageName) === -1) {
            // add missing / to sprite path
            if (spritePathInCSS.lastIndexOf("/") !== spritePathInCSS.length-1) {
                spritePathInCSS += "/";
            }
            spritePathInCSS += resultImageName.substring(resultImageName.lastIndexOf("/")+1);
        }

        function readIconDirectory() {
            var files = fs.readdir(iconDirectoryPath, function (err, files) {
                if (!err) {
                    filterHoverIcons(filterResultIcon(files));
                } else {
                    console.log('Directory could not be read.', err);
                    process.exit(0);
                }
            });
        }

        function filterResultIcon(files) {
            var result = [];
            // assume there is a "/" in the resultImageName
            var icons = resultImageName.substring(resultImageName.lastIndexOf('/') + 1);

            for(var i = 0, ilen = files.length; i < ilen; i++) {
                current = files[i];
                if (current !== icons) {
                    result.push(current);
                }
            }

            return result;
        }

        function filterHoverIcons(files) {
            var hoverIcons = [],
                icons = [],
                current,
                next,
                outputDirectory = tmpDirectory + "/";
            for(var i = 0, j = 1, ilen = files.length; i < ilen; i++, j++) {
                current = files[i];
                next = files[j];
                if (next && (next.indexOf(HOVERPOSTFIX) > 0)) {
                    // separate images with _hover images to separate array
                    hoverIcons.push(next);
                    // add the future generated combined icon
                    icons.push(outputDirectory + next.replace(HOVERPOSTFIX, COMBINEDPOSTFIX));
                } else if (current.indexOf(HOVERPOSTFIX) > 0) {
                    // skip _hover images as these have already been handled
                } else {
                    icons.push(iconDirectoryPath + current);
                }
            }
            generateHoverIcons(hoverIcons, function() {
                readIconData(icons, function() {
                    cleanUp(hoverIcons);
                });
            });
        }

        function generateHoverIcons(files, next) {
            var combined,
                current,
                original,
                outputDirectory = tmpDirectory + "/";
            async.map(files, function (icon, callback) {
                var current = iconDirectoryPath + icon,
                    original = current.replace(HOVERPOSTFIX, ""),
                    combined = outputDirectory + icon.replace(HOVERPOSTFIX, COMBINEDPOSTFIX);

                // appends another.jpg to img.png from top-to-bottom
                gm(original).append(current, false).write(combined, callback);
            }, function (err, results) {
                if (!err && results) {
                    next();
                } else {
                    console.log("generateHoverIcons didn't work. Error", err);
                }
            });
        }

        function readIconData(icons, next) {
            async.map(icons, function (icon, callback) {
                gm(icon).size(callback);
            }, function (err, results) {
                if (!err) {
                    for(var i = 0, ilen = results.length; i < ilen; i++) {
                        results[i].file = icons[i];
                    }
                    writeSpriteImage(results, next);
                } else {
                    console.log("readIconData didn't work.");
                    next();
                }
            });
        }

        function writeSpriteImage(iconImages, next) {
            var sprite = null,
                offsetX = 0;

            for(var i = 0, ilen = iconImages.length; i < ilen; i++) {
                var currentIcon = iconImages[i].file;

                // calculate offset for sprite
                iconImages[i].offsetX = offsetX;
                // Note negative on purpose
                offsetX -= iconImages[i].width;
                if (currentIcon.indexOf(iconDirectoryPath) == 0) {
                    iconImages[i].offsetY = 0;
                } else {
                    // the icon has a hover state
                    // Note negative on purpose
                    iconImages[i].offsetY = -(iconImages[i].height/2);
                }

                if (sprite === null) {
                    sprite = gm(currentIcon);
                } else {
                    // appends another.jpg to img.png from left-to-right
                    sprite.append(currentIcon, true);
                }
            }

            // create parent folder as there the parent folder should not exist
            fs.mkdir(resultImageName.substring(0, resultImageName.lastIndexOf("/")), 0755, function (err) {
                if (!err || (err && err.code === 'EEXIST')){
                    // write sprite if directory has been created or exists
                    sprite.write(resultImageName, function (err) {
                        if (!err) {
                            writeSpriteCSS(iconImages, next);
                        } else {
                            console.log("writeSpriteImage didn't work. Error", err);
                        }
                    });
                } else {
                    console.log("writeSpriteImage create folder didn't work. Error", err);
                }
            });
        }

        function writeSpriteCSS(iconImages, next) {
            var file,
                className,
                css = "";

            for(var i = 0, ilen = iconImages.length; i < ilen; i++) {
                icon = iconImages[i],
                file = icon.file,
                className = file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf(".")).replace(COMBINEDPOSTFIX, "");

                if (file.indexOf(iconDirectoryPath) != 0) {
                    // generate CSS style declarations
                    css += generateCSS(className, icon.width, icon.height/2, icon.offsetX, 0);

                    // add hover style
                    css += generateCSS(className + ":hover", icon.width, icon.height/2, icon.offsetX, icon.offsetY);
                } else {
                    // generate CSS style declarations
                    css += generateCSS(className, icon.width, icon.height, icon.offsetX, 0);
                }
            }

            // write CSS
            fs.writeFile(resultCSSName, css, function(err) {
                if (!err) {
                    next();
                } else {
                    console.log("writeSpriteCSS didn't work. ", err);
                    console.log("You probably need to manually remove the temporary directory ", tmpDirectory);
                }
            });
        }

        function generateCSS(className, width, height, offsetX, offsetY) {
            var spriteBackgroundImage = "    background-image: url('" + spritePathInCSS + "') !important;\n",
                backgroundRepeat = "    background-repeat: no-repeat !important;\n",
                css = "";

            css += "." + className + " {\n";
            css += "    width: " + width + "px;\n";
            css += "    height: " + height + "px;\n";
            css += spriteBackgroundImage;
            css += backgroundRepeat;
            css += "    background-position: " + offsetX + "px " + offsetY + "px !important;\n";
            css += "}\n\n";

            return css;
        }

        function cleanUp(files) {
            async.map(files, function (icon, callback) {
                var outputDirectory = tmpDirectory + "/",
                    combined = outputDirectory + icon.replace(HOVERPOSTFIX, COMBINEDPOSTFIX);

                fs.unlink(combined, callback);
            }, function (err, results) {
                if (!err && results) {
                    fs.rmdir(tmpDirectory, function(err, result) {
                        if (!err) {
                            var endtime = (new Date()).getTime();
                            grunt.log.writeln('CSS Sprite completed in ' + ((endtime - starttime) / 1000) + ' seconds');
                            done();
                        } else {
                            console.log("cleanUp didn't work. ", err);
                            console.log("You probably need to manually remove the temporary directory ", tmpDirectory);
                        }
                    });
                } else {
                    console.log("generateHoverIcons didn't work. Error", err);
                }
            });
        }

        // remove sprite if exists and then create temporary directory where generated sprite stuff goes
        fs.unlink(resultImageName, function (err, result) {
            fs.mkdir(tmpDirectory, 0755, readIconDirectory);
        });
    });

};
<|endoftext|>


<commit_before>/**
 * Created by MinhTu on 3/31/2017.
 */
var config = {
    // basicUrl:  'https://damp-brushlands-61241.herokuapp.com/api/'
    basicUrl : 'http://localhost:8000/api/'
};
<commit_msg>decorate answer result<commit_after>/**
 * Created by MinhTu on 3/31/2017.
 */
var config = {
    basicUrl:  'https://damp-brushlands-61241.herokuapp.com/api/'
    // basicUrl : 'http://localhost:8000/api/'
};
<|endoftext|>


<commit_before>import React from 'react';
import {Link} from 'react-router';

export default () => (

Hello world!

    <Link to="/other">other</Link>

);
<commit_msg>Make Home a stateful component to make hotreload demo work<commit_after>import React from 'react';
import {Link} from 'react-router';

export default class Home extends React.Component {
  constructor() {
    super();

    this.state = {world: 'world'};
  }

  render() {
    return (

Hello world!

        <Link to="/other">other</Link>

    );
  }
}
<|endoftext|>


<commit_before>'use strict';

(function (angular, buildfire) {
  angular.module('seminarNotesPluginWidget')
    .controller('WidgetHomeCtrl', ['$scope', 'TAG_NAMES', 'LAYOUTS', 'DataStore', 'PAGINATION', 'Buildfire', 'Location', '$rootScope', 'ViewStack', '$sce', 'UserData', 'SORT', '$modal',
      function ($scope, TAG_NAMES, LAYOUTS, DataStore, PAGINATION, Buildfire, Location, $rootScope, ViewStack, $sce, UserData, SORT, $modal) {
        var WidgetHome = this;
        var currentListLayout, currentSortOrder = null;
        $rootScope.deviceHeight = window.innerHeight;
        $rootScope.deviceWidth = window.innerWidth || 320;
        WidgetHome.busy = false;
        WidgetHome.items = [];
        $scope.isClicked = false;
        WidgetHome.bookmarkItem = [];
        WidgetHome.bookmarks = {};
        $scope.isFetchedAllData = false;
        var searchOptions = {
          skip: 0,
          limit: PAGINATION.itemCount
        };

        /**
         * WidgetHome.sortingOptions are used to show options in Sort Items drop-down menu in home.html.
         */
        WidgetHome.sortingOptions = [
          SORT.MANUALLY,
          SORT.ITEM_TITLE_A_Z,
          SORT.ITEM_TITLE_Z_A,
          SORT.NEWEST_PUBLICATION_DATE,
          SORT.OLDEST_PUBLICATION_DATE,
          SORT.NEWEST_FIRST,
          SORT.OLDEST_FIRST
        ];

        /**
         * getSearchOptions(value) is used to get searchOptions with one more key sort which decide the order of sorting.
         */
        var getSearchOptions = function (value) {
          switch (value) {
            case SORT.ITEM_TITLE_A_Z:
              searchOptions.sort = {"title": 1};
              break;
            case SORT.ITEM_TITLE_Z_A:
              searchOptions.sort = {"title": -1};
              break;
            case SORT.NEWEST_PUBLICATION_DATE:
              searchOptions.sort = {"publishedOn": 1};
              break;
            case SORT.OLDEST_PUBLICATION_DATE:
              searchOptions.sort = {"publishedOn": -1};
              break;
            case SORT.NEWEST_FIRST:
              searchOptions.sort = {"dateCreated": -1};
              break;
            case SORT.OLDEST_FIRST:
              searchOptions.sort = {"dateCreated": 1};
              break;
            default :
              searchOptions.sort = {"rank": 1};
              break;
          }
          return searchOptions;
        };

        WidgetHome.data = {
          design: {
            itemListLayout: LAYOUTS.itemListLayout[0].name
          }
        };
        WidgetHome.init = function () {
          Buildfire.spinner.show();
          var success = function (result) {
              Buildfire.spinner.hide();
              if (result && result.data) {
                WidgetHome.data = result.data;
              }
              else {
                WidgetHome.data = {
                  design: {
                    itemListLayout: LAYOUTS.itemListLayout[0].name
                  }
                };
              }
              if (WidgetHome.data && !WidgetHome.data.design) {
                WidgetHome.data.design = {
                  itemListLayout: LAYOUTS.itemListLayout[0].name
                };
              }
              currentListLayout = WidgetHome.data.design.itemListLayout;
              if (!WidgetHome.data.design)
                WidgetHome.data.design = {};
              if (!WidgetHome.data.design.itemListLayout) {
                WidgetHome.data.design.itemListLayout = LAYOUTS.itemListLayout[0].name;
              }
              if (!WidgetHome.data.content)
                WidgetHome.data.content = {};
              if (WidgetHome.data.content.sortBy) {
                currentSortOrder = WidgetHome.data.content.sortBy;
              }

              if (!WidgetHome.data.design.itemListBgImage) {
                $rootScope.itemListbackgroundImage = "";
              } else {
                $rootScope.itemListbackgroundImage = WidgetHome.data.design.itemListBgImage;
              }
              console.log("==============", WidgetHome.data.design)
            }
            , error = function (err) {
              Buildfire.spinner.hide();
              WidgetHome.data = {design: {itemListLayout: LAYOUTS.itemListLayout[0].name}};
              console.error('Error while getting data', err);
            };
          DataStore.get(TAG_NAMES.SEMINAR_INFO).then(success, error);
        };

        WidgetHome.getBookMarkData = function (setBookMarks) {
          Buildfire.spinner.show();
          var err = function (error) {
            Buildfire.spinner.hide();
            console.log("============ There is an error in getting data", error);
          }, result = function (result) {
            Buildfire.spinner.hide();
            console.log("===========Bookmarks", result);
            WidgetHome.bookmarks = result;
            if (setBookMarks)
              WidgetHome.setBookmarks();
          };
          UserData.search({}, TAG_NAMES.SEMINAR_BOOKMARKS).then(result, err);
        };

        WidgetHome.setBookmarks = function () {
          for (var item = 0; item < WidgetHome.items.length; item++) {
            for (var bookmark in WidgetHome.bookmarks) {
              if (WidgetHome.items[item].id == WidgetHome.bookmarks[bookmark].data.itemIds) {
                WidgetHome.items[item].isBookmarked = true;
              }
            }
          }
          $scope.isFetchedAllData = true;
        };
        WidgetHome.init();

        WidgetHome.safeHtml = function (html) {
          if (html) {
            var $html = $('
', {html: html});
            $html.find('iframe').each(function (index, element) {
              var src = element.src;
              console.log('element is: ', src, src.indexOf('http'));
              src = src && src.indexOf('file://') != -1 ? src.replace('file://', 'http://') : src;
              element.src = src && src.indexOf('http') != -1 ? src : 'http:' + src;
            });
            return $sce.trustAsHtml($html.html());
          }
        };

        /**
         * This event listener is bound for "Carousel:LOADED" event broadcast
         */
        $rootScope.$on("Carousel:LOADED", function () {
          WidgetHome.view = null;
          if (!WidgetHome.view) {
            WidgetHome.view = new Buildfire.components.carousel.view("#carousel", []);
          }
          if (WidgetHome.data.content && WidgetHome.data.content.carouselImages) {
            WidgetHome.view.loadItems(WidgetHome.data.content.carouselImages);
          } else {
            WidgetHome.view.loadItems([]);
          }
        });
        WidgetHome.showBookmarkItems = function () {
          if (WidgetHome.currentLoggedInUser) {
            ViewStack.push({
              template: 'Bookmarks',
              params: {
                controller: "WidgetBookmarkCtrl as WidgetBookmark"
              }
            });
          } else {
            WidgetHome.openLogin();
          }
        };

        WidgetHome.showItemNotes = function () {
          if (WidgetHome.currentLoggedInUser) {
            ViewStack.push({
              template: 'Notes',
              params: {
                controller: "WidgetNotesCtrl as WidgetNotes"
              }
            });
          }
          else {
            WidgetHome.openLogin();
          }
        };
        var onUpdateCallback = function (event) {
          console.log(event);
          setTimeout(function () {
            $scope.$digest();
            if (event && event.tag === TAG_NAMES.SEMINAR_INFO) {
              WidgetHome.data = event.data;
              if (!WidgetHome.data.design)
                WidgetHome.data.design = {};
              if (!WidgetHome.data.content)
                WidgetHome.data.content = {};
              if (event.data.content.sortBy && currentSortOrder != event.data.content.sortBy) {
                WidgetHome.data.content.sortBy = event.data.content.sortBy;
                WidgetHome.items = [];
                searchOptions.skip = 0;
                WidgetHome.busy = false;
                WidgetHome.loadMore();
              }
              if (!WidgetHome.data.design.itemListBgImage) {
                $rootScope.itemListbackgroundImage = "";
              } else {
                $rootScope.itemListbackgroundImage = WidgetHome.data.design.itemListBgImage;
              }
            }
            else if (event && event.tag === TAG_NAMES.SEMINAR_ITEMS) {
              console.log("============items", event);
            }

            if (!WidgetHome.data.design.itemListLayout) {
              WidgetHome.data.design.itemListLayout = LAYOUTS.itemListLayout[0].name;
            }
            if (currentListLayout != WidgetHome.data.design.itemListLayout && WidgetHome.view && WidgetHome.data.content.carouselImages) {
              WidgetHome.view._destroySlider();
              WidgetHome.view = null;
              console.log("==========1")
            }
            else {
              if (WidgetHome.view) {
                WidgetHome.view.loadItems(WidgetHome.data.content.carouselImages);
                console.log("==========2")
              }
            }
            currentListLayout = WidgetHome.data.design.itemListLayout;
            $scope.$digest();
            $rootScope.$digest();
          }, 0);
        };
        DataStore.onUpdate().then(null, null, onUpdateCallback);

        WidgetHome.loadMore = function () {
          console.log("===============In loadmore");
          if (WidgetHome.busy) return;
          WidgetHome.busy = true;
          WidgetHome.getItems();
        };

        WidgetHome.getItems = function () {
          Buildfire.spinner.show();
          var successAll = function (resultAll) {
              Buildfire.spinner.hide();
              WidgetHome.items = WidgetHome.items.length ? WidgetHome.items.concat(resultAll) : resultAll;
              searchOptions.skip = searchOptions.skip + PAGINATION.itemCount;
              if (resultAll.length == PAGINATION.itemCount) {
                WidgetHome.busy = false;
              }
              WidgetHome.setBookmarks();
            },
            errorAll = function (error) {
              Buildfire.spinner.hide();
              console.log("error", error)
            };
          console.log("***********", WidgetHome.data.content);
          if (WidgetHome.data && WidgetHome.data.content && WidgetHome.data.content.sortBy) {
            searchOptions = getSearchOptions(WidgetHome.data.content.sortBy);
          }
          DataStore.search(searchOptions, TAG_NAMES.SEMINAR_ITEMS).then(successAll, errorAll);
        };

        WidgetHome.openDetails = function (itemId) {
          ViewStack.push({
            template: 'Item',
            params: {
              controller: "WidgetItemCtrl as WidgetItem",
              itemId: itemId
            }
          });

          //buildfire.messaging.sendMessageToControl({
          //  type: 'OpenItem',
          //  data: {"id": itemId}
          //});
        };

        WidgetHome.currentLoggedInUser = null;

        /**
         * Method to open buildfire auth login pop up and allow user to login using credentials.
         */
        WidgetHome.openLogin = function () {
          buildfire.auth.login({}, function () {

          });
        };

        var loginCallback = function () {
          buildfire.auth.getCurrentUser(function (err, user) {
            console.log("=========User", user);
            if (user) {
              WidgetHome.currentLoggedInUser = user;
              $scope.$apply();
              WidgetHome.getBookMarkData(true);
            }
          });
        };

        buildfire.auth.onLogin(loginCallback);

        /**
         * Check for current logged in user, if not show ogin screen
         */
        buildfire.auth.getCurrentUser(function (err, user) {
          console.log("===========LoggedInUser", user);
          if (user) {
            WidgetHome.currentLoggedInUser = user;
            $scope.$apply();
            WidgetHome.getBookMarkData();
          }
        });

        WidgetHome.addToBookmark = function (itemId) {
          Buildfire.spinner.show();
          WidgetHome.bookmarkItem = {
            data: {
              itemIds: itemId
            }
          };
          var successItem = function (result) {
            Buildfire.spinner.hide();
            console.log("Inserted", result);
            $scope.isClicked = itemId;
            WidgetHome.setBookmarks();
            $modal.open({
              templateUrl: 'templates/Bookmark_Confirm.html',
              size: 'sm'
            });
          }, errorItem = function () {
            Buildfire.spinner.hide();
            return console.error('There was a problem saving your data');
          };
          console.log("===============", WidgetHome.currentLoggedInUser.username);
          UserData.insert(WidgetHome.bookmarkItem.data, TAG_NAMES.SEMINAR_BOOKMARKS).then(successItem, errorItem);
        };

        WidgetHome.showSearchPage = function () {
          if (WidgetHome.currentLoggedInUser) {
            ViewStack.push({
              template: 'Search',
              params: {
                controller: "WidgetSearchCtrl as WidgetSearch"
              }
            });
          } else {
            WidgetHome.openLogin();
          }
        };

        WidgetHome.showDescription = function (description) {
          return !((description == '

') || (description == '

') || (description == ''));
        };

        $rootScope.$on('NEW_ITEM_ADDED', function (e) {
          WidgetHome.items = [];
          searchOptions.skip = 0;
          WidgetHome.busy = false;
          WidgetHome.loadMore();
        });
      }])
})(window.angular, window.buildfire);
<commit_msg>Also update item on home page when edited on details page<commit_after>'use strict';

(function (angular, buildfire) {
  angular.module('seminarNotesPluginWidget')
    .controller('WidgetHomeCtrl', ['$scope', 'TAG_NAMES', 'LAYOUTS', 'DataStore', 'PAGINATION', 'Buildfire', 'Location', '$rootScope', 'ViewStack', '$sce', 'UserData', 'SORT', '$modal',
      function ($scope, TAG_NAMES, LAYOUTS, DataStore, PAGINATION, Buildfire, Location, $rootScope, ViewStack, $sce, UserData, SORT, $modal) {
        var WidgetHome = this;
        var currentListLayout, currentSortOrder = null;
        $rootScope.deviceHeight = window.innerHeight;
        $rootScope.deviceWidth = window.innerWidth || 320;
        WidgetHome.busy = false;
        WidgetHome.items = [];
        $scope.isClicked = false;
        WidgetHome.bookmarkItem = [];
        WidgetHome.bookmarks = {};
        $scope.isFetchedAllData = false;
        var searchOptions = {
          skip: 0,
          limit: PAGINATION.itemCount
        };

        /**
         * WidgetHome.sortingOptions are used to show options in Sort Items drop-down menu in home.html.
         */
        WidgetHome.sortingOptions = [
          SORT.MANUALLY,
          SORT.ITEM_TITLE_A_Z,
          SORT.ITEM_TITLE_Z_A,
          SORT.NEWEST_PUBLICATION_DATE,
          SORT.OLDEST_PUBLICATION_DATE,
          SORT.NEWEST_FIRST,
          SORT.OLDEST_FIRST
        ];

        /**
         * getSearchOptions(value) is used to get searchOptions with one more key sort which decide the order of sorting.
         */
        var getSearchOptions = function (value) {
          switch (value) {
            case SORT.ITEM_TITLE_A_Z:
              searchOptions.sort = {"title": 1};
              break;
            case SORT.ITEM_TITLE_Z_A:
              searchOptions.sort = {"title": -1};
              break;
            case SORT.NEWEST_PUBLICATION_DATE:
              searchOptions.sort = {"publishedOn": 1};
              break;
            case SORT.OLDEST_PUBLICATION_DATE:
              searchOptions.sort = {"publishedOn": -1};
              break;
            case SORT.NEWEST_FIRST:
              searchOptions.sort = {"dateCreated": -1};
              break;
            case SORT.OLDEST_FIRST:
              searchOptions.sort = {"dateCreated": 1};
              break;
            default :
              searchOptions.sort = {"rank": 1};
              break;
          }
          return searchOptions;
        };

        WidgetHome.data = {
          design: {
            itemListLayout: LAYOUTS.itemListLayout[0].name
          }
        };
        WidgetHome.init = function () {
          Buildfire.spinner.show();
          var success = function (result) {
              Buildfire.spinner.hide();
              if (result && result.data) {
                WidgetHome.data = result.data;
              }
              else {
                WidgetHome.data = {
                  design: {
                    itemListLayout: LAYOUTS.itemListLayout[0].name
                  }
                };
              }
              if (WidgetHome.data && !WidgetHome.data.design) {
                WidgetHome.data.design = {
                  itemListLayout: LAYOUTS.itemListLayout[0].name
                };
              }
              currentListLayout = WidgetHome.data.design.itemListLayout;
              if (!WidgetHome.data.design)
                WidgetHome.data.design = {};
              if (!WidgetHome.data.design.itemListLayout) {
                WidgetHome.data.design.itemListLayout = LAYOUTS.itemListLayout[0].name;
              }
              if (!WidgetHome.data.content)
                WidgetHome.data.content = {};
              if (WidgetHome.data.content.sortBy) {
                currentSortOrder = WidgetHome.data.content.sortBy;
              }

              if (!WidgetHome.data.design.itemListBgImage) {
                $rootScope.itemListbackgroundImage = "";
              } else {
                $rootScope.itemListbackgroundImage = WidgetHome.data.design.itemListBgImage;
              }
              console.log("==============", WidgetHome.data.design)
            }
            , error = function (err) {
              Buildfire.spinner.hide();
              WidgetHome.data = {design: {itemListLayout: LAYOUTS.itemListLayout[0].name}};
              console.error('Error while getting data', err);
            };
          DataStore.get(TAG_NAMES.SEMINAR_INFO).then(success, error);
        };

        WidgetHome.getBookMarkData = function (setBookMarks) {
          Buildfire.spinner.show();
          var err = function (error) {
            Buildfire.spinner.hide();
            console.log("============ There is an error in getting data", error);
          }, result = function (result) {
            Buildfire.spinner.hide();
            console.log("===========Bookmarks", result);
            WidgetHome.bookmarks = result;
            if (setBookMarks)
              WidgetHome.setBookmarks();
          };
          UserData.search({}, TAG_NAMES.SEMINAR_BOOKMARKS).then(result, err);
        };

        WidgetHome.setBookmarks = function () {
          for (var item = 0; item < WidgetHome.items.length; item++) {
            for (var bookmark in WidgetHome.bookmarks) {
              if (WidgetHome.items[item].id == WidgetHome.bookmarks[bookmark].data.itemIds) {
                WidgetHome.items[item].isBookmarked = true;
              }
            }
          }
          $scope.isFetchedAllData = true;
        };
        WidgetHome.init();

        WidgetHome.safeHtml = function (html) {
          if (html) {
            var $html = $('
', {html: html});
            $html.find('iframe').each(function (index, element) {
              var src = element.src;
              console.log('element is: ', src, src.indexOf('http'));
              src = src && src.indexOf('file://') != -1 ? src.replace('file://', 'http://') : src;
              element.src = src && src.indexOf('http') != -1 ? src : 'http:' + src;
            });
            return $sce.trustAsHtml($html.html());
          }
        };

        /**
         * This event listener is bound for "Carousel:LOADED" event broadcast
         */
        $rootScope.$on("Carousel:LOADED", function () {
          WidgetHome.view = null;
          if (!WidgetHome.view) {
            WidgetHome.view = new Buildfire.components.carousel.view("#carousel", []);
          }
          if (WidgetHome.data.content && WidgetHome.data.content.carouselImages) {
            WidgetHome.view.loadItems(WidgetHome.data.content.carouselImages);
          } else {
            WidgetHome.view.loadItems([]);
          }
        });
        WidgetHome.showBookmarkItems = function () {
          if (WidgetHome.currentLoggedInUser) {
            ViewStack.push({
              template: 'Bookmarks',
              params: {
                controller: "WidgetBookmarkCtrl as WidgetBookmark"
              }
            });
          } else {
            WidgetHome.openLogin();
          }
        };

        WidgetHome.showItemNotes = function () {
          if (WidgetHome.currentLoggedInUser) {
            ViewStack.push({
              template: 'Notes',
              params: {
                controller: "WidgetNotesCtrl as WidgetNotes"
              }
            });
          }
          else {
            WidgetHome.openLogin();
          }
        };
        var onUpdateCallback = function (event) {
          console.log(event);
          setTimeout(function () {
            $scope.$digest();
            if (event && event.tag === TAG_NAMES.SEMINAR_INFO) {
              WidgetHome.data = event.data;
              if (!WidgetHome.data.design)
                WidgetHome.data.design = {};
              if (!WidgetHome.data.content)
                WidgetHome.data.content = {};
              if (event.data.content.sortBy && currentSortOrder != event.data.content.sortBy) {
                WidgetHome.data.content.sortBy = event.data.content.sortBy;
                WidgetHome.items = [];
                searchOptions.skip = 0;
                WidgetHome.busy = false;
                WidgetHome.loadMore();
              }
              if (!WidgetHome.data.design.itemListBgImage) {
                $rootScope.itemListbackgroundImage = "";
              } else {
                $rootScope.itemListbackgroundImage = WidgetHome.data.design.itemListBgImage;
              }
            }
            else if (event && event.tag === TAG_NAMES.SEMINAR_ITEMS) {
              console.log("============items", event);
            }

            if (!WidgetHome.data.design.itemListLayout) {
              WidgetHome.data.design.itemListLayout = LAYOUTS.itemListLayout[0].name;
            }
            if (currentListLayout != WidgetHome.data.design.itemListLayout && WidgetHome.view && WidgetHome.data.content.carouselImages) {
              WidgetHome.view._destroySlider();
              WidgetHome.view = null;
              console.log("==========1")
            }
            else {
              if (WidgetHome.view) {
                WidgetHome.view.loadItems(WidgetHome.data.content.carouselImages);
                console.log("==========2")
              }
            }
            currentListLayout = WidgetHome.data.design.itemListLayout;
            $scope.$digest();
            $rootScope.$digest();
          }, 0);
        };
        DataStore.onUpdate().then(null, null, onUpdateCallback);

        WidgetHome.loadMore = function () {
          console.log("===============In loadmore");
          if (WidgetHome.busy) return;
          WidgetHome.busy = true;
          WidgetHome.getItems();
        };

        WidgetHome.getItems = function () {
          Buildfire.spinner.show();
          var successAll = function (resultAll) {
              Buildfire.spinner.hide();
              WidgetHome.items = WidgetHome.items.length ? WidgetHome.items.concat(resultAll) : resultAll;
              searchOptions.skip = searchOptions.skip + PAGINATION.itemCount;
              if (resultAll.length == PAGINATION.itemCount) {
                WidgetHome.busy = false;
              }
              WidgetHome.setBookmarks();
            },
            errorAll = function (error) {
              Buildfire.spinner.hide();
              console.log("error", error)
            };
          console.log("***********", WidgetHome.data.content);
          if (WidgetHome.data && WidgetHome.data.content && WidgetHome.data.content.sortBy) {
            searchOptions = getSearchOptions(WidgetHome.data.content.sortBy);
          }
          DataStore.search(searchOptions, TAG_NAMES.SEMINAR_ITEMS).then(successAll, errorAll);
        };

        WidgetHome.openDetails = function (itemId) {
          ViewStack.push({
            template: 'Item',
            params: {
              controller: "WidgetItemCtrl as WidgetItem",
              itemId: itemId
            }
          });

          //buildfire.messaging.sendMessageToControl({
          //  type: 'OpenItem',
          //  data: {"id": itemId}
          //});
        };

        WidgetHome.currentLoggedInUser = null;

        /**
         * Method to open buildfire auth login pop up and allow user to login using credentials.
         */
        WidgetHome.openLogin = function () {
          buildfire.auth.login({}, function () {

          });
        };

        var loginCallback = function () {
          buildfire.auth.getCurrentUser(function (err, user) {
            console.log("=========User", user);
            if (user) {
              WidgetHome.currentLoggedInUser = user;
              $scope.$apply();
              WidgetHome.getBookMarkData(true);
            }
          });
        };

        buildfire.auth.onLogin(loginCallback);

        /**
         * Check for current logged in user, if not show ogin screen
         */
        buildfire.auth.getCurrentUser(function (err, user) {
          console.log("===========LoggedInUser", user);
          if (user) {
            WidgetHome.currentLoggedInUser = user;
            $scope.$apply();
            WidgetHome.getBookMarkData();
          }
        });

        WidgetHome.addToBookmark = function (itemId) {
          Buildfire.spinner.show();
          WidgetHome.bookmarkItem = {
            data: {
              itemIds: itemId
            }
          };
          var successItem = function (result) {
            Buildfire.spinner.hide();
            console.log("Inserted", result);
            $scope.isClicked = itemId;
            WidgetHome.setBookmarks();
            $modal.open({
              templateUrl: 'templates/Bookmark_Confirm.html',
              size: 'sm'
            });
          }, errorItem = function () {
            Buildfire.spinner.hide();
            return console.error('There was a problem saving your data');
          };
          console.log("===============", WidgetHome.currentLoggedInUser.username);
          UserData.insert(WidgetHome.bookmarkItem.data, TAG_NAMES.SEMINAR_BOOKMARKS).then(successItem, errorItem);
        };

        WidgetHome.showSearchPage = function () {
          if (WidgetHome.currentLoggedInUser) {
            ViewStack.push({
              template: 'Search',
              params: {
                controller: "WidgetSearchCtrl as WidgetSearch"
              }
            });
          } else {
            WidgetHome.openLogin();
          }
        };

        WidgetHome.showDescription = function (description) {
          return !((description == '

') || (description == '

') || (description == ''));
        };

        $rootScope.$on('NEW_ITEM_ADDED_UPDATED', function (e) {
          WidgetHome.items = [];
          searchOptions.skip = 0;
          WidgetHome.busy = false;
          WidgetHome.loadMore();
        });
      }])
})(window.angular, window.buildfire);
<|endoftext|>


<commit_before>"use strict";

var util = require('util');
var SerialPort = require("serialport").SerialPort;

function Arduinode(path, options, openImmediately){
  var self = this;
  self.sp = new SerialPort(path, options, openImmediately);
  self.buf = [];
  self.callback = null;

  // arduinoは\r\nを返してくる.
  self.sp.on("data", function(data){
    for(var i = 0; i < data.length; i++){
      if( data[i] != 10){
        // \rは無視する.
        if(data[i] != 13){
          self.buf.push(data[i]);
        }
      }else{
        var received = new Buffer(self.buf).toString();
        if(received === "READY"){
          self.emit("open");
        }else if(typeof(self.callback) == "function"){
          self.callback(new Buffer(self.buf).toString());
          self.callback = null;
        }
        self.buf = [];
      }
    }
  });
}

util.inherits(Arduinode, SerialPort);

Arduinode.prototype.send = function(cmd, callback) {

  var self = this;
  self.callback = callback;
  var sendCmd = cmd.replace(/\n$/, "") + "\n";
  self.sp.write(sendCmd, function(err, writeBytes){
    if(err){
      self.emit("error", err);
    }else if(writeBytes != sendCmd.length){
      self.emit("error", "write bytes mismatch.");
    }
  });
}

module.exports.Arduinode = Arduinode;

<commit_msg>コールバックをキューで管理するようにした.<commit_after>"use strict";

var util = require('util');
var SerialPort = require("serialport").SerialPort;

function Arduinode(path, options, openImmediately){
  var self = this;
  self.sp = new SerialPort(path, options, openImmediately);
  self.buf = [];
  self.callback = [];
  self.error = null;

  // arduinoは\r\nを返してくる.
  self.sp.on("data", function(data){
    for(var i = 0; i < data.length; i++){
      if( data[i] != 10){
        // \rは無視する.
        if(data[i] != 13){
          self.buf.push(data[i]);
        }
      }else{
        var received = new Buffer(self.buf).toString();
        if(received === "READY"){
          self.emit("open");
        }else{
          var cb = self.callback.shift();
          if(typeof(cb) == "function"){
            cb(self.error, new Buffer(self.buf).toString());
            self.errro = null;
          }
        }
        self.buf = [];
      }
    }
  });
}

util.inherits(Arduinode, SerialPort);

Arduinode.prototype.send = function(cmd, callback) {

  var self = this;
  self.callback.push(callback);
  var sendCmd = cmd.replace(/\n$/, "") + "\n";
  self.sp.write(sendCmd, function(err, writeBytes){
    if(err){
      self.error = err;
      self.emit("error", err);
    }else if(writeBytes != sendCmd.length){
      self.error = "Write bytes mismatch.";
    }
  });
}

module.exports.Arduinode = Arduinode;

/*
 * NOTE:
 *
 *
 * Arduinoのシリアルバッファが大きくないので、
 * 以下の様なコードを書くと直ぐにバッファが溢れて
 * 正常にコマンドが送信できなくなる.
 *
 *  arduinode.on("open", function(){
 *    for(var i = 0; i < 10; i++){
 *      arduinode.send("ai/read/" + i, function(err, resp){
 *        if(err) throw err;
 *        console.log(resp);
 *      });
 *    }
 *  });
 *
 */
<|endoftext|>


<commit_before>"use strict"; // strict mode syntax

//Any file that requires jQuery should be
//placed within this annon function
require(["libs/jquery/jquery-1.11.2.js"],function(jquery) {
  require(["libs/jquery/jquery-ui.js"]);
  require(["libs/SlickGrid/lib/jquery.event.drag-2.2.js"],function(drag) {
    require(["libs/SlickGrid/slick.core.js"], function(core) {
      require(["libs/SlickGrid/slick.editors.js"]);
      require(["libs/SlickGrid/lib/firebugx.js"]);
      require(["javascript/slickTable.js"]);
      require(["libs/SlickGrid/slick.grid.js"]);
    });
  });
});

require(["libs/PapaParse/papaparse.min.js"]);
require(["libs/chartjs/Chart.js"]);

require(["libs/jsfx/audio.js"], function (audio) {
    require(["libs/jsfx/jsfx.js"]);
    require(["libs/jsfx/jsfxlib.js"]);
});

require(["javascript/files.js"], function(print){
  loadListener();
  createListener();
});

require(["javascript/chart.js"]);
require(["javascript/overlay.js"]);
require(["javascript/arrayInfo.js"]);
require(["javascript/audioPlayer.js"]);
require(["javascript/arrayCollection.js"]);
require(["javascript/global.js"]);
require(["javascript/summary.js"]);
require(["javascript/prompts.js"]);
require(["javascript/printer.js"]);

var player;
var overlay;
var summary;
var chart;
var type = null;
var lineColors = [];
var slickTable;
// initial data load
// (this is called after fileOpen from files.js)
var loadData = function (data) {
    document.getElementById('start').style.display = 'none';
    document.querySelector('#overlay').setAttribute('style', '');
    document.querySelector('#slickTable').innerHTML = '';
    slickTable = loadSlickTable(data.data);
    document.getElementById('tableCount').innerHTML = "[ Total Row: " + (data.data.length - 1) + " ] [ Total Column: " + (data.data[0].length - 1) + " ]";
    document.getElementById('remInstruction').innerHTML = "*To remove specific row or column: delete the contents in the chosen labels cell"
    chart = loadChart(data.data, type);
    player = new Instrument(26);
    overlay = new Overlay(data);
    overlay.updateSize(chart);
    var collection = new ArrayCollection(data.data);
    player.setCollection(collection.collection);
    summary = new DataSummary(collection);
    summary.dataSummary();
    linkSlickTable(chart, player, overlay, summary);
    document.getElementById("content").style.position = "inherit"; //overides corresponding style in index.html that hides the content tag
    document.getElementById("content").style.top = ""; // meant to leave it blank: to overide corresponding style in index.html that hides the content tag
    document.getElementById("content").style.left = ""; // meant to leave it blank: to overide corresponding style in index.html that hides the content tag
    document.getElementById('rTypeSelBody').style.display = 'block';
    document.getElementById('plot-header').style.display = 'inline';
    document.getElementById('tableControls').style.display = 'block';
    document.getElementById('summaryBox').style.display = 'block';
    fixSlick();
}

// The play button
var playStopAudioButton = function () {
  //Change the speed of the audio based on speed input.
  var bpm = 80 + 40 * document.getElementById('bpm').value;
  player.bpm = bpm;
  //DO NOT CHANGE/DELETE: Fixes audio issue involving slider
  if(overlay.slider[0] === 0 && overlay.slider[1] === 0){
   overlay.slider[1] = chart.datasets[0].length;
  }
    player.playToggle(document.getElementById("lineDropdown").value - 1, overlay.slider[0], overlay.slider[1]);
}

// Opens the color editor
var openColorEditor = function () {
    var editor = document.getElementById('summary-editor');
    editor.style.display = editor.style.display == 'inline' ? 'none' : 'block';
}

var focusElement = function(elementClass) {
  document.getElementsByClassName(elementClass)[0].style.backgroundColor = "#000";
  document.getElementsByClassName(elementClass)[0].style.color = "#FFF";
}

var blurElement = function(elementClass) {
  document.getElementsByClassName(elementClass)[0].style.backgroundColor = "#FFF";
  document.getElementsByClassName(elementClass)[0].style.color = "#000";
}
<commit_msg>Added safari browser typechecking<commit_after>"use strict"; // strict mode syntax

//Any file that requires jQuery should be
//placed within this annon function
require(["libs/jquery/jquery-1.11.2.js"],function(jquery) {
  require(["libs/jquery/jquery-ui.js"]);
  require(["libs/SlickGrid/lib/jquery.event.drag-2.2.js"],function(drag) {
    require(["libs/SlickGrid/slick.core.js"], function(core) {
      require(["libs/SlickGrid/slick.editors.js"]);
      require(["libs/SlickGrid/lib/firebugx.js"]);
      require(["javascript/slickTable.js"]);
      require(["libs/SlickGrid/slick.grid.js"]);
    });
  });
});

require(["libs/PapaParse/papaparse.min.js"]);
require(["libs/chartjs/Chart.js"]);

require(["libs/jsfx/audio.js"], function (audio) {
    require(["libs/jsfx/jsfx.js"]);
    require(["libs/jsfx/jsfxlib.js"]);
});

require(["javascript/files.js"], function(print){
  loadListener();
  createListener();
});

require(["javascript/chart.js"]);
require(["javascript/overlay.js"]);
require(["javascript/arrayInfo.js"]);
require(["javascript/audioPlayer.js"]);
require(["javascript/arrayCollection.js"]);
require(["javascript/global.js"]);
require(["javascript/summary.js"]);
require(["javascript/prompts.js"]);
require(["javascript/printer.js"]);

var player;
var overlay;
var summary;
var chart;
var type = null;
var lineColors = [];
var slickTable;
// initial data load
// (this is called after fileOpen from files.js)
var loadData = function (data) {
    document.getElementById('start').style.display = 'none';
    document.querySelector('#overlay').setAttribute('style', '');
    document.querySelector('#slickTable').innerHTML = '';
    slickTable = loadSlickTable(data.data);
    document.getElementById('tableCount').innerHTML = "[ Total Row: " + (data.data.length - 1) + " ] [ Total Column: " + (data.data[0].length - 1) + " ]";
    document.getElementById('remInstruction').innerHTML = "*To remove specific row or column: delete the contents in the chosen labels cell"
    chart = loadChart(data.data, type);
    if(Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0)
      player = new WaveForm("sine");
    else
      player = new Instrument(26);
    overlay = new Overlay(data);
    overlay.updateSize(chart);
    var collection = new ArrayCollection(data.data);
    player.setCollection(collection.collection);
    summary = new DataSummary(collection);
    summary.dataSummary();
    linkSlickTable(chart, player, overlay, summary);
    document.getElementById("content").style.position = "inherit"; //overides corresponding style in index.html that hides the content tag
    document.getElementById("content").style.top = ""; // meant to leave it blank: to overide corresponding style in index.html that hides the content tag
    document.getElementById("content").style.left = ""; // meant to leave it blank: to overide corresponding style in index.html that hides the content tag
    document.getElementById('rTypeSelBody').style.display = 'block';
    document.getElementById('plot-header').style.display = 'inline';
    document.getElementById('tableControls').style.display = 'block';
    document.getElementById('summaryBox').style.display = 'block';
    fixSlick();
}

// The play button
var playStopAudioButton = function () {
  //Change the speed of the audio based on speed input.
  var bpm = 80 + 40 * document.getElementById('bpm').value;
  player.bpm = bpm;
  //DO NOT CHANGE/DELETE: Fixes audio issue involving slider
  if(overlay.slider[0] === 0 && overlay.slider[1] === 0){
   overlay.slider[1] = chart.datasets[0].length;
  }
    player.playToggle(document.getElementById("lineDropdown").value - 1, overlay.slider[0], overlay.slider[1]);
}

// Opens the color editor
var openColorEditor = function () {
    var editor = document.getElementById('summary-editor');
    editor.style.display = editor.style.display == 'inline' ? 'none' : 'block';
}

var focusElement = function(elementClass) {
  document.getElementsByClassName(elementClass)[0].style.backgroundColor = "#000";
  document.getElementsByClassName(elementClass)[0].style.color = "#FFF";
}

var blurElement = function(elementClass) {
  document.getElementsByClassName(elementClass)[0].style.backgroundColor = "#FFF";
  document.getElementsByClassName(elementClass)[0].style.color = "#000";
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

"use strict";

const fs = require('fs');
const chalk = require('chalk');
const meow = require('meow');
const util = require('util')

const cli=new meow(`
    Usage
      $ rawText2JSON <file>
`);

if(!cli.input.length || cli.input[0] === 'help') {
  console.log(cli.help);
}

let file_name=cli.input[0];

fs.readFile(file_name, (err, data) => {
  if(err) {throw err;}
  let output_file_name = file_name.replace(/\.[\w]+$/g, '.json');

  fs.writeFile(output_file_name, JSON.stringify(data.toString()), (err) => {
    if (err) {throw err;}
    console.log(chalk.green('JSON file created sucessfully! \n'));
  });
});

process.on('uncaughtException', (err) => {
   console.log(chalk.red('Error: '+err.message));
});<commit_msg>add .json ext to original file name rather than replacing the original extension name<commit_after>#!/usr/bin/env node

"use strict";

const fs = require('fs');
const chalk = require('chalk');
const meow = require('meow');
const util = require('util')

const cli=new meow(`
    Usage
      $ rawText2JSON <file>
`);

if(!cli.input.length || cli.input[0] === 'help') {
  console.log(cli.help);
}

let file_name=cli.input[0];

fs.readFile(file_name, (err, data) => {
  if(err) {throw err;}
  let output_file_name = file_name+'.json';

  fs.writeFile(output_file_name, JSON.stringify(data.toString()), (err) => {
    if (err) {throw err;}
    console.log(chalk.green('JSON file created sucessfully! \n'));
  });
});

process.on('uncaughtException', (err) => {
   console.log(chalk.red('Error: '+err.message));
});<|endoftext|>


<commit_before><commit_msg>Added comp Shopkeeper.<commit_after><|endoftext|>


<commit_before>var stage;
var board;
var index;
var r_size;
var c_size;
var question_size;
var size;
var num_on_bulbs;
var node_list;
var base;

var bulb_start = new Array();
bulb_start[0] = '<img src="images/off.png" class="bulb" class="off_bulb" id="';
bulb_start[1] = '';

/*
var stage = 1;
var board = new Array();
var index = new Array();
var r_size = 5;
var c_size = 5;
var question_size = 5;
var size = r_size * c_size;
var num_on_bulbs = 0;
var node_list = new Array();
var base = ( r_size > c_size ) ? r_size : c_size ;

for (var r = 0; r < r_size; ++r) {
        board[r]= new Array();
        index[r] = new Array()
        var idx = 'row' + r;
        for( var c = 0 ; c < c_size ; ++c){
            node_list[ r * c_size + c ] = ( r * base + c  );
            board[r][c] = false;
            index[r][c] = new Array();
            for(var on = 0; on < 2; on++) {
                index[r][c][on] = idx + "col" + c + '_' + on;
            }
        }
}
*/
function in_range(r, c) {
    return r >= 0 && r < r_size && c >= 0 && c < c_size;
}

function press(r, c){
        for(var i = r-1 ; i <= (r+1) ; i++ ){
            if( i >= 0 && i < r_size){
                for(var j = c-1 ; j <= (c+1) ; j++ ){
                    if( j >= 0 && j < c_size ){
                        board[i][j] = !board[i][j];
                        for(var on = 0; on < 2 ; on++ )
                            $( "#" + index[i][j][on] ).toggle();
                        if(board[i][j]){
                            num_on_bulbs++;
                        }
                        else{
                            num_on_bulbs--;
                        }
                    }
                }
            }
        }
    }

function float2int( val ){
    return val | 0;
}

function random_question(q_size){
    for (var i = 0; i < q_size; i++) {
        var rn = i + float2int( Math.random() * ( size - i ) ) ;
        var t = node_list[i] ;
        node_list[i] = node_list[rn] ;
        node_list[rn] = t;

        press( float2int( node_list[i] / base ) , node_list[i] % base );
    }

    $("#stage").text("Stage " + (stage++) );
}

function once_click( r , c)
{
   press( r , c );
   $("#pop")[0].play();
   if(num_on_bulbs==0){
       swal({
            title: '   Well done, Tommy Atkins!      ',
            text: '',
            confirmButtonColor: '#FC0A20',
            confirmButtonText: 'Yes, Milord!',
            html: true
       });
       random_question( question_size );
   }
}

function square_color_fill(r, c, color) {
    for(var i = r - 1; i <= r + 1; i++) {
        for (var j = c - 1; j <= c + 1; j++) {
            if (in_range(i, j)) {
                for(var on = 0; on < 2; on++) {
                    $('#' + index[i][j][on]).css('background-color', color);
                }
            }
        }
    }
}

function init(row_num, col_num, q_num) {
    r_size = row_num;
    c_size = col_num;
    stage = 1;
    board = new Array();
    index = new Array();
    size = r_size * c_size;
    question_size = float2int(q_num / 20 * size) + 1;
    num_on_bulbs = 0;
    node_list = new Array();
    base = ( r_size > c_size ) ? r_size : c_size ;
    for (var r = 0; r < r_size; ++r) {
        board[r]= new Array();
        index[r] = new Array()
        var idx = 'row' + r;
        for( var c = 0 ; c < c_size ; ++c){
            node_list[ r * c_size + c ] = ( r * base + c  );
            board[r][c] = false;
            index[r][c] = new Array();
            for(var on = 0 ; on < 2 ; on++ )
            {
                index[r][c][on] = idx + "col" + c + '_' + on;
            }
        }
    }
}

function build_board(row_num, col_num) {
    init(row_num, col_num, q_num);
    $("#Board").empty();
    for (var r = 0; r < r_size; r++) {
        var cur_row = "
";
        for (var c = 0; c < c_size; c++) {
            cur_row += '';

            for( var on = 0 ; on < 2 ; on++ )
                cur_row += bulb_start[on] + index[r][c][on] + '" ' +
                    'onclick    ="once_click('+r+','+c+')" ' +
                    'onmouseover="square_color_fill('+r+','+c+','+"'#BCF5A9'"+')" ' +
                    'onmouseout ="square_color_fill('+r+','+c+','+"'pink'" + ')" ' +
                    img_end ;

            cur_row += "	" ;
        }
        cur_row += "
";
        $("#Board").append( cur_row );
        for( var c = 0 ; c < c_size ; c++ )
            $("#" + index[r][c][1]).toggle();

    }
}

$(document).ready(function(){

//preload images
var images  = [
    "images/Keep-calm-and-carry-on-scan.jpg",
    "images/neutral-indeed-small.png"
];
var image_url;
for( image_url in images ){
    var img = new Image(0,0);
    img.src = image_url;
}

    build_board(5, 5);
    while(num_on_bulbs == 0)
        random_question(question_size);

    $('#set').click(function(){
        var row_num = parseInt($('#row_num').val(), 10);
        var col_num = parseInt($('#col_num').val(), 10);
        var q_num = parseInt($('#q_num').val(), 10);
        if (isNaN(row_num) || isNaN(col_num) || isNaN(q_num)) {
            swal({
                title: 'Error',
                text: 'Integers only.',
                type: 'error'
            });
        } else if (row_num < 3 || col_num < 3 || q_num < 1 || q_num > 10) {
            swal({
                title: 'Error',
                text: 'Note the input range.',
                type: 'error'
            });
        } else {
            build_board(row_num, col_num, q_num);
            while (num_on_bulbs == 0)
                random_question(question_size);
        }
    });

});
<commit_msg>fix custom difficulty bug<commit_after>var stage;
var board;
var index;
var r_size;
var c_size;
var question_size;
var size;
var num_on_bulbs;
var node_list;
var base;

var bulb_start = new Array();
bulb_start[0] = '<img src="images/off.png" class="bulb" class="off_bulb" id="';
bulb_start[1] = '';

/*
var stage = 1;
var board = new Array();
var index = new Array();
var r_size = 5;
var c_size = 5;
var question_size = 5;
var size = r_size * c_size;
var num_on_bulbs = 0;
var node_list = new Array();
var base = ( r_size > c_size ) ? r_size : c_size ;

for (var r = 0; r < r_size; ++r) {
        board[r]= new Array();
        index[r] = new Array()
        var idx = 'row' + r;
        for( var c = 0 ; c < c_size ; ++c){
            node_list[ r * c_size + c ] = ( r * base + c  );
            board[r][c] = false;
            index[r][c] = new Array();
            for(var on = 0; on < 2; on++) {
                index[r][c][on] = idx + "col" + c + '_' + on;
            }
        }
}
*/
function in_range(r, c) {
    return r >= 0 && r < r_size && c >= 0 && c < c_size;
}

function press(r, c){
        for(var i = r-1 ; i <= (r+1) ; i++ ){
            if( i >= 0 && i < r_size){
                for(var j = c-1 ; j <= (c+1) ; j++ ){
                    if( j >= 0 && j < c_size ){
                        board[i][j] = !board[i][j];
                        for(var on = 0; on < 2 ; on++ )
                            $( "#" + index[i][j][on] ).toggle();
                        if(board[i][j]){
                            num_on_bulbs++;
                        }
                        else{
                            num_on_bulbs--;
                        }
                    }
                }
            }
        }
    }

function float2int( val ){
    return val | 0;
}

function random_question(q_size){
    for (var i = 0; i < q_size; i++) {
        var rn = i + float2int( Math.random() * ( size - i ) ) ;
        var t = node_list[i] ;
        node_list[i] = node_list[rn] ;
        node_list[rn] = t;

        press( float2int( node_list[i] / base ) , node_list[i] % base );
    }

    $("#stage").text("Stage " + (stage++) );
}

function once_click( r , c)
{
   press( r , c );
   $("#pop")[0].play();
   if(num_on_bulbs==0){
       swal({
            title: '   Well done, Tommy Atkins!      ',
            text: '',
            confirmButtonColor: '#FC0A20',
            confirmButtonText: 'Yes, Milord!',
            html: true
       });
       random_question( question_size );
   }
}

function square_color_fill(r, c, color) {
    for(var i = r - 1; i <= r + 1; i++) {
        for (var j = c - 1; j <= c + 1; j++) {
            if (in_range(i, j)) {
                for(var on = 0; on < 2; on++) {
                    $('#' + index[i][j][on]).css('background-color', color);
                }
            }
        }
    }
}

function init(row_num, col_num, q_num) {
    r_size = row_num;
    c_size = col_num;
    stage = 1;
    board = new Array();
    index = new Array();
    size = r_size * c_size;
    question_size = float2int(q_num / 20 * size) + 1;
    num_on_bulbs = 0;
    node_list = new Array();
    base = ( r_size > c_size ) ? r_size : c_size ;
    for (var r = 0; r < r_size; ++r) {
        board[r]= new Array();
        index[r] = new Array()
        var idx = 'row' + r;
        for( var c = 0 ; c < c_size ; ++c){
            node_list[ r * c_size + c ] = ( r * base + c  );
            board[r][c] = false;
            index[r][c] = new Array();
            for(var on = 0 ; on < 2 ; on++ )
            {
                index[r][c][on] = idx + "col" + c + '_' + on;
            }
        }
    }
}

function build_board(row_num, col_num, q_num) {
    init(row_num, col_num, q_num);
    $("#Board").empty();
    for (var r = 0; r < r_size; r++) {
        var cur_row = "
";
        for (var c = 0; c < c_size; c++) {
            cur_row += '';

            for( var on = 0 ; on < 2 ; on++ )
                cur_row += bulb_start[on] + index[r][c][on] + '" ' +
                    'onclick    ="once_click('+r+','+c+')" ' +
                    'onmouseover="square_color_fill('+r+','+c+','+"'#BCF5A9'"+')" ' +
                    'onmouseout ="square_color_fill('+r+','+c+','+"'pink'" + ')" ' +
                    img_end ;

            cur_row += "	" ;
        }
        cur_row += "
";
        $("#Board").append( cur_row );
        for( var c = 0 ; c < c_size ; c++ )
            $("#" + index[r][c][1]).toggle();

    }
}

$(document).ready(function(){

//preload images
var images  = [
    "images/Keep-calm-and-carry-on-scan.jpg",
    "images/neutral-indeed-small.png"
];
var image_url;
for( image_url in images ){
    var img = new Image(0,0);
    img.src = image_url;
}

    build_board(5, 5, 4);
    while(num_on_bulbs == 0)
        random_question(question_size);

    $('#set').click(function(){
        var row_num = parseInt($('#row_num').val(), 10);
        var col_num = parseInt($('#col_num').val(), 10);
        var q_num = parseInt($('#q_num').val(), 10);
        if (isNaN(row_num) || isNaN(col_num) || isNaN(q_num)) {
            swal({
                title: 'Error',
                text: 'Integers only.',
                type: 'error'
            });
        } else if (row_num < 3 || col_num < 3 || q_num < 1 || q_num > 10) {
            swal({
                title: 'Error',
                text: 'Note the input range.',
                type: 'error'
            });
        } else {
            build_board(row_num, col_num, q_num);
            while (num_on_bulbs == 0)
                random_question(question_size);
        }
    });

});
<|endoftext|>