<commit_before>/**
 * @license
 * Copyright The Closure Library Authors.
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview goog.dom.animationFrame permits work to be done in-sync with
 * the render refresh rate of the browser and to divide work up globally based
 * on whether the intent is to measure or to mutate the DOM. The latter avoids
 * repeated style recalculation which can be really slow.
 *
 * Goals of the API:
 *

 *
Make it easy to schedule work for the next animation frame.
 *
Make it easy to only do work once per animation frame, even if two
 *       events fire that trigger the same work.
 *
Make it easy to do all work in two phases to avoid repeated style
 *       recalculation caused by interleaved reads and writes.
 *
Avoid creating closures per schedule operation.
 *

 *
 *
 * Programmatic:
 *

 * let animationTask = goog.dom.animationFrame.createTask(
 *     {
 *       measure: function(state) {
 *         state.width = goog.style.getSize(elem).width;
 *         this.animationTask();
 *       },
 *       mutate: function(state) {
 *         goog.style.setWidth(elem, Math.floor(state.width / 2));
 *       },
 *     },
 *     this);
 *

 *
 * See also
 * https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame
 */

goog.provide('goog.dom.animationFrame');
goog.provide('goog.dom.animationFrame.Spec');
goog.provide('goog.dom.animationFrame.State');

goog.require('goog.dom.animationFrame.polyfill');

// Install the polyfill.
goog.dom.animationFrame.polyfill.install();

/**
 * @typedef {{
 *   id: number,
 *   fn: !Function,
 *   context: (!Object|undefined)
 * }}
 * @private
 */
goog.dom.animationFrame.Task_;

/**
 * @typedef {{
 *   measureTask: goog.dom.animationFrame.Task_,
 *   mutateTask: goog.dom.animationFrame.Task_,
 *   state: (!Object|undefined),
 *   args: (!Array|undefined),
 *   isScheduled: boolean
 * }}
 * @private
 */
goog.dom.animationFrame.TaskSet_;

/**
 * @typedef {{
 *   measure: (!Function|undefined),
 *   mutate: (!Function|undefined)
 * }}
 */
goog.dom.animationFrame.Spec;

/**
 * A type to represent state. Users may add properties as desired.
 * @constructor
 * @final
 */
goog.dom.animationFrame.State = function() {};

/**
 * Saves a set of tasks to be executed in the next requestAnimationFrame phase.
 * This list is initialized once before any event firing occurs. It is not
 * affected by the fired events or the requestAnimationFrame processing (unless
 * a new event is created during the processing).
 * @private {!Array<!Array<goog.dom.animationFrame.TaskSet_>>}
 */
goog.dom.animationFrame.tasks_ = [[], []];

/**
 * Values are 0 or 1, for whether the first or second array should be used to
 * lookup or add tasks.
 * @private {number}
 */
goog.dom.animationFrame.doubleBufferIndex_ = 0;

/**
 * Whether we have already requested an animation frame that hasn't happened
 * yet.
 * @private {boolean}
 */
goog.dom.animationFrame.requestedFrame_ = false;

/**
 * Counter to generate IDs for tasks.
 * @private {number}
 */
goog.dom.animationFrame.taskId_ = 0;

/**
 * Whether the animationframe runTasks_ loop is currently running.
 * @private {boolean}
 */
goog.dom.animationFrame.running_ = false;

/**
 * Returns a function that schedules the two passed-in functions to be run upon
 * the next animation frame. Calling the function again during the same
 * animation frame does nothing.
 *
 * The function under the "measure" key will run first and together with all
 * other functions scheduled under this key and the function under "mutate" will
 * run after that.
 *
 * @param {{
 *   measure: (function(this:THIS, !goog.dom.animationFrame.State)|undefined),
 *   mutate: (function(this:THIS, !goog.dom.animationFrame.State)|undefined)
 * }} spec
 * @param {THIS=} opt_context Context in which to run the function.
 * @return {function(...?)}
 * @template THIS
 */
goog.dom.animationFrame.createTask = function(spec, opt_context) {
  'use strict';
  var id = goog.dom.animationFrame.taskId_++;
  var measureTask = {id: id, fn: spec.measure, context: opt_context};
  var mutateTask = {id: id, fn: spec.mutate, context: opt_context};

  var taskSet = {
    measureTask: measureTask,
    mutateTask: mutateTask,
    state: {},
    args: undefined,
    isScheduled: false
  };

  return function() {
    'use strict';
    // Save args and state.
    if (arguments.length > 0) {
      // The state argument goes last. That is kinda horrible but compatible
      // with {@see wiz.async.method}.
      if (!taskSet.args) {
        taskSet.args = [];
      }
      taskSet.args.length = 0;
      taskSet.args.push.apply(taskSet.args, arguments);
      taskSet.args.push(taskSet.state);
    } else {
      if (!taskSet.args || taskSet.args.length == 0) {
        taskSet.args = [taskSet.state];
      } else {
        taskSet.args[0] = taskSet.state;
        taskSet.args.length = 1;
      }
    }
    if (!taskSet.isScheduled) {
      taskSet.isScheduled = true;
      var tasksArray = goog.dom.animationFrame
                           .tasks_[goog.dom.animationFrame.doubleBufferIndex_];
      tasksArray.push(
          /** @type {goog.dom.animationFrame.TaskSet_} */ (taskSet));
    }
    goog.dom.animationFrame.requestAnimationFrame_();
  };
};

/**
 * Run scheduled tasks.
 * @private
 */
goog.dom.animationFrame.runTasks_ = function() {
  'use strict';
  goog.dom.animationFrame.running_ = true;
  goog.dom.animationFrame.requestedFrame_ = false;
  var tasksArray = goog.dom.animationFrame
                       .tasks_[goog.dom.animationFrame.doubleBufferIndex_];
  var taskLength = tasksArray.length;

  // During the runTasks_, if there is a recursive call to queue up more
  // task(s) for the next frame, we use double-buffering for that.
  goog.dom.animationFrame.doubleBufferIndex_ =
      (goog.dom.animationFrame.doubleBufferIndex_ + 1) % 2;

  var task;

  // Run all the measure tasks first.
  for (var i = 0; i < taskLength; ++i) {
    task = tasksArray[i];
    var measureTask = task.measureTask;
    task.isScheduled = false;
    if (measureTask.fn) {
      // TODO (perumaal): Handle any exceptions thrown by the lambda.
      measureTask.fn.apply(measureTask.context, task.args);
    }
  }

  // Run the mutate tasks next.
  for (var i = 0; i < taskLength; ++i) {
    task = tasksArray[i];
    var mutateTask = task.mutateTask;
    task.isScheduled = false;
    if (mutateTask.fn) {
      // TODO (perumaal): Handle any exceptions thrown by the lambda.
      mutateTask.fn.apply(mutateTask.context, task.args);
    }

    // Clear state for next vsync.
    task.state = {};
  }

  // Clear the tasks array as we have finished processing all the tasks.
  tasksArray.length = 0;
  goog.dom.animationFrame.running_ = false;
};

/**
 * @return {boolean} Whether the animationframe is currently running. For use
 *     by callers who need not to delay tasks scheduled during runTasks_ for an
 *     additional frame.
 */
goog.dom.animationFrame.isRunning = function() {
  'use strict';
  return goog.dom.animationFrame.running_;
};

/**
 * Request {@see goog.dom.animationFrame.runTasks_} to be called upon the
 * next animation frame if we haven't done so already.
 * @private
 */
goog.dom.animationFrame.requestAnimationFrame_ = function() {
  'use strict';
  if (goog.dom.animationFrame.requestedFrame_) {
    return;
  }
  goog.dom.animationFrame.requestedFrame_ = true;
  window.requestAnimationFrame(goog.dom.animationFrame.runTasks_);
};
<commit_msg>Use ES6 const/let more throughout Closure Library. RELNOTES: n/a<commit_after>/**
 * @license
 * Copyright The Closure Library Authors.
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview goog.dom.animationFrame permits work to be done in-sync with
 * the render refresh rate of the browser and to divide work up globally based
 * on whether the intent is to measure or to mutate the DOM. The latter avoids
 * repeated style recalculation which can be really slow.
 *
 * Goals of the API:
 *

 *
Make it easy to schedule work for the next animation frame.
 *
Make it easy to only do work once per animation frame, even if two
 *       events fire that trigger the same work.
 *
Make it easy to do all work in two phases to avoid repeated style
 *       recalculation caused by interleaved reads and writes.
 *
Avoid creating closures per schedule operation.
 *

 *
 *
 * Programmatic:
 *

 * let animationTask = goog.dom.animationFrame.createTask(
 *     {
 *       measure: function(state) {
 *         state.width = goog.style.getSize(elem).width;
 *         this.animationTask();
 *       },
 *       mutate: function(state) {
 *         goog.style.setWidth(elem, Math.floor(state.width / 2));
 *       },
 *     },
 *     this);
 *

 *
 * See also
 * https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame
 */

goog.provide('goog.dom.animationFrame');
goog.provide('goog.dom.animationFrame.Spec');
goog.provide('goog.dom.animationFrame.State');

goog.require('goog.dom.animationFrame.polyfill');

// Install the polyfill.
goog.dom.animationFrame.polyfill.install();

/**
 * @typedef {{
 *   id: number,
 *   fn: !Function,
 *   context: (!Object|undefined)
 * }}
 * @private
 */
goog.dom.animationFrame.Task_;

/**
 * @typedef {{
 *   measureTask: goog.dom.animationFrame.Task_,
 *   mutateTask: goog.dom.animationFrame.Task_,
 *   state: (!Object|undefined),
 *   args: (!Array|undefined),
 *   isScheduled: boolean
 * }}
 * @private
 */
goog.dom.animationFrame.TaskSet_;

/**
 * @typedef {{
 *   measure: (!Function|undefined),
 *   mutate: (!Function|undefined)
 * }}
 */
goog.dom.animationFrame.Spec;

/**
 * A type to represent state. Users may add properties as desired.
 * @constructor
 * @final
 */
goog.dom.animationFrame.State = function() {};

/**
 * Saves a set of tasks to be executed in the next requestAnimationFrame phase.
 * This list is initialized once before any event firing occurs. It is not
 * affected by the fired events or the requestAnimationFrame processing (unless
 * a new event is created during the processing).
 * @private {!Array<!Array<goog.dom.animationFrame.TaskSet_>>}
 */
goog.dom.animationFrame.tasks_ = [[], []];

/**
 * Values are 0 or 1, for whether the first or second array should be used to
 * lookup or add tasks.
 * @private {number}
 */
goog.dom.animationFrame.doubleBufferIndex_ = 0;

/**
 * Whether we have already requested an animation frame that hasn't happened
 * yet.
 * @private {boolean}
 */
goog.dom.animationFrame.requestedFrame_ = false;

/**
 * Counter to generate IDs for tasks.
 * @private {number}
 */
goog.dom.animationFrame.taskId_ = 0;

/**
 * Whether the animationframe runTasks_ loop is currently running.
 * @private {boolean}
 */
goog.dom.animationFrame.running_ = false;

/**
 * Returns a function that schedules the two passed-in functions to be run upon
 * the next animation frame. Calling the function again during the same
 * animation frame does nothing.
 *
 * The function under the "measure" key will run first and together with all
 * other functions scheduled under this key and the function under "mutate" will
 * run after that.
 *
 * @param {{
 *   measure: (function(this:THIS, !goog.dom.animationFrame.State)|undefined),
 *   mutate: (function(this:THIS, !goog.dom.animationFrame.State)|undefined)
 * }} spec
 * @param {THIS=} opt_context Context in which to run the function.
 * @return {function(...?)}
 * @template THIS
 */
goog.dom.animationFrame.createTask = function(spec, opt_context) {
  'use strict';
  const id = goog.dom.animationFrame.taskId_++;
  const measureTask = {id: id, fn: spec.measure, context: opt_context};
  const mutateTask = {id: id, fn: spec.mutate, context: opt_context};

  const taskSet = {
    measureTask: measureTask,
    mutateTask: mutateTask,
    state: {},
    args: undefined,
    isScheduled: false
  };

  return function() {
    'use strict';
    // Save args and state.
    if (arguments.length > 0) {
      // The state argument goes last. That is kinda horrible but compatible
      // with {@see wiz.async.method}.
      if (!taskSet.args) {
        taskSet.args = [];
      }
      taskSet.args.length = 0;
      taskSet.args.push.apply(taskSet.args, arguments);
      taskSet.args.push(taskSet.state);
    } else {
      if (!taskSet.args || taskSet.args.length == 0) {
        taskSet.args = [taskSet.state];
      } else {
        taskSet.args[0] = taskSet.state;
        taskSet.args.length = 1;
      }
    }
    if (!taskSet.isScheduled) {
      taskSet.isScheduled = true;
      const tasksArray =
          goog.dom.animationFrame
              .tasks_[goog.dom.animationFrame.doubleBufferIndex_];
      tasksArray.push(
          /** @type {goog.dom.animationFrame.TaskSet_} */ (taskSet));
    }
    goog.dom.animationFrame.requestAnimationFrame_();
  };
};

/**
 * Run scheduled tasks.
 * @private
 */
goog.dom.animationFrame.runTasks_ = function() {
  'use strict';
  goog.dom.animationFrame.running_ = true;
  goog.dom.animationFrame.requestedFrame_ = false;
  const tasksArray = goog.dom.animationFrame
                         .tasks_[goog.dom.animationFrame.doubleBufferIndex_];
  const taskLength = tasksArray.length;

  // During the runTasks_, if there is a recursive call to queue up more
  // task(s) for the next frame, we use double-buffering for that.
  goog.dom.animationFrame.doubleBufferIndex_ =
      (goog.dom.animationFrame.doubleBufferIndex_ + 1) % 2;

  let task;

  // Run all the measure tasks first.
  for (let i = 0; i < taskLength; ++i) {
    task = tasksArray[i];
    const measureTask = task.measureTask;
    task.isScheduled = false;
    if (measureTask.fn) {
      // TODO (perumaal): Handle any exceptions thrown by the lambda.
      measureTask.fn.apply(measureTask.context, task.args);
    }
  }

  // Run the mutate tasks next.
  for (let i = 0; i < taskLength; ++i) {
    task = tasksArray[i];
    const mutateTask = task.mutateTask;
    task.isScheduled = false;
    if (mutateTask.fn) {
      // TODO (perumaal): Handle any exceptions thrown by the lambda.
      mutateTask.fn.apply(mutateTask.context, task.args);
    }

    // Clear state for next vsync.
    task.state = {};
  }

  // Clear the tasks array as we have finished processing all the tasks.
  tasksArray.length = 0;
  goog.dom.animationFrame.running_ = false;
};

/**
 * @return {boolean} Whether the animationframe is currently running. For use
 *     by callers who need not to delay tasks scheduled during runTasks_ for an
 *     additional frame.
 */
goog.dom.animationFrame.isRunning = function() {
  'use strict';
  return goog.dom.animationFrame.running_;
};

/**
 * Request {@see goog.dom.animationFrame.runTasks_} to be called upon the
 * next animation frame if we haven't done so already.
 * @private
 */
goog.dom.animationFrame.requestAnimationFrame_ = function() {
  'use strict';
  if (goog.dom.animationFrame.requestedFrame_) {
    return;
  }
  goog.dom.animationFrame.requestedFrame_ = true;
  window.requestAnimationFrame(goog.dom.animationFrame.runTasks_);
};
<|endoftext|>


<commit_before>
function initPageView(elementId, nodeId){
	var interfacesPanel;
	var ipInterfaceGrid;
	var physicalInterfaceGrid;
	var searchIpGrid;

	ipInterfaceGrid = new OpenNMS.ux.IPInterfaceGrid({
		id:'nodeInterfaceGrid',
		title:'IP Interfaces',
		viewConfig:{
			autoFill: true,
			forceFit: true,
			scrollOffset: 5,
			getRowClass : function(record, rowIndex, p, store) {
				return getIpStatusColor(record.data.isDown, record.data.isManaged);
			}
		},
		nodeId: nodeId,
		height:495
	});

	physicalInterfaceGrid = new OpenNMS.ux.SNMPInterfaceGrid({
		id:'nodePhysicalInterfaceGrid',
		title:'Physical Interfaces',
		viewConfig:{
			autoFill: true,
	  		forceFit: true,
	  		scrollOffset:5,
  		 	getRowClass : function(record, rowIndex, p, store){
	            return getSnmpStatusColor(record.data.ifAdminStatus, record.data.ifOperStatus);
            }
		},
		nodeId: nodeId,
		height:495
	});

	searchIpGrid = new OpenNMS.ux.SearchFilterGrid({
		id:'ipSearchGrid',
		title:'IP Interfaces',
		grid:ipInterfaceGrid

	});

	searchPhysicalIntergaceGrid = new OpenNMS.ux.SearchFilterGrid({
		id:'physicalSearchGrid',
		title:'Physical Interfaces',
		grid:physicalInterfaceGrid
	});

	interfacesPanel = new Ext.TabPanel({
		renderTo:elementId,
		activeTab:0,
		width:'auto',
		autoHeight:true,
		minHeight:400,
		bodyBorder:false,
		deferredRender: !Ext.isIE,
		border:false,
		items:[
			searchIpGrid,
			searchPhysicalIntergaceGrid
		]
	});

	function getIpStatusColor(isDown, isManaged) {
		var bgStyle = 'grid-status-blue';
		if (isManaged) {
			bgStyle = 'grid-status-green';
			if (isDown == 'true') {
				bgStyle = 'grid-status-red';
			}
		}

		return String.format('x-grid3-row {0}', bgStyle);
	}

	function getSnmpStatusColor(ifAdminStatus, ifOperStatus){
		var bgStyle;
		if(ifAdminStatus != 1){
			bgStyle = 'grid-status-blue';
		}else if(ifAdminStatus == 1 && ifOperStatus == 1){
			bgStyle = 'grid-status-green';
		}else if(ifAdminStatus == 1 && ifOperStatus != 1){
			bgStyle = 'grid-status-red';
		}

		return String.format('x-grid3-row {0}', bgStyle);
	};

};<commit_msg>check for various ismanaged flags<commit_after>
function initPageView(elementId, nodeId){
	var interfacesPanel;
	var ipInterfaceGrid;
	var physicalInterfaceGrid;
	var searchIpGrid;

	ipInterfaceGrid = new OpenNMS.ux.IPInterfaceGrid({
		id:'nodeInterfaceGrid',
		title:'IP Interfaces',
		viewConfig:{
			autoFill: true,
			forceFit: true,
			scrollOffset: 5,
			getRowClass : function(record, rowIndex, p, store) {
				return getIpStatusColor(record.data.isDown, record.data.isManaged);
			}
		},
		nodeId: nodeId,
		height:495
	});

	physicalInterfaceGrid = new OpenNMS.ux.SNMPInterfaceGrid({
		id:'nodePhysicalInterfaceGrid',
		title:'Physical Interfaces',
		viewConfig:{
			autoFill: true,
	  		forceFit: true,
	  		scrollOffset:5,
  		 	getRowClass : function(record, rowIndex, p, store){
	            return getSnmpStatusColor(record.data.ifAdminStatus, record.data.ifOperStatus);
            }
		},
		nodeId: nodeId,
		height:495
	});

	searchIpGrid = new OpenNMS.ux.SearchFilterGrid({
		id:'ipSearchGrid',
		title:'IP Interfaces',
		grid:ipInterfaceGrid

	});

	searchPhysicalIntergaceGrid = new OpenNMS.ux.SearchFilterGrid({
		id:'physicalSearchGrid',
		title:'Physical Interfaces',
		grid:physicalInterfaceGrid
	});

	interfacesPanel = new Ext.TabPanel({
		renderTo:elementId,
		activeTab:0,
		width:'auto',
		autoHeight:true,
		minHeight:400,
		bodyBorder:false,
		deferredRender: !Ext.isIE,
		border:false,
		items:[
			searchIpGrid,
			searchPhysicalIntergaceGrid
		]
	});

	function getIpStatusColor(isDown, isManaged) {
		var bgStyle;
		if (isManaged == 'U' || isManaged == 'F' || isManaged == 'N') {
			bgStyle = 'grid-status-blue';
		} else {
			bgStyle = 'grid-status-green';
			if (isDown == 'true') {
				bgStyle = 'grid-status-red';
			}
		}

		return String.format('x-grid3-row {0}', bgStyle);
	}

	function getSnmpStatusColor(ifAdminStatus, ifOperStatus){
		var bgStyle;
		if(ifAdminStatus != 1){
			bgStyle = 'grid-status-blue';
		}else if(ifAdminStatus == 1 && ifOperStatus == 1){
			bgStyle = 'grid-status-green';
		}else if(ifAdminStatus == 1 && ifOperStatus != 1){
			bgStyle = 'grid-status-red';
		}

		return String.format('x-grid3-row {0}', bgStyle);
	};

};<|endoftext|>


<commit_before>function HTMLActuator() {
  this.tileContainer    = document.querySelector(".tile-container");
  this.scoreContainer   = document.querySelector(".score-container");
  this.bestContainer    = document.querySelector(".best-container");
  this.messageContainer = document.querySelector(".game-message");

  this.score = 0;
}

HTMLActuator.prototype.actuate = function (grid, metadata) {
  var self = this;

  window.requestAnimationFrame(function () {
    self.clearContainer(self.tileContainer);

    grid.cells.forEach(function (column) {
      column.forEach(function (cell) {
        if (cell) {
          self.addTile(cell);
        }
      });
    });

    self.updateScore(metadata.score);
    self.updateBestScore(metadata.bestScore);

    if (metadata.terminated) {
      if (metadata.over) {
        self.message(false); // You lose
      } else if (metadata.won) {
        self.message(true); // You win!
      }
    }

  });
};

// Continues the game (both restart and keep playing)
HTMLActuator.prototype.continue = function () {
  this.clearMessage();
};

HTMLActuator.prototype.clearContainer = function (container) {
  while (container.firstChild) {
    container.removeChild(container.firstChild);
  }
};

HTMLActuator.prototype.addTile = function (tile) {
  var text = " 甲乙丙丁戊己庚辛壬癸终天地人和〇";
  var self = this;
  var log2 = function (n) { var ret = 0; while (n > 1) ret++, n >>= 1; return ret; }

  var wrapper   = document.createElement("div");
  var inner     = document.createElement("div");
  var position  = tile.previousPosition || { x: tile.x, y: tile.y };
  var positionClass = this.positionClass(position);

  // We can't use classlist because it somehow glitches when replacing classes
  var classes = ["tile", "tile-" + tile.value, positionClass];

  if (tile.value > 2048) classes.push("tile-super");

  this.applyClasses(wrapper, classes);

  inner.classList.add("tile-inner");
  inner.textContent = text[log2(tile.value)];

  if (tile.previousPosition) {
    // Make sure that the tile gets rendered in the previous position first
    window.requestAnimationFrame(function () {
      classes[2] = self.positionClass({ x: tile.x, y: tile.y });
      self.applyClasses(wrapper, classes); // Update the position
    });
  } else if (tile.mergedFrom) {
    classes.push("tile-merged");
    this.applyClasses(wrapper, classes);

    // Render the tiles that merged
    tile.mergedFrom.forEach(function (merged) {
      self.addTile(merged);
    });
  } else {
    classes.push("tile-new");
    this.applyClasses(wrapper, classes);
  }

  // Add the inner part of the tile to the wrapper
  wrapper.appendChild(inner);

  // Put the tile on the board
  this.tileContainer.appendChild(wrapper);
};

HTMLActuator.prototype.applyClasses = function (element, classes) {
  element.setAttribute("class", classes.join(" "));
};

HTMLActuator.prototype.normalizePosition = function (position) {
  return { x: position.x + 1, y: position.y + 1 };
};

HTMLActuator.prototype.positionClass = function (position) {
  position = this.normalizePosition(position);
  return "tile-position-" + position.x + "-" + position.y;
};

HTMLActuator.prototype.updateScore = function (score) {
  var text = function (n) {
    return ('' + n).split('').map(function (c) { return '〇一二三四五六七八九'[c]; }).join('');
  };
  this.clearContainer(this.scoreContainer);

  var difference = score - this.score;
  this.score = score;

  this.scoreContainer.textContent = text(this.score);

  if (difference > 0) {
    var addition = document.createElement("div");
    addition.classList.add("score-addition");
    addition.textContent = text(difference);

    this.scoreContainer.appendChild(addition);
  }
};

HTMLActuator.prototype.updateBestScore = function (bestScore) {
  var text = function (n) {
    return ('' + n).split('').map(function (c) { return '〇一二三四五六七八九'[c]; }).join('');
  };
  this.bestContainer.textContent = text(bestScore);
};

HTMLActuator.prototype.message = function (won) {
  var type    = won ? "game-won" : "game-over";
  var message = won ? "胜利！" : "失败……";

  this.messageContainer.classList.add(type);
  this.messageContainer.getElementsByTagName("p")[0].textContent = message;
};

HTMLActuator.prototype.clearMessage = function () {
  // IE only takes one value to remove at a time.
  this.messageContainer.classList.remove("game-won");
  this.messageContainer.classList.remove("game-over");
};
<commit_msg>modify localization string...<commit_after>function HTMLActuator() {
  this.tileContainer    = document.querySelector(".tile-container");
  this.scoreContainer   = document.querySelector(".score-container");
  this.bestContainer    = document.querySelector(".best-container");
  this.messageContainer = document.querySelector(".game-message");

  this.score = 0;
}

HTMLActuator.prototype.actuate = function (grid, metadata) {
  var self = this;

  window.requestAnimationFrame(function () {
    self.clearContainer(self.tileContainer);

    grid.cells.forEach(function (column) {
      column.forEach(function (cell) {
        if (cell) {
          self.addTile(cell);
        }
      });
    });

    self.updateScore(metadata.score);
    self.updateBestScore(metadata.bestScore);

    if (metadata.terminated) {
      if (metadata.over) {
        self.message(false); // You lose
      } else if (metadata.won) {
        self.message(true); // You win!
      }
    }

  });
};

// Continues the game (both restart and keep playing)
HTMLActuator.prototype.continue = function () {
  this.clearMessage();
};

HTMLActuator.prototype.clearContainer = function (container) {
  while (container.firstChild) {
    container.removeChild(container.firstChild);
  }
};

HTMLActuator.prototype.addTile = function (tile) {
  var text = " 甲乙丙丁戊己庚辛壬癸终天地人和初〇";
  var self = this;
  var log2 = function (n) { var ret = 0; while (n > 1) ret++, n >>= 1; return ret; }

  var wrapper   = document.createElement("div");
  var inner     = document.createElement("div");
  var position  = tile.previousPosition || { x: tile.x, y: tile.y };
  var positionClass = this.positionClass(position);

  // We can't use classlist because it somehow glitches when replacing classes
  var classes = ["tile", "tile-" + tile.value, positionClass];

  if (tile.value > 2048) classes.push("tile-super");

  this.applyClasses(wrapper, classes);

  inner.classList.add("tile-inner");
  inner.textContent = text[log2(tile.value)];

  if (tile.previousPosition) {
    // Make sure that the tile gets rendered in the previous position first
    window.requestAnimationFrame(function () {
      classes[2] = self.positionClass({ x: tile.x, y: tile.y });
      self.applyClasses(wrapper, classes); // Update the position
    });
  } else if (tile.mergedFrom) {
    classes.push("tile-merged");
    this.applyClasses(wrapper, classes);

    // Render the tiles that merged
    tile.mergedFrom.forEach(function (merged) {
      self.addTile(merged);
    });
  } else {
    classes.push("tile-new");
    this.applyClasses(wrapper, classes);
  }

  // Add the inner part of the tile to the wrapper
  wrapper.appendChild(inner);

  // Put the tile on the board
  this.tileContainer.appendChild(wrapper);
};

HTMLActuator.prototype.applyClasses = function (element, classes) {
  element.setAttribute("class", classes.join(" "));
};

HTMLActuator.prototype.normalizePosition = function (position) {
  return { x: position.x + 1, y: position.y + 1 };
};

HTMLActuator.prototype.positionClass = function (position) {
  position = this.normalizePosition(position);
  return "tile-position-" + position.x + "-" + position.y;
};

HTMLActuator.prototype.updateScore = function (score) {
  var text = function (n) {
    return ('' + n).split('').map(function (c) { return '〇一二三四五六七八九'[c]; }).join('');
  };
  this.clearContainer(this.scoreContainer);

  var difference = score - this.score;
  this.score = score;

  this.scoreContainer.textContent = text(this.score);

  if (difference > 0) {
    var addition = document.createElement("div");
    addition.classList.add("score-addition");
    addition.textContent = text(difference);

    this.scoreContainer.appendChild(addition);
  }
};

HTMLActuator.prototype.updateBestScore = function (bestScore) {
  var text = function (n) {
    return ('' + n).split('').map(function (c) { return '〇一二三四五六七八九'[c]; }).join('');
  };
  this.bestContainer.textContent = text(bestScore);
};

HTMLActuator.prototype.message = function (won) {
  var type    = won ? "game-won" : "game-over";
  var message = won ? "胜利！" : "失败……";

  this.messageContainer.classList.add(type);
  this.messageContainer.getElementsByTagName("p")[0].textContent = message;
};

HTMLActuator.prototype.clearMessage = function () {
  // IE only takes one value to remove at a time.
  this.messageContainer.classList.remove("game-won");
  this.messageContainer.classList.remove("game-over");
};
<|endoftext|>


<commit_before>// This file contains methods responsible for introspecting the current path for certain values.

import type NodePath from "./index";
import includes from "lodash/collection/includes";
import * as t from "babel-types";

/**
 * Match the current node if it matches the provided `pattern`.
 *
 * For example, given the match `React.createClass` it would match the
 * parsed nodes of `React.createClass` and `React["createClass"]`.
 */

export function matchesPattern(pattern: string, allowPartial?: boolean): boolean {
  // not a member expression
  if (!this.isMemberExpression()) return false;

  var parts = pattern.split(".");
  var search = [this.node];
  var i = 0;

  function matches(name) {
    var part = parts[i];
    return part === "*" || name === part;
  }

  while (search.length) {
    var node = search.shift();

    if (allowPartial && i === parts.length) {
      return true;
    }

    if (t.isIdentifier(node)) {
      // this part doesn't match
      if (!matches(node.name)) return false;
    } else if (t.isLiteral(node)) {
      // this part doesn't match
      if (!matches(node.value)) return false;
    } else if (t.isMemberExpression(node)) {
      if (node.computed && !t.isLiteral(node.property)) {
        // we can't deal with this
        return false;
      } else {
        search.unshift(node.property);
        search.unshift(node.object);
        continue;
      }
    } else if (t.isThisExpression(node)) {
      if (!matches("this")) return false;
    } else {
      // we can't deal with this
      return false;
    }

    // too many parts
    if (++i > parts.length) {
      return false;
    }
  }

  return i === parts.length;
}

/**
 * Check whether we have the input `key`. If the `key` references an array then we check
 * if the array has any items, otherwise we just check if it's falsy.
 */

export function has(key): boolean {
  var val = this.node[key];
  if (val && Array.isArray(val)) {
    return !!val.length;
  } else {
    return !!val;
  }
}

/**
 * Description
 */

export function isStatic() {
  return this.scope.isStatic(this.node);
}

/**
 * Alias of `has`.
 */

export var is = has;

/**
 * Opposite of `has`.
 */

export function isnt(key): boolean {
  return !this.has(key);
}

/**
 * Check whether the path node `key` strict equals `value`.
 */

export function equals(key, value): boolean {
  return this.node[key] === value;
}

/**
 * Check the type against our stored internal type of the node. This is handy when a node has
 * been removed yet we still internally know the type and need it to calculate node replacement.
 */

export function isNodeType(type: string): boolean {
  return t.isType(this.type, type);
}

/**
 * This checks whether or now we're in one of the following positions:
 *
 *   for (KEY in right);
 *   for (KEY;;);
 *
 * This is because these spots allow VariableDeclarations AND normal expressions so we need
 * to tell the path replacement that it's ok to replace this with an expression.
 */

 export function canHaveVariableDeclarationOrExpression() {
    return (this.key === "init" || this.key === "left") && this.parentPath.isFor();
 }

/**
 * Check whether the current path references a completion record
 */

export function isCompletionRecord(allowInsideFunction?) {
  var path = this;
  var first = true;

  do {
    var container = path.container;

    // we're in a function so can't be a completion record
    if (path.isFunction() && !first) {
      return !!allowInsideFunction;
    }

    first = false;

    // check to see if we're the last item in the container and if we are
    // we're a completion record!
    if (Array.isArray(container) && path.key !== container.length - 1) {
      return false;
    }
  } while ((path = path.parentPath) && !path.isProgram());

  return true;
}

/**
 * Check whether or not the current `key` allows either a single statement or block statement
 * so we can explode it if necessary.
 */

export function isStatementOrBlock() {
  if (this.parentPath.isLabeledStatement() || t.isBlockStatement(this.container)) {
    return false;
  } else {
    return includes(t.STATEMENT_OR_BLOCK_KEYS, this.key);
  }
}

/**
 * Check if the currently assigned path references the `importName` of `moduleSource`.
 */

export function referencesImport(moduleSource, importName) {
  if (!this.isReferencedIdentifier()) return false;

  var binding = this.scope.getBinding(this.node.name);
  if (!binding || binding.kind !== "module") return false;

  var path = binding.path;
  var parent = path.parentPath;
  if (!parent.isImportDeclaration()) return false;

  // check moduleSource
  if (parent.node.source.value === moduleSource) {
    if (!importName) return true;
  } else {
    return false;
  }

  if (path.isImportDefaultSpecifier() && importName === "default") {
    return true;
  }

  if (path.isImportNamespaceSpecifier() && importName === "*") {
    return true;
  }

  if (path.isImportSpecifier() && path.node.imported.name === importName) {
    return true;
  }

  return false;
}

/**
 * Get the source code associated with this node.
 */

export function getSource() {
  var node = this.node;
  if (node.end) {
    return this.hub.file.code.slice(node.start, node.end);
  } else {
    return "";
  }
}

export function willIMaybeExecuteBefore(target) {
  return this._guessExecutionStatusRelativeTo(target) !== "after";
}

/**
 * Given a `target` check the execution status of it relative to the current path.
 *
 * "Execution status" simply refers to where or not we **think** this will execuete
 * before or after the input `target` element.
 */

export function _guessExecutionStatusRelativeTo(target) {
  // check if the two paths are in different functions, we can't track execution of these
  var targetFuncParent = target.scope.getFunctionParent();
  var selfFuncParent = this.scope.getFunctionParent();
  if (targetFuncParent !== selfFuncParent) {
    return "function";
  }

  var targetPaths = target.getAncestry();
  //if (targetPaths.indexOf(this) >= 0) return "after";

  var selfPaths   = this.getAncestry();

  // get ancestor where the branches intersect
  var commonPath;
  var targetIndex;
  var selfIndex;
  for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) {
    var selfPath = selfPaths[selfIndex];
    targetIndex = targetPaths.indexOf(selfPath);
    if (targetIndex >= 0) {
      commonPath = selfPath;
      break;
    }
  }
  if (!commonPath) {
    return "before";
  }

  // get the relationship paths that associate these nodes to their common ancestor
  var targetRelationship = targetPaths[targetIndex - 1];
  var selfRelationship   = selfPaths[selfIndex - 1];
  if (!targetRelationship || !selfRelationship) {
    return "before";
  }

  // container list so let's see which one is after the other
  if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) {
    return targetRelationship.key > selfRelationship.key ? "before" : "after";
  }

  // otherwise we're associated by a parent node, check which key comes before the other
  var targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key);
  var selfKeyPosition   = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key);
  return targetKeyPosition > selfKeyPosition ? "before" : "after";
}

/**
 * Resolve a "pointer" `NodePath` to it's absolute path.
 */

export function resolve(dangerous, resolved) {
  return this._resolve(dangerous, resolved) || this;
}

export function _resolve(dangerous?, resolved?): ?NodePath {
  // detect infinite recursion
  // todo: possibly have a max length on this just to be safe
  if (resolved && resolved.indexOf(this) >= 0) return;

  // we store all the paths we've "resolved" in this array to prevent infinite recursion
  resolved = resolved || [];
  resolved.push(this);

  if (this.isVariableDeclarator()) {
    if (this.get("id").isIdentifier()) {
      return this.get("init").resolve(dangerous, resolved);
    } else {
      // otherwise it's a request for a pattern and that's a bit more tricky
    }
  } else if (this.isReferencedIdentifier()) {
    var binding = this.scope.getBinding(this.node.name);
    if (!binding) return;

    // reassigned so we can't really resolve it
    if (!binding.constant) return;

    // todo - lookup module in dependency graph
    if (binding.kind === "module") return;

    if (binding.path !== this) {
      return binding.path.resolve(dangerous, resolved);
    }
  } else if (this.isTypeCastExpression()) {
    return this.get("expression").resolve(dangerous, resolved);
  } else if (dangerous && this.isMemberExpression()) {
    // this is dangerous, as non-direct target assignments will mutate it's state
    // making this resolution inaccurate

    var targetKey = this.toComputedKey();
    if (!t.isLiteral(targetKey)) return;

    var targetName = targetKey.value;

    var target = this.get("object").resolve(dangerous, resolved);

    if (target.isObjectExpression()) {
      var props = target.get("properties");
      for (var prop of (props: Array)) {
        if (!prop.isProperty()) continue;

        var key = prop.get("key");

        // { foo: obj }
        var match = prop.isnt("computed") && key.isIdentifier({ name: targetName });

        // { "foo": "obj" } or { ["foo"]: "obj" }
        match = match || key.isLiteral({ value: targetName });

        if (match) return prop.get("value").resolve(dangerous, resolved);
      }
    } else if (target.isArrayExpression() && !isNaN(+targetName)) {
      var elems = target.get("elements");
      var elem = elems[targetName];
      if (elem) return elem.resolve(dangerous, resolved);
    }
  }
}
<commit_msg>don't deopt _guessExecutionStatusRelativeTo on specific function cases<commit_after>// This file contains methods responsible for introspecting the current path for certain values.

import type NodePath from "./index";
import includes from "lodash/collection/includes";
import * as t from "babel-types";

/**
 * Match the current node if it matches the provided `pattern`.
 *
 * For example, given the match `React.createClass` it would match the
 * parsed nodes of `React.createClass` and `React["createClass"]`.
 */

export function matchesPattern(pattern: string, allowPartial?: boolean): boolean {
  // not a member expression
  if (!this.isMemberExpression()) return false;

  var parts = pattern.split(".");
  var search = [this.node];
  var i = 0;

  function matches(name) {
    var part = parts[i];
    return part === "*" || name === part;
  }

  while (search.length) {
    var node = search.shift();

    if (allowPartial && i === parts.length) {
      return true;
    }

    if (t.isIdentifier(node)) {
      // this part doesn't match
      if (!matches(node.name)) return false;
    } else if (t.isLiteral(node)) {
      // this part doesn't match
      if (!matches(node.value)) return false;
    } else if (t.isMemberExpression(node)) {
      if (node.computed && !t.isLiteral(node.property)) {
        // we can't deal with this
        return false;
      } else {
        search.unshift(node.property);
        search.unshift(node.object);
        continue;
      }
    } else if (t.isThisExpression(node)) {
      if (!matches("this")) return false;
    } else {
      // we can't deal with this
      return false;
    }

    // too many parts
    if (++i > parts.length) {
      return false;
    }
  }

  return i === parts.length;
}

/**
 * Check whether we have the input `key`. If the `key` references an array then we check
 * if the array has any items, otherwise we just check if it's falsy.
 */

export function has(key): boolean {
  var val = this.node[key];
  if (val && Array.isArray(val)) {
    return !!val.length;
  } else {
    return !!val;
  }
}

/**
 * Description
 */

export function isStatic() {
  return this.scope.isStatic(this.node);
}

/**
 * Alias of `has`.
 */

export var is = has;

/**
 * Opposite of `has`.
 */

export function isnt(key): boolean {
  return !this.has(key);
}

/**
 * Check whether the path node `key` strict equals `value`.
 */

export function equals(key, value): boolean {
  return this.node[key] === value;
}

/**
 * Check the type against our stored internal type of the node. This is handy when a node has
 * been removed yet we still internally know the type and need it to calculate node replacement.
 */

export function isNodeType(type: string): boolean {
  return t.isType(this.type, type);
}

/**
 * This checks whether or now we're in one of the following positions:
 *
 *   for (KEY in right);
 *   for (KEY;;);
 *
 * This is because these spots allow VariableDeclarations AND normal expressions so we need
 * to tell the path replacement that it's ok to replace this with an expression.
 */

 export function canHaveVariableDeclarationOrExpression() {
    return (this.key === "init" || this.key === "left") && this.parentPath.isFor();
 }

/**
 * Check whether the current path references a completion record
 */

export function isCompletionRecord(allowInsideFunction?) {
  var path = this;
  var first = true;

  do {
    var container = path.container;

    // we're in a function so can't be a completion record
    if (path.isFunction() && !first) {
      return !!allowInsideFunction;
    }

    first = false;

    // check to see if we're the last item in the container and if we are
    // we're a completion record!
    if (Array.isArray(container) && path.key !== container.length - 1) {
      return false;
    }
  } while ((path = path.parentPath) && !path.isProgram());

  return true;
}

/**
 * Check whether or not the current `key` allows either a single statement or block statement
 * so we can explode it if necessary.
 */

export function isStatementOrBlock() {
  if (this.parentPath.isLabeledStatement() || t.isBlockStatement(this.container)) {
    return false;
  } else {
    return includes(t.STATEMENT_OR_BLOCK_KEYS, this.key);
  }
}

/**
 * Check if the currently assigned path references the `importName` of `moduleSource`.
 */

export function referencesImport(moduleSource, importName) {
  if (!this.isReferencedIdentifier()) return false;

  var binding = this.scope.getBinding(this.node.name);
  if (!binding || binding.kind !== "module") return false;

  var path = binding.path;
  var parent = path.parentPath;
  if (!parent.isImportDeclaration()) return false;

  // check moduleSource
  if (parent.node.source.value === moduleSource) {
    if (!importName) return true;
  } else {
    return false;
  }

  if (path.isImportDefaultSpecifier() && importName === "default") {
    return true;
  }

  if (path.isImportNamespaceSpecifier() && importName === "*") {
    return true;
  }

  if (path.isImportSpecifier() && path.node.imported.name === importName) {
    return true;
  }

  return false;
}

/**
 * Get the source code associated with this node.
 */

export function getSource() {
  var node = this.node;
  if (node.end) {
    return this.hub.file.code.slice(node.start, node.end);
  } else {
    return "";
  }
}

export function willIMaybeExecuteBefore(target) {
  return this._guessExecutionStatusRelativeTo(target) !== "after";
}

/**
 * Given a `target` check the execution status of it relative to the current path.
 *
 * "Execution status" simply refers to where or not we **think** this will execuete
 * before or after the input `target` element.
 */

export function _guessExecutionStatusRelativeTo(target) {
  // check if the two paths are in different functions, we can't track execution of these
  var targetFuncParent = target.scope.getFunctionParent();
  var selfFuncParent = this.scope.getFunctionParent();

  if (targetFuncParent !== selfFuncParent) {
    var targetFuncPath = targetFuncParent.path;
    if (!targetFuncPath.isFunctionDeclaration()) return "function";

    // so we're in a completely different function, if this is a function declaration
    // then we can be a bit smarter and handle cases where the function is either
    // a. not called at all (part of an export)
    // b. called directly
    var binding = targetFuncPath.scope.getBinding(targetFuncPath.node.id.name);

    // no references!
    if (!binding.references) return "before";

    var referencePaths: Array = binding.referencePaths;

    // verify that all of the references are calls
    for (let path of referencePaths) {
      if (path.key !== "callee" || !path.parentPath.isCallExpression()) {
        return "function";
      }
    }

    var allStatus;

    // verify that all the calls have the same execution status
    for (let path of referencePaths) {
      var status = this._guessExecutionStatusRelativeTo(path);
      if (allStatus) {
        if (allStatus !== status) return "function";
      } else {
        allStatus = status;
      }
    }

    return allStatus || "function";
  }

  var targetPaths = target.getAncestry();
  if (targetPaths.indexOf(this) >= 0) return "after";

  var selfPaths   = this.getAncestry();

  // get ancestor where the branches intersect
  var commonPath;
  var targetIndex;
  var selfIndex;
  for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) {
    var selfPath = selfPaths[selfIndex];
    targetIndex = targetPaths.indexOf(selfPath);
    if (targetIndex >= 0) {
      commonPath = selfPath;
      break;
    }
  }
  if (!commonPath) {
    return "before";
  }

  // get the relationship paths that associate these nodes to their common ancestor
  var targetRelationship = targetPaths[targetIndex - 1];
  var selfRelationship   = selfPaths[selfIndex - 1];
  if (!targetRelationship || !selfRelationship) {
    return "before";
  }

  // container list so let's see which one is after the other
  if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) {
    return targetRelationship.key > selfRelationship.key ? "before" : "after";
  }

  // otherwise we're associated by a parent node, check which key comes before the other
  var targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key);
  var selfKeyPosition   = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key);
  return targetKeyPosition > selfKeyPosition ? "before" : "after";
}

/**
 * Resolve a "pointer" `NodePath` to it's absolute path.
 */

export function resolve(dangerous, resolved) {
  return this._resolve(dangerous, resolved) || this;
}

export function _resolve(dangerous?, resolved?): ?NodePath {
  // detect infinite recursion
  // todo: possibly have a max length on this just to be safe
  if (resolved && resolved.indexOf(this) >= 0) return;

  // we store all the paths we've "resolved" in this array to prevent infinite recursion
  resolved = resolved || [];
  resolved.push(this);

  if (this.isVariableDeclarator()) {
    if (this.get("id").isIdentifier()) {
      return this.get("init").resolve(dangerous, resolved);
    } else {
      // otherwise it's a request for a pattern and that's a bit more tricky
    }
  } else if (this.isReferencedIdentifier()) {
    var binding = this.scope.getBinding(this.node.name);
    if (!binding) return;

    // reassigned so we can't really resolve it
    if (!binding.constant) return;

    // todo - lookup module in dependency graph
    if (binding.kind === "module") return;

    if (binding.path !== this) {
      return binding.path.resolve(dangerous, resolved);
    }
  } else if (this.isTypeCastExpression()) {
    return this.get("expression").resolve(dangerous, resolved);
  } else if (dangerous && this.isMemberExpression()) {
    // this is dangerous, as non-direct target assignments will mutate it's state
    // making this resolution inaccurate

    var targetKey = this.toComputedKey();
    if (!t.isLiteral(targetKey)) return;

    var targetName = targetKey.value;

    var target = this.get("object").resolve(dangerous, resolved);

    if (target.isObjectExpression()) {
      var props = target.get("properties");
      for (var prop of (props: Array)) {
        if (!prop.isProperty()) continue;

        var key = prop.get("key");

        // { foo: obj }
        var match = prop.isnt("computed") && key.isIdentifier({ name: targetName });

        // { "foo": "obj" } or { ["foo"]: "obj" }
        match = match || key.isLiteral({ value: targetName });

        if (match) return prop.get("value").resolve(dangerous, resolved);
      }
    } else if (target.isArrayExpression() && !isNaN(+targetName)) {
      var elems = target.get("elements");
      var elem = elems[targetName];
      if (elem) return elem.resolve(dangerous, resolved);
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

require('../models/project');

var options = {
  includes: 'assign watchers',
  defaults: {
    watchers: []
  }
};

exports.defaultOptions = options;

var crud = require('../controllers/crud.js');
var projectController = crud('projects', options);

var mongoose = require('mongoose'),
  Project = mongoose.model('Project'),
  Task = mongoose.model('Task'),
  User = mongoose.model('User'),
  _ = require('lodash'),
  elasticsearch = require('./elasticsearch.js');

Object.keys(projectController).forEach(function(methodName) {
  if (methodName !== 'destroy') {
    exports[methodName] = projectController[methodName];
  }
});

exports.destroy = function(req, res, next) {
  if (req.locals.error) {
    return next();
  }

  Task.find({ project: req.params.id }).then(function(tasks) {
    //FIXME: do it with mongo aggregate
    var groupedTasks = _.groupBy(tasks, function(task) {
      return task.discussions.length > 0
        ? 'release'
        : 'remove';
    });

    groupedTasks.remove = groupedTasks.remove || [];
    groupedTasks.release = groupedTasks.release || [];

    Task.update({ _id: { $in: groupedTasks.release }},
        {  project: null }).exec();

    Task.remove({ _id: { $in: groupedTasks.remove }}).then(function() {
      //FIXME: needs to be optimized to one query
      groupedTasks.remove.forEach(function(task) {
        elasticsearch.delete(task, 'task', null, next);
      });

      var removeTaskIds = _(groupedTasks.remove)
        .pluck('_id')
        .map(function(i) { return i.toString(); })
        .value();

      User.update({ 'profile.starredTasks': { $in: removeTaskIds } },
          { $pull: { 'profile.starredTasks': { $in: removeTaskIds } } }).exec();
    });

    projectController.destroy(req, res, next);

  });
};

exports.getByEntity = function (req, res, next) {
  if (req.locals.error) {
    return next();
  }

  var entities = {users: 'creator', _id: '_id'},
    entityQuery = {};

  entityQuery[entities[req.params.entity]] = req.params.id;

  var starredOnly = false;
  var ids = req.locals.data.ids;
  if (ids && ids.length) {
    entityQuery._id = { $in: ids };
    starredOnly = true;
  }
  var Query = Project.find(entityQuery);

  Query.populate(options.includes);

  var pagination = req.locals.data.pagination;
  if (pagination && pagination.type && pagination.type === 'page') {
    Query.sort(pagination.sort)
      .skip(pagination.start)
      .limit(pagination.limit);
  }

  Query.exec(function (err, projects) {
    if (err) {
      req.locals.error = { message: 'Can\'t get projects' };
    } else {
      if (starredOnly) {
        projects.forEach(function(project) {
          project.star = true;
        });
      }

      req.locals.result = projects;
    }

    next();
  });
};

exports.getByDiscussion = function (req, res, next) {
  if (req.locals.error) {
    return next();
  }

  if (req.params.entity !== 'discussions') return next();

  var entityQuery = {
    discussions: req.params.id,
    project: { $ne: null, $exists: true }
  };

  var starredOnly = false;
  var ids = req.locals.data.ids;
  if (ids && ids.length) {
    entityQuery._id = { $in: ids };
    starredOnly = true;
  }

  var Query = Task.find(entityQuery, {project: 1, _id: 0});
  Query.populate('project');

  Query.exec(function (err, projects) {
    if (err) {
      req.locals.error = { message: 'Can\'t get projects' };
    } else {
      projects = _.uniq(projects, 'project._id');
      projects = _.map(projects, function (item) {
        return item.project;
      });

      if (starredOnly) {
        projects.forEach(function(project) {
          project.star = true;
        });
      }

      req.locals.result = projects;

      next();
    }
  });
};
<commit_msg>load more projects<commit_after>'use strict';

require('../models/project');

var options = {
  includes: 'assign watchers',
  defaults: {
    watchers: []
  }
};

exports.defaultOptions = options;

var crud = require('../controllers/crud.js');
var projectController = crud('projects', options);

var mongoose = require('mongoose'),
  Project = mongoose.model('Project'),
  Task = mongoose.model('Task'),
  User = mongoose.model('User'),
  _ = require('lodash'),
  elasticsearch = require('./elasticsearch.js');

Object.keys(projectController).forEach(function(methodName) {
  if (methodName !== 'destroy') {
    exports[methodName] = projectController[methodName];
  }
});

exports.destroy = function(req, res, next) {
  if (req.locals.error) {
    return next();
  }

  Task.find({ project: req.params.id }).then(function(tasks) {
    //FIXME: do it with mongo aggregate
    var groupedTasks = _.groupBy(tasks, function(task) {
      return task.discussions.length > 0
        ? 'release'
        : 'remove';
    });

    groupedTasks.remove = groupedTasks.remove || [];
    groupedTasks.release = groupedTasks.release || [];

    Task.update({ _id: { $in: groupedTasks.release }},
        {  project: null }).exec();

    Task.remove({ _id: { $in: groupedTasks.remove }}).then(function() {
      //FIXME: needs to be optimized to one query
      groupedTasks.remove.forEach(function(task) {
        elasticsearch.delete(task, 'task', null, next);
      });

      var removeTaskIds = _(groupedTasks.remove)
        .pluck('_id')
        .map(function(i) { return i.toString(); })
        .value();

      User.update({ 'profile.starredTasks': { $in: removeTaskIds } },
          { $pull: { 'profile.starredTasks': { $in: removeTaskIds } } }).exec();
    });

    projectController.destroy(req, res, next);

  });
};

exports.getByEntity = function (req, res, next) {
  if (req.locals.error) {
    return next();
  }

  var entities = {users: 'creator', _id: '_id'},
    entityQuery = {};

  entityQuery[entities[req.params.entity]] = req.params.id;

  var starredOnly = false;
  var ids = req.locals.data.ids;
  if (ids && ids.length) {
    entityQuery._id = { $in: ids };
    starredOnly = true;
  }
  var Query = Project.find(entityQuery);

  Query.populate(options.includes);

  Project.find(entityQuery).count({}, function(err, c) {
    req.locals.data.pagination.count = c;

		var pagination = req.locals.data.pagination;
	  if (pagination && pagination.type && pagination.type === 'page') {
	    Query.sort(pagination.sort)
	      .skip(pagination.start)
	      .limit(pagination.limit);
	  }

	  Query.exec(function (err, projects) {
	    if (err) {
	      req.locals.error = { message: 'Can\'t get projects' };
	    } else {
	      if (starredOnly) {
	        projects.forEach(function(project) {
	          project.star = true;
	        });
	      }

	      req.locals.result = projects;
	    }

	    next();
	  });

	});

};

exports.getByDiscussion = function (req, res, next) {
  if (req.locals.error) {
    return next();
  }

  if (req.params.entity !== 'discussions') return next();

  var entityQuery = {
    discussions: req.params.id,
    project: { $ne: null, $exists: true }
  };

  var starredOnly = false;
  var ids = req.locals.data.ids;
  if (ids && ids.length) {
    entityQuery._id = { $in: ids };
    starredOnly = true;
  }

  var Query = Task.find(entityQuery, {project: 1, _id: 0});
  Query.populate('project');

  Query.exec(function (err, projects) {
    if (err) {
      req.locals.error = { message: 'Can\'t get projects' };
    } else {
      projects = _.uniq(projects, 'project._id');
      projects = _.map(projects, function (item) {
        return item.project;
      });

      if (starredOnly) {
        projects.forEach(function(project) {
          project.star = true;
        });
      }

      req.locals.result = projects;

      next();
    }
  });
};
<|endoftext|>


<commit_before>module.exports = {
  plugins: [
    'jsx-a11y',
    'react'
  ],
  ecmaFeatures: {
    jsx: true
  },
  rules: {
    // Enforce that anchors have content
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/anchor-has-content.md
    'jsx-a11y/anchor-has-content': ['error', { components: [''] }],

    // Require ARIA roles to be valid and non-abstract
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-role.md
    'jsx-a11y/aria-role': ['error', { ignoreNonDom: false }],

    // Enforce all aria-* props are valid.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-props.md
    'jsx-a11y/aria-props': 'error',

    // Enforce ARIA state and property values are valid.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-proptypes.md
    'jsx-a11y/aria-proptypes': 'error',

    // Enforce that elements that do not support ARIA roles, states, and
    // properties do not have those attributes.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-unsupported-elements.md
    'jsx-a11y/aria-unsupported-elements': 'error',

    // disallow href "#"
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/href-no-hash.md
    'jsx-a11y/href-no-hash': ['error', { components: ['a'] }],

    // Require <img> to have a non-empty `alt` prop, or role="presentation"
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/img-has-alt.md
    'jsx-a11y/img-has-alt': 'error',

    // Prevent img alt text from containing redundant words like "image", "picture", or "photo"
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/img-redundant-alt.md
    'jsx-a11y/img-redundant-alt': 'error',

    // require that JSX labels use "htmlFor"
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/label-has-for.md
    'jsx-a11y/label-has-for': ['error', { components: ['label'] }],

    // require that mouseover/out come with focus/blur, for keyboard-only users
    // TODO: evaluate
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/mouse-events-have-key-events.md
    'jsx-a11y/mouse-events-have-key-events': 'off',

    // Prevent use of `accessKey`
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-access-key.md
    'jsx-a11y/no-access-key': 'error',

    // require onBlur instead of onChange
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-onchange.md
    'jsx-a11y/no-onchange': 'off',

    // Enforce that elements with onClick handlers must be focusable.
    // TODO: evaluate
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/onclick-has-focus.md
    'jsx-a11y/onclick-has-focus': 'off',

    // require things with onClick to have an aria role
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/onclick-has-role.md
    'jsx-a11y/onclick-has-role': 'off',

    // Enforce that elements with ARIA roles must have all required attributes
    // for that role.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/role-has-required-aria-props.md
    'jsx-a11y/role-has-required-aria-props': 'error',

    // Enforce that elements with explicit or implicit roles defined contain
    // only aria-* properties supported by that role.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/role-supports-aria-props.md
    'jsx-a11y/role-supports-aria-props': 'error',

    // Enforce tabIndex value is not greater than zero.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/tabindex-no-positive.md
    'jsx-a11y/tabindex-no-positive': 'error',

    // ensure <hX> tags have content and are not aria-hidden
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/heading-has-content.md
    'jsx-a11y/heading-has-content': ['error', { components: [''] }],

    // require HTML elements to have a "lang" prop
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/html-has-lang.md
    'jsx-a11y/html-has-lang': 'error',

    // require HTML element's lang prop to be valid
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/lang.md
    'jsx-a11y/lang': 'error',

    // prevent distracting elements, like <marquee> and <blink>
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-distracting-elements.md
    'jsx-a11y/no-distracting-elements': ['error', {
      elements: ['marquee', 'blink'],
    }],

    // only allow <th> to have the "scope" attr
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/scope.md
    'jsx-a11y/scope': 'error',

    // require onClick be accompanied by onKeyUp/onKeyDown/onKeyPress
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/click-events-have-key-events.md
    // TODO: enable?
    'jsx-a11y/click-events-have-key-events': 'off',

    // Enforce that DOM elements without semantic behavior not have interaction handlers
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-static-element-interactions.md
    'jsx-a11y/no-static-element-interactions': 'error',

    // ensure emoji are accessible
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/accessible-emoji.md
    'jsx-a11y/accessible-emoji': 'error',

    // elements with aria-activedescendant must be tabbable
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-activedescendant-has-tabindex.md
    'jsx-a11y/aria-activedescendant-has-tabindex': 'error',

    // ensure iframe elements have a unique title
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/iframe-has-title.md
    'jsx-a11y/iframe-has-title': 'error',

    // prohibit autoFocus prop
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-autofocus.md
    'jsx-a11y/no-autofocus': 'error',

    // ensure HTML elements do not specify redundant ARIA roles
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-redundant-roles.md
    'jsx-a11y/no-redundant-roles': 'error',
  },
};
<commit_msg>[eslint config] [breaking] enable rules:<commit_after>module.exports = {
  plugins: [
    'jsx-a11y',
    'react'
  ],
  ecmaFeatures: {
    jsx: true
  },
  rules: {
    // Enforce that anchors have content
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/anchor-has-content.md
    'jsx-a11y/anchor-has-content': ['error', { components: [''] }],

    // Require ARIA roles to be valid and non-abstract
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-role.md
    'jsx-a11y/aria-role': ['error', { ignoreNonDom: false }],

    // Enforce all aria-* props are valid.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-props.md
    'jsx-a11y/aria-props': 'error',

    // Enforce ARIA state and property values are valid.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-proptypes.md
    'jsx-a11y/aria-proptypes': 'error',

    // Enforce that elements that do not support ARIA roles, states, and
    // properties do not have those attributes.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-unsupported-elements.md
    'jsx-a11y/aria-unsupported-elements': 'error',

    // disallow href "#"
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/href-no-hash.md
    'jsx-a11y/href-no-hash': ['error', { components: ['a'] }],

    // Enforce that all elements that require alternative text have meaningful information
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/alt-text.md
    'jsx-a11y/alt-text': ['error', {
      elements: ['img', 'object', 'area', 'input[type="image"]'],
      img: [],
      object: [],
      area: [],
      'input[type="image"]': [],
    }],

    // Prevent img alt text from containing redundant words like "image", "picture", or "photo"
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/img-redundant-alt.md
    'jsx-a11y/img-redundant-alt': 'error',

    // require that JSX labels use "htmlFor"
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/label-has-for.md
    'jsx-a11y/label-has-for': ['error', { components: ['label'] }],

    // require that mouseover/out come with focus/blur, for keyboard-only users
    // TODO: evaluate
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/mouse-events-have-key-events.md
    'jsx-a11y/mouse-events-have-key-events': 'off',

    // Prevent use of `accessKey`
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-access-key.md
    'jsx-a11y/no-access-key': 'error',

    // require onBlur instead of onChange
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-onchange.md
    'jsx-a11y/no-onchange': 'off',

    // Elements with an interactive role and interaction handlers must be focusable
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/interactive-supports-focus.md
    'jsx-a11y/interactive-supports-focus': 'error',

    // Enforce that elements with ARIA roles must have all required attributes
    // for that role.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/role-has-required-aria-props.md
    'jsx-a11y/role-has-required-aria-props': 'error',

    // Enforce that elements with explicit or implicit roles defined contain
    // only aria-* properties supported by that role.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/role-supports-aria-props.md
    'jsx-a11y/role-supports-aria-props': 'error',

    // Enforce tabIndex value is not greater than zero.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/tabindex-no-positive.md
    'jsx-a11y/tabindex-no-positive': 'error',

    // ensure <hX> tags have content and are not aria-hidden
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/heading-has-content.md
    'jsx-a11y/heading-has-content': ['error', { components: [''] }],

    // require HTML elements to have a "lang" prop
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/html-has-lang.md
    'jsx-a11y/html-has-lang': 'error',

    // require HTML element's lang prop to be valid
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/lang.md
    'jsx-a11y/lang': 'error',

    // prevent distracting elements, like <marquee> and <blink>
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-distracting-elements.md
    'jsx-a11y/no-distracting-elements': ['error', {
      elements: ['marquee', 'blink'],
    }],

    // only allow <th> to have the "scope" attr
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/scope.md
    'jsx-a11y/scope': 'error',

    // require onClick be accompanied by onKeyUp/onKeyDown/onKeyPress
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/click-events-have-key-events.md
    // TODO: enable?
    'jsx-a11y/click-events-have-key-events': 'off',

    // Enforce that DOM elements without semantic behavior not have interaction handlers
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-static-element-interactions.md
    'jsx-a11y/no-static-element-interactions': ['error', {
      handlers: [
        'onClick',
        'onMouseDown',
        'onMouseUp',
        'onKeyPress',
        'onKeyDown',
        'onKeyUp',
      ]
    }],

    // A non-interactive element does not support event handlers (mouse and key handlers)
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-noninteractive-element-interactions.md
    'jsx-a11y/no-noninteractive-element-interactions': ['error', {
      handlers: [
        'onClick',
        'onMouseDown',
        'onMouseUp',
        'onKeyPress',
        'onKeyDown',
        'onKeyUp',
      ]
    }],

    // ensure emoji are accessible
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/accessible-emoji.md
    'jsx-a11y/accessible-emoji': 'error',

    // elements with aria-activedescendant must be tabbable
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-activedescendant-has-tabindex.md
    'jsx-a11y/aria-activedescendant-has-tabindex': 'error',

    // ensure iframe elements have a unique title
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/iframe-has-title.md
    'jsx-a11y/iframe-has-title': 'error',

    // prohibit autoFocus prop
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-autofocus.md
    'jsx-a11y/no-autofocus': ['error', { ignoreNonDOM: true }],

    // ensure HTML elements do not specify redundant ARIA roles
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-redundant-roles.md
    'jsx-a11y/no-redundant-roles': 'error',

    // media elements must have captions
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/media-has-caption.md
    'jsx-a11y/media-has-caption': ['error', {
      audio: [],
      video: [],
      track: [],
    }],

    // WAI-ARIA roles should not be used to convert an interactive element to non-interactive
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-interactive-element-to-noninteractive-role.md
    'jsx-a11y/no-interactive-element-to-noninteractive-role': ['error', {
      tr: ['none', 'presentation'],
    }],

    // WAI-ARIA roles should not be used to convert a non-interactive element to interactive
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-noninteractive-element-to-interactive-role.md
    'jsx-a11y/no-noninteractive-element-to-interactive-role': ['error', {
      ul: ['listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid'],
      ol: ['listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid'],
      li: ['menuitem', 'option', 'row', 'tab', 'treeitem'],
      table: ['grid'],
      td: ['gridcell'],
    }],

    // Tab key navigation should be limited to elements on the page that can be interacted with.
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-noninteractive-tabindex.md
    'jsx-a11y/no-noninteractive-tabindex': ['error', {
      tags: [],
      roles: ['tabpanel'],
    }],
  },
};
<|endoftext|>


<commit_before>const path = require(`path`)
const queue = require(`async/queue`)
const { cpuCoreCount } = require(`gatsby-core-utils`)
const { processFile } = require(`./process-file`)

exports.IMAGE_PROCESSING_JOB_NAME = `IMAGE_PROCESSING`

/** @typedef {import('./process-file').TransformArgs} TransformArgs */

/**
 * @typedef WorkerInput
 * @property {string} contentDigest
 * @property {{outputPath: string, args: TransformArgs[]}} operations
 * @property {object} pluginOptions
 */

/**
 * the queue concurrency is 1 as we only want to transform 1 file at a time.
 * @param {(job: WorkerInput, callback: Function) => undefined} task
 */
const q = queue(
  async ({ inputPaths, outputDir, args }) =>
    Promise.all(
      processFile(
        inputPaths[0].path,
        args.operations.map(operation => {
          return {
            outputPath: path.join(outputDir, operation.outputPath),
            args: operation.args,
          }
        }),
        args.pluginOptions
      )
    ),
  Math.max(1, cpuCoreCount() - 1)
)

/**
 * @param {{inputPaths: string[], outputDir: string, args: WorkerInput}} args
 * @return Promise
 */
exports.IMAGE_PROCESSING = ({ inputPaths, outputDir, args }) => {
  if (args.isLazy) {
    return Promise.resolve()
  }

  return new Promise((resolve, reject) => {
    q.push({ inputPaths, outputDir, args }, function (err) {
      if (err) {
        return reject(err)
      }

      return resolve()
    })
  })
}
<commit_msg>fix(gatsby-plugin-sharp): run sharp in 1 core when in gatsby worker (#33505)<commit_after>const path = require(`path`)
const queue = require(`async/queue`)
const { cpuCoreCount } = require(`gatsby-core-utils`)
const { processFile } = require(`./process-file`)

exports.IMAGE_PROCESSING_JOB_NAME = `IMAGE_PROCESSING`

/** @typedef {import('./process-file').TransformArgs} TransformArgs */

/**
 * @typedef WorkerInput
 * @property {string} contentDigest
 * @property {{outputPath: string, args: TransformArgs[]}} operations
 * @property {object} pluginOptions
 */

/**
 * the queue concurrency is 1 as we only want to transform 1 file at a time.
 * @param {(job: WorkerInput, callback: Function) => undefined} task
 */
const q = queue(
  async ({ inputPaths, outputDir, args }) =>
    Promise.all(
      processFile(
        inputPaths[0].path,
        args.operations.map(operation => {
          return {
            outputPath: path.join(outputDir, operation.outputPath),
            args: operation.args,
          }
        }),
        args.pluginOptions
      )
    ),
  // When inside query workers, we only want to use the current core
  process.env.GATSBY_WORKER_POOL_WORKER ? 1 : Math.max(1, cpuCoreCount() - 1)
)

/**
 * @param {{inputPaths: string[], outputDir: string, args: WorkerInput}} args
 * @return Promise
 */
exports.IMAGE_PROCESSING = ({ inputPaths, outputDir, args }) => {
  if (args.isLazy) {
    return Promise.resolve()
  }

  return new Promise((resolve, reject) => {
    q.push({ inputPaths, outputDir, args }, function (err) {
      if (err) {
        return reject(err)
      }

      return resolve()
    })
  })
}
<|endoftext|>


<commit_before>import angular from 'angular';
import _ from 'underscore/underscore';
import ajv from 'ajv';

let aceOptions = {
  showIntentGuides: true,
  showPrintMargin: false,
  useSoftTabs: true,
  // behavioursEnabled: true,
  // wrapBehavioursEnable: true,
  theme: 'solarized_dark'
};

export const aceJsonSchemaOptions = angular.merge({
  mode: 'json'
}, aceOptions);

export const aceJavaScriptOptions = angular.merge({
  mode: 'javascript'
}, aceOptions);

export const aceHTMLOptions = angular.merge({
  mode: 'html'
}, aceOptions);

export function validJsonDirective() {
  return {
    restrict: 'A',
    require: '?ngModel',
    link: function($scope, $el, $attrs, $ctrl) {
      if (!$ctrl) return;
      let validJsonChecker = (new ajv()).compile({});

      let assignCheckerAndValidate = function(jsonSchema) {
        try {
          validJsonChecker = (new ajv()).compile(jsonSchema);
//          console.log('using validJsonChecker from: ', jsonSchema);
        } catch (e) {
          console.log("jsonSchema compilation error in validJsonDirective -- will resort to default schema");
          validJsonChecker = (new ajv()).compile({});
        }
        $ctrl.$validate();
      };

      $attrs.$observe('jsonSchema', (jsonSchemaVarStr) => {
        assignCheckerAndValidate($scope.$eval(jsonSchemaVarStr) || {});
        $scope.$watch(jsonSchemaVarStr, function(newVal, oldVal) {
          // console.log('jsonSchema scope watch fired');
          assignCheckerAndValidate(newVal || {});
        }, true); // deep watch
      });

      $ctrl.$validators.validJson = function(modelValue, viewValue) {
        try {
          let val = validJsonChecker(eval("(" + viewValue + ")"));
//          console.log(val, validJsonChecker.errors, (new ajv().errorsText(validJsonChecker.errors)));
          return val;
        } catch(e) {
          return false;
        }
      };

    }
  };
}

export function validObjectDirective() {
  let directiveDefinitionsObject = {
    require: 'ngModel',
    link: function($scope, $el, $attrs, $ctrl) {
      $ctrl.$validators.validObject = function(modelValue, viewValue) { // object is javascript, not necessarily json
        try {
          return _.isObject(eval("(" + viewValue + ")"));
        } catch(e) {
          return false;
        }
      }
    }
  };
  return directiveDefinitionsObject;
}

export function validStateObjectDirective() {
  let directiveDefinitionsObject = {
    require: 'ngModel',
    link: function($scope, $el, $attrs, $ctrl) {
      $ctrl.$validators.validStateObject = function(modelValue, viewValue) { // object is javascript, not necessarily json
        try {
          return _.isObject(eval("(" + viewValue + ")")) || _.isNumber(eval("(" + viewValue + ")")) || _.isString(eval("(" + viewValue + ")"));
        } catch(e) {
          return false;
        }
      }
    }
  };
  return directiveDefinitionsObject;
}

export function validFunctionDirective() {
  let directiveDefinitionsObject = {
    require: 'ngModel',
    link: function($scope, $el, $attrs, $ctrl) {
      $ctrl.$validators.validFunction = function(modelValue, viewValue) { // valid js function
        if (_.isEmpty(viewValue)) return false;
        try {
          return _.isFunction(eval("(" + viewValue + ")"));
        } catch(e) {
          return false;
        }
      }
    }
  };
  return directiveDefinitionsObject;
}
<commit_msg>ace options<commit_after>import angular from 'angular';
import _ from 'underscore/underscore';
import ajv from 'ajv';

let aceOptions = {
  showIntentGuides: true,
  showPrintMargin: false,
  useSoftTabs: true,
  // behavioursEnabled: true,
  // wrapBehavioursEnable: true,
  theme: 'github'
};

export const aceJsonSchemaOptions = angular.merge({
  mode: 'javascript'
}, aceOptions);

export const aceJavaScriptOptions = angular.merge({
  mode: 'javascript'
}, aceOptions);

export const aceHTMLOptions = angular.merge({
  mode: 'html'
}, aceOptions);

export function validJsonDirective() {
  return {
    restrict: 'A',
    require: '?ngModel',
    link: function($scope, $el, $attrs, $ctrl) {
      if (!$ctrl) return;
      let validJsonChecker = (new ajv()).compile({});

      let assignCheckerAndValidate = function(jsonSchema) {
        try {
          validJsonChecker = (new ajv()).compile(jsonSchema);
//          console.log('using validJsonChecker from: ', jsonSchema);
        } catch (e) {
          console.log("jsonSchema compilation error in validJsonDirective -- will resort to default schema");
          validJsonChecker = (new ajv()).compile({});
        }
        $ctrl.$validate();
      };

      $attrs.$observe('jsonSchema', (jsonSchemaVarStr) => {
        assignCheckerAndValidate($scope.$eval(jsonSchemaVarStr) || {});
        $scope.$watch(jsonSchemaVarStr, function(newVal, oldVal) {
          // console.log('jsonSchema scope watch fired');
          assignCheckerAndValidate(newVal || {});
        }, true); // deep watch
      });

      $ctrl.$validators.validJson = function(modelValue, viewValue) {
        try {
          let val = validJsonChecker(eval("(" + viewValue + ")"));
//          console.log(val, validJsonChecker.errors, (new ajv().errorsText(validJsonChecker.errors)));
          return val;
        } catch(e) {
          return false;
        }
      };

    }
  };
}

export function validObjectDirective() {
  let directiveDefinitionsObject = {
    require: 'ngModel',
    link: function($scope, $el, $attrs, $ctrl) {
      $ctrl.$validators.validObject = function(modelValue, viewValue) { // object is javascript, not necessarily json
        try {
          return _.isObject(eval("(" + viewValue + ")"));
        } catch(e) {
          return false;
        }
      }
    }
  };
  return directiveDefinitionsObject;
}

export function validStateObjectDirective() {
  let directiveDefinitionsObject = {
    require: 'ngModel',
    link: function($scope, $el, $attrs, $ctrl) {
      $ctrl.$validators.validStateObject = function(modelValue, viewValue) { // object is javascript, not necessarily json
        try {
          return _.isObject(eval("(" + viewValue + ")")) || _.isNumber(eval("(" + viewValue + ")")) || _.isString(eval("(" + viewValue + ")"));
        } catch(e) {
          return false;
        }
      }
    }
  };
  return directiveDefinitionsObject;
}

export function validFunctionDirective() {
  let directiveDefinitionsObject = {
    require: 'ngModel',
    link: function($scope, $el, $attrs, $ctrl) {
      $ctrl.$validators.validFunction = function(modelValue, viewValue) { // valid js function
        if (_.isEmpty(viewValue)) return false;
        try {
          return _.isFunction(eval("(" + viewValue + ")"));
        } catch(e) {
          return false;
        }
      }
    }
  };
  return directiveDefinitionsObject;
}
<|endoftext|>


<commit_before>const path = require('path');
const fs = require('fs-plus');
const temp = require('temp').track();

describe('GitDiff when targeting nested repository', () => {
  let editor, editorElement, projectPath, screenUpdates;

  beforeEach(() => {
    screenUpdates = 0;
    spyOn(window, 'requestAnimationFrame').andCallFake(fn => {
      fn();
      screenUpdates++;
    });
    spyOn(window, 'cancelAnimationFrame').andCallFake(i => null);

    projectPath = temp.mkdirSync('git-diff-spec-');

    fs.copySync(path.join(__dirname, 'fixtures', 'working-dir'), projectPath);
    fs.moveSync(
      path.join(projectPath, 'git.git'),
      path.join(projectPath, '.git')
    );

    // The nested repo doesn't need to be managed by the temp module because
    // it's a part of our test environment.
    const nestedPath = path.join(projectPath, 'nested-repository');
    // Initialize the repository contents.
    fs.copySync(path.join(__dirname, 'fixtures', 'working-dir'), nestedPath);
    fs.moveSync(
      path.join(nestedPath, 'git.git'),
      path.join(nestedPath, '.git')
    );

    atom.project.setPaths([projectPath]);

    jasmine.attachToDOM(atom.workspace.getElement());

    waitsForPromise(async () => {
      await atom.workspace.open(path.join(nestedPath, 'sample.js'));
      await atom.packages.activatePackage('git-diff');
    });

    runs(() => {
      editor = atom.workspace.getActiveTextEditor();
      editorElement = atom.views.getView(editor);
    });
  });

  afterEach(() => {
    temp.cleanup();
  });

  describe('When git-diff targets a file in a nested git-repository', () => {
    /***
     * Non-hack regression prevention for nested repositories. If we know
     * that our project path contains two repositories, we can ensure that
     * git-diff is targeting the correct one by creating an artificial change
     * in the ancestor repository, which is percieved differently within the
     * child. In this case, creating a new file will not generate markers in
     * the ancestor repo, even if there are changes; but changes will be
     * marked within the child repo. So all we have to do is check if
     * markers exist and we know we're targeting the proper repository,
     * If no markers exist, we're targeting an ancestor repo.
     */
    it('uses the innermost repository', () => {
      editor.insertText('a');
      waitsFor(() => screenUpdates > 0);
      runs(() => {
        expect(editorElement.querySelectorAll('.git-line-modified').length)
          .toBe(1);
      });
    });
  });
});
<commit_msg>chore: I forgot how touchy the linter settings were.<commit_after>const path = require('path');
const fs = require('fs-plus');
const temp = require('temp').track();

describe('GitDiff when targeting nested repository', () => {
  let editor, editorElement, projectPath, screenUpdates;

  beforeEach(() => {
    screenUpdates = 0;
    spyOn(window, 'requestAnimationFrame').andCallFake(fn => {
      fn();
      screenUpdates++;
    });
    spyOn(window, 'cancelAnimationFrame').andCallFake(i => null);

    projectPath = temp.mkdirSync('git-diff-spec-');

    fs.copySync(path.join(__dirname, 'fixtures', 'working-dir'), projectPath);
    fs.moveSync(
      path.join(projectPath, 'git.git'),
      path.join(projectPath, '.git')
    );

    // The nested repo doesn't need to be managed by the temp module because
    // it's a part of our test environment.
    const nestedPath = path.join(projectPath, 'nested-repository');
    // Initialize the repository contents.
    fs.copySync(path.join(__dirname, 'fixtures', 'working-dir'), nestedPath);
    fs.moveSync(
      path.join(nestedPath, 'git.git'),
      path.join(nestedPath, '.git')
    );

    atom.project.setPaths([projectPath]);

    jasmine.attachToDOM(atom.workspace.getElement());

    waitsForPromise(async () => {
      await atom.workspace.open(path.join(nestedPath, 'sample.js'));
      await atom.packages.activatePackage('git-diff');
    });

    runs(() => {
      editor = atom.workspace.getActiveTextEditor();
      editorElement = atom.views.getView(editor);
    });
  });

  afterEach(() => {
    temp.cleanup();
  });

  describe('When git-diff targets a file in a nested git-repository', () => {
    /***
     * Non-hack regression prevention for nested repositories. If we know
     * that our project path contains two repositories, we can ensure that
     * git-diff is targeting the correct one by creating an artificial change
     * in the ancestor repository, which is percieved differently within the
     * child. In this case, creating a new file will not generate markers in
     * the ancestor repo, even if there are changes; but changes will be
     * marked within the child repo. So all we have to do is check if
     * markers exist and we know we're targeting the proper repository,
     * If no markers exist, we're targeting an ancestor repo.
     */
    it('uses the innermost repository', () => {
      editor.insertText('a');
      waitsFor(() => screenUpdates > 0);
      runs(() => {
        expect(
          editorElement.querySelectorAll('.git-line-modified').length
        ).toBe(1);
      });
    });
  });
});
<|endoftext|>


<commit_before>import constants from 'src/database/constants';
import exceptions from 'src/database/exceptions';
import SqlCommands from 'src/database/sql-related/sqlCommands';

const sqlCommands = new SqlCommands();

// dummy function to init sequence running
function initPromiseSequence() {
  return new Promise((resolve, reject) => {
    resolve(true);
  });
}

export default class dataDelete {
  static constructor() {}

  /*
   * external library not functioning so I cannot do anything here
   * link of bug: https://github.com/agershun/alasql/issues/414
   * force delete
   */
  static deleteAllEntities(databaseName) {
    return new Promise((resolve, reject) =>
      initPromiseSequence()
      .then(() =>
        sqlCommands.deleteTable(constants.ENTITIES_USER)
        .then(isSuccess => isSuccess)
        .catch(sqlErr => reject(sqlErr)))
      .then(() =>
        sqlCommands.deleteTable(constants.ENTITIES_ORGANIZATION)
        .then(isSuccess => isSuccess)
        .catch(sqlErr => reject(sqlErr)))
      .then(() =>
        sqlCommands.deleteTable(constants.ENTITIES_FILE_MANAGER)
        .then(isSuccess => isSuccess)
        .catch(sqlErr => reject(sqlErr)))
      .then(() =>
        sqlCommands.deleteTable(constants.ENTITIES_FOLDER)
        .then(isSuccess => isSuccess)
        .catch(sqlErr => reject(sqlErr)))
      .then(() => { // brute-force delete
        if (!window.indexedDB) {
          reject(exceptions.IndexedDBNotSupported);
        }
        return window.indexedDB.deleteDatabase(databaseName);
      })
      .then(() => resolve(true))
      .catch(sqlErr => reject(sqlErr)));
  }

  static deleteFile(fileId) {
    sqlCommands.deleteFile(fileId);
  }

  static deleteFolder(folderId) {
    return sqlCommands.deleteFolder(folderId);
  }
}
<commit_msg>Add return statement to deleteFile() in dataDelete.js<commit_after>import constants from 'src/database/constants';
import exceptions from 'src/database/exceptions';
import SqlCommands from 'src/database/sql-related/sqlCommands';

const sqlCommands = new SqlCommands();

// dummy function to init sequence running
function initPromiseSequence() {
  return new Promise((resolve, reject) => {
    resolve(true);
  });
}

export default class dataDelete {
  static constructor() {}

  /*
   * external library not functioning so I cannot do anything here
   * link of bug: https://github.com/agershun/alasql/issues/414
   * force delete
   */
  static deleteAllEntities(databaseName) {
    return new Promise((resolve, reject) =>
      initPromiseSequence()
      .then(() =>
        sqlCommands.deleteTable(constants.ENTITIES_USER)
        .then(isSuccess => isSuccess)
        .catch(sqlErr => reject(sqlErr)))
      .then(() =>
        sqlCommands.deleteTable(constants.ENTITIES_ORGANIZATION)
        .then(isSuccess => isSuccess)
        .catch(sqlErr => reject(sqlErr)))
      .then(() =>
        sqlCommands.deleteTable(constants.ENTITIES_FILE_MANAGER)
        .then(isSuccess => isSuccess)
        .catch(sqlErr => reject(sqlErr)))
      .then(() =>
        sqlCommands.deleteTable(constants.ENTITIES_FOLDER)
        .then(isSuccess => isSuccess)
        .catch(sqlErr => reject(sqlErr)))
      .then(() => { // brute-force delete
        if (!window.indexedDB) {
          reject(exceptions.IndexedDBNotSupported);
        }
        return window.indexedDB.deleteDatabase(databaseName);
      })
      .then(() => resolve(true))
      .catch(sqlErr => reject(sqlErr)));
  }

  static deleteFile(fileId) {
    return sqlCommands.deleteFile(fileId);
  }

  static deleteFolder(folderId) {
    return sqlCommands.deleteFolder(folderId);
  }
}
<|endoftext|>


<commit_before>'use strict';

module.exports = {
	db: 'mongodb://localhost/lt-dash-dev',
	graphiteHost: 'http://unity-ci.powerhouse.local:8090',
	memcachedHost: [ 'http://unity-ci.powerhouse.local:11211'],
	app: {
		title: 'lt-dash - Development Environment'
	},
	facebook: {
		clientID: process.env.FACEBOOK_ID || 'APP_ID',
		clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
		callbackURL: '/auth/facebook/callback'
	},
	twitter: {
		clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
		clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
		callbackURL: '/auth/twitter/callback'
	},
	google: {
		clientID: process.env.GOOGLE_ID || 'APP_ID',
		clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
		callbackURL: '/auth/google/callback'
	},
	linkedin: {
		clientID: process.env.LINKEDIN_ID || 'APP_ID',
		clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
		callbackURL: '/auth/linkedin/callback'
	},
	github: {
		clientID: process.env.GITHUB_ID || 'APP_ID',
		clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
		callbackURL: '/auth/github/callback'
	},
	mailer: {
		from: process.env.MAILER_FROM || 'MAILER_FROM',
		options: {
			service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
			auth: {
				user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
				pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
			}
		}
	}
};
<commit_msg>back to localhost<commit_after>'use strict';

module.exports = {
	db: 'mongodb://localhost/lt-dash-dev',
	graphiteHost: 'http://localhost:8090',
	memcachedHost: [ 'http://localhost:11211'],
	app: {
		title: 'lt-dash - Development Environment'
	},
	facebook: {
		clientID: process.env.FACEBOOK_ID || 'APP_ID',
		clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
		callbackURL: '/auth/facebook/callback'
	},
	twitter: {
		clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
		clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
		callbackURL: '/auth/twitter/callback'
	},
	google: {
		clientID: process.env.GOOGLE_ID || 'APP_ID',
		clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
		callbackURL: '/auth/google/callback'
	},
	linkedin: {
		clientID: process.env.LINKEDIN_ID || 'APP_ID',
		clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
		callbackURL: '/auth/linkedin/callback'
	},
	github: {
		clientID: process.env.GITHUB_ID || 'APP_ID',
		clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
		callbackURL: '/auth/github/callback'
	},
	mailer: {
		from: process.env.MAILER_FROM || 'MAILER_FROM',
		options: {
			service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
			auth: {
				user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
				pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
			}
		}
	}
};
<|endoftext|>