<commit_before>window.requestAnimFrame = (function (callback) {
  return window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequestAnimationFrame ||
  window.oRequestAnimationFrame ||
  window.msRequestAnimationFrame ||
  function (callback) {
    window.setTimeout(callback, 1000 / 60);
  }
})();

var dx = 0;
var dy = 0;

var screenWidth = 1600;
var screenHeight = 900;

var linearSpeed = 50;

var field = {
  grid: 10, width: 160, height: 90, parts: []
};

var fieldPartsCount = field.width * field.height;
var fieldPartsLeft = fieldPartsCount;

var id = getRandomInt(1000, 9999);
var connectedCombines = {};

var combine = {
  id: id,
  grain: 0,
  maxGrain: 5000,
  fuel: 300,
  maxFuel: 300,
  x: 100, y: 100, angle: 0, width: 80, height: 80,
  header: { x1: 0, y1: 0, x2: 10, y2: 10},
  back: { x1: 0, y1: 0, x2: 10, y2: 10},
  diagonal: 0,
  diagonalAngleRad: 0,
  diagonalAngleDeg: 0,
  diagonal2: 0,
  diagonal2AngleRad: 0,
  diagonal2AngleDeg: 0,
  sprite: null
};

combine.diagonal = combine.height / 2;
combine.diagonal2 = Math.sqrt(Math.pow(combine.height / 10, 2) + Math.pow(combine.width - 30, 2));
combine.diagonal2AngleRad = Math.atan2(combine.height / 10, combine.width - 30);
combine.diagonal2AngleDeg = combine.diagonal2AngleRad * 180 / Math.PI;

var canvas = document.getElementById("canvas");
canvas.width = screenWidth;
canvas.height = screenHeight;
var context = canvas.getContext("2d");

var bufferCanvas = document.createElement('canvas');
bufferCanvas.width = screenWidth;
bufferCanvas.height = screenHeight;
var bufferContext = bufferCanvas.getContext("2d");

var serverCanvas = document.createElement('canvas');
serverCanvas.width = screenWidth;
serverCanvas.height = screenHeight;
var serverContext = serverCanvas.getContext("2d");

var fieldCanvas = document.createElement('canvas');
fieldCanvas.width = screenWidth;
fieldCanvas.height = screenHeight;
var fieldContext = fieldCanvas.getContext("2d");

var spritesImage = new Image();
spritesImage.src = 'atlas.png';
spritesImage.onload = function() {
  generateField();
  renderField(fieldContext);
  var date = new Date();
  var time = date.getTime();
  animate(time);
}

/*
var socket = io();
socket.on('combine', function(combineMsg){
connectedCombines[combineMsg.id] = combineMsg;
});

socket.on('empty', function(msg){
fieldContext.drawImage(spritesImage, 20, 60, 20, 20, msg.i * field.grid, msg.j * field.grid, field.grid, field.grid);
});

socket.on('straw', function(msg){
fieldContext.drawImage(spritesImage, 40, 60, 20, 20, msg.i * field.grid, msg.j * field.grid, field.grid, field.grid);
});
*/

document.onkeydown = function (e) {
  var key = e.keyCode;
  if (key == 37) dx = -1;
  else if (key == 38) dy = -1;
  else if (key == 39) dx = 1;
  else if (key == 40) dy = 1;
  else return true;
  return false;
};

document.onkeyup = function (e) {
  var key = e.keyCode;
  if (key == 37 || key == 39) dx = 0;
  else if (key == 38 || key == 40) dy = 0;
  else return true;
  return false;
};

function generateField() {
  for (var i = 0; i < field.width; i++) {
    if (!field.parts[i]) {
      field.parts[i] = [];
    }
    for (var j = 0; j < field.height; j++) {
      field.parts[i][j] = {
        type: 0
      };
    }
  }
}

function renderField(ctx) {
  for (var i = 0; i < field.width; i++) {
    for (var j = 0; j < field.height; j++) {
      var partOfField = field.parts[i][j];
      ctx.drawImage(spritesImage, 0, 60, 20, 20, i * field.grid, j * field.grid, field.grid, field.grid);
    }
  }
}

function updateFieldView(ctx, i, j, type) {
  if (field.parts[i] === undefined || field.parts[i][j] === undefined) {
    return false;
  }
  var partOfField = field.parts[i][j];
  if (partOfField.type === 0 && type === 1) {
    partOfField.type = type;
    if (combine.grain < combine.maxGrain) {
      combine.grain += 1;
    }
    fieldPartsLeft--;
    // socket.emit('empty', {i:i, j:j});
    ctx.drawImage(spritesImage, 20, 60, 20, 20, i * field.grid, j * field.grid, field.grid, field.grid);
    return true;
  } else if (partOfField.type === 1 && type === 2) {
    partOfField.type = type;
    // socket.emit('straw', {i:i, j:j});
    ctx.drawImage(spritesImage, 40, 60, 20, 20, i * field.grid, j * field.grid, field.grid, field.grid);
    return false;
  }
}

function animate(lastTime) {

  // update
  var date = new Date();
  var time = date.getTime();
  var timeDiff = time - lastTime;
  var linearDistEachFrame = linearSpeed * timeDiff / 1000;

  if (dy !== 0) {
    if (combine.fuel > 0) {
      combine.fuel -= timeDiff * 0.001;
    } else {
      combine.fuel = 0;
    }
    if (dy == 1) {
      combine.angle += linearDistEachFrame * -dx;
    } else {
      combine.angle += linearDistEachFrame * dx;
    }
  }

  combine.x -= dy * Math.cos(combine.angle * Math.PI / 180) * linearDistEachFrame;
  combine.y -= dy * Math.sin(combine.angle * Math.PI / 180) * linearDistEachFrame;

  var diagonalAngle1 = combine.angle + 60;//combine.diagonalAngleDeg;
  var diagonalAngle2 = combine.angle - 60;//combine.diagonalAngleDeg;
  var diagonalAngleRad1 = diagonalAngle1 * Math.PI / 180;
  var diagonalAngleRad2 = diagonalAngle2 * Math.PI / 180;
  combine.header.x1 = Math.cos(diagonalAngleRad1) * combine.diagonal + combine.x;
  combine.header.y1 = Math.sin(diagonalAngleRad1) * combine.diagonal + combine.y;
  combine.header.x2 = Math.cos(diagonalAngleRad2) * combine.diagonal + combine.x;
  combine.header.y2 = Math.sin(diagonalAngleRad2) * combine.diagonal + combine.y;

  var diagonalAngleBack1 = combine.angle + combine.diagonal2AngleDeg - 180;
  var diagonalAngleBack2 = combine.angle - combine.diagonal2AngleDeg - 180;
  var diagonalAngleBackRad1 = diagonalAngleBack1 * Math.PI / 180;
  var diagonalAngleBackRad2 = diagonalAngleBack2 * Math.PI / 180;
  combine.back.x1 = Math.cos(diagonalAngleBackRad1) * combine.diagonal2 + combine.x;
  combine.back.y1 = Math.sin(diagonalAngleBackRad1) * combine.diagonal2 + combine.y;
  combine.back.x2 = Math.cos(diagonalAngleBackRad2) * combine.diagonal2 + combine.x;
  combine.back.y2 = Math.sin(diagonalAngleBackRad2) * combine.diagonal2 + combine.y;

  // socket.emit('combine', {id:combine.id, x:combine.x, y:combine.y, angle:combine.angle});

  bufferContext.clearRect(0, 0, bufferCanvas.width, bufferCanvas.height);
  renderCombine(bufferContext, combine);
  // for (var prop in connectedCombines) {
  //   if (connectedCombines.hasOwnProperty(prop)) {
  //     renderCombine(bufferContext, connectedCombines[prop]);
  //   }
  // }

  if (dy < 0) {
    if (bline(combine.header.x1, combine.header.y1, combine.header.x2, combine.header.y2, 1)) {
      bline(combine.back.x1, combine.back.y1, combine.back.x2, combine.back.y2, 2);
    }
  }

  var grainLevel = combine.grain * 100/combine.maxGrain;
  var fuelLevel = combine.fuel * 100/combine.maxFuel;
  renderBar(bufferContext, grainLevel, 10, 10);
  renderBar(bufferContext, fuelLevel, 40, 10);

  bufferContext.fillText(Math.floor((fieldPartsCount-fieldPartsLeft)/fieldPartsCount * 100) + "% done", 80, 20);
  bufferContext.fillText("grain", 9, 122);
  bufferContext.fillText("fuel", 42, 122);

  context.clearRect(0, 0, canvas.width, canvas.height);
  context.drawImage(fieldCanvas, 0, 0);
  context.drawImage(bufferCanvas, 0, 0);
  // context.drawImage(serverCanvas, 0, 0);

  lastTime = time;
  requestAnimFrame(function () {
    animate(lastTime);
  });
}

function renderBar(ctx, level, x, y) {
  ctx.save();
  ctx.fillStyle="#FFFFFF";
  ctx.fillRect(x, y, 20, 100);
  ctx.fillStyle="#68c1e7";
  ctx.fillRect(x,100 + y - level, 20, level);
  ctx.strokeStyle="#000000";
  ctx.strokeRect(x, y, 20, 100);
  ctx.restore();
}

function renderCombine(ctx, combineObj) {
  ctx.save();
  ctx.translate(combineObj.x, combineObj.y);
  ctx.rotate(combineObj.angle * Math.PI / 180);
  ctx.translate(-combine.width, -combine.height / 2);
  ctx.translate(30, 0);
  ctx.drawImage(spritesImage, 0, 0, 20, 20, 0, 0, combine.width, combine.height);
  ctx.restore();
}

function bline(x0, y0, x1, y1, type) {
  x0 = Math.floor(x0/field.grid);
  y0 = Math.floor(y0/field.grid);
  x1 = Math.floor(x1/field.grid);
  y1 = Math.floor(y1/field.grid);
  var dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
  var dy = Math.abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
  var err = (dx>dy ? dx : -dy)/2;
  var notEmptyField = false;
  while (true) {
    if (updateFieldView(fieldContext, x0, y0, type)) {
      notEmptyField = true;
    }
    if (x0 === x1 && y0 === y1) break;
    var e2 = err;
    if (e2 > -dx) { err -= dy; x0 += sx; }
    if (e2 < dy) { err += dx; y0 += sy; }
  }
  return notEmptyField;
}

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
<commit_msg>unused variable commented<commit_after>window.requestAnimFrame = (function (callback) {
  return window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequestAnimationFrame ||
  window.oRequestAnimationFrame ||
  window.msRequestAnimationFrame ||
  function (callback) {
    window.setTimeout(callback, 1000 / 60);
  }
})();

var dx = 0;
var dy = 0;

var screenWidth = 1600;
var screenHeight = 900;

var linearSpeed = 50;

var field = {
  grid: 10, width: 160, height: 90, parts: []
};

var fieldPartsCount = field.width * field.height;
var fieldPartsLeft = fieldPartsCount;

var id = getRandomInt(1000, 9999);
var connectedCombines = {};

var combine = {
  id: id,
  grain: 0,
  maxGrain: 5000,
  fuel: 300,
  maxFuel: 300,
  x: 100, y: 100, angle: 0, width: 80, height: 80,
  header: { x1: 0, y1: 0, x2: 10, y2: 10},
  back: { x1: 0, y1: 0, x2: 10, y2: 10},
  diagonal: 0,
  diagonalAngleRad: 0,
  diagonalAngleDeg: 0,
  diagonal2: 0,
  diagonal2AngleRad: 0,
  diagonal2AngleDeg: 0,
  sprite: null
};

combine.diagonal = combine.height / 2;
combine.diagonal2 = Math.sqrt(Math.pow(combine.height / 10, 2) + Math.pow(combine.width - 30, 2));
combine.diagonal2AngleRad = Math.atan2(combine.height / 10, combine.width - 30);
combine.diagonal2AngleDeg = combine.diagonal2AngleRad * 180 / Math.PI;

var canvas = document.getElementById("canvas");
canvas.width = screenWidth;
canvas.height = screenHeight;
var context = canvas.getContext("2d");

var bufferCanvas = document.createElement('canvas');
bufferCanvas.width = screenWidth;
bufferCanvas.height = screenHeight;
var bufferContext = bufferCanvas.getContext("2d");

var serverCanvas = document.createElement('canvas');
serverCanvas.width = screenWidth;
serverCanvas.height = screenHeight;
var serverContext = serverCanvas.getContext("2d");

var fieldCanvas = document.createElement('canvas');
fieldCanvas.width = screenWidth;
fieldCanvas.height = screenHeight;
var fieldContext = fieldCanvas.getContext("2d");

var spritesImage = new Image();
spritesImage.src = 'atlas.png';
spritesImage.onload = function() {
  generateField();
  renderField(fieldContext);
  var date = new Date();
  var time = date.getTime();
  animate(time);
}

/*
var socket = io();
socket.on('combine', function(combineMsg){
connectedCombines[combineMsg.id] = combineMsg;
});

socket.on('empty', function(msg){
fieldContext.drawImage(spritesImage, 20, 60, 20, 20, msg.i * field.grid, msg.j * field.grid, field.grid, field.grid);
});

socket.on('straw', function(msg){
fieldContext.drawImage(spritesImage, 40, 60, 20, 20, msg.i * field.grid, msg.j * field.grid, field.grid, field.grid);
});
*/

document.onkeydown = function (e) {
  var key = e.keyCode;
  if (key == 37) dx = -1;
  else if (key == 38) dy = -1;
  else if (key == 39) dx = 1;
  else if (key == 40) dy = 1;
  else return true;
  return false;
};

document.onkeyup = function (e) {
  var key = e.keyCode;
  if (key == 37 || key == 39) dx = 0;
  else if (key == 38 || key == 40) dy = 0;
  else return true;
  return false;
};

function generateField() {
  for (var i = 0; i < field.width; i++) {
    if (!field.parts[i]) {
      field.parts[i] = [];
    }
    for (var j = 0; j < field.height; j++) {
      field.parts[i][j] = {
        type: 0
      };
    }
  }
}

function renderField(ctx) {
  for (var i = 0; i < field.width; i++) {
    for (var j = 0; j < field.height; j++) {
      // var partOfField = field.parts[i][j];
      ctx.drawImage(spritesImage, 0, 60, 20, 20, i * field.grid, j * field.grid, field.grid, field.grid);
    }
  }
}

function updateFieldView(ctx, i, j, type) {
  if (field.parts[i] === undefined || field.parts[i][j] === undefined) {
    return false;
  }
  var partOfField = field.parts[i][j];
  if (partOfField.type === 0 && type === 1) {
    partOfField.type = type;
    if (combine.grain < combine.maxGrain) {
      combine.grain += 1;
    }
    fieldPartsLeft--;
    // socket.emit('empty', {i:i, j:j});
    ctx.drawImage(spritesImage, 20, 60, 20, 20, i * field.grid, j * field.grid, field.grid, field.grid);
    return true;
  } else if (partOfField.type === 1 && type === 2) {
    partOfField.type = type;
    // socket.emit('straw', {i:i, j:j});
    ctx.drawImage(spritesImage, 40, 60, 20, 20, i * field.grid, j * field.grid, field.grid, field.grid);
    return false;
  }
}

function animate(lastTime) {

  // update
  var date = new Date();
  var time = date.getTime();
  var timeDiff = time - lastTime;
  var linearDistEachFrame = linearSpeed * timeDiff / 1000;

  if (dy !== 0) {
    if (combine.fuel > 0) {
      combine.fuel -= timeDiff * 0.001;
    } else {
      combine.fuel = 0;
    }
    if (dy == 1) {
      combine.angle += linearDistEachFrame * -dx;
    } else {
      combine.angle += linearDistEachFrame * dx;
    }
  }

  combine.x -= dy * Math.cos(combine.angle * Math.PI / 180) * linearDistEachFrame;
  combine.y -= dy * Math.sin(combine.angle * Math.PI / 180) * linearDistEachFrame;

  var diagonalAngle1 = combine.angle + 60;//combine.diagonalAngleDeg;
  var diagonalAngle2 = combine.angle - 60;//combine.diagonalAngleDeg;
  var diagonalAngleRad1 = diagonalAngle1 * Math.PI / 180;
  var diagonalAngleRad2 = diagonalAngle2 * Math.PI / 180;
  combine.header.x1 = Math.cos(diagonalAngleRad1) * combine.diagonal + combine.x;
  combine.header.y1 = Math.sin(diagonalAngleRad1) * combine.diagonal + combine.y;
  combine.header.x2 = Math.cos(diagonalAngleRad2) * combine.diagonal + combine.x;
  combine.header.y2 = Math.sin(diagonalAngleRad2) * combine.diagonal + combine.y;

  var diagonalAngleBack1 = combine.angle + combine.diagonal2AngleDeg - 180;
  var diagonalAngleBack2 = combine.angle - combine.diagonal2AngleDeg - 180;
  var diagonalAngleBackRad1 = diagonalAngleBack1 * Math.PI / 180;
  var diagonalAngleBackRad2 = diagonalAngleBack2 * Math.PI / 180;
  combine.back.x1 = Math.cos(diagonalAngleBackRad1) * combine.diagonal2 + combine.x;
  combine.back.y1 = Math.sin(diagonalAngleBackRad1) * combine.diagonal2 + combine.y;
  combine.back.x2 = Math.cos(diagonalAngleBackRad2) * combine.diagonal2 + combine.x;
  combine.back.y2 = Math.sin(diagonalAngleBackRad2) * combine.diagonal2 + combine.y;

  // socket.emit('combine', {id:combine.id, x:combine.x, y:combine.y, angle:combine.angle});

  bufferContext.clearRect(0, 0, bufferCanvas.width, bufferCanvas.height);
  renderCombine(bufferContext, combine);
  // for (var prop in connectedCombines) {
  //   if (connectedCombines.hasOwnProperty(prop)) {
  //     renderCombine(bufferContext, connectedCombines[prop]);
  //   }
  // }

  if (dy < 0) {
    if (bline(combine.header.x1, combine.header.y1, combine.header.x2, combine.header.y2, 1)) {
      bline(combine.back.x1, combine.back.y1, combine.back.x2, combine.back.y2, 2);
    }
  }

  var grainLevel = combine.grain * 100/combine.maxGrain;
  var fuelLevel = combine.fuel * 100/combine.maxFuel;
  renderBar(bufferContext, grainLevel, 10, 10);
  renderBar(bufferContext, fuelLevel, 40, 10);

  bufferContext.fillText(Math.floor((fieldPartsCount-fieldPartsLeft)/fieldPartsCount * 100) + "% done", 80, 20);
  bufferContext.fillText("grain", 9, 122);
  bufferContext.fillText("fuel", 42, 122);

  context.clearRect(0, 0, canvas.width, canvas.height);
  context.drawImage(fieldCanvas, 0, 0);
  context.drawImage(bufferCanvas, 0, 0);
  // context.drawImage(serverCanvas, 0, 0);

  lastTime = time;
  requestAnimFrame(function () {
    animate(lastTime);
  });
}

function renderBar(ctx, level, x, y) {
  ctx.save();
  ctx.fillStyle="#FFFFFF";
  ctx.fillRect(x, y, 20, 100);
  ctx.fillStyle="#68c1e7";
  ctx.fillRect(x,100 + y - level, 20, level);
  ctx.strokeStyle="#000000";
  ctx.strokeRect(x, y, 20, 100);
  ctx.restore();
}

function renderCombine(ctx, combineObj) {
  ctx.save();
  ctx.translate(combineObj.x, combineObj.y);
  ctx.rotate(combineObj.angle * Math.PI / 180);
  ctx.translate(-combine.width, -combine.height / 2);
  ctx.translate(30, 0);
  ctx.drawImage(spritesImage, 0, 0, 20, 20, 0, 0, combine.width, combine.height);
  ctx.restore();
}

function bline(x0, y0, x1, y1, type) {
  x0 = Math.floor(x0/field.grid);
  y0 = Math.floor(y0/field.grid);
  x1 = Math.floor(x1/field.grid);
  y1 = Math.floor(y1/field.grid);
  var dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
  var dy = Math.abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
  var err = (dx>dy ? dx : -dy)/2;
  var notEmptyField = false;
  while (true) {
    if (updateFieldView(fieldContext, x0, y0, type)) {
      notEmptyField = true;
    }
    if (x0 === x1 && y0 === y1) break;
    var e2 = err;
    if (e2 > -dx) { err -= dy; x0 += sx; }
    if (e2 < dy) { err += dx; y0 += sy; }
  }
  return notEmptyField;
}

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
<|endoftext|>


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

    angular
      .module('password.reset')
      .directive('pwAlternateListItems', pwAlternateListItems);

    function pwAlternateListItems() {
        return {
            restrict: 'E',
            scope: {
                header: '@',
                methods: '=',
                icon: '@'
            },
            controller: AlternateListItemsController,
            controllerAs: 'vm',
            bindToController: true,
            templateUrl: 'reset/alternate-list-items.html'
        };
    }

    function AlternateListItemsController($routeParams, dataService,
                                          dialogService) {
        var vm = this;

        vm.send = send;

        activate();

        //////////////////////////////////////////////////////////////////

        function activate() {
        }

        function send(method) {
            dataService
              .put('reset/' + $routeParams.resetId, method)
              .then(function sent() {
                  dialogService.verify(method.value);
              }, failedToSend);

            dialogService.progress();
        }

        function failedToSend(response) {
            dialogService
              .fail('Unable to send verification.', response.data);
        }
    }
})();
<commit_msg>unnecessary whitespace<commit_after>(function () {
    'use strict';

    angular
      .module('password.reset')
      .directive('pwAlternateListItems', pwAlternateListItems);

    function pwAlternateListItems() {
        return {
            restrict: 'E',
            scope: {
                header: '@',
                methods: '=',
                icon: '@'
            },
            controller: AlternateListItemsController,
            controllerAs: 'vm',
            bindToController: true,
            templateUrl: 'reset/alternate-list-items.html'
        };
    }

    function AlternateListItemsController($routeParams, dataService,
                                          dialogService) {
        var vm = this;

        vm.send = send;

        activate();

        //////////////////////////////////////////////////////////////////

        function activate() {
        }

        function send(method) {
            dataService
              .put('reset/' + $routeParams.resetId, method)
              .then(function sent() {
                  dialogService.verify(method.value);
              }, failedToSend);

            dialogService.progress();
        }

        function failedToSend(response) {
            dialogService
              .fail('Unable to send verification.', response.data);
        }
    }
})();
<|endoftext|>


<commit_before>define (
	[
		'jquery',
		'sprintf',
		'js-cookie'
	],
	function (
		jquery,
		sprintf,
		Cookies
	) {
		var Translate = function (options) {

			this.defaultLanguage = 'en';
			this.language = 'en';
			this.translations = {};
			this.cookie = 'language';

		};

		var p = Translate.prototype;

		var args;
		var i;
		var tmp;

		p.initialize = function (options)
		{
			if (typeof (options) === 'undefined') {
				options = {};
			}

			this.defaultLanguage = options.defaultLanguage || 'en';
			this.tracker = options.tracker || null;
			this.cookie = options.cookie || 'language';

			this.language = this.getLanguage ();

			var deferred = jquery.Deferred();
			this.deferred = deferred;

			$.getJSON ('locales/languages.json', function (data) {

				this.translations = [];
				this.tryLoadTranslations ([ this.language, this.language.substr (0, 2) ]);

			}.bind (this));

			return deferred;

		};

		/**
		 * Get current language
		 * @returns string
		 */
		p.getLanguage = function ()
		{
			var language;

			if (this.cookie && Cookies.get (this.cookie)) {
				language = Cookies.get(this.cookie);
			}
			else if (typeof (navigator.language) !== 'undefined') {
				language = navigator.language;
			}
			else
				language = this.defaultLanguage;

			return language;
		};

		/**
		 * Go trough all provided translations and stop as soon
		 * as we have succesfully loaded one.
		 * @param locales
		 */
		p.tryLoadTranslations = function (locales) {

			var locale = locales.shift ();

			$.getJSON("locales/"+ locale +".json", function(json) {

				this.setTranslation (json);

			}.bind(this)).fail (function () {

				if (locales.length > 0) {
					this.tryLoadTranslations (locales);
				}
				else {
					this.noTranslation ();
				}

			}.bind (this));

		};

		p.setTranslation = function (bundle)
		{
			this.translations = bundle;
			this.deferred.resolve ();
		};

		p.noTranslation = function()
		{
			this.deferred.resolve ();
		};

		p.translate = function (string)
		{
			if(string === "")
				return string;

			args = [];
			for (i = 0; i < arguments.length; i ++) {
				args.push (arguments[i]);
			}

			string = args.shift ();

			// Also check first variable
			tmp = null;

			if (args.length > 0) {
				tmp = this.getArgumentNumericValue(args[0]);
			}

			if (tmp !== null) {
				this.track (string, true);
				string = this.getTranslation (string, tmp);
			}
			else {
				this.track (string, false);
				string = this.getTranslation (string);
			}

			return sprintf.vsprintf (string, args);
		};

		p.track = function (string, isPluralizable)
		{
			var img = new Image();
			img.src = sprintf.vsprintf (
				this.tracker,
				[
					encodeURIComponent(string),
					isPluralizable ? 1 : 0
				]
			);
		};

		p.getPluralized = function (options, amount)
		{
			if (amount === 0 || amount > 1) {
				if (typeof (options.plural) !== 'undefined') {
					return options.plural;
				}
			}

			else {
				if (typeof (options.single) !== 'undefined') {
					return options.single;
				}
			}

			// Not found? Return first value.
			//noinspection LoopStatementThatDoesntLoopJS
			for (var key in options) {
				return options[key];
			}
		};

		p.getTranslation = function (string, amount)
		{
			if (typeof (this.translations.resources) === 'undefined') {
				return string;
			}

			var value = this.translations.resources[string];

			if (typeof (value) === 'undefined') {
				return string;
			}

			else if (typeof (value) === 'object') {
				return this.getPluralized (value, amount);
			}

			else {
				return value;
			}
		};

		p.changeLanguage = function (language)
		{
			Cookies.set (this.cookie, language, { expires: 365 });
		};

		p.getArgumentNumericValue = function (argument)
		{
			if ($.isNumeric (argument)) {
				return parseFloat (argument);
			}
			return null;
		};

		return Translate;
	}
);<commit_msg>Base structure working. That's good enough for now.<commit_after>define (
	[
		'jquery',
		'sprintf',
		'js-cookie'
	],
	function (
		jquery,
		sprintf,
		Cookies
	) {
		var Translate = function (options) {

			this.defaultLanguage = 'en';
			this.language = 'en';
			this.translations = {};
			this.cookie = 'language';

		};

		var p = Translate.prototype;

		var args;
		var i;
		var tmp;

		p.initialize = function (options)
		{
			if (typeof (options) === 'undefined') {
				options = {};
			}

			this.defaultLanguage = options.defaultLanguage || 'en';
			this.tracker = options.tracker || null;
			this.cookie = options.cookie || 'language';

			this.language = this.getLanguage ();

			var deferred = jquery.Deferred();
			this.deferred = deferred;

			$.getJSON ('locales/languages.json')
				.done (function (data) {
					this.translations = [];
					this.tryLoadTranslations ([ this.language, this.language.substr (0, 2) ]);
					}.bind (this)
				)

				.fail (function () {
					deferred.resolve ();
				}.bind (this));

			return deferred;

		};

		/**
		 * Get current language
		 * @returns string
		 */
		p.getLanguage = function ()
		{
			var language;

			if (this.cookie && Cookies.get (this.cookie)) {
				language = Cookies.get(this.cookie);
			}
			else if (typeof (navigator.language) !== 'undefined') {
				language = navigator.language;
			}
			else
				language = this.defaultLanguage;

			return language;
		};

		/**
		 * Go trough all provided translations and stop as soon
		 * as we have succesfully loaded one.
		 * @param locales
		 */
		p.tryLoadTranslations = function (locales) {

			var locale = locales.shift ();

			$.getJSON("locales/"+ locale +".json", function(json) {

				this.setTranslation (json);

			}.bind(this)).fail (function () {

				if (locales.length > 0) {
					this.tryLoadTranslations (locales);
				}
				else {
					this.noTranslation ();
				}

			}.bind (this));

		};

		p.setTranslation = function (bundle)
		{
			this.translations = bundle;
			this.deferred.resolve ();
		};

		p.noTranslation = function()
		{
			this.deferred.resolve ();
		};

		p.translate = function (string)
		{
			if(string === "")
				return string;

			args = [];
			for (i = 0; i < arguments.length; i ++) {
				args.push (arguments[i]);
			}

			string = args.shift ();

			// Also check first variable
			tmp = null;

			if (args.length > 0) {
				tmp = this.getArgumentNumericValue(args[0]);
			}

			if (tmp !== null) {
				this.track (string, true);
				string = this.getTranslation (string, tmp);
			}
			else {
				this.track (string, false);
				string = this.getTranslation (string);
			}

			return sprintf.vsprintf (string, args);
		};

		p.track = function (string, isPluralizable)
		{
			var img = new Image();
			img.src = sprintf.vsprintf (
				this.tracker,
				[
					encodeURIComponent(string),
					isPluralizable ? 1 : 0
				]
			);
		};

		p.getPluralized = function (options, amount)
		{
			if (amount === 0 || amount > 1) {
				if (typeof (options.plural) !== 'undefined') {
					return options.plural;
				}
			}

			else {
				if (typeof (options.single) !== 'undefined') {
					return options.single;
				}
			}

			// Not found? Return first value.
			//noinspection LoopStatementThatDoesntLoopJS
			for (var key in options) {
				return options[key];
			}
		};

		p.getTranslation = function (string, amount)
		{
			if (typeof (this.translations.resources) === 'undefined') {
				return string;
			}

			var value = this.translations.resources[string];

			if (typeof (value) === 'undefined') {
				return string;
			}

			else if (typeof (value) === 'object') {
				return this.getPluralized (value, amount);
			}

			else {
				return value;
			}
		};

		p.changeLanguage = function (language)
		{
			Cookies.set (this.cookie, language, { expires: 365 });
		};

		p.getArgumentNumericValue = function (argument)
		{
			if ($.isNumeric (argument)) {
				return parseFloat (argument);
			}
			return null;
		};

		return Translate;
	}
);<|endoftext|>


<commit_before>/*setcompatmode.js ver0.0.4*/
/*
setcompatmode.js

Copyright (c) 2015 prprhyt

This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/

var patharray = new Array(2);
for(var i=0;i<2;i++){
  patharray[i]= new Array();
}
var fso = new ActiveXObject("Scripting.FileSystemObject");

var objApl = WScript.CreateObject("Shell.Application");

var title = "Select the Folder";
var option = 0x0050;
var root = "";
var folder = objApl.BrowseForFolder(0, title, option, root);

if (folder == null) {
    WScript.Echo("You must select the folder");
    WScript.Quit();//quit
}else{

  WScript.echo(folder.Self.Path);
}
var ScriptFolderPath = String(WScript.ScriptFullName).replace(WScript.ScriptName,"");

var WshShell = WScript.CreateObject("WScript.Shell");
var writevalue = "HKCU\\Software\\microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced";

var Origin_FolderOptReg = new Array();
Origin_FolderOptReg[0]=WshShell.RegRead(writevalue+"\\Hidden");//元の状態を一時保存
Origin_FolderOptReg[1]=WshShell.RegRead(writevalue+"\\HideFileExt");

//GetExtensionNameを正常に利用するには拡張子等の表示を有効にする必要あり
WshShell.RegWrite(writevalue+"\\Hidden", 0x01, "REG_DWORD");//隠しファイルとフォルダ表示
WshShell.RegWrite(writevalue+"\\HideFileExt", 0x00, "REG_DWORD");//拡張子表示
WshShell.RegWrite("HKCU\\Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers\\","","REG_SZ");//キー未作成であっても対応できるように該当キーを作成
WshShell.Run( "RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters ",1,true);

var objFolder = objApl.NameSpace(folder.Self.Path);

var objFolderItems = objFolder.Items();

var exn_array =["exe","msi"];//検索対象の拡張子
var value_array=["~ WINXPSP3","~ MSIAUTO"];//互換モードの要素

if(exn_array.length!=value_array.length){
    WScript.Echo("Different number of ExtensionName array and Value array");
    WScript.Quit();//quit
}

GetFilePathFromExtensionName(objFolderItems,exn_array);
var files_sum=0;
for(var i=0;i<exn_array.length;i++){
  files_sum += patharray[i].length;
}

if(wmi_addComatinfo(patharray,value_array)!=0){
   WScript.echo("error");
 }else{
   WScript.echo("End:"+folder.Self.Path+"\n"+files_sum+"files complete.");
}

//WshShell.RegWrite(writevalue+"\\Hidden", Origin_FolderOptReg[0], "REG_DWORD");
//WshShell.RegWrite(writevalue+"\\HideFileExt", Origin_FolderOptReg[1], "REG_DWORD");

objFolderItems = null;
objFolder = null;
objApl = null;

function wmi_addComatinfo(add_name ,add_value){//Nameに\\を含む場合、RegWriteが有効でないためWMIを利用する
  var AppCompatFlagsRegistryKey = "Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers";
  var name;
  var Data;
  var result=0;
  var objRegistry = GetObject("winmgmts://./root/default:StdRegProv");
    for(var i=0;i<add_value.length;i++){
      Data = add_value[i];
      for(var j=0;j<add_name[i].length;j++){
        name=add_name[i][j];
        try {
          result = objRegistry.SetStringValue(0x80000001 /*HKCU*/, AppCompatFlagsRegistryKey, name, Data);
        } catch (e) {
           result++;
        }
      }
    }
  return result;
}

function GetFilePathFromExtensionName(tmpFolderItems , exn_array_s) {
    var objFolderItemsB;
    var objItem;

    for (var i=0;i<tmpFolderItems.Count;i++){

        objItem = tmpFolderItems.Item(i);
        if (objItem.IsFolder==true) {
           objFolderItemsB = objItem.GetFolder;
           GetFilePathFromExtensionName(objFolderItemsB.Items(),exn_array_s);
        } else {
         for(var j=0;j<exn_array_s.length;j++){
           if(fso.GetExtensionName(objItem.Name)==exn_array_s[j].toLowerCase()||fso.GetExtensionName(objItem.Name)==exn_array_s[j].toUpperCase()){
            patharray[j][patharray[j].length]=objItem.Path;
           }
         }
        }

    }

    objItem = null;
    objFolderItemsB = null;

}
<commit_msg>Update to version 0.0.5<commit_after>/*setcompatmode.js ver0.0.5*/
/*
setcompatmode.js

Copyright (c) 2015 prprhyt

This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/

var patharray = new Array(2);
for(var i=0;i<2;i++){
  patharray[i]= new Array();
}
var fso = new ActiveXObject("Scripting.FileSystemObject");

var objApl = WScript.CreateObject("Shell.Application");

var title = "Select the Folder";
var option = 0x0050;
var root = "";
var folder = objApl.BrowseForFolder(0, title, option, root);

if (folder == null) {
    WScript.Echo("You must select the folder");
    WScript.Quit();//quit
}
var ScriptFolderPath = String(WScript.ScriptFullName).replace(WScript.ScriptName,"");

var WshShell = WScript.CreateObject("WScript.Shell");
var writevalue = "HKCU\\Software\\microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced";

var Origin_FolderOptReg = new Array();
Origin_FolderOptReg[0]=WshShell.RegRead(writevalue+"\\Hidden");//元の状態を一時保存
Origin_FolderOptReg[1]=WshShell.RegRead(writevalue+"\\HideFileExt");

//GetExtensionNameを正常に利用するには拡張子等の表示を有効にする必要あり
WshShell.RegWrite(writevalue+"\\Hidden", 0x01, "REG_DWORD");//隠しファイルとフォルダ表示
WshShell.RegWrite(writevalue+"\\HideFileExt", 0x00, "REG_DWORD");//拡張子表示
WshShell.RegWrite("HKCU\\Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers\\","","REG_SZ");//キー未作成であっても対応できるように該当キーを作成
WshShell.Run( "RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters ",1,true);

var objFolder = objApl.NameSpace(folder.Self.Path);

var objFolderItems = objFolder.Items();

var exn_array =["exe","msi"];//検索対象の拡張子
var value_array=["~ WINXPSP3","~ MSIAUTO"];//互換モードの要素

if(exn_array.length!=value_array.length){
    WScript.Echo("Different number of ExtensionName array and Value array");
    WScript.Quit();//quit
}

GetFilePathFromExtensionName(objFolderItems,exn_array);
var files_sum=0;
for(var i=0;i<exn_array.length;i++){
  files_sum += patharray[i].length;
}

if(wmi_addComatinfo(patharray,value_array)!=0){
   WScript.echo("error");
 }else{
   WScript.echo("End:"+folder.Self.Path+"\n"+files_sum+"files complete.");
}

//WshShell.RegWrite(writevalue+"\\Hidden", Origin_FolderOptReg[0], "REG_DWORD");
//WshShell.RegWrite(writevalue+"\\HideFileExt", Origin_FolderOptReg[1], "REG_DWORD");

objFolderItems = null;
objFolder = null;
objApl = null;

function wmi_addComatinfo(add_name ,add_value){//Nameに\\を含む場合、RegWriteが有効でないためWMIを利用する
  var AppCompatFlagsRegistryKey = "Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers";
  var name;
  var Data;
  var result=0;
  var objRegistry = GetObject("winmgmts://./root/default:StdRegProv");
    for(var i=0;i<add_value.length;i++){
      Data = add_value[i];
      for(var j=0;j<add_name[i].length;j++){
        name=add_name[i][j];
        try {
          result = objRegistry.SetStringValue(0x80000001 /*HKCU*/, AppCompatFlagsRegistryKey, name, Data);
        } catch (e) {
           result++;
        }
      }
    }
  return result;
}

function GetFilePathFromExtensionName(tmpFolderItems , exn_array_s) {
    var objFolderItemsB;
    var objItem;

    for (var i=0;i<tmpFolderItems.Count;i++){

        objItem = tmpFolderItems.Item(i);
        if (objItem.IsFolder==true) {
           objFolderItemsB = objItem.GetFolder;
           GetFilePathFromExtensionName(objFolderItemsB.Items(),exn_array_s);
        } else {
         for(var j=0;j<exn_array_s.length;j++){
           if(fso.GetExtensionName(objItem.Name)==exn_array_s[j].toLowerCase()||fso.GetExtensionName(objItem.Name)==exn_array_s[j].toUpperCase()){
            patharray[j][patharray[j].length]=objItem.Path;
           }
         }
        }

    }

    objItem = null;
    objFolderItemsB = null;

}
<|endoftext|>


<commit_before>/*setcompatmode.js ver0.0.3*/

var patharray = new Array(2);
for(var i=0;i<2;i++){
  patharray[i]= new Array();
}
var fso = new ActiveXObject("Scripting.FileSystemObject");

var objApl = WScript.CreateObject("Shell.Application");

var title = "Select the Folder";
var option = 0x0050;
var root = "";
var folder = objApl.BrowseForFolder(0, title, option, root);

if (folder == null) {
    WScript.Echo("You must select the folder");
    WScript.Quit();//quit
}else{

  WScript.echo(folder.Self.Path);
}
var ScriptFolderPath = String(WScript.ScriptFullName).replace(WScript.ScriptName,"");

var WshShell = WScript.CreateObject("WScript.Shell");
var writevalue = "HKCU\\Software\\microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced";

var Origin_FolderOptReg = new Array();
Origin_FolderOptReg[0]=WshShell.RegRead(writevalue+"\\Hidden");//元の状態を一時保存
Origin_FolderOptReg[1]=WshShell.RegRead(writevalue+"\\HideFileExt");

//GetExtensionNameを正常に利用するには拡張子等の表示を有効にする必要あり
WshShell.RegWrite(writevalue+"\\Hidden", 0x01, "REG_DWORD");//隠しファイルとフォルダ表示
WshShell.RegWrite(writevalue+"\\HideFileExt", 0x00, "REG_DWORD");//拡張子表示
WshShell.RegWrite("HKCU\\Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers\\","","REG_SZ");//キー未作成であっても対応できるように該当キーを作成
WshShell.Run( "RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters ",1,true);

var objFolder = objApl.NameSpace(folder.Self.Path);

var objFolderItems = objFolder.Items();

var exn_array =["exe","msi"];//検索対象の拡張子
var value_array=["~ WINXPSP3","~ MSIAUTO"];//互換モードの要素

if(exn_array.length!=value_array.length){
    WScript.Echo("Different number of ExtensionName array and Value array");
    WScript.Quit();//quit
}

GetFilePathFromExtensionName(objFolderItems,exn_array);
var files_sum=0;
for(var i=0;i<exn_array.length;i++){
  files_sum += patharray[i].length;
}

if(wmi_addComatinfo(patharray,value_array)!=0){
   WScript.echo("error");
 }else{
   WScript.echo("End:"+folder.Self.Path+"\n"+files_sum+"files complete.");
}

//WshShell.RegWrite(writevalue+"\\Hidden", Origin_FolderOptReg[0], "REG_DWORD");
//WshShell.RegWrite(writevalue+"\\HideFileExt", Origin_FolderOptReg[1], "REG_DWORD");

objFolderItems = null;
objFolder = null;
objApl = null;

function wmi_addComatinfo(add_name ,add_value){//Nameに\\を含む場合、RegWriteが有効でないためWMIを利用する
  var AppCompatFlagsRegistryKey = "Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers";
  var name;
  var Data;
  var result=0;
  var objRegistry = GetObject("winmgmts://./root/default:StdRegProv");
    for(var i=0;i<add_value.length;i++){
      Data = add_value[i];
      for(var j=0;j<add_name[i].length;j++){
        name=add_name[i][j];
        try {
          result = objRegistry.SetStringValue(0x80000001 /*HKCU*/, AppCompatFlagsRegistryKey, name, Data);
        } catch (e) {
           result++;
        }
      }
    }
  return result;
}

function GetFilePathFromExtensionName(tmpFolderItems , exn_array_s) {
    var objFolderItemsB;
    var objItem;

    for (var i=0;i<tmpFolderItems.Count;i++){

        objItem = tmpFolderItems.Item(i);
        if (objItem.IsFolder==true) {
           objFolderItemsB = objItem.GetFolder;
           GetFilePathFromExtensionName(objFolderItemsB.Items(),exn_array);
        } else {
         for(var j=0;j<exn_array_s.length;j++){
           if(fso.GetExtensionName(objItem.Name)==exn_array_s[j].toLowerCase()||fso.GetExtensionName(objItem.Name)==exn_array_s[j].toUpperCase()){
            patharray[j][patharray[j].length]=objItem.Path;
           }
         }
        }

    }

    objItem = null;
    objFolderItemsB = null;

}
<commit_msg>add mit license in code (version 0.0.3)<commit_after>/*setcompatmode.js ver0.0.3*/
/*
setcompatmode.js

Copyright (c) 2015 prprhyt

This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/

var patharray = new Array(2);
for(var i=0;i<2;i++){
  patharray[i]= new Array();
}
var fso = new ActiveXObject("Scripting.FileSystemObject");

var objApl = WScript.CreateObject("Shell.Application");

var title = "Select the Folder";
var option = 0x0050;
var root = "";
var folder = objApl.BrowseForFolder(0, title, option, root);

if (folder == null) {
    WScript.Echo("You must select the folder");
    WScript.Quit();//quit
}else{

  WScript.echo(folder.Self.Path);
}
var ScriptFolderPath = String(WScript.ScriptFullName).replace(WScript.ScriptName,"");

var WshShell = WScript.CreateObject("WScript.Shell");
var writevalue = "HKCU\\Software\\microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced";

var Origin_FolderOptReg = new Array();
Origin_FolderOptReg[0]=WshShell.RegRead(writevalue+"\\Hidden");//元の状態を一時保存
Origin_FolderOptReg[1]=WshShell.RegRead(writevalue+"\\HideFileExt");

//GetExtensionNameを正常に利用するには拡張子等の表示を有効にする必要あり
WshShell.RegWrite(writevalue+"\\Hidden", 0x01, "REG_DWORD");//隠しファイルとフォルダ表示
WshShell.RegWrite(writevalue+"\\HideFileExt", 0x00, "REG_DWORD");//拡張子表示
WshShell.RegWrite("HKCU\\Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers\\","","REG_SZ");//キー未作成であっても対応できるように該当キーを作成
WshShell.Run( "RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters ",1,true);

var objFolder = objApl.NameSpace(folder.Self.Path);

var objFolderItems = objFolder.Items();

var exn_array =["exe","msi"];//検索対象の拡張子
var value_array=["~ WINXPSP3","~ MSIAUTO"];//互換モードの要素

if(exn_array.length!=value_array.length){
    WScript.Echo("Different number of ExtensionName array and Value array");
    WScript.Quit();//quit
}

GetFilePathFromExtensionName(objFolderItems,exn_array);
var files_sum=0;
for(var i=0;i<exn_array.length;i++){
  files_sum += patharray[i].length;
}

if(wmi_addComatinfo(patharray,value_array)!=0){
   WScript.echo("error");
 }else{
   WScript.echo("End:"+folder.Self.Path+"\n"+files_sum+"files complete.");
}

//WshShell.RegWrite(writevalue+"\\Hidden", Origin_FolderOptReg[0], "REG_DWORD");
//WshShell.RegWrite(writevalue+"\\HideFileExt", Origin_FolderOptReg[1], "REG_DWORD");

objFolderItems = null;
objFolder = null;
objApl = null;

function wmi_addComatinfo(add_name ,add_value){//Nameに\\を含む場合、RegWriteが有効でないためWMIを利用する
  var AppCompatFlagsRegistryKey = "Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers";
  var name;
  var Data;
  var result=0;
  var objRegistry = GetObject("winmgmts://./root/default:StdRegProv");
    for(var i=0;i<add_value.length;i++){
      Data = add_value[i];
      for(var j=0;j<add_name[i].length;j++){
        name=add_name[i][j];
        try {
          result = objRegistry.SetStringValue(0x80000001 /*HKCU*/, AppCompatFlagsRegistryKey, name, Data);
        } catch (e) {
           result++;
        }
      }
    }
  return result;
}

function GetFilePathFromExtensionName(tmpFolderItems , exn_array_s) {
    var objFolderItemsB;
    var objItem;

    for (var i=0;i<tmpFolderItems.Count;i++){

        objItem = tmpFolderItems.Item(i);
        if (objItem.IsFolder==true) {
           objFolderItemsB = objItem.GetFolder;
           GetFilePathFromExtensionName(objFolderItemsB.Items(),exn_array);
        } else {
         for(var j=0;j<exn_array_s.length;j++){
           if(fso.GetExtensionName(objItem.Name)==exn_array_s[j].toLowerCase()||fso.GetExtensionName(objItem.Name)==exn_array_s[j].toUpperCase()){
            patharray[j][patharray[j].length]=objItem.Path;
           }
         }
        }

    }

    objItem = null;
    objFolderItemsB = null;

}
<|endoftext|>


<commit_before>(function($){
	if(jQuery.browser.rhino){
        print("\nWARNING! The Fixture Plugin Is Included!!!!!!\n")
    }
	//
	//  fixture =
	//    true
	//    "some name"
	//    function(){ ... }
	//  default ...
	//    true ... all are on
	//    false ... all are off ... just don't include
	//    function ... uses this function to convert true, some name
	//

	var ajax = $.ajax;
/**
 *  @class jQuery
 */
// break
    /**
     * Translates an $.ajax settings into a url.  Replace this function if you want to change how
     * fixtures get looked up.
     * @param {Object} settings
     * @return {String} the url that will be used for the fixture
     */
	$.fixture = function(settings){
		var url = settings.url, match, left, right;
        url = url.replace(/%2F/g,"~").replace(/%20/g,"_");

		if ( settings.data && settings.processData && typeof settings.data !== "string" )
			settings.data = jQuery.param(settings.data);

        if(settings.data && settings.type.toLowerCase() == "get")
            url += ($.String.steal(url,'?') ? '&' : '?') + settings.data

        match = url.match(/^(?:https?:\/\/[^\/]*)?\/?([^\?]*)\??(.*)?/);
		left = match[1];

		right = settings.type ? '.'+settings.type.toLowerCase() : '.post';
		if(match[2]){
			left += '/';
			right = match[2].replace(/\#|&/g,'-').replace(/\//g, '~')+right;
		}
//		return left+encodeURIComponent( right);
		return left + right;

	}
// break
/**
 * Adds the fixture option to settings. If present, loads from fixture location instead
 * of provided url.  This is useful for simulating ajax responses before the server is done.
 * @param {Object} settings
 */
	$.ajax = function(settings){
		var func = $.fixture
		if (!settings.fixture) {
			return ajax.apply($, arguments);
		}
		else if (typeof settings.fixture == "string") {
			if($.fixture[settings.fixture])
				settings.fixture = $.fixture[settings.fixture]
			else{
//				settings.url = steal.root.join('test/fixtures/' + settings.fixture)
				var appName = window.location.href.match(/^((http[s]?|file):\/)?\/?([^:\/\s]+)(:\d+)?\/(\w+)*\//)[5];
				settings.url = '/' + appName + 'test/fixtures/' + settings.fixture;
				settings.type = "GET"
				return ajax(settings);
			}
		}
		if (typeof settings.fixture == "function") {

                setTimeout(function(){
                    if(settings.success)
                        settings.success.apply(null, settings.fixture(settings, "success")  )
                    if(settings.complete)
                        settings.complete.apply(null, settings.fixture(settings, "complete")  )
                }, 13)

            return;
		}
		var settings = jQuery.extend(true, settings, jQuery.extend(true, {}, jQuery.ajaxSettings, settings));

//		settings.url = steal.root.join('test/fixtures/'+func(settings)); // convert settings
		var appName = window.location.href.match(/^((http[s]?|file):\/)?\/?([^:\/\s]+)(:\d+)?\/(\w+)*\//)[5];
		settings.url = '/' + appName + '/test/fixtures/'+func(settings); // convert settings
		settings.data = null;
		settings.type = 'GET';
		return ajax(settings);
	}

	var get = $.get;
	/**
	 * Adds a fixture param.
	 * @param {Object} url
	 * @param {Object} data
	 * @param {Object} callback
	 * @param {Object} type
	 * @param {Object} fixture
	 */
	$.get = function( url, data, callback, type, fixture ){
		// shift arguments if data argument was ommited
		if ( jQuery.isFunction( data ) ) {
			callback = data;
			data = null;
		}

		return jQuery.ajax({
			type: "GET",
			url: url,
			data: data,
			success: callback,
			dataType: type,
			fixture : fixture
		});
	}
	var post = $.post;
	/**
	 * Adds a fixture param.
	 * @param {Object} url
	 * @param {Object} data
	 * @param {Object} callback
	 * @param {Object} type
	 * @param {Object} fixture
	 */
	$.post= function( url, data, callback, type, fixture ) {
		if ( jQuery.isFunction( data ) ) {
			callback = data;
			data = {};
		}

		return jQuery.ajax({
			type: "POST",
			url: url,
			data: data,
			success: callback,
			dataType: type,
			fixture : fixture
		});
	}

	$.extend($.fixture, {
        "-restUpdate": function(settings,cbType){
            switch(cbType){
                case "success":
                    return [jQuery.extend({id: parseInt(settings.url)}, settings.data)]
                case "complete":
                    return [{ responseText: ""}, "success"]
            }
        },
        "-restDestroy" : function(){return [true]},
        "-restCreate" : function(settings, cbType){
            switch(cbType){
                case "success":
                    return [{id: parseInt(Math.random()*1000)}];
                case "complete":
                    return [{
                                responseText: "",
                                getResponseHeader: function(){ return "/blah/"+parseInt(Math.random()*1000) }
                            }, "success"]
            }

        }
    })

/**
 * @page fixtures Fixtures
 * @tag ajax
 *
Fixtures

 * Fixtures simulate AJAX responses.  They are a great
 * technique to use when you want to develop JavaScript
 * independantly of the backend.  This page provides a brief walkthrough
 * of how to create and use fixtures.
 *
Basic Examples

@codestart
//Named Fixture
$.ajax({url: "task.json",
  dataType: "json",
  type: "get",
  fixture: "first.json", //finds fixture in test/fixtures/first.json
  success: myCallback});

//Calculated Fixture
$.ajax({url: "tasks",
  data : {id: 5},
  type: "get",
  fixture: true, //finds fixture in test/tasks/id=5.get
  success: myCallback })
@codeend

 *
Creating Fixtures

 *
Fixtures sit in your test/fixtures
 * folder.  There are 2 types of fixtures:

 *

 *
Calculated - the name of the fixture is calculated from the url and data passed to
 *       $.ajax.

 *
Named - you give the name of the fixture.

 *

 *
Using Fixturesa

 * To enable fixtures, you have to include the dom/fixtures plugin.  To disable fixtures,
 * simply remove the plugin.
 * To make a request use a fixture,
 * [jQuery.ajax]
 * [jQuery.get]
 * [jQuery.post]
 */

})(jQuery);

<commit_msg>Restored fixtures absolute path for test folder.<commit_after>(function($){
	if(jQuery.browser.rhino){
        print("\nWARNING! The Fixture Plugin Is Included!!!!!!\n")
    }
	//
	//  fixture =
	//    true
	//    "some name"
	//    function(){ ... }
	//  default ...
	//    true ... all are on
	//    false ... all are off ... just don't include
	//    function ... uses this function to convert true, some name
	//

	var ajax = $.ajax;
/**
 *  @class jQuery
 */
// break
    /**
     * Translates an $.ajax settings into a url.  Replace this function if you want to change how
     * fixtures get looked up.
     * @param {Object} settings
     * @return {String} the url that will be used for the fixture
     */
	$.fixture = function(settings){
		var url = settings.url, match, left, right;
        url = url.replace(/%2F/g,"~").replace(/%20/g,"_");

		if ( settings.data && settings.processData && typeof settings.data !== "string" )
			settings.data = jQuery.param(settings.data);

        if(settings.data && settings.type.toLowerCase() == "get")
            url += ($.String.steal(url,'?') ? '&' : '?') + settings.data

        match = url.match(/^(?:https?:\/\/[^\/]*)?\/?([^\?]*)\??(.*)?/);
		left = match[1];

		right = settings.type ? '.'+settings.type.toLowerCase() : '.post';
		if(match[2]){
			left += '/';
			right = match[2].replace(/\#|&/g,'-').replace(/\//g, '~')+right;
		}
//		return left+encodeURIComponent( right);
        return left + right;

	}
// break
/**
 * Adds the fixture option to settings. If present, loads from fixture location instead
 * of provided url.  This is useful for simulating ajax responses before the server is done.
 * @param {Object} settings
 */
	$.ajax = function(settings){
		var func = $.fixture
		if (!settings.fixture) {
			return ajax.apply($, arguments);
		}
		else if (typeof settings.fixture == "string") {
			if($.fixture[settings.fixture])
				settings.fixture = $.fixture[settings.fixture]
			else{
				settings.url = steal.root.join('test/fixtures/' + settings.fixture)
				settings.type = "GET"
				return ajax(settings);
			}
		}
		if (typeof settings.fixture == "function") {

                setTimeout(function(){
                    if(settings.success)
                        settings.success.apply(null, settings.fixture(settings, "success")  )
                    if(settings.complete)
                        settings.complete.apply(null, settings.fixture(settings, "complete")  )
                }, 13)

            return;
		}
		var settings = jQuery.extend(true, settings, jQuery.extend(true, {}, jQuery.ajaxSettings, settings));

		settings.url = steal.root.join('test/fixtures/'+func(settings)); // convert settings
		settings.data = null;
		settings.type = 'GET';
		return ajax(settings);
	}

	var get = $.get;
	/**
	 * Adds a fixture param.
	 * @param {Object} url
	 * @param {Object} data
	 * @param {Object} callback
	 * @param {Object} type
	 * @param {Object} fixture
	 */
	$.get = function( url, data, callback, type, fixture ){
		// shift arguments if data argument was ommited
		if ( jQuery.isFunction( data ) ) {
			callback = data;
			data = null;
		}

		return jQuery.ajax({
			type: "GET",
			url: url,
			data: data,
			success: callback,
			dataType: type,
			fixture : fixture
		});
	}
	var post = $.post;
	/**
	 * Adds a fixture param.
	 * @param {Object} url
	 * @param {Object} data
	 * @param {Object} callback
	 * @param {Object} type
	 * @param {Object} fixture
	 */
	$.post= function( url, data, callback, type, fixture ) {
		if ( jQuery.isFunction( data ) ) {
			callback = data;
			data = {};
		}

		return jQuery.ajax({
			type: "POST",
			url: url,
			data: data,
			success: callback,
			dataType: type,
			fixture : fixture
		});
	}

	$.extend($.fixture, {
        "-restUpdate": function(settings,cbType){
            switch(cbType){
                case "success":
                    return [jQuery.extend({id: parseInt(settings.url)}, settings.data)]
                case "complete":
                    return [{ responseText: ""}, "success"]
            }
        },
        "-restDestroy" : function(){return [true]},
        "-restCreate" : function(settings, cbType){
            switch(cbType){
                case "success":
                    return [{id: parseInt(Math.random()*1000)}];
                case "complete":
                    return [{
                                responseText: "",
                                getResponseHeader: function(){ return "/blah/"+parseInt(Math.random()*1000) }
                            }, "success"]
            }

        }
    })

/**
 * @page fixtures Fixtures
 * @tag ajax
 *
Fixtures

 * Fixtures simulate AJAX responses.  They are a great
 * technique to use when you want to develop JavaScript
 * independantly of the backend.  This page provides a brief walkthrough
 * of how to create and use fixtures.
 *
Basic Examples

@codestart
//Named Fixture
$.ajax({url: "task.json",
  dataType: "json",
  type: "get",
  fixture: "first.json", //finds fixture in test/fixtures/first.json
  success: myCallback});

//Calculated Fixture
$.ajax({url: "tasks",
  data : {id: 5},
  type: "get",
  fixture: true, //finds fixture in test/tasks/id=5.get
  success: myCallback })
@codeend

 *
Creating Fixtures

 *
Fixtures sit in your test/fixtures
 * folder.  There are 2 types of fixtures:

 *

 *
Calculated - the name of the fixture is calculated from the url and data passed to
 *       $.ajax.

 *
Named - you give the name of the fixture.

 *

 *
Using Fixturesa

 * To enable fixtures, you have to include the dom/fixtures plugin.  To disable fixtures,
 * simply remove the plugin.
 * To make a request use a fixture,
 * [jQuery.ajax]
 * [jQuery.get]
 * [jQuery.post]
 */

})(jQuery);

<|endoftext|>


<commit_before>const _ = require('lodash');
const Item = require('./Item');

function checkItem(item) {
    item = _.pick(item, ['type', 'minDmg', 'maxDmg', 'critChance', 'critDmg']);
    let errors = [];
    let notNumbers = filterNotNumbers(item, ['minDmg', 'maxDmg', 'critChance', 'critDmg']);
    if (notNumbers.length) {
        errors.push({
            id: "mustBeNumber",
            properties: notNumbers
        });
    }
    if (_.intersection(notNumbers, ['minDmg', 'maxDmg']).length === 0) {
        if (item.minDmg > item.maxDmg) {
            errors.push({
                id: "mustBeLessThan",
                properties: ["minDmg", "maxDmg"]
            });
        }
    }
    let notPositive = filterNotPositive(item, ['minDmg', 'maxDmg'], notNumbers);
    if (notPositive.length) {
        errors.push({
            id: "mustBePositive",
            properties: notPositive
        });
    }
    let negative = filterNegative(item, ['critChance', 'critDmg'], notNumbers.concat(notPositive));
    if (negative.length) {
        errors.push({
            id: "mustNotBeNegative",
            properties: negative
        });
    }
    if (!Item.types.some(type => type === item.type)) {
        errors.push({
            id: "notValidType",
            properties: ["type"]
        });
    }
    let isValid = !errors.length;
    if (isValid) {
        if (item.critChance === 0)
            delete item.critChance;
        if (item.critDmg === 0)
            delete item.critDmg;
    } else
        item = undefined;

    return {
        item,
        isValid,
        errors
    };
}

function filterNotNumbers(item, props, excludes) {
    return _
        .difference(props, excludes || [])
        .filter(prop => Number(item[prop]) !== item[prop]);
}

function filterNotPositive(item, props, excludes) {
    return _
        .difference(props, excludes || [])
        .filter(prop => item[prop] <= 0);
}

function filterNegative(item, props, excludes) {
    return _
        .difference(props, excludes || [])
        .filter(prop => item[prop] < 0);
}

module.exports = {
    checkItem
};
<commit_msg>character validation<commit_after>const _ = require('lodash');
const Item = require('./Item');

function checkItem(item) {
    item = _.pick(item, ['type', 'minDmg', 'maxDmg', 'critChance', 'critDmg']);
    let errors = [];
    let notNumbers = filterNotNumbers(item, ['minDmg', 'maxDmg', 'critChance', 'critDmg']);
    if (notNumbers.length) {
        errors.push({
            id: "mustBeNumber",
            properties: notNumbers
        });
    }
    if (_.intersection(notNumbers, ['minDmg', 'maxDmg']).length === 0) {
        if (item.minDmg > item.maxDmg) {
            errors.push({
                id: "mustBeLessThan",
                properties: ["minDmg", "maxDmg"]
            });
        }
    }
    let notPositive = filterNotPositive(item, ['minDmg', 'maxDmg'], notNumbers);
    if (notPositive.length) {
        errors.push({
            id: "mustBePositive",
            properties: notPositive
        });
    }
    let negative = filterNegative(item, ['critChance', 'critDmg'], notNumbers.concat(notPositive));
    if (negative.length) {
        errors.push({
            id: "mustNotBeNegative",
            properties: negative
        });
    }
    if (!Item.types.some(type => type === item.type)) {
        errors.push({
            id: "notValidType",
            properties: ["type"]
        });
    }
    let isValid = !errors.length;
    if (isValid) {
        if (item.critChance === 0)
            delete item.critChance;
        if (item.critDmg === 0)
            delete item.critDmg;
    } else
        item = undefined;

    return {
        item,
        isValid,
        errors
    };
}

// > checkChar({atkSpd:'asd', dmg: 3, critChance: 5, critDmg: 6})
// {char: undefined, isValid: false, errors: [{id: "mustBeNumber", properties: ["atkSpd"]}, {id: "mustBeCorrectId", properties: ['_id']}]}
function checkChar(char) {
    char = _.pick(char, ['_id', 'atkSpd', 'dmg', 'critChance', 'critDmg']);
    let errors = [];
    let notNumbers = filterNotNumbers(char, ['atkSpd', 'dmg', 'critChance', 'critDmg']);
    if (notNumbers.length) {
        errors.push({
            id: "mustBeNumber",
            properties: notNumbers
        });
    }
    let negative = filterNegative(char, ['minDmg', 'maxDmg'], notNumbers);
    if (negative.length) {
        errors.push({
            id: "mustNotBeNegative",
            properties: negative
        });
    }
    let notId = filterNotId(char, ['_id']);
    if (notId.length) {
        errors.push({
            id: "mustBeCorrectId",
            properties: notId
        });
    }
    let isValid = !errors.length;
    if (isValid) {
        Object.keys(char)
            .filter(prop => prop !== '_id')
            .forEach(prop => {
                if (char[prop] === 0)
                    delete char[prop];
            });
    }
    else
        char = undefined;

    return {
        char,
        isValid,
        errors
    };
}

// > filterNotNumbers({minDmg:1, maxDmg:'2'}, ['minDmg', 'maxDmg'])
// ["maxDmg"]
function filterNotNumbers(item, props, excludes) {
    return _
        .difference(props, excludes || [])
        .filter(prop => Number(item[prop]) !== item[prop]);
}

function filterNotPositive(item, props, excludes) {
    return _
        .difference(props, excludes || [])
        .filter(prop => item[prop] <= 0);
}

function filterNegative(item, props, excludes) {
    return _
        .difference(props, excludes || [])
        .filter(prop => item[prop] < 0);
}

// > filterNotId({id1:1, id2:'22341jd0s943k,kfksldjasdfsdksdfkashk'}, ['id1', 'id2'])
// ["id1"]
function filterNotId(item, props, excludes) {
    return _
        .difference(props, excludes || [])
        .filter(prop => String(item[prop]) !== item[prop] || item[prop].length < 24 || item[prop].length > 36);
}
module.exports = {
    checkItem,
    checkChar
};
<|endoftext|>


<commit_before>const os = require('os')

const host = os.hostname().toLowerCase()
const rxrc = 'node_modules/@rxrc'

const targetRoot = '/'

const ioType = 'linux'
const pkgType = 'pacman'

const defaults = {
  dmode: '0755',
  fmode: '0644',
  user: 'root',
  group: 'root'
}

const unlinks = []

const directories = [{
  src: `${rxrc}/systemd-units/system/user@.service.d`,
  dst: 'etc/systemd/system/user@.service.d'
}]

const files = [{
  src: 'etc/mkinitcpio.conf',
  pkgs: ['mkinitcpio']
}, {
  src: 'etc/mkinitcpio.nvidia.conf',
  dst: 'etc/mkinitcpio.conf',
  order: 200,
  pkgs: ['mkinitcpio', 'nvidia']
}, {
  src: 'etc/vconsole.conf',
  pkgs: ['terminus-font']
}, {
  src: 'etc/locale.gen'
}, {
  src: 'etc/locale.conf'
}, {
  src: 'etc/sysctl.d/99-sysctl.conf'
}, {
  src: `${rxrc}/archrc-private/etc/fstab.${host}`,
  dst: 'etc/fstab'
}, {
  src: `${rxrc}/archrc-private/refind/refind.conf`,
  dst: 'boot/efi/EFI/refind/refind.conf',
  hosts: ['sleipnir']
}, {
  src: `${rxrc}/archrc-private/refind/refind_linux.${host}.conf`,
  dst: 'boot/refind_linux.conf',
  hosts: ['sleipnir']
}, {
  src: `${rxrc}/archrc-private/loader/loader.conf`,
  dst: 'boot/efi/loader/loader.conf',
  hosts: ['frigg']
}, {
  src: `${rxrc}/archrc-private/loader/entries/arch.${host}.conf`,
  dst: 'boot/efi/loader/entries/arch.conf',
  hosts: ['frigg']
}, {
  src: 'etc/default/grub',
  pkgs: ['grub'],
  hosts: ['frigg']
}, {
  src: `etc/default/grub.${host}`,
  dst: 'etc/default/grub',
  pkgs: ['grub'],
  hosts: ['gungnir']
}, {
  src: `${rxrc}/systemd-units/system/efistub-update@.path`,
  dst: 'etc/systemd/system/efistub-update@.path',
  pkgs: ['efibootmgr']
}, {
  src: `${rxrc}/systemd-units/system/efistub-update@.service`,
  dst: 'etc/systemd/system/efistub-update@.service',
  pkgs: ['efibootmgr']
}, {
  src: `${rxrc}/systemd-units/system/efistub-ucode-update@.path`,
  dst: 'etc/systemd/system/efistub-ucode-update@.path',
  pkgs: ['efibootmgr', 'intel-ucode']
}, {
  src: `${rxrc}/systemd-units/system/efistub-ucode-update@.service`,
  dst: 'etc/systemd/system/efistub-ucode-update@.service',
  pkgs: ['efibootmgr', 'intel-ucode']
}, {
  src: `${rxrc}/systemd-units/system/refind-update.path`,
  dst: 'etc/systemd/system/refind-update.path',
  pkgs: ['refind-efi']
}, {
  src: `${rxrc}/systemd-units/system/refind-update.service`,
  dst: 'etc/systemd/system/refind-update.service',
  pkgs: ['refind-efi']
}, {
  src: `${rxrc}/systemd-units/system/netctl-auto-resume@.service`,
  dst: 'etc/systemd/system/netctl-auto-resume@.service',
  hosts: ['gungnir', 'frigg', 'mjolnir']
}, {
  src: 'etc/pacman.conf',
  pkgs: ['pacman']
}, {
  src: 'etc/nftables.conf',
  pkgs: ['nftables']
}, {
  src: 'etc/sudoers',
  fmode: '0440',
  pkgs: ['sudo']
}, {
  src: 'etc/ssh/sshd_config',
  pkgs: ['openssh']
}, {
  src: `etc/systemd/network/wired.${host}.network`,
  dst: 'etc/systemd/network/wired.network',
  hosts: ['mimir', 'sleipnir']
}, {
  src: 'etc/systemd/journald.conf.d/size.conf',
  hosts: ['gungnir', 'mjolnir']
}, {
  src: 'etc/udev/rules.d/99-lowbat.rules',
  hosts: ['gungnir', 'mjolnir']
}, {
  src: 'etc/modules-load.d/virtualbox.conf',
  pkgs: ['virtualbox']
}, {
  src: 'etc/modprobe.d/alsa-base.conf',
  hosts: ['gungnir']
}, {
  src: 'etc/X11/xorg.conf.d/15-dpms.conf'
}, {
  src: 'etc/X11/xorg.conf.d/20-intel.conf',
  pkgs: ['xf86-video-intel'],
  hosts: ['frigg']
}, {
  src: `etc/X11/xorg.conf.d/20-intel.${host}.conf`,
  dst: 'etc/X11/xorg.conf.d/20-intel.conf',
  pkgs: ['xf86-video-intel'],
  hosts: ['gungnir']
}, {
  src: `etc/X11/xorg.${host}.conf`,
  dst: 'etc/X11/xorg.conf',
  pkgs: ['nvidia'],
  hosts: ['mimir', 'mjolnir']
}, {
  src: `etc/pacman.d/hooks/nvidia.hook`,
  pkgs: ['nvidia']
}, {
  src: 'etc/X11/xorg.conf.d/10-keyboard.conf',
  pkgs: ['xkeyboard-config-chromebook']
}, {
  src: 'etc/X11/xorg.conf.d/50-synaptics.conf',
  pkgs: ['xf86-input-synaptics'],
  hosts: ['gungnir']
}, {
  src: 'etc/X11/xorg.conf.d/30-touchpad.conf',
  pkgs: ['xf86-input-libinput'],
  hosts: ['mjolnir']
}, {
  src: 'etc/X11/xorg.conf.d/50-mtrack.conf',
  pkgs: ['xf86-input-mtrack-git'],
  hosts: ['frigg']
}, {
  src: `${rxrc}/systemd-units/logind.conf.d/acpi.conf`,
  dst: 'etc/systemd/logind.conf.d/acpi.conf'
}, {
  src: `${rxrc}/systemd-units/coredump.conf.d/disable.conf`,
  dst: 'etc/systemd/coredump.conf.d/disable.conf'
}, {
  src: 'etc/systemd/system/chromeos-kbd_backlight.service',
  hosts: ['gungnir']
}, {
  src: `${rxrc}/systemd-units/system/numlock.service`,
  dst: 'etc/systemd/system/numlock.service'
}, {
  src: `${rxrc}/systemd-units/system/xscreensaver-lock@.service`,
  dst: 'etc/systemd/system/xscreensaver-lock@.service',
  pkgs: ['xscreensaver-arch-logo']
}, {
  src: 'etc/lightdm/lightdm.conf',
  pkgs: ['lightdm']
}, {
  src: 'etc/lightdm/display_setup.sh',
  fmode: '0755',
  pkgs: ['lightdm']
}, {
  src: `etc/lightdm/display_setup.${host}.sh`,
  dst: 'etc/lightdm/display_setup.sh',
  fmode: '0755',
  order: 200,
  pkgs: ['lightdm'],
  hosts: ['mjolnir']
}, {
  src: 'etc/lightdm/lightdm-gtk-greeter.conf',
  pkgs: ['lightdm-gtk-greeter']
}, {
  src: `${rxrc}/archrc-private/etc/samba/smb.${host}.conf`,
  dst: 'etc/samba/smb.conf',
  pkgs: ['samba']
}, {
  src: `${rxrc}/archrc-private/etc/samba/users.${host}.map`,
  dst: 'etc/samba/users.map',
  pkgs: ['samba']
}, {
  src: `${rxrc}/archrc-private/etc/nginx/nginx.${host}.conf`,
  dst: 'etc/nginx/nginx.conf',
  pkgs: ['nginx']
}, {
  src: 'node_modules/@razor-x/archutil/bin/archutil',
  dst: 'usr/local/bin/archutil',
  fmode: '0755'
}, {
  src: 'archutil.yml',
  dst: 'usr/local/etc/archutil.yml'
}, {
  src: 'usr/local/bin/xcleanup',
  fmode: '0755',
  pkgs: ['lightdm']
}, {
  src: 'usr/local/bin/touchpad-toggle',
  fmode: '0755',
  pkgs: ['xf86-input-synaptics']
}, {
  src: 'usr/local/bin/chromeos-kbd_backlight',
  fmode: '0755',
  hosts: ['gungnir']
}, {
  src: 'usr/local/bin/chromeos-sound-output-toggle',
  fmode: '0755',
  hosts: ['gungnir']
}]

const symlinks = []

module.exports = {
  unlinks,
  directories,
  files,
  symlinks,
  targetRoot,
  ioType,
  pkgType,
  defaults
}
<commit_msg>Change backticks<commit_after>const os = require('os')

const host = os.hostname().toLowerCase()
const rxrc = 'node_modules/@rxrc'

const targetRoot = '/'

const ioType = 'linux'
const pkgType = 'pacman'

const defaults = {
  dmode: '0755',
  fmode: '0644',
  user: 'root',
  group: 'root'
}

const unlinks = []

const directories = [{
  src: `${rxrc}/systemd-units/system/user@.service.d`,
  dst: 'etc/systemd/system/user@.service.d'
}]

const files = [{
  src: 'etc/mkinitcpio.conf',
  pkgs: ['mkinitcpio']
}, {
  src: 'etc/mkinitcpio.nvidia.conf',
  dst: 'etc/mkinitcpio.conf',
  order: 200,
  pkgs: ['mkinitcpio', 'nvidia']
}, {
  src: 'etc/vconsole.conf',
  pkgs: ['terminus-font']
}, {
  src: 'etc/locale.gen'
}, {
  src: 'etc/locale.conf'
}, {
  src: 'etc/sysctl.d/99-sysctl.conf'
}, {
  src: `${rxrc}/archrc-private/etc/fstab.${host}`,
  dst: 'etc/fstab'
}, {
  src: `${rxrc}/archrc-private/refind/refind.conf`,
  dst: 'boot/efi/EFI/refind/refind.conf',
  hosts: ['sleipnir']
}, {
  src: `${rxrc}/archrc-private/refind/refind_linux.${host}.conf`,
  dst: 'boot/refind_linux.conf',
  hosts: ['sleipnir']
}, {
  src: `${rxrc}/archrc-private/loader/loader.conf`,
  dst: 'boot/efi/loader/loader.conf',
  hosts: ['frigg']
}, {
  src: `${rxrc}/archrc-private/loader/entries/arch.${host}.conf`,
  dst: 'boot/efi/loader/entries/arch.conf',
  hosts: ['frigg']
}, {
  src: 'etc/default/grub',
  pkgs: ['grub'],
  hosts: ['frigg']
}, {
  src: `etc/default/grub.${host}`,
  dst: 'etc/default/grub',
  pkgs: ['grub'],
  hosts: ['gungnir']
}, {
  src: `${rxrc}/systemd-units/system/efistub-update@.path`,
  dst: 'etc/systemd/system/efistub-update@.path',
  pkgs: ['efibootmgr']
}, {
  src: `${rxrc}/systemd-units/system/efistub-update@.service`,
  dst: 'etc/systemd/system/efistub-update@.service',
  pkgs: ['efibootmgr']
}, {
  src: `${rxrc}/systemd-units/system/efistub-ucode-update@.path`,
  dst: 'etc/systemd/system/efistub-ucode-update@.path',
  pkgs: ['efibootmgr', 'intel-ucode']
}, {
  src: `${rxrc}/systemd-units/system/efistub-ucode-update@.service`,
  dst: 'etc/systemd/system/efistub-ucode-update@.service',
  pkgs: ['efibootmgr', 'intel-ucode']
}, {
  src: `${rxrc}/systemd-units/system/refind-update.path`,
  dst: 'etc/systemd/system/refind-update.path',
  pkgs: ['refind-efi']
}, {
  src: `${rxrc}/systemd-units/system/refind-update.service`,
  dst: 'etc/systemd/system/refind-update.service',
  pkgs: ['refind-efi']
}, {
  src: `${rxrc}/systemd-units/system/netctl-auto-resume@.service`,
  dst: 'etc/systemd/system/netctl-auto-resume@.service',
  hosts: ['gungnir', 'frigg', 'mjolnir']
}, {
  src: 'etc/pacman.conf',
  pkgs: ['pacman']
}, {
  src: 'etc/nftables.conf',
  pkgs: ['nftables']
}, {
  src: 'etc/sudoers',
  fmode: '0440',
  pkgs: ['sudo']
}, {
  src: 'etc/ssh/sshd_config',
  pkgs: ['openssh']
}, {
  src: `etc/systemd/network/wired.${host}.network`,
  dst: 'etc/systemd/network/wired.network',
  hosts: ['mimir', 'sleipnir']
}, {
  src: 'etc/systemd/journald.conf.d/size.conf',
  hosts: ['gungnir', 'mjolnir']
}, {
  src: 'etc/udev/rules.d/99-lowbat.rules',
  hosts: ['gungnir', 'mjolnir']
}, {
  src: 'etc/modules-load.d/virtualbox.conf',
  pkgs: ['virtualbox']
}, {
  src: 'etc/modprobe.d/alsa-base.conf',
  hosts: ['gungnir']
}, {
  src: 'etc/X11/xorg.conf.d/15-dpms.conf'
}, {
  src: 'etc/X11/xorg.conf.d/20-intel.conf',
  pkgs: ['xf86-video-intel'],
  hosts: ['frigg']
}, {
  src: `etc/X11/xorg.conf.d/20-intel.${host}.conf`,
  dst: 'etc/X11/xorg.conf.d/20-intel.conf',
  pkgs: ['xf86-video-intel'],
  hosts: ['gungnir']
}, {
  src: `etc/X11/xorg.${host}.conf`,
  dst: 'etc/X11/xorg.conf',
  pkgs: ['nvidia'],
  hosts: ['mimir', 'mjolnir']
}, {
  src: 'etc/pacman.d/hooks/nvidia.hook',
  pkgs: ['nvidia']
}, {
  src: 'etc/X11/xorg.conf.d/10-keyboard.conf',
  pkgs: ['xkeyboard-config-chromebook']
}, {
  src: 'etc/X11/xorg.conf.d/50-synaptics.conf',
  pkgs: ['xf86-input-synaptics'],
  hosts: ['gungnir']
}, {
  src: 'etc/X11/xorg.conf.d/30-touchpad.conf',
  pkgs: ['xf86-input-libinput'],
  hosts: ['mjolnir']
}, {
  src: 'etc/X11/xorg.conf.d/50-mtrack.conf',
  pkgs: ['xf86-input-mtrack-git'],
  hosts: ['frigg']
}, {
  src: `${rxrc}/systemd-units/logind.conf.d/acpi.conf`,
  dst: 'etc/systemd/logind.conf.d/acpi.conf'
}, {
  src: `${rxrc}/systemd-units/coredump.conf.d/disable.conf`,
  dst: 'etc/systemd/coredump.conf.d/disable.conf'
}, {
  src: 'etc/systemd/system/chromeos-kbd_backlight.service',
  hosts: ['gungnir']
}, {
  src: `${rxrc}/systemd-units/system/numlock.service`,
  dst: 'etc/systemd/system/numlock.service'
}, {
  src: `${rxrc}/systemd-units/system/xscreensaver-lock@.service`,
  dst: 'etc/systemd/system/xscreensaver-lock@.service',
  pkgs: ['xscreensaver-arch-logo']
}, {
  src: 'etc/lightdm/lightdm.conf',
  pkgs: ['lightdm']
}, {
  src: 'etc/lightdm/display_setup.sh',
  fmode: '0755',
  pkgs: ['lightdm']
}, {
  src: `etc/lightdm/display_setup.${host}.sh`,
  dst: 'etc/lightdm/display_setup.sh',
  fmode: '0755',
  order: 200,
  pkgs: ['lightdm'],
  hosts: ['mjolnir']
}, {
  src: 'etc/lightdm/lightdm-gtk-greeter.conf',
  pkgs: ['lightdm-gtk-greeter']
}, {
  src: `${rxrc}/archrc-private/etc/samba/smb.${host}.conf`,
  dst: 'etc/samba/smb.conf',
  pkgs: ['samba']
}, {
  src: `${rxrc}/archrc-private/etc/samba/users.${host}.map`,
  dst: 'etc/samba/users.map',
  pkgs: ['samba']
}, {
  src: `${rxrc}/archrc-private/etc/nginx/nginx.${host}.conf`,
  dst: 'etc/nginx/nginx.conf',
  pkgs: ['nginx']
}, {
  src: 'node_modules/@razor-x/archutil/bin/archutil',
  dst: 'usr/local/bin/archutil',
  fmode: '0755'
}, {
  src: 'archutil.yml',
  dst: 'usr/local/etc/archutil.yml'
}, {
  src: 'usr/local/bin/xcleanup',
  fmode: '0755',
  pkgs: ['lightdm']
}, {
  src: 'usr/local/bin/touchpad-toggle',
  fmode: '0755',
  pkgs: ['xf86-input-synaptics']
}, {
  src: 'usr/local/bin/chromeos-kbd_backlight',
  fmode: '0755',
  hosts: ['gungnir']
}, {
  src: 'usr/local/bin/chromeos-sound-output-toggle',
  fmode: '0755',
  hosts: ['gungnir']
}]

const symlinks = []

module.exports = {
  unlinks,
  directories,
  files,
  symlinks,
  targetRoot,
  ioType,
  pkgType,
  defaults
}
<|endoftext|>


<commit_before>describe('ddTimepicker', function () {
    var $scope,
        $sniffer,
        $document,
        $timeout,
        element;

    beforeEach(function () {
        module('dd.ui.dd-timepicker');

        inject(function ($rootScope, $compile, _$timeout_, _$sniffer_, _$document_) {
            $scope = $rootScope.$new();
            $sniffer = _$sniffer_;
            $timeout = _$timeout_;
            $document = _$document_;

            element = $compile(angular.element('<input id="time1" class="form-control" dd-timepicker type="text" ng-model="time" />'))($scope);
            $scope.$digest();

        });
    });

    describe('Change model value', function () {

        it('apply parsed user input for model', function () {

            changeInputValue(element, '8a');

            element.trigger('blur');
            $timeout.flush();

            expect($scope.time).toEqual('08:00');
        });

        it('clear model if invalid time', function () {

            changeInputValue(element, 'kepalas');

            element.trigger('blur');
            $timeout.flush();

            expect($scope.time).toBeNull();
        });

        it('do not change model if not blured', function () {

            $scope.time = '10:15';

            changeInputValue(element, '8p');

            expect($scope.time).toBe($scope.time);
        });

    });

    function changeInputValue(el, value) {
        el.val(value);
        el.trigger($sniffer.hasEvent('input') ? 'input' : 'change');
        $scope.$digest();
    }
});<commit_msg>feat(timepicker): add unit test for date conversion check<commit_after>describe('ddTimepicker', function () {
    var $scope,
        $sniffer,
        $document,
        $timeout,
        $compile,
        element;

    beforeEach(function () {
        module('dd.ui.dd-timepicker');

        inject(function ($rootScope, _$compile_, _$timeout_, _$sniffer_, _$document_) {
            $scope = $rootScope.$new();
            $sniffer = _$sniffer_;
            $timeout = _$timeout_;
            $document = _$document_;
            $compile = _$compile_;

            element = $compile(angular.element('<input id="time1" class="form-control" dd-timepicker type="text" ng-model="time" />'))($scope);
            $scope.$digest();

        });
    });

    describe('Change model value', function () {

        it('apply parsed user input for model', function () {

            changeInputValue(element, '8a');

            expect($scope.time).toEqual('08:00');
        });

        it('clear model if invalid time', function () {

            changeInputValue(element, 'kepalas');

            expect($scope.time).toBeNull();
        });

        it('do not change model if not blured', function () {

            $scope.time = '10:15';

            changeInputValue(element, '8p');

            expect($scope.time).toBe($scope.time);
        });

        it('return model as Date if is-date-type="true"', function () {

            $scope.time = '10:15';
            element = $compile(angular.element('<input id="time1" is-date-type="true" class="form-control" dd-timepicker type="text" ng-model="time" />'))($scope);
            $scope.$digest();

            changeInputValue(element, '10:20');

            expect($scope.time instanceof Date).toBe(true);
            expect($scope.time.getHours()).toBe(10);
            expect($scope.time.getMinutes()).toBe(20);
        });

    });

    function changeInputValue(el, value) {
        el.val(value);
        el.trigger($sniffer.hasEvent('input') ? 'input' : 'change');
        $scope.$digest();
        element.trigger('blur');
    }
});<|endoftext|>


<commit_before>// ==UserScript==
// @name        SfReader
// @namespace   http://gmscripts.bhe.me
// @author      hitsmaxft <mfthits#gmail.com>
// @description Better SF reader UI
// @include     http://comic.sfacg.com/*
// @version     3.0
// @require http://code.jquery.com/jquery-1.11.0.min.js

// @grant GM_info
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_xmlhttpRequest
// @grant GM_registerMenuCommand
// @grant unsafeWindow

// @require http://sizzlemctwizzle.com/130400.js?show
// ==/UserScript==

this.$ = this.jQuery = jQuery.noConflict(true)
var debug_mode = false

(function(jQuery, debug_mode){
	var $ = jQuery

	var debug = function (msg) {
		if (debug_mode) {
			console.log("debug: " + msg)
		}
	}

	var SfReader = function() {
		this.debug = debug_mode

		this.initAttr = function(){
			var attr = [
			'comicName'
			, 'picCount'
			, 'picAy'
			]

			for (i in attr) {
				var name = attr[i]
				this[name] = unsafeWindow[name]
			}

			this.cur = unsafeWindow.GetArgsFromHref(unsafeWindow.location.href, "p") - 1
			this.hostId = unsafeWindow.getHost()
			this.host = unsafeWindow.hosts[unsafeWindow.getHost()]
			this.cache = [];

			this.$curPic = $("#curPic")

			this.$statusBar = this.renderStatusBar()
			this.notif = this.$statusBar.find("#reader_notification")
			this.$pager_text = this.$statusBar.find("#page_indicator span")
			this.notif_text = this.notif.find("span")

			var imgLoadEvent = $.Deferred()
			this.$EImgLoading = imgLoadEvent

			$("#curPic").on('load', function(e) {
				$(this).get(0).scrollIntoView()
				imgLoadEvent.resolve(function(){})
			})

			$(document.body).prepend(this.$statusBar)
		}

	}

	SfReader.prototype.hookRenderPager= function() {
		setInterval((function() {
			this.$pager_text.text("第" + (this.cur+1) + "/" + this.picCount + "页")

		}).bind(this), 100);
	}

	SfReader.prototype.renderStatusBar= function(msg) {
			var box = $("

")
			box.attr("id", "sfreader_box")
			box.attr("style", "position:fixed;z-index:9999999;background-color:none;padding:10px 30px;width:100%")
			var inner_box = $("

")
			inner_box.attr("id" , "reader_notification")
			inner_box.attr("style", "display:none;")
			var pager_box = $("

")
			pager_box.attr("id", "page_indicator")
			var clean_box = $("

")
			var inner_span = $("")
			inner_span.attr("style", "padding:3px 5px;font-size:1.8em;float:left;color:#fff;background-color:#AF2F15")
			pager_box.append(inner_span[0].cloneNode(true))
			inner_box.append(inner_span)
			inner_span.attr("id", "sfreader-notif-text")
			inner_box.append(clean_box)
			box.append(pager_box)
			box.append(inner_box)
			return  box
	}

	SfReader.prototype.sendMsgWithCallback = function(callback, msg, done_text) {
		this.notif_text.text(msg)
		this.notif.fadeIn()
		this.$EImgLoading.done(
			(function(callback){
				debug("loading fadeout")
				// fadeOut with done text
				setTimeout( (function() {
					this.notif.fadeOut()
					if (done_text)
						this.notif_text.text(done_text)
				}).bind(this), 600)
			}).bind(this)
		)

		callback()
	}

	SfReader.prototype.sendMsg = function(msg, timeout) {
		var latency = timeout || 2;
		this.notif_text.text(msg)
		this.notif.fadeIn()
		setTimeout(
			(function(){this.fadeOut()}).bind(this.notif)
		, 400)
	}
	SfReader.prototype.start = function(page) {
		this.initAttr();

		this.bindPagerButton();
		this.hookRenderPager();
		debug("enjoy sf reader")
	}

	SfReader.prototype.bindPagerButton = function() {

		var pagers = $(".page_turning")
		var pre_links  =  pagers.find(".redfont_input:contains(上一页)")

		var next_links  = pagers.find(".redfont_input:contains(下一页)")

		next_links.push($("#curPic").parent()[0])

		var self = this

		pre_links.each(function(ind , item){
			item.href = "javascript:;"
			item.onclick = (function(e) {
				e.preventDefault();
				this.nav2Page(-1);
			}).bind(self)
		})
		next_links.each(function(ind , item){
			item.href = "javascript:;"
			item.onclick = (function(e) {
				e.preventDefault();
				this.nav2Page(1);
			}).bind(self)
		})

	}

	SfReader.prototype.setImg = function(page) {
		var imgEl = this.$curPic
		imgEl.attr("src" , this.host  + this.picAy[page])
		this.cur = page
		debug("set img url 2 " + imgEl.src)
	}
	SfReader.prototype.render = function(page) {
		debug("rend nothing with page " + page)
	}
	SfReader.prototype.nav2Page = function(pos) {
		if (pos !== -1  && pos !== 1) {
			debug("erro in pos nav : " + pos)
			return false
		}

		var page_id = parseInt(this.cur, 0) + parseInt(pos, 0)

		if (
			page_id < 0
			|| page_id >= this.picCount
			) {

			debug("out of range")
			this.sendMsg("到头啦, 看其他话吧")
			return false
		}

		debug(" go to pageid : " + page_id)

		this.sendMsgWithCallback(
				(function(){
					debug("make resolve")
					this.setImg(page_id)
				}).bind(this)
				, "翻页中..."
				, "翻页完成"
		)

		debug("end of callback")

		setTimeout(this.render(page_id), 0)
	};

	var reader  = new SfReader()

	$(document).ready(
		function() {
			reader.start()
		}
	)

})($, debug_mode)
<commit_msg>fix load bug<commit_after>// ==UserScript==
// @name        SfReader
// @namespace   http://gmscripts.bhe.me
// @author      hitsmaxft <mfthits#gmail.com>
// @description Better SF reader UI
// @include     http://comic.sfacg.com/*
// @version     3.0
// @require http://code.jquery.com/jquery-1.11.0.min.js
//
// @grant GM_info
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_xmlhttpRequest
// @grant GM_registerMenuCommand
// @grant unsafeWindow
//
// @require http://sizzlemctwizzle.com/130400js?show
// ==/UserScript==

var debug_mode = false;

if (typeof unsafeWindow == "undefined") {
	unsafeWindow = window

}

//port jquery into unsafeWindow
if(debug_mode) {
	unsafeWindow.$=jQuery
	unsafeWindow.jQuery=jQuery
}

this.$ = this.jQuery = jQuery.noConflict(true)

;(
	function(jQuery){
		var $ = jQuery

		var debug = function (msg) {
			if (debug_mode) {
				console.log(msg)
			}
		}

		var SfReader = function() {
			this.debug = debug_mode

			this.initAttr = function(){
				var attr = [
				'comicName'
				, 'picCount'
				, 'picAy'
				]

				for (i in attr) {
					var name = attr[i]
					this[name] = unsafeWindow[name]
				}

				this.cur = unsafeWindow.GetArgsFromHref(unsafeWindow.location.href, "p") - 1
				this.hostId = unsafeWindow.getHost()
				this.host = unsafeWindow.hosts[unsafeWindow.getHost()]
				this.cache = [];

				this.$curPic = $("#curPic")

				this.$statusBar = this.renderStatusBar()
				this.notif = this.$statusBar.find("#reader_notification")
				this.$pager_text = this.$statusBar.find("#page_indicator span")
				this.notif_text = this.notif.find("span")

				var imgLoadEvent = $.Deferred()
				this.$EImgLoading = imgLoadEvent

				$("#curPic").on('load', function(e) {
					$(this).get(0).scrollIntoView()
					imgLoadEvent.resolve(function(){})
				})

				$(document.body).prepend(this.$statusBar)
			}

		}

		SfReader.prototype.hookRenderPager= function() {
			setInterval((function() {
				this.$pager_text.text("第" + (this.cur+1) + "/" + this.picCount + "页")

			}).bind(this), 100);
		}

		SfReader.prototype.renderStatusBar= function(msg) {
			var box = $("

")
			box.attr("id", "sfreader_box")
			box.attr("style", "position:fixed;z-index:9999999;background-color:none;padding:10px 30px;width:100%")
			var inner_box = $("

")
			inner_box.attr("id" , "reader_notification")
			inner_box.attr("style", "display:none;")
			var pager_box = $("

")
			pager_box.attr("id", "page_indicator")
			var clean_box = $("

")
			var inner_span = $("")
			inner_span.attr("style", "padding:3px 5px;font-size:1.8em;float:left;color:#fff;background-color:#AF2F15")
			pager_box.append(inner_span[0].cloneNode(true))
			inner_box.append(inner_span)
			inner_span.attr("id", "sfreader-notif-text")
			inner_box.append(clean_box)
			box.append(pager_box)
			box.append(inner_box)
			return  box
		}

		SfReader.prototype.sendMsgWithCallback = function(callback, msg, done_text) {
			this.notif_text.text(msg)
			this.notif.fadeIn()
			this.$EImgLoading.done(
				(function(callback){
					debug("loading fadeout")
				// fadeOut with done text
				setTimeout( (function() {
					this.notif.fadeOut()
					if (done_text)
						this.notif_text.text(done_text)
				}).bind(this), 600)
			}).bind(this)
				)

			callback()
		}

		SfReader.prototype.sendMsg = function(msg, timeout) {
			var latency = timeout || 2;
			this.notif_text.text(msg)
			this.notif.fadeIn()
			setTimeout(
				(function(){this.fadeOut()}).bind(this.notif)
				, 400)
		}
		SfReader.prototype.start = function(page) {
			this.initAttr();

			this.bindPagerButton();
			this.hookRenderPager();
			debug("enjoy sf reader")
		}

		SfReader.prototype.bindPagerButton = function() {

			var pagers = $(".page_turning")
			var pre_links  =  pagers.find(".redfont_input:contains(上一页)")

			var next_links  = pagers.find(".redfont_input:contains(下一页)")

			next_links.push($("#curPic").parent()[0])

			var self = this

			pre_links.each(function(ind , item){
				item.href = "javascript:;"
				item.onclick = (function(e) {
					e.preventDefault();
					this.nav2Page(-1);
				}).bind(self)
			})
			next_links.each(function(ind , item){
				item.href = "javascript:;"
				item.onclick = (function(e) {
					e.preventDefault();
					this.nav2Page(1);
				}).bind(self)
			})

		}

		SfReader.prototype.setImg = function(page) {
			var imgEl = this.$curPic
			imgEl.attr("src" , this.host  + this.picAy[page])
			this.cur = page
			debug("set img url 2 " + imgEl.src)
		}
		SfReader.prototype.render = function(page) {
			debug("rend nothing with page " + page)
		}
		SfReader.prototype.nav2Page = function(pos) {
			if (pos !== -1  && pos !== 1) {
				debug("erro in pos nav : " + pos)
				return false
			}

			var page_id = parseInt(this.cur, 0) + parseInt(pos, 0)

			if (
				page_id < 0
				|| page_id >= this.picCount
				) {

				debug("out of range")
			this.sendMsg("到头啦, 看其他话吧")
			return false
		}

		debug(" go to pageid : " + page_id)

		this.sendMsgWithCallback(
			(function(){
				debug("make resolve")
				this.setImg(page_id)
			}).bind(this)
			, "翻页中..."
			, "翻页完成"
			)

		debug("end of callback")

		setTimeout(this.render(page_id), 0)
	};

	var reader  = new SfReader()

	$(document).ready(function() {
			reader.start()
	})

})($)
<|endoftext|>