<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_mes<commit_msg>Should work now<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_mess<|endoftext|>


<commit_before>var LABEL_WIDTH = 200,
	VTX_DIST = 40, // Distance between centers of two consecutive vertices
	VTX_RAD = 4,
	LABEL_OFFSET = 10; // Distance between label and center of vertex

// Translate every vertex (hence entire graphic) by this much
var VTX_TRANS = {x: 0, y: 20};

var canvas = d3.select("#canvas");
var sidePanel = d3.select("#side-panel");

// Overall width of canvas
var WIDTH = canvas.style("width");
WIDTH = +(WIDTH.substring(0, WIDTH.length - 2));

////////////////// Helper functions //////////////////

// Return absolute coordinates of center of vertex
// Accepts either a vertex object or an ID string
function vertexPos(v) {

	// If v is an ID string, use it to retrieve vertex
	if(v.name == undefined)
		v = canvas.select("#" + v).datum();

	var pos = {
		x: (v.series == "tac" ? LABEL_WIDTH : WIDTH - LABEL_WIDTH) + VTX_TRANS.x,
		y: v.index * VTX_DIST + VTX_TRANS.y
	};
	return pos;
}

// Callback for when a vertex is clicked
function vertexClicked(v) {

	// Hide all edges first
	edges.classed("active", false);

	// Select current vertex & deselect all others
	vertices.classed("selected", function(w) {return w.id == v.id;});

	// Show edges incident to the clicked vertex
	edges.classed("active", function(e) {
			return e.l == v.id || e.r == v.id;
		})
		.classed("selected", false);

	// Clear the side panel
	sidePanel.select("#instructions").remove();
	sidePanel.selectAll("div").html("");

	showInfo(v, sidePanel.select("#selected-char"));
}

// Fill selection with info from vertex v
function showInfo(v, selection) {
	selection.html("")
	  .append("img")
		.attr("src", "pics/" + v.id + ".jpg");
	selection.append("h2")
		.html(v.name);

	var wiki_handle = v.wiki_handle;
	if(wiki_handle == undefined)
		/*
		 * Replace spaces with _s and 's (as in Beatrice d'Hirson) with %27s
		 */
		wiki_handle = v.name.replace(/ /g, "_").replace(/\'/g, "%27");

	var url = "http://";
	var link_url = "http://";
	if(v.series == "tac") {
		url += "en.wikipedia.org/w/api.php?";
		link_url += "en.wikipedia.org/wiki/";
	}
	else {
		url += "awoiaf.westeros.org/api.php?";
		link_url += "awoiaf.westeros.org/index.php/";
	}
	link_url += wiki_handle;

	url += "action=query&redirects&format=json&&titles=" + wiki_handle + "&prop=extracts&utf8&exintro&exsentences=3&explaintext";
	var req = new XMLHttpRequest();
	req.open("GET", url, true);

	req.onload = function() {
		var pages = JSON.parse(this.response).query.pages;
		for(var pageid in pages) {
			selection.append("p").html(pages[pageid].extract);
			break; // Only want one page
		}
		selection.append("a")
		    .attr("href", link_url)
		    .html("Read more");
	};

	req.onerror = function() {
		console.log("Error opening " + url);
	};

	req.send();
}

function edgeClicked(e) {

	// Deselect other edges and select this one
	edges.classed("selected", function(f) {
			return f.l == e.l && f.r == e.r;
		});

	// Get the endpoint of e that is NOT the selected vertex
	var otherV = (canvas.select(".vertex.selected").classed("tac") ? e.r : e.l); // ID
	otherV = canvas.select("#" + otherV).datum(); // Vertex object

	showInfo(otherV, sidePanel.select("#connected-char"));

	// Show connections between characters in a bulleted list
	var connections = d3.select("#connections").html("");
	connections.append("h2")
		.html("Connections");
	var ul = connections.append("ul");
	d3.text("blurbs/" + e.l + "-" + e.r, function(error, blurb) {
			if(error == null) {
				blurb = blurb.split("\n"); // Each newline marks a new bullet
				for(var i = 0; i < blurb.length; i++) {
					blurb[i] = blurb[i].trim();
					if(blurb[i].length == 0) // Skip empty lines
						continue;
					ul.append("li").html(blurb[i]);
				}
			}
			else
				console.log(error);
		});

}

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

// Draw vertices
var vertices = canvas.selectAll(".vertex") // Should be empty
	.data(vertexList)
  .enter().append("g")
	.classed("vertex", true)
	.classed("tac", function(v) {return v.series == "tac";})
	.classed("asoiaf", function(v) {return v.series == "asoiaf";})
	.attr("id", function(v) {return v.id;})
	.attr("transform", function(v) {
			var pos = vertexPos(v);
			return "translate(" + pos.x + "," + pos.y + ")";
		});

vertices.append("circle")
	.attr("r", VTX_RAD);

vertices.append("text")
	.text(function(v) {return v.name;})
	.attr("x", function(v) {return v.series == "tac" ? -LABEL_OFFSET : LABEL_OFFSET;})
	.attr("y", 4);

// Draw edges

var edges = canvas.selectAll(".edge"); // Should be empty
var pairsProcessed = 0;

// Return callback for adding edge to edgeList
function addEdge(e) {
	return function() {

		if(this.status == 200 || this.status == 0) // File exists; add an edge
			edgeList.push(e);

		drawIfDone();

	};
}

// Draw edges when done with last pair
function drawIfDone() {
	if(++pairsProcessed == tac_chars.length * asoiaf_chars.length) {
		// Done with last pair; draw edges
		edges = edges.data(edgeList)
		  .enter().append("line")
			.attr("x1", vertexPos("clemence").x) // Use any TAC character
			.attr("y1", function(e) {return vertexPos(e.l).y;})
			.attr("x2", vertexPos("sansa").x) // Use any ASOIAF character
			.attr("y2", function(e) {return vertexPos(e.r).y;})
			.on("click", edgeClicked)
			.classed("edge", true);

		vertices.on("click", vertexClicked);
	}
}

for(var i = 0; i < tac_chars.length; i++) {
	for(var j = 0; j < asoiaf_chars.length; j++) {
		var req = new XMLHttpRequest();
		var e = {l: tac_chars[i], r: asoiaf_chars[j]};
		req.open("HEAD", "blurbs/" + e.l + "-" + e.r, true); // True makes it asynchronous
		req.onload = addEdge(e);
		req.onerror = drawIfDone; // onload not called; still darw edges if done
		req.send();
	}
}
<commit_msg>Use encodeURI() to encode wiki handles<commit_after>var LABEL_WIDTH = 200,
	VTX_DIST = 40, // Distance between centers of two consecutive vertices
	VTX_RAD = 4,
	LABEL_OFFSET = 10; // Distance between label and center of vertex

// Translate every vertex (hence entire graphic) by this much
var VTX_TRANS = {x: 0, y: 20};

var canvas = d3.select("#canvas");
var sidePanel = d3.select("#side-panel");

// Overall width of canvas
var WIDTH = canvas.style("width");
WIDTH = +(WIDTH.substring(0, WIDTH.length - 2));

////////////////// Helper functions //////////////////

// Return absolute coordinates of center of vertex
// Accepts either a vertex object or an ID string
function vertexPos(v) {

	// If v is an ID string, use it to retrieve vertex
	if(v.name == undefined)
		v = canvas.select("#" + v).datum();

	var pos = {
		x: (v.series == "tac" ? LABEL_WIDTH : WIDTH - LABEL_WIDTH) + VTX_TRANS.x,
		y: v.index * VTX_DIST + VTX_TRANS.y
	};
	return pos;
}

// Callback for when a vertex is clicked
function vertexClicked(v) {

	// Hide all edges first
	edges.classed("active", false);

	// Select current vertex & deselect all others
	vertices.classed("selected", function(w) {return w.id == v.id;});

	// Show edges incident to the clicked vertex
	edges.classed("active", function(e) {
			return e.l == v.id || e.r == v.id;
		})
		.classed("selected", false);

	// Clear the side panel
	sidePanel.select("#instructions").remove();
	sidePanel.selectAll("div").html("");

	showInfo(v, sidePanel.select("#selected-char"));
}

// Fill selection with info from vertex v
function showInfo(v, selection) {
	selection.html("")
	  .append("img")
		.attr("src", "pics/" + v.id + ".jpg");
	selection.append("h2")
		.html(v.name);

	/* Assume v.wiki_handle is a correctly encoded URL if defined,
	 * e.g. %20 instead of ' '.
	 */
	var wiki_handle = v.wiki_handle;
	if(wiki_handle == undefined)
		wiki_handle = encodeURI(v.name);

	var url = "http://";
	var link_url = "http://";
	if(v.series == "tac") {
		url += "en.wikipedia.org/w/api.php?";
		link_url += "en.wikipedia.org/wiki/";
	}
	else {
		url += "awoiaf.westeros.org/api.php?";
		link_url += "awoiaf.westeros.org/index.php/";
	}
	link_url += wiki_handle;

	url += "action=query&redirects&format=json&&titles=" + wiki_handle + "&prop=extracts&utf8&exintro&exsentences=3&explaintext";
	var req = new XMLHttpRequest();
	req.open("GET", url, true);

	req.onload = function() {
		var pages = JSON.parse(this.response).query.pages;
		for(var pageid in pages) {
			selection.append("p").html(pages[pageid].extract);
			break; // Only want one page
		}
		selection.append("a")
		    .attr("href", link_url)
		    .html("Read more");
	};

	req.onerror = function() {
		console.log("Error opening " + url);
	};

	req.send();
}

function edgeClicked(e) {

	// Deselect other edges and select this one
	edges.classed("selected", function(f) {
			return f.l == e.l && f.r == e.r;
		});

	// Get the endpoint of e that is NOT the selected vertex
	var otherV = (canvas.select(".vertex.selected").classed("tac") ? e.r : e.l); // ID
	otherV = canvas.select("#" + otherV).datum(); // Vertex object

	showInfo(otherV, sidePanel.select("#connected-char"));

	// Show connections between characters in a bulleted list
	var connections = d3.select("#connections").html("");
	connections.append("h2")
		.html("Connections");
	var ul = connections.append("ul");
	d3.text("blurbs/" + e.l + "-" + e.r, function(error, blurb) {
			if(error == null) {
				blurb = blurb.split("\n"); // Each newline marks a new bullet
				for(var i = 0; i < blurb.length; i++) {
					blurb[i] = blurb[i].trim();
					if(blurb[i].length == 0) // Skip empty lines
						continue;
					ul.append("li").html(blurb[i]);
				}
			}
			else
				console.log(error);
		});

}

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

// Draw vertices
var vertices = canvas.selectAll(".vertex") // Should be empty
	.data(vertexList)
  .enter().append("g")
	.classed("vertex", true)
	.classed("tac", function(v) {return v.series == "tac";})
	.classed("asoiaf", function(v) {return v.series == "asoiaf";})
	.attr("id", function(v) {return v.id;})
	.attr("transform", function(v) {
			var pos = vertexPos(v);
			return "translate(" + pos.x + "," + pos.y + ")";
		});

vertices.append("circle")
	.attr("r", VTX_RAD);

vertices.append("text")
	.text(function(v) {return v.name;})
	.attr("x", function(v) {return v.series == "tac" ? -LABEL_OFFSET : LABEL_OFFSET;})
	.attr("y", 4);

// Draw edges

var edges = canvas.selectAll(".edge"); // Should be empty
var pairsProcessed = 0;

// Return callback for adding edge to edgeList
function addEdge(e) {
	return function() {

		if(this.status == 200 || this.status == 0) // File exists; add an edge
			edgeList.push(e);

		drawIfDone();

	};
}

// Draw edges when done with last pair
function drawIfDone() {
	if(++pairsProcessed == tac_chars.length * asoiaf_chars.length) {
		// Done with last pair; draw edges
		edges = edges.data(edgeList)
		  .enter().append("line")
			.attr("x1", vertexPos("clemence").x) // Use any TAC character
			.attr("y1", function(e) {return vertexPos(e.l).y;})
			.attr("x2", vertexPos("sansa").x) // Use any ASOIAF character
			.attr("y2", function(e) {return vertexPos(e.r).y;})
			.on("click", edgeClicked)
			.classed("edge", true);

		vertices.on("click", vertexClicked);
	}
}

for(var i = 0; i < tac_chars.length; i++) {
	for(var j = 0; j < asoiaf_chars.length; j++) {
		var req = new XMLHttpRequest();
		var e = {l: tac_chars[i], r: asoiaf_chars[j]};
		req.open("HEAD", "blurbs/" + e.l + "-" + e.r, true); // True makes it asynchronous
		req.onload = addEdge(e);
		req.onerror = drawIfDone; // onload not called; still darw edges if done
		req.send();
	}
}
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustabl<commit_msg>Someone poisoned the waterhole!<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//// poor-man's enums

var RED = 'r'; // always goes first
var BLACK = 'b';
var EMPTY = '.';

var WIDTH = 7;
var HEIGHT = 6;

var IN_PROGRESS = 0;
var RED_WON = 1;
var BLACK_WON = 2;
var DRAW = 3;

var ERROR_ILLEGAL_MOVE = 0;
var ERROR_NO_LEGAL_MOVES_FOUND = 1;

///////////////////////////////////////////////////////////////////////////////
//// game-agnostic primatives

Array.prototype.clone = function() {
	return this.slice(0);
};

function clone2DArray(array) {
    var a = [];
    for(var i = 0; i < array.length; ++i) {
        a.push(array[i].clone());
    }
    return a;
}

function initArray(size, value) {
    var array = [];
    for(var i = 0; i < size; ++i) {
        array.push(value);
    }
    return array;
}

function init2DArray(width, height, value) {
    var array = [];
    for(var x = 0; x < width; ++x) {
        array[x] = initArray(height, value);
    }
    return array;
}

function incKey(obj, key) {
    if(!(key in obj)) {
        obj[key] = 0;
    }
    obj[key]++;
    return obj;
}

///////////////////////////////////////////////////////////////////////////////
//// Connect Four logic

function Board() {
    // (0, 0) is bottom left
    this.board = init2DArray(WIDTH, HEIGHT, EMPTY);
    this.turn = RED;
    this.status = IN_PROGRESS;
    this.moveHistory = [];
}

Board.prototype.clone = function() {
    var b = new Board();
    b.board = clone2DArray(this.board);
    b.turn = this.turn;
    b.status = this.status;
    b.moveHistory = this.moveHistory.clone();
    return b;
};

Board.prototype.toString = function() {
    var rows = [];
    rows.push("0  1  2  3  4  5  6");
    rows.push("-------------------");
    for(var y = HEIGHT - 1; y >= 0; --y) {
        var row = [];
        for(var x = 0; x < WIDTH; ++x) {
            row.push(this.board[x][y]);
        }
        rows.push(row.join("  "));
    }
    rows.push("===================");
    rows.push("Status: " + this._prettyStatus(this.status));
    return rows.join('\n');
};

Board.prototype._prettyStatus = function(status) {
    switch(status) {
        case RED_WON:
            return "red wins!";
        case BLACK_WON:
            return "black wins!";
        case DRAW:
            return "draw";
        case IN_PROGRESS:
            return "in progress...";
    }
};

// destructive operation
Board.prototype.makeMove = function(move) {
    if(!this.isLegalMove(move)) {
        throw ERROR_ILLEGAL_MOVE;
    }
    var y = HEIGHT - 1;
    while(y > 0 && this.board[move][y - 1] == EMPTY) {
        y--;
    }
    this.board[move][y] = this.turn;
    this.moveHistory.push(move);
    this.status = this._calcStatus([move, y], this.turn);
    this.turn = this.turn == RED ? BLACK : RED;
    return this;
};

Board.prototype.isLegalMove = function(move) {
    return this.board[move][HEIGHT - 1] == EMPTY;
};

Board.prototype._calcStatus = function(pos, turn) {
    var winCode = turn == RED ? RED_WON : BLACK_WON;
    if(this._dirCheck(pos, turn, [0, -1]) >= 3) {
        return winCode;
    }
    if(this._dirCheck(pos, turn, [1, 0]) + this._dirCheck(pos, turn, [-1, 0]) >= 3) {
        return winCode;
    }
    if(this._dirCheck(pos, turn, [1, 1]) + this._dirCheck(pos, turn, [-1, -1]) >= 3) {
        return winCode;
    }
    if(this._dirCheck(pos, turn, [-1, 1]) + this._dirCheck(pos, turn, [1, -1]) >= 3) {
        return winCode;
    }

    if(this._isDrawn()) {
        return DRAW;
    }

    return IN_PROGRESS;
};

// Starting from a position on the board, and given a direction, return
// how many pieces of a given color are in that direction in a row.
Board.prototype._dirCheck = function(pos, turn, vec) {
    for(var factor = 1; factor <= 3; ++factor) {
        var x = pos[0] + vec[0] * factor;
        var y = pos[1] + vec[1] * factor;
        if(x < 0 || x > WIDTH - 1 || y < 0 || y > HEIGHT - 1
                || this.board[x][y] != turn) {
            return factor - 1;
        }
    }
    return 3;
};

Board.prototype._isDrawn = function() {
    return this.moveHistory.length >= WIDTH * HEIGHT;
};

///////////////////////////////////////////////////////////////////////////////
//// playing algorithms

function randomMove() {
    return Math.floor(WIDTH * Math.random());
}

function randomLegalMove(board) {
    var move = randomMove();
    var tries = 100;
    while(!board.isLegalMove(move)) {
        move = randomMove();
        tries--;
        if(tries < 0) {
            throw ERROR_NO_LEGAL_MOVES_FOUND;
        }
    }
    return move;
}

function oppositeColor(color) {
    return color == RED ? BLACK : RED;
}

function IWon(myColor, boardStatus) {
    return (myColor == RED && boardStatus == RED_WON)
        || (myColor == BLACK && boardStatus == BLACK_WON);
}

function ILost(myColor, boardStatus) {
    return (myColor == RED && boardStatus == BLACK_WON)
        || (myColor == BLACK && boardStatus == RED_WON);
}

// Strategy: make any random legal move
function ChaosMonkey(color) {
    this.color = color;
}

ChaosMonkey.prototype.description = function() {
    return "Chaos Monkey";
};

ChaosMonkey.prototype.nextMove = randomLegalMove;

// Stategy: most simple Monte Carlo.
// Can configure number of simulations to run.
function SimpleMonteCarlo(color, tries) {
    this.color = color;
    this.tries = tries;
    this.weightsHistory = [];
}

SimpleMonteCarlo.prototype.description = function() {
    return "Simple Monte Carlo, " + this.tries + " tries";
};

SimpleMonteCarlo.prototype.nextMove = function(board) {
    var moveScores = initArray(WIDTH, 0);
    for(var t = 0; t < this.tries; ++t) {
        var move = randomMove();
        var finalStatus = this.simulateFromMoveToEndOfGame(board, move);
        if(finalStatus == DRAW) {
            moveScores[move] += 0;
        } else if(IWon(this.color, finalStatus)) {
            moveScores[move]++;
        } else if(ILost(this.color, finalStatus)) {
           moveScores[move]--;
        } else if(finalStatus == ERROR_ILLEGAL_MOVE) {
            moveScores[move] -= 1000;
        }
    }
    this.weightsHistory.push(moveScores);
    return moveScores.indexOf(Math.max.apply(null, moveScores));
}
;
SimpleMonteCarlo.prototype.simulateFromMoveToEndOfGame = function(board, moveToTest) {
    if(!board.isLegalMove(moveToTest)) {
        return ERROR_ILLEGAL_MOVE;
    }
    var b = board.clone();
    b.makeMove(moveToTest);
    while(b.status == IN_PROGRESS) {
        b.makeMove(randomLegalMove(b));
    }
    return b.status;
};

///////////////////////////////////////////////////////////////////////////////
//// running games

// playerA must be red and will go first
function playSingleGame(botA, botB) {
    var board = new Board();
    while(true) {
        board.makeMove(botA.nextMove(board));
        if(board.status != IN_PROGRESS) {
            return board;
        }
        board.makeMove(botB.nextMove(board));
        if(board.status != IN_PROGRESS) {
            return board;
        }
    }
}

// The bot factory should take a single argument: color. Both bots will have
// their chance to go first.
function playManyGames(botFactoryA, botFactoryB, numOfGames) {
    var gamesLog = [];
    for(var i = 0; i < numOfGames; ++i) {
        var red, black, winner, loser, playerAisRed, winnerId;
        if(Math.random() < 0.5) {
            red = botFactoryA(RED);
            black = botFactoryB(BLACK);
            playerAisRed = true;
        } else {
            red = botFactoryB(RED);
            black = botFactoryA(BLACK);
            playerAisRed = false;
        }
        var board = playSingleGame(red, black);
        if(board.status == RED_WON) {
            winner = red;
            loser = black;
            winnerId = playerAisRed ? 1 : 2;
        } else if(board.status == BLACK_WON) {
            winner = black;
            loser = red;
            winnerId = playerAisRed ? 2 : 1;
        } else {
            winner = DRAW;
            loser = DRAW;
            winnerId = 0;
        }
        gamesLog.push({winnerId: winnerId,
            winner: winner, loser: loser,
            board: board});
    }
    return gamesLog;
}

///////////////////////////////////////////////////////////////////////////////
//// analysis tools

// generate high-level totals of who won how many games
function summarizeGames(games) {
    var totals = {};
    for(var i = 0; i < games.length; ++i) {
        if(games[i].winner === DRAW) {
            incKey(totals, "draw");
        } else {
            incKey(totals, games[i].winner.description());
        }
    }
    return totals;
}

// find an example of a bot losing to another bot
function findLoss(botFactoryA, botFactoryB, desiredLoserId) {
    var game;
    do {
        game = playManyGames(botFactoryA, botFactoryB, 1)[0];
    } while(game.winnerId == desiredLoserId);
    return game;
}

// print the blow-by-blow, with weight statistics, of a
// monte carlo algorithm loss
function replayMonteCarloLoss(game) {
    var board = new Board();
    var weightsTurn = 0;
    console.log(game);
    console.log(board.toString());
    for(var i = 0; i < game.board.moveHistory.length; ++i) {
        board.makeMove(game.board.moveHistory[i]);
        console.log(board.toString());
        if(board.turn == game.loser.color && board.status == IN_PROGRESS) {
            console.log(game.loser.weightsHistory[weightsTurn]);
            weightsTurn++;
        }
    }
}

///////////////////////////////////////////////////////////////////////////////
//// main

// bot factories
var monkey = function(color) { return new ChaosMonkey(color) ; };
var smc100 = function(color) { return new SimpleMonteCarlo(color, 100); };
var smc200 = function(color) { return new SimpleMonteCarlo(color, 200); };

// console.log(summarizeGames(playManyGames(smc100, smc200, 1000)));
// console.log(summarizeGames(playManyGames(monkey, smc200, 1000)));

replayMonteCarloLoss(findLoss(monkey, smc100, 2));<commit_msg>added wildly successful DepthMatters bot<commit_after>///////////////////////////////////////////////////////////////////////////////
//// poor-man's enums

var RED = 'r'; // always goes first
var BLACK = 'b';
var EMPTY = '.';

var WIDTH = 7;
var HEIGHT = 6;

var IN_PROGRESS = 0;
var RED_WON = 1;
var BLACK_WON = 2;
var DRAW = 3;

var ERROR_ILLEGAL_MOVE = 0;
var ERROR_NO_LEGAL_MOVES_FOUND = 1;

///////////////////////////////////////////////////////////////////////////////
//// game-agnostic primatives

Array.prototype.clone = function() {
	return this.slice(0);
};

function clone2DArray(array) {
    var a = [];
    for(var i = 0; i < array.length; ++i) {
        a.push(array[i].clone());
    }
    return a;
}

function initArray(size, value) {
    var array = [];
    for(var i = 0; i < size; ++i) {
        array.push(value);
    }
    return array;
}

function init2DArray(width, height, value) {
    var array = [];
    for(var x = 0; x < width; ++x) {
        array[x] = initArray(height, value);
    }
    return array;
}

function incKey(obj, key) {
    if(!(key in obj)) {
        obj[key] = 0;
    }
    obj[key]++;
    return obj;
}

///////////////////////////////////////////////////////////////////////////////
//// Connect Four logic

function Board() {
    // (0, 0) is bottom left
    this.board = init2DArray(WIDTH, HEIGHT, EMPTY);
    this.turn = RED;
    this.status = IN_PROGRESS;
    this.moveHistory = [];
}

Board.prototype.clone = function() {
    var b = new Board();
    b.board = clone2DArray(this.board);
    b.turn = this.turn;
    b.status = this.status;
    b.moveHistory = this.moveHistory.clone();
    return b;
};

Board.prototype.toString = function() {
    var rows = [];
    rows.push("0  1  2  3  4  5  6");
    rows.push("-------------------");
    for(var y = HEIGHT - 1; y >= 0; --y) {
        var row = [];
        for(var x = 0; x < WIDTH; ++x) {
            row.push(this.board[x][y]);
        }
        rows.push(row.join("  "));
    }
    rows.push("===================");
    rows.push("Status: " + this._prettyStatus(this.status));
    return rows.join('\n');
};

Board.prototype._prettyStatus = function(status) {
    switch(status) {
        case RED_WON:
            return "red wins!";
        case BLACK_WON:
            return "black wins!";
        case DRAW:
            return "draw";
        case IN_PROGRESS:
            return "in progress...";
    }
};

// destructive operation
Board.prototype.makeMove = function(move) {
    if(!this.isLegalMove(move)) {
        throw ERROR_ILLEGAL_MOVE;
    }
    var y = HEIGHT - 1;
    while(y > 0 && this.board[move][y - 1] == EMPTY) {
        y--;
    }
    this.board[move][y] = this.turn;
    this.moveHistory.push(move);
    this.status = this._calcStatus([move, y], this.turn);
    this.turn = this.turn == RED ? BLACK : RED;
    return this;
};

Board.prototype.isLegalMove = function(move) {
    return this.board[move][HEIGHT - 1] == EMPTY;
};

Board.prototype._calcStatus = function(pos, turn) {
    var winCode = turn == RED ? RED_WON : BLACK_WON;
    if(this._dirCheck(pos, turn, [0, -1]) >= 3) {
        return winCode;
    }
    if(this._dirCheck(pos, turn, [1, 0]) + this._dirCheck(pos, turn, [-1, 0]) >= 3) {
        return winCode;
    }
    if(this._dirCheck(pos, turn, [1, 1]) + this._dirCheck(pos, turn, [-1, -1]) >= 3) {
        return winCode;
    }
    if(this._dirCheck(pos, turn, [-1, 1]) + this._dirCheck(pos, turn, [1, -1]) >= 3) {
        return winCode;
    }

    if(this._isDrawn()) {
        return DRAW;
    }

    return IN_PROGRESS;
};

// Starting from a position on the board, and given a direction, return
// how many pieces of a given color are in that direction in a row.
Board.prototype._dirCheck = function(pos, turn, vec) {
    for(var factor = 1; factor <= 3; ++factor) {
        var x = pos[0] + vec[0] * factor;
        var y = pos[1] + vec[1] * factor;
        if(x < 0 || x > WIDTH - 1 || y < 0 || y > HEIGHT - 1
                || this.board[x][y] != turn) {
            return factor - 1;
        }
    }
    return 3;
};

Board.prototype._isDrawn = function() {
    return this.moveHistory.length >= WIDTH * HEIGHT;
};

///////////////////////////////////////////////////////////////////////////////
//// playing algorithms

function randomMove() {
    return Math.floor(WIDTH * Math.random());
}

function randomLegalMove(board) {
    var move = randomMove();
    var tries = 100;
    while(!board.isLegalMove(move)) {
        move = randomMove();
        tries--;
        if(tries < 0) {
            throw ERROR_NO_LEGAL_MOVES_FOUND;
        }
    }
    return move;
}

function oppositeColor(color) {
    return color == RED ? BLACK : RED;
}

function IWon(myColor, boardStatus) {
    return (myColor == RED && boardStatus == RED_WON)
        || (myColor == BLACK && boardStatus == BLACK_WON);
}

function ILost(myColor, boardStatus) {
    return (myColor == RED && boardStatus == BLACK_WON)
        || (myColor == BLACK && boardStatus == RED_WON);
}

// Strategy: make any random legal move
function ChaosMonkey(color) {
    this.color = color;
}

ChaosMonkey.prototype.description = function() {
    return "Chaos Monkey";
};

ChaosMonkey.prototype.nextMove = randomLegalMove;

function Lefty(color) {
    this.color = color;
}

// Strategy: make left-most legal move
Lefty.prototype.description = function() {
    return "Lefty";
};

Lefty.prototype.nextMove = function(board) {
    for(var x = 0; x < WIDTH; ++x) {
        if(board.isLegalMove(x)) {
            return x;
        }
    }
};

// Stategy: most simple Monte Carlo.
// Can configure number of simulations to run.
function SimpleMonteCarlo(color, tries) {
    this.color = color;
    this.tries = tries;
    this.weightsHistory = [];
}

SimpleMonteCarlo.prototype.description = function() {
    return "Simple Monte Carlo, " + this.tries + " tries";
};

SimpleMonteCarlo.prototype.nextMove = function(board) {
    var moveScores = initArray(WIDTH, 0);
    for(var t = 0; t < this.tries; ++t) {
        var move = randomMove();
        var finalStatus = this.simulateFromMoveToEndOfGame(board, move);
        if(finalStatus == DRAW) {
            moveScores[move] += 0;
        } else if(IWon(this.color, finalStatus)) {
            moveScores[move]++;
        } else if(ILost(this.color, finalStatus)) {
           moveScores[move]--;
        } else if(finalStatus == ERROR_ILLEGAL_MOVE) {
            moveScores[move] -= 1000;
        }
    }
    this.weightsHistory.push(moveScores);
    return moveScores.indexOf(Math.max.apply(null, moveScores));
};

SimpleMonteCarlo.prototype.simulateFromMoveToEndOfGame = function(board, moveToTest) {
    if(!board.isLegalMove(moveToTest)) {
        return ERROR_ILLEGAL_MOVE;
    }
    var b = board.clone();
    b.makeMove(moveToTest);
    while(b.status == IN_PROGRESS) {
        b.makeMove(randomLegalMove(b));
    }
    return b.status;
};

function DepthMatters(color, tries) {
    this.color = color;
    this.tries = tries;
    this.weightsHistory = [];
}

DepthMatters.prototype.description = function() {
    return "Depth Matters, " + this.tries + " tries";
};

DepthMatters.prototype.nextMove = function(board) {
    var moveScores = initArray(WIDTH, 0);
    for(var t = 0; t < this.tries; ++t) {
        var move = randomMove();
        var finalBoard = this.simulateFromMoveToEndOfGame(board, move);
        if(finalBoard == ERROR_ILLEGAL_MOVE) {
            moveScores[move] -= 1000;
        } else if(IWon(this.color, finalBoard.status)) {
            moveScores[move]++;
        } else if(ILost(this.color, finalBoard.status)) {
            if(finalBoard.moveHistory.length - board.moveHistory.length < 3) {
                moveScores[move] -= 100;
            } else {
                moveScores[move]--;
            }
        } else if(finalBoard.status == DRAW) {
            moveScores[move] += 0;
        }
    }
    this.weightsHistory.push(moveScores);
    return moveScores.indexOf(Math.max.apply(null, moveScores));
};

DepthMatters.prototype.simulateFromMoveToEndOfGame = function(board, moveToTest) {
    if(!board.isLegalMove(moveToTest)) {
        return ERROR_ILLEGAL_MOVE;
    }
    var b = board.clone();
    b.makeMove(moveToTest);
    while(b.status == IN_PROGRESS) {
        b.makeMove(randomLegalMove(b));
    }
    return b;
};

///////////////////////////////////////////////////////////////////////////////
//// running games

// playerA must be red and will go first
function playSingleGame(botA, botB) {
    var board = new Board();
    while(true) {
        board.makeMove(botA.nextMove(board));
        if(board.status != IN_PROGRESS) {
            return board;
        }
        board.makeMove(botB.nextMove(board));
        if(board.status != IN_PROGRESS) {
            return board;
        }
    }
}

// The bot factory should take a single argument: color. Both bots will have
// their chance to go first.
function playManyGames(botFactoryA, botFactoryB, numOfGames) {
    var gamesLog = [];
    for(var i = 0; i < numOfGames; ++i) {
        var red, black, winner, loser, playerAisRed, winnerId;
        if(Math.random() < 0.5) {
            red = botFactoryA(RED);
            black = botFactoryB(BLACK);
            playerAisRed = true;
        } else {
            red = botFactoryB(RED);
            black = botFactoryA(BLACK);
            playerAisRed = false;
        }
        var board = playSingleGame(red, black);
        if(board.status == RED_WON) {
            winner = red;
            loser = black;
            winnerId = playerAisRed ? 1 : 2;
        } else if(board.status == BLACK_WON) {
            winner = black;
            loser = red;
            winnerId = playerAisRed ? 2 : 1;
        } else {
            winner = DRAW;
            loser = DRAW;
            winnerId = 0;
        }
        gamesLog.push({winnerId: winnerId,
            winner: winner, loser: loser,
            board: board});
    }
    return gamesLog;
}

///////////////////////////////////////////////////////////////////////////////
//// analysis tools

// generate high-level totals of who won how many games
function summarizeGames(games) {
    var totals = {};
    for(var i = 0; i < games.length; ++i) {
        if(games[i].winner === DRAW) {
            incKey(totals, "draw");
        } else {
            incKey(totals, games[i].winner.description());
        }
    }
    return totals;
}

// find an example of a bot losing to another bot
function findLoss(botFactoryA, botFactoryB, desiredLoserId) {
    var game;
    var attempts = 0;
    do {
        game = playManyGames(botFactoryA, botFactoryB, 1)[0];
        attempts++;
    } while(game.winnerId == desiredLoserId);
    console.log("Lost game found in " + attempts + " attempts.");
    return game;
}

// print the blow-by-blow, with weight statistics, of a
// monte carlo algorithm loss
function replayMonteCarloLoss(game) {
    _replayMonteCarlo(game, "loser");
}

function replayMonteCarloWin(game) {
    _replayMonteCarlo(game, "winner");
}

function _replayMonteCarlo(game, winnerOrLoser) {
    var board = new Board();
    var weightsTurn = 0;
    console.log(game);
    console.log(board.toString());
    for(var i = 0; i < game.board.moveHistory.length; ++i) {
        board.makeMove(game.board.moveHistory[i]);
        console.log(board.toString());
        if(board.turn == game[winnerOrLoser].color && board.status == IN_PROGRESS) {
            console.log(game[winnerOrLoser].weightsHistory[weightsTurn]);
            weightsTurn++;
        }
    }
}

///////////////////////////////////////////////////////////////////////////////
//// main

// bot factories
var monkey = function(color) { return new ChaosMonkey(color); };
var lefty = function(color) { return new Lefty(color); };
var smc100 = function(color) { return new SimpleMonteCarlo(color, 100); };
var smc200 = function(color) { return new SimpleMonteCarlo(color, 200); };
var smc300 = function(color) { return new SimpleMonteCarlo(color, 300); };
var depth100 = function(color) { return new DepthMatters(color, 100); };
var depth300 = function(color) { return new DepthMatters(color, 300); };

console.time("main");

// console.log(summarizeGames(playManyGames(smc100, smc200, 1000)));
// console.log(summarizeGames(playManyGames(monkey, smc200, 1000)));
console.log(summarizeGames(playManyGames(depth300, monkey, 500)));
console.log(summarizeGames(playManyGames(depth300, lefty, 500)));
console.log(summarizeGames(playManyGames(depth300, smc100, 500)));
console.log(summarizeGames(playManyGames(depth300, smc300, 500)));

// replayMonteCarloWin(findLoss(monkey, depth100, 1));

console.timeEnd("main");<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random<commit_msg>Fixed a typo<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random(<|endoftext|>


<commit_before>/**
 * @description A logging tool for node js.
 * @file main.js
 * @author Johannes Tegnér
 * @contributors Henrik Myntti
 */

module.exports = (function(){

  var colors = require('./colors.js');
  var util = require('util');

  var shouldPrintFunctionName = true;

  var tags = {
      trace:    true
    , debug:    true
    , error:    true
    , warning:  true
    , info:     true
    , todo:     true
  };

  var tagcolors = {
      trace:    colors.textnormal.cyan
    , debug:    colors.textnormal.blue
    , error:    colors.textnormal.red
    , warning:  colors.textnormal.yellow
    , info:     colors.textnormal.white
    , todo:     colors.textnormal.green
  };

 /**
   * Print a debug string formatted as "(date) tag: string with %s|d|j values" where % values will be replaced with passed arguments.
   * @param {string} tag Tag to use.
   * @param {string} string String to print.
   * @param {string} color Color code.
   * @param {null|undefined|Array} args Arguments.
   */
  var print = function(tag, string, color, args, toStdErr) {
    if(args !== undefined && args !== null) {
      for(var i=0; i<args.length; i++){
        string = util.format(string, args[i]);
      }
    }
    // [TagColor]Tag[/TagColor][Cyan]\tDate[/Cyan]Text\n
    var out = util.format("%s%s%s%s\t(%s)%s: %s%s", color, tag, colors.reset, colors.textnormal.cyan, (new Date()).toLocaleTimeString(), getCaller(3),  colors.reset, string);
    if(toStdErr){
      console.error(out);
    } else {
      console.log(out);
    }
  };

  var getCaller = function(depth) {
    if(!shouldPrintFunctionName) {
      return "";
    }
    depth = depth === undefined ? 0 : depth;
    var funcName = "global/anonymous";
    var caller = arguments.callee.caller;
    for(var i=1;i<depth;i++) {
      if(caller.caller) {
        caller = caller.caller;
      }
    }
    if(caller.name !== "") {
      funcName = caller.name;
    }
    return "[" + funcName + "]";
  };

  return {
    /**
     * Depth to use when iterating objects.
     */
    depth: 3,
    /**
     * If function names should be printed in the output, this should be set to true.
     * Default is true.
     * @param {boolean} state State to set it to.
     */
    showFunctionName: function(state) {
      shouldPrintFunctionName = state;
    },
    /**
     * Set color of a tag.
     * @param {string} tag Tag name (debug, trace, error, info or warning).
     * @param {string} color Color as string (black, red, green, yellow, blue, purple, cyan, white).
     */
    setcolor: function(tag, color) {
      color = color.toLowerCase();
      tag = tag.toLowerCase();
      if(colors.textnormal[color] === undefined) {
        print("error", "Failed to set color of tag with name %s. The color (%s) is not a valid color.", colors.textnormal.red, [tag, color]);
      } else if(tagcolors[tag] === undefined) {
        print("error", "Failed to set color of tag with name %s. The tag does not exist.", colors.textnormal.red, [tag]);
      }
      tagcolors[tag] = colors.textnormal[color];
    },
    /**
     * Set one or many tags to active or inactive.
     * @param {boolean} value True if active, false if inactive.
     * @param {...} args Argument list, one or many string of which to set to given value.
     */
    set: function(value, args) {
      for(var i=1;i<arguments.length;i++) {
        var tag = arguments[i].toLowerCase();
        if(tag in tags) {
          tags[tag] = value;
        } else {
          print("error", "Failed to set tag " + tag + " to " + (value ? "Active" : "Inactive") + ", tag do not exist.", colors.textnormal.red, null);
        }
      }
    },
    /**
     * Get current state of given tag, or the whole tags object.
     * @param {undefined|string} tag Tag as string or omitted for whole tags object.
     * @return {object|boolean} If tag is active, true, else false. Or whole tags object if tag is omitted.
     */
    get: function(tag) {
      if(tag === undefined){
        return tags;
      } else {
        tag = tag.toLowerCase();
        if(tag in tags) {
          return tags[tag];
        }
      }
      print("error", "Failed to get tag " + tag + ", tag do not exist.", colors.textnormal.red, null);
      return false;
    },
    /**
     * Output arguments to trace log.
     * @param {...} args Argument list.
     */
    trace: function(args) {
      if(tags.trace) {
        var reg = new RegExp('\r?\n','g');
        var out = tagcolors.trace + "trace\t(" + (new Date()).toLocaleTimeString() + ")" + getCaller(2) + ": " + colors.reset + tagcolors.trace + " [ length: " + arguments.length + " ] " + colors.reset + "\n";
        for (var i = 0, il = arguments.length; i < il; i++) {
          out += tagcolors.trace + "["+ i + "]\t" + colors.reset;
          var text = util.inspect(arguments[i], { showHidden: true, depth: this.depth });
          out += text.replace(reg, tagcolors.trace + "\n *\t" + colors.reset) + colors.reset;
          out += "\n";
        }
        out += tagcolors.trace + "end trace" + colors.reset;
        console.log(out);
      }
    },
    /**
     * Prints a debug string to stdout.
     * The string uses % placeholders and replaces them with arguments passed.
     * Possible placeholders: %s - string, %d - number, %j json.
     * @param {string} str String to print.
     * @param {...} args Argument list.
     */
    debug: function(str, args) {
      if(tags.debug) {
        print("Debug", str, tagcolors.debug, (args !== undefined ? Array.prototype.slice.call(arguments, 1) : []));
      }
    },
    /**
     * Prints a error string to stdout.
     * The string uses % placeholders and replaces them with arguments passed.
     * Possible placeholders: %s - string, %d - number, %j json.
     * @param {string} str String to print.
     * @param {...} args Argument list.
     */
    error: function(str, args) {
      if(tags.error) {
         print("Error", str, tagcolors.error, (args !== undefined ? Array.prototype.slice.call(arguments, 1) : []), true);
      }
    },
    /**
     * Prints a warning string to stdout.
     * The string uses % placeholders and replaces them with arguments passed.
     * Possible placeholders: %s - string, %d - number, %j json.
     * @param {string} str String to print.
     * @param {...} args Argument list.
     */
    warning: function(str, args) {
      if(tags.warning) {
        print("Warning", str, tagcolors.warning, (args !== undefined ? Array.prototype.slice.call(arguments, 1) : []));
      }
    },
    /**
     * Prints a info string to stdout.
     * The string uses % placeholders and replaces them with arguments passed.
     * Possible placeholders: %s - string, %d - number, %j json.
     * @param {string} str String to print.
     * @param {...} args Argument list.
     */
    info: function(str, args) {
      if(tags.info) {
        print("Info", str, tagcolors.info, (args !== undefined ? Array.prototype.slice.call(arguments, 1) : []));
      }
    },
    todo: function(str, args) {
      if(tags.todo){
        print("Todo", str, tagcolors.todo, (args !== undefined ? Array.prototype.slice.call(arguments,1) : []));
      }
    }
  };
})();
<commit_msg>Minor fix, replaced \n with os.EOL (\r\n for win and \n for others). Set showFunctionName to false by default.<commit_after>/**
 * @description A logging tool for node js.
 * @file main.js
 * @author Johannes Tegnér
 * @contributors Henrik Myntti
 */

module.exports = (function(){

  var colors = require('./colors.js');
  var util = require('util');
  var os = require('os');

  var shouldPrintFunctionName = false;

  var tags = {
      trace:    true
    , debug:    true
    , error:    true
    , warning:  true
    , info:     true
    , todo:     true
  };

  var tagcolors = {
      trace:    colors.textnormal.cyan
    , debug:    colors.textnormal.blue
    , error:    colors.textnormal.red
    , warning:  colors.textnormal.yellow
    , info:     colors.textnormal.white
    , todo:     colors.textnormal.green
  };

 /**
   * Print a debug string formatted as "(date) tag: string with %s|d|j values" where % values will be replaced with passed arguments.
   * @param {string} tag Tag to use.
   * @param {string} string String to print.
   * @param {string} color Color code.
   * @param {null|undefined|Array} args Arguments.
   * @param {boolean} toStdErr If the data should be printed to stderr or stdout.
   */
  var print = function(tag, string, color, args, toStdErr) {
    if(args !== undefined && args !== null) {
      for(var i=0; i<args.length; i++){
        string = util.format(string, args[i]);
      }
    }
    // [TagColor]Tag[/TagColor][Cyan]\tDate[/Cyan]Text\n
    var out = util.format("%s%s%s%s\t(%s)%s: %s%s", color, tag, colors.reset, colors.textnormal.cyan, (new Date()).toLocaleTimeString(), getCaller(3),  colors.reset, string);
    if(toStdErr){
      console.error(out);
    } else {
      console.log(out);
    }
  };

  /**
   * Get calling function
   * @param {int} depth Depth to go in callstack.
   * @returns {string} Function name.
   */
  var getCaller = function(depth) {
    if(!shouldPrintFunctionName) {
      return "";
    }
    depth = depth === undefined ? 0 : depth;
    var funcName = "global/anonymous";
    var caller = arguments.callee.caller;
    for(var i=1;i<depth;i++) {
      if(caller.caller) {
        caller = caller.caller;
      }
    }
    if(caller.name !== "") {
      funcName = caller.name;
    }
    return "[" + funcName + "]";
  };

  return {
    /**
     * Depth to use when iterating objects.
     */
    depth: 3,
    /**
     * If function names should be printed in the output, this should be set to true.
     * Default is true.
     * @param {boolean} state State to set it to.
     */
    showFunctionName: function(state) {
      shouldPrintFunctionName = state;
    },
    /**
     * Set color of a tag.
     * @param {string} tag Tag name (debug, trace, error, info or warning).
     * @param {string} color Color as string (black, red, green, yellow, blue, purple, cyan, white).
     */
    setcolor: function(tag, color) {
      color = color.toLowerCase();
      tag = tag.toLowerCase();
      if(colors.textnormal[color] === undefined) {
        print("error", "Failed to set color of tag with name %s. The color (%s) is not a valid color.", colors.textnormal.red, [tag, color]);
      } else if(tagcolors[tag] === undefined) {
        print("error", "Failed to set color of tag with name %s. The tag does not exist.", colors.textnormal.red, [tag]);
      }
      tagcolors[tag] = colors.textnormal[color];
    },
    /**
     * Set one or many tags to active or inactive.
     * @param {boolean} value True if active, false if inactive.
     * @param {...} args Argument list, one or many string of which to set to given value.
     */
    set: function(value, args) {
      for(var i=1;i<arguments.length;i++) {
        var tag = arguments[i].toLowerCase();
        if(tag in tags) {
          tags[tag] = value;
        } else {
          print("error", "Failed to set tag " + tag + " to " + (value ? "Active" : "Inactive") + ", tag do not exist.", colors.textnormal.red, null);
        }
      }
    },
    /**
     * Get current state of given tag, or the whole tags object.
     * @param {undefined|string} tag Tag as string or omitted for whole tags object.
     * @return {object|boolean} If tag is active, true, else false. Or whole tags object if tag is omitted.
     */
    get: function(tag) {
      if(tag === undefined){
        return tags;
      } else {
        tag = tag.toLowerCase();
        if(tag in tags) {
          return tags[tag];
        }
      }
      print("error", "Failed to get tag " + tag + ", tag do not exist.", colors.textnormal.red, null);
      return false;
    },
    /**
     * Output arguments to trace log.
     * @param {...} args Argument list.
     */
    trace: function(args) {
      if(tags.trace) {
        var reg = new RegExp('\r?\n','g');
        var out = tagcolors.trace + "trace\t(" + (new Date()).toLocaleTimeString() + ")" + getCaller(2) + ": " + colors.reset + tagcolors.trace + " [ length: " + arguments.length + " ] " + colors.reset + os.EOL;
        for (var i = 0, il = arguments.length; i < il; i++) {
          out += tagcolors.trace + "["+ i + "]\t" + colors.reset;
          var text = util.inspect(arguments[i], { showHidden: true, depth: this.depth });
          out += text.replace(reg, tagcolors.trace + os.EOL + " *\t" + colors.reset) + colors.reset;
          out += os.EOL;
        }
        out += tagcolors.trace + "end trace" + colors.reset;
        console.log(out);
      }
    },
    /**
     * Prints a debug string to stdout.
     * The string uses % placeholders and replaces them with arguments passed.
     * Possible placeholders: %s - string, %d - number, %j json.
     * @param {string} str String to print.
     * @param {...} args Argument list.
     */
    debug: function(str, args) {
      if(tags.debug) {
        print("Debug", str, tagcolors.debug, (args !== undefined ? Array.prototype.slice.call(arguments, 1) : []));
      }
    },
    /**
     * Prints a error string to stdout.
     * The string uses % placeholders and replaces them with arguments passed.
     * Possible placeholders: %s - string, %d - number, %j json.
     * @param {string} str String to print.
     * @param {...} args Argument list.
     */
    error: function(str, args) {
      if(tags.error) {
         print("Error", str, tagcolors.error, (args !== undefined ? Array.prototype.slice.call(arguments, 1) : []), true);
      }
    },
    /**
     * Prints a warning string to stdout.
     * The string uses % placeholders and replaces them with arguments passed.
     * Possible placeholders: %s - string, %d - number, %j json.
     * @param {string} str String to print.
     * @param {...} args Argument list.
     */
    warning: function(str, args) {
      if(tags.warning) {
        print("Warning", str, tagcolors.warning, (args !== undefined ? Array.prototype.slice.call(arguments, 1) : []));
      }
    },
    /**
     * Prints a info string to stdout.
     * The string uses % placeholders and replaces them with arguments passed.
     * Possible placeholders: %s - string, %d - number, %j json.
     * @param {string} str String to print.
     * @param {...} args Argument list.
     */
    info: function(str, args) {
      if(tags.info) {
        print("Info", str, tagcolors.info, (args !== undefined ? Array.prototype.slice.call(arguments, 1) : []));
      }
    },
    todo: function(str, args) {
      if(tags.todo){
        print("Todo", str, tagcolors.todo, (args !== undefined ? Array.prototype.slice.call(arguments,1) : []));
      }
    }
  };
})();
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//Firs<commit_msg>Fixing an error introduced in the last commit<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First<|endoftext|>


<commit_before>var board = [
[{symbol: '\u2656', selected: 0, highlighted: 0, color: 'white', type: 'rook'},
{symbol: '\u2658', selected: 0, highlighted: 0, color: 'white', type: 'knight'},
{symbol: '\u2657', selected: 0, highlighted: 0, color: 'white', type: 'bishop'},
{symbol: '\u2655', selected: 0, highlighted: 0, color: 'white', type: 'queen'},
{symbol: '\u2654', selected: 0, highlighted: 0, color: 'white', type: 'king'},
{symbol: '\u2657', selected: 0, highlighted: 0, color: 'white', type: 'bishop'},
{symbol: '\u2658', selected: 0, highlighted: 0, color: 'white', type: 'knight'},
{symbol: '\u2656', selected: 0, highlighted: 0, color: 'white', type: 'rook'}],
[{symbol: '\u2659', selected: 0, highlighted: 0, color: 'white', type: 'pawn'},
{symbol: '\u2659', selected: 0, highlighted: 0, color: 'white', type: 'pawn'},
{symbol: '\u2659', selected: 0, highlighted: 0, color: 'white', type: 'pawn'},
{symbol: '\u2659', selected: 0, highlighted: 0, color: 'white', type: 'pawn'},
{symbol: '\u2659', selected: 0, highlighted: 0, color: 'white', type: 'pawn'},
{symbol: '\u2659', selected: 0, highlighted: 0, color: 'white', type: 'pawn'},
{symbol: '\u2659', selected: 0, highlighted: 0, color: 'white', type: 'pawn'},
{symbol: '\u2659', selected: 0, highlighted: 0, color: 'white', type: 'pawn'}],
[{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''}],
[{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''}],
[{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''}],
[{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''}],
[{symbol: '\u265F', selected: 0, highlighted: 0, color: 'black', type: 'pawn'},
{symbol: '\u265F', selected: 0, highlighted: 0, color: 'black', type: 'pawn'},
{symbol: '\u265F', selected: 0, highlighted: 0, color: 'black', type: 'pawn'},
{symbol: '\u265F', selected: 0, highlighted: 0, color: 'black', type: 'pawn'},
{symbol: '\u265F', selected: 0, highlighted: 0, color: 'black', type: 'pawn'},
{symbol: '\u265F', selected: 0, highlighted: 0, color: 'black', type: 'pawn'},
{symbol: '\u265F', selected: 0, highlighted: 0, color: 'black', type: 'pawn'},
{symbol: '\u265F', selected: 0, highlighted: 0, color: 'black', type: 'pawn'}],
[{symbol: '\u265C', selected: 0, highlighted: 0, color: 'black', type: 'rook'},
{symbol: '\u265E', selected: 0, highlighted: 0, color: 'black', type: 'knight'},
{symbol: '\u265D', selected: 0, highlighted: 0, color: 'black', type: 'bishop'},
{symbol: '\u265A', selected: 0, highlighted: 0, color: 'black', type: 'king'},
{symbol: '\u265B', selected: 0, highlighted: 0, color: 'black', type: 'queen'},
{symbol: '\u265D', selected: 0, highlighted: 0, color: 'black', type: 'bishop'},
{symbol: '\u265E', selected: 0, highlighted: 0, color: 'black', type: 'knight'},
{symbol: '\u265C', selected: 0, highlighted: 0, color: 'black', type: 'rook'}]];

// at https://github.com/jspencersharpe/Chess-Game.git
$(document).ready(function(){
  //Function generates the board with initial state of all the pieces
  generateGrid(board);

  //When piece is clicked, function determines which piece is selected
  currentBoardState(8, 8);
  $('td').click(function(){
  $('td').removeClass("selectedPiece");
  $(this).text();
  $(this).addClass("selectedPiece");
  var columnPosition = $(this).nextAll('td');
  var y = 7 - columnPosition.length;
  var rowPosition = $(this).parent('tr').nextAll('tr');
  var x = 7 - rowPosition.length;
  // board[x][y].selected === 1;
  console.log(x + ', ' + y);
  // console.log(board[x]);
  console.log(board[x][y]);
  var possibleMoves = rules(x, y);
  })
  // $('td').click(function(){
  //   $('td').removeClass("possibleMoves");

  // })
}); //end of DOMContentLoaded

function generateGrid(board){
  var $table = document.querySelector('#board');
$table.innerHTML = '';
  board.forEach(function(row){
  var $tr = document.createElement('tr');
  row.forEach(function(cell){
    var $td = createTableCell(cell);
    $td.textContent = cell.symbol;
    $tr.appendChild($td);
  });
  $table.appendChild($tr);
  });
}

function createTableCell(value){
  var $td = document.createElement('td');
  return $td;
}

//Loads currentBoardState() into memory
function currentBoardState(x, y){
  var board = [];
  for(var i = 0; i < x; i++){
  board[i] = [];
  for(var j = 0; j < y; j++){
    board[i][j] = board}
  }
return board;
}

function rules(x, y){
  if (board[x][y].symbol === "\u2659"){
    posX = x + 1;
    posY = y;
    console.log(posX, posY)
    board[posX][posY].highlighted = 1;
    console.log(board[posX][posY])
    if (board[posX][posY].highlighted == 1){
      $('td').addClass("possibleMoves");
    }
  }
  //highlight (possibleMoves)
  //If counter of pawns variable === 0
  //Then highlight (test[x + 1][y]) && (test[x + 2][y])
  // console.log(possibleMoves[0]);
  //.log(possibleMoves);
  //highlightPossibleMoves(possibleMoves);
}

function highlightPossibleMoves(array) {
  $('td').removeClass("possibleMoves");
  // for(var i = 0, i < 0; i++){
  $('td').addClass("possibleMoves");
  // }
}

/*Implement into moving of pieces.
 var clicks = 0;
  function onClick() {
      clicks += 1;
      document.getElementById("clicks").innerHTML = clicks;
  };

//////// Capturing Pieces

// if statement about white pieces interfering with black pieces
/
var whitePieces = [wPawn1, wPawn2, wPawn3, wPawn4];
  var whiteCaptured = [];
  whiteCaptured = pieces.slice(1, 2)
      // whiteCaptured contains [wPawn2]
*/

<commit_msg>Added and cleaned out comments on the main.js file<commit_after>// at https://github.com/jspencersharpe/Chess-Game.git
var board = [
[{symbol: '\u2656', selected: 0, highlighted: 0, color: 'white', type: 'rook'},
{symbol: '\u2658', selected: 0, highlighted: 0, color: 'white', type: 'knight'},
{symbol: '\u2657', selected: 0, highlighted: 0, color: 'white', type: 'bishop'},
{symbol: '\u2655', selected: 0, highlighted: 0, color: 'white', type: 'queen'},
{symbol: '\u2654', selected: 0, highlighted: 0, color: 'white', type: 'king'},
{symbol: '\u2657', selected: 0, highlighted: 0, color: 'white', type: 'bishop'},
{symbol: '\u2658', selected: 0, highlighted: 0, color: 'white', type: 'knight'},
{symbol: '\u2656', selected: 0, highlighted: 0, color: 'white', type: 'rook'}],
[{symbol: '\u2659', selected: 0, highlighted: 0, color: 'white', type: 'pawn'},
{symbol: '\u2659', selected: 0, highlighted: 0, color: 'white', type: 'pawn'},
{symbol: '\u2659', selected: 0, highlighted: 0, color: 'white', type: 'pawn'},
{symbol: '\u2659', selected: 0, highlighted: 0, color: 'white', type: 'pawn'},
{symbol: '\u2659', selected: 0, highlighted: 0, color: 'white', type: 'pawn'},
{symbol: '\u2659', selected: 0, highlighted: 0, color: 'white', type: 'pawn'},
{symbol: '\u2659', selected: 0, highlighted: 0, color: 'white', type: 'pawn'},
{symbol: '\u2659', selected: 0, highlighted: 0, color: 'white', type: 'pawn'}],
[{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''}],
[{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''}],
[{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''}],
[{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''},
{symbol: '', selected: 0, highlighted: 0, color: '', type: ''}],
[{symbol: '\u265F', selected: 0, highlighted: 0, color: 'black', type: 'pawn'},
{symbol: '\u265F', selected: 0, highlighted: 0, color: 'black', type: 'pawn'},
{symbol: '\u265F', selected: 0, highlighted: 0, color: 'black', type: 'pawn'},
{symbol: '\u265F', selected: 0, highlighted: 0, color: 'black', type: 'pawn'},
{symbol: '\u265F', selected: 0, highlighted: 0, color: 'black', type: 'pawn'},
{symbol: '\u265F', selected: 0, highlighted: 0, color: 'black', type: 'pawn'},
{symbol: '\u265F', selected: 0, highlighted: 0, color: 'black', type: 'pawn'},
{symbol: '\u265F', selected: 0, highlighted: 0, color: 'black', type: 'pawn'}],
[{symbol: '\u265C', selected: 0, highlighted: 0, color: 'black', type: 'rook'},
{symbol: '\u265E', selected: 0, highlighted: 0, color: 'black', type: 'knight'},
{symbol: '\u265D', selected: 0, highlighted: 0, color: 'black', type: 'bishop'},
{symbol: '\u265A', selected: 0, highlighted: 0, color: 'black', type: 'king'},
{symbol: '\u265B', selected: 0, highlighted: 0, color: 'black', type: 'queen'},
{symbol: '\u265D', selected: 0, highlighted: 0, color: 'black', type: 'bishop'},
{symbol: '\u265E', selected: 0, highlighted: 0, color: 'black', type: 'knight'},
{symbol: '\u265C', selected: 0, highlighted: 0, color: 'black', type: 'rook'}]];

$(document).ready(function(){   //Loads DOM
  generateGrid(board);  //Generates board with initial state of all the pieces
  currentBoardState(8, 8); //When piece is clicked, piece and location determined
    $('td').click(function(){
    $('td').removeClass("selectedPiece");
    $(this).text();
    $(this).addClass("selectedPiece");
    var columnPosition = $(this).nextAll('td');
    var y = 7 - columnPosition.length;
    var rowPosition = $(this).parent('tr').nextAll('tr');
    var x = 7 - rowPosition.length;
    // board[x][y].selected === 1;
    console.log(x + ', ' + y);
    console.log(board[x][y]);
    var possibleMoves = rules(x, y);
    })
}); //end of DOMContentLoaded

function generateGrid(board){ //Creates initial board of pieces
  var $table = document.querySelector('#board');
$table.innerHTML = '';
  board.forEach(function(row){
  var $tr = document.createElement('tr');
  row.forEach(function(cell){
    var $td = createTableCell(cell);
    $td.textContent = cell.symbol;
    $tr.appendChild($td);
  });
  $table.appendChild($tr);
  });
}
function createTableCell(value){ //Creates each cell on the board
  var $td = document.createElement('td');
  return $td;
}

function currentBoardState(x, y){ //Loads currentBoardState() into memory
  var board = [];
  for(var i = 0; i < x; i++){
  board[i] = [];
  for(var j = 0; j < y; j++){
    board[i][j] = board}
  }
  return board;
}

function rules(x, y){ //Implements rules to know which cells need highlighting
  if (board[x][y].symbol === "\u2659"){
    posX = x + 1;
    posY = y;
    console.log(posX, posY)
    board[posX][posY].highlighted = 1;
    console.log(board[posX][posY])
  }
  highlightPossibleMoves(posX,posY);
}

function highlightPossibleMoves(posX, posY) {
   if (board[posX][posY].highlighted === 1){
      $('td').addClass("possibleMoves"); //highlights possible moves
  }
}

  //highlight (possibleMoves)
  //If counter of pawns variable === 0
  //Then highlight (test[x + 1][y]) && (test[x + 2][y])
  // console.log(possibleMoves[0]);
  //.log(possibleMoves);
  //highlightPossibleMoves(possibleMoves);

/*Implement into moving of pieces.
 var clicks = 0;
  function onClick() {
      clicks += 1;
      document.getElementById("clicks").innerHTML = clicks;
  };

//////// Capturing Pieces

// if statement about white pieces interfering with black pieces
/
var whitePieces = [wPawn1, wPawn2, wPawn3, wPawn4];
  var whiteCaptured = [];
  whiteCaptured = pieces.slice(1, 2)
      // whiteCaptured contains [wPawn2]
*/
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the<commit_msg>Incompatible dimensions found, Cthuhlu Error 666<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the <|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/Contents/Developer/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep)
    counter = counter + step
    if (process.env.FAKETIME) {
      t_offset = t_offset + timeout;
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = timeout * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  } else {
    var args = ['push']
    child_proces<commit_msg>Sprint complete<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/Contents/Developer/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep)
    counter = counter + step
    if (process.env.FAKETIME) {
      t_offset = t_offset + timeout;
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = timeout * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  } else {
    var args = ['push']
    child_process<|endoftext|>