<commit_before>var epubParser;

epubParser = (function () {
  var fs = require("fs");
  var xml2js = require("xml2js");
  var _ = require("lodash");
  var mkdirp = require("mkdirp");
  var yauzl = require("yauzl");
  var PATH = require('path');
  var parser = new xml2js.Parser();

  function open(path, outDir) {
    // a container to pass book file locations
    var bookData = {
      cover: "",
      path: path,
      epubName: path
        .split("/")
        .pop(),
      tmp: PATH.basename(path, ".epub") + "/",
      outDir: outDir
    }
    return new Promise(function (resolve, reject) {
      mkdirp("./" + bookData.tmp, function (err) {
        if (err)
          reject(err);
       // Unzip the content and cover
        yauzl
          .open(path, {
            lazyEntries: true
          }, function (err, zipfile) {
            if (err)
              throw err;
            zipfile.readEntry();
            zipfile.on("entry", function (entry) {
              // at file entry
              zipfile
                .openReadStream(entry, function (err, readStream) {
                  if (err)
                    reject(err);
                  var fileName = entry
                    .fileName
                    .split("/")
                    .pop();
                  if(bookData.cover === 'notfound'){
                    if(fileName.split(".").pop() === "jpg" || fileName.split(".").pop() === "jpeg"){
                      bookData.cover = fileName;
                      readStream.pipe(fs.createWriteStream("./" + bookData.tmp + fileName));
                      readStream.on("end", function () {
                        zipfile.readEntry();
                      });
                    }
                  }
                  else if (fileName === bookData.cover){
                      readStream.pipe(fs.createWriteStream("./" + bookData.tmp + fileName));
                      readStream.on("end", function () {
                        zipfile.readEntry();
                      });
                    }
                  else if (fileName === (bookData.cover + ".jpg") ||
                  fileName === (bookData.cover + ".jpeg") || fileName === (bookData.cover + ".png")) {
                      bookData.cover = fileName;
                      readStream.pipe(fs.createWriteStream("./" + bookData.tmp + fileName));
                      readStream.on("end", function () {
                        zipfile.readEntry();
                      });
                    }
                  // get the xml parse and try to find cover image if exists
                  // it is assumed that xml file is on the top directory level
                  else if (fileName.split(".").pop() === "opf") {
                    console.log("got opf");
                    bookData.content = fileName;
                    readStream.pipe(fs.createWriteStream("./" + bookData.tmp + fileName));
                    readStream.on("end", function () {
                    fs.readFile("./" + bookData.tmp + fileName, function(err, data) {
                    parser.parseString(data, function (err, result) {
                        var metadata = result.package.metadata[0].meta
                        if(typeof metadata !== "undefined")
                        for(var i = 0; i< metadata.length; i++){
                            if(metadata[i]["$"].name === "cover"){
                              bookData.cover = metadata[i]["$"].content;
                            }
                        }
                        if(bookData.cover===''){
                          bookData.cover = "notfound";
                        }
                        zipfile.readEntry();
                    })
                });
                    });
                  } else
                    zipfile.readEntry();
                  }
                );
            });
            zipfile.once("end", function (err) {
              if (err)
                console.log(err);
              zipfile.close();
              resolve(bookData);
            });
            zipfile.on("error", function (err) {
              if (err)
                console.log(err);
              zipfile.close();
              reject(err);
            })
          });
      });
    });
  }

  var convArr = function (arr) {
    var jsonData = {};
    _.forEach(arr, function (elem) {
      var keys = Object.keys(elem);
      _.forEach(keys, function (key) {
        var value = elem[key];
        jsonData[key] = value;
      });
    })
    return jsonData;
  };

  function xmlParser(bookData) {
    var Book = {};
    return new Promise(function (resolve, reject) {
      fs
        .readFile("./" + bookData.tmp + bookData.content, function (err, data) {
          if (err)
            reject(err);
          parser
            .parseString(data, function (err, result) {
              var jsondata = JSON.parse(JSON.stringify(result));
              var book = convArr(jsondata.package.metadata);
              var cover = _.filter(book.meta, (i) => i["$"].name === "cover");
              var rating = _.filter(book.meta, (i) => i["$"].name === "calibre:rating");
              var bookPath = bookData.outDir + "/Books/" + book["dc:creator"][0]._ + "/" + book["dc:title"][0];
              mkdirp(bookPath, function (err) {
                if (err)
                  reject(err);
                if (cover !== "undefined" && cover.length > 0)
                  fs.rename("./" + bookData.tmp + bookData.cover, bookPath + "/" + cover[0]["$"].content, function (err) {
                    if (err)
                      reject(err);
                    fs
                      .rename(bookData.path, bookPath + "/" + bookData.epubName, function (err) {
                        if (err)
                          reject(err);
                        fs
                          .rename("./" + bookData.tmp + bookData.content, bookPath + "/" + bookData.content, function (err) {
                            if (err)
                              reject(err);
                            fs
                              .rmdir("./" + bookData.tmp, function (err) {
                                if (err)
                                  reject(err);
                                }
                              );
                          });
                      });
                  });
                  else if (bookData.cover !== "" && bookData.cover !== "notfound")
                  fs.rename("./" + bookData.tmp + bookData.cover, bookPath + "/" + bookData.cover, function (err) {
                    if (err)
                      reject(err);
                    fs
                      .rename(bookData.path, bookPath + "/" + bookData.epubName, function (err) {
                        if (err)
                          reject(err);
                        fs
                          .rename("./" + bookData.tmp + bookData.content, bookPath + "/" + bookData.content, function (err) {
                            if (err)
                              reject(err);
                            fs
                              .rmdir("./" + bookData.tmp, function (err) {
                                if (err)
                                  reject(err);
                                }
                              );
                          });
                      });
                  });
                  else
                    fs
                      .rename(bookData.path, bookPath + "/" + bookData.epubName, function (err) {
                        if (err)
                          reject(err);
                        fs
                          .rename("./" + bookData.tmp + bookData.content, bookPath + "/" + bookData.content, function (err) {
                            if (err)
                              reject(err);
                            fs
                              .rmdir("./" + bookData.tmp, function (err) {
                                if (err)
                                  reject(err);
                                }
                              );
                          });
                      });
                }
              );
              Book.author = book["dc:creator"][0]._;
              Book.title = book["dc:title"][0];
              if (typeof book["dc:description"] !== "undefined")
                Book.description = book["dc:description"][0];
              if (typeof cover[0] !== "undefined")
                Book.cover = cover[0]["$"].content;
              Book.subject = book["dc:subject"];
              if (typeof book["dc:language"][0] !== "undefined")
                Book.language = typeof book["dc:language"][0] === "object"
                  ? book["dc:language"][0]._
                  : book["dc:language"][0];
              if (typeof book["dc:publisher"] !== "undefined")
                Book.publisher = book["dc:publisher"][0];
              if (typeof book["dc:date"] !== "undefined")
                Book.pubdate = typeof book["dc:date"][0] === "object"
                  ? book["dc:date"][0]._
                  : book["dc:date"][0];
              if (typeof rating[0] !== "undefined")
                Book.rating = rating[0]["$"].content;
              resolve(Book);
            });
        });
    });
  }
  function parse(path, outDir, callback) {
    open(path, outDir)
      .then(xmlParser)
      .then(callback);
  }
  return {parse: parse};

})();

module.exports = epubParser;<commit_msg>Another hotfix<commit_after>var epubParser;

epubParser = (function () {
  var fs = require("fs");
  var xml2js = require("xml2js");
  var _ = require("lodash");
  var mkdirp = require("mkdirp");
  var yauzl = require("yauzl");
  var PATH = require('path');
  var parser = new xml2js.Parser();

  function open(path, outDir) {
    // a container to pass book file locations
    var bookData = {
      cover: "",
      path: path,
      epubName: path
        .split("/")
        .pop(),
      tmp: PATH.basename(path, ".epub") + "/",
      outDir: outDir
    }
    return new Promise(function (resolve, reject) {
      mkdirp("./" + bookData.tmp, function (err) {
        if (err)
          reject(err);
       // Unzip the content and cover
        yauzl
          .open(path, {
            lazyEntries: true
          }, function (err, zipfile) {
            if (err)
              throw err;
            zipfile.readEntry();
            zipfile.on("entry", function (entry) {
              // at file entry
              zipfile
                .openReadStream(entry, function (err, readStream) {
                  if (err)
                    reject(err);
                  var fileName = entry
                    .fileName
                    .split("/")
                    .pop();
                  if(bookData.cover === 'notfound'){
                    if(fileName.split(".").pop() === "jpg" || fileName.split(".").pop() === "jpeg"){
                      bookData.cover = fileName;
                      readStream.pipe(fs.createWriteStream("./" + bookData.tmp + fileName));
                      readStream.on("end", function () {
                        zipfile.readEntry();
                      });
                    }
                  }
                  else if (fileName === bookData.cover){
                      readStream.pipe(fs.createWriteStream("./" + bookData.tmp + fileName));
                      readStream.on("end", function () {
                        zipfile.readEntry();
                      });
                    }
                  else if (fileName === (bookData.cover + ".jpg") ||
                  fileName === (bookData.cover + ".jpeg") || fileName === (bookData.cover + ".png")) {
                      bookData.cover = fileName;
                      readStream.pipe(fs.createWriteStream("./" + bookData.tmp + fileName));
                      readStream.on("end", function () {
                        zipfile.readEntry();
                      });
                    }
                  // get the xml parse and try to find cover image if exists
                  // it is assumed that xml file is on the top directory level
                  else if (fileName.split(".").pop() === "opf") {
                    console.log("got opf");
                    bookData.content = fileName;
                    readStream.pipe(fs.createWriteStream("./" + bookData.tmp + fileName));
                    readStream.on("end", function () {
                    fs.readFile("./" + bookData.tmp + fileName, function(err, data) {
                    parser.parseString(data, function (err, result) {
                        var metadata = result.package.metadata[0].meta
                        if(typeof metadata !== "undefined")
                        for(var i = 0; i< metadata.length; i++){
                            if(metadata[i]["$"].name === "cover"){
                              bookData.cover = metadata[i]["$"].content;
                            }
                        }
                        if(bookData.cover===''){
                          bookData.cover = "notfound";
                        }
                        zipfile.readEntry();
                    })
                });
                    });
                  } else
                    zipfile.readEntry();
                  }
                );
            });
            zipfile.once("end", function (err) {
              if (err)
                console.log(err);
              zipfile.close();
              resolve(bookData);
            });
            zipfile.on("error", function (err) {
              if (err)
                console.log(err);
              zipfile.close();
              reject(err);
            })
          });
      });
    });
  }

  var convArr = function (arr) {
    var jsonData = {};
    _.forEach(arr, function (elem) {
      var keys = Object.keys(elem);
      _.forEach(keys, function (key) {
        var value = elem[key];
        jsonData[key] = value;
      });
    })
    return jsonData;
  };

  function xmlParser(bookData) {
    var Book = {};
    return new Promise(function (resolve, reject) {
      fs
        .readFile("./" + bookData.tmp + bookData.content, function (err, data) {
          if (err)
            reject(err);
          parser
            .parseString(data, function (err, result) {
              var jsondata = JSON.parse(JSON.stringify(result));
              var book = convArr(jsondata.package.metadata);
              var cover = _.filter(book.meta, (i) => i["$"].name === "cover");
              var rating = _.filter(book.meta, (i) => i["$"].name === "calibre:rating");
              var bookPath = bookData.outDir + "/Books/" + book["dc:creator"][0]._ + "/" + book["dc:title"][0];
              mkdirp(bookPath, function (err) {
                if (err)
                  reject(err);
                if (cover !== "undefined" && cover.length > 0)
                  fs.rename("./" + bookData.tmp + bookData.cover, bookPath + "/" + cover[0]["$"].content, function (err) {
                    if (err)
                      reject(err);
                    fs
                      .rename(bookData.path, bookPath + "/" + bookData.epubName, function (err) {
                        if (err)
                          reject(err);
                        fs
                          .rename("./" + bookData.tmp + bookData.content, bookPath + "/" + bookData.content, function (err) {
                            if (err)
                              reject(err);
                            fs
                              .rmdir("./" + bookData.tmp, function (err) {
                                if (err)
                                  reject(err);
                                }
                              );
                          });
                      });
                  });
                  else if (bookData.cover !== "" && bookData.cover !== "notfound")
                  fs.rename("./" + bookData.tmp + bookData.cover, bookPath + "/" + bookData.cover, function (err) {
                    if (err)
                      reject(err);
                    fs
                      .rename(bookData.path, bookPath + "/" + bookData.epubName, function (err) {
                        if (err)
                          reject(err);
                        fs
                          .rename("./" + bookData.tmp + bookData.content, bookPath + "/" + bookData.content, function (err) {
                            if (err)
                              reject(err);
                            fs
                              .rmdir("./" + bookData.tmp, function (err) {
                                if (err)
                                  reject(err);
                                }
                              );
                          });
                      });
                  });
                  else
                    fs
                      .rename(bookData.path, bookPath + "/" + bookData.epubName, function (err) {
                        if (err)
                          reject(err);
                        fs
                          .rename("./" + bookData.tmp + bookData.content, bookPath + "/" + bookData.content, function (err) {
                            if (err)
                              reject(err);
                            fs
                              .rmdir("./" + bookData.tmp, function (err) {
                                if (err)
                                  reject(err);
                                }
                              );
                          });
                      });
                }
              );
              Book.author = book["dc:creator"][0]._;
              Book.title = book["dc:title"][0];
              if (typeof book["dc:description"] !== "undefined")
                Book.description = book["dc:description"][0];
              if (typeof cover[0] !== "undefined")
                Book.cover = cover[0]["$"].content;
              if (typeof cover [0] === "undefined" && bookData.cover !== "notfound" && bookData.cover !== "")
                Book.cover = bookData.cover;
              Book.subject = book["dc:subject"];
              if (typeof book["dc:language"][0] !== "undefined")
                Book.language = typeof book["dc:language"][0] === "object"
                  ? book["dc:language"][0]._
                  : book["dc:language"][0];
              if (typeof book["dc:publisher"] !== "undefined")
                Book.publisher = book["dc:publisher"][0];
              if (typeof book["dc:date"] !== "undefined")
                Book.pubdate = typeof book["dc:date"][0] === "object"
                  ? book["dc:date"][0]._
                  : book["dc:date"][0];
              if (typeof rating[0] !== "undefined")
                Book.rating = rating[0]["$"].content;
              resolve(Book);
            });
        });
    });
  }
  function parse(path, outDir, callback) {
    open(path, outDir)
      .then(xmlParser)
      .then(callback);
  }
  return {parse: parse};

})();

module.exports = epubParser;<|endoftext|>


<commit_before>// Copyright 2013 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Flags: --harmony-symbols --harmony-collections
// Flags: --expose-gc --allow-natives-syntax

var symbols = []

// Test different forms of constructor calls, all equivalent.
function TestNew() {
  function IndirectSymbol() { return new Symbol }
  function indirect() { return new IndirectSymbol() }
  for (var i = 0; i < 10; ++i) {
    symbols.push(new Symbol)
    symbols.push(new Symbol())
    symbols.push(Symbol())
    symbols.push(indirect())
  }
  %OptimizeFunctionOnNextCall(indirect)
  indirect()  // Call once before GC throws away type feedback.
  gc()        // Promote existing symbols and then allocate some more.
  for (var i = 0; i < 10; ++i) {
    symbols.push(new Symbol)
    symbols.push(new Symbol())
    symbols.push(Symbol())
    symbols.push(indirect())
  }
}
TestNew()

function TestType() {
  for (var i in symbols) {
    assertTrue(%_IsSymbol(symbols[i]))
    assertEquals("object", typeof symbols[i])
    assertTrue(typeof symbols[i] === "object")
    assertEquals("[object Symbol]", Object.prototype.toString.call(symbols[i]))
  }
}
TestType()

function TestEquality() {
  // Every symbol should equal itself.
  for (var i in symbols) {
    assertSame(symbols[i], symbols[i])
    assertEquals(symbols[i], symbols[i])
    assertTrue(Object.is(symbols[i], symbols[i]))
    assertTrue(symbols[i] === symbols[i])
    assertTrue(symbols[i] == symbols[i])
  }

  // All symbols should be distinct.
  for (var i = 0; i < symbols.length; ++i) {
    for (var j = i + 1; j < symbols.length; ++j) {
      assertFalse(Object.is(symbols[i], symbols[j]))
      assertFalse(symbols[i] === symbols[j])
      assertFalse(symbols[i] == symbols[j])
    }
  }
}
TestEquality()

function TestGet() {
  for (var i in symbols) {
    assertEquals("[object Symbol]", symbols[i].toString())
    assertEquals(undefined, symbols[i].valueOf)
    assertEquals(undefined, symbols[i].a)
    assertEquals(undefined, symbols[i]["a" + "b"])
    assertEquals(undefined, symbols[i]["" + "1"])
    assertEquals(undefined, symbols[i][62])
  }
}
TestGet()

function TestSet() {
  for (var i in symbols) {
    symbols[i].toString = 0
    assertEquals("[object Symbol]", symbols[i].toString())
    symbols[i].a = 0
    assertEquals(undefined, symbols[i].a)
    symbols[i]["a" + "b"] = 0
    assertEquals(undefined, symbols[i]["a" + "b"])
    symbols[i][62] = 0
    assertEquals(undefined, symbols[i][62])
  }
}
TestSet()

function TestCollections() {
  var set = new Set
  var map = new Map
  var weakmap = new WeakMap
  for (var i in symbols) {
    set.add(symbols[i])
    map.set(symbols[i], i)
    weakmap.set(symbols[i], i)
  }
  assertEquals(symbols.length, set.size)
  assertEquals(symbols.length, map.size)
  for (var i in symbols) {
    assertTrue(set.has(symbols[i]))
    assertTrue(map.has(symbols[i]))
    assertTrue(weakmap.has(symbols[i]))
    assertEquals(i, map.get(symbols[i]))
    assertEquals(i, weakmap.get(symbols[i]))
  }
  for (var i in symbols) {
    assertTrue(set.delete(symbols[i]))
    assertTrue(map.delete(symbols[i]))
    assertTrue(weakmap.delete(symbols[i]))
  }
  assertEquals(0, set.size)
  assertEquals(0, map.size)
}
TestCollections()

function TestKeySet(obj) {
  // Set the even symbols via assignment.
  for (var i = 0; i < symbols.length; i += 2) {
    obj[symbols[i]] = i
  }
}

function TestKeyDefine(obj) {
  // Set the odd symbols via defineProperty (as non-enumerable).
  for (var i = 1; i < symbols.length; i += 2) {
    Object.defineProperty(obj, symbols[i], {value: i, configurable: true})
  }
}

function TestKeyGet(obj) {
  var obj2 = Object.create(obj)
  for (var i in symbols) {
    assertEquals(i|0, obj[symbols[i]])
    assertEquals(i|0, obj2[symbols[i]])
  }
}

function TestKeyHas() {
  for (var i in symbols) {
    assertTrue(symbols[i] in obj)
    assertTrue(Object.hasOwnProperty.call(obj, symbols[i]))
  }
}

function TestKeyEnum(obj) {
  for (var name in obj) {
    assertFalse(%_IsSymbol(name))
  }
}

function TestKeyKeys(obj) {
  assertEquals(0, Object.keys(obj).length)
  assertTrue(symbols.length <= Object.getOwnPropertyNames(obj).length)
}

function TestKeyDescriptor(obj) {
  for (var i in symbols) {
    var desc = Object.getOwnPropertyDescriptor(obj, symbols[i]);
    assertEquals(i|0, desc.value)
    assertTrue(desc.configurable)
    assertEquals(i % 2 == 0, desc.writable)
    assertEquals(i % 2 == 0, desc.enumerable)
    assertEquals(i % 2 == 0,
        Object.prototype.propertyIsEnumerable.call(obj, symbols[i]))
  }
}

function TestKeyDelete(obj) {
  for (var i in symbols) {
    delete obj[symbols[i]]
  }
  for (var i in symbols) {
    assertEquals(undefined, Object.getOwnPropertyDescriptor(obj, symbols[i]))
  }
}

var objs = [{}, [], Object.create(null), Object(1), new Map, function(){}]

for (var i in objs) {
  var obj = objs[i]
  TestKeySet(obj)
  TestKeyDefine(obj)
  TestKeyGet(obj)
  TestKeyHas(obj)
  TestKeyEnum(obj)
  TestKeyKeys(obj)
  TestKeyDescriptor(obj)
  TestKeyDelete(obj)
}
<commit_msg>ES6 symbols: refine test for getOwnPropertyNames<commit_after>// Copyright 2013 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Flags: --harmony-symbols --harmony-collections
// Flags: --expose-gc --allow-natives-syntax

var symbols = []

// Test different forms of constructor calls, all equivalent.
function TestNew() {
  function IndirectSymbol() { return new Symbol }
  function indirect() { return new IndirectSymbol() }
  for (var i = 0; i < 10; ++i) {
    symbols.push(new Symbol)
    symbols.push(new Symbol())
    symbols.push(Symbol())
    symbols.push(indirect())
  }
  %OptimizeFunctionOnNextCall(indirect)
  indirect()  // Call once before GC throws away type feedback.
  gc()        // Promote existing symbols and then allocate some more.
  for (var i = 0; i < 10; ++i) {
    symbols.push(new Symbol)
    symbols.push(new Symbol())
    symbols.push(Symbol())
    symbols.push(indirect())
  }
}
TestNew()

function TestType() {
  for (var i in symbols) {
    assertTrue(%_IsSymbol(symbols[i]))
    assertEquals("object", typeof symbols[i])
    assertTrue(typeof symbols[i] === "object")
    assertEquals("[object Symbol]", Object.prototype.toString.call(symbols[i]))
  }
}
TestType()

function TestEquality() {
  // Every symbol should equal itself.
  for (var i in symbols) {
    assertSame(symbols[i], symbols[i])
    assertEquals(symbols[i], symbols[i])
    assertTrue(Object.is(symbols[i], symbols[i]))
    assertTrue(symbols[i] === symbols[i])
    assertTrue(symbols[i] == symbols[i])
  }

  // All symbols should be distinct.
  for (var i = 0; i < symbols.length; ++i) {
    for (var j = i + 1; j < symbols.length; ++j) {
      assertFalse(Object.is(symbols[i], symbols[j]))
      assertFalse(symbols[i] === symbols[j])
      assertFalse(symbols[i] == symbols[j])
    }
  }
}
TestEquality()

function TestGet() {
  for (var i in symbols) {
    assertEquals("[object Symbol]", symbols[i].toString())
    assertEquals(undefined, symbols[i].valueOf)
    assertEquals(undefined, symbols[i].a)
    assertEquals(undefined, symbols[i]["a" + "b"])
    assertEquals(undefined, symbols[i]["" + "1"])
    assertEquals(undefined, symbols[i][62])
  }
}
TestGet()

function TestSet() {
  for (var i in symbols) {
    symbols[i].toString = 0
    assertEquals("[object Symbol]", symbols[i].toString())
    symbols[i].a = 0
    assertEquals(undefined, symbols[i].a)
    symbols[i]["a" + "b"] = 0
    assertEquals(undefined, symbols[i]["a" + "b"])
    symbols[i][62] = 0
    assertEquals(undefined, symbols[i][62])
  }
}
TestSet()

function TestCollections() {
  var set = new Set
  var map = new Map
  var weakmap = new WeakMap
  for (var i in symbols) {
    set.add(symbols[i])
    map.set(symbols[i], i)
    weakmap.set(symbols[i], i)
  }
  assertEquals(symbols.length, set.size)
  assertEquals(symbols.length, map.size)
  for (var i in symbols) {
    assertTrue(set.has(symbols[i]))
    assertTrue(map.has(symbols[i]))
    assertTrue(weakmap.has(symbols[i]))
    assertEquals(i, map.get(symbols[i]))
    assertEquals(i, weakmap.get(symbols[i]))
  }
  for (var i in symbols) {
    assertTrue(set.delete(symbols[i]))
    assertTrue(map.delete(symbols[i]))
    assertTrue(weakmap.delete(symbols[i]))
  }
  assertEquals(0, set.size)
  assertEquals(0, map.size)
}
TestCollections()

function TestKeySet(obj) {
  // Set the even symbols via assignment.
  for (var i = 0; i < symbols.length; i += 2) {
    obj[symbols[i]] = i
  }
}

function TestKeyDefine(obj) {
  // Set the odd symbols via defineProperty (as non-enumerable).
  for (var i = 1; i < symbols.length; i += 2) {
    Object.defineProperty(obj, symbols[i], {value: i, configurable: true})
  }
}

function TestKeyGet(obj) {
  var obj2 = Object.create(obj)
  for (var i in symbols) {
    assertEquals(i|0, obj[symbols[i]])
    assertEquals(i|0, obj2[symbols[i]])
  }
}

function TestKeyHas() {
  for (var i in symbols) {
    assertTrue(symbols[i] in obj)
    assertTrue(Object.hasOwnProperty.call(obj, symbols[i]))
  }
}

function TestKeyEnum(obj) {
  for (var name in obj) {
    assertFalse(%_IsSymbol(name))
  }
}

function TestKeyNames(obj) {
  assertEquals(0, Object.keys(obj).length)

  var names = Object.getOwnPropertyNames(obj)
  assertTrue(symbols.length <= names.length)
  // TODO(rossberg): once we have iterators, the following would be:
  //   var expected = new Set(symbols)
  var expected = new Set
  for (var i = 0; i < symbols.length; ++i) expected.add(symbols[i])
  for (var i = 0; i < names.length; ++i) {
    var name = names[i]
    var asString = String(name)
    if (asString !== name) {
      assertEquals("[object Symbol]", asString)
      assertTrue(expected.has(name))
      expected.delete(name)
    }
  }
  assertEquals(0, expected.size)
}

function TestKeyDescriptor(obj) {
  for (var i in symbols) {
    var desc = Object.getOwnPropertyDescriptor(obj, symbols[i]);
    assertEquals(i|0, desc.value)
    assertTrue(desc.configurable)
    assertEquals(i % 2 == 0, desc.writable)
    assertEquals(i % 2 == 0, desc.enumerable)
    assertEquals(i % 2 == 0,
        Object.prototype.propertyIsEnumerable.call(obj, symbols[i]))
  }
}

function TestKeyDelete(obj) {
  for (var i in symbols) {
    delete obj[symbols[i]]
  }
  for (var i in symbols) {
    assertEquals(undefined, Object.getOwnPropertyDescriptor(obj, symbols[i]))
  }
}

var objs = [{}, [], Object.create(null), Object(1), new Map, function(){}]

for (var i in objs) {
  var obj = objs[i]
  TestKeySet(obj)
  TestKeyDefine(obj)
  TestKeyGet(obj)
  TestKeyHas(obj)
  TestKeyEnum(obj)
  TestKeyNames(obj)
  TestKeyDescriptor(obj)
  TestKeyDelete(obj)
}
<|endoftext|>


<commit_before>ig.module(
    'game.entities.player'
)
.requires(
    'impact.entity',
    'game.entities.projectiles.demonfang',
    'game.entities.projectiles.lightning',
    'game.entities.projectiles.fiercedemonfang'
)
.defines(function(){
    EntityPlayer = ig.Entity.extend({
        /* Collision Properties
         * type: What group does the player belong to?
         *  TYPE.A: Friendly
         *  TYPE.B: Enemy
         * checkAgainst: What entities do we check against?
         * collides: What happens if we collide with an entity?
        */
        type: ig.Entity.TYPE.A,
        checkAgainst: ig.Entity.TYPE.NONE,
        collides: ig.Entity.COLLIDES.ACTIVE,

        name: 'Kratos',

        /* Setup player properties */
        animSheet: new ig.AnimationSheet('media/kratos-d.png', 140, 100), // Animation sheet
        size: {x: 40, y: 50}, // Size of collision bounding box
        flip: true, // Set flip property to true
        accelGround: 200, // How fast we accelerate for movement on the ground
        accelAir: 310, // How fast we accelerate in the air
        jump: 360, // How high can we jump?
        friction: {x: 500, y: 0}, // Resistance against movement
        maxVel: {x: 100, y: 160}, // Cap our maximum velocity from acceleration
        attacking: false, // Boolean to control when we can attack
        startPosition: null, // Our starting position in the game world, used for respawning
        offset: {x: 50, y: 30},
        running: false,
        arte: null, // Which arte are we using?
        // miniMap: { mapColor: '#0000FF', mapSize: 4, icon: 'media/plus.png', iconOffset: {x: 0, y: 0} },

        /* Player stats */
        // Just temporary for now
        stats : {
            str: 10,
            mag: 5,
            def: 9,
            spd: 10,
            totalExp: 0,
            nextExp: 10,
            level: 1,
            hp: 150,
            tp: 100,
            maxHP: 150,
            maxTP: 100,
        },

        skillPoints: 10, // How many skill points we have to allocate
        health: 150, // Override base health value
        tp: 100, // Technical Points

        init: function(x, y, settings){
            this.parent(x, y, settings);
            /* Set up player animations */

            /* this.addAnim(name, speed, frames)
             * name: string
             *  - the identifier for this animation
             * speed: number
             *  - how fast to iterate through frame cycle
             * frames: array
             *  - array of what frames to animate
            */

            this.addAnim('idle', 1, [1]);
            this.addAnim('walk', 0.10, [14, 15, 16, 17, 18, 19, 20]);
            this.addAnim('run', 0.10, [28, 29, 30, 31, 32, 33]);
            this.addAnim('jump', 0.10, [48]);
            this.addAnim('fall', 0.10, [48]);
            this.addAnim('lightningBlade', 0.10, [57, 58, 59, 60], true);
            this.addAnim('hellPyre', 0.10, [71, 72, 73, 74, 75, 76, 77, 84, 85, 86, 87, 88, 89, 90, 91], false)
            this.addAnim('demon_fang', 0.10, [73, 74, 75, 76], false);

            this.atkTimer = new ig.Timer(1.5);
            this.startPosition = {x:x, y:y};
            this.parent(x, y, settings);
        },

        update: function(){
            // Set up movement cases
            console.log(this.pos.y);
            var accel = this.standing ? this.accelGround : this.accelAir;
            if(ig.input.state('left') && !ig.game.menuVisible && !this.attacking){
                this.accel.x = -accel;
                this.flip = false;
                /*
                 *  Lightning blade framework
                 *  -------------------------
                 * Pressing left/right in combination with 'a' will trigger
                 * the lightning blade attack.
                 *
                 * Implementation
                 * --------------
                 * 1. Put timer on attack. This is to:
                 *      - Prevent spamming of arte (cooldown)
                 *      - Allow animations to finish
                 *      - Lock player into specific animation
                 * 2. If player has not attacked (!this.attacking):
                 *      - Initiate attack. Reset timer.
                 * 3. Until timer expires, we set attacking = true, preventing
                 *    additional triggers of Lightning Blade.
                 * 4. Once the timer expires, we reset the attacking boolean flag.
                 *
                 * TODO
                 * ----
                 * 1. Setup animation frames for Lightning blade
                */
                // Trigger Lightning blade facing left
                if(ig.input.state('attack') && !this.attacking){
                    this.atkTimer.reset();
                    // ig.game.spawnEntity(EntityDemonFang, this.pos.x - 20, this.pos.y + 7, {flip: !this.flip});
                    this.tp -= 5;
                    this.currentAnim = this.anims.lightningBlade;
                    // ig.game.spawnEntity(EntityFierceDemonFang, this.pos.x - 30, this.pos.y + 4, {flip: !this.flip});
                    console.log('Lightning blade');
                    if(this.atkTimer.delta() < 0){
                        this.attacking = true;
                        this.size.x = 50;
                        this.offset.x = 25;
                        // this.offset.x = 25;
                    }
                }
            } else if(ig.input.state('right') && !ig.game.menuVisible && !this.attacking){
                this.accel.x = accel;
                this.flip = true;
                // Trigger lightning blade facing right
                if(ig.input.state('attack') && !this.attacking){
                    this.atkTimer.reset();
                    this.vel.x = 10;
                    // this.pos.x += 30;
                    // ig.game.spawnEntity(EntityDemonFang, this.pos.x + 40, this.pos.y + 7, {flip: !this.flip});
                    // ig.game.spawnEntity(EntityFierceDemonFang, this.pos.x + 20, this.pos.y + 4, {flip: !this.flip});
                    console.log('Lightning blade');
                    if(this.atkTimer.delta() < 0){
                        this.attacking = true;
                        this.size.x = 50;
                        this.arte = 'lightning_blade';
                        console.log("Doing an attack")
                    }
                }
            } else if(ig.input.state('down') && !ig.game.menuVisible && !this.attacking){
                if(ig.input.state('attack') && !this.attacking){
                    this.atkTimer.reset();
                    console.log('Casting Spell');
                    // ig.game.spawnEntity(EntityLightning, this.pos.x + 40, this.pos.y - 40, {flip: !this.flip});
                    ig.game.spawnEntity(EntityLightning, this.pos.x + 30, this.pos.y - 40, {flip: !this.flip});
                    // ig.game.spawnEntity(EntityLightning, this.pos.x + 20, this.pos.y - 40, {flip: !this.flip});
                    if(this.atkTimer.delta() < 0){
                        this.attacking = true;
                    }
                }

             } else if(ig.input.state('up') && !ig.game.menuVisible && !this.attacking){
                // Stop the player
                this.accel.x = 0;
                if(ig.input.state('attack') && !this.attacking){
                    this.atkTimer.reset();
                    console.log('Hell Pyre');
                    if(this.atkTimer.delta() < 0){
                        this.attacking = true;
                        this.arte = 'hell_pyre';
                    }
                }

             } else if(ig.input.state('attack') && !ig.game.menuVisible && !this.attacking){
                this.accel.x = 0;
                if(this.flip === false){
                    ig.game.spawnEntity(EntityDemonFang, this.pos.x - 20, this.pos.y + 7, {flip: !this.flip});
                } else if (this.flip = true){
                    ig.game.spawnEntity(EntityDemonFang, this.pos.x + 40, this.pos.y + 7, {flip: !this.flip});
                }
                this.atkTimer.reset();
                    console.log('Demon Fang');
                    if(this.atkTimer.delta() < 0){
                        this.attacking = true;
                        this.arte = 'demon_fang';
                    }
             } else {
                // If we aren't moving in any direction, we must
                // be standing still. Therefore, accel = 0
                this.accel.x = 0;
            }

            // Used to reset attack timer after time has elasped.
            // Once the timer has expired, we can attack again
            if(this.atkTimer.delta() > 0){
                this.attacking = false;
            }

            // If the player is using an arte, stop them in place
            // The player will be stopped based on this.atkTimer
            // NOTE: this is also useful for spell casting cooldowns
            if(this.attacking){
                // Stop the player
                this.accel.x = 0;
            }

            // Jumping logic: CASE 1
            if(this.standing && ig.input.state('jump') && !ig.game.menuVisible) {
                if(this.vel.y == 0) {
                    this.vel.y = -this.jump;
                    this.falling = false;
                }
            }

            // Jumping logic: CASE 2
            else if(!this.standing && !ig.input.state('jump') && !this.falling && !ig.game.menuVisible){
                this.vel.y = Math.floor(this.vel.y/3);
                this.falling = true;
            }

            // Flip the player based on left/right movement
            this.currentAnim.flip.x = this.flip;

            this.parent();

            /* Here we animate the player based on which arte they are using */
            if(this.attacking === true && this.arte === 'lightning_blade'){
                this.currentAnim = this.anims.lightningBlade;
                this.size.x = 65;
                if(this.flip === true){
                    //this.offset.x = 25;
                }
            }

            else if (this.attacking === true && this.arte === 'hell_pyre'){
                this.currentAnim = this.anims.hellPyre;
            }

            else if (this.attacking === true && this.arte === 'demon_fang'){
                this.currentAnim = this.anims.demon_fang;
            } else {
                this.size.x = 40;
                this.offset.x = 50;
            }
            // Animate player based on velocity
            // This may be refactored later

            // CASE 1: Y-velocity is negative and we aren't standing...
            //         therefore we are jumping.
            if(this.vel.y < 0 && !this.standing && !this.attacking)
                this.currentAnim = this.anims.jump;
            // CASE 2: Y-velocity is positive and we aren't standing...
            //         Y-velocity is only positive when falling
            else if(this.vel.y > 0 && !this.standing && !this.attacking)
                this.currentAnim = this.anims.fall;
            // CASE 3: X-velocity is not zero, we must be moving
            else if(this.vel.x > 0 && this.vel.x < 100 && !this.attacking || this.vel.x < 0 && this.vel.x > -100 && !this.attacking) {
                this.currentAnim = this.anims.walk;
            }
            else if(this.vel.x >= 100 && !this.attacking || this.vel.x <= -100 && !this.attacking) {
                this.currentAnim = this.anims.run;
            }
            // CASE 4: We are not moving, play idle animation
            else if (this.vel.y === 0 && this.vel.x == 0 && !this.attacking) {
                this.currentAnim = this.anims.idle;

            }

        },

        // This method is called on player's death
        kill: function() {
            this.parent();
            ig.game.respawnPlayerAtLastCheckpoint(this.pos.x, this.pos.y);
        },

        // On a player's death, this method checks # of lives and displays the proper screen
        // If lives > 0, respawn the player, else show game over screen
        onDeath: function() {
            ig.game.lives --;
            if(ig.game.lives < 0)
                ig.game.gameOver();
        },

    });
});
<commit_msg>Removing console logs from overloading game loop<commit_after>ig.module(
    'game.entities.player'
)
.requires(
    'impact.entity',
    'game.entities.projectiles.demonfang',
    'game.entities.projectiles.lightning',
    'game.entities.projectiles.fiercedemonfang'
)
.defines(function(){
    EntityPlayer = ig.Entity.extend({
        /* Collision Properties
         * type: What group does the player belong to?
         *  TYPE.A: Friendly
         *  TYPE.B: Enemy
         * checkAgainst: What entities do we check against?
         * collides: What happens if we collide with an entity?
        */
        type: ig.Entity.TYPE.A,
        checkAgainst: ig.Entity.TYPE.NONE,
        collides: ig.Entity.COLLIDES.ACTIVE,

        name: 'Kratos',

        /* Setup player properties */
        animSheet: new ig.AnimationSheet('media/kratos-d.png', 140, 100), // Animation sheet
        size: {x: 40, y: 50}, // Size of collision bounding box
        flip: true, // Set flip property to true
        accelGround: 200, // How fast we accelerate for movement on the ground
        accelAir: 310, // How fast we accelerate in the air
        jump: 360, // How high can we jump?
        friction: {x: 500, y: 0}, // Resistance against movement
        maxVel: {x: 100, y: 160}, // Cap our maximum velocity from acceleration
        attacking: false, // Boolean to control when we can attack
        startPosition: null, // Our starting position in the game world, used for respawning
        offset: {x: 50, y: 30},
        running: false,
        arte: null, // Which arte are we using?
        // miniMap: { mapColor: '#0000FF', mapSize: 4, icon: 'media/plus.png', iconOffset: {x: 0, y: 0} },

        /* Player stats */
        // Just temporary for now
        stats : {
            str: 10,
            mag: 5,
            def: 9,
            spd: 10,
            totalExp: 0,
            nextExp: 10,
            level: 1,
            hp: 150,
            tp: 100,
            maxHP: 150,
            maxTP: 100,
        },

        skillPoints: 10, // How many skill points we have to allocate
        health: 150, // Override base health value
        tp: 100, // Technical Points

        init: function(x, y, settings){
            this.parent(x, y, settings);
            /* Set up player animations */

            /* this.addAnim(name, speed, frames)
             * name: string
             *  - the identifier for this animation
             * speed: number
             *  - how fast to iterate through frame cycle
             * frames: array
             *  - array of what frames to animate
            */

            this.addAnim('idle', 1, [1]);
            this.addAnim('walk', 0.10, [14, 15, 16, 17, 18, 19, 20]);
            this.addAnim('run', 0.10, [28, 29, 30, 31, 32, 33]);
            this.addAnim('jump', 0.10, [48]);
            this.addAnim('fall', 0.10, [48]);
            this.addAnim('lightningBlade', 0.10, [57, 58, 59, 60], true);
            this.addAnim('hellPyre', 0.10, [71, 72, 73, 74, 75, 76, 77, 84, 85, 86, 87, 88, 89, 90, 91], false)
            this.addAnim('demon_fang', 0.10, [73, 74, 75, 76], false);

            this.atkTimer = new ig.Timer(1.5);
            this.demonFangTimer = new ig.Timer(0.5);
            this.startPosition = {x:x, y:y};
            this.parent(x, y, settings);
        },

        update: function(){
            var accel = this.standing ? this.accelGround : this.accelAir;
            if(ig.input.state('left') && !ig.game.menuVisible && !this.attacking){
                this.accel.x = -accel;
                this.flip = false;
                /*
                 *  Lightning blade framework
                 *  -------------------------
                 * Pressing left/right in combination with 'a' will trigger
                 * the lightning blade attack.
                 *
                 * Implementation
                 * --------------
                 * 1. Put timer on attack. This is to:
                 *      - Prevent spamming of arte (cooldown)
                 *      - Allow animations to finish
                 *      - Lock player into specific animation
                 * 2. If player has not attacked (!this.attacking):
                 *      - Initiate attack. Reset timer.
                 * 3. Until timer expires, we set attacking = true, preventing
                 *    additional triggers of Lightning Blade.
                 * 4. Once the timer expires, we reset the attacking boolean flag.
                 *
                 * TODO
                 * ----
                 * 1. Setup animation frames for Lightning blade
                */
                // Trigger Lightning blade facing left
                if(ig.input.state('attack') && !this.attacking){
                    this.atkTimer.reset();
                    // ig.game.spawnEntity(EntityDemonFang, this.pos.x - 20, this.pos.y + 7, {flip: !this.flip});
                    this.tp -= 5;
                    this.currentAnim = this.anims.lightningBlade;
                    // ig.game.spawnEntity(EntityFierceDemonFang, this.pos.x - 30, this.pos.y + 4, {flip: !this.flip});
                    if(this.atkTimer.delta() < 0){
                        this.attacking = true;
                        this.size.x = 50;
                        this.offset.x = 25;
                        // this.offset.x = 25;
                    }
                }
            } else if(ig.input.state('right') && !ig.game.menuVisible && !this.attacking){
                this.accel.x = accel;
                this.flip = true;
                // Trigger lightning blade facing right
                if(ig.input.state('attack') && !this.attacking){
                    this.atkTimer.reset();
                    this.vel.x = 10;
                    // this.pos.x += 30;
                    // ig.game.spawnEntity(EntityDemonFang, this.pos.x + 40, this.pos.y + 7, {flip: !this.flip});
                    // ig.game.spawnEntity(EntityFierceDemonFang, this.pos.x + 20, this.pos.y + 4, {flip: !this.flip});
                    if(this.atkTimer.delta() < 0){
                        this.attacking = true;
                        this.size.x = 50;
                        this.arte = 'lightning_blade';
                        console.log("Doing an attack")
                    }
                }
            } else if(ig.input.state('down') && !ig.game.menuVisible && !this.attacking){
                if(ig.input.state('attack') && !this.attacking){
                    this.atkTimer.reset();
                    // ig.game.spawnEntity(EntityLightning, this.pos.x + 40, this.pos.y - 40, {flip: !this.flip});
                    ig.game.spawnEntity(EntityLightning, this.pos.x + 30, this.pos.y - 40, {flip: !this.flip});
                    // ig.game.spawnEntity(EntityLightning, this.pos.x + 20, this.pos.y - 40, {flip: !this.flip});
                    if(this.atkTimer.delta() < 0){
                        this.attacking = true;
                    }
                }

             } else if(ig.input.state('up') && !ig.game.menuVisible && !this.attacking){
                // Stop the player
                this.accel.x = 0;
                if(ig.input.state('attack') && !this.attacking){
                    this.atkTimer.reset();
                    if(this.atkTimer.delta() < 0){
                        this.attacking = true;
                        this.arte = 'hell_pyre';
                    }
                }

             } else if(ig.input.state('attack') && !ig.game.menuVisible && !this.attacking){
                this.accel.x = 0;
                this.demonFangTimer.reset();
                if(this.flip === false){
                    ig.game.spawnEntity(EntityDemonFang, this.pos.x - 20, this.pos.y + 7, {flip: !this.flip});
                } else if (this.flip = true){
                    ig.game.spawnEntity(EntityDemonFang, this.pos.x + 40, this.pos.y + 7, {flip: !this.flip});
                }
                console.log('Demon Fang');
                if(this.demonFangTimer.delta() < 0){
                    this.attacking = true;
                    this.arte = 'demon_fang';
                }
             } else {
                // If we aren't moving in any direction, we must
                // be standing still. Therefore, accel = 0
                this.accel.x = 0;
            }

            // Used to reset attack timer after time has elasped.
            // Once the timer has expired, we can attack again
            if(this.atkTimer.delta() > 0){
                this.attacking = false;
            }

            if(this.demonFangTimer.delta() > 0){
                this.attacking = false;
            }

            // If the player is using an arte, stop them in place
            // The player will be stopped based on this.atkTimer
            // NOTE: this is also useful for spell casting cooldowns
            if(this.attacking){
                // Stop the player
                this.accel.x = 0;
            }

            // Jumping logic: CASE 1
            if(this.standing && ig.input.state('jump') && !ig.game.menuVisible && !this.attacking) {
                if(this.vel.y == 0) {
                    this.vel.y = -this.jump;
                    this.falling = false;
                }
            }

            // Jumping logic: CASE 2
            else if(!this.standing && !ig.input.state('jump') && !this.falling && !ig.game.menuVisible && !this.attacking){
                this.vel.y = Math.floor(this.vel.y/3);
                this.falling = true;
            }

            // Flip the player based on left/right movement
            this.currentAnim.flip.x = this.flip;

            this.parent();

            /* Here we animate the player based on which arte they are using */
            if(this.attacking === true && this.arte === 'lightning_blade'){
                this.currentAnim = this.anims.lightningBlade;
                // Restore default size parameters
                this.size.x = 65;
            }

            else if (this.attacking === true && this.arte === 'hell_pyre'){
                this.currentAnim = this.anims.hellPyre;
            }

            else if (this.attacking === true && this.arte === 'demon_fang'){
                this.currentAnim = this.anims.demon_fang;
            } else {
                this.size.x = 40;
                this.offset.x = 50;
            }
            // Animate player based on velocity
            // This may be refactored later

            // CASE 1: Y-velocity is negative and we aren't standing...
            //         therefore we are jumping.
            if(this.vel.y < 0 && !this.standing && !this.attacking)
                this.currentAnim = this.anims.jump;
            // CASE 2: Y-velocity is positive and we aren't standing...
            //         Y-velocity is only positive when falling
            else if(this.vel.y > 0 && !this.standing && !this.attacking)
                this.currentAnim = this.anims.fall;
            // CASE 3: X-velocity is not zero, we must be moving
            else if(this.vel.x > 0 && this.vel.x < 100 && !this.attacking || this.vel.x < 0 && this.vel.x > -100 && !this.attacking) {
                this.currentAnim = this.anims.walk;
            }
            else if(this.vel.x >= 100 && !this.attacking || this.vel.x <= -100 && !this.attacking) {
                this.currentAnim = this.anims.run;
            }
            // CASE 4: We are not moving, play idle animation
            else if (this.vel.y === 0 && this.vel.x == 0 && !this.attacking) {
                this.currentAnim = this.anims.idle;

            }

        },

        // This method is called on player's death
        kill: function() {
            this.parent();
            ig.game.respawnPlayerAtLastCheckpoint(this.pos.x, this.pos.y);
        },

        // On a player's death, this method checks # of lives and displays the proper screen
        // If lives > 0, respawn the player, else show game over screen
        onDeath: function() {
            ig.game.lives --;
            if(ig.game.lives < 0)
                ig.game.gameOver();
        },

    });
});
<|endoftext|>


<commit_before>var amountTotal = document.getElementById("sum-total");
var incAmount = document.getElementsByName("incAmount");
var expAmount = document.getElementsByName("expAmount");
var incAmountTotal = 0;
var expenseContainer = document.getElementById("expenseContainer");
var mainContainer = document.getElementById("mainContainer");
var diffContainer = document.getElementById("diffContainer")
var diff = document.getElementById("diff");
var expAmountTtl = 0
var incomeTotalFinal = document.getElementById("incomeTotal");
var expenseTotalFinal = document.getElementById("expenseTotal");
var expAmountTotal = document.getElementById("expSum-total");
var mainIncome = document.getElementById("mainIncome");
var mainExpense = document.getElementById("mainExpense");
var welcomeContainer = document.getElementById("welcome");
var amountArr = [];
var amountArr2 = [];
var expAmountArr = [];
var expAmountArr2 = [];
var incomeSrc = document.getElementsByName("incomeSrc");
var expenseSrc = document.getElementsByName("expense-name");
var highest = 0;
var expHighest = 0;
var idIncomeN = 4;
var idExpenseN = 4;

//Income Input handlers
for (var index = 0; index < idIncomeN; index++) {
    var incInID = document.getElementById("amount#" + (index + 1));
    incInID.addEventListener("input", addIncome);
};

// Sum of Inputs
function addUp(a, b) {
    return a + b;
};

// Income input function
function addIncome() {
    for (var i = 0; i < idIncomeN; i++) {
        incAmount = document.getElementsByName("incAmount");
        amountArr[i] = parseFloat(incAmount[i].value) || 0;
        incAmountTotal = amountArr.reduce(addUp);
        amountTotal.innerHTML = incAmountTotal;

    };
};

// Expense Input function
function addExpenses() {
    for (var i = 0; i < idExpenseN; i++) {
        expAmount = document.getElementsByName("expAmount");
        expAmountArr[i] = parseFloat(expAmount[i].value) || 0;
        expAmountTtl = expAmountArr.reduce(addUp);
        expAmountTotal.innerHTML = expAmountTtl;
    };
};

for (var index = 0; index < idExpenseN; index++) {
    var expInID = document.getElementById("expAmount#" + (index + 1));
    expInID.addEventListener("input", addExpenses);
};

// Button Handlers
var nextBtn = document.getElementById("next-btn");
var backBtn = document.getElementById("back-btn");
var backBtn2 = document.getElementById("back-btn2");
var backBtn3 = document.getElementById("back-btn3");
var calculate = document.getElementById("calculate-btn");
var addFeildInc = document.getElementById("add-btnI");
var addFeildExp = document.getElementById("add-btnE");
var deleteBtnInc = document.getElementById("deleteBtnInc");
var deleteBtnExp = document.getElementById("deleteBtnExp");

nextBtn.addEventListener("click", toExpenses);
backBtn.addEventListener("click", toIncome);
backBtn2.addEventListener("click", toExpenses);
backBtn3.addEventListener("click", toIncome);
calculate.addEventListener("click", toDiff);
deleteBtnInc.addEventListener("click", removeInputInc);
deleteBtnExp.addEventListener("click", removeInputExp);

function removeInputInc(){
    var input = document.getElementById("amount#" + idIncomeN);
    var incSource = document.getElementById("incomeSrc" + idIncomeN);
    input.outerHTML = "";
    incSource.outerHTML = "";
    delete input, incSource;
    idIncomeN--
};
function removeInputExp(){
    var input = document.getElementById("expAmount#" + idExpenseN);
    var expSource = document.getElementById("expenseName" + idExpenseN)
    input.outerHTML = "";
    expSource.outerHTML = "";
    delete input, expSource;
    idExpenseN--

};

var incAmountName = document.getElementById("amountName");
var incInputs = document.getElementById("incomeInputs");
addFeildInc.addEventListener("click", addInputI);
function addInputI() {
    idIncomeN++
    var input = document.createElement("input");
    input.setAttribute("id", "amount#" + idIncomeN);
    input.setAttribute("name", "incAmount");
    input.setAttribute("placeholder", "Enter Amount");
    input.setAttribute("type", "number");
    incInputs.appendChild(input).className = "form-control";
    for (var index = 0; index < idIncomeN; index++) {
        var incInID = document.getElementById("amount#" + (index + 1));
        incInID.addEventListener("input", addIncome);
    };

    // Income Source Inputs
    var inputSrc = document.createElement("input");
    inputSrc.setAttribute("id", "incomeSrc" + idIncomeN);
    inputSrc.setAttribute("name", "incomeSrc");
    inputSrc.setAttribute("placeholder", "Enter Source");
    inputSrc.setAttribute("type", "text");
    incAmountName.appendChild(inputSrc).className = "form-control";
    incomeSrc = document.getElementsByName("incomeSrc");;
};

var expenseName = document.getElementById("expenseName");
var expenseInputs = document.getElementById("expenseInputs");
addFeildExp.addEventListener("click", addInputE);
function addInputE() {
    idExpenseN++

    var inputNum = document.createElement("input");
    inputNum.setAttribute("id", "expAmount#" + idExpenseN);
    inputNum.setAttribute("name", "expAmount");
    inputNum.setAttribute("placeholder", "Enter Amount");
    inputNum.setAttribute("type", "number");
    expenseInputs.appendChild(inputNum).className = "form-control";
    for (var index = 0; index < idExpenseN; index++) {
        var expInID = document.getElementById("expAmount#" + (index + 1));
        expInID.addEventListener("input", addExpenses);
    };

    var inputSrc = document.createElement("input");
    inputSrc.setAttribute("id", "expenseName" + idExpenseN);
    inputSrc.setAttribute("name", "expense-name");
    inputSrc.setAttribute("placeholder", "Enter Expense");
    inputSrc.setAttribute("type", "text");
    expenseName.appendChild(inputSrc).className = "form-control";
    expenseSrc = document.getElementsByName("expense-name");

};

function toExpenses() {
    mainContainer.className = "hide";
    expenseContainer.className = "container well";
    diffContainer.className = "hide";
};

function toIncome() {
    expenseContainer.className = "hide";
    mainContainer.className = "container well";
    diffContainer.className = "hide";
};

function toDiff() {
    expenseContainer.className = "hide";
    mainContainer.className = "hide";
    diffContainer.className = "container well";
    diff.innerHTML = incAmountTotal - expAmountTtl;
    incomeTotalFinal.innerHTML = incAmountTotal;
    expenseTotalFinal.innerHTML = expAmountTtl;

    findHighestIncome();

    findHighestExpense();
};

function findHighestIncome() {
    amountArr2 = amountArr.slice();
    amountArr2.sort(function (a, b) {
        return b - a;
    });
    highest = amountArr2.shift() || 0;
    var a = amountArr.indexOf(highest);
    if (incAmountTotal == 0){
        mainIncome.innerHTML = "No Income";
    }
    else if (incomeSrc[a].value === "") {
        mainIncome.innerHTML = "No Source Stated" + " (" + highest + ")";
    }
    else {
        mainIncome.innerHTML = incomeSrc[a].value + " (" + highest + ")";
    };
};

function findHighestExpense() {
    expAmountArr2 = expAmountArr.slice();
    expAmountArr2.sort(function (a, b) {
        return b - a;
    });
    expHighest = expAmountArr2.shift() || 0;
    var b = expAmountArr.indexOf(expHighest);
    if (expAmountTtl == 0){
        mainExpense.innerHTML = "No Expenses";
    }
    else if (expenseSrc[b].value === "") {
        mainExpense.innerHTML = "No Source Stated" + " (" + expHighest + ")";
    }
    else {
        mainExpense.innerHTML = expenseSrc[b].value + " (" + expHighest + ")";
    };
};
<commit_msg>Squash delete button bug<commit_after>var amountTotal = document.getElementById("sum-total");
var incAmount = document.getElementsByName("incAmount");
var expAmount = document.getElementsByName("expAmount");
var incAmountTotal = 0;
var expenseContainer = document.getElementById("expenseContainer");
var mainContainer = document.getElementById("mainContainer");
var diffContainer = document.getElementById("diffContainer")
var diff = document.getElementById("diff");
var expAmountTtl = 0
var incomeTotalFinal = document.getElementById("incomeTotal");
var expenseTotalFinal = document.getElementById("expenseTotal");
var expAmountTotal = document.getElementById("expSum-total");
var mainIncome = document.getElementById("mainIncome");
var mainExpense = document.getElementById("mainExpense");
var welcomeContainer = document.getElementById("welcome");
var amountArr = [];
var amountArr2 = [];
var expAmountArr = [];
var expAmountArr2 = [];
var incomeSrc = document.getElementsByName("incomeSrc");
var expenseSrc = document.getElementsByName("expense-name");
var highest = 0;
var expHighest = 0;
var idIncomeN = 4;
var idExpenseN = 4;

//Income Input handlers
for (var index = 0; index < idIncomeN; index++) {
    var incInID = document.getElementById("amount#" + (index + 1));
    incInID.addEventListener("input", addIncome);
};

// Sum of Inputs
function addUp(a, b) {
    return a + b;
};

// Income input function
function addIncome() {
    for (var i = 0; i < idIncomeN; i++) {
        incAmount = document.getElementsByName("incAmount");
        amountArr[i] = parseFloat(incAmount[i].value) || 0;
        incAmountTotal = amountArr.reduce(addUp);
        amountTotal.innerHTML = incAmountTotal;

    };
};

// Expense Input function
function addExpenses() {
    for (var i = 0; i < idExpenseN; i++) {
        expAmount = document.getElementsByName("expAmount");
        expAmountArr[i] = parseFloat(expAmount[i].value) || 0;
        expAmountTtl = expAmountArr.reduce(addUp);
        expAmountTotal.innerHTML = expAmountTtl;
    };
};

for (var index = 0; index < idExpenseN; index++) {
    var expInID = document.getElementById("expAmount#" + (index + 1));
    expInID.addEventListener("input", addExpenses);
};

// Button Handlers
var nextBtn = document.getElementById("next-btn");
var backBtn = document.getElementById("back-btn");
var backBtn2 = document.getElementById("back-btn2");
var backBtn3 = document.getElementById("back-btn3");
var calculate = document.getElementById("calculate-btn");
var addFeildInc = document.getElementById("add-btnI");
var addFeildExp = document.getElementById("add-btnE");
var deleteBtnInc = document.getElementById("deleteBtnInc");
var deleteBtnExp = document.getElementById("deleteBtnExp");

nextBtn.addEventListener("click", toExpenses);
backBtn.addEventListener("click", toIncome);
backBtn2.addEventListener("click", toExpenses);
backBtn3.addEventListener("click", toIncome);
calculate.addEventListener("click", toDiff);
deleteBtnInc.addEventListener("click", removeInputInc);
deleteBtnExp.addEventListener("click", removeInputExp);

function removeInputInc(){
    var input = document.getElementById("amount#" + idIncomeN);
    var incSource = document.getElementById("incomeSrc" + idIncomeN);
    input.outerHTML = "";
    incSource.outerHTML = "";
    delete input, incSource;
    --idIncomeN;
    amountArr.pop();
    addIncome();
};
function removeInputExp(){
    var input = document.getElementById("expAmount#" + idExpenseN);
    var expSource = document.getElementById("expenseName" + idExpenseN)
    input.outerHTML = "";
    expSource.outerHTML = "";
    delete input, expSource;
    idExpenseN--;
    expAmountArr.pop();
    addExpenses();

};

var incAmountName = document.getElementById("amountName");
var incInputs = document.getElementById("incomeInputs");
addFeildInc.addEventListener("click", addInputI);
function addInputI() {
    idIncomeN++
    var input = document.createElement("input");
    input.setAttribute("id", "amount#" + idIncomeN);
    input.setAttribute("name", "incAmount");
    input.setAttribute("placeholder", "Enter Amount");
    input.setAttribute("type", "number");
    incInputs.appendChild(input).className = "form-control";
    for (var index = 0; index < idIncomeN; index++) {
        var incInID = document.getElementById("amount#" + (index + 1));
        incInID.addEventListener("input", addIncome);
    };

    // Income Source Inputs
    var inputSrc = document.createElement("input");
    inputSrc.setAttribute("id", "incomeSrc" + idIncomeN);
    inputSrc.setAttribute("name", "incomeSrc");
    inputSrc.setAttribute("placeholder", "Enter Source");
    inputSrc.setAttribute("type", "text");
    incAmountName.appendChild(inputSrc).className = "form-control";
    incomeSrc = document.getElementsByName("incomeSrc");;
};

var expenseName = document.getElementById("expenseName");
var expenseInputs = document.getElementById("expenseInputs");
addFeildExp.addEventListener("click", addInputE);
function addInputE() {
    idExpenseN++

    var inputNum = document.createElement("input");
    inputNum.setAttribute("id", "expAmount#" + idExpenseN);
    inputNum.setAttribute("name", "expAmount");
    inputNum.setAttribute("placeholder", "Enter Amount");
    inputNum.setAttribute("type", "number");
    expenseInputs.appendChild(inputNum).className = "form-control";
    for (var index = 0; index < idExpenseN; index++) {
        var expInID = document.getElementById("expAmount#" + (index + 1));
        expInID.addEventListener("input", addExpenses);
    };

    var inputSrc = document.createElement("input");
    inputSrc.setAttribute("id", "expenseName" + idExpenseN);
    inputSrc.setAttribute("name", "expense-name");
    inputSrc.setAttribute("placeholder", "Enter Expense");
    inputSrc.setAttribute("type", "text");
    expenseName.appendChild(inputSrc).className = "form-control";
    expenseSrc = document.getElementsByName("expense-name");

};

function toExpenses() {
    mainContainer.className = "hide";
    expenseContainer.className = "container well";
    diffContainer.className = "hide";
};

function toIncome() {
    expenseContainer.className = "hide";
    mainContainer.className = "container well";
    diffContainer.className = "hide";
};

function toDiff() {
    expenseContainer.className = "hide";
    mainContainer.className = "hide";
    diffContainer.className = "container well";
    diff.innerHTML = incAmountTotal - expAmountTtl;
    incomeTotalFinal.innerHTML = incAmountTotal;
    expenseTotalFinal.innerHTML = expAmountTtl;

    findHighestIncome();

    findHighestExpense();
};

function findHighestIncome() {
    amountArr2 = amountArr.slice();
    amountArr2.sort(function (a, b) {
        return b - a;
    });
    highest = amountArr2.shift() || 0;
    var a = amountArr.indexOf(highest);
    if (incAmountTotal == 0){
        mainIncome.innerHTML = "No Income";
    }
    else if (incomeSrc[a].value === "") {
        mainIncome.innerHTML = "No Source Stated" + " (" + highest + ")";
    }
    else {
        mainIncome.innerHTML = incomeSrc[a].value + " (" + highest + ")";
    };
};

function findHighestExpense() {
    expAmountArr2 = expAmountArr.slice();
    expAmountArr2.sort(function (a, b) {
        return b - a;
    });
    expHighest = expAmountArr2.shift() || 0;
    var b = expAmountArr.indexOf(expHighest);
    if (expAmountTtl == 0){
        mainExpense.innerHTML = "No Expenses";
    }
    else if (expenseSrc[b].value === "") {
        mainExpense.innerHTML = "No Source Stated" + " (" + expHighest + ")";
    }
    else {
        mainExpense.innerHTML = expenseSrc[b].value + " (" + expHighest + ")";
    };
};
<|endoftext|>


<commit_before>#! /usr/bin/env node
var inquirer = require("inquirer");
var path=require('path');
var fs=require('fs');
console.log('Please input your GitHub Username and a token to access public/private repository information (to be created on GitHub Settings > Personal access tokens)');
var questions = [
  {
    type: "input",
    name: "User",
    message: "GitHub username"
  }, {
    type: "input",
    name: "token",
    message: "GitHub token"
  }
  ];
 inquirer.prompt(questions, function( answers ) {
	answers.gitaccess = 'git';
	console.log( JSON.stringify(answers, null, "  "));
	fs.writeFile(path.join(__dirname,'../config.json'), JSON.stringify(answers, null, "  "), function(err) {
	  if (err) { console.log(err); process.exit(1); }
	});
});
<commit_msg>fixed some<commit_after>#! /usr/bin/env node
var inquirer = require("inquirer");
var path=require('path');
var fs=require('fs');
console.log('Please input your GitHub Username and a token to access public/private repository information (to be created on GitHub Settings > Personal access tokens)');
var questions = [
  {
    type: "input",
    name: "User",
    message: "GitHub username"
  }, {
    type: "input",
    name: "token",
    message: "GitHub token"
  }
  ];
 inquirer.prompt(questions, function( answers ) {
	answers.gitaccess = 'https';
	console.log( JSON.stringify(answers, null, "  "));
	fs.writeFile(path.join(__dirname,'../config.json'), JSON.stringify(answers, null, "  "), function(err) {
	  if (err) { console.log(err); process.exit(1); }
	});
});
<|endoftext|>


<commit_before>

if (/log/.test(location.hash)) {
  if (/ui/.test(location.hash)) {
    var div = document.createElement('div');
    document.body.appendChild(div);
    ydn.debug.log('ydn.db', 100, div);
  } else {
    ydn.debug.log('ydn.db', 100);
  }
}

var db;
var options = {}; // options = {Mechanisms: ['websql']};
var db_name_event = "tck_test_1_1";
var store_inline = "ts";    // in-line key store
var store_outline = "ts2"; // out-of-line key store

var events_schema = {
  stores: [
    {
      name: store_inline,
      keyPath: 'id',
      dispatchEvents: true,
      type: 'NUMERIC'},
    {
      name: store_outline,
      dispatchEvents: true,
      type: 'NUMERIC'}
  ]};

module("Event", {
  setup: function() {

  },
  teardown: function() {
    //db.close();
    //ydn.db.deleteDatabase(db.getName());
  }
});

asyncTest("connected", function () {
  expect(2);

  var db = new ydn.db.Storage(db_name_event, events_schema);

  db.addEventListener('connected', function(e) {
    equal(e.type, 'connected', 'connected event');
    ok( e.version > 0, 'version number');
    start();
  });

});

asyncTest("created RecordEvent", function () {
  expect(5);

  var db = new ydn.db.Storage(db_name_event, events_schema);

  var key = Math.ceil(Math.random() * 100000);
  var data = { test:"random value", name:"name " + key, id:key };

  db.addEventListener(['created', 'updated'], function(e) {
    //console.log(e);
    equal(e.name, 'RecordEvent', 'event name');
    equal(e.getStoreName(), store_inline, 'store name');
    //equal(e.store_name, store_inline, 'store name');
    equal(e.type, 'created', 'type');
    equal(e.getKey(), key, 'key');
    deepEqual(e.getValue(), data, 'value');
    start();
  });

  db.add(store_inline, data);

  setTimeout(function() {
    // don't wait more than 5 sec.
    start();
  }, 1000);
});

asyncTest("created StoreEvent", function () {
  expect(5);

  var db = new ydn.db.Storage(db_name_event, events_schema);

  var keys = [Math.ceil(Math.random() * 100000),
    Math.ceil(Math.random() * 100000)];
  var data = [{name:"rand key 1", id: keys[0]}, {name:"rand key 2", id: keys[1]}];

  db.addEventListener(['created', 'updated'], function(e) {
    // console.log(e);
    equal(e.name, 'StoreEvent', 'event name');
    equal(e.getStoreName(), store_inline, 'store name');
    //equal(e.store_name, store_inline, 'store name');
    equal(e.type, 'created', 'type');
    deepEqual(e.getKeys(), keys, 'keys');
    deepEqual(e.getValues(), data, 'values');
    start();
  });

  db.add(store_inline, data);
  setTimeout(function() {
    // don't wait more than 5 sec.
    start();
  }, 1000);

});

asyncTest("updated RecordEvent", function () {
  expect(10);

  var db = new ydn.db.Storage(db_name_event, events_schema);

  var key = Math.ceil(Math.random() * 100000);
  var data = { test:"random value", name:"name " + key, id:key };

  var firedCreatedEvent = false;
  db.addEventListener(['created', 'updated'], function(e) {
    //console.log(e);
    if (!firedCreatedEvent) {
      equal(e.name, 'RecordEvent', 'event name');
      equal(e.getStoreName(), store_inline, 'store name');
      //equal(e.store_name, store_inline, 'store name');
      equal(e.type, 'created', 'type');
      equal(e.getKey(), key, 'key');
      deepEqual(e.getValue(), data, 'value');
      firedCreatedEvent = true;
    } else {
      equal(e.name, 'RecordEvent', 'event name');
      equal(e.getStoreName(), store_inline, 'store name');
      //equal(e.store_name, store_inline, 'store name');
      equal(e.type, 'updated', 'type');
      equal(e.getKey(), key, 'key');
      deepEqual(e.getValue(), data, 'value');
      start();
    }

  });

  db.add(store_inline, data);
  db.put(store_inline, data);
  setTimeout(function() {
    // don't wait more than 5 sec.
    start();
  }, 1000);
});

asyncTest("updated StoreEvent", function () {
  expect(10);

  var db = new ydn.db.Storage(db_name_event, events_schema);
  var keys = [Math.ceil(Math.random() * 100000),
    Math.ceil(Math.random() * 100000)];
  var data = [{name:"rand key 1", id: keys[0]}, {name:"rand key 2", id: keys[1]}];

  var firedCreatedEvent = false;
  db.addEventListener(['created', 'updated'], function(e) {
    //console.log(e);
    if (!firedCreatedEvent) {
      equal(e.name, 'StoreEvent', 'event name');
      equal(e.getStoreName(), store_inline, 'store name');
      //equal(e.store_name, store_inline, 'store name');
      equal(e.type, 'created', 'type');
      deepEqual(e.getKeys(), keys, 'created key');
      deepEqual(e.getValues(), data, 'created value');
      firedCreatedEvent = true;
    } else {
      equal(e.name, 'StoreEvent', 'event name');
      equal(e.getStoreName(), store_inline, 'store name');
      //equal(e.store_name, store_inline, 'store name');
      equal(e.type, 'updated', 'type');
      deepEqual(e.getKeys(), keys, 'updated key');
      deepEqual(e.getValues(), data, 'updated value');

      start();
    }
  });

  db.add(store_inline, data);
  db.put(store_inline, data);
  setTimeout(function() {
    // don't wait more than 5 sec.
    start();
  }, 1000);
});

<commit_msg>clean up.<commit_after>

if (/log/.test(location.hash)) {
  if (/ui/.test(location.hash)) {
    var div = document.createElement('div');
    document.body.appendChild(div);
    ydn.debug.log('ydn.db', 100, div);
  } else {
    ydn.debug.log('ydn.db', 100);
  }
}

var db;
var options = {}; // options = {Mechanisms: ['websql']};
var db_name_event = "tck_test_1_1";
var store_inline = "ts";    // in-line key store
var store_outline = "ts2"; // out-of-line key store

var events_schema = {
  stores: [
    {
      name: store_inline,
      keyPath: 'id',
      dispatchEvents: true,
      type: 'NUMERIC'},
    {
      name: store_outline,
      dispatchEvents: true,
      type: 'NUMERIC'}
  ]};

module("Event", {
  setup: function() {

  },
  teardown: function() {
    //db.close();
    //ydn.db.deleteDatabase(db.getName());
  }
});

asyncTest("connected", function () {
  expect(2);

  var db = new ydn.db.Storage(db_name_event, events_schema);

  db.addEventListener('connected', function(e) {
    equal(e.type, 'connected', 'connected event');
    ok( e.version > 0, 'version number');
    start();
  });

});

asyncTest("created RecordEvent", function () {
  expect(5);

  var db = new ydn.db.Storage(db_name_event, events_schema);

  var key = Math.ceil(Math.random() * 100000);
  var data = { test:"random value", name:"name " + key, id:key };

  db.addEventListener(['created', 'updated'], function(e) {
    //console.log(e);
    equal(e.name, 'RecordEvent', 'event name');
    equal(e.getStoreName(), store_inline, 'store name');
    //equal(e.store_name, store_inline, 'store name');
    equal(e.type, 'created', 'type');
    equal(e.getKey(), key, 'key');
    deepEqual(e.getValue(), data, 'value');
    start();
  });

  db.add(store_inline, data);

  setTimeout(function() {
    // don't wait more than 5 sec.
    start();
  }, 1000);
});

asyncTest("created StoreEvent", function () {
  expect(5);

  var db = new ydn.db.Storage(db_name_event, events_schema);

  var keys = [Math.ceil(Math.random() * 100000),
    Math.ceil(Math.random() * 100000)];
  var data = [{name:"rand key 1", id: keys[0]}, {name:"rand key 2", id: keys[1]}];

  db.addEventListener(['created', 'updated'], function(e) {
    // console.log(e);
    equal(e.name, 'StoreEvent', 'event name');
    equal(e.getStoreName(), store_inline, 'store name');
    //equal(e.store_name, store_inline, 'store name');
    equal(e.type, 'created', 'type');
    deepEqual(e.getKeys(), keys, 'keys');
    deepEqual(e.getValues(), data, 'values');
    start();
  });

  db.add(store_inline, data);
  setTimeout(function() {
    // don't wait more than 5 sec.
    start();
  }, 1000);

});

asyncTest("updated RecordEvent", function () {
  expect(10);

  var db = new ydn.db.Storage(db_name_event, events_schema);

  var key = Math.ceil(Math.random() * 100000);
  var data = { test:"random value", name:"name " + key, id:key };

  var firedCreatedEvent = false;
  db.addEventListener(['created', 'updated'], function(e) {
    //console.log(e);
    if (!firedCreatedEvent) {
      equal(e.name, 'RecordEvent', 'event name');
      equal(e.getStoreName(), store_inline, 'store name');
      //equal(e.store_name, store_inline, 'store name');
      equal(e.type, 'created', 'type');
      equal(e.getKey(), key, 'key');
      deepEqual(e.getValue(), data, 'value');
      firedCreatedEvent = true;
    } else {
      equal(e.name, 'RecordEvent', 'event name');
      equal(e.getStoreName(), store_inline, 'store name');
      //equal(e.store_name, store_inline, 'store name');
      equal(e.type, 'updated', 'type');
      equal(e.getKey(), key, 'key');
      deepEqual(e.getValue(), data, 'value');
    }
    start();
  });

  db.add(store_inline, data);
  db.put(store_inline, data);
  setTimeout(function() {
    // don't wait more than 5 sec.
    start();
  }, 2000);
});

asyncTest("updated StoreEvent", function () {
  expect(10);

  var db = new ydn.db.Storage(db_name_event, events_schema);
  var keys = [Math.ceil(Math.random() * 100000),
    Math.ceil(Math.random() * 100000)];
  var data = [{name:"rand key 1", id: keys[0]}, {name:"rand key 2", id: keys[1]}];

  var firedCreatedEvent = false;
  db.addEventListener(['created', 'updated'], function(e) {
    //console.log(e);
    if (!firedCreatedEvent) {
      equal(e.name, 'StoreEvent', 'event name');
      equal(e.getStoreName(), store_inline, 'store name');
      //equal(e.store_name, store_inline, 'store name');
      equal(e.type, 'created', 'type');
      deepEqual(e.getKeys(), keys, 'created key');
      deepEqual(e.getValues(), data, 'created value');
      firedCreatedEvent = true;
    } else {
      equal(e.name, 'StoreEvent', 'event name');
      equal(e.getStoreName(), store_inline, 'store name');
      //equal(e.store_name, store_inline, 'store name');
      equal(e.type, 'updated', 'type');
      deepEqual(e.getKeys(), keys, 'updated key');
      deepEqual(e.getValues(), data, 'updated value');

      start();
    }
  });

  db.add(store_inline, data);
  db.put(store_inline, data);
  setTimeout(function() {
    // don't wait more than 5 sec.
    start();
  }, 1000);
});

<|endoftext|>


<commit_before>'use strict';

var React = require('react/addons'),
    Header = require('./components/Header'),
    Menu = require('./components/Menu'),
    Router = require('react-router'),
    AppState = require('./stores/AppState'),
    AppStateActionCreators = require('./actions/AppStateActionCreators'),
    ReactCSSTransitionGroup = React.addons.CSSTransitionGroup,
    DocumentTitle = require('react-document-title'),
    RouteHandler = Router.RouteHandler,
    Navigation = Router.Navigation;

var App = React.createClass({
    mixins: [Router.State, Navigation],
    nextTransition: null,

    getInitialState() {
        return this.getStateFromStores();
    },

    back() {
        AppStateActionCreators.setNextTransition('slideBack');
        if(history.state != null) {
            this.goBack();
        } else {
            this.transitionTo('/');
        }
        AppStateActionCreators.resetTransitions();
    },

    contentHandler() {
        if(this.state.menuOpen) {
            AppStateActionCreators.closeMenu();
        }
    },

    render() {
        var name = this.getRoutes().reverse()[0].name,
            menuOpen = this.state.menuOpen ? 'open' : '';

        return (
            <DocumentTitle title='Simple Gym 3.0'>

                    <Menu />

                        <ReactCSSTransitionGroup className='content' component="div" transitionName={AppState.getNextTransition()}>
                            <RouteHandler key={name} />
                        </ReactCSSTransitionGroup>

            </DocumentTitle>
        );
    },

    getStateFromStores() {
        return AppState.getAll();
    },

    componentDidMount() {
        AppState.addChangeListener(this._onChange);
    },

    componentWillUnmount() {
        AppState.removeChangeListener(this._onChange);
    },

    _onChange() {
        this.setState(this.getStateFromStores());
    },

    shouldComponentUpdate(nextProps, nextState) {
        // when resetting nextTransition, we don't need to re-render
        return !(this.state.nextTransition !== nextState.nextTransition && nextState.nextTransition === 'slide');
    }
});

module.exports = App;
<commit_msg>refactoring<commit_after>'use strict';

var React = require('react/addons'),
    Header = require('./components/Header'),
    Menu = require('./components/Menu'),
    Router = require('react-router'),
    AppState = require('./stores/AppState'),
    AppStateActionCreators = require('./actions/AppStateActionCreators'),
    ReactCSSTransitionGroup = React.addons.CSSTransitionGroup,
    DocumentTitle = require('react-document-title'),
    RouteHandler = Router.RouteHandler,
    Navigation = Router.Navigation;

var App = React.createClass({
    mixins: [Router.State, Navigation],
    nextTransition: null,

    getInitialState() {
        return {
            menuOpen: AppState.getMenuOpen(),
            nextTransition: AppState.getNextTransition()
        };
    },

    back() {
        AppStateActionCreators.setNextTransition('slideBack');
        if(history.state != null) {
            this.goBack();
        } else {
            this.transitionTo('/');
        }
        AppStateActionCreators.resetTransitions();
    },

    contentHandler() {
        if(this.state.menuOpen) {
            AppStateActionCreators.closeMenu();
        }
    },

    render() {
        var name = this.getRoutes().reverse()[0].name,
            menuOpen = this.state.menuOpen ? 'open' : '';

        return (
            <DocumentTitle title='Simple Gym 3.0'>

                    <Menu />

                        <ReactCSSTransitionGroup className='content' component="div" transitionName={AppState.getNextTransition()}>
                            <RouteHandler key={name} />
                        </ReactCSSTransitionGroup>

            </DocumentTitle>
        );
    },

    getStateFromStores() {
        return AppState.getAll();
    },

    componentDidMount() {
        AppState.addChangeListener(this._onChange);
    },

    componentWillUnmount() {
        AppState.removeChangeListener(this._onChange);
    },

    _onChange() {
        this.setState(this.getStateFromStores());
    },

    shouldComponentUpdate(nextProps, nextState) {
        // when resetting nextTransition, we don't need to re-render
        return !(this.state.nextTransition !== nextState.nextTransition && nextState.nextTransition === 'slide');
    }
});

module.exports = App;
<|endoftext|>


<commit_before>var util = require("util");
var path = require("path");
var Q = require("q");
var _ = require("lodash");
var exec = require('child_process').exec;

var fs = require('graceful-fs');
var parse = require("../../parse");
var BaseGenerator = require("../page");
var stringUtils = require("../../utils/string");

var Generator = function() {
    BaseGenerator.apply(this, arguments);
};
util.inherits(Generator, BaseGenerator);

Generator.prototype.finish = function() {
    var that = this;

    return BaseGenerator.prototype.finish.apply(this)
    .then(function() {
        var d = Q.defer();
        var format = that.options.extension || path.extname(that.options.output).replace("\.", "") || "pdf";

        if (!that.options.cover && fs.existsSync(path.join(that.options.output, "cover.jpg"))) {
            that.options.cover = path.join(that.options.output, "cover.jpg");
        }

        var _options = {
            "--cover": that.options.cover,
            "--title": that.options.title,
            "--comments": that.options.description,
            "--authors": that.options.author,
            "--publisher": "GitBook",
            "--chapter": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter ')]",
            "--chapter-mark": "pagebreak",
            "--page-breaks-before": "/",
            "--level1-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-1 ')]",
            "--level2-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-2 ')]",
            "--level3-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-3 ')]",
            "--no-chapters-in-toc": true,
            "--max-levels": "1",
            "--breadth-first": true
        };

        if (format == "pdf") {
            var pdfOptions = that.options.pdf;

            _.extend(_options, {
                "--margin-left": String(pdfOptions.margin.left),
                "--margin-right": String(pdfOptions.margin.right),
                "--margin-top": String(pdfOptions.margin.top),
                "--margin-bottom": String(pdfOptions.margin.bottom),
                "--pdf-default-font-size": String(pdfOptions.fontSize),
                "--pdf-mono-font-size": String(pdfOptions.fontSize),
                "--paper-size": String(pdfOptions.paperSize),
                "--pdf-page-numbers": Boolean(pdfOptions.pageNumbers),
                "--pdf-header-template": String(pdfOptions.headerTemplate),
                "--pdf-footer-template": String(pdfOptions.footerTemplate)
            });

            if ('options' in pdfOptions) {
              _.extend(_options, pdfOptions.options);
            }
        }

        var command = [
            "ebook-convert",
            path.join(that.options.output, "SUMMARY.html"),
            path.join(that.options.output, "index."+format),
            stringUtils.optionsToShellArgs(_options)
        ].join(" ");

        if (that.options.xvfb) {
          command = ["xvfb-run"].concat(command);
        }

        exec(command, function (error, stdout, stderr) {
            if (error) {
                if (error.code == 127) {
                    error.message = "Need to install ebook-convert from Calibre";
                } else {
                    error.message = error.message + " "+stdout;
                }
                return d.reject(error);
            }
            d.resolve();
        });

        return d.promise;
    });
};

module.exports = Generator;
<commit_msg>Refactor ebook options<commit_after>var util = require("util");
var path = require("path");
var Q = require("q");
var _ = require("lodash");
var exec = require('child_process').exec;

var fs = require('graceful-fs');
var parse = require("../../parse");
var BaseGenerator = require("../page");
var stringUtils = require("../../utils/string");

var Generator = function() {
    BaseGenerator.apply(this, arguments);
};
util.inherits(Generator, BaseGenerator);

Generator.prototype.finish = function() {
    var that = this;

    return BaseGenerator.prototype.finish.apply(this)
    .then(function() {
        var d = Q.defer();
        var format = that.options.extension || path.extname(that.options.output).replace("\.", "") || "pdf";

        if (!that.options.cover && fs.existsSync(path.join(that.options.output, "cover.jpg"))) {
            that.options.cover = path.join(that.options.output, "cover.jpg");
        }

        var _options = {
            "--cover": that.options.cover,
            "--title": that.options.title,
            "--comments": that.options.description,
            "--authors": that.options.author,
            "--publisher": "GitBook",
            "--chapter": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter ')]",
            "--chapter-mark": "pagebreak",
            "--page-breaks-before": "/",
            "--level1-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-1 ')]",
            "--level2-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-2 ')]",
            "--level3-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-3 ')]",
            "--no-chapters-in-toc": true,
            "--max-levels": "1",
            "--breadth-first": true
        };

        if (format == "pdf") {
            var pdfOptions = that.options.pdf;

            _.extend(_options, {
                "--margin-left": String(pdfOptions.margin.left),
                "--margin-right": String(pdfOptions.margin.right),
                "--margin-top": String(pdfOptions.margin.top),
                "--margin-bottom": String(pdfOptions.margin.bottom),
                "--pdf-default-font-size": String(pdfOptions.fontSize),
                "--pdf-mono-font-size": String(pdfOptions.fontSize),
                "--paper-size": String(pdfOptions.paperSize),
                "--pdf-page-numbers": Boolean(pdfOptions.pageNumbers),
                "--pdf-header-template": String(pdfOptions.headerTemplate),
                "--pdf-footer-template": String(pdfOptions.footerTemplate)
            });
        }

        if (that.options.ebook && 'options' in that.options.ebook) {
          _.extend(_options, that.options.ebook.options);
        }

        var command = (that.options.ebook && that.options.ebook.xvfb === true) ? ["xvfb-run"] : [];
        command = command.concat([
            "ebook-convert",
            path.join(that.options.output, "SUMMARY.html"),
            path.join(that.options.output, "index."+format),
            stringUtils.optionsToShellArgs(_options)
        ]).join(" ");

        exec(command, function (error, stdout, stderr) {
            if (error) {
                if (error.code == 127) {
                    error.message = "Need to install ebook-convert from Calibre";
                } else {
                    error.message = error.message + " "+stdout;
                }
                return d.reject(error);
            }
            d.resolve();
        });

        return d.promise;
    });
};

module.exports = Generator;
<|endoftext|>