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

const exec = require("child_process").execSync;

const generator = require("./generator");
const fu = require("./futil");

const dirs = [
  // Flux
  "./app",
  "./app/actions",
  "./app/constants",
  "./app/components",
  "./app/dispatcher",
  "./app/stores",
  "./app/utils",

  // Build
  "./public",
  "./public/css",
  "./public/img",
  "./public/js",

  // Jest
  "./__tests__"
];

const npms = [
  // Babel
  "yarn add --dev @babel/cli",
  "yarn add --dev @babel/core",
  "yarn add --dev @babel/preset-env",
  "yarn add --dev @babel/preset-react",

  // Stage 0
  "yarn add --dev @babel/plugin-proposal-function-bind",

  // Stage 1
  "yarn add --dev @babel/plugin-proposal-export-default-from",
  "yarn add --dev @babel/plugin-proposal-logical-assignment-operators",
  "yarn add --dev @babel/plugin-proposal-optional-chaining",
  "yarn add --dev @babel/plugin-proposal-pipeline-operator",
  "yarn add --dev @babel/plugin-proposal-nullish-coalescing-operator",
  "yarn add --dev @babel/plugin-proposal-do-expressions",

  // Stage 2
  "yarn add --dev @babel/plugin-proposal-decorators",
  ,
  "yarn add --dev @babel/plugin-proposal-function-sent",
  "yarn add --dev @babel/plugin-proposal-export-namespace-from",
  "yarn add --dev @babel/plugin-proposal-numeric-separator",
  "yarn add --dev @babel/plugin-proposal-throw-expressions",

  // Stage 3
  "yarn add --dev @babel/plugin-syntax-dynamic-import",
  "yarn add --dev @babel/plugin-syntax-import-meta",
  "yarn add --dev @babel/plugin-proposal-class-properties",
  "yarn add --dev @babel/plugin-proposal-json-strings",

  // React.js
  "yarn add react",
  "yarn add react-dom",
  "yarn add prop-types",
  //  "yarn add --dev raf",

  // Flux
  "yarn add flux",

  // Immutable.js
  "yarn add immutable",

  // Jest
  "yarn add --dev jest-cli",
  "yarn add --dev babel-jest",
  "yarn add --dev babel-core@^7.0.0-0",
  "yarn add --dev regenerator-runtime",

  // WebPack
  "yarn add --dev webpack",
  "yarn add --dev webpack-cli",
  "yarn add --dev webpack-dev-server",
  "yarn add --dev webpack-bundle-analyzer",
  "yarn add --dev babel-loader",

  // ESLint
  "yarn add --dev eslint",
  "yarn add --dev babel-eslint",
  "yarn add --dev eslint-plugin-import",
  "yarn add --dev eslint-plugin-react",
  "yarn add --dev eslint-plugin-jsx-a11y",
  "yarn add --dev eslint-config-airbnb",

  // Prettier
  "yarn add --dev prettier",
  "yarn add --dev eslint-plugin-prettier",
  "yarn add --dev eslint-config-prettier"
];

const npms_plus = [
  "yarn add @material-ui/core",
  "yarn add @material-ui/icons",
  "yarn add react-router-dom",
  "yarn add axios"
];

const repository = {
  type: "git",
  url: "https://example.com"
};

const jest = {
  unmockedModulePathPatterns: [
    "<rootDir>/node_modules/react",
    "<rootDir>/node_modules/react-dom",
    "<rootDir>/node_modules/react-addons-test-utils"
  ],
  transform: {
    "^.+\\.jsx?$": "babel-jest"
  },
  moduleFileExtensions: ["js", "json"]
};

const scripts = {
  start: "webpack-dev-server --progress --colors --mode development",
  dev: "webpack -p --progress --colors --mode development",
  build: "webpack -p --progress --colors --mode production",
  test: "jest",
  lint: "eslint app/** __tests__/**",
  fix: "eslint app/** __tests__/** --fix",
  "bundle-analyze":
    "webpack --profile --json > stats.json && webpack-bundle-analyzer ./stats.json"
};

const eslint = {
  extends: ["airbnb", "prettier", "prettier/react"],
  parser: "babel-eslint",
  env: {
    browser: true,
    jest: true
  },
  plugins: ["prettier"],
  rules: {
    "react/jsx-filename-extension": [1, { extensions: [".js"] }],
    "react/no-find-dom-node": 0,
    "jsx-a11y/anchor-is-valid": [
      "error",
      {
        components: ["Link"],
        specialLink: ["to", "hrefLeft", "hrefRight"],
        aspects: ["noHref", "invalidHref", "preferButton"]
      }
    ]
  }
};

const keywords = {
  keywords: ["react", "flux"]
};

main();

function main() {
  console.log("*** starter-react-flux ***");
  const args = process.argv;
  switch (args.length) {
    case 3:
      if (args[2] == "init") {
        setupReact();
        setupReactPlus();
        showComplete();
      } else if (args[2] == "init-basic") {
        setupReact();
        showUsage();
      }
      break;
    case 4:
      if (args[2] == "generate" && args[3] == "test") {
        generator.ComponentTestFiles();
        showComplete();
      } else {
        showUsage();
      }
      break;
    case 5:
      if (args[2] == "generate" && args[3] == "store") {
        generator.StoreFile(args[4]);
        showComplete();
      } else if (args[2] == "generate" && args[3] == "action") {
        generator.ActionFile(args[4]);
        showComplete();
      } else if (args[2] == "generate" && args[3] == "container") {
        generator.ContainerFile(args[4]);
        showComplete();
      } else if (args[2] == "generate" && args[3] == "component") {
        generator.ComponentFile(args[4]);
        showComplete();
      } else {
        showUsage();
      }
      break;
    default:
      showUsage();
      break;
  }
}

function showUsage() {
  console.log("*** starter-react-flux ***");
  console.log("Usage:");
  console.log(
    "starter-react-flux init                      : Setup a React/Flux project."
  );
  console.log(
    "starter-react-flux generate container [Name] : Generate the Component."
  );
  console.log(
    "starter-react-flux generate component [Name] : Generate the Container."
  );
  console.log(
    "starter-react-flux generate store  [Name]    : Generate the Store. "
  );
  console.log(
    "starter-react-flux generate action [Name]    : Generate the ActionCreators."
  );
  console.log(
    "starter-react-flux generate test             : Generate tests of components."
  );
  process.exit(-1);
}

function showComplete() {
  console.log("Completed!");
}

function setupReact(arg) {
  fu.createDirectories(dirs);
  exec("npm init -y", fu.puts);
  fu.fixJSON("package.json", "description", "React template.");
  fu.fixJSON("package.json", "repository", repository);
  fu.fixJSON("package.json", "jest", jest);
  fu.fixJSON("package.json", "scripts", scripts);
  fu.fixJSON("package.json", "keywords", keywords);
  fu.fixJSON("package.json", "license", "MIT");

  fu.createJSON(".eslintrc", eslint);
  fu.createJSON(".babelrc", {
    presets: ["@babel/preset-react", "@babel/preset-env"],
    plugins: [
      "@babel/plugin-proposal-function-bind",
      "@babel/plugin-proposal-export-default-from",
      "@babel/plugin-proposal-logical-assignment-operators",
      ["@babel/plugin-proposal-optional-chaining", { loose: false }],
      ["@babel/plugin-proposal-pipeline-operator", { proposal: "minimal" }],
      ["@babel/plugin-proposal-nullish-coalescing-operator", { loose: false }],
      "@babel/plugin-proposal-do-expressions",
      ["@babel/plugin-proposal-decorators", { legacy: true }],
      "@babel/plugin-proposal-function-sent",
      "@babel/plugin-proposal-export-namespace-from",
      "@babel/plugin-proposal-numeric-separator",
      "@babel/plugin-proposal-throw-expressions",
      "@babel/plugin-syntax-dynamic-import",
      "@babel/plugin-syntax-import-meta",
      ["@babel/plugin-proposal-class-properties", { loose: false }],
      "@babel/plugin-proposal-json-strings"
    ]
  });
  console.log(__dirname);
  fu.createFile("./public/index.html", fu.readFile("./public/index.html"));
  fu.createFile("./public/css/style.css", fu.readFile("./public/main.css"));
  fu.createFile("webpack.config.js", fu.readFile("./app/webpack.js"));
  fu.createFile("./app/App.js", fu.readFile("./app/App.js"));
  fu.createFile(
    "./app/dispatcher/AppDispatcher.js",
    fu.readFile("./app/dispatcher/dispatcher.js")
  );
  fu.createFile(
    "./app/constants/AppConstants.js",
    fu.readFile("./app/constants/constant.js")
  );
  fu.createFile(
    "./app/components/Navi.js",
    fu.readFile("./app/components/Navi.js")
  );
  fu.createFile(
    "./app/components/Menu.js",
    fu.readFile("./app/components/Menu.js")
  );
  fu.createFile(
    "./app/components/Content.js",
    fu.readFile("./app/components/Content.js")
  );
  fu.createFile(
    "./__tests__/Content-test.js",
    fu.readFile("./__tests__/Content-test.js")
  );

  generator.StoreFile("Sample");
  generator.ActionFile("Sample");
  generator.ContainerFile("Top");
  generator.ContainerFile("Sample");
  npmInstall(npms);
}

function setupReactPlus() {
  npmInstall(npms_plus);
}

function npmInstall(npms) {
  npms.map(command => {
    console.log(command);
    exec(command, fu.puts);
  });
}
<commit_msg>add transform-runtime<commit_after>#!/usr/bin/env node

const exec = require("child_process").execSync;

const generator = require("./generator");
const fu = require("./futil");

const dirs = [
  // Flux
  "./app",
  "./app/actions",
  "./app/constants",
  "./app/components",
  "./app/dispatcher",
  "./app/stores",
  "./app/utils",

  // Build
  "./public",
  "./public/css",
  "./public/img",
  "./public/js",

  // Jest
  "./__tests__"
];

const npms = [
  // Babel
  "yarn add --dev @babel/cli",
  "yarn add --dev @babel/core",
  "yarn add --dev @babel/preset-env",
  "yarn add --dev @babel/preset-react",

  // Stage 0
  "yarn add --dev @babel/plugin-proposal-function-bind",

  // Stage 1
  "yarn add --dev @babel/plugin-proposal-export-default-from",
  "yarn add --dev @babel/plugin-proposal-logical-assignment-operators",
  "yarn add --dev @babel/plugin-proposal-optional-chaining",
  "yarn add --dev @babel/plugin-proposal-pipeline-operator",
  "yarn add --dev @babel/plugin-proposal-nullish-coalescing-operator",
  "yarn add --dev @babel/plugin-proposal-do-expressions",

  // Stage 2
  "yarn add --dev @babel/plugin-proposal-decorators",
  "yarn add --dev @babel/plugin-proposal-function-sent",
  "yarn add --dev @babel/plugin-proposal-export-namespace-from",
  "yarn add --dev @babel/plugin-proposal-numeric-separator",
  "yarn add --dev @babel/plugin-proposal-throw-expressions",

  // Stage 3
  "yarn add --dev @babel/plugin-syntax-dynamic-import",
  "yarn add --dev @babel/plugin-syntax-import-meta",
  "yarn add --dev @babel/plugin-proposal-class-properties",
  "yarn add --dev @babel/plugin-proposal-json-strings",

  "yarn add --dev @babel/plugin-transform-runtime",

  // React.js
  "yarn add react",
  "yarn add react-dom",
  "yarn add prop-types",
  //  "yarn add --dev raf",

  // Flux
  "yarn add flux",

  // Immutable.js
  "yarn add immutable",

  // Jest
  "yarn add --dev jest-cli",
  "yarn add --dev babel-jest",
  "yarn add --dev babel-core@^7.0.0-0",
  "yarn add --dev regenerator-runtime",

  // WebPack
  "yarn add --dev webpack",
  "yarn add --dev webpack-cli",
  "yarn add --dev webpack-dev-server",
  "yarn add --dev webpack-bundle-analyzer",
  "yarn add --dev babel-loader",

  // ESLint
  "yarn add --dev eslint",
  "yarn add --dev babel-eslint",
  "yarn add --dev eslint-plugin-import",
  "yarn add --dev eslint-plugin-react",
  "yarn add --dev eslint-plugin-jsx-a11y",
  "yarn add --dev eslint-config-airbnb",

  // Prettier
  "yarn add --dev prettier",
  "yarn add --dev eslint-plugin-prettier",
  "yarn add --dev eslint-config-prettier"
];

const npms_plus = [
  "yarn add @material-ui/core",
  "yarn add @material-ui/icons",
  "yarn add react-router-dom",
  "yarn add axios"
];

const repository = {
  type: "git",
  url: "https://example.com"
};

const jest = {
  unmockedModulePathPatterns: [
    "<rootDir>/node_modules/react",
    "<rootDir>/node_modules/react-dom",
    "<rootDir>/node_modules/react-addons-test-utils"
  ],
  transform: {
    "^.+\\.jsx?$": "babel-jest"
  },
  moduleFileExtensions: ["js", "json"]
};

const scripts = {
  start: "webpack-dev-server --progress --colors --mode development",
  dev: "webpack -p --progress --colors --mode development",
  build: "webpack -p --progress --colors --mode production",
  test: "jest",
  lint: "eslint app/** __tests__/**",
  fix: "eslint app/** __tests__/** --fix",
  "bundle-analyze":
    "webpack --profile --json > stats.json && webpack-bundle-analyzer ./stats.json"
};

const eslint = {
  extends: ["airbnb", "prettier", "prettier/react"],
  parser: "babel-eslint",
  env: {
    browser: true,
    jest: true
  },
  plugins: ["prettier"],
  rules: {
    "react/jsx-filename-extension": [1, { extensions: [".js"] }],
    "react/no-find-dom-node": 0,
    "jsx-a11y/anchor-is-valid": [
      "error",
      {
        components: ["Link"],
        specialLink: ["to", "hrefLeft", "hrefRight"],
        aspects: ["noHref", "invalidHref", "preferButton"]
      }
    ]
  }
};

const keywords = {
  keywords: ["react", "flux"]
};

main();

function main() {
  console.log("*** starter-react-flux ***");
  const args = process.argv;
  switch (args.length) {
    case 3:
      if (args[2] == "init") {
        setupReact();
        setupReactPlus();
        showComplete();
      } else if (args[2] == "init-basic") {
        setupReact();
        showUsage();
      }
      break;
    case 4:
      if (args[2] == "generate" && args[3] == "test") {
        generator.ComponentTestFiles();
        showComplete();
      } else {
        showUsage();
      }
      break;
    case 5:
      if (args[2] == "generate" && args[3] == "store") {
        generator.StoreFile(args[4]);
        showComplete();
      } else if (args[2] == "generate" && args[3] == "action") {
        generator.ActionFile(args[4]);
        showComplete();
      } else if (args[2] == "generate" && args[3] == "container") {
        generator.ContainerFile(args[4]);
        showComplete();
      } else if (args[2] == "generate" && args[3] == "component") {
        generator.ComponentFile(args[4]);
        showComplete();
      } else {
        showUsage();
      }
      break;
    default:
      showUsage();
      break;
  }
}

function showUsage() {
  console.log("*** starter-react-flux ***");
  console.log("Usage:");
  console.log(
    "starter-react-flux init                      : Setup a React/Flux project."
  );
  console.log(
    "starter-react-flux generate container [Name] : Generate the Component."
  );
  console.log(
    "starter-react-flux generate component [Name] : Generate the Container."
  );
  console.log(
    "starter-react-flux generate store  [Name]    : Generate the Store. "
  );
  console.log(
    "starter-react-flux generate action [Name]    : Generate the ActionCreators."
  );
  console.log(
    "starter-react-flux generate test             : Generate tests of components."
  );
  process.exit(-1);
}

function showComplete() {
  console.log("Completed!");
}

function setupReact(arg) {
  fu.createDirectories(dirs);
  exec("npm init -y", fu.puts);
  fu.fixJSON("package.json", "description", "React template.");
  fu.fixJSON("package.json", "repository", repository);
  fu.fixJSON("package.json", "jest", jest);
  fu.fixJSON("package.json", "scripts", scripts);
  fu.fixJSON("package.json", "keywords", keywords);
  fu.fixJSON("package.json", "license", "MIT");

  fu.createJSON(".eslintrc", eslint);
  fu.createJSON(".babelrc", {
    presets: ["@babel/preset-react", "@babel/preset-env"],
    plugins: [
      "@babel/plugin-transform-runtime",
      "@babel/plugin-proposal-function-bind",
      "@babel/plugin-proposal-export-default-from",
      "@babel/plugin-proposal-logical-assignment-operators",
      ["@babel/plugin-proposal-optional-chaining", { loose: false }],
      ["@babel/plugin-proposal-pipeline-operator", { proposal: "minimal" }],
      ["@babel/plugin-proposal-nullish-coalescing-operator", { loose: false }],
      "@babel/plugin-proposal-do-expressions",
      ["@babel/plugin-proposal-decorators", { legacy: true }],
      "@babel/plugin-proposal-function-sent",
      "@babel/plugin-proposal-export-namespace-from",
      "@babel/plugin-proposal-numeric-separator",
      "@babel/plugin-proposal-throw-expressions",
      "@babel/plugin-syntax-dynamic-import",
      "@babel/plugin-syntax-import-meta",
      ["@babel/plugin-proposal-class-properties", { loose: false }],
      "@babel/plugin-proposal-json-strings"
    ]
  });
  console.log(__dirname);
  fu.createFile("./public/index.html", fu.readFile("./public/index.html"));
  fu.createFile("./public/css/style.css", fu.readFile("./public/main.css"));
  fu.createFile("webpack.config.js", fu.readFile("./app/webpack.js"));
  fu.createFile("./app/App.js", fu.readFile("./app/App.js"));
  fu.createFile(
    "./app/dispatcher/AppDispatcher.js",
    fu.readFile("./app/dispatcher/dispatcher.js")
  );
  fu.createFile(
    "./app/constants/AppConstants.js",
    fu.readFile("./app/constants/constant.js")
  );
  fu.createFile(
    "./app/components/Navi.js",
    fu.readFile("./app/components/Navi.js")
  );
  fu.createFile(
    "./app/components/Menu.js",
    fu.readFile("./app/components/Menu.js")
  );
  fu.createFile(
    "./app/components/Content.js",
    fu.readFile("./app/components/Content.js")
  );
  fu.createFile(
    "./__tests__/Content-test.js",
    fu.readFile("./__tests__/Content-test.js")
  );

  generator.StoreFile("Sample");
  generator.ActionFile("Sample");
  generator.ContainerFile("Top");
  generator.ContainerFile("Sample");
  npmInstall(npms);
}

function setupReactPlus() {
  npmInstall(npms_plus);
}

function npmInstall(npms) {
  npms.map(command => {
    console.log(command);
    exec(command, fu.puts);
  });
}
<|endoftext|>


<commit_before>/***

 This will reset the preferences that have been deprecated by Mozilla
 and used in the ghacks user.js up to and including release 57-alpha

 It is in reverse order, so feel free to remove sections that do not apply

 For instructions see:
 https://github.com/ghacksuserjs/ghacks-user.js/wiki/3.1-Bulk-Pref-Resetting-[Scratchpad]

***/

(function() {
  let ops = [
    /* deprecated */

    /* ESR52.x users can remove sections 53-57 but it is not
       crucial as your user.js will reinstate them */
    /* 57 */
    'social.whitelist',
    'social.toast-notifications.enabled',
    'social.shareDirectory',
    'social.remote-install.enabled',
    'social.directories',
    'social.share.activationPanelEnabled',
    'social.enabled',
    'media.eme.chromium-api.enabled',
    'devtools.webide.autoinstallFxdtAdapters',
    'browser.casting.enabled',
    'browser.bookmarks.showRecentlyBookmarked',
    /* 56 */
    'extensions.screenshots.system-disabled',
    'extensions.formautofill.experimental',
    /* 55 */
    'geo.security.allowinsecure',
    'browser.selfsupport.enabled',
    'browser.selfsupport.url',
    'browser.newtabpage.directory.ping',
    'browser.formfill.saveHttpsForms',
    'browser.formautofill.enabled',
    'dom.enable_user_timing',
    'dom.keyboardevent.code.enabled',
    'browser.tabs.animate',
    'browser.fullscreen.animate',
    /* 54 */
    'browser.safebrowsing.reportMalwareMistakeURL',
    'browser.safebrowsing.reportPhishMistakeURL',
    'media.eme.apiVisible',
    'dom.archivereader.enabled',
    /* 53 */
    'security.tls.unrestricted_rc4_fallback',
    'plugin.scan.Acrobat',
    'plugin.scan.Quicktime',
    'plugin.scan.WindowsMediaPlayer',
    'media.getusermedia.screensharing.allow_on_old_platforms',
    'dom.beforeAfterKeyboardEvent.enabled',
    /* End of ESR52.x section */

    /* 52 */
    'network.http.sendSecureXSiteReferrer',
    'media.gmp-eme-adobe.enabled',
    'media.gmp-eme-adobe.visible',
    'media.gmp-eme-adobe.autoupdate',
    'dom.telephony.enabled',
    'dom.battery.enabled',
    /* 51 */
    'media.block-play-until-visible',
    'dom.vr.oculus050.enabled',
    'network.http.spdy.enabled.v3-1',
    /* 50 */
    'browser.usedOnWindows10.introURL',
    'plugins.update.notifyUser',
    'browser.safebrowsing.enabled',
    'security.ssl3.ecdhe_ecdsa_rc4_128_sha',
    'security.ssl3.ecdhe_rsa_rc4_128_sha',
    'security.ssl3.rsa_rc4_128_md5',
    'security.ssl3.rsa_rc4_128_sha',
    'plugins.update.url',
    /* 49 */
    'loop.enabled',
    'loop.server',
    'loop.feedback.formURL',
    'loop.feedback.manualFormURL',
    'loop.facebook.appId',
    'loop.facebook.enabled',
    'loop.facebook.fallbackUrl',
    'loop.facebook.shareUrl',
    'loop.logDomains',
    'dom.disable_window_open_feature.scrollbars',
    'dom.push.udp.wakeupEnabled',
    /* 48 */
    'browser.urlbar.unifiedcomplete',
    /* 47 */
    'toolkit.telemetry.unifiedIsOptIn',
    'datareporting.healthreport.about.reportUrlUnified',
    'browser.history.allowPopState',
    'browser.history.allowPushState',
    'browser.history.allowReplaceState',
    /* 46 */
    'datareporting.healthreport.service.enabled',
    'datareporting.healthreport.documentServerURI',
    'datareporting.policy.dataSubmissionEnabled.v2',
    'browser.safebrowsing.appRepURL',
    'browser.polaris.enabled',
    'browser.pocket.enabled',
    'browser.pocket.api',
    'browser.pocket.site',
    'browser.pocket.oAuthConsumerKey',
    /* 45 */
    'browser.sessionstore.privacy_level_deferred',
    /* 44 */
    'browser.safebrowsing.provider.google.appRepURL',
    'security.tls.insecure_fallback_hosts.use_static_list',
    'dom.workers.sharedWorkers.enabled',
    'dom.disable_image_src_set',
    /* 43 */
    'browser.safebrowsing.gethashURL',
    'browser.safebrowsing.updateURL',
    'browser.safebrowsing.malware.reportURL',
    'browser.trackingprotection.gethashURL',
    'browser.trackingprotection.updateURL',
    'pfs.datasource.url',
    'browser.search.showOneOffButtons',
    /* 42 and earlier */
    'privacy.clearOnShutdown.passwords', // 42
    'full-screen-api.approval-required', // 42
    'browser.safebrowsing.reportErrorURL', // 41
    'browser.safebrowsing.reportGenericURL', // 41
    'browser.safebrowsing.reportMalwareErrorURL', // 41
    'browser.safebrowsing.reportMalwareURL', // 41
    'browser.safebrowsing.reportURL', // 41
    'plugins.enumerable_names', // 41
    'network.http.spdy.enabled.http2draft', // 41
    'camera.control.autofocus_moving_callback.enabled', // 37
    'privacy.donottrackheader.value', // 36
    'network.websocket.enabled', // 35
    'dom.network.enabled', // 31
    'pageThumbs.enabled', // 25

    /* reset parrot: check your open about:config after running the script */
    '_user.js.parrot'
  ]

  if("undefined" === typeof(Services)) {
    alert("about:config needs to be the active tab!");
    return;
  }

  let c = 0;
  for (let i = 0, len = ops.length; i < len; i++) {
    if (Services.prefs.prefHasUserValue(ops[i])) {
      Services.prefs.clearUserPref(ops[i]);
      if (!Services.prefs.prefHasUserValue(ops[i])) {
        console.log("reset", ops[i]);
        c++;
      } else { console.log("failed to reset", ops[i]); }
    }
  }

  focus();

  let d = (c==1) ? " pref" : " prefs";
  if (c > 0) {
    alert("successfully reset " + c + d + "\n\nfor details check the Browser Console (Ctrl+Shift+J)");
  } else { alert("nothing to reset"); }

})();
<commit_msg>url change<commit_after>/***

 This will reset the preferences that have been deprecated by Mozilla
 and used in the ghacks user.js up to and including release 57-alpha

 It is in reverse order, so feel free to remove sections that do not apply

 For instructions see:
 https://github.com/ghacksuserjs/ghacks-user.js/wiki/3.1-Resetting-Inactive-Prefs-[Scripts]

***/

(function() {
  let ops = [
    /* deprecated */

    /* ESR52.x users can remove sections 53-57 but it is not
       crucial as your user.js will reinstate them */
    /* 57 */
    'social.whitelist',
    'social.toast-notifications.enabled',
    'social.shareDirectory',
    'social.remote-install.enabled',
    'social.directories',
    'social.share.activationPanelEnabled',
    'social.enabled',
    'media.eme.chromium-api.enabled',
    'devtools.webide.autoinstallFxdtAdapters',
    'browser.casting.enabled',
    'browser.bookmarks.showRecentlyBookmarked',
    /* 56 */
    'extensions.screenshots.system-disabled',
    'extensions.formautofill.experimental',
    /* 55 */
    'geo.security.allowinsecure',
    'browser.selfsupport.enabled',
    'browser.selfsupport.url',
    'browser.newtabpage.directory.ping',
    'browser.formfill.saveHttpsForms',
    'browser.formautofill.enabled',
    'dom.enable_user_timing',
    'dom.keyboardevent.code.enabled',
    'browser.tabs.animate',
    'browser.fullscreen.animate',
    /* 54 */
    'browser.safebrowsing.reportMalwareMistakeURL',
    'browser.safebrowsing.reportPhishMistakeURL',
    'media.eme.apiVisible',
    'dom.archivereader.enabled',
    /* 53 */
    'security.tls.unrestricted_rc4_fallback',
    'plugin.scan.Acrobat',
    'plugin.scan.Quicktime',
    'plugin.scan.WindowsMediaPlayer',
    'media.getusermedia.screensharing.allow_on_old_platforms',
    'dom.beforeAfterKeyboardEvent.enabled',
    /* End of ESR52.x section */

    /* 52 */
    'network.http.sendSecureXSiteReferrer',
    'media.gmp-eme-adobe.enabled',
    'media.gmp-eme-adobe.visible',
    'media.gmp-eme-adobe.autoupdate',
    'dom.telephony.enabled',
    'dom.battery.enabled',
    /* 51 */
    'media.block-play-until-visible',
    'dom.vr.oculus050.enabled',
    'network.http.spdy.enabled.v3-1',
    /* 50 */
    'browser.usedOnWindows10.introURL',
    'plugins.update.notifyUser',
    'browser.safebrowsing.enabled',
    'security.ssl3.ecdhe_ecdsa_rc4_128_sha',
    'security.ssl3.ecdhe_rsa_rc4_128_sha',
    'security.ssl3.rsa_rc4_128_md5',
    'security.ssl3.rsa_rc4_128_sha',
    'plugins.update.url',
    /* 49 */
    'loop.enabled',
    'loop.server',
    'loop.feedback.formURL',
    'loop.feedback.manualFormURL',
    'loop.facebook.appId',
    'loop.facebook.enabled',
    'loop.facebook.fallbackUrl',
    'loop.facebook.shareUrl',
    'loop.logDomains',
    'dom.disable_window_open_feature.scrollbars',
    'dom.push.udp.wakeupEnabled',
    /* 48 */
    'browser.urlbar.unifiedcomplete',
    /* 47 */
    'toolkit.telemetry.unifiedIsOptIn',
    'datareporting.healthreport.about.reportUrlUnified',
    'browser.history.allowPopState',
    'browser.history.allowPushState',
    'browser.history.allowReplaceState',
    /* 46 */
    'datareporting.healthreport.service.enabled',
    'datareporting.healthreport.documentServerURI',
    'datareporting.policy.dataSubmissionEnabled.v2',
    'browser.safebrowsing.appRepURL',
    'browser.polaris.enabled',
    'browser.pocket.enabled',
    'browser.pocket.api',
    'browser.pocket.site',
    'browser.pocket.oAuthConsumerKey',
    /* 45 */
    'browser.sessionstore.privacy_level_deferred',
    /* 44 */
    'browser.safebrowsing.provider.google.appRepURL',
    'security.tls.insecure_fallback_hosts.use_static_list',
    'dom.workers.sharedWorkers.enabled',
    'dom.disable_image_src_set',
    /* 43 */
    'browser.safebrowsing.gethashURL',
    'browser.safebrowsing.updateURL',
    'browser.safebrowsing.malware.reportURL',
    'browser.trackingprotection.gethashURL',
    'browser.trackingprotection.updateURL',
    'pfs.datasource.url',
    'browser.search.showOneOffButtons',
    /* 42 and earlier */
    'privacy.clearOnShutdown.passwords', // 42
    'full-screen-api.approval-required', // 42
    'browser.safebrowsing.reportErrorURL', // 41
    'browser.safebrowsing.reportGenericURL', // 41
    'browser.safebrowsing.reportMalwareErrorURL', // 41
    'browser.safebrowsing.reportMalwareURL', // 41
    'browser.safebrowsing.reportURL', // 41
    'plugins.enumerable_names', // 41
    'network.http.spdy.enabled.http2draft', // 41
    'camera.control.autofocus_moving_callback.enabled', // 37
    'privacy.donottrackheader.value', // 36
    'network.websocket.enabled', // 35
    'dom.network.enabled', // 31
    'pageThumbs.enabled', // 25

    /* reset parrot: check your open about:config after running the script */
    '_user.js.parrot'
  ]

  if("undefined" === typeof(Services)) {
    alert("about:config needs to be the active tab!");
    return;
  }

  let c = 0;
  for (let i = 0, len = ops.length; i < len; i++) {
    if (Services.prefs.prefHasUserValue(ops[i])) {
      Services.prefs.clearUserPref(ops[i]);
      if (!Services.prefs.prefHasUserValue(ops[i])) {
        console.log("reset", ops[i]);
        c++;
      } else { console.log("failed to reset", ops[i]); }
    }
  }

  focus();

  let d = (c==1) ? " pref" : " prefs";
  if (c > 0) {
    alert("successfully reset " + c + d + "\n\nfor details check the Browser Console (Ctrl+Shift+J)");
  } else { alert("nothing to reset"); }

})();
<|endoftext|>


<commit_before><commit_msg>修复Firefox下不能正常填入简介的Bug<commit_after><|endoftext|>


<commit_before>export const fingeringForChord = (chord) => {
    switch (chord) {
        "G#7sus":"1324",
        "G#sus":"1344",
        "G#9":"3323",
        "G#m6":"1312",
        "G#6":"1313",
        "G#maj7":"1333",
        "G#m7":"1322",
        "G#+":"5443",
        "G#-":"1212",
        "G#m":"1342",
        "G#7":"1323",
        "G#":"5343",

        "G7sus":"0213",
        "Gsus":"0233",
        "G9":"4210",
        "Gm6":"0201",
        "G6":"0202",
        "Gmaj7":"0222",
        "Gm7":"0211",
        "G+":"0332",
        "G-":"0101",
        "Gm":"0231",
        "G7":"0212",
        "G":"0232",

        "F#7sus":"4424",
        "F#sus":"6679",
        "F#9":"3444",
        "F#m6":"2324",
        "F#6":"3324",
        "F#maj7":"2413",
        "F#m7":"2424",
        "F#+":"3221",
        "F#-":"2323",
        "F#m":"2120",
        "F#7":"3424",
        "F#":"3121",

        "F7sus":"3313",
        "Fsus":"5568",
        "F9":"2333",
        "Fm6":"1214",
        "F6":"2213",
        "Fmaj7":"2413",
        "Fm7":"1313",
        "F+":"2110",
        "F-":"1212",
        "Fm":"1013",
        "F7":"2310",
        "F":"2010",

        "E7sus":"2202",
        "Esus":"4457",
        "E9":"1222",
        "Em6":"0102",
        "E6":"4444",
        "Emaj7":"1302",
        "Em7":"0202",
        "E+":"2114",
        "E-":"0101",
        "Em":"0432",
        "E7":"1202",
        "E":"4442",

        "A-":"2323",
        "A+": "211x",
        "Am7":"xxxx",
        "Amaj7":"2444",
        "A6":"2424",
        "Am6":"2423",
        "A9":"x1x2",
        "Asus":"22xx",
        "A7sus":"x2xx",

        "A#-":"x1x1",
        "A#+":"3221",
        "A#m7":"1111",
        "A#maj7":"321x",
        "A#6":"x211",
        "A#m6":"x111",
        "A#9":"1213",
        "A#sus":"3311",
        "A#7sus":"1311",

        "B-":"1212",
        "B+":"4332",
        "Bm7":"2222",
        "Bmaj7":"3322",
        "B6":"1322",
        "Bm6":"1222",
        "B9":"2324",
        "Bsus":"4422",
        "B7sus":"2422",

        "C-":"2323",
        "C+":"1xx3",
        "Cm7":"3333",
        "Cmaj7":"xxx2",
        "C6":"xxxx",
        "Cm6":"2333",
        "C9":"x2x1",
        "Csus":"xx13",
        "C7sus":"xx11",

        "C#-":"x1x1",
        "C#+":"2114",
        "C#m7":"4444",
        "C#maj7":"1113",
        "C#6":"1111",
        "C#m6":"11x1",
        "C#9":"1312",
        "C#sus":"1124",
        "C#7sus":"1122",

        "D-":"1212",
        "D+":"3221",
        "Dm7":"2213",
        "Dmaj7":"2224",
        "D6":"2222",
        "Dm6":"2212",
        "D9":"2423",
        "Dsus":"223x",
        "D7sus":"2233",

        "D#-":"2323",
        "D#+":"4332",
        "D#m7":"3324",
        "D#maj7":"3335",
        "D#6":"3333",
        "D#m6":"3323",
        "D#9":"x111",
        "D#sus":"3346",
        "D#7sus":"3344"
        }
};<commit_msg>removed reference to case<commit_after>export const fingeringForChord = (chord) => {
        "G#7sus":"1324",
        "G#sus":"1344",
        "G#9":"3323",
        "G#m6":"1312",
        "G#6":"1313",
        "G#maj7":"1333",
        "G#m7":"1322",
        "G#+":"5443",
        "G#-":"1212",
        "G#m":"1342",
        "G#7":"1323",
        "G#":"5343",

        "G7sus":"0213",
        "Gsus":"0233",
        "G9":"4210",
        "Gm6":"0201",
        "G6":"0202",
        "Gmaj7":"0222",
        "Gm7":"0211",
        "G+":"0332",
        "G-":"0101",
        "Gm":"0231",
        "G7":"0212",
        "G":"0232",

        "F#7sus":"4424",
        "F#sus":"6679",
        "F#9":"3444",
        "F#m6":"2324",
        "F#6":"3324",
        "F#maj7":"2413",
        "F#m7":"2424",
        "F#+":"3221",
        "F#-":"2323",
        "F#m":"2120",
        "F#7":"3424",
        "F#":"3121",

        "F7sus":"3313",
        "Fsus":"5568",
        "F9":"2333",
        "Fm6":"1214",
        "F6":"2213",
        "Fmaj7":"2413",
        "Fm7":"1313",
        "F+":"2110",
        "F-":"1212",
        "Fm":"1013",
        "F7":"2310",
        "F":"2010",

        "E7sus":"2202",
        "Esus":"4457",
        "E9":"1222",
        "Em6":"0102",
        "E6":"4444",
        "Emaj7":"1302",
        "Em7":"0202",
        "E+":"2114",
        "E-":"0101",
        "Em":"0432",
        "E7":"1202",
        "E":"4442",

        "A-":"2323",
        "A+": "211x",
        "Am7":"xxxx",
        "Amaj7":"2444",
        "A6":"2424",
        "Am6":"2423",
        "A9":"x1x2",
        "Asus":"22xx",
        "A7sus":"x2xx",

        "A#-":"x1x1",
        "A#+":"3221",
        "A#m7":"1111",
        "A#maj7":"321x",
        "A#6":"x211",
        "A#m6":"x111",
        "A#9":"1213",
        "A#sus":"3311",
        "A#7sus":"1311",

        "B-":"1212",
        "B+":"4332",
        "Bm7":"2222",
        "Bmaj7":"3322",
        "B6":"1322",
        "Bm6":"1222",
        "B9":"2324",
        "Bsus":"4422",
        "B7sus":"2422",

        "C-":"2323",
        "C+":"1xx3",
        "Cm7":"3333",
        "Cmaj7":"xxx2",
        "C6":"xxxx",
        "Cm6":"2333",
        "C9":"x2x1",
        "Csus":"xx13",
        "C7sus":"xx11",

        "C#-":"x1x1",
        "C#+":"2114",
        "C#m7":"4444",
        "C#maj7":"1113",
        "C#6":"1111",
        "C#m6":"11x1",
        "C#9":"1312",
        "C#sus":"1124",
        "C#7sus":"1122",

        "D-":"1212",
        "D+":"3221",
        "Dm7":"2213",
        "Dmaj7":"2224",
        "D6":"2222",
        "Dm6":"2212",
        "D9":"2423",
        "Dsus":"223x",
        "D7sus":"2233",

        "D#-":"2323",
        "D#+":"4332",
        "D#m7":"3324",
        "D#maj7":"3335",
        "D#6":"3333",
        "D#m6":"3323",
        "D#9":"x111",
        "D#sus":"3346",
        "D#7sus":"3344"
};<|endoftext|>


<commit_before>'use strict';

describe('Users E2E Tests:', function () {
  describe('Not authenticated user', function () {
    it('Should login', function () {

      //browser.get('http://localhost:3000');
      //
      //element(by.id('username')).sendKeys('test');
      //element(by.id('password')).sendKeys('#Test123456');
      //element(by.css('button[type=submit]')).click();
      //element(by.binding('error')).getText().then(function (errorText) {
      //  expect(errorText).toBe('Invalid username or password');
      //});
    });
  });
});
<commit_msg>Test for places e2e<commit_after>'use strict';

describe('Places E2E Tests:', function () {
    describe('Places', function () {
        var startCount;

        beforeEach(function () {
            browser.get('http://localhost:3000/places');
            element.all(by.repeater('places in model.places')).count().then(function (originalCount) {
                startCount = originalCount;
            });
        });

        it('Create place', function () {
            element(by.css('button[ng-click="addEdit()"]')).click();
            element(by.id('title')).sendKeys('test');
            element(by.css('button[ng-click="save()"]')).click();

            expect(element.all(by.repeater('places in model.places')).count()).toBe(startCount + 1);
        });
    });
});
<|endoftext|>


<commit_before>'use strict';
/*!
 * TODO: Description.
 */
var dgram = require('dgram');
var util = require('util');
var debug = require('debug')('discovery:UdpBroadcast');
var Manager = require('../manager');

var Defaults = {
  DGRAM_TYPE: 'udp4',
  PORT: 44201,
  TIMEOUT: 1000,
  ANNOUNCE_INTERVAL: 3000,
  MULTICAST_ADDRESS: '224.0.0.234'
};

/**
 * Creates a new instance of UdpBroadcastManager with the provided `options`.
 *
 * The UdpBroadcastManager provides a client connection to the
 * zero-configuration, UDP-based discovery system that is used by SuperCluster
 * by default. Because it requires zero configuration to use, it's ideal for
 * initial exploration and development. However, it's not expected to work
 * at-scale, and should be replaced with the included HTTP-based version.
 *
 * For more information, see the README.
 *
 * @param {Object} options
 */
function UdpBroadcastManager(options) {
  if (!(this instanceof UdpBroadcastManager)) {
    return new UdpBroadcastManager(options);
  }

  options = options || {};

  this.dgramType = options.dgramType ? String(options.dgramType).toLowerCase() : Defaults.DGRAM_TYPE;
  this.port = options.port || Defaults.PORT;
  this.address = options.address || null;
  this.multicastAddress = options.multicastAddress || Defaults.MULTICAST_ADDRESS;

  this._initSocket();
}
util.inherits(UdpBroadcastManager, Manager);
UdpBroadcastManager.Defaults = Defaults;

/**
 * TODO: Description.
 */
UdpBroadcastManager.prototype.destroy = destroy;
function destroy() {
  var self = this;

  self.socket.close();

  return self;
}

/**
 * TODO: Description.
 */
UdpBroadcastManager.prototype.generateId = generateId;
function generateId() {
  var self = this;
  var data = self.socket.address();

  return data.address + data.port;
}

/**
 * TODO: Description.
 */
UdpBroadcastManager.prototype.addLocalService = addLocalService;
function addLocalService(service, reason) {
  var self = this;

  self._send('available', service, reason);

  return self;
}

/**
 * TODO: Description.
 */
UdpBroadcastManager.prototype.removeLocalService = removeLocalService
function removeLocalService(service, reason) {
  var self = this;

  self._send('unavailable', service, reason);

  return self;
}

/**
 * TODO: Description.
 */
UdpBroadcastManager.prototype.updateLocalService = updateLocalService;
function updateLocalService(service, reason) {
  var self = this;

  self._send('update', service, reason);

  return self;
}

/**
 * TODO: Description.
 */
UdpBroadcastManager.prototype._send = _send;
function _send(event, service, reason) {
  var self = this;
  var buf = JSON.stringify({
    event: event,
    service: service,
    reason: reason
  });

  debug('Sending: %s', buf);

  buf = new Buffer(buf);

  self.socket.send(buf, 0, buf.length, self.port, self.multicastAddress);

  return self;
}

/**
 * TODO: Description.
 */
UdpBroadcastManager.prototype._initSocket = _initSocket;
function _initSocket() {
  var self = this;

  self.socket = dgram.createSocket(self.dgramType);
  self.socket.bind(self.port, self.address);

  self.socket.on('listening', function () {
    self.socket.addMembership(self.multicastAddress);
  });
  self.socket.on('error', function (err) {
    self.emit('error', err);
  });
  self.socket.on('message', function (message) {
    message = JSON.parse(message);

    var event = message.event;
    var service = message.service;
    var reason = message.reason;

    self.emit(event, service.name, service, reason);
  });

  return self;
}

/*!
 * Export `UdpBroadcastManager`.
 */
module.exports = UdpBroadcastManager;
<commit_msg>Add delimiter to UdpBroadcastManager ID.<commit_after>'use strict';
/*!
 * TODO: Description.
 */
var dgram = require('dgram');
var util = require('util');
var debug = require('debug')('discovery:UdpBroadcast');
var Manager = require('../manager');

var Defaults = {
  DGRAM_TYPE: 'udp4',
  PORT: 44201,
  TIMEOUT: 1000,
  ANNOUNCE_INTERVAL: 3000,
  MULTICAST_ADDRESS: '224.0.0.234'
};

/**
 * Creates a new instance of UdpBroadcastManager with the provided `options`.
 *
 * The UdpBroadcastManager provides a client connection to the
 * zero-configuration, UDP-based discovery system that is used by SuperCluster
 * by default. Because it requires zero configuration to use, it's ideal for
 * initial exploration and development. However, it's not expected to work
 * at-scale, and should be replaced with the included HTTP-based version.
 *
 * For more information, see the README.
 *
 * @param {Object} options
 */
function UdpBroadcastManager(options) {
  if (!(this instanceof UdpBroadcastManager)) {
    return new UdpBroadcastManager(options);
  }

  options = options || {};

  this.dgramType = options.dgramType ? String(options.dgramType).toLowerCase() : Defaults.DGRAM_TYPE;
  this.port = options.port || Defaults.PORT;
  this.address = options.address || null;
  this.multicastAddress = options.multicastAddress || Defaults.MULTICAST_ADDRESS;

  this._initSocket();
}
util.inherits(UdpBroadcastManager, Manager);
UdpBroadcastManager.Defaults = Defaults;

/**
 * TODO: Description.
 */
UdpBroadcastManager.prototype.destroy = destroy;
function destroy() {
  var self = this;

  self.socket.close();

  return self;
}

/**
 * TODO: Description.
 */
UdpBroadcastManager.prototype.generateId = generateId;
function generateId() {
  var self = this;
  var data = self.socket.address();

  return data.address + ':' + data.port;
}

/**
 * TODO: Description.
 */
UdpBroadcastManager.prototype.addLocalService = addLocalService;
function addLocalService(service, reason) {
  var self = this;

  self._send('available', service, reason);

  return self;
}

/**
 * TODO: Description.
 */
UdpBroadcastManager.prototype.removeLocalService = removeLocalService
function removeLocalService(service, reason) {
  var self = this;

  self._send('unavailable', service, reason);

  return self;
}

/**
 * TODO: Description.
 */
UdpBroadcastManager.prototype.updateLocalService = updateLocalService;
function updateLocalService(service, reason) {
  var self = this;

  self._send('update', service, reason);

  return self;
}

/**
 * TODO: Description.
 */
UdpBroadcastManager.prototype._send = _send;
function _send(event, service, reason) {
  var self = this;
  var buf = JSON.stringify({
    event: event,
    service: service,
    reason: reason
  });

  debug('Sending: %s', buf);

  buf = new Buffer(buf);

  self.socket.send(buf, 0, buf.length, self.port, self.multicastAddress);

  return self;
}

/**
 * TODO: Description.
 */
UdpBroadcastManager.prototype._initSocket = _initSocket;
function _initSocket() {
  var self = this;

  self.socket = dgram.createSocket(self.dgramType);
  self.socket.bind(self.port, self.address);

  self.socket.on('listening', function () {
    self.socket.addMembership(self.multicastAddress);
  });
  self.socket.on('error', function (err) {
    self.emit('error', err);
  });
  self.socket.on('message', function (message) {
    message = JSON.parse(message);

    var event = message.event;
    var service = message.service;
    var reason = message.reason;

    self.emit(event, service.name, service, reason);
  });

  return self;
}

/*!
 * Export `UdpBroadcastManager`.
 */
module.exports = UdpBroadcastManager;
<|endoftext|>


<commit_before>import undoable from 'redux-undo'
import omit from 'lodash/object/omit'

import {
	changeStudentName,
	changeStudentAdvisor,
	changeStudentCreditsNeeded,
	changeStudentMatriculation,
	changeStudentGraduation,
	changeStudentSetting,
	addAreaToStudent,
	removeAreaFromStudent,
	addScheduleToStudent,
	destroyScheduleFromStudent,
	moveCourseAcrossSchedules,
	setOverrideOnStudent,
	removeOverrideFromStudent,
	addFabricationToStudent,
	removeFabricationFromStudent,
	renameScheduleInStudent,
	reorderScheduleInStudent,
	moveScheduleInStudent,
	addCourseToSchedule,
	removeCourseFromSchedule,
	reorderCourseInSchedule,
} from '../../models/student'

import {
	INIT_STUDENT,
	IMPORT_STUDENT,
	DESTROY_STUDENT,
	CHANGE_NAME,
	CHANGE_ADVISOR,
	CHANGE_CREDITS_NEEDED,
	CHANGE_MATRICULATION,
	CHANGE_GRADUATION,
	CHANGE_SETTING,
	ADD_AREA,
	REMOVE_AREA,
	REMOVE_AREAS,
	ADD_SCHEDULE,
	DESTROY_SCHEDULE,
	DESTROY_SCHEDULES,
	RENAME_SCHEDULE,
	REORDER_SCHEDULE,
	MOVE_SCHEDULE,
	ADD_COURSE,
	REMOVE_COURSE,
	REORDER_COURSE,
	MOVE_COURSE,
	SET_OVERRIDE,
	REMOVE_OVERRIDE,
	ADD_FABRICATION,
	REMOVE_FABRICATION,
} from '../constants/students'

const initialState = {}

function reducer(state = initialState, action) {
	const {type, payload} = action

	switch (type) {
		case INIT_STUDENT:
		case IMPORT_STUDENT: {
			if (payload.error) {
				return state
			}
			return {...state, [payload.id]: payload}
		}

		case DESTROY_STUDENT: {
			return omit(state, [payload.studentId])
		}

		case CHANGE_NAME: {
			const student = changeStudentName(state[payload.studentId], payload.name)
			return {...state, [student.id]: student}
		}
		case CHANGE_ADVISOR: {
			const student = changeStudentAdvisor(state[payload.studentId], payload.advisor)
			return {...state, [student.id]: student}
		}
		case CHANGE_CREDITS_NEEDED: {
			const student = changeStudentCreditsNeeded(state[payload.studentId], payload.credits)
			return {...state, [student.id]: student}
		}
		case CHANGE_MATRICULATION: {
			const student = changeStudentMatriculation(state[payload.studentId], payload.matriculation)
			return {...state, [student.id]: student}
		}
		case CHANGE_GRADUATION: {
			const student = changeStudentGraduation(state[payload.studentId], payload.graduation)
			return {...state, [student.id]: student}
		}
		case CHANGE_SETTING: {
			const student = changeStudentSetting(state[payload.studentId], payload.key, payload.value)
			return {...state, [student.id]: student}
		}

		case ADD_AREA: {
			const student = addAreaToStudent(state[payload.studentId], payload.area)
			return {...state, [student.id]: student}
		}
		case REMOVE_AREA: {
			const student = removeAreaFromStudent(state[payload.studentId], payload.areaId)
			return {...state, [student.id]: student}
		}
		case REMOVE_AREAS: {
			let student = {...state[payload.studentId]}
			for (const areaId of payload.areaIds) {
				student = removeAreaFromStudent(student, areaId)
			}
			return {...state, [student.id]: student}
		}

		case ADD_SCHEDULE: {
			const student = addScheduleToStudent(state[payload.studentId], payload.schedule)
			return {...state, [student.id]: student}
		}
		case DESTROY_SCHEDULE: {
			const student = destroyScheduleFromStudent(state[payload.studentId], payload.scheduleId)
			return {...state, [student.id]: student}
		}
		case DESTROY_SCHEDULES: {
			let student = state[payload.studentId]
			for (const id of payload.scheduleIds) {
				student = destroyScheduleFromStudent(student, id)
			}
			return {...state, [student.id]: student}
		}
		case RENAME_SCHEDULE: {
			const student = renameScheduleInStudent(state[payload.studentId], payload.scheduleId, payload.newTitle)
			return {...state, [student.id]: student}
		}
		case REORDER_SCHEDULE: {
			const student = reorderScheduleInStudent(state[payload.studentId], payload.scheduleId, payload.newIndex)
			return {...state, [student.id]: student}
		}
		case MOVE_SCHEDULE: {
			const student = moveScheduleInStudent(state[payload.studentId], payload.scheduleId, {year: payload.year, semester: payload.semester})
			return {...state, [student.id]: student}
		}

		case ADD_COURSE: {
			const student = addCourseToSchedule(state[payload.studentId], payload.scheduleId, payload.clbid)
			return {...state, [student.id]: student}
		}
		case REMOVE_COURSE: {
			const student = removeCourseFromSchedule(state[payload.studentId], payload.scheduleId, payload.clbid)
			return {...state, [student.id]: student}
		}
		case REORDER_COURSE: {
			const student = reorderCourseInSchedule(state[payload.studentId], payload.scheduleId, {clbid: payload.clbid, index: payload.index})
			return {...state, [student.id]: student}
		}
		case MOVE_COURSE: {
			const student = moveCourseAcrossSchedules(state[payload.studentId], payload.scheduleId, {fromScheduleId: payload.fromScheduleId, toScheduleId: payload.toScheduleId, clbid: payload.clbid})
			return {...state, [student.id]: student}
		}

		case SET_OVERRIDE: {
			const student = setOverrideOnStudent(state[payload.studentId], payload.key, payload.value)
			return {...state, [student.id]: student}
		}
		case REMOVE_OVERRIDE: {
			const student = removeOverrideFromStudent(state[payload.studentId], payload.override)
			return {...state, [student.id]: student}
		}
		case ADD_FABRICATION: {
			const student = addFabricationToStudent(state[payload.studentId], payload.fabrication)
			return {...state, [student.id]: student}
		}
		case REMOVE_FABRICATION: {
			const student = removeFabricationFromStudent(state[payload.studentId], payload.fabricationId)
			return {...state, [student.id]: student}
		}

		default: {
			return state
		}
	}
}

export default undoable(reducer, {
	limit: 10,

	initialState: initialState,
})
<commit_msg>export the plain students reducer for testing<commit_after>import undoable from 'redux-undo'
import omit from 'lodash/object/omit'

import {
	changeStudentName,
	changeStudentAdvisor,
	changeStudentCreditsNeeded,
	changeStudentMatriculation,
	changeStudentGraduation,
	changeStudentSetting,
	addAreaToStudent,
	removeAreaFromStudent,
	addScheduleToStudent,
	destroyScheduleFromStudent,
	moveCourseAcrossSchedules,
	setOverrideOnStudent,
	removeOverrideFromStudent,
	addFabricationToStudent,
	removeFabricationFromStudent,
	renameScheduleInStudent,
	reorderScheduleInStudent,
	moveScheduleInStudent,
	addCourseToSchedule,
	removeCourseFromSchedule,
	reorderCourseInSchedule,
} from '../../models/student'

import {
	INIT_STUDENT,
	IMPORT_STUDENT,
	DESTROY_STUDENT,
	CHANGE_NAME,
	CHANGE_ADVISOR,
	CHANGE_CREDITS_NEEDED,
	CHANGE_MATRICULATION,
	CHANGE_GRADUATION,
	CHANGE_SETTING,
	ADD_AREA,
	REMOVE_AREA,
	REMOVE_AREAS,
	ADD_SCHEDULE,
	DESTROY_SCHEDULE,
	DESTROY_SCHEDULES,
	RENAME_SCHEDULE,
	REORDER_SCHEDULE,
	MOVE_SCHEDULE,
	ADD_COURSE,
	REMOVE_COURSE,
	REORDER_COURSE,
	MOVE_COURSE,
	SET_OVERRIDE,
	REMOVE_OVERRIDE,
	ADD_FABRICATION,
	REMOVE_FABRICATION,
} from '../constants/students'

const initialState = {}

export function reducer(state = initialState, action) {
	const {type, payload} = action

	switch (type) {
		case INIT_STUDENT:
		case IMPORT_STUDENT: {
			if (payload.error) {
				return state
			}
			return {...state, [payload.id]: payload}
		}

		case DESTROY_STUDENT: {
			return omit(state, [payload.studentId])
		}

		case CHANGE_NAME: {
			const student = changeStudentName(state[payload.studentId], payload.name)
			return {...state, [student.id]: student}
		}
		case CHANGE_ADVISOR: {
			const student = changeStudentAdvisor(state[payload.studentId], payload.advisor)
			return {...state, [student.id]: student}
		}
		case CHANGE_CREDITS_NEEDED: {
			const student = changeStudentCreditsNeeded(state[payload.studentId], payload.credits)
			return {...state, [student.id]: student}
		}
		case CHANGE_MATRICULATION: {
			const student = changeStudentMatriculation(state[payload.studentId], payload.matriculation)
			return {...state, [student.id]: student}
		}
		case CHANGE_GRADUATION: {
			const student = changeStudentGraduation(state[payload.studentId], payload.graduation)
			return {...state, [student.id]: student}
		}
		case CHANGE_SETTING: {
			const student = changeStudentSetting(state[payload.studentId], payload.key, payload.value)
			return {...state, [student.id]: student}
		}

		case ADD_AREA: {
			const student = addAreaToStudent(state[payload.studentId], payload.area)
			return {...state, [student.id]: student}
		}
		case REMOVE_AREA: {
			const student = removeAreaFromStudent(state[payload.studentId], payload.areaId)
			return {...state, [student.id]: student}
		}
		case REMOVE_AREAS: {
			let student = {...state[payload.studentId]}
			for (const areaId of payload.areaIds) {
				student = removeAreaFromStudent(student, areaId)
			}
			return {...state, [student.id]: student}
		}

		case ADD_SCHEDULE: {
			const student = addScheduleToStudent(state[payload.studentId], payload.schedule)
			return {...state, [student.id]: student}
		}
		case DESTROY_SCHEDULE: {
			const student = destroyScheduleFromStudent(state[payload.studentId], payload.scheduleId)
			return {...state, [student.id]: student}
		}
		case DESTROY_SCHEDULES: {
			let student = state[payload.studentId]
			for (const id of payload.scheduleIds) {
				student = destroyScheduleFromStudent(student, id)
			}
			return {...state, [student.id]: student}
		}
		case RENAME_SCHEDULE: {
			const student = renameScheduleInStudent(state[payload.studentId], payload.scheduleId, payload.newTitle)
			return {...state, [student.id]: student}
		}
		case REORDER_SCHEDULE: {
			const student = reorderScheduleInStudent(state[payload.studentId], payload.scheduleId, payload.newIndex)
			return {...state, [student.id]: student}
		}
		case MOVE_SCHEDULE: {
			const student = moveScheduleInStudent(state[payload.studentId], payload.scheduleId, {year: payload.year, semester: payload.semester})
			return {...state, [student.id]: student}
		}

		case ADD_COURSE: {
			const student = addCourseToSchedule(state[payload.studentId], payload.scheduleId, payload.clbid)
			return {...state, [student.id]: student}
		}
		case REMOVE_COURSE: {
			const student = removeCourseFromSchedule(state[payload.studentId], payload.scheduleId, payload.clbid)
			return {...state, [student.id]: student}
		}
		case REORDER_COURSE: {
			const student = reorderCourseInSchedule(state[payload.studentId], payload.scheduleId, {clbid: payload.clbid, index: payload.index})
			return {...state, [student.id]: student}
		}
		case MOVE_COURSE: {
			const student = moveCourseAcrossSchedules(state[payload.studentId], payload.scheduleId, {fromScheduleId: payload.fromScheduleId, toScheduleId: payload.toScheduleId, clbid: payload.clbid})
			return {...state, [student.id]: student}
		}

		case SET_OVERRIDE: {
			const student = setOverrideOnStudent(state[payload.studentId], payload.key, payload.value)
			return {...state, [student.id]: student}
		}
		case REMOVE_OVERRIDE: {
			const student = removeOverrideFromStudent(state[payload.studentId], payload.override)
			return {...state, [student.id]: student}
		}
		case ADD_FABRICATION: {
			const student = addFabricationToStudent(state[payload.studentId], payload.fabrication)
			return {...state, [student.id]: student}
		}
		case REMOVE_FABRICATION: {
			const student = removeFabricationFromStudent(state[payload.studentId], payload.fabricationId)
			return {...state, [student.id]: student}
		}

		default: {
			return state
		}
	}
}

export default undoable(reducer, {
	limit: 10,

	initialState: initialState,
})
<|endoftext|>


<commit_before>var async = require('../lib');
var expect = require('chai').expect;

describe('autoInject', function () {

    it("basics", function (done) {
        var callOrder = [];
        async.autoInject({
            task1: function(task2, callback){
                expect(task2).to.equal(2);
                setTimeout(function(){
                    callOrder.push('task1');
                    callback(null, 1);
                }, 25);
            },
            task2: function(callback){
                setTimeout(function(){
                    callOrder.push('task2');
                    callback(null, 2);
                }, 50);
            },
            task3: function(task2, callback){
                expect(task2).to.equal(2);
                callOrder.push('task3');
                callback(null, 3);
            },
            task4: function(task1, task2, callback){
                expect(task1).to.equal(1);
                expect(task2).to.equal(2);
                callOrder.push('task4');
                callback(null, 4);
            },
            task5: function(task2, callback){
                expect(task2).to.equal(2);
                setTimeout(function(){
                    callOrder.push('task5');
                    callback(null, 5);
                }, 0);
            },
            task6: function(task2, callback){
                expect(task2).to.equal(2);
                callOrder.push('task6');
                callback(null, 6);
            }
        },
        function(err, results){
            expect(results.task6).to.equal(6);
            expect(callOrder).to.eql(['task2','task3','task6','task5','task1','task4']);
            done();
        });
    });

    it('should work with array tasks', function (done) {
        var callOrder = [];

        async.autoInject({
            task1: function (cb) {
                callOrder.push('task1');
                cb(null, 1);
            },
            task2: ['task3', function ( task3 , cb ) {
                expect(task3).to.equal(3);
                callOrder.push('task2');
                cb(null, 2);
            }],
            task3: function (cb) {
                callOrder.push('task3');
                cb(null, 3);
            }
        }, function () {
            expect(callOrder).to.eql(['task1','task3','task2']);
            done();
        });
    });

    it('should handle array tasks with just a function', function (done) {
        async.autoInject({
            a: [function (cb) {
                cb(null, 1);
            }],
            b: ["a", function (a, cb) {
                expect(a).to.equal(1);
                cb();
            }]
        }, done);
    });

    var arrowSupport = true;
    try {
        new Function('x => x');
    } catch (e) {
        arrowSupport = false;
    }

    if (arrowSupport) {
        // Needs to be run on ES6 only

        /* eslint {no-eval: 0}*/
        eval("(function() {                                                 " +
             "    it('should work with es6 arrow syntax', function (done) { " +
             "        async.autoInject({                                    " +
             "            task1: (cb)           => cb(null, 1),             " +
             "            task2: ( task3 , cb ) => cb(null, 2),             " +
             "            task3: cb             => cb(null, 3)              " +
             "        }, (err, results) => {                                " +
             "            expect(results.task1).to.equal(1);                " +
             "            expect(results.task3).to.equal(3);                " +
             "            done();                                           " +
             "        });                                                   " +
             "    });                                                       " +
             "})                                                            "
        )();

        /* eslint {no-eval: 0}*/
        eval("(function() {                                                 " +
             "    it('should work with es6 obj method syntax', function (done) { " +
             "        async.autoInject({                                    " +
             "            task1 (cb){             cb(null, 1) },            " +
             "            task2 ( task3 , cb ) {  cb(null, 2) },            " +
             "            task3 (cb) {            cb(null, 3) },            " +
             "            task4 ( task2 , cb ) {  cb(null) },               " +
             "            task5 ( task4 = 4 , cb ) { cb(null, task4 + 1) }  " +
             "        }, (err, results) => {                                " +
             "            expect(results.task1).to.equal(1);                " +
             "            expect(results.task3).to.equal(3);                " +
             "            expect(results.task4).to.equal(undefined);        " +
             "            expect(results.task5).to.equal(5);                " +
             "            done();                                           " +
             "        });                                                   " +
             "    });                                                       " +
             "})                                                            "
        )();
    }
});
<commit_msg>Fix test to pass NodeJs 4<commit_after>var async = require('../lib');
var expect = require('chai').expect;

describe('autoInject', function () {

    it("basics", function (done) {
        var callOrder = [];
        async.autoInject({
            task1: function(task2, callback){
                expect(task2).to.equal(2);
                setTimeout(function(){
                    callOrder.push('task1');
                    callback(null, 1);
                }, 25);
            },
            task2: function(callback){
                setTimeout(function(){
                    callOrder.push('task2');
                    callback(null, 2);
                }, 50);
            },
            task3: function(task2, callback){
                expect(task2).to.equal(2);
                callOrder.push('task3');
                callback(null, 3);
            },
            task4: function(task1, task2, callback){
                expect(task1).to.equal(1);
                expect(task2).to.equal(2);
                callOrder.push('task4');
                callback(null, 4);
            },
            task5: function(task2, callback){
                expect(task2).to.equal(2);
                setTimeout(function(){
                    callOrder.push('task5');
                    callback(null, 5);
                }, 0);
            },
            task6: function(task2, callback){
                expect(task2).to.equal(2);
                callOrder.push('task6');
                callback(null, 6);
            }
        },
        function(err, results){
            expect(results.task6).to.equal(6);
            expect(callOrder).to.eql(['task2','task3','task6','task5','task1','task4']);
            done();
        });
    });

    it('should work with array tasks', function (done) {
        var callOrder = [];

        async.autoInject({
            task1: function (cb) {
                callOrder.push('task1');
                cb(null, 1);
            },
            task2: ['task3', function ( task3 , cb ) {
                expect(task3).to.equal(3);
                callOrder.push('task2');
                cb(null, 2);
            }],
            task3: function (cb) {
                callOrder.push('task3');
                cb(null, 3);
            }
        }, function () {
            expect(callOrder).to.eql(['task1','task3','task2']);
            done();
        });
    });

    it('should handle array tasks with just a function', function (done) {
        async.autoInject({
            a: [function (cb) {
                cb(null, 1);
            }],
            b: ["a", function (a, cb) {
                expect(a).to.equal(1);
                cb();
            }]
        }, done);
    });

    var arrowSupport = true;
    try {
        new Function('x => x');
    } catch (e) {
        arrowSupport = false;
    }

    if (arrowSupport) {
        // Needs to be run on ES6 only

        /* eslint {no-eval: 0}*/
        eval("(function() {                                                 " +
             "    it('should work with es6 arrow syntax', function (done) { " +
             "        async.autoInject({                                    " +
             "            task1: (cb)           => cb(null, 1),             " +
             "            task2: ( task3 , cb ) => cb(null, 2),             " +
             "            task3: cb             => cb(null, 3)              " +
             "        }, (err, results) => {                                " +
             "            expect(results.task1).to.equal(1);                " +
             "            expect(results.task3).to.equal(3);                " +
             "            done();                                           " +
             "        });                                                   " +
             "    });                                                       " +
             "})                                                            "
        )();
    }

    var defaultSupport = true;
    try {
        eval('function x(y = 1){ return y }');
    }catch (e){
        defaultSupport = false;
    }

    if(arrowSupport && defaultSupport){
        // Needs to be run on ES6 only

        /* eslint {no-eval: 0}*/
        eval("(function() {                                                 " +
             "    it('should work with es6 obj method syntax', function (done) { " +
             "        async.autoInject({                                    " +
             "            task1 (cb){             cb(null, 1) },            " +
             "            task2 ( task3 , cb ) {  cb(null, 2) },            " +
             "            task3 (cb) {            cb(null, 3) },            " +
             "            task4 ( task2 , cb ) {  cb(null) },               " +
             "            task5 ( task4 = 4 , cb ) { cb(null, task4 + 1) }  " +
             "        }, (err, results) => {                                " +
             "            expect(results.task1).to.equal(1);                " +
             "            expect(results.task3).to.equal(3);                " +
             "            expect(results.task4).to.equal(undefined);        " +
             "            expect(results.task5).to.equal(5);                " +
             "            done();                                           " +
             "        });                                                   " +
             "    });                                                       " +
             "})                                                            "
        )();
    }
});
<|endoftext|>


<commit_before>// Entry point for map webapp
//
// NOTE: Modules that are not compatible with asynchronous module loading
// (AMD) are included in the webapp's HTML file to prevent issues.
require([
    "models/map", "models/legend", "dojo/mouse", "dojo/on", "dojo/dom",
    "dojo/json", "esri/dijit/Geocoder", "esri/layers/KMLLayer","esri/dijit/BasemapGallery",
    "esri/arcgis/utils","dojo/parser","dojo/dom-style", "cmwapi-adapter/cmwapi-adapter",
    "dojo/domReady!"],
    function(Map, Legend, Mouse, On, Dom, JSON, Geocoder, KMLLayer, BasemapGallery, arcgisUtils, parser, domStyle, cmwapiAdapter) {
        var map = new Map("map", {
            center: [-76.809469, 39.168101],
            zoom: 7,
            basemap: "streets"
        });
    if (OWF.Util.isRunningInOWF()) {

        OWF.ready(function () {
            OWF.notifyWidgetReady();

            var dropZone = Dom.byId("map");

            geocoder = new Geocoder({
                map: map
            }, "search");
            geocoder.startup();

            var basemapGallery = new BasemapGallery({
                showArcGISBasemaps: true,
                map: map
            }, "basemapGallery");
            basemapGallery.startup();

            basemapGallery.on("error", function(msg) {
                console.log("basemap gallery error:  ", msg);
            });

           var adapter = new cmwapiAdapter(map);

            $('#tooltip-x-button').on('click', function() {
                $('#no-overlay-tooltip').hide();
            });
            $('#overlay').on('click', function() {
                toggleOverlayManager();
            });

            $('#basemaps').on('click', function() {
                toggleBaseMaps();
            });
            $('#overlay-add-icon').on('click', function() {
                setStateAdd();
            });
            $('#overlay-delete-icon').on('click', function() {
                setStateRemove();
            });
            $('#overlay-back-icon').on('click', function() {
                setStateInit();
            });
            $('#overlay-manager-add-button').on('click', function() {
                var featureName = $('#feature-add-name').val();
                var featureId = $('#feature-add-id').val();
                var featureUrl = $('#feature-add-url').val();
                var featureParams = $('#feature-add-params').val();
                var overlayName = $('#overlay-add-name').val();
                var overlayId = $('#overlay-add-id').val();
                if($('#overlay-selection').val() == 'Add New Overlay') {
                    adapter.overlayManager.sendOverlayCreate(overlayId, overlayName);
                    adapter.overlayManager.sendFeaturePlotUrl(overlayId, featureId, featureName,
                        'kml', featureUrl, featureParams);
                } else if('Default Overlay') {
                    adapter.overlayManager.sendOverlayCreate('default-overlay-id', 'Default Overlay');
                    adapter.overlayManager.sendFeaturePlotUrl('default-overlay-id',
                        featureId, featureName,'kml', featureUrl, featureParams);
                }
                else {
                    adapter.overlayManager.sendFeaturePlotUrl($('#overlay-selection').find(":selected").attr('id'),
                        featureId, featureName,'kml', featureUrl, featureParams);
                }
                setStateInit();
            });

            $('#overlay-manager-delete-button').on('click', function() {
                $("#overlay-tree input:checkbox:checked").each(function(index) {
                    if($(this).attr('node-type') === 'overlay') {
                        adapter.overlayManager.sendOverlayRemove($(this).attr('id'));
                    }
                    if($(this).attr('node-type') === 'feature') {
                        var node = $('#overlay-tree').tree('getNodeById', $(this).attr('id'));
                        adapter.overlayManager.sendFeatureUnplot(node.parent.id,$(this).attr('id'));
                    }

                });

            });

            $('#overlay-selection').on('change', function() {
                if(this.value === 'Add New Overlay') {
                    $('#add-overlay-div').show();
                } else {
                    $('#add-overlay-div').hide();
                }
                resizeOverlayManager();
                checkAddFormCompleted();
            });

            var resizeOverlayManager = function() {
                var height = $('#overlay-manager-add').height() + 100;
                $('#popover_overlay_wrapper').css('height', height + 'px');
            }
            var checkInvalidUrl = function() {
                return $('#feature-add-url').parent().hasClass('has-error');
            }

            var updateOverlaySelection = function() {
                $('#overlay-selection > option').remove();
                var defaultHtml = '<option id= "default-overlay-id">Default Overlay</option>';
                $('#overlay-selection').append(defaultHtml);
                var overlayObject = adapter.overlayManager.getOverlays();
                for(var key in overlayObject) {
                    if(!(overlayObject[key].id == 'default-overlay-id')) {
                        var appendHtml = ' <option id= "'+ overlayObject[key].id +'">' + overlayObject[key].name + '</option>'
                        $('#overlay-selection').append(appendHtml);
                    }
                }
                var defaultHtmlAdd = '<option id= "add-new-overlay-option">Add New Overlay</option>'
                $('#overlay-selection').append(defaultHtmlAdd);
                $('#overlay-selection').val('Default Overlay');
            }

            var isOverlayTreeEmpty = function() {
                return adapter.overlayManager.getOverlayTree().length === 0;
            };
            $('form').find('.form-control.default').keyup(function() {
                checkAddFormCompleted();
            });
            $('#feature-add-url').keyup(function() {
                if(!isValidUrl($(this).val())) {
                    $(this).parent().removeClass('has-success');
                    $(this).parent().addClass('has-error');
                    $('.help-block').show();
                } else {
                    $(this).parent().removeClass('has-error');
                    $(this).parent().addClass('has-success');
                    $(this).removeClass('has-error');
                    $('.help-block').hide();
                }
                resizeOverlayManager();
            });

            var isValidUrl = function(url){
                  return /\b(https?|ftp|file):\/\/[\-A-Za-z0-9+&@#\/%?=~_|!:,.;]*[\-A-Za-z0-9+&@#\/%=~_|]/.test(url);
            }

            var checkAddFormCompleted = function() {
                var emptyInputs = $('.form-control.default').filter(function() {
                    return $(this).val() === '' && $(this).is(':visible');
                }).length;
                if(emptyInputs === 0) {
                    $('#overlay-manager-add-button').removeClass('disabled');
                } else {
                    $('#overlay-manager-add-button').addClass('disabled');
                }
            };

            $("[rel=tooltip]").tooltip({ placement: 'bottom'});

            var data = adapter.overlayManager.getOverlayTree();
            var $tree = $('#overlay-tree');
            $tree.tree({
                data: data,
                dragAndDrop:true,
                autoOpen: 1,
                onCreateLi: function(node, $li) {
                    node['node-type'] = node.type;
                    var image = 'http://www.graphicsfuel.com/wp-content/uploads/2012/03/folder-icon-512x512.png';
                    if(node.type === 'overlay') {
                        image = 'http://www.graphicsfuel.com/wp-content/uploads/2012/03/folder-icon-512x512.png';
                    } else {
                        image = 'http://img0056.popscreencdn.com/103222765_watchmen-smiley-1-pin-button-badge-magnet-moore-gibbons-.jpg';
                    }
                    $li.find('.jqtree-title').before(
                        '<input type="checkbox" id="' + node.id+ '" class ="tree-node" node-type="' + node.type + '" isHidden="' + node.isHidden + '"/>' +
                        '<img src=' + image + ' alt="Overlay Icon" height="25" width="25">'
                    );
                }
            });
        $tree.bind('tree.dblclick',
            function(event) {
                console.log(event.node);
            }
        );
            var clearAddInputs = function() {
                $('#feature-add-name').val('');
                $('#feature-add-id').val('');
                $('#feature-add-url').val('');
                $('#feature-add-params').val('');
                $('#overlay-add-name').val('');
                $('#overlay-add-id').val('');
            };

            /**
            * Whenever either the trees parent nodes are clicked the children nodes are also checked
            * respectively.
            **/
            var bindSelectionHandlers = function() {
                $("#overlay-tree.default input:checkbox").off('change');
                $("#overlay-tree.default input:checkbox").on('change', function () {
                    var node = $('#overlay-tree').tree('getNodeById', $(this).attr('id'));
                    $(this).parent().next('ul').find('input:checkbox').prop('checked', $(this).prop("checked"));
                    if($(this).is(':checked') && $(this).attr('node-type') === 'overlay') {
                        adapter.overlayManager.sendOverlayShow($(this).attr('id'));
                    } else if(!($(this).is(':checked')) && $(this).attr('node-type') === 'overlay') {
                        adapter.overlayManager.sendOverlayHide($(this).attr('id'));
                    } else if($(this).is(':checked') && $(this).attr('node-type') === 'feature') {
                        adapter.overlayManager.sendFeatureShow(node.parent.id, $(this).attr('id'))
                    } else if(!($(this).is(':checked')) && $(this).attr('node-type') === 'feature') {
                        adapter.overlayManager.sendFeatureHide(node.parent.id, $(this).attr('id'))
                    }
                    $(this).prop('checked');
                });
                $("#overlay-tree.remove input:checkbox").on('change', function () {
                    $(this).parent().next('ul').find('input:checkbox').prop('checked', $(this).prop("checked"));
                });
            }

            /**
            * Method used by the button binded to the basemaps icon.
            * Toggles the basemaps popover open/close.
            * If the overlay manager popover is already open then close it.
            **/
            var toggleBaseMaps = function() {
                $('#popover_content_wrapper').toggle();
                $('#overlay').removeClass('selected');
                $('#popover_overlay_wrapper').hide();
                $('#basemaps').toggleClass('selected');
            }

            /**
            * Method used by the button binded to the overlay manager icon.
            * Toggles the overlay manager open/close.
            * If the basemap popover is already open then close it.
            * Resize the window to the correct size given the tree.
            **/
            var toggleOverlayManager = function() {
                $('#popover_overlay_wrapper').toggle();
                $('#basemaps').removeClass('selected');
                $('#popover_content_wrapper').hide();
                $('#overlay').toggleClass('selected');
                setStateInit()
            }

            /**
            * This function is used to automatically adjust the size of the window to the size of the tree plus
            * a given specified offset/padding.
            **/
            var resizeOverlayToTree = function(tree, offset) {
                var treeHeight = $(tree).css('height');
                treeHeight = parseInt(treeHeight.substr(0, treeHeight.length-2));
                $('#popover_overlay_wrapper').css('height', (treeHeight + offset) + 'px');
            }

            /**
            * This function is called each time the tree needs to be updated, the updating is handled through
            * jquery tree.
            **/
            var updateTreeData = function() {
                $('#overlay-tree').tree('loadData',adapter.overlayManager.getOverlayTree());
                resizeOverlayToTree('#overlay-tree', 90);
                if(!isOverlayTreeEmpty()) {
                    $('#no-overlay-tooltip').hide();
                } else {
                    $('#no-overlay-tooltip').show();
                }
                updateCheckBoxes();
                bindSelectionHandlers();
                setStateInit();
            }
            adapter.overlayManager.bindTreeChangeHandler(updateTreeData);

            var updateCheckBoxes = function() {
                $("#overlay-tree.default input:checkbox").each(function(index) {
                    if(($(this).attr('ishidden') == 'false')) {
                        $(this).attr('checked', 'checked');
                    }
                });
            }

            var setStateInit = function() {
                $('#overlay-delete-icon').removeClass('disabled');
                $('#no-overlay-tooltip').hide();
                if(isOverlayTreeEmpty()) {
                    $('#no-overlay-tooltip').show();
                    $('#overlay-delete-icon').addClass('disabled');
                }
                $('#overlay-manager-add-button').hide();
                $('#overlay-manager-delete-button').hide();
                $('#overlay-manager-add').hide();
                $('#overlay-manager-delete').hide();
                $('#overlay-back-icon').hide();
                $('#overlay-add-icon').show();
                $('#overlay-delete-icon').show();
                $('#overlay-tree').show();
                $('#overlay-tree').addClass('default');
                $('#overlay-tree').removeClass('remove');
                $('#overlay-tree').css('top','50px');
                $('.help-block').hide();
                $('#feature-add-url').parent().removeClass('has-success');
                $('#feature-add-url').parent().removeClass('has-error');
                updateCheckBoxes();
                bindSelectionHandlers();
                resizeOverlayToTree('#overlay-tree', 90);
            }
            var setStateAdd = function() {
                $('#no-overlay-tooltip').hide();
                clearAddInputs();
                $('#overlay-add-icon').hide();
                $('#overlay-delete-icon').hide();
                $('#overlay-manager-delete-button').hide();
                $('#add-overlay-div').hide();
                $('#overlay-manager-delete').hide();
                $('#overlay-tree').hide();
                $('#overlay-back-icon').show();
                $('#overlay-manager-add').show();
                $('#overlay-manager-add-button').show();
                $('#overlay-manager').show();
                $('#overlay-manager-subtitle').show();
                checkAddFormCompleted();
                updateOverlaySelection();
                resizeOverlayManager();
            }
            var setStateRemove = function() {
                $('#no-overlay-tooltip').hide();
                $('#overlay-add-icon').hide();
                $('#overlay-delete-icon').hide();
                $('#add-overlay-div').hide();
                $('#overlay-manager-add-button').hide();
                $('#overlay-manager-add').hide();
                $('#overlay-manager-delete').show();
                $('#overlay-manager').show();
                $('#overlay-manager-delete-button').show();
                $('#delete-feature-subtitle').show();
                $('#overlay-back-icon').show();
                $('#overlay-tree').show();
                $("#overlay-tree.default input:checkbox").off('change');
                $('#overlay-tree').removeClass('default');
                $('#overlay-tree').addClass('remove');
                $("#overlay-tree.remove input:checkbox").removeAttr('checked');
                bindSelectionHandlers();
                updateOverlaySelection();
                $('#overlay-tree').css('top','85px');
                resizeOverlayToTree('#overlay-tree', 125);
            }
        });
    }
    });<commit_msg>Fixed bug where you could not add a feature to an existing overlay.<commit_after>// Entry point for map webapp
//
// NOTE: Modules that are not compatible with asynchronous module loading
// (AMD) are included in the webapp's HTML file to prevent issues.
require([
    "models/map", "models/legend", "dojo/mouse", "dojo/on", "dojo/dom",
    "dojo/json", "esri/dijit/Geocoder", "esri/layers/KMLLayer","esri/dijit/BasemapGallery",
    "esri/arcgis/utils","dojo/parser","dojo/dom-style", "cmwapi-adapter/cmwapi-adapter",
    "dojo/domReady!"],
    function(Map, Legend, Mouse, On, Dom, JSON, Geocoder, KMLLayer, BasemapGallery, arcgisUtils, parser, domStyle, cmwapiAdapter) {
        var map = new Map("map", {
            center: [-76.809469, 39.168101],
            zoom: 7,
            basemap: "streets"
        });
    if (OWF.Util.isRunningInOWF()) {

        OWF.ready(function () {
            OWF.notifyWidgetReady();

            var dropZone = Dom.byId("map");

            geocoder = new Geocoder({
                map: map
            }, "search");
            geocoder.startup();

            var basemapGallery = new BasemapGallery({
                showArcGISBasemaps: true,
                map: map
            }, "basemapGallery");
            basemapGallery.startup();

            basemapGallery.on("error", function(msg) {
                console.log("basemap gallery error:  ", msg);
            });

           var adapter = new cmwapiAdapter(map);

            $('#tooltip-x-button').on('click', function() {
                $('#no-overlay-tooltip').hide();
            });
            $('#overlay').on('click', function() {
                toggleOverlayManager();
            });

            $('#basemaps').on('click', function() {
                toggleBaseMaps();
            });
            $('#overlay-add-icon').on('click', function() {
                setStateAdd();
            });
            $('#overlay-delete-icon').on('click', function() {
                setStateRemove();
            });
            $('#overlay-back-icon').on('click', function() {
                setStateInit();
            });
            $('#overlay-manager-add-button').on('click', function() {
                var featureName = $('#feature-add-name').val();
                var featureId = $('#feature-add-id').val();
                var featureUrl = $('#feature-add-url').val();
                var featureParams = $('#feature-add-params').val();
                var overlayName = $('#overlay-add-name').val();
                var overlayId = $('#overlay-add-id').val();
                if($('#overlay-selection').val() == 'Add New Overlay') {
                    adapter.overlayManager.sendOverlayCreate(overlayId, overlayName);
                    adapter.overlayManager.sendFeaturePlotUrl(overlayId, featureId, featureName,
                        'kml', featureUrl, featureParams);
                } else if($('#overlay-selection').val() == 'Default Overlay') {
                    adapter.overlayManager.sendOverlayCreate('default-overlay-id', 'Default Overlay');
                    adapter.overlayManager.sendFeaturePlotUrl('default-overlay-id',
                        featureId, featureName,'kml', featureUrl, featureParams);
                }
                else {
                    adapter.overlayManager.sendFeaturePlotUrl($('#overlay-selection').find(":selected").attr('id'),
                        featureId, featureName,'kml', featureUrl, featureParams);
                }
                setStateInit();
            });

            $('#overlay-manager-delete-button').on('click', function() {
                $("#overlay-tree input:checkbox:checked").each(function(index) {
                    if($(this).attr('node-type') === 'overlay') {
                        adapter.overlayManager.sendOverlayRemove($(this).attr('id'));
                    }
                    if($(this).attr('node-type') === 'feature') {
                        var node = $('#overlay-tree').tree('getNodeById', $(this).attr('id'));
                        adapter.overlayManager.sendFeatureUnplot(node.parent.id,$(this).attr('id'));
                    }

                });

            });

            $('#overlay-selection').on('change', function() {
                if(this.value === 'Add New Overlay') {
                    $('#add-overlay-div').show();
                } else {
                    $('#add-overlay-div').hide();
                }
                resizeOverlayManager();
                checkAddFormCompleted();
            });

            var resizeOverlayManager = function() {
                var height = $('#overlay-manager-add').height() + 100;
                $('#popover_overlay_wrapper').css('height', height + 'px');
            }
            var checkInvalidUrl = function() {
                return $('#feature-add-url').parent().hasClass('has-error');
            }

            var updateOverlaySelection = function() {
                $('#overlay-selection > option').remove();
                var defaultHtml = '<option id= "default-overlay-id">Default Overlay</option>';
                $('#overlay-selection').append(defaultHtml);
                var overlayObject = adapter.overlayManager.getOverlays();
                for(var key in overlayObject) {
                    if(!(overlayObject[key].id == 'default-overlay-id')) {
                        var appendHtml = ' <option id= "'+ overlayObject[key].id +'">' + overlayObject[key].name + '</option>'
                        $('#overlay-selection').append(appendHtml);
                    }
                }
                var defaultHtmlAdd = '<option id= "add-new-overlay-option">Add New Overlay</option>'
                $('#overlay-selection').append(defaultHtmlAdd);
                $('#overlay-selection').val('Default Overlay');
            }

            var isOverlayTreeEmpty = function() {
                return adapter.overlayManager.getOverlayTree().length === 0;
            };
            $('form').find('.form-control.default').keyup(function() {
                checkAddFormCompleted();
            });
            $('#feature-add-url').keyup(function() {
                if(!isValidUrl($(this).val())) {
                    $(this).parent().removeClass('has-success');
                    $(this).parent().addClass('has-error');
                    $('.help-block').show();
                } else {
                    $(this).parent().removeClass('has-error');
                    $(this).parent().addClass('has-success');
                    $(this).removeClass('has-error');
                    $('.help-block').hide();
                }
                resizeOverlayManager();
            });

            var isValidUrl = function(url){
                  return /\b(https?|ftp|file):\/\/[\-A-Za-z0-9+&@#\/%?=~_|!:,.;]*[\-A-Za-z0-9+&@#\/%=~_|]/.test(url);
            }

            var checkAddFormCompleted = function() {
                var emptyInputs = $('.form-control.default').filter(function() {
                    return $(this).val() === '' && $(this).is(':visible');
                }).length;
                if(emptyInputs === 0) {
                    $('#overlay-manager-add-button').removeClass('disabled');
                } else {
                    $('#overlay-manager-add-button').addClass('disabled');
                }
            };

            $("[rel=tooltip]").tooltip({ placement: 'bottom'});

            var data = adapter.overlayManager.getOverlayTree();
            var $tree = $('#overlay-tree');
            $tree.tree({
                data: data,
                dragAndDrop:true,
                autoOpen: 1,
                onCreateLi: function(node, $li) {
                    node['node-type'] = node.type;
                    var image = 'http://www.graphicsfuel.com/wp-content/uploads/2012/03/folder-icon-512x512.png';
                    if(node.type === 'overlay') {
                        image = 'http://www.graphicsfuel.com/wp-content/uploads/2012/03/folder-icon-512x512.png';
                    } else {
                        image = 'http://img0056.popscreencdn.com/103222765_watchmen-smiley-1-pin-button-badge-magnet-moore-gibbons-.jpg';
                    }
                    $li.find('.jqtree-title').before(
                        '<input type="checkbox" id="' + node.id+ '" class ="tree-node" node-type="' + node.type + '" isHidden="' + node.isHidden + '"/>' +
                        '<img src=' + image + ' alt="Overlay Icon" height="25" width="25">'
                    );
                }
            });
        $tree.bind('tree.dblclick',
            function(event) {
                console.log(event.node);
            }
        );
            var clearAddInputs = function() {
                $('#feature-add-name').val('');
                $('#feature-add-id').val('');
                $('#feature-add-url').val('');
                $('#feature-add-params').val('');
                $('#overlay-add-name').val('');
                $('#overlay-add-id').val('');
            };

            /**
            * Whenever either the trees parent nodes are clicked the children nodes are also checked
            * respectively.
            **/
            var bindSelectionHandlers = function() {
                $("#overlay-tree.default input:checkbox").off('change');
                $("#overlay-tree.default input:checkbox").on('change', function () {
                    var node = $('#overlay-tree').tree('getNodeById', $(this).attr('id'));
                    $(this).parent().next('ul').find('input:checkbox').prop('checked', $(this).prop("checked"));
                    if($(this).is(':checked') && $(this).attr('node-type') === 'overlay') {
                        adapter.overlayManager.sendOverlayShow($(this).attr('id'));
                    } else if(!($(this).is(':checked')) && $(this).attr('node-type') === 'overlay') {
                        adapter.overlayManager.sendOverlayHide($(this).attr('id'));
                    } else if($(this).is(':checked') && $(this).attr('node-type') === 'feature') {
                        adapter.overlayManager.sendFeatureShow(node.parent.id, $(this).attr('id'))
                    } else if(!($(this).is(':checked')) && $(this).attr('node-type') === 'feature') {
                        adapter.overlayManager.sendFeatureHide(node.parent.id, $(this).attr('id'))
                    }
                    $(this).prop('checked');
                });
                $("#overlay-tree.remove input:checkbox").on('change', function () {
                    $(this).parent().next('ul').find('input:checkbox').prop('checked', $(this).prop("checked"));
                });
            }

            /**
            * Method used by the button binded to the basemaps icon.
            * Toggles the basemaps popover open/close.
            * If the overlay manager popover is already open then close it.
            **/
            var toggleBaseMaps = function() {
                $('#popover_content_wrapper').toggle();
                $('#overlay').removeClass('selected');
                $('#popover_overlay_wrapper').hide();
                $('#basemaps').toggleClass('selected');
            }

            /**
            * Method used by the button binded to the overlay manager icon.
            * Toggles the overlay manager open/close.
            * If the basemap popover is already open then close it.
            * Resize the window to the correct size given the tree.
            **/
            var toggleOverlayManager = function() {
                $('#popover_overlay_wrapper').toggle();
                $('#basemaps').removeClass('selected');
                $('#popover_content_wrapper').hide();
                $('#overlay').toggleClass('selected');
                setStateInit()
            }

            /**
            * This function is used to automatically adjust the size of the window to the size of the tree plus
            * a given specified offset/padding.
            **/
            var resizeOverlayToTree = function(tree, offset) {
                var treeHeight = $(tree).css('height');
                treeHeight = parseInt(treeHeight.substr(0, treeHeight.length-2));
                $('#popover_overlay_wrapper').css('height', (treeHeight + offset) + 'px');
            }

            /**
            * This function is called each time the tree needs to be updated, the updating is handled through
            * jquery tree.
            **/
            var updateTreeData = function() {
                $('#overlay-tree').tree('loadData',adapter.overlayManager.getOverlayTree());
                resizeOverlayToTree('#overlay-tree', 90);
                if(!isOverlayTreeEmpty()) {
                    $('#no-overlay-tooltip').hide();
                } else {
                    $('#no-overlay-tooltip').show();
                }
                updateCheckBoxes();
                bindSelectionHandlers();
                setStateInit();
            }
            adapter.overlayManager.bindTreeChangeHandler(updateTreeData);

            var updateCheckBoxes = function() {
                $("#overlay-tree.default input:checkbox").each(function(index) {
                    if(($(this).attr('ishidden') == 'false')) {
                        $(this).attr('checked', 'checked');
                    }
                });
            }

            var setStateInit = function() {
                $('#overlay-delete-icon').removeClass('disabled');
                $('#no-overlay-tooltip').hide();
                if(isOverlayTreeEmpty()) {
                    $('#no-overlay-tooltip').show();
                    $('#overlay-delete-icon').addClass('disabled');
                }
                $('#overlay-manager-add-button').hide();
                $('#overlay-manager-delete-button').hide();
                $('#overlay-manager-add').hide();
                $('#overlay-manager-delete').hide();
                $('#overlay-back-icon').hide();
                $('#overlay-add-icon').show();
                $('#overlay-delete-icon').show();
                $('#overlay-tree').show();
                $('#overlay-tree').addClass('default');
                $('#overlay-tree').removeClass('remove');
                $('#overlay-tree').css('top','50px');
                $('.help-block').hide();
                $('#feature-add-url').parent().removeClass('has-success');
                $('#feature-add-url').parent().removeClass('has-error');
                updateCheckBoxes();
                bindSelectionHandlers();
                resizeOverlayToTree('#overlay-tree', 90);
            }
            var setStateAdd = function() {
                $('#no-overlay-tooltip').hide();
                clearAddInputs();
                $('#overlay-add-icon').hide();
                $('#overlay-delete-icon').hide();
                $('#overlay-manager-delete-button').hide();
                $('#add-overlay-div').hide();
                $('#overlay-manager-delete').hide();
                $('#overlay-tree').hide();
                $('#overlay-back-icon').show();
                $('#overlay-manager-add').show();
                $('#overlay-manager-add-button').show();
                $('#overlay-manager').show();
                $('#overlay-manager-subtitle').show();
                checkAddFormCompleted();
                updateOverlaySelection();
                resizeOverlayManager();
            }
            var setStateRemove = function() {
                $('#no-overlay-tooltip').hide();
                $('#overlay-add-icon').hide();
                $('#overlay-delete-icon').hide();
                $('#add-overlay-div').hide();
                $('#overlay-manager-add-button').hide();
                $('#overlay-manager-add').hide();
                $('#overlay-manager-delete').show();
                $('#overlay-manager').show();
                $('#overlay-manager-delete-button').show();
                $('#delete-feature-subtitle').show();
                $('#overlay-back-icon').show();
                $('#overlay-tree').show();
                $("#overlay-tree.default input:checkbox").off('change');
                $('#overlay-tree').removeClass('default');
                $('#overlay-tree').addClass('remove');
                $("#overlay-tree.remove input:checkbox").removeAttr('checked');
                bindSelectionHandlers();
                updateOverlaySelection();
                $('#overlay-tree').css('top','85px');
                resizeOverlayToTree('#overlay-tree', 125);
            }
        });
    }
    });<|endoftext|>