<commit_before>var education = {
  "name": "Education",
  "entries": [{
    "business": "Massachusetts Institute of Technology",
    "position": "Masters of Engineering Student",
    "startYear": 2016,
    "endYear": null,
    "features": [
      "EECS M.Eng student working in the Fluid Interfaces group of the Media Lab",
      "Received Bachelor of Science in Computer Science in 2016"
    ],
    "keywords": [],
    "importance": 10
  }],
  "entryTemplate": genericEntryTemplate,
  "sectionTemplate": genericSectionTemplate
};

var experience = {
  "name": "Experience",
  "entries": [
  {
    "business": "MIT Media Lab",
    "moreLink": "http://fluid.media.mit.edu/node/227",
    "position": "Fluid Interfaces Graduate Researcher",
    "startYear": 2016,
    "endYear": null,
    "features": [
      "Designing adaptable, modular interfaces for the Reality Editor, a novel AR IoT platform",
      "Assisting the maintenance and refactoring of this platform's growing codebase"
    ],
    "keywords": ["C++", "JavaScript", "Node"],
    "importance": 10
  },
  {
    "business": "CSAIL Distributed Robotics Laboratory",
    "moreLink": "http://groups.csail.mit.edu/drl/wiki/index.php?title=Main_Page",
    "position": "Undergraduate Researcher",
    "startYear": 2015,
    "endYear": 2016,
    "features": [
      "Built an online game for crowdsourcing the design of robots"
    ],
    "keywords": ["JavaScript", "React", "Node"],
    "importance": 9
  },
  {
    "business": "Mozilla",
    "moreLink": "https://www.mozilla.org/",
    "position": "Firefox OS Systems Front End Team Intern",
    "years": [2014, 2015],
    "features": [
      "Produced several major features and improvements over two summer internships",
      "Ensured full test coverage and production-grade reliability of work",
      "Spearheaded research project to uncover a significant market opportunity for Firefox OS"
    ],
    "keywords": ["C++", "JavaScript", "Android Internals"],
    "importance": 9
  },
  {
    "business": "MIT Media Lab",
    "moreLink": "http://fluid.media.mit.edu/node/227",
    "position": "Fluid Interfaces Undergraduate Researcher",
    "startYear": 2012,
    "endYear": 2014,
    "features": [
      "Specified meaningful multimodal interactions between connected objects",
      //"Implementing low-latency network connections using AllJoyn and\
      //  OpenSoundControl"
      "Optimized low-latency data transfer over UDP",
      "2nd author on UBICOMP 2013 publication \"Reality Editor: Programming Smarter Objects\""
    ],
    "keywords": ["C++", "iOS", "Augmented Reality", "Internet of Things"],
    "importance": 8
  },
  {
    "business": "iNetDispatch, LLC.",
    "moreLink": "http://www.inetdispatch.com/",
    "position": "Intern",
    "startYear": 2011,
    "endYear": 2012,
    "features": [
      "Developed a real-time chat system for dispatchers and units in the field",
      "Implemented global drag and drop for user interactions",
      "Created a playback feature to show the previous locations of units",
    ],
    "keywords": ["ActionScript"],
    "importance": 3
  },
  {
    "business": "Dryden Flight Research Center",
    "position": "Data Acquisition Engineer Intern",
    "startYear": 2011,
    "endYear": 2011,
    "features": [
      "Wrote utilities for the analysis of flight data with an\
       emphasis on real-time visualization",
      "Coordinated flight test with group, designing procedures to\
       guarantee safety and repeatability",
      "Shared findings and practices in a technical presentation"
    ],
    "keywords": ["Matlab"],
    "importance": 6
  },
  {
    "business": "Infinite Heart",
    "position": "Interaction Designer",
    "startYear": 2011,
    "endYear": 2011,
    "features": [
      "Designed a series of 3D interactive applets for use on the Infinite "+
       "Heart website and in Infinite heart seminars",
      "Synthesized several novel visualization and interaction methods"
    ],
    "keywords": ["Java", "OpenGL"],
    "importance": 1
  },
  {
    "business": "Phoenix Country Day School",
    "moreLink": "http://community.pcds.org/netcommunity/page.aspx?pid=1228",
    "position": "SMALLab Teaching Assistant",
    "startYear": 2011,
    "endYear": 2012,
    "features": [
      "Planned and taught a series of introductory programming lectures",
      "Advised and assisted students in the creation of digital "+
       "interactive art and educational games",
      "Created a SMALLab-tailored gesture recognition engine to facilitate "+
       "students’ use of non-standard interaction designs"
    ],
    "keywords": ["Java", "OptiTrack"],
    "importance": 1
  }],
  "entryTemplate": genericEntryTemplate,
  "sectionTemplate": genericSectionTemplate
};

var projects = {
  "name": "Projects",
  "entries": [
  {
    "name": "New XKit",
    "moreLink": "https://github.com/new-xkit/XKit/",
    "startYear": 2015,
    "endYear": null,
    "features": [
      "Forked and revitalized a popular open source project for improving Tumblr",
      "Triaging bugs and supporting users while adapting to Tumblr's ever-changing website"
    ],
    "keywords": ["JavaScript", "Browser Extension", "Open Source"]
  },
  {
    "name": "Cabbage Legs",
    "startYear": 2015,
    "endYear": 2015,
    "moreLink": "https://hobinjk.github.io/cabbage-legs/",
    "importance": 8,
    "features": [
      "Programmed a genetic algorithm that optimizes simulated quadripedal robots"
    ],
    "keywords": ["JavaScript", "Canvas"]
  },
  {
    "name": "Aqueduct",
    "startYear": 2015,
    "endYear": 2015,
    "moreLink": "https://hobinjk.github.io/aqueduct/",
    "importance": 6,
    "features": [
      "Implemented simple static analysis of JavaScript for type assignment"
    ],
    "keywords": ["JavaScript"]
  },
  {
    "name": "Nineteen Below",
    "startYear": 2015,
    "endYear": 2016,
    "moreLink": "https://hobinjk.github.io/nineteen-below/",
    "importance": 3,
    "features": [
      "Created a simple game based on procedurally generated ice block puzzles"
    ],
    "keywords": ["JavaScript", "Canvas"]
  },
  {
    "name": "Haven",
    "startYear": 2013,
    "endYear": 2014,
    "moreLink": "https://github.com/hobinjk/haven/",
    "importance": 7,
    "features": [
      "Designed a secure filesharing site based on client-side encryption"
    ],
    "keywords": ["Go", "JavaScript", "OpenSSL", "Emscripten"]
  },
  {
    "name": "Human + Computer",
    "startYear": 2014,
    "endYear": 2014,
    "importance": 4,
    "features": [
      "Produced an interactive art project exploring transhumanism",
    ],
    "keywords": ["C", "Design", "Fabrication"]
  },
  {
    "name": "Tansley Effect",
    "startYear": 2014,
    "endYear": null,
    "features": [
      "Cofounded a startup to optimize data sharing within academic research groups",
      "Interviewed potential customers to refine and improve business strategy and design",
      "Prepared a website on a compressed timescale for a demo day presentation"
    ],
    "keywords": ["JavaScript", "HTML", "Communication"],
    "importance": 6
  },
  {
    "name": "Firefox Development",
    "startYear": 2011,
    "endYear": null,
    "features": [
      "Fixed bugs #659576 and #570760",
      "Began creation of a global keyboard shortcuts popup (bug #492557)",
    ],
    "keywords": ["JavaScript", "HTML", "Open Source"],
    "importance": 2
  },
  {
    "name": "Random Hall Laundry Server",
    "moreLink": "http://laundry.mit.edu/",
    "startYear": 2013,
    "endYear": 2016,
    "importance": 6,
    "features": [
      "Collaborated with other students to build a joint web application and hardware installation",
      // "Hardware uses off-the-shelf components to determine the power-on state of any machine",
      // "Web application interfaces with the hardware to display machine usage in real-time"
    ],
    "keywords": ["JavaScript", "Node", "Internet of Things"]
  },
  {
    "name": "Student Groups",
    "startYear": 2012,
    "endYear": 2016,
    "features": [
      "President of the Laboratory for Chocolate Science (2012–2016)",
      "Random Hall Judiciary Committee Member (2013–2014) and Chair (2014–2015)",
      // "Secretary of the MIT Science Fiction Society"
      // "Computer Chair, Laundry King, and Webmaster for Random Hall"
    ],
    "keywords": ["Leadership", "Communication", "Fundraising"]
  }
  ],
  "entryTemplate": projectsEntryTemplate,
  "sectionTemplate": genericSectionTemplate
};

var resume = {
  "name": "James Hobin",
  "email": "hobinjk@mit.edu",
  "address": "MIT  Cambridge, MA 02139",
  "phone": "(623) 297–8310",
  "username": "hobinjk",
  "sections": [
    education,
    experience,
    projects
  ]
};
<commit_msg>Concretize New XKit's influence<commit_after>var education = {
  "name": "Education",
  "entries": [{
    "business": "Massachusetts Institute of Technology",
    "position": "Masters of Engineering Student",
    "startYear": 2016,
    "endYear": null,
    "features": [
      "EECS M.Eng student working in the Fluid Interfaces group of the Media Lab",
      "Received Bachelor of Science in Computer Science in 2016"
    ],
    "keywords": [],
    "importance": 10
  }],
  "entryTemplate": genericEntryTemplate,
  "sectionTemplate": genericSectionTemplate
};

var experience = {
  "name": "Experience",
  "entries": [
  {
    "business": "MIT Media Lab",
    "moreLink": "http://fluid.media.mit.edu/node/227",
    "position": "Fluid Interfaces Graduate Researcher",
    "startYear": 2016,
    "endYear": null,
    "features": [
      "Designing adaptable, modular interfaces for the Reality Editor, a novel AR IoT platform",
      "Assisting the maintenance and refactoring of this platform's growing codebase"
    ],
    "keywords": ["C++", "JavaScript", "Node"],
    "importance": 10
  },
  {
    "business": "CSAIL Distributed Robotics Laboratory",
    "moreLink": "http://groups.csail.mit.edu/drl/wiki/index.php?title=Main_Page",
    "position": "Undergraduate Researcher",
    "startYear": 2015,
    "endYear": 2016,
    "features": [
      "Built an online game for crowdsourcing the design of robots"
    ],
    "keywords": ["JavaScript", "React", "Node"],
    "importance": 9
  },
  {
    "business": "Mozilla",
    "moreLink": "https://www.mozilla.org/",
    "position": "Firefox OS Systems Front End Team Intern",
    "years": [2014, 2015],
    "features": [
      "Produced several major features and improvements over two summer internships",
      "Ensured full test coverage and production-grade reliability of work",
      "Spearheaded research project to uncover a significant market opportunity for Firefox OS"
    ],
    "keywords": ["C++", "JavaScript", "Android Internals"],
    "importance": 9
  },
  {
    "business": "MIT Media Lab",
    "moreLink": "http://fluid.media.mit.edu/node/227",
    "position": "Fluid Interfaces Undergraduate Researcher",
    "startYear": 2012,
    "endYear": 2014,
    "features": [
      "Specified meaningful multimodal interactions between connected objects",
      //"Implementing low-latency network connections using AllJoyn and\
      //  OpenSoundControl"
      "Optimized low-latency data transfer over UDP",
      "2nd author on UBICOMP 2013 publication \"Reality Editor: Programming Smarter Objects\""
    ],
    "keywords": ["C++", "iOS", "Augmented Reality", "Internet of Things"],
    "importance": 8
  },
  {
    "business": "iNetDispatch, LLC.",
    "moreLink": "http://www.inetdispatch.com/",
    "position": "Intern",
    "startYear": 2011,
    "endYear": 2012,
    "features": [
      "Developed a real-time chat system for dispatchers and units in the field",
      "Implemented global drag and drop for user interactions",
      "Created a playback feature to show the previous locations of units",
    ],
    "keywords": ["ActionScript"],
    "importance": 3
  },
  {
    "business": "Dryden Flight Research Center",
    "position": "Data Acquisition Engineer Intern",
    "startYear": 2011,
    "endYear": 2011,
    "features": [
      "Wrote utilities for the analysis of flight data with an\
       emphasis on real-time visualization",
      "Coordinated flight test with group, designing procedures to\
       guarantee safety and repeatability",
      "Shared findings and practices in a technical presentation"
    ],
    "keywords": ["Matlab"],
    "importance": 6
  },
  {
    "business": "Infinite Heart",
    "position": "Interaction Designer",
    "startYear": 2011,
    "endYear": 2011,
    "features": [
      "Designed a series of 3D interactive applets for use on the Infinite "+
       "Heart website and in Infinite heart seminars",
      "Synthesized several novel visualization and interaction methods"
    ],
    "keywords": ["Java", "OpenGL"],
    "importance": 1
  },
  {
    "business": "Phoenix Country Day School",
    "moreLink": "http://community.pcds.org/netcommunity/page.aspx?pid=1228",
    "position": "SMALLab Teaching Assistant",
    "startYear": 2011,
    "endYear": 2012,
    "features": [
      "Planned and taught a series of introductory programming lectures",
      "Advised and assisted students in the creation of digital "+
       "interactive art and educational games",
      "Created a SMALLab-tailored gesture recognition engine to facilitate "+
       "students’ use of non-standard interaction designs"
    ],
    "keywords": ["Java", "OptiTrack"],
    "importance": 1
  }],
  "entryTemplate": genericEntryTemplate,
  "sectionTemplate": genericSectionTemplate
};

var projects = {
  "name": "Projects",
  "entries": [
  {
    "name": "New XKit",
    "moreLink": "https://github.com/new-xkit/XKit/",
    "startYear": 2015,
    "endYear": null,
    "features": [
      "Forked and revitalized a popular open source project for improving Tumblr",
      "Supporting over 400,000 users across Chrome, Firefox, and Safari"
      // "Triaging bugs and supporting users while adapting to Tumblr's ever-changing website"
    ],
    "keywords": ["JavaScript", "Browser Extension", "Open Source"]
  },
  {
    "name": "Cabbage Legs",
    "startYear": 2015,
    "endYear": 2015,
    "moreLink": "https://hobinjk.github.io/cabbage-legs/",
    "importance": 8,
    "features": [
      "Programmed a genetic algorithm that optimizes simulated quadripedal robots"
    ],
    "keywords": ["JavaScript", "Canvas"]
  },
  {
    "name": "Aqueduct",
    "startYear": 2015,
    "endYear": 2015,
    "moreLink": "https://hobinjk.github.io/aqueduct/",
    "importance": 6,
    "features": [
      "Implemented simple static analysis of JavaScript for type assignment"
    ],
    "keywords": ["JavaScript"]
  },
  {
    "name": "Nineteen Below",
    "startYear": 2015,
    "endYear": 2016,
    "moreLink": "https://hobinjk.github.io/nineteen-below/",
    "importance": 3,
    "features": [
      "Created a simple game based on procedurally generated ice block puzzles"
    ],
    "keywords": ["JavaScript", "Canvas"]
  },
  {
    "name": "Haven",
    "startYear": 2013,
    "endYear": 2014,
    "moreLink": "https://github.com/hobinjk/haven/",
    "importance": 7,
    "features": [
      "Designed a secure filesharing site based on client-side encryption"
    ],
    "keywords": ["Go", "JavaScript", "OpenSSL", "Emscripten"]
  },
  {
    "name": "Human + Computer",
    "startYear": 2014,
    "endYear": 2014,
    "importance": 4,
    "features": [
      "Produced an interactive art project exploring transhumanism",
    ],
    "keywords": ["C", "Design", "Fabrication"]
  },
  {
    "name": "Tansley Effect",
    "startYear": 2014,
    "endYear": null,
    "features": [
      "Cofounded a startup to optimize data sharing within academic research groups",
      "Interviewed potential customers to refine and improve business strategy and design",
      "Prepared a website on a compressed timescale for a demo day presentation"
    ],
    "keywords": ["JavaScript", "HTML", "Communication"],
    "importance": 6
  },
  {
    "name": "Firefox Development",
    "startYear": 2011,
    "endYear": null,
    "features": [
      "Fixed bugs #659576 and #570760",
      "Began creation of a global keyboard shortcuts popup (bug #492557)",
    ],
    "keywords": ["JavaScript", "HTML", "Open Source"],
    "importance": 2
  },
  {
    "name": "Random Hall Laundry Server",
    "moreLink": "http://laundry.mit.edu/",
    "startYear": 2013,
    "endYear": 2016,
    "importance": 6,
    "features": [
      "Collaborated with other students to build a joint web application and hardware installation",
      // "Hardware uses off-the-shelf components to determine the power-on state of any machine",
      // "Web application interfaces with the hardware to display machine usage in real-time"
    ],
    "keywords": ["JavaScript", "Node", "Internet of Things"]
  },
  {
    "name": "Student Groups",
    "startYear": 2012,
    "endYear": 2016,
    "features": [
      "President of the Laboratory for Chocolate Science (2012–2016)",
      "Random Hall Judiciary Committee Member (2013–2014) and Chair (2014–2015)",
      // "Secretary of the MIT Science Fiction Society"
      // "Computer Chair, Laundry King, and Webmaster for Random Hall"
    ],
    "keywords": ["Leadership", "Communication", "Fundraising"]
  }
  ],
  "entryTemplate": projectsEntryTemplate,
  "sectionTemplate": genericSectionTemplate
};

var resume = {
  "name": "James Hobin",
  "email": "hobinjk@mit.edu",
  "address": "MIT  Cambridge, MA 02139",
  "phone": "(623) 297–8310",
  "username": "hobinjk",
  "sections": [
    education,
    experience,
    projects
  ]
};
<|endoftext|>


<commit_before>module.exports = {
  _id: '_design/styleguides',

  views: {
    byPublisher: {
      map: function(doc) {
        if (doc.publisher) {
          emit(doc.publisher, null);
        }
      },
      reduce: '_count'
    },

    floppyVsHyperlink: {
      map: function(doc) {
        if (doc.text) {
          if (/floppy|diskette|ZIP-disk|CD/i.test(doc.text)) {
            emit('floppy', null);
          }
          if (/hyperlink/i.test(doc.text)) {
            emit('hyperlink', null);
          }
        }
      },
      reduce: '_count'
    }
  },

  // couchdb-lucene
  fulltext: {
    styleguides: {
      index: function(doc) {
        if (!doc.text) {
          return null;
        }

        var ret = new Document();
        ret.add(doc.text);

        [ 'title', 'about', 'url', 'publisher' ].forEach(function(p) {
          if (doc[p]) {
            ret.add(Array.isArray(doc[p]) ? doc[p].join(', ') : doc[p], { field: p, store: 'yes', index: (p === 'about') ? 'analyzed': 'no' });
          }
        });

        return ret;
      }
    }
  },

  // cloudant
  indexes: {
    styleguides: {
      index: function(doc) {
        if (doc.text) {
          index("default", doc.text);
          [ 'title', 'about', 'url', 'publisher' ].forEach(function(p) {
            if (doc[p]) {
              index(p, Array.isArray(doc[p]) ? doc[p].join(', ') : doc[p], { store: true, index: p === 'about' });
            }
          });
        }
      }
    }
  },

  language: 'javascript'
};
<commit_msg>fix view<commit_after>module.exports = {
  _id: '_design/styleguides',

  views: {
    byPublisher: {
      map: function(doc) {
        if (doc.publisher) {
          emit(doc.publisher, null);
        }
      },
      reduce: '_count'
    },

    floppyVsHyperlink: {
      map: function(doc) {
        if (doc.text) {
          if (/floppy|diskette|disk|ZIP-disk/i.test(doc.text)) {
            emit('floppy', null);
          }
          if (/hyperlink/i.test(doc.text)) {
            emit('hyperlink', null);
          }
        }
      },
      reduce: '_count'
    }
  },

  // couchdb-lucene
  fulltext: {
    styleguides: {
      index: function(doc) {
        if (!doc.text) {
          return null;
        }

        var ret = new Document();
        ret.add(doc.text);

        [ 'title', 'about', 'url', 'publisher' ].forEach(function(p) {
          if (doc[p]) {
            ret.add(Array.isArray(doc[p]) ? doc[p].join(', ') : doc[p], { field: p, store: 'yes', index: (p === 'about') ? 'analyzed': 'no' });
          }
        });

        return ret;
      }
    }
  },

  // cloudant
  indexes: {
    styleguides: {
      index: function(doc) {
        if (doc.text) {
          index("default", doc.text);
          [ 'title', 'about', 'url', 'publisher' ].forEach(function(p) {
            if (doc[p]) {
              index(p, Array.isArray(doc[p]) ? doc[p].join(', ') : doc[p], { store: true, index: p === 'about' });
            }
          });
        }
      }
    }
  },

  language: 'javascript'
};
<|endoftext|>


<commit_before>/**
 * @module deep
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 */
if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}

define([
    "require",
    "./lib/utils",
    "./lib/nodes",
    "./lib/query",
    "./lib/compose",
    "./lib/collider",
    "./lib/errors",
    "./lib/stores/store",
    "./lib/ocm",
    "./lib/protocol",
    "./lib/sheet",
    "./lib/promise",
    "./lib/chain",
    "./lib/flatten",
    "./lib/compiler",
    "./lib/emitter",
    "./lib/rql",
    "./lib/stores/chain"
    ], function (require, utils) {

    if(typeof deep !== 'undefined')
    {
        console.log("***********************************************************************************");
        console.warn("You trying to load deepjs modules two times (maybe from two different node_modules)");
        console.warn("Will use previous loaded deep instance.");
        console.log("***********************************************************************************");
        return deep;
    }

    deep = function deepStart(obj, schema, options) {
        var h = new deep.Chain(options);
        try {
            if (typeof obj === 'string')
                obj = deep.get(obj);
            if (typeof schema === 'string')
                schema = deep.get(schema);
            var doStart = function doStartChain(obj, schema)
            {
                var r = obj;
                if (obj && obj._deep_query_node_)
                {
                    r = obj.value;
                    h._state.nodes = [obj];
                }
                else
                    h._state.nodes = [deep.nodes.root(obj, schema, options)];

                if (r && r._deep_store_)
                    h.store(r)
                    .done(function(s){
                        this._state.nodes = [deep.nodes.root(s)];
                    });

                h._state.root = h._state.nodes[0];
                h._start({success:r, error:null});
            };
            var alls = null;
            if ((obj && (obj.then || obj.promise)) || (schema && (schema.then || schema.promise)))
                deep.all(obj, schema)
                .done(function (res) {
                    doStart(res[0], res[1]);
                })
                .fail(function (error) {
                    h._state.nodes = null;
                    h._start({success:null, error:error});
                });
            else
                doStart(obj, schema);
        } catch (error) {
            console.log("internal chain start error : ", error);
            h._state.nodes = [deep.nodes.root({}, schema, options)];
            h._start({ success:null, error:error });
        }
        return h;
    };
    deep.utils = require("./lib/utils");

    deep.transformers = {};
    /**
     * rethrow any throw during chain execution.
     * @property rethrow
     * @static
     * @type {Boolean}
     */
    deep.rethrow = false;

    /**
     * are you on nodejs or not
     * @static
     * @property isNode
     * @type {Boolean}
     */
    deep.isNode = (typeof process !== 'undefined' && process.versions && process.versions.node);

    /**
     * a magic context that follow promise context and switch automaticaly
     * @static
     * @property interpret
     */
    deep.context = {};

    /**
     * where to place YOUR globals (deep does'nt have any globals)
     * @static
     * @property globals
     */
    deep.globals = {};

    /**
     * where to place YOUR globals headers to set on each store call (deep does'nt have any globals)
     * @static
     * @property globals
     */
    deep.globalHaders = {};

    deep.debug = true;

    deep.destructiveLoad = false;

    //require("./lib/utils")(deep);
    deep.errors = require("./lib/errors");
    deep.rql = require("./lib/rql");
    deep.collider = require("./lib/collider");

    deep.nodes = require("./lib/nodes");
    deep.deepLoad = function(entry, context, destructive, excludeFunctions){
        if(!entry._deep_query_node_)
            entry = deep.nodes.root(entry);
        return deep.nodes.deepLoad([entry])
    };
    /**
     * final namespace for deepjs/query
     * @static
     * @property Querier
     * @type {DeepQuery}
     */
    var Querier = deep.Querier = require("./lib/query");
    /**
     * perform a (synched) query query
     * @example
     *
     * deep.query({ hello:"world", test:1 }, "/*?=world"); // will return ["world"]
     *
     * @method query
     * @param {Object} object any object to query
     * @param {String} query the query
     * @static
     * @return {Array} the result aray
     */
    deep.query = Querier.query;

    deep.ui = {};
    deep.client = {};

    var compiler = require("./lib/compiler");
    deep.Shared = compiler.Shared;
    deep.compile = compiler.compile;
    deep.up = compiler.up;
    deep.bottom = compiler.bottom;

    deep.compose = require("./lib/compose");
    deep.Arguments = deep.compose.Arguments;

    var flat = require("./lib/flatten");
    deep.extendsChilds = flat.extendsChilds;
    deep.extendsBackgrounds = flat.extendsBackgrounds;
    utils.flatten = deep.flatten = flat.flatten;

    var proto = require("./lib/protocol");
    deep.protocol = proto.protocol;
    deep.protocols = proto.protocols;
    deep.get = proto.get;
    deep.getAll = proto.getAll;

    var ocm = require("./lib/ocm");
    deep.ocm = ocm;
    deep.Modes = ocm.Modes;
    deep.Roles = ocm.Roles;
    deep.modes = ocm.modes;
    deep.roles = ocm.roles;
    deep.getModes = ocm.getModes;

    var event = require("./lib/emitter");
    deep.Event = event.Event;
    deep.Emitter = event.Emitter;

    var sheets = require("./lib/sheet");
    for(var i in sheets)
        deep[i] = sheets[i];

    var promise = require("./lib/promise");
    for(var i in promise)
        deep[i] = promise[i];

    var chains = require("./lib/chain");
    deep.Chain = chains.Chain;
    deep.chain = chains.chain;

    var stores = require("./lib/stores/store");
    deep.Store = stores.Store;
    deep.store = stores.store;
    deep.client = {};

    require("./lib/stores/chain");
    deep.delay = function(ms){
        return deep({}).delay(ms);
    }

    //_________________________________________________________________________________

    deep.coreUnits = deep.coreUnits || [];
    deep.coreUnits.push(
        "js::deepjs/units/equals",
        "js::deepjs/units/queries",
        "js::deepjs/units/collisions",
        "js::deepjs/units/colliders",
        "js::deepjs/units/compositions",
        "js::deepjs/units/flatten",
        "js::deepjs/units/promises",
        "js::deepjs/units/chain",
        "js::deepjs/units/replace",
        "js::deepjs/units/remove",
        "js::deepjs/units/interpret",
        "js::deepjs/units/range",
        "js::deepjs/units/relations",
        "js::deepjs/units/context",
        "js::deepjs/units/ocm",
        "js::deepjs/units/sheets",
        "js::deepjs/units/shared",
        "js::deepjs/units/parcours",
        "js::deepjs/units/deepload",
        "js::deepjs/units/utils",
        "js::deepjs/units/restrictions",
        "js::deepjs/units/custom-chain"
    );
    //_________________________________________________________________________________
    return deep;
});<commit_msg>optimise deep start chain<commit_after>/**
 * @module deep
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 */
if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}

define([
    "require",
    "./lib/utils",
    "./lib/nodes",
    "./lib/query",
    "./lib/compose",
    "./lib/collider",
    "./lib/errors",
    "./lib/stores/store",
    "./lib/ocm",
    "./lib/protocol",
    "./lib/sheet",
    "./lib/promise",
    "./lib/flatten",
    "./lib/compiler",
    "./lib/emitter",
    "./lib/rql",
    "./lib/restrictions",
    "./lib/chains/deep",
    "./lib/chains/restful",
    //"./lib/stores/chain",
    "./lib/chains/deep2"
    ], function (require, utils) {

    if(typeof deep !== 'undefined')
    {
        console.log("***********************************************************************************");
        console.warn("You trying to load deepjs modules two times (maybe from two different node_modules)");
        console.warn("Will use previous loaded deep instance.");
        console.log("***********************************************************************************");
        return deep;
    }

    deep = function deepStart(obj, schema, options) {
        // console.log("CHAIN START : context : ", deep.context)
        options = options || {};
        var h = new deep.Chain(options._state || null, options), d;
        try {
            if (typeof obj === 'string')
                obj = deep.get(obj, options);

            if (typeof schema === 'string')
                schema = deep.get(schema, options);

            if(!schema && obj && (obj.then || obj.promise))
                d = deep.when(obj)
                .done(function (res) {
                    h._init(res);
                    h._start();
                });
            if(schema  && (schema.then || schema.promise))
                if(obj && (obj.then || obj.promise))
                    d = deep.all(obj, schema)
                    .done(function (res) {
                        h._init(res[0], res[1]);
                        h._start();
                    });
                else
                    d = deep.when(schema)
                    .done(function (res) {
                        h._init(null, res);
                        h._start();
                    });
            if(d)
                d.fail(function (error) {
                    h._start({success:null, error:error});
                });
            else
            {
                h._init(obj, schema);
                h._start();
            }
        } catch (error) {
            //console.log("internal chain start error : ", error);
            h._start({ success:null, error:error });
        }
        return h;
    };
    deep.utils = require("./lib/utils");

    deep.transformers = {};
    /**
     * rethrow any throw during chain execution.
     * @property rethrow
     * @static
     * @type {Boolean}
     */
    deep.rethrow = false;

    /**
     * are you on nodejs or not
     * @static
     * @property isNode
     * @type {Boolean}
     */
    deep.isNode = (typeof process !== 'undefined' && process.versions && process.versions.node);

    /**
     * a magic context that follow promise context and switch automaticaly
     * @static
     * @property interpret
     */
    deep.context = {};

    /**
     * where to place YOUR globals (deep does'nt have any globals)
     * @static
     * @property globals
     */
    deep.globals = {};

    /**
     * where to place YOUR globals headers to set on each store call (deep does'nt have any globals)
     * @static
     * @property globals
     */
    deep.globalHaders = {};

    deep.debug = true;

    deep.destructiveLoad = false;

    //require("./lib/utils")(deep);
    deep.errors = require("./lib/errors");
    deep.rql = require("./lib/rql");
    deep.collider = require("./lib/collider");

    deep.nodes = require("./lib/nodes");
    deep.deepLoad = function(entry, context, destructive, excludeFunctions){
        if(!entry._deep_query_node_)
            entry = deep.nodes.root(entry);
        return deep.nodes.deepLoad([entry])
    };
    /**
     * final namespace for deepjs/query
     * @static
     * @property Querier
     * @type {DeepQuery}
     */
    var Querier = deep.Querier = require("./lib/query");
    /**
     * perform a (synched) query query
     * @example
     *
     * deep.query({ hello:"world", test:1 }, "/*?=world"); // will return ["world"]
     *
     * @method query
     * @param {Object} object any object to query
     * @param {String} query the query
     * @static
     * @return {Array} the result aray
     */
    deep.query = Querier.query;

    deep.ui = {};
    deep.client = {};

    var compiler = require("./lib/compiler");
    deep.Shared = compiler.Shared;
    deep.compile = compiler.compile;
    deep.up = compiler.up;
    deep.bottom = compiler.bottom;

    deep.compose = require("./lib/compose");
    deep.Arguments = deep.compose.Arguments;

    var flat = require("./lib/flatten");
    deep.extendsChilds = flat.extendsChilds;
    deep.extendsBackgrounds = flat.extendsBackgrounds;
    utils.flatten = deep.flatten = flat.flatten;

    var proto = require("./lib/protocol");
    deep.protocol = proto.protocol;
    deep.protocols = proto.protocols;
    deep.get = proto.get;
    deep.getAll = proto.getAll;

    var ocm = require("./lib/ocm");
    deep.ocm = ocm;
    deep.Modes = ocm.Modes;
    deep.Roles = ocm.Roles;
    deep.modes = ocm.modes;
    deep.roles = ocm.roles;
    deep.getModes = ocm.getModes;

    var event = require("./lib/emitter");
    deep.Event = event.Event;
    deep.Emitter = event.Emitter;

    var sheets = require("./lib/sheet");
    for(var i in sheets)
        deep[i] = sheets[i];

    var promise = require("./lib/promise");
    for(var i in promise)
        deep[i] = promise[i];

    var chains = require("./lib/chain");
    deep.Chain = chains.Chain;
    deep.chain = chains.chain;

    var stores = require("./lib/stores/store");
    deep.Store = stores.Store;
    deep.store = stores.store;
    deep.client = {};

    require("./lib/stores/chain");
    deep.delay = function(ms){
        return deep({}).delay(ms);
    }

    //_________________________________________________________________________________

    deep.coreUnits = deep.coreUnits || [];
    deep.coreUnits.push(
        "js::deepjs/units/equals",
        "js::deepjs/units/queries",
        "js::deepjs/units/collisions",
        "js::deepjs/units/colliders",
        "js::deepjs/units/compositions",
        "js::deepjs/units/flatten",
        "js::deepjs/units/promises",
        "js::deepjs/units/chain",
        "js::deepjs/units/replace",
        "js::deepjs/units/remove",
        "js::deepjs/units/interpret",
        "js::deepjs/units/range",
        "js::deepjs/units/relations",
        "js::deepjs/units/context",
        "js::deepjs/units/ocm",
        "js::deepjs/units/sheets",
        "js::deepjs/units/shared",
        "js::deepjs/units/parcours",
        "js::deepjs/units/deepload",
        "js::deepjs/units/utils",
        "js::deepjs/units/restrictions",
        "js::deepjs/units/custom-chain"
    );
    //_________________________________________________________________________________
    return deep;
});<|endoftext|>


<commit_before>var NUMBER_OF_SQUARE = 17;
var PLAYGROUND_WIDTH = 600;
var SQUARE_WIDTH = PLAYGROUND_WIDTH / NUMBER_OF_SQUARE;
var MAX_CHARACTER = 5;

var CHARACTER_PARAMETER = [
  {
    "id": 0,
    "name": "daisyo",
    "cost": 1,
    "hitPoint": 3,
    "attack": 1,
    "attacableRange": 2,
    "move": 1
  },
  {
    "id": 1,
    "name": "pupepon",
    "cost": 3,
    "hitPoint": 7,
    "attack": 3,
    "attacableRange": 2,
    "move": 3
  },
  {
    "id": 2,
    "name": "haseaki",
    "cost": 2,
    "hitPoint": 3,
    "attack": 2,
    "attacableRange": 2,
    "move": 2
  },
  {
    "id": 3,
    "name": "miho",
    "cost": 5,
    "hitPoint": 8,
    "attack": 3,
    "attacableRange": 2,
    "move": 2
  }
]

character = function(id, posx, posy, charaId) {
  this.posx = posx;
  this.posy = posy;
  this.charaId = charaId;
  this.id = id;
  this.name = CHARACTER_PARAMETER[charaId].name;
  this.cost = CHARACTER_PARAMETER[charaId].cost;
  this.hitPoint = CHARACTER_PARAMETER[charaId].hitPoint;
  this.attack = CHARACTER_PARAMETER[charaId].attack;
  this.attacableRange = CHARACTER_PARAMETER[charaId].attacableRange;
  this.move = CHARACTER_PARAMETER[charaId].move;
}

test_Friend = [];
test_Friend[0] = new character(0, 9, 9, 0);
test_Friend[1] = new character(1, 8, 9, 3);
test_Friend[2] = new character(2, 10, 9, 3);
test_Friend[3] = new character(3, 9, 8, 3);
test_Friend[4] = new character(4, 9, 10, 3);

test_Enemy = [];
test_Enemy[0] = new character(100, 3, 3, 0);
test_Enemy[1] = new character(101, 2, 3, 2);
test_Enemy[2] = new character(102, 4, 3, 3);
test_Enemy[3] = new character(103, 3, 2, 1);
test_Enemy[4] = new character(104, 3, 4, 1);

// Declarations
var selectX = -1;
var selectY = -1;
var selectedCharacter = -1;
var overX = -1;
var overY = -1;

// ==============================================================================================
$(function(){
  /* canvas */
  playGround = $("#play-ground").get(0);
  ctxCanvas  = playGround.getContext("2d");
  canvasPosition = $('#play-ground').position();

  /* Event */
  $('#play-ground').bind({
    "mousemove": function(e){
      redraw(e);
    },
    "click": function(e){
      selectCharacter(e);
      redraw(e);
    }
  });

  /* For Debug */
  //console.log(CHARACTER_PARAMETER[3].name);

});

// ==============================================================================================
function redraw(e){
  ctxCanvas.clearRect(0, 0, PLAYGROUND_WIDTH, PLAYGROUND_WIDTH);
  drawHoverMarker(e);

  //drawCharacter();
  var i;
  for (i = 0; i < 5; i++){
      ctxCanvas.fillStyle = "red";
      drawCharacter(test_Friend[i].posx, test_Friend[i].posy, test_Friend[i].charaId);
      ctxCanvas.fillStyle = "blue";
      drawCharacter(test_Enemy[i].posx, test_Enemy[i].posy, test_Enemy[i].charaId);
  }

  drawField();
}

function drawHoverMarker(e){
    if (!e) {
      console.log("drawHoverMarker !e");
    } else {
      overX = (e.pageX - canvasPosition.left) / SQUARE_WIDTH;
      overY = (e.pageY - canvasPosition.top) / SQUARE_WIDTH;

      var obj = convertPosition(overX, overY, false);
      obj.x -= SQUARE_WIDTH / 2;
      obj.y -= SQUARE_WIDTH / 2;
    };

    ctxCanvas.lineWidth = 0.0;
    ctxCanvas.fillStyle = 'rgb(192, 80, 77)';
    ctxCanvas.globalAlpha = 0.7;
    ctxCanvas.beginPath();
    ctxCanvas.fillRect(obj.x, obj.y, SQUARE_WIDTH, SQUARE_WIDTH);
    ctxCanvas.stroke();
}

function drawCharacter(posx,posy,charaId){
  var obj = convertPosition(posx, posy, false);
  ctxCanvas.font = "18px 'MS Pゴシック'";
  switch(charaId){
    case 0:
      ctxCanvas.fillText("D", obj.x, obj.y);
      break;
    case 1:
      ctxCanvas.fillText("P", obj.x, obj.y);
      break;
    case 2:
      ctxCanvas.fillText("H", obj.x, obj.y);
      break;
    case 3:
      ctxCanvas.fillText("M", obj.x, obj.y);
      break;
  }
  ctxCanvas.stroke();
}

function drawField(){
  var i;

  for (i=0; i<=17;i++) {
    if (i === 0 || i === NUMBER_OF_SQUARE) {
      ctxCanvas.beginPath();
      ctxCanvas.lineWidth = 10.0;
    } else {
      ctxCanvas.beginPath();
      ctxCanvas.lineWidth = 1.0;
    }
    ctxCanvas.moveTo(i * SQUARE_WIDTH, 0);
    ctxCanvas.lineTo(i * SQUARE_WIDTH, PLAYGROUND_WIDTH);
    ctxCanvas.stroke();
    ctxCanvas.moveTo(0, i * SQUARE_WIDTH);
    ctxCanvas.lineTo(PLAYGROUND_WIDTH, i * SQUARE_WIDTH);
    ctxCanvas.stroke();
  }

}

function selectCharacter(e){
    /*
    (selectY, selectX)
    */
    if (e) {
      selectX = Math.floor((e.pageX - canvasPosition.left) / SQUARE_WIDTH);
      selectY = Math.floor((e.pageY - canvasPosition.top) / SQUARE_WIDTH);
    };
    //console.log(selectX, selectY);

    // クリックしたとこのキャラを検索。
    // 同じキャラが選択されたとき or 見つからなかったとき、-1を代入。
    var temp = searchCharacter(selectX, selectY, 0, true);
    if (selectedCharacter === temp[1] || temp[0] === false) {
      selectedCharacter = -1;
    } else {
      selectedCharacter = temp[1];
    }
    console.log('selected', selectedCharacter);

    // クリックしたとこ以外の、距離が1(隣接する)キャラを検索。
    var temp = searchCharacter(selectX, selectY, 1, false);
    console.log(temp.length - 1 + ' character(s) found.');
    console.log(temp);

}

function searchCharacter(x, y, range, flag){
  /*
    x, y はマスの座標を取る。
    flag:
     true: クリックしたところを含む
     false: クリックしたところを含まない
  */
  var i, j, k;
  var foundCharacter = [];
  foundCharacter.push(false);

    tx = x - range; //検索範囲の一番左のマス
    ty = y - range; //検索範囲の一番上のマス
    range = 2 * range + 1;

    for (i = 0; i < range; i++) {
      for (j = 0; j < range; j++) {
        for (k = 0; k < MAX_CHARACTER; k++){
          if(test_Friend[k].posx === tx + i && test_Friend[k].posy === ty + j){
            foundCharacter.push(test_Friend[k].id);
          }
          if(test_Enemy[k].posx === tx + i && test_Enemy[k].posy === ty + j){
            foundCharacter.push(test_Enemy[k].id);
          }
        }
      }
    }

  if (flag === false) {
    var temp = searchCharacter(x, y, 0, true);
    for(i = 1; i < foundCharacter.length; i++){
      if (foundCharacter[i] === temp[1]){
        foundCharacter.splice(i, 1);
      }
    }
  }

  if (typeof foundCharacter[1] === 'undefined') {
    return foundCharacter;
  } else {
    foundCharacter[0] = true;
    return foundCharacter;
  }

}

// ==============================================================================================
/*
  posX: x座標,
  posY: y座標,
  flag:
    true : 座標 -> マス
    false: マス   -> 座標
*/
function convertPosition(posX, posY, flag) {
  var canvasPosition = $('#play-ground').position();
  var tx;
  var ty;

  posX = Math.floor(posX);
  posY = Math.floor(posY);

  if (flag === true) {
    tx = posX / SQUARE_WIDTH;
    ty = posY / SQUARE_WIDTH;

    return {x: Math.floor(tx), y: Math.floor(ty)}
  }
  else if (flag === false) {
    tx = (posX + 1) * (SQUARE_WIDTH) - (SQUARE_WIDTH / 2);
    ty = (posY + 1) * (SQUARE_WIDTH) - (SQUARE_WIDTH / 2);

    return {x: Math.floor(tx), y: Math.floor(ty)}
  }

  // 失敗したときのために
  return {x: -1, y: -1}
};<commit_msg>Improve on redraw<commit_after>var NUMBER_OF_SQUARE = 17;
var PLAYGROUND_WIDTH = 600;
var SQUARE_WIDTH = PLAYGROUND_WIDTH / NUMBER_OF_SQUARE;
var MAX_CHARACTER = 5;

var CHARACTER_PARAMETER = [
  {
    "id": 0,
    "name": "daisyo",
    "cost": 1,
    "hitPoint": 3,
    "attack": 1,
    "attacableRange": 2,
    "move": 1
  },
  {
    "id": 1,
    "name": "pupepon",
    "cost": 3,
    "hitPoint": 7,
    "attack": 3,
    "attacableRange": 2,
    "move": 3
  },
  {
    "id": 2,
    "name": "haseaki",
    "cost": 2,
    "hitPoint": 3,
    "attack": 2,
    "attacableRange": 2,
    "move": 2
  },
  {
    "id": 3,
    "name": "miho",
    "cost": 5,
    "hitPoint": 8,
    "attack": 3,
    "attacableRange": 2,
    "move": 2
  }
]

character = function(id, posx, posy, charaId) {
  this.posx = posx;
  this.posy = posy;
  this.charaId = charaId;
  this.id = id;
  this.name = CHARACTER_PARAMETER[charaId].name;
  this.cost = CHARACTER_PARAMETER[charaId].cost;
  this.hitPoint = CHARACTER_PARAMETER[charaId].hitPoint;
  this.attack = CHARACTER_PARAMETER[charaId].attack;
  this.attacableRange = CHARACTER_PARAMETER[charaId].attacableRange;
  this.move = CHARACTER_PARAMETER[charaId].move;
}

test_Friend = [];
test_Friend[0] = new character(0, 9, 9, 0);
test_Friend[1] = new character(1, 8, 9, 3);
test_Friend[2] = new character(2, 10, 9, 3);
test_Friend[3] = new character(3, 9, 8, 3);
test_Friend[4] = new character(4, 9, 10, 3);

test_Enemy = [];
test_Enemy[0] = new character(100, 3, 3, 0);
test_Enemy[1] = new character(101, 2, 3, 2);
test_Enemy[2] = new character(102, 4, 3, 3);
test_Enemy[3] = new character(103, 3, 2, 1);
test_Enemy[4] = new character(104, 3, 4, 1);

// Declarations
var selectX = -1;
var selectY = -1;
var selectedCharacter = -1;
var overX = -1;
var overY = -1;
var onFiled = false;

// ==============================================================================================
$(function(){
  /* canvas */
  playGround = $("#play-ground").get(0);
  ctxCanvas  = playGround.getContext("2d");
  canvasPosition = $('#play-ground').position();

  /* Event */
  $('#play-ground').bind({
    "mousemove": function(e){
    	onFiled = true;
      redraw(e, onFiled);
    },
    "mouseout": function(e){
    	onFiled = false;
    	redraw(e, onFiled);
    },
    "click": function(e){
      selectCharacter(e, onFiled);
      redraw(e);
    }
  });

  /* For Debug */
  //console.log(CHARACTER_PARAMETER[3].name);

});

// ==============================================================================================
function redraw(e, flag){
  ctxCanvas.clearRect(0, 0, PLAYGROUND_WIDTH, PLAYGROUND_WIDTH);
  if (flag === true) {
  	drawHoverMarker(e);
	}

  //drawCharacter();
  var i;
  for (i = 0; i < 5; i++){
      ctxCanvas.fillStyle = "red";
      drawCharacter(test_Friend[i].posx, test_Friend[i].posy, test_Friend[i].charaId);
      ctxCanvas.fillStyle = "blue";
      drawCharacter(test_Enemy[i].posx, test_Enemy[i].posy, test_Enemy[i].charaId);
  }

  drawField();
}

function drawHoverMarker(e){
    if (!e) {
      console.log("drawHoverMarker !e");
    } else {
      overX = (e.pageX - canvasPosition.left) / SQUARE_WIDTH;
      overY = (e.pageY - canvasPosition.top) / SQUARE_WIDTH;

      var obj = convertPosition(overX, overY, false);
      obj.x -= SQUARE_WIDTH / 2;
      obj.y -= SQUARE_WIDTH / 2;
    };

    ctxCanvas.lineWidth = 0.0;
    ctxCanvas.fillStyle = 'rgb(192, 80, 77)';
    ctxCanvas.globalAlpha = 0.7;
    ctxCanvas.beginPath();
    ctxCanvas.fillRect(obj.x, obj.y, SQUARE_WIDTH, SQUARE_WIDTH);
    ctxCanvas.stroke();
}

function drawCharacter(posx,posy,charaId){
  var obj = convertPosition(posx, posy, false);
  ctxCanvas.font = "18px 'MS Pゴシック'";
  switch(charaId){
    case 0:
      ctxCanvas.fillText("D", obj.x, obj.y);
      break;
    case 1:
      ctxCanvas.fillText("P", obj.x, obj.y);
      break;
    case 2:
      ctxCanvas.fillText("H", obj.x, obj.y);
      break;
    case 3:
      ctxCanvas.fillText("M", obj.x, obj.y);
      break;
  }
  ctxCanvas.stroke();
}

function drawField(){
  var i;

  for (i=0; i<=17;i++) {
    if (i === 0 || i === NUMBER_OF_SQUARE) {
      ctxCanvas.beginPath();
      ctxCanvas.lineWidth = 10.0;
    } else {
      ctxCanvas.beginPath();
      ctxCanvas.lineWidth = 1.0;
    }
    ctxCanvas.moveTo(i * SQUARE_WIDTH, 0);
    ctxCanvas.lineTo(i * SQUARE_WIDTH, PLAYGROUND_WIDTH);
    ctxCanvas.stroke();
    ctxCanvas.moveTo(0, i * SQUARE_WIDTH);
    ctxCanvas.lineTo(PLAYGROUND_WIDTH, i * SQUARE_WIDTH);
    ctxCanvas.stroke();
  }

}

function selectCharacter(e){
    /*
    (selectY, selectX)
    */
    if (e) {
      selectX = Math.floor((e.pageX - canvasPosition.left) / SQUARE_WIDTH);
      selectY = Math.floor((e.pageY - canvasPosition.top) / SQUARE_WIDTH);
    };
    //console.log(selectX, selectY);

    // クリックしたとこのキャラを検索。
    // 同じキャラが選択されたとき or 見つからなかったとき、-1を代入。
    var temp = searchCharacter(selectX, selectY, 0, true);
    if (selectedCharacter === temp[1] || temp[0] === false) {
      selectedCharacter = -1;
    } else {
      selectedCharacter = temp[1];
    }
    console.log('selected', selectedCharacter);

    // クリックしたとこ以外の、距離が1(隣接する)キャラを検索。
    var temp = searchCharacter(selectX, selectY, 1, false);
    console.log(temp.length - 1 + ' character(s) found.');
    console.log(temp);

}

function searchCharacter(x, y, range, flag){
  /*
    x, y はマスの座標を取る。
    flag:
     true: クリックしたところを含む
     false: クリックしたところを含まない
  */
  var i, j, k;
  var foundCharacter = [];
  foundCharacter.push(false);

    tx = x - range; //検索範囲の一番左のマス
    ty = y - range; //検索範囲の一番上のマス
    range = 2 * range + 1;

    for (i = 0; i < range; i++) {
      for (j = 0; j < range; j++) {
        for (k = 0; k < MAX_CHARACTER; k++){
          if(test_Friend[k].posx === tx + i && test_Friend[k].posy === ty + j){
            foundCharacter.push(test_Friend[k].id);
          }
          if(test_Enemy[k].posx === tx + i && test_Enemy[k].posy === ty + j){
            foundCharacter.push(test_Enemy[k].id);
          }
        }
      }
    }

  if (flag === false) {
    var temp = searchCharacter(x, y, 0, true);
    for(i = 1; i < foundCharacter.length; i++){
      if (foundCharacter[i] === temp[1]){
        foundCharacter.splice(i, 1);
      }
    }
  }

  if (typeof foundCharacter[1] === 'undefined') {
    return foundCharacter;
  } else {
    foundCharacter[0] = true;
    return foundCharacter;
  }

}

// ==============================================================================================
/*
  posX: x座標,
  posY: y座標,
  flag:
    true : 座標 -> マス
    false: マス   -> 座標
*/
function convertPosition(posX, posY, flag) {
  var canvasPosition = $('#play-ground').position();
  var tx;
  var ty;

  posX = Math.floor(posX);
  posY = Math.floor(posY);

  if (flag === true) {
    tx = posX / SQUARE_WIDTH;
    ty = posY / SQUARE_WIDTH;

    return {x: Math.floor(tx), y: Math.floor(ty)}
  }
  else if (flag === false) {
    tx = (posX + 1) * (SQUARE_WIDTH) - (SQUARE_WIDTH / 2);
    ty = (posY + 1) * (SQUARE_WIDTH) - (SQUARE_WIDTH / 2);

    return {x: Math.floor(tx), y: Math.floor(ty)}
  }

  // 失敗したときのために
  return {x: -1, y: -1}
};<|endoftext|>


<commit_before>var chalk = require('chalk');
var readline = require('readline');
var execSync = require('child_process').execSync;
var ansi = require('ansi-escapes');

readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
process.stdin.resume();

var PROMPT = 'Enter a file glob: ';
var INPUT = [];

function printGitStatus() {
	var output = execSync('git -c color.ui=always status');
}

function renderLine() {
	process.stdout.clearLine();
	process.stdout.cursorTo(0);
	process.stdout.write(PROMPT);
	process.stdout.write(chalk.red(INPUT.join('')));
}

function backspace() {
	if (INPUT.pop()) {
		process.stdout.write(ansi.cursorMove(-1));
	}
}

function getAllGitFiles(glob) {
	if (typeof glob === 'undefined') glob = '';

	var files;
	try {
		files = execSync("{ git diff --name-only; git ls-files --other --exclude-standard; } | sort | uniq | grep '" + glob +  "'");
	} catch (e) {
		return '';
	}
	return files.toString('utf8');
}

function eraseLinesBelow() {
	process.stdout.write(ansi.eraseDown);
}

process.stdin.on('keypress', function(char, key) {
	if (key.ctrl && key.name === 'c') {
    process.exit();
  } else if (key.name === 'backspace') {
		backspace();
	} else if (key.name === 'return') {
		return
	} else {
		if (typeof char !== 'undefined') {
			INPUT.push(char + '');
		}
		renderLine();
	}

	process.stdout.write(ansi.cursorSavePosition);

	eraseLinesBelow();
	var glob = INPUT.join('')
	var files = getAllGitFiles(glob);
	console.log()
	console.log()
	console.log(chalk.red(files))

	process.stdout.write(ansi.cursorRestorePosition);
});

renderLine();
process.stdout.write(ansi.cursorSavePosition);
var files = getAllGitFiles();
console.log();
console.log();
console.log(chalk.red(files));
process.stdout.write(ansi.cursorRestorePosition);

process.on('exit', function() {
	process.stdout.clearLine();
	eraseLinesBelow();
	console.log();
});
<commit_msg>Tidy a bit<commit_after>var chalk = require('chalk');
var readline = require('readline');
var execSync = require('child_process').execSync;
var ansi = require('ansi-escapes');

readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
process.stdin.resume();

var PROMPT = 'Enter a file glob: ';
var INPUT = [];

function renderLine() {
	process.stdout.clearLine();
	process.stdout.cursorTo(0);
	process.stdout.write(PROMPT);
	process.stdout.write(chalk.red(INPUT.join('')));
}

function backspace() {
	if (INPUT.pop()) {
		process.stdout.write(ansi.cursorMove(-1));
	}
}

function getAllGitFiles(glob) {
	if (typeof glob === 'undefined') glob = '';

	var files;
	try {
		files = execSync("{ git diff --name-only; git ls-files --other --exclude-standard; } | sort | uniq | grep '" + glob +  "'");
	} catch (e) {
		return '';
	}
	return files.toString('utf8');
}

function printBelow(files) {
	process.stdout.write(ansi.cursorSavePosition);
	console.log()
	console.log()
	console.log(chalk.red(files))
	process.stdout.write(ansi.cursorRestorePosition);
}

function eraseBelow() {
	process.stdout.write(ansi.eraseDown);
}

process.stdin.on('keypress', function(char, key) {
	if (key.ctrl && key.name === 'c') {
    process.exit();
  } else if (key.name === 'backspace') {
		backspace();
	} else if (key.name === 'return') {
		return
	} else {
		if (typeof char !== 'undefined') {
			INPUT.push(char + '');
		}
		renderLine();
	}

	eraseBelow();

	var glob = INPUT.join('')
	var files = getAllGitFiles(glob);
	printBelow(files);
});

renderLine();
var files = getAllGitFiles();
printBelow(files);

process.on('exit', function() {
	process.stdout.clearLine();
	eraseBelow();
	console.log();
});
<|endoftext|>


<commit_before>var extend = require('extend');

var defaults = {
};

module.exports = (parameters) => {
   var options = extend({}, defaults, parameters);
};<commit_msg>add a couple of necessary defaults<commit_after>var extend = require('extend');

var defaults = {
   bootstrap: false,
   navigation: false
};

module.exports = (parameters) => {
   var options = extend({}, defaults, parameters);
};<|endoftext|>


<commit_before>document.getElementById("id_business_level_version").innerHTML="Business level version 2017.12.06.1";

navigator.geolocation.getCurrentPosition(on_gps_success, on_gps_error);

//----------------------------------------------
function on_gps_success(p)
{
	document.getElementById("id_p").innerHTML = "Lat = " + p.coords.latitude + " Long = " + p.coords.longitude + " Accuracy = " + p.coords.accuracy + "m";
}
//-----------------------------------------------
function on_gps_error(e)
{
	alert(e.code);
}
//------------------------------------------------<commit_msg>Adding altitude<commit_after>document.getElementById("id_business_level_version").innerHTML="Business level version 2017.12.06.2";

navigator.geolocation.getCurrentPosition(on_gps_success, on_gps_error);

//----------------------------------------------
function on_gps_success(p)
{
	document.getElementById("id_p").innerHTML = "Lat = " + p.coords.latitude + "
 Long = " + p.coords.longitude + "
 Accuracy = " + p.coords.accuracy + "m" + "
 Altitude = " + p.coords.altitude + "m";
}
//-----------------------------------------------
function on_gps_error(e)
{
	alert(e.code);
}
//------------------------------------------------<|endoftext|>


<commit_before>var setupEditor = function(aId)
{
    var editor = ace.edit(aId);
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/json");
    editor.getSession().setTabSize(2);
    editor.getSession().setUseSoftTabs(true);
    editor.setFontSize(20);
    return editor;
}

var edSource = setupEditor("edSource");
var edTransform = setupEditor("edTransform");
var edResult = setupEditor("edResult");

var distributions = []

var EditorIsInvalid = function(aEditor)
{
    var retval = null;

    var ljsonString = aEditor.getValue();
    try
    {
        JSON.parse(ljsonString);
    }
    catch (err)
    {
        retval = err.message;
    }

    return retval;
}

var ValidateJson = function(aEditor, aMessageSelector)
{
    $(aMessageSelector).text(EditorIsInvalid(aEditor));
}

var UpdateResult = function()
{
    if (!(EditorIsInvalid(edSource) || EditorIsInvalid(edTransform)))
    {
        lsourceJson = JSON.parse(edSource.getValue());
        ltransformJson = JSON.parse(edTransform.getValue());

        try
        {
            var lresult = null;

            var ltransform = "transform-t" in ltransformJson ? ltransformJson["transform-t"] : null;

            var clresult = sUTL.compilelib([ltransformJson], distributions, true)

            if ("fail" in clresult)
            {
              lresult = clresult["fail"]
            }
            else
            {
              lresult = sUTL.evaluate(lsourceJson, ltransform, clresult["lib"] || {})
            }

            edResult.setValue(JSON.stringify(lresult, null, space=2))
            edResult.gotoLine(0);
        }
        catch (e)
        {
            edResult.setValue("Exception: " + e.message)
            edResult.gotoLine(0);
        }
    }
}

edSource.getSession().on('change', function(e) {
    ValidateJson(edSource, "#sourcemsg");
    setStoredText("sourceTextsUTL2", edSource.getValue())
    UpdateResult();
});

edTransform.getSession().on('change', function(e) {
    ValidateJson(edTransform, "#transformmsg");
    setStoredText("transformTextsUTL2", edTransform.getValue())
    UpdateResult();
});

var getStoredText = function(aKey, aDefault)
{
    var retval;

    if(typeof(Storage) !== "undefined") {
        retval = localStorage[aKey]
    }

    retval = retval || aDefault;

    return retval;
}

var setStoredText = function(aKey, aValue)
{
    if(typeof(Storage) !== "undefined") {
        localStorage[aKey] = aValue
    }
}

var _defaultSource = {
  "head": "#@.in[0]" ,
  "tail": "##@.in[1:]",
  "back": "##@.in[-1:]",
  "front": "##@.in[:-1]",
  "append": [
    "&&",
    "#@.head",
    "#@.tail"
  ],
  "reverse":
  {
    "&": "if",
    "cond": "#@.in",
    "true":
    {"'":
      [
        "&&",
        {
          "!": "#$.reverse",
          "in":
          {
            "!": "#$.tail",
            "in": "#@.in"
          }
        },
        {
          "!": "#$.head",
          "in": "#@.in"
        }
      ]
    },
    "false": {"'": []}
  },
  "add3": {
    "&": "+",
    "a": "#@.item",
    "b": 3
  }
}

var _defaultTransform =
{
  "language": "sUTL0",
  "transform-t":
  {
    "div": {
      "&": "=",
      "a": {
        "&": "+",
        "a": 3,
        "b": 4
      },
      "b": -2
    },
    "mapper1": {
      "!": "#*.map_l",
      "list": [1,2, 3],
      "t": "#$.add3"
    },
    "mapper2": {
      "!": "#*.map_l",
      "list": [1,2, 3],
      "t": {"'": {
        "&": "+",
        "a": "#@.item",
        "b": 3
      }}
    },
    "backer": {
      "!": "#$.back",
      "in": [1, 2, 4, 6, 7, 3, 9]
    },
    "fronter": {
      "!": "#$.front",
      "in": [1, 2, 4, 6, 7, 3, 9]
    }
  },
  "requires": ["map_l"]
}

$(document).ready(function(){
  edSource.setValue(getStoredText("sourceTextsUTL2",  JSON.stringify(_defaultSource, null, 2)))
  edSource.gotoLine(0);
  edTransform.setValue(getStoredText("transformTextsUTL2", JSON.stringify(_defaultTransform, null, 2)))
  edTransform.gotoLine(0);
});

<commit_msg>Better default source and transform<commit_after>var setupEditor = function(aId)
{
    var editor = ace.edit(aId);
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/json");
    editor.getSession().setTabSize(2);
    editor.getSession().setUseSoftTabs(true);
    editor.setFontSize(20);
    return editor;
}

var edSource = setupEditor("edSource");
var edTransform = setupEditor("edTransform");
var edResult = setupEditor("edResult");

var distributions = []

var EditorIsInvalid = function(aEditor)
{
    var retval = null;

    var ljsonString = aEditor.getValue();
    try
    {
        JSON.parse(ljsonString);
    }
    catch (err)
    {
        retval = err.message;
    }

    return retval;
}

var ValidateJson = function(aEditor, aMessageSelector)
{
    $(aMessageSelector).text(EditorIsInvalid(aEditor));
}

var UpdateResult = function()
{
    if (!(EditorIsInvalid(edSource) || EditorIsInvalid(edTransform)))
    {
        lsourceJson = JSON.parse(edSource.getValue());
        ltransformJson = JSON.parse(edTransform.getValue());

        try
        {
            var lresult = null;

            var ltransform = "transform-t" in ltransformJson ? ltransformJson["transform-t"] : null;

            var clresult = sUTL.compilelib([ltransformJson], distributions, true)

            if ("fail" in clresult)
            {
              lresult = clresult["fail"]
            }
            else
            {
              lresult = sUTL.evaluate(lsourceJson, ltransform, clresult["lib"] || {})
            }

            edResult.setValue(JSON.stringify(lresult, null, space=2))
            edResult.gotoLine(0);
        }
        catch (e)
        {
            edResult.setValue("Exception: " + e.message)
            edResult.gotoLine(0);
        }
    }
}

edSource.getSession().on('change', function(e) {
    ValidateJson(edSource, "#sourcemsg");
    setStoredText("sourceTextsUTL2", edSource.getValue())
    UpdateResult();
});

edTransform.getSession().on('change', function(e) {
    ValidateJson(edTransform, "#transformmsg");
    setStoredText("transformTextsUTL2", edTransform.getValue())
    UpdateResult();
});

var getStoredText = function(aKey, aDefault)
{
    var retval;

    if(typeof(Storage) !== "undefined") {
        retval = localStorage[aKey]
    }

    retval = retval || aDefault;

    return retval;
}

var setStoredText = function(aKey, aValue)
{
    if(typeof(Storage) !== "undefined") {
        localStorage[aKey] = aValue
    }
}

var _defaultSource = [1, 2, 3, 4]

var _defaultTransform =
{
  "language": "sUTL0",
  "transform-t": {
    "sum": {
      "!": "#*.sum_core",
      "list": "#$"
    }
  },
  "requires": [
    "sum_core"
  ]
}

$(document).ready(function(){
  edSource.setValue(getStoredText("sourceTextsUTL2",  JSON.stringify(_defaultSource, null, 2)))
  edSource.gotoLine(0);
  edTransform.setValue(getStoredText("transformTextsUTL2", JSON.stringify(_defaultTransform, null, 2)))
  edTransform.gotoLine(0);
});

<|endoftext|>


<commit_before>#!/usr/bin/node

/*
 * Really dumb ICB client, currently just used for testing.
 */
var net = require('net');

var client = function() {
  var socket = net.createConnection(7326, process.ARGV[2]);

  socket.setEncoding("utf8");

  socket.on('connect', function(connect) {
    sendicbmsg("ajperkin\001jperkin@icbjs\001test\001login");
  });

  socket.on('data', function(data) {
    data.split("\0").forEach(function(line) {
      console.log(line.replace(/\001/g, "^A").slice(1));
    });
  });

  function sendicbmsg(message) {
    socket.write(String.fromCharCode(message.length) + message);
  }
}

if (!process.ARGV[2]) {
  console.log("usage: icb.js <server>");
  process.exit(2);
}
client();
<commit_msg>Shorten default nickname, was too long..<commit_after>#!/usr/bin/node

/*
 * Really dumb ICB client, currently just used for testing.
 */
var net = require('net');

var client = function() {
  var socket = net.createConnection(7326, process.ARGV[2]);

  socket.setEncoding("utf8");

  socket.on('connect', function(connect) {
    sendicbmsg("ajperkin\001jperkin@js\001test\001login");
  });

  socket.on('data', function(data) {
    data.split("\0").forEach(function(line) {
      console.log(line.replace(/\001/g, "^A").slice(1));
    });
  });

  function sendicbmsg(message) {
    socket.write(String.fromCharCode(message.length) + message);
  }
}

if (!process.ARGV[2]) {
  console.log("usage: icb.js <server>");
  process.exit(2);
}
client();
<|endoftext|>


<commit_before><commit_msg>level can specify a player start position to warp to<commit_after><|endoftext|>


<commit_before>//get a reference to the canvas
var ctx = $('#canvas')[0].getContext("2d");

//draw a circle
ctx.beginPath();
ctx.arc(75, 75, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
<commit_msg>deleted game.js =(<commit_after><|endoftext|>


<commit_before>var game = {
  level: parseInt(localStorage.level, 10) - 1 || 0,
  answers: (localStorage.answers && JSON.parse(localStorage.answers)) || {},

  start: function() {
    $('#level-counter .total').text(levels.length);
    $('#editor').show();
    $('#share').hide();

    $('#submit').on('click', function() {
      var level = levels[game.level];
      var code = $('#code').val();
      var selector = level.selector || '';
      $('#pond ' +  selector).attr('style', code);
      $('#code').focus();

      game.saveAnswer();
      game.check(level);
    });

    $('#code').on('keydown', function(e) {
      if (e.keyCode === 13) {
        var max = $(this).data('lines');
        var code = $(this).val();
        var trim = code.trim();
        var codeLength = code.split('\n').length;
        var trimLength = trim.split('\n').length;

        if (codeLength >= max) {

          if (codeLength === trimLength) {
            e.preventDefault();
            $('#submit').click();
          } else {
            $('#code').focus().val('').val(trim);
          }
        }
      }
    });

    $('#editor').on('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
      $(this).removeClass();
    });

    $('.arrow').on('click', function() {
      $('#editor').show();
      $('#share').hide();

      $('#code').focus();
      game.saveAnswer();
    });

    $('.arrow.left').on('click', function() {
      if (game.level >= 1) {
        game.prev();
      }
    });

    $('.arrow.right').on('click', function() {
      if (game.level < (levels.length - 1)) {
        game.next();
      }
    });

    game.next();
  },

  prev: function() {
    this.level--;

    var levelData = levels[this.level];
    localStorage.setItem('level', this.level);
    this.loadLevel(levelData);
  },

  next: function() {
    this.level++;

    var levelData = levels[this.level];
    localStorage.setItem('level', this.level);
    this.loadLevel(levelData);
  },

  loadLevel: function(level) {
    $('#background, #pond').removeClass('wrap').attr('style', '').empty();

    var answer = game.answers[level.name];
    $('#code').val(answer);

    $('#level-counter .current').text(this.level + 1);
    $('#instructions').html(level.instructions);
    $('#before').text(level.before);
    $('#after').text(level.after);

    $('.arrow.disabled').removeClass('disabled');

    if (this.level === 0) {
      $('.arrow.left').addClass('disabled');
    }

    if (this.level === levels.length - 1) {
      $('.arrow.right').addClass('disabled');
    }

    this.loadDocs();

    var lines = Object.keys(level.style).length;
    $('#code').height(20 * lines).data("lines", lines);

    var string = level.board;
    var markup = '';
    var colors = {
      'g': 'green',
      'r': 'red',
      'y': 'yellow'
    };

    for (var i = 0; i < string.length; i++) {
      var c = string.charAt(i);
      var color = colors[c];

      var lilypad = $('
').addClass('lilypad ' + color).data('color', color);
      var frog = $('
').addClass('frog ' + color).data('color', color);

      $('
').addClass('bg').css(game.transform()).appendTo(lilypad);
      $('
').addClass('bg animated pulse infinite').appendTo(frog);

      $('#background').append(lilypad);
      $('#pond').append(frog);
    }

    var classes = level.classes;

    if (classes) {
      for (var rule in classes) {
        $(rule).addClass(classes[rule]);
      }
    }

    var selector = level.selector || '';
    $('#background ' + selector).css(level.style);
  },

  loadDocs: function() {
    $('#instructions code').each(function() {
      var code = $(this);
      var text = code.text();

      if (docs.hasOwnProperty(text)) {
        code.addClass('help');

        code.on('mouseenter', function(e) {

          if ($('.tooltip').length === 0) {
            var tooltip = $('

').html(docs[text]);
            var tooltipX = code.offset().left;
            var tooltipY = code.offset().top + code.height() + 13;

            tooltip.css({top: tooltipY, left: tooltipX}).appendTo($('body'));
          }
        }).on('mouseleave', function() {
          $('.tooltip').remove();
        });
      }
    });
  },

  check: function(level) {
    var lilypads = {};
    var frogs = {};
    var correct = true;

    $('.frog').each(function() {
      var key = JSON.stringify($(this).position());
      var val = $(this).data('color');
      frogs[key] = val;
    });

    $('.lilypad').each(function() {
      var key = JSON.stringify($(this).position());
      var val = $(this).data('color');

      if (!(key in frogs) || frogs[key] !== val) {
        correct = false;
      }
    });

    if (correct) {
      ga('send', {
        hitType: 'event',
        eventCategory: level.name,
        eventAction: 'correct',
        eventLabel: $('#code').val()
      });

      if (game.level >= levels.length - 1) {
        $('.frog').addClass('animated bounceOutUp');

        setTimeout(function() {
          game.win();
        }, 2500);
      } else {
        $('.frog').addClass('animated bounceOutUp');

        setTimeout(function() {
          game.next();
        }, 2500);
      }
    } else {
      ga('send', {
        hitType: 'event',
        eventCategory: level.name,
        eventAction: 'incorrect',
        eventLabel: $('#code').val()
      });

      this.tryagain();
    }
  },

  saveAnswer: function() {
    var level = levels[this.level];
    game.answers[level.name] = $('#code').val();
    localStorage.setItem('answers', JSON.stringify(game.answers));
  },

  tryagain: function() {
    $('#editor').addClass('animated shake');
  },

  win: function() {
    var level =   {
        name: 'win',
        instructions: '
You win! Thanks to your mastery of flexbox, you were able to help all of the frogs to their lilypads. Just look how hoppy they are!
',
        board: 'gyrgyrgyrgyrgyrgyrgyrgyrg',
        classes: {'#pond, #background': 'wrap'},
        style: {},
        before: "#pond {\n  display: flex;\n",
        after: "}",
      };

    this.loadLevel(level);

    $('#editor').hide();
    $('#share').show();
    $('.frog .bg').removeClass('pulse').addClass('bounce');
  },

  transform: function() {
    var scale = 1 + ((Math.random() / 5) - 0.2);
    var rotate = 360 * Math.random();

    return {'transform': 'scale(' + scale + ') rotate(' + rotate + 'deg)'};
  }
};

$(document).ready(function() {
  game.start();
});
<commit_msg>save answers before window unload<commit_after>var game = {
  level: parseInt(localStorage.level, 10) - 1 || 0,
  answers: (localStorage.answers && JSON.parse(localStorage.answers)) || {},

  start: function() {
    $('#level-counter .total').text(levels.length);
    $('#editor').show();
    $('#share').hide();

    $('#submit').on('click', function() {
      var level = levels[game.level];
      var code = $('#code').val();
      var selector = level.selector || '';
      $('#pond ' +  selector).attr('style', code);
      $('#code').focus();

      game.saveAnswer();
      game.check(level);
    });

    $('#code').on('keydown', function(e) {
      if (e.keyCode === 13) {
        var max = $(this).data('lines');
        var code = $(this).val();
        var trim = code.trim();
        var codeLength = code.split('\n').length;
        var trimLength = trim.split('\n').length;

        if (codeLength >= max) {

          if (codeLength === trimLength) {
            e.preventDefault();
            $('#submit').click();
          } else {
            $('#code').focus().val('').val(trim);
          }
        }
      }
    });

    $('#editor').on('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
      $(this).removeClass();
    });

    $('.arrow').on('click', function() {
      $('#editor').show();
      $('#share').hide();

      $('#code').focus();
      game.saveAnswer();
    });

    $('.arrow.left').on('click', function() {
      if (game.level >= 1) {
        game.prev();
      }
    });

    $('.arrow.right').on('click', function() {
      if (game.level < (levels.length - 1)) {
        game.next();
      }
    });

    $(window).on('beforeunload', function() {
      game.saveAnswer();
    });

    game.next();
  },

  prev: function() {
    this.level--;

    var levelData = levels[this.level];
    localStorage.setItem('level', this.level);
    this.loadLevel(levelData);
  },

  next: function() {
    this.level++;

    var levelData = levels[this.level];
    localStorage.setItem('level', this.level);
    this.loadLevel(levelData);
  },

  loadLevel: function(level) {
    $('#background, #pond').removeClass('wrap').attr('style', '').empty();

    var answer = game.answers[level.name];
    $('#code').val(answer);

    $('#level-counter .current').text(this.level + 1);
    $('#instructions').html(level.instructions);
    $('#before').text(level.before);
    $('#after').text(level.after);

    $('.arrow.disabled').removeClass('disabled');

    if (this.level === 0) {
      $('.arrow.left').addClass('disabled');
    }

    if (this.level === levels.length - 1) {
      $('.arrow.right').addClass('disabled');
    }

    this.loadDocs();

    var lines = Object.keys(level.style).length;
    $('#code').height(20 * lines).data("lines", lines);

    var string = level.board;
    var markup = '';
    var colors = {
      'g': 'green',
      'r': 'red',
      'y': 'yellow'
    };

    for (var i = 0; i < string.length; i++) {
      var c = string.charAt(i);
      var color = colors[c];

      var lilypad = $('
').addClass('lilypad ' + color).data('color', color);
      var frog = $('
').addClass('frog ' + color).data('color', color);

      $('
').addClass('bg').css(game.transform()).appendTo(lilypad);
      $('
').addClass('bg animated pulse infinite').appendTo(frog);

      $('#background').append(lilypad);
      $('#pond').append(frog);
    }

    var classes = level.classes;

    if (classes) {
      for (var rule in classes) {
        $(rule).addClass(classes[rule]);
      }
    }

    var selector = level.selector || '';
    $('#background ' + selector).css(level.style);
  },

  loadDocs: function() {
    $('#instructions code').each(function() {
      var code = $(this);
      var text = code.text();

      if (docs.hasOwnProperty(text)) {
        code.addClass('help');

        code.on('mouseenter', function(e) {

          if ($('.tooltip').length === 0) {
            var tooltip = $('

').html(docs[text]);
            var tooltipX = code.offset().left;
            var tooltipY = code.offset().top + code.height() + 13;

            tooltip.css({top: tooltipY, left: tooltipX}).appendTo($('body'));
          }
        }).on('mouseleave', function() {
          $('.tooltip').remove();
        });
      }
    });
  },

  check: function(level) {
    var lilypads = {};
    var frogs = {};
    var correct = true;

    $('.frog').each(function() {
      var key = JSON.stringify($(this).position());
      var val = $(this).data('color');
      frogs[key] = val;
    });

    $('.lilypad').each(function() {
      var key = JSON.stringify($(this).position());
      var val = $(this).data('color');

      if (!(key in frogs) || frogs[key] !== val) {
        correct = false;
      }
    });

    if (correct) {
      ga('send', {
        hitType: 'event',
        eventCategory: level.name,
        eventAction: 'correct',
        eventLabel: $('#code').val()
      });

      if (game.level >= levels.length - 1) {
        $('.frog').addClass('animated bounceOutUp');

        setTimeout(function() {
          game.win();
        }, 2500);
      } else {
        $('.frog').addClass('animated bounceOutUp');

        setTimeout(function() {
          game.next();
        }, 2500);
      }
    } else {
      ga('send', {
        hitType: 'event',
        eventCategory: level.name,
        eventAction: 'incorrect',
        eventLabel: $('#code').val()
      });

      this.tryagain();
    }
  },

  saveAnswer: function() {
    var level = levels[this.level];
    game.answers[level.name] = $('#code').val();
    localStorage.setItem('answers', JSON.stringify(game.answers));
  },

  tryagain: function() {
    $('#editor').addClass('animated shake');
  },

  win: function() {
    var level =   {
        name: 'win',
        instructions: '
You win! Thanks to your mastery of flexbox, you were able to help all of the frogs to their lilypads. Just look how hoppy they are!
',
        board: 'gyrgyrgyrgyrgyrgyrgyrgyrg',
        classes: {'#pond, #background': 'wrap'},
        style: {},
        before: "#pond {\n  display: flex;\n",
        after: "}",
      };

    this.loadLevel(level);

    $('#editor').hide();
    $('#share').show();
    $('.frog .bg').removeClass('pulse').addClass('bounce');
  },

  transform: function() {
    var scale = 1 + ((Math.random() / 5) - 0.2);
    var rotate = 360 * Math.random();

    return {'transform': 'scale(' + scale + ') rotate(' + rotate + 'deg)'};
  }
};

$(document).ready(function() {
  game.start();
});
<|endoftext|>


<commit_before>var args = require('minimist')(process.argv.slice(2)),
    fs   = require('fs'),
    path = require('path'),
    exec = require('child_process').exec;

var TIME_FILE = path.join('\/Users', 'wluu', 'Desktop', 'time.json');

if(args.start){
    var jobs = {
        data: []
    };

    try {
        var j = JSON.parse(fs.readFileSync(TIME_FILE, {encoding: 'utf8'})),
            d = j.data[j.data.length - 1];

        if(d.endMs === -1){
            throw new Error('Already started timer on ' + d.startTimeSlice);
        } else {
            jobs = j;
        }
    }
    catch(err){

        if(err.message === 'ENOENT, no such file or directory \'' + TIME_FILE + '\''){
            print(TIME_FILE + ' doesn\'t exist. Will create one.');
            fs.appendFileSync(TIME_FILE, '');
            // and continue forward to start the timer
        } else {
            print(err.message);
            return;
        }

    }

    var timeSlice = getTimeSlice(new Date());
    print('Started timer at ' + timeSlice);

    jobs.data.push({
        startMs: Date.now(),
        endMs: -1,
        elapsed: -1,
        jira: '',
        startTimeSlice: timeSlice,
        endTimeSlice: ''
    });

    fs.writeFileSync(TIME_FILE, JSON.stringify(jobs));
} else if (args.stop){
    var jobs = {
        data: []
    };

    try {
        var j = JSON.parse(fs.readFileSync(TIME_FILE, {encoding: 'utf8'})),
            d = j.data[j.data.length - 1];

        if(d.endMs !== -1){
            throw new Error('Previous job finished. Run \'node job.js start\' to start another timer.');
        } else {
            jobs = j;
        }
    } catch(err){
        if(err.message === 'ENOENT, no such file or directory \'' + TIME_FILE + '\''){
            print('A job does not exist. To start the timer, run \'node job.js start\'');
        } else {
            print(err.message);
        }
        return;
    }

    var endMs     = Date.now(),
        timeSlice = getTimeSlice(new Date());

    var lastJob         = jobs.data.length - 1,
        lastJob              = jobs.data[lastJob];
        lastJob.endMs        = endMs,
        lastJob.elapsed      = endMs - lastJob.startMs,
        lastJob.jira         = getJiraFormat(lastJob.elapsed),
        lastJob.endTimeSlice = timeSlice;

    print('Ended timer at ' + timeSlice);
    print('Jira format: ' + lastJob.jira);

    fs.writeFileSync(TIME_FILE, JSON.stringify(jobs));
} else if(args.last) {
    try {
        var jobs    = JSON.parse(fs.readFileSync(TIME_FILE, {encoding: 'utf8'})),
            lastJob = jobs.data[jobs.data.length - 1];

        print(JSON.stringify(lastJob, null, '\t'));

    } catch(err) {

        if(err.message === 'ENOENT, no such file or directory \'' + TIME_FILE + '\''){
            print(TIME_FILE + ' doesn\'t exist. So .... nothing to show.');
        } else {
            print(err.message);
        }

    }
} else if(args.clean){
    // Unlink the stored file
    fs.unlinkSync(TIME_FILE);
    print("Successfully deleted.")
} else {
    print('What is ' + arg + '???');
}

// returns a Jira ready format to log work e.g. 3h 30m
function getJiraFormat(ms){
    var x = ms / 1000;
        seconds = Math.floor(x % 60);
        x /= 60;
        minutes = Math.floor(x % 60);
        x /= 60;
        hours = Math.floor(x % 24);
        x /= 24;
        days = Math.floor(x % 7);
        x /= 7;
        weeks = Math.floor(x);

    var ret = (weeks ? weeks + 'w ' : '') + (days ? days + 'd ' : '') + (hours ? hours + 'h ' : '') + (minutes ? minutes + 'm' : '');
    return ret != '' ? ret : (ms + 'ms too small to process.');
}

// returns date and time in human readable format
function getTimeSlice(date){
    return new Date(date).toString();
}

function print(s){
    console.log(s);
}<commit_msg>Switch to comma from semi-colon<commit_after>var args = require('minimist')(process.argv.slice(2)),
    fs   = require('fs'),
    path = require('path'),
    exec = require('child_process').exec;

var TIME_FILE = path.join('\/Users', 'wluu', 'Desktop', 'time.json');

if(args.start){
    var jobs = {
        data: []
    };

    try {
        var j = JSON.parse(fs.readFileSync(TIME_FILE, {encoding: 'utf8'})),
            d = j.data[j.data.length - 1];

        if(d.endMs === -1){
            throw new Error('Already started timer on ' + d.startTimeSlice);
        } else {
            jobs = j;
        }
    }
    catch(err){

        if(err.message === 'ENOENT, no such file or directory \'' + TIME_FILE + '\''){
            print(TIME_FILE + ' doesn\'t exist. Will create one.');
            fs.appendFileSync(TIME_FILE, '');
            // and continue forward to start the timer
        } else {
            print(err.message);
            return;
        }

    }

    var timeSlice = getTimeSlice(new Date());
    print('Started timer at ' + timeSlice);

    jobs.data.push({
        startMs: Date.now(),
        endMs: -1,
        elapsed: -1,
        jira: '',
        startTimeSlice: timeSlice,
        endTimeSlice: ''
    });

    fs.writeFileSync(TIME_FILE, JSON.stringify(jobs));
} else if (args.stop){
    var jobs = {
        data: []
    };

    try {
        var j = JSON.parse(fs.readFileSync(TIME_FILE, {encoding: 'utf8'})),
            d = j.data[j.data.length - 1];

        if(d.endMs !== -1){
            throw new Error('Previous job finished. Run \'node job.js start\' to start another timer.');
        } else {
            jobs = j;
        }
    } catch(err){
        if(err.message === 'ENOENT, no such file or directory \'' + TIME_FILE + '\''){
            print('A job does not exist. To start the timer, run \'node job.js start\'');
        } else {
            print(err.message);
        }
        return;
    }

    var endMs     = Date.now(),
        timeSlice = getTimeSlice(new Date());

    var lastJob         = jobs.data.length - 1,
        lastJob              = jobs.data[lastJob],
        lastJob.endMs        = endMs,
        lastJob.elapsed      = endMs - lastJob.startMs,
        lastJob.jira         = getJiraFormat(lastJob.elapsed),
        lastJob.endTimeSlice = timeSlice;

    print('Ended timer at ' + timeSlice);
    print('Jira format: ' + lastJob.jira);

    fs.writeFileSync(TIME_FILE, JSON.stringify(jobs));
} else if(args.last) {
    try {
        var jobs    = JSON.parse(fs.readFileSync(TIME_FILE, {encoding: 'utf8'})),
            lastJob = jobs.data[jobs.data.length - 1];

        print(JSON.stringify(lastJob, null, '\t'));

    } catch(err) {

        if(err.message === 'ENOENT, no such file or directory \'' + TIME_FILE + '\''){
            print(TIME_FILE + ' doesn\'t exist. So .... nothing to show.');
        } else {
            print(err.message);
        }

    }
} else if(args.clean){
    // Unlink the stored file
    fs.unlinkSync(TIME_FILE);
    print("Successfully deleted.")
} else {
    print('What is ' + arg + '???');
}

// returns a Jira ready format to log work e.g. 3h 30m
function getJiraFormat(ms){
    var x = ms / 1000;
        seconds = Math.floor(x % 60);
        x /= 60;
        minutes = Math.floor(x % 60);
        x /= 60;
        hours = Math.floor(x % 24);
        x /= 24;
        days = Math.floor(x % 7);
        x /= 7;
        weeks = Math.floor(x);

    var ret = (weeks ? weeks + 'w ' : '') + (days ? days + 'd ' : '') + (hours ? hours + 'h ' : '') + (minutes ? minutes + 'm' : '');
    return ret != '' ? ret : (ms + 'ms too small to process.');
}

// returns date and time in human readable format
function getTimeSlice(date){
    return new Date(date).toString();
}

function print(s){
    console.log(s);
}
<|endoftext|>