<commit_before>(function () {
  atc = function (elementID) {
    var Timeline = function (elementID) {
      this.element = document.getElementById(elementID);
      this.queue = [];
      this.queueIndex = 0;
      this.stopped = false;
      this.duration = 0;
      this.endText = "";
      this.defaults = {
        frameRate: atc.defaults.frameRate,
        pauseDuration: atc.defaults.pauseDuration,
        loop: atc.defaults.loop
      };
    };

    Timeline.prototype.go = function (timelineObj) {
      var thiz = this,
          funktion,
          len,
          nextAnimation;

      if (timelineObj) {
        funktion = function () {
          timelineObj.go();
        };

        this.addToQueue(funktion, timelineObj.duration, timelineObj.endText);
      } else {
        len = this.queue.length;
        this.stopped = false;

        nextAnimation = function () {
          if (thiz.queueIndex < len && !thiz.stopped) {
            thiz.queue[thiz.queueIndex].funktion();
            setTimeout(nextAnimation, thiz.queue[thiz.queueIndex].duration);
            thiz.queueIndex += 1;
          } else if (!thiz.stopped) {
            thiz.queueIndex = 0;
            if (thiz.defaults.loop) {
              nextAnimation();
            }
          }
        };

        nextAnimation();
      }

      return this;
    };

    Timeline.prototype.stop = function () {
      var thiz = this,
      funktion = function () {
        thiz.stopped = true;
      };

      this.addToQueue(funktion, 0, this.findText());

      return this;
    };

    Timeline.prototype.findText = function () {
      var text;

      try {
        text = this.queue[this.queue.length - 1].endText;
      } catch (e) {
        text = this.element.textContent;
      }

      return text;
    };

    Timeline.prototype.addToQueue = function (funktion, duration, endText) {
      this.duration += duration;
      this.endText = endText;
      this.queue.push({ funktion: funktion, duration: duration, endText: endText });
    };

    Timeline.prototype.text = function (text) {
      if (text) {
        var thiz = this,
            funktion;

        funktion = function () {
          thiz.element.textContent = text;
        };

        this.addToQueue(funktion, 0, text);

        return this;
      } else {
        return this.element.textContent;
      }
    };

    Timeline.prototype.html = function (html) {
      var thiz = this,
      funktion = function () {
        thiz.element.innerHTML = html;
      };

      this.addToQueue(funktion, 0, html);

      return this;
    };

    Timeline.prototype.switchElement = function (elementID) {
      var thiz = this,
      funktion = function () {
        thiz.element = document.getElementById(elementID);
      };

      this.addToQueue(funktion, 0, this.element.textContent); // TODO fix endText value

      return this;
    };

    Timeline.prototype.custom = function (funktion, duration, endText) {
      duration = duration || 0;
      endText = endText || this.findText();

      this.addToQueue(funktion, duration, endText);

      return this;
    };

    Timeline.prototype.frameByFrame = function (frames, loops, duration) {
      var thiz = this,
          len = frames.length,
          lastFrame = frames[len - 1],
          totalFrames,
          frameRate,
          nextFrame,
          reset,
          funktion,
          i,
          j,
          k = 1,
          l = 0;

      loops = loops || 1;
      totalFrames = len * loops;
      duration = duration || totalFrames * this.defaults.frameRate;
      frameRate = duration / totalFrames;

      nextFrame = function () {
        thiz.element.textContent = frames[l];
        if (l < len - 1) {
          l += 1;
        } else {
          l = 0;
        }
      };

      reset = function () {
        k = 1;
      };

      funktion = function () {
        for (i = 0; i < loops; i++) {
          for (j = 0; j < len; j++) {
            setTimeout(nextFrame, frameRate * k);
            k += 1;
          }
        }
        setTimeout(reset, duration);
      };

      this.addToQueue(funktion, duration, lastFrame);

      return this;
    };

    Timeline.prototype.rollNumbers = function (startValue, endValue, increment, duration) {
      var thiz = this,
          difference = endValue - startValue,
          newValue = startValue,
          addFrame,
          totalFrames,
          frameRate,
          nextFrame,
          reset,
          funktion,
          i;

      increment = increment || 1;
      addFrame = increment;

      if (difference < 0) {
        difference = -difference;
        addFrame = -addFrame;
      }

      totalFrames = difference / increment;
      frameRate = duration / totalFrames || this.defaults.frameRate;
      duration = duration || this.defaults.frameRate * totalFrames;

      nextFrame = function () {
        newValue += addFrame;
        thiz.element.textContent = newValue;
      };

      reset = function () {
        thiz.element.textContent = endValue;
        newValue = startValue;
      };

      funktion = function () {
        for (i = 1; i < totalFrames; i++) {
          setTimeout(nextFrame, frameRate * i);
        }
        setTimeout(reset, duration);
      };

      this.addToQueue(funktion, duration, endValue);

      return this;
    };

    Timeline.prototype.erase = function (duration) {
      var thiz = this,
          originalText = this.findText(),
          textArray = originalText.split(''),
          len = originalText.length,
          frameRate = duration / len || this.defaults.frameRate,
          nextFrame,
          reset,
          funktion,
          i;

      duration = duration || this.defaults.frameRate * len;

      nextFrame = function () {
        textArray.pop();
        thiz.element.textContent = textArray.join('');
      };

      reset = function () {
        textArray = originalText.split('');
      };

      funktion = function () {
        for (i = 1; i <= len; i++) {
          setTimeout(nextFrame, frameRate * i);
        }
        setTimeout(reset, duration);
      };

      this.addToQueue(funktion, duration, "");

      return this;
    };

    Timeline.prototype.typeIn = function (text, duration) {
      var thiz = this,
          textArray = text.split(''),
          displayTextArray = [],
          len = text.length,
          frameRate = duration / len || this.defaults.frameRate,
          nextFrame,
          reset,
          funktion,
          i;

      duration = duration || this.defaults.frameRate * len;

      nextFrame = function () {
        displayTextArray.push(textArray.shift());
        thiz.element.textContent = displayTextArray.join('');
      };

      reset = function () {
        textArray = displayTextArray;
        displayTextArray = [];
      };

      funktion = function () {
        for (i = 1; i <= len; i++) {
          setTimeout(nextFrame, frameRate * i);
        }
        setTimeout(reset, duration);
      };

      this.addToQueue(funktion, duration, text);

      return this;
    };

    Timeline.prototype.pause = function (duration) {
      var endText = this.findText(),
          funktion = function () {};

      duration = duration || this.defaults.pauseDuration;
      this.addToQueue(funktion, duration, endText);

      return this;
    };

    Timeline.prototype.clearTimeline = function () {
      this.queue = [];
      this.duration = 0;
      this.endText = "";

      return this;
    };

    return new Timeline(elementID);
  };

  atc.defaults = {
    frameRate: 1000/24,
    pauseDuration: 2000,
    loop: false
  };
}());<commit_msg>added default setting methods<commit_after>(function () {
  atc = function (elementID) {
    var Timeline = function (elementID) {
      this.element = document.getElementById(elementID);
      this.queue = [];
      this.queueIndex = 0;
      this.stopped = false;
      this.duration = 0;
      this.endText = "";
      this.defaults = {
        frameRate: atc.defaults.frameRate,
        pauseDuration: atc.defaults.pauseDuration,
        loop: atc.defaults.loop
      };
    };

    Timeline.prototype.go = function (timelineObj) {
      var thiz = this,
          funktion,
          len,
          nextAnimation;

      if (timelineObj) {
        funktion = function () {
          timelineObj.go();
        };

        this.addToQueue(funktion, timelineObj.duration, timelineObj.endText);
      } else {
        len = this.queue.length;
        this.stopped = false;

        nextAnimation = function () {
          if (thiz.queueIndex < len && !thiz.stopped) {
            thiz.queue[thiz.queueIndex].funktion();
            setTimeout(nextAnimation, thiz.queue[thiz.queueIndex].duration);
            thiz.queueIndex += 1;
          } else if (!thiz.stopped) {
            thiz.queueIndex = 0;
            if (thiz.defaults.loop) {
              nextAnimation();
            }
          }
        };

        nextAnimation();
      }

      return this;
    };

    Timeline.prototype.stop = function () {
      var thiz = this,
      funktion = function () {
        thiz.stopped = true;
      };

      this.addToQueue(funktion, 0, this.findText());

      return this;
    };

    Timeline.prototype.frameRate = function (frameRate) {
      this.defaults.frameRate = frameRate || this.defaults.frameRate;

      return this;
    };

    Timeline.prototype.pauseDuration = function (duration) {
      this.defaults.pauseDuration = duration || this.defaults.pauseDuration;

      return this;
    };

    Timeline.prototype.loop = function (bool) {
      if (typeof bool === "undefined") {
        this.defaults.loop = true;
      } else {
        this.defaults.loop = bool;
      }

      return this;
    };

    Timeline.prototype.findText = function () {
      var text;

      try {
        text = this.queue[this.queue.length - 1].endText;
      } catch (e) {
        text = this.element.textContent;
      }

      return text;
    };

    Timeline.prototype.addToQueue = function (funktion, duration, endText) {
      this.duration += duration;
      this.endText = endText;
      this.queue.push({ funktion: funktion, duration: duration, endText: endText });
    };

    Timeline.prototype.text = function (text) {
      if (text) {
        var thiz = this,
            funktion;

        funktion = function () {
          thiz.element.textContent = text;
        };

        this.addToQueue(funktion, 0, text);

        return this;
      } else {
        return this.element.textContent;
      }
    };

    Timeline.prototype.html = function (html) {
      var thiz = this,
      funktion = function () {
        thiz.element.innerHTML = html;
      };

      this.addToQueue(funktion, 0, html);

      return this;
    };

    Timeline.prototype.switchElement = function (elementID) {
      var thiz = this,
      funktion = function () {
        thiz.element = document.getElementById(elementID);
      };

      this.addToQueue(funktion, 0, this.element.textContent); // TODO fix endText value

      return this;
    };

    Timeline.prototype.custom = function (funktion, duration, endText) {
      duration = duration || 0;
      endText = endText || this.findText();

      this.addToQueue(funktion, duration, endText);

      return this;
    };

    Timeline.prototype.frameByFrame = function (frames, loops, duration) {
      var thiz = this,
          len = frames.length,
          lastFrame = frames[len - 1],
          totalFrames,
          frameRate,
          nextFrame,
          reset,
          funktion,
          i,
          j,
          k = 1,
          l = 0;

      loops = loops || 1;
      totalFrames = len * loops;
      duration = duration || totalFrames * this.defaults.frameRate;
      frameRate = duration / totalFrames;

      nextFrame = function () {
        thiz.element.textContent = frames[l];
        if (l < len - 1) {
          l += 1;
        } else {
          l = 0;
        }
      };

      reset = function () {
        k = 1;
      };

      funktion = function () {
        for (i = 0; i < loops; i++) {
          for (j = 0; j < len; j++) {
            setTimeout(nextFrame, frameRate * k);
            k += 1;
          }
        }
        setTimeout(reset, duration);
      };

      this.addToQueue(funktion, duration, lastFrame);

      return this;
    };

    Timeline.prototype.rollNumbers = function (startValue, endValue, increment, duration) {
      var thiz = this,
          difference = endValue - startValue,
          newValue = startValue,
          addFrame,
          totalFrames,
          frameRate,
          nextFrame,
          reset,
          funktion,
          i;

      increment = increment || 1;
      addFrame = increment;

      if (difference < 0) {
        difference = -difference;
        addFrame = -addFrame;
      }

      totalFrames = difference / increment;
      frameRate = duration / totalFrames || this.defaults.frameRate;
      duration = duration || this.defaults.frameRate * totalFrames;

      nextFrame = function () {
        newValue += addFrame;
        thiz.element.textContent = newValue;
      };

      reset = function () {
        thiz.element.textContent = endValue;
        newValue = startValue;
      };

      funktion = function () {
        for (i = 1; i < totalFrames; i++) {
          setTimeout(nextFrame, frameRate * i);
        }
        setTimeout(reset, duration);
      };

      this.addToQueue(funktion, duration, endValue);

      return this;
    };

    Timeline.prototype.erase = function (duration) {
      var thiz = this,
          originalText = this.findText(),
          textArray = originalText.split(''),
          len = originalText.length,
          frameRate = duration / len || this.defaults.frameRate,
          nextFrame,
          reset,
          funktion,
          i;

      duration = duration || this.defaults.frameRate * len;

      nextFrame = function () {
        textArray.pop();
        thiz.element.textContent = textArray.join('');
      };

      reset = function () {
        textArray = originalText.split('');
      };

      funktion = function () {
        for (i = 1; i <= len; i++) {
          setTimeout(nextFrame, frameRate * i);
        }
        setTimeout(reset, duration);
      };

      this.addToQueue(funktion, duration, "");

      return this;
    };

    Timeline.prototype.typeIn = function (text, duration) {
      var thiz = this,
          textArray = text.split(''),
          displayTextArray = [],
          len = text.length,
          frameRate = duration / len || this.defaults.frameRate,
          nextFrame,
          reset,
          funktion,
          i;

      duration = duration || this.defaults.frameRate * len;

      nextFrame = function () {
        displayTextArray.push(textArray.shift());
        thiz.element.textContent = displayTextArray.join('');
      };

      reset = function () {
        textArray = displayTextArray;
        displayTextArray = [];
      };

      funktion = function () {
        for (i = 1; i <= len; i++) {
          setTimeout(nextFrame, frameRate * i);
        }
        setTimeout(reset, duration);
      };

      this.addToQueue(funktion, duration, text);

      return this;
    };

    Timeline.prototype.pause = function (duration) {
      var endText = this.findText(),
          funktion = function () {};

      duration = duration || this.defaults.pauseDuration;
      this.addToQueue(funktion, duration, endText);

      return this;
    };

    Timeline.prototype.clearTimeline = function () {
      this.queue = [];
      this.duration = 0;
      this.endText = "";

      return this;
    };

    return new Timeline(elementID);
  };

  atc.defaults = {
    frameRate: 1000/24,
    pauseDuration: 2000,
    loop: false
  };

  atc.frameRate = function (frameRate) {
    atc.defaults.frameRate = frameRate || atc.defaults.frameRate;

    return atc;
  };

  atc.pauseDuration = function (duration) {
    atc.defaults.pauseDuration = duration || atc.defaults.pauseDuration;

    return atc;
  };

  atc.loop = function (bool) {
    if (typeof bool === "undefined") {
      atc.defaults.loop = true;
    } else {
      atc.defaults.loop = bool;
    }

    return atc;
  };
}());<|endoftext|>


<commit_before>function drawHeavyProcessTables() {
  /* CPU table first. */
  $.ajax('/api/heavy_process_stat', { dataType: 'json' }).done(function(response) {
    var cpu_table = [];
    cpu_table[0] = ['Process', 'CPU usage', 'Change'];
    for (var i = 0; i < response.cpuList.length; i++) {
        var cpu_entry = [
            response.cpuList[i].process_name,
            response.cpuList[i].cpu_usage,
            response.cpuList[i].change
        ];
        cpu_table.push(cpu_entry);
    }

    /* mem */
    var mem_table = [];
    mem_table[0] = ['Process', 'Memory usage', 'Change'];
    for (var i = 0; i < response.memList.length; i++) {
        var mem_entry = [
            response.memList[i].process_name,
            response.memList[i].mem_usage,
            response.memList[i].change
        ];
    };

    var options = {
      curveType: 'function',
      legend: 'top',
      fontName: 'maven pro',
      vAxis: {
        maxValue: 3.0,
        minValue: 0.0,
        viewWindow: {
          min: 0.0
        },
        gridlines: {
          count: 16,
          color: '#f6f6f6'
        }
      },
      hAxis: {
        gridlines: {
          color: '#f6f6f6'
        },
        viewWindow: {
          min:0,
          max:29},
        },
        colors: ['#ff2d55', '#5ac8fa', '#4cd964']
    };
    var cpu_chart_data = google.visualization.arrayToDataTable(cpu_table);
    var cpu_chart = new google.visualization.Table(document.getElementById('hps-cpu-chart-div'));
    cpu_chart.draw(cpu_chart_data, options);

    var mem_char_data = google.visualization.arrayToDataTable(mem_table);
    var mem_chart = new google.visualization.Table(document.getElementById('hps-mem-chart-div'));
    mem_chart.draw(mem_chart_data, options);

    if (!hps_refresh) {
      hps_refresh = setInterval(drawHeavyProcessTables, 2000);
    }

  });
};
<commit_msg>change => tendency<commit_after>function drawHeavyProcessTables() {
  /* CPU table first. */
  $.ajax('/api/heavy_process_stat', { dataType: 'json' }).done(function(response) {
    var cpu_table = [];
    cpu_table[0] = ['Process', 'CPU usage', 'Tendency'];
    for (var i = 0; i < response.cpuList.length; i++) {
        var cpu_entry = [
            response.cpuList[i].process_name,
            response.cpuList[i].cpu_usage,
            response.cpuList[i].tendency
        ];
        cpu_table.push(cpu_entry);
    }

    /* mem */
    var mem_table = [];
    mem_table[0] = ['Process', 'Memory usage', 'Tendency'];
    for (var i = 0; i < response.memList.length; i++) {
        var mem_entry = [
            response.memList[i].process_name,
            response.memList[i].mem_usage,
            response.memList[i].tendency
        ];
    };

    var options = {
      curveType: 'function',
      legend: 'top',
      fontName: 'maven pro',
      vAxis: {
        maxValue: 3.0,
        minValue: 0.0,
        viewWindow: {
          min: 0.0
        },
        gridlines: {
          count: 16,
          color: '#f6f6f6'
        }
      },
      hAxis: {
        gridlines: {
          color: '#f6f6f6'
        },
        viewWindow: {
          min:0,
          max:29},
        },
        colors: ['#ff2d55', '#5ac8fa', '#4cd964']
    };
    var cpu_chart_data = google.visualization.arrayToDataTable(cpu_table);
    var cpu_chart = new google.visualization.Table(document.getElementById('hps-cpu-chart-div'));
    cpu_chart.draw(cpu_chart_data, options);

    var mem_char_data = google.visualization.arrayToDataTable(mem_table);
    var mem_chart = new google.visualization.Table(document.getElementById('hps-mem-chart-div'));
    mem_chart.draw(mem_chart_data, options);

    if (!hps_refresh) {
      hps_refresh = setInterval(drawHeavyProcessTables, 2000);
    }

  });
};
<|endoftext|>


<commit_before>/**
 * Copyright 2014 Flipkart Internet Pvt. Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function Queue() {
  this.requests = {};
  this.refreshTime = 5;
  this.timeout = 4000;
}

Queue.prototype.enqueue = function (key, ajaxRequest) {
  console.log("Adding: " + key);
  this.requests[key] = ajaxRequest;
};

Queue.prototype.remove = function (key) {
  console.log("Removing: " + key);
  delete this.requests[key];
};

Queue.prototype.start = function () {
  setInterval($.proxy(this.executeCalls, this),this.refreshTime * 1000);
};

Queue.prototype.executeCalls = function () {
  for (var property in this.requests) {
    if (this.requests.hasOwnProperty(property)) {
          this.requests[property]();
    }
  }
};

function Tile() {
}

function TileFactory() {
  this.tileObject = "";
}

function submitClicked(e) {
	console.log('submit clicked');
}

function pushTilesObject(object) {
	tileData.push(object);
}

TileFactory.prototype.updateTileData = function() {
  var selectedTile = $("#"+this.tileObject.id);
	selectedTile.find(".tile-title").text(this.tileObject.title);
	var tileid= this.tileObject.id;
	var prepareTileData = { };
	prepareTileData[this.tileObject.id] = this.tileObject;
	pushTilesObject(prepareTileData);
  this.createGraph(this.tileObject, selectedTile);
  var tileListIndex = tileList.indexOf(this.tileObject.id);
	var tileDataIndex = tileData[tileListIndex];
  tileData.splice(tileDataIndex, 1);
  tileData.splice(tileDataIndex, 0, this.tileObject);
}

TileFactory.prototype.createTileData = function(object) {
	var selectedTile = $("#"+object.id);
	selectedTile.find(".tile-title").text(object.title);
	var tileid= object.id;
	var prepareTileData = { };
	prepareTileData[object.id] = object;
	pushTilesObject(prepareTileData);
}

TileFactory.prototype.getTileFormValue = function(form, modal, object) {
	var tileFormValue = {};
	tileFormValue.title = form.find(".tile-title").val();
	tileFormValue.table = form.find(".tile-table").val();
	tileFormValue.id = form.find(".tileId").val();
	tileFormValue.timeUnit = form.find(".tile-time-unit").val();
	tileFormValue.timeValue = form.find(".tile-time-value").val();
	tileFormValue.chartType = form.find(".tile-chart-type").val();
	//updateTile(tileFormValue, modal);
}

function setConfigValue(object) {
  console.log('setting');
  console.log(object.tableDropdownIndex);
	var form = $("#addWidgetModal").find("form");
	form.find(".tile-title").val(object.title);
	form.find(".tile-table").val(parseInt(object.tableDropdownIndex));
	form.find(".tile-time-unit").val(object.timeUnit);
	form.find(".tile-time-value").val(object.timeValue);
	form.find(".tile-chart-type").val(object.chartType);
  $('.tile-table').selectpicker('refresh');
}

function clearForm() {
	var form = $("#tile-configuration").find("form");
	form.find(".tile-title").val('');
	form.find(".tile-table").val('');
	form.find(".tile-time-unit").val('');
	form.find(".tile-time-value").val('');
	form.find(".tile-chart-type").val('');
}

function newBtnElement() {
	return "
<button data-target='#addWidgetModal' class='tile-add-btn tile-add-btn btn btn-primary filter-nav-button glyphicon glyphicon-plus custom-add-btn'onClick='setClicketData(this)'  data-toggle='modal' id='row-"+row+"'></button>
"
}

// create new div
TileFactory.prototype.createNewRow = function(tileElement) {
	tileElement.addClass("col-md-12"); // add class for div which is full width
	if(panelRow.length == 0) { // initial page
		row = 1;
		panelRow.push({widgetType : this.tileObject.widgetType, id : this.tileObject.id});
		tileElement.addClass("row-"+row);
	} else { // incremetn row value by one
		panelRow.push({widgetType : this.tileObject.widgetType, id : this.tileObject.id});
		row = panelRow.length;
		tileElement.addClass("row-"+row);
	}
	if(this.tileObject.widgetType != "full") // dont add row add button for full widget
		tileElement.append(newBtnElement());
	return tileElement;
}

// Add click event for tile config icon
TileFactory.prototype.triggerConfig = function(tileElement, object) {
	tileElement.find(".widget-toolbox").find(".glyphicon-cog").click(function () {
	$("#addWidgetModal").modal('show');
	$("#addWidgetModal").find(".tileId").val(object.id);
  $(".vizualization-type").hide();
  currentChartType = object.chartType;
  removeFilters();
	var tileListIndex = tileList.indexOf(object.id);
	var tileDataIndex = tileData[tileListIndex];
  var tileId = tileList[tileListIndex];
  var selectedTileObject = tileDataIndex[tileId];
  console.log(object);
  if(object.filters.length > 0) {
    filterRowArray = [];
    for(var invokeFilter = 0; invokeFilter< object.filters.length; invokeFilter++ ) {
      console.log('**')
      console.log(invokeFilter);
      addFitlers();
    }
   //setFilters(object);
    setTimeout(function() {   //calls click event after a certain time
    setFilters(object.filters);
}, 1000);
  }
    if(selectedTileObject) {
      setConfigValue(selectedTileObject);
    }
	});
}

// Save action for tile config save button
TileFactory.prototype.saveTileConfig = function(object) {
	$("#tile-configuration").find(".save-changes").click( function () {
    var form = $("#tile-configuration").find("form");
    form.off('submit');
    form.on('submit', $.proxy(function (e) {
			this.getTileFormValue(form, "tile-configuration", object)
	    $("#tile-configuration").modal('hide');
	    e.preventDefault();
    }, object));
	});
}

TileFactory.prototype.createGraph = function(object, tileElement) {
  if(object.chartType == "line") {
    var lineGraph = new LineTile();
		//lineGraph.render(tileElement, object);
    lineGraph.getQuery(tileElement, this.tileObject);
	} else if(object.chartType == "radar") {
    tileElement.find(".chart-item").append('

');
    var radarGraph = new RadarTile();
		radarGraph.render(tileElement, object);
  }
}

TileFactory.prototype.create = function () {
	var tileElement = $(handlebars("#tile-template", {
		tileId: this.tileObject.id
		, title: this.tileObject.title
	}));
	var row = 0;// row
	var clickedRow;// clicked row
	if(defaultPlusBtn) { // check its new row
		tileElement = this.createNewRow(tileElement)
	} else {// row button action
		var splitValue = customBtn.id.split("-");
		var rowObject = panelRow[splitValue[1] - 1];
		clickedRow = rowObject.id
		if(this.tileObject.widgetType != rowObject.widgetType) {// f choosen type and row type is not equal
			tileElement = this.createNewRow(tileElement);
			defaultPlusBtn = true;
		}

		if(this.tileObject.widgetType == 'small'&& rowObject.widgetType == 'small') {
			var findElement = $("."+customBtn.id);
			if(findElement.find(".row-col-1").length == 0) {
				tileElement.addClass('row-col-1');
				tileElement.append("
<button data-target='#addWidgetModal' class='tile-add-btn tile-add-btn btn btn-primary filter-nav-button glyphicon glyphicon-plus custom-add-btn row-col-1'onClick='setClicketData(this)'  data-toggle='modal' id='row-"+splitValue[1]+"'></button>
");
			}
		}
	}

	if(this.tileObject.widgetType == "full") {
		tileElement.find(".tile").addClass('col-md-12');
	} else if(this.tileObject.widgetType == "medium") {
		tileElement.find(".tile").addClass('col-md-6');
		tileElement.find(".tile").width(590);
	} else if(this.tileObject.widgetType == "small") {
		tileElement.find(".tile").addClass('col-md-4');
		tileElement.find(".tile").width(300);
		tileElement.find(".tile").height(200);
	}

	tileElement.find(".chart-item").append('
10,000
');
	tileElement.find(".chart-item").append('

');
	tileElement.find(".chart-item").append('

');

	if(defaultPlusBtn) {// new row
		tileElement.insertBefore('.float-clear');
	} else {// remove row btn and add new div based on type
		customBtn.remove();
		tileElement.insertAfter('#'+clickedRow);
	}

  this.createGraph(this.tileObject, tileElement);
	this.triggerConfig(tileElement, this.tileObject);// add event for tile config
	this.createTileData(this.tileObject);
	this.saveTileConfig(this.tileObject);// add event for tile save btn
};
<commit_msg>fixed incorrect filter row displayed<commit_after>/**
 * Copyright 2014 Flipkart Internet Pvt. Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function Queue() {
  this.requests = {};
  this.refreshTime = 5;
  this.timeout = 4000;
}

Queue.prototype.enqueue = function (key, ajaxRequest) {
  console.log("Adding: " + key);
  this.requests[key] = ajaxRequest;
};

Queue.prototype.remove = function (key) {
  console.log("Removing: " + key);
  delete this.requests[key];
};

Queue.prototype.start = function () {
  setInterval($.proxy(this.executeCalls, this),this.refreshTime * 1000);
};

Queue.prototype.executeCalls = function () {
  for (var property in this.requests) {
    if (this.requests.hasOwnProperty(property)) {
          this.requests[property]();
    }
  }
};

function Tile() {
}

function TileFactory() {
  this.tileObject = "";
}

function submitClicked(e) {
	console.log('submit clicked');
}

function pushTilesObject(object) {
	tileData.push(object);
}

TileFactory.prototype.updateTileData = function() {
  var selectedTile = $("#"+this.tileObject.id);
	selectedTile.find(".tile-title").text(this.tileObject.title);
	var tileid= this.tileObject.id;
	var prepareTileData = { };
	prepareTileData[this.tileObject.id] = this.tileObject;
  this.createGraph(this.tileObject, selectedTile);
  var tileListIndex = tileList.indexOf(this.tileObject.id);
	var tileDataIndex = tileData[tileListIndex];
  tileData.splice(tileDataIndex, 1);
  tileData.splice(tileDataIndex, 0, prepareTileData);
}

TileFactory.prototype.createTileData = function(object) {
	var selectedTile = $("#"+object.id);
	selectedTile.find(".tile-title").text(object.title);
	var tileid= object.id;
	var prepareTileData = { };
	prepareTileData[object.id] = object;
	pushTilesObject(prepareTileData);
}

TileFactory.prototype.getTileFormValue = function(form, modal, object) {
	var tileFormValue = {};
	tileFormValue.title = form.find(".tile-title").val();
	tileFormValue.table = form.find(".tile-table").val();
	tileFormValue.id = form.find(".tileId").val();
	tileFormValue.timeUnit = form.find(".tile-time-unit").val();
	tileFormValue.timeValue = form.find(".tile-time-value").val();
	tileFormValue.chartType = form.find(".tile-chart-type").val();
	//updateTile(tileFormValue, modal);
}

function setConfigValue(object) {
	var form = $("#addWidgetModal").find("form");
	form.find(".tile-title").val(object.title);
	form.find(".tile-table").val(parseInt(object.tableDropdownIndex));
	form.find(".tile-time-unit").val(object.timeUnit);
	form.find(".tile-time-value").val(object.timeValue);
	form.find(".tile-chart-type").val(object.chartType);
  $('.tile-table').selectpicker('refresh');
}

function clearForm() {
	var form = $("#tile-configuration").find("form");
	form.find(".tile-title").val('');
	form.find(".tile-table").val('');
	form.find(".tile-time-unit").val('');
	form.find(".tile-time-value").val('');
	form.find(".tile-chart-type").val('');
}

function newBtnElement() {
	return "
<button data-target='#addWidgetModal' class='tile-add-btn tile-add-btn btn btn-primary filter-nav-button glyphicon glyphicon-plus custom-add-btn'onClick='setClicketData(this)'  data-toggle='modal' id='row-"+row+"'></button>
"
}

// create new div
TileFactory.prototype.createNewRow = function(tileElement) {
	tileElement.addClass("col-md-12"); // add class for div which is full width
	if(panelRow.length == 0) { // initial page
		row = 1;
		panelRow.push({widgetType : this.tileObject.widgetType, id : this.tileObject.id});
		tileElement.addClass("row-"+row);
	} else { // incremetn row value by one
		panelRow.push({widgetType : this.tileObject.widgetType, id : this.tileObject.id});
		row = panelRow.length;
		tileElement.addClass("row-"+row);
	}
	if(this.tileObject.widgetType != "full") // dont add row add button for full widget
		tileElement.append(newBtnElement());
	return tileElement;
}

// Add click event for tile config icon
TileFactory.prototype.triggerConfig = function(tileElement, object) {
	tileElement.find(".widget-toolbox").find(".glyphicon-cog").click(function () {
	$("#addWidgetModal").modal('show');
	$("#addWidgetModal").find(".tileId").val(object.id);
  $(".vizualization-type").hide();
  currentChartType = object.chartType;
  removeFilters();
	var tileListIndex = tileList.indexOf(object.id);
	var tileDataIndex = tileData[tileListIndex];
  var tileId = tileList[tileListIndex];
  var selectedTileObject = tileDataIndex[tileId];
  if(object.filters.length > 0) {
    filterRowArray = [];
    for(var invokeFilter = 0; invokeFilter< selectedTileObject.filters.length; invokeFilter++ ) {
      addFitlers();
    }
   //setFilters(object);
    setTimeout(function() {   //calls click event after a certain time
    setFilters(selectedTileObject.filters);
    }, 1000);
  }
    if(selectedTileObject) {
      setConfigValue(selectedTileObject);
    }
	});
}

// Save action for tile config save button
TileFactory.prototype.saveTileConfig = function(object) {
	$("#tile-configuration").find(".save-changes").click( function () {
    var form = $("#tile-configuration").find("form");
    form.off('submit');
    form.on('submit', $.proxy(function (e) {
			this.getTileFormValue(form, "tile-configuration", object)
	    $("#tile-configuration").modal('hide');
	    e.preventDefault();
    }, object));
	});
}

TileFactory.prototype.createGraph = function(object, tileElement) {
  if(object.chartType == "line") {
    var lineGraph = new LineTile();
		//lineGraph.render(tileElement, object);
    lineGraph.getQuery(tileElement, this.tileObject);
	} else if(object.chartType == "radar") {
    tileElement.find(".chart-item").append('

');
    var radarGraph = new RadarTile();
		radarGraph.render(tileElement, object);
  }
}

TileFactory.prototype.create = function () {
	var tileElement = $(handlebars("#tile-template", {
		tileId: this.tileObject.id
		, title: this.tileObject.title
	}));
	var row = 0;// row
	var clickedRow;// clicked row
	if(defaultPlusBtn) { // check its new row
		tileElement = this.createNewRow(tileElement)
	} else {// row button action
		var splitValue = customBtn.id.split("-");
		var rowObject = panelRow[splitValue[1] - 1];
		clickedRow = rowObject.id
		if(this.tileObject.widgetType != rowObject.widgetType) {// f choosen type and row type is not equal
			tileElement = this.createNewRow(tileElement);
			defaultPlusBtn = true;
		}

		if(this.tileObject.widgetType == 'small'&& rowObject.widgetType == 'small') {
			var findElement = $("."+customBtn.id);
			if(findElement.find(".row-col-1").length == 0) {
				tileElement.addClass('row-col-1');
				tileElement.append("
<button data-target='#addWidgetModal' class='tile-add-btn tile-add-btn btn btn-primary filter-nav-button glyphicon glyphicon-plus custom-add-btn row-col-1'onClick='setClicketData(this)'  data-toggle='modal' id='row-"+splitValue[1]+"'></button>
");
			}
		}
	}

	if(this.tileObject.widgetType == "full") {
		tileElement.find(".tile").addClass('col-md-12');
	} else if(this.tileObject.widgetType == "medium") {
		tileElement.find(".tile").addClass('col-md-6');
		tileElement.find(".tile").width(590);
	} else if(this.tileObject.widgetType == "small") {
		tileElement.find(".tile").addClass('col-md-4');
		tileElement.find(".tile").width(300);
		tileElement.find(".tile").height(200);
	}

	tileElement.find(".chart-item").append('
10,000
');
	tileElement.find(".chart-item").append('

');
	tileElement.find(".chart-item").append('

');

	if(defaultPlusBtn) {// new row
		tileElement.insertBefore('.float-clear');
	} else {// remove row btn and add new div based on type
		customBtn.remove();
		tileElement.insertAfter('#'+clickedRow);
	}

  this.createGraph(this.tileObject, tileElement);
	this.triggerConfig(tileElement, this.tileObject);// add event for tile config
	this.createTileData(this.tileObject);
	this.saveTileConfig(this.tileObject);// add event for tile save btn
};
<|endoftext|>


<commit_before>import * as delaney from './delaney';
import * as delaney2d from './delaney2d';
import * as derived from './derived';
import * as fundamental from './fundamental';
import * as properties from './properties';
import * as tilings from './tilings';

const _assert = (condition, message) => {
  if (!condition)
    throw new Error(message || 'assertion error');
};

export const collapse = (ds, toBeRemoved, connectorIndex) => {
  const dim = delaney.dim(ds);
  const k = connectorIndex;
  const old2new = {};
  let next = 1;

  for (const D of ds.elements()) {
    if (toBeRemoved.indexOf(D) < 0) {
      old2new[D] = next;
      ++next;
    }
    else {
      const Dk = ds.s(k, D);

      _assert(
        old2new[Dk] == null,
        `${k}-neighbor ${Dk} of removed element ${D} must also be removed`
      );
    }
  }

  const size = next - 1;
  const ops = new Array(dim + 1).fill(0).map(_ => []);
  const brs = new Array(dim).fill(0).map(_ => []);

  for (const D of ds.elements()) {
    if (old2new[D]) {
      for (const i of ds.indices()) {
        const Di = ds.s(i, D);

        if (i != connectorIndex) {
          while (!old2new[Di])
            Di = ds.s(i, ds.s(connectorIndex, Di));
        }

        ops[i].push([old2new[D], old2new[Di]]);

        if (i < dim)
          brs[i].push([old2new[D], ds.v(i, i + 1, D)]);
      }
    }
  }

  return delaney.build(dim, size, (_, i) => ops[i], (_, i) => brs[i]);
};

const isFundamentalTile = (ds, D) => {
  const idcs = ds.indices().filter(i => i < ds.dim);
  const sub = derived.subsymbol(ds, idcs, D);

  if (ds.dim == 3) {
    return delaney2d.curvature(sub) == 4;
  }
  else if (ds.dim == 2) {
    return properties.isLoopless(sub) && ds.v(0, 1, D) == 1;
  }
};

const mergeTiles = (ds, seeds) => {
  const idcs = ds.indices().filter(i => i != ds.dim - 1);
  const removed = [].concat(...properties.orbits(ds, idcs, seeds));

  return collapse(ds, removed, ds.dim);
};

const mergeFundamentalTiles = ds => {
  const seeds = [];

  for (const [D, i] of fundamental.innerEdges(ds)) {
    if (i < ds.dim)
      continue;

    if (isFundamentalTile(ds, D) && isFundamentalTile(ds, ds.s(i, D)))
      seeds.push(D);
  }

  return mergeTiles(ds, seeds);
};

const mergeNonFundamentalTiles = ds => {
  const idcsTile = ds.indices().filter(i => i < ds.dim);
  const idcsFacet = ds.indices().filter(i => i < ds.dim - 1);

  const seeds = [];

  for (const orbit of properties.orbits(ds, idcsTile, ds.elements())) {
    if (!isFundamentalTile(ds, orbit[0]))
      continue;

    for (const E of properties.orbitReps(ds, idcsFacet, orbit)) {
      if (!isFundamentalTile(ds, ds.s(ds.dim, E))) {
        seeds.push(E);
        break;
      }
    }
  }

  return mergeTiles(ds, seeds);
};

const mergeFacets = ds => {
  const dim = delaney.dim(ds);
  const seeds = ds.elements().filter(D => delaney.m(ds, dim, dim - 1, D) == 2);
  const idcs = ds.indices().filter(i => i != dim - 2);
  const removed = [].concat(...properties.orbits(ds, idcs, seeds));

  return collapse(ds, removed, dim - 1);
};

const mergeEdges = ds => {
  const idcs = ds.indices().filter(i => i > 0);

  const seeds = [];

  for (const orbit of properties.orbits(ds, idcs, ds.elements())) {
    if (orbit.every(D => delaney.m(ds, 1, 2, D) == 2))
      seeds.push(orbit[0]);
  }

  const removed = [].concat(...properties.orbits(ds, idcs, seeds));
  return collapse(ds, removed, 1);
};

const chain = (ds, ...fns) => {
  for (const fn of fns)
    ds = fn(ds);

  return ds;
};

export const simplify = ds => chain(
  ds,

  mergeFundamentalTiles, mergeFacets,
  mergeNonFundamentalTiles, mergeFacets,
  mergeEdges,

  derived.dual, mergeFacets, derived.dual
);

if (require.main == module) {
  const test = ds => {
    console.log(`#input D-symbol`);
    console.log(`${ds}`);

    const dsx = derived.canonical(simplify(ds));
    console.log(`#output D-symbol`);
    console.log(`${dsx}`);
    console.log();
  }

  const symbols = [
    delaney.parse('<1.1:1:1,1,1:3,6>'),
    delaney.parse('<1.1:2:1 2,1 2,2:3 6,4>'),
    delaney.parse('<1.1:2 3:2,1 2,1 2,2:6,3 2,6>'),
    delaney.parse('<003.1:72 3:2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72,71 3 34 69 7 46 14 11 13 54 17 40 56 21 52 28 25 27 43 31 42 72 49 37 48 53 44 70 50 55 62 59 61 68 65 67,5 6 9 10 14 13 31 32 19 20 23 24 28 27 37 38 33 34 39 40 45 46 64 63 51 52 59 60 58 57 61 62 72 71 69 70,15 16 17 18 45 46 8 66 65 64 63 68 67 51 52 22 57 58 59 60 61 62 41 42 32 39 40 47 48 38 44 50 72 71 56 70:4 4 3 4 4 3 4 4 3 3,3 3 3 3 3 3 3 3 3 3 3 3,6 6 4 4 4 4 4 4>')
  ];

  for (const ds of symbols) {
    test(derived.barycentricSubdivision(ds));
  }
}
<commit_msg>simplify: run facet and edge merges in a loop<commit_after>import * as delaney from './delaney';
import * as delaney2d from './delaney2d';
import * as derived from './derived';
import * as fundamental from './fundamental';
import * as properties from './properties';
import * as tilings from './tilings';

const _assert = (condition, message) => {
  if (!condition)
    throw new Error(message || 'assertion error');
};

export const collapse = (ds, toBeRemoved, connectorIndex) => {
  const dim = delaney.dim(ds);
  const k = connectorIndex;
  const old2new = {};
  let next = 1;

  for (const D of ds.elements()) {
    if (toBeRemoved.indexOf(D) < 0) {
      old2new[D] = next;
      ++next;
    }
    else {
      const Dk = ds.s(k, D);

      _assert(
        old2new[Dk] == null,
        `${k}-neighbor ${Dk} of removed element ${D} must also be removed`
      );
    }
  }

  const size = next - 1;
  const ops = new Array(dim + 1).fill(0).map(_ => []);
  const brs = new Array(dim).fill(0).map(_ => []);

  for (const D of ds.elements()) {
    if (old2new[D]) {
      for (const i of ds.indices()) {
        const Di = ds.s(i, D);

        if (i != connectorIndex) {
          while (!old2new[Di])
            Di = ds.s(i, ds.s(connectorIndex, Di));
        }

        ops[i].push([old2new[D], old2new[Di]]);

        if (i < dim)
          brs[i].push([old2new[D], ds.v(i, i + 1, D)]);
      }
    }
  }

  return delaney.build(dim, size, (_, i) => ops[i], (_, i) => brs[i]);
};

const isFundamentalTile = (ds, D) => {
  const idcs = ds.indices().filter(i => i < ds.dim);
  const sub = derived.subsymbol(ds, idcs, D);

  if (ds.dim == 3) {
    return delaney2d.curvature(sub) == 4;
  }
  else if (ds.dim == 2) {
    return properties.isLoopless(sub) && ds.v(0, 1, D) == 1;
  }
};

const mergeTiles = (ds, seeds) => {
  const idcs = ds.indices().filter(i => i != ds.dim - 1);
  const removed = [].concat(...properties.orbits(ds, idcs, seeds));

  return collapse(ds, removed, ds.dim);
};

const mergeFundamentalTiles = ds => {
  const seeds = [];

  for (const [D, i] of fundamental.innerEdges(ds)) {
    if (i < ds.dim)
      continue;

    if (isFundamentalTile(ds, D) && isFundamentalTile(ds, ds.s(i, D)))
      seeds.push(D);
  }

  return mergeTiles(ds, seeds);
};

const mergeNonFundamentalTiles = ds => {
  const idcsTile = ds.indices().filter(i => i < ds.dim);
  const idcsFacet = ds.indices().filter(i => i < ds.dim - 1);

  const seeds = [];

  for (const orbit of properties.orbits(ds, idcsTile, ds.elements())) {
    if (!isFundamentalTile(ds, orbit[0]))
      continue;

    for (const E of properties.orbitReps(ds, idcsFacet, orbit)) {
      if (!isFundamentalTile(ds, ds.s(ds.dim, E))) {
        seeds.push(E);
        break;
      }
    }
  }

  return mergeTiles(ds, seeds);
};

const mergeFacets = ds => {
  const dim = delaney.dim(ds);
  const seeds = ds.elements().filter(D => delaney.m(ds, dim, dim - 1, D) == 2);
  const idcs = ds.indices().filter(i => i != dim - 2);
  const removed = [].concat(...properties.orbits(ds, idcs, seeds));

  return collapse(ds, removed, dim - 1);
};

const mergeEdges = ds => {
  const idcs = ds.indices().filter(i => i > 0);

  const seeds = [];

  for (const orbit of properties.orbits(ds, idcs, ds.elements())) {
    if (orbit.every(D => delaney.m(ds, 1, 2, D) == 2))
      seeds.push(orbit[0]);
  }

  const removed = [].concat(...properties.orbits(ds, idcs, seeds));
  return collapse(ds, removed, 1);
};

const chain = (ds, ...fns) => {
  for (const fn of fns)
    ds = fn(ds);

  return ds;
};

export const simplify = ds => {
  ds = chain(
    ds, mergeFundamentalTiles, mergeFacets, mergeNonFundamentalTiles
  );

  let dsOld;

  do {
    dsOld = ds;
    ds = chain(
      ds, mergeFacets, mergeEdges, derived.dual, mergeFacets, derived.dual
    );
  }
  while (ds.size < dsOld.size);

  return ds;
};

if (require.main == module) {
  const test = ds => {
    console.log(`#input D-symbol`);
    console.log(`${ds}`);

    const dsx = derived.canonical(simplify(ds));
    console.log(`#output D-symbol`);
    console.log(`${dsx}`);
    console.log();
  }

  const symbols = [
    delaney.parse('<1.1:1:1,1,1:3,6>'),
    delaney.parse('<1.1:2:1 2,1 2,2:3 6,4>'),
    delaney.parse('<1.1:2 3:2,1 2,1 2,2:6,3 2,6>'),
    delaney.parse('<003.1:72 3:2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72,71 3 34 69 7 46 14 11 13 54 17 40 56 21 52 28 25 27 43 31 42 72 49 37 48 53 44 70 50 55 62 59 61 68 65 67,5 6 9 10 14 13 31 32 19 20 23 24 28 27 37 38 33 34 39 40 45 46 64 63 51 52 59 60 58 57 61 62 72 71 69 70,15 16 17 18 45 46 8 66 65 64 63 68 67 51 52 22 57 58 59 60 61 62 41 42 32 39 40 47 48 38 44 50 72 71 56 70:4 4 3 4 4 3 4 4 3 3,3 3 3 3 3 3 3 3 3 3 3 3,6 6 4 4 4 4 4 4>')
  ];

  for (const ds of symbols) {
    test(derived.barycentricSubdivision(ds));
  }
}
<|endoftext|>


<commit_before>'use strict';

const inquirer = require('inquirer');
const ora = require('ora');
const fs = require('fs');
const path = require('upath');
const pingyInit = require('@pingy/init');
const compilerMap = require('./compilerMap');
const updatePkgScripts = require('./updatePkgScripts');
const installDeps = require('./installDeps');
const npmInit = require('./npmInit');
const scaffold = require('./scaffold');
const renderLastInit = require('./renderLastInit');

const pkgJsonPath = path.join(process.cwd(), 'package.json');
const dotPingyJsonPath = path.join(process.cwd(), '.pingy.json');
const pingyJsonPath = path.join(process.cwd(), 'pingy.json');
const pkgJsonExists = fs.existsSync(pkgJsonPath);
const pingyJsonExists = fs.existsSync(pingyJsonPath) || fs.existsSync(dotPingyJsonPath);

const requiredLastInitProps = ['html', 'scripts', 'styles'];
const createChoices = type => [type, ...compilerMap[type].map(x => x.name)];

const stage1 = [
  {
    type: 'list',
    name: 'html',
    message: 'What document format do you wish to use',
    choices: createChoices('HTML'),
  },
  {
    type: 'list',
    name: 'styles',
    message: 'What styles format do you wish to use',
    choices: createChoices('CSS'),
  },
  {
    type: 'list',
    name: 'scripts',
    message: 'What scripts format do you wish to use',
    choices: createChoices('JS'),
  }
];

function performActions(answers, options) {
  const scaffoldOptions = pingyInit.transformOptions(answers, options);

  updatePkgScripts();
  return scaffold(scaffoldOptions).then(() => installDeps(scaffoldOptions, options));
}

function processAnswers(options) {
  return (answers) => {
    global.conf.set('lastInit', answers);

    npmInit()
      .then(() => performActions(answers, options))
      .catch(e => ora().fail(e.stack));
  };
}

function prompt(options) {
  const hasLastInit = !requiredLastInitProps.some(prop => !global.conf.has(`lastInit.${prop}`));
  const lastInit = hasLastInit ? global.conf.get('lastInit') : null;
  return new Promise((resolve) => {
    if (pingyJsonExists && pkgJsonExists) {
      return inquirer
        .prompt([
          {
            type: 'confirm',
            name: 'resume',
            default: false,
            message:
              'Looks like you have run `pingy init` already. Pingy has detected a pingy.json and package.json in your project, do you want to continue anyway?',
          }
        ])
        .then(answers => resolve(answers.resume));
    }
    return resolve(true);
  })
    .then((resume) => {
      if (!resume || !lastInit || options.ask) return resume;
      return inquirer
        .prompt([
          {
            type: 'confirm',
            name: 'repeatLastInit',
            default: true,
            message: `Do you want to initialize your project using the same settings as last time?\n${renderLastInit(
              lastInit
            )}`,
          }
        ])
        .then((answers) => {
          if (answers.repeatLastInit) {
            global.repeatLastInit = true;
          }
          return resume;
        });
    })
    .then((resume) => {
      if (global.repeatLastInit) return processAnswers(options)(lastInit);
      if (resume) return inquirer.prompt(stage1).then(processAnswers(options));
      return null;
    });
}

function init(options) {
  return prompt(options);
}

module.exports = init;
<commit_msg>[cli,init,scaffold-primitive] Progress towards greater abstraction and custom scaffolds<commit_after>'use strict';

const inquirer = require('inquirer');
const ora = require('ora');
const fs = require('fs');
const path = require('upath');
const pingyInit = require('@pingy/init');
const compilerMap = require('@pingy/init/compilerMap');
const updatePkgScripts = require('./updatePkgScripts');
const installDeps = require('./installDeps');
const npmInit = require('./npmInit');
const scaffold = require('./scaffold');
const renderLastInit = require('./renderLastInit');

const pkgJsonPath = path.join(process.cwd(), 'package.json');
const dotPingyJsonPath = path.join(process.cwd(), '.pingy.json');
const pingyJsonPath = path.join(process.cwd(), 'pingy.json');
const pkgJsonExists = fs.existsSync(pkgJsonPath);
const pingyJsonExists = fs.existsSync(pingyJsonPath) || fs.existsSync(dotPingyJsonPath);

const requiredLastInitProps = ['html', 'scripts', 'styles'];
const createChoices = type => [type, ...compilerMap[type].map(x => x.name)];

const stage1 = [
  {
    type: 'list',
    name: 'html',
    message: 'What document format do you wish to use',
    choices: createChoices('HTML'),
  },
  {
    type: 'list',
    name: 'styles',
    message: 'What styles format do you wish to use',
    choices: createChoices('CSS'),
  },
  {
    type: 'list',
    name: 'scripts',
    message: 'What scripts format do you wish to use',
    choices: createChoices('JS'),
  }
];

function performActions(answers, options) {
  const scaffoldOptions = pingyInit.transformOptions(answers, options);

  updatePkgScripts();
  return scaffold(scaffoldOptions).then(() => installDeps(scaffoldOptions, options));
}

function processAnswers(options) {
  return (answers) => {
    global.conf.set('lastInit', answers);

    npmInit()
      .then(() => performActions(answers, options))
      .catch(e => ora().fail(e.stack));
  };
}

function prompt(options) {
  const hasLastInit = !requiredLastInitProps.some(prop => !global.conf.has(`lastInit.${prop}`));
  const lastInit = hasLastInit ? global.conf.get('lastInit') : null;
  return new Promise((resolve) => {
    if (pingyJsonExists && pkgJsonExists) {
      return inquirer
        .prompt([
          {
            type: 'confirm',
            name: 'resume',
            default: false,
            message:
              'Looks like you have run `pingy init` already. Pingy has detected a pingy.json and package.json in your project, do you want to continue anyway?',
          }
        ])
        .then(answers => resolve(answers.resume));
    }
    return resolve(true);
  })
    .then((resume) => {
      if (!resume || !lastInit || options.ask) return resume;
      return inquirer
        .prompt([
          {
            type: 'confirm',
            name: 'repeatLastInit',
            default: true,
            message: `Do you want to initialize your project using the same settings as last time?\n${renderLastInit(
              lastInit
            )}`,
          }
        ])
        .then((answers) => {
          if (answers.repeatLastInit) {
            global.repeatLastInit = true;
          }
          return resume;
        });
    })
    .then((resume) => {
      if (global.repeatLastInit) return processAnswers(options)(lastInit);
      if (resume) return inquirer.prompt(stage1).then(processAnswers(options));
      return null;
    });
}

function init(options) {
  return prompt(options);
}

module.exports = init;
<|endoftext|>


<commit_before>var defaultsVersion = '1.2.2';
var objName = 'findbartweak';
var objPathString = 'findbartweak';

// We define this here so we can use it also as the default value for the preference
this.__defineGetter__('minTextboxWidth', function() {
	if(Services.appinfo.OS == 'Darwin') { return 176; }
	else if(Services.appinfo.OS == 'WINNT') {
		if(Services.navigator.oscpu && Services.navigator.oscpu.indexOf('Windows NT 5.1') == 0) { return 127; }
		else { return 120; }
	}
	else { return 180; }
});

// Some of our preferences should coincide with firefox defaults that may change with OS
var defaultBranch = Services.prefs.getDefaultBranch('');

var prefList = {
	highlightByDefault: true,
	highlightOnFindAgain: false,
	hideWhenFinderHidden: false,
	minNoDelay: 3,
	highlightColor: "#EF0FFF",
	useCounter: true,

	findInTabs: true,
	alwaysOpenFIT: false,
	maxFIT: 1000,
	FITFull: false,
	multipleFITFull: false,

	useGrid: true,
	gridLimit: 100,
	gridAdjustPadding: 0,
	gridAdjustWidth: 0,

	sightsCurrent: true,
	sightsHighlights: false,
	sightsStyle: 'focus',
	sightsRepeat: 1,
	sightsColor: '#EF0FFF',
	sightsSameColor: false,
	sightsSameColorAll: true,
	sightsAllColor: '#EF0FFF',
	sightsAllSameColor: true,
	sightsLimit: 10,

	blurCloses: false,
	perTab: (Services.vc.compare(Services.appinfo.platformVersion, "25.0a1") >= 0),
	onStartup: false,
	findbarHidden: true,

	movetoTop: false,
	movetoBottom: false,
	movetoRight: false,
	FF25Tweaks: true,
	hideClose: false,
	hideLabels: false,
	hideFindLabel: false,
	findFieldWidth: (Services.appinfo.OS != 'Darwin' && Services.appinfo.OS != 'WINNT') ? 240 : minTextboxWidth,
	selectColor: '#38d878',
	keepSelectContrast: true,

	fillSelectedText: false,
	fillTextShowFindBar: true,
	layoutEatSpaces: defaultBranch.getBoolPref('layout.word_select.eat_space_to_next_word'),
	layoutStopAtPunctuation: defaultBranch.getBoolPref('layout.word_select.stop_at_punctuation'),

	ctrlFCloses: true,
	ctrlFClosesOnValue: true,
	keepButtons: false,
	FAYTmode: 'quick',

	/* to revert the builtin preferences */
	FAYTtimeout: defaultBranch.getIntPref('accessibility.typeaheadfind.timeout'),
	FAYTenabled: defaultBranch.getBoolPref('accessibility.typeaheadfind'),
	FAYTprefill: defaultBranch.getBoolPref('accessibility.typeaheadfind.prefillwithselection'),
	resetNative: false,

	lwthemebgImage: '',
	lwthemebgWidth: 0,
	lwthemecolor: '',
	lwthemebgColor: ''
};

var perTabFB = false;
var onTopFB = false;
var mFinder = false;

function startAddon(window) {
	prepareObject(window);
	window[objName].moduleAid.load(objName, true);
}

function stopAddon(window) {
	removeObject(window);
}

function startPreferences(window) {
	replaceObjStrings(window.document);
	preparePreferences(window);
	window[objName].moduleAid.load('preferences', true);
}

function startConditions(aReason) {
	return true;
}

function onStartup(aReason) {
	if(Services.vc.compare(Services.appinfo.platformVersion, "25.0a1") >= 0) { perTabFB = true; }
	if(Services.vc.compare(Services.appinfo.platformVersion, "26.0a1") >= 0) { onTopFB = true; }
	if(Services.vc.compare(Services.appinfo.platformVersion, "26.0a1") >= 0) { mFinder = true; }

	moduleAid.load('builtinPrefs');
	moduleAid.load('highlightColor');
	moduleAid.load('findInTabsSandbox');
	moduleAid.load('compatibilityFix/sandboxFixes');

	// Apply the add-on to every window opened and to be opened
	windowMediator.callOnAll(startAddon, 'navigator:browser');
	windowMediator.register(startAddon, 'domwindowopened', 'navigator:browser');

	// Apply the add-on to every window opened and to be opened
	windowMediator.callOnAll(startAddon, 'navigator:view-source');
	windowMediator.register(startAddon, 'domwindowopened', 'navigator:view-source');

	// Apply the add-on to every preferences window opened and to be opened
	windowMediator.callOnAll(startPreferences, null, "chrome://"+objPathString+"/content/options.xul");
	windowMediator.register(startPreferences, 'domwindowopened', null, "chrome://"+objPathString+"/content/options.xul");
	browserMediator.callOnAll(startPreferences, "chrome://"+objPathString+"/content/options.xul");
	browserMediator.register(startPreferences, 'pageshow', "chrome://"+objPathString+"/content/options.xul");
}

function onShutdown(aReason) {
	// remove the add-on from all windows
	windowMediator.callOnAll(stopAddon, null, null, true);
	browserMediator.callOnAll(stopAddon, null, true);

	moduleAid.unload('compatibilityFix/sandboxFixes');
	moduleAid.unload('findInTabsSandbox');
	moduleAid.unload('highlightColor');
	moduleAid.unload('builtinPrefs');
}
<commit_msg>move findbar to top was backed out again<commit_after>var defaultsVersion = '1.2.3';
var objName = 'findbartweak';
var objPathString = 'findbartweak';

// We define this here so we can use it also as the default value for the preference
this.__defineGetter__('minTextboxWidth', function() {
	if(Services.appinfo.OS == 'Darwin') { return 176; }
	else if(Services.appinfo.OS == 'WINNT') {
		if(Services.navigator.oscpu && Services.navigator.oscpu.indexOf('Windows NT 5.1') == 0) { return 127; }
		else { return 120; }
	}
	else { return 180; }
});

// Some of our preferences should coincide with firefox defaults that may change with OS
var defaultBranch = Services.prefs.getDefaultBranch('');

var prefList = {
	highlightByDefault: true,
	highlightOnFindAgain: false,
	hideWhenFinderHidden: false,
	minNoDelay: 3,
	highlightColor: "#EF0FFF",
	useCounter: true,

	findInTabs: true,
	alwaysOpenFIT: false,
	maxFIT: 1000,
	FITFull: false,
	multipleFITFull: false,

	useGrid: true,
	gridLimit: 100,
	gridAdjustPadding: 0,
	gridAdjustWidth: 0,

	sightsCurrent: true,
	sightsHighlights: false,
	sightsStyle: 'focus',
	sightsRepeat: 1,
	sightsColor: '#EF0FFF',
	sightsSameColor: false,
	sightsSameColorAll: true,
	sightsAllColor: '#EF0FFF',
	sightsAllSameColor: true,
	sightsLimit: 10,

	blurCloses: false,
	perTab: (Services.vc.compare(Services.appinfo.platformVersion, "25.0a1") >= 0),
	onStartup: false,
	findbarHidden: true,

	movetoTop: false,
	movetoBottom: false,
	movetoRight: false,
	FF25Tweaks: true,
	hideClose: false,
	hideLabels: false,
	hideFindLabel: false,
	findFieldWidth: (Services.appinfo.OS != 'Darwin' && Services.appinfo.OS != 'WINNT') ? 240 : minTextboxWidth,
	selectColor: '#38d878',
	keepSelectContrast: true,

	fillSelectedText: false,
	fillTextShowFindBar: true,
	layoutEatSpaces: defaultBranch.getBoolPref('layout.word_select.eat_space_to_next_word'),
	layoutStopAtPunctuation: defaultBranch.getBoolPref('layout.word_select.stop_at_punctuation'),

	ctrlFCloses: true,
	ctrlFClosesOnValue: true,
	keepButtons: false,
	FAYTmode: 'quick',

	/* to revert the builtin preferences */
	FAYTtimeout: defaultBranch.getIntPref('accessibility.typeaheadfind.timeout'),
	FAYTenabled: defaultBranch.getBoolPref('accessibility.typeaheadfind'),
	FAYTprefill: defaultBranch.getBoolPref('accessibility.typeaheadfind.prefillwithselection'),
	resetNative: false,

	lwthemebgImage: '',
	lwthemebgWidth: 0,
	lwthemecolor: '',
	lwthemebgColor: ''
};

var perTabFB = false;
var onTopFB = false;
var mFinder = false;

function startAddon(window) {
	prepareObject(window);
	window[objName].moduleAid.load(objName, true);
}

function stopAddon(window) {
	removeObject(window);
}

function startPreferences(window) {
	replaceObjStrings(window.document);
	preparePreferences(window);
	window[objName].moduleAid.load('preferences', true);
}

function startConditions(aReason) {
	return true;
}

function onStartup(aReason) {
	if(Services.vc.compare(Services.appinfo.platformVersion, "25.0a1") >= 0) { perTabFB = true; }
	//if(Services.vc.compare(Services.appinfo.platformVersion, "26.0a1") >= 0) { onTopFB = true; } // Backed out of Trunk until further notice
	if(Services.vc.compare(Services.appinfo.platformVersion, "26.0a1") >= 0) { mFinder = true; }

	moduleAid.load('builtinPrefs');
	moduleAid.load('highlightColor');
	moduleAid.load('findInTabsSandbox');
	moduleAid.load('compatibilityFix/sandboxFixes');

	// Apply the add-on to every window opened and to be opened
	windowMediator.callOnAll(startAddon, 'navigator:browser');
	windowMediator.register(startAddon, 'domwindowopened', 'navigator:browser');

	// Apply the add-on to every window opened and to be opened
	windowMediator.callOnAll(startAddon, 'navigator:view-source');
	windowMediator.register(startAddon, 'domwindowopened', 'navigator:view-source');

	// Apply the add-on to every preferences window opened and to be opened
	windowMediator.callOnAll(startPreferences, null, "chrome://"+objPathString+"/content/options.xul");
	windowMediator.register(startPreferences, 'domwindowopened', null, "chrome://"+objPathString+"/content/options.xul");
	browserMediator.callOnAll(startPreferences, "chrome://"+objPathString+"/content/options.xul");
	browserMediator.register(startPreferences, 'pageshow', "chrome://"+objPathString+"/content/options.xul");
}

function onShutdown(aReason) {
	// remove the add-on from all windows
	windowMediator.callOnAll(stopAddon, null, null, true);
	browserMediator.callOnAll(stopAddon, null, true);

	moduleAid.unload('compatibilityFix/sandboxFixes');
	moduleAid.unload('findInTabsSandbox');
	moduleAid.unload('highlightColor');
	moduleAid.unload('builtinPrefs');
}
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { bindActionCreators } from 'redux'
import {
  Text,
  View,
  TouchableHighlight,
  AsyncStorage
} from 'react-native'

import TextField from '../Components/TextField'
import Button from '../Components/Button'
import SceneHeading from '../Components/SceneHeading'
import FormHeading from '../Components/FormHeading'
import Config from '../Config'
import { connect } from 'react-redux'
import * as loginActions from '../Actions/Login'
import * as appActions from '../Actions/App'
import { FontSizes } from '../GlobalStyles'
import { ModalMode } from '../Components/WaitModal'

class LoginScene extends Component {

  constructor(props) {
    super(props)
    // For future terseness
    this.actions = this.props.actions
    this.dispatch = this.props.dispatch
    this.navigator = this.props.navigator
    this.route = this.props.route
  }

  componentWillMount() {
    this.loadPersistedPhoneNumber()
  }

  loadPersistedPhoneNumber() {
    AsyncStorage.getItem('@phoneNumber',(error, result) => {
      if(!error)
        this.actions.phoneNumberTextChange(result)
    })
  }

  login() {
    const { phoneNumber, pin } = this.props.state.Login
    this.props.dispatch(appActions.setModal({
      modalVisible: true,
      modalText: "Logging in",
      modalMode: ModalMode.WAITING
    }))

    this.actions.attempt(
      phoneNumber,
      pin,
      this.navigator
    )
    AsyncStorage.setItem('@phoneNumber',phoneNumber,(error) => {
      if(error) {
        console.log('Could not store phone number')
      } else {
        console.log('Phone number stored '+phoneNumber)
      }

    })
  }

  render() {
    const { phoneNumber, pin } = this.props.state.Login
    let footer = <Text style={{fontStyle: 'italic', fontSize: FontSizes.p}}>ECD v{Config.version}</Text>

    if(Config.debug) {
      footer =
        <View style={{flex: 1, justifyContent: 'flex-end', alignItems: 'center', padding: 10}}>
          <Text style={{fontStyle: 'italic', fontSize: FontSizes.p}}>RN v{Config.rnVersion}</Text>
          <Text style={{fontStyle: 'italic', fontSize: FontSizes.p}}>ECD v{Config.version}</Text>
        </View>
    } else {
      footer =
        <View style={{flex: 1, justifyContent: 'flex-end', alignItems: 'center', padding: 10}}>
          <Text style={{fontStyle: 'italic', fontSize: FontSizes.p}}>ECD v{Config.version}</Text>
        </View>
    }

    return (
      <View style={{flex: 1, flexDirection: 'column', justifyContent: 'space-between'}}>
        <View style={{height: 20}}/>
        <View style={{height: 320}}>
          <SceneHeading text="ECD APP"/>

          <FormHeading text="Login"/>
          <TextField
            value={ phoneNumber }
            ref="phoneNumber"
            onChangeText={ (text) => this.actions.phoneNumberTextChange(text) }
            placeholder="Phone Number"
            maxLength={10}
            keyboardType="phone-pad"
            returnKeyType="next"
            onSubmitEditing={ () => this.refs.pin.textInput.focus() }
          />

          <TextField
            value={ pin }
            ref="pin"
            onChangeText={ (text) => this.actions.pinTextChange(text) }
            placeholder="PIN"
            maxLength={4}
            secureTextEntry={true}
            keyboardType="phone-pad"
            onSubmitEditing={ () => this.login() }
            width={ this.screenWidth * 0.6 }
          />
          <View style={{flex: 1, alignItems: 'center'}}>
            <Button text="Login" onPress={() => this.login()}/>
          </View>
        </View>
        {footer}
      </View>
    )
  }
}

export default connect(
  (state) => ({
    state: state
  }),
  (dispatch) => ({
    actions: bindActionCreators(loginActions, dispatch)
  })
)(LoginScene)<commit_msg>added crashing on easteregg for testing<commit_after>import React, { Component } from 'react'
import { bindActionCreators } from 'redux'
import {
  Text,
  View,
  TouchableHighlight,
  AsyncStorage,
  NativeModules
} from 'react-native'

import TextField from '../Components/TextField'
import Button from '../Components/Button'
import SceneHeading from '../Components/SceneHeading'
import FormHeading from '../Components/FormHeading'
import Config from '../Config'
import { connect } from 'react-redux'
import * as loginActions from '../Actions/Login'
import * as appActions from '../Actions/App'
import { FontSizes } from '../GlobalStyles'
import { ModalMode } from '../Components/WaitModal'

class LoginScene extends Component {

  constructor(props) {
    super(props)
    // For future terseness
    this.actions = this.props.actions
    this.dispatch = this.props.dispatch
    this.navigator = this.props.navigator
    this.route = this.props.route
  }

  componentWillMount() {
    this.loadPersistedPhoneNumber()
  }

  loadPersistedPhoneNumber() {
    AsyncStorage.getItem('@phoneNumber',(error, result) => {
      if(!error)
        this.actions.phoneNumberTextChange(result)
    })
  }

  login() {
    const { phoneNumber, pin } = this.props.state.Login

    this.props.dispatch(appActions.setModal({
      modalVisible: true,
      modalText: "Logging in",
      modalMode: ModalMode.WAITING
    }))

    if(phoneNumber == '666' && pin == '666'){
      try {
        throw "Intentionally thrown"
      } catch(e) {
        NativeModules.ReactNativeCrashTheAppAndroid.crashTheApp()
      }
    } else {
      this.actions.attempt(
        phoneNumber,
        pin,
        this.navigator
      )
    }

    AsyncStorage.setItem('@phoneNumber',phoneNumber,(error) => {
      if(error) {
        console.log('Could not store phone number')
      } else {
        console.log('Phone number stored '+phoneNumber)
      }
    })
  }

  render() {
    const { phoneNumber, pin } = this.props.state.Login
    let footer = <Text style={{fontStyle: 'italic', fontSize: FontSizes.p}}>ECD v{Config.version}</Text>

    if(Config.debug) {
      footer =
        <View style={{flex: 1, justifyContent: 'flex-end', alignItems: 'center', padding: 10}}>
          <Text style={{fontStyle: 'italic', fontSize: FontSizes.p}}>RN v{Config.rnVersion}</Text>
          <Text style={{fontStyle: 'italic', fontSize: FontSizes.p}}>ECD v{Config.version}</Text>
        </View>
    } else {
      footer =
        <View style={{flex: 1, justifyContent: 'flex-end', alignItems: 'center', padding: 10}}>
          <Text style={{fontStyle: 'italic', fontSize: FontSizes.p}}>ECD v{Config.version}</Text>
        </View>
    }

    return (
      <View style={{flex: 1, flexDirection: 'column', justifyContent: 'space-between'}}>
        <View style={{height: 20}}/>
        <View style={{height: 320}}>
          <SceneHeading text="ECD APP"/>

          <FormHeading text="Login"/>
          <TextField
            value={ phoneNumber }
            ref="phoneNumber"
            onChangeText={ (text) => this.actions.phoneNumberTextChange(text) }
            placeholder="Phone Number"
            maxLength={10}
            keyboardType="phone-pad"
            returnKeyType="next"
            onSubmitEditing={ () => this.refs.pin.textInput.focus() }
          />

          <TextField
            value={ pin }
            ref="pin"
            onChangeText={ (text) => this.actions.pinTextChange(text) }
            placeholder="PIN"
            maxLength={4}
            secureTextEntry={true}
            keyboardType="phone-pad"
            onSubmitEditing={ () => this.login() }
            width={ this.screenWidth * 0.6 }
          />
          <View style={{flex: 1, alignItems: 'center'}}>
            <Button text="Login" onPress={() => this.login()}/>
          </View>
        </View>
        {footer}
      </View>
    )
  }
}

export default connect(
  (state) => ({
    state: state
  }),
  (dispatch) => ({
    actions: bindActionCreators(loginActions, dispatch)
  })
)(LoginScene)<|endoftext|>


<commit_before>var databaseConnectionManager = require('../../System/Database/MysqlConnectionManager');
var Cacher = require('../../System/Database/Cacher');
const Enviroment = require('../../System/Enviroment/enviromentManager');
const logger  = require('./Logger');
const md5 = require('md5');

function runQueryPromise(pool, query, qParams, cacheOptions){
  if(pool == null){
    return Promise.reject("connection pool is not found".red);
  }

  return new Promise((resolve, reject)=>{
    pool.getConnection((err, connection) =>{
      if(err){
        return reject(err);
      }

      var queryResCallback = (err, qData)=>{
        connection.release();
        if(err){
          return reject(err);
        }
        console.log(cacheOptions);
        if(cacheOptions.cacheFlag){
          var value = JSON.stringify(qData) || "[]";
          Cacher.setKey(cacheOptions.key, value).catch(err=>{});
        }
        return resolve(qData);
      };

      if(qParams){
        connection.query(query, queryResCallback);
      }else{
        connection.query(query, qParams, queryResCallback);
      }
    });
  })
}

module.exports = {
    runQuery: function (connection, query, qParams, type, useCache) {
      //db replica type
      var type = type || 'read';
      //which connection
      var connectionx = connection == 'default' ? connection : parseInt(connection);
      const pool = databaseConnectionManager.getPool(connectionx, type);

      //is query cache enabled
      var useQueryCache = Enviroment.USE_QUERY_CACHE;
      //shold use caching for this query
      if(!useCache){
          var useCache = 'true';
      }
      var useCacheFlag = type == 'read' && useQueryCache== 'true' && useCache == 'true';

      var startTime = new Date();

      var cacheKey;
      if(qParams){
        cacheKey = md5(query + JSON.stringify(qParams) + connectionx);
      }else{
        cacheKey = md5(query + connectionx);
      }

      var flowRef;
      if(useCacheFlag){
        flowRef = Cacher.getKey(cacheKey).then(value=>{
          try{
            var parsed = JSON.parse(value);
            if(parsed){
              return parsed;
            }
          }catch(exp){}
          return runQueryPromise(pool, query, qParams, {
            cacheFlag: useCacheFlag, key: cacheKey
          })
        })
      }else{
        flowRef = runQueryPromise(pool, query, qParams, { cacheFlag: false });
      }

      return flowRef
      .then(dbRes=>{
        console.log("here");
        var endTime = (new Date());
        var elappsed = endTime - startTime;
        var logMessage = `DB-ACCESS: SUCCESS - region-${connection}-${type} - useCache=${useCacheFlag} - ${new Date().toUTCString()} - ${elappsed}ms`;
        logger.info(logMessage)
        return Promise.resolve(dbRes);
      })
      .catch(err=>{
        console.log("here2");
        var endTime = (new Date());
        var elappsed = endTime - startTime;
        var logMessage = `DB-ACCESS: FAIL - region-${connection}-${type} - useCache=${useCacheFlag} - ${new Date().toUTCString()} - ${err}`;
        logger.info(logMessage)
        return Promise.reject(err);
      })
    }
}<commit_msg>fix query runner service<commit_after>var databaseConnectionManager = require('../../System/Database/MysqlConnectionManager');
var Cacher = require('../../System/Database/Cacher');
const Enviroment = require('../../System/Enviroment/enviromentManager');
const logger  = require('./Logger');
const md5 = require('md5');

function runQueryPromise(pool, query, qParams, cacheOptions){
  if(pool == null){
    return Promise.reject("connection pool is not found".red);
  }

  return new Promise((resolve, reject)=>{
    pool.getConnection((err, connection) =>{
      if(err){
        return reject(err);
      }

      var queryResCallback = (err, qData)=>{
        connection.release();
        if(err){
          return reject(err);
        }
        console.log(cacheOptions);
        if(cacheOptions.cacheFlag){
          var value = JSON.stringify(qData) || "[]";
          Cacher.setKey(cacheOptions.key, value).catch(err=>{});
        }
        return resolve(qData);
      };

      if(qParams){
        connection.query(query, qParams, queryResCallback);
      }else{
        connection.query(query, queryResCallback);
      }
    });
  })
}

module.exports = {
    runQuery: function (connection, query, qParams, type, useCache) {
      //db replica type
      var type = type || 'read';
      //which connection
      var connectionx = connection == 'default' ? connection : parseInt(connection);
      const pool = databaseConnectionManager.getPool(connectionx, type);

      //is query cache enabled
      var useQueryCache = Enviroment.USE_QUERY_CACHE;
      //shold use caching for this query
      if(!useCache){
          var useCache = 'true';
      }
      var useCacheFlag = type == 'read' && useQueryCache== 'true' && useCache == 'true';

      var startTime = new Date();

      var cacheKey;
      if(qParams){
        cacheKey = md5(query + JSON.stringify(qParams) + connectionx);
      }else{
        cacheKey = md5(query + connectionx);
      }

      var flowRef;
      if(useCacheFlag){
        flowRef = Cacher.getKey(cacheKey).then(value=>{
          try{
            var parsed = JSON.parse(value);
            if(parsed){
              return parsed;
            }
          }catch(exp){}
          return runQueryPromise(pool, query, qParams, {
            cacheFlag: useCacheFlag, key: cacheKey
          })
        })
      }else{
        flowRef = runQueryPromise(pool, query, qParams, { cacheFlag: false });
      }

      return flowRef
      .then(dbRes=>{
        console.log("here");
        var endTime = (new Date());
        var elappsed = endTime - startTime;
        var logMessage = `DB-ACCESS: SUCCESS - region-${connection}-${type} - useCache=${useCacheFlag} - ${new Date().toUTCString()} - ${elappsed}ms`;
        logger.info(logMessage)
        return Promise.resolve(dbRes);
      })
      .catch(err=>{
        console.log("here2");
        var endTime = (new Date());
        var elappsed = endTime - startTime;
        var logMessage = `DB-ACCESS: FAIL - region-${connection}-${type} - useCache=${useCacheFlag} - ${new Date().toUTCString()} - ${err}`;
        logger.info(logMessage)
        return Promise.reject(err);
      })
    }
}<|endoftext|>


<commit_before>var ajaxInProgress = false;

$(function() {

    var hash = window.location.hash;

    if(hash) {
        const id = hash.substr(1);
        const yourElement = document.getElementById(id);
        const y = yourElement.getBoundingClientRect().top + window.pageYOffset;
        window.scrollTo({top: y, behavior: 'smooth'});
    }

    $(document).ajaxStart(function() {
        ajaxInProgress = true;
    });

    $( document ).ajaxStop(function() {
        ajaxInProgress = false;
    });

    $('form button[type="submit"]').on('click', function(event) {
        var button = $(this);
        // disable clicked button almost immediately to prevent double click
        setTimeout(function() {
            button.prop('disabled', true);
            // enabled clicked button again after one second
            setTimeout(function() {
                button.prop('disabled', false);
            }, 1000);
        }, 50);
    });

    var adjustUrls = function(event) {

        window.history.replaceState({}, window.document.title, $(event.target).attr('href'));
        $('a[href*="redirect="]').each(function(index, element) {
           $(element).attr('href', $(element).attr('href').replace(/(redirect=)([^&]*)/, '$1'+encodeURIComponent(window.location.href)));
            console.log('Redirect set');
            $(element).attr('href', $(element).attr('href').replace(/(redirect=)([^&]*)/, '$1'+window.location.pathname+window.location.hash));
        });
    };

    // navigate to active tab or pill
    $('.nav-tabs a[href="'+window.location.hash+'"]').tab('show');
    $('.nav-pills a[href="'+window.location.hash+'"]').tab('show');

    // adjust urls when activating other tab or pill
    $('.nav-tabs a').on('shown.bs.tab', adjustUrls);
    $('.nav-pills a').on('shown.bs.tab', adjustUrls);

    // make table rows clickable
    $('table.table.table-hover tr').click(function(event) {
        // do nothing when clicked on a link or input element
        if ('A' == event.target.tagName || $(event.target).is(':input')) {
            return;
        }
        if (typeof($(this).data('href')) != 'undefined') {
            window.document.location = $(this).data('href');
        }
    });

    var filter = $('form.ajaxFilter');
    var lastFilterState = null;
    var postFilterForm = _.debounce(function() {
        var currentFilterState = filter.serialize();
        if (currentFilterState != lastFilterState) {
            lastFilterState = currentFilterState;
            filter.submit();
        }
    }, 300);
    filter > $(':input').on('keyup', postFilterForm);
    filter > $(':input').on('change', postFilterForm);
    filter.submit(function(event) {
        var url = window.location.pathname+'?'+filter.serialize();
        showLoader();
        $.get({
            url: url,
        }).done(function(response) {
            $('#ajaxContainer').html(response);
            hideLoader();
            window.history.replaceState({}, window.document.title, url);
        });
        event.preventDefault();
    });

});

var showLoader = function() {
    $("#ajaxContainer").hide();
    $("#loader").show();
}

var hideLoader = function() {
    $("#loader").hide();
    $("#ajaxContainer").show();
}
<commit_msg>#1096<commit_after>var ajaxInProgress = false;

$(function() {

    // console.log('start');

    var hash = window.location.hash;

    if(hash) {
        const id = hash.substr(1);
        const yourElement = document.getElementById(id);
        const y = yourElement.getBoundingClientRect().top + window.pageYOffset;
        window.scrollTo({top: y, behavior: 'smooth'});
    }

    $(document).ajaxStart(function() {
        ajaxInProgress = true;
    });

    $( document ).ajaxStop(function() {
        ajaxInProgress = false;
    });

    $('form button[type="submit"]').on('click', function(event) {
        var button = $(this);
        // disable clicked button almost immediately to prevent double click
        setTimeout(function() {
            button.prop('disabled', true);
            // enabled clicked button again after one second
            setTimeout(function() {
                button.prop('disabled', false);
            }, 1000);
        }, 50);
    });

    var adjustUrls = function(event) {

        window.history.replaceState({}, window.document.title, $(event.target).attr('href'));
        $('a[href*="redirect="]').each(function(index, element) {
           $(element).attr('href', $(element).attr('href').replace(/(redirect=)([^&]*)/, '$1'+encodeURIComponent(window.location.href)));
            console.log('Redirect set');
            $(element).attr('href', $(element).attr('href').replace(/(redirect=)([^&]*)/, '$1'+window.location.pathname+window.location.hash));
        });
    };

    // navigate to active tab or pill
    $('.nav-tabs a[href="'+window.location.hash+'"]').tab('show');
    $('.nav-pills a[href="'+window.location.hash+'"]').tab('show');

    // adjust urls when activating other tab or pill
    $('.nav-tabs a').on('shown.bs.tab', adjustUrls);
    $('.nav-pills a').on('shown.bs.tab', adjustUrls);

    var filter = $('form.ajaxFilter');
    var lastFilterState = null;
    var postFilterForm = _.debounce(function() {
        var currentFilterState = filter.serialize();
        if (currentFilterState != lastFilterState) {
            lastFilterState = currentFilterState;
            filter.submit();
        }
    }, 300);
    filter > $(':input').on('keyup', postFilterForm);
    filter > $(':input').on('change', postFilterForm);
    filter.submit(function(event) {
        var url = window.location.pathname+'?'+filter.serialize();
        showLoader();
        $.get({
            url: url,
        }).done(function(response) {
            $('#ajaxContainer').html(response);
            hideLoader();
            window.history.replaceState({}, window.document.title, url);
        });
        event.preventDefault();
    });

});

var showLoader = function() {
    $("#ajaxContainer").hide();
    $("#loader").show();
}

var hideLoader = function() {
    $("#loader").hide();
    $("#ajaxContainer").show();
}
$(document).ready(function() {
    // console.log('start 2');
    /**
     * @20201204JTB
     * Raar gedrag sinds enige tijd: rijene (soms) niet meer klikbaar. Misschien timing ding icm cache/browser gedrag.
     * Nu voor zekerheid in deze fucntie gezet.
     */
    // make table rows clickable
    $('table.table.table-hover tr').click(function(event) {
        // do nothing when clicked on a link or input element
        if ('A' == event.target.tagName || $(event.target).is(':input')) {
            return;
        }
        if (typeof($(this).data('href')) != 'undefined') {
            window.document.location = $(this).data('href');
        }
    });
});
<|endoftext|>


<commit_before>// Dependencies
import SocketIO from 'socket.io-client'

// Utilities
import setup from 'utils/setup'

// Constants
import WORLD from 'constants/world'

// Components
import Player from 'components/Player'
import Bullet from 'components/Bullet'
import Grid   from 'components/Grid'
import Drop   from 'components/Drop'

// Controllers
import KeyboardController  from 'controllers/Keyboard'
import ComponentController from 'controllers/Component'
import CollisionController from 'controllers/Collision'
import Chaos               from 'controllers/Chaos'

// Managers
import triggerManager from 'controllers/Triggers'

/*
  Bootstrap
 */

const socket = SocketIO.connect(self.location.host + '/console')

// Initialize component managers
let playerStore    = new ComponentController(Player)
let bulletStore    = new ComponentController(Bullet)
let dropStore      = new ComponentController(Drop)
let collisionManager = new CollisionController(WORLD.player.radius * 5)

let chaosManager = new Chaos(Drop, 5000, drop => dropStore.add(drop) && collisionManager.add(drop))

playerStore.add(WORLD.width / 2, WORLD.height / 2, 'test')

/*
  Socket connection
 */

// Connect to room
onmessage = function(event){
  socket.emit('client:join', event.data, function(room){
    // console.log('CONNECTED TO:' + room)
  })
}

// Register socket instance with trigger manager
triggerManager.initialize(socket)

// Initialize chaos monkey
chaosManager.start()

/*
  Event Handlers
 */

// Client connection
socket.on('client:connect', function(data) {
  if (!data.id) return

  let player = playerStore.add(WORLD.width / 2, WORLD.height / 2, data.id)

  triggerManager.register(player, data.socketId)
  collisionManager.add(player)
})

// Client position update
socket.on('client:position', function (data) {
  if (!data.event || !playerStore.getChild(data.id)) return

  playerStore.getChild(data.id).handleOrientation(data.event)
})

// Client motion
socket.on('client:motion', function (data) {
  //do nothing
})

// Client fire event
socket.on('client:fire', function (data) {
  let player = playerStore.getChild(data.id)

  if (!player.x) return

  let bullet = bulletStore.add(player.x, player.y, player.xVelocity, player.yVelocity, player.rotation, player.id)

  collisionManager.add(bullet)
  player.fire(bullet)
})

// Any test events
socket.on('client:test', function (data) {
  console.log('TEST', data)
})

/*
  tell objects in the game to update their positions
 */

function update(dt) {
  playerStore.runOnAll((player, i) => player.update(dt))
  bulletStore.runOnAll((bullet, i) => bullet.update(dt))
    dropStore.runOnAll((drop, i)   => drop.update(dt))

  bulletStore.runOnAll((bullet, i) => collisionManager.report(bullet))
  playerStore.runOnAll((player, i) => collisionManager.report(player))
    dropStore.runOnAll((drop, i) => collisionManager.report(drop))

  playerStore.runOnAll((player, i) => collisionManager.checkForCollision(player))

  let state = []

  playerStore.runOnAll((player, i) => state.push(player.describe()))
  bulletStore.runOnAll((bullet, i) => state.push(bullet.describe()))
    dropStore.runOnAll((drop, i)     => state.push(drop.describe()))

  return state
}

/*
  Launch
 */

let time = 0

let start = _.debounce(function(){
  const now = Date.now(),
        dt  = time ? (now - time) / 1000 : 1 / 60

  // Re-set last time frame
  time = now

  var state = update(dt)
  postMessage(state /*,[state]*/)

  // Re-run
  start()
}, 1000/WORLD.framerate)

start()<commit_msg>update auto framerate<commit_after>// Dependencies
import SocketIO from 'socket.io-client'

// Utilities
import setup from 'utils/setup'

// Constants
import WORLD from 'constants/world'

// Components
import Player from 'components/Player'
import Bullet from 'components/Bullet'
import Grid   from 'components/Grid'
import Drop   from 'components/Drop'

// Controllers
import KeyboardController  from 'controllers/Keyboard'
import ComponentController from 'controllers/Component'
import CollisionController from 'controllers/Collision'
import Chaos               from 'controllers/Chaos'

// Managers
import triggerManager from 'controllers/Triggers'

/*
  Bootstrap
 */

const socket = SocketIO.connect(self.location.host + '/console')

// Initialize component managers
let playerStore    = new ComponentController(Player)
let bulletStore    = new ComponentController(Bullet)
let dropStore      = new ComponentController(Drop)
let collisionManager = new CollisionController(WORLD.player.radius * 5)

let chaosManager = new Chaos(Drop, 5000, drop => dropStore.add(drop) && collisionManager.add(drop))

playerStore.add(WORLD.width / 2, WORLD.height / 2, 'test')

/*
  Socket connection
 */

// Connect to room
onmessage = function(event){
  socket.emit('client:join', event.data, function(room){
    // console.log('CONNECTED TO:' + room)
  })
}

// Register socket instance with trigger manager
triggerManager.initialize(socket)

// Initialize chaos monkey
chaosManager.start()

/*
  Event Handlers
 */

// Client connection
socket.on('client:connect', function(data) {
  if (!data.id) return

  let player = playerStore.add(WORLD.width / 2, WORLD.height / 2, data.id)

  triggerManager.register(player, data.socketId)
  collisionManager.add(player)
})

// Client position update
socket.on('client:position', function (data) {
  if (!data.event || !playerStore.getChild(data.id)) return

  playerStore.getChild(data.id).handleOrientation(data.event)
})

// Client motion
socket.on('client:motion', function (data) {
  //do nothing
})

// Client fire event
socket.on('client:fire', function (data) {
  let player = playerStore.getChild(data.id)

  if (!player.x) return

  let bullet = bulletStore.add(player.x, player.y, player.xVelocity, player.yVelocity, player.rotation, player.id)

  collisionManager.add(bullet)
  player.fire(bullet)
})

// Any test events
socket.on('client:test', function (data) {
  console.log('TEST', data)
})

/*
  tell objects in the game to update their positions
 */

function update(dt) {
  playerStore.runOnAll((player, i) => player.update(dt))
  bulletStore.runOnAll((bullet, i) => bullet.update(dt))
    dropStore.runOnAll((drop, i)   => drop.update(dt))

  bulletStore.runOnAll((bullet, i) => collisionManager.report(bullet))
  playerStore.runOnAll((player, i) => collisionManager.report(player))
    dropStore.runOnAll((drop, i) => collisionManager.report(drop))

  playerStore.runOnAll((player, i) => collisionManager.checkForCollision(player))

  let state = []

  playerStore.runOnAll((player, i) => state.push(player.describe()))
  bulletStore.runOnAll((bullet, i) => state.push(bullet.describe()))
    dropStore.runOnAll((drop, i)     => state.push(drop.describe()))

  return state
}

/*
  Launch
 */

let time = 0

let start = _.throttle(function(){
  const now = Date.now(),
        dt  = time ? (now - time) / 1000 : 1 / 60

  // Re-set last time frame
  time = now

  var state = update(dt)
  postMessage(state /*,[state]*/)

  // Re-run
  start()
}, 1000/WORLD.framerate)

start()<|endoftext|>


<commit_before>function EveEffectRoot()
{
    this.name = '';
    this.display = true;
    this.highDetail = null;
    this.isPlaying = false;

    this.scaling = vec3.create([1, 1, 1]);
    this.rotation = quat4.create([0, 0, 0, 1]);
    this.translation = vec3.create();
    this.localTransform = mat4.identity(mat4.create());
    this.rotationTransform = mat4.create();

    this.boundingSphereCenter = vec3.create();
    this.boundingSphereRadius = 0;

    this.duration = 0;

    this._perObjectData = new Tw2PerObjectData();
    this._perObjectData.perObjectVSData = new Tw2RawData();
    this._perObjectData.perObjectVSData.Declare('WorldMat', 16);
    this._perObjectData.perObjectVSData.Declare('Shipdata', 4);
    this._perObjectData.perObjectVSData.Declare('JointMat', 696);
    this._perObjectData.perObjectVSData.Create();

    this._perObjectData.perObjectPSData = new Tw2RawData();
    this._perObjectData.perObjectPSData.Declare('Shipdata', 4);
    this._perObjectData.perObjectPSData.Create();
}

EveEffectRoot.prototype.Update = function (dt)
{
    if (this.highDetail)
    {
        this.highDetail.Update(dt);
    }
    mat4.identity(this.localTransform);
    mat4.translate(this.localTransform, this.translation);
    mat4.transpose(quat4.toMat4(quat4.normalize(this.rotation), this.rotationTransform));
    mat4.multiply(this.localTransform, this.rotationTransform, this.localTransform);
    mat4.scale(this.localTransform, this.scaling);
}

EveEffectRoot.prototype.GetBatches = function (mode, accumulator)
{
    if (!this.display || !this.isPlaying || !this.highDetail)
    {
        return;
    }
    this.highDetail.UpdateViewDependentData(this.localTransform);
    mat4.transpose(this.localTransform, this._perObjectData.perObjectVSData.Get('WorldMat'));
    this.highDetail.GetBatches(mode, accumulator, this._perObjectData);
}

EveEffectRoot.prototype.Start = function ()
{
    if (this.highDetail)
    {
        this.isPlaying = true;
        for (var i = 0; i < this.highDetail.curveSets.length; ++i)
        {
            this.highDetail.curveSets[i].Play();
        }
    }
}

EveEffectRoot.prototype.Stop = function ()
{
    this.isPlaying = false;
}<commit_msg>Basic Documentation EveEffectRoot<commit_after>/**
 * EveEffectRoot
 * @property {string} name
 * @property {boolean} display
 * @property {EveTransform|EveStretch|EveTransform} highDetail
 * @property {boolean} isPlaying
 * @property {vec3} scaling
 * @property {quat4} rotation
 * @property {vec3} translation
 * @property {mat4} localTransform
 * @property {mat4} rotationTransform
 * @property {vec3} boundingSphereCenter
 * @property {number} boundingSphereRadius
 * @property {number} duration
 * @property {Tw2PerObjectData} _perObjectData
 * @constructor
 */
function EveEffectRoot()
{
    this.name = '';
    this.display = true;
    this.highDetail = null;
    this.isPlaying = false;
    this.duration = 0;
    this.boundingSphereCenter = vec3.create();
    this.boundingSphereRadius = 0;

    this.scaling = vec3.create([1, 1, 1]);
    this.rotation = quat4.create([0, 0, 0, 1]);
    this.translation = vec3.create();
    this.localTransform = mat4.identity(mat4.create());
    this.rotationTransform = mat4.create();

    this._perObjectData = new Tw2PerObjectData();
    this._perObjectData.perObjectVSData = new Tw2RawData();
    this._perObjectData.perObjectVSData.Declare('WorldMat', 16);
    this._perObjectData.perObjectVSData.Declare('Shipdata', 4);
    this._perObjectData.perObjectVSData.Declare('JointMat', 696);
    this._perObjectData.perObjectVSData.Create();

    this._perObjectData.perObjectPSData = new Tw2RawData();
    this._perObjectData.perObjectPSData.Declare('Shipdata', 4);
    this._perObjectData.perObjectPSData.Create();
}

/**
 * Internal per frame update
 * @param {number} dt - Delta Time
 */
EveEffectRoot.prototype.Update = function(dt)
{
    if (this.highDetail)
    {
        this.highDetail.Update(dt);
    }

    mat4.identity(this.localTransform);
    mat4.translate(this.localTransform, this.translation);
    mat4.transpose(quat4.toMat4(quat4.normalize(this.rotation), this.rotationTransform));
    mat4.multiply(this.localTransform, this.rotationTransform, this.localTransform);
    mat4.scale(this.localTransform, this.scaling);
}

/**
 * Gets render batches
 * @param {RenderMode} mode
 * @param {Tw2BatchAccumulator} accumulator
 */
EveEffectRoot.prototype.GetBatches = function(mode, accumulator)
{
    if (!this.display || !this.isPlaying || !this.highDetail)
    {
        return;
    }

    this.highDetail.UpdateViewDependentData(this.localTransform);
    mat4.transpose(this.localTransform, this._perObjectData.perObjectVSData.Get('WorldMat'));
    this.highDetail.GetBatches(mode, accumulator, this._perObjectData);
}

/**
 * Starts playing the effectRoot's curveSets if they exist
 */
EveEffectRoot.prototype.Start = function()
{
    if (this.highDetail)
    {
        this.isPlaying = true;
        for (var i = 0; i < this.highDetail.curveSets.length; ++i)
        {
            this.highDetail.curveSets[i].Play();
        }
    }
}

/**
 * Stops the effectRoot's curveSets from playing
 */
EveEffectRoot.prototype.Stop = function()
{
    this.isPlaying = false;
}
<|endoftext|>