<commit_before>if (!customValidators) {
  console.error('Cannot define validator validateCnsaToggles()', new Date());
} else {
  customValidators.validateCnsaToggles = function(viewValue, form, model) {
    var fieldId = form.fieldId,
        elementIds = [],
        noMsg = {},
        id,
        noneSelected = true;

    model[form.key[0]] = viewValue;

    // var toggles = [
    //   "toggle_periop_complic_dvt",
    //   "toggle_periop_complic_pe",
    //   "toggle_periop_complic_neural",
    //   "toggle_periop_complic_mi",
    //   "toggle_periop_complic_uti",
    //   "toggle_periop_complic_cva",
    //   "toggle_periop_complic_pneum",
    //   "toggle_periop_complic_coaguopathy",
    //   "toggle_periop_complic_durotomy",
    //   "toggle_periop_complic_seroma",
    //   "toggle_periop_complic_wound_dehisc",
    //   "toggle_periop_complic_cfs_leak",
    //   "toggle_periop_complic_ssi",
    //   "toggle_periop_complic_hematoma",
    //   "toggle_periop_complic_pain",
    //   "toggle_periop_complic_other",

    //   "toggle_complications_dvt",
    //   "toggle_complications_pe",
    //   "toggle_complications_neuro",
    //   "toggle_complications_mi",
    //   "toggle_complications_uti",
    //   "toggle_complications_cva",
    //   "toggle_complications_pneum",
    //   "toggle_complications_ssi",
    //   "toggle_complications_hematoma",

    //   "toggle_maj_surg_cervical",
    //   "toggle_maj_surg_thoracolumbar",
    //   "toggle_maj_surg_hip",
    //   "toggle_maj_surg_knee"
    // ];

    // Set value of backend toggle
    var backendKey = form.key[0].replace(/^toggle_/i, '');

    // BWB if the model has the same key -{toggle_}
    // and this validator is on the toggle, then just do this
    // don't whitelist anymore...
    if (_.has(model, backendKey)) {
      if (model[backendKey] != null) {
        model[backendKey] = viewValue ? 1 : 0;
      } else {
        model[backendKey] = viewValue ? 1 : null;
      }
    }

    // Handle the special case for thoraco lumbar treatment
    var toggleGroups = {
      nd_discectomy: {
        dependsOn: 'toggle_neural_decomp',
        satisfiedBy: [
          ["toggle_neural_decomp", "toggle_nd_t4", "toggle_nd_t4_discect"],
          ["toggle_neural_decomp", "toggle_nd_t5", "toggle_nd_t5_discect"],
          ["toggle_neural_decomp", "toggle_nd_t6", "toggle_nd_t6_discect"],
          ["toggle_neural_decomp", "toggle_nd_t7", "toggle_nd_t7_discect"],
          ["toggle_neural_decomp", "toggle_nd_t8", "toggle_nd_t8_discect"],
          ["toggle_neural_decomp", "toggle_nd_t9", "toggle_nd_t9_discect"],
          ["toggle_neural_decomp", "toggle_nd_t10", "toggle_nd_t10_discect"],
          ["toggle_neural_decomp", "toggle_nd_t11", "toggle_nd_t11_discect"],
          ["toggle_neural_decomp", "toggle_nd_t12", "toggle_nd_t12_discect"],
          ["toggle_neural_decomp", "toggle_nd_l1", "toggle_nd_l1_discect"],
          ["toggle_neural_decomp", "toggle_nd_l2", "toggle_nd_l2_discect"],
          ["toggle_neural_decomp", "toggle_nd_l3", "toggle_nd_l3_discect"],
          ["toggle_neural_decomp", "toggle_nd_l4", "toggle_nd_l4_discect"],
          ["toggle_neural_decomp", "toggle_nd_l5", "toggle_nd_l5_discect"],
          ["toggle_neural_decomp", "toggle_nd_s1", "toggle_nd_s1_discect"]
        ]
      },
      nd_osteotomy: {
        dependsOn: 'toggle_neural_decomp',
        satisfiedBy: [
          ["toggle_neural_decomp", "toggle_nd_t4", "toggle_nd_t4_osteot"],
          ["toggle_neural_decomp", "toggle_nd_t5", "toggle_nd_t5_osteot"],
          ["toggle_neural_decomp", "toggle_nd_t6", "toggle_nd_t6_osteot"],
          ["toggle_neural_decomp", "toggle_nd_t7", "toggle_nd_t7_osteot"],
          ["toggle_neural_decomp", "toggle_nd_t8", "toggle_nd_t8_osteot"],
          ["toggle_neural_decomp", "toggle_nd_t9", "toggle_nd_t9_osteot"],
          ["toggle_neural_decomp", "toggle_nd_t10", "toggle_nd_t10_osteot"],
          ["toggle_neural_decomp", "toggle_nd_t11", "toggle_nd_t11_osteot"],
          ["toggle_neural_decomp", "toggle_nd_t12", "toggle_nd_t12_osteot"],
          ["toggle_neural_decomp", "toggle_nd_l1", "toggle_nd_l1_osteot"],
          ["toggle_neural_decomp", "toggle_nd_l2", "toggle_nd_l2_osteot"],
          ["toggle_neural_decomp", "toggle_nd_l3", "toggle_nd_l3_osteot"],
          ["toggle_neural_decomp", "toggle_nd_l4", "toggle_nd_l4_osteot"],
          ["toggle_neural_decomp", "toggle_nd_l5", "toggle_nd_l5_osteot"],
          ["toggle_neural_decomp", "toggle_nd_s1", "toggle_nd_s1_osteot"]
        ]
      },
      nd_facetectomy: {
        dependsOn: 'toggle_neural_decomp',
        satisfiedBy: [
          ["toggle_neural_decomp", "toggle_nd_t4", "toggle_nd_t4_facetect"],
          ["toggle_neural_decomp", "toggle_nd_t5", "toggle_nd_t5_facetect"],
          ["toggle_neural_decomp", "toggle_nd_t6", "toggle_nd_t6_facetect"],
          ["toggle_neural_decomp", "toggle_nd_t7", "toggle_nd_t7_facetect"],
          ["toggle_neural_decomp", "toggle_nd_t8", "toggle_nd_t8_facetect"],
          ["toggle_neural_decomp", "toggle_nd_t9", "toggle_nd_t9_facetect"],
          ["toggle_neural_decomp", "toggle_nd_t10", "toggle_nd_t10_facetect"],
          ["toggle_neural_decomp", "toggle_nd_t11", "toggle_nd_t11_facetect"],
          ["toggle_neural_decomp", "toggle_nd_t12", "toggle_nd_t12_facetect"],
          ["toggle_neural_decomp", "toggle_nd_l1", "toggle_nd_l1_facetect"],
          ["toggle_neural_decomp", "toggle_nd_l2", "toggle_nd_l2_facetect"],
          ["toggle_neural_decomp", "toggle_nd_l3", "toggle_nd_l3_facetect"],
          ["toggle_neural_decomp", "toggle_nd_l4", "toggle_nd_l4_facetect"],
          ["toggle_neural_decomp", "toggle_nd_l5", "toggle_nd_l5_facetect"],
          ["toggle_neural_decomp", "toggle_nd_s1", "toggle_nd_s1_facetect"]
        ]
      },
      pa_spacer: {
        dependsOn: 'toggle_arthrodesis',
        satisfiedBy: [
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t4t5", "toggle_pa_t4t5_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t5t6", "toggle_pa_t5t6_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t6t7", "toggle_pa_t6t7_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t7t8", "toggle_pa_t7t8_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t8t9", "toggle_pa_t8t9_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t9t10", "toggle_pa_t9t10_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t10t11", "toggle_pa_t10t11_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t11t12", "toggle_pa_t11t12_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t12l1", "toggle_pa_t12l1_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_l1l2", "toggle_pa_l1l2_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_l2l3", "toggle_pa_l2l3_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_l3l4", "toggle_pa_l3l4_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_l4l5", "toggle_pa_l4l5_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_l5s1", "toggle_pa_l5s1_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_s1p", "toggle_pa_s1p_spacer"]
        ]
      }
    };

    // For all grouped toggles
    for (var property in toggleGroups) {
      var grouping = toggleGroups[property];

      // If we at least have the first
      if (model[grouping.dependsOn]) {
        // Check model value for each toggle in grouping
        for (var i = 0; i < grouping.satisfiedBy.length; i++) {
          var satisfyingGroup = grouping.satisfiedBy[i],
              satisfied = true;

          for (var k = 0; k < satisfyingGroup.length; k++) {
            if (!model[satisfyingGroup[k]]) {
              satisfied = false;
              break;
            }
          }

          if (satisfied) {
            model[property] = 1;
            break;
          }
        }
      }
    }

    return {
      valid: true
    }

  }
}
<commit_msg>test - cnsa toggles<commit_after>if (!customValidators) {
  console.error('Cannot define validator validateCnsaToggles()', new Date());
} else {
  customValidators.validateCnsaToggles = function(viewValue, form, model) {
    var fieldId = form.fieldId,
        elementIds = [],
        noMsg = {},
        id,
        noneSelected = true;

    model[form.key[0]] = viewValue;

    // var toggles = [
    //   "toggle_periop_complic_dvt",
    //   "toggle_periop_complic_pe",
    //   "toggle_periop_complic_neural",
    //   "toggle_periop_complic_mi",
    //   "toggle_periop_complic_uti",
    //   "toggle_periop_complic_cva",
    //   "toggle_periop_complic_pneum",
    //   "toggle_periop_complic_coaguopathy",
    //   "toggle_periop_complic_durotomy",
    //   "toggle_periop_complic_seroma",
    //   "toggle_periop_complic_wound_dehisc",
    //   "toggle_periop_complic_cfs_leak",
    //   "toggle_periop_complic_ssi",
    //   "toggle_periop_complic_hematoma",
    //   "toggle_periop_complic_pain",
    //   "toggle_periop_complic_other",

    //   "toggle_complications_dvt",
    //   "toggle_complications_pe",
    //   "toggle_complications_neuro",
    //   "toggle_complications_mi",
    //   "toggle_complications_uti",
    //   "toggle_complications_cva",
    //   "toggle_complications_pneum",
    //   "toggle_complications_ssi",
    //   "toggle_complications_hematoma",

    //   "toggle_maj_surg_cervical",
    //   "toggle_maj_surg_thoracolumbar",
    //   "toggle_maj_surg_hip",
    //   "toggle_maj_surg_knee"
    // ];

    // Set value of backend toggle
    var backendKey = form.key[0].replace(/^toggle_/i, '');

    console.log('model', model);
    console.log('backendKey', backendKey);

    // BWB if the model has the same key -{toggle_}
    // and this validator is on the toggle, then just do this
    // don't whitelist anymore...
    if (_.has(model, backendKey)) {
      if (model[backendKey] != null) {
        console.log('!= null');
        model[backendKey] = viewValue ? 1 : 0;
      } else {
        console.log('== null');
        model[backendKey] = viewValue ? 1 : null;
      }
    }

    console.log('new model', model);

    // Handle the special case for thoraco lumbar treatment
    var toggleGroups = {
      nd_discectomy: {
        dependsOn: 'toggle_neural_decomp',
        satisfiedBy: [
          ["toggle_neural_decomp", "toggle_nd_t4", "toggle_nd_t4_discect"],
          ["toggle_neural_decomp", "toggle_nd_t5", "toggle_nd_t5_discect"],
          ["toggle_neural_decomp", "toggle_nd_t6", "toggle_nd_t6_discect"],
          ["toggle_neural_decomp", "toggle_nd_t7", "toggle_nd_t7_discect"],
          ["toggle_neural_decomp", "toggle_nd_t8", "toggle_nd_t8_discect"],
          ["toggle_neural_decomp", "toggle_nd_t9", "toggle_nd_t9_discect"],
          ["toggle_neural_decomp", "toggle_nd_t10", "toggle_nd_t10_discect"],
          ["toggle_neural_decomp", "toggle_nd_t11", "toggle_nd_t11_discect"],
          ["toggle_neural_decomp", "toggle_nd_t12", "toggle_nd_t12_discect"],
          ["toggle_neural_decomp", "toggle_nd_l1", "toggle_nd_l1_discect"],
          ["toggle_neural_decomp", "toggle_nd_l2", "toggle_nd_l2_discect"],
          ["toggle_neural_decomp", "toggle_nd_l3", "toggle_nd_l3_discect"],
          ["toggle_neural_decomp", "toggle_nd_l4", "toggle_nd_l4_discect"],
          ["toggle_neural_decomp", "toggle_nd_l5", "toggle_nd_l5_discect"],
          ["toggle_neural_decomp", "toggle_nd_s1", "toggle_nd_s1_discect"]
        ]
      },
      nd_osteotomy: {
        dependsOn: 'toggle_neural_decomp',
        satisfiedBy: [
          ["toggle_neural_decomp", "toggle_nd_t4", "toggle_nd_t4_osteot"],
          ["toggle_neural_decomp", "toggle_nd_t5", "toggle_nd_t5_osteot"],
          ["toggle_neural_decomp", "toggle_nd_t6", "toggle_nd_t6_osteot"],
          ["toggle_neural_decomp", "toggle_nd_t7", "toggle_nd_t7_osteot"],
          ["toggle_neural_decomp", "toggle_nd_t8", "toggle_nd_t8_osteot"],
          ["toggle_neural_decomp", "toggle_nd_t9", "toggle_nd_t9_osteot"],
          ["toggle_neural_decomp", "toggle_nd_t10", "toggle_nd_t10_osteot"],
          ["toggle_neural_decomp", "toggle_nd_t11", "toggle_nd_t11_osteot"],
          ["toggle_neural_decomp", "toggle_nd_t12", "toggle_nd_t12_osteot"],
          ["toggle_neural_decomp", "toggle_nd_l1", "toggle_nd_l1_osteot"],
          ["toggle_neural_decomp", "toggle_nd_l2", "toggle_nd_l2_osteot"],
          ["toggle_neural_decomp", "toggle_nd_l3", "toggle_nd_l3_osteot"],
          ["toggle_neural_decomp", "toggle_nd_l4", "toggle_nd_l4_osteot"],
          ["toggle_neural_decomp", "toggle_nd_l5", "toggle_nd_l5_osteot"],
          ["toggle_neural_decomp", "toggle_nd_s1", "toggle_nd_s1_osteot"]
        ]
      },
      nd_facetectomy: {
        dependsOn: 'toggle_neural_decomp',
        satisfiedBy: [
          ["toggle_neural_decomp", "toggle_nd_t4", "toggle_nd_t4_facetect"],
          ["toggle_neural_decomp", "toggle_nd_t5", "toggle_nd_t5_facetect"],
          ["toggle_neural_decomp", "toggle_nd_t6", "toggle_nd_t6_facetect"],
          ["toggle_neural_decomp", "toggle_nd_t7", "toggle_nd_t7_facetect"],
          ["toggle_neural_decomp", "toggle_nd_t8", "toggle_nd_t8_facetect"],
          ["toggle_neural_decomp", "toggle_nd_t9", "toggle_nd_t9_facetect"],
          ["toggle_neural_decomp", "toggle_nd_t10", "toggle_nd_t10_facetect"],
          ["toggle_neural_decomp", "toggle_nd_t11", "toggle_nd_t11_facetect"],
          ["toggle_neural_decomp", "toggle_nd_t12", "toggle_nd_t12_facetect"],
          ["toggle_neural_decomp", "toggle_nd_l1", "toggle_nd_l1_facetect"],
          ["toggle_neural_decomp", "toggle_nd_l2", "toggle_nd_l2_facetect"],
          ["toggle_neural_decomp", "toggle_nd_l3", "toggle_nd_l3_facetect"],
          ["toggle_neural_decomp", "toggle_nd_l4", "toggle_nd_l4_facetect"],
          ["toggle_neural_decomp", "toggle_nd_l5", "toggle_nd_l5_facetect"],
          ["toggle_neural_decomp", "toggle_nd_s1", "toggle_nd_s1_facetect"]
        ]
      },
      pa_spacer: {
        dependsOn: 'toggle_arthrodesis',
        satisfiedBy: [
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t4t5", "toggle_pa_t4t5_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t5t6", "toggle_pa_t5t6_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t6t7", "toggle_pa_t6t7_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t7t8", "toggle_pa_t7t8_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t8t9", "toggle_pa_t8t9_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t9t10", "toggle_pa_t9t10_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t10t11", "toggle_pa_t10t11_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t11t12", "toggle_pa_t11t12_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_t12l1", "toggle_pa_t12l1_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_l1l2", "toggle_pa_l1l2_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_l2l3", "toggle_pa_l2l3_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_l3l4", "toggle_pa_l3l4_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_l4l5", "toggle_pa_l4l5_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_l5s1", "toggle_pa_l5s1_spacer"],
          ["toggle_arthrodesis", "toggle_post_arthrod", "toggle_pa_s1p", "toggle_pa_s1p_spacer"]
        ]
      }
    };

    // For all grouped toggles
    for (var property in toggleGroups) {
      var grouping = toggleGroups[property];

      // If we at least have the first
      if (model[grouping.dependsOn]) {
        // Check model value for each toggle in grouping
        for (var i = 0; i < grouping.satisfiedBy.length; i++) {
          var satisfyingGroup = grouping.satisfiedBy[i],
              satisfied = true;

          for (var k = 0; k < satisfyingGroup.length; k++) {
            if (!model[satisfyingGroup[k]]) {
              satisfied = false;
              break;
            }
          }

          if (satisfied) {
            model[property] = 1;
            break;
          }
        }
      }
    }

    return {
      valid: true
    }

  }
}
<|endoftext|>


<commit_before>var $ = require('jquery');

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var Enemy = require('./enemies');
var Game = require("./game.js");

var enemy = new Enemy();
var game = new Game();

$('start-game').css('visibility', 'visible');

function repeat() {
  if (game.active === true) {
    setTimeout(function() {
    requestAnimationFrame(repeat);
    game.repeat();
  }, 1000 / 100);
  //  game.keepScore();
  }
}

$(document).on("click", function () {
    $('#start-game').css('visibility', 'hidden');
    $('#game-over').css('visibility', 'hidden');
    $('#you-win').css('visibility', 'hidden');
    game.startGame();
    repeat();
    enemy.increaseCounter();
    game.playThemeSong();
});

$(document).on("keydown", function (key) {
  if (key.which === 32) {
    if ($('start-game').css('visibility', 'hidden')) {
      game.bluecifer.moveUp();
      game.detectCeilingCollision();
    }
    else {
      game.resetGame();
    }
  }
  else if (key.which === 13) {
      game.pauseThemeSong();
  }
  else if (key.which === 85 && $('start-game').css('visibility', 'visible')) {
    var code = prompt("Enter cheat code");
    game.cheat(code);
  }
});
<commit_msg>fixed bug so that final score counter now goes away when new game is started<commit_after>var $ = require('jquery');

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var Enemy = require('./enemies');
var Game = require("./game.js");

var enemy = new Enemy();
var game = new Game();

$('start-game').css('visibility', 'visible');

function repeat() {
  if (game.active === true) {
    setTimeout(function() {
    requestAnimationFrame(repeat);
    game.repeat();
  }, 1000 / 100);
  //  game.keepScore();
  }
}

$(document).on("click", function () {
    $('#start-game').css('visibility', 'hidden');
    $('#game-over').css('visibility', 'hidden');
    $('#you-win').css('visibility', 'hidden');
    $("#final-score-display").text("");
    game.startGame();
    repeat();
    enemy.increaseCounter();
    game.playThemeSong();
});

$(document).on("keydown", function (key) {
  if (key.which === 32) {
    if ($('start-game').css('visibility', 'hidden')) {
      game.bluecifer.moveUp();
      game.detectCeilingCollision();
    }
    else {
      game.resetGame();
    }
  }
  else if (key.which === 13) {
      game.pauseThemeSong();
  }
  else if (key.which === 85 && $('start-game').css('visibility', 'visible')) {
    var code = prompt("Enter cheat code");
    game.cheat(code);
  }
});
<|endoftext|>


<commit_before>/**
 * @fileoverview Tests for no-missing-require rule.
 * @author Toru Nagashima
 * @copyright 2015 Toru Nagashima. All rights reserved.
 * See LICENSE file in root directory for full license.
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

var path = require("path"),
    RuleTester = require("eslint").RuleTester,
    rule = require("../../../lib/rules/no-missing-import");

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
 * Makes a file path to a fixture.
 * @param {string} name - A name.
 * @returns {string} A file path to a fixture.
 */
function fixture(name) {
    return path.resolve(__dirname, "../../fixtures/no-missing-require", name);
}

//------------------------------------------------------------------------------
// Test
//------------------------------------------------------------------------------

var ruleTester = new RuleTester();
ruleTester.run("no-missing-import", rule, {
    valid: [
        {
            filename: fixture("test.js"),
            code: "import eslint from 'eslint';",
            env: {node: true},
            ecmaFeatures: {modules: true}
        },
        {
            filename: fixture("test.js"),
            code: "import eslint from 'eslint/lib/ast-utils';",
            env: {node: true},
            ecmaFeatures: {modules: true}
        },
        {
            filename: fixture("test.js"),
            code: "import a from './a';",
            env: {node: true},
            ecmaFeatures: {modules: true}
        },
        {
            filename: fixture("test.js"),
            code: "import a from './a.js';",
            env: {node: true},
            ecmaFeatures: {modules: true}
        },
        {
            filename: fixture("test.js"),
            code: "import resolve from 'resolve';",
            options: [{"publish": "*.js"}],
            env: {node: true},
            ecmaFeatures: {modules: true}
        },
        {
            filename: fixture("test.js"),
            code: "import mocha from 'mocha';",
            env: {node: true},
            ecmaFeatures: {modules: true}
        },

        // Ignores it if the filename is unknown.
        {
            code: "import abc from 'no-exist-package-0';",
            env: {node: true},
            ecmaFeatures: {modules: true}
        },
        {
            code: "import b from './b';",
            env: {node: true},
            ecmaFeatures: {modules: true}
        }
    ],
    invalid: [
        {
            filename: fixture("test.js"),
            code: "import abc from 'no-exist-package-0';",
            env: {node: true},
            ecmaFeatures: {modules: true},
            errors: [
                "\"no-exist-package-0\" is not found.",
                "\"no-exist-package-0\" is not published."
            ]
        },
        {
            filename: fixture("test.js"),
            code: "import test from '@mysticatea/test';",
            env: {node: true},
            ecmaFeatures: {modules: true},
            errors: [
                "\"@mysticatea/test\" is not found.",
                "\"@mysticatea/test\" is not published."
            ]
        },
        {
            filename: fixture("test.js"),
            code: "import abc from 'no-exist-package-0';",
            options: [{"publish": null}],
            env: {node: true},
            ecmaFeatures: {modules: true},
            errors: ["\"no-exist-package-0\" is not found."]
        },
        {
            filename: fixture("test.js"),
            code: "import b from './b';",
            env: {node: true},
            ecmaFeatures: {modules: true},
            errors: ["\"./b\" is not found."]
        },
        {
            filename: fixture("test.js"),
            code: "import a from './a.json';",
            env: {node: true},
            ecmaFeatures: {modules: true},
            errors: ["\"./a.json\" is not found."]
        },
        {
            filename: fixture("test.js"),
            code: "import async from 'async';",
            env: {node: true},
            ecmaFeatures: {modules: true},
            errors: ["\"async\" is not published."]
        },
        {
            filename: fixture("test.js"),
            code: "import mocha from 'mocha';",
            options: [{"publish": "*.js"}],
            env: {node: true, es6: true},
            ecmaFeatures: {modules: true},
            errors: ["\"mocha\" is not published."]
        }
    ]
});
<commit_msg>Fix: tests of `no-missing-import` for v2<commit_after>/**
 * @fileoverview Tests for no-missing-require rule.
 * @author Toru Nagashima
 * @copyright 2015 Toru Nagashima. All rights reserved.
 * See LICENSE file in root directory for full license.
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

var path = require("path"),
    RuleTester = require("eslint").RuleTester,
    rule = require("../../../lib/rules/no-missing-import");

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
 * Makes a file path to a fixture.
 * @param {string} name - A name.
 * @returns {string} A file path to a fixture.
 */
function fixture(name) {
    return path.resolve(__dirname, "../../fixtures/no-missing-require", name);
}

//------------------------------------------------------------------------------
// Test
//------------------------------------------------------------------------------

var ruleTester = new RuleTester();
ruleTester.run("no-missing-import", rule, {
    valid: [
        {
            filename: fixture("test.js"),
            code: "import eslint from 'eslint';",
            env: {node: true},
            parserOptions: {sourceType: "module"}
        },
        {
            filename: fixture("test.js"),
            code: "import eslint from 'eslint/lib/ast-utils';",
            env: {node: true},
            parserOptions: {sourceType: "module"}
        },
        {
            filename: fixture("test.js"),
            code: "import a from './a';",
            env: {node: true},
            parserOptions: {sourceType: "module"}
        },
        {
            filename: fixture("test.js"),
            code: "import a from './a.js';",
            env: {node: true},
            parserOptions: {sourceType: "module"}
        },
        {
            filename: fixture("test.js"),
            code: "import resolve from 'resolve';",
            options: [{"publish": "*.js"}],
            env: {node: true},
            parserOptions: {sourceType: "module"}
        },
        {
            filename: fixture("test.js"),
            code: "import mocha from 'mocha';",
            env: {node: true},
            parserOptions: {sourceType: "module"}
        },

        // Ignores it if the filename is unknown.
        {
            code: "import abc from 'no-exist-package-0';",
            env: {node: true},
            parserOptions: {sourceType: "module"}
        },
        {
            code: "import b from './b';",
            env: {node: true},
            parserOptions: {sourceType: "module"}
        }
    ],
    invalid: [
        {
            filename: fixture("test.js"),
            code: "import abc from 'no-exist-package-0';",
            env: {node: true},
            parserOptions: {sourceType: "module"},
            errors: [
                "\"no-exist-package-0\" is not found.",
                "\"no-exist-package-0\" is not published."
            ]
        },
        {
            filename: fixture("test.js"),
            code: "import test from '@mysticatea/test';",
            env: {node: true},
            parserOptions: {sourceType: "module"},
            errors: [
                "\"@mysticatea/test\" is not found.",
                "\"@mysticatea/test\" is not published."
            ]
        },
        {
            filename: fixture("test.js"),
            code: "import abc from 'no-exist-package-0';",
            options: [{"publish": null}],
            env: {node: true},
            parserOptions: {sourceType: "module"},
            errors: ["\"no-exist-package-0\" is not found."]
        },
        {
            filename: fixture("test.js"),
            code: "import b from './b';",
            env: {node: true},
            parserOptions: {sourceType: "module"},
            errors: ["\"./b\" is not found."]
        },
        {
            filename: fixture("test.js"),
            code: "import a from './a.json';",
            env: {node: true},
            parserOptions: {sourceType: "module"},
            errors: ["\"./a.json\" is not found."]
        },
        {
            filename: fixture("test.js"),
            code: "import async from 'async';",
            env: {node: true},
            parserOptions: {sourceType: "module"},
            errors: ["\"async\" is not published."]
        },
        {
            filename: fixture("test.js"),
            code: "import mocha from 'mocha';",
            options: [{"publish": "*.js"}],
            env: {node: true, es6: true},
            parserOptions: {sourceType: "module"},
            errors: ["\"mocha\" is not published."]
        }
    ]
});
<|endoftext|>


<commit_before>// Pseudocode
// place field with placeholder "item"
// place field with placeholder "quantity"
// place submit button

// add items object called item
//     property name will be item
//     property value will be quantity

// display list
//     place remove button next to item displayed

// initial
// var items = {}

// function addItem() {
//     var item = document.getElementById("item")
//     var quantity = document.getElementById("quantity")
//     items[item.value] = quantity.value
//     printItem(item.value, quantity.value)
// }

// function printItem(item, quantity){
//   var myList = document.getElementById("printitems")
//   var mySection= document.createElement("div")
//   myList.appendChild(mySection)

//   var itemPrint = document.createElement("label")
//   itemPrint.innerHTML = quantity + ": " + item
//   myList.appendChild(itemPrint)

//   var itemRemoveButton = document.createElement("button")
//   itemRemoveButton.setAttribute("id", item)

// }

// var addItemsToList = document.getElementById("submit")
// addItemsToList.addEventListener("click", addItem, false)

// function addItem() {
//     var item = document.getElementById("item").value
//     var node = document.createElement('LI')
//     var textnode = document.createTextNode(item)
//     node.appendChild(textnode)
//     document.getElementById("printList").appendChild(node)
// }

// Refactored
var addItemsToList = document.getElementById("button_submit")
addItemsToList.addEventListener("click", addItem, false)

function addItem(){
  var item = document.getElementById('item').value
  var quantity = document.getElementById('quantity').value

  if (item.length == 0 || quantity.length ==0) {
    alert('Please enter an item on the list')
  }
  else {
    increaseList()
  }
}

function increaseList() {
  var item = document.getElementById('item').value
  var quantity = document.getElementById('quantity').value
  var listItem = document.createElement('li')
  listItem.setAttribute('id', item)
  var listItemText = document.createTextNode(quantity + ': ' + item)

  listItem.appendChild(listItemText)
  document.getElementById('groceryList').appendChild(listItem)

  makeRemoveButton(item)
}

function makeRemoveButton(item){
  var button = document.createElement('button')

  button.setAttribute('id', item)
  button.setAttribute('class', 'remove')
  button.innerHTML = 'Remove'

  document.getElementById(item).appendChild(button)

  clearInputField()
}

function clearInputField() {
  document.getElementById('item').value = ''
  document.getElementById('quantity').value = ''
}<commit_msg>Functionality complete, visual aspect needed<commit_after>// Pseudocode
// place field with placeholder "item"
// place field with placeholder "quantity"
// place submit button

// add items object called item
//     property name will be item
//     property value will be quantity

// display list
//     place remove button next to item displayed

// initial
// var items = {}

// function addItem() {
//     var item = document.getElementById("item")
//     var quantity = document.getElementById("quantity")
//     items[item.value] = quantity.value
//     printItem(item.value, quantity.value)
// }

// function printItem(item, quantity){
//   var myList = document.getElementById("printitems")
//   var mySection= document.createElement("div")
//   myList.appendChild(mySection)

//   var itemPrint = document.createElement("label")
//   itemPrint.innerHTML = quantity + ": " + item
//   myList.appendChild(itemPrint)

//   var itemRemoveButton = document.createElement("button")
//   itemRemoveButton.setAttribute("id", item)

// }

// var addItemsToList = document.getElementById("submit")
// addItemsToList.addEventListener("click", addItem, false)

// function addItem() {
//     var item = document.getElementById("item").value
//     var node = document.createElement('LI')
//     var textnode = document.createTextNode(item)
//     node.appendChild(textnode)
//     document.getElementById("printList").appendChild(node)
// }

// Refactored
var addItemsToList = document.getElementById("button_submit")
addItemsToList.addEventListener("click", addItem, false)

function addItem() {
  var item = document.getElementById('item').value
  var quantity = document.getElementById('quantity').value

  if (item.length == 0 || quantity.length == 0) {
    alert('Please enter an item on the list')
  }
  else {
    increaseList()
  }
}

function increaseList() {
  var item = document.getElementById('item').value
  var quantity = document.getElementById('quantity').value
  var listItem = document.createElement('li')
  listItem.setAttribute('id', item)
  var listItemText = document.createTextNode(quantity + ': ' + item)

  listItem.appendChild(listItemText)
  document.getElementById('groceryList').appendChild(listItem)

  makeRemoveButton(item)
}

function makeRemoveButton(item) {
  var button = document.createElement('button')

  button.setAttribute('id', item)
  button.setAttribute('class', 'remove')
  button.innerHTML = 'Remove'

  document.getElementById(item).appendChild(button)

  clearInputField()
}

function clearInputField() {
  document.getElementById('item').value = ''
  document.getElementById('quantity').value = ''
}

document.addEventListener("click", function(event) {
    evaluate_click(event.target.id)
})

function evaluate_click(element) {
    var clicked_element = document.getElementById(element)
    document.getElementById('groceryList').removeChild(clicked_element)
}<|endoftext|>


<commit_before>/*!
 * bootstrap-calendar plugin
 * Original author: @ahmontero
 * Licensed under the MIT license
 *
 * jQuery lightweight plugin boilerplate
 * Original author: @ajpiano
 * Further changes, comments: @addyosmani
 * Licensed under the MIT license
 */

// the semi-colon before the function invocation is a safety
// net against concatenated scripts and/or other plugins
// that are not closed properly.
;
(function ($, window, document, undefined) {

    /**
     * 微型模板引擎 tmpl 0.2
     *
     * 0.2 更新:
     * 1. 修复转义字符与id判断的BUG
     * 2. 放弃低效的 with 语句从而最高提升3.5倍的执行效率
     * 3. 使用随机内部变量防止与模板变量产生冲突
     *
     * @author	John Resig, Tang Bin
     * @see		http://ejohn.org/blog/javascript-micro-templating/
     * @name	tmpl
     * @param	{String}	模板内容或者装有模板内容的元素ID
     * @param	{Object}	附加的数据
     * @return	{String}	解析好的模板
     *
     * @example
     * 方式一：在页面嵌入模板
     *
     * tmpl('tmpl-demo', {name: 'demo data', list: [202, 96, 133, 134]})
     *
     * 方式二：直接传入模板：
     * var demoTmpl =
     * '<ol title="<%=name%>">'
     * + '<% for (var i = 0, l = list.length; i < length; i ++) { %>'
     * +	'
<%=list[i]%>
'
     * + '<% } %>'
     * +'
';
     * var render = tmpl(demoTmpl);
     * render({name: 'demo data', list: [202, 96, 133, 134]});
     *
     * 这两种方式区别在于第一个会自动缓存编译好的模板，
     * 而第二种缓存交给外部对象控制，如例二中的 render 变量。
     */

    //    var tmpl = (function (cache, $) {
    //        return function (str, data) {
    //            var fn = !/s/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML)
    //
    //            : function (data) {
    //                    var i, variable = [$],
    //                        value = [[]];
    //                    for (i in data) {
    //                        variable.push(i);
    //                        value.push(data[i]);
    //                    };
    //                    return (new Function(variable, fn.$)).apply(data, value).join("");
    //                };
    //
    //            fn.$ = fn.$ || $ + ".push('" + str.replace(/\\/g, "\\")
    //                .replace(/ [rtn] /g, " ")
    //                .split("<%").join("t")
    //                .replace(/((^|%>)[^t]*)'/g, "$1r")
    //                .replace(/t=(.*?)%>/g, "',$1,'")
    //                .split("t").join("');")
    //                .split("%>").join($ + ".push('")
    //                .split("r").join("\'") + "');return " + $;
    //
    //            return data ? fn(data) : fn;
    //        }
    //    })({}, '$' + (+new Date));
    // Simple JavaScript Templating
    // John Resig - http://ejohn.org/ - MIT Licensed
    (function () {
        var cache = {};

        this.tmpl = function tmpl(str, data) {
            // Figure out if we're getting a template, or if we need to
            // load the template - and be sure to cache the result.
            var fn = !/\W/.test(str) ?
                cache[str] = cache[str] ||
                tmpl(document.getElementById(str).innerHTML) :

            // Generate a reusable function that will serve as a template
            // generator (and which will be cached).
            new Function("obj",
                "var p=[],print=function(){p.push.apply(p,arguments);};" +

            // Introduce the data as local variables using with(){}
            "with(obj){p.push('" +

            // Convert the template into pure JavaScript
            str
                .replace(/[\r\t\n]/g, " ")
                .split("<%").join("\t")
                .replace(/((^|%>)[^\t]*)'/g, "$1\r")
                .replace(/\t=(.*?)%>/g, "',$1,'")
                .split("\t").join("');")
                .split("%>").join("p.push('")
                .split("\r").join("\\'") + "');}return p.join('');");

            // Provide some basic currying to the user
            return data ? fn(data) : fn;
        };
    })();

    var pluginName = 'LiveScheduler',

        defaults = {
            weekStart: 1,
            msg_days: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
            msg_months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
            msg_today: 'Today',
            msg_events_today: 'Events Today', // when today click.
            url: "",
            events: null
        },
        timeline_template = tmpl('
' +
            '
' +
						'

' +
						'
' +
            '上一周' +
            '
' +
						'

' +
            '
' +
            '&lt' +
            '
' +
            '
' +
            '&gt' +
            '
' +
            '
' +
            '下一周' +
            '

' +
						 '<% for (var i = 0, length = seven_day.length; i < length; i ++) { %>' +
	            '<li class="" id="day_<%= seven_day[i] %>">' +
	            ' <%= seven_day[i].format("ddd") %>
<%= seven_day[i].date() %>' +
	            '
' +
	            '<% } %>' +

            '
' +
            '
'),

				events_list_template = '
' +

        '<% for (var ix = 0, lengthx = seven_day_events.length; ix < lengthx; ix ++) { %>' +
						'
' +
						'<% if (seven_day_events[ix].length>0){ %>' +
				'<% for (var jx = 0 ,sde=seven_day_events[ix][0], lengthy = seven_day_events[ix][0].LiveInfo.length; jx < lengthy; jx ++) { %>' +
            '
' +

            '
' +
            '<a href="<%= sde.LiveInfo[jx].url %>"><%= sde.LiveInfo[jx].title.substring(0,10) %>' +
						'
<%= sde.LiveInfo[jx].time%>
' +
						'
<%= sde.LiveInfo[jx].classroom%>
' +
						'
<%= sde.LiveInfo[jx].course.substring(0,6) %>
' +
            '
' +

            ' <li class="event_status" style="background-color:<%= sde.LiveInfo[jx].color %>' +
						' <% if( sde.LiveInfo[jx].status !=null ){ %>'+
            ' <%= sde.LiveInfo[jx].status %>' +
						' <% } %>' +
            '
' +

            '
' +
						'<% } %>' +
		        '<% } %>' +
							'
' +
            '<% } %>',
        daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],

        today = new Date();

    // The actual plugin constructor

    function Plugin(element, options) {
        this.element = $(element);

        // jQuery has an extend method that merges the
        // contents of two or more objects, storing the
        // result in the first object. The first object
        // is generally empty because we don't want to alter
        // the default options for future instances of the plugin
        this.options = $.extend({}, defaults, options);

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    };

    Plugin.prototype.init = function () {
        // Place initialization logic here
        // You already have access to the DOM element and
        // the options via the instance, e.g. this.element
        // and this.options
        this.weekStart = this.options.weekStart || 1;
        this.days = this.options.msg_days;
        this.months = this.options.msg_months;
        this.msg_today = this.options.msg_today;
        this.msg_events_hdr = this.options.msg_events_header;
        this.events = this.options.events;
        this.url = this.options.url;

        this.live_date = new Date();

        var now = moment();
        this.mm = now.month();
        this.yy = now.year();
        this.today = now.date();
        this.middleDay = now;

        this.renderCalendar(getSevenDays(now));

    };

    Plugin.prototype.renderCalendar = function (daylist) {

        if (this.calendar) {
            $(".timeline").remove();
            $("#accordion_event_table").remove();
        }

        var that = this;
        var elt = tmpl(events_list_template);

        this.calendar = $(timeline_template({
            seven_day: daylist
        }))
            .appendTo(this.element).on({
                click: $.proxy(this.click, this)
            });
        $.ajax({
            type: "POST",
            url: this.url,
            data: {
                "days": _.map(daylist, function (k) {
                    return moment(k).utc().format();
                })

            },
            // crossDomain:true,
            dataType: "json",
            jsonp: false

        }).done(function (da) {

            if (da.length > 0) {

                var days = _.map(daylist, function (k) {
                    return moment(k).utc().format();
                });
                that.events = _.map(days, function (date) {
                    return _.filter(da, function (re) {
                        return moment(re.date).date() == moment(date).date();
                    }
                        );

                });

                var v = {

                    seven_day_events: that.events
                }
                // console.log(v);
                $(elt(v)).appendTo(that.element)

            }

        }).fail(function (jqXHR, textStatus, errorThrown) {
            // console.log(textStatus);
        });

    };

    Plugin.prototype.click = function (e) {
        e.stopPropagation();
        e.preventDefault();
        var target = $(e.target).closest('li');
        if (target.length == 1) {
            if (target.is('.pre')) {

                if (target.is('.fast')) {
                    this.middleDay = moment(this.middleDay).subtract('d', 7);
                    this.renderCalendar(getSevenDays(this.middleDay));
                } else {
                    this.middleDay = moment(this.middleDay).subtract('d', 1);
                    this.renderCalendar(getSevenDays(this.middleDay));
                }
            } else if (target.is('.next')) {

                if (target.is('.fast')) {
                    this.middleDay = moment(this.middleDay).add('d', 7);
                    this.renderCalendar(getSevenDays(this.middleDay));
                } else {
                    this.middleDay = moment(this.middleDay).add('d', 1);
                    this.renderCalendar(getSevenDays(this.middleDay));
                }

            }
        }

    };

    var getSevenDays = function (middleDay) {

        var daylist = new Array();
        var startDay = moment(middleDay).subtract('d', Math.floor(7 / 2));

        _(7).times(function (n) {
            var ss = startDay.add('d', 1);
            daylist.push(moment(ss));

        });
        return daylist;
    };

    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName,
                    new Plugin(this, options));
            }
        });
    }

})(jQuery, window, document);<commit_msg>substring title<commit_after>/*!
 * bootstrap-calendar plugin
 * Original author: @ahmontero
 * Licensed under the MIT license
 *
 * jQuery lightweight plugin boilerplate
 * Original author: @ajpiano
 * Further changes, comments: @addyosmani
 * Licensed under the MIT license
 */

// the semi-colon before the function invocation is a safety
// net against concatenated scripts and/or other plugins
// that are not closed properly.
;
(function ($, window, document, undefined) {

    (function () {
        var cache = {};

        this.tmpl = function tmpl(str, data) {
            // Figure out if we're getting a template, or if we need to
            // load the template - and be sure to cache the result.
            var fn = !/\W/.test(str) ?
                cache[str] = cache[str] ||
                tmpl(document.getElementById(str).innerHTML) :

            // Generate a reusable function that will serve as a template
            // generator (and which will be cached).
            new Function("obj",
                "var p=[],print=function(){p.push.apply(p,arguments);};" +

            // Introduce the data as local variables using with(){}
            "with(obj){p.push('" +

            // Convert the template into pure JavaScript
            str
                .replace(/[\r\t\n]/g, " ")
                .split("<%").join("\t")
                .replace(/((^|%>)[^\t]*)'/g, "$1\r")
                .replace(/\t=(.*?)%>/g, "',$1,'")
                .split("\t").join("');")
                .split("%>").join("p.push('")
                .split("\r").join("\\'") + "');}return p.join('');");

            // Provide some basic currying to the user
            return data ? fn(data) : fn;
        };
    })();

    var pluginName = 'LiveScheduler',

        defaults = {
            weekStart: 1,
            msg_days: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
            msg_months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
            msg_today: 'Today',
            msg_events_today: 'Events Today', // when today click.
            url: "",
            events: null
        },
        timeline_template = tmpl('
' +
            '
' +
						'

' +
						'
' +
            '上一周' +
            '
' +
						'

' +
            '
' +
            '&lt' +
            '
' +
            '
' +
            '&gt' +
            '
' +
            '
' +
            '下一周' +
            '

' +
						 '<% for (var i = 0, length = seven_day.length; i < length; i ++) { %>' +
	            '<li class="" id="day_<%= seven_day[i] %>">' +
	            ' <%= seven_day[i].format("ddd") %>
<%= seven_day[i].date() %>' +
	            '
' +
	            '<% } %>' +

            '
' +
            '
'),

				events_list_template = '
' +

        '<% for (var ix = 0, lengthx = seven_day_events.length; ix < lengthx; ix ++) { %>' +
						'
' +
						'<% if (seven_day_events[ix].length>0){ %>' +
				'<% for (var jx = 0 ,sde=seven_day_events[ix][0], lengthy = seven_day_events[ix][0].LiveInfo.length; jx < lengthy; jx ++) { %>' +
            '
' +

            '
' +
            '<a href="<%= sde.LiveInfo[jx].url %>"><%= sde.LiveInfo[jx].title.substring(0,10) %>' +
						'
<%= sde.LiveInfo[jx].time%>
' +
						'
<%= sde.LiveInfo[jx].classroom%>
' +
						'
<%= sde.LiveInfo[jx].course %>
' +
            '
' +
						' <% if( sde.LiveInfo[jx].status !=null ){ %>'+
            ' <li style="background-color:<%= sde.LiveInfo[jx].color %>;">' +
            ' <%= sde.LiveInfo[jx].status %>' +
            '
' +
						'<% } %>' +
            '
' +
						'<% } %>' +
		        '<% } %>' +
							'
' +
            '<% } %>',
        daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],

        today = new Date();

    // The actual plugin constructor

    function Plugin(element, options) {
        this.element = $(element);

        this.options = $.extend({}, defaults, options);

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    };

    Plugin.prototype.init = function () {
        // Place initialization logic here
        // You already have access to the DOM element and
        // the options via the instance, e.g. this.element
        // and this.options
        this.weekStart = this.options.weekStart || 1;
        this.days = this.options.msg_days;
        this.months = this.options.msg_months;
        this.msg_today = this.options.msg_today;
        this.msg_events_hdr = this.options.msg_events_header;
        this.events = this.options.events;
        this.url = this.options.url;

        this.live_date = new Date();

        var now = moment();
        this.mm = now.month();
        this.yy = now.year();
        this.today = now.date();
        this.middleDay = now;

        this.renderCalendar(getSevenDays(now));

    };

    Plugin.prototype.renderCalendar = function (daylist) {

        if (this.calendar) {
            $(".timeline").remove();
            $("#accordion_event_table").remove();
        }

        var that = this;
        var elt = tmpl(events_list_template);

        this.calendar = $(timeline_template({
            seven_day: daylist
        }))
            .appendTo(this.element).on({
                click: $.proxy(this.click, this)
            });
        $.ajax({
            type: "POST",
            url: this.url,
            data: {
                "days": _.map(daylist, function (k) {
                    return moment(k).utc().format();
                })

            },
            // crossDomain:true,
            dataType: "json",
            jsonp: false

        }).done(function (da) {

            if (da.length > 0) {

                var days = _.map(daylist, function (k) {
                    return moment(k).utc().format();
                });
                that.events = _.map(days, function (date) {
                    return _.filter(da, function (re) {
                        return moment(re.date).date() == moment(date).date();
                    }
                        );

                });

                var v = {

                    seven_day_events: that.events
                }
                // console.log(v);
                $(elt(v)).appendTo(that.element)

            }

        }).fail(function (jqXHR, textStatus, errorThrown) {
            // console.log(textStatus);
        });

    };

    Plugin.prototype.click = function (e) {
        e.stopPropagation();
        e.preventDefault();
        var target = $(e.target).closest('li');
        if (target.length == 1) {
            if (target.is('.pre')) {

                if (target.is('.fast')) {
                    this.middleDay = moment(this.middleDay).subtract('d', 7);
                    this.renderCalendar(getSevenDays(this.middleDay));
                } else {
                    this.middleDay = moment(this.middleDay).subtract('d', 1);
                    this.renderCalendar(getSevenDays(this.middleDay));
                }
            } else if (target.is('.next')) {

                if (target.is('.fast')) {
                    this.middleDay = moment(this.middleDay).add('d', 7);
                    this.renderCalendar(getSevenDays(this.middleDay));
                } else {
                    this.middleDay = moment(this.middleDay).add('d', 1);
                    this.renderCalendar(getSevenDays(this.middleDay));
                }

            }
        }

    };

    var getSevenDays = function (middleDay) {

        var daylist = new Array();
        var startDay = moment(middleDay).subtract('d', Math.floor(7 / 2));

        _(7).times(function (n) {
            var ss = startDay.add('d', 1);
            daylist.push(moment(ss));

        });
        return daylist;
    };

    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName,
                    new Plugin(this, options));
            }
        });
    }

})(jQuery, window, document);
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    jshint = require('gulp-jshint'),
    mocha = require('gulp-mocha'),
    complexity = require('gulp-complexity'),
    git = require('gulp-git'),
    bump = require('gulp-bump');

gulp.task('complexity', function () {
    gulp.src('lib/**/*.js')
        .pipe(complexity({
            cyclomatic: [5],
            halstead: [16],
            maintainability: [100]
        }));
});

gulp.task('lint', function () {
    gulp.src(['gulpfile.js', 'lib/**/*.js', 'test/**/*.js'])
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(jshint.reporter('fail'));
});

gulp.task('test', function () {
    gulp.src('test/**/*.js', { read: false })
        .pipe(mocha({
            reporter: 'spec',
            bail: true
        }));
});

gulp.task('release', function () {
    var version = require('./package.json').version;

    return gulp.src('./package.json')
        .pipe(git.commit(version))
        .pipe(git.tag(version, version))
        .pipe(git.push("origin", "master"));
});

gulp.task('bump', function () {
    gulp.src('./package.json')
        .pipe(bump({ type: 'build'}))
        .pipe(gulp.dest('./'));
});

gulp.task('watch', function () {
    gulp.watch(['**/*.js', '!node_modules/**/*.js'], ['default']);
});

gulp.task('default', ['lint', 'test']);
gulp.task('tdd', ['default', 'watch']);<commit_msg>Removed bit of gulp config that's not working at the moment.<commit_after>var gulp = require('gulp'),
    jshint = require('gulp-jshint'),
    mocha = require('gulp-mocha'),
    complexity = require('gulp-complexity'),
    git = require('gulp-git'),
    bump = require('gulp-bump');

gulp.task('complexity', function () {
    gulp.src('lib/**/*.js')
        .pipe(complexity({
            cyclomatic: [5],
            halstead: [16],
            maintainability: [100]
        }));
});

gulp.task('lint', function () {
    gulp.src(['gulpfile.js', 'lib/**/*.js', 'test/**/*.js'])
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(jshint.reporter('fail'));
});

gulp.task('test', function () {
    gulp.src('test/**/*.js', { read: false })
        .pipe(mocha({
            reporter: 'spec',
            bail: true
        }));
});

gulp.task('release', function () {
    var version = require('./package.json').version;

    return gulp.src('./package.json')
        .pipe(git.commit(version))
        .pipe(git.tag(version, version));
});

gulp.task('bump', function () {
    gulp.src('./package.json')
        .pipe(bump({ type: 'build'}))
        .pipe(gulp.dest('./'));
});

gulp.task('watch', function () {
    gulp.watch(['**/*.js', '!node_modules/**/*.js'], ['default']);
});

gulp.task('default', ['lint', 'test']);
gulp.task('tdd', ['default', 'watch']);<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const glob = require('glob');
const svgo = require('svgo');
const merge = require('webpack-merge');
const mkdirp = require('mkdirp');
const loaderUtils = require('loader-utils');
const { RawSource } = require('webpack-sources');
const MultiEntryPlugin = require('webpack/lib/MultiEntryPlugin');
const RawModule = require('webpack/lib/RawModule');

// Helpers
const formatOptions = require('./options-formatter');
const generateSVG = require('./generate-svg');
const generateStyles = require('./generate-styles');
const { stripVariables, findVariables } = require('./variable-parser');

// Errors & Warnings
const {
    OptionsMismatchWarning,
    VariablesNotSupportedInLanguageWarning,
    VariablesNotSupportedWithFragmentsWarning
} = require('./errors');

const plugin = {
    name: 'SVGSpritemapPlugin'
};

module.exports = class SVGSpritemapPlugin {
    constructor(pattern, options) {
        this.options = formatOptions(pattern, options);

        // Dependencies
        this.files = [];
        this.directories = [];
    }

    apply(compiler) {
        compiler.hooks.entryOption.tap(plugin, (context, entry) => {
            const { output: outputOptions } = this.options;

            if ( !outputOptions.svg4everybody ) {
                return;
            }

            // This is a little hacky but there's no other way since Webpack
            // doesn't support virtual files (https://github.com/rmarscher/virtual-module-webpack-plugin)
            const helper = {
                file: fs.readFileSync(path.join(__dirname, 'templates/svg4everybody.template.js'), 'utf8'),
                path: path.join(__dirname, '../svg4everybody-helper.js')
            };

            // Write the helper file to disk
            fs.writeFileSync(helper.path, helper.file.replace('/* PLACEHOLDER */', JSON.stringify(outputOptions.svg4everybody)), 'utf8');

            // Append helper to entry
            const applyEntryPlugin = (entries, name = 'main') => {
                const plugin = new MultiEntryPlugin(context, entries, name);
                plugin.apply(compiler);
            };

            if ( typeof entry === 'string' ) {
                applyEntryPlugin([entry, helper.path]);
            } else if ( Array.isArray(entry) ) {
                if ( !entry.includes(helper.path) ) {
                    applyEntryPlugin([...entry, helper.path]);
                }
            } else if ( typeof entry === 'object' && entry !== null ) {
                Object.keys(entry).forEach((name) => {
                    if ( typeof entry[name] === 'string' ) {
                        applyEntryPlugin([entry[name], helper.path], name);
                    } else if ( Array.isArray(entry[name]) ) {
                        if ( !entry[name].includes(helper.path) ) {
                            applyEntryPlugin([...entry[name], helper.path], name);
                        }
                    } else {
                        throw new Error(`Unsupported sub-entry type for svg4everybody helper: '${typeof entry[name]}'`);
                    }
                });
            } else {
                throw new Error(`Unsupported entry type for svg4everybody helper: '${typeof entry}'`);
            }

            return true;
        });

        // Update dependencies when needed
        compiler.hooks.environment.tap(plugin, this.updateDependencies.bind(this));
        compiler.hooks.watchRun.tap(plugin, this.updateDependencies.bind(this));

        // Generate spritemap
        compiler.hooks.make.tapAsync(plugin, (compilation, callback) => {
            const { sprite: spriteOptions, output: outputOptions, styles: stylesOptions } = this.options;

            if ( spriteOptions.generate.view && !spriteOptions.generate.use ) {
                compilation.warnings.push(new OptionsMismatchWarning(`Using sprite.generate.view requires sprite.generate.use to be enabled`));
            }

            if ( spriteOptions.generate.use && !spriteOptions.generate.symbol ) {
                compilation.warnings.push(new OptionsMismatchWarning(`Using sprite.generate.use requires sprite.generate.symbol to be enabled`));
            }

            if ( spriteOptions.generate.title && !spriteOptions.generate.symbol ) {
                compilation.warnings.push(new OptionsMismatchWarning(`Using sprite.generate.title requires sprite.generate.symbol to be enabled`));
            }

            if ( spriteOptions.generate.symbol === true && spriteOptions.generate.view === true ) {
                compilation.warnings.push(new OptionsMismatchWarning(`Both sprite.generate.symbol and sprite.generate.view are set to true which will cause identifier conflicts, use a string value (postfix) for either of these options`));
            }

            // Generate SVG
            generateSVG(this.files, {
                sprite: spriteOptions,
                output: outputOptions
            }).then((spritemap) => {
                if ( !spritemap ) {
                    return callback();
                }

                // Create chunk and add spritemap to compilation.assets
                const sourceChunk = compilation.addChunk(outputOptions.chunk.name);
                compilation.assets[outputOptions.filename] = new RawSource(spritemap);

                // Set up a dummy module that we can add to our source chunk
                // To prevent it from getting cleaned up, this seems to be required
                // to correctly link the spritemap asset to the chunk
                const module = new RawModule('', `${outputOptions.chunk.name}-dummy-module`);
                module.buildInfo = {};
                module.buildMeta = {};
                module.hash = '';
                sourceChunk.addModule(module);

                // Generate styles
                if ( stylesOptions ) {
                    const extension = path.extname(stylesOptions.filename).substring(1).toLowerCase();
                    this.styles = generateStyles(spritemap, {
                        extension: extension,
                        prefix: spriteOptions.prefix,
                        postfix: {
                            symbol: spriteOptions.generate.symbol,
                            view: spriteOptions.generate.view
                        },
                        format: {
                            type: stylesOptions.format,
                            publicPath: (() => {
                                const hashes = this.getSpritemapHashes(compilation);
                                const filename = this.hashFilename(outputOptions.filename, hashes);

                                return `${compilation.outputOptions.publicPath || '/'}${filename}`;
                            })()
                        },
                        variables: stylesOptions.variables
                    });

                    // Emit a warning when variables are detected while the language doesn't support it
                    if ( !['scss', 'sass'].includes(extension) && findVariables(spritemap).length ) {
                        compilation.warnings.push(new VariablesNotSupportedInLanguageWarning(extension));
                    }

                    // Emit a warning when variables are detected while the stylesOptions.format is set to 'fragment'
                    if ( stylesOptions.format === 'fragment' && findVariables(spritemap).length ) {
                        compilation.warnings.push(new VariablesNotSupportedWithFragmentsWarning());
                    }

                    if ( stylesOptions.format === 'fragment' && !spriteOptions.generate.view ) {
                        compilation.warnings.push(new OptionsMismatchWarning(`Using styles.format with value 'fragment' in combination with sprite.generate.view with value false will result in CSS fragments not working correctly`));
                    }

                    // Include warnings received from the style formatters
                    if ( this.styles.warnings.length ) {
                        compilation.warnings = [...compilation.warnings, ...this.styles.warnings];
                    }

                    // Write the styles file before compilation starts to make sure the files
                    // are written to disk before other plugins/loaders (e.g. mini-css-extract-plugin) can use them
                    this.stylesType = this.getStylesType(this.styles.content, stylesOptions.filename);
                    this.writeStylesToDisk(this.styles.content, this.stylesType);

                    if ( typeof this.styles !== 'undefined' && this.stylesType === 'asset' ) {
                        compilation.assets[stylesOptions.filename] = new RawSource(this.styles.content);
                    }
                }

                // Overwrite the spritemap chunk hash to the custom SVG contenthash to make sure
                // webpack notices the changes and prints the stats output again
                compilation.hooks.chunkHash.tap(plugin, (chunk, chunkHash) => {
                    const { output: outputOptions } = this.options;

                    if ( chunk.name !== outputOptions.chunk.name || !spritemap ) {
                        return;
                    }

                    chunkHash.digest = () => this.getContentHash(spritemap);
                });

                // Optimize spritemap SVG/filename
                compilation.hooks.optimizeAssets.tapAsync(plugin, (assets, callback) => {
                    const { output: outputOptions, sprite: spriteOptions } = this.options;

                    // Strip variables from spritemap SVG
                    const stripped = stripVariables(compilation.assets[outputOptions.filename].source());
                    compilation.assets[outputOptions.filename] = new RawSource(stripped);

                    // Rewrite the source chunk files hashes
                    const hashes = this.getSpritemapHashes(compilation);
                    const sourceChunk = compilation.namedChunks.get(outputOptions.chunk.name);
                    sourceChunk.files = sourceChunk.files.map((filename) => {
                        if ( filename !== outputOptions.filename ) {
                            return filename;
                        }

                        return this.hashFilename(filename, hashes);
                    });

                    // Rewrite the compilation.assets hashes for the spritemap asset
                    const hashedAssets = this.rewriteAssetsHashes(outputOptions.filename, compilation.assets, hashes);
                    compilation.assets = hashedAssets.assets;

                    if ( outputOptions.svgo === false ) {
                        return callback();
                    }

                    const SVGOptimizer = new svgo(merge({
                        plugins: [
                            // Disable the removeTitle plugin when title elements should be generated
                            { removeTitle: !spriteOptions.generate.title }
                        ]
                    }, outputOptions.svgo, {
                        plugins: [
                            // Force disable cleanupIDs as the identifiers are to be used to target a specific sprite
                            { cleanupIDs: false }
                        ]
                    }));
                    SVGOptimizer.optimize(assets[hashedAssets.filename].source()).then((output) => {
                        // Update the optimized asset based on the hashed filename
                        compilation.assets[hashedAssets.filename] = new RawSource(output.data);

                        return callback();
                    });
                });

                // Optimize styles filename
                compilation.hooks.optimizeAssets.tapAsync(plugin, (assets, callback) => {
                    const { styles: stylesOptions } = this.options;

                    if ( typeof this.styles === 'undefined' || this.stylesType !== 'asset' ) {
                        return callback();
                    }

                    // Rewrite the compilation.assets hashes for the styles asset
                    const hashedAssets = this.rewriteAssetsHashes(stylesOptions.filename, compilation.assets, this.getStylesHashes(compilation));

                    // Update the compilation assets with the hashed ones
                    compilation.assets = hashedAssets.assets;

                    return callback();
                });

                // Make sure we add the generated SVG as a file to the spritemap chunk
                compilation.hooks.afterOptimizeChunkAssets.tap(plugin, () => {
                    compilation.chunks.forEach((chunk) => {
                        if ( chunk.name !== outputOptions.chunk.name ) {
                            return;
                        }

                        chunk.files.push(outputOptions.filename);
                    });
                });

                callback();
            }).catch((error) => {
                throw new Error(error);
            });
        });

        // Clean up the spritemap chunk
        compiler.hooks.emit.tapAsync(plugin, (compilation, callback) => {
            const { output: outputOptions } = this.options;

            if ( outputOptions.chunk.keep ) {
                return callback();
            }

            compilation.chunks.forEach((chunk) => {
                if ( chunk.name !== outputOptions.chunk.name ) {
                    return;
                }

                delete compilation.assets[chunk.files[0]];
            });

            return callback();
        });

        // Add context dependencies to webpack compilation to make sure watching works correctly
        compiler.hooks.afterCompile.tap(plugin, (compilation) => {
            this.directories.forEach((directory) => {
                compilation.contextDependencies.add(directory);
            });
        });
    }

    updateDependencies() {
        const { input: inputOptions } = this.options;

        this.files = inputOptions.patterns.reduce((accumulator, value) => {
            const files = glob.sync(value, inputOptions.options).map((file) => {
                return path.resolve(file);
            });

            if ( !files.length ) {
                return accumulator;
            }

            // Transform to Set temporarily to remove duplicates
            return [...new Set(accumulator.concat(files))];
        }, []);

        this.directories = inputOptions.patterns.reduce((accumulator, value) => {
            const pattern = value.substring(0, value.lastIndexOf(path.sep));
            const directories = glob.sync(pattern, inputOptions.options).map((directory) => {
                return path.resolve(directory);
            });

            if ( !directories.length ) {
                return accumulator;
            }

            // Transform to Set temporarily to remove duplicates
            return [...new Set(accumulator.concat(directories))];
        }, []);
    }

    getStylesType(styles, filename = '') {
        if ( !styles || !filename ) {
            return;
        }

        if ( path.parse(filename).dir ) {
            return 'dir';
        }

        if ( filename.startsWith('~') ) {
            return 'module';
        }

        return 'asset';
    }

    writeStylesToDisk(styles, type) {
        const { styles: stylesOptions } = this.options;

        const location = {
            'dir': stylesOptions.filename,
            'module': path.resolve(__dirname, '../', stylesOptions.filename.replace('~', ''))
        }[type];

        if ( typeof location === 'undefined' ) {
            return;
        }

        // check is location exist
        const locationExists = fs.existsSync(location);

        // Make sure we don't rewrite the file when it's correct already
        const contents = locationExists && fs.readFileSync(location, 'utf8');
        if ( contents === styles ) {
            return;
        }

        if ( type === 'dir' && !locationExists ) {
            const dirname = path.dirname(location);

            if ( !fs.existsSync(dirname) ) {
                mkdirp.sync(dirname);
            }
        }

        fs.writeFileSync(location, styles, 'utf8');
    }

    rewriteAssetsHashes(filename, assets = {}, hashes = []) {
        if ( !filename || !Object.keys(assets).length || !hashes.length ) {
            return;
        }

        // Update patterns in original filename with hash values accordingly
        const hashedFilename = this.hashFilename(filename, hashes);

        // Update the assets when the filename contained hashes
        if ( hashedFilename !== filename ) {
            assets[hashedFilename] = assets[filename];
            delete assets[filename];
        }

        // Return the resulting (hashed) filename together with the assets
        return {
            filename: hashedFilename,
            assets: assets
        };
    }

    hashFilename(filename, hashes = []) {
        if ( !hashes.length ) {
            return;
        }

        return hashes.reduce((output, hash) => {
            const pattern = new RegExp(hash.pattern, 'ig');
            return output.replace(pattern, hash.value);
        }, filename);
    }

    getSpritemapHashes(compilation) {
        const { output: outputOptions } = this.options;

        if ( !compilation ) {
            return [];
        }

        return [{
            pattern: /\[hash]/,
            value: compilation.getStats().hash
        }, {
            pattern: /\[contenthash]/,
            value: this.getContentHash(compilation.assets[outputOptions.filename].source())
        }];
    }

    getStylesHashes(compilation) {
        const { styles: stylesOptions } = this.options;

        if ( !compilation ) {
            return [];
        }

        return [{
            pattern: /\[hash]/,
            value: compilation.getStats().hash
        }, {
            pattern: /\[contenthash]/,
            value: this.getContentHash(compilation.assets[stylesOptions.filename].source())
        }];
    }

    getContentHash(source) {
        return loaderUtils.getHashDigest(source, 'sha1', 'hex', 16);
    }
};
<commit_msg>Clean up .map files if they exist<commit_after>const fs = require('fs');
const path = require('path');
const glob = require('glob');
const svgo = require('svgo');
const merge = require('webpack-merge');
const mkdirp = require('mkdirp');
const loaderUtils = require('loader-utils');
const { RawSource } = require('webpack-sources');
const MultiEntryPlugin = require('webpack/lib/MultiEntryPlugin');
const RawModule = require('webpack/lib/RawModule');

// Helpers
const formatOptions = require('./options-formatter');
const generateSVG = require('./generate-svg');
const generateStyles = require('./generate-styles');
const { stripVariables, findVariables } = require('./variable-parser');

// Errors & Warnings
const {
    OptionsMismatchWarning,
    VariablesNotSupportedInLanguageWarning,
    VariablesNotSupportedWithFragmentsWarning
} = require('./errors');

const plugin = {
    name: 'SVGSpritemapPlugin'
};

module.exports = class SVGSpritemapPlugin {
    constructor(pattern, options) {
        this.options = formatOptions(pattern, options);

        // Dependencies
        this.files = [];
        this.directories = [];
    }

    apply(compiler) {
        compiler.hooks.entryOption.tap(plugin, (context, entry) => {
            const { output: outputOptions } = this.options;

            if ( !outputOptions.svg4everybody ) {
                return;
            }

            // This is a little hacky but there's no other way since Webpack
            // doesn't support virtual files (https://github.com/rmarscher/virtual-module-webpack-plugin)
            const helper = {
                file: fs.readFileSync(path.join(__dirname, 'templates/svg4everybody.template.js'), 'utf8'),
                path: path.join(__dirname, '../svg4everybody-helper.js')
            };

            // Write the helper file to disk
            fs.writeFileSync(helper.path, helper.file.replace('/* PLACEHOLDER */', JSON.stringify(outputOptions.svg4everybody)), 'utf8');

            // Append helper to entry
            const applyEntryPlugin = (entries, name = 'main') => {
                const plugin = new MultiEntryPlugin(context, entries, name);
                plugin.apply(compiler);
            };

            if ( typeof entry === 'string' ) {
                applyEntryPlugin([entry, helper.path]);
            } else if ( Array.isArray(entry) ) {
                if ( !entry.includes(helper.path) ) {
                    applyEntryPlugin([...entry, helper.path]);
                }
            } else if ( typeof entry === 'object' && entry !== null ) {
                Object.keys(entry).forEach((name) => {
                    if ( typeof entry[name] === 'string' ) {
                        applyEntryPlugin([entry[name], helper.path], name);
                    } else if ( Array.isArray(entry[name]) ) {
                        if ( !entry[name].includes(helper.path) ) {
                            applyEntryPlugin([...entry[name], helper.path], name);
                        }
                    } else {
                        throw new Error(`Unsupported sub-entry type for svg4everybody helper: '${typeof entry[name]}'`);
                    }
                });
            } else {
                throw new Error(`Unsupported entry type for svg4everybody helper: '${typeof entry}'`);
            }

            return true;
        });

        // Update dependencies when needed
        compiler.hooks.environment.tap(plugin, this.updateDependencies.bind(this));
        compiler.hooks.watchRun.tap(plugin, this.updateDependencies.bind(this));

        // Generate spritemap
        compiler.hooks.make.tapAsync(plugin, (compilation, callback) => {
            const { sprite: spriteOptions, output: outputOptions, styles: stylesOptions } = this.options;

            if ( spriteOptions.generate.view && !spriteOptions.generate.use ) {
                compilation.warnings.push(new OptionsMismatchWarning(`Using sprite.generate.view requires sprite.generate.use to be enabled`));
            }

            if ( spriteOptions.generate.use && !spriteOptions.generate.symbol ) {
                compilation.warnings.push(new OptionsMismatchWarning(`Using sprite.generate.use requires sprite.generate.symbol to be enabled`));
            }

            if ( spriteOptions.generate.title && !spriteOptions.generate.symbol ) {
                compilation.warnings.push(new OptionsMismatchWarning(`Using sprite.generate.title requires sprite.generate.symbol to be enabled`));
            }

            if ( spriteOptions.generate.symbol === true && spriteOptions.generate.view === true ) {
                compilation.warnings.push(new OptionsMismatchWarning(`Both sprite.generate.symbol and sprite.generate.view are set to true which will cause identifier conflicts, use a string value (postfix) for either of these options`));
            }

            // Generate SVG
            generateSVG(this.files, {
                sprite: spriteOptions,
                output: outputOptions
            }).then((spritemap) => {
                if ( !spritemap ) {
                    return callback();
                }

                // Create chunk and add spritemap to compilation.assets
                const sourceChunk = compilation.addChunk(outputOptions.chunk.name);
                compilation.assets[outputOptions.filename] = new RawSource(spritemap);

                // Set up a dummy module that we can add to our source chunk
                // To prevent it from getting cleaned up, this seems to be required
                // to correctly link the spritemap asset to the chunk
                const module = new RawModule('', `${outputOptions.chunk.name}-dummy-module`);
                module.buildInfo = {};
                module.buildMeta = {};
                module.hash = '';
                sourceChunk.addModule(module);

                // Generate styles
                if ( stylesOptions ) {
                    const extension = path.extname(stylesOptions.filename).substring(1).toLowerCase();
                    this.styles = generateStyles(spritemap, {
                        extension: extension,
                        prefix: spriteOptions.prefix,
                        postfix: {
                            symbol: spriteOptions.generate.symbol,
                            view: spriteOptions.generate.view
                        },
                        format: {
                            type: stylesOptions.format,
                            publicPath: (() => {
                                const hashes = this.getSpritemapHashes(compilation);
                                const filename = this.hashFilename(outputOptions.filename, hashes);

                                return `${compilation.outputOptions.publicPath || '/'}${filename}`;
                            })()
                        },
                        variables: stylesOptions.variables
                    });

                    // Emit a warning when variables are detected while the language doesn't support it
                    if ( !['scss', 'sass'].includes(extension) && findVariables(spritemap).length ) {
                        compilation.warnings.push(new VariablesNotSupportedInLanguageWarning(extension));
                    }

                    // Emit a warning when variables are detected while the stylesOptions.format is set to 'fragment'
                    if ( stylesOptions.format === 'fragment' && findVariables(spritemap).length ) {
                        compilation.warnings.push(new VariablesNotSupportedWithFragmentsWarning());
                    }

                    if ( stylesOptions.format === 'fragment' && !spriteOptions.generate.view ) {
                        compilation.warnings.push(new OptionsMismatchWarning(`Using styles.format with value 'fragment' in combination with sprite.generate.view with value false will result in CSS fragments not working correctly`));
                    }

                    // Include warnings received from the style formatters
                    if ( this.styles.warnings.length ) {
                        compilation.warnings = [...compilation.warnings, ...this.styles.warnings];
                    }

                    // Write the styles file before compilation starts to make sure the files
                    // are written to disk before other plugins/loaders (e.g. mini-css-extract-plugin) can use them
                    this.stylesType = this.getStylesType(this.styles.content, stylesOptions.filename);
                    this.writeStylesToDisk(this.styles.content, this.stylesType);

                    if ( typeof this.styles !== 'undefined' && this.stylesType === 'asset' ) {
                        compilation.assets[stylesOptions.filename] = new RawSource(this.styles.content);
                    }
                }

                // Overwrite the spritemap chunk hash to the custom SVG contenthash to make sure
                // webpack notices the changes and prints the stats output again
                compilation.hooks.chunkHash.tap(plugin, (chunk, chunkHash) => {
                    const { output: outputOptions } = this.options;

                    if ( chunk.name !== outputOptions.chunk.name || !spritemap ) {
                        return;
                    }

                    chunkHash.digest = () => this.getContentHash(spritemap);
                });

                // Optimize spritemap SVG/filename
                compilation.hooks.optimizeAssets.tapAsync(plugin, (assets, callback) => {
                    const { output: outputOptions, sprite: spriteOptions } = this.options;

                    // Strip variables from spritemap SVG
                    const stripped = stripVariables(compilation.assets[outputOptions.filename].source());
                    compilation.assets[outputOptions.filename] = new RawSource(stripped);

                    // Rewrite the source chunk files hashes
                    const hashes = this.getSpritemapHashes(compilation);
                    const sourceChunk = compilation.namedChunks.get(outputOptions.chunk.name);
                    sourceChunk.files = sourceChunk.files.map((filename) => {
                        if ( filename !== outputOptions.filename ) {
                            return filename;
                        }

                        return this.hashFilename(filename, hashes);
                    });

                    // Rewrite the compilation.assets hashes for the spritemap asset
                    const hashedAssets = this.rewriteAssetsHashes(outputOptions.filename, compilation.assets, hashes);
                    compilation.assets = hashedAssets.assets;

                    if ( outputOptions.svgo === false ) {
                        return callback();
                    }

                    const SVGOptimizer = new svgo(merge({
                        plugins: [
                            // Disable the removeTitle plugin when title elements should be generated
                            { removeTitle: !spriteOptions.generate.title }
                        ]
                    }, outputOptions.svgo, {
                        plugins: [
                            // Force disable cleanupIDs as the identifiers are to be used to target a specific sprite
                            { cleanupIDs: false }
                        ]
                    }));
                    SVGOptimizer.optimize(assets[hashedAssets.filename].source()).then((output) => {
                        // Update the optimized asset based on the hashed filename
                        compilation.assets[hashedAssets.filename] = new RawSource(output.data);

                        return callback();
                    });
                });

                // Optimize styles filename
                compilation.hooks.optimizeAssets.tapAsync(plugin, (assets, callback) => {
                    const { styles: stylesOptions } = this.options;

                    if ( typeof this.styles === 'undefined' || this.stylesType !== 'asset' ) {
                        return callback();
                    }

                    // Rewrite the compilation.assets hashes for the styles asset
                    const hashedAssets = this.rewriteAssetsHashes(stylesOptions.filename, compilation.assets, this.getStylesHashes(compilation));

                    // Update the compilation assets with the hashed ones
                    compilation.assets = hashedAssets.assets;

                    return callback();
                });

                // Make sure we add the generated SVG as a file to the spritemap chunk
                compilation.hooks.afterOptimizeChunkAssets.tap(plugin, () => {
                    compilation.chunks.forEach((chunk) => {
                        if ( chunk.name !== outputOptions.chunk.name ) {
                            return;
                        }

                        chunk.files.push(outputOptions.filename);
                    });
                });

                callback();
            }).catch((error) => {
                throw new Error(error);
            });
        });

        // Clean up the spritemap chunk
        compiler.hooks.emit.tapAsync(plugin, (compilation, callback) => {
            const { output: outputOptions } = this.options;
            const assets = compilation.assets;

            if ( outputOptions.chunk.keep ) {
                return callback();
            }

            compilation.chunks.forEach((chunk) => {
                const sourceMapStr = `${chunk.files[0]}.map`;

                if ( chunk.name !== outputOptions.chunk.name ) {
                    return;
                }

                delete assets[chunk.files[0]];

                if (assets[sourceMapStr]) {
                    delete compilation.assets[sourceMapStr];
                }
            });

            return callback();
        });

        // Add context dependencies to webpack compilation to make sure watching works correctly
        compiler.hooks.afterCompile.tap(plugin, (compilation) => {
            this.directories.forEach((directory) => {
                compilation.contextDependencies.add(directory);
            });
        });
    }

    updateDependencies() {
        const { input: inputOptions } = this.options;

        this.files = inputOptions.patterns.reduce((accumulator, value) => {
            const files = glob.sync(value, inputOptions.options).map((file) => {
                return path.resolve(file);
            });

            if ( !files.length ) {
                return accumulator;
            }

            // Transform to Set temporarily to remove duplicates
            return [...new Set(accumulator.concat(files))];
        }, []);

        this.directories = inputOptions.patterns.reduce((accumulator, value) => {
            const pattern = value.substring(0, value.lastIndexOf(path.sep));
            const directories = glob.sync(pattern, inputOptions.options).map((directory) => {
                return path.resolve(directory);
            });

            if ( !directories.length ) {
                return accumulator;
            }

            // Transform to Set temporarily to remove duplicates
            return [...new Set(accumulator.concat(directories))];
        }, []);
    }

    getStylesType(styles, filename = '') {
        if ( !styles || !filename ) {
            return;
        }

        if ( path.parse(filename).dir ) {
            return 'dir';
        }

        if ( filename.startsWith('~') ) {
            return 'module';
        }

        return 'asset';
    }

    writeStylesToDisk(styles, type) {
        const { styles: stylesOptions } = this.options;

        const location = {
            'dir': stylesOptions.filename,
            'module': path.resolve(__dirname, '../', stylesOptions.filename.replace('~', ''))
        }[type];

        if ( typeof location === 'undefined' ) {
            return;
        }

        // check is location exist
        const locationExists = fs.existsSync(location);

        // Make sure we don't rewrite the file when it's correct already
        const contents = locationExists && fs.readFileSync(location, 'utf8');
        if ( contents === styles ) {
            return;
        }

        if ( type === 'dir' && !locationExists ) {
            const dirname = path.dirname(location);

            if ( !fs.existsSync(dirname) ) {
                mkdirp.sync(dirname);
            }
        }

        fs.writeFileSync(location, styles, 'utf8');
    }

    rewriteAssetsHashes(filename, assets = {}, hashes = []) {
        if ( !filename || !Object.keys(assets).length || !hashes.length ) {
            return;
        }

        // Update patterns in original filename with hash values accordingly
        const hashedFilename = this.hashFilename(filename, hashes);

        // Update the assets when the filename contained hashes
        if ( hashedFilename !== filename ) {
            assets[hashedFilename] = assets[filename];
            delete assets[filename];
        }

        // Return the resulting (hashed) filename together with the assets
        return {
            filename: hashedFilename,
            assets: assets
        };
    }

    hashFilename(filename, hashes = []) {
        if ( !hashes.length ) {
            return;
        }

        return hashes.reduce((output, hash) => {
            const pattern = new RegExp(hash.pattern, 'ig');
            return output.replace(pattern, hash.value);
        }, filename);
    }

    getSpritemapHashes(compilation) {
        const { output: outputOptions } = this.options;

        if ( !compilation ) {
            return [];
        }

        return [{
            pattern: /\[hash]/,
            value: compilation.getStats().hash
        }, {
            pattern: /\[contenthash]/,
            value: this.getContentHash(compilation.assets[outputOptions.filename].source())
        }];
    }

    getStylesHashes(compilation) {
        const { styles: stylesOptions } = this.options;

        if ( !compilation ) {
            return [];
        }

        return [{
            pattern: /\[hash]/,
            value: compilation.getStats().hash
        }, {
            pattern: /\[contenthash]/,
            value: this.getContentHash(compilation.assets[stylesOptions.filename].source())
        }];
    }

    getContentHash(source) {
        return loaderUtils.getHashDigest(source, 'sha1', 'hex', 16);
    }
};
<|endoftext|>


<commit_before>
var loadLists = () => new Promise((resolve,reject) => {
	wlAPI.http.lists.all()
		.done( (dat,statusCode) => resolve(dat, statusCode) )
		.fail( (a,b,c) => reject(a,b,c) );
});

var loadTasks = ListId => new Promise((resolve,reject) => {
	wlAPI.http.tasks.forList(ListId)
		.done( (dat,statusCode) => resolve(dat, statusCode) )
		.fail( (a,b,c) => reject(a,b,c) );
});

var renderTaskList = (tasksDat, listId) => {
	var list_content = '';
	tasksDat.reverse().forEach( task => {
		list_content += `<li class="task" data-task-id="${task.id}"><div>${task.title}</div></li>`;
	});
	document.querySelector('#tasklist > ul').innerHTML = list_content;
	document.querySelector('#tasklist').dataset["listId"] = listId;
};

var initTaskList = listsDat => {
	loadTasks(listsDat[0].id)
		.then( tasksDat => renderTaskList(tasksDat, listsDat[0].id) )
		.catch( e => console.error(e.stack) );
};

var initListSelect = () => {
	loadLists()
		.then( listsDat => {
			var listsSelect = document.querySelector("#lists_list");

			listsDat.forEach( list => {
				listsSelect.innerHTML += `<option value="${list.id}">${list.title}</option>`;
			});

			listsSelect.addEventListener('change', () => {
				document.querySelector('#tasklist > ul').innerHTML = `<li><div>Loading...</div></li>`;
				loadTasks(listsSelect.value)
					.then( tasksDat => {
						renderTaskList(tasksDat, listsSelect.value);
					})
					.catch( e => console.error(e) );
			});

			initTaskList(listsDat);
	})
	.catch( (a,b,c) => console.error(a,b,c) );
};

var initUserInfo = () => {
	wlAPI.http.user.all()
		.done(user => {
			document.querySelector("#header").innerHTML = `
				`;
			document.querySelector("#hello").innerHTML = `Hi, ${user.name}, what are you doing today?`;
		})
		.fail((a,b,c) => {
			console.error(a,b,c);
		})
};

var initCreateTask = () => {
	var newtaskInput = document.querySelector('#newtask-title');
	if(newtaskInput)
		newtaskInput.addEventListener('keydown', (e) => {
			if(e.keyCode == 13) {
				var taskData = {
					'list_id': parseInt(document.querySelector('#tasklist').dataset["listId"]),
					'title': document.querySelector('#newtask-title').value
				};
				wlAPI.http.tasks.create(taskData)
					.done((task) => {
						var newtaskli = document.createElement("li");
						newtaskli.className = "task";
						newtaskli.dataset["taskId"] = task.id;
						var inNewtask = document.createElement("div");
						inNewtask.innerHTML = task.title;

						newtaskli.appendChild(inNewtask);

						document.querySelector('#tasklist > ul').insertBefore(newtaskli, document.querySelector('.task'));
						document.querySelector('#newtask-title').value = "";
					})
					.fail((a,b,c) => {
						console.error(a,b,c);
					})

			}
		}, false)
};

wlAPI.initialized.done( () => {
	initListSelect();
	initUserInfo();
});

window.onload = initCreateTask;

<commit_msg>Refactor<commit_after>let _ = dom => document.querySelector(dom);

let updateList = listId =>
	wlAPI.http.tasks.forList(listId)
		.done( tasksDat => renderTaskList(tasksDat, listId))
		.fail( e => console.error(e.stack) );

let addTask = taskData =>
	wlAPI.http.tasks.create(taskData)
		.done( task => {
			let parser = new DOMParser();
			let newTaskDoc = parser.parseFromString(`

${task.title}

`, "text/html");

			_('#tasklist > ul').insertBefore(newTaskDoc.querySelector('li.task'), _('.task'));
			_('#newtask-title').value = "";
		}).fail( e => console.error(e.stack) );

let renderTaskList = (tasksDat, listId) => {
	let list_content = '';
	tasksDat.reverse().forEach( task => {
		list_content += `<li class="task" data-task-id="${task.id}"><div>${task.title}</div></li>`;
	});
	_('#tasklist > ul').innerHTML = list_content;
	_('#tasklist').dataset["listId"] = listId;
};

let renderListList = listsDat => {
	let listsSelect = _("#lists_list");

	listsDat.forEach( list => {
		listsSelect.innerHTML += `<option value="${list.id}">${list.title}</option>`;
	});

	listsSelect.addEventListener('change', () => {
		_('#tasklist > ul').innerHTML = `<li><div>Loading...</div></li>`;
		updateList(listsSelect.value);
	});
};

// ================

let initListAndMenu = () => {
	wlAPI.http.lists.all()
		.done( listsDat => {
			renderListList(listsDat);
			updateList(listsDat[0].id); // init Task List
		}).fail( e => console.error(e.stack) );
};

let initUserInfo = () => {
	wlAPI.http.user.all()
		.done(user => {
			_("#header").innerHTML = `<img src="http://a.wunderlist.com/api/v1/avatar?user_id=${user.id}" alt="user avatar" />`;
			_("#hello").innerHTML = `Hi, ${user.name}, what are you doing today?`;
		}).fail( e => console.error(e.stack) );
};

let initInputBox = () =>
	_('#newtask-title').addEventListener('keydown', event => {
		if(event.keyCode == 13) // when click enter
			addTask({
				'list_id': parseInt(_('#tasklist').dataset["listId"]),
				'title': _('#newtask-title').value
			});
	}, false);

window.onload = () => {
	wlAPI.initialized.done( () => {
		initListAndMenu();
		initUserInfo();
		initInputBox();
	});
};

<|endoftext|>


<commit_before>/*
 /   Testing the configuration files.
/                                      */

/* Dependencies */
var fs = require('fs')
var path = require('path')
var should = require('should')
var expect = require('chai').expect

/* Application */
var Dev = require('../config/dev')
var Prod = require('../config/prod')

/* Tests */
describe('Configuration files.', function () {
  it('Configuration files should be JSON objects.', function (done) {
    expect(typeof (Dev)).to.equal('object')
    expect(typeof (Prod)).to.equal('object')
    done()
  })

  it('Configuration files should contain CKAN (default) instance.', function (done) {
    expect(Dev).to.have.a.property('CkanInstance')
    expect(Prod).to.have.a.property('CkanInstance')
    done()
  })

})
<commit_msg>added test for database schema<commit_after>/*
 /   Testing the configuration files.
/                                      */

/* Dependencies */
var fs = require('fs')
var path = require('path')
var should = require('should')
var expect = require('chai').expect

/* Application */
var Dev = require('../config/dev')
var Prod = require('../config/prod')

/* Tests */
describe('Configuration files.', function () {
  it('Configuration files should be JSON objects.', function (done) {
    expect(typeof (Dev)).to.equal('object')
    expect(typeof (Prod)).to.equal('object')
    done()
  })

  it('Configuration files should contain CKAN (default) instance.', function (done) {
    expect(Dev).to.have.a.property('CkanInstance')
    expect(Prod).to.have.a.property('CkanInstance')
    done()
  })

  it('Configuration files should contain database properties.', function (done) {
    expect(Dev).to.have.a.property('database')
    expect(Prod).to.have.a.property('database')

    expect(Dev.database[0]).to.have.a.property('name')
    expect(Dev.database[0]).to.have.a.property('schema')
    expect(Prod.database[0]).to.have.a.property('name')
    expect(Prod.database[0]).to.have.a.property('schema')
    done()
  })

})
<|endoftext|>