<commit_before>//   Licensed to the Apache Software Foundation (ASF) under one or more
//   contributor license agreements.  See the NOTICE file distributed with
//   this work for additional information regarding copyright ownership.
//   The ASF licenses this file to You under the Apache License, Version 2.0
//   (the "License"); you may not use this file except in compliance with
//   the License.  You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//   $Id$ -->

// jscript to run FOP, adapted from the Jakarta-Ant project.

// rpm_mode is irrelevant on Windows
// var rpm_mode=true;
var fop_exec_args = "";
var no_config=false;
var fop_exec_debug=false;
var debug=false;
var keep_open=false;
var show_help=false;

var config_wanted = new Array("FOP_HOME", "CLASSPATH", "FOP_HYPHENATION_PATH", "FOP_OPTS", "JAVA_OPTS", "LOGCHOICE", "LOGLEVEL");

// parse command-line arguments
function read_args() {
  var args = WScript.Arguments;
  var named = new ActiveXObject("Scripting.Dictionary");
  for (i = 0; i < args.length; i++) {
	switch(args(i)) {
	case "--debug":
	  debug=true;
	  break;
	case "--execdebug":
	  fop_exec_debug=true;
	  break;
	case "--keepopen":
	  keep_open=true;
	  break;
	case "--noconfig":
	  no_config=true;
	  break;
	case "-h":
	case "--help":
	case "--h":
	case "-help":
	  show_help=true;
	  // fop_exec_args=fop_exec_args + " -h";
	  break;
	default:
	  fop_exec_args=fop_exec_args + " " + args(i);
	}
  }
  if (debug) {
	WScript.Echo("debug: " + debug);
	WScript.Echo("execdebug: " + fop_exec_debug);
 	WScript.Echo("keepopen: " + keep_open);
 	WScript.Echo("noconfig: " + no_config);
	WScript.Echo("help: " + show_help);
 	WScript.Echo("fop arguments: " + fop_exec_args);
  }
}

var help_text="Usage:\n"
  + WScript.ScriptFullName + " [script options] [FOP options]\n"
  + "Script Options:\n"
  + "  --help, -h             print this message and FOP help\n"
  + "  --debug                print debugging information for this launch script\n"
  + "  --execdebug            print FOP exec line generated by this launch script\n"
  + "  --keepopen             keep FOP's command window open\n"
  + "  --noconfig             suppress reading of configuration file and registry";

function read_environment() {
  for (i in config_wanted) {
	if (!config.Exists(config_wanted[i])) {
		var env_var_string = "%" + config_wanted[i] + "%";
		var env_var = shell.ExpandEnvironmentStrings(env_var_string);
		if (env_var != "" && env_var != env_var_string) {
		  config.Add(config_wanted[i], env_var);
		  if (debug) {
			WScript.Echo(config_wanted[i] + " env: "
						 + config.Item(config_wanted[i]));
		  }
		}
	}
  }
}

function read_desktop(dtname) {
  if (fs.FolderExists(dtname)) {
	var fopname = fs.GetFolder(dtname).ParentFolder.Path
	  + "\\Application Data\\Fop";
	if (fs.FolderExists(fopname)) {
	  var fop_conf_name = fs.GetFolder(fopname).Path + "\\fop.conf";
	  if (fs.FileExists(fop_conf_name)) {
		// source fop_conf_file
		var conf_file = fs.openTextFile(fs.GetFile(fop_conf_name));
		var conf_lines = new ActiveXObject("Scripting.Dictionary");
		while (!conf_file.AtEndOfStream) {
		  var line = conf_file.ReadLine();
		  var m = line.match(/(.+?)=(.+)/);
		  if (m != null) {
			conf_lines.Add(m[1], m[2]);
		  }
		}
		for (j in config_wanted) {
		  if (!config.Exists(config_wanted[j])
			  && conf_lines.Exists(config_wanted[j])) {
			config.Add(config_wanted[j], conf_lines.Item(config_wanted[j]));
			if (debug) {
			  WScript.Echo(config_wanted[j] + " " + dts[i] + ": "
						   + config.Item(config_wanted[i]));
			}
		  }
		}
	  }
	}
  }
}

function read_registry(section) {
  for (j in config_wanted) {
	if (!config.Exists(config_wanted[j])) {
	  var reg_var;
	  try {
		reg_var = shell.RegRead(section + "\\Software\\Fop\\"
								+ config_wanted[j]);
		config.Add(config_wanted[j], reg_var);
		if (debug) {
		  WScript.Echo(config_wanted[j] + " " + rks[i] + ": "
					   + config.Item(config_wanted[j]));
		}
	  } catch(e) {}
	}
  }
}

// construct FOP_HOME from the script folder
function get_fop_home() {
  if (!config.Exists("FOP_HOME")
	  || !fs.FolderExists(config.Item("FOP_HOME"))) {
	var fop_home = WScript.ScriptFullName;
	fop_home = fop_home.substring(0, fop_home.length
								  - WScript.ScriptName.length - 1);
	if (config.Exists("FOP_HOME")) {
	  config.Remove("FOP_HOME");
	}
	config.Add("FOP_HOME", fop_home);
	if (debug) {
	  WScript.Echo("FOP_HOME dyn: " + config.Item("FOP_HOME"));
	}
  }
}

function get_java_cmd() {
  var java_home = shell.ExpandEnvironmentStrings("%JAVA_HOME%");
  javacmd = "java";
  if (java_home != "" && typeof(java_home) != "undefined"
	  && fs.FolderExists(java_home)) {
	var javacmd_candidate = java_home + "\\bin\\java.exe";
	if (fs.FileExists(javacmd_candidate)) {
	  javacmd = javacmd_candidate;
	}
  }
  if (debug) {
	WScript.Echo("java command: " + javacmd);
  }
}

function get_local_classpath() {
  if (config.Exists("CLASSPATH")) {
	local_classpath = config.Item("CLASSPATH");
	if (debug) {
	  WScript.Echo("local classpath: " + local_classpath);
	}
  }

  // add fop.jar, fop-sandbox and fop-hyph.jar, which reside in $FOP_HOME/build
  var lcp = local_classpath;
  local_classpath = config.Item("FOP_HOME") + "\\build\\fop.jar;"
	+ config.Item("FOP_HOME") + "\\build\\fop-sandbox.jar;"
	+ config.Item("FOP_HOME") + "\\build\\fop-hyph.jar";
  if (lcp != "") {
	local_classpath += ";" + lcp;
  }
  if (debug) {
	WScript.Echo("local classpath: " + local_classpath);
  }

  // add in the dependency .jar files, which reside in $FOP_HOME/lib
  var libdir_name = config.Item("FOP_HOME") + "\\lib";
  var dirlibs;
  if (fs.FolderExists(libdir_name)) {
	dirlibs = fs.GetFolder(libdir_name).Files;
	var e = new Enumerator(dirlibs);
	for (; !e.atEnd(); e.moveNext()) {
	  if (e.item().Name.match("\.jar$")) {
		local_classpath = libdir_name + "\\" + e.item().Name + ";" + local_classpath;
	  }
	}
	if (debug) {
	  WScript.Echo("local classpath: " + local_classpath);
	}
  }

  // add in user-defined hyphenation JARs
  if (config.Exists("FOP_HYPHENATION_PATH")) {
	local_classpath += ";" + config.Item("FOP_HYPHENATION_PATH");
	if (debug) {
	  WScript.Echo("local classpath: " + local_classpath);
	}
  }
}

// Execute fop via shell.Exec
function fop_exec() {
  var fop_exec_command = "\"" + javacmd + "\" "
	+ (config.Exists("JAVA_OPTS")?config.Item("JAVA_OPTS") + " ":"")
	+ (config.Exists("LOGCHOICE")?config.Item("LOGCHOICE") + " ":"")
	+ (config.Exists("LOGLEVEL")?config.Item("LOGLEVEL") + " ":"")
	"-classpath \"" + local_classpath + "\" "
	+ (config.Exists("FOP_OPTS")?config.Item("FOP_OPTS"):"")
	+ "org.apache.fop.cli.Main " + fop_exec_args;
  if (debug || fop_exec_debug) {
	WScript.Echo(fop_exec_command);
  }

  var fop_run = shell.Exec(fop_exec_command);
  while (true) {
	while (!fop_run.StdOut.AtEndOfStream) {
	  WScript.Echo(fop_run.StdOut.ReadLine());
	}
	while (!fop_run.StdErr.AtEndOfStream) {
	  WScript.Echo(fop_run.StdErr.ReadLine());
	}
	if (fop_run.Status == 1) {
	  break;
	}
	WScript.Sleep(100);
  }
  if (debug) {
	WScript.Echo("exit status: " + fop_run.ExitCode);
  }
}

// Execute fop via shell.Run
function fop_run() {
  var fop_exec_command = "cmd /" + (keep_open?"K":"C") + " \""
	+ "\"" + javacmd + "\" "
	+ (config.Exists("JAVA_OPTS")?config.Item("JAVA_OPTS") + " ":"")
	+ (config.Exists("LOGCHOICE")?config.Item("LOGCHOICE") + " ":"")
	+ (config.Exists("LOGLEVEL")?config.Item("LOGLEVEL") + " ":"")
	+ "-classpath \"" + local_classpath + "\" "
	+ (config.Exists("FOP_OPTS")?config.Item("FOP_OPTS") + " ":"")
	+ "org.apache.fop.cli.Main " + fop_exec_args + "\"";
  if (debug || fop_exec_debug) {
	WScript.Echo(fop_exec_command);
  }
  var exit_code = shell.Run(fop_exec_command, 1, 1);
  if (debug) {
	WScript.Echo("exit status: " + exit_code);
  } else {
	if (exit_code != 0) {
	  WScript.Echo("A FOP error occurred (FOP exit status: " + exit_code + ")\n"
	               + "Use option --keepopen to see FOP's output\n"
                       + "(that is two dashes)");
	}
  }
}

function get_log_choice() {
  // The default commons logger for JDK1.4 is JDK1.4Logger.
  // To use a different logger, uncomment the one desired below
  if (!config.Exists("LOGCHOICE")) {
	// config.Add("LOGCHOICE","\"-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.NoOpLog\"");
	// config.Add("LOGCHOICE","\"-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog\"");
	// config.Add("LOGCHOICE","\"-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger\"");
	if (debug && config.Exists("LOGCHOICE")) {
	  WScript.Echo("LOGCHOICE script: " + config.Item("LOGCHOICE"));
	}
  }
}

function get_log_level() {
  // Logging levels
  // Below option is only if you are using SimpleLog instead of the default JDK1.4 Logger.
  // To set logging levels for JDK 1.4 Logger, edit the %JAVA_HOME%/JRE/LIB/logging.properties
  // file instead.
  // Possible SimpleLog values:  "trace", "debug", "info" (default), "warn", "error", or "fatal".
  if (!config.Exists("LOGLEVEL")) {
	// config.Add("LOGLEVEL","\"-Dorg.apache.commons.logging.simplelog.defaultlog=INFO\"");
	if (debug && config.Exists("LOGLEVEL")) {
	  WScript.Echo("LOGLEVEL script: " + config.Item("LOGLEVEL"));
	}
  }
}

var shell = WScript.CreateObject("WScript.Shell");
var fs = WScript.CreateObject("Scripting.FileSystemObject");

// configuration
var config = new ActiveXObject("Scripting.Dictionary");

read_args();
read_environment();
if (!no_config) {
  // read user and system-wide fop configurations
  var spec = shell.SpecialFolders;
  var dts = new Array("Desktop", "AllUsersDesktop");
  for (i in dts) {
	read_desktop(spec(dts[i]));
  }
  // read user and system-wide registry
  var rks = new Array("HKCU", "HKLM");
  for (i in rks) {
	read_registry(rks[i]);
  }
}

get_fop_home();
get_log_choice();
get_log_level();
var javacmd = "";
get_java_cmd();
var local_classpath = "";
get_local_classpath();

// Show script help if requested
if (show_help) {
  // fop_exec_args = "";
  keep_open = true;
  WScript.Echo(help_text);
}

// fop_exec();
fop_run();
<commit_msg>Bugzilla 50590: Fix typo in fop_exec() function in fop.js. Thanks to sergeyb49.AT.gmail.<commit_after>//   Licensed to the Apache Software Foundation (ASF) under one or more
//   contributor license agreements.  See the NOTICE file distributed with
//   this work for additional information regarding copyright ownership.
//   The ASF licenses this file to You under the Apache License, Version 2.0
//   (the "License"); you may not use this file except in compliance with
//   the License.  You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//   $Id$ -->

// jscript to run FOP, adapted from the Jakarta-Ant project.

// rpm_mode is irrelevant on Windows
// var rpm_mode=true;
var fop_exec_args = "";
var no_config=false;
var fop_exec_debug=false;
var debug=false;
var keep_open=false;
var show_help=false;

var config_wanted = new Array("FOP_HOME", "CLASSPATH", "FOP_HYPHENATION_PATH", "FOP_OPTS", "JAVA_OPTS", "LOGCHOICE", "LOGLEVEL");

// parse command-line arguments
function read_args() {
  var args = WScript.Arguments;
  var named = new ActiveXObject("Scripting.Dictionary");
  for (i = 0; i < args.length; i++) {
	switch(args(i)) {
	case "--debug":
	  debug=true;
	  break;
	case "--execdebug":
	  fop_exec_debug=true;
	  break;
	case "--keepopen":
	  keep_open=true;
	  break;
	case "--noconfig":
	  no_config=true;
	  break;
	case "-h":
	case "--help":
	case "--h":
	case "-help":
	  show_help=true;
	  // fop_exec_args=fop_exec_args + " -h";
	  break;
	default:
	  fop_exec_args=fop_exec_args + " " + args(i);
	}
  }
  if (debug) {
	WScript.Echo("debug: " + debug);
	WScript.Echo("execdebug: " + fop_exec_debug);
 	WScript.Echo("keepopen: " + keep_open);
 	WScript.Echo("noconfig: " + no_config);
	WScript.Echo("help: " + show_help);
 	WScript.Echo("fop arguments: " + fop_exec_args);
  }
}

var help_text="Usage:\n"
  + WScript.ScriptFullName + " [script options] [FOP options]\n"
  + "Script Options:\n"
  + "  --help, -h             print this message and FOP help\n"
  + "  --debug                print debugging information for this launch script\n"
  + "  --execdebug            print FOP exec line generated by this launch script\n"
  + "  --keepopen             keep FOP's command window open\n"
  + "  --noconfig             suppress reading of configuration file and registry";

function read_environment() {
  for (i in config_wanted) {
	if (!config.Exists(config_wanted[i])) {
		var env_var_string = "%" + config_wanted[i] + "%";
		var env_var = shell.ExpandEnvironmentStrings(env_var_string);
		if (env_var != "" && env_var != env_var_string) {
		  config.Add(config_wanted[i], env_var);
		  if (debug) {
			WScript.Echo(config_wanted[i] + " env: "
						 + config.Item(config_wanted[i]));
		  }
		}
	}
  }
}

function read_desktop(dtname) {
  if (fs.FolderExists(dtname)) {
	var fopname = fs.GetFolder(dtname).ParentFolder.Path
	  + "\\Application Data\\Fop";
	if (fs.FolderExists(fopname)) {
	  var fop_conf_name = fs.GetFolder(fopname).Path + "\\fop.conf";
	  if (fs.FileExists(fop_conf_name)) {
		// source fop_conf_file
		var conf_file = fs.openTextFile(fs.GetFile(fop_conf_name));
		var conf_lines = new ActiveXObject("Scripting.Dictionary");
		while (!conf_file.AtEndOfStream) {
		  var line = conf_file.ReadLine();
		  var m = line.match(/(.+?)=(.+)/);
		  if (m != null) {
			conf_lines.Add(m[1], m[2]);
		  }
		}
		for (j in config_wanted) {
		  if (!config.Exists(config_wanted[j])
			  && conf_lines.Exists(config_wanted[j])) {
			config.Add(config_wanted[j], conf_lines.Item(config_wanted[j]));
			if (debug) {
			  WScript.Echo(config_wanted[j] + " " + dts[i] + ": "
						   + config.Item(config_wanted[i]));
			}
		  }
		}
	  }
	}
  }
}

function read_registry(section) {
  for (j in config_wanted) {
	if (!config.Exists(config_wanted[j])) {
	  var reg_var;
	  try {
		reg_var = shell.RegRead(section + "\\Software\\Fop\\"
								+ config_wanted[j]);
		config.Add(config_wanted[j], reg_var);
		if (debug) {
		  WScript.Echo(config_wanted[j] + " " + rks[i] + ": "
					   + config.Item(config_wanted[j]));
		}
	  } catch(e) {}
	}
  }
}

// construct FOP_HOME from the script folder
function get_fop_home() {
  if (!config.Exists("FOP_HOME")
	  || !fs.FolderExists(config.Item("FOP_HOME"))) {
	var fop_home = WScript.ScriptFullName;
	fop_home = fop_home.substring(0, fop_home.length
								  - WScript.ScriptName.length - 1);
	if (config.Exists("FOP_HOME")) {
	  config.Remove("FOP_HOME");
	}
	config.Add("FOP_HOME", fop_home);
	if (debug) {
	  WScript.Echo("FOP_HOME dyn: " + config.Item("FOP_HOME"));
	}
  }
}

function get_java_cmd() {
  var java_home = shell.ExpandEnvironmentStrings("%JAVA_HOME%");
  javacmd = "java";
  if (java_home != "" && typeof(java_home) != "undefined"
	  && fs.FolderExists(java_home)) {
	var javacmd_candidate = java_home + "\\bin\\java.exe";
	if (fs.FileExists(javacmd_candidate)) {
	  javacmd = javacmd_candidate;
	}
  }
  if (debug) {
	WScript.Echo("java command: " + javacmd);
  }
}

function get_local_classpath() {
  if (config.Exists("CLASSPATH")) {
	local_classpath = config.Item("CLASSPATH");
	if (debug) {
	  WScript.Echo("local classpath: " + local_classpath);
	}
  }

  // add fop.jar, fop-sandbox and fop-hyph.jar, which reside in $FOP_HOME/build
  var lcp = local_classpath;
  local_classpath = config.Item("FOP_HOME") + "\\build\\fop.jar;"
	+ config.Item("FOP_HOME") + "\\build\\fop-sandbox.jar;"
	+ config.Item("FOP_HOME") + "\\build\\fop-hyph.jar";
  if (lcp != "") {
	local_classpath += ";" + lcp;
  }
  if (debug) {
	WScript.Echo("local classpath: " + local_classpath);
  }

  // add in the dependency .jar files, which reside in $FOP_HOME/lib
  var libdir_name = config.Item("FOP_HOME") + "\\lib";
  var dirlibs;
  if (fs.FolderExists(libdir_name)) {
	dirlibs = fs.GetFolder(libdir_name).Files;
	var e = new Enumerator(dirlibs);
	for (; !e.atEnd(); e.moveNext()) {
	  if (e.item().Name.match("\.jar$")) {
		local_classpath = libdir_name + "\\" + e.item().Name + ";" + local_classpath;
	  }
	}
	if (debug) {
	  WScript.Echo("local classpath: " + local_classpath);
	}
  }

  // add in user-defined hyphenation JARs
  if (config.Exists("FOP_HYPHENATION_PATH")) {
	local_classpath += ";" + config.Item("FOP_HYPHENATION_PATH");
	if (debug) {
	  WScript.Echo("local classpath: " + local_classpath);
	}
  }
}

// Execute fop via shell.Exec
function fop_exec() {
  var fop_exec_command = "\"" + javacmd + "\" "
	+ (config.Exists("JAVA_OPTS")?config.Item("JAVA_OPTS") + " ":"")
	+ (config.Exists("LOGCHOICE")?config.Item("LOGCHOICE") + " ":"")
	+ (config.Exists("LOGLEVEL")?config.Item("LOGLEVEL") + " ":"")
	+ "-classpath \"" + local_classpath + "\" "
	+ (config.Exists("FOP_OPTS")?config.Item("FOP_OPTS"):"")
	+ "org.apache.fop.cli.Main " + fop_exec_args;
  if (debug || fop_exec_debug) {
	WScript.Echo(fop_exec_command);
  }

  var fop_run = shell.Exec(fop_exec_command);
  while (true) {
	while (!fop_run.StdOut.AtEndOfStream) {
	  WScript.Echo(fop_run.StdOut.ReadLine());
	}
	while (!fop_run.StdErr.AtEndOfStream) {
	  WScript.Echo(fop_run.StdErr.ReadLine());
	}
	if (fop_run.Status == 1) {
	  break;
	}
	WScript.Sleep(100);
  }
  if (debug) {
	WScript.Echo("exit status: " + fop_run.ExitCode);
  }
}

// Execute fop via shell.Run
function fop_run() {
  var fop_exec_command = "cmd /" + (keep_open?"K":"C") + " \""
	+ "\"" + javacmd + "\" "
	+ (config.Exists("JAVA_OPTS")?config.Item("JAVA_OPTS") + " ":"")
	+ (config.Exists("LOGCHOICE")?config.Item("LOGCHOICE") + " ":"")
	+ (config.Exists("LOGLEVEL")?config.Item("LOGLEVEL") + " ":"")
	+ "-classpath \"" + local_classpath + "\" "
	+ (config.Exists("FOP_OPTS")?config.Item("FOP_OPTS") + " ":"")
	+ "org.apache.fop.cli.Main " + fop_exec_args + "\"";
  if (debug || fop_exec_debug) {
	WScript.Echo(fop_exec_command);
  }
  var exit_code = shell.Run(fop_exec_command, 1, 1);
  if (debug) {
	WScript.Echo("exit status: " + exit_code);
  } else {
	if (exit_code != 0) {
	  WScript.Echo("A FOP error occurred (FOP exit status: " + exit_code + ")\n"
	               + "Use option --keepopen to see FOP's output\n"
                       + "(that is two dashes)");
	}
  }
}

function get_log_choice() {
  // The default commons logger for JDK1.4 is JDK1.4Logger.
  // To use a different logger, uncomment the one desired below
  if (!config.Exists("LOGCHOICE")) {
	// config.Add("LOGCHOICE","\"-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.NoOpLog\"");
	// config.Add("LOGCHOICE","\"-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog\"");
	// config.Add("LOGCHOICE","\"-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger\"");
	if (debug && config.Exists("LOGCHOICE")) {
	  WScript.Echo("LOGCHOICE script: " + config.Item("LOGCHOICE"));
	}
  }
}

function get_log_level() {
  // Logging levels
  // Below option is only if you are using SimpleLog instead of the default JDK1.4 Logger.
  // To set logging levels for JDK 1.4 Logger, edit the %JAVA_HOME%/JRE/LIB/logging.properties
  // file instead.
  // Possible SimpleLog values:  "trace", "debug", "info" (default), "warn", "error", or "fatal".
  if (!config.Exists("LOGLEVEL")) {
	// config.Add("LOGLEVEL","\"-Dorg.apache.commons.logging.simplelog.defaultlog=INFO\"");
	if (debug && config.Exists("LOGLEVEL")) {
	  WScript.Echo("LOGLEVEL script: " + config.Item("LOGLEVEL"));
	}
  }
}

var shell = WScript.CreateObject("WScript.Shell");
var fs = WScript.CreateObject("Scripting.FileSystemObject");

// configuration
var config = new ActiveXObject("Scripting.Dictionary");

read_args();
read_environment();
if (!no_config) {
  // read user and system-wide fop configurations
  var spec = shell.SpecialFolders;
  var dts = new Array("Desktop", "AllUsersDesktop");
  for (i in dts) {
	read_desktop(spec(dts[i]));
  }
  // read user and system-wide registry
  var rks = new Array("HKCU", "HKLM");
  for (i in rks) {
	read_registry(rks[i]);
  }
}

get_fop_home();
get_log_choice();
get_log_level();
var javacmd = "";
get_java_cmd();
var local_classpath = "";
get_local_classpath();

// Show script help if requested
if (show_help) {
  // fop_exec_args = "";
  keep_open = true;
  WScript.Echo(help_text);
}

// fop_exec();
fop_run();
<|endoftext|>


<commit_before>var mysql =  require('mysql');

console.log ( "1 --------------------------" ) ;
  var connection =  mysql.createConnection({
  	host : "localhost",
  	user : "root",
  	password: ""
  });
console.log ( "2 --------------------------" ) ;
  connection.connect();
console.log ( "2a --------------------------" ) ;
  connection.query( "use cdcol" );
console.log ( "3 --------------------------" ) ;
var strQuery = "select * from cds";

  connection.query( strQuery, function(err, rows){
  	if(err)	{
  		throw err;
  	}else{
  		for ( var i = 0 ; i < rows.length ; i++ )
  		{
  		console.log( rows[i] );
  		}
  	}
  	connection.end() ;
  });<commit_msg>mysql connector<commit_after>var mysql =  require('mysql2');
var T = require ( "Tango" ) ;
  var dburl = T.getProperty ( "dburl", "mysql://root:@localhost/cdcol" ) ;

  var connection =  mysql.createConnection ( dburl ) ;
  connection.connect();
  connection.query( "use cdcol" );
var strQuery = "select * from cds";

connection.query( strQuery, function(err, rows, fields ){
    // console.log ( fields ) ;
  	if(err)	{
  		throw err;
  	}else{
  		for ( var i = 0 ; i < rows.length ; i++ )
  		{
  		// console.log( rows[i] );
  		}
  	}
  	connection.end() ;
  });
q.on('end', function(result) {
        console.log("(end)");
    });<|endoftext|>


<commit_before>import assert from 'assert';
import AppStartup from '../../src/app-startup.js';
import React from 'react';
import {addons} from 'react/addons';
import sinon from 'sinon';

assert.called = sinon.assert.called;

const TestUtils = addons.TestUtils;

class ComponentDouble extends React.Component {
  render() {
    return ;
  }
}

var rendererOutput;
describe('app startup', function() {

  function render(data={}) {
    const shallowRenderer = TestUtils.createRenderer();
    let app = new AppStartup(ComponentDouble, shallowRenderer.render.bind(shallowRenderer));
    app.renderClientSide(data);
    rendererOutput = shallowRenderer.getRenderOutput();
  }

  it('renders the given component', function() {
    sinon.spy(ComponentDouble.prototype, 'render');
    render();
    assert.called(ComponentDouble.prototype.render);
  });
  it('with the given data', function() {
    let data = {my: 'data'};
    render(data);
    assert.deepEqual(rendererOutput.props.props, {kataGroups: data});
  });
});
<commit_msg>Group things nicer and ensure the component is rendered into the right DOM node.<commit_after>import assert from 'assert';
import AppStartup from '../../src/app-startup.js';
import React from 'react';
import {addons} from 'react/addons';
import sinon from 'sinon';

assert.called = sinon.assert.called;
assert.calledWith = sinon.assert.calledWith;

assert.renderedIntoDomNode = function(renderFunction, domNode) {
  assert.equal(renderFunction.firstCall.args[1], domNode);
};

const TestUtils = addons.TestUtils;

describe('app startup', function() {

  describe('the given component', function() {

    class ComponentDouble extends React.Component {
      render() {
        return ;
      }
    }

    let rendererOutput;
    function render(data={}) {
      const shallowRenderer = TestUtils.createRenderer();
      let app = new AppStartup(ComponentDouble, shallowRenderer.render.bind(shallowRenderer));
      app.renderClientSide(data);
      rendererOutput = shallowRenderer.getRenderOutput();
    }

    it('is rendered into given DOM node', function() {
      const domNode = 'some ref';
      const renderFunction = sinon.stub();
      const ComponentStub = class extends React.Component {};
      let app = new AppStartup(ComponentStub, renderFunction);
      app.renderClientSide({}, domNode);

      assert.renderedIntoDomNode(renderFunction, domNode);
    });

    it('is rendered', function() {
      sinon.spy(ComponentDouble.prototype, 'render');
      render();
      assert.calledWith(ComponentDouble.prototype.render);
    });

    it('with the given data', function() {
      let data = {my: 'data'};
      render(data);
      assert.deepEqual(rendererOutput.props.props, {kataGroups: data});
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var nikko = require('../lib/nikko.js');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports['awesome'] = {
  setUp: function(done) {
    // setup here
    done();
  },
  'no args': function(test) {
    test.expect(1);
    // tests here
    test.equal(nikko.awesome(), 'awesome', 'should be awesome.');
    test.done();
  },
};
<commit_msg>TEST: clean sheet<commit_after>'use strict';

var assert = require('chai').assert;
var fs = require('fs');
var path = require('path');
var Mode = require('stat-mode');
var rm = require('rimraf').sync;
var equal = require('assert-dir-equal');
var exec = require('child_process').exec;
var fixture = path.resolve.bind(path, __dirname, 'fixtures');

var Nikko = require('../');

describe('Nikko', function(){

});<|endoftext|>


<commit_before>mf.include("chat_commands.js");
mf.include("iterators.js");
mf.include("navigator.js");
mf.include("player_tracker.js");
mf.include("inventory.js");

(function() {

    var flatten_types = new Set([mf.ItemType.Sand, mf.ItemType.Grass, mf.ItemType.Dirt, mf.ItemType.Gravel, mf.ItemType.Stone, mf.ItemType.Sandstone]);

    function flatten_add_type(speaker, args, responder_fun) {
        var arg = args.join(" ");
        var item_type = items.findBlockTypeUnambiguously(arg, responder_fun);
        if (item_type === undefined) {
            return;
        }
        item_type = item_type.id;
        if (!flatten_types.add(item_type)) {
            responder_fun("Already flattening " + items.nameForId(item_type));
        } else {
            responder_fun("Now flattening " + items.nameForId(item_type));
        }
    }

    function flatten_remove_type(speaker, args, responder_fun) {
        var arg = args.join(" ");
        var item_type = items.findBlockTypeUnambiguously(arg, responder_fun);
        if (item_type === undefined) {
            return;
        }
        item_type = item_type.id;
        if (!flatten_types.contains(item_type)) {
            responder_fun("Already not flattening " + items.nameForId(item_type));
            return;
        } else {
            flatten_types.remove(item_type);
            responder_fun("No longer flattening " + items.nameForId(item_type));
        }
    }

    function flatten_list(speaker, responder_fun) {
        responder_fun("Flattening " + flatten_types.list().mapped(function(type) {return items.nameForId(type);}).join(", "));
    }

    chat_commands.registerCommand("flatten", function(speaker, args, responder_fun) {
        if (!isNaN(args[0])) {
            return;
        }
        var command = args.shift();
        if (command === "add") {
            if (args.length > 0) {
                flatten_add_type(speaker, args, responder_fun);
            } else {
                responder_fun("Must specify a type to add");
            }
            return;
        }
        if (command === "remove") {
            if (args.length > 0) {
                flatten_remove_type(speaker, args, responder_fun);
            } else {
                responder_fun("Must specify a type to remove");
            }
            return;
        }
        if (command === "list") {
            flatten_list(speaker, responder_fun);
            return;
        }
        responder_fun("Unrecognized command: " + command);
    }, 1, Infinity);

    chat_commands.registerCommand("flatten", function(speaker, args, responder_fun) {
        if (isNaN(args[0])) {
            return;
        }
        var player = player_tracker.entityForPlayer(speaker);
        if (player === undefined) {
            responder_fun("I can't see you, " + speaker + ".");
            return;
        }
        var radius = 8;
        if (args.length > 0) {
            var arg = args.shift();
            if (isNaN(arg)) {
                responder_fun("Not a number: " + arg);
                return;
            } else {
                radius = parseInt(arg);
            }
        }
        var player_position = player.position.floored();
        var max_height_level = 128;
        if (args.length > 0) {
            var arg = args.shift();
            if (isNaN(arg)) {
                responder_fun("Not a number: " + arg);
                return;
            }
            max_height_level = player_position.z + parseInt(arg);
        }
        var respond = responder_fun;
        var min_height_level = player.position.z;
        var has_pick = true;
        var has_axe = true;
        var has_shovel = true;
        var block_positions;
        var block_index;
        var running;
        var flattened;

        function done() {
            running = false;
            task_manager.done();
        }

        function start_punch() {
            navigator.navigateTo(block_positions[block_index], {
                end_radius: 4,
                timeout_milliseconds: 1000 * 1,
                arrived_func: function() {
                    if (!running) {
                        // stopped
                        return;
                    }
                    if (! mf.isDiggable(mf.blockAt(block_positions[block_index]).type)) {
                        block_positions.removeAt(block_index);
                        mine_blocks();
                        return;
                    }
                    mf.onStoppedDigging(function asdf() {
                        mf.removeHandler(mf.onStoppedDigging, asdf);
                        block_positions.removeAt(block_index);
                        mine_blocks();
                    });
                    flattened = true;
                    mf.startDigging(block_positions[block_index]);
                },
                cant_find_func: function() {
                    block_index++;
                    mine_blocks();
                },
            });
        }

        var mine_blocks = function() {
            if (block_positions.length === 0) {
                respond("I can't find anything else to flatten!");
                done();
                return;
            }
            if (block_index >= block_positions.length) {
                if (!flattened) {
                    respond("I can't reach any of the " + block_positions.length + " remaining blocks.  Done!");
                    done();
                    return;
                } else {
                    block_index = 0;
                    flattened = false;
                }
            }
            var block_position = block_positions[block_index];
            var block_type = mf.blockAt(block_position).type;
            if (! flatten_types.contains(block_type)) {
                block_positions.removeAt(block_index);
                mine_blocks();
                return;
            }
            if (!inventory.equipBestTool(block_type, start_punch)) {
                // couldn't equip proper tool
                var missing_tools = items.toolsForBlock(block_type);
                if (missing_tools === items.tools.shovels) {
                    if (has_shovel) {
                        respond("I don't have any shovels!");
                        has_shovel = false;
                        if (!inventory.equipNonTool(start_punch)) {
                            start_punch();
                        }
                    }
                } else if (missing_tools === items.tools.pickaxes) {
                    if (has_pick) {
                        respond("I don't have any pickaxes!  I'm going to skip over any blocks that require a pickaxe for material.");
                        has_pick = false;
                    }
                    block_index++;
                    mine_blocks();
                } else  if (missing_tools === items.tools.axes) {
                    if (has_axe) {
                        respond("I don't have any axes!");
                        has_axe = false;
                        if (! inventory.equipNonTool(start_punch)) {
                            start_punch();
                        }
                    }
                } else {
                    throw "I didn't know I was going to need a " + items.nameForId(missing_tools[0]);
                }
            }
        };
        var start_mining = function() {
            block_positions = new iterators.StripeIterable({
                corner1: new mf.Point(player_position.x - radius, player_position.y - radius, min_height_level),
                corner2: new mf.Point(player_position.x + radius, player_position.y + radius, max_height_level),
                stripe_width: 6,
                z_direction: -1,
            }).toArray();
            block_index = 0;
            flattened = false;
            if (block_positions.length <= 0) {
                respond("I don't see anything to flatten!");
                done();
                return;
            }
            max_height_level = block_positions[0].z;
            mine_blocks();
        };
        task_manager.doLater(new task_manager.Task(function start() {
                running = true;
                navigator.navigateTo(player.position, {
                    end_radius: 16,
                    timeout_milliseconds: 1000 * 10,
                    arrived_func: start_mining,
                    path_found_func: function() {
                        responder_fun("Going to try and flatten");
                    },
                    cant_find_func: function() {
                        responder_fun("Sorry, I can't get to you!");
                        done();
                    },
                });
            }, function stop() {
                running = false;
            }, function toString() {
                if (block_positions !== undefined && block_positions.length > 0) {
                    return "flatten (" + player_position.x + ", " + player_position.y + ") r=" + radius + " z=[" + min_height_level + " : " + block_positions[0].z + "]";
                } else {
                    return "flatten (" + player_position.x + ", " + player_position.y + ") r=" + radius + " z=[" + min_height_level + " : " + max_height_level + "]";
                }

            })
        );
    }, 0, 2);

})();
<commit_msg>Flatten supports adding/removing comma-separated lists, no longer spams when navigator has problems<commit_after>mf.include("chat_commands.js");
mf.include("iterators.js");
mf.include("navigator.js");
mf.include("player_tracker.js");
mf.include("inventory.js");

(function() {

    var flatten_types = new Set([mf.ItemType.Sand, mf.ItemType.Grass, mf.ItemType.Dirt, mf.ItemType.Gravel, mf.ItemType.Stone, mf.ItemType.Sandstone]);

    function get_flatten_database() {
        var db = {};
        for (var val in flatten_types.values) {
            db[parseInt(val)] = items.nameForId(val);
        }
        return db;
    }

    function flatten_add_type(speaker, args, responder_fun) {
        var arg = args.join(" ");
        var str_item_types = arg.split(",");
        var invalid_types = [];
        var valid_types = [];
        for (var i = 0; i < str_item_types.length; i++) {
            var item_type = str_item_types[i].trim();
            var matching_types = items.lookupBlockType(item_type);
            if (matching_types.length !== 1) {
                invalid_types.push(item_type);
                continue;
            }
            item_type = matching_types[0].id;
            valid_types.push(items.nameForId(item_type));
            flatten_types.add(item_type);
        }
        if (invalid_types.length > 0) {
            responder_fun("Ambiguous or unknown types: " + invalid_types.join(", "));
        }
        if (valid_types.length > 0) {
            responder_fun("Now flattening " + valid_types.join(", "));
        }
    }

    function flatten_remove_type(speaker, args, responder_fun) {
        var arg = args.join(" ");
        if (arg === "*" || arg === "everything" || arg === "all") {
            flatten_types.clear();
            responder_fun("No longer flattening anything");
            return;
        }
        var str_item_types = arg.split(",");
        var invalid_types = [];
        var valid_types = [];
        for (var i = 0; i < str_item_types.length; i++) {
            var item_type = str_item_types[i].trim();
            var matching_types = items.lookupInDatabase(item_type, get_flatten_database());
            if (matching_types.length !== 1) {
                invalid_types.push(item_type);
                continue;
            }
            item_type = matching_types[0].id;
            valid_types.push(items.nameForId(item_type));
            flatten_types.remove(item_type);
        }
        if (invalid_types.length > 0) {
            responder_fun("Ambiguous, unknown, or already not flattening " + invalid_types.join(", "));
        }
        if (valid_types.length > 0) {
            responder_fun("No longer flattening " + valid_types.join(", "));
        }
    }

    function flatten_list(speaker, responder_fun) {
        responder_fun("Flattening " + flatten_types.list().mapped(function(type) {return items.nameForId(type);}).join(", "));
    }

    chat_commands.registerCommand("flatten", function(speaker, args, responder_fun) {
        if (!isNaN(args[0])) {
            return;
        }
        var command = args.shift();
        if (command === "add") {
            if (args.length > 0) {
                flatten_add_type(speaker, args, responder_fun);
            } else {
                responder_fun("Must specify a type to add");
            }
            return;
        }
        if (command === "remove") {
            if (args.length > 0) {
                flatten_remove_type(speaker, args, responder_fun);
            } else {
                responder_fun("Must specify a type to remove");
            }
            return;
        }
        if (command === "list") {
            flatten_list(speaker, responder_fun);
            return;
        }
        responder_fun("Unrecognized command: " + command);
    }, 1, Infinity);

    chat_commands.registerCommand("flatten", function(speaker, args, responder_fun) {
        if (isNaN(args[0])) {
            return;
        }
        var player = player_tracker.entityForPlayer(speaker);
        if (player === undefined) {
            responder_fun("I can't see you, " + speaker + ".");
            return;
        }
        var radius = 8;
        if (args.length > 0) {
            var arg = args.shift();
            if (isNaN(arg)) {
                responder_fun("Not a number: " + arg);
                return;
            } else {
                radius = parseInt(arg);
            }
        }
        var player_position = player.position.floored();
        var max_height_level = 128;
        if (args.length > 0) {
            var arg = args.shift();
            if (isNaN(arg)) {
                responder_fun("Not a number: " + arg);
                return;
            }
            max_height_level = player_position.z + parseInt(arg);
        }
        var respond = responder_fun;
        var min_height_level = player.position.z;
        var has_pick = true;
        var has_axe = true;
        var has_shovel = true;
        var block_positions;
        var block_index;
        var running;
        var flattened;

        function done() {
            running = false;
            task_manager.done();
        }

        function start_punch() {
            navigator.navigateTo(block_positions[block_index], {
                end_radius: 4,
                timeout_milliseconds: 1000 * 1,
                arrived_func: function() {
                    if (!running) {
                        // stopped
                        return;
                    }
                    if (! mf.isDiggable(mf.blockAt(block_positions[block_index]).type)) {
                        block_positions.removeAt(block_index);
                        mine_blocks();
                        return;
                    }
                    mf.onStoppedDigging(function asdf() {
                        mf.removeHandler(mf.onStoppedDigging, asdf);
                        block_positions.removeAt(block_index);
                        mine_blocks();
                    });
                    flattened = true;
                    mf.startDigging(block_positions[block_index]);
                },
                cant_find_func: function() {
                    block_index++;
                    mine_blocks();
                },
            });
        }

        var mine_blocks = function() {
            if (block_positions.length === 0) {
                respond("I can't find anything else to flatten!");
                done();
                return;
            }
            if (block_index >= block_positions.length) {
                if (!flattened) {
                    respond("I can't reach any of the " + block_positions.length + " remaining blocks.  Done!");
                    done();
                    return;
                } else {
                    block_index = 0;
                    flattened = false;
                }
            }
            var block_position = block_positions[block_index];
            var block_type = mf.blockAt(block_position).type;
            if (! flatten_types.contains(block_type)) {
                block_positions.removeAt(block_index);
                mine_blocks();
                return;
            }
            if (!inventory.equipBestTool(block_type, start_punch)) {
                // couldn't equip proper tool
                var missing_tools = items.toolsForBlock(block_type);
                if (missing_tools === items.tools.shovels) {
                    if (has_shovel) {
                        respond("I don't have any shovels!");
                        has_shovel = false;
                        if (!inventory.equipNonTool(start_punch)) {
                            start_punch();
                        }
                    }
                } else if (missing_tools === items.tools.pickaxes) {
                    if (has_pick) {
                        respond("I don't have any pickaxes!  I'm going to skip over any blocks that require a pickaxe for material.");
                        has_pick = false;
                    }
                    block_index++;
                    mine_blocks();
                } else  if (missing_tools === items.tools.axes) {
                    if (has_axe) {
                        respond("I don't have any axes!");
                        has_axe = false;
                        if (! inventory.equipNonTool(start_punch)) {
                            start_punch();
                        }
                    }
                } else {
                    throw "I didn't know I was going to need a " + items.nameForId(missing_tools[0]);
                }
            }
        };
        var start_mining = function() {
            block_positions = new iterators.StripeIterable({
                corner1: new mf.Point(player_position.x - radius, player_position.y - radius, min_height_level),
                corner2: new mf.Point(player_position.x + radius, player_position.y + radius, max_height_level),
                stripe_width: 6,
                z_direction: -1,
            }).toArray();
            block_index = 0;
            flattened = false;
            if (block_positions.length <= 0) {
                respond("I don't see anything to flatten!");
                done();
                return;
            }
            max_height_level = block_positions[0].z;
            mine_blocks();
        };
        task_manager.doLater(new task_manager.Task(function start() {
                navigator.navigateTo(player.position, {
                    end_radius: 16,
                    timeout_milliseconds: 1000 * 10,
                    arrived_func: start_mining,
                    path_found_func: function() {
                        if (! running) {
                            responder_fun("Going to try and flatten");
                        }
                        running = true;
                    },
                    cant_find_func: function() {
                        responder_fun("Sorry, I can't get to you!");
                        done();
                    },
                });
            }, function stop() {
                running = false;
            }, function toString() {
                if (block_positions !== undefined && block_positions.length > 0) {
                    return "flatten (" + player_position.x + ", " + player_position.y + ") r=" + radius + " z=[" + min_height_level + " : " + block_positions[0].z + "]";
                } else {
                    return "flatten (" + player_position.x + ", " + player_position.y + ") r=" + radius + " z=[" + min_height_level + " : " + max_height_level + "]";
                }

            })
        );
    }, 0, 2);

})();
<|endoftext|>


<commit_before>// Currently in sync with Node.js test/parallel/test-util-types.js
// https://github.com/nodejs/node/commit/519a11b24fa453e5cefe13df10ab9696616b5b91

// Flags: --experimental-vm-modules --expose-internals
'use strict';
require('./common');
const assert = require('assert');
const { types, inspect } = require('util');
const vm = require('vm');

// [browserify] We can't test this in userland
// const { internalBinding } = require('internal/test/binding');
// const { JSStream } = internalBinding('js_stream');
// const external = (new JSStream())._externalStream;

const wasmBuffer = Buffer.from('0061736d01000000', 'hex');

for (const [ value, _method ] of [
  // [ external, 'isExternal' ],
  [ new Date() ],
  [ (function() { return arguments; })(), 'isArgumentsObject' ],
  [ new Boolean(), 'isBooleanObject' ],
  [ new Number(), 'isNumberObject' ],
  [ new String(), 'isStringObject' ],
  [ Object(Symbol()), 'isSymbolObject' ],
  [ Object(BigInt(0)), 'isBigIntObject' ],
  [ new Error(), 'isNativeError' ],
  [ new RegExp() ],
  [ async function() {}, 'isAsyncFunction' ],
  [ function*() {}, 'isGeneratorFunction' ],
  [ (function*() {})(), 'isGeneratorObject' ],
  [ Promise.resolve() ],
  [ new Map() ],
  [ new Set() ],
  [ (new Map())[Symbol.iterator](), 'isMapIterator' ],
  [ (new Set())[Symbol.iterator](), 'isSetIterator' ],
  [ new WeakMap() ],
  [ new WeakSet() ],
  [ new ArrayBuffer() ],
  [ new Uint8Array() ],
  [ new Uint8ClampedArray() ],
  [ new Uint16Array() ],
  [ new Uint32Array() ],
  [ new Int8Array() ],
  [ new Int16Array() ],
  [ new Int32Array() ],
  [ new Float32Array() ],
  [ new Float64Array() ],
  [ new BigInt64Array() ],
  [ new BigUint64Array() ],
  [ Object.defineProperty(new Uint8Array(),
                          Symbol.toStringTag,
                          { value: 'foo' }) ],
  [ new DataView(new ArrayBuffer()) ],
  [ new SharedArrayBuffer() ],
  [ new Proxy({}, {}), 'isProxy' ],
  [ new WebAssembly.Module(wasmBuffer), 'isWebAssemblyCompiledModule' ],
]) {
  const method = _method || `is${value.constructor.name}`;
  assert(method in types, `Missing ${method} for ${inspect(value)}`);
  assert(types[method](value), `Want ${inspect(value)} to match ${method}`);

  for (const key of Object.keys(types)) {
    if ((types.isArrayBufferView(value) ||
         types.isAnyArrayBuffer(value)) && key.includes('Array') ||
         key === 'isBoxedPrimitive') {
      continue;
    }

    assert.strictEqual(types[key](value),
                       key === method,
                       `${inspect(value)}: ${key}, ` +
                       `${method}, ${types[key](value)}`);
  }
}

// Check boxed primitives.
[
  new Boolean(),
  new Number(),
  new String(),
  Object(Symbol()),
  Object(BigInt(0))
].forEach((entry) => assert(types.isBoxedPrimitive(entry)));

{
  assert(!types.isUint8Array({ [Symbol.toStringTag]: 'Uint8Array' }));
  assert(types.isUint8Array(vm.runInNewContext('new Uint8Array')));

  assert(!types.isUint8ClampedArray({
    [Symbol.toStringTag]: 'Uint8ClampedArray'
  }));
  assert(types.isUint8ClampedArray(
    vm.runInNewContext('new Uint8ClampedArray')
  ));

  assert(!types.isUint16Array({ [Symbol.toStringTag]: 'Uint16Array' }));
  assert(types.isUint16Array(vm.runInNewContext('new Uint16Array')));

  assert(!types.isUint32Array({ [Symbol.toStringTag]: 'Uint32Array' }));
  assert(types.isUint32Array(vm.runInNewContext('new Uint32Array')));

  assert(!types.isInt8Array({ [Symbol.toStringTag]: 'Int8Array' }));
  assert(types.isInt8Array(vm.runInNewContext('new Int8Array')));

  assert(!types.isInt16Array({ [Symbol.toStringTag]: 'Int16Array' }));
  assert(types.isInt16Array(vm.runInNewContext('new Int16Array')));

  assert(!types.isInt32Array({ [Symbol.toStringTag]: 'Int32Array' }));
  assert(types.isInt32Array(vm.runInNewContext('new Int32Array')));

  assert(!types.isFloat32Array({ [Symbol.toStringTag]: 'Float32Array' }));
  assert(types.isFloat32Array(vm.runInNewContext('new Float32Array')));

  assert(!types.isFloat64Array({ [Symbol.toStringTag]: 'Float64Array' }));
  assert(types.isFloat64Array(vm.runInNewContext('new Float64Array')));

  assert(!types.isBigInt64Array({ [Symbol.toStringTag]: 'BigInt64Array' }));
  assert(types.isBigInt64Array(vm.runInNewContext('new BigInt64Array')));

  assert(!types.isBigUint64Array({ [Symbol.toStringTag]: 'BigUint64Array' }));
  assert(types.isBigUint64Array(vm.runInNewContext('new BigUint64Array')));
}

{
  const primitive = true;
  const arrayBuffer = new ArrayBuffer();
  const buffer = Buffer.from(arrayBuffer);
  const dataView = new DataView(arrayBuffer);
  const uint8Array = new Uint8Array(arrayBuffer);
  const uint8ClampedArray = new Uint8ClampedArray(arrayBuffer);
  const uint16Array = new Uint16Array(arrayBuffer);
  const uint32Array = new Uint32Array(arrayBuffer);
  const int8Array = new Int8Array(arrayBuffer);
  const int16Array = new Int16Array(arrayBuffer);
  const int32Array = new Int32Array(arrayBuffer);
  const float32Array = new Float32Array(arrayBuffer);
  const float64Array = new Float64Array(arrayBuffer);
  const bigInt64Array = new BigInt64Array(arrayBuffer);
  const bigUint64Array = new BigUint64Array(arrayBuffer);

  const fakeBuffer = Object.create(Buffer.prototype);
  const fakeDataView = Object.create(DataView.prototype);
  const fakeUint8Array = Object.create(Uint8Array.prototype);
  const fakeUint8ClampedArray = Object.create(Uint8ClampedArray.prototype);
  const fakeUint16Array = Object.create(Uint16Array.prototype);
  const fakeUint32Array = Object.create(Uint32Array.prototype);
  const fakeInt8Array = Object.create(Int8Array.prototype);
  const fakeInt16Array = Object.create(Int16Array.prototype);
  const fakeInt32Array = Object.create(Int32Array.prototype);
  const fakeFloat32Array = Object.create(Float32Array.prototype);
  const fakeFloat64Array = Object.create(Float64Array.prototype);
  const fakeBigInt64Array = Object.create(BigInt64Array.prototype);
  const fakeBigUint64Array = Object.create(BigUint64Array.prototype);

  const stealthyDataView =
    Object.setPrototypeOf(new DataView(arrayBuffer), Uint8Array.prototype);
  const stealthyUint8Array =
    Object.setPrototypeOf(new Uint8Array(arrayBuffer), ArrayBuffer.prototype);
  const stealthyUint8ClampedArray =
    Object.setPrototypeOf(
      new Uint8ClampedArray(arrayBuffer), ArrayBuffer.prototype
    );
  const stealthyUint16Array =
    Object.setPrototypeOf(new Uint16Array(arrayBuffer), Uint16Array.prototype);
  const stealthyUint32Array =
    Object.setPrototypeOf(new Uint32Array(arrayBuffer), Uint32Array.prototype);
  const stealthyInt8Array =
    Object.setPrototypeOf(new Int8Array(arrayBuffer), Int8Array.prototype);
  const stealthyInt16Array =
    Object.setPrototypeOf(new Int16Array(arrayBuffer), Int16Array.prototype);
  const stealthyInt32Array =
    Object.setPrototypeOf(new Int32Array(arrayBuffer), Int32Array.prototype);
  const stealthyFloat32Array =
    Object.setPrototypeOf(
      new Float32Array(arrayBuffer), Float32Array.prototype
    );
  const stealthyFloat64Array =
    Object.setPrototypeOf(
      new Float64Array(arrayBuffer), Float64Array.prototype
    );
  const stealthyBigInt64Array =
    Object.setPrototypeOf(
      new BigInt64Array(arrayBuffer), BigInt64Array.prototype
    );
  const stealthyBigUint64Array =
    Object.setPrototypeOf(
      new BigUint64Array(arrayBuffer), BigUint64Array.prototype
    );

  const all = [
    primitive, arrayBuffer, buffer, fakeBuffer,
    dataView, fakeDataView, stealthyDataView,
    uint8Array, fakeUint8Array, stealthyUint8Array,
    uint8ClampedArray, fakeUint8ClampedArray, stealthyUint8ClampedArray,
    uint16Array, fakeUint16Array, stealthyUint16Array,
    uint32Array, fakeUint32Array, stealthyUint32Array,
    int8Array, fakeInt8Array, stealthyInt8Array,
    int16Array, fakeInt16Array, stealthyInt16Array,
    int32Array, fakeInt32Array, stealthyInt32Array,
    float32Array, fakeFloat32Array, stealthyFloat32Array,
    float64Array, fakeFloat64Array, stealthyFloat64Array,
    bigInt64Array, fakeBigInt64Array, stealthyBigInt64Array,
    bigUint64Array, fakeBigUint64Array, stealthyBigUint64Array
  ];

  const expected = {
    isArrayBufferView: [
      buffer,
      dataView, stealthyDataView,
      uint8Array, stealthyUint8Array,
      uint8ClampedArray, stealthyUint8ClampedArray,
      uint16Array, stealthyUint16Array,
      uint32Array, stealthyUint32Array,
      int8Array, stealthyInt8Array,
      int16Array, stealthyInt16Array,
      int32Array, stealthyInt32Array,
      float32Array, stealthyFloat32Array,
      float64Array, stealthyFloat64Array,
      bigInt64Array, stealthyBigInt64Array,
      bigUint64Array, stealthyBigUint64Array
    ],
    isTypedArray: [
      buffer,
      uint8Array, stealthyUint8Array,
      uint8ClampedArray, stealthyUint8ClampedArray,
      uint16Array, stealthyUint16Array,
      uint32Array, stealthyUint32Array,
      int8Array, stealthyInt8Array,
      int16Array, stealthyInt16Array,
      int32Array, stealthyInt32Array,
      float32Array, stealthyFloat32Array,
      float64Array, stealthyFloat64Array,
      bigInt64Array, stealthyBigInt64Array,
      bigUint64Array, stealthyBigUint64Array
    ],
    isUint8Array: [
      buffer, uint8Array, stealthyUint8Array
    ],
    isUint8ClampedArray: [
      uint8ClampedArray, stealthyUint8ClampedArray
    ],
    isUint16Array: [
      uint16Array, stealthyUint16Array
    ],
    isUint32Array: [
      uint32Array, stealthyUint32Array
    ],
    isInt8Array: [
      int8Array, stealthyInt8Array
    ],
    isInt16Array: [
      int16Array, stealthyInt16Array
    ],
    isInt32Array: [
      int32Array, stealthyInt32Array
    ],
    isFloat32Array: [
      float32Array, stealthyFloat32Array
    ],
    isFloat64Array: [
      float64Array, stealthyFloat64Array
    ],
    isBigInt64Array: [
      bigInt64Array, stealthyBigInt64Array
    ],
    isBigUint64Array: [
      bigUint64Array, stealthyBigUint64Array
    ]
  };

  for (const testedFunc of Object.keys(expected)) {
    const func = types[testedFunc];
    const yup = [];
    for (const value of all) {
      if (func(value)) {
        yup.push(value);
      }
    }
    console.log('Testing', testedFunc);
    assert.deepStrictEqual(yup, expected[testedFunc]);
  }
}

// (async () => {
//   const m = new vm.SourceTextModule('');
//   await m.link(() => 0);
//   m.instantiate();
//   await m.evaluate();
//   assert.ok(types.isModuleNamespaceObject(m.namespace));
// })();
<commit_msg>Test against userland util.types<commit_after>// Currently in sync with Node.js test/parallel/test-util-types.js
// https://github.com/nodejs/node/commit/519a11b24fa453e5cefe13df10ab9696616b5b91

// Flags: --experimental-vm-modules --expose-internals
'use strict';
require('./common');
const assert = require('assert');
const { types } = require('../../');
const vm = require('vm');

const inspect = value => {
  try {
    return JSON.stringify(value);
  } catch (e) {
    return `${typeof value}: ${value}`;
  }
};

// [browserify] We can't test this in userland
// const { internalBinding } = require('internal/test/binding');
// const { JSStream } = internalBinding('js_stream');
// const external = (new JSStream())._externalStream;

const wasmBuffer = Buffer.from('0061736d01000000', 'hex');

for (const [ value, _method ] of [
  // [ external, 'isExternal' ],
  [ new Date() ],
  [ (function() { return arguments; })(), 'isArgumentsObject' ],
  [ new Boolean(), 'isBooleanObject' ],
  [ new Number(), 'isNumberObject' ],
  [ new String(), 'isStringObject' ],
  [ Object(Symbol()), 'isSymbolObject' ],
  [ Object(BigInt(0)), 'isBigIntObject' ],
  // [ new Error(), 'isNativeError' ],
  [ new RegExp() ],
  [ async function() {}, 'isAsyncFunction' ],
  [ function*() {}, 'isGeneratorFunction' ],
  [ (function*() {})(), 'isGeneratorObject' ],
  [ Promise.resolve() ],
  [ new Map() ],
  [ new Set() ],
  [ (new Map())[Symbol.iterator](), 'isMapIterator' ],
  [ (new Set())[Symbol.iterator](), 'isSetIterator' ],
  [ new WeakMap() ],
  [ new WeakSet() ],
  [ new ArrayBuffer() ],
  [ new Uint8Array() ],
  [ new Uint8ClampedArray() ],
  [ new Uint16Array() ],
  [ new Uint32Array() ],
  [ new Int8Array() ],
  [ new Int16Array() ],
  [ new Int32Array() ],
  [ new Float32Array() ],
  [ new Float64Array() ],
  [ new BigInt64Array() ],
  [ new BigUint64Array() ],
  [ Object.defineProperty(new Uint8Array(),
                          Symbol.toStringTag,
                          { value: 'foo' }) ],
  [ new DataView(new ArrayBuffer()) ],
  [ new SharedArrayBuffer() ],
  // [ new Proxy({}, {}), 'isProxy' ],
  [ new WebAssembly.Module(wasmBuffer), 'isWebAssemblyCompiledModule' ],
]) {
  const method = _method || `is${value.constructor.name}`;
  assert(method in types, `Missing ${method} for ${inspect(value)}`);
  assert(types[method](value), `Want ${inspect(value)} to match ${method}`);

  for (const key of Object.keys(types)) {
    if ((types.isArrayBufferView(value) ||
         types.isAnyArrayBuffer(value)) && key.includes('Array') ||
         key === 'isBoxedPrimitive') {
      continue;
    }

    assert.strictEqual(types[key](value),
                       key === method,
                       `${inspect(value)}: ${key}, ` +
                       `${method}, ${types[key](value)}`);
  }
}

// Check boxed primitives.
[
  new Boolean(),
  new Number(),
  new String(),
  Object(Symbol()),
  Object(BigInt(0))
].forEach((entry) => assert(types.isBoxedPrimitive(entry)));

{
  assert(!types.isUint8Array({ [Symbol.toStringTag]: 'Uint8Array' }));
  assert(types.isUint8Array(vm.runInNewContext('new Uint8Array')));

  assert(!types.isUint8ClampedArray({
    [Symbol.toStringTag]: 'Uint8ClampedArray'
  }));
  assert(types.isUint8ClampedArray(
    vm.runInNewContext('new Uint8ClampedArray')
  ));

  assert(!types.isUint16Array({ [Symbol.toStringTag]: 'Uint16Array' }));
  assert(types.isUint16Array(vm.runInNewContext('new Uint16Array')));

  assert(!types.isUint32Array({ [Symbol.toStringTag]: 'Uint32Array' }));
  assert(types.isUint32Array(vm.runInNewContext('new Uint32Array')));

  assert(!types.isInt8Array({ [Symbol.toStringTag]: 'Int8Array' }));
  assert(types.isInt8Array(vm.runInNewContext('new Int8Array')));

  assert(!types.isInt16Array({ [Symbol.toStringTag]: 'Int16Array' }));
  assert(types.isInt16Array(vm.runInNewContext('new Int16Array')));

  assert(!types.isInt32Array({ [Symbol.toStringTag]: 'Int32Array' }));
  assert(types.isInt32Array(vm.runInNewContext('new Int32Array')));

  assert(!types.isFloat32Array({ [Symbol.toStringTag]: 'Float32Array' }));
  assert(types.isFloat32Array(vm.runInNewContext('new Float32Array')));

  assert(!types.isFloat64Array({ [Symbol.toStringTag]: 'Float64Array' }));
  assert(types.isFloat64Array(vm.runInNewContext('new Float64Array')));

  assert(!types.isBigInt64Array({ [Symbol.toStringTag]: 'BigInt64Array' }));
  assert(types.isBigInt64Array(vm.runInNewContext('new BigInt64Array')));

  assert(!types.isBigUint64Array({ [Symbol.toStringTag]: 'BigUint64Array' }));
  assert(types.isBigUint64Array(vm.runInNewContext('new BigUint64Array')));
}

{
  const primitive = true;
  const arrayBuffer = new ArrayBuffer();
  const buffer = Buffer.from(arrayBuffer);
  const dataView = new DataView(arrayBuffer);
  const uint8Array = new Uint8Array(arrayBuffer);
  const uint8ClampedArray = new Uint8ClampedArray(arrayBuffer);
  const uint16Array = new Uint16Array(arrayBuffer);
  const uint32Array = new Uint32Array(arrayBuffer);
  const int8Array = new Int8Array(arrayBuffer);
  const int16Array = new Int16Array(arrayBuffer);
  const int32Array = new Int32Array(arrayBuffer);
  const float32Array = new Float32Array(arrayBuffer);
  const float64Array = new Float64Array(arrayBuffer);
  const bigInt64Array = new BigInt64Array(arrayBuffer);
  const bigUint64Array = new BigUint64Array(arrayBuffer);

  const fakeBuffer = Object.create(Buffer.prototype);
  const fakeDataView = Object.create(DataView.prototype);
  const fakeUint8Array = Object.create(Uint8Array.prototype);
  const fakeUint8ClampedArray = Object.create(Uint8ClampedArray.prototype);
  const fakeUint16Array = Object.create(Uint16Array.prototype);
  const fakeUint32Array = Object.create(Uint32Array.prototype);
  const fakeInt8Array = Object.create(Int8Array.prototype);
  const fakeInt16Array = Object.create(Int16Array.prototype);
  const fakeInt32Array = Object.create(Int32Array.prototype);
  const fakeFloat32Array = Object.create(Float32Array.prototype);
  const fakeFloat64Array = Object.create(Float64Array.prototype);
  const fakeBigInt64Array = Object.create(BigInt64Array.prototype);
  const fakeBigUint64Array = Object.create(BigUint64Array.prototype);

  const stealthyDataView =
    Object.setPrototypeOf(new DataView(arrayBuffer), Uint8Array.prototype);
  const stealthyUint8Array =
    Object.setPrototypeOf(new Uint8Array(arrayBuffer), ArrayBuffer.prototype);
  const stealthyUint8ClampedArray =
    Object.setPrototypeOf(
      new Uint8ClampedArray(arrayBuffer), ArrayBuffer.prototype
    );
  const stealthyUint16Array =
    Object.setPrototypeOf(new Uint16Array(arrayBuffer), Uint16Array.prototype);
  const stealthyUint32Array =
    Object.setPrototypeOf(new Uint32Array(arrayBuffer), Uint32Array.prototype);
  const stealthyInt8Array =
    Object.setPrototypeOf(new Int8Array(arrayBuffer), Int8Array.prototype);
  const stealthyInt16Array =
    Object.setPrototypeOf(new Int16Array(arrayBuffer), Int16Array.prototype);
  const stealthyInt32Array =
    Object.setPrototypeOf(new Int32Array(arrayBuffer), Int32Array.prototype);
  const stealthyFloat32Array =
    Object.setPrototypeOf(
      new Float32Array(arrayBuffer), Float32Array.prototype
    );
  const stealthyFloat64Array =
    Object.setPrototypeOf(
      new Float64Array(arrayBuffer), Float64Array.prototype
    );
  const stealthyBigInt64Array =
    Object.setPrototypeOf(
      new BigInt64Array(arrayBuffer), BigInt64Array.prototype
    );
  const stealthyBigUint64Array =
    Object.setPrototypeOf(
      new BigUint64Array(arrayBuffer), BigUint64Array.prototype
    );

  const all = [
    primitive, arrayBuffer, buffer, fakeBuffer,
    dataView, fakeDataView, stealthyDataView,
    uint8Array, fakeUint8Array, stealthyUint8Array,
    uint8ClampedArray, fakeUint8ClampedArray, stealthyUint8ClampedArray,
    uint16Array, fakeUint16Array, stealthyUint16Array,
    uint32Array, fakeUint32Array, stealthyUint32Array,
    int8Array, fakeInt8Array, stealthyInt8Array,
    int16Array, fakeInt16Array, stealthyInt16Array,
    int32Array, fakeInt32Array, stealthyInt32Array,
    float32Array, fakeFloat32Array, stealthyFloat32Array,
    float64Array, fakeFloat64Array, stealthyFloat64Array,
    bigInt64Array, fakeBigInt64Array, stealthyBigInt64Array,
    bigUint64Array, fakeBigUint64Array, stealthyBigUint64Array
  ];

  const expected = {
    isArrayBufferView: [
      buffer,
      dataView, stealthyDataView,
      uint8Array, stealthyUint8Array,
      uint8ClampedArray, stealthyUint8ClampedArray,
      uint16Array, stealthyUint16Array,
      uint32Array, stealthyUint32Array,
      int8Array, stealthyInt8Array,
      int16Array, stealthyInt16Array,
      int32Array, stealthyInt32Array,
      float32Array, stealthyFloat32Array,
      float64Array, stealthyFloat64Array,
      bigInt64Array, stealthyBigInt64Array,
      bigUint64Array, stealthyBigUint64Array
    ],
    isTypedArray: [
      buffer,
      uint8Array, stealthyUint8Array,
      uint8ClampedArray, stealthyUint8ClampedArray,
      uint16Array, stealthyUint16Array,
      uint32Array, stealthyUint32Array,
      int8Array, stealthyInt8Array,
      int16Array, stealthyInt16Array,
      int32Array, stealthyInt32Array,
      float32Array, stealthyFloat32Array,
      float64Array, stealthyFloat64Array,
      bigInt64Array, stealthyBigInt64Array,
      bigUint64Array, stealthyBigUint64Array
    ],
    isUint8Array: [
      buffer, uint8Array, stealthyUint8Array
    ],
    isUint8ClampedArray: [
      uint8ClampedArray, stealthyUint8ClampedArray
    ],
    isUint16Array: [
      uint16Array, stealthyUint16Array
    ],
    isUint32Array: [
      uint32Array, stealthyUint32Array
    ],
    isInt8Array: [
      int8Array, stealthyInt8Array
    ],
    isInt16Array: [
      int16Array, stealthyInt16Array
    ],
    isInt32Array: [
      int32Array, stealthyInt32Array
    ],
    isFloat32Array: [
      float32Array, stealthyFloat32Array
    ],
    isFloat64Array: [
      float64Array, stealthyFloat64Array
    ],
    isBigInt64Array: [
      bigInt64Array, stealthyBigInt64Array
    ],
    isBigUint64Array: [
      bigUint64Array, stealthyBigUint64Array
    ]
  };

  for (const testedFunc of Object.keys(expected)) {
    const func = types[testedFunc];
    const yup = [];
    for (const value of all) {
      if (func(value)) {
        yup.push(value);
      }
    }
    console.log('Testing', testedFunc);
    assert.deepStrictEqual(yup, expected[testedFunc]);
  }
}

// (async () => {
//   const m = new vm.SourceTextModule('');
//   await m.link(() => 0);
//   m.instantiate();
//   await m.evaluate();
//   assert.ok(types.isModuleNamespaceObject(m.namespace));
// })();
<|endoftext|>


<commit_before>goog.require('ol.Map');
goog.require('ol.RendererHint');
goog.require('ol.View2D');
goog.require('ol.layer.Tile');
goog.require('ol.layer.Vector');
goog.require('ol.source.GeoJSON');
goog.require('ol.source.OSM');

var geoJSONSource = new ol.source.GeoJSON(
    /** @type {ol.source.GeoJSONOptions} */ ({
      geoJSON: {
        'type': 'FeatureCollection',
        features: [
          {
            'type': 'Feature',
            'geometry': {
              'type': 'Point',
              'coordinates': [0, 0]
            }
          },
          {
            'type': 'Feature',
            'geometry': {
              'type': 'LineString',
              'coordinates': [[-1e7, -1e7], [1e7, 1e7]]
            }
          },
          {
            'type': 'Feature',
            'geometry': {
              'type': 'LineString',
              'coordinates': [[-1e7, 1e7], [1e7, -1e7]]
            }
          },
          {
            'type': 'Feature',
            'geometry': {
              'type': 'Polygon',
              'coordinates': [[[-5e6, -5e6], [0, 5e6], [5e6, -5e6]]]
            }
          }
        ]
      }
    }));

var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    }),
    new ol.layer.Vector({
      source: geoJSONSource
    })
  ],
  renderer: ol.RendererHint.CANVAS,
  target: 'map',
  view: new ol.View2D({
    center: [0, 0],
    zoom: 2
  })
});
<commit_msg>Add MultiLineString to GeoJSON demo<commit_after>goog.require('ol.Map');
goog.require('ol.RendererHint');
goog.require('ol.View2D');
goog.require('ol.layer.Tile');
goog.require('ol.layer.Vector');
goog.require('ol.source.GeoJSON');
goog.require('ol.source.OSM');

var geoJSONSource = new ol.source.GeoJSON(
    /** @type {ol.source.GeoJSONOptions} */ ({
      geoJSON: {
        'type': 'FeatureCollection',
        features: [
          {
            'type': 'Feature',
            'geometry': {
              'type': 'Point',
              'coordinates': [0, 0]
            }
          },
          {
            'type': 'Feature',
            'geometry': {
              'type': 'LineString',
              'coordinates': [[-1e7, -1e7], [1e7, 1e7]]
            }
          },
          {
            'type': 'Feature',
            'geometry': {
              'type': 'LineString',
              'coordinates': [[-1e7, 1e7], [1e7, -1e7]]
            }
          },
          {
            'type': 'Feature',
            'geometry': {
              'type': 'Polygon',
              'coordinates': [[[-5e6, -5e6], [0, 5e6], [5e6, -5e6]]]
            }
          },
          {
            'type': 'Feature',
            'geometry': {
              'type': 'MultiLineString',
              'coordinates': [
                [[-1e6, -7.5e5], [-1e6, 7.5e5]],
                [[1e6, -7.5e5], [1e6, 7.5e5]],
                [[-7.5e5, -1e6], [7.5e5, -1e6]],
                [[-7.5e5, 1e6], [7.5e5, 1e6]]
              ]
            }
          }
        ]
      }
    }));

var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    }),
    new ol.layer.Vector({
      source: geoJSONSource
    })
  ],
  renderer: ol.RendererHint.CANVAS,
  target: 'map',
  view: new ol.View2D({
    center: [0, 0],
    zoom: 2
  })
});
<|endoftext|>


<commit_before>
import React from 'react';
import { expect } from 'chai';
import { shallow, mount, render } from 'enzyme';
import Panel from '../src/components/panel.jsx';
import sinon from 'sinon';
import form from './forms/empty.json';

var components = require('./forms/componentSpec.js');

describe('Panel', function () {
  describe(' Panel component', function () {
    var component= {
      "input": false,
      "title": "testpanel",
      "theme": "warning",
      "components": [
        components.textfeild,
        components.password,
        components.phoneNumber
      ],
      "type": "panel",
      "conditional": {
        "show": "",
        "when": null,
        "eq": ""
      }
    };
    var attachToForm = sinon.spy();

    it('Renders a basic panel component', function (done) {
      const element = shallow(<Panel
        component={component}
        attachToForm={attachToForm}
        {...this.props} />)
      expect(element.find('.panel').length).to.equal(1);
      done();
    });

    it('Test the theme of panel component', function (done) {
      const element = shallow(<Panel
        component={component}
        attachToForm={attachToForm}
        {...this.props} />).find('.panel');
      expect(element.nodes[0].props.className).to.equal('panel panel-' + component.theme + ' ');
      done();
    });

    it('Test the label of panel component', function (done) {
      const element = shallow(<Panel
        component={component}
        attachToForm={attachToForm}
        {...this.props} />).find('.panel');
      expect(element.nodes[0].props.children[0].props.className).to.equal('panel-heading');
      expect(element.nodes[0].props.children[0].props.children.props.className).to.equal('panel-title');
      done();
    });

    it('Check the nested components of Panel', function (done) {
      const element = shallow(<Panel
        component={component}
        attachToForm={attachToForm}
        {...this.props} />).find('.panel-body');

      //To test type of nested components of panel
      for (var i= 0; i<component.components.length; i++) {
        expect(element.nodes[0].props.children.props.component.components[i].type).to.equal(component.components[i].type);
      }
      done();
    });

  });

});
<commit_msg>Transferring props is not needed, as we passed the component to shallow directly.<commit_after>
import React from 'react';
import { expect } from 'chai';
import { shallow, mount, render } from 'enzyme';
import Panel from '../src/components/panel.jsx';
import sinon from 'sinon';
import form from './forms/empty.json';

var components = require('./forms/componentSpec.js');

describe('Panel', function () {
  describe(' Panel component', function () {
    var component= {
      "input": false,
      "title": "testpanel",
      "theme": "warning",
      "components": [
        components.textfeild,
        components.password,
        components.phoneNumber
      ],
      "type": "panel",
      "conditional": {
        "show": "",
        "when": null,
        "eq": ""
      }
    };
    var attachToForm = sinon.spy();

    it('Renders a basic panel component', function (done) {
      const element = shallow(<Panel
        component={component}
        attachToForm={attachToForm}
        />)
      expect(element.find('.panel').length).to.equal(1);
      done();
    });

    it('Test the theme of panel component', function (done) {
      const element = shallow(<Panel
        component={component}
        attachToForm={attachToForm}
        />).find('.panel');
      expect(element.nodes[0].props.className).to.equal('panel panel-' + component.theme + ' ');
      done();
    });

    it('Test the label of panel component', function (done) {
      const element = shallow(<Panel
        component={component}
        attachToForm={attachToForm}
        />).find('.panel');
      expect(element.nodes[0].props.children[0].props.className).to.equal('panel-heading');
      expect(element.nodes[0].props.children[0].props.children.props.className).to.equal('panel-title');
      done();
    });

    it('Check the nested components of Panel', function (done) {
      const element = shallow(<Panel
        component={component}
        attachToForm={attachToForm}
        />).find('.panel-body');

      //To test type of nested components of panel
      for (var i= 0; i<component.components.length; i++) {
        expect(element.nodes[0].props.children.props.component.components[i].type).to.equal(component.components[i].type);
      }
      done();
    });

  });

});
<|endoftext|>


<commit_before>define(['jquery', 'backbone', 'underscore'], function($, Backbone, _){
    var InfiniteScrollView = Backbone.View.extend({
        // Generic InfiniteScrollView implementation
        scrollCallbacks: [function(){ console.log("Scrolled!"); }],
        infiniteScrollEnabled: true,

        // Used to capture once a scroll has occured and on which element
        elScrolled: false,
        windowScrolled: false,

        handleScroll: function() {
            // Are we enabled? Has anything been scrolled?
            if ((this.infiniteScrollEnabled) && (this.windowScrolled || this.elScrolled)) {
                this.infiniteScrollEnabled = false; // Infinite scroll disabled for duration of handling 1 event
                var thresholdSurpassed = false;
                if (this.scrollThreshold) {
                    if (this.elScrolled) {
                        thresholdSurpassed = ((this.scrollElement.scrollTop / this.scrollElement.scrollHeight) > this.scrollThreshold);
                    } else {
                        thresholdSurpassed = (($(document).scrollTop() / $(document).height()) > this.scrollThreshold);
                    }
                }
                // Call our callbacks with the correct `this` context
                if ((this.scrollThreshold && thresholdSurpassed) || !this.scrollThreshold) {
                    _.each(this.scrollCallbacks, _.bind(function(cb) { cb.apply(this); }, this));
                }
                this.infiniteScrollEnabled = true;
                this.windowScrolled = false;
                this.elScrolled = false;
            }
        },

        initScroll: function(windowScroll, scrollElement) {
            // Initialises the scroll event handlers and sets an interval to observe them
            // `windowScroll` should be a boolean saying if we want to listen to window.scroll events
            // `scrollElement` is an optional DOM element we want to listen to scroll events for
            if (windowScroll) {
                $(window).scroll(
                    _.bind(function(){ this.windowScrolled = true; }, this)
                );
            }
            if (scrollElement) {
                this.scrollElement = scrollElement;
                $(scrollElement).scroll(
                    _.bind(function(){ this.elScrolled = true; }, this)
                );
            }
            if (windowScroll || scrollElement) {
                this.scrollInterval = window.setInterval(_.bind(this.handleScroll, this), 250); // limit to 250ms per Mr. Resig's suggestion
            }
        },

        onClose: function() {
            if (this.scrollInterval) {
                // Stop looking for scroll events
                window.clearInterval(this.scrollInterval);
            }
        }
    });
    return InfiniteScrollView;
});
<commit_msg>Updated use an options object for optional arguments<commit_after>define(['jquery', 'backbone', 'underscore'], function($, Backbone, _){
    var InfiniteScrollView = Backbone.View.extend({
        // Generic InfiniteScrollView implementation
        scrollCallbacks: [function(){ console.log("Scrolled!"); }],
        infiniteScrollEnabled: true,

        // Used to capture once a scroll has occured and on which element
        elScrolled: false,
        windowScrolled: false,

        handleScroll: function() {
            // Are we enabled? Has anything been scrolled?
            if ((this.infiniteScrollEnabled) && (this.windowScrolled || this.elScrolled)) {
                this.infiniteScrollEnabled = false; // Infinite scroll disabled for duration of handling 1 event
                var thresholdSurpassed = false;
                if (this.scrollThreshold) {
                    if (this.elScrolled) {
                        thresholdSurpassed = ((this.scrollElement.scrollTop / this.scrollElement.scrollHeight) > this.scrollThreshold);
                    } else {
                        thresholdSurpassed = (($(document).scrollTop() / $(document).height()) > this.scrollThreshold);
                    }
                }
                // Call our callbacks with the correct `this` context
                if ((this.scrollThreshold && thresholdSurpassed) || !this.scrollThreshold) {
                    _.each(this.scrollCallbacks, _.bind(function(cb) { cb.apply(this); }, this));
                }
                this.infiniteScrollEnabled = true;
                this.windowScrolled = false;
                this.elScrolled = false;
            }
        },

        initScroll: function(options) {
            // Initialises the scroll event handlers and sets an interval to observe them
            // The options object can contain any or none of the following:
            //  * `windowScroll` should be a boolean saying if we want to listen to window.scroll events
            //  * `scrollElement` is an optional DOM element we want to listen to scroll events for
            //  * `intervalPeriod` time in ms which we should check if the user has scrolled
            //  * `scrollThreshold` a floating point integer between 0 and 1 - The ratio representating
            //                      how far down a page scroll should the `scrollCallbacks` be called.
            this.scrollThreshold = options.scrollThreshold ? options.scrollThreshold : null;
            if (options.windowScroll) {
                $(window).scroll(
                    _.bind(function(){ this.windowScrolled = true; }, this)
                );
            }
            if (options.scrollElement) {
                this.scrollElement = options.scrollElement;
                $(options.scrollElement).scroll(
                    _.bind(function(){ this.elScrolled = true; }, this)
                );
            }
            var intervalPeriod = options.intervalPeriod ? options.intervalPeriod : 250; // default of 250ms per Mr. Resig's suggestion
            if (options.windowScroll || options.scrollElement) {
                this.scrollInterval = window.setInterval(_.bind(this.handleScroll, this), intervalPeriod);
            }
        },

        onClose: function() {
            if (this.scrollInterval) {
                // Stop looking for scroll events
                window.clearInterval(this.scrollInterval);
            }
        }
    });
    return InfiniteScrollView;
});
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Service.extend({
  store: Ember.inject.service(),
  feedModel: null,
  createOrFindFeedModel: function() {
    if (this.get('feedModel') == null) {
      var newFeedModel = this.get('store').createRecord('feed', { });
      this.set('feedModel', newFeedModel);
    }
    return this.get('feedModel');
  },
  downloadGtfsArchiveAndParseIntoFeedModel: function(retries) {
    retries = (retries || 60);
    if (retries-- <= 0) {
      throw "Timeout"
    }
    var feedModel = this.createOrFindFeedModel();
    var url = feedModel.get('url');
    var adapter = this.get('store').adapterFor('feeds');
    var fetch_info_url = adapter.urlPrefix()+'/feeds/fetch_info';
    var controller = this;
    var promise = adapter.ajax(fetch_info_url, 'post', {data:{url:url}});
    promise.then(function(response) {
      if (response.status == 'complete') {
        feedModel.set('id', response.feed.onestop_id);
        return response.operators.map(function(operator){feedModel.addOperator(operator)});
      } else if (response.status == 'processing') {
        return Ember.run.later(controller, function(){this.downloadGtfsArchiveAndParseIntoFeedModel(retries)}, 1000);
      }
    });
    return promise
  },
	toChangeset: function() {
    var feedModel = this.createOrFindFeedModel();
    var changes = [];
    changes.push({action:'createUpdate', feed:feedModel.toChange()})
    feedModel.get('operators').map(function(operator){
      changes.push({action:'createUpdate', operator:operator.toChange()})
    });
		var changeset = this.get('store').createRecord('changeset', {
			notes: 'This is a test. TODO put a custom message here.',
			payload: {
				changes: changes
			}
		});
		return changeset;
	}
});
<commit_msg>Move to fetchinfo route for now...<commit_after>import Ember from 'ember';

export default Ember.Service.extend({
  store: Ember.inject.service(),
  feedModel: null,
  createOrFindFeedModel: function() {
    if (this.get('feedModel') == null) {
      var newFeedModel = this.get('store').createRecord('feed', { });
      this.set('feedModel', newFeedModel);
    }
    return this.get('feedModel');
  },
	toChangeset: function() {
    var feedModel = this.createOrFindFeedModel();
    var changes = [];
    changes.push({action:'createUpdate', feed:feedModel.toChange()})
    feedModel.get('operators').map(function(operator){
      changes.push({action:'createUpdate', operator:operator.toChange()})
    });
		var changeset = this.get('store').createRecord('changeset', {
			notes: 'This is a test. TODO put a custom message here.',
			payload: {
				changes: changes
			}
		});
		return changeset;
	}
});
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');

var PREFIX = '#/?',
    PREFIX_REGEXP = /^(#\/\?)+/g,

    SEPARATOR_EQ = '=',
    SEPARATOR_KEYS = '&',
    SEPARATOR_VALUES = '|';

module.exports = function(cursor, keys) {
  var _oldHash;

  function _treeToHash() {
    var hash = [],
        state = cursor.get();

    for (var key in state)
      // Filters:
      if (key === 'filters')
        state.filters.forEach(function(filter) {
          hash.push(
            filter.field + SEPARATOR_EQ + filter.values.join(SEPARATOR_VALUES)
          );
        });
      // Other parameters:
      else if (state[key] && ~keys.indexOf(key))
        hash.push(key + SEPARATOR_EQ + state[key]);

    return PREFIX + hash.join(SEPARATOR_KEYS);
  }

  function _hashToTree() {
    var state = { filters: [] },
        hash = location.hash.replace(PREFIX_REGEXP, '');

    hash.split(SEPARATOR_KEYS).forEach(function(str) {
      var arr = str.split(SEPARATOR_EQ),
          key = arr[0],
          val = arr[1];

      if (!val || !key)
        return;

      if (~keys.indexOf(key))
        state[key] = val;
      else
        state.filters.push({
          field: key,
          values: val.split(SEPARATOR_VALUES)
        });
    });

    return state;
  }

  cursor.on('update', function() {
    location.hash = _treeToHash();
  });

  window.addEventListener('hashchange', function() {
    var hash = location.hash;

    if (hash !== _oldHash) {
      _oldHash = hash;
      var newState = _hashToTree();

      if (!_.isEqual(newState, cursor.get()))
        cursor.set(newState);
    }
  });

  // Boostrap:
  _oldHash = location.hash;
  cursor.set(_hashToTree());
};
<commit_msg>[explore] Fixed #41: Encore / decode URLs<commit_after>'use strict';

var _ = require('lodash');

var PREFIX = '#/?',
    PREFIX_REGEXP = /^(#\/\?)+/g,

    SEPARATOR_EQ = '=',
    SEPARATOR_KEYS = '&',
    SEPARATOR_VALUES = '|';

module.exports = function(cursor, keys) {
  var _oldHash;

  function _treeToHash() {
    var hash = [],
        state = cursor.get();

    for (var key in state)
      // Filters:
      if (key === 'filters')
        state.filters.forEach(function(filter) {
          hash.push(
            filter.field + SEPARATOR_EQ + filter.values.join(SEPARATOR_VALUES)
          );
        });
      // Other parameters:
      else if (state[key] && ~keys.indexOf(key))
        hash.push(key + SEPARATOR_EQ + state[key]);

    return decodeURI(PREFIX + hash.join(SEPARATOR_KEYS));
  }

  function _hashToTree() {
    var state = { filters: [] },
        hash = decodeURI(location.hash.replace(PREFIX_REGEXP, ''));

    hash.split(SEPARATOR_KEYS).forEach(function(str) {
      var arr = str.split(SEPARATOR_EQ),
          key = arr[0],
          val = arr[1];

      if (!val || !key)
        return;

      if (~keys.indexOf(key))
        state[key] = val;
      else
        state.filters.push({
          field: key,
          values: val.split(SEPARATOR_VALUES)
        });
    });

    return state;
  }

  cursor.on('update', function() {
    location.hash = _treeToHash();
  });

  window.addEventListener('hashchange', function() {
    var hash = location.hash;

    if (hash !== _oldHash) {
      _oldHash = hash;
      var newState = _hashToTree();

      if (!_.isEqual(newState, cursor.get()))
        cursor.set(newState);
    }
  });

  // Boostrap:
  _oldHash = location.hash;
  cursor.set(_hashToTree());
};
<|endoftext|>


<commit_before>var module = QUnit.module;
var Enumerable = require('../linq.min');
require("../extensions/linq.qunit.js")({'Enumerable': Enumerable});

module("Projection");

var expected, actual; // will be removed

test("traverseDepthFirst", function () {
    actual = Enumerable.make(1).traverseDepthFirst("$+$").take(7).toArray();
    deepEqual(actual, [1, 2, 4, 8, 16, 32, 64]);
    actual = Enumerable.make(1).traverseDepthFirst("$+$", "v,nl=>{v:v,nl:nl}").take(3).toArray();
    deepEqual(actual, [{ v: 1, nl: 0 }, { v: 2, nl: 1 }, { v: 4, nl: 2 }]);
});

test("traverseBreadthFirst", function () {
    actual = Enumerable.make(1).traverseBreadthFirst("$+$").take(7).toArray();
    deepEqual(actual, [1, 2, 4, 8, 16, 32, 64]);
    actual = Enumerable.make(1).traverseBreadthFirst("$+$", "v,nl=>{v:v,nl:nl}").take(3).toArray();
    deepEqual(actual, [{ v: 1, nl: 0 }, { v: 2, nl: 1 }, { v: 4, nl: 2 }]);
});

test("flatten", function () {
    var array = [1, 31, [431, 41, 5], [1431, 43, [344, 3], 43], 43];
    actual = Enumerable.from(array).flatten().toArray();
    deepEqual(actual, [1, 31, 431, 41, 5, 1431, 43, 344, 3, 43, 43]);
});

test("pairwise", function () {
    actual = Enumerable.range(1, 4).pairwise("prev,next=>{p:prev,n:next}").toArray();
    deepEqual(actual, [{ p: 1, n: 2 }, { p: 2, n: 3 }, { p: 3, n: 4 }]);
});

test("scan", function () {
    actual = Enumerable.range(1, 10).scan("a,b=>a+b").toArray();
    deepEqual(actual, [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]);
    var seed = 100;
    actual = Enumerable.range(1, 10).scan(seed, "a,b=>a+b").toArray();
    deepEqual(actual, [100, 101, 103, 106, 110, 115, 121, 128, 136, 145, 155]);
});

test("select", function () {
    actual = Enumerable.range(1, 10).select("i=>i*10").toArray();
    deepEqual(actual, [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]);
    actual = Enumerable.range(1, 10).select("i,index=>i*10+index").toArray();
    deepEqual(actual, [10, 21, 32, 43, 54, 65, 76, 87, 98, 109]);
});

test("selectMany", function () {
    actual = Enumerable.range(1, 5).selectMany("i=>Enumerable.repeat(i,2)").toArray();
    deepEqual(actual, [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]);
    actual = Enumerable.range(1, 5).selectMany("i,index=>Enumerable.repeat(i,index+1)").toArray();
    deepEqual(actual, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]);
    actual = Enumerable.range(1, 5).selectMany("i=>Enumerable.repeat(i,2)", "i=>i*10").toArray();
    deepEqual(actual, [10, 10, 20, 20, 30, 30, 40, 40, 50, 50]);
    actual = Enumerable.range(1, 5).selectMany("i,index=>Enumerable.repeat(i,index+1)", "i=>i*10").toArray();
    deepEqual(actual, [10, 20, 20, 30, 30, 30, 40, 40, 40, 40, 50, 50, 50, 50, 50]);
});

test("where", function () {
    actual = Enumerable.range(1, 10).where("i=>i%2==0").toArray();
    deepEqual(actual, [2, 4, 6, 8, 10]);
    actual = Enumerable.range(1, 10).where("i,index=>(i+index)%3==0").toArray();
    deepEqual(actual, [2, 5, 8]);
});

test("choose", function () {
    Enumerable.range(1, 10).choose(function (x) {
        return x % 2 == 0 ? null : x;
    }).is(1, 3, 5, 7, 9);

    Enumerable.range(1, 10).choose().is(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
});

test("ofType", function () {
    var seq = Enumerable.from([1, 2, "hoge", "3", 4, true]);
    deepEqual(seq.ofType(Number).toArray(), [1, 2, 4]);
    deepEqual(seq.ofType(String).toArray(), ["hoge", "3"]);
    deepEqual(seq.ofType(Boolean).toArray(), [true]);

    var Cls = function (val) { this.val = val; }
    seq = Enumerable.from([new Cls("a"), new Cls("b"), 1, 2, new Cls("c"), 3]);
    deepEqual(seq.ofType(Cls).select("$.val").toArray(), ["a", "b", "c"]);
});

test("zip", function () {
    actual = Enumerable.range(1, 10).zip(Enumerable.range(20, 5), "outer,inner=>outer+inner").toArray();
    deepEqual(actual, [21, 23, 25, 27, 29]);
    actual = Enumerable.range(1, 10).zip(Enumerable.range(20, 5), "outer,inner,index=>outer+inner+index").toArray();
    deepEqual(actual, [21, 24, 27, 30, 33]);
});

test("zip2", function () {
    [1, 2, 3]
        .zip(
            [-3, 4, 10],
            [5, 6, 7],
            function (x, y, z) { return x * y * z; })
        .is(-15, 48, 210);

    [1, 2, 3]
        .zip(
            [-3, 4, 10],
            [-3, 4, 10],
            function (x, y, z, i) { return i; })
        .is(0, 1, 2);

    [1, 2, 3]
        .zip(
            [-3, 4, 10],
            [-7, 20, 30, 100],
            function (x, y, z) { return x * y + z; })
        .is(-10, 28, 60);

    [1, 2, 3]
        .zip(
            [-3, 4, 10],
            [-7, 20, 30, 100],
            function (x, y, z, i) { return z + i; })
        .is(-7, 21, 32);

    Enumerable.from("abc").zip("fghk", "lmnopq", "stuv", "yz0124", "56780",
        function (a, b, c, d, e, f) { return a + b + c + d + e + f })
    .is("aflsy5", "bgmtz6", "chnu07");
});

test("merge", function () {

    [1, 2, 3].merge([-3, 4, 10]).is(1, -3, 2, 4, 3, 10);

    [1, 2, 3].merge([-3, 4], [-7, 20, 30, 100])
        .is(1, -3, -7, 2, 4, 20, 3, 30, 100);

});
<commit_msg>Fixed projection.selectMany test<commit_after>var module = QUnit.module;
var Enumerable = require('../linq.min');
require("../extensions/linq.qunit.js")({'Enumerable': Enumerable});

module("Projection");

var expected, actual; // will be removed

test("traverseDepthFirst", function () {
    actual = Enumerable.make(1).traverseDepthFirst("$+$").take(7).toArray();
    deepEqual(actual, [1, 2, 4, 8, 16, 32, 64]);
    actual = Enumerable.make(1).traverseDepthFirst("$+$", "v,nl=>{v:v,nl:nl}").take(3).toArray();
    deepEqual(actual, [{ v: 1, nl: 0 }, { v: 2, nl: 1 }, { v: 4, nl: 2 }]);
});

test("traverseBreadthFirst", function () {
    actual = Enumerable.make(1).traverseBreadthFirst("$+$").take(7).toArray();
    deepEqual(actual, [1, 2, 4, 8, 16, 32, 64]);
    actual = Enumerable.make(1).traverseBreadthFirst("$+$", "v,nl=>{v:v,nl:nl}").take(3).toArray();
    deepEqual(actual, [{ v: 1, nl: 0 }, { v: 2, nl: 1 }, { v: 4, nl: 2 }]);
});

test("flatten", function () {
    var array = [1, 31, [431, 41, 5], [1431, 43, [344, 3], 43], 43];
    actual = Enumerable.from(array).flatten().toArray();
    deepEqual(actual, [1, 31, 431, 41, 5, 1431, 43, 344, 3, 43, 43]);
});

test("pairwise", function () {
    actual = Enumerable.range(1, 4).pairwise("prev,next=>{p:prev,n:next}").toArray();
    deepEqual(actual, [{ p: 1, n: 2 }, { p: 2, n: 3 }, { p: 3, n: 4 }]);
});

test("scan", function () {
    actual = Enumerable.range(1, 10).scan("a,b=>a+b").toArray();
    deepEqual(actual, [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]);
    var seed = 100;
    actual = Enumerable.range(1, 10).scan(seed, "a,b=>a+b").toArray();
    deepEqual(actual, [100, 101, 103, 106, 110, 115, 121, 128, 136, 145, 155]);
});

test("select", function () {
    actual = Enumerable.range(1, 10).select("i=>i*10").toArray();
    deepEqual(actual, [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]);
    actual = Enumerable.range(1, 10).select("i,index=>i*10+index").toArray();
    deepEqual(actual, [10, 21, 32, 43, 54, 65, 76, 87, 98, 109]);
});

test("selectMany", function () {
    actual = Enumerable.range(1, 5).selectMany("i=>this.repeat(i,2)").toArray();
    deepEqual(actual, [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]);
    actual = Enumerable.range(1, 5).selectMany("i,index=>this.repeat(i,index+1)").toArray();
    deepEqual(actual, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]);
    actual = Enumerable.range(1, 5).selectMany("i=>this.repeat(i,2)", "i=>i*10").toArray();
    deepEqual(actual, [10, 10, 20, 20, 30, 30, 40, 40, 50, 50]);
    actual = Enumerable.range(1, 5).selectMany("i,index=>this.repeat(i,index+1)", "i=>i*10").toArray();
    deepEqual(actual, [10, 20, 20, 30, 30, 30, 40, 40, 40, 40, 50, 50, 50, 50, 50]);

    actual = Enumerable.range(1, 5)
                       .selectMany(function(i) { return Enumerable.repeat(i, 2); })
                       .toArray();
    deepEqual(actual, [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]);
    actual = Enumerable.range(1, 5)
                       .selectMany(function(i, index) { return Enumerable.repeat(i, index + 1); })
                       .toArray();
    deepEqual(actual, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]);
    actual = Enumerable.range(1, 5)
                       .selectMany(function(i) { return Enumerable.repeat(i, 2); }, "i=>i*10")
                       .toArray();
    deepEqual(actual, [10, 10, 20, 20, 30, 30, 40, 40, 50, 50]);
    actual = Enumerable.range(1, 5)
                       .selectMany(function(i, index) { return Enumerable.repeat(i, index + 1); }, "i=>i*10")
                       .toArray();
    deepEqual(actual, [10, 20, 20, 30, 30, 30, 40, 40, 40, 40, 50, 50, 50, 50, 50]);
});

test("where", function () {
    actual = Enumerable.range(1, 10).where("i=>i%2==0").toArray();
    deepEqual(actual, [2, 4, 6, 8, 10]);
    actual = Enumerable.range(1, 10).where("i,index=>(i+index)%3==0").toArray();
    deepEqual(actual, [2, 5, 8]);
});

test("choose", function () {
    Enumerable.range(1, 10).choose(function (x) {
        return x % 2 == 0 ? null : x;
    }).is(1, 3, 5, 7, 9);

    Enumerable.range(1, 10).choose().is(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
});

test("ofType", function () {
    var seq = Enumerable.from([1, 2, "hoge", "3", 4, true]);
    deepEqual(seq.ofType(Number).toArray(), [1, 2, 4]);
    deepEqual(seq.ofType(String).toArray(), ["hoge", "3"]);
    deepEqual(seq.ofType(Boolean).toArray(), [true]);

    var Cls = function (val) { this.val = val; }
    seq = Enumerable.from([new Cls("a"), new Cls("b"), 1, 2, new Cls("c"), 3]);
    deepEqual(seq.ofType(Cls).select("$.val").toArray(), ["a", "b", "c"]);
});

test("zip", function () {
    actual = Enumerable.range(1, 10).zip(Enumerable.range(20, 5), "outer,inner=>outer+inner").toArray();
    deepEqual(actual, [21, 23, 25, 27, 29]);
    actual = Enumerable.range(1, 10).zip(Enumerable.range(20, 5), "outer,inner,index=>outer+inner+index").toArray();
    deepEqual(actual, [21, 24, 27, 30, 33]);
});

test("zip2", function () {
    [1, 2, 3]
        .zip(
            [-3, 4, 10],
            [5, 6, 7],
            function (x, y, z) { return x * y * z; })
        .is(-15, 48, 210);

    [1, 2, 3]
        .zip(
            [-3, 4, 10],
            [-3, 4, 10],
            function (x, y, z, i) { return i; })
        .is(0, 1, 2);

    [1, 2, 3]
        .zip(
            [-3, 4, 10],
            [-7, 20, 30, 100],
            function (x, y, z) { return x * y + z; })
        .is(-10, 28, 60);

    [1, 2, 3]
        .zip(
            [-3, 4, 10],
            [-7, 20, 30, 100],
            function (x, y, z, i) { return z + i; })
        .is(-7, 21, 32);

    Enumerable.from("abc").zip("fghk", "lmnopq", "stuv", "yz0124", "56780",
        function (a, b, c, d, e, f) { return a + b + c + d + e + f })
    .is("aflsy5", "bgmtz6", "chnu07");
});

test("merge", function () {

    [1, 2, 3].merge([-3, 4, 10]).is(1, -3, 2, 4, 3, 10);

    [1, 2, 3].merge([-3, 4], [-7, 20, 30, 100])
        .is(1, -3, -7, 2, 4, 20, 3, 30, 100);

});
<|endoftext|>