<commit_before>/*global define, $*/
define(
	[ 'jquery' ],
	function( $ )
	{
		var signals;
		var wrapper = $( '.center-wrapper' );
		var canvas = $( '#homescreen' );
		var ctx = canvas[0].getContext( '2d' );
		var size;

		// todo: get canvas size from cam/image

		function init( shared )
		{
			signals = shared.signals;
			signals['draw'].add( draw );
			signals['cam-started'].add( activateCanvas );
			signals['capture'].add( sendCapture );

			updateCanvasSize( { width: 640, height: 480 } );

			canvas.click( canvasClicked );
		}

		function canvasClicked( event )
		{
			event.preventDefault();

			signals['capture'].dispatch();
		}

		function updateCanvasSize( new_size )
		{
			canvas.attr( new_size );
			size = new_size;
		}

		function draw( instructions )
		{
			clear();

			for ( var key in instructions )
			{
				if (
					typeof instructions[key] === 'object' &&
					instructions[key].updated
				)
				{
					drawByInstruction( instructions[key], ctx );

					//console.log( 'DRAW KEY', key );
				}

				else
				{
					//console.log( 'DONT DRAW', key );
				}
			}
		}

		function drawByInstruction( obj, ctx )
		{
			if ( obj.updated )
			{
				if ( typeof obj === 'object' )
				{
					if ( obj.shape === 'line' )
					{
						drawLine( obj, ctx );
					}

					if ( obj.shape === 'circle' )
					{
						drawCircle( obj, ctx );
					}

					if ( obj.shape === 'rect' )
					{
						drawRect( obj, ctx );
					}
				}
			}
		}

		function drawCircle( c, ctx )
		{
			if ( typeof c === 'object' )
			{
				ctx.beginPath();
				ctx.arc( c.pos.elements[0], c.pos.elements[1], c.rad, 0, Math.PI * 2, true );
				ctx.closePath();
				ctx.fillStyle = c.color;
				ctx.fill();
			}
		}

		function drawLine( l, ctx )
		{
			if ( typeof l === 'object' )
			{
				ctx.beginPath();
				ctx.lineWidth = l.width;
				ctx.strokeStyle = l.color;
				ctx.moveTo( l.points[0].pos.elements[0], l.points[0].pos.elements[1] );
				ctx.lineTo( l.points[1].pos.elements[0], l.points[1].pos.elements[1] );
				ctx.stroke();
				ctx.closePath();
			}
		}

		function drawRect( r, ctx )
		{
			if ( typeof r === 'object' )
			{
				ctx.fillStyle = r.color;
				ctx.fillRect( r.pos.elements[0], r.pos.elements[1], r.width, r.height );
				ctx.fill();
			}
		}

		function clear( obj )
		{
			if ( size )
			{
				var clr = obj || { x: 0, y: 0, width: size.width, height: size.height };

				ctx.clearRect( clr.x, clr.y, clr.width, clr.height );
			}
		}

		function activateCanvas()
		{
			wrapper.addClass( 'is-active' );
		}

		function getImageUrlFromCanvas()
		{
			return canvas[0].toDataURL( 'image/png' );
		}

		function sendCapture()
		{
			var src = getImageUrlFromCanvas();

			signals['canvas-img'].dispatch( src );
		}

		var canvas_manager = {
			init: init
		};

		return canvas_manager;
	}
);<commit_msg>remove comments<commit_after>/*global define, $*/
define(
	[ 'jquery' ],
	function( $ )
	{
		var signals;
		var wrapper = $( '.center-wrapper' );
		var canvas = $( '#homescreen' );
		var ctx = canvas[0].getContext( '2d' );
		var size;

		// todo: get canvas size from cam/image

		function init( shared )
		{
			signals = shared.signals;
			signals['draw'].add( draw );
			signals['cam-started'].add( activateCanvas );
			signals['capture'].add( sendCapture );

			updateCanvasSize( { width: 640, height: 480 } );

			canvas.click( canvasClicked );
		}

		function canvasClicked( event )
		{
			event.preventDefault();

			signals['capture'].dispatch();
		}

		function updateCanvasSize( new_size )
		{
			canvas.attr( new_size );
			size = new_size;
		}

		function draw( instructions )
		{
			clear();

			for ( var key in instructions )
			{
				if (
					typeof instructions[key] === 'object' &&
					instructions[key].updated
				)
				{
					drawByInstruction( instructions[key], ctx );
				}
			}
		}

		function drawByInstruction( obj, ctx )
		{
			if ( obj.updated )
			{
				if ( typeof obj === 'object' )
				{
					if ( obj.shape === 'line' )
					{
						drawLine( obj, ctx );
					}

					if ( obj.shape === 'circle' )
					{
						drawCircle( obj, ctx );
					}

					if ( obj.shape === 'rect' )
					{
						drawRect( obj, ctx );
					}
				}
			}
		}

		function drawCircle( c, ctx )
		{
			if ( typeof c === 'object' )
			{
				ctx.beginPath();
				ctx.arc( c.pos.elements[0], c.pos.elements[1], c.rad, 0, Math.PI * 2, true );
				ctx.closePath();
				ctx.fillStyle = c.color;
				ctx.fill();
			}
		}

		function drawLine( l, ctx )
		{
			if ( typeof l === 'object' )
			{
				ctx.beginPath();
				ctx.lineWidth = l.width;
				ctx.strokeStyle = l.color;
				ctx.moveTo( l.points[0].pos.elements[0], l.points[0].pos.elements[1] );
				ctx.lineTo( l.points[1].pos.elements[0], l.points[1].pos.elements[1] );
				ctx.stroke();
				ctx.closePath();
			}
		}

		function drawRect( r, ctx )
		{
			if ( typeof r === 'object' )
			{
				ctx.fillStyle = r.color;
				ctx.fillRect( r.pos.elements[0], r.pos.elements[1], r.width, r.height );
				ctx.fill();
			}
		}

		function clear( obj )
		{
			if ( size )
			{
				var clr = obj || { x: 0, y: 0, width: size.width, height: size.height };

				ctx.clearRect( clr.x, clr.y, clr.width, clr.height );
			}
		}

		function activateCanvas()
		{
			wrapper.addClass( 'is-active' );
		}

		function getImageUrlFromCanvas()
		{
			return canvas[0].toDataURL( 'image/png' );
		}

		function sendCapture()
		{
			var src = getImageUrlFromCanvas();

			signals['canvas-img'].dispatch( src );
		}

		var canvas_manager = {
			init: init
		};

		return canvas_manager;
	}
);<|endoftext|>


<commit_before>/*
 * Geddy JavaScript Web development framework
 * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
 *
 * 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.
 *
*/

var sys = require('sys');

var fleegix = require('geddy-core/lib/fleegix');

var Config = function (dirname) {

  this.environment = 'development';
  this.port = 8000;
  this.dirname = dirname;
  this.staticFilePath = dirname + '/public';
  this.plugins = {};

  this.sessions = {
    store: 'memory'
  };
  /*
  this.database = {
    adapter: 'couchdb'
    dbHostname: 'localhost',
    dbName: 'geddy_db',
    dbPort: 5984
  };

  this.sessions = {
    store: 'couchdb',
    key: 'sid',
    expiry: 14 * 24 * 60 * 60,
    dbHostname: 'localhost',
    dbName: 'geddy_sessions',
    dbPort: 5984
  };

  this.plugins = {
    'Auth': {
      // Pluggable auth types to check, in order
      authTypes: ['Cookie', 'Basic'],
      // The key to look for in the session to indicate logged-in status
      authedSessionKey: 'login',
      // The page to redirect to when hitting an auth-required HTML page
      htmlRedirect: '/login'
    }
  };
  */

  // Override with app-level opts
  var opts = require(dirname + '/config/config');
  fleegix.mixin(this, opts, true);
};

exports.Config = Config;
<commit_msg>Add session key name and expiry to default memory-based session config.<commit_after>/*
 * Geddy JavaScript Web development framework
 * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
 *
 * 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.
 *
*/

var sys = require('sys');

var fleegix = require('geddy-core/lib/fleegix');

var Config = function (dirname) {

  this.environment = 'development';
  this.port = 8000;
  this.dirname = dirname;
  this.staticFilePath = dirname + '/public';
  this.plugins = {};

  this.sessions = {
    store: 'memory',
    key: 'sid',
    expiry: 14 * 24 * 60 * 60
  };
  /*
  this.database = {
    adapter: 'couchdb'
    dbHostname: 'localhost',
    dbName: 'geddy_db',
    dbPort: 5984
  };

  this.sessions = {
    store: 'couchdb',
    key: 'sid',
    expiry: 14 * 24 * 60 * 60,
    dbHostname: 'localhost',
    dbName: 'geddy_sessions',
    dbPort: 5984
  };

  this.plugins = {
    'Auth': {
      // Pluggable auth types to check, in order
      authTypes: ['Cookie', 'Basic'],
      // The key to look for in the session to indicate logged-in status
      authedSessionKey: 'login',
      // The page to redirect to when hitting an auth-required HTML page
      htmlRedirect: '/login'
    }
  };
  */

  // Override with app-level opts
  var opts = require(dirname + '/config/config');
  fleegix.mixin(this, opts, true);
};

exports.Config = Config;
<|endoftext|>


<commit_before>'use strict';
var nodemailer = require('nodemailer');

module.exports = function(robot) {

	robot.hear(/send mail/i, function(res){
		// Generate test SMTP service account from ethereal.email
		// Only needed if you don't have a real mail account for testing
		nodemailer.createTestAccount(function (err, account) {

			// create reusable transporter object using the default SMTP transport
			var transporter = nodemailer.createTransport({
				host: 'smtp.ethereal.email',
				port: 587,
				secure: false, // true for 465, false for other ports
				auth: {
					user: 'muratz', // generated ethereal user
					pass: 'pass' // generated ethereal password
				}
			});

			// setup email data with unicode symbols
			var mailOptions = {
				from: '"Fred Foo 👻" <foo@blurdybloop.com>', // sender address
				to: 'bar@blurdybloop.com, baz@blurdybloop.com', // list of receivers
				subject: 'Hello ✔', // Subject line
				text: 'Hello world?', // plain text body
				html: '<b>Hello world?</b>' // html body
			};

			// send mail with defined transport object
			transporter.sendMail(mailOptions, function (error, info) {
				if (error) {
					return res.reply('error');
					//return console.log(error);
				}
				res.reply('Message sent: %s', info.messageId);
				//console.log('Message sent: %s', info.messageId);

				// Preview only available when sending through an Ethereal account
				res.reply('Preview URL: %s', nodemailer.getTestMessageUrl(info));
				//console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));

				// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@blurdybloop.com>
				// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
			});
		});

		res.send("Islem Tamam");
	});
}<commit_msg>deneme<commit_after>'use strict';
var nodemailer = require('nodemailer');

module.exports = function(robot) {

	robot.hear(/send mail/i, function(res){
		res.send("world");
	});
}<|endoftext|>


<commit_before>"use strict";
const scrapeIt = require("scrape-it");
const unzip = require("unzipper");
const rimraf = require("rimraf");
const url = require("url");

scrapeIt("https://developers.eveonline.com/resource/resources", {
    sde_link: { selector: ".content > h3:nth-child(4) + ul li:last-child a", attr: "href" },
    versioned_filename: { selector: ".content > h3:nth-child(6) + ul li:last-child a", attr: "href" }
}).then(scrape => {
    const link = scrape.sde_link;
    const versionedFilename = scrape.versioned_filename;
    if (typeof link !== "string" || typeof versionedFilename !== "string") throw new Error("Couldn't scrape SDE link!");
    const captures = versionedFilename.match(/YC-(\d+)-(\d+)_(\d+)\.(\d+)/);
    const year = captures[1],
        month = captures[2],
        major = captures[3],
        minor = captures[4];
    const version = `${year}.${month}.${major}-${minor}`;
    const current = require("../package.json").version;
    if (version === current) return console.log(`Already at version ${version}, not redownloading SDE.`);

    const https = require("https");
    const fs = require("fs");

    console.log(`Removing existing sde.zip, if it exists...`);
    try { fs.unlinkSync("sde.zip"); } catch(e) {} // Attempt to remove existing sde zip
    const file = fs.createWriteStream("sde.zip");

    console.log(`Downloading ${link} as sde.zip...`);
    const request = https.get(link, response => {
        let size = 0;
        const responseSize = response.headers["content-length"];
        console.log(`Response size is ${responseSize} bytes.`);
        response.on("data", buf => {
            size += buf.length;
            process.stdout.clearLine();
            process.stdout.cursorTo(0);
            process.stdout.write(`Downloaded ${size}/${responseSize} bytes (${(size/responseSize * 100).toFixed(2)}%)...`);
        });
        response.pipe(file);
    });
    file.on("finish", () => {
        console.log();
        console.log(`Done downloading!`);

        console.log(`Removing existing "sde" folder.`);
        rimraf.sync("sde");
        console.log(`Extracting downloaded zip...`);
        const dest = unzip.Extract({ path: "." });
        fs.createReadStream("sde.zip").pipe(dest);
        dest.on("close", () => {
            console.log(`Extraction complete!`);
            console.log(`Updating package.json...`);
            const package = require("../package.json");
            package.version = version;
            fs.writeFileSync(require("path").join(__dirname, "../package.json"), JSON.stringify(package, null, 2));
            console.log(`Done! SDE Upgrade complete!`);
        });
    });
}).catch(err => console.error(err));<commit_msg>Fix strict mode bug in script<commit_after>"use strict";
const scrapeIt = require("scrape-it");
const unzip = require("unzipper");
const rimraf = require("rimraf");
const url = require("url");

scrapeIt("https://developers.eveonline.com/resource/resources", {
    sde_link: { selector: ".content > h3:nth-child(4) + ul li:last-child a", attr: "href" },
    versioned_filename: { selector: ".content > h3:nth-child(6) + ul li:last-child a", attr: "href" }
}).then(scrape => {
    const link = scrape.sde_link;
    const versionedFilename = scrape.versioned_filename;
    if (typeof link !== "string" || typeof versionedFilename !== "string") throw new Error("Couldn't scrape SDE link!");
    const captures = versionedFilename.match(/YC-(\d+)-(\d+)_(\d+)\.(\d+)/);
    const year = captures[1],
        month = captures[2],
        major = captures[3],
        minor = captures[4];
    const version = `${year}.${month}.${major}-${minor}`;
    const current = require("../package.json").version;
    if (version === current) return console.log(`Already at version ${version}, not redownloading SDE.`);

    const https = require("https");
    const fs = require("fs");

    console.log(`Removing existing sde.zip, if it exists...`);
    try { fs.unlinkSync("sde.zip"); } catch(e) {} // Attempt to remove existing sde zip
    const file = fs.createWriteStream("sde.zip");

    console.log(`Downloading ${link} as sde.zip...`);
    const request = https.get(link, response => {
        let size = 0;
        const responseSize = response.headers["content-length"];
        console.log(`Response size is ${responseSize} bytes.`);
        response.on("data", buf => {
            size += buf.length;
            process.stdout.clearLine();
            process.stdout.cursorTo(0);
            process.stdout.write(`Downloaded ${size}/${responseSize} bytes (${(size/responseSize * 100).toFixed(2)}%)...`);
        });
        response.pipe(file);
    });
    file.on("finish", () => {
        console.log();
        console.log(`Done downloading!`);

        console.log(`Removing existing "sde" folder.`);
        rimraf.sync("sde");
        console.log(`Extracting downloaded zip...`);
        const dest = unzip.Extract({ path: "." });
        fs.createReadStream("sde.zip").pipe(dest);
        dest.on("close", () => {
            console.log(`Extraction complete!`);
            console.log(`Updating package.json...`);
            const p = require("../package.json");
            p.version = version;
            fs.writeFileSync(require("path").join(__dirname, "../package.json"), JSON.stringify(p, null, 2));
            console.log(`Done! SDE Upgrade complete!`);
        });
    });
}).catch(err => console.error(err));<|endoftext|>


<commit_before>/*global $:true, _:true, T4:true */
(function() {
  function testView(options) {
    var setup = {
      dimensions: options.dimensions,
      winLength: options.winLength
    };
    var model = new T4.Model(setup);
    var canvas = $('<canvas id="canvas1" width="300" height="300"></canvas>');
    $('body').append(canvas);
    var view = new T4.View(model, canvas);
    model.restart();
    _.each(options.moves.split(' '), function(move) {
      var x = parseInt(move[0], 10);
      var y = parseInt(move[1], 10);
      model.take(model.getSquare([x, y]));
    });
    view.update();
  }

  function onReady() {
    testView({
      dimensions: [6, 6],
      winLength: 4,
      moves: '00 11 01 22 10 33 02 44'
    });
  }
  $(document).ready(onReady);
}());<commit_msg>use strict in view<commit_after>/*global $:true, _:true, T4:true */
(function() {
  "use strict";

  function testView(options) {
    var setup = {
      dimensions: options.dimensions,
      winLength: options.winLength
    };
    var model = new T4.Model(setup);
    var canvas = $('<canvas id="canvas1" width="300" height="300"></canvas>');
    $('body').append(canvas);
    var view = new T4.View(model, canvas);
    model.restart();
    _.each(options.moves.split(' '), function(move) {
      var x = parseInt(move[0], 10);
      var y = parseInt(move[1], 10);
      model.take(model.getSquare([x, y]));
    });
    view.update();
  }

  function onReady() {
    testView({
      dimensions: [6, 6],
      winLength: 4,
      moves: '00 11 01 22 10 33 02 44'
    });
  }
  $(document).ready(onReady);
}());<|endoftext|>


<commit_before>#!/usr/bin/env node

var util = require('util'),
    http = require('http'),
    fs = require('fs'),
    url = require('url'),
    events = require('events');

var DEFAULT_PORT = 8000;

function main(argv) {
  new HttpServer({
    'GET': createServlet(StaticServlet),
    'HEAD': createServlet(StaticServlet)
  }).start(Number(argv[2]) || DEFAULT_PORT);
}

function escapeHtml(value) {
  return value.toString().
    replace('<', '<').
    replace('>', '>').
    replace('"', '"');
}

function createServlet(Class) {
  var servlet = new Class();
  return servlet.handleRequest.bind(servlet);
}

/**
 * An Http server implementation that uses a map of methods to decide
 * action routing.
 *
 * @param {Object} Map of method => Handler function
 */
function HttpServer(handlers) {
  this.handlers = handlers;
  this.server = http.createServer(this.handleRequest_.bind(this));
}

HttpServer.prototype.start = function(port) {
  this.port = port;
  this.server.listen(port);
  util.puts('Http Server running at http://localhost:' + port + '/');
};

HttpServer.prototype.parseUrl_ = function(urlString) {
  var parsed = url.parse(urlString);
  parsed.pathname = url.resolve('/', parsed.pathname);
  return url.parse(url.format(parsed), true);
};

HttpServer.prototype.handleRequest_ = function(req, res) {
  var logEntry = req.method + ' ' + req.url;
  if (req.headers['user-agent']) {
    logEntry += ' ' + req.headers['user-agent'];
  }
  util.puts(logEntry);
  req.url = this.parseUrl_(req.url);
  var handler = this.handlers[req.method];
  if (!handler) {
    res.writeHead(501);
    res.end();
  } else {
    handler.call(this, req, res);
  }
};

/**
 * Handles static content.
 */
function StaticServlet() {}

StaticServlet.MimeMap = {
  'txt': 'text/plain',
  'html': 'text/html',
  'css': 'text/css',
  'xml': 'application/xml',
  'json': 'application/json',
  'js': 'application/javascript',
  'jpg': 'image/jpeg',
  'jpeg': 'image/jpeg',
  'gif': 'image/gif',
  'png': 'image/png',
  'svg': 'image/svg+xml'
};

StaticServlet.prototype.handleRequest = function(req, res) {
  var self = this;
  var path = ('./' + req.url.pathname).replace('//','/').replace(/%(..)/g, function(match, hex){
    return String.fromCharCode(parseInt(hex, 16));
  });
  var parts = path.split('/');
  if (parts[parts.length-1].charAt(0) === '.')
    return self.sendForbidden_(req, res, path);
  fs.stat(path, function(err, stat) {
    if (err)
      return self.sendMissing_(req, res, path);
    if (stat.isDirectory())
      return self.sendDirectory_(req, res, path);
    return self.sendFile_(req, res, path);
  });
}

StaticServlet.prototype.sendError_ = function(req, res, error) {
  res.writeHead(500, {
      'Content-Type': 'text/html'
  });
  res.write('<!doctype html>\n');
  res.write('<title>Internal Server Error</title>\n');
  res.write('
Internal Server Error
');
  res.write('
' + escapeHtml(util.inspect(error)) + '
');
  util.puts('500 Internal Server Error');
  util.puts(util.inspect(error));
};

StaticServlet.prototype.sendMissing_ = function(req, res, path) {
  path = path.substring(1);
  res.writeHead(404, {
      'Content-Type': 'text/html'
  });
  res.write('<!doctype html>\n');
  res.write('<title>404 Not Found</title>\n');
  res.write('
Not Found
');
  res.write(
    '
The requested URL ' +
    escapeHtml(path) +
    ' was not found on this server.
'
  );
  res.end();
  util.puts('404 Not Found: ' + path);
};

StaticServlet.prototype.sendForbidden_ = function(req, res, path) {
  path = path.substring(1);
  res.writeHead(403, {
      'Content-Type': 'text/html'
  });
  res.write('<!doctype html>\n');
  res.write('<title>403 Forbidden</title>\n');
  res.write('
Forbidden
');
  res.write(
    '
You do not have permission to access ' +
    escapeHtml(path) + ' on this server.
'
  );
  res.end();
  util.puts('403 Forbidden: ' + path);
};

StaticServlet.prototype.sendRedirect_ = function(req, res, redirectUrl) {
  res.writeHead(301, {
      'Content-Type': 'text/html',
      'Location': redirectUrl
  });
  res.write('<!doctype html>\n');
  res.write('<title>301 Moved Permanently</title>\n');
  res.write('
Moved Permanently
');
  res.write(
    '
The document has moved here.
'
  );
  res.end();
  util.puts('301 Moved Permanently: ' + redirectUrl);
};

StaticServlet.prototype.sendFile_ = function(req, res, path) {
  var self = this;
  var file = fs.createReadStream(path);
  res.writeHead(200, {
    'Content-Type': StaticServlet.
      MimeMap[path.split('.').pop()] || 'text/plain'
  });
  if (req.method === 'HEAD') {
    res.end();
  } else {
    file.on('data', res.write.bind(res));
    file.on('close', function() {
      res.end();
    });
    file.on('error', function(error) {
      self.sendError_(req, res, error);
    });
  }
};

StaticServlet.prototype.sendDirectory_ = function(req, res, path) {
  var self = this;
  if (path.match(/[^\/]$/)) {
    req.url.pathname += '/';
    var redirectUrl = url.format(url.parse(url.format(req.url)));
    return self.sendRedirect_(req, res, redirectUrl);
  }
  fs.readdir(path, function(err, files) {
    if (err)
      return self.sendError_(req, res, error);

    if (!files.length)
      return self.writeDirectoryIndex_(req, res, path, []);

    var remaining = files.length;
    files.forEach(function(fileName, index) {
      fs.stat(path + '/' + fileName, function(err, stat) {
        if (err)
          return self.sendError_(req, res, err);
        if (stat.isDirectory()) {
          files[index] = fileName + '/';
        }
        if (!(--remaining))
          return self.writeDirectoryIndex_(req, res, path, files);
      });
    });
  });
};

StaticServlet.prototype.writeDirectoryIndex_ = function(req, res, path, files) {
  path = path.substring(1);
  res.writeHead(200, {
    'Content-Type': 'text/html'
  });
  if (req.method === 'HEAD') {
    res.end();
    return;
  }
  res.write('<!doctype html>\n');
  res.write('<title>' + escapeHtml(path) + '</title>\n');
  res.write('\n');
  res.write('
Directory: ' + escapeHtml(path) + '
');
  res.write('
');
  files.forEach(function(fileName) {
    if (fileName.charAt(0) !== '.') {
      res.write('
' +
        escapeHtml(fileName) + '
');
    }
  });
  res.write('
');
  res.end();
};

// Must be last,
main(process.argv);
<commit_msg>style(web-server): remove a special character<commit_after>#!/usr/bin/env node

var util = require('util'),
    http = require('http'),
    fs = require('fs'),
    url = require('url'),
    events = require('events');

var DEFAULT_PORT = 8000;

function main(argv) {
  new HttpServer({
    'GET': createServlet(StaticServlet),
    'HEAD': createServlet(StaticServlet)
  }).start(Number(argv[2]) || DEFAULT_PORT);
}

function escapeHtml(value) {
  return value.toString().
    replace('<', '<').
    replace('>', '>').
    replace('"', '"');
}

function createServlet(Class) {
  var servlet = new Class();
  return servlet.handleRequest.bind(servlet);
}

/**
 * An Http server implementation that uses a map of methods to decide
 * action routing.
 *
 * @param {Object} Map of method => Handler function
 */
function HttpServer(handlers) {
  this.handlers = handlers;
  this.server = http.createServer(this.handleRequest_.bind(this));
}

HttpServer.prototype.start = function(port) {
  this.port = port;
  this.server.listen(port);
  util.puts('Http Server running at http://localhost:' + port + '/');
};

HttpServer.prototype.parseUrl_ = function(urlString) {
  var parsed = url.parse(urlString);
  parsed.pathname = url.resolve('/', parsed.pathname);
  return url.parse(url.format(parsed), true);
};

HttpServer.prototype.handleRequest_ = function(req, res) {
  var logEntry = req.method + ' ' + req.url;
  if (req.headers['user-agent']) {
    logEntry += ' ' + req.headers['user-agent'];
  }
  util.puts(logEntry);
  req.url = this.parseUrl_(req.url);
  var handler = this.handlers[req.method];
  if (!handler) {
    res.writeHead(501);
    res.end();
  } else {
    handler.call(this, req, res);
  }
};

/**
 * Handles static content.
 */
function StaticServlet() {}

StaticServlet.MimeMap = {
  'txt': 'text/plain',
  'html': 'text/html',
  'css': 'text/css',
  'xml': 'application/xml',
  'json': 'application/json',
  'js': 'application/javascript',
  'jpg': 'image/jpeg',
  'jpeg': 'image/jpeg',
  'gif': 'image/gif',
  'png': 'image/png',
  'svg': 'image/svg+xml'
};

StaticServlet.prototype.handleRequest = function(req, res) {
  var self = this;
  var path = ('./' + req.url.pathname).replace('//','/').replace(/%(..)/g, function(match, hex){
    return String.fromCharCode(parseInt(hex, 16));
  });
  var parts = path.split('/');
  if (parts[parts.length-1].charAt(0) === '.')
    return self.sendForbidden_(req, res, path);
  fs.stat(path, function(err, stat) {
    if (err)
      return self.sendMissing_(req, res, path);
    if (stat.isDirectory())
      return self.sendDirectory_(req, res, path);
    return self.sendFile_(req, res, path);
  });
}

StaticServlet.prototype.sendError_ = function(req, res, error) {
  res.writeHead(500, {
      'Content-Type': 'text/html'
  });
  res.write('<!doctype html>\n');
  res.write('<title>Internal Server Error</title>\n');
  res.write('
Internal Server Error
');
  res.write('
' + escapeHtml(util.inspect(error)) + '
');
  util.puts('500 Internal Server Error');
  util.puts(util.inspect(error));
};

StaticServlet.prototype.sendMissing_ = function(req, res, path) {
  path = path.substring(1);
  res.writeHead(404, {
      'Content-Type': 'text/html'
  });
  res.write('<!doctype html>\n');
  res.write('<title>404 Not Found</title>\n');
  res.write('
Not Found
');
  res.write(
    '
The requested URL ' +
    escapeHtml(path) +
    ' was not found on this server.
'
  );
  res.end();
  util.puts('404 Not Found: ' + path);
};

StaticServlet.prototype.sendForbidden_ = function(req, res, path) {
  path = path.substring(1);
  res.writeHead(403, {
      'Content-Type': 'text/html'
  });
  res.write('<!doctype html>\n');
  res.write('<title>403 Forbidden</title>\n');
  res.write('
Forbidden
');
  res.write(
    '
You do not have permission to access ' +
    escapeHtml(path) + ' on this server.
'
  );
  res.end();
  util.puts('403 Forbidden: ' + path);
};

StaticServlet.prototype.sendRedirect_ = function(req, res, redirectUrl) {
  res.writeHead(301, {
      'Content-Type': 'text/html',
      'Location': redirectUrl
  });
  res.write('<!doctype html>\n');
  res.write('<title>301 Moved Permanently</title>\n');
  res.write('
Moved Permanently
');
  res.write(
    '
The document has moved here.
'
  );
  res.end();
  util.puts('301 Moved Permanently: ' + redirectUrl);
};

StaticServlet.prototype.sendFile_ = function(req, res, path) {
  var self = this;
  var file = fs.createReadStream(path);
  res.writeHead(200, {
    'Content-Type': StaticServlet.
      MimeMap[path.split('.').pop()] || 'text/plain'
  });
  if (req.method === 'HEAD') {
    res.end();
  } else {
    file.on('data', res.write.bind(res));
    file.on('close', function() {
      res.end();
    });
    file.on('error', function(error) {
      self.sendError_(req, res, error);
    });
  }
};

StaticServlet.prototype.sendDirectory_ = function(req, res, path) {
  var self = this;
  if (path.match(/[^\/]$/)) {
    req.url.pathname += '/';
    var redirectUrl = url.format(url.parse(url.format(req.url)));
    return self.sendRedirect_(req, res, redirectUrl);
  }
  fs.readdir(path, function(err, files) {
    if (err)
      return self.sendError_(req, res, error);

    if (!files.length)
      return self.writeDirectoryIndex_(req, res, path, []);

    var remaining = files.length;
    files.forEach(function(fileName, index) {
      fs.stat(path + '/' + fileName, function(err, stat) {
        if (err)
          return self.sendError_(req, res, err);
        if (stat.isDirectory()) {
          files[index] = fileName + '/';
        }
        if (!(--remaining))
          return self.writeDirectoryIndex_(req, res, path, files);
      });
    });
  });
};

StaticServlet.prototype.writeDirectoryIndex_ = function(req, res, path, files) {
  path = path.substring(1);
  res.writeHead(200, {
    'Content-Type': 'text/html'
  });
  if (req.method === 'HEAD') {
    res.end();
    return;
  }
  res.write('<!doctype html>\n');
  res.write('<title>' + escapeHtml(path) + '</title>\n');
  res.write('\n');
  res.write('
Directory: ' + escapeHtml(path) + '
');
  res.write('
');
  files.forEach(function(fileName) {
    if (fileName.charAt(0) !== '.') {
      res.write('
' +
        escapeHtml(fileName) + '
');
    }
  });
  res.write('
');
  res.end();
};

// Must be last,
main(process.argv);
<|endoftext|>


<commit_before>import Handler from 'routes/route-handler';
import { getRouteMap, mapRoutes, resetRouteMap, setNotFound } from 'routes/route-map';
import History from './routes/history';
import { addAfterEach, addBeforeEach, resetHooks } from './routes/global-hooks';
import pjax from './routes/pjax';
import { $ready } from 'core/dom';
import { $copy, $extend, $isArray } from 'core/types';
import { uri } from 'wee-location';

const defaults = {
	scrollBehavior(to, from, savedPosition) {
		if (savedPosition) {
			return savedPosition;
		} else {
			return { x: 0, y: 0 };
		}
	},
	transition: null,
	onError: []
};
let settings = $copy(defaults);
let hasPjax = false;

export let history = new History(settings);

/**
 * Set base configurations for router
 *
 * @param {Object} config
 * @returns {router}
 */
function router(config = {}) {
	$extend(settings, config);

	// Update scrollBehavior property in case that was changed
	history.scrollBehavior = settings.scrollBehavior;
	history.transition = settings.transition;

	return router;
}

router.settings = settings;

/**
 * Register global after hook
 *
 * @param {Function} fn
 * @returns {router}
 */
router.afterEach = function registerAfterEach(fn) {
	addAfterEach(fn);

	return this;
}

/**
 * Register global before hook
 *
 * @param {Function} fn
 * @returns {router}
 */
router.beforeEach = function registerBeforeEach(fn) {
	addBeforeEach(fn);

	return this;
};

/**
 * Retrieve current route
 *
 * @returns {Object}
 */
router.currentRoute = function currentRoute() {
	return history.current;
}

/**
 * Register routes
 *
 * @param {Array} routes
 * @returns {router}
 */
router.map = function routerMap(routes) {
	mapRoutes(routes);

	return this;
}

/**
 * Set the catch all route that is matched if no other routes match
 *
 * @param {Object} route
 * @returns {router}
 */
router.notFound = function notFound(route) {
	route.path = '*';
	route.name = 'notFound';

	setNotFound(route);

	return this;
}

/**
 * Configure and initialize pjax navigation
 *
 * @param {Object} config
 * @returns {router}
 */
router.pjax = function initPjax(config = {}) {
	// Prevent initializing pjax multiple times
	if (! hasPjax) {
		hasPjax = pjax.init(config);

		if (hasPjax) {
			// Prep pjax after initialization of routes
			this.onReady(() => {
				pjax.onTrigger = function onPjaxTrigger(destination) {
					history.push(destination)
						.catch(error => {
							settings.onError.forEach(callback => callback(error));
						});
				};

				history.begin = pjax.go;
				history.replacePage = pjax.replace;
			});
		}
	}

	return this;
}

/**
 * Register onError method
 *
 * @param {Function|Array} error
 */
router.onError = function onError(error) {
	if ($isArray(error)) {
		settings.onError = settings.onError.concat(error);
	} else {
		settings.onError.push(error);
	}

	return this;
}

/**
 * Register callbacks to be executed on ready
 *
 * @param {Function} success
 */
router.onReady = function onReady(success) {
	history.onReady(success);

	return this;
}

/**
 * Navigate to URL and add item to history
 *
 * @param {string|Object} path
 * @param {boolean|Object} modifyPjax
 */
router.push = function push(path, modifyPjax = false) {
	if (modifyPjax === true) {
		pjax.pause();
	} else if ($isArray(modifyPjax)) {
		pjax.override(modifyPjax);
	}

	return history.push(path)
		.then(pjax.resume, pjax.resume);
}

/**
 * Navigate to URL and replace item in history
 *
 * @param {string|Object} path
 * @param {boolean|Ojbect} modifyPjax
 */
router.replace = function replace(path, modifyPjax = false) {
	if (modifyPjax === true) {
		pjax.pause();
	} else if ($isArray(modifyPjax)) {
		pjax.override(modifyPjax);
	}

	return history.replace(path)
		.then(pjax.resume, pjax.resume);
}

/**
 * Reset all routes - mainly for testing purposes
 */
router.reset = function reset() {
	resetRouteMap();
	resetHooks();
	hasPjax = false;
	pjax.reset();
	window.removeEventListener('popstate', history.popstate);
	history = new History(settings.scrollBehavior);
	settings = $copy(defaults);
}

/**
 * Retrieve all routes or specific route by name/path
 *
 * @param {string} [value]
 * @param {string} keyType
 * @returns {Object|Array}
 */
router.routes = function routes(key, keyType = 'path') {
	let routeMaps = getRouteMap();
	let map;

	if (key) {
		if (routeMaps.pathMap.hasOwnProperty(key)) {
			return routeMaps.pathMap[key];
		} else if (routeMaps.nameMap.hasOwnProperty(key)) {
			return routeMaps.nameMap[key];
		} else {
			return null;
		}
	}

	if (keyType === 'path') {
		map = routeMaps.pathMap;
	} else if (keyType === 'name') {
		map = routeMaps.nameMap;
	} else if (keyType === 'list') {
		map = routeMaps.pathList;
	}

	return map;
}

/**
 * Evaluate mapped routes against current or provided URL
 *
 * @returns {router}
 */
router.run = function runRoutes() {
	// Process routes when document is loaded
	$ready(() => {
		history.navigate(uri().fullPath)
			.catch(error => {
				settings.onError.forEach(callback => callback(error));
			});
	});

	return this;

	// TODO: This is going to set the state of the current route in history
	// TODO: I don't think that will be desirable
	// TODO: Do we need a way to evaluate routes without changing history.current?
	// const { pathMap, nameMap } = getRouteMap();
	//
	// if (pathMap[value]) {
	// 	history.navigate(value);
	// } else if (nameMap[value]) {
	// 	history.navigate(value);
	// }
}

export default router;
export const RouteHandler = Handler;<commit_msg>Return promise from router.run/evaluate only current path<commit_after>import Handler from 'routes/route-handler';
import { getRouteMap, mapRoutes, resetRouteMap, setNotFound } from 'routes/route-map';
import History from './routes/history';
import { addAfterEach, addBeforeEach, resetHooks } from './routes/global-hooks';
import pjax from './routes/pjax';
import { $ready } from 'core/dom';
import { $copy, $extend, $isArray } from 'core/types';
import { uri } from 'wee-location';

const defaults = {
	scrollBehavior(to, from, savedPosition) {
		if (savedPosition) {
			return savedPosition;
		} else {
			return { x: 0, y: 0 };
		}
	},
	transition: null,
	onError: []
};
let settings = $copy(defaults);
let hasPjax = false;

export let history = new History(settings);

/**
 * Set base configurations for router
 *
 * @param {Object} config
 * @returns {router}
 */
function router(config = {}) {
	$extend(settings, config);

	// Update scrollBehavior property in case that was changed
	history.scrollBehavior = settings.scrollBehavior;
	history.transition = settings.transition;

	return router;
}

router.settings = settings;

/**
 * Register global after hook
 *
 * @param {Function} fn
 * @returns {router}
 */
router.afterEach = function registerAfterEach(fn) {
	addAfterEach(fn);

	return this;
}

/**
 * Register global before hook
 *
 * @param {Function} fn
 * @returns {router}
 */
router.beforeEach = function registerBeforeEach(fn) {
	addBeforeEach(fn);

	return this;
};

/**
 * Retrieve current route
 *
 * @returns {Object}
 */
router.currentRoute = function currentRoute() {
	return history.current;
}

/**
 * Register routes
 *
 * @param {Array} routes
 * @returns {router}
 */
router.map = function routerMap(routes) {
	mapRoutes(routes);

	return this;
}

/**
 * Set the catch all route that is matched if no other routes match
 *
 * @param {Object} route
 * @returns {router}
 */
router.notFound = function notFound(route) {
	route.path = '*';
	route.name = 'notFound';

	setNotFound(route);

	return this;
}

/**
 * Configure and initialize pjax navigation
 *
 * @param {Object} config
 * @returns {router}
 */
router.pjax = function initPjax(config = {}) {
	// Prevent initializing pjax multiple times
	if (! hasPjax) {
		hasPjax = pjax.init(config);

		if (hasPjax) {
			// Prep pjax after initialization of routes
			this.onReady(() => {
				pjax.onTrigger = function onPjaxTrigger(destination) {
					history.push(destination)
						.catch(error => {
							settings.onError.forEach(callback => callback(error));
						});
				};

				history.begin = pjax.go;
				history.replacePage = pjax.replace;
			});
		}
	}

	return this;
}

/**
 * Register onError method
 *
 * @param {Function|Array} error
 */
router.onError = function onError(error) {
	if ($isArray(error)) {
		settings.onError = settings.onError.concat(error);
	} else {
		settings.onError.push(error);
	}

	return this;
}

/**
 * Register callbacks to be executed on ready
 *
 * @param {Function} success
 */
router.onReady = function onReady(success) {
	history.onReady(success);

	return this;
}

/**
 * Navigate to URL and add item to history
 *
 * @param {string|Object} path
 * @param {boolean|Object} modifyPjax
 */
router.push = function push(path, modifyPjax = false) {
	if (modifyPjax === true) {
		pjax.pause();
	} else if ($isArray(modifyPjax)) {
		pjax.override(modifyPjax);
	}

	return history.push(path)
		.then(pjax.resume, pjax.resume);
}

/**
 * Navigate to URL and replace item in history
 *
 * @param {string|Object} path
 * @param {boolean|Ojbect} modifyPjax
 */
router.replace = function replace(path, modifyPjax = false) {
	if (modifyPjax === true) {
		pjax.pause();
	} else if ($isArray(modifyPjax)) {
		pjax.override(modifyPjax);
	}

	return history.replace(path)
		.then(pjax.resume, pjax.resume);
}

/**
 * Reset all routes - mainly for testing purposes
 */
router.reset = function reset() {
	resetRouteMap();
	resetHooks();
	hasPjax = false;
	pjax.reset();
	window.removeEventListener('popstate', history.popstate);
	history = new History(settings.scrollBehavior);
	settings = $copy(defaults);
}

/**
 * Retrieve all routes or specific route by name/path
 *
 * @param {string} [value]
 * @param {string} keyType
 * @returns {Object|Array}
 */
router.routes = function routes(key, keyType = 'path') {
	let routeMaps = getRouteMap();
	let map;

	if (key) {
		if (routeMaps.pathMap.hasOwnProperty(key)) {
			return routeMaps.pathMap[key];
		} else if (routeMaps.nameMap.hasOwnProperty(key)) {
			return routeMaps.nameMap[key];
		} else {
			return null;
		}
	}

	if (keyType === 'path') {
		map = routeMaps.pathMap;
	} else if (keyType === 'name') {
		map = routeMaps.nameMap;
	} else if (keyType === 'list') {
		map = routeMaps.pathList;
	}

	return map;
}

/**
 * Evaluate mapped routes against current or provided URL
 *
 * @returns {router}
 */
router.run = function runRoutes() {
	return history.navigate(uri().fullPath);
}

export default router;
export const RouteHandler = Handler;<|endoftext|>


<commit_before>var Baby = require('babyparse'),
    fs = require('fs'),
    request = require('request'),
    mongo = require('./mongo');

var getMoneyflows = function(buy) {
    return new Promise((resolve, reject) => {
        var url;
        if (buy) {
            url = 'http://www.wsj.com/mdc/public/npage/2_3045-mfgppl-mfxml2csv.html';
        } else {
            url = 'http://www.wsj.com/mdc/public/npage/2_3045-mflppg-mfxml2csv.html';
        }
        request.get(url, function (error, res, body) {
            if (!error && res.statusCode == 200) {
                var csv = body;
                var parsed = Baby.parse(csv, {
                    skipEmptyLines: true,
                    delimiter: '\t'
                });
                resolve(parsed.data);
            } else {
                reject(error);
            }
        });
    })
};

var parseMoneyflows = function(data, flow) {
    var parsed = [],
        index = 3;
    while (data[index] != null) {
        var obj = {
            company:                data[index][0],
            name:                   data[index][0].substring(0, data[index][0].lastIndexOf('(') - 1),
            symbol:                 data[index][0].substring(data[index][0].lastIndexOf('(') + 1, data[index][0].lastIndexOf(')')),
            price:                  data[index][1],
            change:                 data[index][2],
            percent_change:         data[index][3],
            one_week_change:        data[index][4],
            total_money_flow:       data[index][5],
            total_tick_up:          data[index][6],
            total_tick_down:        data[index][7],
            total_up_down_ratio:    data[index][8],
            block_money_flow:       data[index][9],
            block_tick_up:          data[index][10],
            block_tick_down:        data[index][11],
            block_up_down_ratio:    data[index][9],
            timestamp:              data[0][0].substring(data[0][0].indexOf(',') + 3, data[0][0].length),
            flow:                   flow
        };
        parsed.push(obj);
        index++;
    }
    mongo.upsertMoneyflows(parsed);
    return parsed;
};

var getBuyStocks = function() {
    return new Promise((resolve, reject) => {
        getMoneyflows(true).then((data) => {
            if (!data) {
                reject('error');
            } else {
                resolve(parseMoneyflows(data, 'buy'));
            }
        })
    });
};

var getSellStocks = function() {
    return new Promise((resolve, reject) => {
        getMoneyflows(false).then((data) => {
            if (!data) {
                reject('error');
            } else {
                resolve(parseMoneyflows(data, 'sell'));
            }
        })
    });
};

module.exports = {
    getMoneyflows: getMoneyflows,
    getBuyStocks: getBuyStocks,
    getSellStocks: getSellStocks
};
<commit_msg>Changed strings to floats<commit_after>var Baby = require('babyparse'),
    fs = require('fs'),
    request = require('request'),
    mongo = require('./mongo');

var getMoneyflows = function(buy) {
    return new Promise((resolve, reject) => {
        var url;
        if (buy) {
            url = 'http://www.wsj.com/mdc/public/npage/2_3045-mfgppl-mfxml2csv.html';
        } else {
            url = 'http://www.wsj.com/mdc/public/npage/2_3045-mflppg-mfxml2csv.html';
        }
        request.get(url, function (error, res, body) {
            if (!error && res.statusCode == 200) {
                var csv = body;
                var parsed = Baby.parse(csv, {
                    skipEmptyLines: true,
                    delimiter: '\t'
                });
                resolve(parsed.data);
            } else {
                reject(error);
            }
        });
    })
};

var parseMoneyflows = function(data, flow) {
    var parsed = [],
        index = 3;
    while (data[index] != null) {
        var obj = {
            company:                    data[index][0],
            name:                       data[index][0].substring(0, data[index][0].lastIndexOf('(') - 1),
            symbol:                     data[index][0].substring(data[index][0].lastIndexOf('(') + 1, data[index][0].lastIndexOf(')')),
            price:                      parseFloat(data[index][1], 2),
            change:                     parseFloat(data[index][2], 2),
            percent_change:             parseFloat(data[index][3], 2),
            one_week_percent_change:    parseFloat(data[index][4], 2),
            total_money_flow:           parseFloat(data[index][5], 2),
            total_tick_up:              parseFloat(data[index][6], 2),
            total_tick_down:            parseFloat(data[index][7], 2),
            total_up_down_ratio:        parseFloat(data[index][8], 2),
            block_trades_money_flow:    parseFloat(data[index][9], 2),
            block_trades_tick_up:       parseFloat(data[index][10], 2),
            block_trades_tick_down:     parseFloat(data[index][11], 2),
            block_trades_up_down_ratio: parseFloat(data[index][12], 2),
            timestamp:                  data[0][0].substring(data[0][0].indexOf(',') + 3, data[0][0].length),
            flow:                       flow
        };
        parsed.push(obj);
        index++;
    }
    mongo.upsertMoneyflows(parsed);
    return parsed;
};

var getBuyStocks = function() {
    return new Promise((resolve, reject) => {
        getMoneyflows(true).then((data) => {
            if (!data) {
                reject('error');
            } else {
                resolve(parseMoneyflows(data, 'buy'));
            }
        })
    });
};

var getSellStocks = function() {
    return new Promise((resolve, reject) => {
        getMoneyflows(false).then((data) => {
            if (!data) {
                reject('error');
            } else {
                resolve(parseMoneyflows(data, 'sell'));
            }
        })
    });
};

module.exports = {
    getMoneyflows: getMoneyflows,
    getBuyStocks: getBuyStocks,
    getSellStocks: getSellStocks
};
<|endoftext|>


<commit_before>/*global text,expect,ok,module,notEqual,Butter,test,window*/
(function (window, document, undefined, Butter) {

  module("Media", {
    setup: function () {
    },
    teardown: function () {
    }
  });

  test( "No media check", function () {
    expect(1);
    try {
      butter.addTrack();
      ok( false, "Media error not received" );
    }
    catch (e) {
      ok( true, "No media error received" );
    } //try
  });

  test( "Create Media object", function () {
    expect(2);
    var m1 = new Butter.Media( { name: "Media 1", media: document.getElementById('audio-test') } );
    ok( m1.getName() === "Media 1", "Name is correct" );
    ok( m1.getMedia() === document.getElementById('audio-test'), "Media element is correct" );
  });

  test( "Add, retrieve, and remove Media object", function () {
    expect(8);

    var butter = new Butter();

    var m1 = new Butter.Media( { name: "Media 1", media: document.getElementById('audio-test') } );
    butter.addMedia( m1 );
    ok( butter.getMedia("Media 1") === m1 && m1.getName() === "Media 1", "Method 1 object stored and retrieved" );

    var m2 = butter.addMedia( { name: "Media 2", media: document.getElementById('audio-test') } );
    ok( butter.getMedia("Media 2") === m2 && m2.getName() === "Media 2", "Method 2 object stored and retrieved" );

    ok( butter.getCurrentMedia() === m1, "Current media is Media 1" );
    butter.setMedia( m2 );
    ok( butter.getCurrentMedia() === m2, "Current media is Media 2" );
    butter.setMedia( m1 );
    ok( butter.getCurrentMedia() === m1, "Current media is Media 1 again" );

    butter.removeMedia( m2 );
    butter.removeMedia( "Media 1" );

    ok( butter.getMedia("Media 1") === undefined, "Media 1 doesn't exist" );
    ok( butter.getMedia("Media 2") === undefined, "Media 2 doesn't exist" );

    ok( butter.getAllMedia().length === 0, "There are no Media" );
  });

  test( "Create Track object", function () {
    expect(1);

    var butter = new Butter();

    var t1 = new Butter.Track( { name: "Track 1" } );
    ok( t1.getName() === "Track 1", "Track name is correct" );
  });

  test( "Add, retrieve, and remove Track", function () {
    expect(5);

    var butter = new Butter();

    var m = butter.addMedia();

    var t1 = new Butter.Track( { name: "Track 1" } );
    butter.addTrack( t1 );
    var t2 = butter.addTrack( { name: "Track 2" } );

    ok( butter.getTrack("Track 1") === t1 && butter.getTrack("Track 1").getName() === "Track 1", "Track generation method 1");
    ok( butter.getTrack("Track 2") === t2 && butter.getTrack("Track 2").getName() === "Track 2", "Track generation method 2");

    butter.removeTrack( "Track 1" );
    butter.removeTrack( t2 );

    ok( butter.getTrack( "Track 1" ) === undefined, "Track 1 doesn't exist" );
    ok( butter.getTrack( "Track 2" ) === undefined, "Track 2 doesn't exist" );

    ok( butter.getTracks().length === 0, "There are no Tracks" );
  });

  test("Create TrackEvent object", function () {
    expect(1);
    var te1 = new Butter.TrackEvent( { name: "TrackEvent 1", start: 0, end: 1 } );
    ok( te1.getName() === "TrackEvent 1" && te1.start === 0 && te1.end === 1, "TrackEvent is setup correctly");
  });

  test("Add, retrieve, and remove TrackEvent", function () {
    expect(9);

    var butter = new Butter();

    var m = butter.addMedia();

    var t = butter.addTrack();

    var te1 = new Butter.TrackEvent( { name: "TrackEvent 1", start: 0, end: 1 } );

    butter.addTrackEvent( t, te1 );
    var te2 = butter.addTrackEvent( t, { name: "TrackEvent 2", start: 1, end: 2 } );

    var te3 = t.addTrackEvent( { name: "TrackEvent 3", start: 2, end: 3 } );
    var te4 = t.addTrackEvent( new Butter.TrackEvent( { name: "TrackEvent 4", start: 3, end: 4 } ) );

    ok( te1 === butter.getTrackEvent( "TrackEvent 1" ), "TrackEvent method 1 is correct" );
    ok( te2 === butter.getTrackEvent( "TrackEvent 2" ), "TrackEvent method 2 is correct" );
    ok( te3 === butter.getTrackEvent( "TrackEvent 3" ), "TrackEvent method 3 is correct" );
    ok( te4 === butter.getTrackEvent( "TrackEvent 4" ), "TrackEvent method 4 is correct" );

    butter.removeTrackEvent( "TrackEvent 1" );
    butter.removeTrackEvent( te2 );
    t.removeTrackEvent( te3 );
    t.removeTrackEvent( "TrackEvent 4" );

    ok( butter.getTrackEvent( "TrackEvent 1" ) === undefined, "TrackEvent 1 doesn't exist" );
    ok( butter.getTrackEvent( "TrackEvent 2" ) === undefined, "TrackEvent 2 doesn't exist" );
    ok( butter.getTrackEvent( "TrackEvent 3" ) === undefined, "TrackEvent 3 doesn't exist" );
    ok( butter.getTrackEvent( "TrackEvent 4" ) === undefined, "TrackEvent 4 doesn't exist" );

    var tracks = butter.getTrackEvents();
    for ( var track in tracks ) {
      ok( tracks[ track ].length === 0, "No TrackEvents remain" );
    }

  });

  test("Media objects have their own tracks", function () {
    var butter = new Butter();
    var m1 = butter.addMedia();
    var m2 = butter.addMedia();

    butter.addTrack( { name:"Track 1" } );

    butter.setMedia( m2 );

    butter.addTrack( { name:"Track 2" } );

    butter.setMedia( m1 );
    ok( butter.getTrack( "Track 1" ) !== undefined, "Track 1 is on Media 1");
    ok( butter.getTrack( "Track 2" ) === undefined, "Track 2 is not on Media 1");

    butter.setMedia( m2 );
    ok( butter.getTrack( "Track 1" ) === undefined, "Track 1 is not on Media 1");
    ok( butter.getTrack( "Track 2" ) !== undefined, "Track 2 is on Media 1");

  });

})(window, document, undefined, Butter);
<commit_msg>Sorted tests a bit and added a module for each section.<commit_after>/*global text,expect,ok,module,notEqual,Butter,test,window*/
(function (window, document, undefined, Butter) {

  module( "Media" );

  test( "No media check", function () {
    expect(1);
    try {
      butter.addTrack();
      ok( false, "Media error not received" );
    }
    catch (e) {
      ok( true, "No media error received" );
    } //try
  });

  test( "Create Media object", function () {
    expect(2);
    var m1 = new Butter.Media( { name: "Media 1", media: document.getElementById('audio-test') } );
    ok( m1.getName() === "Media 1", "Name is correct" );
    ok( m1.getMedia() === document.getElementById('audio-test'), "Media element is correct" );
  });

  test( "Add, retrieve, and remove Media object", function () {
    expect(8);

    var butter = new Butter();

    var m1 = new Butter.Media( { name: "Media 1", media: document.getElementById('audio-test') } );
    butter.addMedia( m1 );
    ok( butter.getMedia("Media 1") === m1 && m1.getName() === "Media 1", "Method 1 object stored and retrieved" );

    var m2 = butter.addMedia( { name: "Media 2", media: document.getElementById('audio-test') } );
    ok( butter.getMedia("Media 2") === m2 && m2.getName() === "Media 2", "Method 2 object stored and retrieved" );

    ok( butter.getCurrentMedia() === m1, "Current media is Media 1" );
    butter.setMedia( m2 );
    ok( butter.getCurrentMedia() === m2, "Current media is Media 2" );
    butter.setMedia( m1 );
    ok( butter.getCurrentMedia() === m1, "Current media is Media 1 again" );

    butter.removeMedia( m2 );
    butter.removeMedia( "Media 1" );

    ok( butter.getMedia("Media 1") === undefined, "Media 1 doesn't exist" );
    ok( butter.getMedia("Media 2") === undefined, "Media 2 doesn't exist" );

    ok( butter.getAllMedia().length === 0, "There are no Media" );
  });

  test("Media objects have their own tracks", function () {
    var butter = new Butter();
    var m1 = butter.addMedia();
    var m2 = butter.addMedia();

    butter.addTrack( { name:"Track 1" } );

    butter.setMedia( m2 );

    butter.addTrack( { name:"Track 2" } );

    butter.setMedia( m1 );
    ok( butter.getTrack( "Track 1" ) !== undefined, "Track 1 is on Media 1");
    ok( butter.getTrack( "Track 2" ) === undefined, "Track 2 is not on Media 1");

    butter.setMedia( m2 );
    ok( butter.getTrack( "Track 1" ) === undefined, "Track 1 is not on Media 1");
    ok( butter.getTrack( "Track 2" ) !== undefined, "Track 2 is on Media 1");

  });

  module( "Track" );

  test( "Create Track object", function () {
    expect(1);

    var butter = new Butter();

    var t1 = new Butter.Track( { name: "Track 1" } );
    ok( t1.getName() === "Track 1", "Track name is correct" );
  });

  test( "Add, retrieve, and remove Track", function () {
    expect(5);

    var butter = new Butter();

    var m = butter.addMedia();

    var t1 = new Butter.Track( { name: "Track 1" } );
    butter.addTrack( t1 );
    var t2 = butter.addTrack( { name: "Track 2" } );

    ok( butter.getTrack("Track 1") === t1 && butter.getTrack("Track 1").getName() === "Track 1", "Track generation method 1");
    ok( butter.getTrack("Track 2") === t2 && butter.getTrack("Track 2").getName() === "Track 2", "Track generation method 2");

    butter.removeTrack( "Track 1" );
    butter.removeTrack( t2 );

    ok( butter.getTrack( "Track 1" ) === undefined, "Track 1 doesn't exist" );
    ok( butter.getTrack( "Track 2" ) === undefined, "Track 2 doesn't exist" );

    ok( butter.getTracks().length === 0, "There are no Tracks" );
  });

  module( "TrackEvent" );

  test("Create TrackEvent object", function () {
    expect(1);
    var te1 = new Butter.TrackEvent( { name: "TrackEvent 1", start: 0, end: 1 } );
    ok( te1.getName() === "TrackEvent 1" && te1.start === 0 && te1.end === 1, "TrackEvent is setup correctly");
  });

  test("Add, retrieve, and remove TrackEvent", function () {
    expect(9);

    var butter = new Butter();

    var m = butter.addMedia();

    var t = butter.addTrack();

    var te1 = new Butter.TrackEvent( { name: "TrackEvent 1", start: 0, end: 1 } );

    butter.addTrackEvent( t, te1 );
    var te2 = butter.addTrackEvent( t, { name: "TrackEvent 2", start: 1, end: 2 } );

    var te3 = t.addTrackEvent( { name: "TrackEvent 3", start: 2, end: 3 } );
    var te4 = t.addTrackEvent( new Butter.TrackEvent( { name: "TrackEvent 4", start: 3, end: 4 } ) );

    ok( te1 === butter.getTrackEvent( "TrackEvent 1" ), "TrackEvent method 1 is correct" );
    ok( te2 === butter.getTrackEvent( "TrackEvent 2" ), "TrackEvent method 2 is correct" );
    ok( te3 === butter.getTrackEvent( "TrackEvent 3" ), "TrackEvent method 3 is correct" );
    ok( te4 === butter.getTrackEvent( "TrackEvent 4" ), "TrackEvent method 4 is correct" );

    butter.removeTrackEvent( "TrackEvent 1" );
    butter.removeTrackEvent( te2 );
    t.removeTrackEvent( te3 );
    t.removeTrackEvent( "TrackEvent 4" );

    ok( butter.getTrackEvent( "TrackEvent 1" ) === undefined, "TrackEvent 1 doesn't exist" );
    ok( butter.getTrackEvent( "TrackEvent 2" ) === undefined, "TrackEvent 2 doesn't exist" );
    ok( butter.getTrackEvent( "TrackEvent 3" ) === undefined, "TrackEvent 3 doesn't exist" );
    ok( butter.getTrackEvent( "TrackEvent 4" ) === undefined, "TrackEvent 4 doesn't exist" );

    var tracks = butter.getTrackEvents();
    for ( var track in tracks ) {
      ok( tracks[ track ].length === 0, "No TrackEvents remain" );
    }

  });

})(window, document, undefined, Butter);
<|endoftext|>


<commit_before>'use strict'

const assert = require('assert')
const Driver = require('./../index').Driver
const ExpectedConditions = require('./../index').ExpectedConditions
const ChromeService = require('./../index').ChromeService
const CDP = require('chrome-remote-interface')
const fs = require('fs')
const expect = require('chai').expect
const createMockServer = require('./../fixtures/server')

describe('core api', function () {
  const baseHtml = fs.readFileSync(__dirname + '/../fixtures/static/base.html', 'utf-8')
  const baseUrl = process.env.CHROMINATOR_MOCK_SERVER_BASE_URL
  var driver
  var service

  before(function (done) {
    service = new ChromeService()
    service.start().then((result) => {
      driver = result
      done()
    })
  })

  after(function () {
    service.stop()
  })

  describe('query', function () {
    it('can query elements', function (done) {
      driver.setContent(baseHtml).then(() => {
        return driver.querySelectorAll({selector: 'div'})
      }).then((nodes) => {
        expect(nodes.length).to.be.above(1)

        done()
      }).catch((err) => {
        done(err)
      })
    })

    it('can query element', function (done) {
      var outerNode
      driver.setContent(baseHtml).then(() => {
        return driver.querySelector({selector: 'div#outer'})
      }).then((node) => {
        outerNode = node
        return outerNode.getAttribute('class')
      }).then((value) => {
        expect(value).to.equal('outer')
        return outerNode.getAttributes()
      }).then((attrs) => {
        expect(attrs).to.deep.equal({id: 'outer', class: 'outer'})

        done()
      }).catch((err) => {
        done(err)
      })
    })

    it('can query element from node', function (done) {
      driver.setContent(baseHtml).then(() => {
        return driver.querySelector({selector: 'div#outer'})
      }).then((node) => {
        return node.querySelector({selector: 'div#inner'})
      }).then((node) => {
        return node.getAttribute('class')
      }).then((value) => {
        expect(value).to.equal('inner')

        done()
      }).catch((err) => {
        done(err)
      })
    })
  })

  it('can query elements from node', function (done) {
    driver.setContent(baseHtml).then(() => {
      return driver.querySelector({selector: 'div#outer'})
    }).then((node) => {
      return node.querySelectorAll({selector: 'div'})
    }).then((nodes) => {
      expect(nodes.length).to.be.above(1)

      done()
    }).catch((err) => {
      done(err)
    })

    it('can navigate to google.com', function (done) {
      driver.navigate({url: 'https://www.google.com'}).then(() => {
        return driver.querySelector({selector: 'input[name="q"]'})
      }).then(() => {
        client.close()
        done()
      }).catch((err) => {
        client.close()
        done(err)
      })
    })
  })

  it('can click an element', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.querySelector({selector: 'div#inner'})
    }).then((node) => {
      return node.click()
    }).then(() => {
      return driver.querySelector({selector: 'div#innerClick'})
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('can send keys to an element', function (done) {
    var inputElem
    var name = 'Naru 1 💩'
    driver.navigate({url: baseUrl + '/input.html'}).then(() => {
      return driver.querySelector({selector: 'input#name'})
    }).then((node) => {
      inputElem = node
      return inputElem.sendKeys(name)
    }).then((node) => {
      return inputElem.getProperty('value')
    }).then((value) => {
      expect(value).to.equal(name)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('evaluate can return number', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.evaluate({functionDeclaration: function () { return 1 }})
    }).then((result) => {
      expect(result).to.equal(1)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('evaluate can return string', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.evaluate({functionDeclaration: function () { return 'foo' }})
    }).then((result) => {
      expect(result).to.equal('foo')
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('evaluate can return null', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.evaluate({functionDeclaration: 'return null;'})
    }).then((result) => {
      expect(result).to.equal(null)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('evaluate can handle function with numeric argument', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.evaluate({functionDeclaration: function (name) { return name }, args: [1]})
    }).then((result) => {
      expect(result).to.equal(1)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('evaluate can handle function with string argument', function (done) {
    const name = 'jesg'
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.evaluate({functionDeclaration: function (name) { return name }, args: [name]})
    }).then((result) => {
      expect(result).to.equal(name)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('evaluateAsync can resolve primitive', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.evaluateAsync({functionDeclaration: function () { resolve(1) }})
    }).then((result) => {
      expect(result).to.equal(1)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('evaluateAsync can resolve setTimeout', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.evaluateAsync({functionDeclaration: function () { setTimeout(function () { resolve(1) }, 10) }})
    }).then((result) => {
      expect(result).to.equal(1)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('node evaluate can get class attribute', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.querySelector({selector: 'div#inner'})
    }).then((node) => {
      return node.evaluate({functionDeclaration: function () { return this.getAttribute('class') }})
    }).then((result) => {
      expect(result).to.equal('inner')
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('node arg evaluate can get class attribute', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.querySelector({selector: 'div#inner'})
    }).then((node) => {
      return driver.evaluate({functionDeclaration: function (node) { return node.getAttribute('class') }, args: [node]})
    }).then((result) => {
      expect(result).to.equal('inner')
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('node evaluateAsync can resolve setTimeout', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.querySelector({selector: 'div#inner'})
    }).then((node) => {
      return node.evaluateAsync({functionDeclaration: function () { setTimeout(function () { resolve(1) }, 10) }})
    }).then((result) => {
      expect(result).to.equal(1)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('node can set value property', function (done) {
    let node
    const name = 'jesg'
    driver.navigate({url: baseUrl + '/input.html'}).then(() => {
      return driver.querySelector({selector: 'input#name'})
    }).then((result) => {
      node = result
      return node.setProperty('value', name)
    }).then(() => {
      return node.getProperty('value')
    }).then((result) => {
      expect(result).to.equal(name)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('node can equal itself', function (done) {
    let firstNode
    driver.navigate({url: baseUrl + '/base.html'}).then(() => {
      return driver.querySelector({selector: 'div#outer'})
    }).then((result) => {
      firstNode = result
      return driver.querySelector({selector: 'div#outer'})
    }).then((result) => {
      return firstNode.equal(result)
    }).then((result) => {
      expect(result).to.be.true
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('node does not equal another node', function (done) {
    let firstNode
    driver.navigate({url: baseUrl + '/base.html'}).then(() => {
      return driver.querySelector({selector: 'div#outer'})
    }).then((result) => {
      firstNode = result
      return driver.querySelector({selector: 'div#inner'})
    }).then((result) => {
      return firstNode.equal(result)
    }).then((result) => {
      expect(result).to.be.false
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('can search google', function (done) {
        // TODO refactor to use the mock server
    let firstNode
    driver.navigate({url: 'https://google.com'}).then(() => {
      return driver.querySelector({selector: 'input[name="q"]'})
    }).then((node) => {
      return node.sendKeys('yellow')
    }).then((result) => {
      return driver.until(ExpectedConditions.is_node_present({selector: 'button[value="Search"]'}))
    }).then((node) => {
      return node.click()
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('can get visible text', function (done) {
    let firstNode
    driver.navigate({url: baseUrl + '/base.html'}).then(() => {
      return driver.querySelector('#greeting')
    }).then((node) => {
      return node.text()
    }).then((result) => {
      expect(result).to.equal('hi')
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })
})
<commit_msg>delete old comment<commit_after>'use strict'

const assert = require('assert')
const Driver = require('./../index').Driver
const ExpectedConditions = require('./../index').ExpectedConditions
const ChromeService = require('./../index').ChromeService
const CDP = require('chrome-remote-interface')
const fs = require('fs')
const expect = require('chai').expect
const createMockServer = require('./../fixtures/server')

describe('core api', function () {
  const baseHtml = fs.readFileSync(__dirname + '/../fixtures/static/base.html', 'utf-8')
  const baseUrl = process.env.CHROMINATOR_MOCK_SERVER_BASE_URL
  var driver
  var service

  before(function (done) {
    service = new ChromeService()
    service.start().then((result) => {
      driver = result
      done()
    })
  })

  after(function () {
    service.stop()
  })

  describe('query', function () {
    it('can query elements', function (done) {
      driver.setContent(baseHtml).then(() => {
        return driver.querySelectorAll({selector: 'div'})
      }).then((nodes) => {
        expect(nodes.length).to.be.above(1)

        done()
      }).catch((err) => {
        done(err)
      })
    })

    it('can query element', function (done) {
      var outerNode
      driver.setContent(baseHtml).then(() => {
        return driver.querySelector({selector: 'div#outer'})
      }).then((node) => {
        outerNode = node
        return outerNode.getAttribute('class')
      }).then((value) => {
        expect(value).to.equal('outer')
        return outerNode.getAttributes()
      }).then((attrs) => {
        expect(attrs).to.deep.equal({id: 'outer', class: 'outer'})

        done()
      }).catch((err) => {
        done(err)
      })
    })

    it('can query element from node', function (done) {
      driver.setContent(baseHtml).then(() => {
        return driver.querySelector({selector: 'div#outer'})
      }).then((node) => {
        return node.querySelector({selector: 'div#inner'})
      }).then((node) => {
        return node.getAttribute('class')
      }).then((value) => {
        expect(value).to.equal('inner')

        done()
      }).catch((err) => {
        done(err)
      })
    })
  })

  it('can query elements from node', function (done) {
    driver.setContent(baseHtml).then(() => {
      return driver.querySelector({selector: 'div#outer'})
    }).then((node) => {
      return node.querySelectorAll({selector: 'div'})
    }).then((nodes) => {
      expect(nodes.length).to.be.above(1)

      done()
    }).catch((err) => {
      done(err)
    })

    it('can navigate to google.com', function (done) {
      driver.navigate({url: 'https://www.google.com'}).then(() => {
        return driver.querySelector({selector: 'input[name="q"]'})
      }).then(() => {
        client.close()
        done()
      }).catch((err) => {
        client.close()
        done(err)
      })
    })
  })

  it('can click an element', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.querySelector({selector: 'div#inner'})
    }).then((node) => {
      return node.click()
    }).then(() => {
      return driver.querySelector({selector: 'div#innerClick'})
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('can send keys to an element', function (done) {
    var inputElem
    var name = 'Naru 1 💩'
    driver.navigate({url: baseUrl + '/input.html'}).then(() => {
      return driver.querySelector({selector: 'input#name'})
    }).then((node) => {
      inputElem = node
      return inputElem.sendKeys(name)
    }).then((node) => {
      return inputElem.getProperty('value')
    }).then((value) => {
      expect(value).to.equal(name)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('evaluate can return number', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.evaluate({functionDeclaration: function () { return 1 }})
    }).then((result) => {
      expect(result).to.equal(1)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('evaluate can return string', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.evaluate({functionDeclaration: function () { return 'foo' }})
    }).then((result) => {
      expect(result).to.equal('foo')
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('evaluate can return null', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.evaluate({functionDeclaration: 'return null;'})
    }).then((result) => {
      expect(result).to.equal(null)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('evaluate can handle function with numeric argument', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.evaluate({functionDeclaration: function (name) { return name }, args: [1]})
    }).then((result) => {
      expect(result).to.equal(1)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('evaluate can handle function with string argument', function (done) {
    const name = 'jesg'
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.evaluate({functionDeclaration: function (name) { return name }, args: [name]})
    }).then((result) => {
      expect(result).to.equal(name)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('evaluateAsync can resolve primitive', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.evaluateAsync({functionDeclaration: function () { resolve(1) }})
    }).then((result) => {
      expect(result).to.equal(1)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('evaluateAsync can resolve setTimeout', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.evaluateAsync({functionDeclaration: function () { setTimeout(function () { resolve(1) }, 10) }})
    }).then((result) => {
      expect(result).to.equal(1)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('node evaluate can get class attribute', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.querySelector({selector: 'div#inner'})
    }).then((node) => {
      return node.evaluate({functionDeclaration: function () { return this.getAttribute('class') }})
    }).then((result) => {
      expect(result).to.equal('inner')
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('node arg evaluate can get class attribute', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.querySelector({selector: 'div#inner'})
    }).then((node) => {
      return driver.evaluate({functionDeclaration: function (node) { return node.getAttribute('class') }, args: [node]})
    }).then((result) => {
      expect(result).to.equal('inner')
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('node evaluateAsync can resolve setTimeout', function (done) {
    driver.navigate({url: baseUrl + '/clickable.html'}).then(() => {
      return driver.querySelector({selector: 'div#inner'})
    }).then((node) => {
      return node.evaluateAsync({functionDeclaration: function () { setTimeout(function () { resolve(1) }, 10) }})
    }).then((result) => {
      expect(result).to.equal(1)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('node can set value property', function (done) {
    let node
    const name = 'jesg'
    driver.navigate({url: baseUrl + '/input.html'}).then(() => {
      return driver.querySelector({selector: 'input#name'})
    }).then((result) => {
      node = result
      return node.setProperty('value', name)
    }).then(() => {
      return node.getProperty('value')
    }).then((result) => {
      expect(result).to.equal(name)
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('node can equal itself', function (done) {
    let firstNode
    driver.navigate({url: baseUrl + '/base.html'}).then(() => {
      return driver.querySelector({selector: 'div#outer'})
    }).then((result) => {
      firstNode = result
      return driver.querySelector({selector: 'div#outer'})
    }).then((result) => {
      return firstNode.equal(result)
    }).then((result) => {
      expect(result).to.be.true
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('node does not equal another node', function (done) {
    let firstNode
    driver.navigate({url: baseUrl + '/base.html'}).then(() => {
      return driver.querySelector({selector: 'div#outer'})
    }).then((result) => {
      firstNode = result
      return driver.querySelector({selector: 'div#inner'})
    }).then((result) => {
      return firstNode.equal(result)
    }).then((result) => {
      expect(result).to.be.false
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('can search google', function (done) {
    let firstNode
    driver.navigate({url: 'https://google.com'}).then(() => {
      return driver.querySelector({selector: 'input[name="q"]'})
    }).then((node) => {
      return node.sendKeys('yellow')
    }).then((result) => {
      return driver.until(ExpectedConditions.is_node_present({selector: 'button[value="Search"]'}))
    }).then((node) => {
      return node.click()
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })

  it('can get visible text', function (done) {
    let firstNode
    driver.navigate({url: baseUrl + '/base.html'}).then(() => {
      return driver.querySelector('#greeting')
    }).then((node) => {
      return node.text()
    }).then((result) => {
      expect(result).to.equal('hi')
    }).then(() => {
      done()
    }).catch((err) => {
      done(err)
    })
  })
})
<|endoftext|>


<commit_before>'use strict'

var express = require('express')
var imageUrl = require('../lib/image-url')
var request = require('supertest')
var scale = require('..')
var should = require('should')

var app = express()
var port = app.listen().address().port
app.use('/images', express.static('test/images'))
app.use('/scale1', scale({baseHost: 'localhost:' + port}))
app.use('/scale2', scale({
  baseHost: 'localhost:' + port,
  cors: {origin: 'http://example.com'},
}))

describe('Test CORS', function() {
  it('should send Access-Control-Allow-Origin:* header', function(done) {
    request(app)
      .get(imageUrl('/scale1')(110, {url: '/images/a.jpg'}))
      .expect('Access-Control-Allow-Origin', '*')
      .expect(200, done)
  })

  it('should send ACAO:example.com header', function(done) {
    request(app)
      .get(imageUrl('/scale2')(110, {url: '/images/a.jpg'}))
      .expect('Access-Control-Allow-Origin', 'http://example.com')
      .expect(200, done)
  })
})
<commit_msg>fix eslint error<commit_after>'use strict'

var express = require('express')
var imageUrl = require('../lib/image-url')
var request = require('supertest')
var scale = require('..')

var app = express()
var port = app.listen().address().port
app.use('/images', express.static('test/images'))
app.use('/scale1', scale({baseHost: 'localhost:' + port}))
app.use('/scale2', scale({
  baseHost: 'localhost:' + port,
  cors: {origin: 'http://example.com'},
}))

describe('Test CORS', function() {
  it('should send Access-Control-Allow-Origin:* header', function(done) {
    request(app)
      .get(imageUrl('/scale1')(110, {url: '/images/a.jpg'}))
      .expect('Access-Control-Allow-Origin', '*')
      .expect(200, done)
  })

  it('should send ACAO:example.com header', function(done) {
    request(app)
      .get(imageUrl('/scale2')(110, {url: '/images/a.jpg'}))
      .expect('Access-Control-Allow-Origin', 'http://example.com')
      .expect(200, done)
  })
})
<|endoftext|>


<commit_before>var assert = require('assert');
var _ = require('lodash');

var apos;

function anonReq() {
  return {
    res: {
      __: function(x) { return x; }
    },
    browserCall: apos.app.request.browserCall,
    getBrowserCalls: apos.app.request.getBrowserCalls,
    query: {}
  };
}

function adminReq() {
  return _.merge(anonReq(), {
    user: {
      permissions: {
        admin: true
      }
    }
  });
}

describe('Docs', function() {
  //////
  // EXISTENCE
  //////

  it('should be a property of the apos object', function(done) {
    apos = require('../index.js')({
      root: module,
      shortName: 'test',
      hostName: 'test.com',
      modules: {
        'apostrophe-express': {
          secret: 'xxx',
          port: 7939
        }
      },
      afterInit: function(callback) {
        assert(apos.docs);
        apos.argv._ = [];
        return callback(null);
      },
      afterListen: function(err) {
        done();
      }
    });
  });

  it('should have a db property', function() {
    assert(apos.docs.db);
  });

  //////
  // SETUP
  //////

  it('should make sure all of the expected indexes are configured', function(done){
    var expectedIndexes = ['type', 'slug', 'sortTitle', 'tags', 'published'];
    var actualIndexes = []

    apos.docs.db.indexInformation(function(err, info){
      assert(!err);

      // Extract the actual index info we care about
      _.each(info, function(index){
        actualIndexes.push(index[0][0]);
      });

      // Now make sure everything in expectedIndexes is in actualIndexes
      _.each(expectedIndexes, function(index){
        assert(_.contains(actualIndexes, index))
      });

      // Lastly, make sure there is a text index present
      assert(info.highSearchText_text_lowSearchText_text_title_text_searchBoost_text[0][1] === 'text');
      done();
    });
  });

  it('should make sure there is no test data hanging around from last time', function(done){
    // Attempt to remove all the test people we know about
    apos.docs.db.remove({
      $or: [
        { slug: 'larry' },
        { slug: 'lori' },
        { slug: 'carl' },
        { slug: 'peter' }
      ]
    }, function(err){
      assert(!err);
      // Now look for one of them and make sure they don't exist anymore
      apos.docs.db.find({ slug: 'larry' }).toArray(function(err, docs){
        assert(docs.length === 0);
        done();
      });
    });
  });

  it('should be able to use db to insert documents', function(done){
    var testItems = [
      {
        slug: 'lori',
        published: true,
        type: 'testPerson',
        firstName: 'Lori',
        lastName: 'Pizzaroni',
        age: 32,
        alive: true
      },
      {
        slug: 'larry',
        published: true,
        type: 'testPerson',
        firstName: 'Larry',
        lastName: 'Cherber',
        age: 28,
        alive: true
      },
      {
        slug: 'carl',
        published: true,
        type: 'testPerson',
        firstName: 'Carl',
        lastName: 'Sagan',
        age: 62,
        alive: false
      }
    ]

    apos.docs.db.insert(testItems, function(err){
      assert(!err);
      done();
    });
  });

  //////
  // UNIQUENESS
  //////

  it('should fail if you try to insert a document with the same unique key twice', function(done){
    apos.docs.db.insert([
      {
        type: 'testPerson',
        published: false,
        age: 70,
        slug: 'peter'
      },
      {
        type: 'testPerson',
        published: false,
        age: 70,
        slug: 'peter'
      }
    ], function(err){
      assert(err);
      done();
    });
  });

  //////
  // FINDING
  //////

  it('should have a find method on docs that returns a cursor', function(){
    var cursor = apos.docs.find();
    assert(cursor);
  });

  it('should be able to find all PUBLISHED test documents and ouput them as an array', function(done){
    var cursor = apos.docs.find(anonReq(), { type: 'testPerson' });

    cursor.toArray(function(err, docs){
      assert(!err);
      // There should be only 3 results.
      assert(docs.length === 3);
      // They should all have a type of testPerson
      assert(docs[0].type === 'testPerson');
      done();
    });
  });

  //////
  // PROJECTIONS
  //////

  it('should be able to specify which fields to get by passing a projection object', function(done){
    var cursor = apos.docs.find(anonReq(), { type: 'testPerson' }, { age: 1 });
    cursor.toArray(function(err, docs){
      // There SHOULD be an age
      assert(docs[0].age);

      // There SHOULD NOT be a firstName
      assert(!docs[0].firstName);
      done();
    });
  });

  //////
  // PUBLISHED vs UNPUBLISHED
  //////

  it('should be that non-admins DO NOT get unpublished docs by default', function(done) {
    var cursor = apos.docs.find(anonReq(), { type: 'testPerson' });
    cursor.toArray(function(err, docs){
      _.each(docs, function(doc){
        // There SHOULD NOT be a firstName
        assert(doc.published);
      });

      done();
    });
  });

  it('should be that non-admins do not get unpublished docs, even if they ask for them', function(done) {
    var cursor = apos.docs.find(anonReq(), { type: 'testPerson' }).published(false);
    cursor.toArray(function(err, docs){
      assert(docs.length === 0);
      done();
    });
  });

  it('should be that admins can get unpublished docs if they ask for them', function(done) {
    var cursor = apos.docs.find(adminReq(), { type: 'testPerson' }).published(false);
    cursor.toArray(function(err, docs){
      assert(!docs[0].published);
      done();
    });
  });

  it('should be that admins can get a mixture of unpublished docs and published docs if they ask', function(done) {
    var cursor = apos.docs.find(adminReq(), { type: 'testPerson' }).published(null);
    cursor.toArray(function(err, docs) {
      assert(docs.length === 4);
      done();
    });
  });

  //////
  // SORTING
  //////

  it('should be able to sort', function(done) {
    var cursor = apos.docs.find(anonReq(), { type: 'testPerson' }).sort({ age: 1 });
    cursor.toArray(function(err, docs) {
      assert(docs[0].slug == 'larry');
      done();
    });
  });

  it('should be able to sort by multiple keys', function(done) {
    var cursor = apos.docs.find(anonReq(), { type: 'testPerson' }).sort({ firstName:1 , age: 1 });
    cursor.toArray(function(err, docs) {
      assert(docs[0].slug == 'carl');
      assert(docs[1].slug == 'larry');
      done();
    });
  });

});
<commit_msg>added new tests for apos.docs.instert and apos.docs.update<commit_after>var assert = require('assert');
var _ = require('lodash');

var apos;

function anonReq() {
  return {
    res: {
      __: function(x) { return x; }
    },
    browserCall: apos.app.request.browserCall,
    getBrowserCalls: apos.app.request.getBrowserCalls,
    query: {}
  };
}

function adminReq() {
  return _.merge(anonReq(), {
    user: {
      permissions: {
        admin: true
      }
    }
  });
}

describe('Docs', function() {
  //////
  // EXISTENCE
  //////

  it('should be a property of the apos object', function(done) {
    apos = require('../index.js')({
      root: module,
      shortName: 'test',
      hostName: 'test.com',
      modules: {
        'apostrophe-express': {
          secret: 'xxx',
          port: 7939
        }
      },
      afterInit: function(callback) {
        assert(apos.docs);
        apos.argv._ = [];
        return callback(null);
      },
      afterListen: function(err) {
        done();
      }
    });
  });

  it('should have a db property', function() {
    assert(apos.docs.db);
  });

  //////
  // SETUP
  //////

  it('should make sure all of the expected indexes are configured', function(done){
    var expectedIndexes = ['type', 'slug', 'sortTitle', 'tags', 'published'];
    var actualIndexes = []

    apos.docs.db.indexInformation(function(err, info){
      assert(!err);

      // Extract the actual index info we care about
      _.each(info, function(index){
        actualIndexes.push(index[0][0]);
      });

      // Now make sure everything in expectedIndexes is in actualIndexes
      _.each(expectedIndexes, function(index){
        assert(_.contains(actualIndexes, index))
      });

      // Lastly, make sure there is a text index present
      assert(info.highSearchText_text_lowSearchText_text_title_text_searchBoost_text[0][1] === 'text');
      done();
    });
  });

  it('should make sure there is no test data hanging around from last time', function(done){
    // Attempt to remove all the test people we know about
    apos.docs.db.remove({
      $or: [
        { slug: 'larry' },
        { slug: 'lori' },
        { slug: 'carl' },
        { slug: 'peter' },
        { slug: 'one'},
        { slug: /^one\d+$/}
      ]
    }, function(err){
      assert(!err);
      // Now look for one of them and make sure they don't exist anymore
      apos.docs.db.find({ slug: 'larry' }).toArray(function(err, docs){
        assert(docs.length === 0);
        done();
      });
    });
  });

  it('should be able to use db to insert documents', function(done){
    var testItems = [
      {
        slug: 'lori',
        published: true,
        type: 'testPerson',
        firstName: 'Lori',
        lastName: 'Pizzaroni',
        age: 32,
        alive: true
      },
      {
        slug: 'larry',
        published: true,
        type: 'testPerson',
        firstName: 'Larry',
        lastName: 'Cherber',
        age: 28,
        alive: true
      },
      {
        slug: 'carl',
        published: true,
        type: 'testPerson',
        firstName: 'Carl',
        lastName: 'Sagan',
        age: 62,
        alive: false
      }
    ]

    apos.docs.db.insert(testItems, function(err){
      assert(!err);
      done();
    });
  });

  //////
  // UNIQUENESS
  //////

  it('should fail if you try to insert a document with the same unique key twice', function(done){
    apos.docs.db.insert([
      {
        type: 'testPerson',
        published: false,
        age: 70,
        slug: 'peter'
      },
      {
        type: 'testPerson',
        published: false,
        age: 70,
        slug: 'peter'
      }
    ], function(err){
      assert(err);
      done();
    });
  });

  //////
  // FINDING
  //////

  it('should have a find method on docs that returns a cursor', function(){
    var cursor = apos.docs.find();
    assert(cursor);
  });

  it('should be able to find all PUBLISHED test documents and ouput them as an array', function(done){
    var cursor = apos.docs.find(anonReq(), { type: 'testPerson' });

    cursor.toArray(function(err, docs){
      assert(!err);
      // There should be only 3 results.
      assert(docs.length === 3);
      // They should all have a type of testPerson
      assert(docs[0].type === 'testPerson');
      done();
    });
  });

  //////
  // PROJECTIONS
  //////

  it('should be able to specify which fields to get by passing a projection object', function(done){
    var cursor = apos.docs.find(anonReq(), { type: 'testPerson' }, { age: 1 });
    cursor.toArray(function(err, docs){
      // There SHOULD be an age
      assert(docs[0].age);

      // There SHOULD NOT be a firstName
      assert(!docs[0].firstName);
      done();
    });
  });

  //////
  // PUBLISHED vs UNPUBLISHED
  //////

  it('should be that non-admins DO NOT get unpublished docs by default', function(done) {
    var cursor = apos.docs.find(anonReq(), { type: 'testPerson' });
    cursor.toArray(function(err, docs){
      _.each(docs, function(doc){
        // There SHOULD NOT be a firstName
        assert(doc.published);
      });

      done();
    });
  });

  it('should be that non-admins do not get unpublished docs, even if they ask for them', function(done) {
    var cursor = apos.docs.find(anonReq(), { type: 'testPerson' }).published(false);
    cursor.toArray(function(err, docs){
      assert(docs.length === 0);
      done();
    });
  });

  it('should be that admins can get unpublished docs if they ask for them', function(done) {
    var cursor = apos.docs.find(adminReq(), { type: 'testPerson' }).published(false);
    cursor.toArray(function(err, docs){
      assert(!docs[0].published);
      done();
    });
  });

  it('should be that admins can get a mixture of unpublished docs and published docs if they ask', function(done) {
    var cursor = apos.docs.find(adminReq(), { type: 'testPerson' }).published(null);
    cursor.toArray(function(err, docs) {
      assert(docs.length === 4);
      done();
    });
  });

  //////
  // SORTING
  //////

  it('should be able to sort', function(done) {
    var cursor = apos.docs.find(anonReq(), { type: 'testPerson' }).sort({ age: 1 });
    cursor.toArray(function(err, docs) {
      assert(docs[0].slug == 'larry');
      done();
    });
  });

  it('should be able to sort by multiple keys', function(done) {
    var cursor = apos.docs.find(anonReq(), { type: 'testPerson' }).sort({ firstName:1 , age: 1 });
    cursor.toArray(function(err, docs) {
      assert(docs[0].slug == 'carl');
      assert(docs[1].slug == 'larry');
      done();
    });
  });

  //////
  // INSTERTING
  //////

  it('should have an insert method on docs that returns the new database object', function(done) {
    var object = {
      slug: 'one',
      published: true,
      type: 'testPerson',
      firstName: 'Gary',
      lastName: 'Ferber',
      age: 15,
      alive: true
    };

    apos.docs.insert(adminReq(), object, function(err, object){
      assert(!err);
      assert(object);
      assert(object._id);
      done();
    });
  });

  it ('should have inserted a new object into the docs collection in the database', function(done){
    var cursor = apos.docs.find(adminReq(), { type: 'testPerson', slug: 'one' });
    cursor.toArray(function(err, docs) {
      assert(docs[0].slug == 'one');
      done();
    });
  });

  it('should insert a new doc and alter the slug since that slug already exists', function(done) {
    var object = {
      slug: 'one',
      published: true,
      type: 'testPerson',
      firstName: 'Harry',
      lastName: 'Gerber',
      age: 29,
      alive: true
    };

    apos.docs.insert(adminReq(), object, function(err, object){
      assert(!err);
      assert(object);
      assert(object.slug.match(/^one\d+$/));
      done();
    });
  });

  //////
  // UPDATING
  //////

  it('should have an update method on docs that updates an existing database object based on the _id property', function(done) {
    var cursor = apos.docs.find(adminReq(), { slug: 'one' }).toArray(function(err,docs){
      assert(!err);
      // we should have a document
      assert(docs);
      // there should be only one document in our results
      assert(docs.length === 1);

      // grab the object
      var object = docs[0];
      // we want to use the _id property to update this docuemtn
      var updateId = object._id;
      // we want update the alive property
      object.alive = false

      apos.docs.update(adminReq(), updateId, object, function(err, object) {
        assert(!err);
        assert(object);
        // has the property been updated?
        assert(object.alive === false);
        done();
      });
    });
  });

  it('should have an update method on docs that updates an existing database object based on a property that is not the _id', function(done) {
    var object = {
      slug: 'one',
      published: true,
      type: 'testPerson',
      firstName: 'Gary',
      lastName: 'Ferber',
      age: 15,
      alive: true
    };

    apos.docs.update(adminReq(), { slug: 'one' }, object, function(err, object) {
      assert(!err);
      assert(object);
      // has the property been updated?
      assert(object.alive === true);
      done();
    });
  });

  it('should have an update method on docs that updates a specific property of an existing database object', function(done) {

    apos.docs.update(adminReq(), { slug: 'one' }, { $set: { alive: false } }, function(err, object) {
      assert(!err);
      assert(object);
      // has the property been updated?
      assert(object.alive === false);
      done();
    });
  });

  //////
  // TRASH
  //////

});
<|endoftext|>