<commit_before>var prev, next;
var values = [];  // 0 - start 1 - name, 2 - date, 3/4/5 - coords, 6 - order, 7 - world, 8 - timeRadius, 9 - coordsRadius, 10 - action, 11 - count, (12 - submit origin)
function main() {
    var items = location.search.substr(1).split("&");
    for (var i = 0; i < items.length; i++) {
        var tmp = items[i].split("=");
        values[i] = tmp[1];
        if (values[i] === null) {
            values[i] = "";
        }
    }
    if (values[6] === 0) {
        prev = parseInt(values[0]) + parseInt(values[11]);
        next = parseInt(values[0]) - parseInt(values[11]);
    } else if (values[6] === 1) {
        prev = parseInt(values[0]) - parseInt(values[11]);
        next = parseInt(values[0]) + parseInt(values[11]);
    }
    if (prev < 0) {
        prev = 0;
    }
    if (next < 0) {
        next = 0;
    }

    if (location.search != "") {
        $("#name").val(values[1]);
        $("#date").val(values[2]);
        $("#X").val(values[3]);
        $("#Y").val(values[4]);
        $("#Z").val(values[5]);
        if (values[6] === "0") {
            $("#radio1").attr("checked", true);
            $("#radio2").attr("checked", false);
        } else if (values[6] === "1") {
            $("#radio2").attr("checked", true);
            $("#radio1").attr("checked", false);
        }
        $("#world").val(values[7]);
        $("#timeRadius").val(values[8]);
        $("#coordsRadius").val(values[9]);
        $("#action").val(values[10]);
        $("#count").val(values[11]);
    }

    $(".button").button();
    $("#radioset").buttonset();
    $("#world").selectmenu();
    $("#action").selectmenu();
    $("#date").datetimepicker({
        controlType: "select",
        oneLine: true,
        dateFormat: "yy-mm-dd",
        timeFormat: "HH:mm:ss"
    });
    $("#timeRadius").timepicker({
        controlType: "select",
        oneLine: true,
        timeFormat: "H:m"
    });
}

function change(place) { // ?start=&name=&date=&X=&Y=&Z=&order=&world=&timeRadius=&coordsRadius=&action=&count=&submit=
    if (place === "prev") {
        location.search = "?start=" + prev + "&name=" + values[1] + "&date=" + values[2] + "&X=" + values[3] + "&Y=" + values[4] + "&Z=" + values[5] + "&order=" + values[6] + "&world=" + values[7] + "&timeRadius=" + values[8] + "&coordsRadius=" + values[9] + "&action=" + values[10] + "&count=" + values[11] + "&submit=Prev";
    } else if (place === "next") {
        location.search = "?start=" + next + "&name=" + values[1] + "&date=" + values[2] + "&X=" + values[3] + "&Y=" + values[4] + "&Z=" + values[5] + "&order=" + values[6] + "&world=" + values[7] + "&timeRadius=" + values[8] + "&coordsRadius=" + values[9] + "&action=" + values[10] + "&count=" + values[11] + "&submit=Next";
    }
}<commit_msg>Paging fix.<commit_after>var prev, next;
var values = [];  // 0 - start 1 - name, 2 - date, 3/4/5 - coords, 6 - order, 7 - world, 8 - timeRadius, 9 - coordsRadius, 10 - action, 11 - count, (12 - submit origin)
function main() {
    var items = location.search.substr(1).split("&");
    for (var i = 0; i < items.length; i++) {
        var tmp = items[i].split("=");
        values[i] = tmp[1];
        if (values[i] === null) {
            values[i] = "";
        }
    }
    if (values[6] === "0") {
        prev = parseInt(values[0]) + parseInt(values[11]);
        next = parseInt(values[0]) - parseInt(values[11]);
    } else if (values[6] === "1") {
        prev = parseInt(values[0]) - parseInt(values[11]);
        next = parseInt(values[0]) + parseInt(values[11]);
    }
    if (prev < 0) {
        prev = 0;
    }
    if (next < 0) {
        next = 0;
    }

    if (location.search != "") {
        $("#name").val(values[1]);
        $("#date").val(values[2]);
        $("#X").val(values[3]);
        $("#Y").val(values[4]);
        $("#Z").val(values[5]);
        if (values[6] === "0") {
            $("#radio1").attr("checked", true);
            $("#radio2").attr("checked", false);
        } else if (values[6] === "1") {
            $("#radio2").attr("checked", true);
            $("#radio1").attr("checked", false);
        }
        $("#world").val(values[7]);
        $("#timeRadius").val(values[8]);
        $("#coordsRadius").val(values[9]);
        $("#action").val(values[10]);
        $("#count").val(values[11]);
    }

    $(".button").button();
    $("#radioset").buttonset();
    $("#world").selectmenu();
    $("#action").selectmenu();
    $("#date").datetimepicker({
        controlType: "select",
        oneLine: true,
        dateFormat: "yy-mm-dd",
        timeFormat: "HH:mm:ss"
    });
    $("#timeRadius").timepicker({
        controlType: "select",
        oneLine: true,
        timeFormat: "H:m"
    });
}

function change(place) { // ?start=&name=&date=&X=&Y=&Z=&order=&world=&timeRadius=&coordsRadius=&action=&count=&submit=
    if (place === "prev") {
        location.search = "?start=" + prev + "&name=" + values[1] + "&date=" + values[2] + "&X=" + values[3] + "&Y=" + values[4] + "&Z=" + values[5] + "&order=" + values[6] + "&world=" + values[7] + "&timeRadius=" + values[8] + "&coordsRadius=" + values[9] + "&action=" + values[10] + "&count=" + values[11] + "&submit=Prev";
    } else if (place === "next") {
        location.search = "?start=" + next + "&name=" + values[1] + "&date=" + values[2] + "&X=" + values[3] + "&Y=" + values[4] + "&Z=" + values[5] + "&order=" + values[6] + "&world=" + values[7] + "&timeRadius=" + values[8] + "&coordsRadius=" + values[9] + "&action=" + values[10] + "&count=" + values[11] + "&submit=Next";
    }
}<|endoftext|>


<commit_before>(function(Handsontable){
  'use strict';

  Handsontable.EditorManager = function(instance, priv, selection){
    var that = this;
    var $document = $(document);
    var keyCodes = Handsontable.helper.keyCode;

    var activeEditor;

    var init = function () {

      function onKeyDown(event) {

        if (!instance.isListening()) {
          return;
        }

        if (priv.settings.beforeOnKeyDown) { // HOT in HOT Plugin
          priv.settings.beforeOnKeyDown.call(instance, event);
        }

        Handsontable.hooks.run(instance, 'beforeKeyDown', event);

        if (!event.isImmediatePropagationStopped()) {

          priv.lastKeyCode = event.keyCode;
          if (selection.isSelected()) {
            var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)

            if (!activeEditor.isWaiting()) {
              if (!Handsontable.helper.isMetaKey(event.keyCode) && !ctrlDown && !that.isEditorOpened()) {

                var charCode = event.which || event.keyCode;
                var charStr = String.fromCharCode(charCode);
                if (event.keyCode < 96) {
                  charStr = charStr.toLowerCase();
                }

                that.openEditor(charStr);
                event.preventDefault();
                event.stopPropagation(); //required by HandsontableEditor
                return;
              }
            }

            var rangeModifier = event.shiftKey ? selection.setRangeEnd : selection.setRangeStart;

              switch (event.keyCode) {

                case keyCodes.A:
                  if (ctrlDown) {
                    selection.selectAll(); //select all cells

                    event.preventDefault();
                    event.stopPropagation();
                    break;
                  }

                case keyCodes.ARROW_UP:

                  if (that.isEditorOpened() && !activeEditor.isWaiting()){
                    that.closeEditorAndSaveChanges(ctrlDown);
                  }

                  moveSelectionUp(event.shiftKey);

                  event.preventDefault();
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.ARROW_DOWN:
                  if (that.isEditorOpened() && !activeEditor.isWaiting()){
                    that.closeEditorAndSaveChanges(ctrlDown);
                  }

                  moveSelectionDown(event.shiftKey);

                  event.preventDefault();
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.ARROW_RIGHT:
                  if(that.isEditorOpened()  && !activeEditor.isWaiting()){
                    that.closeEditorAndSaveChanges(ctrlDown);
                  }

                  moveSelectionRight(event.shiftKey);

                  event.preventDefault();
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.ARROW_LEFT:
                  if(that.isEditorOpened() && !activeEditor.isWaiting()){
                    that.closeEditorAndSaveChanges(ctrlDown);
                  }

                  moveSelectionLeft(event.shiftKey);

                  event.preventDefault();
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.TAB:
                  var tabMoves = typeof priv.settings.tabMoves === 'function' ? priv.settings.tabMoves(event) : priv.settings.tabMoves;
                  if (event.shiftKey) {
                    selection.transformStart(-tabMoves.row, -tabMoves.col); //move selection left
                  }
                  else {
                    selection.transformStart(tabMoves.row, tabMoves.col, true); //move selection right (add a new column if needed)
                  }
                  event.preventDefault();
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.BACKSPACE:
                case keyCodes.DELETE:
                  selection.empty(event);
                  that.prepareEditor();
                  event.preventDefault();
                  break;

                case keyCodes.F2: /* F2 */
                  that.openEditor();
                  event.preventDefault(); //prevent Opera from opening Go to Page dialog
                  break;

                case keyCodes.ENTER: /* return/enter */
                  if(that.isEditorOpened()){

                    if (activeEditor.state !== Handsontable.EditorState.WAITING){
                      that.closeEditorAndSaveChanges(ctrlDown);
                    }

                    moveSelectionAfterEnter(event.shiftKey);

                  } else {

                    if (instance.getSettings().enterBeginsEditing){
                      that.openEditor();
                    } else {
                      moveSelectionAfterEnter(event.shiftKey);
                    }

                  }

                  event.preventDefault(); //don't add newline to field
                  event.stopImmediatePropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.ESCAPE:
                  if(that.isEditorOpened()){
                    that.closeEditorAndRestoreOriginalValue(ctrlDown);
                  }
                  event.preventDefault();
                  break;

                case keyCodes.HOME:
                  if (event.ctrlKey || event.metaKey) {
                    rangeModifier(new WalkontableCellCoords(0, priv.selRange.from.col));
                  }
                  else {
                    rangeModifier(new WalkontableCellCoords(priv.selRange.from.row, 0));
                  }
                  event.preventDefault(); //don't scroll the window
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.END:
                  if (event.ctrlKey || event.metaKey) {
                    rangeModifier(new WalkontableCellCoords(instance.countRows() - 1, priv.selRange.from.col));
                  }
                  else {
                    rangeModifier(new WalkontableCellCoords(priv.selRange.from.row, instance.countCols() - 1));
                  }
                  event.preventDefault(); //don't scroll the window
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.PAGE_UP:
                  selection.transformStart(-instance.countVisibleRows(), 0);
                  instance.view.wt.scrollVertical(-instance.countVisibleRows());
                  instance.view.render();
                  event.preventDefault(); //don't page up the window
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.PAGE_DOWN:
                  selection.transformStart(instance.countVisibleRows(), 0);
                  instance.view.wt.scrollVertical(instance.countVisibleRows());
                  instance.view.render();
                  event.preventDefault(); //don't page down the window
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                default:
                  break;
              }

          }
        }
      }
      $document.on('keydown.handsontable.' + instance.guid, onKeyDown);

      function onDblClick(event, coords, elem) {
        if(elem.nodeName == "TD") { //may be TD or TH
          //that.instance.destroyEditor();
          that.openEditor();
        }
      }

      instance.view.wt.update('onCellDblClick', onDblClick);

      instance.addHook('afterDestroy', function(){
        $document.off('keydown.handsontable.' + instance.guid);
      });

      function moveSelectionAfterEnter(shiftKey){
        var enterMoves = typeof priv.settings.enterMoves === 'function' ? priv.settings.enterMoves(event) : priv.settings.enterMoves;

        if (shiftKey) {
          selection.transformStart(-enterMoves.row, -enterMoves.col); //move selection up
        }
        else {
          selection.transformStart(enterMoves.row, enterMoves.col, true); //move selection down (add a new row if needed)
        }
      }

      function moveSelectionUp(shiftKey){
        if (shiftKey) {
          selection.transformEnd(-1, 0);
        }
        else {
          selection.transformStart(-1, 0);
        }
      }

      function moveSelectionDown(shiftKey){
        if (shiftKey) {
          selection.transformEnd(1, 0); //expanding selection down with shift
        }
        else {
          selection.transformStart(1, 0); //move selection down
        }
      }

      function moveSelectionRight(shiftKey){
        if (shiftKey) {
          selection.transformEnd(0, 1);
        }
        else {
          selection.transformStart(0, 1);
        }
      }

      function moveSelectionLeft(shiftKey){
        if (shiftKey) {
          selection.transformEnd(0, -1);
        }
        else {
          selection.transformStart(0, -1);
        }
      }
    };

    /**
     * Destroy current editor, if exists
     * @param {Boolean} revertOriginal
     */
    this.destroyEditor = function (revertOriginal) {
      this.closeEditor(revertOriginal);
    };

    this.getActiveEditor = function () {
      return activeEditor;
    };

    /**
     * Prepare text input to be displayed at given grid cell
     */
    this.prepareEditor = function () {

      if (activeEditor && activeEditor.isWaiting()){

        this.closeEditor(false, false, function(dataSaved){
          if(dataSaved){
            that.prepareEditor();
          }
        });

        return;
      }

      var row = priv.selRange.highlight.row;
      var col = priv.selRange.highlight.col;
      var prop = instance.colToProp(col);
      var td = instance.getCell(row, col);
      var originalValue = instance.getDataAtCell(row, col);
      var cellProperties = instance.getCellMeta(row, col);

      var editorClass = instance.getCellEditor(cellProperties);
      activeEditor = Handsontable.editors.getEditor(editorClass, instance);

      activeEditor.prepare(row, col, prop, td, originalValue, cellProperties);

    };

    this.isEditorOpened = function () {
      return activeEditor.isOpened();
    };

    this.openEditor = function (initialValue) {
      if (!activeEditor.cellProperties.readOnly){
        activeEditor.beginEditing(initialValue);
      }
    };

    this.closeEditor = function (restoreOriginalValue, ctrlDown, callback) {

      if (!activeEditor){
        if(callback) {
          callback(false);
        }
      }
      else {
        activeEditor.finishEditing(restoreOriginalValue, ctrlDown, callback);
      }
    };

    this.closeEditorAndSaveChanges = function(ctrlDown){
      return this.closeEditor(false, ctrlDown);
    };

    this.closeEditorAndRestoreOriginalValue = function(ctrlDown){
      return this.closeEditor(true, ctrlDown);
    };

    init();
  };

})(Handsontable);
<commit_msg>Fix for opening the editor with a uppercase letter starts entry with a lowercase letter #HOT-21<commit_after>(function(Handsontable){
  'use strict';

  Handsontable.EditorManager = function(instance, priv, selection){
    var that = this;
    var $document = $(document);
    var keyCodes = Handsontable.helper.keyCode;

    var activeEditor;

    var init = function () {

      function onKeyDown(event) {

        if (!instance.isListening()) {
          return;
        }

        if (priv.settings.beforeOnKeyDown) { // HOT in HOT Plugin
          priv.settings.beforeOnKeyDown.call(instance, event);
        }

        Handsontable.hooks.run(instance, 'beforeKeyDown', event);

        if (!event.isImmediatePropagationStopped()) {

          priv.lastKeyCode = event.keyCode;
          if (selection.isSelected()) {
            var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)

            if (!activeEditor.isWaiting()) {
              if (!Handsontable.helper.isMetaKey(event.keyCode) && !ctrlDown && !that.isEditorOpened()) {

                var charCode = event.keyCode;
                var charStr = String.fromCharCode(charCode);
                var isUp = (charCode >= 65 && charCode <= 90) ? true : false; // uppercase
                var isLow = (charCode >= 97 && charCode <= 122) ? true : false; // lowercase
                // uppercase w/out shift or lowercase with shift == caps lock
                if ((isUp && !event.shiftKey) || (isLow && event.shiftKey)) {
                  charStr = charStr.toLowerCase();
                }
                that.openEditor(charStr);

                event.preventDefault();
                event.stopPropagation(); //required by HandsontableEditor
                return;
              }
            }

            var rangeModifier = event.shiftKey ? selection.setRangeEnd : selection.setRangeStart;

              switch (event.keyCode) {

                case keyCodes.A:
                  if (ctrlDown) {
                    selection.selectAll(); //select all cells

                    event.preventDefault();
                    event.stopPropagation();
                    break;
                  }

                case keyCodes.ARROW_UP:

                  if (that.isEditorOpened() && !activeEditor.isWaiting()){
                    that.closeEditorAndSaveChanges(ctrlDown);
                  }

                  moveSelectionUp(event.shiftKey);

                  event.preventDefault();
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.ARROW_DOWN:
                  if (that.isEditorOpened() && !activeEditor.isWaiting()){
                    that.closeEditorAndSaveChanges(ctrlDown);
                  }

                  moveSelectionDown(event.shiftKey);

                  event.preventDefault();
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.ARROW_RIGHT:
                  if(that.isEditorOpened()  && !activeEditor.isWaiting()){
                    that.closeEditorAndSaveChanges(ctrlDown);
                  }

                  moveSelectionRight(event.shiftKey);

                  event.preventDefault();
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.ARROW_LEFT:
                  if(that.isEditorOpened() && !activeEditor.isWaiting()){
                    that.closeEditorAndSaveChanges(ctrlDown);
                  }

                  moveSelectionLeft(event.shiftKey);

                  event.preventDefault();
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.TAB:
                  var tabMoves = typeof priv.settings.tabMoves === 'function' ? priv.settings.tabMoves(event) : priv.settings.tabMoves;
                  if (event.shiftKey) {
                    selection.transformStart(-tabMoves.row, -tabMoves.col); //move selection left
                  }
                  else {
                    selection.transformStart(tabMoves.row, tabMoves.col, true); //move selection right (add a new column if needed)
                  }
                  event.preventDefault();
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.BACKSPACE:
                case keyCodes.DELETE:
                  selection.empty(event);
                  that.prepareEditor();
                  event.preventDefault();
                  break;

                case keyCodes.F2: /* F2 */
                  that.openEditor();
                  event.preventDefault(); //prevent Opera from opening Go to Page dialog
                  break;

                case keyCodes.ENTER: /* return/enter */
                  if(that.isEditorOpened()){

                    if (activeEditor.state !== Handsontable.EditorState.WAITING){
                      that.closeEditorAndSaveChanges(ctrlDown);
                    }

                    moveSelectionAfterEnter(event.shiftKey);

                  } else {

                    if (instance.getSettings().enterBeginsEditing){
                      that.openEditor();
                    } else {
                      moveSelectionAfterEnter(event.shiftKey);
                    }

                  }

                  event.preventDefault(); //don't add newline to field
                  event.stopImmediatePropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.ESCAPE:
                  if(that.isEditorOpened()){
                    that.closeEditorAndRestoreOriginalValue(ctrlDown);
                  }
                  event.preventDefault();
                  break;

                case keyCodes.HOME:
                  if (event.ctrlKey || event.metaKey) {
                    rangeModifier(new WalkontableCellCoords(0, priv.selRange.from.col));
                  }
                  else {
                    rangeModifier(new WalkontableCellCoords(priv.selRange.from.row, 0));
                  }
                  event.preventDefault(); //don't scroll the window
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.END:
                  if (event.ctrlKey || event.metaKey) {
                    rangeModifier(new WalkontableCellCoords(instance.countRows() - 1, priv.selRange.from.col));
                  }
                  else {
                    rangeModifier(new WalkontableCellCoords(priv.selRange.from.row, instance.countCols() - 1));
                  }
                  event.preventDefault(); //don't scroll the window
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.PAGE_UP:
                  selection.transformStart(-instance.countVisibleRows(), 0);
                  instance.view.wt.scrollVertical(-instance.countVisibleRows());
                  instance.view.render();
                  event.preventDefault(); //don't page up the window
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                case keyCodes.PAGE_DOWN:
                  selection.transformStart(instance.countVisibleRows(), 0);
                  instance.view.wt.scrollVertical(instance.countVisibleRows());
                  instance.view.render();
                  event.preventDefault(); //don't page down the window
                  event.stopPropagation(); //required by HandsontableEditor
                  break;

                default:
                  break;
              }

          }
        }
      }
      $document.on('keydown.handsontable.' + instance.guid, onKeyDown);

      function onDblClick(event, coords, elem) {
        if(elem.nodeName == "TD") { //may be TD or TH
          //that.instance.destroyEditor();
          that.openEditor();
        }
      }

      instance.view.wt.update('onCellDblClick', onDblClick);

      instance.addHook('afterDestroy', function(){
        $document.off('keydown.handsontable.' + instance.guid);
      });

      function moveSelectionAfterEnter(shiftKey){
        var enterMoves = typeof priv.settings.enterMoves === 'function' ? priv.settings.enterMoves(event) : priv.settings.enterMoves;

        if (shiftKey) {
          selection.transformStart(-enterMoves.row, -enterMoves.col); //move selection up
        }
        else {
          selection.transformStart(enterMoves.row, enterMoves.col, true); //move selection down (add a new row if needed)
        }
      }

      function moveSelectionUp(shiftKey){
        if (shiftKey) {
          selection.transformEnd(-1, 0);
        }
        else {
          selection.transformStart(-1, 0);
        }
      }

      function moveSelectionDown(shiftKey){
        if (shiftKey) {
          selection.transformEnd(1, 0); //expanding selection down with shift
        }
        else {
          selection.transformStart(1, 0); //move selection down
        }
      }

      function moveSelectionRight(shiftKey){
        if (shiftKey) {
          selection.transformEnd(0, 1);
        }
        else {
          selection.transformStart(0, 1);
        }
      }

      function moveSelectionLeft(shiftKey){
        if (shiftKey) {
          selection.transformEnd(0, -1);
        }
        else {
          selection.transformStart(0, -1);
        }
      }
    };

    /**
     * Destroy current editor, if exists
     * @param {Boolean} revertOriginal
     */
    this.destroyEditor = function (revertOriginal) {
      this.closeEditor(revertOriginal);
    };

    this.getActiveEditor = function () {
      return activeEditor;
    };

    /**
     * Prepare text input to be displayed at given grid cell
     */
    this.prepareEditor = function () {

      if (activeEditor && activeEditor.isWaiting()){

        this.closeEditor(false, false, function(dataSaved){
          if(dataSaved){
            that.prepareEditor();
          }
        });

        return;
      }

      var row = priv.selRange.highlight.row;
      var col = priv.selRange.highlight.col;
      var prop = instance.colToProp(col);
      var td = instance.getCell(row, col);
      var originalValue = instance.getDataAtCell(row, col);
      var cellProperties = instance.getCellMeta(row, col);

      var editorClass = instance.getCellEditor(cellProperties);
      activeEditor = Handsontable.editors.getEditor(editorClass, instance);

      activeEditor.prepare(row, col, prop, td, originalValue, cellProperties);

    };

    this.isEditorOpened = function () {
      return activeEditor.isOpened();
    };

    this.openEditor = function (initialValue) {
      if (!activeEditor.cellProperties.readOnly){
        activeEditor.beginEditing(initialValue);
      }
    };

    this.closeEditor = function (restoreOriginalValue, ctrlDown, callback) {

      if (!activeEditor){
        if(callback) {
          callback(false);
        }
      }
      else {
        activeEditor.finishEditing(restoreOriginalValue, ctrlDown, callback);
      }
    };

    this.closeEditorAndSaveChanges = function(ctrlDown){
      return this.closeEditor(false, ctrlDown);
    };

    this.closeEditorAndRestoreOriginalValue = function(ctrlDown){
      return this.closeEditor(true, ctrlDown);
    };

    init();
  };

})(Handsontable);
<|endoftext|>


<commit_before>'use strict';
var ES = require('es-abstract/es6');
var supportsDescriptors = require('define-properties').supportsDescriptors;
var has = require('has');
var global = require('system.global')();
var isString = require('is-string');
var isCallable = require('is-callable');

var parseIterable = function (iterator) {
	var done = false;
	var iterableResponse;
	var tempArray = [];

	if (iterator && typeof iterator.next === 'function') {
		while (!done) {
			iterableResponse = iterator.next();
			if (
				has(iterableResponse, 'value')
				&& has(iterableResponse, 'done')
			) {
				if (iterableResponse.done === true) {
					done = true;
					break; // eslint-disable-line no-restricted-syntax

				} else if (iterableResponse.done !== false) {
					break; // eslint-disable-line no-restricted-syntax
				}

				tempArray.push(iterableResponse.value);
			} else if (iterableResponse.done === true) {
				done = true;
				break; // eslint-disable-line no-restricted-syntax
			} else {
				break; // eslint-disable-line no-restricted-syntax
			}
		}
	}

	return done ? tempArray : false;
};

var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';
var iteratorSymbol;
var forOfOnly;
var hasSet = !!global.Set && isCallable(Set.prototype.values);
var hasMap = !!global.Map && isCallable(Map.prototype.entries);

if (hasSymbols) {
	iteratorSymbol = Symbol.iterator;
} else {
	var supportsStrIterator = (function () {
		try {
			var supported = false;
			var obj = { // eslint-disable-line no-unused-vars
				'@@iterator': function () {
					return {
						'next': function () {
							supported = true;
							return {
								'done': true,
								'value': undefined
							};
						}
					};
				}
			};

			Function('obj', // eslint-disable-line no-new-func
				'for (var x of obj) {}'
			)(obj);
			return supported;
		} catch (e) {
			return false;
		}
	}());

	if (supportsStrIterator) {
		iteratorSymbol = '@@iterator';
	} else if (hasMap) {
		var map = new Map();
		map.set(1, 2);
		var y;
		Function('map', 'y', 'for (var x of map) {y = x}')(map, y); // eslint-disable-line no-new-func
		if (y[0] === 1 && y[1] === 2) {
			forOfOnly = true;
		}
	}
}

var isSet;
if (hasSet) {
	var setSize = Object.getOwnPropertyDescriptor(Set.prototype, 'size').get;
	isSet = function (set) {
		try {
			setSize.call(set);
			return true;
		} catch (e) {
			return false;
		}
	};
}

var isMap;
if (hasMap) {
	var mapSize = Object.getOwnPropertyDescriptor(Map.prototype, 'size').get;
	isMap = function (m) {
		try {
			mapSize.call(m);
			return true;
		} catch (e) {
			return false;
		}
	};
}

var setValues = hasSet && Set.prototype.values;
var mapEntries = hasMap && Map.prototype.entries;
var usingIterator = function (items) {
	if (has(items, iteratorSymbol)) {
		return items[iteratorSymbol]();
	} else if (hasSet && isSet(items)) {
		return setValues.call(items);
	} else if (hasMap && isMap(items)) {
		return mapEntries.call(items);
	}
	return items;
};

var strMatch = String.prototype.match;

/*! https://mths.be/array-from v0.2.0 by @mathias */
module.exports = function from(arrayLike) {
	var defineProperty = supportsDescriptors ? Object.defineProperty : function put(object, key, descriptor) {
		object[key] = descriptor.value;
	};
	var C = this;
	if (arrayLike === null || typeof arrayLike === 'undefined') {
		throw new TypeError('`Array.from` requires an array-like object, not `null` or `undefined`');
	}
	var items = ES.ToObject(arrayLike);

	var mapFn, T;
	if (typeof arguments[1] !== 'undefined') {
		mapFn = arguments[1];
		if (!ES.IsCallable(mapFn)) {
			throw new TypeError('When provided, the second argument to `Array.from` must be a function');
		}
		if (arguments.length > 2) {
			T = arguments[2];
		}
	}

	var len = ES.ToLength(items.length);
	var A = ES.IsCallable(C) ? ES.ToObject(new C(len)) : new Array(len);
	var k = 0;
	var kValue, mappedValue;

	// variables for rebuilding array from iterator
	var arrayFromIterable = parseIterable(usingIterator(arrayLike));

	if (arrayFromIterable) {
		items = arrayFromIterable;
		len = arrayFromIterable.length;
	} else if (isString(items)) {
		items = strMatch.call(items, /[\uD800-\uDBFF][\uDC00-\uDFFF]?|[^\uD800-\uDFFF]|./g) || [];
		len = items.length;
	} else if (forOfOnly) {
		try {
			// Safari 8's native Map or Set can't be iterated except with for..of
			return Function('items', 'arrayLike', 'var arr = []; for (var entry of arrayLike) { arr.push(entry); } return arr')(); // eslint-disable-line no-new-func
		} catch (e) {
			/* for..of seems to not be supported, fallback to basic iteration */
		}
	}

	while (k < len) {
		kValue = items[k];
		if (mapFn) {
			mappedValue = typeof T === 'undefined' ? mapFn(kValue, k) : ES.Call(mapFn, T, [kValue, k]);
		} else {
			mappedValue = kValue;
		}
		defineProperty(A, k, {
			'configurable': true,
			'enumerable': true,
			'value': mappedValue,
			'writable': true
		});
		k += 1;
	}
	A.length = len;
	return A;
};
<commit_msg>Don't use unexpected side-effects<commit_after>'use strict';
var ES = require('es-abstract/es6');
var supportsDescriptors = require('define-properties').supportsDescriptors;
var has = require('has');
var global = require('system.global')();
var isString = require('is-string');
var isCallable = require('is-callable');

var parseIterable = function (iterator) {
	var done = false;
	var iterableResponse;
	var tempArray = [];

	if (iterator && typeof iterator.next === 'function') {
		while (!done) {
			iterableResponse = iterator.next();
			if (
				has(iterableResponse, 'value')
				&& has(iterableResponse, 'done')
			) {
				if (iterableResponse.done === true) {
					done = true;
					break; // eslint-disable-line no-restricted-syntax

				} else if (iterableResponse.done !== false) {
					break; // eslint-disable-line no-restricted-syntax
				}

				tempArray.push(iterableResponse.value);
			} else if (iterableResponse.done === true) {
				done = true;
				break; // eslint-disable-line no-restricted-syntax
			} else {
				break; // eslint-disable-line no-restricted-syntax
			}
		}
	}

	return done ? tempArray : false;
};

var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';
var iteratorSymbol;
var forOf;
var hasSet = !!global.Set && isCallable(Set.prototype.values);
var hasMap = !!global.Map && isCallable(Map.prototype.entries);

if (hasSymbols) {
	iteratorSymbol = Symbol.iterator;
} else {
	var supportsStrIterator = (function () {
		try {
			var supported = false;
			var obj = { // eslint-disable-line no-unused-vars
				'@@iterator': function () {
					return {
						'next': function () {
							supported = true;
							return {
								'done': true,
								'value': undefined
							};
						}
					};
				}
			};

			Function('obj', // eslint-disable-line no-new-func
				'for (var x of obj) {}'
			)(obj);
			return supported;
		} catch (e) {
			return false;
		}
	}());

	if (supportsStrIterator) {
		iteratorSymbol = '@@iterator';
	} else {
		try {
			if (Function('for (var x of [0]) x;')() === 0) { // eslint-disable-line no-new-func
				forOf = Function('iterable', 'var arr = []; for (var value of iterable) arr.push(value); return arr;'); // eslint-disable-line no-new-func
			}
		} catch (e) {
		}
	}
}

var isSet;
if (hasSet) {
	var setSize = Object.getOwnPropertyDescriptor(Set.prototype, 'size').get;
	isSet = function (set) {
		try {
			setSize.call(set);
			return true;
		} catch (e) {
			return false;
		}
	};
}

var isMap;
if (hasMap) {
	var mapSize = Object.getOwnPropertyDescriptor(Map.prototype, 'size').get;
	isMap = function (m) {
		try {
			mapSize.call(m);
			return true;
		} catch (e) {
			return false;
		}
	};
}

var setValues = hasSet && Set.prototype.values;
var mapEntries = hasMap && Map.prototype.entries;
var usingIterator = function (items) {
	if (has(items, iteratorSymbol)) {
		return items[iteratorSymbol]();
	} else if (hasSet && isSet(items)) {
		return setValues.call(items);
	} else if (hasMap && isMap(items)) {
		return mapEntries.call(items);
	}
	return items;
};

var strMatch = String.prototype.match;

/*! https://mths.be/array-from v0.2.0 by @mathias */
module.exports = function from(arrayLike) {
	var defineProperty = supportsDescriptors ? Object.defineProperty : function put(object, key, descriptor) {
		object[key] = descriptor.value;
	};
	var C = this;
	if (arrayLike === null || typeof arrayLike === 'undefined') {
		throw new TypeError('`Array.from` requires an array-like object, not `null` or `undefined`');
	}
	var items = ES.ToObject(arrayLike);

	var mapFn, T;
	if (typeof arguments[1] !== 'undefined') {
		mapFn = arguments[1];
		if (!ES.IsCallable(mapFn)) {
			throw new TypeError('When provided, the second argument to `Array.from` must be a function');
		}
		if (arguments.length > 2) {
			T = arguments[2];
		}
	}

	var len = ES.ToLength(items.length);
	var A = ES.IsCallable(C) ? ES.ToObject(new C(len)) : new Array(len);
	var k = 0;
	var kValue, mappedValue;

	// variables for rebuilding array from iterator
	var arrayFromIterable = parseIterable(usingIterator(arrayLike));

	if (arrayFromIterable) {
		items = arrayFromIterable;
		len = arrayFromIterable.length;
	} else if (isString(items)) {
		items = strMatch.call(items, /[\uD800-\uDBFF][\uDC00-\uDFFF]?|[^\uD800-\uDFFF]|./g) || [];
		len = items.length;
	} else if (forOf) {
		// Safari 8's native Map or Set can't be iterated except with for..of
		items = forOf(items);
		len = items.length;
	}

	while (k < len) {
		kValue = items[k];
		if (mapFn) {
			mappedValue = typeof T === 'undefined' ? mapFn(kValue, k) : ES.Call(mapFn, T, [kValue, k]);
		} else {
			mappedValue = kValue;
		}
		defineProperty(A, k, {
			'configurable': true,
			'enumerable': true,
			'value': mappedValue,
			'writable': true
		});
		k += 1;
	}
	A.length = len;
	return A;
};
<|endoftext|>


<commit_before>/* npm deps */
stream  = require('stream');
http    = require('http');
url     = require('url');
express = require('express');
git     = require('git-rev');
ffmpeg  = require('fluent-ffmpeg');
require('array.prototype.findindex');

/* internal deps */
config = require('./channels_config');
streams = require('./lib/stream-manager');
changlue = require('./lib/channels-glue');

/*
 * express webapp: expose a number of endpoints and APIs
 */
var app = express();

app.get('/', function (req, res) {
        res.send("node-iptv-proxy");
});

app.get('/list', function(req, res) {
        /* list available channels */
        res.send({ channels: Object.keys(config.channels) });
});

app.get('/playlist', function(req, res) {
        var playlist = "";

        res.header("Content-Type", "audio/x-mpegurl");

        playlist += '#EXTM3U\r\n';
        Object.keys(config.channels).map(function(val) {
                playlist += '#EXTINF:-1 tvg-name="' + val + '",' + val + '\r\n';
                playlist += 'http://' + req.headers['host'] + '/stream/' + val+ '\r\n';
        });

        res.send(playlist);
});

app.get('/version', function(req, res) {
        git.short(function(commit) {
                res.send({ version: commit });
        });
});

app.get('/status', function(req, res){
        function decode_authdata(headers) {
                var username = "";
                try {
                        username = new Buffer(headers['authorization'].replace("Basic ",""), 'base64')
                                .toString().split(':')[0];
                } catch(e) {
                        username = "none";
                }

                return username;
        }

        function get_http_stats(client) {
                try {
                        return {
                                sent: client.socket.bytesWritten,
                                remoteAddr: client.req.headers['x-forwarded-for']
                                            || client.req.connection.remoteAddress,
                                remotePort: client.socket.remotePort,
                                username: decode_authdata(client.req.headers)
                        };
                } catch(e) {
                        return {
                                sent: 0,
                                remoteAddr: "127.0.0.1",
                                remotePort: 0,
                                username: "internal"
                        };
                }
        }

        /* reply with some useful info / statistics */
        res.send({
                streams: streams.current.map(function(el) {
                        return { id: el.id,
                                clients: el.clients.map(function(el) {
                                        return get_http_stats(el);
                                })
                        };
                })
        });
});

app.get('/transcode/:chan/:profile?', function(req, res) {
        if (!config.transcode) {
                res.send(404, "Transcoding not enabled");
                return;
        }

        var chan = req.params.chan;
        var profile = req.params.profile || config.transcode["default"];

        if (profile == "disable" || !config.transcode[profile]) {
                res.send(404, "Invalid profile");
                return;
        }

        console.log("TRANSCODE: " + chan + " " + profile);

        /* check wether the channel is already being transcoded*/
        changlue.try_chan("trans-" + profile + "-" + chan, function(liveStream) {
                res.set(liveStream.headers);
                streams.addClient("trans-" + profile + "-" + chan, res);
        }, function() {
                /* if not, grab the corresponding (uncompressed) source stream
                 * and fire up ffmpeg */
                changlue.get_chan(chan, function(sourceStream) {
                        var fakeClient = new (stream.PassThrough)({allowHalfOpen: false});
                        var transcodedChan = new (stream.PassThrough)();

                        res.writeHead(200, sourceStream.headers);

                        /* register fake (internal) client on source stream */
                        streams.addClient(chan, fakeClient);

                        /* register new transcoding channel and attach actual client to it */
                        streams.addChan("trans-" + profile + "-" + chan,
                                        transcodedChan, sourceStream.headers,
                                        function() {
                                                fakeClient.end();

                                                /* FIXME: hackish, for some reason end
                                                 *  doesn't always trigger this */
                                                streams.killClient(chan, fakeClient);
                                        });
                        streams.addClient("trans-" + profile + "-" + chan, res);

                        /* start encoding */
                        config.transcode[profile](new ffmpeg({ source: fakeClient }))
                                .fromFormat('mpegts')
                                .toFormat('mpegts')
                                .on('error', function (e) {
                                        console.log("FFMPEG_ERRROR: " + e.message);

                                        res.end();
                                        streams.killChan("trans-" + profile + "-" + chan);
                                })
                                .writeToStream(transcodedChan);
                }, function() {
                        res.send(503, "Failed to start stream");
                });
        });
});

app.get('/stream/:chan', function(req, res) {
        var chan = req.params.chan;

        changlue.get_chan(chan, function(liveStream) {
                res.set(liveStream.headers);
                streams.addClient(chan, res);
        }, function(err) {
                if (err == "NotFound")
                        res.send(404, "not found");
                else
                        res.send(503, "Failed to start stream");
        });
});

app.listen(config.server.port);
<commit_msg>api: pretty print JSON responses<commit_after>/* npm deps */
stream  = require('stream');
http    = require('http');
url     = require('url');
express = require('express');
git     = require('git-rev');
ffmpeg  = require('fluent-ffmpeg');
require('array.prototype.findindex');

/* internal deps */
config = require('./channels_config');
streams = require('./lib/stream-manager');
changlue = require('./lib/channels-glue');

/*
 * express webapp: expose a number of endpoints and APIs
 */
var app = express();

app.set('json spaces', 2);

app.get('/', function (req, res) {
        res.send("node-iptv-proxy");
});

app.get('/list', function(req, res) {
        /* list available channels */
        res.json({ channels: Object.keys(config.channels) });
});

app.get('/playlist', function(req, res) {
        var playlist = "";

        res.header("Content-Type", "audio/x-mpegurl");

        playlist += '#EXTM3U\r\n';
        Object.keys(config.channels).map(function(val) {
                playlist += '#EXTINF:-1 tvg-name="' + val + '",' + val + '\r\n';
                playlist += 'http://' + req.headers['host'] + '/stream/' + val+ '\r\n';
        });

        res.send(playlist);
});

app.get('/version', function(req, res) {
        git.short(function(commit) {
                res.json({ version: commit });
        });
});

app.get('/status', function(req, res){
        function decode_authdata(headers) {
                var username = "";
                try {
                        username = new Buffer(headers['authorization'].replace("Basic ",""), 'base64')
                                .toString().split(':')[0];
                } catch(e) {
                        username = "none";
                }

                return username;
        }

        function get_http_stats(client) {
                try {
                        return {
                                sent: client.socket.bytesWritten,
                                remoteAddr: client.req.headers['x-forwarded-for']
                                            || client.req.connection.remoteAddress,
                                remotePort: client.socket.remotePort,
                                username: decode_authdata(client.req.headers)
                        };
                } catch(e) {
                        return {
                                sent: 0,
                                remoteAddr: "127.0.0.1",
                                remotePort: 0,
                                username: "internal"
                        };
                }
        }

        /* reply with some useful info / statistics */
        res.json({
                streams: streams.current.map(function(el) {
                        return { id: el.id,
                                clients: el.clients.map(function(el) {
                                        return get_http_stats(el);
                                })
                        };
                })
        });
});

app.get('/transcode/:chan/:profile?', function(req, res) {
        if (!config.transcode) {
                res.send(404, "Transcoding not enabled");
                return;
        }

        var chan = req.params.chan;
        var profile = req.params.profile || config.transcode["default"];

        if (profile == "disable" || !config.transcode[profile]) {
                res.send(404, "Invalid profile");
                return;
        }

        console.log("TRANSCODE: " + chan + " " + profile);

        /* check wether the channel is already being transcoded*/
        changlue.try_chan("trans-" + profile + "-" + chan, function(liveStream) {
                res.set(liveStream.headers);
                streams.addClient("trans-" + profile + "-" + chan, res);
        }, function() {
                /* if not, grab the corresponding (uncompressed) source stream
                 * and fire up ffmpeg */
                changlue.get_chan(chan, function(sourceStream) {
                        var fakeClient = new (stream.PassThrough)({allowHalfOpen: false});
                        var transcodedChan = new (stream.PassThrough)();

                        res.writeHead(200, sourceStream.headers);

                        /* register fake (internal) client on source stream */
                        streams.addClient(chan, fakeClient);

                        /* register new transcoding channel and attach actual client to it */
                        streams.addChan("trans-" + profile + "-" + chan,
                                        transcodedChan, sourceStream.headers,
                                        function() {
                                                fakeClient.end();

                                                /* FIXME: hackish, for some reason end
                                                 *  doesn't always trigger this */
                                                streams.killClient(chan, fakeClient);
                                        });
                        streams.addClient("trans-" + profile + "-" + chan, res);

                        /* start encoding */
                        config.transcode[profile](new ffmpeg({ source: fakeClient }))
                                .fromFormat('mpegts')
                                .toFormat('mpegts')
                                .on('error', function (e) {
                                        console.log("FFMPEG_ERRROR: " + e.message);

                                        res.end();
                                        streams.killChan("trans-" + profile + "-" + chan);
                                })
                                .writeToStream(transcodedChan);
                }, function() {
                        res.send(503, "Failed to start stream");
                });
        });
});

app.get('/stream/:chan', function(req, res) {
        var chan = req.params.chan;

        changlue.get_chan(chan, function(liveStream) {
                res.set(liveStream.headers);
                streams.addClient(chan, res);
        }, function(err) {
                if (err == "NotFound")
                        res.send(404, "not found");
                else
                        res.send(503, "Failed to start stream");
        });
});

app.listen(config.server.port);
<|endoftext|>


<commit_before>import { Component, Modal } from 'substance'
import EntityEditor from '../../entities/EntityEditor'
import entityRenderers from '../../entities/entityRenderers'

export default class Bibliography extends Component {

  getInitialState() {
    return {
      entityId: undefined
    }
  }

  render($$) {
    let el = $$('div').addClass('sc-bibliography')
    let editorSession = this.context.editorSession
    let entityDb = this.context.editorSession.getDocument()

    if (this.state.editEntity) {
      var modal = $$(Modal, {
        width: 'medium',
        textAlign: 'center'
      })

      modal.append(
        $$(EntityEditor, {
          editorSession: editorSession,
          node: entityDb.get(this.state.entityId)
        })
      )
    }

    this.context.referenceManager.getBibliography().forEach((reference) => {
      let fragments = entityRenderers[reference.type]($$, reference.id, entityDb)
      el.append(
        $$('div').addClass('se-reference').append(
          $$('div').addClass('se-text').append(
            ...fragments
          ),
          $$('div').addClass('se-actions').append(
            $$('button').append('Edit').on('click', this._toggleEditor.bind(this, reference.id)),
            $$('button').append('Delete')
          )
        )
      )
    })
    return el
  }

  _toggleEditor(referenceId) {
    console.log('TODO: open editor for ', referenceId)
  }
}
<commit_msg>Linting.<commit_after>import { Component, Modal } from 'substance'
import EntityEditor from '../../entities/EntityEditor'
import entityRenderers from '../../entities/entityRenderers'

export default class Bibliography extends Component {

  getInitialState() {
    return {
      entityId: undefined
    }
  }

  render($$) {
    let el = $$('div').addClass('sc-bibliography')
    let editorSession = this.context.editorSession
    let entityDb = this.context.editorSession.getDocument()

    if (this.state.editEntity) {
      var modal = $$(Modal, {
        width: 'medium',
        textAlign: 'center'
      })

      modal.append(
        $$(EntityEditor, {
          editorSession: editorSession,
          node: entityDb.get(this.state.entityId)
        })
      )
    }

    this.context.referenceManager.getBibliography().forEach((reference) => {
      let fragments = entityRenderers[reference.type]($$, reference.id, entityDb)
      el.append(
        $$('div').addClass('se-reference').append(
          $$('div').addClass('se-text').append(
            ...fragments
          ),
          $$('div').addClass('se-actions').append(
            $$('button').append('Edit').on('click', this._toggleEditor.bind(this, reference.id)),
            $$('button').append('Delete')
          )
        )
      )
    })
    return el
  }

  _toggleEditor(referenceId) {
    console.warn('TODO: open editor for ', referenceId)
  }
}
<|endoftext|>


<commit_before>/* This is an experimental loader for ShaderToys. It will attempt to load
 * the shader indicated by the "shader" variable in the URL.
 */
RendererConfig.dome.fullSphere    = false;

var textureLoader = new THREE.TextureLoader();

function setupScene(scene) {
    const apiKey = "BdHtW4";

    alert("ShaderToys are generally licensed for non-commercial use (CC-BY-NC-SA 3.0).\nFor non-free exhibition, contact the author via the ShaderToy link.");

    var mesh;

    function processShader(data) {
        var shader = JSON.parse(data).Shader;

        console.log(shader.info.name, "by", shader.info.username, shader);

        if(shader.renderpass.length > 1) {
            console.log("Warning: Multiple render passes not currently supported");
        }

        var material;
        var fragmentShader = shader.renderpass[0].code;
        var shaderInputs   = shader.renderpass[0].inputs;
        var textures       = [];
        var samplerTypes   = ["sampler2D", "sampler2D", "sampler2D", "sampler2D"];

        for(var i = 0; i < shaderInputs.length; i++) {
            console.log("ShaderInput:", i, shaderInputs[i].ctype);
            switch (shaderInputs[i].ctype) {
                case "texture":
                    function textureLoaded(i, texture) {
                        material.uniforms.iChannelResolution.value[i].x = texture.image.width;
                        material.uniforms.iChannelResolution.value[i].y = texture.image.height;
                    }
                    var texture = textureLoader.load(
                        "../textures/shadertoy" + shaderInputs[i].src,
                        textureLoaded.bind(null, i)
                    );
                    if(shaderInputs[i].sampler.wrap == "repeat") {
                        texture.wrapS = THREE.RepeatWrapping;
                        texture.wrapT = THREE.RepeatWrapping;
                    }
                    textures[shaderInputs[i].channel] = texture;
                    console.log("Sampler:", shaderInputs[i].sampler);
                    break;
                case "cubemap":
                    var filename = shaderInputs[i].src.replace(/\.([a-z]+$)/,"\_NUM.$1");
                    var texture = new THREE.CubeTextureLoader()
                        .setPath('../textures/shadertoy')
                        .load(
                            [
                                filename.replace("_NUM",""),
                                filename.replace("_NUM","_1"),
                                filename.replace("_NUM","_2"),
                                filename.replace("_NUM","_3"),
                                filename.replace("_NUM","_4"),
                                filename.replace("_NUM","_5")
                            ]
                        );
                    textures[shaderInputs[i].channel] = texture;
                    samplerTypes[shaderInputs[i].channel] = "samplerCube";
                    break;
            }
        }

        for(var i = 0; i < 4; i++) {
            var slotLabel = "_slot" + i + "_";
            fragmentShaderPreamble = fragmentShaderPreamble.replace(slotLabel, samplerTypes[i]);
            if(samplerTypes[i] == "samplerCube") {
                var regex =new RegExp("texture\\(iChannel"+i,"g");
                fragmentShader = fragmentShader.replace(regex, "textureCube(iChannel"+i);
            }
        }

        material = new THREE.RawShaderMaterial( {
            vertexShader:   vertexShader,
            fragmentShader: fragmentShaderPreamble + fragmentShader,
            uniforms: {
                iGlobalTime: {value: 1.0 },
                iChannel0:   {value: textures[0] },
                iChannel1:   {value: textures[1] },
                iChannel2:   {value: textures[2] },
                iChannel3:   {value: textures[3] },
                iChannelResolution:    {value: [
                    new THREE.Vector3(256, 256),
                    new THREE.Vector3(256, 256),
                    new THREE.Vector3(256, 256),
                    new THREE.Vector3(256, 256)
                ]},
                iResolution: {value: new THREE.Vector2(1024, 1024)},
                iMouse:      {value: new THREE.Vector4(0, 0, 0, 0)},
            }
        } );

        mesh.material = material;

        // Use username, unless there is a "Original Author:" in the comments.
        var fields = fragmentShader.match(/Original Author: (.*)/);
        if(fields) {
            shader.info.username = fields[1];
        }

        var credit = getTextElement(shader.info.name + "\nShadertoy by " + shader.info.username, 4);
        credit.position.z = -4;
        credit.position.y = 0.55;
        scene.add(credit);
    }

    var query = parseQuery();
    if(query.shader !== null) {
        loadUrl("https://www.shadertoy.com/api/v1/shaders/" + query.shader + "?key=" + apiKey, processShader);
    }
    if(query.ambulatory) {
        fragmentShaderPreamble = "#define AMBULATORY\n" + fragmentShaderPreamble;
    }

    var geometry = new THREE.SphereBufferGeometry(RendererConfig.dome.radius, 60, 40);
    geometry.scale( -1, 1, 1 );

    mesh = new THREE.Mesh( geometry );
    mesh.rotation.y = -Math.PI/2;
    mesh.rotation.x = RendererConfig.dome.inclination;
    scene.add( mesh );

    RendererConfig.animationCallback = function(t) {
        if(mesh.material.uniforms) {
            mesh.material.uniforms.iGlobalTime.value = t;
        }
    }
}

var fragmentShaderPreamble = function() {/*!
#define texture    texture2D
#define textureLod texture2D

precision highp float;
varying   float longitude;
varying   float latitude;
varying   vec2  vUV;

uniform float     iGlobalTime;
uniform vec2      iResolution;
uniform vec4      iMouse;
uniform _slot0_   iChannel0;
uniform _slot1_   iChannel1;
uniform _slot2_   iChannel2;
uniform _slot3_   iChannel3;
uniform vec3      iChannelResolution[4];

void mainVR( out vec4 fragColor, in vec2 fragCoord, in vec3 ro, in vec3 rd );

void main()  {
    float sinOfLatitude = -sin( latitude );
    vec3 rd = vec3(
        sin( longitude ) * sinOfLatitude,
        cos( latitude ),
        cos( longitude ) * sinOfLatitude
    );
    //normalize(rd);

#ifdef AMBULATORY
    vec3 ro = vec3(0., 0., -iGlobalTime);
#else
    vec3 ro = vec3(0., 0., 0.);
#endif
    mainVR( gl_FragColor, vUV * vec2(1024), ro, rd );
}
*/}.getComment();

var vertexShader = function() {/*!
attribute vec3 position;
attribute vec2 uv;
uniform   mat4 projectionMatrix;
uniform   mat4 modelViewMatrix;
varying   float longitude;
varying   float latitude;
varying   vec2 vUV;

#define M_PI 3.1415926535897932384626433832795

void main() {
    vUV = uv;
    longitude = -2. * M_PI * (uv.x - 0.5);
    latitude  = -1. * M_PI * (uv.y - 1.0);
    gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
*/}.getComment();
<commit_msg>Added flipY attribute to ShaderToy loader (cloud demo now looks better!).<commit_after>/* This is an experimental loader for ShaderToys. It will attempt to load
 * the shader indicated by the "shader" variable in the URL.
 */
RendererConfig.dome.fullSphere    = false;

var textureLoader = new THREE.TextureLoader();

function setupScene(scene) {
    const apiKey = "BdHtW4";

    alert("ShaderToys are generally licensed for non-commercial use (CC-BY-NC-SA 3.0).\nFor non-free exhibition, contact the author via the ShaderToy link.");

    var mesh;

    function processShader(data) {
        var shader = JSON.parse(data).Shader;

        console.log(shader.info.name, "by", shader.info.username, shader);

        if(shader.renderpass.length > 1) {
            console.log("Warning: Multiple render passes not currently supported");
        }

        var material;
        var fragmentShader = shader.renderpass[0].code;
        var shaderInputs   = shader.renderpass[0].inputs;
        var textures       = [];
        var samplerTypes   = ["sampler2D", "sampler2D", "sampler2D", "sampler2D"];

        for(var i = 0; i < shaderInputs.length; i++) {
            console.log("ShaderInput:", i, shaderInputs[i].ctype);
            switch (shaderInputs[i].ctype) {
                case "texture":
                    function textureLoaded(i, texture) {
                        material.uniforms.iChannelResolution.value[i].x = texture.image.width;
                        material.uniforms.iChannelResolution.value[i].y = texture.image.height;
                    }
                    var texture = textureLoader.load(
                        "../textures/shadertoy" + shaderInputs[i].src,
                        textureLoaded.bind(null, i)
                    );
                    if(shaderInputs[i].sampler.vflip == "false") {
                        texture.flipY = false;
                    }
                    if(shaderInputs[i].sampler.wrap == "repeat") {
                        texture.wrapS = THREE.RepeatWrapping;
                        texture.wrapT = THREE.RepeatWrapping;
                    }
                    if(shaderInputs[i].sampler.srgb == "true") {
                        texture.encoding = THREE.sRGBEncoding;
                    }
                    textures[shaderInputs[i].channel] = texture;
                    console.log("Sampler:", shaderInputs[i].sampler);
                    break;
                case "cubemap":
                    var filename = shaderInputs[i].src.replace(/\.([a-z]+$)/,"\_NUM.$1");
                    var texture = new THREE.CubeTextureLoader()
                        .setPath('../textures/shadertoy')
                        .load(
                            [
                                filename.replace("_NUM",""),
                                filename.replace("_NUM","_1"),
                                filename.replace("_NUM","_2"),
                                filename.replace("_NUM","_3"),
                                filename.replace("_NUM","_4"),
                                filename.replace("_NUM","_5")
                            ]
                        );
                    textures[shaderInputs[i].channel] = texture;
                    samplerTypes[shaderInputs[i].channel] = "samplerCube";
                    break;
            }
        }

        for(var i = 0; i < 4; i++) {
            var slotLabel = "_slot" + i + "_";
            fragmentShaderPreamble = fragmentShaderPreamble.replace(slotLabel, samplerTypes[i]);
            if(samplerTypes[i] == "samplerCube") {
                var regex =new RegExp("texture\\(iChannel"+i,"g");
                fragmentShader = fragmentShader.replace(regex, "textureCube(iChannel"+i);
            }
        }

        material = new THREE.RawShaderMaterial( {
            vertexShader:   vertexShader,
            fragmentShader: fragmentShaderPreamble + fragmentShader,
            uniforms: {
                iGlobalTime: {value: 1.0 },
                iChannel0:   {value: textures[0] },
                iChannel1:   {value: textures[1] },
                iChannel2:   {value: textures[2] },
                iChannel3:   {value: textures[3] },
                iChannelResolution:    {value: [
                    new THREE.Vector3(256, 256),
                    new THREE.Vector3(256, 256),
                    new THREE.Vector3(256, 256),
                    new THREE.Vector3(256, 256)
                ]},
                iResolution: {value: new THREE.Vector2(1024, 1024)},
                iMouse:      {value: new THREE.Vector4(0, 0, 0, 0)},
            }
        } );

        mesh.material = material;

        // Use username, unless there is a "Original Author:" in the comments.
        var fields = fragmentShader.match(/Original Author: (.*)/);
        if(fields) {
            shader.info.username = fields[1];
        }

        var credit = getTextElement(shader.info.name + "\nShadertoy by " + shader.info.username, 4);
        credit.position.z = -4;
        credit.position.y = 0.55;
        scene.add(credit);
    }

    var query = parseQuery();
    if(query.shader !== null) {
        loadUrl("https://www.shadertoy.com/api/v1/shaders/" + query.shader + "?key=" + apiKey, processShader);
    }
    if(query.ambulatory) {
        fragmentShaderPreamble = "#define AMBULATORY\n" + fragmentShaderPreamble;
    }

    var geometry = new THREE.SphereBufferGeometry(RendererConfig.dome.radius, 60, 40);
    geometry.scale( -1, 1, 1 );

    mesh = new THREE.Mesh( geometry );
    mesh.rotation.y = -Math.PI/2;
    mesh.rotation.x = RendererConfig.dome.inclination;
    scene.add( mesh );

    RendererConfig.animationCallback = function(t) {
        if(mesh.material.uniforms) {
            mesh.material.uniforms.iGlobalTime.value = t;
        }
    }
}

var fragmentShaderPreamble = function() {/*!
#define texture    texture2D
#define textureLod texture2D

precision highp float;
varying   float longitude;
varying   float latitude;
varying   vec2  vUV;

uniform float     iGlobalTime;
uniform vec2      iResolution;
uniform vec4      iMouse;
uniform _slot0_   iChannel0;
uniform _slot1_   iChannel1;
uniform _slot2_   iChannel2;
uniform _slot3_   iChannel3;
uniform vec3      iChannelResolution[4];

void mainVR( out vec4 fragColor, in vec2 fragCoord, in vec3 ro, in vec3 rd );

void main()  {
    float sinOfLatitude = -sin( latitude );
    vec3 rd = vec3(
        sin( longitude ) * sinOfLatitude,
        cos( latitude ),
        cos( longitude ) * sinOfLatitude
    );
    //normalize(rd);

#ifdef AMBULATORY
    vec3 ro = vec3(0., 0., -iGlobalTime);
#else
    vec3 ro = vec3(0., 0., 0.);
#endif
    mainVR( gl_FragColor, vUV * vec2(1024), ro, rd );
}
*/}.getComment();

var vertexShader = function() {/*!
attribute vec3 position;
attribute vec2 uv;
uniform   mat4 projectionMatrix;
uniform   mat4 modelViewMatrix;
varying   float longitude;
varying   float latitude;
varying   vec2 vUV;

#define M_PI 3.1415926535897932384626433832795

void main() {
    vUV = uv;
    longitude = -2. * M_PI * (uv.x - 0.5);
    latitude  = -1. * M_PI * (uv.y - 1.0);
    gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
*/}.getComment();
<|endoftext|>


<commit_before>/*jshint curly:false,forin:false*/

AnimationFrame.shim();

window.castor =
{
	// castor._hasClass
	_hasClass: function( el, className ) {
		if( el.classList ) return el.classList.contains( className );
		else return new RegExp( '\\b' + className + '\\b' ).test( el.className );
	},
	// castor._addClass
	_addClass: function( el, className ) {
		if( el.classList ) el.classList.add( className );
		else if( !this._hasClass( el, className )) el.className += ' ' + className;
	},
	// castor._removeClass
	_removeClass: function( el, className ) {
		if( el.classList ) el.classList.remove( className );
		else el.className = el.className.replace( new RegExp( '\\b' + className + '\\b', 'g' ), '' );
	},
	// castor._toggleClass
	_toggleClass: function( el, className ) {
		if( !this._hasClass( el, className )) this._addClass( el, className );
		else this._removeClass( el, className );
	},
	// castor._isString
	_isString: function( str ) {
		return Object.prototype.toString.call( str ) === "[object String]";
	},
	// castor._on
	_on: function( type, el, handler ) {
		if( !el )return;
		if( el.attachEvent ) el.attachEvent( 'on' + type, handler );
		else el.addEventListener( type, handler );
	},
	// castor._off
	_off: function( type, el, handler ) {
		if( !el )return;
		if( el.detachEvent ) el.detachEvent( 'on' + type, handler );
		else el.removeEventListener( type, handler );
	},
	// castor._transitionEvent
	_transitionEvent: function() {
		var transition;
		var el = document.createElement('fakeelement');
		var transitions = {
			'transition':'transitionend',
			'OTransition':'oTransitionEnd',
			'MozTransition':'transitionend',
			'WebkitTransition':'webkitTransitionEnd',
		};
		for( transition in transitions ) {
			if( el.style[transition] !== undefined ) {
				return transitions[transition];
			}
		}
	},
	// castor._extend
	// see: https://github.com/angus-c/just#just-extend
	_extend: function()
	{
		var args = [].slice.call( arguments );
		var deep = false;
		if( typeof args[0] === 'boolean' ) {
			deep = args.shift();
		}
		var result = args[0];
		var extenders = args.slice(1);
		var len = extenders.length;
		for( var i = 0; i < len; i++ ) {
			var extender = extenders[i];
			for( var key in extender ) {
				var value = extender[ key ];
				if( deep && value && ( typeof value == 'object' )) {
					var base = Array.isArray( value ) ? [] : {};
					result[ key ] = this._extend( true, base, value );
				}
				else {
					result[ key ] = value;
				}
			}
		}
		return result;
	},
};

(function( ElementPrototype )
{
	// matches polyfill
	ElementPrototype.matches = ElementPrototype.matches ||
	function( selector ) {
		var matches = ( this.document || this.ownerDocument ).querySelectorAll( selector );
		var i = matches.length;
		while( --i >= 0 && matches.item( i ) !== this );
		return i > -1;
	};

	// closest polyfill
	ElementPrototype.closest = ElementPrototype.closest ||
	function( selector ) {
		var el = this;
		while( el.matches && !el.matches( selector )) {
			el = el.parentNode;
		}
		return el.matches ? el : null;
	};
})( Element.prototype );

(function creditsLog() {
	var css = function( args ) {
		var string = "font-size:{0};color:{1};padding:{2};line-height:24px;text-shadow:0 1px #000;background:#263238;text-decoration:none;";
		return string.replace( /{(\d+)}/g, function( match, number ) {
			return args[ number ];
		});
	};
	console.log(
		"\n%cSite made with %c♥ %cby Paul Ryley\n%chttps://twitter.com/pryley\n%chttps://geminilabs.io%c\n\n",
		css(['12px', '#fff', '8px 0 8px 10px']),
		css(['12px', '#f44336', '8px 0']),
		css(['12px', '#fff', '8px 10px 8px 0']),
		css(['11px', '#90caf9', '5px']),
		css(['11px', '#90caf9', '8px 5px']),
		""
	);
}());
<commit_msg>remove deprecated IE browser support<commit_after>/*jshint curly:false,forin:false*/

AnimationFrame.shim();

window.castor =
{
	// castor._hasClass
	_hasClass: function( el, className ) {
		if( el.classList ) return el.classList.contains( className );
		else return new RegExp( '\\b' + className + '\\b' ).test( el.className );
	},
	// castor._addClass
	_addClass: function( el, className ) {
		if( el.classList ) el.classList.add( className );
		else if( !this._hasClass( el, className )) el.className += ' ' + className;
	},
	// castor._removeClass
	_removeClass: function( el, className ) {
		if( el.classList ) el.classList.remove( className );
		else el.className = el.className.replace( new RegExp( '\\b' + className + '\\b', 'g' ), '' );
	},
	// castor._toggleClass
	_toggleClass: function( el, className ) {
		if( !this._hasClass( el, className )) this._addClass( el, className );
		else this._removeClass( el, className );
	},
	// castor._isString
	_isString: function( str ) {
		return Object.prototype.toString.call( str ) === "[object String]";
	},
	// castor._on
	_on: function( type, el, handler ) {
		if( !el )return;
		el.addEventListener( type, handler, false );
	},
	// castor._off
	_off: function( type, el, handler ) {
		if( !el )return;
		el.removeEventListener( type, handler, false );
	},
	// castor._transitionEvent
	_transitionEvent: function() {
		var transition;
		var el = document.createElement('fakeelement');
		var transitions = {
			'transition':'transitionend',
			'OTransition':'oTransitionEnd',
			'MozTransition':'transitionend',
			'WebkitTransition':'webkitTransitionEnd',
		};
		for( transition in transitions ) {
			if( el.style[transition] !== undefined ) {
				return transitions[transition];
			}
		}
	},
	// castor._extend
	// see: https://github.com/angus-c/just#just-extend
	_extend: function()
	{
		var args = [].slice.call( arguments );
		var deep = false;
		if( typeof args[0] === 'boolean' ) {
			deep = args.shift();
		}
		var result = args[0];
		var extenders = args.slice(1);
		var len = extenders.length;
		for( var i = 0; i < len; i++ ) {
			var extender = extenders[i];
			for( var key in extender ) {
				var value = extender[ key ];
				if( deep && value && ( typeof value == 'object' )) {
					var base = Array.isArray( value ) ? [] : {};
					result[ key ] = this._extend( true, base, value );
				}
				else {
					result[ key ] = value;
				}
			}
		}
		return result;
	},
};

(function( ElementPrototype )
{
	// matches polyfill
	ElementPrototype.matches = ElementPrototype.matches ||
	function( selector ) {
		var matches = ( this.document || this.ownerDocument ).querySelectorAll( selector );
		var i = matches.length;
		while( --i >= 0 && matches.item( i ) !== this );
		return i > -1;
	};

	// closest polyfill
	ElementPrototype.closest = ElementPrototype.closest ||
	function( selector ) {
		var el = this;
		while( el.matches && !el.matches( selector )) {
			el = el.parentNode;
		}
		return el.matches ? el : null;
	};
})( Element.prototype );

(function creditsLog() {
	var css = function( args ) {
		var string = "font-size:{0};color:{1};padding:{2};line-height:24px;text-shadow:0 1px #000;background:#263238;text-decoration:none;";
		return string.replace( /{(\d+)}/g, function( match, number ) {
			return args[ number ];
		});
	};
	console.log(
		"\n%cSite made with %c♥ %cby Paul Ryley\n%chttps://twitter.com/pryley\n%chttps://geminilabs.io%c\n\n",
		css(['12px', '#fff', '8px 0 8px 10px']),
		css(['12px', '#f44336', '8px 0']),
		css(['12px', '#fff', '8px 10px 8px 0']),
		css(['11px', '#90caf9', '5px']),
		css(['11px', '#90caf9', '8px 5px']),
		""
	);
}());
<|endoftext|>


<commit_before>/**
 * Blueprint API Configuration
 * (sails.config.blueprints)
 *
 * These settings are for the global configuration of blueprint routes and
 * request options (which impact the behavior of blueprint actions).
 *
 * You may also override any of these settings on a per-controller basis
 * by defining a '_config' key in your controller defintion, and assigning it
 * a configuration object with overrides for the settings in this file.
 * A lot of the configuration options below affect so-called "CRUD methods",
 * or your controllers' `find`, `create`, `update`, and `destroy` actions.
 *
 * It's important to realize that, even if you haven't defined these yourself, as long as
 * a model exists with the same name as the controller, Sails will respond with built-in CRUD
 * logic in the form of a JSON API, including support for sort, pagination, and filtering.
 *
 * For more information on the blueprint API, check out:
 * http://sailsjs.org/#/documentation/reference/blueprint-api
 *
 * For more information on the settings in this file, see:
 * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.blueprints.html
 *
 */

module.exports.blueprints = {

    /***************************************************************************
     *                                                                          *
     * Action routes speed up the backend development workflow by               *
     * eliminating the need to manually bind routes. When enabled, GET, POST,   *
     * PUT, and DELETE routes will be generated for every one of a controller's *
     * actions.                                                                 *
     *                                                                          *
     * If an `index` action exists, additional naked routes will be created for *
     * it. Finally, all `actions` blueprints support an optional path           *
     * parameter, `id`, for convenience.                                        *
     *                                                                          *
     * `actions` are enabled by default, and can be OK for production--         *
     * however, if you'd like to continue to use controller/action autorouting  *
     * in a production deployment, you must take great care not to              *
     * inadvertently expose unsafe/unintentional controller logic to GET        *
     * requests.                                                                *
     *                                                                          *
     ***************************************************************************/

    actions: true,

    /***************************************************************************
     *                                                                          *
     * RESTful routes (`sails.config.blueprints.rest`)                          *
     *                                                                          *
     * REST blueprints are the automatically generated routes Sails uses to     *
     * expose a conventional REST API on top of a controller's `find`,          *
     * `create`, `update`, and `destroy` actions.                               *
     *                                                                          *
     * For example, a BoatController with `rest` enabled generates the          *
     * following routes:                                                        *
     * :::::::::::::::::::::::::::::::::::::::::::::::::::::::                  *
     *  GET /boat/:id? -> BoatController.find                                   *
     *  POST /boat -> BoatController.create                                     *
     *  PUT /boat/:id -> BoatController.update                                  *
     *  DELETE /boat/:id -> BoatController.destroy                              *
     *                                                                          *
     * `rest` blueprint routes are enabled by default, and are suitable for use *
     * in a production scenario, as long you take standard security precautions *
     * (combine w/ policies, etc.)                                              *
     *                                                                          *
     ***************************************************************************/

    rest: true,

    /***************************************************************************
     *                                                                          *
     * Shortcut routes are simple helpers to provide access to a                *
     * controller's CRUD methods from your browser's URL bar. When enabled,     *
     * GET, POST, PUT, and DELETE routes will be generated for the              *
     * controller's`find`, `create`, `update`, and `destroy` actions.           *
     *                                                                          *
     * `shortcuts` are enabled by default, but should be disabled in            *
     * production.                                                              *
     *                                                                          *
     ***************************************************************************/

    shortcuts: true,

    /***************************************************************************
     *                                                                          *
     * An optional mount path for all blueprint routes on a controller,         *
     * including `rest`, `actions`, and `shortcuts`. This allows you to take    *
     * advantage of blueprint routing, even if you need to namespace your API   *
     * methods.                                                                 *
     *                                                                          *
     * (NOTE: This only applies to blueprint autoroutes, not manual routes from *
     * `sails.config.routes`)                                                   *
     *                                                                          *
     ***************************************************************************/

    // prefix: '',

    /***************************************************************************
     *                                                                          *
     * Whether to pluralize controller names in blueprint routes.               *
     *                                                                          *
     * (NOTE: This only applies to blueprint autoroutes, not manual routes from *
     * `sails.config.routes`)                                                   *
     *                                                                          *
     * For example, REST blueprints for `FooController` with `pluralize`        *
     * enabled:                                                                 *
     * GET /foos/:id?                                                           *
     * POST /foos                                                               *
     * PUT /foos/:id?                                                           *
     * DELETE /foos/:id?                                                        *
     *                                                                          *
     ***************************************************************************/

    pluralize: false,

    /***************************************************************************
     *                                                                          *
     * Whether the blueprint controllers should populate model fetches with     *
     * data from other models which are linked by associations                  *
     *                                                                          *
     * If you have a lot of data in one-to-many associations, leaving this on   *
     * may result in very heavy api calls                                       *
     *                                                                          *
     ***************************************************************************/

    // populate: true,

    /****************************************************************************
     *                                                                           *
     * Whether to run Model.watch() in the find and findOne blueprint actions.   *
     * Can be overridden on a per-model basis.                                   *
     *                                                                           *
     ****************************************************************************/

    autoWatch: true,

    /****************************************************************************
     *                                                                           *
     * The default number of records to show in the response from a "find"       *
     * action. Doubles as the default size of populated arrays if populate is    *
     * true.                                                                     *
     *                                                                           *
     ****************************************************************************/

    defaultLimit: 25

};
<commit_msg>Disable blueprints.<commit_after>/**
 * Blueprint API Configuration
 * (sails.config.blueprints)
 *
 * These settings are for the global configuration of blueprint routes and
 * request options (which impact the behavior of blueprint actions).
 *
 * You may also override any of these settings on a per-controller basis
 * by defining a '_config' key in your controller defintion, and assigning it
 * a configuration object with overrides for the settings in this file.
 * A lot of the configuration options below affect so-called "CRUD methods",
 * or your controllers' `find`, `create`, `update`, and `destroy` actions.
 *
 * It's important to realize that, even if you haven't defined these yourself, as long as
 * a model exists with the same name as the controller, Sails will respond with built-in CRUD
 * logic in the form of a JSON API, including support for sort, pagination, and filtering.
 *
 * For more information on the blueprint API, check out:
 * http://sailsjs.org/#/documentation/reference/blueprint-api
 *
 * For more information on the settings in this file, see:
 * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.blueprints.html
 *
 */

module.exports.blueprints = {

    /***************************************************************************
     *                                                                          *
     * Action routes speed up the backend development workflow by               *
     * eliminating the need to manually bind routes. When enabled, GET, POST,   *
     * PUT, and DELETE routes will be generated for every one of a controller's *
     * actions.                                                                 *
     *                                                                          *
     * If an `index` action exists, additional naked routes will be created for *
     * it. Finally, all `actions` blueprints support an optional path           *
     * parameter, `id`, for convenience.                                        *
     *                                                                          *
     * `actions` are enabled by default, and can be OK for production--         *
     * however, if you'd like to continue to use controller/action autorouting  *
     * in a production deployment, you must take great care not to              *
     * inadvertently expose unsafe/unintentional controller logic to GET        *
     * requests.                                                                *
     *                                                                          *
     ***************************************************************************/

    actions: false,

    /***************************************************************************
     *                                                                          *
     * RESTful routes (`sails.config.blueprints.rest`)                          *
     *                                                                          *
     * REST blueprints are the automatically generated routes Sails uses to     *
     * expose a conventional REST API on top of a controller's `find`,          *
     * `create`, `update`, and `destroy` actions.                               *
     *                                                                          *
     * For example, a BoatController with `rest` enabled generates the          *
     * following routes:                                                        *
     * :::::::::::::::::::::::::::::::::::::::::::::::::::::::                  *
     *  GET /boat/:id? -> BoatController.find                                   *
     *  POST /boat -> BoatController.create                                     *
     *  PUT /boat/:id -> BoatController.update                                  *
     *  DELETE /boat/:id -> BoatController.destroy                              *
     *                                                                          *
     * `rest` blueprint routes are enabled by default, and are suitable for use *
     * in a production scenario, as long you take standard security precautions *
     * (combine w/ policies, etc.)                                              *
     *                                                                          *
     ***************************************************************************/

    rest: false,

    /***************************************************************************
     *                                                                          *
     * Shortcut routes are simple helpers to provide access to a                *
     * controller's CRUD methods from your browser's URL bar. When enabled,     *
     * GET, POST, PUT, and DELETE routes will be generated for the              *
     * controller's`find`, `create`, `update`, and `destroy` actions.           *
     *                                                                          *
     * `shortcuts` are enabled by default, but should be disabled in            *
     * production.                                                              *
     *                                                                          *
     ***************************************************************************/

    shortcuts: false,

    /***************************************************************************
     *                                                                          *
     * An optional mount path for all blueprint routes on a controller,         *
     * including `rest`, `actions`, and `shortcuts`. This allows you to take    *
     * advantage of blueprint routing, even if you need to namespace your API   *
     * methods.                                                                 *
     *                                                                          *
     * (NOTE: This only applies to blueprint autoroutes, not manual routes from *
     * `sails.config.routes`)                                                   *
     *                                                                          *
     ***************************************************************************/

    // prefix: '',

    /***************************************************************************
     *                                                                          *
     * Whether to pluralize controller names in blueprint routes.               *
     *                                                                          *
     * (NOTE: This only applies to blueprint autoroutes, not manual routes from *
     * `sails.config.routes`)                                                   *
     *                                                                          *
     * For example, REST blueprints for `FooController` with `pluralize`        *
     * enabled:                                                                 *
     * GET /foos/:id?                                                           *
     * POST /foos                                                               *
     * PUT /foos/:id?                                                           *
     * DELETE /foos/:id?                                                        *
     *                                                                          *
     ***************************************************************************/

    pluralize: false,

    /***************************************************************************
     *                                                                          *
     * Whether the blueprint controllers should populate model fetches with     *
     * data from other models which are linked by associations                  *
     *                                                                          *
     * If you have a lot of data in one-to-many associations, leaving this on   *
     * may result in very heavy api calls                                       *
     *                                                                          *
     ***************************************************************************/

    // populate: true,

    /****************************************************************************
     *                                                                           *
     * Whether to run Model.watch() in the find and findOne blueprint actions.   *
     * Can be overridden on a per-model basis.                                   *
     *                                                                           *
     ****************************************************************************/

    autoWatch: false,

    /****************************************************************************
     *                                                                           *
     * The default number of records to show in the response from a "find"       *
     * action. Doubles as the default size of populated arrays if populate is    *
     * true.                                                                     *
     *                                                                           *
     ****************************************************************************/

    defaultLimit: 25

};
<|endoftext|>


<commit_before>const mongoose = require( 'mongoose' );

module.exports = function( Model ) {
  // if ( !( Model instanceof mongoose.model ) ) throw new Error( 'Invalid mongoose model ' );

  function get( query = {} ) {
    return Model.findOne( query );
  }

  function query( query = {} ) {
    return Model.find( query );
  }

  function save( doc ) {
    let _doc;

    try {
      _doc = new Model( doc );
      return _doc.save();
    } catch( error ) {
      return new Promise(( resolve, reject ) => reject( error ));
    }

  }

  function update( query = {}, doc, options = { multi: false } ) {
    try {
      return Model.update( query, doc, options );
    } catch( error ) {
      return new Promise(( resolve, reject ) => reject( error ));
    }

  }

  function logicalRemove( query ) {
    return Model.update( query, { $set: { active: false } } );
  }

  return {
    get,
    query,
    save,
    update,
    logicalRemove
  };
};
<commit_msg>[UPDATE]: Agora a data de update é atualizada quando logicalRemove é chamada.<commit_after>const mongoose = require( 'mongoose' );

module.exports = function( Model ) {
  // if ( !( Model instanceof mongoose.model ) ) throw new Error( 'Invalid mongoose model ' );

  function get( query = {} ) {
    return Model.findOne( query );
  }

  function query( query = {} ) {
    return Model.find( query );
  }

  function save( doc ) {
    let _doc;

    try {
      _doc = new Model( doc );
      return _doc.save();
    } catch( error ) {
      return new Promise(( resolve, reject ) => reject( error ));
    }

  }

  function update( query = { _id: undefined }, doc, options = { multi: false } ) {
    try {
      return Model.update( query, doc, options );
    } catch( error ) {
      return new Promise(( resolve, reject ) => reject( error ));
    }

  }

  function logicalRemove( query ) {
    return Model.update( query, { $set: { active: false, lastUpdate: Date.now() } } );
  }

  return {
    get,
    query,
    save,
    update,
    logicalRemove
  };
};
<|endoftext|>