<commit_before>var rimraf = require("rimraf");
var fs = require("fs-extra");
var util = require("util");

util._extend({
  encoding: "utf8",
  timeout: 0,
  maxBuffer: false,
  killSignal: "SIGTERM",
  cwd: null,
  env: null
});

var parseBuildPlatforms = function(argumentPlatform) {
  // this will make it build no platform when the platform option is specified
  // without a value which makes argumentPlatform into a boolean
  var inputPlatforms = argumentPlatform || process.platform + ";" + process.arch;

  // Do some scrubbing to make it easier to match in the regexes bellow
  inputPlatforms = inputPlatforms.replace("darwin", "mac");
  inputPlatforms = inputPlatforms.replace(/;ia|;x|;arm/, "");

  var buildAll = /^all$/.test(inputPlatforms);

  var buildPlatforms = {
    mac: /mac/.test(inputPlatforms) || buildAll,
    win: /win/.test(inputPlatforms) || buildAll,
    linux32: /linux32/.test(inputPlatforms) || buildAll,
    linux64: /linux64/.test(inputPlatforms) || buildAll
  };

  return buildPlatforms;
};

module.exports = function(grunt) {
  "use strict";

  var buildPlatforms = parseBuildPlatforms(grunt.option("platforms"));
  var currentVersion = grunt.file.readJSON("package.json").version;

  // buildPlatforms = parseBuildPlatforms(grunt.option("platforms"))
  var packageJson = grunt.file.readJSON("package.json");
  var _VERSION = packageJson.version;

  grunt.log.writeln("Building " + packageJson.version);

  grunt.initConfig({
    // Wipe out previous builds and test reporting.
    clean: {
      all: [
        "build/komanda-source",
        "build/releases/**",
        "node_modules",
        "vendor"
      ],
      some: [
        "build/komanda-source",
        "build/releases/**"
      ]
    },

    handlebars: {
      compile: {
        options: {
          amd: true,
          namespace: "Templates",
          partialsUseNamespace: true,
          processName: function(filePath) {
            var file = filePath.replace(/.*\/(\w+)\.hbs/, "$1");
            return file;
          }
        },
        files:{
          "app/templates.js": ["app/templates/*.hbs"]
        }
      }
    },

    // Run your source code through JSHint"s defaults.
    jshint: {
      jshintrc: ".jshint",
      options: {
        smarttabs: true,
        proto: true,
        eqnull: true,
        quotmark: "double"
      },
      all: [
        "app/**/*.js",
        "!app/templates.js",
        "!app/lib/deps/**/*.js"
      ]
    },

    // This task uses James Burke"s excellent r.js AMD builder to take all
    // modules and concatenate them into a single file.
    requirejs: {
      release: {
        options: {
          mainConfigFile: "app/config.js",
          generateSourceMaps: false,
          include: ["main"],
          out: "build/komanda-source/komanda.js",
          optimize: "uglify2",

          // Since we bootstrap with nested `require` calls this option allows
          // R.js to find them.
          findNestedDependencies: true,

          // Include a minimal AMD implementation shim.
          name: "almond",

          // Setting the base url to the distribution directory allows the
          // Uglify minification process to correctly map paths for Source
          // Maps.
          baseUrl: "build/komanda-source/app",

          // Wrap everything in an IIFE.
          wrap: true,

          // Do not preserve any license comments when working with source
          // maps.  These options are incompatible.
          preserveLicenseComments: false
        }
      }
    },

    // This task simplifies working with CSS inside Backbone Boilerplate
    // projects.  Instead of manually specifying your stylesheets inside the
    // HTML, you can use `@imports` and this task will concatenate only those
    // paths.
    styles: {
      // Out the concatenated contents of the following styles into the below
      // development file path.
      "build/komanda-source/komanda.css": {
        // Point this to where your `index.css` file is location.
        src: "app/styles/index.css",

        // The relative path to use for the @imports.
        paths: ["app/styles"],

        // Rewrite image paths during release to be relative to the `img`
        // directory.
        // forceRelative: [ "/app/images/", "/app/fonts" ]
      }
    },

    // Minify the distribution CSS.
    cssmin: {
      release: {
        files: {
          "build/komanda-source/komanda.css": ["build/komanda-source/komanda.css"]
        }
      }
    },

    server: {
      options: {
        host: "0.0.0.0",
        port: 8000
      },

      development: {},

      release: {
        options: {
          prefix: "build/komanda-source"
        }
      },

      test: {
        options: {
          forever: false,
          port: 8001
        }
      }
    },

    processhtml: {
      release: {
        files: {
          "build/komanda-source/index.html": ["index.html"]
        }
      }
    },

    // Move vendor and app logic during a build.
    copy: {
      release: {
        files: [
          { src: "package.json", dest: "build/komanda-source/package.json" },
          { src: ["app/**"], dest: "build/komanda-source/" },
          { src: "vendor/**", dest: "build/komanda-source/" },
          { src: "themes/**", dest: "build/komanda-source/" }
        ]
      }
    },

    compress: {
      release: {
        options: {
          archive: "build/komanda-source/komanda.js.gz"
        },

        files: ["build/komanda-source/komanda.js"]
      }
    },

    nodewebkit: {
      options: {
        version: "0.10.2",
        appName: "Komanda",
        appVersion: "1.0.0.beta",
        buildDir: "./build",
        cacheDir: "./build/cache",
        platforms: ["osx", "win", "linux32", "linux64"],
        macIcns: "app/styles/images/logo/komanda.icns",
        macCredits: "credits.html"
      },
      // src: ["./**/*"],
      src: [
        "./build/komanda-source/**/*",
        // "./node_modules/irc/**/*",
      ]
    },

    exec: {
      win: {
        cmd: '"build/cache/<%= nodewebkit.options.version %>/win/nw.exe" .'
      },
      mac: {
        cmd: "build/cache/<%= nodewebkit.options.version %>/osx/node-webkit.app/Contents/MacOS/node-webkit ."
      },
      linux32: {
        cmd: "build/cache/<%= nodewebkit.options.version %>/linux32/nw ."
      },
      linux64: {
        cmd: "build/cache/<%= nodewebkit.options.version %>/linux64/nw ."
      },
      createDmg: {
        cmd: "dist/mac/yoursway-create-dmg/create-dmg --volname \"Komanda " + currentVersion + "\" --background ./dist/mac/background.png --window-size 480 540 --icon-size 128 --app-drop-link 240 370 --icon \"Komanda\" 240 110 ./build/releases/Komanda/osx/Komanda-" + currentVersion + "-Mac.dmg ./build/releases/Komanda/osx/"
      },
      createWinInstall: {
        cmd: "makensis dist/windows/installer.nsi"
      },
      createWinUpdate: {
        cmd: "makensis dist/windows/updater.nsi"
      }
    },

    shell: {
      npm: {
        options: {
          stdout: false,
          stderr: false,
          stdin: false
        },
        command: "npm install"
      },
      runnw: {
        options: {
          stdout: false,
          stderr: false,
          stdin: false
        },
        command: "./build/cache/0.10.2/osx/node-webkit.app/Contents/MacOS/node-webkit . > /dev/null 2>&1"
      },

      linux64: {
        options: {
          stdout: false,
          stderr: false,
          stdin: false,
        },
        command: "./build/cache/0.10.2/linux64/nw ./build/komanda-source/"
      },

      linux32: {
        options: {
          stdout: false,
          stderr: false,
          stdin: false,
        },
        command: "./build/cache/0.10.2/linux32/nw ./build/komanda-source/"
      },

      create_dmg: {
        options: {
          stdout: true
        },
        command: "./dist/mac/yoursway-create-dmg/create-dmg --volname \"Komanda " + _VERSION + "\" --background ./dist/mac/background.png --window-size 480 540 --icon-size 128 --app-drop-link 240 370 --icon \"Komanda\" 240 110 ./build/releases/Komanda/osx/Komanda-" + _VERSION + ".dmg ./build/releases/Komanda/osx/"
      }
    },

    revision: {
      options: {
        property: "revision",
        ref: "HEAD",
        short: true
      }
    },

    replace: {
      revision: {
        options: {
          patterns: [{
            match: "GIT_REVISION",
            replacement: "<%= revision %>"
          }]
        },
        files: [{
          src: "build/komanda-source/app/main.js",
          dest: "build/komanda-source/app/main.js"
        }]
      }
    }
  });

  grunt.registerTask("cleanBuildDir", "remove unneeded files from the build dir.", function() {
    fs.mkdirSync("build/komanda-source/images");
    fs.mkdirSync("build/komanda-source/fonts");

    fs.copySync("build/komanda-source/app/styles/images", "build/komanda-source/images");
    fs.copySync("build/komanda-source/app/styles/fonts", "build/komanda-source/fonts");
    fs.copySync("build/komanda-source/app/sounds", "build/komanda-source/sounds");
    fs.copySync("build/komanda-source/vendor/bower/octicons/octicons", "build/komanda-source/fonts/octicons/");
    fs.copySync("node_modules/irc/", "build/komanda-source/node_modules/irc/");
    fs.copySync("node_modules/gitter-marked/", "build/komanda-source/node_modules/gitter-marked/");
    fs.copySync("node_modules/highlight.js/", "build/komanda-source/node_modules/highlight.js/");

    rimraf.sync("build/komanda-source/app", function(error) {
      console.log(error);
    });

    rimraf.sync("build/komanda-source/vendor", function(error) {
      console.log(error);
    });

  });

  // Grunt contribution tasks.
  grunt.loadNpmTasks("grunt-contrib-clean");
  grunt.loadNpmTasks("grunt-contrib-jshint");
  grunt.loadNpmTasks("grunt-contrib-cssmin");
  grunt.loadNpmTasks("grunt-contrib-copy");
  grunt.loadNpmTasks("grunt-contrib-compress");

  // Third-party tasks.
  grunt.loadNpmTasks("grunt-exec");
  grunt.loadNpmTasks("grunt-npm-install");
  grunt.loadNpmTasks("grunt-open");
  grunt.loadNpmTasks("grunt-node-webkit-builder");
  grunt.loadNpmTasks("grunt-bbb-server");
  grunt.loadNpmTasks("grunt-processhtml");
  grunt.loadNpmTasks("grunt-contrib-handlebars");
  grunt.loadNpmTasks("grunt-contrib-requirejs");
  grunt.loadNpmTasks("grunt-bbb-styles");
  grunt.loadNpmTasks("grunt-shell");
  grunt.loadNpmTasks("grunt-git-revision");
  grunt.loadNpmTasks("grunt-replace");

  grunt.registerTask("default", [

  ]);

  grunt.registerTask("build", function(platforms) {
    var targetPlatforms = parseBuildPlatforms(platforms);
    // Overwrite initial nodewebkit.options.platforms array with the
    // platforms returned by parseBuildPlatforms
    var targetPlatformsArray = [];
    Object.keys(targetPlatforms).forEach(function(target) {
      if (targetPlatforms[target]) {
        // grunt-node-webkit-builder doesn't understand `mac`,
        // so map it to `osx` before adding it to the array
        if (target === "mac") {
          target = "osx";
        }
        targetPlatformsArray.push(target);
      }
    });
    grunt.config.set("nodewebkit.options.platforms", targetPlatformsArray);

    grunt.task.run([
      "clean:some",
      //"npm-install",
      "jshint",
      "processhtml",
      "copy",
      "revision",
      "replace:revision",
      "requirejs",
      "styles",
      "cssmin",
      "cleanBuildDir",
      "nodewebkit"
    ]);
  });

  grunt.registerTask("run", function() {
    var start = parseBuildPlatforms();
    if(start.win){
      grunt.task.run("run:win");
    }else if(start.mac){
      grunt.task.run("run:mac");
    }else if(start.linux32){
      grunt.task.run("run:linux32");
    }else if(start.linux64){
      grunt.task.run("run:linux64");
    }else{
      grunt.log.writeln("OS not supported.");
    }
  });

  grunt.registerTask("run:mac", [
    "default",
    "shell:runnw"
  ]);

  grunt.registerTask("run:win", [
    "default",
    "exec:win"
  ]);

  grunt.registerTask("run:linux32", [
    "default",
    "copy",
    "exec:linux32"
  ]);

  grunt.registerTask("run:linux64", [
    "default",
    "copy",
    "exec:linux64"
  ]);
};
<commit_msg>Use application logo on windows<commit_after>var rimraf = require("rimraf");
var fs = require("fs-extra");
var util = require("util");

util._extend({
  encoding: "utf8",
  timeout: 0,
  maxBuffer: false,
  killSignal: "SIGTERM",
  cwd: null,
  env: null
});

var parseBuildPlatforms = function(argumentPlatform) {
  // this will make it build no platform when the platform option is specified
  // without a value which makes argumentPlatform into a boolean
  var inputPlatforms = argumentPlatform || process.platform + ";" + process.arch;

  // Do some scrubbing to make it easier to match in the regexes bellow
  inputPlatforms = inputPlatforms.replace("darwin", "mac");
  inputPlatforms = inputPlatforms.replace(/;ia|;x|;arm/, "");

  var buildAll = /^all$/.test(inputPlatforms);

  var buildPlatforms = {
    mac: /mac/.test(inputPlatforms) || buildAll,
    win: /win/.test(inputPlatforms) || buildAll,
    linux32: /linux32/.test(inputPlatforms) || buildAll,
    linux64: /linux64/.test(inputPlatforms) || buildAll
  };

  return buildPlatforms;
};

module.exports = function(grunt) {
  "use strict";

  var buildPlatforms = parseBuildPlatforms(grunt.option("platforms"));
  var currentVersion = grunt.file.readJSON("package.json").version;

  // buildPlatforms = parseBuildPlatforms(grunt.option("platforms"))
  var packageJson = grunt.file.readJSON("package.json");
  var _VERSION = packageJson.version;

  grunt.log.writeln("Building " + packageJson.version);

  grunt.initConfig({
    // Wipe out previous builds and test reporting.
    clean: {
      all: [
        "build/komanda-source",
        "build/releases/**",
        "node_modules",
        "vendor"
      ],
      some: [
        "build/komanda-source",
        "build/releases/**"
      ]
    },

    handlebars: {
      compile: {
        options: {
          amd: true,
          namespace: "Templates",
          partialsUseNamespace: true,
          processName: function(filePath) {
            var file = filePath.replace(/.*\/(\w+)\.hbs/, "$1");
            return file;
          }
        },
        files:{
          "app/templates.js": ["app/templates/*.hbs"]
        }
      }
    },

    // Run your source code through JSHint"s defaults.
    jshint: {
      jshintrc: ".jshint",
      options: {
        smarttabs: true,
        proto: true,
        eqnull: true,
        quotmark: "double"
      },
      all: [
        "app/**/*.js",
        "!app/templates.js",
        "!app/lib/deps/**/*.js"
      ]
    },

    // This task uses James Burke"s excellent r.js AMD builder to take all
    // modules and concatenate them into a single file.
    requirejs: {
      release: {
        options: {
          mainConfigFile: "app/config.js",
          generateSourceMaps: false,
          include: ["main"],
          out: "build/komanda-source/komanda.js",
          optimize: "uglify2",

          // Since we bootstrap with nested `require` calls this option allows
          // R.js to find them.
          findNestedDependencies: true,

          // Include a minimal AMD implementation shim.
          name: "almond",

          // Setting the base url to the distribution directory allows the
          // Uglify minification process to correctly map paths for Source
          // Maps.
          baseUrl: "build/komanda-source/app",

          // Wrap everything in an IIFE.
          wrap: true,

          // Do not preserve any license comments when working with source
          // maps.  These options are incompatible.
          preserveLicenseComments: false
        }
      }
    },

    // This task simplifies working with CSS inside Backbone Boilerplate
    // projects.  Instead of manually specifying your stylesheets inside the
    // HTML, you can use `@imports` and this task will concatenate only those
    // paths.
    styles: {
      // Out the concatenated contents of the following styles into the below
      // development file path.
      "build/komanda-source/komanda.css": {
        // Point this to where your `index.css` file is location.
        src: "app/styles/index.css",

        // The relative path to use for the @imports.
        paths: ["app/styles"],

        // Rewrite image paths during release to be relative to the `img`
        // directory.
        // forceRelative: [ "/app/images/", "/app/fonts" ]
      }
    },

    // Minify the distribution CSS.
    cssmin: {
      release: {
        files: {
          "build/komanda-source/komanda.css": ["build/komanda-source/komanda.css"]
        }
      }
    },

    server: {
      options: {
        host: "0.0.0.0",
        port: 8000
      },

      development: {},

      release: {
        options: {
          prefix: "build/komanda-source"
        }
      },

      test: {
        options: {
          forever: false,
          port: 8001
        }
      }
    },

    processhtml: {
      release: {
        files: {
          "build/komanda-source/index.html": ["index.html"]
        }
      }
    },

    // Move vendor and app logic during a build.
    copy: {
      release: {
        files: [
          { src: "package.json", dest: "build/komanda-source/package.json" },
          { src: ["app/**"], dest: "build/komanda-source/" },
          { src: "vendor/**", dest: "build/komanda-source/" },
          { src: "themes/**", dest: "build/komanda-source/" }
        ]
      }
    },

    compress: {
      release: {
        options: {
          archive: "build/komanda-source/komanda.js.gz"
        },

        files: ["build/komanda-source/komanda.js"]
      }
    },

    nodewebkit: {
      options: {
        version: "0.10.2",
        appName: "Komanda",
        appVersion: "1.0.0.beta",
        buildDir: "./build",
        cacheDir: "./build/cache",
        platforms: ["osx", "win", "linux32", "linux64"],
        macIcns: "app/styles/images/logo/komanda.icns",
        macCredits: "credits.html",
        winIco: "app/styles/images/logo/komanda.ico"
      },
      // src: ["./**/*"],
      src: [
        "./build/komanda-source/**/*",
        // "./node_modules/irc/**/*",
      ]
    },

    exec: {
      win: {
        cmd: '"build/cache/<%= nodewebkit.options.version %>/win/nw.exe" .'
      },
      mac: {
        cmd: "build/cache/<%= nodewebkit.options.version %>/osx/node-webkit.app/Contents/MacOS/node-webkit ."
      },
      linux32: {
        cmd: "build/cache/<%= nodewebkit.options.version %>/linux32/nw ."
      },
      linux64: {
        cmd: "build/cache/<%= nodewebkit.options.version %>/linux64/nw ."
      },
      createDmg: {
        cmd: "dist/mac/yoursway-create-dmg/create-dmg --volname \"Komanda " + currentVersion + "\" --background ./dist/mac/background.png --window-size 480 540 --icon-size 128 --app-drop-link 240 370 --icon \"Komanda\" 240 110 ./build/releases/Komanda/osx/Komanda-" + currentVersion + "-Mac.dmg ./build/releases/Komanda/osx/"
      },
      createWinInstall: {
        cmd: "makensis dist/windows/installer.nsi"
      },
      createWinUpdate: {
        cmd: "makensis dist/windows/updater.nsi"
      }
    },

    shell: {
      npm: {
        options: {
          stdout: false,
          stderr: false,
          stdin: false
        },
        command: "npm install"
      },
      runnw: {
        options: {
          stdout: false,
          stderr: false,
          stdin: false
        },
        command: "./build/cache/0.10.2/osx/node-webkit.app/Contents/MacOS/node-webkit . > /dev/null 2>&1"
      },

      linux64: {
        options: {
          stdout: false,
          stderr: false,
          stdin: false,
        },
        command: "./build/cache/0.10.2/linux64/nw ./build/komanda-source/"
      },

      linux32: {
        options: {
          stdout: false,
          stderr: false,
          stdin: false,
        },
        command: "./build/cache/0.10.2/linux32/nw ./build/komanda-source/"
      },

      create_dmg: {
        options: {
          stdout: true
        },
        command: "./dist/mac/yoursway-create-dmg/create-dmg --volname \"Komanda " + _VERSION + "\" --background ./dist/mac/background.png --window-size 480 540 --icon-size 128 --app-drop-link 240 370 --icon \"Komanda\" 240 110 ./build/releases/Komanda/osx/Komanda-" + _VERSION + ".dmg ./build/releases/Komanda/osx/"
      }
    },

    revision: {
      options: {
        property: "revision",
        ref: "HEAD",
        short: true
      }
    },

    replace: {
      revision: {
        options: {
          patterns: [{
            match: "GIT_REVISION",
            replacement: "<%= revision %>"
          }]
        },
        files: [{
          src: "build/komanda-source/app/main.js",
          dest: "build/komanda-source/app/main.js"
        }]
      }
    }
  });

  grunt.registerTask("cleanBuildDir", "remove unneeded files from the build dir.", function() {
    fs.mkdirSync("build/komanda-source/images");
    fs.mkdirSync("build/komanda-source/fonts");

    fs.copySync("build/komanda-source/app/styles/images", "build/komanda-source/images");
    fs.copySync("build/komanda-source/app/styles/fonts", "build/komanda-source/fonts");
    fs.copySync("build/komanda-source/app/sounds", "build/komanda-source/sounds");
    fs.copySync("build/komanda-source/vendor/bower/octicons/octicons", "build/komanda-source/fonts/octicons/");
    fs.copySync("node_modules/irc/", "build/komanda-source/node_modules/irc/");
    fs.copySync("node_modules/gitter-marked/", "build/komanda-source/node_modules/gitter-marked/");
    fs.copySync("node_modules/highlight.js/", "build/komanda-source/node_modules/highlight.js/");

    rimraf.sync("build/komanda-source/app", function(error) {
      console.log(error);
    });

    rimraf.sync("build/komanda-source/vendor", function(error) {
      console.log(error);
    });

  });

  // Grunt contribution tasks.
  grunt.loadNpmTasks("grunt-contrib-clean");
  grunt.loadNpmTasks("grunt-contrib-jshint");
  grunt.loadNpmTasks("grunt-contrib-cssmin");
  grunt.loadNpmTasks("grunt-contrib-copy");
  grunt.loadNpmTasks("grunt-contrib-compress");

  // Third-party tasks.
  grunt.loadNpmTasks("grunt-exec");
  grunt.loadNpmTasks("grunt-npm-install");
  grunt.loadNpmTasks("grunt-open");
  grunt.loadNpmTasks("grunt-node-webkit-builder");
  grunt.loadNpmTasks("grunt-bbb-server");
  grunt.loadNpmTasks("grunt-processhtml");
  grunt.loadNpmTasks("grunt-contrib-handlebars");
  grunt.loadNpmTasks("grunt-contrib-requirejs");
  grunt.loadNpmTasks("grunt-bbb-styles");
  grunt.loadNpmTasks("grunt-shell");
  grunt.loadNpmTasks("grunt-git-revision");
  grunt.loadNpmTasks("grunt-replace");

  grunt.registerTask("default", [

  ]);

  grunt.registerTask("build", function(platforms) {
    var targetPlatforms = parseBuildPlatforms(platforms);
    // Overwrite initial nodewebkit.options.platforms array with the
    // platforms returned by parseBuildPlatforms
    var targetPlatformsArray = [];
    Object.keys(targetPlatforms).forEach(function(target) {
      if (targetPlatforms[target]) {
        // grunt-node-webkit-builder doesn't understand `mac`,
        // so map it to `osx` before adding it to the array
        if (target === "mac") {
          target = "osx";
        }
        targetPlatformsArray.push(target);
      }
    });
    grunt.config.set("nodewebkit.options.platforms", targetPlatformsArray);

    grunt.task.run([
      "clean:some",
      //"npm-install",
      "jshint",
      "processhtml",
      "copy",
      "revision",
      "replace:revision",
      "requirejs",
      "styles",
      "cssmin",
      "cleanBuildDir",
      "nodewebkit"
    ]);
  });

  grunt.registerTask("run", function() {
    var start = parseBuildPlatforms();
    if(start.win){
      grunt.task.run("run:win");
    }else if(start.mac){
      grunt.task.run("run:mac");
    }else if(start.linux32){
      grunt.task.run("run:linux32");
    }else if(start.linux64){
      grunt.task.run("run:linux64");
    }else{
      grunt.log.writeln("OS not supported.");
    }
  });

  grunt.registerTask("run:mac", [
    "default",
    "shell:runnw"
  ]);

  grunt.registerTask("run:win", [
    "default",
    "exec:win"
  ]);

  grunt.registerTask("run:linux32", [
    "default",
    "copy",
    "exec:linux32"
  ]);

  grunt.registerTask("run:linux64", [
    "default",
    "copy",
    "exec:linux64"
  ]);
};
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Mark Eschbach
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

module.exports = function( grunt ){
	var config = {
		bower: { install: { options: { copy: false, verbose: true } } },
		contact : {},
		migrate: {
			options: {
				verbose: true
			}
		},
		uglify: {}
	};

	grunt.initConfig( config );
	grunt.loadNpmTasks( "grunt-contrib-concat" );
	grunt.loadNpmTasks( "grunt-contrib-uglify" );
	grunt.loadNpmTasks( "grunt-bower-task" );
	grunt.registerTask( "default", [] );
}
<commit_msg>Adding task for simple setup<commit_after>/*
 * Copyright 2015 Mark Eschbach
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

module.exports = function( grunt ){
	var config = {
		pkg: grunt.file.readJSON('package.json'),
		bower: { install: { options: { copy: false, verbose: true } } },
		contact : {},
		migrate: {
			options: {
				verbose: true
			}
		},
		uglify: {}
	};

	grunt.initConfig( config );
	grunt.loadNpmTasks( "grunt-contrib-concat" );
	grunt.loadNpmTasks( "grunt-contrib-uglify" );
	grunt.loadNpmTasks( "grunt-bower-task" );
	grunt.loadNpmTasks( "grunt-db-migrate" );

	grunt.registerTask( "setup", ["bower:install", "migrate:up" ] );
	grunt.registerTask( "default", [] );
}
<|endoftext|>


<commit_before>var incAns = 0;
var diff = "";
let toGuess = "";
let guessed = "";
let give = "";
let onPage = "";
let h = "";
let m = "";
let e = "";
findAWord("Easy");
findAWord("Med");
findAWord("Hard");
// console.log(easyWord);
// console.log(medWord);
// console.log(hardWord);
document.getElementById("characters").innerHTML = "Guessed Characters: ";
let jjj = [5,4,3,2,1];

function Validate(val) {

    if (!val.match(/^[a-zA-Z]+$/) || val.length > 1) {
        alert('Only a single alphabet character are allowed');
        return false;
    }

    // else if (val.length > 1) {
    //     alert('Only single alphabet characters are allowed');
    //     return false;
    // }
    return true;
}

function incorrectChangeMan() {
    incAns++;
    if (incAns === 1) {
        document.getElementById("hangman").innerHTML = "--------
 | \t |
 | O
 |
 |
 |
 |
 |
 |
 |____";
    } else if (incAns === 2) {
        document.getElementById("hangman").innerHTML = "--------
 | \t |
 | O
 | |
 |
 |
 |
 |
 |
 |____";

    } else if (incAns === 3) {
        document.getElementById("hangman").innerHTML = "--------
 | \t |
 | O
 | /|
 |
 |
 |
 |
 |
 |____";

    } else if (incAns === 4) {
        document.getElementById("hangman").innerHTML = "--------
 | \t |
 | O
 | /|\\
 |
 |
 |
 |
 |
 |____";

    } else if (incAns === 5) {
        document.getElementById("hangman").innerHTML = "--------
 | \t |
 | O
 | /|\\
 | \t |
 |
 |
 |
 |
 |____";

    } else if (incAns === 6) {
        document.getElementById("hangman").innerHTML = "--------
 | \t |
 | O
 | /|\\
 | \t |
 | /
 |
 |
 |
 |____";

    } else if (incAns === 7) {
        document.getElementById("hangman").innerHTML = "--------
 | \t |
 | O
 | /|\\
 |  |
 | / \\
 |
 |
 |
 |____";
    }
    else if (incAns === 8) {
        alert("YOU LOST, refresh");
    }
}

function startGame(k) {
    // console.log(easyWord);
    // console.log(medWord);
    // console.log(hardWord);
    console.log("Pur", e, m, h);
    if (k === "Easy") {
        toGuess = e;
    } else if (k === "Med") {
        toGuess = m;
    } else {
        toGuess = h;
    }

    for (let i = 0; i < toGuess.length; i++) {
        give += "_ ";
    }
    console.log(toGuess);
    document.getElementById("message").innerHTML = give;

}

function findAWord(k) {
    var requestURL = "https://raw.githubusercontent.com/nichharp/nichharp.github.io/master/words_alpha.txt";
    var request = new XMLHttpRequest();
    request.open('GET', requestURL);
    request.responseType = "text";
    request.send();
    let cur = "";
    request.onload = function () {
        requestData = request.response;
        requestData = requestData.split("\n");
        // console.log(requestData);
        do {
            let rand = Math.floor(Math.random() * 370101 + 1);
            if (k === "Easy") {
                if (requestData[rand].length > 8) {
                    console.log(requestData[rand]);
                    e = (requestData[rand]);
                    cur = (requestData[rand]);

                }
            } else if (k === "Med") {
                if (requestData[rand].length < 8 && requestData[rand].length > 4) {
                    console.log(requestData[rand]);
                    m = (requestData[rand]);
                    cur = (requestData[rand]);

                }
            } else {
                if (requestData[rand].length < 5) {
                    console.log(requestData[rand]);
                    h = (requestData[rand]);
                    cur = (requestData[rand]);

                }
            }
        } while (cur === "");

    };
    // // console.log(re);
    // cur = request.onload;
    // return cur;#
    // pur = cur;

}

function makeAGuess(isVal) {
    let guess = document.getElementById('guess').value;
    guess = guess.toLowerCase();
    if (isVal === true) {
        console.log(toGuess.indexOf(guess));

        if (guessed.indexOf(guess) > -1) {
            alert("You have guessed this character before. Try another");
            console.log("Guessed Before");
        }
        if (toGuess.indexOf(guess) > -1) {
            onPage = document.getElementById("message").innerHTML; //has a space at the end  //onPage is the _ _ _ _ _ _

            console.log("correct guess");              // tell me its a correct guess
            console.log(onPage);
            let instancesOf = [];

            for (let j = 0; j < toGuess.length; j++) {
                if (instancesOf.includes(toGuess.indexOf(guess, j)) === false) {
                    instancesOf.push(toGuess.indexOf(guess, j));
                }
            }
            if (instancesOf.indexOf(-1)!==-1) {
                instancesOf.splice(instancesOf.indexOf(-1) , 1);
            }

            let onPageArray = [];
            for (let i = 0; i < onPage.length; i++) {
                onPageArray.push(onPage.charAt(i));
            }
            console.log(onPageArray);
            console.log(instancesOf ,instancesOf.length);

            for (let k = 0; k < instancesOf.length; k++) {
                onPageArray.splice(instancesOf[k] * 2, 1, guess);
            }
            onPage = onPageArray.toString();
            onPage = onPage.replace(/,/g, "");
            guessed += guess;
            console.log(onPage);

            // console.log(onPage);
            // onPage = document.getElementById("message").innerHTML;  //onPage is the _ _ _ _ _ _
            // // onPage = onPage.replace(/ /g, "");
            // onPage = onPage.replace(/↵/g, "");

            // console.log(onPage);
            // let onPageArray = [];

            // console.log(onPage);
            // console.log(toGuess.indexOf(guess));
            // console.log(guess);
            // console.log(onPageArray);

            // console.log(onPageArray);

            // onPage = onPageArray.toString();
            // // console.log(onPage);

            // onPage = onPage.replace(/,/g, "");
            // console.log(onPage);
            // // console.log(guessed);
            // console.log(guessed);

            // console.log(toGuess.indexOf(guess));
            // } while ((toGuess.indexOf(guess) !== -1));

            // onPageArray = onPage.split("");
            // console.log(onPageArray);

            // onPageArray.splice(toGuess.indexOf(guess), 1, guess);
            // console.log(onPageArray);
            // onPage = onPageArray.toString();
            // console.log(onPage);

            // onPage = onPage.replace(",", "");
            // console.log(onPage);

            document.getElementById("message").innerHTML = onPage;                      //need to change the _ _ _ _ shows the guess _ _ a _ _ _
            // if (onPageArray === toGuess)
        }
        else {
            incorrectChangeMan();
            console.log("wrong guess");
        }
        document.getElementById("characters").innerHTML += guess;
    } else {

    }
    if (document.getElementById("message").innerHTML.replace(/ /g, "").replace(/_/g, "") === toGuess) {
        alert("YOU WIN!!!");
    }

}

<commit_msg>Final Commit for Hangman Changes<commit_after>var incAns = 0;
var diff = "";
let toGuess = "";
let guessed = "";
let give = "";
let onPage = "";
let h = "";
let m = "";
let e = "";
findAWord("Easy");
findAWord("Med");
findAWord("Hard");
// console.log(easyWord);
// console.log(medWord);
// console.log(hardWord);
document.getElementById("characters").innerHTML = "Guessed Characters: ";

function Validate(val) {

    if (!val.match(/^[a-zA-Z]+$/) || val.length > 1) {
        alert('Only a single alphabet character are allowed');
        return false;
    }

    // else if (val.length > 1) {
    //     alert('Only single alphabet characters are allowed');
    //     return false;
    // }
    return true;
}

function incorrectChangeMan() {
    incAns++;
    if (incAns === 1) {
        document.getElementById("hangman").innerHTML = "--------
 | \t |
 | O
 |
 |
 |
 |
 |
 |
 |____";
    } else if (incAns === 2) {
        document.getElementById("hangman").innerHTML = "--------
 | \t |
 | O
 | |
 |
 |
 |
 |
 |
 |____";

    } else if (incAns === 3) {
        document.getElementById("hangman").innerHTML = "--------
 | \t |
 | O
 | /|
 |
 |
 |
 |
 |
 |____";

    } else if (incAns === 4) {
        document.getElementById("hangman").innerHTML = "--------
 | \t |
 | O
 | /|\\
 |
 |
 |
 |
 |
 |____";

    } else if (incAns === 5) {
        document.getElementById("hangman").innerHTML = "--------
 | \t |
 | O
 | /|\\
 | \t |
 |
 |
 |
 |
 |____";

    } else if (incAns === 6) {
        document.getElementById("hangman").innerHTML = "--------
 | \t |
 | O
 | /|\\
 | \t |
 | /
 |
 |
 |
 |____";

    } else if (incAns === 7) {
        document.getElementById("hangman").innerHTML = "--------
 | \t |
 | O
 | /|\\
 |  |
 | / \\
 |
 |
 |
 |____";
    }
    else if (incAns === 8) {
        alert("YOU LOST, the correct answer was "+ toGuess +", refresh");
    }
}

function startGame(k) {
    // console.log(easyWord);
    // console.log(medWord);
    // console.log(hardWord);
    console.log("Pur", e, m, h);
    if (k === "Easy") {
        toGuess = e;
    } else if (k === "Med") {
        toGuess = m;
    } else {
        toGuess = h;
    }
    console.log(toGuess , toGuess.length);
    toGuess = toGuess.slice(0,-1)
    for (let i = 0; i < toGuess.length; i++) {
        give += "_ ";
    }
    console.log(toGuess , toGuess.length, toGuess.split(""),);
    document.getElementById("message").innerHTML = give;

}

function findAWord(k) {
    var requestURL = "https://raw.githubusercontent.com/nichharp/nichharp.github.io/master/words_alpha.txt";
    var request = new XMLHttpRequest();
    request.open('GET', requestURL);
    request.responseType = "text";
    request.send();
    let cur = "";
    request.onload = function () {
        requestData = request.response;
        requestData = requestData.split("\n");
        // console.log(requestData);
        do {
            let rand = Math.floor(Math.random() * 370101 + 1);
            if (k === "Easy") {
                if (requestData[rand].length > 8) {
                    console.log(requestData[rand]);
                    e = (requestData[rand]);
                    cur = (requestData[rand]);

                }
            } else if (k === "Med") {
                if (requestData[rand].length < 8 && requestData[rand].length > 4) {
                    console.log(requestData[rand]);
                    m = (requestData[rand]);
                    cur = (requestData[rand]);

                }
            } else {
                if (requestData[rand].length < 5) {
                    console.log(requestData[rand]);
                    h = (requestData[rand]);
                    cur = (requestData[rand]);

                }
            }
        } while (cur === "");

    };
    // // console.log(re);
    // cur = request.onload;
    // return cur;#
    // pur = cur;

}

function makeAGuess(isVal) {
    let guess = document.getElementById('guess').value;
    guess = guess.toLowerCase();
    if (isVal === true) {
        console.log(toGuess.indexOf(guess));

        if (guessed.indexOf(guess) > -1) {
            alert("You have guessed this character before. Try another");
            console.log("Guessed Before");
        }
        if (toGuess.indexOf(guess) > -1) {
            onPage = document.getElementById("message").innerHTML; //has a space at the end  //onPage is the _ _ _ _ _ _

            console.log("correct guess");              // tell me its a correct guess
            console.log(onPage);
            let instancesOf = [];

            for (let j = 0; j < toGuess.length; j++) {
                if (instancesOf.includes(toGuess.indexOf(guess, j)) === false) {
                    instancesOf.push(toGuess.indexOf(guess, j));
                }
            }
            if (instancesOf.indexOf(-1)!==-1) {
                instancesOf.splice(instancesOf.indexOf(-1) , 1);
            }

            let onPageArray = [];
            for (let i = 0; i < onPage.length; i++) {
                onPageArray.push(onPage.charAt(i));
            }
            console.log(onPageArray);
            console.log(instancesOf ,instancesOf.length);

            for (let k = 0; k < instancesOf.length; k++) {
                onPageArray.splice(instancesOf[k] * 2, 1, guess);
            }
            onPage = onPageArray.toString();
            onPage = onPage.replace(/,/g, "");
            guessed += guess;
            console.log(onPage);

            // console.log(onPage);
            // onPage = document.getElementById("message").innerHTML;  //onPage is the _ _ _ _ _ _
            // // onPage = onPage.replace(/ /g, "");
            // onPage = onPage.replace(/↵/g, "");

            // console.log(onPage);
            // let onPageArray = [];

            // console.log(onPage);
            // console.log(toGuess.indexOf(guess));
            // console.log(guess);
            // console.log(onPageArray);

            // console.log(onPageArray);

            // onPage = onPageArray.toString();
            // // console.log(onPage);

            // onPage = onPage.replace(/,/g, "");
            // console.log(onPage);
            // // console.log(guessed);
            // console.log(guessed);

            // console.log(toGuess.indexOf(guess));
            // } while ((toGuess.indexOf(guess) !== -1));

            // onPageArray = onPage.split("");
            // console.log(onPageArray);

            // onPageArray.splice(toGuess.indexOf(guess), 1, guess);
            // console.log(onPageArray);
            // onPage = onPageArray.toString();
            // console.log(onPage);

            // onPage = onPage.replace(",", "");
            // console.log(onPage);

            document.getElementById("message").innerHTML = onPage;                      //need to change the _ _ _ _ shows the guess _ _ a _ _ _
            // if (onPageArray === toGuess)
        }
        else {
            incorrectChangeMan();
            console.log("wrong guess");
        }
        document.getElementById("characters").innerHTML += guess;
    } else {

    }
    if (document.getElementById("message").innerHTML.replace(/ /g, "").replace(/_/g, "") === toGuess) {
        alert("YOU WIN!!!");
    }

}

<|endoftext|>


<commit_before>
import React from "react";
import {createStore} from "redux";

import {leanReducer, connectLean} from "../src/lean";

import {render} from "./helpers";

describe("handler context", () => {
    test("has state from initial state", () => {
        const spy = jest.fn();
        const store = createStore(leanReducer);
        let handler = null;

        let Hello = ({name, setName}) => {
            handler = setName;
            return
Hello {name}
;
        };

        Hello = connectLean({
            scope: "ascope",
            getInitialState() {
                return {name: "from initial"};
            },
            setName() {
                spy(this.state.name);
                this.setState({name: "from handler"});
            },
        })(Hello);

        render(store, Hello);
        handler();
        expect(spy).toHaveBeenLastCalledWith("from initial");
    });
});

<commit_msg>test handlers: state not overridden by mapstate<commit_after>
import React from "react";
import {createStore} from "redux";

import {leanReducer, connectLean} from "../src/lean";

import {render} from "./helpers";

describe("handler context", () => {
    test("has state from initial state", () => {
        const spy = jest.fn();
        const store = createStore(leanReducer);
        let handler = null;

        let Hello = ({name, setName}) => {
            handler = setName;
            return
Hello {name}
;
        };

        Hello = connectLean({
            scope: "ascope",
            getInitialState() {
                return {name: "from initial"};
            },
            setName() {
                spy(this.state.name);
                this.setState({name: "from handler"});
            },
        })(Hello);

        render(store, Hello);
        handler();
        expect(spy).toHaveBeenLastCalledWith("from initial");
    });

    test("state is not overridden by map state", () => {
        const spy = jest.fn();
        const store = createStore(leanReducer);
        let handler = null;

        let Hello = ({name, setName}) => {
            handler = setName;
            return
Hello {name}
;
        };

        Hello = connectLean({
            scope: "ascope",
            getInitialState() {
                return {name: "from initial"};
            },
            mapState() {
                return {name: "from mapState"};
            },
            setName() {
                spy(this.state.name);
                this.setState({name: "from handler"});
            },
        })(Hello);

        render(store, Hello);
        handler();
        expect(spy).toHaveBeenLastCalledWith("from initial");
    });

});

<|endoftext|>


<commit_before>/*
	Endless: A bidirectional, React infinite scroll component.
	Based on ReactList (https://github.com/orgsync/react-list)
*/

/* global define, module, require, setTimeout, clearTimeout, window */
/* jshint -W116 */ // Don't warn about single-line if's.

(function(root, factory) {
	if (typeof define === 'function' && define.amd) {
		define(['react'], factory);
	} else if (typeof exports !== 'undefined') {
		module.exports = factory(require('react'));
	} else {
		root.Endless = factory(root.React);
	}
})(this, function(React) {
	'use strict';

	var buildReactElement = function(jsonml) {
		if (!Array.isArray(jsonml)) {
			return jsonml;
		}

		if (jsonml.length > 1 &&
			(typeof jsonml[1] !== 'object' || Array.isArray(jsonml[1]))
		) {
			jsonml.splice(1, 0, null);
		}

		return React.createElement.apply(React, jsonml.map(buildReactElement));
	};

	var requestAnimationFrame =
		(typeof window !== 'undefined' && window.requestAnimationFrame) ||
		function(cb) {
			return setTimeout(cb, 16);
		};

	var cancelAnimationFrame =
		(typeof window !== 'undefined' && window.cancelAnimationFrame) ||
		clearTimeout;

	var isEqualSubset = function(a, b) {
		for (var key in a)
			if (b[key] !== a[key]) return false;
		return true;
	};

	var isEqual = function(a, b) {
		return isEqualSubset(a, b) && isEqualSubset(b, a);
	};

	return React.createClass({
		getDefaultProps: function() {
			return {
				items: [],
				margin: 2000,
				atTop: false,
				atBottom: false,
				onScroll: function( /* key, above, below */ ) {},
				onMount: function( /* event */ ) {},
				onUnmount: function() {}
			};
		},

		getInitialState: function() {
			this.lastState = this.lastState ||  { jumpToIndex: null, offset: 0 };

			if (this.props.items.length) {
				if (this.props.atTop) {
					this.lastState.jumpToIndex = 0;
					this.lastState.position = 'top';
				} else if (this.props.atBottom) {
					this.lastState.jumpToIndex = this.props.items.length - 1;
					this.lastState.position = 'bottom';
				} else {
					this.lastState.jumpToIndex = 0;
					this.lastState.position = buildReactElement(this.props.items[0]).key;
				}
			}

			return {
				itemHeight: 25,
				columns: 1,
				topReached: this.props.atTop,
				bottomReached: this.props.atBottom,
				topRemoved: 0,
				bottomRemoved: 0
			};
		},

		update: function() {
			if (this.lastState.jumpToIndex !== null) {
				this.scrollTo(this.lastState.jumpToIndex, this.lastState.offset);
				this.lastState.jumpToIndex = null;
			}

			var items = this.props.items,
				itemsEl = this.refs.items.getDOMNode(),
				itemEls = itemsEl.children,
				itemHeight = this.state.itemHeight,
				viewTop = this.getScroll(),
				viewHeight = this.getViewportHeight(),
				viewBottom = viewTop + viewHeight,
				elBottom = this.getDOMNode().scrollHeight,
				last = this.lastState,
				position, i, offset, above, below;

			if (!itemEls.length) return;

			itemHeight = this.state.itemHeight = (
				(this.getBottom(itemEls[itemEls.length - 1]) - this.getTop(itemEls[0])) / itemEls.length
			) || 10;

			if (this.state.bottomReached && !this.state.bottomRemoved && viewBottom >= elBottom) {
				position = 'bottom';
				offset = 0;
				above = viewHeight / itemHeight;
				below = 0;
			} else if (this.state.topReached && !this.state.topRemoved && viewTop <= 0) {
				position = 'top';
				offset = 0;
				above = 0;
				below = viewHeight / itemHeight;
			} else {
				for (i = 0; i < itemEls.length; i++) {
					offset = itemEls[i].offsetTop + itemEls[i].scrollHeight - viewTop;
					if (offset >= 0) break;
				}
				if (i == itemEls.length) i--;

				position = buildReactElement(items[i]).key; // building in case it is JSONML
				if (viewTop < itemEls[0].offsetTop) {
					offset = viewTop - itemEls[0].offsetTop;
					above = -offset / itemHeight;
				} else {
					above = 0;
				}
				below = Math.max(0, Math.max(
					viewHeight / itemHeight, (viewBottom - itemEls[itemEls.length - 1].offsetTop) / itemHeight // view far below rendered items
				) - above);
			}

			above = Math.round(above);
			below = Math.round(below);

			if (last.position !== position || last.above !== above || last.below !== below) {
				last.position = position;
				last.offset = offset;
				last.above = above;
				last.below = below;
				this.afid = requestAnimationFrame(this.update);
				this.props.onScroll(position, above, below);
			} else if(last.offset !== offset) {
				this.afid = requestAnimationFrame(this.update);
			} else {
				this.stid = setTimeout(this.update, 200);
			}
		},

		componentDidMount: function() {
			this.update();
			this.props.onMount();
		},

		componentWillUnmount: function() {
			cancelAnimationFrame(this.afid);
			clearTimeout(this.stid);
			this.props.onUnmount();
		},

		shouldComponentUpdate: function(props, state) {
			if (isEqual(this.props, props) && isEqual(this.state, state)) return false;
			return true;
		},

		componentWillReceiveProps: function(nextProps) {
			this.setState({
				topReached: this.state.topReached || nextProps.atTop,
				bottomReached: this.state.bottomReached || nextProps.atBottom
			});
		},

		componentDidUpdate: function(prevProps) {
			if (this.lastState.jumpToIndex !== null) return;

			var prevItems = prevProps.items.map(buildReactElement),
				items = this.props.items.map(buildReactElement),
				jumpRequired, newIndex = null,
				newMetrics, i,
				topAdded, topRemoved, bottomAdded, bottomRemoved;

			if (!items.length || !prevItems.length) return;

			newMetrics = [].slice.call(this.refs.items.getDOMNode().children).map(function(itemEl) {
				return {
					top: this.getTop(itemEl),
					bottom: this.getBottom(itemEl)
				};
			}.bind(this));

			if (newMetrics && this.metrics && items.length && prevItems.length) {
				for (i = 0; i < items.length && items[i].key != prevItems[0].key; i++);
				topAdded = (i == items.length) ? 0 : newMetrics[i].top - newMetrics[0].top;

				for (i = 0; i < prevItems.length && prevItems[i].key != items[0].key; i++);
				topRemoved = (i == prevItems.length) ? 0 : this.metrics[i].top - this.metrics[0].top;

				for (i = items.length - 1; i >= 0 && items[i].key != prevItems[prevItems.length - 1].key; i--);
				bottomAdded = (i < 0) ? 0 : newMetrics[items.length - 1].bottom - newMetrics[i].bottom;

				for (i = prevItems.length - 1; i >= 0 && prevItems[i].key != items[items.length - 1].key; i--);
				bottomRemoved = (i < 0) ? 0 : this.metrics[prevItems.length - 1].bottom - this.metrics[i].bottom;

				//		console.log(topRemoved, topAdded, bottomRemoved, bottomAdded);

				this.setState({
					topRemoved: Math.max(0, this.state.topRemoved + topRemoved - topAdded),
					bottomRemoved: Math.max(0, this.state.bottomRemoved + bottomRemoved - bottomAdded)
				});
			}

			//	console.log('Rendered', items[0].key, 'through', items[items.length-1].key,
			//				'Removed space ', this.state.topRemoved, this.state.bottomRemoved);
			this.metrics = newMetrics;

			if (items[0].key != prevItems[0].key) jumpRequired = true;
			if (prevProps.topReached != this.props.topReached) jumpRequired = true;

			if (jumpRequired) {
				if (this.lastState.position == 'top') {
					newIndex = 0;
				} else if (this.lastState.position == 'bottom') {
					newIndex = items.length - 1;
				} else
					for (i = 0; i < items.length; i++) {
						if (items[i].key == this.lastState.position) {
							newIndex = i;
							break;
						}
					}

				if (newIndex === null) {
					newIndex = 0;
					console.log('couldnt find ', this.lastState.position, 'in', items[0].key, items[items.length - 1].key);
				}

				this.lastState.jumpToIndex = newIndex;
			}

		},

		getTop: function(el) {
			return el.getBoundingClientRect().top - parseFloat(window.getComputedStyle(el).marginTop);
		},

		getBottom: function(el) {
			return el.getBoundingClientRect().bottom + parseFloat(window.getComputedStyle(el).marginBottom);
		},

		getScrollParent: function() {
			for (var el = this.getDOMNode(); el; el = el.parentElement) {
				var overflowY = window.getComputedStyle(el).overflowY;
				if (overflowY === 'auto' || overflowY === 'scroll') return el;
			}
			return window;
		},

		// Get scroll position relative to the top of the list.
		getScroll: function() {
			var scrollParent = this.getScrollParent();
			var el = this.getDOMNode();
			if (scrollParent === el) {
				return el.scrollTop;
			} else if (scrollParent === window) {
				return -el.getBoundingClientRect().top;
			} else {
				return scrollParent.scrollTop - el.offsetTop;
			}
		},

		setScroll: function(y) {
			var scrollParent = this.getScrollParent(),
				el = this.getDOMNode();
			if (scrollParent != el) y += el.offsetTop;
			if (scrollParent === window) return window.scrollTo(0, y);
			scrollParent.scrollTop = y;
		},

		getViewportHeight: function() {
			var scrollParent = this.getScrollParent();
			return scrollParent === window ? scrollParent.innerHeight : scrollParent.clientHeight;
		},

		scrollTo: function(index, offset) {
			var y = this.refs.items.getDOMNode().children[index].offsetTop + offset;

			//	console.log(
			//		"scrolling from", this.getScroll(), "to",
			//		this.refs.items.getDOMNode().children[index].offsetTop, offset
			//	);
			this.setScroll(y);
		},

		render: function() {
			return buildReactElement(['div', {
					style: {
						position: 'relative'
					}
				},
				['div', {
					style: {
						height: this.state.topRemoved + (this.state.topReached ? 0 : this.props.margin)
					}
				}],
				['div', {
					ref: 'items'
				}].concat(this.props.items), ['div', {
					style: {
						height: this.state.bottomRemoved + (this.state.bottomReached ? 0 : this.props.margin)
					}
				}]
			]);
		}
	});
});
<commit_msg>Fixes for when items are hidden or floating<commit_after>/*
	Endless: A bidirectional, React infinite scroll component.
	Based on ReactList (https://github.com/orgsync/react-list)
*/

/* global define, module, require, setTimeout, clearTimeout, window */
/* jshint -W116 */ // Don't warn about single-line if's.

(function(root, factory) {
	if (typeof define === 'function' && define.amd) {
		define(['react'], factory);
	} else if (typeof exports !== 'undefined') {
		module.exports = factory(require('react'));
	} else {
		root.Endless = factory(root.React);
	}
})(this, function(React) {
	'use strict';

	var buildReactElement = function(jsonml) {
		if (!Array.isArray(jsonml)) {
			return jsonml;
		}

		if (jsonml.length > 1 &&
			(typeof jsonml[1] !== 'object' || Array.isArray(jsonml[1]))
		) {
			jsonml.splice(1, 0, null);
		}

		return React.createElement.apply(React, jsonml.map(buildReactElement));
	};

	var requestAnimationFrame =
		(typeof window !== 'undefined' && window.requestAnimationFrame) ||
		function(cb) {
			return setTimeout(cb, 16);
		};

	var cancelAnimationFrame =
		(typeof window !== 'undefined' && window.cancelAnimationFrame) ||
		clearTimeout;

	var isEqualSubset = function(a, b) {
		for (var key in a)
			if (b[key] !== a[key]) return false;
		return true;
	};

	var isEqual = function(a, b) {
		return isEqualSubset(a, b) && isEqualSubset(b, a);
	};

	return React.createClass({
		getDefaultProps: function() {
			return {
				items: [],
				margin: 2000,
				atTop: false,
				atBottom: false,
				onScroll: function( /* key, above, below */ ) {},
				onMount: function( /* event */ ) {},
				onUnmount: function() {}
			};
		},

		getInitialState: function() {
			this.lastState = this.lastState ||  { jumpToIndex: null, offset: 0 };

			if (this.props.items.length) {
				if (this.props.atTop) {
					this.lastState.jumpToIndex = 0;
					this.lastState.position = 'top';
				} else if (this.props.atBottom) {
					this.lastState.jumpToIndex = this.props.items.length - 1;
					this.lastState.position = 'bottom';
				} else {
					this.lastState.jumpToIndex = 0;
					this.lastState.position = buildReactElement(this.props.items[0]).key;
				}
			}

			return {
				itemHeight: 25,
				columns: 1,
				topReached: this.props.atTop,
				bottomReached: this.props.atBottom,
				topRemoved: 0,
				bottomRemoved: 0
			};
		},

		update: function() {
			if (this.lastState.jumpToIndex !== null) {
				this.scrollTo(this.lastState.jumpToIndex, this.lastState.offset);
				this.lastState.offset = 0;
				this.lastState.jumpToIndex = null;
			}

			var items = this.props.items,
				itemsEl = this.refs.items.getDOMNode(),
				itemEls = itemsEl.children,
				itemHeight = this.state.itemHeight,
				viewTop = this.getScroll(),
				viewHeight = this.getViewportHeight(),
				viewBottom = viewTop + viewHeight,
				elBottom = this.getDOMNode().scrollHeight,
				last = this.lastState,
				position, i, offset, above, below;

			if (!itemEls.length) return;

			itemHeight = this.state.itemHeight = Math.max(20,
				(this.getBottom(itemEls[itemEls.length - 1]) - this.getTop(itemEls[0])) / itemEls.length
			);

			if (this.state.bottomReached && !this.state.bottomRemoved && viewBottom >= elBottom) {
				position = 'bottom';
				offset = 0;
				above = viewHeight / itemHeight;
				below = 0;
			} else if (this.state.topReached && !this.state.topRemoved && viewTop <= 0) {
				position = 'top';
				offset = 0;
				above = 0;
				below = viewHeight / itemHeight;
			} else {
				for (i = 0; i < itemEls.length; i++) {
					offset = itemEls[i].offsetTop + itemEls[i].scrollHeight - viewTop;
					if (offset >= 0) break;
				}
				if (i == itemEls.length) i--; // All the items are above the viewport; pick last one.

				position = buildReactElement(items[i]).key; // building in case it is JSONML
				if (viewTop < itemEls[0].offsetTop) {
					offset = viewTop - itemEls[0].offsetTop;
					above = -offset / itemHeight;
				} else {
					above = 0;
				}
				below = Math.max(0, Math.max(
					viewHeight / itemHeight, (viewBottom - itemEls[itemEls.length - 1].offsetTop) / itemHeight // view far below rendered items
				) - above);
			}

			above = Math.round(above);
			below = Math.round(below);

			if (last.position !== position || last.above !== above || last.below !== below) {
				last.position = position;
				last.offset = offset;
				last.above = above;
				last.below = below;

				this.afid = requestAnimationFrame(this.update);
				this.props.onScroll(position, above, below);
			} else if(last.offset !== offset) {
				this.afid = requestAnimationFrame(this.update);
			} else {
				this.stid = setTimeout(this.update, 200);
			}
		},

		componentDidMount: function() {
			this.update();
			this.props.onMount();
		},

		componentWillUnmount: function() {
			cancelAnimationFrame(this.afid);
			clearTimeout(this.stid);
			this.props.onUnmount();
		},

		shouldComponentUpdate: function(props, state) {
			if (isEqual(this.props, props) && isEqual(this.state, state)) return false;
			return true;
		},

		componentWillReceiveProps: function(nextProps) {
			this.setState({
				topReached: this.state.topReached || nextProps.atTop,
				bottomReached: this.state.bottomReached || nextProps.atBottom,
				topRemoved: nextProps.atTop? 0: this.state.topRemoved,
				bottomRemoved: nextProps.atBottom? 0: this.state.bottomRemoved,
			});
		},

		componentDidUpdate: function(prevProps) {
//			if (this.lastState.jumpToIndex !== null) return;

			var prevItems = prevProps.items.map(buildReactElement),
				items = this.props.items.map(buildReactElement),
				jumpRequired, newIndex = null,
				metrics, prevMetrics = this.metrics, i,
				topAdded, topRemoved, bottomAdded, bottomRemoved;

			if (!items.length || !prevItems.length) return;

			metrics = [].slice.call(this.refs.items.getDOMNode().children).map(function(itemEl) {
				return {
					top: this.getTop(itemEl),
					bottom: this.getBottom(itemEl)
				};
			}.bind(this));

			if(prevMetrics && prevMetrics.length !== prevItems.length) {
				console.log("Endless Error: prevMetrics.length ≠ prevItems.length", prevMetrics.length, prevItems.length);
			}

			if (metrics && prevMetrics && items.length && prevItems.length) {
				for (i = 0; i < items.length && items[i].key != prevItems[0].key; i++);
				topAdded = (i == items.length) ? 0 : metrics[i].top - metrics[0].top;

				for (i = 0; i < prevItems.length && prevItems[i].key != items[0].key; i++);
				topRemoved = (i == prevItems.length) ? 0 : prevMetrics[i].top - prevMetrics[0].top;

				for (i = items.length - 1; i >= 0 && items[i].key != prevItems[prevItems.length - 1].key; i--);
				bottomAdded = (i < 0) ? 0 : metrics[metrics.length - 1].bottom - metrics[i].bottom;

				for (i = prevItems.length - 1; i >= 0 && prevItems[i].key != items[items.length - 1].key; i--);
				bottomRemoved = (i < 0) ? 0 : prevMetrics[prevMetrics.length - 1].bottom - prevMetrics[i].bottom;

				//		console.log(topRemoved, topAdded, bottomRemoved, bottomAdded);

				this.setState({
					topRemoved: Math.max(0, this.state.topRemoved + topRemoved - topAdded),
					bottomRemoved: Math.max(0, this.state.bottomRemoved + bottomRemoved - bottomAdded)
				});
			}

			//	console.log('Rendered', items[0].key, 'through', items[items.length-1].key,
			//				'Removed space ', this.state.topRemoved, this.state.bottomRemoved);
			this.metrics = metrics;

			if (items[0].key != prevItems[0].key) jumpRequired = true;
			if (prevProps.topReached != this.props.topReached) jumpRequired = true;
			if (this.lastState.position === 'bottom') jumpRequired = true;

			if (jumpRequired) {
				if (this.lastState.position == 'top') {
					newIndex = 0;
				} else if (this.lastState.position == 'bottom') {
					newIndex = items.length - 1;
				} else
					for (i = 0; i < items.length; i++) {
						if (items[i].key == this.lastState.position) {
							newIndex = i;
							break;
						}
					}

				if (newIndex === null) {
//					newIndex = 0;
					console.log('couldnt find ', this.lastState.position, 'in', items[0].key, items[items.length - 1].key);
				} else {
					this.lastState.jumpToIndex = newIndex;
				}

			}
		},

		getTop: function(el) {
			return el.getBoundingClientRect().top - parseFloat(window.getComputedStyle(el).marginTop);
		},

		getBottom: function(el) {
			return el.getBoundingClientRect().bottom + parseFloat(window.getComputedStyle(el).marginBottom);
		},

		getScrollParent: function() {
			for (var el = this.getDOMNode(); el; el = el.parentElement) {
				var overflowY = window.getComputedStyle(el).overflowY;
				if (overflowY === 'auto' || overflowY === 'scroll') return el;
			}
			return window;
		},

		// Get scroll position relative to the top of the list.
		getScroll: function() {
			var scrollParent = this.getScrollParent();
			var el = this.getDOMNode();
			if (scrollParent === el) {
				return el.scrollTop;
			} else if (scrollParent === window) {
				return -el.getBoundingClientRect().top;
			} else {
				return scrollParent.getBoundingClientRect().top -
					el.getBoundingClientRect().top +
					parseFloat(window.getComputedStyle(scrollParent).borderTop);
			}
		},

		setScroll: function(y) {
			var scrollParent = this.getScrollParent(),
				el = this.getDOMNode();
			if (scrollParent != el) y += (scrollParent.scrollTop -
					(scrollParent.getBoundingClientRect().top -
					el.getBoundingClientRect().top +
					parseFloat(window.getComputedStyle(scrollParent).borderTop)));
			if (scrollParent === window) return window.scrollTo(0, y);
			scrollParent.scrollTop = y;
		},

		getViewportHeight: function() {
			var scrollParent = this.getScrollParent();
			return scrollParent === window ? scrollParent.innerHeight : scrollParent.clientHeight;
		},

		scrollTo: function(index, offset) {
			var y = this.refs.items.getDOMNode().children[index].offsetTop + offset;

			//	console.log(
			//		"scrolling from", this.getScroll(), "to",
			//		this.refs.items.getDOMNode().children[index].offsetTop, offset
			//	);
			this.setScroll(y);
		},

		render: function() {
			return buildReactElement(['div', {
					style: {
						position: 'relative'
					}
				},
				['div', {
					style: {
						height: this.state.topRemoved + (this.state.topReached ? 0 : this.props.margin)
					}
				}],
				['div', {
					ref: 'items'
				}].concat(this.props.items), ['div', {
					style: {
						clear: 'both',
						height: this.state.bottomRemoved + (this.state.bottomReached ? 0 : this.props.margin)
					}
				}]
			]);
		}
	});
});
<|endoftext|>


<commit_before>var audioCtx = new (window.AudioContext || window.webkitAudioContext)(),
    source = audioCtx.createBufferSource(),
    xhr = new XMLHttpRequest(),
    pbDiff = 0,
    minPb = 1.1,
    maxPb = 2.0;

xhr.open("GET", "/sounds/engine.wav", true);
xhr.responseType = "arraybuffer";
xhr.onload = function(e){
  audioCtx.decodeAudioData(this.response, function(buffer) {
    source.buffer = buffer;
    source.loop = true;
    source.connect(audioCtx.destination);
    source.start();
  });
};

xhr.send();

window.onkeyup = function(e) {
  if (e.keyCode == 38) {
    pbDiff = -0.02;
  }
};

window.onkeydown = function(e) {
  if (e.keyCode == 38) {
    pbDiff = 0.02;
  }
};

setInterval(function(){
  var currPb = source.playbackRate.value;

  if ((pbDiff < 0 && currPb > minPb) || (pbDiff > 0 && currPb < maxPb)) {
    source.playbackRate.value += pbDiff;
  }
}, 50);
<commit_msg>Dead space<commit_after>var audioCtx = new (window.AudioContext || window.webkitAudioContext)(),
    source = audioCtx.createBufferSource(),
    xhr = new XMLHttpRequest(),
    pbDiff = 0,
    minPb = 1.1,
    maxPb = 2.2;

xhr.open("GET", "/sounds/engine.wav", true);
xhr.responseType = "arraybuffer";
xhr.onload = function(e){
  audioCtx.decodeAudioData(this.response, function(buffer) {
    source.buffer = buffer;
    source.loop = true;
    source.connect(audioCtx.destination);
    source.start();
  });
};

xhr.send();

window.onkeyup = function(e) {
  if (e.keyCode == 38) {
    pbDiff = -0.02;
  }
};

window.onkeydown = function(e) {
  if (e.keyCode == 38) {
    pbDiff = 0.02;
  }
};

setInterval(function(){
  var currPb = source.playbackRate.value;

  if ((pbDiff < 0 && currPb > minPb) || (pbDiff > 0 && currPb < maxPb)) {
    source.playbackRate.value += pbDiff;
  }
}, 50);
<|endoftext|>


<commit_before>import babel from 'rollup-plugin-babel'
import nodeResolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import json from 'rollup-plugin-json'
import glob from 'glob'

const START = '\0START'

export default {
  entry: START,
  dest: './dist/tests.js',
  format: 'umd',
  plugins: [
    {
      resolveId (id) {
        if (id === START) return START
      },
      load (id) {
        if (id === START) {
          let index = glob.sync('tests/**/*.test.js').map((f) => {
            return `import './${f}'`
          }).join('\n')
          return index
        }
      }
    },
    json({
      include: 'node_modules/**'
    }),
    babel({
      // overriding babelrc
      babelrc: false,
      presets: [
        [ 'es2015', { 'modules': false } ]
      ],
      plugins: [
        'external-helpers',
        ['babel-plugin-transform-builtin-extend', {
          globals: ['Error']
        }]
      ]
    }),
    nodeResolve(),
    commonjs({
      include: 'node_modules/**'
    })
  ],
  // let rollup skip tape
  external: ['tape', 'd3'],
  globals: {
    // instead of using tape directly
    // we want to use the one managed by the test suite
    tape: 'substanceTest.test',
    d3: 'd3'
  }
}
<commit_msg>Fix order of plugins<commit_after>import babel from 'rollup-plugin-babel'
import nodeResolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import json from 'rollup-plugin-json'
import glob from 'glob'

const START = '\0START'

export default {
  entry: START,
  dest: './dist/tests.js',
  format: 'umd',
  plugins: [
    {
      resolveId (id) {
        if (id === START) return START
      },
      load (id) {
        if (id === START) {
          let index = glob.sync('tests/**/*.test.js').map((f) => {
            return `import './${f}'`
          }).join('\n')
          return index
        }
      }
    },
    json({
      include: 'node_modules/**'
    }),
    nodeResolve({
      jsnext: true
    }),
    commonjs({
      include: 'node_modules/**'
    }),
    babel({
      // overriding babelrc
      babelrc: false,
      presets: [
        [ 'es2015', { 'modules': false } ]
      ],
      plugins: [
        'external-helpers',
        ['babel-plugin-transform-builtin-extend', {
          globals: ['Error']
        }]
      ]
    })
  ],
  // let rollup skip tape
  external: ['tape', 'd3'],
  globals: {
    // instead of using tape directly
    // we want to use the one managed by the test suite
    tape: 'substanceTest.test',
    d3: 'd3'
  }
}
<|endoftext|>


<commit_before>import istanbul from 'rollup-plugin-istanbul';

import commonjs from 'rollup-plugin-commonjs';
import resolve from 'rollup-plugin-node-resolve';
import multiEntry from 'rollup-plugin-multi-entry';

export default {
  input: 'tests/**/*-test.js',
  output: {
    file: 'build/bundle-test.js',
    format: 'cjs',
    sourcemap: true,
    interop: false
  },
  external: ['ava'],
  plugins: [multiEntry(), istanbul({
    exclude: ['tests/**/*-test.js']
  }), resolve(), commonjs()]
};
<commit_msg>chore(test): get rid of rollup<commit_after><|endoftext|>


<commit_before>/*!
 * qwebs
 * Copyright(c) 2016 Benoît Claveau
 * MIT Licensed
 */

"use strict";

class InfoService {
	constructor() {
	};

	whoiam() {
		return "I'm Info service.";
	};

	getInfo(request, response) {
		let content = {
			whoiam: this.whoiam()
		};
		return response.send({ request: request, content: content });
	};

	getMessage(request, response) {
		let content = {
			text: "hello world"
		};
		return response.send({ request: request, content: content });
	};

	save(request, response) {
		let content = {
			status: "saved"
		};
		return response.send({ request: request, content: content });
	};

	update(request, response) {
		let content = {
			status: "updated"
		};
		return response.send({ request: request, content: content });
	};

	delete(request, response) {
		let content = {
			status: "deleted"
		};
		return response.send({ request: request, content: content });
	};

        redirect(request, response) {
                return response.redirect({ url: "get" });
        }
};

exports = module.exports = InfoService;
<commit_msg>Update info.js<commit_after>/*!
 * qwebs
 * Copyright(c) 2016 Benoît Claveau
 * MIT Licensed
 */

"use strict";

const Readable = require('stream').Readable;

class InfoService {
	constructor() {
	};

	whoiam() {
		return "I'm Info service.";
	};

	getInfo(request, response) {
		let content = {
			whoiam: this.whoiam()
		};
		return response.send({ request: request, content: content });
	};

	getMessage(request, response) {
		let source = new Readable;
		setTimeout(() => source.push({ text: "hello world" }), 1000);
		return response.send({ request: request, stream: source }); //use stream instead of content
	};

	save(request, response) {
		let content = {
			status: "saved"
		};
		return response.send({ request: request, content: content });
	};

	update(request, response) {
		let content = {
			status: "updated"
		};
		return response.send({ request: request, content: content });
	};

	delete(request, response) {
		let content = {
			status: "deleted"
		};
		return response.send({ request: request, content: content });
	};

        redirect(request, response) {
                return response.redirect({ url: "get" });
        }
};

exports = module.exports = InfoService;
<|endoftext|>


<commit_before>// TODO: complete the following function
/* global QUnit: false, dbtester: false */
'use strict';
QUnit.test('dbtester.is2NF test', function (assert) {
  var attrs = ['A', 'B', 'C', 'D', 'E'];
  var fds = [{
    left: ['A', 'B', 'C'],
    right: ['C', 'D'],
    type: 'fd'
  }, {
    left: ['A', 'B'],
    right: ['E', 'C'],
    type: 'fd'
  }];
  assert.ok(dbtester.is2NF(attrs, fds), 'In 3NF');
});

QUnit.test('dbtester.is3NF test', function (assert) {
  var attrs = ['A', 'B', 'C', 'D', 'E'];
  var fds = [{
    left: ['A', 'B', 'C'],
    right: ['C', 'D'],
    type: 'fd'
  }, {
    left: ['A', 'B'],
    right: ['E', 'C'],
    type: 'fd'
  }];
  assert.ok(dbtester.is3NF(attrs, fds), 'In 3NF');
});

// TODO: complete the following
QUnit.test('dbtester.isBCNF test', function (assert) {
  var attrs = ['A', 'B', 'C', 'D', 'E'];
  var fds = [{
    left: ['A', 'B', 'C'],
    right: ['C', 'D'],
    type: 'fd'
  }, {
    left: ['A', 'B'],
    right: ['E', 'C'],
    type: 'fd'
  }];
  assert.ok(dbtester.isBCNF(attrs, fds), 'In BCNF');

  fds = [{
    left: ['A', 'B'],
    right: ['C', 'D'],
    type: 'fd'
  }, {
    left: ['A', 'B'],
    right: ['E'],
    type: 'fd'
  }];
  assert.ok(dbtester.isBCNF(attrs, fds), 'In BCNF');

  fds = [{
    left: ['A', 'B'],
    right: ['C', 'D'],
    type: 'fd'
  }, {
    left: ['A', 'B', 'D'],
    right: ['E'],
    type: 'fd'
  }];
  assert.ok(dbtester.isBCNF(attrs, fds), 'In BCNF');

  fds = [{
    left: ['A', 'B'],
    right: ['C', 'D'],
    type: 'fd'
  }, {
    left: ['A'],
    right: ['E'],
    type: 'fd'
  }];
  assert.ok(!dbtester.isBCNF(attrs, fds), 'In BCNF');

  fds = [{
    left: ['A'],
    right: ['B'],
    type: 'fd'
  }, {
    left: ['B', 'C'],
    right: ['E'],
    type: 'fd'
  }, {
    left: ['D', 'E'],
    right: ['A'],
    type: 'fd'
  }];
  assert.ok(!dbtester.isBCNF(attrs, fds), 'Not BCNF');

  fds = [{
    left: ['A', 'B'],
    right: ['C', 'D'],
    type: 'fd'
  }];
  assert.ok(!dbtester.isBCNF(attrs, fds), 'Not BCNF');

  fds = [{
    left: ['A', 'B'],
    right: ['D'],
    type: 'fd'
  }, {
    left: ['A', 'B', 'C'],
    right: ['E'],
    type: 'fd'
  }];
  assert.ok(!dbtester.isBCNF(attrs, fds), 'Not BCNF');
});
<commit_msg>added more tests for nf checks<commit_after>// TODO: complete the following function
/* global QUnit: false, dbtester: false */
'use strict';
QUnit.test('dbtester.is2NF test', function (assert) {
  var attrs = ['A', 'B', 'C', 'D', 'E'];
  var fds = [{
    left: ['A', 'B', 'C'],
    right: ['C', 'D'],
    type: 'fd'
  }, {
    left: ['A', 'B'],
    right: ['E', 'C'],
    type: 'fd'
  }];
  assert.ok(dbtester.is2NF(attrs, fds), 'In 2NF');

  fds = [];
  assert.ok(dbtester.is2NF(attrs, fds), 'In 2NF');

  fds = [{
    left: ['A', 'C'],
    right: ['B'],
    type: 'fd'
  }, {
    left: ['B'],
    right: ['D'],
    type: 'fd'
  }, {
    left: ['D'],
    right: ['E'],
    type: 'fd'
  }];
  assert.ok(dbtester.is2NF(attrs, fds), 'In 2NF');

  fds = [{
    left: ['A', 'B'],
    right: ['C', 'D', 'E'],
    type: 'fd'
  }, {
    left: ['B', 'D'],
    right: ['E'],
    type: 'fd'
  }];
  assert.ok(dbtester.is2NF(attrs, fds), 'In 2NF');

  fds = [{
    left: ['A', 'B'],
    right: ['C', 'D', 'E'],
    type: 'fd'
  }, {
    left: ['C'],
    right: ['B'],
    type: 'fd'
  }];
  assert.ok(dbtester.is2NF(attrs, fds), 'In 3NF already');

  fds = [{
    left: ['A'],
    right: ['B'],
    type: 'fd'
  }];
  assert.ok(!dbtester.is2NF(attrs, fds), 'Not in 2NF');

  fds = [{
    left: ['A'],
    right: ['B'],
    type: 'fd'
  }, {
    left: ['A', 'B'],
    right: ['C', 'D'],
    type: 'fd'
  }];
  assert.ok(!dbtester.is2NF(attrs, fds), 'Not in 2NF');
});

QUnit.test('dbtester.is3NF test', function (assert) {
  var attrs = ['A', 'B', 'C', 'D', 'E'];
  var fds = [{
    left: ['A', 'B', 'C'],
    right: ['C', 'D'],
    type: 'fd'
  }, {
    left: ['A', 'B'],
    right: ['E', 'C'],
    type: 'fd'
  }];
  assert.ok(dbtester.is3NF(attrs, fds), 'In 3NF');

  fds = [];
  assert.ok(dbtester.is3NF(attrs, fds), 'In 3NF');

  fds = [{
    left: ['A', 'B'],
    right: ['C', 'D', 'E'],
    type: 'fd'
  }, {
    left: ['C'],
    right: ['B'],
    type: 'fd'
  }];
  assert.ok(dbtester.is3NF(attrs, fds), 'In 3NF');

  fds = [{
    left: ['A', 'B'],
    right: ['C', 'D', 'E'],
    type: 'fd'
  }, {
    left: ['C'],
    right: ['B'],
    type: 'fd'
  }, {
    left: ['C'],
    right: ['C'],
    type: 'fd'
  }];
  assert.ok(dbtester.is3NF(attrs, fds), 'In 3NF');

  fds = [{
    left: ['C'],
    right: ['B'],
    type: 'fd'
  }, {
    left: ['A', 'B', 'E'],
    right: ['C', 'D'],
    type: 'fd'
  }];
  assert.ok(dbtester.is3NF(attrs, fds), 'In 3NF');

  fds = [{
    left: ['A'],
    right: ['B'],
    type: 'fd'
  }, {
    left: ['A', 'B'],
    right: ['C', 'D', 'E'],
    type: 'fd'
  }];
  assert.ok(dbtester.is3NF(attrs, fds), 'In BCNF already');

  fds = [{
    left: ['A', 'B'],
    right: ['C', 'D', 'E'],
    type: 'fd'
  }, {
    left: ['D', 'E'],
    right: ['A', 'B', 'C'],
    type: 'fd'
  }, {
    left: ['C'],
    right: ['A', 'B'],
    type: 'fd'
  }];
  assert.ok(dbtester.is3NF(attrs, fds), 'In BCNF already');

  fds = [{
    left: ['A'],
    right: ['B'],
    type: 'fd'
  }];
  assert.ok(!dbtester.is3NF(attrs, fds), 'Not even in 2NF');

  fds = [{
    left: ['A'],
    right: ['B'],
    type: 'fd'
  }, {
    left: ['A', 'B'],
    right: ['C', 'D'],
    type: 'fd'
  }];
  assert.ok(!dbtester.is3NF(attrs, fds), 'Not even in 2NF');

  fds = [{
    left: ['A', 'B'],
    right: ['C', 'D', 'E'],
    type: 'fd'
  }, {
    left: ['B', 'D'],
    right: ['E'],
    type: 'fd'
  }];
  assert.ok(!dbtester.is3NF(attrs, fds), 'Not in 3NF');
});

QUnit.test('dbtester.isBCNF test', function (assert) {
  var attrs = ['A', 'B', 'C', 'D', 'E'];
  var fds = [{
    left: ['A', 'B', 'C'],
    right: ['C', 'D'],
    type: 'fd'
  }, {
    left: ['A', 'B'],
    right: ['E', 'C'],
    type: 'fd'
  }];
  assert.ok(dbtester.isBCNF(attrs, fds), 'In BCNF');

  fds = [];
  assert.ok(dbtester.isBCNF(attrs, fds), 'In BCNF');

  fds = [{
    left: ['A', 'B'],
    right: ['C', 'D'],
    type: 'fd'
  }, {
    left: ['A', 'B'],
    right: ['E'],
    type: 'fd'
  }];
  assert.ok(dbtester.isBCNF(attrs, fds), 'In BCNF');

  fds = [{
    left: ['A'],
    right: ['B'],
    type: 'fd'
  }, {
    left: ['A', 'B'],
    right: ['C', 'D', 'E'],
    type: 'fd'
  }];
  assert.ok(dbtester.isBCNF(attrs, fds), 'In BCNF');

  fds = [{
    left: ['A', 'B'],
    right: ['C', 'D'],
    type: 'fd'
  }, {
    left: ['A', 'B', 'D'],
    right: ['E'],
    type: 'fd'
  }];
  assert.ok(dbtester.isBCNF(attrs, fds), 'In BCNF');

  fds = [{
    left: ['A', 'B'],
    right: ['C', 'D', 'E'],
    type: 'fd'
  }, {
    left: ['D', 'E'],
    right: ['A', 'B', 'C'],
    type: 'fd'
  }, {
    left: ['C'],
    right: ['A', 'B'],
    type: 'fd'
  }];
  assert.ok(dbtester.isBCNF(attrs, fds), 'In BCNF');

  fds = [{
    left: ['A', 'B'],
    right: ['C', 'D'],
    type: 'fd'
  }, {
    left: ['A'],
    right: ['E'],
    type: 'fd'
  }];
  assert.ok(!dbtester.isBCNF(attrs, fds), 'In BCNF');

  fds = [{
    left: ['A'],
    right: ['B'],
    type: 'fd'
  }, {
    left: ['A', 'B'],
    right: ['C', 'D'],
    type: 'fd'
  }];
  assert.ok(!dbtester.isBCNF(attrs, fds), 'Not even in 2NF');

  fds = [{
    left: ['A', 'B'],
    right: ['C', 'D', 'E'],
    type: 'fd'
  }, {
    left: ['B', 'D'],
    right: ['E'],
    type: 'fd'
  }];
  assert.ok(!dbtester.isBCNF(attrs, fds), 'Not even in 3NF');

  fds = [{
    left: ['A'],
    right: ['B'],
    type: 'fd'
  }, {
    left: ['B', 'C'],
    right: ['E'],
    type: 'fd'
  }, {
    left: ['D', 'E'],
    right: ['A'],
    type: 'fd'
  }];
  assert.ok(!dbtester.isBCNF(attrs, fds), 'Not BCNF');

  fds = [{
    left: ['A', 'B'],
    right: ['C', 'D'],
    type: 'fd'
  }];
  assert.ok(!dbtester.isBCNF(attrs, fds), 'Not BCNF');

  fds = [{
    left: ['A', 'B'],
    right: ['D'],
    type: 'fd'
  }, {
    left: ['A', 'B', 'C'],
    right: ['E'],
    type: 'fd'
  }];
  assert.ok(!dbtester.isBCNF(attrs, fds), 'Not BCNF');
});
<|endoftext|>


<commit_before>const weh = require('./index2')

const plugin = ({ value = 'hi' }) => {
  return ['pre_write', files => {
    return files.map(file => Object.assign(file, { contents: value }))
  }]
}

const hook = files => files.map(file => Object.assign(file, { contents: 'a' }))

weh(async site => {
  site.config({ source: '_test' })
  site.hook('pre_read', hook)
  return site
}).then(cool => {
  console.log(cool)
})
<commit_msg>update example for plugin stuff<commit_after>const weh = require('./index2')

const plugin = ({ value = 'hi' }) => {
  return ['pre_write', files => {
    return files.map(file => Object.assign(file, { contents: value }))
  }]
}

weh(async site => {
  site.config({ source: '_test' })
  site.use(plugin)
  return site
}).then(cool => {
  console.log(cool.files)
})
<|endoftext|>


<commit_before>define(function(require) {
	var Hub = require('streamhub-sdk');
	var View = require('streamhub-ticker/views/TickerView');

	return function(sdk, opts) {
        var view = new View({
            streams: Hub.Streams.forCollection($.extend({}, opts, {articleId: opts.articleId1}).start(),
            feedStreams: Hub.Streams.forCollection($.extend({}, opts, {articleId: opts.articleId2}).start(),
            el: document.getElementById(opts.elementId),
        });

        return view;
    };
});<commit_msg>Remove example js define statement<commit_after>define(['streamhub-sdk', 'streamhub-ticker/views/TickerView'],
function(Hub, View) {
	return function(sdk, opts) {
        var view = new View({
            streams: Hub.Streams.forCollection($.extend({}, opts, {articleId: opts.articleId1}).start(),
            feedStreams: Hub.Streams.forCollection($.extend({}, opts, {articleId: opts.articleId2}).start(),
            el: document.getElementById(opts.elementId),
        });

        return view;
    };
});
<|endoftext|>


<commit_before>$(function() {
    $('#intro').show();
    $.mininc(function(g) {
        // event handlers
        $('#startgame').click(function() {
            g.set('startgameclicked', true);
        });
        $('#click').click(function() {
            g.set('clicks', g.get('clicks') + 1);
            g.update('#clickcount');
        });

        // game hooks
        g.hook('startgameclicked', g.hook.truthy, function() {
            $('#intro').hide('slow');
            $('#game').show('slow');
        });
        g.hook('clicks', g.hook.gte(10), function() {
            $('#click10').show('slow');
        });

        // save / restore
        g.restore(g.autosave = '__example_mininc_game_data');

        // initialize default variables
        g.setDefault('clicks', 0);

        // set everything up
        g.update('*');
    });
});
<commit_msg>fixed borky example with new update syntax<commit_after>$(function() {
    $('#intro').show();
    $.mininc(function(g) {
        // event handlers
        $('#startgame').click(function() {
            g.set('startgameclicked', true);
        });
        $('#click').click(function() {
            g.set('clicks', g.get('clicks') + 1);
            g.update('#clickcount [data-mininc]');
        });

        // game hooks
        g.hook('startgameclicked', g.hook.truthy, function() {
            $('#intro').hide('slow');
            $('#game').show('slow');
        });
        g.hook('clicks', g.hook.gte(10), function() {
            $('#click10').show('slow');
        });

        // save / restore
        g.restore(g.autosave = '__example_mininc_game_data');

        // initialize default variables
        g.setDefault('clicks', 0);

        // set everything up
        g.update('*[data-mininc]');
    });
});
<|endoftext|>


<commit_before>var koa = require('koa');
var koaValidator = require('lib/koa-validator');
var app = koa();

// adding middleware extends Context with validation methods
app.use(koaValidator());

app.use(function *(){
  this.checkQuery('getparam', 'Invalid getparam').isInt();
  this.checkParams('urlparam', 'No url param').notEmpty();
  this.checkBody('postParam', 'Invalid postparam').isAlpha();
  var errors = this.validationErrors();
  yield errors if errors
  yield next;
});

app.listen(3000);
<commit_msg>Extend example<commit_after>var koa = require('koa');
var bodyParser = require('koa-body-parser');
var router = require('koa-router');
var koaValidator = require('./lib');
var app = koa();

// body needs to be parsed before using checkBody
app.use(bodyParser());

// adding middleware extends Context with validation methods
app.use(koaValidator());

app.use(function *(next){
	this.checkQuery('getparam', 'Invalid getparam').isInt().notEmpty();
	this.checkParams('urlparam', 'No url param').notEmpty();
	this.checkBody('postParam', 'Invalid postparam').isAlpha();
	var errors = this.validationErrors();
	if (errors) {
		this.body = errors
	}
	else {
		this.body = 'No validation errors'
	}

	yield next;
});

app.listen(3000);
<|endoftext|>


<commit_before>var dotty = require("./lib/index");

var object = {
  a: {
    b: {
      x: "y",
    },
    c: {
      x: "z",
    },
  },
};

console.log(dotty.exists(object, "a.b.x")); // true
console.log(dotty.exists(object, ["a", "b", "x"])); // true
console.log(dotty.exists(object, "a.b.z")); // false
console.log(dotty.exists(object, ["a", "b", "z"])); // false

console.log(dotty.get(object, "a.b.x")); // "y"
console.log(dotty.get(object, ["a", "b", "x"])); // "y"
console.log(dotty.get(object, "a.b.z")); // undefined
console.log(dotty.get(object, ["a", "b", "z"])); // undefine

dotty.put(object, "a.b.hello", "hi");
dotty.put(object, ["a", "c", "yo"], "sup");

console.log(dotty.search(object, "a.b.*"));
console.log(dotty.search(object, ["a", "b", "*"]));
console.log(dotty.search(object, "a.*.x"));
console.log(dotty.search(object, ["a", "*", "x"]));
console.log(dotty.search(object, ["a", "*", /..+/]));

console.log(dotty.remove(object, "a.b.x"));
console.log(dotty.remove(object, "a.b.y"));

console.log(dotty.deepKeys(object));
console.log(dotty.deepKeys(object, {leavesOnly: true}));
console.log(dotty.deepKeys(object, {leavesOnly: true, asStrings: true}));

console.log(object);
<commit_msg>Docs: Update examples with expected output<commit_after>var dotty = require("./lib/index");

var object = {
  a: {
    b: {
      x: "y",
    },
    c: {
      x: "z",
    },
  },
};

console.log(dotty.exists(object, "a.b.x")); // true
console.log(dotty.exists(object, ["a", "b", "x"])); // true
console.log(dotty.exists(object, "a.b.z")); // false
console.log(dotty.exists(object, ["a", "b", "z"])); // false

console.log(dotty.get(object, "a.b.x")); // "y"
console.log(dotty.get(object, ["a", "b", "x"])); // "y"
console.log(dotty.get(object, "a.b.z")); // undefined
console.log(dotty.get(object, "a.b.z.z"));  // undefined
console.log(dotty.get(object, ["a", "b", "z"])); // undefined

dotty.put(object, "a.b.hello", "hi");
dotty.put(object, ["a", "c", "yo"], "sup");

console.log(dotty.search(object, "a.b.*")); // ["y", "hi"]
console.log(dotty.search(object, ["a", "b", "*"])); // ["y", "hi"]
console.log(dotty.search(object, "a.*.x")); // ["y", "z"]
console.log(dotty.search(object, ["a", "*", "x"]));  // ["y", "z"]
console.log(dotty.search(object, ["a", "*", /..+/]));  // ["hi", "sup"]

console.log(dotty.remove(object, "a.b.x"));
console.log(dotty.remove(object, "a.b.y"));

console.log(dotty.deepKeys(object));
/**
  [
    [ 'a' ],
    [ 'a', 'b' ],
    [ 'a', 'b', 'hello' ],
    [ 'a', 'c' ],
    [ 'a', 'c', 'x' ],
    [ 'a', 'c', 'yo' ]
  ]
 */

console.log(dotty.deepKeys(object, {leavesOnly: true}));
/**
  [
    [ 'a', 'b', 'hello' ],
    [ 'a', 'c', 'x' ],
    [ 'a', 'c', 'yo' ]
  ]
 */

console.log(dotty.deepKeys(object, {leavesOnly: true, asStrings: true}));
/**
  [
    'a.b.hello',
    'a.c.x',
    'a.c.yo'
  ]
 */

console.log(object);
/**
  {
    a: {
      b: {
        hello: "hi"
      },
      c: {
        x: "z',
        yo: 'sup'
      }
    }
  }
 */
<|endoftext|>


<commit_before>'use strict'

var pino = require('./')()

pino.info('hello world')
pino.error('this is at error level')
pino.info('the answer is %d', 42)
pino.info({ obj: 42 }, 'hello world')
pino.info({ obj: 42, b: 2 }, 'hello world')
pino.info({ obj: { aa: 'bbb' } }, 'another')
setImmediate(function () {
  pino.info('after setImmediate')
})
pino.error(new Error('an error'))

var child = pino.child({ a: 'property' })
child.info('hello child!')

var childsChild = child.child({ another: 'property' })
childsChild.info('hello baby..')

pino.debug('this should be mute')

pino.level = 'trace'

pino.debug('this is a debug statement')

pino.child({ another: 'property' }).debug('this is a debug statement via child')
pino.trace('this is a trace statement')

pino.debug('this is a "debug" statement with "')
<commit_msg>Updated example to not change the type of a property.<commit_after>'use strict'

var pino = require('./')()

pino.info('hello world')
pino.error('this is at error level')
pino.info('the answer is %d', 42)
pino.info({ obj: 42 }, 'hello world')
pino.info({ obj: 42, b: 2 }, 'hello world')
pino.info({ nested: { obj: 42 } }, 'nested')
setImmediate(function () {
  pino.info('after setImmediate')
})
pino.error(new Error('an error'))

var child = pino.child({ a: 'property' })
child.info('hello child!')

var childsChild = child.child({ another: 'property' })
childsChild.info('hello baby..')

pino.debug('this should be mute')

pino.level = 'trace'

pino.debug('this is a debug statement')

pino.child({ another: 'property' }).debug('this is a debug statement via child')
pino.trace('this is a trace statement')

pino.debug('this is a "debug" statement with "')
<|endoftext|>