<commit_before>/*
 * Initialize a quotes database
 *
 * Inserts the quotes from
 *   _The Pragmatic Programmer_
 * into a local or mLab MongoDB database
 *
 * © 2017 Team Pengo
 *
 * Authors: Khyati Kulshreshtha,
 *          Monyette Tanzillo,
 *          Claudio Gentile,
 *          Peter Martinson
*/
const mongoose    = require('mongoose'),
      quoteSchema = require('../models/quoteSchema.js'),
      Quote       = mongoose.model('Quote', quoteSchema);

// list the quotes
var allQuotes = [
  {
    quote    : "Care About Your Craft",
    subquote : "Why spend your life developing software unless you care about doing it well?"
  },
  {
    quote    : "Think! About Your Work",
    subquote : "Turn off the autopilot and take control. Constantly critique and appraise your work."
  },
  {
    quote    : "Provide Options, Don't Make Lame Excuses",
    subquote : "Instead of excuses, provide options. Don't say it can't be done; explain what can be done."
  },
  {
    quote    : "Don't Live with Broken Windows",
    subquote : "Fix bad designs, wrong decisions, and poor code when you see them."
  },
  {
    quote    : "Be a Catalyst for Change",
    subquote : "You can't force change on people. Instead, show them how the future might be and help them participate in creating it."
  },
  {
    quote    : "Remember the Big Picture",
    subquote : "Don't get so engrossed in the details that you forget to check what's happening around you."
  },
  {
    quote    : "Make Quality a Requirements Issue",
    subquote : "Involve your users in determining the project's real quality requirements."
  },
  {
    quote    : "Invest Regularly in Your Knowledge Portfolio",
    subquote : "Make learning a habit."
  },
  {
    quote    : "Critically Analyze What You Read and Hear",
    subquote : "Don't be swayed by vendors, media hype, or dogma. Analyze information in terms of you and your project."
  },
  {
    quote    : "It's Both What You Say and the Way You Say It",
    subquote : "There's no point in having great ideas if you don't communicate them effectively."
  },
  {
    quote    : "DRY – Don't Repeat Yourself",
    subquote : "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system."
  },
  {
    quote    : "Make It Easy to Reuse",
    subquote : "If it's easy to reuse, people will. Create an environment that supports reuse."
  },
  {
    quote    : "Eliminate Effects Between Unrelated Things",
    subquote : "Design components that are self-contained. independent, and have a single, well-defined purpose."
  },
  {
    quote    : "There Are No Final Decisions",
    subquote : "No decision is cast in stone. Instead, consider each as being written in the sand at the beach, and plan for change."
  },
  {
    quote    : "Use Tracer Bullets to Find the Target",
    subquote : "Tracer bullets let you home in on your target by trying things and seeing how close they land."
  },
  {
    quote    : "Prototype to Learn",
    subquote : "Prototyping is a learning experience. Its value lies not in the code you produce, but in the lessons you learn."
  },
  {
    quote    : "Program Close to the Problem Domain",
    subquote : "Design and code in your user's language."
  },
  {
    quote    : "Estimate to Avoid Surprises",
    subquote : "Estimate before you start. You'll spot potential problems up front."
  },
  {
    quote    : "Iterate the Schedule with the Code",
    subquote : "Use experience you gain as you implement to refine the project time scales."
  },
  {
    quote    : "Keep Knowledge in Plain Text",
    subquote : "Plain text won't become obsolete. It helps leverage your work and simplifies debugging and testing."
  },
  {
    quote    : "Use the Power of Command Shells",
    subquote : "Use the shell when graphical user interfaces don't cut it."
  },
  {
    quote    : "Use a Single Editor Well",
    subquote : "The editor should be an extension of your hand; make sure your editor is configurable, extensible, and programmable."
  },
  {
    quote    : "Always Use Source Code Control",
    subquote : "Source code control is a time machine for your work – you can go back."
  },
  {
    quote    : "Fix the Problem, Not the Blame",
    subquote : "It doesn't really matter whether the bug is your fault or someone else's – it is still your problem, and it still needs to be fixed."
  },
  {
    quote    : "Don't Panic When Debugging",
    subquote : "Take a deep breath and THINK! about what could be causing the bug."
  },
  {
    quote    : "'select' Isn't Broken.",
    subquote : "It is rare to find a bug in the OS or the compiler, or even a third-party product or library. The bug is most likely in the application."
  },
  {
    quote    : "Don't Assume It – Prove It",
    subquote : "Prove your assumptions in the actual environment – with real data and boundary conditions."
  },
  {
    quote    : "Learn a Text Manipulation Language.",
    subquote : "You spend a large part of each day working with text. Why not have the computer do some of it for you?"
  },
  {
    quote    : "Write Code That Writes Code",
    subquote : "Code generators increase your productivity and help avoid duplication."
  },
  {
    quote    : "You Can't Write Perfect Software",
    subquote : "Software can't be perfect. Protect your code and users from the inevitable errors."
  },
  {
    quote    : "Design with Contracts",
    subquote : "Use contracts to document and verify that code does no more and no less than it claims to do."
  },
  {
    quote    : "Crash Early",
    subquote : "A dead program normally does a lot less damage than a crippled one."
  },
  {
    quote    : "Use Assertions to Prevent the Impossible",
    subquote : "Assertions validate your assumptions. Use them to protect your code from an uncertain world."
  },
  {
    quote    : "Use Exceptions for Exceptional Problems",
    subquote : "Exceptions can suffer from all the readability and maintainability problems of classic spaghetti code. Reserve exceptions for exceptional things."
  },
  {
    quote    : "Finish What You Start",
    subquote : "Where possible, the routine or object that allocates a resource should be responsible for deallocating it."
  },
  {
    quote    : "Minimize Coupling Between Modules",
    subquote : "Avoid coupling by writing 'shy' code and applying the Law of Demeter."
  },
  {
    quote    : "Configure, Don't Integrate",
    subquote : "Implement technology choices for an application as configuration options, not through integration or engineering."
  },
  {
    quote    : "Put Abstractions in Code, Details in Metadata",
    subquote : "Program for the general case, and put the specifics outside the compiled code base."
  },
  {
    quote    : "Analyze Workflow to Improve Concurrency",
    subquote : "Exploit concurrency in your user's workflow."
  },
  {
    quote    : "Design Using Services",
    subquote : "Design in terms of services – independent, concurrent objects behind well-defined, consistent interfaces."
  },
  {
    quote    : "Always Design for Concurrency",
    subquote : "Allow for concurrency, and you'll design cleaner interfaces with fewer assumptions."
  },
  {
    quote    : "Separate Views from Models",
    subquote : "Gain flexibility at low cost by designing your application in terms of models and views."
  },
  {
    quote    : "Use Blackboards to Coordinate Workflow",
    subquote : "Use blackboards to coordinate disparate facts and agents, while maintaining independence and isolation among participants."
  },
  {
    quote    : "Don't Program by Coincidence",
    subquote : "Rely only on reliable things. Beware of accidental complexity, and don't confuse a happy coincidence with a purposeful plan."
  },
  {
    quote    : "Estimate the Order of Your Algorithms",
    subquote : "Get a feel for how long things are likely to take before you write code."
  },
  {
    quote    : "Test Your Estimates",
    subquote : "Mathematical analysis of algorithms doesn't tell you everything. Try timing your code in its target environment."
  },
  {
    quote    : "Refactor Early, Refactor Often",
    subquote : "Just as you might weed and rearrange a garden, rewrite, rework, and re-architect code when it needs it. Fix the root of the problem."
  },
  {
    quote    : "Design to Test",
    subquote : "Start thinking about testing before you write a line of code."
  },
  {
    quote    : "Test Your Software, or Your Users Will",
    subquote : "Test ruthlessly. Don't make your users find bugs for you."
  },
  {
    quote    : "Don't Use Wizard Code You Don't Understand",
    subquote : "Wizards can generate reams of code. Make sure you understand all of it before you incorporate it into your project."
  },
  {
    quote    : "Don't Gather Requirements – Dig for Them",
    subquote : "Requirements rarely lie on the surface. They're buried deep beneath layers of assumptions, misconceptions, and politics."
  },
  {
    quote    : "Work With a User to Think Like a User",
    subquote : "It's the best way to gain insight into how the system will really be used."
  },
  {
    quote    : "Abstractions Live Longer than Details",
    subquote : "Invest in the abstraction, not the implementation. Abstractions can survive the barrage of changes from different implementations and new technologies."
  },
  {
    quote    : "Use a Project Glossary",
    subquote : "Create and maintain a single source of all the specific terms and vocabulary for a project."
  },
  {
    quote    : "Don't Think Outside the Box – Find the Box",
    subquote : "When faced with an impossible problem, identify the real constraints. Ask yourself                                                                       : 'Does it have to be done this way? Does it have to be done at all?'"
  },
  {
    quote    : "Start When You're Ready.",
    subquote : "You've been building experience all your life. Don't ignore niggling doubts."
  },
  {
    quote    : "Some Things Are Better Done than Described",
    subquote : "Don't fall into the specification spiral – at some point you need to start coding."
  },
  {
    quote    : "Don't Be a Slave to Formal Methods.",
    subquote : "Don't blindly adopt any technique without putting it into the context of your development practices and capabilities."
  },
  {
    quote    : "Costly Tools Don't Produce Better Designs",
    subquote : "Beware of vendor hype, industry dogma, and the aura of the price tag. Judge tools on their merits."
  },
  {
    quote    : "Organize Teams Around Functionality",
    subquote : "Don't separate designers from coders, testers from data modelers. Build teams the way you build code."
  },
  {
    quote    : "Don't Use Manual Procedures",
    subquote : "A shell script or batch file will execute the same instructions, in the same order, time after time."
  },
  {
    quote    : "Test Early. Test Often. Test Automatically",
    subquote : "Tests that run with every build are much more effective than test plans that sit on a shelf."
  },
  {
    quote    : "Coding Ain't Done 'Til All the Tests Run",
    subquote : "'Nuff said."
  },
  {
    quote    : "Use Saboteurs to Test Your Testing",
    subquote : "Introduce bugs on purpose in a separate copy of the source to verify that testing will catch them."
  },
  {
    quote    : "Test State Coverage, Not Code Coverage",
    subquote : "Identify and test significant program states. Just testing lines of code isn't enough."
  },
  {
    quote    : "Find Bugs Once",
    subquote : "Once a human tester finds a bug, it should be the last time a human tester finds that bug. Automatic tests should check for it from then on."
  },
  {
    quote    : "English is Just a Programming Language",
    subquote : "Write documents as you would write code: honor the DRY principle, use metadata, MVC, automatic generation, and so on."
  },
  {
    quote    : "Build Documentation In, Don't Bolt It On",
    subquote : "Documentation created separately from code is less likely to be correct and up to date."
  },
  {
    quote    : "Gently Exceed Your Users' Expectations",
    subquote : "Come to understand your users' expectations, then deliver just that little bit more."
  },
  {
    quote    : "Sign Your Work",
    subquote : "Craftsmen of an earlier age were proud to sign their work. You should be, too."
  }
];

module.exports = function() {

  var allDocuments = [];
  allQuotes.forEach(function(element, index) {
    allDocuments[index] = {
      quote_id      : index + 1,
      source        : "The Pragmatic Programmer",
      source_href   : "https://pragprog.com/the-pragmatic-programmer/extracts/tips",
      quote         : element.quote,
      quote_href    : "",
      subquote      : element.subquote,
      subquote_href : ""
    };
  });

  // empty the database!
  Quote.remove({}, function(err) {
    if (err) console.log(err);
    console.log("database emptied.");
  });

  // Load all documents into the database
  Quote.create(allDocuments, function (err, results) {
    if (err) console.log(err);
    console.log("database populated:");
    console.log(results);
  });
}

<commit_msg>Update initializeQuoteDB.js<commit_after>/*
 * Initialize a quotes database
 *
 * Inserts the quotes from
 *   _The Pragmatic Programmer_
 * into a local or mLab MongoDB database
 *
 * © 2017 Team Pengo
 *
 * Authors: Khyati Kulshreshtha,
 *          Monyett Tanzillo,
 *          Claudio Gentile,
 *          Peter Martinson
*/
const mongoose    = require('mongoose'),
      quoteSchema = require('../models/quoteSchema.js'),
      Quote       = mongoose.model('Quote', quoteSchema);

// list the quotes
var allQuotes = [
  {
    quote    : "Care About Your Craft",
    subquote : "Why spend your life developing software unless you care about doing it well?"
  },
  {
    quote    : "Think! About Your Work",
    subquote : "Turn off the autopilot and take control. Constantly critique and appraise your work."
  },
  {
    quote    : "Provide Options, Don't Make Lame Excuses",
    subquote : "Instead of excuses, provide options. Don't say it can't be done; explain what can be done."
  },
  {
    quote    : "Don't Live with Broken Windows",
    subquote : "Fix bad designs, wrong decisions, and poor code when you see them."
  },
  {
    quote    : "Be a Catalyst for Change",
    subquote : "You can't force change on people. Instead, show them how the future might be and help them participate in creating it."
  },
  {
    quote    : "Remember the Big Picture",
    subquote : "Don't get so engrossed in the details that you forget to check what's happening around you."
  },
  {
    quote    : "Make Quality a Requirements Issue",
    subquote : "Involve your users in determining the project's real quality requirements."
  },
  {
    quote    : "Invest Regularly in Your Knowledge Portfolio",
    subquote : "Make learning a habit."
  },
  {
    quote    : "Critically Analyze What You Read and Hear",
    subquote : "Don't be swayed by vendors, media hype, or dogma. Analyze information in terms of you and your project."
  },
  {
    quote    : "It's Both What You Say and the Way You Say It",
    subquote : "There's no point in having great ideas if you don't communicate them effectively."
  },
  {
    quote    : "DRY – Don't Repeat Yourself",
    subquote : "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system."
  },
  {
    quote    : "Make It Easy to Reuse",
    subquote : "If it's easy to reuse, people will. Create an environment that supports reuse."
  },
  {
    quote    : "Eliminate Effects Between Unrelated Things",
    subquote : "Design components that are self-contained. independent, and have a single, well-defined purpose."
  },
  {
    quote    : "There Are No Final Decisions",
    subquote : "No decision is cast in stone. Instead, consider each as being written in the sand at the beach, and plan for change."
  },
  {
    quote    : "Use Tracer Bullets to Find the Target",
    subquote : "Tracer bullets let you home in on your target by trying things and seeing how close they land."
  },
  {
    quote    : "Prototype to Learn",
    subquote : "Prototyping is a learning experience. Its value lies not in the code you produce, but in the lessons you learn."
  },
  {
    quote    : "Program Close to the Problem Domain",
    subquote : "Design and code in your user's language."
  },
  {
    quote    : "Estimate to Avoid Surprises",
    subquote : "Estimate before you start. You'll spot potential problems up front."
  },
  {
    quote    : "Iterate the Schedule with the Code",
    subquote : "Use experience you gain as you implement to refine the project time scales."
  },
  {
    quote    : "Keep Knowledge in Plain Text",
    subquote : "Plain text won't become obsolete. It helps leverage your work and simplifies debugging and testing."
  },
  {
    quote    : "Use the Power of Command Shells",
    subquote : "Use the shell when graphical user interfaces don't cut it."
  },
  {
    quote    : "Use a Single Editor Well",
    subquote : "The editor should be an extension of your hand; make sure your editor is configurable, extensible, and programmable."
  },
  {
    quote    : "Always Use Source Code Control",
    subquote : "Source code control is a time machine for your work – you can go back."
  },
  {
    quote    : "Fix the Problem, Not the Blame",
    subquote : "It doesn't really matter whether the bug is your fault or someone else's – it is still your problem, and it still needs to be fixed."
  },
  {
    quote    : "Don't Panic When Debugging",
    subquote : "Take a deep breath and THINK! about what could be causing the bug."
  },
  {
    quote    : "'select' Isn't Broken.",
    subquote : "It is rare to find a bug in the OS or the compiler, or even a third-party product or library. The bug is most likely in the application."
  },
  {
    quote    : "Don't Assume It – Prove It",
    subquote : "Prove your assumptions in the actual environment – with real data and boundary conditions."
  },
  {
    quote    : "Learn a Text Manipulation Language.",
    subquote : "You spend a large part of each day working with text. Why not have the computer do some of it for you?"
  },
  {
    quote    : "Write Code That Writes Code",
    subquote : "Code generators increase your productivity and help avoid duplication."
  },
  {
    quote    : "You Can't Write Perfect Software",
    subquote : "Software can't be perfect. Protect your code and users from the inevitable errors."
  },
  {
    quote    : "Design with Contracts",
    subquote : "Use contracts to document and verify that code does no more and no less than it claims to do."
  },
  {
    quote    : "Crash Early",
    subquote : "A dead program normally does a lot less damage than a crippled one."
  },
  {
    quote    : "Use Assertions to Prevent the Impossible",
    subquote : "Assertions validate your assumptions. Use them to protect your code from an uncertain world."
  },
  {
    quote    : "Use Exceptions for Exceptional Problems",
    subquote : "Exceptions can suffer from all the readability and maintainability problems of classic spaghetti code. Reserve exceptions for exceptional things."
  },
  {
    quote    : "Finish What You Start",
    subquote : "Where possible, the routine or object that allocates a resource should be responsible for deallocating it."
  },
  {
    quote    : "Minimize Coupling Between Modules",
    subquote : "Avoid coupling by writing 'shy' code and applying the Law of Demeter."
  },
  {
    quote    : "Configure, Don't Integrate",
    subquote : "Implement technology choices for an application as configuration options, not through integration or engineering."
  },
  {
    quote    : "Put Abstractions in Code, Details in Metadata",
    subquote : "Program for the general case, and put the specifics outside the compiled code base."
  },
  {
    quote    : "Analyze Workflow to Improve Concurrency",
    subquote : "Exploit concurrency in your user's workflow."
  },
  {
    quote    : "Design Using Services",
    subquote : "Design in terms of services – independent, concurrent objects behind well-defined, consistent interfaces."
  },
  {
    quote    : "Always Design for Concurrency",
    subquote : "Allow for concurrency, and you'll design cleaner interfaces with fewer assumptions."
  },
  {
    quote    : "Separate Views from Models",
    subquote : "Gain flexibility at low cost by designing your application in terms of models and views."
  },
  {
    quote    : "Use Blackboards to Coordinate Workflow",
    subquote : "Use blackboards to coordinate disparate facts and agents, while maintaining independence and isolation among participants."
  },
  {
    quote    : "Don't Program by Coincidence",
    subquote : "Rely only on reliable things. Beware of accidental complexity, and don't confuse a happy coincidence with a purposeful plan."
  },
  {
    quote    : "Estimate the Order of Your Algorithms",
    subquote : "Get a feel for how long things are likely to take before you write code."
  },
  {
    quote    : "Test Your Estimates",
    subquote : "Mathematical analysis of algorithms doesn't tell you everything. Try timing your code in its target environment."
  },
  {
    quote    : "Refactor Early, Refactor Often",
    subquote : "Just as you might weed and rearrange a garden, rewrite, rework, and re-architect code when it needs it. Fix the root of the problem."
  },
  {
    quote    : "Design to Test",
    subquote : "Start thinking about testing before you write a line of code."
  },
  {
    quote    : "Test Your Software, or Your Users Will",
    subquote : "Test ruthlessly. Don't make your users find bugs for you."
  },
  {
    quote    : "Don't Use Wizard Code You Don't Understand",
    subquote : "Wizards can generate reams of code. Make sure you understand all of it before you incorporate it into your project."
  },
  {
    quote    : "Don't Gather Requirements – Dig for Them",
    subquote : "Requirements rarely lie on the surface. They're buried deep beneath layers of assumptions, misconceptions, and politics."
  },
  {
    quote    : "Work With a User to Think Like a User",
    subquote : "It's the best way to gain insight into how the system will really be used."
  },
  {
    quote    : "Abstractions Live Longer than Details",
    subquote : "Invest in the abstraction, not the implementation. Abstractions can survive the barrage of changes from different implementations and new technologies."
  },
  {
    quote    : "Use a Project Glossary",
    subquote : "Create and maintain a single source of all the specific terms and vocabulary for a project."
  },
  {
    quote    : "Don't Think Outside the Box – Find the Box",
    subquote : "When faced with an impossible problem, identify the real constraints. Ask yourself                                                                       : 'Does it have to be done this way? Does it have to be done at all?'"
  },
  {
    quote    : "Start When You're Ready.",
    subquote : "You've been building experience all your life. Don't ignore niggling doubts."
  },
  {
    quote    : "Some Things Are Better Done than Described",
    subquote : "Don't fall into the specification spiral – at some point you need to start coding."
  },
  {
    quote    : "Don't Be a Slave to Formal Methods.",
    subquote : "Don't blindly adopt any technique without putting it into the context of your development practices and capabilities."
  },
  {
    quote    : "Costly Tools Don't Produce Better Designs",
    subquote : "Beware of vendor hype, industry dogma, and the aura of the price tag. Judge tools on their merits."
  },
  {
    quote    : "Organize Teams Around Functionality",
    subquote : "Don't separate designers from coders, testers from data modelers. Build teams the way you build code."
  },
  {
    quote    : "Don't Use Manual Procedures",
    subquote : "A shell script or batch file will execute the same instructions, in the same order, time after time."
  },
  {
    quote    : "Test Early. Test Often. Test Automatically",
    subquote : "Tests that run with every build are much more effective than test plans that sit on a shelf."
  },
  {
    quote    : "Coding Ain't Done 'Til All the Tests Run",
    subquote : "'Nuff said."
  },
  {
    quote    : "Use Saboteurs to Test Your Testing",
    subquote : "Introduce bugs on purpose in a separate copy of the source to verify that testing will catch them."
  },
  {
    quote    : "Test State Coverage, Not Code Coverage",
    subquote : "Identify and test significant program states. Just testing lines of code isn't enough."
  },
  {
    quote    : "Find Bugs Once",
    subquote : "Once a human tester finds a bug, it should be the last time a human tester finds that bug. Automatic tests should check for it from then on."
  },
  {
    quote    : "English is Just a Programming Language",
    subquote : "Write documents as you would write code: honor the DRY principle, use metadata, MVC, automatic generation, and so on."
  },
  {
    quote    : "Build Documentation In, Don't Bolt It On",
    subquote : "Documentation created separately from code is less likely to be correct and up to date."
  },
  {
    quote    : "Gently Exceed Your Users' Expectations",
    subquote : "Come to understand your users' expectations, then deliver just that little bit more."
  },
  {
    quote    : "Sign Your Work",
    subquote : "Craftsmen of an earlier age were proud to sign their work. You should be, too."
  }
];

module.exports = function() {

  var allDocuments = [];
  allQuotes.forEach(function(element, index) {
    allDocuments[index] = {
      quote_id      : index + 1,
      source        : "The Pragmatic Programmer",
      source_href   : "https://pragprog.com/the-pragmatic-programmer/extracts/tips",
      quote         : element.quote,
      quote_href    : "",
      subquote      : element.subquote,
      subquote_href : ""
    };
  });

  // empty the database!
  Quote.remove({}, function(err) {
    if (err) console.log(err);
    console.log("database emptied.");
  });

  // Load all documents into the database
  Quote.create(allDocuments, function (err, results) {
    if (err) console.log(err);
    console.log("database populated:");
    console.log(results);
  });
}

<|endoftext|>


<commit_before>function Game()
{
	this.snake = new Snake();
	this.lose = false;
	this.apple = new Apple();
	this.board = new Board(50);
	this.board.generateBoard();
	this.apple.generateApple();
}

Game.prototype.Turn = function () {
	var lastRowCoord = this.snake.snakeArray[0][0];
	var lastColCoord = this.snake.snakeArray[0][1];
	this.board.renderSnakeCoords(this.snake.snakeArray);
	this.snake.GetKeyStroke();
	this.snake.Move(this.apple);
	if (this.snake.eatenApple)
	{
		this.board.disActivateApple(this.apple.coordinates[0],this.apple.coordinates[1]);
		this.apple.generateApple();
		this.snake.eatenApple = false;
	}
	this.board.disActivateCell(lastRowCoord, lastColCoord);
	this.CheckLose();
	this.LoseBySelfTouch();
}

Game.prototype.CheckLose = function ()
{
	var snakeHeadRow = this.snake.snakeArray[this.snake.snakeArray.length-1][0];
	var snakeHeadCol = this.snake.snakeArray[this.snake.snakeArray.length-1][1];
	if (snakeHeadRow < 0 || snakeHeadRow > 49 || snakeHeadCol < 0 || snakeHeadCol > 49)
	{
		this.lose = true;
		console.log("you lose!");
	}
}

Game.prototype.LoseBySelfTouch = function ()
{
	var snakeHeadRow = this.snake.snakeArray[this.snake.snakeArray.length-1][0];
	var snakeHeadCol = this.snake.snakeArray[this.snake.snakeArray.length-1][1];
	for (var i = 0; i < this.snake.snakeArray.length - 2; i++)
	{
		var row = this.snake.snakeArray[i][0];
		var col = this.snake.snakeArray[i][1];
		if (snakeHeadRow === row && snakeHeadCol === col)
		{
			this.lose = true;
			alert("you lose!");
		}
	}

}

Game.prototype.Start = function () {
	var thisGame = this;
	var startGame = setInterval(function (){
		thisGame.Turn();
		if (thisGame.lose === true)
		{
			clearInterval(startGame);
		}
	}, 50);
}

function Snake ()
{
	this.snakeArray = [[0,0], [0,1], [0,2]];
	this.direction = 2;
	this.score = 0;
	this.eatenApple = false;
}

Snake.prototype.GetKeyStroke = function ()
{
	var thisSnake = this;
		$(document).keydown(function (e)
		{
			switch(e.which)
			{
				case 38:
				thisSnake.direction = 1;
				break;
				case 39:
				thisSnake.direction = 2;
				break;
				case 40:
				thisSnake.direction = 3;
				break;
				case 37:
				thisSnake.direction = 4;
				break;
			}

		});
}
	// move
Snake.prototype.Move = function (apple)
{
	var headRow = this.snakeArray[this.snakeArray.length-1][0];
	var headCol = this.snakeArray[this.snakeArray.length-1][1];
		switch (this.direction)
		{
			// up
			case 1:
				if (this.EatApple(apple))
				{
					var newHeadRow = headRow -1;
					var newHeadCol = headCol + 0;
					var newHead = [newHeadRow, newHeadCol];
					this.snakeArray.push(newHead);
				}
				this.snakeArray.shift();
				var newHeadRow = headRow -1;
				var newHeadCol = headCol + 0;
				var newHead = [newHeadRow, newHeadCol];
				this.snakeArray.push(newHead);
			break;
			// down
			case 3:
				if (this.EatApple(apple))
				{
					var newHeadRow = headRow + 1;
					var newHeadCol = headCol + 0;
					var newHead = [newHeadRow, newHeadCol];
					this.snakeArray.push(newHead);
				}
				this.snakeArray.shift();
				var newHeadRow = headRow + 1;
				var newHeadCol = headCol + 0;
				var newHead = [newHeadRow, newHeadCol];
				this.snakeArray.push(newHead);
			break;
			// right
			case 2:
				if (this.EatApple(apple))
				{
					var newHeadRow = headRow + 0;
					var newHeadCol = headCol + 1;
					var newHead = [newHeadRow, newHeadCol];
					this.snakeArray.push(newHead);
				}
				this.snakeArray.shift();
				var newHeadRow = headRow + 0;
				var newHeadCol = headCol + 1;
				var newHead = [newHeadRow, newHeadCol];
				this.snakeArray.push(newHead);
			break;
			// left
			case 4:
				if (this.EatApple(apple))
				{
					var newHeadRow = headRow + 0;
					var newHeadCol = headCol -1;
					var newHead = [newHeadRow, newHeadCol];
					this.snakeArray.push(newHead);
				}
				this.snakeArray.shift();
				var newHeadRow = headRow + 0;
				var newHeadCol = headCol -1;
				var newHead = [newHeadRow, newHeadCol];
				this.snakeArray.push(newHead);
			break;
		}
}

Snake.prototype.EatApple = function (apple)
{
	var appleRow = apple.coordinates[0];
	var appleCol = apple.coordinates[1];

	var headRow = this.snakeArray[this.snakeArray.length-1][0];
	var headCol = this.snakeArray[this.snakeArray.length-1][1];

	if (appleRow === headRow && appleCol === headCol)
	{
		console.log("eaten apple");
		this.score += 10;
		console.log("your score is now " + this.score);
		this.eatenApple = true;
		return true;

	}
	return false;
}

	// driver code
$(document).ready(function() {

var game = new Game();
game.Start();

});

<commit_msg>minor changes to snake.js<commit_after>function Game ()
{
	this.snake = new Snake();
	this.lose = false;
	this.apple = new Apple();
	this.board = new Board(50);
	this.board.generateBoard();
	this.apple.generateApple();
}

Game.prototype.Turn = function ()
{
	var lastRowCoord = this.snake.snakeArray[0][0];
	var lastColCoord = this.snake.snakeArray[0][1];
	this.board.renderSnakeCoords(this.snake.snakeArray);
	this.snake.GetKeyStroke();
	this.snake.Move(this.apple);
	if (this.snake.eatenApple)
	{
		this.board.disActivateApple(this.apple.coordinates[0],this.apple.coordinates[1]);
		this.apple.generateApple();
		this.snake.eatenApple = false;
	}
	this.board.disActivateCell(lastRowCoord, lastColCoord);
	this.CheckLose();
	this.LoseBySelfTouch();
}

Game.prototype.CheckLose = function ()
{
	var snakeHeadRow = this.snake.snakeArray[this.snake.snakeArray.length-1][0];
	var snakeHeadCol = this.snake.snakeArray[this.snake.snakeArray.length-1][1];
	if (snakeHeadRow < 0 || snakeHeadRow > 49 || snakeHeadCol < 0 || snakeHeadCol > 49)
	{
		this.lose = true;
		alert("you lose!");
	}
}

Game.prototype.LoseBySelfTouch = function ()
{
	var snakeHeadRow = this.snake.snakeArray[this.snake.snakeArray.length-1][0];
	var snakeHeadCol = this.snake.snakeArray[this.snake.snakeArray.length-1][1];
	for (var i = 0; i < this.snake.snakeArray.length - 2; i++)
	{
		var row = this.snake.snakeArray[i][0];
		var col = this.snake.snakeArray[i][1];
		if (snakeHeadRow === row && snakeHeadCol === col)
		{
			this.lose = true;
			alert("you lose!");
		}
	}

}

Game.prototype.Start = function ()
{
	var thisGame = this;
	var startGame = setInterval(function ()
	{
		thisGame.Turn();
		if (thisGame.lose === true)
		{
			clearInterval(startGame);
		}
	}, 50);
}

function Snake ()
{
	this.snakeArray = [[0,0], [0,1], [0,2]];
	this.direction = 2;
	this.score = 0;
	this.eatenApple = false;
}

Snake.prototype.GetKeyStroke = function ()
{
	var thisSnake = this;
		$(document).keydown(function (e)
		{
			switch(e.which)
			{
				case 38:
				thisSnake.direction = 1;
				break;
				case 39:
				thisSnake.direction = 2;
				break;
				case 40:
				thisSnake.direction = 3;
				break;
				case 37:
				thisSnake.direction = 4;
				break;
			}

		});
}
	// move
Snake.prototype.Move = function (apple)
{
	var headRow = this.snakeArray[this.snakeArray.length-1][0];
	var headCol = this.snakeArray[this.snakeArray.length-1][1];
		switch (this.direction)
		{
			// up
			case 1:
				if (this.EatApple(apple))
				{
					var newHeadRow = headRow -1;
					var newHeadCol = headCol + 0;
					var newHead = [newHeadRow, newHeadCol];
					this.snakeArray.push(newHead);
				}
				this.snakeArray.shift();
				var newHeadRow = headRow -1;
				var newHeadCol = headCol + 0;
				var newHead = [newHeadRow, newHeadCol];
				this.snakeArray.push(newHead);
			break;
			// down
			case 3:
				if (this.EatApple(apple))
				{
					var newHeadRow = headRow + 1;
					var newHeadCol = headCol + 0;
					var newHead = [newHeadRow, newHeadCol];
					this.snakeArray.push(newHead);
				}
				this.snakeArray.shift();
				var newHeadRow = headRow + 1;
				var newHeadCol = headCol + 0;
				var newHead = [newHeadRow, newHeadCol];
				this.snakeArray.push(newHead);
			break;
			// right
			case 2:
				if (this.EatApple(apple))
				{
					var newHeadRow = headRow + 0;
					var newHeadCol = headCol + 1;
					var newHead = [newHeadRow, newHeadCol];
					this.snakeArray.push(newHead);
				}
				this.snakeArray.shift();
				var newHeadRow = headRow + 0;
				var newHeadCol = headCol + 1;
				var newHead = [newHeadRow, newHeadCol];
				this.snakeArray.push(newHead);
			break;
			// left
			case 4:
				if (this.EatApple(apple))
				{
					var newHeadRow = headRow + 0;
					var newHeadCol = headCol -1;
					var newHead = [newHeadRow, newHeadCol];
					this.snakeArray.push(newHead);
				}
				this.snakeArray.shift();
				var newHeadRow = headRow + 0;
				var newHeadCol = headCol -1;
				var newHead = [newHeadRow, newHeadCol];
				this.snakeArray.push(newHead);
			break;
		}
}

Snake.prototype.EatApple = function (apple)
{
	var appleRow = apple.coordinates[0];
	var appleCol = apple.coordinates[1];

	var headRow = this.snakeArray[this.snakeArray.length-1][0];
	var headCol = this.snakeArray[this.snakeArray.length-1][1];

	if (appleRow === headRow && appleCol === headCol)
	{
		console.log("eaten apple");
		this.score += 10;
		console.log("your score is now " + this.score);
		this.eatenApple = true;
		return true;
	}
	return false;
}
	// driver code
$(document).ready(function ()
{
var game = new Game();
game.Start();
});	<|endoftext|>


<commit_before>'use strict'

import { Component }   from 'react'
import { Link }        from 'react-router'
import DocumentTitle   from 'react-document-title'
//import { decodeToken, SECP256K1Client, TokenSigner } from 'jsontokens'
import { makeAuthResponse, makeECPrivateKey, getAuthRequestFromURL, redirectUserToApp } from 'blockstack'
//import { Person, fetchAppManifest, publicKeyToAddress, makeDIDFromAddress, makeUUID4, nextMonth } from 'blockstack'

import Header          from '../components/Header'
import Footer          from '../components/Footer'

class AuthPage extends Component {

  constructor(props) {
    super(props)

    this.state = {
      authRequest: null,
      appURI: null
    }

    this.signIn = this.signIn.bind(this)
    this.getAuthRequest = this.getAuthRequest.bind(this)
  }

  componentWillMount() {
    this.getAuthRequest()
  }

  getAuthRequest() {
    const authRequest = getAuthRequestFromURL()
    this.setState({
      authRequest: authRequest
    })
    /*
    fetchAppManifest(authRequest).then(appManifest => {
    }).catch((e) => {
      console.log(e.stack)
    })*/
  }

  signIn() {
    const privateKey = makeECPrivateKey()
    const profile = {
      '@type': 'Person',
      'name': 'Anonymous',
      'image': [
        {
          '@type': 'ImageObject',
          'name': 'avatar',
          'contentUrl': 'https://s3.amazonaws.com/onename/avatar-placeholder.png'
        }
      ]
    }
    const authResponse = makeAuthResponse(privateKey, profile)
    if (this.state.authRequest) {
      redirectUserToApp(this.state.authRequest, authResponse)
    }
  }

  render() {
    return (
      <DocumentTitle title="Sign In with Blockstack">

                  Sign in with Blockstack

                    You're here because you clicked "Sign in with
                    Blockstack" and you don't have the Blockstack app.

                    <Link to="/download" className="btn btn-outline-primary">
                      Download Blockstack
                    </Link>

                  {this.state.authRequest ?

                        - or -

                        <Link className="btn btn-outline-primary"
                              onClick={this.signIn}>
                          Quick Sign In
                        </Link>

                  : null }

                    Note: If you already have Blockstack,
                    go to your settings page in Blockstack and
                    enable the auth protocol handler,
                    then go to the app and try signing in again.

      </DocumentTitle>
    )
  }

}

export default AuthPage<commit_msg>update auth page<commit_after>'use strict'

import { Component }   from 'react'
import { Link }        from 'react-router'
import DocumentTitle   from 'react-document-title'
//import { decodeToken, SECP256K1Client, TokenSigner } from 'jsontokens'
import { makeAuthResponse, makeECPrivateKey, getAuthRequestFromURL, redirectUserToApp } from 'blockstack'
//import { Person, fetchAppManifest, publicKeyToAddress, makeDIDFromAddress, makeUUID4, nextMonth } from 'blockstack'

import Header          from '../components/Header'
import Footer          from '../components/Footer'

class AuthPage extends Component {

  constructor(props) {
    super(props)

    this.state = {
      authRequest: null,
      appURI: null
    }

    this.signIn = this.signIn.bind(this)
    this.getAuthRequest = this.getAuthRequest.bind(this)
  }

  componentWillMount() {
    this.getAuthRequest()
  }

  getAuthRequest() {
    const authRequest = getAuthRequestFromURL()
    this.setState({
      authRequest: authRequest
    })
    /*
    fetchAppManifest(authRequest).then(appManifest => {
    }).catch((e) => {
      console.log(e.stack)
    })*/
  }

  signIn() {
    const privateKey = makeECPrivateKey()
    const profile = {
      '@type': 'Person',
      'name': 'Anonymous',
      'image': [
        {
          '@type': 'ImageObject',
          'name': 'avatar',
          'contentUrl': 'https://s3.amazonaws.com/onename/avatar-placeholder.png'
        }
      ]
    }
    const authResponse = makeAuthResponse(privateKey, profile)
    if (this.state.authRequest) {
      redirectUserToApp(this.state.authRequest, authResponse)
    }
  }

  render() {
    return (
      <DocumentTitle title="Sign In with Blockstack">

                  Sign in with Blockstack

                    You're here because you clicked "Sign in with
                    Blockstack" and you don't have the Blockstack app.

                    <Link to="/install" className="btn btn-outline-primary">
                      Install Blockstack
                    </Link>

                  {this.state.authRequest ?

                        - or -

                        <Link className="btn btn-outline-primary"
                              onClick={this.signIn}>
                          Quick Sign In
                        </Link>

                  : null }

                    Note: If you already have Blockstack,
                    go to your settings page in Blockstack and
                    enable the auth protocol handler,
                    then go to the app and try signing in again.

      </DocumentTitle>
    )
  }

}

export default AuthPage<|endoftext|>


<commit_before>/*
 * Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

module.exports = function(app) {
  'use strict';

  var debug = require('debug')('signalk-server:interfaces:rest');
  var express = require('express');

  var pathPrefix = '/signalk';
  var apiPathPrefix = pathPrefix + '/v1/api/';

  return {
    start: function() {
      app.use('/', express.static(__dirname + '/../../public'));

      app.get(apiPathPrefix + '*', function(req, res) {
        var path = String(req.path).replace(apiPathPrefix, '');
        var data = app.signalk.retrieve();
        var last = data;

        path = path.length > 0 ? path.replace(/\/$/, '').replace(/self/, app.selfId).split('/') : [];

        for(var i in path) {
          var p = path[i];

          if(typeof last[p] !== 'undefined') {
            last = last[p];
          } else {
            res.status(404).send("Not found");
            return
          }
        }

        return res.json(last);
      });

      app.get(pathPrefix, function(req, res) {
        var host = app.config.getExternalHostname();
        var port = app.config.getExternalPort();
        port = (port === '' || port === 80) ? '' : ':' + port;

        res.json({
          'endpoints': {
            'v1': {
              'version': '1.alpha1',
              'signalk-http': 'http://' + host + port + '/signalk/v1/api',
              'signalk-ws': 'http://' + host + port + '/signalk/v1/stream'
            }
          }
        });
      })

    },

    mdns: {
      name: "_signalk-http",
      type: "tcp",
      port: app.config.port
    }
  };
};
<commit_msg>Make signalk-http coincide with the actual URL of the REST API and remove the need to change it in two places.<commit_after>/*
 * Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

module.exports = function(app) {
  'use strict';

  var debug = require('debug')('signalk-server:interfaces:rest');
  var express = require('express');

  var pathPrefix = '/signalk';
  var apiPathPrefix = pathPrefix + '/v1/api/';

  return {
    start: function() {
      app.use('/', express.static(__dirname + '/../../public'));

      app.get(apiPathPrefix + '*', function(req, res) {
        var path = String(req.path).replace(apiPathPrefix, '');
        var data = app.signalk.retrieve();
        var last = data;

        path = path.length > 0 ? path.replace(/\/$/, '').replace(/self/, app.selfId).split('/') : [];

        for(var i in path) {
          var p = path[i];

          if(typeof last[p] !== 'undefined') {
            last = last[p];
          } else {
            res.status(404).send("Not found");
            return
          }
        }

        return res.json(last);
      });

      app.get(pathPrefix, function(req, res) {
        var host = app.config.getExternalHostname();
        var port = app.config.getExternalPort();
        port = (port === '' || port === 80) ? '' : ':' + port;

        res.json({
          'endpoints': {
            'v1': {
              'version': '1.alpha1',
              'signalk-http': 'http://' + host + port + apiPathPrefix,
              'signalk-ws': 'http://' + host + port + '/signalk/v1/stream'
            }
          }
        });
      })

    },

    mdns: {
      name: "_signalk-http",
      type: "tcp",
      port: app.config.port
    }
  };
};
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var xmpp = require('node-xmpp')
  , uuid = require('node-uuid')
  , util = require('util')
  , assert = require('assert')
  //, NullStream = require('./nullstream');

// TODO: This class can be removed once it is completely transitioned to application.js

/**
 * Initialize a new `Client`.
 *
 * @param {Object} options
 */
function Client(options) {
  options = options || {}
  // WORKAROUND: Disable socket streams in underlying node-xmpp, useful in cases
  //             where one is not necessary (such as mounted connections or
  //             tests).
  this._disableStream = options.disableStream || false;

  xmpp.Client.call(this, options);
  this._stack = [];
  this._filters = [];
  this.addListener('stanza', this.handle);
}

/**
 * Inherit from `xmpp.Client`.
 */
util.inherits(Client, xmpp.Client);

/**
 * Utilize the given middleware `handle`.
 *
 * @param {Function} handle
 * @return {Connection} for chaining
 */

Client.prototype.use = function(ns, handle) {
  // TODO: Allow ns to be set as an XPath expression, in order to limit the
  //       scope of the handler.
  // TODO: Alternatively, let the qualifier be the JID to which the stanza is
  //       addressed.  This would be beneficial for components that handle a
  //       domain, but want to be addressed using node@domain.  I'm leaning in
  //       favor of this approach, rather than the XPath one.
  if ('string' != typeof ns) {
    handle = ns;
    ns = null;
  }

  // wrap sub-apps
  // TODO: Implement test cases for this functionality
  if ('function' == typeof handle.handle) {
    var connection = handle;
    connection.send = this.send.bind(this);
    connection.generateID = this.generateID.bind(this);
    handle = function(stanza, next){
      connection.handle(stanza, next);
    };
  }

  this._stack.push({ ns: ns, handle: handle });
  return this;
}

/**
 * Utilize the given filter `handle`.
 *
 * @param {Function} handle
 * @return {Connection} for chaining
 */

Client.prototype.filter = function(handle) {
  this._filters.push({ handle: handle });
  return this;
}

/**
 * Handle stanza, running it through the middleware stack.
 *
 * @api private
 */

Client.prototype.handle = function(stanza, out) {
  var self = this;
  var stack = self._stack;
  var idx = 0;
  var res = self._prepResponse(stanza);

  // stanza is an instance of ltx.Element.  As such, it has the following
  // properties: name, parent, attrs, children.  Additional properties can
  // be assigned, as the stanza is parsed, including the initial set attached
  // here.
  stanza.connection = stanza.connection || this;
  stanza.id = stanza.attrs.id;
  stanza.from = new xmpp.JID(stanza.attrs.from);
  stanza.to = new xmpp.JID(stanza.attrs.to);
  stanza.type = stanza.attrs.type;

  function next(err) {
    var layer = stack[idx++];

    // all done
    if (!layer) {
      // but wait! we have a parent
      if (out) { return out(err); }
      return;
    }

    try {
      var arity = layer.handle.length;
      if (err) {
        if (arity == 4) {
          layer.handle(err, stanza, res, next);
        } else {
          next(err);
        }
      } else {
        if (arity == 2) {
          layer.handle(stanza, next);
        } else if (arity == 3 && res) {
          layer.handle(stanza, res, next);
        } else {
          next();
        }
      }
    } catch (e) {
      if (e instanceof assert.AssertionError) {
        console.error(e.stack + '\n');
        next(e);
      } else {
        next(e);
      }
    }
  }
  next();
}

/**
 * Send stanza, running it through the filter chain.
 *
 * @param {Element|XMLElement} stanza
 */

Client.prototype.send = function(stanza) {
  if (stanza.toXML) {
    stanza = stanza.toXML();
  }

  // TODO: Implement a filter for logging outgoing stanzas.
  /*
  if (stanza.root) {
      console.log('SEND: ' + stanza.root().toString() + '\n');
  } else {
      console.log('SEND: ' + stanza + '\n');
  }
  */

  var self = this;
  var filters = this._filters;
  var idx = 0;
  function next() {
    var filter = filters[idx++];

    // all done, the stanza can be sent
    if (!filter) {
      xmpp.Client.prototype.send.call(self, stanza);
      return;
    }

    // TODO: Implement error handling
    try {
      filter.handle(stanza, next);
    } catch (e) {
      if (e instanceof assert.AssertionError) {
        console.error(e.stack + '\n');
        next();
      } else {
        console.error(e.stack + '\n');
        next();
      }
    }
  }
  if (typeof stanza !== 'string') {
    next();
  } else {
    // raw strings bypass the filter mechanism.
    xmpp.Client.prototype.send.call(this, stanza);
  }
}

/**
 * Override xmpp.Connection's setupStream(), substituting a NullStream for the
 * socket property, if disableStream option is set.
 *
 * @api private
 */
Client.prototype.setupStream = function() {
  if (this._disableStream) {
    this.socket = new NullStream();
    return;
  }
  xmpp.Client.prototype.setupStream.call(this);
}

/**
 * Generate a unique identifier, for use in a stanza's `id` attribute.
 *
 * @return {String}
 */
Client.prototype.generateID = function() {
  return uuid();
}

/**
 * Prepare a response to `stanza`.
 *
 * @api private
 */
Client.prototype._prepResponse = function(stanza) {
  var self = this;

  var res;

  if (stanza.is('iq') && (stanza.attrs.type == 'get' || stanza.attrs.type == 'set')) {
    // TODO: When connected as a component, the from field needs to be set
    //       eplicitly (from = stanza.attrs.to).
    res = new xmpp.Element('iq', { id: stanza.attrs.id,
                                   to: stanza.attrs.from,
                                   type: 'result' })
  }

  if (res) {
    // Hook for for sending the response.
    res.send = function() {
      self.send(this);
    }
  }
  return res;
}

/**
 * Expose `Client`.
 */

module.exports = Client;
<commit_msg>Remove Client.<commit_after><|endoftext|>


<commit_before>var webdav = require('../../lib/index.js'),
    request = require('request')

module.exports = (test, options, index) => test('options method', isValid =>
{
    var server = new webdav.WebDAVServer();
    server.start(options.port + index);
    isValid = isValid.multiple(1, server);

    request({
        url: 'http://localhost:' + (options.port + index),
        method: 'OPTIONS'
    }, (e, res, body) => {
        isValid(res.headers.allow && res.headers.allow.length >= 3 && /^[a-zA-Z,]+$/g.test(res.headers.allow));
    })
})<commit_msg>Fixed the test<commit_after>var webdav = require('../../lib/index.js'),
    request = require('request')

module.exports = (test, options, index) => test('OPTIONS method', isValid =>
{
    var server = new webdav.WebDAVServer();
    server.start(options.port + index);
    isValid = isValid.multiple(1, server);

    request({
        url: 'http://localhost:' + (options.port + index),
        method: 'OPTIONS'
    }, (e, res, body) => {
        isValid(!e && res.headers.allow && res.headers.allow.length >= 3 && /^[a-zA-Z,]+$/g.test(res.headers.allow));
    })
})<|endoftext|>


<commit_before>const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const KEY = require('selenium-webdriver').Key;

const expect = chai.expect;
chai.use(chaiAsPromised);

describe('package', () => {
	it('displays default file', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr?version=0.1.2`);
		await browser.sleep(1000);
		await expect(browser.findElement({ css: '.file-path' }).getText()).to.eventually.contain('/index.min.js');
	});

	it('displays no default file', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/bootstrap`);
		await browser.sleep(1000);
		await expect(browser.findElement({ css: '.file-message' })).to.eventually.not.equal(null);
	});

	it('opening directories works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr?version=0.1.2`);
		await browser.sleep(1000);
		await browser.findElement({ css: '.c-package-file-browser .box-content .file-link:nth-of-type(1) a' }).click();
		await expect(browser.findElement({ css: '.box-content .file-link:nth-of-type(2) .file-path' }).getText()).to.eventually.equal('demos/api_demo.js');
	});

	it('going up in directories works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr?version=0.1.2&path=demos`);
		await browser.sleep(1000);
		await browser.findElement({ css: '.c-package-file-browser .box-content .file-link:nth-of-type(1) a' }).click();
		await expect(browser.findElement({ css: '.box-content .file-link:nth-of-type(1) .file-path' }).getText()).to.eventually.equal('demos');
	});

	it('opening files works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr?version=0.1.2&path=demos`);
		await browser.sleep(1000);
		await browser.findElement({ css: '.box-content .file-link:nth-of-type(2) a' }).click();
		await expect(browser.findElement({ css: 'pre' }).getText()).to.eventually.have.lengthOf.at.least(1);
		let tabs = await browser.getAllWindowHandles();
		await browser.switchTo().window(tabs[1]);
		await browser.close();
		await browser.switchTo().window(tabs[0]);
	});

	it('changing versions works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr`);
		await browser.sleep(1000);
		await browser.findElement({ css: '.version-dropdown-selected-version' }).click();
		await browser.sleep(1000);
		await browser.findElement({ css: '.dropdown-menu-right li:last-of-type a' }).click();
		await browser.sleep(2000);
		await expect(browser.findElement({ css: '.box-content .file-link:nth-of-type(7) .file-path' }).getText()).to.eventually.equal('index.js');
	});

	it('copying url works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr?version=0.1.2`);
		await browser.sleep(1000);
		await browser.findElement({ css: '.box-content .file-link:nth-of-type(4) .c-copy-dropdown span' }).click();
		await browser.sleep(1000);
		await browser.findElement({ css: '.box-content .file-link:nth-of-type(4) .dropdown-menu a' }).click();
		await browser.sleep(1000);
		await browser.executeScript(`let ele = document.createElement('input'); ele.setAttribute('id', 'testInput'); document.body.appendChild(ele)`);
		await browser.findElement({ css: '#testInput' }).sendKeys(KEY.CONTROL, 'v');
		await browser.sleep(1000);
		await expect(browser.findElement({ css: '#testInput' }).getAttribute('value')).to.eventually.equal('https://cdn.jsdelivr.net/npm/jsdelivr@0.1.2/.jshintrc');
		await browser.executeScript(`$('#testInput').remove()`);
	});

	it('adding files to collection works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr`);
		await browser.sleep(2500);
		await browser.findElement({ css: '.box-content .file-link:nth-of-type(7) label' }).click();
		await browser.findElement({ css: '.box-content .file-link:nth-of-type(8) label' }).click();
		await browser.sleep(1000);
		await browser.findElement({ css: '.hidden-sm > .c-collection-box .box-content-button' }).click();
		await browser.sleep(1000);
		await expect(browser.findElement({ css: '.c-collection-links .collection-link:nth-of-type(3) a' }).getText()).to.eventually.equal('https://cdn.jsdelivr.net/npm/jsdelivr@0.1.2/demo.min.js');
	});

	it('removing all files from collection works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr`);
		await browser.sleep(1000);
		await browser.findElement({ css: '.box-content .file-link:nth-of-type(4) label' }).click();
		await browser.findElement({ css: '.box-content .file-link:nth-of-type(5) label' }).click();
		await browser.sleep(1000);
		await browser.executeScript(`arguments[0].click();`, await browser.findElement({ css: '.box-header .fa-trash' }));
		await browser.sleep(1000);
		await expect(browser.findElement({ css: '.hidden-sm > .c-collection-box .box-content .box-message' }).getText()).to.eventually.equal('No files selected. Select the files you want to use using the switches on the left.');
	});

	it('show all files works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr`);
		await browser.sleep(1000);
		await browser.findElement({ css: '.c-package-file-browser .show-more-toggle a' }).click();
		await browser.sleep(1000);
		await expect(browser.findElement({ css: '.c-package-file-browser .box-content div:nth-of-type(11) .file-link:nth-of-type(1) span' }).getText()).to.eventually.contain('README.md');
	});

	it('top files switching versions works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/slick-carousel?version=1.8.1`);
		await browser.sleep(2000);
		let version = await browser.findElement({ css: '.c-stats-table:nth-of-type(1) tr:nth-of-type(2) a' }).getText();
		await browser.findElement({ css: '.c-stats-table:nth-of-type(1) .stats-table-table tr:nth-of-type(2) a' }).click();
		await browser.sleep(2000);
		await expect(browser.findElement({ css: '.c-stats-table .version-dropdown-selected-version a' }).getText()).to.eventually.equal(version);
	});
});
<commit_msg>Increase sleep time in some tests<commit_after>const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const KEY = require('selenium-webdriver').Key;

const expect = chai.expect;
chai.use(chaiAsPromised);

describe('package', () => {
	it('displays default file', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr?version=0.1.2`);
		await browser.sleep(2000);
		await expect(browser.findElement({ css: '.file-path' }).getText()).to.eventually.contain('/index.min.js');
	});

	it('displays no default file', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/bootstrap`);
		await browser.sleep(2000);
		await expect(browser.findElement({ css: '.file-message' })).to.eventually.not.equal(null);
	});

	it('opening directories works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr?version=0.1.2`);
		await browser.sleep(2000);
		await browser.findElement({ css: '.c-package-file-browser .box-content .file-link:nth-of-type(1) a' }).click();
		await expect(browser.findElement({ css: '.box-content .file-link:nth-of-type(2) .file-path' }).getText()).to.eventually.equal('demos/api_demo.js');
	});

	it('going up in directories works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr?version=0.1.2&path=demos`);
		await browser.sleep(2000);
		await browser.findElement({ css: '.c-package-file-browser .box-content .file-link:nth-of-type(1) a' }).click();
		await expect(browser.findElement({ css: '.box-content .file-link:nth-of-type(1) .file-path' }).getText()).to.eventually.equal('demos');
	});

	it('opening files works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr?version=0.1.2&path=demos`);
		await browser.sleep(2000);
		await browser.findElement({ css: '.box-content .file-link:nth-of-type(2) a' }).click();
		await expect(browser.findElement({ css: 'pre' }).getText()).to.eventually.have.lengthOf.at.least(1);
		let tabs = await browser.getAllWindowHandles();
		await browser.switchTo().window(tabs[1]);
		await browser.close();
		await browser.switchTo().window(tabs[0]);
	});

	it('changing versions works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr`);
		await browser.sleep(2000);
		await browser.findElement({ css: '.version-dropdown-selected-version' }).click();
		await browser.sleep(1000);
		await browser.findElement({ css: '.dropdown-menu-right li:last-of-type a' }).click();
		await browser.sleep(2000);
		await expect(browser.findElement({ css: '.box-content .file-link:nth-of-type(7) .file-path' }).getText()).to.eventually.equal('index.js');
	});

	it('copying url works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr?version=0.1.2`);
		await browser.sleep(2000);
		await browser.findElement({ css: '.box-content .file-link:nth-of-type(4) .c-copy-dropdown span' }).click();
		await browser.sleep(1000);
		await browser.findElement({ css: '.box-content .file-link:nth-of-type(4) .dropdown-menu a' }).click();
		await browser.sleep(1000);
		await browser.executeScript(`let ele = document.createElement('input'); ele.setAttribute('id', 'testInput'); document.body.appendChild(ele)`);
		await browser.findElement({ css: '#testInput' }).sendKeys(KEY.CONTROL, 'v');
		await browser.sleep(1000);
		await expect(browser.findElement({ css: '#testInput' }).getAttribute('value')).to.eventually.equal('https://cdn.jsdelivr.net/npm/jsdelivr@0.1.2/.jshintrc');
		await browser.executeScript(`$('#testInput').remove()`);
	});

	it('adding files to collection works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr`);
		await browser.sleep(2500);
		await browser.findElement({ css: '.box-content .file-link:nth-of-type(7) label' }).click();
		await browser.findElement({ css: '.box-content .file-link:nth-of-type(8) label' }).click();
		await browser.sleep(1000);
		await browser.findElement({ css: '.hidden-sm > .c-collection-box .box-content-button' }).click();
		await browser.sleep(1000);
		await expect(browser.findElement({ css: '.c-collection-links .collection-link:nth-of-type(3) a' }).getText()).to.eventually.equal('https://cdn.jsdelivr.net/npm/jsdelivr@0.1.2/demo.min.js');
	});

	it('removing all files from collection works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr`);
		await browser.sleep(2000);
		await browser.findElement({ css: '.box-content .file-link:nth-of-type(4) label' }).click();
		await browser.findElement({ css: '.box-content .file-link:nth-of-type(5) label' }).click();
		await browser.sleep(1000);
		await browser.executeScript(`arguments[0].click();`, await browser.findElement({ css: '.box-header .fa-trash' }));
		await browser.sleep(1000);
		await expect(browser.findElement({ css: '.hidden-sm > .c-collection-box .box-content .box-message' }).getText()).to.eventually.equal('No files selected. Select the files you want to use using the switches on the left.');
	});

	it('show all files works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/jsdelivr`);
		await browser.sleep(2000);
		await browser.findElement({ css: '.c-package-file-browser .show-more-toggle a' }).click();
		await browser.sleep(1000);
		await expect(browser.findElement({ css: '.c-package-file-browser .box-content div:nth-of-type(11) .file-link:nth-of-type(1) span' }).getText()).to.eventually.contain('README.md');
	});

	it('top files switching versions works', async () => {
		await browser.navigate().to(`${BASE_URL}/package/npm/slick-carousel?version=1.8.1`);
		await browser.sleep(2000);
		let version = await browser.findElement({ css: '.c-stats-table:nth-of-type(1) tr:nth-of-type(2) a' }).getText();
		await browser.findElement({ css: '.c-stats-table:nth-of-type(1) .stats-table-table tr:nth-of-type(2) a' }).click();
		await browser.sleep(2000);
		await expect(browser.findElement({ css: '.c-stats-table .version-dropdown-selected-version a' }).getText()).to.eventually.equal(version);
	});
});
<|endoftext|>


<commit_before>require.paths.unshift(__dirname + '/../lib/node', __dirname + '/../');
var assert = require('assert');
var fs = require('fs');

var app = require('tilemill');
var inspect = require('inspect');

var project = '';
var project2 = '';
module.exports = {
    'abilities': function() {
        assert.response(app, { url: '/abilities' }, {
            status: 200
        }, function(res) {
            var data = JSON.parse(res.body);
            assert.ok(data.fonts, 'Available fonts');
            assert.ok(data.datasources, 'Available datasources');
        });
    },
    'version': function() {
        assert.response(app, {
            url: '/api',
        }, {
            status: 200
        }, function(res) {
            var data = JSON.parse(res.body);
            assert.equal(data.api, 'basic', 'API');
            assert.equal(data.version, 1, 'API Version');
        });
    },
    'project manipulation': function() {
        fs.readFile('./test/fixtures/project1.json', 'utf8', function(err, project) {
            assert.response(app, {
                url: '/api/project/Test',
                method: 'PUT',
                headers: {
                    'content-type': 'application/json'
                },
                data: project
            }, {
                status: 200
            }, function(res) {
                assert.equal(JSON.stringify(JSON.parse(res.body)), JSON.stringify(JSON.parse(project)));
            });
            assert.response(app, {
                url: '/api/project/Test',
                method: 'GET',
            }, {
                status: 200
            }, function(res) {
                assert.equal(JSON.stringify(JSON.parse(res.body)), JSON.stringify(JSON.parse(project)));
            });
            assert.response(app, {
                url: '/api/project/Test',
                method: 'PUT',
                headers: {
                    'content-type': 'application/json'
                },
                data: project
            }, {
                status: 200
            }, function(res) {
                assert.equal(JSON.stringify(JSON.parse(res.body)), JSON.stringify(JSON.parse(project)));
            });
            assert.response(app, {url: '/aHR0cDovL2xvY2FsaG9zdDo4ODg5L2FwaS9wcm9qZWN0L1Rlc3Q_MDI3N2M0/world'}, {
                status: 200
            }, function(res) {
                var data = JSON.parse(res.body);
                assert.equal(data.id, 'world', 'Unexpected layer id');
                assert.equal(data.features.length, 245, 'Feature count mismatch');
            });
            assert.response(app, {
                url: '/api/project/Test',
                method: 'DELETE'
            }, {
                status: 200
            }, function(res) {
                assert.equal(res.body, '{}');
            });
        });
    },
    'invalid map': function() {
        assert.response(app, { url: '/foobar' }, {
            status: 500
        }, function(res) {
            var data = JSON.parse(res.body);
            assert.equal(data.message, 'Error loading map file', 'Unexpected error message');
        });
    }
};

var loadFixture = function(file, callback) {
    require('fs').readfile('./test/fixtures/' + file, callback);
}
<commit_msg>Add comments to test.<commit_after>require.paths.unshift(__dirname + '/../lib/node', __dirname + '/../');
var assert = require('assert');
var fs = require('fs');

var app = require('tilemill');
var inspect = require('inspect');

var project = '';
var project2 = '';
module.exports = {
    'abilities': function() {
        assert.response(app, { url: '/abilities' }, {
            status: 200
        }, function(res) {
            var data = JSON.parse(res.body);
            assert.ok(data.fonts, 'Available fonts');
            assert.ok(data.datasources, 'Available datasources');
        });
    },
    'version': function() {
        assert.response(app, {
            url: '/api',
        }, {
            status: 200
        }, function(res) {
            var data = JSON.parse(res.body);
            assert.equal(data.api, 'basic', 'API');
            assert.equal(data.version, 1, 'API Version');
        });
    },
    'project manipulation': function() {
        fs.readFile('./test/fixtures/project1.json', 'utf8', function(err, project) {
            assert.response(app, {
                url: '/api/project/Test',
                method: 'PUT',
                headers: {
                    'content-type': 'application/json'
                },
                data: project
            }, {
                status: 200
            }, function(res) {
                assert.equal(JSON.stringify(JSON.parse(res.body)), JSON.stringify(JSON.parse(project)));
            });
            // Get project
            assert.response(app, {
                url: '/api/project/Test',
                method: 'GET',
            }, {
                status: 200
            }, function(res) {
                assert.equal(JSON.stringify(JSON.parse(res.body)), JSON.stringify(JSON.parse(project)));
            });

            fs.readFile('./test/fixtures/project2.json', 'utf8', function(err, project) {
                // Update project
                assert.response(app, {
                    url: '/api/project/Test',
                    method: 'PUT',
                    headers: {
                        'content-type': 'application/json'
                    },
                    data: project
                }, {
                    status: 200
                }, function(res) {
                    assert.equal(JSON.stringify(JSON.parse(res.body)), JSON.stringify(JSON.parse(project)));
                });
                // Load layer
                assert.response(app, {url: '/aHR0cDovL2xvY2FsaG9zdDo4ODg5L2FwaS9wcm9qZWN0L1Rlc3Q_MDI3N2M0/world'}, {
                    status: 200
                }, function(res) {
                    var data = JSON.parse(res.body);
                    assert.equal(data.id, 'world', 'Unexpected layer id');
                    assert.equal(data.features.length, 245, 'Feature count mismatch');
                });
                // Delete project
                assert.response(app, {
                    url: '/api/project/Test',
                    method: 'DELETE'
                }, {
                    status: 200
                }, function(res) {
                    assert.equal(res.body, '{}');
                });
            });
        });
    },
    'invalid map': function() {
        assert.response(app, { url: '/foobar' }, {
            status: 500
        }, function(res) {
            var data = JSON.parse(res.body);
            assert.equal(data.message, 'Error loading map file', 'Unexpected error message');
        });
    }
};

var loadFixture = function(file, callback) {
    require('fs').readfile('./test/fixtures/' + file, callback);
}
<|endoftext|>


<commit_before>(function (tree) {

tree.mixin = {};
tree.mixin.Call = function (elements, args, index) {
    this.selector = new(tree.Selector)(elements);
    this.arguments = args;
    this.index = index;
};
tree.mixin.Call.prototype = {
    eval: function (env) {
        var mixins, rules = [], match = false;

        for (var i = 0; i < env.frames.length; i++) {
            if ((mixins = env.frames[i].find(this.selector)).length > 0) {
                for (var m = 0; m < mixins.length; m++) {
                    if (mixins[m].match(this.arguments, env)) {
                        try {
                            Array.prototype.push.apply(
                                  rules, mixins[m].eval(env, this.arguments).rules);
                            match = true;
                        } catch (e) {
                            throw { message: e.message, index: e.index, stack: e.stack, call: this.index };
                        }
                    }
                }
                if (match) {
                    return rules;
                } else {
                    throw { message: 'No matching definition was found for `' +
                                      this.selector.toCSS().trim() + '('      +
                                      this.arguments.map(function (a) {
                                          return a.toCSS();
                                      }).join(', ') + ")`",
                            index:   this.index };
                }
            }
        }
        throw { message: this.selector.toCSS().trim() + " is undefined",
                index: this.index };
    }
};

tree.mixin.Definition = function (name, params, rules) {
    this.name = name;
    this.selectors = [new(tree.Selector)([new(tree.Element)(null, name)])];
    this.params = params;
    this.arity = params.length;
    this.rules = rules;
    this._lookups = {};
    this.required = params.reduce(function (count, p) {
        if (p.name && !p.value) { return count + 1 }
        else                    { return count }
    }, 0);
    this.parent = tree.Ruleset.prototype;
    this.frames = [];
};
tree.mixin.Definition.prototype = {
    toCSS: function () { return "" },
    variable: function (name) { return this.parent.variable.call(this, name) },
    find:     function ()     { return this.parent.find.apply(this, arguments) },
    rulesets: function ()     { return this.parent.rulesets.apply(this) },

    eval: function (env, args) {
        var frame = new(tree.Ruleset)(null, []), context;

        for (var i = 0, val; i < this.params.length; i++) {
            if (this.params[i].name) {
                if (val = (args && args[i]) || this.params[i].value) {
                    frame.rules.unshift(new(tree.Rule)(this.params[i].name, val.eval(env)));
                } else {
                    throw { message: "wrong number of arguments for " + this.name +
                            ' (' + args.length + ' for ' + this.arity + ')' };
                }
            }
        }
        return new(tree.Ruleset)(null, this.rules.slice(0)).eval({
            frames: [this, frame].concat(this.frames, env.frames)
        });
    },
    match: function (args, env) {
        var argsLength = (args && args.length) || 0;

        if (argsLength < this.required) {
            return false;
        }

        for (var i = 0; i < Math.min(argsLength, this.arity); i++) {
            if (!this.params[i].name) {
                if (args[i].wildcard) { continue }
                else if (args[i].eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) {
                    return false;
                }
            }
        }
        return true;
    }
};

})(require('less/tree'));
<commit_msg>small refactor in mixin.match<commit_after>(function (tree) {

tree.mixin = {};
tree.mixin.Call = function (elements, args, index) {
    this.selector = new(tree.Selector)(elements);
    this.arguments = args;
    this.index = index;
};
tree.mixin.Call.prototype = {
    eval: function (env) {
        var mixins, rules = [], match = false;

        for (var i = 0; i < env.frames.length; i++) {
            if ((mixins = env.frames[i].find(this.selector)).length > 0) {
                for (var m = 0; m < mixins.length; m++) {
                    if (mixins[m].match(this.arguments, env)) {
                        try {
                            Array.prototype.push.apply(
                                  rules, mixins[m].eval(env, this.arguments).rules);
                            match = true;
                        } catch (e) {
                            throw { message: e.message, index: e.index, stack: e.stack, call: this.index };
                        }
                    }
                }
                if (match) {
                    return rules;
                } else {
                    throw { message: 'No matching definition was found for `' +
                                      this.selector.toCSS().trim() + '('      +
                                      this.arguments.map(function (a) {
                                          return a.toCSS();
                                      }).join(', ') + ")`",
                            index:   this.index };
                }
            }
        }
        throw { message: this.selector.toCSS().trim() + " is undefined",
                index: this.index };
    }
};

tree.mixin.Definition = function (name, params, rules) {
    this.name = name;
    this.selectors = [new(tree.Selector)([new(tree.Element)(null, name)])];
    this.params = params;
    this.arity = params.length;
    this.rules = rules;
    this._lookups = {};
    this.required = params.reduce(function (count, p) {
        if (p.name && !p.value) { return count + 1 }
        else                    { return count }
    }, 0);
    this.parent = tree.Ruleset.prototype;
    this.frames = [];
};
tree.mixin.Definition.prototype = {
    toCSS: function () { return "" },
    variable: function (name) { return this.parent.variable.call(this, name) },
    find:     function ()     { return this.parent.find.apply(this, arguments) },
    rulesets: function ()     { return this.parent.rulesets.apply(this) },

    eval: function (env, args) {
        var frame = new(tree.Ruleset)(null, []), context;

        for (var i = 0, val; i < this.params.length; i++) {
            if (this.params[i].name) {
                if (val = (args && args[i]) || this.params[i].value) {
                    frame.rules.unshift(new(tree.Rule)(this.params[i].name, val.eval(env)));
                } else {
                    throw { message: "wrong number of arguments for " + this.name +
                            ' (' + args.length + ' for ' + this.arity + ')' };
                }
            }
        }
        return new(tree.Ruleset)(null, this.rules.slice(0)).eval({
            frames: [this, frame].concat(this.frames, env.frames)
        });
    },
    match: function (args, env) {
        var argsLength = (args && args.length) || 0, len;

        if (argsLength < this.required) { return false }

        len = Math.min(argsLength, this.arity);

        for (var i = 0; i < len; i++) {
            if (!this.params[i].name) {
                if (args[i].eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) {
                    return false;
                }
            }
        }
        return true;
    }
};

})(require('less/tree'));
<|endoftext|>