<commit_before>/**
 * Copyright (c) 2014-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

// Based on similar script in Jest
// https://github.com/facebook/jest/blob/master/scripts/prettier.js

const chalk = require('chalk');
const glob = require('glob');
const execFileSync = require('child_process').execFileSync;
const prettier = require('prettier');
const fs = require('fs');

const mode = process.argv[2] || 'check';
const shouldWrite = mode === 'write' || mode === 'write-changed';
const onlyChanged = mode === 'check-changed' || mode === 'write-changed';

const defaultOptions = {
  bracketSpacing: false,
  singleQuote: true,
  jsxBracketSameLine: true,
  trailingComma: 'all',
  printWidth: 80,
};
const config = {
  default: {
    patterns: [
      // Internal forwarding modules
      'packages/*/*.js',
      // Source files
      'packages/*/src/**/*.js',
      'packages/shared/**/*.js',
    ],
    ignore: ['**/node_modules/**'],
  },
  scripts: {
    patterns: [
      // Forwarding modules that get published to npm (must be ES5)
      'packages/*/npm/**/*.js',
      // Need to work on Node
      'scripts/**/*.js',
      'fixtures/**/*.js',
    ],
    ignore: [
      '**/node_modules/**',
      // Built files and React repo clone
      'scripts/bench/benchmarks/**',
    ],
    options: {
      trailingComma: 'es5',
    },
  },
};

function exec(command, args) {
  console.log('> ' + [command].concat(args).join(' '));
  var options = {
    cwd: process.cwd(),
    env: process.env,
    stdio: 'pipe',
    encoding: 'utf-8',
  };
  return execFileSync(command, args, options);
}

var mergeBase = exec('git', ['merge-base', 'HEAD', 'master']).trim();
var changedFiles = new Set(
  exec('git', [
    'diff',
    '-z',
    '--name-only',
    '--diff-filter=ACMRTUB',
    mergeBase,
  ]).match(/[^\0]+/g)
);

let didWarn = false;
Object.keys(config).forEach(key => {
  const patterns = config[key].patterns;
  const options = config[key].options;
  const ignore = config[key].ignore;

  const globPattern = patterns.length > 1
    ? `{${patterns.join(',')}}`
    : `${patterns.join(',')}`;
  const files = glob
    .sync(globPattern, {ignore})
    .filter(f => !onlyChanged || changedFiles.has(f));

  if (!files.length) {
    return;
  }

  const args = Object.assign({}, defaultOptions, options);
  files.forEach(file => {
    const input = fs.readFileSync(file, 'utf8');
    if (shouldWrite) {
      const output = prettier.format(input, args);
      if (output !== input) {
        fs.writeFileSync(file, output, 'utf8');
      }
    } else {
      if (!prettier.check(input, args)) {
        if (!didWarn) {
          console.log(
            '\n' +
              chalk.red(
                `  This project uses prettier to format all JavaScript code.\n`
              ) +
              chalk.dim(`    Please run `) +
              chalk.reset('yarn prettier-all') +
              chalk.dim(
                ` and add changes to files listed below to your commit:`
              ) +
              `\n\n`
          );
          didWarn = true;
        }
        console.log(file);
      }
    }
  });
});

if (didWarn) {
  process.exit(1);
}
<commit_msg>Handle prettier error (#11466)<commit_after>/**
 * Copyright (c) 2014-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

// Based on similar script in Jest
// https://github.com/facebook/jest/blob/master/scripts/prettier.js

const chalk = require('chalk');
const glob = require('glob');
const execFileSync = require('child_process').execFileSync;
const prettier = require('prettier');
const fs = require('fs');

const mode = process.argv[2] || 'check';
const shouldWrite = mode === 'write' || mode === 'write-changed';
const onlyChanged = mode === 'check-changed' || mode === 'write-changed';

const defaultOptions = {
  bracketSpacing: false,
  singleQuote: true,
  jsxBracketSameLine: true,
  trailingComma: 'all',
  printWidth: 80,
};
const config = {
  default: {
    patterns: [
      // Internal forwarding modules
      'packages/*/*.js',
      // Source files
      'packages/*/src/**/*.js',
      'packages/shared/**/*.js',
    ],
    ignore: ['**/node_modules/**'],
  },
  scripts: {
    patterns: [
      // Forwarding modules that get published to npm (must be ES5)
      'packages/*/npm/**/*.js',
      // Need to work on Node
      'scripts/**/*.js',
      'fixtures/**/*.js',
    ],
    ignore: [
      '**/node_modules/**',
      // Built files and React repo clone
      'scripts/bench/benchmarks/**',
    ],
    options: {
      trailingComma: 'es5',
    },
  },
};

function exec(command, args) {
  console.log('> ' + [command].concat(args).join(' '));
  var options = {
    cwd: process.cwd(),
    env: process.env,
    stdio: 'pipe',
    encoding: 'utf-8',
  };
  return execFileSync(command, args, options);
}

var mergeBase = exec('git', ['merge-base', 'HEAD', 'master']).trim();
var changedFiles = new Set(
  exec('git', [
    'diff',
    '-z',
    '--name-only',
    '--diff-filter=ACMRTUB',
    mergeBase,
  ]).match(/[^\0]+/g)
);

let didWarn = false;
let didError = false;
Object.keys(config).forEach(key => {
  const patterns = config[key].patterns;
  const options = config[key].options;
  const ignore = config[key].ignore;

  const globPattern = patterns.length > 1
    ? `{${patterns.join(',')}}`
    : `${patterns.join(',')}`;
  const files = glob
    .sync(globPattern, {ignore})
    .filter(f => !onlyChanged || changedFiles.has(f));

  if (!files.length) {
    return;
  }

  const args = Object.assign({}, defaultOptions, options);
  files.forEach(file => {
    try {
      const input = fs.readFileSync(file, 'utf8');
      if (shouldWrite) {
        const output = prettier.format(input, args);
        if (output !== input) {
          fs.writeFileSync(file, output, 'utf8');
        }
      } else {
        if (!prettier.check(input, args)) {
          if (!didWarn) {
            console.log(
              '\n' +
                chalk.red(
                  `  This project uses prettier to format all JavaScript code.\n`
                ) +
                chalk.dim(`    Please run `) +
                chalk.reset('yarn prettier-all') +
                chalk.dim(
                  ` and add changes to files listed below to your commit:`
                ) +
                `\n\n`
            );
            didWarn = true;
          }
          console.log(file);
        }
      }
    } catch (error) {
      didError = true;
      console.log('\n\n' + error.message);
      console.log(file);
    }
  });
});

if (didWarn || didError) {
  process.exit(1);
}
<|endoftext|>


<commit_before>// Login
$("#loginBtn").click(function () {
    login();
});

function login() {
    $("#email").prop("disabled", true);
    $("#password").prop("disabled", true);
    $("#loginBtn").prop("disabled", true);
    arcAjaxRequest("arc/dologin", {
        email: $("#email").val(),
        password: $("#password").val()
    }, showMessage, success);
}

$("#btnReg").click(function () {
    toggleView("reg");
});

$("#btnBackLogin").click(function () {
    toggleView("login");
});

$("#btnForgot").click(function () {
    toggleView("forgot");
});

$("#forgotCancel").click(function () {
    cancelForgot();
});

function toggleView(item) {
    $('#collapseA').collapse('hide');
    $('#collapseB').collapse('hide');
    $('#collapseC').collapse('hide');

    switch (item) {
        case "login":
            $('#collapseA').collapse('show');
            break;
        case "reg":
            $('#collapseB').collapse('show');
            break;
        case "forgot":
            $('#collapseC').collapse('show');
            break;
    }
}

function showMessage() {
    arcGetStatus();
    $("#email").prop("disabled", false);
    $("#password").prop("disabled", false);
    $("#loginBtn").prop("disabled", false);
}

function cancelForgot() {
    toggleView("login");
}

$("#sendReset").click(function () {
    arcAjaxRequest("arc/reset", {
        emailf: $("#emailf").val()
    }, arcGetStatus);
    cancelForgot();
});

function success(data) {
    var jdata = arcGetJson(data);
    if (jdata.redirect) {
        window.location = jdata.redirect;
    }
}

// Register
$("#registerBtn").click(function () {
    arcAjaxRequest("arc/doregister", {
        firstname: $("#firstname").val(),
        lastname: $("#lastname").val(),
        emailr: $("#emailr").val(),
        passwordr: $("#passwordr").val(),
        passwordr2: $("#passwordr2").val()
    }, arcGetStatus, success);
});

$("#password").keypress(function (e) {
    if (e.keyCode == 13) {
        login();
    }
});

//hide password
$(document).ready(function () {
    $("#show_hide_password a").on('click', function (event) {
        event.preventDefault();
        if ($('#show_hide_password input').attr("type") == "text") {
            $('#show_hide_password input').attr('type', 'password');
            $('#show_hide_password i').addClass("bx-hide");
            $('#show_hide_password i').removeClass("bx-show");
        } else if ($('#show_hide_password input').attr("type") == "password") {
            $('#show_hide_password input').attr('type', 'text');
            $('#show_hide_password i').removeClass("bx-hide");
            $('#show_hide_password i').addClass("bx-show");
        }
    });
});<commit_msg>Fixed forgot password<commit_after>// Login
$("#loginBtn").click(function () {
    login();
});

function login() {
    $("#email").prop("disabled", true);
    $("#password").prop("disabled", true);
    $("#loginBtn").prop("disabled", true);
    arcAjaxRequest("arc/dologin", {
        email: $("#email").val(),
        password: $("#password").val()
    }, showMessage, success);
}

$("#btnReg").click(function () {
    toggleView("reg");
});

$("#btnBackLogin").click(function () {
    toggleView("login");
});

$("#btnForgot").click(function () {
    toggleView("forgot");
});

$("#forgotCancel").click(function () {
    cancelForgot();
});

function toggleView(item) {
    $('#collapseA').collapse('hide');
    $('#collapseB').collapse('hide');
    $('#collapseC').collapse('hide');

    switch (item) {
        case "login":
            $('#collapseA').collapse('show');
            break;
        case "reg":
            $('#collapseB').collapse('show');
            break;
        case "forgot":
            $('#collapseC').collapse('show');
            break;
    }
}

function showMessage() {
    arcGetStatus();
    $("#email").prop("disabled", false);
    $("#password").prop("disabled", false);
    $("#loginBtn").prop("disabled", false);
}

function cancelForgot() {
    toggleView("login");
}

$("#sendReset").click(function () {
    arcAjaxRequest("arc/reset", {
        emailf: $("#emailf").val()
    }, arcGetStatus);
});

function success(data) {
    var jdata = arcGetJson(data);
    if (jdata.redirect) {
        window.location = jdata.redirect;
    }
}

// Register
$("#registerBtn").click(function () {
    arcAjaxRequest("arc/doregister", {
        firstname: $("#firstname").val(),
        lastname: $("#lastname").val(),
        emailr: $("#emailr").val(),
        passwordr: $("#passwordr").val(),
        passwordr2: $("#passwordr2").val()
    }, arcGetStatus, success);
});

$("#password").keypress(function (e) {
    if (e.keyCode == 13) {
        login();
    }
});

//hide password
$(document).ready(function () {
    $("#show_hide_password a").on('click', function (event) {
        event.preventDefault();
        if ($('#show_hide_password input').attr("type") == "text") {
            $('#show_hide_password input').attr('type', 'password');
            $('#show_hide_password i').addClass("bx-hide");
            $('#show_hide_password i').removeClass("bx-show");
        } else if ($('#show_hide_password input').attr("type") == "password") {
            $('#show_hide_password input').attr('type', 'text');
            $('#show_hide_password i').removeClass("bx-hide");
            $('#show_hide_password i').addClass("bx-show");
        }
    });
});<|endoftext|>


<commit_before>(function() {
	enyo = window.enyo || {};

	enyo.pathResolverFactory = function() {
		this.paths = {};
	};

	enyo.pathResolverFactory.prototype = {
		addPath: function(inName, inPath) {
			return this.paths[inName] = inPath;
		},
		addPaths: function(inPaths) {
			if (inPaths) {
				for (var n in inPaths) {
					this.addPath(n, inPaths[n]);
				}
			}
		},
		includeTrailingSlash: function(inPath) {
			return (inPath && inPath.slice(-1) !== "/") ? inPath + "/" : inPath;
		},
		// match $name
		rewritePattern: /\$([^\/\\]*)(\/)?/g,
		// replace macros of the form $pathname with the mapped value of paths.pathname
		rewrite: function (inPath) {
			var working, its = this.includeTrailingSlash, paths = this.paths;
			var fn = function(macro, name) {
				working = true;
				return its(paths[name]) || '';
			};
			var result = inPath;
			do {
				working = false;
				result = result.replace(this.rewritePattern, fn);
			} while (working);
			return result;
		}
	};

	enyo.path = new enyo.pathResolverFactory();

	enyo.loaderFactory = function(inMachine, inPathResolver) {
		this.machine = inMachine;
		// package information
		this.packages = [];
		// module information
		this.modules = [];
		// stylesheet paths
		this.sheets = [];
		// (protected) internal dependency stack
		this.stack = [];
		this.pathResolver = inPathResolver || enyo.path;
		this.packageName = "";
		this.packageFolder = "";
		this.finishCallbacks = {};
	};

	enyo.loaderFactory.prototype  = {
		verbose: false,
		loadScript: function(inScript) {
			this.machine.script(inScript);
		},
		loadSheet: function(inSheet) {
			this.machine.sheet(inSheet);
		},
		loadPackage: function(inPackage) {
			this.machine.script(inPackage);
		},
		report: function() {
		},
		//
		load: function(/*<inDependency0, inDependency1 ...>*/) {
			// begin processing dependencies
			this.more({
				index: 0,
				depends: arguments || []
			});
		},
		more: function(inBlock) {
			// a 'block' is a dependency list with a bookmark
			// the bookmark (index) allows us to interrupt
			// processing and then continue asynchronously.
			if (inBlock) {
				// returns true if this block has asynchronous requirements
				// in that case, we unwind the stack. The asynchronous loader
				// must provide the continuation (by calling 'more' again).
				if (this.continueBlock(inBlock)) {
					return;
				}
			}
			// A package is now complete. Pop the block that was interrupted for that package (if any).
			var block = this.stack.pop();
			if (block) {
				// block.packageName is the name of the package that interrupted us
				//this.report("finished package", block.packageName);
				this.verbose && console.groupEnd("* finish package (" + (block.packageName || "anon") + ")");
				// cache the folder for the currently processing package
				this.packageFolder = block.folder;
				// no current package
				this.packageName = "";
				// process this new block
				this.more(block);
			} else {
				this.finish();
			}
		},
		finish: function() {
			this.packageFolder = "";
			this.verbose && console.log("-------------- fini");
			for (var i in this.finishCallbacks) {
				if (this.finishCallbacks[i]) {
					this.finishCallbacks[i]();
					this.finishCallbacks[i] = null;
				}
			}
		},
		continueBlock: function(inBlock) {
			while (inBlock.index < inBlock.depends.length) {
				var d = inBlock.depends[inBlock.index++];
				if (d) {
					if (typeof d == "string") {
						if (this.require(d, inBlock)) {
							// return true to indicate we need to interrupt
							// processing until asynchronous file load completes
							// the load process itself must provide the
							// continuation
							return true;
						}
					} else {
						this.pathResolver.addPaths(d);
					}
				}
			}
		},
		require: function(inPath, inBlock) {
			// process aliases
			var path = this.pathResolver.rewrite(inPath);
			// get path root
			var prefix = this.getPathPrefix(inPath);
			// assemble path
			path = prefix + path;
			// process path
			if ((path.slice(-4) == ".css") || (path.slice(-5) == ".less")) {
				this.verbose && console.log("+ stylesheet: [" + prefix + "][" + inPath + "]");
				this.requireStylesheet(path);
			} else if (path.slice(-3) == ".js" && path.slice(-10) != "package.js") {
				this.verbose && console.log("+ module: [" + prefix + "][" + inPath + "]");
				this.requireScript(inPath, path);
			} else {
				// package
				this.requirePackage(path, inBlock);
				// return true to indicate a package was located and
				// we need to interrupt further processing until it's completed
				return true;
			}
		},
		getPathPrefix: function(inPath) {
			var delim = inPath.slice(0, 1);
			if ((delim != "/") && (delim != "\\") && (delim != "$") && (inPath.slice(0, 5) != "http:")) {
				return this.packageFolder;
			}
			return "";
		},
		requireStylesheet: function(inPath) {
			// stylesheet
			this.sheets.push(inPath);
			this.loadSheet(inPath);
		},
		requireScript: function(inRawPath, inPath) {
			// script file
			this.modules.push({
				packageName: this.packageName,
				rawPath: inRawPath,
				path: inPath
			});
			this.loadScript(inPath);
		},
		decodePackagePath: function(inPath) {
			// A package path can be encoded in two ways:
			//
			//	1. [folder]
			//	2. [folder]/[*package.js]
			//
			// Note: manifest file name must end in "package.js"
			//
			var alias = '', target = '', folder = '', manifest = 'package.js';
			// convert back slashes to forward slashes, remove double slashes, split on slash
			var parts = inPath.replace(/\\/g, "/").replace(/\/\//g, "/").replace(/:\//, "://").split("/");
			if (parts.length) {
				// if inPath has a trailing slash, parts has an empty string which we pop off and ignore
				var name = parts.pop() || parts.pop() || "";
				// test if name includes the manifest tag
				if (name.slice(-manifest.length) !== manifest) {
					// if not a manifest name, it's part of the folder path
					parts.push(name);
				} else {
					// otherwise this is the manifest name
					manifest = name;
				}
				//
				folder = parts.join("/");
				folder = (folder ? folder + "/" : "");
				manifest = folder + manifest;
				//
				// build friendly aliasing:
				//
				for (var i=parts.length-1; i >= 0; i--) {
					if (parts[i] == "source") {
						parts.splice(i, 1);
						break;
					}
				}
				target = parts.join("/");
				//
				// portable aliasing:
				//
				// packages that are rooted at a folder named "enyo" or "lib" do not
				// include that root path in their alias
				//
				//	remove */lib or */enyo prefix
				//
				// e.g. foo/bar/baz/lib/zot -> zot package
				//
				for (var i=parts.length-1, p; p=parts[i]; i--) {
					if (p == "lib" || p == "enyo") {
						parts = parts.slice(i+1);
						break;
					}
				}
				// remove ".." and "."
				for (var i=parts.length-1, p; p=parts[i]; i--) {
					if (p == ".." || p == ".") {
						parts.splice(i, 1);
					}
				}
				//
				alias = parts.join("-");
			}
			return {
				alias: alias,
				target: target,
				folder: folder,
				manifest: manifest
			};
		},
		aliasPackage: function(inPath) {
			var parts = this.decodePackagePath(inPath);
			// cache manifest path
			this.manifest = parts.manifest;
			// cache package info for named packages
			if (parts.alias) {
				// debug only
				/*
				var old = this.pathResolver.paths[parts.name];
				if (old && old != parts.folder) {
					this.verbose && console.warn("mapping alias [" + parts.name + "] to [" + parts.folder + "] replacing [" + old + "]");
				}
				this.verbose && console.log("mapping alias [" + parts.name + "] to [" + parts.folder + "]");
				*/
				//
				// create a path alias for this package
				this.pathResolver.addPath(parts.alias, parts.target);
				//
				// cache current name
				this.packageName = parts.alias;
				// cache package information
				this.packages.push({
					name: parts.alias,
					folder: parts.folder
				});
			}
			// cache current folder
			this.packageFolder = parts.folder;
		},
		requirePackage: function(inPath, inBlock) {
			// cache the interrupted packageFolder
			inBlock.folder = this.packageFolder;
			this.aliasPackage(inPath);
			// cache the name of the package 'inBlock' is loading now
			inBlock.packageName = this.packageName;
			// push inBlock on the continuation stack
			this.stack.push(inBlock);
			// console/user reporting
			this.report("loading package", this.packageName);
			this.verbose && console.group("* start package [" + this.packageName + "]");
			// load the actual package. the package MUST call a continuation function
			// or the process will halt.
			this.loadPackage(this.manifest);
		}
	};
})();
<commit_msg>changed static check for path starting with http: to regex to support mixed case and https dependencies<commit_after>(function() {
	enyo = window.enyo || {};

	enyo.pathResolverFactory = function() {
		this.paths = {};
	};

	enyo.pathResolverFactory.prototype = {
		addPath: function(inName, inPath) {
			return this.paths[inName] = inPath;
		},
		addPaths: function(inPaths) {
			if (inPaths) {
				for (var n in inPaths) {
					this.addPath(n, inPaths[n]);
				}
			}
		},
		includeTrailingSlash: function(inPath) {
			return (inPath && inPath.slice(-1) !== "/") ? inPath + "/" : inPath;
		},
		// match $name
		rewritePattern: /\$([^\/\\]*)(\/)?/g,
		// replace macros of the form $pathname with the mapped value of paths.pathname
		rewrite: function (inPath) {
			var working, its = this.includeTrailingSlash, paths = this.paths;
			var fn = function(macro, name) {
				working = true;
				return its(paths[name]) || '';
			};
			var result = inPath;
			do {
				working = false;
				result = result.replace(this.rewritePattern, fn);
			} while (working);
			return result;
		}
	};

	enyo.path = new enyo.pathResolverFactory();

	enyo.loaderFactory = function(inMachine, inPathResolver) {
		this.machine = inMachine;
		// package information
		this.packages = [];
		// module information
		this.modules = [];
		// stylesheet paths
		this.sheets = [];
		// (protected) internal dependency stack
		this.stack = [];
		this.pathResolver = inPathResolver || enyo.path;
		this.packageName = "";
		this.packageFolder = "";
		this.finishCallbacks = {};
	};

	enyo.loaderFactory.prototype  = {
		verbose: false,
		loadScript: function(inScript) {
			this.machine.script(inScript);
		},
		loadSheet: function(inSheet) {
			this.machine.sheet(inSheet);
		},
		loadPackage: function(inPackage) {
			this.machine.script(inPackage);
		},
		report: function() {
		},
		//
		load: function(/*<inDependency0, inDependency1 ...>*/) {
			// begin processing dependencies
			this.more({
				index: 0,
				depends: arguments || []
			});
		},
		more: function(inBlock) {
			// a 'block' is a dependency list with a bookmark
			// the bookmark (index) allows us to interrupt
			// processing and then continue asynchronously.
			if (inBlock) {
				// returns true if this block has asynchronous requirements
				// in that case, we unwind the stack. The asynchronous loader
				// must provide the continuation (by calling 'more' again).
				if (this.continueBlock(inBlock)) {
					return;
				}
			}
			// A package is now complete. Pop the block that was interrupted for that package (if any).
			var block = this.stack.pop();
			if (block) {
				// block.packageName is the name of the package that interrupted us
				//this.report("finished package", block.packageName);
				this.verbose && console.groupEnd("* finish package (" + (block.packageName || "anon") + ")");
				// cache the folder for the currently processing package
				this.packageFolder = block.folder;
				// no current package
				this.packageName = "";
				// process this new block
				this.more(block);
			} else {
				this.finish();
			}
		},
		finish: function() {
			this.packageFolder = "";
			this.verbose && console.log("-------------- fini");
			for (var i in this.finishCallbacks) {
				if (this.finishCallbacks[i]) {
					this.finishCallbacks[i]();
					this.finishCallbacks[i] = null;
				}
			}
		},
		continueBlock: function(inBlock) {
			while (inBlock.index < inBlock.depends.length) {
				var d = inBlock.depends[inBlock.index++];
				if (d) {
					if (typeof d == "string") {
						if (this.require(d, inBlock)) {
							// return true to indicate we need to interrupt
							// processing until asynchronous file load completes
							// the load process itself must provide the
							// continuation
							return true;
						}
					} else {
						this.pathResolver.addPaths(d);
					}
				}
			}
		},
		require: function(inPath, inBlock) {
			// process aliases
			var path = this.pathResolver.rewrite(inPath);
			// get path root
			var prefix = this.getPathPrefix(inPath);
			// assemble path
			path = prefix + path;
			// process path
			if ((path.slice(-4) == ".css") || (path.slice(-5) == ".less")) {
				this.verbose && console.log("+ stylesheet: [" + prefix + "][" + inPath + "]");
				this.requireStylesheet(path);
			} else if (path.slice(-3) == ".js" && path.slice(-10) != "package.js") {
				this.verbose && console.log("+ module: [" + prefix + "][" + inPath + "]");
				this.requireScript(inPath, path);
			} else {
				// package
				this.requirePackage(path, inBlock);
				// return true to indicate a package was located and
				// we need to interrupt further processing until it's completed
				return true;
			}
		},
		getPathPrefix: function(inPath) {
			var delim = inPath.slice(0, 1);
			if ((delim != "/") && (delim != "\\") && (delim != "$") && !inPath.test(/^https?:/i)) {
				return this.packageFolder;
			}
			return "";
		},
		requireStylesheet: function(inPath) {
			// stylesheet
			this.sheets.push(inPath);
			this.loadSheet(inPath);
		},
		requireScript: function(inRawPath, inPath) {
			// script file
			this.modules.push({
				packageName: this.packageName,
				rawPath: inRawPath,
				path: inPath
			});
			this.loadScript(inPath);
		},
		decodePackagePath: function(inPath) {
			// A package path can be encoded in two ways:
			//
			//	1. [folder]
			//	2. [folder]/[*package.js]
			//
			// Note: manifest file name must end in "package.js"
			//
			var alias = '', target = '', folder = '', manifest = 'package.js';
			// convert back slashes to forward slashes, remove double slashes, split on slash
			var parts = inPath.replace(/\\/g, "/").replace(/\/\//g, "/").replace(/:\//, "://").split("/");
			if (parts.length) {
				// if inPath has a trailing slash, parts has an empty string which we pop off and ignore
				var name = parts.pop() || parts.pop() || "";
				// test if name includes the manifest tag
				if (name.slice(-manifest.length) !== manifest) {
					// if not a manifest name, it's part of the folder path
					parts.push(name);
				} else {
					// otherwise this is the manifest name
					manifest = name;
				}
				//
				folder = parts.join("/");
				folder = (folder ? folder + "/" : "");
				manifest = folder + manifest;
				//
				// build friendly aliasing:
				//
				for (var i=parts.length-1; i >= 0; i--) {
					if (parts[i] == "source") {
						parts.splice(i, 1);
						break;
					}
				}
				target = parts.join("/");
				//
				// portable aliasing:
				//
				// packages that are rooted at a folder named "enyo" or "lib" do not
				// include that root path in their alias
				//
				//	remove */lib or */enyo prefix
				//
				// e.g. foo/bar/baz/lib/zot -> zot package
				//
				for (var i=parts.length-1, p; p=parts[i]; i--) {
					if (p == "lib" || p == "enyo") {
						parts = parts.slice(i+1);
						break;
					}
				}
				// remove ".." and "."
				for (var i=parts.length-1, p; p=parts[i]; i--) {
					if (p == ".." || p == ".") {
						parts.splice(i, 1);
					}
				}
				//
				alias = parts.join("-");
			}
			return {
				alias: alias,
				target: target,
				folder: folder,
				manifest: manifest
			};
		},
		aliasPackage: function(inPath) {
			var parts = this.decodePackagePath(inPath);
			// cache manifest path
			this.manifest = parts.manifest;
			// cache package info for named packages
			if (parts.alias) {
				// debug only
				/*
				var old = this.pathResolver.paths[parts.name];
				if (old && old != parts.folder) {
					this.verbose && console.warn("mapping alias [" + parts.name + "] to [" + parts.folder + "] replacing [" + old + "]");
				}
				this.verbose && console.log("mapping alias [" + parts.name + "] to [" + parts.folder + "]");
				*/
				//
				// create a path alias for this package
				this.pathResolver.addPath(parts.alias, parts.target);
				//
				// cache current name
				this.packageName = parts.alias;
				// cache package information
				this.packages.push({
					name: parts.alias,
					folder: parts.folder
				});
			}
			// cache current folder
			this.packageFolder = parts.folder;
		},
		requirePackage: function(inPath, inBlock) {
			// cache the interrupted packageFolder
			inBlock.folder = this.packageFolder;
			this.aliasPackage(inPath);
			// cache the name of the package 'inBlock' is loading now
			inBlock.packageName = this.packageName;
			// push inBlock on the continuation stack
			this.stack.push(inBlock);
			// console/user reporting
			this.report("loading package", this.packageName);
			this.verbose && console.group("* start package [" + this.packageName + "]");
			// load the actual package. the package MUST call a continuation function
			// or the process will halt.
			this.loadPackage(this.manifest);
		}
	};
})();
<|endoftext|>


<commit_before>var db = require( __configs + 'database');
var config = require(__configs + 'databaseConfig');
var Errors = require(__components + "Errors/errors");
var dbHelpers = require(__components + "Databases/dbHelpers");

module.exports = {

    getStudentSkills: function( studentId, callback ) {
        var q = "select cs.name,cs.description,ss.value from student_skill ss, class_skill cs where ss.studentId = ? and cs.id = ss.classSkillId";
        db.query(q,studentId,callback);
    },

    getStudentTop3Skills: function( studentId,callback ) {
        var q = "select cs.name, cs.description, ss.value from student_skill ss, class_skill cs where ss.studentId = ? and cs.id = ss.classSkillId ORDER BY value desc LIMIT 3";
        db.query(q,studentId,callback)
    }
}<commit_msg>fixed apparent mysql syntax error<commit_after>var db = require( __configs + 'database');
var config = require(__configs + 'databaseConfig');
var Errors = require(__components + "Errors/errors");
var dbHelpers = require(__components + "Databases/dbHelpers");

module.exports = {

    getStudentSkills: function( studentId, callback ) {
        var q = "SELECT cs.name, cs.description, ss.value FROM student_skill ss, class_skill cs WHERE ss.studentId = ? AND cs.id = ss.classSkillId";
        db.query(q,studentId,callback);
    },

    getStudentTop3Skills: function( studentId,callback ) {
        var q = "SELECT cs.name, cs.description, ss.value from student_skill ss, class_skill cs WHERE ss.studentId = 8 AND cs.id = ss.classSkillId ORDER BY value LIMIT 3;"
        db.query(q,studentId,callback)
    }
}
<|endoftext|>


<commit_before>const textarea = document.getElementsByTagName("textarea")[0];
const back = document.getElementsByClassName("mdi-keyboard-backspace")[0];
const toggle = document.getElementById("toggle");
const theme = document.getElementById("theme");
const overlay = document.getElementById("overlay");
const overlayClose = document.getElementsByClassName("mdi-close")[0];
const settings = document.getElementsByClassName("mdi-settings")[0];
const noteList =  document.getElementById("note-list");
const confirmDelete = document.getElementById("confirmDelete");
const yes = document.getElementById("yes");
const no = document.getElementById("no");
const siteName = document.getElementById("siteName");
const openInTab = document.getElementsByClassName("mdi-open-in-new")[0];
const search = document.getElementById("search");
function getContext() {
    return browser.extension.getViews({type: "popup"}).indexOf(window) > -1 ? "popup" :
        browser.extension.getViews({type: "sidebar"}).indexOf(window) > -1 ? "sidebar" :
        browser.extension.getViews({type: "tab"}).indexOf(window) > -1 ? "tab" : undefined;
}
function searchResults() {
    var names = document.getElementsByClassName("name");
    for (var name of names) {
        name.parentNode.style.display = name.innerText.toUpperCase().indexOf(search.value.toUpperCase()) > -1 ? "block" : "none";
    }
}
function openList() {
    search.focus()
    overlay.style.width = "100%";
    back.style.display = "none";
    overlayClose.style.display = "block";
}
function closeList() {
    overlay.style.width = "0";
    back.style.display = "block";
    overlayClose.style.display = "none";
    textarea.focus();
}
function saveGeneralNotes() {
    browser.storage.local.set({
        general_notes: textarea.value || ""
    });
}
async function saveSiteNotes() {
    var res = await browser.storage.local.get("site_notes");
    res.site_notes[back.innerText] = textarea.value || "";
    browser.storage.local.set({site_notes: res.site_notes});
}
async function loadGeneralNotes() {
    textarea.focus();
    toggle.className = "mdi mdi-web";
    toggle.title = "Switch to site notes"
    textarea.removeEventListener("input", saveSiteNotes);
    var res = await browser.storage.local.get("general_notes");
    textarea.value = res.general_notes || "";
    back.innerText = "General Notes";
    textarea.addEventListener("input", saveGeneralNotes);
}
async function siteNoteSetup(site) {
    textarea.focus();
    textarea.removeEventListener("input", saveGeneralNotes);
    toggle.className = "mdi mdi-note";
    toggle.title = "Switch to general notes"
    var res = await browser.storage.local.get("site_notes");
    textarea.value = res.site_notes.hasOwnProperty(site) ? res.site_notes[site] : "";
    back.innerText = site;
    textarea.addEventListener("input", saveSiteNotes);
}
function removeNoteFromList(name) {
    var deleteButton = noteList.querySelector("span[data-delete-site='" + name + "']");
    deleteButton.parentNode.parentNode.removeChild(deleteButton.parentNode);
}
async function deleteNote() {
    var res = await browser.storage.local.get("site_notes");
    delete res.site_notes[siteName.innerText];
    browser.storage.local.set({site_notes: res.site_notes});
    removeNoteFromList(siteName.innerText);
    confirmDelete.style.width = "0";
}
async function loadCustomNote(ele) {
    var tabs = await browser.tabs.query({active: true, currentWindow: true});
    if (ele.target.innerText !== back.innerText && ele.target.className !== "mdi mdi-delete") {
        back.dataset[tabs[0].id] = ele.target.innerText;
    } else {
        delete back.dataset[tabs[0].id]
        loadSiteNotes();
    }
    if (ele.target.innerText === "General Notes") {
        loadGeneralNotes();
    } else if (ele.target.className === "mdi mdi-delete") {
        confirmDelete.style.width = "100%";
        siteName.innerText = ele.target.dataset.deleteSite;
        return;
    } else if (ele.target.className === "name") {
        siteNoteSetup(ele.target.innerText);
    } else {
        return;
    }
    closeList();
}
function closeConfirm() {
    confirmDelete.style.width = "0";
}
async function loadSiteNotes(manualClick = false) {
    var res = await browser.storage.local.get("options");
    var tabs = await browser.tabs.query({active: true, currentWindow: true});
    if (!tabs[0].incognito || manualClick || (res.options.private_browsing && tabs[0].incognito)) {
        var url = tabs[0].url;
        var site = await siteParser(url);
        console.log(site);
        if (site === "general_notes") {
            loadGeneralNotes();
        } else {
            siteNoteSetup(site);
        }
    } else {
        loadGeneralNotes();
    }
}
function changeNoteMode(ele) {
    switch (ele.target.className) {
        case "mdi mdi-web":
            loadSiteNotes(true);
            break;
        case "mdi mdi-note":
            loadSiteNotes();
            break;
    }
}
async function setTheme(mode) {
    var res = await browser.storage.local.get("options");
    switch (mode) {
        case "light":
            var theme = "";
            break;
        case "dark":
            var theme = "_dark";
            break;
    }
    document.body.style.backgroundColor = "#" + res.options["background_color" + theme];
    document.body.style.color = "#" + res.options["font_color" + theme];
    search.style.color = "#" + res.options["font_color" + theme];
    search.style.backgroundColor = "#" + res.options["background_color" + theme];
}
async function changeTheme(ele) {
    var res = await browser.storage.local.get("options");
    switch (ele.target.title) {
        case "Switch to light theme":
            ele.target.title = "Switch to dark theme";
            res.options.theme = "light";
            browser.storage.local.set({options: res.options});
            setTheme("light");
            break;
        case "Switch to dark theme":
            ele.target.title = "Switch to light theme";
            res.options.theme = "dark";
            browser.storage.local.set({options: res.options});
            setTheme("dark");
            break;
    }
}
function addNoteToList(site) {
    var cont = document.createElement("span");
    cont.className = "container";
    var name = document.createElement("div");
    name.innerText = site;
    name.className = "name";
    var del = document.createElement("span");
    del.dataset.deleteSite = site;
    del.className = "mdi mdi-delete";
    cont.append(name);
    cont.append(del);
    noteList.append(cont);
}
async function loadNoteList() {
    var res = await browser.storage.local.get("site_notes");
    for (var site in res.site_notes) {
        if (res.site_notes.hasOwnProperty(site)) {
            addNoteToList(site);
        }
    }
}
function resizePage() {
    textarea.style.height = window.innerHeight - 30 + "px";
    textarea.style.width = window.innerWidth - 2 + "px";
    overlay.style.height = window.innerHeight - 30 + "px";
}
async function pageSetup() {
    var res = await browser.storage.local.get("options");
    switch (res.options.theme) {
        case "light":
            theme.title = "Switch to dark theme";
            break;
        case "dark":
            theme.title = "Switch to light theme";
            break;
    }
    setTheme(res.options.theme);
    if (res.options.font_family === "custom") {
        textarea.style.fontFamily = res.options.font_css;
    } else if (res.options.font_family !== "default") {
        textarea.style.fontFamily = res.options.font_family;
    }
    textarea.style.fontSize = res.options.font_size + "px";
    var context = getContext();
    switch (context) {
        case "tab":
            openInTab.style.display = "none";
            toggle.style.display = "none";
            break;
        case "sidebar":
            browser.tabs.onActivated.addListener(perTabSidebar);
            browser.tabs.onUpdated.addListener(perTabSidebar);
            break;
        case "popup":
            document.body.style.width = res.options.width + "px";
            textarea.style.width = res.options.width + "px";
            textarea.style.height = res.options.height + "px";
            overlay.style.height = res.options.height + "px";
            break;
    }
    if (context !== "popup") {
        window.addEventListener("resize", resizePage);
        resizePage();
    }
    switch (res.options.default_display) {
        case "general_notes":
            loadGeneralNotes();
            break;
        case "site_notes":
            loadSiteNotes();
            break;
    }
    loadNoteList();
}
function options() {
    browser.runtime.openOptionsPage();
}
function openTab() {
    browser.tabs.create({
        active: true,
        url: "notes.html"
    });
}
async function perTabSidebar() {
    var res = await browser.storage.local.get("options");
    var tabs = await browser.tabs.query({active: true, currentWindow: true});
    console.log(tabs[0].id)
    console.log(!back.dataset.hasOwnProperty(tabs[0].id));
    console.log(res.options.default_display)
    if (!back.dataset.hasOwnProperty(tabs[0].id)) {
        switch (res.options.default_display) {
            case "site_notes":
                console.log("HERE")
                loadSiteNotes();
                break;
            case "general_notes":
                loadGeneralNotes();
                break;
        }
    } else {
        siteNoteSetup(back.dataset[tabs[0].id]);
    }
}
function listUpdate(changes) {
    if (changes.hasOwnProperty("site_notes")) {
        var oldValues = Object.keys(changes.site_notes.oldValue);
        var newValues = Object.keys(changes.site_notes.newValue);
        for (var item of oldValues) {
            if (newValues.indexOf(item) === -1) {
                removeNoteFromList(item);
            }
        };
        for (var item of newValues) {
            if (oldValues.indexOf(item) === -1) {
                addNoteToList(item);
            }
        }
    }
}
document.addEventListener("focus", () => {
    textarea.focus();
});
settings.addEventListener("click", options);
toggle.addEventListener("click", changeNoteMode);
theme.addEventListener("click", changeTheme);
back.addEventListener("click", openList);
overlayClose.addEventListener("click", closeList);
noteList.addEventListener("click", loadCustomNote);
no.addEventListener("click", closeConfirm);
yes.addEventListener("click", deleteNote);
openInTab.addEventListener("click", openTab);
search.addEventListener("input", searchResults);
document.addEventListener("DOMContentLoaded", pageSetup);
browser.storage.onChanged.addListener(listUpdate);
<commit_msg>Removed logging<commit_after>const textarea = document.getElementsByTagName("textarea")[0];
const back = document.getElementsByClassName("mdi-keyboard-backspace")[0];
const toggle = document.getElementById("toggle");
const theme = document.getElementById("theme");
const overlay = document.getElementById("overlay");
const overlayClose = document.getElementsByClassName("mdi-close")[0];
const settings = document.getElementsByClassName("mdi-settings")[0];
const noteList =  document.getElementById("note-list");
const confirmDelete = document.getElementById("confirmDelete");
const yes = document.getElementById("yes");
const no = document.getElementById("no");
const siteName = document.getElementById("siteName");
const openInTab = document.getElementsByClassName("mdi-open-in-new")[0];
const search = document.getElementById("search");
function getContext() {
    return browser.extension.getViews({type: "popup"}).indexOf(window) > -1 ? "popup" :
        browser.extension.getViews({type: "sidebar"}).indexOf(window) > -1 ? "sidebar" :
        browser.extension.getViews({type: "tab"}).indexOf(window) > -1 ? "tab" : undefined;
}
function searchResults() {
    var names = document.getElementsByClassName("name");
    for (var name of names) {
        name.parentNode.style.display = name.innerText.toUpperCase().indexOf(search.value.toUpperCase()) > -1 ? "block" : "none";
    }
}
function openList() {
    search.focus()
    overlay.style.width = "100%";
    back.style.display = "none";
    overlayClose.style.display = "block";
}
function closeList() {
    overlay.style.width = "0";
    back.style.display = "block";
    overlayClose.style.display = "none";
    textarea.focus();
}
function saveGeneralNotes() {
    browser.storage.local.set({
        general_notes: textarea.value || ""
    });
}
async function saveSiteNotes() {
    var res = await browser.storage.local.get("site_notes");
    res.site_notes[back.innerText] = textarea.value || "";
    browser.storage.local.set({site_notes: res.site_notes});
}
async function loadGeneralNotes() {
    textarea.focus();
    toggle.className = "mdi mdi-web";
    toggle.title = "Switch to site notes"
    textarea.removeEventListener("input", saveSiteNotes);
    var res = await browser.storage.local.get("general_notes");
    textarea.value = res.general_notes || "";
    back.innerText = "General Notes";
    textarea.addEventListener("input", saveGeneralNotes);
}
async function siteNoteSetup(site) {
    textarea.focus();
    textarea.removeEventListener("input", saveGeneralNotes);
    toggle.className = "mdi mdi-note";
    toggle.title = "Switch to general notes"
    var res = await browser.storage.local.get("site_notes");
    textarea.value = res.site_notes.hasOwnProperty(site) ? res.site_notes[site] : "";
    back.innerText = site;
    textarea.addEventListener("input", saveSiteNotes);
}
function removeNoteFromList(name) {
    var deleteButton = noteList.querySelector("span[data-delete-site='" + name + "']");
    deleteButton.parentNode.parentNode.removeChild(deleteButton.parentNode);
}
async function deleteNote() {
    var res = await browser.storage.local.get("site_notes");
    delete res.site_notes[siteName.innerText];
    browser.storage.local.set({site_notes: res.site_notes});
    removeNoteFromList(siteName.innerText);
    confirmDelete.style.width = "0";
}
async function loadCustomNote(ele) {
    var tabs = await browser.tabs.query({active: true, currentWindow: true});
    if (ele.target.innerText !== back.innerText && ele.target.className !== "mdi mdi-delete") {
        back.dataset[tabs[0].id] = ele.target.innerText;
    } else {
        delete back.dataset[tabs[0].id]
        loadSiteNotes();
    }
    if (ele.target.innerText === "General Notes") {
        loadGeneralNotes();
    } else if (ele.target.className === "mdi mdi-delete") {
        confirmDelete.style.width = "100%";
        siteName.innerText = ele.target.dataset.deleteSite;
        return;
    } else if (ele.target.className === "name") {
        siteNoteSetup(ele.target.innerText);
    } else {
        return;
    }
    closeList();
}
function closeConfirm() {
    confirmDelete.style.width = "0";
}
async function loadSiteNotes(manualClick = false) {
    var res = await browser.storage.local.get("options");
    var tabs = await browser.tabs.query({active: true, currentWindow: true});
    if (!tabs[0].incognito || manualClick || (res.options.private_browsing && tabs[0].incognito)) {
        var url = tabs[0].url;
        var site = await siteParser(url);
        if (site === "general_notes") {
            loadGeneralNotes();
        } else {
            siteNoteSetup(site);
        }
    } else {
        loadGeneralNotes();
    }
}
function changeNoteMode(ele) {
    switch (ele.target.className) {
        case "mdi mdi-web":
            loadSiteNotes(true);
            break;
        case "mdi mdi-note":
            loadSiteNotes();
            break;
    }
}
async function setTheme(mode) {
    var res = await browser.storage.local.get("options");
    switch (mode) {
        case "light":
            var theme = "";
            break;
        case "dark":
            var theme = "_dark";
            break;
    }
    document.body.style.backgroundColor = "#" + res.options["background_color" + theme];
    document.body.style.color = "#" + res.options["font_color" + theme];
    search.style.color = "#" + res.options["font_color" + theme];
    search.style.backgroundColor = "#" + res.options["background_color" + theme];
}
async function changeTheme(ele) {
    var res = await browser.storage.local.get("options");
    switch (ele.target.title) {
        case "Switch to light theme":
            ele.target.title = "Switch to dark theme";
            res.options.theme = "light";
            browser.storage.local.set({options: res.options});
            setTheme("light");
            break;
        case "Switch to dark theme":
            ele.target.title = "Switch to light theme";
            res.options.theme = "dark";
            browser.storage.local.set({options: res.options});
            setTheme("dark");
            break;
    }
}
function addNoteToList(site) {
    var cont = document.createElement("span");
    cont.className = "container";
    var name = document.createElement("div");
    name.innerText = site;
    name.className = "name";
    var del = document.createElement("span");
    del.dataset.deleteSite = site;
    del.className = "mdi mdi-delete";
    cont.append(name);
    cont.append(del);
    noteList.append(cont);
}
async function loadNoteList() {
    var res = await browser.storage.local.get("site_notes");
    for (var site in res.site_notes) {
        if (res.site_notes.hasOwnProperty(site)) {
            addNoteToList(site);
        }
    }
}
function resizePage() {
    textarea.style.height = window.innerHeight - 30 + "px";
    textarea.style.width = window.innerWidth - 2 + "px";
    overlay.style.height = window.innerHeight - 30 + "px";
}
async function pageSetup() {
    var res = await browser.storage.local.get("options");
    switch (res.options.theme) {
        case "light":
            theme.title = "Switch to dark theme";
            break;
        case "dark":
            theme.title = "Switch to light theme";
            break;
    }
    setTheme(res.options.theme);
    if (res.options.font_family === "custom") {
        textarea.style.fontFamily = res.options.font_css;
    } else if (res.options.font_family !== "default") {
        textarea.style.fontFamily = res.options.font_family;
    }
    textarea.style.fontSize = res.options.font_size + "px";
    var context = getContext();
    switch (context) {
        case "tab":
            openInTab.style.display = "none";
            toggle.style.display = "none";
            break;
        case "sidebar":
            browser.tabs.onActivated.addListener(perTabSidebar);
            browser.tabs.onUpdated.addListener(perTabSidebar);
            break;
        case "popup":
            document.body.style.width = res.options.width + "px";
            textarea.style.width = res.options.width + "px";
            textarea.style.height = res.options.height + "px";
            overlay.style.height = res.options.height + "px";
            break;
    }
    if (context !== "popup") {
        window.addEventListener("resize", resizePage);
        resizePage();
    }
    switch (res.options.default_display) {
        case "general_notes":
            loadGeneralNotes();
            break;
        case "site_notes":
            loadSiteNotes();
            break;
    }
    loadNoteList();
}
function options() {
    browser.runtime.openOptionsPage();
}
function openTab() {
    browser.tabs.create({
        active: true,
        url: "notes.html"
    });
}
async function perTabSidebar() {
    var res = await browser.storage.local.get("options");
    var tabs = await browser.tabs.query({active: true, currentWindow: true});
    if (!back.dataset.hasOwnProperty(tabs[0].id)) {
        switch (res.options.default_display) {
            case "site_notes":
                loadSiteNotes();
                break;
            case "general_notes":
                loadGeneralNotes();
                break;
        }
    } else {
        siteNoteSetup(back.dataset[tabs[0].id]);
    }
}
function listUpdate(changes) {
    if (changes.hasOwnProperty("site_notes")) {
        var oldValues = Object.keys(changes.site_notes.oldValue);
        var newValues = Object.keys(changes.site_notes.newValue);
        for (var item of oldValues) {
            if (newValues.indexOf(item) === -1) {
                removeNoteFromList(item);
            }
        };
        for (var item of newValues) {
            if (oldValues.indexOf(item) === -1) {
                addNoteToList(item);
            }
        }
    }
}
document.addEventListener("focus", () => {
    textarea.focus();
});
settings.addEventListener("click", options);
toggle.addEventListener("click", changeNoteMode);
theme.addEventListener("click", changeTheme);
back.addEventListener("click", openList);
overlayClose.addEventListener("click", closeList);
noteList.addEventListener("click", loadCustomNote);
no.addEventListener("click", closeConfirm);
yes.addEventListener("click", deleteNote);
openInTab.addEventListener("click", openTab);
search.addEventListener("input", searchResults);
document.addEventListener("DOMContentLoaded", pageSetup);
browser.storage.onChanged.addListener(listUpdate);
<|endoftext|>


<commit_before>module.exports = {
  rules: {
    /*
     * Ignored rules
     * Inline comments explain why rule is ignored
     */
    'selector-max-id': null, // This would require a major refactor
    'at-rule-no-unknown': null, // we're using LESS
    'scss/at-rule-no-unknown': null // we're using LESS
  },
};
<commit_msg>updated local stylelint<commit_after>module.exports = {
  extends: [
    'kolibri-tools/stylelint-config',
  ],
  rules: {
    /*
     * Ignored rules
     * Inline comments explain why rule is ignored
     */
    'selector-max-id': null, // This would require a major refactor
    'at-rule-no-unknown': null, // we're using LESS
    'scss/at-rule-no-unknown': null // we're using LESS
  },
};
<|endoftext|>


<commit_before>/* globals hopscotch: false */
/*
 * Elements courtesy of https://github.com/gthomas3
 * https://github.com/linkedin/hopscotch/issues/80#issuecomment-48330396
 */
function setCookie(key, value) {
    var expires = new Date();
    expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
    document.cookie = key + '=' + value + ';path=/' + ';expires=' + expires.toUTCString();
}

function deleteCookie(key) {
    document.cookie = key + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

function getCookie(key) {
    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
    return keyValue ? keyValue[2] : null;
}

function isVisible(elem) {
    if (!(elem instanceof Element)) throw Error('DomUtil: elem is not an element.');
    const style = getComputedStyle(elem);
    if (style.display === 'none') return false;
    if (style.visibility !== 'visible') return false;
    if (style.opacity < 0.1) return false;
    if (elem.offsetWidth + elem.offsetHeight + elem.getBoundingClientRect().height +
        elem.getBoundingClientRect().width === 0) {
        return false;
    }
    const elemCenter   = {
        x: elem.getBoundingClientRect().left + elem.offsetWidth / 2,
        y: elem.getBoundingClientRect().top + elem.offsetHeight / 2
    };
    if (elemCenter.x < 0) return false;
    if (elemCenter.x > (document.documentElement.clientWidth || window.innerWidth)) return false;
    if (elemCenter.y < 0) return false;
    if (elemCenter.y > (document.documentElement.clientHeight || window.innerHeight)) return false;
    let pointContainer = document.elementFromPoint(elemCenter.x, elemCenter.y);
    do {
        if (pointContainer === elem) return true;
    } while (pointContainer = pointContainer.parentNode);
    return false;
}

function wrap(el, wrapper, newid) {
    wrapper.setAttribute("id", newid)
    el.parentNode.insertBefore(wrapper, el);
    wrapper.appendChild(el);
}

/*
var waitForElementVisible = function(element, callback) {
    var checkExist = setInterval(function() {
        $element = typeof element == "function" ? $(element()) : $(element);
        if ($element.is(':visible')) {
            clearInterval(checkExist);
            if (typeof callback == "function") {
                callback();
            }
        }
    }, 100);
};

var nextOnCallback = function(callback) {
    var currentStep = window.hopscotch.getCurrStepNum();
    callback(function() {
        window.hopscotch.startTour(theTour, currentStep);
    });
};
*/

var tour = {
    id: 'hello-cloudpak-for-multicloud-management',
    steps: [{
            target: 'icp-user-dropdown',
            title: 'User DropDown Menu',
            content: 'Hey there! IBM is honored to be a partner in your multicloud journey. There\'s plenty of time to read doc and explore sample code, but join us first on this quick feature fly-by!
Through this dropdown, access features in the context of your account here.  Things like client command line configuration, setting a default home page and your login session',
            placement: 'bottom',
            arrowOffset: 260,
            xOffset: -280,
            yOffset: 10,
            delay: 500,
            onNext: ["openUserMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openUserMenu"],
        },
        {
            target: 'icp-user',
            title: 'User Deets',
            content: 'Quick reference on the current user name, role and account.',
            placement: 'left',
            arrowOffset: 0,
            yOffset: 0,
            onNext: ["openUserMenu"],
            onPrev: ["openUserMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openUserMenu"],
        },
        {
            target: 'configure-client',
            title: 'kubectl CLI Config',
            content: 'To access your cluster by using the command line interface (CLI), you must install and configure kubectl, the Kubernetes command line tool. For convenience, the cluster configuration details are provided via this menu entry.  This configuration expires in 12 hours. To continue to use the CLI, you must log in and reconfigure kubectl every 12 hours. To avoid this limitation, you can configure your CLI by using service accounts.',
            placement: 'left',
            arrowOffset: 0,
            yOffset: 0,
            onNext: ["openUserMenu"],
            onPrev: ["openUserMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openUserMenu"],
        },
        {
            target: 'icp-homepage',
            title: 'Favorite Page',
            content: 'Choose your favorite page to see first!',
            placement: 'left',
            arrowOffset: 0,
            yOffset: 0,
            onNext: ["openUserMenu"],
            onPrev: ["openUserMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openUserMenu"],
        },
        {
            target: 'icp-logout',
            title: 'Logout',
            content: 'Would hate to see you go, but this is where you can exit a user session',
            placement: 'left',
            arrowOffset: 0,
            yOffset: 0,
            onNext: ["closeUserMenu"],
            onPrev: ["openUserMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openUserMenu"],
        },
        {
            target: document.querySelectorAll('.hamburger-box')[0],
            title: 'Hamburger Menu',
            content: 'This side menu is your main navigation.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -20,
            onPrev: ["openUserMenu"],
            onNext: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#overview' }},
            title: 'Overview',
            content: 'A great place to understand things at a very high level across all managed systems. Use the Overview page to view, manage, and reorganize the dashboard of your cluster information. You can view details of your clusters and other cloud service providers that IBM Multicloud Manager supports. You can also view details about your applications. The Overview dashboard is continuously refreshed in real time.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            onNext: ["openSideMenu"],
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#topology' }},
            title: 'Topology Page',
            content: 'Architects love this view. It visualizes relationships between components and within an application. With containerization, application boundaries may be hard to understand - but not with CP4MCM. The Topology page uses information from Weave Scope probe to display Kubernetes objects within a cluster. You can view hub cluster resources. As you configure managed clusters, you see more clusters in the Topology view.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            onNext: ["openSideMenu"],
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#applications' }},
            title: 'Applications Page',
            content: 'Developers and Operators appreciate this view. You can use the applications page to create, manage, view details, and troubleshoot application resources, including applications, deployables, channels, and subscriptions.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            onNext: ["openSideMenu"],
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#search' }},
            title: 'Search Page',
            content: 'Operators need this view. The needs of one cluster rhyme with the needs of many. Find what you\'re looking for. There\'s alot to sift through.  With the search page, you get visibility into your resources across all your clusters. You can save your popular ones and the platform will happily suggest other filtered views for your consideration.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            onNext: ["openSideMenu"],
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#clusters' }},
            title: 'Clusters Page',
            content: 'Operators use this view when thinking about their environments from a top-down perspective.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            onNext: ["openSideMenu"],
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#policies' }},
            title: 'Governance and Risk Page',
            content: 'SecOps care about this view. ',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            onNext: ["openSideMenu"],
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#monitoring' }},
            title: 'Monitoring Page',
            content: 'Operators need this view. The needs of one cluster rhyme with the needs of many. With a federated monitoring Grafana Dashboard, you have resource metrics at your fingertips.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            onNext: ["openSideMenu"],
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#releases' }},
            title: 'Helm Releases Page',
            content: 'Developers and Operators manage resources in this view. Content is king and having access to world-class IBM and opensource middleware gives your organization advantages.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            onNext: ["openSideMenu"],
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#local' }},
            title: 'Local Cluster Drill Down',
            content: 'Operators infrequently use this view to look at the MCM Hub\'s cluster underpinning its behavior. Even the best maintained homes have their crawl spaces inspected once in a while.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            multipage: true,
            onNext: function() {
              window.location.href ="/multicloud/overview";
            },
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError: ["openSideMenu"],
        },
        {
            target: { get target() { return '#' + document.querySelector('.bx--tooltip__trigger').firstElementChild.id }},
            title: 'Overview Page',
            content: 'View operations details across all of your cloud providers.',
            placement: 'bottom',
            arrowOffset: 0,
            xOffset: 0,
            multipage: true,
            delay: 4000,
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
        },
    ],
    showPrevButton: true,
    scrollTopMargin: 100,
    onEnd: function() {
        setCookie("toured", "toured");
    }
    //onClose: function() {
    //    setCookie("toured", "toured");
    //}
};

/* ========== */
/* TOUR SETUP */
/* ========== */
var addClickListener = function(el, fn) {
    if (el.addEventListener) {
        el.addEventListener('click', fn, false);
    } else {
        el.attachEvent('onclick', fn);
    }
};

var init = function() {
    var startBtnId = 'startTourBtn',
        calloutId = 'startTourCallout',
        mgr = hopscotch.getCalloutManager(),
        state = hopscotch.getState();

    hopscotch.registerHelper("openUserMenu", function() {
        console.log("openUserMenu invoked ...");
        //var event = document.createEvent("SVGEvents");
        //event.initEvent("click",true,true);
        //document.querySelector('#user-dropdown').dispatchEvent(event);
        document.querySelector('#icp-user-dropdown').firstElementChild.classList.add("is-open");
    });

    hopscotch.registerHelper("closeUserMenu", function() {
        console.log("closeUserMenu invoked ...");
        document.querySelector('#icp-user-dropdown').firstElementChild.classList.remove("is-open");
    });

    hopscotch.registerHelper("openSideMenu", function() {
        //keep console.log("registerHelper invoked ...");
        document.querySelector('.hamburger-box').click();
        //var checkExist = setInterval(function() {
        //    var element = document.querySelectorAll('#overview')[0];
        //    if (element) {
        //      clearInterval(checkExist);
        //keep console.log(document.querySelector('#overview').id);
        // Wrapping React element within a div to avoid Uncaught TypeError: j.getBoundingClientRect is not a function
        // https://github.com/soenkekluth/react-sticky-state/issues/9

        //wrap(document.querySelector('#overview'), document.createElement('div'), 'overview-tour');

        // window.hopscotch.startTour(window.hopscotch.getCurrTour(), window.hopscotch.getCurrStepNum());
        //    }
        //}, 2000);
    });

    if (state && state.indexOf('hello-cloudpak-for-multicloud-management') === 0) {
        // Already started the tour at some point!
        hopscotch.startTour(tour);
    } else {
        // Looking at the page for the first(?) time.
        if (!getCookie("toured")) {
            setTimeout(function() {
                mgr.createCallout({
                    id: calloutId,
                    target: startBtnId,
                    placement: 'bottom',
                    title: 'Friend, interested in a tour?',
                    content: 'We shall not cease from exploration
And the end of all our exploring
Will be to arrive where we started
And know the place for the first time.
∞T.S. Eliot∞',
                    xOffset: -15,
                    yOffset: -15,
                    arrowOffset: 20,
                    width: 240
                });
            }, 100);
        }
    }

    addClickListener(document.getElementById(startBtnId), function() {
        if (!hopscotch.isActive) {
            mgr.removeAllCallouts();
            deleteCookie('toured');
            hopscotch.startTour(tour);
        }
    });

};

init();
<commit_msg>Updating MCM tour<commit_after>/* globals hopscotch: false */
/*
 * Elements courtesy of https://github.com/gthomas3
 * https://github.com/linkedin/hopscotch/issues/80#issuecomment-48330396
 */
function setCookie(key, value) {
    var expires = new Date();
    expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
    document.cookie = key + '=' + value + ';path=/' + ';expires=' + expires.toUTCString();
}

function deleteCookie(key) {
    document.cookie = key + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

function getCookie(key) {
    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
    return keyValue ? keyValue[2] : null;
}

function isVisible(elem) {
    if (!(elem instanceof Element)) throw Error('DomUtil: elem is not an element.');
    const style = getComputedStyle(elem);
    if (style.display === 'none') return false;
    if (style.visibility !== 'visible') return false;
    if (style.opacity < 0.1) return false;
    if (elem.offsetWidth + elem.offsetHeight + elem.getBoundingClientRect().height +
        elem.getBoundingClientRect().width === 0) {
        return false;
    }
    const elemCenter   = {
        x: elem.getBoundingClientRect().left + elem.offsetWidth / 2,
        y: elem.getBoundingClientRect().top + elem.offsetHeight / 2
    };
    if (elemCenter.x < 0) return false;
    if (elemCenter.x > (document.documentElement.clientWidth || window.innerWidth)) return false;
    if (elemCenter.y < 0) return false;
    if (elemCenter.y > (document.documentElement.clientHeight || window.innerHeight)) return false;
    let pointContainer = document.elementFromPoint(elemCenter.x, elemCenter.y);
    do {
        if (pointContainer === elem) return true;
    } while (pointContainer = pointContainer.parentNode);
    return false;
}

function wrap(el, wrapper, newid) {
    wrapper.setAttribute("id", newid)
    el.parentNode.insertBefore(wrapper, el);
    wrapper.appendChild(el);
}

/*
var waitForElementVisible = function(element, callback) {
    var checkExist = setInterval(function() {
        $element = typeof element == "function" ? $(element()) : $(element);
        if ($element.is(':visible')) {
            clearInterval(checkExist);
            if (typeof callback == "function") {
                callback();
            }
        }
    }, 100);
};

var nextOnCallback = function(callback) {
    var currentStep = window.hopscotch.getCurrStepNum();
    callback(function() {
        window.hopscotch.startTour(theTour, currentStep);
    });
};
*/

var tour = {
    id: 'hello-cloudpak-for-multicloud-management',
    steps: [{
            target: 'icp-user-dropdown',
            title: 'User DropDown Menu',
            content: 'Hey there! IBM is honored to be a partner in your multicloud journey. There\'s plenty of time to read doc and explore sample code, but join us first on this quick feature fly-by!
Through this dropdown, access features in the context of your account here.  Things like client command line configuration, setting a default home page and your login session',
            placement: 'bottom',
            arrowOffset: 260,
            xOffset: -280,
            yOffset: 10,
            delay: 500,
            onNext: ["openUserMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openUserMenu"],
        },
        {
            target: 'icp-user',
            title: 'User Deets',
            content: 'Quick reference on the current user name, role and account.',
            placement: 'left',
            arrowOffset: 0,
            yOffset: 0,
            onNext: ["openUserMenu"],
            onPrev: ["openUserMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openUserMenu"],
        },
        {
            target: 'configure-client',
            title: 'kubectl CLI Config',
            content: 'To access your cluster by using the command line interface (CLI), you must install and configure kubectl, the Kubernetes command line tool. For convenience, the cluster configuration details are provided via this menu entry.  This configuration expires in 12 hours. To continue to use the CLI, you must log in and reconfigure kubectl every 12 hours. To avoid this limitation, you can configure your CLI by using service accounts.',
            placement: 'left',
            arrowOffset: 0,
            yOffset: 0,
            onNext: ["openUserMenu"],
            onPrev: ["openUserMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openUserMenu"],
        },
        {
            target: 'icp-homepage',
            title: 'Favorite Page',
            content: 'Choose your favorite page to see first!',
            placement: 'left',
            arrowOffset: 0,
            yOffset: 0,
            onNext: ["openUserMenu"],
            onPrev: ["openUserMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openUserMenu"],
        },
        {
            target: 'icp-logout',
            title: 'Logout',
            content: 'Would hate to see you go, but this is where you can exit a user session',
            placement: 'left',
            arrowOffset: 0,
            yOffset: 0,
            onNext: ["closeUserMenu"],
            onPrev: ["openUserMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openUserMenu"],
        },
        {
            target: document.querySelectorAll('.hamburger-box')[0],
            title: 'Hamburger Menu',
            content: 'This side menu is your main navigation.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -20,
            onPrev: ["openUserMenu"],
            onNext: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#overview' }},
            title: 'Overview',
            content: 'A great place to understand things at a very high level across all managed systems. Use the Overview page to view, manage, and reorganize the dashboard of your cluster information. You can view details of your clusters and other cloud service providers that IBM Multicloud Manager supports. You can also view details about your applications. The Overview dashboard is continuously refreshed in real time.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            onNext: ["openSideMenu"],
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#topology' }},
            title: 'Topology Page',
            content: 'Architects love this view. It visualizes relationships between components and within an application. With containerization, application boundaries may be hard to understand - but not with CP4MCM. The Topology page uses information from Weave Scope probe to display Kubernetes objects within a cluster. You can view hub cluster resources. As you configure managed clusters, you see more clusters in the Topology view.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            onNext: ["openSideMenu"],
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#applications' }},
            title: 'Applications Page',
            content: 'Developers and Operators appreciate this view. You can use the applications page to create, manage, view details, and troubleshoot application resources, including applications, deployables, channels, and subscriptions.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            onNext: ["openSideMenu"],
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#search' }},
            title: 'Search Page',
            content: 'Operators need this view. The needs of one cluster rhyme with the needs of many. Find what you\'re looking for. There\'s alot to sift through.  With the search page, you get visibility into your resources across all your clusters. You can save your popular ones and the platform will happily suggest other filtered views for your consideration.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            onNext: ["openSideMenu"],
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#clusters' }},
            title: 'Clusters Page',
            content: 'Operators use this view when thinking about their environments from a top-down perspective.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            onNext: ["openSideMenu"],
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#policies' }},
            title: 'Governance and Risk Page',
            content: 'SecOps care about this view. ',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            onNext: ["openSideMenu"],
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#monitoring' }},
            title: 'Monitoring Page',
            content: 'Operators need this view. The needs of one cluster rhyme with the needs of many. With a federated monitoring Grafana Dashboard, you have resource metrics at your fingertips.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            onNext: ["openSideMenu"],
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#releases' }},
            title: 'Helm Releases Page',
            content: 'Developers and Operators manage resources in this view. Content is king and having access to world-class IBM and opensource middleware gives your organization advantages.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            onNext: ["openSideMenu"],
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError:["openSideMenu"],
        },
        {
            target: { get target() { return '#local' }},
            title: 'Local Cluster Drill Down',
            content: 'Operators infrequently use this view to look at the MCM Hub\'s cluster underpinning its behavior. Even the best maintained homes have their crawl spaces inspected once in a while.',
            placement: 'right',
            arrowOffset: 0,
            yOffset: -10,
            delay: 500,
            multipage: true,
            onNext: function() {
              window.location.href ="/multicloud/overview";
            },
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
            onError: ["openSideMenu"],
        },
        {
            target: 'header',
            title: 'Overview Page',
            content: 'View operations details across all of your cloud providers.',
            placement: 'bottom',
            arrowOffset: 0,
            xOffset: 0,
            multipage: true,
            delay: 500,
            onPrev: ["openSideMenu"],
            onClose: function() {
                setCookie("toured", "toured");
            },
        },
    ],
    showPrevButton: true,
    scrollTopMargin: 100,
    onEnd: function() {
        setCookie("toured", "toured");
    }
    //onClose: function() {
    //    setCookie("toured", "toured");
    //}
};

/* ========== */
/* TOUR SETUP */
/* ========== */
var addClickListener = function(el, fn) {
    if (el.addEventListener) {
        el.addEventListener('click', fn, false);
    } else {
        el.attachEvent('onclick', fn);
    }
};

var init = function() {
    var startBtnId = 'startTourBtn',
        calloutId = 'startTourCallout',
        mgr = hopscotch.getCalloutManager(),
        state = hopscotch.getState();

    hopscotch.registerHelper("openUserMenu", function() {
        console.log("openUserMenu invoked ...");
        //var event = document.createEvent("SVGEvents");
        //event.initEvent("click",true,true);
        //document.querySelector('#user-dropdown').dispatchEvent(event);
        document.querySelector('#icp-user-dropdown').firstElementChild.classList.add("is-open");
    });

    hopscotch.registerHelper("closeUserMenu", function() {
        console.log("closeUserMenu invoked ...");
        document.querySelector('#icp-user-dropdown').firstElementChild.classList.remove("is-open");
    });

    hopscotch.registerHelper("openSideMenu", function() {
        //keep console.log("registerHelper invoked ...");
        document.querySelector('.hamburger-box').click();
        //var checkExist = setInterval(function() {
        //    var element = document.querySelectorAll('#overview')[0];
        //    if (element) {
        //      clearInterval(checkExist);
        //keep console.log(document.querySelector('#overview').id);
        // Wrapping React element within a div to avoid Uncaught TypeError: j.getBoundingClientRect is not a function
        // https://github.com/soenkekluth/react-sticky-state/issues/9

        //wrap(document.querySelector('#overview'), document.createElement('div'), 'overview-tour');

        // window.hopscotch.startTour(window.hopscotch.getCurrTour(), window.hopscotch.getCurrStepNum());
        //    }
        //}, 2000);
    });

    if (state && state.indexOf('hello-cloudpak-for-multicloud-management') === 0) {
        // Already started the tour at some point!
        hopscotch.startTour(tour);
        setInterval(function () { hopscotch.nextStep() }, 3000);
    } else {
        // Looking at the page for the first(?) time.
        if (!getCookie("toured")) {
            setTimeout(function() {
                mgr.createCallout({
                    id: calloutId,
                    target: startBtnId,
                    placement: 'bottom',
                    title: 'Friend, interested in a tour?',
                    content: 'We shall not cease from exploration
And the end of all our exploring
Will be to arrive where we started
And know the place for the first time.
∞T.S. Eliot∞',
                    xOffset: -15,
                    yOffset: -15,
                    arrowOffset: 20,
                    width: 240
                });
            }, 100);
        }
    }

    addClickListener(document.getElementById(startBtnId), function() {
        if (!hopscotch.isActive) {
            mgr.removeAllCallouts();
            deleteCookie('toured');
            hopscotch.startTour(tour);
            setInterval(function () { hopscotch.nextStep() }, 3000);
        }
    });

};

init();
<|endoftext|>


<commit_before>angular.module("umbraco").controller("Skybrud.Social.Facebook.OAuth.Controller", ['$scope', 'editorState', function ($scope, editorState) {

    // Define an alias for the editor (eg. used for callbacks)
    var alias = ('skybrudsocial_' + Math.random()).replace('.', '');

    // Get a reference to the current editor state
    var state = editorState.current;

    $scope.expiresDays = null;

    $scope.callback = function (data) {

        $scope.model.value = data;

        updateUI();

        updateBusinessPagesDropdownUI();
    };

    function updateBusinessPagesDropdownUI() {

        var array = $scope.model.value.business_pages;
        if (array) {
            //for (var i = 0; i < array.length; i++)
            //  console.log(array[i]);
            $scope.accounts = array;
        }

        //Whether there is a selected account, bind data
        if ($scope.model.value && $scope.model.value.selected_business_page) {
            $scope.selectedBusinessPage = $scope.model.value.selected_business_page;
        }

        //Register onChange event
        $scope.businessPageSelected = function (selectedAccount) {
            $scope.selectedBusinessPage = selectedAccount;
            $scope.model.value.selected_business_page = selectedAccount;//persists on Umbraco model
        };
    }

    $scope.authorize = function () {

        var url = '/App_Plugins/Skybrud.Social/Dialogs/FacebookOAuth.aspx?callback=' + alias;
        url += "&contentTypeAlias=" + state.contentTypeAlias;
        url += "&propertyAlias=" + $scope.model.alias;

        window.open(url, 'Facebook OAuth', 'scrollbars=no,resizable=yes,menubar=no,width=1050,height=800');

    };

    $scope.clear = function () {

        $scope.model.value = null;

    };

    function format(number, decimals) {
        var text = Math.round(number * 10 * decimals);
        return text / 10 / decimals;
    }

    function updateUI() {

        if ($scope.model.value && $scope.model.value.expires_at) {

            var seconds = (new Date($scope.model.value.expires_at) - new Date()) / 1000;
            $scope.expiresDays = format(seconds / 60 / 60 / 24, 2);

        } else {

            $scope.expiresDays = NaN;

        }

    }

    //load stored data in content editor (UI)
    updateUI();
    updateBusinessPagesDropdownUI();

    // Register the callback function in the global scope
    window[alias] = $scope.callback;

}]);

angular.module("umbraco").controller("Skybrud.Social.Facebook.OAuth.PreValues.Controller", ['$scope', '$http', 'dialogService', function ($scope, $http, dialogService) {

    if (!$scope.model.value) {
        $scope.model.value = {
            appid: '',
            appsecret: '',
            redirecturi: '',
            scope: []
        };
    }

    if (!$scope.model.value.scope) $scope.model.value.scope = [];

    $scope.addScope = function () {

        var d = dialogService.open({
            modalClass: 'SocialDialog',
            template: '/App_Plugins/Skybrud.Social/Facebook/OAuth/ScopesDialog.html',
            show: true,
            callback: function (scopes) {
                $scope.model.value.scope = scopes;
            },
            selection: $scope.model.value.scope
        });

        d.element[0].style.width = '1000px';
        d.element[0].style.marginLeft = '-500px';

    };

    $scope.removeScope = function (index) {
        $scope.model.value.scope.splice(index, 1);
    };

    $scope.suggestedRedirectUri = window.location.origin + '/App_Plugins/Skybrud.Social/Dialogs/FacebookOAuth.aspx';

}]);<commit_msg>Added $scope.$apply to properly propagate the change of the model<commit_after>angular.module("umbraco").controller("Skybrud.Social.Facebook.OAuth.Controller", ['$scope', 'editorState', function ($scope, editorState) {

    // Define an alias for the editor (eg. used for callbacks)
    var alias = ('skybrudsocial_' + Math.random()).replace('.', '');

    // Get a reference to the current editor state
    var state = editorState.current;

    $scope.expiresDays = null;

    $scope.callback = function (data) {
        $scope.$apply(function () {
            $scope.model.value = data;
            updateUI();
            updateBusinessPagesDropdownUI();
        });
    };

    function updateBusinessPagesDropdownUI() {

        var array = $scope.model.value.business_pages;
        if (array) {
            //for (var i = 0; i < array.length; i++)
            //  console.log(array[i]);
            $scope.accounts = array;
        }

        //Whether there is a selected account, bind data
        if ($scope.model.value && $scope.model.value.selected_business_page) {
            $scope.selectedBusinessPage = $scope.model.value.selected_business_page;
        }

        //Register onChange event
        $scope.businessPageSelected = function (selectedAccount) {
            $scope.selectedBusinessPage = selectedAccount;
            $scope.model.value.selected_business_page = selectedAccount;//persists on Umbraco model
        };
    }

    $scope.authorize = function () {

        var url = '/App_Plugins/Skybrud.Social/Dialogs/FacebookOAuth.aspx?callback=' + alias;
        url += "&contentTypeAlias=" + state.contentTypeAlias;
        url += "&propertyAlias=" + $scope.model.alias;

        window.open(url, 'Facebook OAuth', 'scrollbars=no,resizable=yes,menubar=no,width=1050,height=800');

    };

    $scope.clear = function () {
        $scope.model.value = null;
    };

    function format(number, decimals) {
        var text = Math.round(number * 10 * decimals);
        return text / 10 / decimals;
    }

    function updateUI() {

        if ($scope.model.value && $scope.model.value.expires_at) {

            var seconds = (new Date($scope.model.value.expires_at) - new Date()) / 1000;
            $scope.expiresDays = format(seconds / 60 / 60 / 24, 2);

        } else {

            $scope.expiresDays = NaN;

        }

    }

    //load stored data in content editor (UI)
    updateUI();
    updateBusinessPagesDropdownUI();

    // Register the callback function in the global scope
    window[alias] = $scope.callback;

}]);

angular.module("umbraco").controller("Skybrud.Social.Facebook.OAuth.PreValues.Controller", ['$scope', '$http', 'dialogService', function ($scope, $http, dialogService) {

    if (!$scope.model.value) {
        $scope.model.value = {
            appid: '',
            appsecret: '',
            redirecturi: '',
            scope: []
        };
    }

    if (!$scope.model.value.scope) $scope.model.value.scope = [];

    $scope.addScope = function () {

        var d = dialogService.open({
            modalClass: 'SocialDialog',
            template: '/App_Plugins/Skybrud.Social/Facebook/OAuth/ScopesDialog.html',
            show: true,
            callback: function (scopes) {
                $scope.model.value.scope = scopes;
            },
            selection: $scope.model.value.scope
        });

        d.element[0].style.width = '1000px';
        d.element[0].style.marginLeft = '-500px';

    };

    $scope.removeScope = function (index) {
        $scope.model.value.scope.splice(index, 1);
    };

    $scope.suggestedRedirectUri = window.location.origin + '/App_Plugins/Skybrud.Social/Dialogs/FacebookOAuth.aspx';

}]);<|endoftext|>


<commit_before>'use strict';

var VisitModel = require('../models/visit-model');
var Domains = require('../models/domain-model');
var bcrypt = require('bcrypt-nodejs');
var crypto = require('crypto');

/**
 * API endpoints to create new users and log in existing ones
 */

module.exports = function(app, cors) {

    var api = '/api/0_0_1/provisionKeys';

    app.options(api, cors());

    var corsOptions = {
        methods: 'POST',
        maxAge: 300
    };

    app.post(api, function(req, res) {
        var origin = req.get('Origin');

        Domains.find({ host: origin }, function(err, dbResponse) {
            var attributes = {};
            var response = {};

            var writeKey = dbResponse.writeKey;

            attributes.host = req.get('Host');
            attributes.referer = req.get('Referer');
            attributes.session_id = bcrypt.hashSync(crypto.randomBytes(16).toString('base64'));
            attributes.ip_address = req.ip || req.ips;
            attributes.user_agent = req.get('User-Agent');

            if(!req.body.uuid) {
                attributes.uniqueVisitorID = bcrypt.hashSync(crypto.randomBytes(16).toString('base64'));
                response.uuid = attributes.uniqueVisitorID;
            }

            var visit = new VisitModel(attributes);
            visit.events.push(req.body);
            visit.save();

            response.usid = attributes.session_id;
            response.writeKey = attributes.writeKey;

            return res.status(200).json(response);
        });
    });
};<commit_msg>Resolve linting issues<commit_after>'use strict';

var VisitModel = require('../models/visit-model');
var Domains = require('../models/domain-model');
var bcrypt = require('bcrypt-nodejs');
var crypto = require('crypto');

/**
 * API endpoints to create new users and log in existing ones
 */

module.exports = function(app, cors) {

    var api = '/api/0_0_1/provisionKeys';

    app.options(api, cors());

    var corsOptions = {
        methods: 'POST',
        maxAge: 300
    };

    app.post(api, cors(corsOptions), function(req, res) {
        var origin = req.get('Origin');

        Domains.find({ host: origin }, function(err, dbResponse) {
            var attributes = {};
            var response = {};

            attributes.host = req.get('Host');
            attributes.referer = req.get('Referer');
            attributes.session_id = bcrypt.hashSync(crypto.randomBytes(16).toString('base64'));
            attributes.ip_address = req.ip || req.ips;
            attributes.user_agent = req.get('User-Agent');

            if(!req.body.uuid) {
                attributes.uniqueVisitorID = bcrypt.hashSync(crypto.randomBytes(16).toString('base64'));
                response.uuid = attributes.uniqueVisitorID;
            }

            var visit = new VisitModel(attributes);
            visit.events.push(req.body);
            visit.save();

            response.usid = attributes.session_id;
            response.writeKey = dbResponse.writeKey;

            return res.status(200).json(response);
        });
    });
};<|endoftext|>