<commit_before>
module.exports = errorHandler

var cbCalled = false
  , log = require("npmlog")
  , npm = require("../npm.js")
  , rm = require("rimraf")
  , itWorked = false
  , path = require("path")
  , wroteLogFile = false
  , exitCode = 0

process.on("exit", function (code) {
  // console.error("exit", code)
  if (!npm.config || !npm.config.loaded) return
  if (code) itWorked = false
  if (itWorked) log.info("ok")
  else {
    if (!cbCalled) {
      log.error("", "cb() never called!")
    }

    if (wroteLogFile) {
      log.error("", [""
                ,"Additional logging details can be found in:"
                ,"    " + path.resolve("npm-debug.log")
                ].join("\n"))
      wroteLogFile = false
    }
    log.error("not ok", "code", code)
  }

  var doExit = npm.config.get("_exit")
  if (doExit) {
    // actually exit.
    if (exitCode === 0 && !itWorked) {
      exitCode = 1
    }
    if (exitCode !== 0) process.exit(exitCode)
  } else {
    itWorked = false // ready for next exit
  }
})

function exit (code, noLog) {
  exitCode = exitCode || process.exitCode || code

  var doExit = npm.config ? npm.config.get("_exit") : true
  log.verbose("exit", [code, doExit])
  if (log.level === "silent") noLog = true

  if (code && !noLog) writeLogFile(reallyExit)
  else rm("npm-debug.log", function () { rm(npm.tmp, reallyExit) })

  function reallyExit() {
    // truncate once it's been written.
    log.record.length = 0

    itWorked = !code

    // just emit a fake exit event.
    // if we're really exiting, then let it exit on its own, so that
    // in-process stuff can finish or clean up first.
    if (!doExit) process.emit("exit", code)
    npm.spinner.stop()
  }
}

function errorHandler (er) {
  var printStack = false
  // console.error("errorHandler", er)
  if (!npm.config || !npm.config.loaded) {
    // logging won't work unless we pretend that it's ready
    er = er || new Error("Exit prior to config file resolving.")
    console.error(er.stack || er.message)
  }

  if (cbCalled) {
    er = er || new Error("Callback called more than once.")
  }

  cbCalled = true
  if (!er) return exit(0)
  if (typeof er === "string") {
    log.error("", er)
    return exit(1, true)
  } else if (!(er instanceof Error)) {
    log.error("weird error", er)
    return exit(1, true)
  }

  var m = er.code || er.message.match(/^(?:Error: )?(E[A-Z]+)/)
  if (m && !er.code) er.code = m

  switch (er.code) {
  case "ECONNREFUSED":
    log.error("", er)
    log.error("", ["\nIf you are behind a proxy, please make sure that the"
              ,"'proxy' config is set properly.  See: 'npm help config'"
              ].join("\n"))
    printStack = true
    break

  case "EACCES":
  case "EPERM":
    log.error("", er)
    log.error("", ["\nPlease try running this command again as root/Administrator."
              ].join("\n"))
    printStack = true
    break

  case "ELIFECYCLE":
    er.code = "ELIFECYCLE"
    log.error("", er.message)
    log.error("", ["","Failed at the "+er.pkgid+" "+er.stage+" script."
              ,"This is most likely a problem with the "+er.pkgname+" package,"
              ,"not with npm itself."
              ,"Tell the author that this fails on your system:"
              ,"    "+er.script
              ,"You can get their info via:"
              ,"    npm owner ls "+er.pkgname
              ,"There is likely additional logging output above."
              ].join("\n"))
    break

  case "ENOGIT":
    er.code = "ENOGIT"
    log.error("", er.message)
    log.error("", ["","Failed using git."
              ,"This is most likely not a problem with npm itself."
              ,"Please check if you have git installed and in your PATH."
              ].join("\n"))
    break

  case "EJSONPARSE":
    er.code = "EJSONPARSE"
    log.error("", er.message)
    log.error("", "File: "+er.file)
    log.error("", ["Failed to parse package.json data."
              ,"package.json must be actual JSON, not just JavaScript."
              ,"","This is not a bug in npm."
              ,"Tell the package author to fix their package.json file."
              ].join("\n"), "JSON.parse")
    break

  case "E404":
    er.code = "E404"
    var msg = [er.message]
    if (er.pkgid && er.pkgid !== "-") {
      msg.push("", "'"+er.pkgid+"' is not in the npm registry."
              ,"You should bug the author to publish it")
      if (er.parent) {
        msg.push("It was specified as a dependency of '"+er.parent+"'")
      }
      if (er.pkgid.match(/^node[\.\-]|[\.\-]js$/)) {
        var s = er.pkgid.replace(/^node[\.\-]|[\.\-]js$/g, "")
        if (s !== er.pkgid) {
          s = s.replace(/[^a-z0-9]/g, ' ')
          msg.push("\nMaybe try 'npm search " + s + "'")
        }
      }
      msg.push("\nNote that you can also install from a"
              ,"tarball, folder, or http url, or git url.")
    }
    log.error("404", msg.join("\n"))
    break

  case "EPUBLISHCONFLICT":
    er.code = "EPUBLISHCONFLICT"
    log.error("publish fail", ["Cannot publish over existing version."
              ,"Update the 'version' field in package.json and try again."
              ,""
              ,"If the previous version was published in error, see:"
              ,"    npm help unpublish"
              ,""
              ,"To automatically increment version numbers, see:"
              ,"    npm help version"
              ].join("\n"))
    break

  case "EISGIT":
    er.code = "EISGIT"
    log.error("git", [er.message
              ,"    "+er.path
              ,"Refusing to remove it. Update manually,"
              ,"or move it out of the way first."
              ].join("\n"))
    break

  case "ECYCLE":
    er.code = "ECYCLE"
    log.error("cycle", [er.message
              ,"While installing: "+er.pkgid
              ,"Found a pathological dependency case that npm cannot solve."
              ,"Please report this to the package author."
              ].join("\n"))
    break

  case "EBADPLATFORM":
    er.code = "EBADPLATFORM"
    log.error("notsup", [er.message
              ,"Not compatible with your operating system or architecture: "+er.pkgid
              ,"Valid OS:    "+er.os.join(",")
              ,"Valid Arch:  "+er.cpu.join(",")
              ,"Actual OS:   "+process.platform
              ,"Actual Arch: "+process.arch
              ].join("\n"))
    break

  case "EEXIST":
    log.error([er.message
              ,"File exists: "+er.path
              ,"Move it away, and try again."].join("\n"))
    break

  case "ENEEDAUTH":
    log.error("need auth", [er.message
              ,"You need to authorize this machine using `npm adduser`"
              ].join("\n"))
    break

  case "EPEERINVALID":
    var peerErrors = Object.keys(er.peersDepending).map(function (peer) {
      return "Peer " + peer + " wants " + er.packageName + "@"
        + er.peersDepending[peer]
    })
    log.error("peerinvalid", [er.message].concat(peerErrors).join("\n"))
    break

  case "ECONNRESET":
  case "ENOTFOUND":
  case "ETIMEDOUT":
    log.error("network", [er.message
              ,"This is most likely not a problem with npm itself"
              ,"and is related to network connectivity."
              ,"In most cases you are behind a proxy or have bad network settings."
              ,"\nIf you are behind a proxy, please make sure that the"
              ,"'proxy' config is set properly.  See: 'npm help config'"
              ].join("\n"))
    break

  case "ENOPACKAGEJSON":
    log.error("package.json", [er.message
              ,"This is most likely not a problem with npm itself."
              ,"npm can't find a package.json file in your current directory."
              ].join("\n"))
    break

  case "ETARGET":
    log.error("notarget", [er.message
              ,"This is most likely not a problem with npm itself."
              ,"In most cases you or one of your dependencies are requesting"
              ,"a package version that doesn't exist."
              ].join("\n"))
    break

  case "ENOTSUP":
    if (er.required) {
      log.error("notsup", [er.message
                ,"Not compatible with your version of node/npm: "+er.pkgid
                ,"Required: "+JSON.stringify(er.required)
                ,"Actual:   "
                +JSON.stringify({npm:npm.version
                                ,node:npm.config.get("node-version")})
                ].join("\n"))
      break
    } // else passthrough

  case "ENOSPC":
    log.error("nospc", [er.message
              ,"This is most likely not a problem with npm itself"
              ,"and is related to insufficient space on your system."
              ].join("\n"))
    break

  case "EROFS":
    log.error("rofs", [er.message
              ,"This is most likely not a problem with npm itself"
              ,"and is related to read-only permissions."
              ,"\nVerify that the file system is not read-only."
              ].join("\n"))
    break

  default:
    log.error("", er.stack || er.message || er)
    log.error("", ["If you need help, you may report this *entire* log,"
                  ,"including the npm and node versions, at:"
                  ,"    <http://github.com/npm/npm/issues>"
                  ].join("\n"))
    printStack = false
    break
  }

  var os = require("os")
  // just a line break
  if (log.levels[log.level] <= log.levels.error) console.error("")
  log.error("System", os.type() + " " + os.release())
  log.error("command", process.argv
            .map(JSON.stringify).join(" "))
  log.error("cwd", process.cwd())
  log.error("node -v", process.version)
  log.error("npm -v", npm.version)

  ; [ "file"
    , "path"
    , "type"
    , "syscall"
    , "fstream_path"
    , "fstream_unc_path"
    , "fstream_type"
    , "fstream_class"
    , "fstream_finish_call"
    , "fstream_linkpath"
    , "code"
    , "errno"
    , "stack"
    , "fstream_stack"
    ].forEach(function (k) {
      var v = er[k]
      if (k === "stack") {
        if (!printStack) return
        if (!v) v = er.message
      }
      if (!v) return
      if (k === "fstream_stack") v = v.join("\n")
      log.error(k, v)
    })

  exit(typeof er.errno === "number" ? er.errno : 1)
}

var writingLogFile = false
function writeLogFile (cb) {
  if (writingLogFile) return cb()
  writingLogFile = true
  wroteLogFile = true

  var fs = require("graceful-fs")
    , fstr = fs.createWriteStream("npm-debug.log")
    , util = require("util")
    , os = require("os")
    , out = ""

  log.record.forEach(function (m) {
    var pref = [m.id, m.level]
    if (m.prefix) pref.push(m.prefix)
    pref = pref.join(' ')

    m.message.trim().split(/\r?\n/).map(function (line) {
      return (pref + ' ' + line).trim()
    }).forEach(function (line) {
      out += line + os.EOL
    })
  })

  fstr.end(out)
  fstr.on("close", cb)
}
<commit_msg>Update EROFS error to be a bit more informative.<commit_after>
module.exports = errorHandler

var cbCalled = false
  , log = require("npmlog")
  , npm = require("../npm.js")
  , rm = require("rimraf")
  , itWorked = false
  , path = require("path")
  , wroteLogFile = false
  , exitCode = 0

process.on("exit", function (code) {
  // console.error("exit", code)
  if (!npm.config || !npm.config.loaded) return
  if (code) itWorked = false
  if (itWorked) log.info("ok")
  else {
    if (!cbCalled) {
      log.error("", "cb() never called!")
    }

    if (wroteLogFile) {
      log.error("", [""
                ,"Additional logging details can be found in:"
                ,"    " + path.resolve("npm-debug.log")
                ].join("\n"))
      wroteLogFile = false
    }
    log.error("not ok", "code", code)
  }

  var doExit = npm.config.get("_exit")
  if (doExit) {
    // actually exit.
    if (exitCode === 0 && !itWorked) {
      exitCode = 1
    }
    if (exitCode !== 0) process.exit(exitCode)
  } else {
    itWorked = false // ready for next exit
  }
})

function exit (code, noLog) {
  exitCode = exitCode || process.exitCode || code

  var doExit = npm.config ? npm.config.get("_exit") : true
  log.verbose("exit", [code, doExit])
  if (log.level === "silent") noLog = true

  if (code && !noLog) writeLogFile(reallyExit)
  else rm("npm-debug.log", function () { rm(npm.tmp, reallyExit) })

  function reallyExit() {
    // truncate once it's been written.
    log.record.length = 0

    itWorked = !code

    // just emit a fake exit event.
    // if we're really exiting, then let it exit on its own, so that
    // in-process stuff can finish or clean up first.
    if (!doExit) process.emit("exit", code)
    npm.spinner.stop()
  }
}

function errorHandler (er) {
  var printStack = false
  // console.error("errorHandler", er)
  if (!npm.config || !npm.config.loaded) {
    // logging won't work unless we pretend that it's ready
    er = er || new Error("Exit prior to config file resolving.")
    console.error(er.stack || er.message)
  }

  if (cbCalled) {
    er = er || new Error("Callback called more than once.")
  }

  cbCalled = true
  if (!er) return exit(0)
  if (typeof er === "string") {
    log.error("", er)
    return exit(1, true)
  } else if (!(er instanceof Error)) {
    log.error("weird error", er)
    return exit(1, true)
  }

  var m = er.code || er.message.match(/^(?:Error: )?(E[A-Z]+)/)
  if (m && !er.code) er.code = m

  switch (er.code) {
  case "ECONNREFUSED":
    log.error("", er)
    log.error("", ["\nIf you are behind a proxy, please make sure that the"
              ,"'proxy' config is set properly.  See: 'npm help config'"
              ].join("\n"))
    printStack = true
    break

  case "EACCES":
  case "EPERM":
    log.error("", er)
    log.error("", ["\nPlease try running this command again as root/Administrator."
              ].join("\n"))
    printStack = true
    break

  case "ELIFECYCLE":
    er.code = "ELIFECYCLE"
    log.error("", er.message)
    log.error("", ["","Failed at the "+er.pkgid+" "+er.stage+" script."
              ,"This is most likely a problem with the "+er.pkgname+" package,"
              ,"not with npm itself."
              ,"Tell the author that this fails on your system:"
              ,"    "+er.script
              ,"You can get their info via:"
              ,"    npm owner ls "+er.pkgname
              ,"There is likely additional logging output above."
              ].join("\n"))
    break

  case "ENOGIT":
    er.code = "ENOGIT"
    log.error("", er.message)
    log.error("", ["","Failed using git."
              ,"This is most likely not a problem with npm itself."
              ,"Please check if you have git installed and in your PATH."
              ].join("\n"))
    break

  case "EJSONPARSE":
    er.code = "EJSONPARSE"
    log.error("", er.message)
    log.error("", "File: "+er.file)
    log.error("", ["Failed to parse package.json data."
              ,"package.json must be actual JSON, not just JavaScript."
              ,"","This is not a bug in npm."
              ,"Tell the package author to fix their package.json file."
              ].join("\n"), "JSON.parse")
    break

  case "E404":
    er.code = "E404"
    var msg = [er.message]
    if (er.pkgid && er.pkgid !== "-") {
      msg.push("", "'"+er.pkgid+"' is not in the npm registry."
              ,"You should bug the author to publish it")
      if (er.parent) {
        msg.push("It was specified as a dependency of '"+er.parent+"'")
      }
      if (er.pkgid.match(/^node[\.\-]|[\.\-]js$/)) {
        var s = er.pkgid.replace(/^node[\.\-]|[\.\-]js$/g, "")
        if (s !== er.pkgid) {
          s = s.replace(/[^a-z0-9]/g, ' ')
          msg.push("\nMaybe try 'npm search " + s + "'")
        }
      }
      msg.push("\nNote that you can also install from a"
              ,"tarball, folder, or http url, or git url.")
    }
    log.error("404", msg.join("\n"))
    break

  case "EPUBLISHCONFLICT":
    er.code = "EPUBLISHCONFLICT"
    log.error("publish fail", ["Cannot publish over existing version."
              ,"Update the 'version' field in package.json and try again."
              ,""
              ,"If the previous version was published in error, see:"
              ,"    npm help unpublish"
              ,""
              ,"To automatically increment version numbers, see:"
              ,"    npm help version"
              ].join("\n"))
    break

  case "EISGIT":
    er.code = "EISGIT"
    log.error("git", [er.message
              ,"    "+er.path
              ,"Refusing to remove it. Update manually,"
              ,"or move it out of the way first."
              ].join("\n"))
    break

  case "ECYCLE":
    er.code = "ECYCLE"
    log.error("cycle", [er.message
              ,"While installing: "+er.pkgid
              ,"Found a pathological dependency case that npm cannot solve."
              ,"Please report this to the package author."
              ].join("\n"))
    break

  case "EBADPLATFORM":
    er.code = "EBADPLATFORM"
    log.error("notsup", [er.message
              ,"Not compatible with your operating system or architecture: "+er.pkgid
              ,"Valid OS:    "+er.os.join(",")
              ,"Valid Arch:  "+er.cpu.join(",")
              ,"Actual OS:   "+process.platform
              ,"Actual Arch: "+process.arch
              ].join("\n"))
    break

  case "EEXIST":
    log.error([er.message
              ,"File exists: "+er.path
              ,"Move it away, and try again."].join("\n"))
    break

  case "ENEEDAUTH":
    log.error("need auth", [er.message
              ,"You need to authorize this machine using `npm adduser`"
              ].join("\n"))
    break

  case "EPEERINVALID":
    var peerErrors = Object.keys(er.peersDepending).map(function (peer) {
      return "Peer " + peer + " wants " + er.packageName + "@"
        + er.peersDepending[peer]
    })
    log.error("peerinvalid", [er.message].concat(peerErrors).join("\n"))
    break

  case "ECONNRESET":
  case "ENOTFOUND":
  case "ETIMEDOUT":
    log.error("network", [er.message
              ,"This is most likely not a problem with npm itself"
              ,"and is related to network connectivity."
              ,"In most cases you are behind a proxy or have bad network settings."
              ,"\nIf you are behind a proxy, please make sure that the"
              ,"'proxy' config is set properly.  See: 'npm help config'"
              ].join("\n"))
    break

  case "ENOPACKAGEJSON":
    log.error("package.json", [er.message
              ,"This is most likely not a problem with npm itself."
              ,"npm can't find a package.json file in your current directory."
              ].join("\n"))
    break

  case "ETARGET":
    log.error("notarget", [er.message
              ,"This is most likely not a problem with npm itself."
              ,"In most cases you or one of your dependencies are requesting"
              ,"a package version that doesn't exist."
              ].join("\n"))
    break

  case "ENOTSUP":
    if (er.required) {
      log.error("notsup", [er.message
                ,"Not compatible with your version of node/npm: "+er.pkgid
                ,"Required: "+JSON.stringify(er.required)
                ,"Actual:   "
                +JSON.stringify({npm:npm.version
                                ,node:npm.config.get("node-version")})
                ].join("\n"))
      break
    } // else passthrough

  case "ENOSPC":
    log.error("nospc", [er.message
              ,"This is most likely not a problem with npm itself"
              ,"and is related to insufficient space on your system."
              ].join("\n"))
    break

  case "EROFS":
    log.error("rofs", [er.message
              ,"This is most likely not a problem with npm itself"
              ,"and is related to the file system being read-only."
              ,"\nOften virtualized file systems, or other file systems"
              ,"that don't support symlinks, give this error."
              ].join("\n"))
    break

  default:
    log.error("", er.stack || er.message || er)
    log.error("", ["If you need help, you may report this *entire* log,"
                  ,"including the npm and node versions, at:"
                  ,"    <http://github.com/npm/npm/issues>"
                  ].join("\n"))
    printStack = false
    break
  }

  var os = require("os")
  // just a line break
  if (log.levels[log.level] <= log.levels.error) console.error("")
  log.error("System", os.type() + " " + os.release())
  log.error("command", process.argv
            .map(JSON.stringify).join(" "))
  log.error("cwd", process.cwd())
  log.error("node -v", process.version)
  log.error("npm -v", npm.version)

  ; [ "file"
    , "path"
    , "type"
    , "syscall"
    , "fstream_path"
    , "fstream_unc_path"
    , "fstream_type"
    , "fstream_class"
    , "fstream_finish_call"
    , "fstream_linkpath"
    , "code"
    , "errno"
    , "stack"
    , "fstream_stack"
    ].forEach(function (k) {
      var v = er[k]
      if (k === "stack") {
        if (!printStack) return
        if (!v) v = er.message
      }
      if (!v) return
      if (k === "fstream_stack") v = v.join("\n")
      log.error(k, v)
    })

  exit(typeof er.errno === "number" ? er.errno : 1)
}

var writingLogFile = false
function writeLogFile (cb) {
  if (writingLogFile) return cb()
  writingLogFile = true
  wroteLogFile = true

  var fs = require("graceful-fs")
    , fstr = fs.createWriteStream("npm-debug.log")
    , util = require("util")
    , os = require("os")
    , out = ""

  log.record.forEach(function (m) {
    var pref = [m.id, m.level]
    if (m.prefix) pref.push(m.prefix)
    pref = pref.join(' ')

    m.message.trim().split(/\r?\n/).map(function (line) {
      return (pref + ' ' + line).trim()
    }).forEach(function (line) {
      out += line + os.EOL
    })
  })

  fstr.end(out)
  fstr.on("close", cb)
}
<|endoftext|>


<commit_before>/*
 * QUnit - jQuery unit testrunner
 *
 * http://docs.jquery.com/QUnit
 *
 * Copyright (c) 2008 John Resig, Jörn Zaefferer
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Id$
 */

(function($) {

var config = {
	Test: [],
	stats: {
		all: 0,
		bad: 0
	},
	queue: [],
	// block until document ready
	blocking: true
};

//restrict modules/tests by get parameters
config.filters = location.search.length > 1 && $.map( location.search.slice(1).split('&'), decodeURIComponent );

var isLocal = !!(window.location.protocol == 'file:');

$(function() {
	$('#userAgent').html(navigator.userAgent);
	runTest();
});

function synchronize(callback) {
	config.queue.push(callback);
	if(!config.blocking) {
		process();
	}
}

function process() {
	while(config.queue.length && !config.blocking) {
		config.queue.shift()();
	}
}

function stop(allowFailure) {
	config.blocking = true;
}
function start() {
	// A slight delay, to avoid any current callbacks
	setTimeout(function() {
		config.blocking = false;
		process();
	}, 13);
}

function validTest( name ) {
	var filters = config.filters;
	if( !filters )
		return true;

	var i = filters.length,
		run = false;
	while( i-- ){
		var filter = filters[i],
			not = filter.charAt(0) == '!';
		if( not )
			filter = filter.slice(1);
		if( name.indexOf(filter) != -1 )
			return !not;
		if( not )
			run = true;
	}
	return run;
}

function runTest() {
	config.blocking = false;
	var started = +new Date;
	config.fixture = document.getElementById('main').innerHTML;
	config.ajaxSettings = $.ajaxSettings;
	synchronize(function() {
		$('
').html(['Tests completed in ',
			+new Date - started, ' milliseconds.
',
			'', config.stats.bad, ' tests of ', config.stats.all, ' failed.
']
			.join(''))
			.appendTo("body");
		$("#banner").addClass(config.stats.bad ? "fail" : "pass");
	});
}

function test(name, callback, nowait) {
	if(config.currentModule)
		name = config.currentModule + " module: " + name;
	var lifecycle = config.moduleLifecycle || {
		setup: function() {},
		teardown: function() {}
	};

	if ( !validTest(name) )
		return;

	synchronize(function() {
		config.Test = [];
		try {
			lifecycle.setup();
			callback();
			lifecycle.teardown();
		} catch(e) {
			if( typeof console != "undefined" && console.error && console.warn ) {
				console.error("Test " + name + " died, exception and test follows");
				console.error(e);
				console.warn(callback.toString());
			}
			config.Test.push( [ false, "Died on test #" + (config.Test.length+1) + ": " + e.message ] );
		}
	});
	synchronize(function() {
		try {
			reset();
		} catch(e) {
			if( typeof console != "undefined" && console.error && console.warn ) {
				console.error("reset() failed, following Test " + name + ", exception and reset fn follows");
				console.error(e);
				console.warn(reset.toString());
			}
		}

		// don't output pause tests
		if(nowait) return;

		if(config.expected && config.expected != config.Test.length) {
			config.Test.push( [ false, "Expected " + config.expected + " assertions, but " + config.Test.length + " were run" ] );
		}
		config.expected = null;

		var good = 0, bad = 0;
		var ol = document.createElement("ol");
		ol.style.display = "none";
		var li = "", state = "pass";
		for ( var i = 0; i < config.Test.length; i++ ) {
			var li = document.createElement("li");
			li.className = config.Test[i][0] ? "pass" : "fail";
			li.appendChild( document.createTextNode(config.Test[i][1]) );
			ol.appendChild( li );

			config.stats.all++;
			if ( !config.Test[i][0] ) {
				state = "fail";
				bad++;
				config.stats.bad++;
			} else good++;
		}

		var li = document.createElement("li");
		li.className = state;

		var b = document.createElement("strong");
		b.innerHTML = name + " (" + bad + ", " + good + ", " + config.Test.length + ")";
		b.onclick = function(){
			var n = this.nextSibling;
			if ( $.css( n, "display" ) == "none" )
				n.style.display = "block";
			else
				n.style.display = "none";
		};
		$(b).dblclick(function(event) {
			var target = $(event.target).filter("strong").clone();
			if ( target.length ) {
				target.children().remove();
				location.href = location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent($.trim(target.text()));
			}
		});
		li.appendChild( b );
		li.appendChild( ol );

		document.getElementById("tests").appendChild( li );
	});
}

// call on start of module test to prepend name to all tests
function module(name, lifecycle) {
	config.currentModule = name;
	config.moduleLifecycle = lifecycle;
}

/**
 * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
 */
function expect(asserts) {
	config.expected = asserts;
}

/**
 * Resets the test setup. Useful for tests that modify the DOM.
 */
function reset() {
	$("#main").html( config.fixture );
	$.event.global = {};
	$.ajaxSettings = $.extend({}, config.ajaxSettings);
}

/**
 * Asserts true.
 * @example ok( $("a").size() > 5, "There must be at least 5 anchors" );
 */
function ok(a, msg) {
	config.Test.push( [ !!a, msg ] );
}

/**
 * Asserts that two arrays are the same
 */
function isSet(a, b, msg) {
	var ret = true;
	if ( a && b && a.length != undefined && a.length == b.length ) {
		for ( var i = 0; i < a.length; i++ )
			if ( a[i] != b[i] )
				ret = false;
	} else
		ret = false;
	if ( !ret )
		config.Test.push( [ ret, msg + " expected: " + serialArray(b) + " result: " + serialArray(a) ] );
	else
		config.Test.push( [ ret, msg ] );
}

/**
 * Asserts that two objects are equivalent
 */
function isObj(a, b, msg) {
	var ret = true;

	if ( a && b ) {
		for ( var i in a )
			if ( a[i] != b[i] )
				ret = false;

		for ( i in b )
			if ( a[i] != b[i] )
				ret = false;
	} else
		ret = false;

    config.Test.push( [ ret, msg ] );
}

function serialArray( a ) {
	var r = [];

	if ( a && a.length )
        for ( var i = 0; i < a.length; i++ ) {
            var str = a[i].nodeName;
            if ( str ) {
                str = str.toLowerCase();
                if ( a[i].id )
                    str += "#" + a[i].id;
            } else
                str = a[i];
            r.push( str );
        }

	return "[ " + r.join(", ") + " ]";
}

function flatMap(a, block) {
	var result = [];
	$.each(a, function() {
		var x = block.apply(this, arguments);
		if (x !== false)
			result.push(x);
	})
	return result;
}

function serialObject( a ) {
	return "{ " + flatMap(a, function(key, value) {
		return key + ": " + value;
	}).join(", ") + " }";
}

function compare(a, b, msg) {
	var ret = true;
	if ( a && b && a.length != undefined && a.length == b.length ) {
		for ( var i = 0; i < a.length; i++ )
			for(var key in a[i]) {
				if (a[i][key].constructor == Array) {
					for (var arrayKey in a[i][key]) {
						if (a[i][key][arrayKey] != b[i][key][arrayKey]) {
							ret = false;
						}
					}
				} else if (a[i][key] != b[i][key]) {
					ret = false
				}
			}
	} else
		ret = false;
	ok( ret, msg + " expected: " + serialArray(b) + " result: " + serialArray(a) );
}

function compare2(a, b, msg) {
	var ret = true;
	if ( a && b ) {
		for(var key in a) {
			if (a[key].constructor == Array) {
				for (var arrayKey in a[key]) {
					if (a[key][arrayKey] != b[key][arrayKey]) {
						ret = false;
					}
				}
			} else if (a[key] != b[key]) {
				ret = false
			}
		}
		for(key in b) {
			if (b[key].constructor == Array) {
				for (var arrayKey in b[key]) {
					if (a[key][arrayKey] != b[key][arrayKey]) {
						ret = false;
					}
				}
			} else if (a[key] != b[key]) {
				ret = false
			}
		}
	} else
		ret = false;
	ok( ret, msg + " expected: " + serialObject(b) + " result: " + serialObject(a) );
}

/**
 * Returns an array of elements with the given IDs, eg.
 * @example q("main", "foo", "bar")
 * @result [
, , <input id="bar">]
 */
function q() {
	var r = [];
	for ( var i = 0; i < arguments.length; i++ )
		r.push( document.getElementById( arguments[i] ) );
	return r;
}

/**
 * Asserts that a select matches the given IDs
 * @example t("Check for something", "//[a]", ["foo", "baar"]);
 * @result returns true if "//[a]" return two elements with the IDs 'foo' and 'baar'
 */
function t(a,b,c) {
	var f = $(b);
	var s = "";
	for ( var i = 0; i < f.length; i++ )
		s += (s && ",") + '"' + f[i].id + '"';
	isSet(f, q.apply(q,c), a + " (" + b + ")");
}

/**
 * Add random number to url to stop IE from caching
 *
 * @example url("data/test.html")
 * @result "data/test.html?10538358428943"
 *
 * @example url("data/test.php?foo=bar")
 * @result "data/test.php?foo=bar&10538358345554"
 */
function url(value) {
	return value + (/\?/.test(value) ? "&" : "?") + new Date().getTime() + "" + parseInt(Math.random()*100000);
}

/**
 * Checks that the first two arguments are equal, with an optional message.
 * Prints out both actual and expected values.
 *
 * Prefered to ok( actual == expected, message )
 *
 * @example equals( $.format("Received {0} bytes.", 2), "Received 2 bytes." );
 *
 * @param Object actual
 * @param Object expected
 * @param String message (optional)
 */
function equals(actual, expected, message) {
	var result = expected == actual;
	message = message || (result ? "okay" : "failed");
	config.Test.push( [ result, result ? message + ": " + expected : message + " expected: " + expected + " actual: " + actual ] );
}

/**
 * Trigger an event on an element.
 *
 * @example triggerEvent( document.body, "click" );
 *
 * @param DOMElement elem
 * @param String type
 */
function triggerEvent( elem, type, event ) {
	if ( $.browser.mozilla || $.browser.opera ) {
		event = document.createEvent("MouseEvents");
		event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
			0, 0, 0, 0, 0, false, false, false, false, 0, null);
		elem.dispatchEvent( event );
	} else if ( $.browser.msie ) {
		elem.fireEvent("on"+type);
	}
}

// public API as global methods
$.extend(window, {
	test: test,
	module: module,
	expect: expect,
	ok: ok,
	equals: equals,
	start: start,
	stop: stop,
	reset: reset,
	isLocal: isLocal,
	// legacy methods below
	isSet: isSet,
	isObj: isObj,
	compare: compare,
	compare2: compare2,
	serialArray: serialArray,
	q: q,
	t: t,
	url: url,
	triggerEvent: triggerEvent
});

})(jQuery);<commit_msg>qunit: allow either setup or teardown, instead of both or nothing<commit_after>/*
 * QUnit - jQuery unit testrunner
 *
 * http://docs.jquery.com/QUnit
 *
 * Copyright (c) 2008 John Resig, Jörn Zaefferer
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Id$
 */

(function($) {

var config = {
	Test: [],
	stats: {
		all: 0,
		bad: 0
	},
	queue: [],
	// block until document ready
	blocking: true
};

//restrict modules/tests by get parameters
config.filters = location.search.length > 1 && $.map( location.search.slice(1).split('&'), decodeURIComponent );

var isLocal = !!(window.location.protocol == 'file:');

$(function() {
	$('#userAgent').html(navigator.userAgent);
	runTest();
});

function synchronize(callback) {
	config.queue.push(callback);
	if(!config.blocking) {
		process();
	}
}

function process() {
	while(config.queue.length && !config.blocking) {
		config.queue.shift()();
	}
}

function stop(allowFailure) {
	config.blocking = true;
}
function start() {
	// A slight delay, to avoid any current callbacks
	setTimeout(function() {
		config.blocking = false;
		process();
	}, 13);
}

function validTest( name ) {
	var filters = config.filters;
	if( !filters )
		return true;

	var i = filters.length,
		run = false;
	while( i-- ){
		var filter = filters[i],
			not = filter.charAt(0) == '!';
		if( not )
			filter = filter.slice(1);
		if( name.indexOf(filter) != -1 )
			return !not;
		if( not )
			run = true;
	}
	return run;
}

function runTest() {
	config.blocking = false;
	var started = +new Date;
	config.fixture = document.getElementById('main').innerHTML;
	config.ajaxSettings = $.ajaxSettings;
	synchronize(function() {
		$('
').html(['Tests completed in ',
			+new Date - started, ' milliseconds.
',
			'', config.stats.bad, ' tests of ', config.stats.all, ' failed.
']
			.join(''))
			.appendTo("body");
		$("#banner").addClass(config.stats.bad ? "fail" : "pass");
	});
}

function test(name, callback, nowait) {
	if(config.currentModule)
		name = config.currentModule + " module: " + name;
	var lifecycle = $.extend({
		setup: function() {},
		teardown: function() {}
	}, config.moduleLifecycle);

	if ( !validTest(name) )
		return;

	synchronize(function() {
		config.Test = [];
		try {
			lifecycle.setup();
			callback();
			lifecycle.teardown();
		} catch(e) {
			if( typeof console != "undefined" && console.error && console.warn ) {
				console.error("Test " + name + " died, exception and test follows");
				console.error(e);
				console.warn(callback.toString());
			}
			config.Test.push( [ false, "Died on test #" + (config.Test.length+1) + ": " + e.message ] );
		}
	});
	synchronize(function() {
		try {
			reset();
		} catch(e) {
			if( typeof console != "undefined" && console.error && console.warn ) {
				console.error("reset() failed, following Test " + name + ", exception and reset fn follows");
				console.error(e);
				console.warn(reset.toString());
			}
		}

		// don't output pause tests
		if(nowait) return;

		if(config.expected && config.expected != config.Test.length) {
			config.Test.push( [ false, "Expected " + config.expected + " assertions, but " + config.Test.length + " were run" ] );
		}
		config.expected = null;

		var good = 0, bad = 0;
		var ol = document.createElement("ol");
		ol.style.display = "none";
		var li = "", state = "pass";
		for ( var i = 0; i < config.Test.length; i++ ) {
			var li = document.createElement("li");
			li.className = config.Test[i][0] ? "pass" : "fail";
			li.appendChild( document.createTextNode(config.Test[i][1]) );
			ol.appendChild( li );

			config.stats.all++;
			if ( !config.Test[i][0] ) {
				state = "fail";
				bad++;
				config.stats.bad++;
			} else good++;
		}

		var li = document.createElement("li");
		li.className = state;

		var b = document.createElement("strong");
		b.innerHTML = name + " (" + bad + ", " + good + ", " + config.Test.length + ")";
		b.onclick = function(){
			var n = this.nextSibling;
			if ( $.css( n, "display" ) == "none" )
				n.style.display = "block";
			else
				n.style.display = "none";
		};
		$(b).dblclick(function(event) {
			var target = $(event.target).filter("strong").clone();
			if ( target.length ) {
				target.children().remove();
				location.href = location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent($.trim(target.text()));
			}
		});
		li.appendChild( b );
		li.appendChild( ol );

		document.getElementById("tests").appendChild( li );
	});
}

// call on start of module test to prepend name to all tests
function module(name, lifecycle) {
	config.currentModule = name;
	config.moduleLifecycle = lifecycle;
}

/**
 * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
 */
function expect(asserts) {
	config.expected = asserts;
}

/**
 * Resets the test setup. Useful for tests that modify the DOM.
 */
function reset() {
	$("#main").html( config.fixture );
	$.event.global = {};
	$.ajaxSettings = $.extend({}, config.ajaxSettings);
}

/**
 * Asserts true.
 * @example ok( $("a").size() > 5, "There must be at least 5 anchors" );
 */
function ok(a, msg) {
	config.Test.push( [ !!a, msg ] );
}

/**
 * Asserts that two arrays are the same
 */
function isSet(a, b, msg) {
	var ret = true;
	if ( a && b && a.length != undefined && a.length == b.length ) {
		for ( var i = 0; i < a.length; i++ )
			if ( a[i] != b[i] )
				ret = false;
	} else
		ret = false;
	if ( !ret )
		config.Test.push( [ ret, msg + " expected: " + serialArray(b) + " result: " + serialArray(a) ] );
	else
		config.Test.push( [ ret, msg ] );
}

/**
 * Asserts that two objects are equivalent
 */
function isObj(a, b, msg) {
	var ret = true;

	if ( a && b ) {
		for ( var i in a )
			if ( a[i] != b[i] )
				ret = false;

		for ( i in b )
			if ( a[i] != b[i] )
				ret = false;
	} else
		ret = false;

    config.Test.push( [ ret, msg ] );
}

function serialArray( a ) {
	var r = [];

	if ( a && a.length )
        for ( var i = 0; i < a.length; i++ ) {
            var str = a[i].nodeName;
            if ( str ) {
                str = str.toLowerCase();
                if ( a[i].id )
                    str += "#" + a[i].id;
            } else
                str = a[i];
            r.push( str );
        }

	return "[ " + r.join(", ") + " ]";
}

function flatMap(a, block) {
	var result = [];
	$.each(a, function() {
		var x = block.apply(this, arguments);
		if (x !== false)
			result.push(x);
	})
	return result;
}

function serialObject( a ) {
	return "{ " + flatMap(a, function(key, value) {
		return key + ": " + value;
	}).join(", ") + " }";
}

function compare(a, b, msg) {
	var ret = true;
	if ( a && b && a.length != undefined && a.length == b.length ) {
		for ( var i = 0; i < a.length; i++ )
			for(var key in a[i]) {
				if (a[i][key].constructor == Array) {
					for (var arrayKey in a[i][key]) {
						if (a[i][key][arrayKey] != b[i][key][arrayKey]) {
							ret = false;
						}
					}
				} else if (a[i][key] != b[i][key]) {
					ret = false
				}
			}
	} else
		ret = false;
	ok( ret, msg + " expected: " + serialArray(b) + " result: " + serialArray(a) );
}

function compare2(a, b, msg) {
	var ret = true;
	if ( a && b ) {
		for(var key in a) {
			if (a[key].constructor == Array) {
				for (var arrayKey in a[key]) {
					if (a[key][arrayKey] != b[key][arrayKey]) {
						ret = false;
					}
				}
			} else if (a[key] != b[key]) {
				ret = false
			}
		}
		for(key in b) {
			if (b[key].constructor == Array) {
				for (var arrayKey in b[key]) {
					if (a[key][arrayKey] != b[key][arrayKey]) {
						ret = false;
					}
				}
			} else if (a[key] != b[key]) {
				ret = false
			}
		}
	} else
		ret = false;
	ok( ret, msg + " expected: " + serialObject(b) + " result: " + serialObject(a) );
}

/**
 * Returns an array of elements with the given IDs, eg.
 * @example q("main", "foo", "bar")
 * @result [
, , <input id="bar">]
 */
function q() {
	var r = [];
	for ( var i = 0; i < arguments.length; i++ )
		r.push( document.getElementById( arguments[i] ) );
	return r;
}

/**
 * Asserts that a select matches the given IDs
 * @example t("Check for something", "//[a]", ["foo", "baar"]);
 * @result returns true if "//[a]" return two elements with the IDs 'foo' and 'baar'
 */
function t(a,b,c) {
	var f = $(b);
	var s = "";
	for ( var i = 0; i < f.length; i++ )
		s += (s && ",") + '"' + f[i].id + '"';
	isSet(f, q.apply(q,c), a + " (" + b + ")");
}

/**
 * Add random number to url to stop IE from caching
 *
 * @example url("data/test.html")
 * @result "data/test.html?10538358428943"
 *
 * @example url("data/test.php?foo=bar")
 * @result "data/test.php?foo=bar&10538358345554"
 */
function url(value) {
	return value + (/\?/.test(value) ? "&" : "?") + new Date().getTime() + "" + parseInt(Math.random()*100000);
}

/**
 * Checks that the first two arguments are equal, with an optional message.
 * Prints out both actual and expected values.
 *
 * Prefered to ok( actual == expected, message )
 *
 * @example equals( $.format("Received {0} bytes.", 2), "Received 2 bytes." );
 *
 * @param Object actual
 * @param Object expected
 * @param String message (optional)
 */
function equals(actual, expected, message) {
	var result = expected == actual;
	message = message || (result ? "okay" : "failed");
	config.Test.push( [ result, result ? message + ": " + expected : message + " expected: " + expected + " actual: " + actual ] );
}

/**
 * Trigger an event on an element.
 *
 * @example triggerEvent( document.body, "click" );
 *
 * @param DOMElement elem
 * @param String type
 */
function triggerEvent( elem, type, event ) {
	if ( $.browser.mozilla || $.browser.opera ) {
		event = document.createEvent("MouseEvents");
		event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
			0, 0, 0, 0, 0, false, false, false, false, 0, null);
		elem.dispatchEvent( event );
	} else if ( $.browser.msie ) {
		elem.fireEvent("on"+type);
	}
}

// public API as global methods
$.extend(window, {
	test: test,
	module: module,
	expect: expect,
	ok: ok,
	equals: equals,
	start: start,
	stop: stop,
	reset: reset,
	isLocal: isLocal,
	// legacy methods below
	isSet: isSet,
	isObj: isObj,
	compare: compare,
	compare2: compare2,
	serialArray: serialArray,
	q: q,
	t: t,
	url: url,
	triggerEvent: triggerEvent
});

})(jQuery);<|endoftext|>


<commit_before>
module.exports = new function() {

  var webdriver = require("selenium-webdriver");

  webdriver.WebDriver.prototype.waitJqueryReady = function() {
    var self = this;

    return self.flow_.execute(function() {
      self.executeScript("return typeof jQuery != String(undefined) ? (!jQuery.active === jQuery.isReady) : null;").then(function(isReady) {
        switch (isReady) {
          case true:
            return true
            break;

          case false:
            self.waitJqueryReady();
            break;

          case null:
            self.controlFlow().timeout(30*1000)
            break;
        }
      })
    }, "WebDriver.waitJqueryReady()");

  }

  return webdriver;
}
<commit_msg>Fix for alert box error<commit_after>
module.exports = new function() {

  var webdriver = require("selenium-webdriver");

  webdriver.WebDriver.prototype.waitJqueryReady = function() {
    var self = this;

    return self.flow_.execute(function() {
      self.switchTo().alert().then(
        function() {
          return true;
        },
        function() {
          self.executeScript("return typeof jQuery != String(undefined) ? (!jQuery.active === jQuery.isReady) : null;").then(function(isReady) {
            switch (isReady) {
              case true:
                return true
              break;

              case false:
                self.waitJqueryReady();
              break;

              case null:
                self.controlFlow().timeout(30*1000)
              break;
            }
          });
        }
      );
    }, "WebDriver.waitJqueryReady()");

  }

  return webdriver;
}
<|endoftext|>


<commit_before>/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/

var path = require('path');
var fs = require('fs-extra');
var Handlebars = require('handlebars');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpack = require('webpack');

var Build = require('@jupyterlab/buildutils').Build;
var package_data = require('./package.json');

// Handle the extensions.
var jlab = package_data.jupyterlab;
var extensions = jlab.extensions;
var mimeExtensions = jlab.mimeExtensions;
Build.ensureAssets({
  packageNames: Object.keys(mimeExtensions).concat(Object.keys(extensions)),
  output: jlab.outputDir
});

// Create the entry point file.
var source = fs.readFileSync('index.js').toString();
var template = Handlebars.compile(source);
var data = {
  jupyterlab_extensions: extensions,
  jupyterlab_mime_extensions: mimeExtensions,
};
var result = template(data);

// Ensure a clear build directory.
var buildDir = path.resolve(jlab.buildDir);
if (fs.existsSync(buildDir)) {
  fs.removeSync(buildDir);
}
fs.ensureDirSync(buildDir);

fs.writeFileSync(path.join(buildDir, 'index.out.js'), result);
fs.copySync('./package.json', path.join(buildDir, 'package.json'));
fs.copySync('./templates/error.html', path.join(buildDir, 'error.html'));

// Set up variables for watch mode.
var localLinked = {};
var ignoreCache = Object.create(null);
Object.keys(jlab.linkedPackages).forEach(function (name) {
  var localPath = require.resolve(path.join(name, 'package.json'));
  localLinked[name] = path.dirname(localPath);
});

/**
 * Sync a local path to a linked package path if they are files and differ.
 */
function maybeSync(localPath, name, rest) {
  var stats = fs.statSync(localPath);
  if (!stats.isFile(localPath)) {
    return;
  }
  var source = fs.realpathSync(path.join(jlab.linkedPackages[name], rest));
  if (source === fs.realpathSync(localPath)) {
    return;
  }
  fs.watchFile(source, { 'interval': 500 }, function(curr) {
    if (!curr || curr.nlink === 0) {
      return;
    }
    try {
      fs.copySync(source, localPath);
    } catch (err) {
      console.error(err);
    }
  });
}

/**
 * A WebPack Plugin that copies the assets to the static directory.
 */
function JupyterLabPlugin() { }

JupyterLabPlugin.prototype.apply = function(compiler) {

  compiler.plugin('after-emit', function(compilation, callback) {
    var staticDir = jlab.staticDir;
    if (!staticDir) {
      callback();
      return;
    }
    // Ensure a clean static directory on the first emit.
    if (this._first && fs.existsSync(staticDir)) {
      fs.removeSync(staticDir);
    }
    this._first = false;
    fs.copySync(buildDir, staticDir);
    callback();
  }.bind(this));
};

JupyterLabPlugin.prototype._first = true;

module.exports = {
  mode: 'development',
  profile: true,
  entry: {
    main: ['whatwg-fetch', path.resolve(buildDir, 'index.out.js')],
    vendor: jlab.vendor
  },
  output: {
    path: path.resolve(buildDir),
    publicPath: jlab.publicUrl || '{{base_url}}lab/static/',
    filename: '[name].[chunkhash].js'
  },
  module: {
    rules: [
      { test: /^JUPYTERLAB_RAW_LOADER_/, use: 'raw-loader' },
      { test: /^JUPYTERLAB_URL_LOADER_/, use: 'url-loader?limit=10000' },
      { test: /^JUPYTERLAB_FILE_LOADER_/, use: 'file-loader' },
      { test: /\.css$/, use: ['style-loader', 'css-loader'] },
      { test: /\.md$/, use: 'raw-loader' },
      { test: /\.txt$/, use: 'raw-loader' },
      { test: /\.js$/, use: ['source-map-loader'], enforce: 'pre',
        // eslint-disable-next-line no-undef
        exclude: /node_modules/
      },
      { test: /\.(jpg|png|gif)$/, use: 'file-loader' },
      { test: /\.js.map$/, use: 'file-loader' },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream' },
      { test: /\.otf(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream' },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, use: 'file-loader' },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=image/svg+xml' }
    ],
  },
  watchOptions: {
    ignored: function(localPath) {
      localPath = path.resolve(localPath);
      if (localPath in ignoreCache) {
        return ignoreCache[localPath];
      }
      // Limit the watched files to those in our local linked package dirs.
      var ignore = true;
      Object.keys(localLinked).some(function (name) {
        // Bail if already found.
        var rootPath = localLinked[name];
        var contained = localPath.indexOf(rootPath + path.sep) !== -1;
        if (localPath !== rootPath && !contained) {
          return false;
        }
        var rest = localPath.slice(rootPath.length);
        if (rest.indexOf('node_modules') === -1) {
          ignore = false;
          maybeSync(localPath, name, rest);
        }
        return true;
      });
      ignoreCache[localPath] = ignore;
      return ignore;
    }
  },
  node: {
    fs: 'empty'
  },
  bail: true,
  devtool: 'source-map',
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join('templates', 'template.html'),
      title: jlab.name || 'JupyterLab'
    }),
    new webpack.HashedModuleIdsPlugin(),
    new JupyterLabPlugin({})
  ]
};
<commit_msg>Split out the vega-* packages which are large and not always needed.<commit_after>/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/

var path = require('path');
var fs = require('fs-extra');
var Handlebars = require('handlebars');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpack = require('webpack');

var Build = require('@jupyterlab/buildutils').Build;
var package_data = require('./package.json');

// Handle the extensions.
var jlab = package_data.jupyterlab;
var extensions = jlab.extensions;
var mimeExtensions = jlab.mimeExtensions;
Build.ensureAssets({
  packageNames: Object.keys(mimeExtensions).concat(Object.keys(extensions)),
  output: jlab.outputDir
});

// Create the entry point file.
var source = fs.readFileSync('index.js').toString();
var template = Handlebars.compile(source);
var data = {
  jupyterlab_extensions: extensions,
  jupyterlab_mime_extensions: mimeExtensions,
};
var result = template(data);

// Ensure a clear build directory.
var buildDir = path.resolve(jlab.buildDir);
if (fs.existsSync(buildDir)) {
  fs.removeSync(buildDir);
}
fs.ensureDirSync(buildDir);

fs.writeFileSync(path.join(buildDir, 'index.out.js'), result);
fs.copySync('./package.json', path.join(buildDir, 'package.json'));
fs.copySync('./templates/error.html', path.join(buildDir, 'error.html'));

// Set up variables for watch mode.
var localLinked = {};
var ignoreCache = Object.create(null);
Object.keys(jlab.linkedPackages).forEach(function (name) {
  var localPath = require.resolve(path.join(name, 'package.json'));
  localLinked[name] = path.dirname(localPath);
});

/**
 * Sync a local path to a linked package path if they are files and differ.
 */
function maybeSync(localPath, name, rest) {
  var stats = fs.statSync(localPath);
  if (!stats.isFile(localPath)) {
    return;
  }
  var source = fs.realpathSync(path.join(jlab.linkedPackages[name], rest));
  if (source === fs.realpathSync(localPath)) {
    return;
  }
  fs.watchFile(source, { 'interval': 500 }, function(curr) {
    if (!curr || curr.nlink === 0) {
      return;
    }
    try {
      fs.copySync(source, localPath);
    } catch (err) {
      console.error(err);
    }
  });
}

/**
 * A WebPack Plugin that copies the assets to the static directory.
 */
function JupyterLabPlugin() { }

JupyterLabPlugin.prototype.apply = function(compiler) {

  compiler.plugin('after-emit', function(compilation, callback) {
    var staticDir = jlab.staticDir;
    if (!staticDir) {
      callback();
      return;
    }
    // Ensure a clean static directory on the first emit.
    if (this._first && fs.existsSync(staticDir)) {
      fs.removeSync(staticDir);
    }
    this._first = false;
    fs.copySync(buildDir, staticDir);
    callback();
  }.bind(this));
};

JupyterLabPlugin.prototype._first = true;

module.exports = {
  mode: 'development',
  profile: true,
  entry: {
    main: ['whatwg-fetch', path.resolve(buildDir, 'index.out.js')]
  },
  output: {
    path: path.resolve(buildDir),
    publicPath: jlab.publicUrl || '{{base_url}}lab/static/',
    filename: '[name].[chunkhash].js'
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        // Split out the vega files, which are large and not always needed.
        vega: {
          test: /[\\/]node_modules[\\/]vega/
        }
      }
    }
  },
  module: {
    rules: [
      { test: /^JUPYTERLAB_RAW_LOADER_/, use: 'raw-loader' },
      { test: /^JUPYTERLAB_URL_LOADER_/, use: 'url-loader?limit=10000' },
      { test: /^JUPYTERLAB_FILE_LOADER_/, use: 'file-loader' },
      { test: /\.css$/, use: ['style-loader', 'css-loader'] },
      { test: /\.md$/, use: 'raw-loader' },
      { test: /\.txt$/, use: 'raw-loader' },
      { test: /\.js$/, use: ['source-map-loader'], enforce: 'pre',
        // eslint-disable-next-line no-undef
        exclude: /node_modules/
      },
      { test: /\.(jpg|png|gif)$/, use: 'file-loader' },
      { test: /\.js.map$/, use: 'file-loader' },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream' },
      { test: /\.otf(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream' },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, use: 'file-loader' },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=image/svg+xml' }
    ],
  },
  watchOptions: {
    ignored: function(localPath) {
      localPath = path.resolve(localPath);
      if (localPath in ignoreCache) {
        return ignoreCache[localPath];
      }
      // Limit the watched files to those in our local linked package dirs.
      var ignore = true;
      Object.keys(localLinked).some(function (name) {
        // Bail if already found.
        var rootPath = localLinked[name];
        var contained = localPath.indexOf(rootPath + path.sep) !== -1;
        if (localPath !== rootPath && !contained) {
          return false;
        }
        var rest = localPath.slice(rootPath.length);
        if (rest.indexOf('node_modules') === -1) {
          ignore = false;
          maybeSync(localPath, name, rest);
        }
        return true;
      });
      ignoreCache[localPath] = ignore;
      return ignore;
    }
  },
  node: {
    fs: 'empty'
  },
  bail: true,
  devtool: 'source-map',
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join('templates', 'template.html'),
      title: jlab.name || 'JupyterLab'
    }),
    new webpack.HashedModuleIdsPlugin(),
    new JupyterLabPlugin({})
  ]
};
<|endoftext|>


<commit_before>var ALLOWED_NUMBER_OF_DIGITS_AFTER_DECIMAL = 1;

var measurement = {
    getData: function (includeObject) {
        var formattedstudentListArray = [];
        var data = null;
        $.ajax({
            async: false,
            url: "/clinician/patient/patientMeasurements?patientUUID=" + includeObject.patientUUID + "&attributeName=" + includeObject.attributeName,
            dataType: "json",
            success: function (measurements) {
                data = measurements;
            },
            error: function(request, status, error) {
            	showDefaultErrorDiv();
            }
        });
        return data;
    },

    createChartData: function (jsonData, includeObject) {
    	var colors = jsonData.mapQuestionnaireColor('value');
        return {
            labels: jsonData.timeMapProperty('dataTime'),
            datasets: [
                {
                    label: "",
                    borderColor: colors,
                    backgroundColor: colors,
                    fill: false,
                    data: jsonData.mapQuestionnaire('value'),
                    lineTension: 0
                }
            ]
        };
    },
    renderChart: function (chartData, includeObject) {
        var context2D = document.getElementById(includeObject.canvasId).getContext("2d");
        var timeFormat = 'DD/MM/YYYY HH:mm';
        var myChart = new Chart(context2D, {
            type: 'bar',
            data: chartData,
            options: {
                responsive: true,
            	elements: {
                    point:{
                        radius: 0
                    }
                },
                scales: {
                	xAxes: [{
                		type: "time",
                		time: {
                			format: timeFormat,
                			tooltipFormat: 'll HH:mm'
                		},
                		scaleLabel: {
                			display: true,
                		}
                	},
                ],
                yAxes: [{
                        display: true,
                        scaleLabel: {
                            show: false,
                        },
                        ticks: {
                            suggestedMin: -1,
                            suggestedMax: 1,
                        }
                    }]
                },
                legend: {
                    display: false,
                }
            }
        });
        return myChart;
    },

    initChart: function (includeObject) {
        var measurements = measurement.getData(includeObject);
        chartData = measurement.createChartData(measurements, includeObject);
        measurement.renderChart(chartData, includeObject);
    }
};<commit_msg>Added parameter for controlling the width of the bar.<commit_after>var ALLOWED_NUMBER_OF_DIGITS_AFTER_DECIMAL = 1;

var measurement = {
    getData: function (includeObject) {
        var formattedstudentListArray = [];
        var data = null;
        $.ajax({
            async: false,
            url: "/clinician/patient/patientMeasurements?patientUUID=" + includeObject.patientUUID + "&attributeName=" + includeObject.attributeName,
            dataType: "json",
            success: function (measurements) {
                data = measurements;
            },
            error: function(request, status, error) {
            	showDefaultErrorDiv();
            }
        });
        return data;
    },

    createChartData: function (jsonData, includeObject) {
    	var colors = jsonData.mapQuestionnaireColor('value');
        return {
            labels: jsonData.timeMapProperty('dataTime'),
            datasets: [
                {
                    label: "",
                    borderColor: colors,
                    backgroundColor: colors,
                    fill: false,
                    data: jsonData.mapQuestionnaire('value'),
                    lineTension: 0
                }
            ]
        };
    },
    renderChart: function (chartData, includeObject) {
        var context2D = document.getElementById(includeObject.canvasId).getContext("2d");
        var timeFormat = 'DD/MM/YYYY HH:mm';
        var myChart = new Chart(context2D, {
            type: 'bar',
            data: chartData,
            options: {
                responsive: true,
            	elements: {
                    point:{
                        radius: 0
                    }
                },
                scales: {
                	xAxes: [{
                		type: "time",
                		barPercentage: 0.05,
                		time: {
                			format: timeFormat,
                			tooltipFormat: 'll HH:mm'
                		},
                		scaleLabel: {
                			display: true,
                		}
                	},
                ],
                yAxes: [{
                        display: true,
                        scaleLabel: {
                            show: false,
                        },
                        ticks: {
                            suggestedMin: -1,
                            suggestedMax: 1,
                        }
                    }]
                },
                legend: {
                    display: false,
                }
            }
        });
        return myChart;
    },

    initChart: function (includeObject) {
        var measurements = measurement.getData(includeObject);
        chartData = measurement.createChartData(measurements, includeObject);
        measurement.renderChart(chartData, includeObject);
    }
};<|endoftext|>


<commit_before>describe('Landing page', function() {
  it('should have the correct title', function(done, server, client) {
    var title = client.evalSync(function() {
      var titleText = $('title').text();

      emit('return', titleText);
    });

    title.should.equal('NEBUL4');

    done();
  });
});

describe('Gameplay', function() {
  it('up arrow should move ship forwards', function(done, server, client) {
    var position = client.evalSync(function() {
      var initial = 0, after = 0;

      App.container.on('playerLoaded', function() {
        initial = App.player.position.z;

        App.pushKey('up');
      });

      App.container.on('playerChanged', function() {
        after = App.player.position.z;

        emit('return', { initial: initial, after: after });
      });
    });

    position.initial.should.be.exactly(0);
    position.after.should.be.exactly(0.1);

    done();
  });

  it('konami code should work', function(done, server, client) {
    var codeDidTrigger = client.evalSync(function() {

      App.container.on('playerLoaded', function() {
        App.pushKeys('up up down down left right left right b a', 1);
      });

      App.container.on('konami', function() {
        emit('return', true);
      });
    });

    codeDidTrigger.should.equal(true);

    done();
  });
});
<commit_msg>Fooling around with the tests<commit_after>describe('Landing page', function() {
  it('should have the correct title', function(done, server, client) {
    var title = client.evalSync(function() {
      var titleText = $('title').text();

      emit('return', titleText);
    });

    title.should.equal('NEBUL4');

    done();
  });
});

describe('Gameplay', function() {
  it('up arrow should move ship forwards', function(done, server, client) {
    var position = client.evalSync(function() {
      var initial = 0, after = 0;

      console.log(App.container);
      emit('return', { initial: initial, after: after });
      // App.container.on('playerLoaded', function(e, player) {
      //   initial = player.position.z;
      //
      //   App.pushKey('up');
      // });
      //
      // App.container.on('playerChanged', function(e, player) {
      //   after = player.position.z;
      //
      //   emit('return', { initial: initial, after: after });
      // });
    });

    position.initial.should.be.exactly(0);
    console.log(position.after);
    // position.after.should.be.exactly(0.1);

    done();
  });

  // it('konami code should work', function(done, server, client) {
  //   var codeDidTrigger = client.evalSync(function() {
  //
  //     App.container.on('playerLoaded', function() {
  //       App.pushKeys('up up down down left right left right b a', 1);
  //     });
  //
  //     App.container.on('konami', function() {
  //       emit('return', true);
  //     });
  //   });
  //
  //   codeDidTrigger.should.equal(true);
  //
  //   done();
  // });
});
<|endoftext|>


<commit_before>//= wrapped

/*
    NOTE: This file is used by the create-ng-domain action.
    You can modify or extend the DomainServiceFactory but it is recommended that you not delete it.
*/

angular
    .module("@grails.codegen.defaultPackage@.core")
    .factory("DomainServiceFactory", DomainServiceFactory);

function DomainServiceFactory($resource) {
    return function(url, paramDefaults, actions, options) {
        return $resource(
            url,
            paramDefaults || null,
            actions || {"update": {method: "PUT"}, "list": {method: "GET", isArray: true}},
            options || {}
        );
    }
}

<commit_msg>Extend the actions property<commit_after>//= wrapped

/*
    NOTE: This file is used by the create-ng-domain action.
    You can modify or extend the DomainServiceFactory but it is recommended that you not delete it.
*/

angular
    .module("@grails.codegen.defaultPackage@.core")
    .factory("DomainServiceFactory", DomainServiceFactory);

function DomainServiceFactory($resource) {
    return function(url, paramDefaults, actions, options) {
        var resourceActions = {"update": {method: "PUT"}, "list": {method: "GET", isArray: true}};
        angular.extend(resourceActions, actions);

        return $resource(
            url,
            paramDefaults || null,
            resourceActions,
            options || {}
        );
    }
}

<|endoftext|>


<commit_before>process.argv.forEach(function(val, index, array) {
	console.log(index + ': ' + val);
});

console.log(process.argv);
<commit_msg>Tidy up<commit_after><|endoftext|>


<commit_before>'use strict'

import React, {
	Component,
	StyleSheet,
	Text,
	View,
	Image,
	ListView
} from 'react-native'

const MOVIE_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json'

class Movie extends Component {
	constructor(props) {
		super(props);
		this.state = {
			dataSource: new ListView.DataSource({
				rowHasChanged: (row1, row2) => row1 !== row2
			}),
			loaded: false
		}
	}

	componentDidMount() {
		this.fetchData()
	}

	fetchData() {
		fetch(MOVIE_URL)
			.then((response) => response.json())
			.then((responseData) => {
				this.setState({
					dataSource: this.state.dataSource.cloneWithRows(responseData.movies),
					loaded: true
				})
			})
			.catch(function(err) {
				alert(err)
			})
			.done()
	}

	render() {
		if (!this.state.loaded) {
			return this.renderLoadingView()
		}
		/*let movie = this.state.movies_data[0];
		return this.renderMovie(movie);*/
		return (
			<ListView
       			 style={styles.listView}
        		 dataSource={this.state.dataSource}
       			 renderRow={ this.renderMovie} />
		)
	}

	renderLoadingView() {
		return (
			<View style={styles.container}>
            <Text>
                正在加载电影数据.....
            </Text>
          </View>
		)
	}

	renderMovie(movie) {
		return (
			<View style={styles.container}>
                <Image
                  style={styles.image}
                  source={{uri: movie.posters.thumbnail}} />
                <View style={styles.rightContainer}>
                    <Text style={styles.title}>{movie.title}</Text>
                    <Text style={styles.year}>{movie.year}</Text>
                </View>
          </View>
		)
	}

}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		backgroundColor: '#F5FCFF',
		paddingLeft: 20
	},
	rightContainer: {
		flex: 1
	},
	image: {
		width: 53,
		height: 81,
	},
	title: {
		fontSize: 20,
		marginBottom: 8,
		textAlign: 'center'
	},
	year: {
		textAlign: 'center'
	},
	listView: {
		paddingTop: 20,
		backgroundColor: "#F5FCFF"
	}
})

export default Movie<commit_msg>format<commit_after>'use strict'

import React, {
	Component,
	StyleSheet,
	Text,
	View,
	Image,
	ListView
} from 'react-native'

const MOVIE_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json'

class Movie extends Component {
	constructor(props) {
		super(props);
		this.state = {
			dataSource: new ListView.DataSource({
				rowHasChanged: (row1, row2) => row1 !== row2
			}),
			loaded: false
		}
	}

	componentDidMount() {
		this.fetchData()
	}

	fetchData() {
		fetch(MOVIE_URL)
			.then((response) => response.json())
			.then((responseData) => {
				this.setState({
					dataSource: this.state.dataSource.cloneWithRows(responseData.movies),
					loaded: true
				})
			})
			.catch(function(err) {
				alert(err)
			})
			.done()
		}
	render() {
		if (!this.state.loaded) {
			return this.renderLoadingView()
		}

		return (
			<ListView
					style={styles.listView}
					dataSource={this.state.dataSource}
					renderRow={ this.renderMovie} />
		)
	}

	renderLoadingView() {
		return (
			<View style={styles.container}>
				<Text>
					正在加载电影数据.....
				</Text>
			</View>
		)
	}

	renderMovie(movie) {
		return (
			<View style={styles.container}>
        <Image
          style={styles.image}
          source={{uri: movie.posters.thumbnail}} />
        <View style={styles.rightContainer}>
            <Text style={styles.title}>{movie.title}</Text>
            <Text style={styles.year}>{movie.year}</Text>
        </View>
			</View>
		)
	}

}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		backgroundColor: '#F5FCFF',
		paddingLeft: 20
	},
	rightContainer: {
		flex: 1
	},
	image: {
		width: 53,
		height: 81,
	},
	title: {
		fontSize: 20,
		marginBottom: 8,
		textAlign: 'center'
	},
	year: {
		textAlign: 'center'
	},
	listView: {
		paddingTop: 20,
		backgroundColor: "#F5FCFF"
	}
})

export default Movie<|endoftext|>


<commit_before>describe('Valencia-Tech Repair Database website', function() {

  beforeEach(function () {
        browser.get('http://localhost:3000');
    });

    /*---------------------------------------------*/

  it('should have a title', function(){
        expect(browser.getTitle()).toEqual('Valencia Tech Repair');
    });

})// End main test funcction
<commit_msg>Rework of test file due to Protractor error<commit_after>describe('Valencia-Tech Repair Database website', function() {

    /*---------------------------------------------*/

  it('should have a title', function(){
        browser.get('http://localhost:3000');
        expect(browser.getTitle()).toEqual('Valencia Tech Repair');
    });

})// End main test funcction
<|endoftext|>


<commit_before>
// REQUEST HANDLING //////////////////////////////////////////////////
// note: only meant for portal/links/fields request, everything else
// does not count towards “loading”

window.activeRequests = [];
window.failedRequestCount = 0;
window.statusTotalMapTiles = 0;
window.statusCachedMapTiles = 0;
window.statusSuccessMapTiles = 0;
window.statusStaleMapTiles = 0;
window.statusErrorMapTiles = 0;

window.requests = function() {}

//time of last refresh
window.requests._lastRefreshTime = 0;
window.requests._quickRefreshPending = false;

window.requests.add = function(ajax) {
  window.activeRequests.push(ajax);
  renderUpdateStatus();
}

window.requests.remove = function(ajax) {
  window.activeRequests.splice(window.activeRequests.indexOf(ajax), 1);
  renderUpdateStatus();
}

window.requests.abort = function() {
  $.each(window.activeRequests, function(ind, actReq) {
    if(actReq) actReq.abort();
  });

  window.activeRequests = [];
  window.failedRequestCount = 0;
  window.chat._requestPublicRunning  = false;
  window.chat._requestFactionRunning  = false;

  renderUpdateStatus();
}

// gives user feedback about pending operations. Draws current status
// to website. Updates info in layer chooser.
window.renderUpdateStatus = function() {

  var t = '';
  if(!window.isSmartphone()) // space is valueable
    t += 'portals: ';
  var minlvl = getMinPortalLevel();
  if(minlvl === 0)
    t+= 'all';
  else
    t+= 'L'+minlvl+(minlvl<8?'+':'') + '';
  t +='';

  t += ' map: ';
  if(mapRunsUserAction)
    t += 'paused</span';
  else if(isIdle())
    t += 'Idle';
  else if(window.requests._quickRefreshPending)
    t += 'refreshing';
  else if(window.activeRequests.length > 0)
    t += window.activeRequests.length + ' requests';
  else {
    // tooltip with detailed tile counts
    t += '';

    // basic error/out of date/up to date message
    if (window.statusErrorMapTiles) t += 'Errors';
    else if (window.statusStaleMapTiles) t += 'Out of date';
    else t += 'Up to date';

    t += '';

  }
  t += '';

  if(renderLimitReached())
    t += ' RENDER LIMIT'

  if(window.failedRequestCount > 0)
    t += ' ' + window.failedRequestCount + ' failed'

  var portalSelection = $('.leaflet-control-layers-overlays label');
  //it's an array - 0=unclaimed, 1=lvl 1, 2=lvl 2, ..., 8=lvl 8 - 9 relevant entries
  //mark all levels below (but not at) minlvl as disabled
  portalSelection.slice(0, minlvl).addClass('disabled').attr('title', 'Zoom in to show those.');
  //and all from minlvl to 8 as enabled
  portalSelection.slice(minlvl, 8+1).removeClass('disabled').attr('title', '');

  $('#innerstatus').html(t);
  //$('#updatestatus').click(function() { startRefreshTimeout(10); });
  //. ⟳';
}

// sets the timer for the next auto refresh. Ensures only one timeout
// is queued. May be given 'override' in milliseconds if time should
// not be guessed automatically. Especially useful if a little delay
// is required, for example when zooming.
window.startRefreshTimeout = function(override) {
  // may be required to remove 'paused during interaction' message in
  // status bar
  window.renderUpdateStatus();
  if(refreshTimeout) clearTimeout(refreshTimeout);
  if(override == -1) return;  //don't set a new timeout

  var t = 0;
  if(override) {
    window.requests._quickRefreshPending = true;
    t = override;
    //ensure override can't cause too fast a refresh if repeatedly used (e.g. lots of scrolling/zooming)
    timeSinceLastRefresh = new Date().getTime()-window.requests._lastRefreshTime;
    if(timeSinceLastRefresh < 0) timeSinceLastRefresh = 0;  //in case of clock adjustments
    if(timeSinceLastRefresh < MINIMUM_OVERRIDE_REFRESH*1000)
      t = (MINIMUM_OVERRIDE_REFRESH*1000-timeSinceLastRefresh);
  } else {
    window.requests._quickRefreshPending = false;
    t = REFRESH*1000;
    var adj = ZOOM_LEVEL_ADJ * (18 - window.map.getZoom());
    if(adj > 0) t += adj*1000;
  }
  var next = new Date(new Date().getTime() + t).toLocaleTimeString();
  console.log('planned refresh in ' + (t/1000) + ' seconds, at ' + next);
  refreshTimeout = setTimeout(window.requests._callOnRefreshFunctions, t);
  renderUpdateStatus();
}

window.requests._onRefreshFunctions = [];
window.requests._callOnRefreshFunctions = function() {
  console.log('running refresh at ' + new Date().toLocaleTimeString());
  startRefreshTimeout();

  if(isIdle()) {
    console.log('user has been idle for ' + idleTime + ' seconds, or window hidden. Skipping refresh.');
    renderUpdateStatus();
    return;
  }

  console.log('refreshing');

  //store the timestamp of this refresh
  window.requests._lastRefreshTime = new Date().getTime();

  $.each(window.requests._onRefreshFunctions, function(ind, f) {
    f();
  });
}

// add method here to be notified of auto-refreshes
window.requests.addRefreshFunction = function(f) {
  window.requests._onRefreshFunctions.push(f);
}

window.requests.isLastRequest = function(action) {
  var result = true;
  $.each(window.activeRequests, function(ind, req) {
    if(req.action === action) {
      result = false;
      return false;
    }
  });
  return result;
}
<commit_msg>increase refresh timeout considerably when zoomed out. this will reduce requests to the servers when lots of data is visible also, with the new higher tile count when zoomed out (#491) it reduces the odds of a new refresh starting before the old ones have finished<commit_after>
// REQUEST HANDLING //////////////////////////////////////////////////
// note: only meant for portal/links/fields request, everything else
// does not count towards “loading”

window.activeRequests = [];
window.failedRequestCount = 0;
window.statusTotalMapTiles = 0;
window.statusCachedMapTiles = 0;
window.statusSuccessMapTiles = 0;
window.statusStaleMapTiles = 0;
window.statusErrorMapTiles = 0;

window.requests = function() {}

//time of last refresh
window.requests._lastRefreshTime = 0;
window.requests._quickRefreshPending = false;

window.requests.add = function(ajax) {
  window.activeRequests.push(ajax);
  renderUpdateStatus();
}

window.requests.remove = function(ajax) {
  window.activeRequests.splice(window.activeRequests.indexOf(ajax), 1);
  renderUpdateStatus();
}

window.requests.abort = function() {
  $.each(window.activeRequests, function(ind, actReq) {
    if(actReq) actReq.abort();
  });

  window.activeRequests = [];
  window.failedRequestCount = 0;
  window.chat._requestPublicRunning  = false;
  window.chat._requestFactionRunning  = false;

  renderUpdateStatus();
}

// gives user feedback about pending operations. Draws current status
// to website. Updates info in layer chooser.
window.renderUpdateStatus = function() {

  var t = '';
  if(!window.isSmartphone()) // space is valueable
    t += 'portals: ';
  var minlvl = getMinPortalLevel();
  if(minlvl === 0)
    t+= 'all';
  else
    t+= 'L'+minlvl+(minlvl<8?'+':'') + '';
  t +='';

  t += ' map: ';
  if(mapRunsUserAction)
    t += 'paused</span';
  else if(isIdle())
    t += 'Idle';
  else if(window.requests._quickRefreshPending)
    t += 'refreshing';
  else if(window.activeRequests.length > 0)
    t += window.activeRequests.length + ' requests';
  else {
    // tooltip with detailed tile counts
    t += '';

    // basic error/out of date/up to date message
    if (window.statusErrorMapTiles) t += 'Errors';
    else if (window.statusStaleMapTiles) t += 'Out of date';
    else t += 'Up to date';

    t += '';

  }
  t += '';

  if(renderLimitReached())
    t += ' RENDER LIMIT'

  if(window.failedRequestCount > 0)
    t += ' ' + window.failedRequestCount + ' failed'

  var portalSelection = $('.leaflet-control-layers-overlays label');
  //it's an array - 0=unclaimed, 1=lvl 1, 2=lvl 2, ..., 8=lvl 8 - 9 relevant entries
  //mark all levels below (but not at) minlvl as disabled
  portalSelection.slice(0, minlvl).addClass('disabled').attr('title', 'Zoom in to show those.');
  //and all from minlvl to 8 as enabled
  portalSelection.slice(minlvl, 8+1).removeClass('disabled').attr('title', '');

  $('#innerstatus').html(t);
  //$('#updatestatus').click(function() { startRefreshTimeout(10); });
  //. ⟳';
}

// sets the timer for the next auto refresh. Ensures only one timeout
// is queued. May be given 'override' in milliseconds if time should
// not be guessed automatically. Especially useful if a little delay
// is required, for example when zooming.
window.startRefreshTimeout = function(override) {
  // may be required to remove 'paused during interaction' message in
  // status bar
  window.renderUpdateStatus();
  if(refreshTimeout) clearTimeout(refreshTimeout);
  if(override == -1) return;  //don't set a new timeout

  var t = 0;
  if(override) {
    window.requests._quickRefreshPending = true;
    t = override;
    //ensure override can't cause too fast a refresh if repeatedly used (e.g. lots of scrolling/zooming)
    timeSinceLastRefresh = new Date().getTime()-window.requests._lastRefreshTime;
    if(timeSinceLastRefresh < 0) timeSinceLastRefresh = 0;  //in case of clock adjustments
    if(timeSinceLastRefresh < MINIMUM_OVERRIDE_REFRESH*1000)
      t = (MINIMUM_OVERRIDE_REFRESH*1000-timeSinceLastRefresh);
  } else {
    window.requests._quickRefreshPending = false;
    t = REFRESH*1000;

    // new getThinnedEntitiesV4 involves a LOT more requests when zoomed out above a data level of 13
    // so, to give the refresh a chance to complete (and also reduce load on niantic servers), boost the refresh interval
    // in this case
    // (TODO: complete rewrite of refresh+request handling. don't start timer until complete, and retry error=TIMEOUT requests)
    if (getPortalDataZoom() <=12 ) t = t*4;

    var adj = ZOOM_LEVEL_ADJ * (18 - getPortalDataZoom());
    if(adj > 0) t += adj*1000;
  }
  var next = new Date(new Date().getTime() + t).toLocaleTimeString();
  console.log('planned refresh in ' + (t/1000) + ' seconds, at ' + next);
  refreshTimeout = setTimeout(window.requests._callOnRefreshFunctions, t);
  renderUpdateStatus();
}

window.requests._onRefreshFunctions = [];
window.requests._callOnRefreshFunctions = function() {
  console.log('running refresh at ' + new Date().toLocaleTimeString());
  startRefreshTimeout();

  if(isIdle()) {
    console.log('user has been idle for ' + idleTime + ' seconds, or window hidden. Skipping refresh.');
    renderUpdateStatus();
    return;
  }

  console.log('refreshing');

  //store the timestamp of this refresh
  window.requests._lastRefreshTime = new Date().getTime();

  $.each(window.requests._onRefreshFunctions, function(ind, f) {
    f();
  });
}

// add method here to be notified of auto-refreshes
window.requests.addRefreshFunction = function(f) {
  window.requests._onRefreshFunctions.push(f);
}

window.requests.isLastRequest = function(action) {
  var result = true;
  $.each(window.activeRequests, function(ind, req) {
    if(req.action === action) {
      result = false;
      return false;
    }
  });
  return result;
}
<|endoftext|>


<commit_before>
describe("Checking SubclassJS initialization", function() {

    it ("", function() {
        expect(Subclass.issetPlugin('SubclassParameter')).toBe(true);
        expect(Subclass.issetPlugin('SubclassService')).toBe(true);
    });
});

describe("Checking services", function() {

    it ("existence", function() {
        expect(app.issetService('search')).toBe(true);
        expect(app.issetService('search_engine')).toBe(true);
        expect(app.issetService('search_mysql_engine')).toBe(true);
        expect(app.issetService('search_solr_engine')).toBe(true);
        expect(app.issetService('search_sphinx_engine')).toBe(true);
    });

    it ("creation", function() {
        var search = app.getService('search');
        var searchAnother = app.getService('search');
        expect(search.getMode()).toBe('dev');
        expect(search._extraArg).toBe('extraArg');
        expect(search._extraCalled).toBe(true);
        expect(search._serviceManager instanceof Subclass.Service.ServiceManager).toBe(true);

        expect(search == searchAnother).toBe(true);
        expect(search.isError()).toBe(true);
        expect(search.getCache()).toBe(true);

        var searchEngines = Object.keys(search.getEngines());
        expect(searchEngines).toContain('mysql');
        expect(searchEngines).toContain('solr');
        expect(searchEngines).toContain('sphinx');

        expect(search.getUsedEngine().getName()).toBe('mysql');
        expect(search.search(['word'])).toBe('Mysql search results of keywords: "word"');

        search.setUsedEngine('solr');
        expect(search.search(['word'])).toBe('Solr search results of keywords: "word"');

        search.setUsedEngine('sphinx');
        expect(search.search(['word'])).toBe('Sphinx search results of keywords: "word"');

        var mySearch = app.getService('my_search');
        expect(mySearch.search(['word'])).toBe('Search words "word" using engine "solr". (custom search)');

        var myMysqlEngine = search.getEngine('mysql');
        expect(myMysqlEngine.getMode()).toBe('dev');
    });

    it ("not allowed actions", function() {

    });
});<commit_msg>Fixed bugs<commit_after>
describe("Checking SubclassJS initialization", function() {

    it ("", function() {
        expect(Subclass.issetPlugin('SubclassParameter')).toBe(true);
        expect(Subclass.issetPlugin('SubclassService')).toBe(true);
    });
});

describe("Checking services", function() {

    it ("existence", function() {
        expect(app.issetService('search')).toBe(true);
        expect(app.issetService('search_engine')).toBe(true);
        expect(app.issetService('search_mysql_engine')).toBe(true);
        expect(app.issetService('search_solr_engine')).toBe(true);
        expect(app.issetService('search_sphinx_engine')).toBe(true);
    });

    it ("creation", function() {
        var search = app.getService('search');
        var searchAnother = app.getService('search');

        //console.log(Object.keys(app.getServiceManager().getServices()));
        //console.log(app.getServiceManager().getServicesByTag('search'));

        expect(search.getMode()).toBe('dev');
        expect(search._extraArg).toBe('extraArg');
        expect(search._extraCalled).toBe(true);
        expect(search._serviceManager instanceof Subclass.Service.ServiceManager).toBe(true);

        expect(search == searchAnother).toBe(true);
        expect(search.isError()).toBe(true);
        expect(search.getCache()).toBe(true);

        var searchEngines = Object.keys(search.getEngines());
        expect(searchEngines).toContain('mysql');
        expect(searchEngines).toContain('solr');
        expect(searchEngines).toContain('sphinx');

        expect(search.getUsedEngine().getName()).toBe('mysql');
        expect(search.search(['word'])).toBe('Mysql search results of keywords: "word"');

        search.setUsedEngine('solr');
        expect(search.search(['word'])).toBe('Solr search results of keywords: "word"');

        search.setUsedEngine('sphinx');
        expect(search.search(['word'])).toBe('Sphinx search results of keywords: "word"');

        var mySearch = app.getService('my_search');
        expect(mySearch.search(['word'])).toBe('Search words "word" using engine "solr". (custom search)');

        var myMysqlEngine = search.getEngine('mysql');
        expect(myMysqlEngine.getMode()).toBe('dev');
    });

    it ("not allowed actions", function() {

    });
});<|endoftext|>


<commit_before>"use strict";

var request = require("request");
var mongoose = require("mongoose");
var ts = require("./testServer");

var server = ts.server;
var Entity = ts.Entity;

function testRoute(test, route, expectStatusCode, expectBody) {
    var testCount = 4;
    test.expect(testCount);
    request({uri: "http://localhost:8080/fetch" + route, method: "GET"}, function(err, resp, body) {
        if ( typeof body === "string" && body.length > 0 ) { // Request is a finicky package.
            body = JSON.parse(body);
        }
        test.ifError(err);
        test.equal(resp.statusCode, expectStatusCode);
        test.equal(expectBody.name, body.name);
        test.equal(expectBody._id, body._id);
        test.done();
    });
}

module.exports = {
    setUp: function(done) {
        mongoose.connect("mongodb://localhost:27017");
        mongoose.connection.once("open", function() {
            server.listen(8080, function() {
                done();
            });
        });
    },
    tearDown: function(done) {
        mongoose.connection.close(function() {
            server.close(function() {
                done();
            });
        });
    },
    "Succeeds on non-running route": function(test) {
        testRoute(test, "", 200, {});
    },
    "Fetches entity from route": function(test) {
        var obj = new Entity({name: "abc"});
        obj.save(function() {
            testRoute(test, "/" + obj.id, 200, {name: "abc", _id: obj.id});
        });
    },
    "Entity not found": function(test) {
        testRoute(test, "/507f1f77bcf86cd799439011", 404, {});
    },
    "Invalid object Id": function(test) {
        testRoute(test, "/abc123", 404, {});
    },
    "Poorly constructed lumina function": function(test) {
        test.expect(1);
        test.throws(function() {
            ts.lumen.illuminate({
                fetchObjectsFromRoute : {},
                handler: function(req, res, next) {
                    res.send(200);
                    return next();
                }
            });
        });
        test.done();
    }
};
<commit_msg>Updated tests to include error messages.<commit_after>"use strict";

var request = require("request");
var mongoose = require("mongoose");
var ts = require("./testServer");

var server = ts.server;
var Entity = ts.Entity;

function testRoute(test, route, expectStatusCode, expectBody) {
    var testCount = 6;
    test.expect(testCount);
    request({uri: "http://localhost:8080/fetch" + route, method: "GET"}, function(err, resp, body) {
        if ( typeof body === "string" && body.length > 0 ) { // Request is a finicky package.
            body = JSON.parse(body);
        }
        test.ifError(err);
        test.equal(resp.statusCode, expectStatusCode);
        test.equal(expectBody.name, body.name);
        test.equal(expectBody._id, body._id);
        test.equal(expectBody.code, body.code);
        test.equal(expectBody.message, body.message);
        test.done();
    });
}

module.exports = {
    setUp: function(done) {
        mongoose.connect("mongodb://localhost:27017");
        mongoose.connection.once("open", function() {
            server.listen(8080, function() {
                done();
            });
        });
    },
    tearDown: function(done) {
        mongoose.connection.close(function() {
            server.close(function() {
                done();
            });
        });
    },
    "Succeeds on non-running route": function(test) {
        testRoute(test, "", 200, {});
    },
    "Fetches entity from route": function(test) {
        var obj = new Entity({name: "abc"});
        obj.save(function() {
            testRoute(test, "/" + obj.id, 200, {name: "abc", _id: obj.id});
        });
    },
    "Entity not found": function(test) {
        testRoute(test, "/507f1f77bcf86cd799439011", 404, {code: "NotFoundError", message: "Object of type Entity (507f1f77bcf86cd799439011) not found."});
    },
    "Invalid object Id": function(test) {
        testRoute(test, "/abc123", 404, {code: "NotFoundError", message: "Object of type Entity (abc123) not found."});
    },
    "Poorly constructed lumina function": function(test) {
        test.expect(1);
        test.throws(function() {
            ts.lumen.illuminate({
                fetchObjectsFromRoute : {},
                handler: function(req, res, next) {
                    res.send(200);
                    return next();
                }
            });
        });
        test.done();
    }
};
<|endoftext|>


<commit_before>/* eslint-disable no-undef */
const assert = require('assert');
const fs = require('fs-extra');
const os = require('os');
const path = require('path');
const pathExists = require('path-exists');
const rename = require('../rename');
const yargs = require('yargs');
const yargsOptions = require('../lib/yargsOptions');

// remove test directory
fs.removeSync('./test');
// create test files/directories
fs.ensureDirSync('test');
fs.ensureDirSync('test/another-dir');
for (let i = 1; i < 31; i++) {
  let num = inWords(i);
  fs.writeFileSync((i < 20 ? 'test/' : 'test/another-dir/') + num.trim().replace(' ', '-') + '.txt', 'file ' + num.trim(), 'utf8');
}
let undoFile = os.homedir() + '/.rename/undo.json';
if (!pathExists.sync(undoFile)) {
  try {
    fs.ensureFileSync(undoFile);
    fs.writeJSONSync(undoFile, []);
  } catch(e) {
    console.log('Could not write ' + undoFile);
  }
}

// run tests
runTest('rename -v test/one.txt test/one-renamed.txt', 'Rename a single file', 'test/one.txt', 'test/one-renamed.txt');

runTest('rename test/f*.txt test/multiple',
  'Rename multiple files the same thing with appended index',
  ['test/four.txt', 'test/five.txt', 'test/fourteen.txt', 'test/fifteen.txt'],
  ['test/multiple1.txt', 'test/multiple2.txt', 'test/multiple3.txt', 'test/multiple4.txt']);

runTest('rename -v test/two.txt "{{p}}/{{f|upper}}.{{\'testing-stuff\'|camel}}"',
  'Rename with variables and filters', 'test/two.txt', 'test/TWO.testingStuff');

runTest('rename -v test/th* test/same --noindex -force', 'Force multiple files to be renamed the same',
  ['test/three.txt', 'test/thirteen.txt'], 'test/same.txt');

  runTest('rename -v test/one-renamed.txt "test/another-dir/{{os.platform}}"', 'Move a file to a new directory',
    'test/one-renamed.txt', 'test/another-dir/' + os.platform() + '.txt');

// HELPER FUNCTIONS

function runTest(command, description, old, expected, undo) {
  runCommand(command, undo);
  let oldFile;
  let newFile;
  if (Array.isArray(old)) {
    oldFile = old.some(f => fs.existsSync(f));
  } else {
    oldFile = fs.existsSync(old);
  }
  if (Array.isArray(expected)) {
    newFile = expected.every(f => fs.existsSync(f));
  } else {
    newFile = fs.existsSync(expected);
  }
  describe(description, function () {
    it(command, function () {
      assert.equal(oldFile, false);
      assert.equal(newFile, true);
    });
  });
}

function runCommand(command, undo) {
  undo = undo || false;
  let argv = yargs.options(yargsOptions).parse(command.replace(/^rename /, '') + (!undo ? ' --noundo' : ''));
  let newFileName = path.parse(argv._.pop());
  let files = rename.getFileArray(argv._);
  let options = rename.argvToOptions(argv);
  let operations = rename.getOperations(files, newFileName, options);
  rename.run(operations, options, false);
}

function inWords (num) {
  let a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
  let b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
  if ((num = num.toString()).length > 9) return 'overflow';
  let n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
  if (!n) return;
  let str = '';
  str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
  str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
  str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
  str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
  str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) : '';
  return str;
}
<commit_msg>Test for keep option<commit_after>/* eslint-disable no-undef */
const assert = require('assert');
const fs = require('fs-extra');
const os = require('os');
const path = require('path');
const pathExists = require('path-exists');
const rename = require('../rename');
const yargs = require('yargs');
const yargsOptions = require('../lib/yargsOptions');

// remove test directory
fs.removeSync('./test');
// create test files/directories
fs.ensureDirSync('test');
fs.ensureDirSync('test/another-dir');
for (let i = 1; i < 31; i++) {
  let num = inWords(i);
  fs.writeFileSync((i < 20 ? 'test/' : 'test/another-dir/') + num.trim().replace(' ', '-') + '.txt', 'file ' + num.trim(), 'utf8');
}
let undoFile = os.homedir() + '/.rename/undo.json';
if (!pathExists.sync(undoFile)) {
  try {
    fs.ensureFileSync(undoFile);
    fs.writeJSONSync(undoFile, []);
  } catch(e) {
    console.log('Could not write ' + undoFile);
  }
}

// run tests
runTest('rename -v test/one.txt test/one-renamed.txt', 'Rename a single file', 'test/one.txt', 'test/one-renamed.txt');

runTest('rename -v test/f*.txt test/multiple',
  'Rename multiple files the same thing with appended index',
  ['test/four.txt', 'test/five.txt', 'test/fourteen.txt', 'test/fifteen.txt'],
  ['test/multiple1.txt', 'test/multiple2.txt', 'test/multiple3.txt', 'test/multiple4.txt']);

runTest('rename -v test/two.txt "{{p}}/{{f|upper}}.{{\'testing-stuff\'|camel}}"',
  'Rename with variables and filters', 'test/two.txt', 'test/TWO.testingStuff');

runTest('rename -v test/th* test/same --noindex -force', 'Force multiple files to be renamed the same',
  ['test/three.txt', 'test/thirteen.txt'], 'test/same.txt');

runTest('rename -v test/six* test/keep --noindex -k', 'Multiple files to be renamed the same but with keep option',
  ['test/six.txt', 'test/sixteen.txt'], ['test/keep.txt', 'test/keep-1.txt']);

runTest('rename -v test/one-renamed.txt "test/another-dir/{{os.platform}}"', 'Move a file to a new directory',
    'test/one-renamed.txt', 'test/another-dir/' + os.platform() + '.txt');

// HELPER FUNCTIONS

function runTest(command, description, old, expected, undo) {
  runCommand(command, undo);
  let oldFile;
  let newFile;
  if (Array.isArray(old)) {
    oldFile = old.some(f => fs.existsSync(f));
  } else {
    oldFile = fs.existsSync(old);
  }
  if (Array.isArray(expected)) {
    newFile = expected.every(f => fs.existsSync(f));
  } else {
    newFile = fs.existsSync(expected);
  }
  describe(description, function () {
    it(command, function () {
      assert.equal(oldFile, false);
      assert.equal(newFile, true);
    });
  });
}

function runCommand(command, undo) {
  undo = undo || false;
  let argv = yargs.options(yargsOptions).parse(command.replace(/^rename /, '') + (!undo ? ' --noundo' : ''));
  let newFileName = path.parse(argv._.pop());
  let files = rename.getFileArray(argv._);
  let options = rename.argvToOptions(argv);
  let operations = rename.getOperations(files, newFileName, options);
  rename.run(operations, options, false);
}

function inWords (num) {
  let a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
  let b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
  if ((num = num.toString()).length > 9) return 'overflow';
  let n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
  if (!n) return;
  let str = '';
  str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
  str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
  str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
  str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
  str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) : '';
  return str;
}
<|endoftext|>