<commit_before>/**
 * @copyright 2015, Robin Dietrich
 * @license AGPLv3 <http://www.gnu.org/licenses/agpl.html>
 */
define(function(require, exports, module) {
    main.consumes = [
        "Plugin", "language", "ext", "tabManager", "c9", "save",
        "settings", "preferences", "fs"
    ];
    main.provides = ["cpp"];

    return main;

    // returns true if file is handled by us (by extension)
    function is_c_cpp(filename) {
        // handled extensions
        var _extensions = ["c", "h", "cc", "cpp", "hpp", "cxx", "hxx"];

        // get extension
        var _extension = filename.split(".");
        if (_extension.length < 2)
            return false;

        _extension = _extension[_extension.length - 1];
        return (_extensions.indexOf(_extension) >= 0);
    }

    function main(options, imports, register) {
        var _ = require("lodash");
        var language = imports.language;
        var ext = imports.ext;
        var Plugin = imports.Plugin;
        var plugin = new Plugin("Robin Dietrich", main.consumes);
        var tabManager = imports.tabManager;
        var c9 = imports.c9;
        var save = imports.save;
        var settings = imports.settings;
        var prefs = imports.preferences;
        var fs = imports.fs;

        // Use this to get the full file path for clang-autocomplete
        var basedir = c9.workspaceDir;

        // External clang_tool component
        var clang_tool = null;

        function loadClangTool() {
            ext.loadRemotePlugin("clang_tool", {
                code: require("text!./cpp_server.js"),
                redefine: !clang_tool
            }, function(err, plugin) {
                if (err) {
                    alert("[c9.ide.language.cpp] Error initializing server: ", err);
                    return;
                }

                clang_tool = plugin;
                clang_tool.load();
                clang_tool.setArgs(settings.get("project/c_cpp/@compilerArguments").split("\n"));
            });
        }

        c9.on("connect", loadClangTool);
        c9.on("disconnect", function() {
            if (clang_tool) {
                clang_tool.indexClear();
                clang_tool = null;
            }
        });

        // Register our language handler
        var worker = null;

        language.registerLanguageHandler('plugins/c9.ide.language.cpp/cpp_worker', function(err, worker_) {
            if (err) {
                alert("[[c9.ide.language.cpp] Error initializing worker: ", err);
                return;
            }

            // Set worker object and register callback's
            worker = worker_;

            // Put each document that is opened and handled on the index
            worker.on("documentOpened", function(event) {
                if (is_c_cpp(event.data.path))
                    clang_tool.indexTouch(basedir+event.data.path);
            });

            // Automatically free memory of closed objects
            worker.on("documentClosed", function(event) {
                if (is_c_cpp(event.data.path))
                    clang_tool.indexClear(basedir+event.data.path);
            });

            // Handle code completion
            worker.on("completion", function(event) {
                var value = tabManager.focussedTab.document.value;
                var path = basedir+tabManager.focussedTab.path;

                // add temporary data to index
                clang_tool.indexTouchUnsaved(path, value);

                // do the code completion
                clang_tool.cursorCandidatesAt(path, event.data.pos.row+1, event.data.pos.column+1, function(err, res) {
                    worker.emit("completionResult", {data: {id: event.data.id, results: res}});
                });
            });

            // Handle diagnostics
            worker.on("diagnose", function(event) {
                var value = tabManager.focussedTab.document.value;
                var path = basedir+tabManager.focussedTab.path;

                // add temporary data to index
                //clang_tool.indexTouch(path);
                //clang_tool.indexTouchUnsaved(path, value);

                // diagnosis
                clang_tool.fileDiagnose(path, function(err, res) {
                    // This is unstable, @todo: find out what's crashing clang
                    //worker.emit("diagnoseResult", {data: {id: event.data.id, results: res, path: path}});
                    worker.emit("diagnoseResult", {data: {id: event.data.id, results: [], path: path}});
                })
            });
        });

        // Initialize the plugin
        plugin.on("load", function() {
            // Add project specific preferences
            prefs.add({
                "Project" : {
                    "C / C++" : {
                        position: 1000,
                        "Compiler Arguments" : {
                           type: "textarea",
                           width: 200,
                           height: 130,
                           rowheight: 155,
                           path: "project/c_cpp/@compilerArguments",
                           position: 5000
                        }
                    }
                }
            }, plugin);

            // Set default values
            settings.on("read", function(e) {
                settings.setDefaults("project/c_cpp", [
                    ["compilerArguments", "-I/usr/include\n-I/usr/local/include"]
                ]);
            }, plugin);

            // Listen to updates
            settings.on("project/c_cpp/@compilerArguments", function(value) {
                if (clang_tool)
                    clang_tool.setArgs(value.split("\n"));
            }, plugin);
        });

        // Make sure the plugin is unloaded correctly so that cached translation units get purged
        plugin.on("unload", function(){
            if (clang_tool) {
                clang_tool.unload();
                clang_tool = null;
                worker = null;
            }
        });

        // Public api for the cpp plugin
        plugin.freezePublicAPI({});

        // Registers our plugin with C9
        register(null, { cpp: plugin });
    }
});
<commit_msg>Implemented outline + diagnose in worker, added css<commit_after>/**
 * @copyright 2015, Robin Dietrich
 * @license AGPLv3 <http://www.gnu.org/licenses/agpl.html>
 */
define(function(require, exports, module) {
    main.consumes = [
        "Plugin", "language", "ext", "tabManager", "c9", "save",
        "settings", "preferences", "fs", "ui"
    ];
    main.provides = ["cpp"];

    return main;

    // returns true if file is handled by us (by extension)
    function is_c_cpp(filename) {
        // handled extensions
        var _extensions = ["c", "h", "cc", "cpp", "hpp", "cxx", "hxx"];

        // get extension
        var _extension = filename.split(".");
        if (_extension.length < 2)
            return false;

        _extension = _extension[_extension.length - 1];
        return (_extensions.indexOf(_extension) >= 0);
    }

    function main(options, imports, register) {
        var _ = require("lodash");
        var language = imports.language;
        var ext = imports.ext;
        var Plugin = imports.Plugin;
        var plugin = new Plugin("Robin Dietrich", main.consumes);
        var tabManager = imports.tabManager;
        var c9 = imports.c9;
        var save = imports.save;
        var settings = imports.settings;
        var prefs = imports.preferences;
        var fs = imports.fs;
        var ui = imports.ui;

        // Use this to get the full file path for clang-autocomplete
        var basedir = c9.workspaceDir;

        // External clang_tool component
        var clang_tool = null;

        function loadClangTool() {
            ext.loadRemotePlugin("clang_tool", {
                code: require("text!./cpp_server.js"),
                redefine: !clang_tool
            }, function(err, plugin) {
                if (err) {
                    alert("[c9.ide.language.cpp] Error initializing server: ", err);
                    return;
                }

                clang_tool = plugin;
                clang_tool.load();
                clang_tool.setArgs(settings.get("project/c_cpp/@compilerArguments").split("\n"));
            });
        }

        c9.on("connect", loadClangTool);
        c9.on("disconnect", function() {
            if (clang_tool) {
                clang_tool.indexClear();
                clang_tool = null;
            }
        });

        // Register our language handler
        var worker = null;

        language.registerLanguageHandler('plugins/c9.ide.language.cpp/cpp_worker', function(err, worker_) {
            if (err) {
                alert("[[c9.ide.language.cpp] Error initializing worker: ", err);
                return;
            }

            // Set worker object and register callback's
            worker = worker_;

            // Put each document that is opened and handled on the index
            worker.on("documentOpened", function(event) {
                if (!is_c_cpp(event.data.path))
                    return;

                // add to index
                clang_tool.indexTouch(basedir+event.data.path);
            });

            // Listen fo file saves and add on-disk content to the index
            // This might trigger when documentClosed is emitted and do one
            // additional parse before indexClear is called.
            save.on("afterSave", function(ev) {
                if (!is_c_cpp(ev.path))
                    return;

                // add / update on index
                clang_tool.indexTouch(basedir+ev.path);
            });

            // Automatically free memory of closed objects
            worker.on("documentClosed", function(event) {
                if (!is_c_cpp(event.data.path))
                    return;

                clang_tool.indexClear(basedir+event.data.path);
            });

            //
            // Important:
            // Do not run indexTouch or indexTouchUnsaved for each and every worker action.
            // Certain actions may be interleaved, creating a indexTouch <-> indexTouchUnsaved chain
            // that takes forever to resolve.
            //
            // + Call indexTouchUnsaved in all worker functions that handle temp data
            // + Call indexTouch only on save events
            //

            // Handle code completion
            worker.on("_completion", function(event) {
                var value = tabManager.focussedTab.document.value;
                var path = basedir+tabManager.focussedTab.path;

                // add temporary data to index
                clang_tool.indexTouchUnsaved(path, value);

                // do the code completion
                clang_tool.cursorCandidatesAt(path, event.data.pos.row+1, event.data.pos.column+1, function(err, res) {
                    worker.emit("_completionResult", {data: {id: event.data.id, results: res}});
                });
            });

            // Handle diagnostics
            worker.on("_diagnose", function(event) {
                var value = tabManager.focussedTab.document.value;
                var path = basedir+tabManager.focussedTab.path;

                clang_tool.fileDiagnose(path, function(err, res) {
                    res = _.filter(res, function(r) {
                        return r.file == path;
                    });

                    worker.emit("_diagnoseResult", {data: {id: event.data.id, results: res, path: path}});
                    //worker.emit("_diagnoseResult", {data: {id: event.data.id, results: [], path: path}});
                });
            });

            // Handle outline
            worker.on("_outline", function(event) {
                var path = basedir+tabManager.focussedTab.path;

                if (!is_c_cpp(path)) // Outline is called independet of handlesLanguage
                    return;

                // generate outline
                clang_tool.fileOutline(path, function(err, res) {
                    worker.emit("_outlineResult", {data: {id: event.data.id, results: res}});
                });
            });
        });

        // Initialize the plugin
        plugin.on("load", function() {
            // Add project specific preferences
            prefs.add({
                "Project" : {
                    "C / C++" : {
                        position: 1000,
                        "Compiler Arguments" : {
                           type: "textarea",
                           width: 200,
                           height: 130,
                           rowheight: 155,
                           path: "project/c_cpp/@compilerArguments",
                           position: 5000
                        }
                    }
                }
            }, plugin);

            // Set default values
            settings.on("read", function(e) {
                settings.setDefaults("project/c_cpp", [
                    ["compilerArguments", "-I/usr/include\n-I/usr/local/include"]
                ]);
            }, plugin);

            // Listen to updates
            settings.on("project/c_cpp/@compilerArguments", function(value) {
                if (clang_tool)
                    clang_tool.setArgs(value.split("\n"));
            }, plugin);

            // Add css
            ui.insertCss(require("text!./icons.css"), false, plugin);
            console.log("Added css", options.staticPrefix, require("text!./icons.css"));
        });

        // Make sure the plugin is unloaded correctly so that cached translation units get purged
        plugin.on("unload", function(){
            if (clang_tool) {
                clang_tool.unload();
                clang_tool = null;
                worker = null;
            }
        });

        // Public api for the cpp plugin
        plugin.freezePublicAPI({});

        // Registers our plugin with C9
        register(null, { cpp: plugin });
    }
});
<|endoftext|>


<commit_before>// dna.js Template Cloner, version 0.2 (beta)
// GPLv3/MIT, see: dnajs.org/license.html
// Copyright (c) 2013 Center Key Software and other contributors

var dna = {};

dna.util = {
   defaults: function(options, defaults) {
      //Sets each missing field in options to its default value
      if (options)
         for (var field in defaults)
            if (defaults.hasOwnProperty(field))
               if (typeof options[field] == 'undefined')
                  options[field] = defaults[field];
      return options ? options : defaults;
      }
   };

dna.core = {
   templates: $('.dna-template'),
   findFieldElems: function(template) {
      //Returns list of elements whose content is a dna field
      var regex = /^(~~|{{).*(~~|}})$/;  //dna field, example: ~~title~~
      return template.find('*').filter(
         function() { return $(this).text().match(regex); }
         );
      },
   compile: function(template) {
      //Prepares template to be cloned
      var regex = /~~|{{|}}/g;  //dna base pairs
      dna.core.findFieldElems(template).each(function() {
         var elem = $(this);
         elem.addClass('dna-field').data('dna-field', elem.text().replace(regex, '')).empty();
         });
      return template.addClass('dna-compiled').data('dna', 0);
      },
   getTemplate: function(name) {
      var template = dna.core.templates.filter('[data-dna-name=' + name + ']');
      if (!template.hasClass('dna-compiled'))
         dna.core.compile(template);
      return template;
      }
   };

dna.api = {
   clone: function(name, dataObj, options) {
      options = dna.util.defaults(options, { fade: false });
      var template = dna.core.getTemplate(name);
      var elem = template.clone(true, true).removeClass('dna-template dna-compiled');
      template.data('dna', template.data('dna') + 1);
      elem.addClass('dna-clone').find('.dna-field').each(function() {
         console.log($(this).data('dna-field'));
         $(this).html(dataObj[$(this).data('dna-field')]);
         });
      if (options.top)
         template.after(elem);
      else
         template.parent().append(elem);
      if (options.fade)
         elem.hide().fadeIn();
      return elem;
      },
   empty: function(name, options) {
      options = dna.util.defaults(options, { fade: false });
      var elems = dna.core.getTemplate(name).parent().children('.dna-clone');
      var duration = options.fade ? 'normal' : 0;
      return elems.fadeOut(duration, function() { $(this).remove(); });
      }
   };

dna.clone = dna.api.clone;
dna.empty = dna.api.empty;
<commit_msg>Select templates when first needed, patterns compiled only once, and support for images<commit_after>// dna.js Template Cloner, version 0.2 (beta)
// GPLv3/MIT, see: dnajs.org/license.html
// Copyright (c) 2013 Center Key Software and other contributors

var dna = {};

dna.util = {
   defaults: function(options, defaults) {
      //Sets each missing field in options to its default value
      if (options)
         for (var field in defaults)
            if (defaults.hasOwnProperty(field))
               if (typeof options[field] == 'undefined')
                  options[field] = defaults[field];
      return options ? options : defaults;
      }
   };

dna.core = {
   templates: null,
   regexDnaField: /^(~~|{{).*(~~|}})$/,  //example: ~~title~~
   regexDnaBasePairs: /~~|{{|}}/g,  //mathces the two "~~" strings so they can be removed
   getTemplates: function() {
      if (!dna.core.templates)
         dna.core.templates = $('.dna-template');
      return dna.core.templates;
      },
   findFieldElems: function(template) {
      //Returns list of elements whose content is a dna field
      return template.find('*').filter(
         function() { return $(this).text().match(dna.core.regexDnaField); }
         );
      },
   compile: function(template) {
      //Prepares template to be cloned
      dna.core.findFieldElems(template).each(function() {
         var elem = $(this);
         elem.addClass('dna-field').data('dna-field', elem.text().replace(dna.core.regexDnaBasePairs, '')).empty();
         });
      template.find('img[data-dna-src]').each(function () {
         $(this).addClass('dna-image-field')
            .data('dna-src', $(this).data('dna-src').replace(dna.core.regexDnaBasePairs, ''));
         });
      return template.addClass('dna-compiled').data('dna', 0);
      },
   getTemplate: function(name) {
      var template = dna.core.getTemplates().filter('[data-dna-name=' + name + ']');
      if (!template.hasClass('dna-compiled'))
         dna.core.compile(template);
      return template;
      }
   };

dna.api = {
   clone: function(name, dataObj, options) {
      options = dna.util.defaults(options, { fade: false });
      var template = dna.core.getTemplate(name);
      var elem = template.clone(true, true).removeClass('dna-template dna-compiled');
      template.data('dna', template.data('dna') + 1);
      elem.addClass('dna-clone').find('.dna-field').each(function() {
         $(this).html(dataObj[$(this).data('dna-field')]);
         });
      elem.find('.dna-image-field').each(function() {
         $(this).attr('src', dataObj[$(this).data('dna-src')]);
         });
      if (options.top)
         template.after(elem);
      else
         template.parent().append(elem);
      if (options.fade)
         elem.hide().fadeIn();
      return elem;
      },
   empty: function(name, options) {
      options = dna.util.defaults(options, { fade: false });
      var elems = dna.core.getTemplate(name).parent().children('.dna-clone');
      var duration = options.fade ? 'normal' : 0;
      return elems.fadeOut(duration, function() { $(this).remove(); });
      }
   };

dna.clone = dna.api.clone;
dna.empty = dna.api.empty;
<|endoftext|>


<commit_before>/* ex: set tabstop=2 softtabstop=2 shiftwidth=2 : */
/*jshint unused:false, boss:true */
/*global DOMTokenList:true */

/**
 * @description
 * shorthand for getElementById
 * @param el
 */
function ___(el) {
  return document.getElementById(el);
}

/**
 * @name elementHasClass
 * @function
 *
 * @description
 *
 * @param element
 * @param _className
 */
function elementHasClass(el, _className) {
  // has to do this check first because if _className is not present
  // and el is absence as well, it should not return true
  if (!el) {
    throw new Error("elementHasClass failed becase element is undefined");
  }
  if (!_className) {
    return true;
  }
  if (!el.className) {
    return false;
  }

  // so that we do not have to make special case for the 1st / last item
  return (new RegExp("\\b" + _className + "\\b").test(el.className));
}

/**
 * @name elementCanBeDescribedAs
 * @function
 *
 * @description
 *
 * support 4 selectors:
 * 1.  #id
 * 2.  .className
 * 3.  tagName
 * 4.  tagName.className
 *
 * @param el
 * @param selector
 */
function elementFitsDescription(el, selector) {
  if (!selector) {
    return false;
  }
  if (!el) {
    return false;
  }

  var _tagName, _className, pos;

  switch (selector.charAt(0)) {
  case "#" :
    if ("#" + el.id === selector) {
      return el;
    }
    break;
  case "." :
    // so we do not have to consider whether the className is the first or the last
    if (elementHasClass(el, selector.substring(1))) {
      return el;
    }
    break;
  default :
    pos = selector.indexOf(".");
    // tagName.className
    // now we know that "." will not be the leading character
    if (~pos) {
      _tagName = selector;
      _className = _tagName.splice(0, pos).substring(1);
      if ((el.tagName.toLowerCase() === _tagName) && elementHasClass(el, _className)) {
        return el;
      }
    }
    // tagName
    else {
      // apparently `#' will not be at 0
      if (selector.indexOf("#") > 0) {
        throw new Error(selector + "not supported, use #id instead.");
      }
      else {
        if (el.tagName.toLowerCase() === selector) {
          return el;
        }
      }
    }
    // end of default branch
  }
  return null;
}

/**
 * @name manipulateClass
 * @function
 *
 * @description
 * order of execution:
 * remove then add
 *
 * @param el
 * @param option
 * parameters:
 * {
 *    add   : STRING/ARRAY (must be unique)
 *    remove: STRING/ARRAY (must be unique)
 * }
 */
function manipulateClass(el, option) {
  if (!el || !option || typeof option !== "object") {
    return;
  }

  var toAdd = [], toRemove = [];
  if (option.add) {
    if (typeof option.add === "string") {
      toAdd = option.add.split(/\s+/).unique();
    }
    else if (typeof option.add === "array") {
      toAdd = option.add;
    }
  }
  if (option.remove) {
    if (typeof option.remove === "string") {
      toRemove = option.remove.split(/\s+/).unique();
    }
    if (typeof option.remove === "array") {
      toRemove = option.remove;
    }
  }

  if ("classList" in document.body && "DOMTokenList" in window) {
    if (toRemove.length) {
      DOMTokenList.prototype.remove.apply(el.classList, toRemove);
    }
    if (toAdd.length) {
      DOMTokenList.prototype.add.apply(el.classList, toAdd);
    }
    return;
  }

  var  _classNameArray, _className = el.className;

  if (!_className) {
    if (option.add) {
      el.className = option.add;
      return;
    }
    // nothing else to do
    return;
  }

  // FIXME: use classList as much as possible
  _classNameArray = _className.split(/\s+/).unique();

  if (option.remove) {
    _classNameArray = _classNameArray.diff(toRemove);
  }
  if (option.add) {
    // in case there is duplicate
    var classToAdd = option.add.split(" ");

    // remove duplicates and join two arraries
    [].push.apply(_classNameArray, toAdd.diff(_classNameArray));
  }
  el.className = _classNameArray.join(" ");
  return;
}

/**
 * @name toggleElement
 * @function
 *
 * @description
 * @param el
 * @param state
 */
function toggleElement(el, state) {
  if (!___(el)) {
    return;
  }
  return ___(el).style.display = state ? state : "none";
}
<commit_msg>setting null at the end of function<commit_after>/* ex: set tabstop=2 softtabstop=2 shiftwidth=2 : */
/*jshint unused:false, boss:true */
/*global DOMTokenList:true */

/**
 * @description
 * shorthand for getElementById
 * @param el
 */
function ___(el) {
  return document.getElementById(el);
}

/**
 * @name elementHasClass
 * @function
 *
 * @description
 *
 * @param element
 * @param _className
 */
function elementHasClass(el, _className) {
  // has to do this check first because if _className is not present
  // and el is absence as well, it should not return true
  if (!el) {
    throw new Error("elementHasClass failed becase element is undefined");
  }
  if (!_className) {
    return true;
  }
  if (!el.className) {
    return false;
  }

  // so that we do not have to make special case for the 1st / last item
  return (new RegExp("\\b" + _className + "\\b").test(el.className));
}

/**
 * @name elementCanBeDescribedAs
 * @function
 *
 * @description
 *
 * support 4 selectors:
 * 1.  #id
 * 2.  .className
 * 3.  tagName
 * 4.  tagName.className
 *
 * @param el
 * @param selector
 */
function elementFitsDescription(el, selector) {
  if (!selector) {
    return false;
  }
  if (!el) {
    return false;
  }

  var _tagName, _className, pos;

  switch (selector.charAt(0)) {
  case "#" :
    if ("#" + el.id === selector) {
      return el;
    }
    break;
  case "." :
    // so we do not have to consider whether the className is the first or the last
    if (elementHasClass(el, selector.substring(1))) {
      return el;
    }
    break;
  default :
    pos = selector.indexOf(".");
    // tagName.className
    // now we know that "." will not be the leading character
    if (~pos) {
      _tagName = selector;
      _className = _tagName.splice(0, pos).substring(1);
      if ((el.tagName.toLowerCase() === _tagName) && elementHasClass(el, _className)) {
        return el;
      }
    }
    // tagName
    else {
      // apparently `#' will not be at 0
      if (selector.indexOf("#") > 0) {
        throw new Error(selector + "not supported, use #id instead.");
      }
      else {
        if (el.tagName.toLowerCase() === selector) {
          return el;
        }
      }
    }
    // end of default branch
  }
  return null;
}

/**
 * @name manipulateClass
 * @function
 *
 * @description
 * order of execution:
 * remove then add
 *
 * @param el
 * @param option
 * parameters:
 * {
 *    add   : STRING/ARRAY (must be unique)
 *    remove: STRING/ARRAY (must be unique)
 * }
 */
function manipulateClass(el, option) {
  if (!el || !option || typeof option !== "object") {
    return;
  }

  var toAdd = [], toRemove = [];
  if (option.add) {
    if (typeof option.add === "string") {
      toAdd = option.add.split(/\s+/).unique();
    }
    else if (typeof option.add === "array") {
      toAdd = option.add;
    }
  }
  if (option.remove) {
    if (typeof option.remove === "string") {
      toRemove = option.remove.split(/\s+/).unique();
    }
    if (typeof option.remove === "array") {
      toRemove = option.remove;
    }
  }

  if ("classList" in document.body && "DOMTokenList" in window) {
    if (toRemove.length) {
      DOMTokenList.prototype.remove.apply(el.classList, toRemove);
    }
    if (toAdd.length) {
      DOMTokenList.prototype.add.apply(el.classList, toAdd);
    }
    return;
  }

  var  _classNameArray, _className = el.className;

  if (!_className) {
    if (option.add) {
      el.className = option.add;
      return;
    }
    // nothing else to do
    return;
  }

  // FIXME: use classList as much as possible
  _classNameArray = _className.split(/\s+/).unique();

  if (option.remove) {
    _classNameArray = _classNameArray.diff(toRemove);
  }
  if (option.add) {
    // in case there is duplicate
    var classToAdd = option.add.split(" ");

    // remove duplicates and join two arraries
    [].push.apply(_classNameArray, toAdd.diff(_classNameArray));
  }
  el.className = _classNameArray.join(" ");
  _classNameArray = null;
  _className = null;
  toAdd = null;
  toRemove = null;
  return;
}

/**
 * @name toggleElement
 * @function
 *
 * @description
 * @param el
 * @param state
 */
function toggleElement(el, state) {
  if (!___(el)) {
    return;
  }
  return ___(el).style.display = state ? state : "none";
}
<|endoftext|>


<commit_before>[$if, [$mt, 10, 20],
    "Uh, well this is awkward.",
    [str, "EVERYTHING IS FINE, MOVE ALONG ", [reduce, $add, [1, 2, 3]]]]
<commit_msg>Added plain JavaScript version.<commit_after>[$if, [$mt, 10, 20],
    "Uh, well this is awkward.",
    [str, "EVERYTHING IS FINE, MOVE ALONG ", [reduce, $add, [1, 2, 3]]]]

(function () {
    if (10 > 20) {
        return "Uh, well this is awkward.";
    }
    else {
        return "EVERYTHING IS FINE, MOVE ALONG " + [1, 2, 3].reduce(function (a, b) {
            return a + b;
        });
    }
}());
<|endoftext|>


<commit_before>var spawn = require("child_process").spawn;
var boundary = require("./boundary.js");

function iis() {
}

iis.getWorkerProcesses = function(callback) {
  var _this = this;

  var appcmd = spawn("appcmd", ["list", "wps"], { cwd: process.env.windir + "\\system32\\inetsrv" });
  var processes = [];

  appcmd.stdout = boundary.delimited(appcmd.stdout);

  appcmd.stdout.on("message", function(message) {
    message = message.toString();

    if (!message)
      return;

    if (message.indexOf("ERROR") != -1) {
      callback(message);
      return;
    }

    var match = /WP "(\d+)" \(applicationPool:(.+?)\)/.exec(message);

    processes.push({
      processId: parseInt(match[1], 10),
      appPool: match[2]
    });
  });

  appcmd.on("error", function() {
    callback(null, [processes]);
  });

  appcmd.on("close", function() {
    callback(null, processes);
  });
};

module.exports = iis;<commit_msg>Fixed a bug that caused permon to start twice on systems where IIS was not installed.<commit_after>var spawn = require("child_process").spawn;
var boundary = require("./boundary.js");

function iis() {
}

iis.getWorkerProcesses = function(callback) {
  var _this = this;

  var appcmd = spawn("appcmd", ["list", "wps"], { cwd: process.env.windir + "\\system32\\inetsrv" });
  var processes = [];

  appcmd.stdout = boundary.delimited(appcmd.stdout);

  appcmd.stdout.on("message", function(message) {
    message = message.toString();

    if (!message)
      return;

    if (message.indexOf("ERROR") != -1) {
      callback(message);
      return;
    }

    var match = /WP "(\d+)" \(applicationPool:(.+?)\)/.exec(message);

    processes.push({
      processId: parseInt(match[1], 10),
      appPool: match[2]
    });
  });

  appcmd.on("error", function() {
    // Ignore if appcmd doesn't exist
    // Don't need to call the callback, 'close' event will be emitted
  });

  appcmd.on("close", function() {
    callback(null, processes);
  });
};

module.exports = iis;<|endoftext|>


<commit_before>var msgRe = /([^ ]+) (<[^>]+>) (.*)/;
var kibozeRe = "neal";

function isinView(oObject) {
	return (oObject.offsetParent.clientHeight <= oObject.offsetTop);
}

function addMessagePart(p, className, text) {
	var e = document.createElement("span");
	e.className = className;
	e.appendChild(document.createTextNode(text));
	p.appendChild(e);
	p.appendChild(document.createTextNode(" "));
}

function addMessage(txt) {
	var lhs = txt.split(" :", 1)[0]
	var parts = lhs.split(' ')
	var ts = new Date(parts[0] * 1000);
	var fullSender = parts[1];
	var command = parts[2];
	var sender = parts[3];
	var forum = parts[4];
	var args = parts.slice(5);
	var msg = txt.substr(lhs.length + 2)

	var a = document.getElementById("a");
	var p = document.createElement("p");

	addMessagePart(p, "timestamp", ts.toLocaleTimeString());

	switch (command) {
	case "PING":
	case "PONG":
		return;
		break;
	case "PRIVMSG":
		addMessagePart(p, "forum", forum);
		addMessagePart(p, "sender", sender);
		addMessagePart(p, "text", msg);
		if (-1 != msg.search(kibozeRe)) {
			var k = document.getElementById("kiboze");
			var p2 = p.cloneNode(true);
			k.insertBefore(p2, k.firstChild);
		}
		break;
	default:
		addMessagePart(p, "forum", forum);
		addMessagePart(p, "sender", sender);
		addMessagePart(p, "raw", command + " " + args + " " + msg);
		break;
	}
	a.appendChild(p);
	p.scrollIntoView(false);
}

function newmsg(event) {
	msgs = event.data.split("\n");

	for (var i = 0; i < msgs.length; i += 1) {
		addMessage(msgs[i]);
	}
}

function handleCommand(event) {
	window.evt = event;
	var oReq = new XMLHttpRequest();
	function reqListener() {
	}
	oReq.onload = reqListener;
	oReq.open("POST", "irc.cgi", true);
	oReq.send(new FormData(event.target));

	event.target.reset();

	return false;
}

function init() {
	var authtok = prompt("Auth token", "");
	document.getElementById("authtok").value = authtok;

	var source = new EventSource("irc.cgi?auth=" + authtok);
	source.onmessage = newmsg;

	document.getElementById("command").onsubmit = handleCommand;
}

window.onload = init;
<commit_msg>Pulse kibozed lines when clicked<commit_after>var msgRe = /([^ ]+) (<[^>]+>) (.*)/;
var kibozeRe = "neal";

function isinView(oObject) {
	return (oObject.offsetParent.clientHeight <= oObject.offsetTop);
}

function addMessagePart(p, className, text) {
	var e = document.createElement("span");
	e.className = className;
	e.appendChild(document.createTextNode(text));
	p.appendChild(e);
	p.appendChild(document.createTextNode(" "));
}

function focus(e) {
	var pct = 1;
	var timeout;

	e.scrollIntoView(false);
	e.style.backgroundColor = "yellow";

	timeout = setInterval(function() {
		pct = pct - 0.1;
		e.style.backgroundColor = "rgba(255, 255, 0, " + pct + ")";
		if (pct <= 0) {
			e.style.backgroundColor = "inherit";
			clearInterval(timeout);
		}
	}, 50)
}

function addMessage(txt) {
	var lhs = txt.split(" :", 1)[0]
	var parts = lhs.split(' ')
	var ts = new Date(parts[0] * 1000);
	var fullSender = parts[1];
	var command = parts[2];
	var sender = parts[3];
	var forum = parts[4];
	var args = parts.slice(5);
	var msg = txt.substr(lhs.length + 2)

	var a = document.getElementById("a");
	var p = document.createElement("p");

	addMessagePart(p, "timestamp", ts.toLocaleTimeString());

	switch (command) {
	case "PING":
	case "PONG":
		return;
		break;
	case "PRIVMSG":
		addMessagePart(p, "forum", forum);
		addMessagePart(p, "sender", sender);
		addMessagePart(p, "text", msg);
		if (-1 != msg.search(kibozeRe)) {
			var k = document.getElementById("kiboze");
			var p2 = p.cloneNode(true);
			k.insertBefore(p2, k.firstChild);
			p2.onclick = function() { focus(p); }
		}
		break;
	default:
		addMessagePart(p, "forum", forum);
		addMessagePart(p, "sender", sender);
		addMessagePart(p, "raw", command + " " + args + " " + msg);
		break;
	}
	a.appendChild(p);
	p.scrollIntoView(false);
}

function newmsg(event) {
	msgs = event.data.split("\n");

	for (var i = 0; i < msgs.length; i += 1) {
		addMessage(msgs[i]);
	}
}

function handleCommand(event) {
	window.evt = event;
	var oReq = new XMLHttpRequest();
	function reqListener() {
	}
	oReq.onload = reqListener;
	oReq.open("POST", "irc.cgi", true);
	oReq.send(new FormData(event.target));

	event.target.reset();

	return false;
}

function init() {
	var authtok = prompt("Auth token", "");
	document.getElementById("authtok").value = authtok;

	var source = new EventSource("irc.cgi?auth=" + authtok);
	source.onmessage = newmsg;

	document.getElementById("command").onsubmit = handleCommand;
}

window.onload = init;
<|endoftext|>


<commit_before>"use strict";

var GameBoyAdvanceInterruptHandler = function() {
	this.FREQUENCY = 16780000;

	this.cpu = null;
	this.enable = false;

	this.IRQ_VBLANK = 0x0;
	this.IRQ_HBLANK = 0x1;
	this.IRQ_VCOUNTER = 0x2;
	this.IRQ_TIMER0 = 0x3;
	this.IRQ_TIMER1 = 0x4;
	this.IRQ_TIMER2 = 0x5;
	this.IRQ_TIMER3 = 0x6;
	this.IRQ_SIO = 0x7;
	this.IRQ_DMA0 = 0x8;
	this.IRQ_DMA1 = 0x9;
	this.IRQ_DMA2 = 0xA;
	this.IRQ_DMA3 = 0xB;
	this.IRQ_KEYPAD = 0xC;
	this.IRQ_GAMEPAK = 0xD;

	this.MASK_VBLANK = 0x0001;
	this.MASK_HBLANK = 0x0002;
	this.MASK_VCOUNTER = 0x0004;
	this.MASK_TIMER0 = 0x0008;
	this.MASK_TIMER1 = 0x0010;
	this.MASK_TIMER2 = 0x0020;
	this.MASK_TIMER3 = 0x0040;
	this.MASK_SIO = 0x0080;
	this.MASK_DMA0 = 0x0100;
	this.MASK_DMA1 = 0x0200;
	this.MASK_DMA2 = 0x0400;
	this.MASK_DMA3 = 0x0800;
	this.MASK_KEYPAD = 0x1000;
	this.MASK_GAMEPAK = 0x2000;

	this.enabledIRQs = new Array(14);
	this.interruptFlags = 0;

	this.dma = new Array();
	for (var i = 0; i < 4; ++i) {
		this.dma.push({
			source: 0,
			dest: 0,
			count: 0,
			srcControl: 0,
			dstControl: 0,
			repeat: 0,
			width: 0,
			drq: 0,
			timing: 0,
			doIrq: 0,
			enable: 0
		});
	}

	this.timersEnabled = 0;
	this.timers = new Array();
	for (var i = 0; i < 4; ++i) {
		this.timers.push({
			reload: 0,
			prescale: 0,
			countUp: 0,
			doIrq: 0,
			enable: 0,
			lastEvent: 0
		});
	}

	this.nextInterrupt = 0;
};

GameBoyAdvanceInterruptHandler.prototype.setCPU = function(cpu) {
	this.cpu = cpu;
}

GameBoyAdvanceInterruptHandler.prototype.setVideo = function(video) {
	this.video = video;
}

GameBoyAdvanceInterruptHandler.prototype.updateTimers = function() {
	this.video.updateTimers(this.cpu);
	if (this.timersEnabled) {
		// TODO: add timer IRQs
		// TODO: check for overflow
		if (this.timersEnabled & 0x1) {
			var timer = this.timers[0];
			if (this.cpu.cycles >= timer.nextEvent) {
				timer.lastEvent = timer.nextEvent;
				timer.nextEvent += timer.prescale;
				++this.cpu.mmu.io.registers[this.cpu.mmu.io.TM0CNT_LO];
			}
		}
		if (this.timersEnabled & 0x2) {
			var timer = this.timers[1];
			if (this.cpu.cycles >= timer.nextEvent) {
				timer.lastEvent = timer.nextEvent;
				timer.nextEvent += timer.prescale;
				++this.cpu.mmu.io.registers[this.cpu.mmu.io.TM1CNT_LO];
			}
		}
		if (this.timersEnabled & 0x4) {
			var timer = this.timers[2];
			if (this.cpu.cycles >= timer.nextEvent) {
				timer.lastEvent = timer.nextEvent;
				timer.nextEvent += timer.prescale;
				++this.cpu.mmu.io.registers[this.cpu.mmu.io.TM2CNT_LO];
			}
		}
		if (this.timersEnabled & 0x8) {
			var timer = this.timers[3];
			if (this.cpu.cycles >= timer.nextEvent) {
				timer.lastEvent = timer.nextEvent;
				timer.nextEvent += timer.prescale;
				++this.cpu.mmu.io.registers[this.cpu.mmu.io.TM3CNT_LO];
			}
		}
	}
}

GameBoyAdvanceInterruptHandler.prototype.swi = function(opcode) {
	switch (opcode) {
	case 0x02:
		// Halt
		if (!this.enable) {
			throw "Requested HALT when interrupts were disabled!";
		}
		this.poll();
		if (this.nextInterrupt >= this.cpu.cycles) {
			this.cpu.cycles = this.nextInterrupt;
		} else {
			throw "Waiting on interrupt forever.";
		}
		break;
	case 0x0B:
		// CpuSet
		var source = this.cpu.gprs[0];
		var dest = this.cpu.gprs[1];
		var mode = this.cpu.gprs[2];
		var count = mode & 0x000FFFFF;
		var fill = mode & 0x01000000;
		var wordsize = (mode & 0x04000000) ? 4 : 2;
		if (fill) {
			if (wordsize == 4) {
				var word = this.cpu.mmu.load32(source);
				for (var i = 0; i < count; ++i) {
					this.cpu.mmu.store32(dest + (i << 2), word);
				}
			} else {
				var word = this.cpu.mmu.load16(source);
				for (var i = 0; i < count; ++i) {
					this.cpu.mmu.store16(dest + (i << 1), word);
				}
			}
		} else {
			if (wordsize == 4) {
				for (var i = 0; i < count; ++i) {
					var word = this.cpu.mmu.load32(source + (i << 2));
					this.cpu.mmu.store32(dest + (i << 2), word);
				}
			} else {
				var i = 0;
				var word;
				if (source & 0x00000002) {
					word = this.cpu.mmu.load16(source);
					this.cpu.mmu.store16(dest, word);
					++i;
				}
				for (; i + 1 < count; i += 2) {
					word = this.cpu.mmu.load32(source + (i << 1));
					this.cpu.mmu.store32(dest + (i << 1), word);
				}
				if (i < count) {
					word = this.cpu.mmu.load16(source + (i << 1));
					this.cpu.mmu.store16(dest + (i << 1), word);
				}
			}
		}
		return;
	case 0x0C:
		// FastCpuSet
		var source = this.cpu.gprs[0];
		var dest = this.cpu.gprs[1];
		var mode = this.cpu.gprs[2];
		var count = mode & 0x000FFFFF;
		var fill = mode & 0x01000000;
		if (fill) {
			var word = this.cpu.mmu.load32(source);
			for (var i = 0; i < count; ++i) {
				this.cpu.mmu.store32(dest + (i << 2), word);
			}
		} else {
			for (var i = 0; i < count; ++i) {
				var word = this.cpu.mmu.load32(source + (i << 2));
				this.cpu.mmu.store32(dest + (i << 2), word);
			}
		}
		return;
	default:
		throw "Unimplemented software interrupt: 0x" + opcode.toString(16);
	}
};

GameBoyAdvanceInterruptHandler.prototype.masterEnable = function(value) {
	this.enable = value;

	if (this.enable) {
		// FIXME: raise remaining IRQs
		this.poll();
	}
};

GameBoyAdvanceInterruptHandler.prototype.setInterruptsEnabled = function(value) {
	this.enabledIRQs = value;

	if (this.enabledIRQs & this.MASK_TIMER0 || this.enabledIRQs & this.MASK_TIMER1 || this.enabledIRQs & this.MASK_TIMER2 || this.enabledIRQs & this.MASK_TIMER3) {
		this.cpu.log('Timing interrupts not implemented');
	}

	if (this.enabledIRQs & this.MASK_SIO) {
		this.cpu.log('Serial I/O interrupts not implemented');
	}

	if (this.enabledIRQs & this.MASK_DMA0 || this.enabledIRQs & this.MASK_DMA1 || this.enabledIRQs & this.MASK_DMA2 || this.enabledIRQs & this.MASK_DMA3) {
		this.cpu.log('DMA interrupts not implemented');
	}

	if (this.enabledIRQs & this.MASK_KEYPAD) {
		this.cpu.log('Keypad interrupts not implemented');
	}

	if (this.enabledIRQs & this.MASK_GAMEPAK) {
		this.cpu.log('Gamepak interrupts not implemented');
	}

	if (this.enable) {
		// FIXME: raise remaining IRQs
		this.poll();
	}
};

GameBoyAdvanceInterruptHandler.prototype.poll = function() {
	this.nextInterrupt = 0; // Clear pending interrupt timer--it'll be reset anyway.
	if (this.enabledIRQs & this.MASK_HBLANK && this.video.hblankIRQ) {
		var next = this.video.nextHblank();
		if (next && (next < this.nextInterrupt || !this.nextInterrupt)) {
			this.nextInterrupt = next;
		}
	}
	if (this.enabledIRQs & this.MASK_VBLANK && this.video.vblankIRQ) {
		var next = this.video.nextVblank();
		if (next && (next < this.nextInterrupt || !this.nextInterrupt)) {
			this.nextInterrupt = next;
		}
	}
	if (this.enabledIRQs & this.MASK_VCOUNTER && this.video.vcounterIRQ) {
		var next = this.video.nextVcounter();
		if (next && (next < this.nextInterrupt || !this.nextInterrupt)) {
			this.nextInterrupt = next;
		}
	}
};

GameBoyAdvanceInterruptHandler.prototype.raiseIRQ = function(irqType) {
	this.interruptFlags |= 1 << irqType;
	this.cpu.mmu.io.registers[this.cpu.mmu.io.IF >> 1] = this.interruptFlags;

	if (this.enable && this.enabledIRQs & this.interruptFlags) {
		this.cpu.raiseIRQ();
	}
};

GameBoyAdvanceInterruptHandler.prototype.dismissIRQs = function(irqMask) {
	this.interruptFlags &= ~irqMask;
	this.cpu.mmu.io.registers[this.cpu.mmu.io.IF >> 1] = this.interruptFlags;
};

GameBoyAdvanceInterruptHandler.prototype.dmaSetSourceAddress = function(dma, address) {
	this.dma[dma].source = address & 0xFFFFFFFE;
};

GameBoyAdvanceInterruptHandler.prototype.dmaSetDestAddress = function(dma, address) {
	this.dma[dma].dest = address & 0xFFFFFFFE;
};

GameBoyAdvanceInterruptHandler.prototype.dmaSetWordCount = function(dma, count) {
	this.dma[dma].count = count ? count : (dma == 3 ? 0x10000 : 0x4000);
};

GameBoyAdvanceInterruptHandler.prototype.dmaWriteControl = function(dma, control) {
	var currentDma = this.dma[dma];
	currentDma.dstControl = (control & 0x0060) >> 5;
	currentDma.srcControl = (control & 0x0180) >> 7;
	currentDma.repeat = control & 0x0200;
	currentDma.width = control & 0x0400;
	currentDma.drq = control & 0x0800;
	currentDma.timing = control & 0x3000;
	currentDma.doIrq = control & 0x4000;
	currentDma.enable = control & 0x8000;

	if (currentDma.repeat) {
		this.cpu.log('DMA repeat not implemented');
	}
	if (currentDma.drq) {
		this.cpu.log('DRQ not implemented');
	}
	if (currentDma.timing) {
		this.cpu.log('DMA start timing other than immediate not implemented');
	}
	if (currentDma.doIrq) {
		this.cpu.log('DMA IRQ not implemented');
	}

	if (!currentDma.timing && currentDma.enable) {
		this.cpu.mmu.serviceDma(dma, currentDma);
	}
};

GameBoyAdvanceInterruptHandler.prototype.timerSetReload = function(timer, reload) {
	this.timers[timer].reload = reload;
};

GameBoyAdvanceInterruptHandler.prototype.timerWriteControl = function(timer, control) {
	var currentTimer = this.timers[timer];
	switch (control & 0x0003) {
	case 0x0000:
		currentTimer.prescale = this.FREQUENCY;
		break;
	case 0x0001:
		currentTimer.prescale = this.FREQUENCY / 64;
		break;
	case 0x0002:
		currentTimer.prescale = this.FREQUENCY / 256;
		break;
	case 0x0003:
		currentTimer.prescale = this.FREQUENCY / 1024;
		break;
	}
	currentTimer.countUp = control & 0x0004;
	currentTimer.doIrq = control & 0x0040;
	var wasEnabled = currentTimer.enable;
	currentTimer.enable = ((control & 0x0080) >> 7) << timer;
	this.timersEnabled = (this.timersEnabled & ~(1 << timer)) | currentTimer.enable;
	if (!wasEnabled && currentTimer.enable) {
		currentTimer.lastEvent = this.cpu.cycles;
		currentTimer.nextEvent = this.cpu.cycles + currentTimer.prescale;
		this.cpu.mmu.io.registers[this.cpu.mmu.io.TM0CNT_LO + (timer << 2)] = currentTimer.reload;
	}

	if (currentTimer.countUp) {
		this.cpu.log('Timer count up not implemented');
	}
	if (currentTimer.doIrq) {
		this.cpu.log('Timer IRQ not implemented');
	}
};
<commit_msg>Raise pending IRQs when enabling them<commit_after>"use strict";

var GameBoyAdvanceInterruptHandler = function() {
	this.FREQUENCY = 16780000;

	this.cpu = null;
	this.enable = false;

	this.IRQ_VBLANK = 0x0;
	this.IRQ_HBLANK = 0x1;
	this.IRQ_VCOUNTER = 0x2;
	this.IRQ_TIMER0 = 0x3;
	this.IRQ_TIMER1 = 0x4;
	this.IRQ_TIMER2 = 0x5;
	this.IRQ_TIMER3 = 0x6;
	this.IRQ_SIO = 0x7;
	this.IRQ_DMA0 = 0x8;
	this.IRQ_DMA1 = 0x9;
	this.IRQ_DMA2 = 0xA;
	this.IRQ_DMA3 = 0xB;
	this.IRQ_KEYPAD = 0xC;
	this.IRQ_GAMEPAK = 0xD;

	this.MASK_VBLANK = 0x0001;
	this.MASK_HBLANK = 0x0002;
	this.MASK_VCOUNTER = 0x0004;
	this.MASK_TIMER0 = 0x0008;
	this.MASK_TIMER1 = 0x0010;
	this.MASK_TIMER2 = 0x0020;
	this.MASK_TIMER3 = 0x0040;
	this.MASK_SIO = 0x0080;
	this.MASK_DMA0 = 0x0100;
	this.MASK_DMA1 = 0x0200;
	this.MASK_DMA2 = 0x0400;
	this.MASK_DMA3 = 0x0800;
	this.MASK_KEYPAD = 0x1000;
	this.MASK_GAMEPAK = 0x2000;

	this.enabledIRQs = 0;
	this.interruptFlags = 0;

	this.dma = new Array();
	for (var i = 0; i < 4; ++i) {
		this.dma.push({
			source: 0,
			dest: 0,
			count: 0,
			srcControl: 0,
			dstControl: 0,
			repeat: 0,
			width: 0,
			drq: 0,
			timing: 0,
			doIrq: 0,
			enable: 0
		});
	}

	this.timersEnabled = 0;
	this.timers = new Array();
	for (var i = 0; i < 4; ++i) {
		this.timers.push({
			reload: 0,
			prescale: 0,
			countUp: 0,
			doIrq: 0,
			enable: 0,
			lastEvent: 0
		});
	}

	this.nextInterrupt = 0;
};

GameBoyAdvanceInterruptHandler.prototype.setCPU = function(cpu) {
	this.cpu = cpu;
}

GameBoyAdvanceInterruptHandler.prototype.setVideo = function(video) {
	this.video = video;
}

GameBoyAdvanceInterruptHandler.prototype.updateTimers = function() {
	this.video.updateTimers(this.cpu);
	if (this.timersEnabled) {
		// TODO: add timer IRQs
		// TODO: check for overflow
		if (this.timersEnabled & 0x1) {
			var timer = this.timers[0];
			if (this.cpu.cycles >= timer.nextEvent) {
				timer.lastEvent = timer.nextEvent;
				timer.nextEvent += timer.prescale;
				++this.cpu.mmu.io.registers[this.cpu.mmu.io.TM0CNT_LO];
			}
		}
		if (this.timersEnabled & 0x2) {
			var timer = this.timers[1];
			if (this.cpu.cycles >= timer.nextEvent) {
				timer.lastEvent = timer.nextEvent;
				timer.nextEvent += timer.prescale;
				++this.cpu.mmu.io.registers[this.cpu.mmu.io.TM1CNT_LO];
			}
		}
		if (this.timersEnabled & 0x4) {
			var timer = this.timers[2];
			if (this.cpu.cycles >= timer.nextEvent) {
				timer.lastEvent = timer.nextEvent;
				timer.nextEvent += timer.prescale;
				++this.cpu.mmu.io.registers[this.cpu.mmu.io.TM2CNT_LO];
			}
		}
		if (this.timersEnabled & 0x8) {
			var timer = this.timers[3];
			if (this.cpu.cycles >= timer.nextEvent) {
				timer.lastEvent = timer.nextEvent;
				timer.nextEvent += timer.prescale;
				++this.cpu.mmu.io.registers[this.cpu.mmu.io.TM3CNT_LO];
			}
		}
	}
}

GameBoyAdvanceInterruptHandler.prototype.swi = function(opcode) {
	switch (opcode) {
	case 0x02:
		// Halt
		if (!this.enable) {
			throw "Requested HALT when interrupts were disabled!";
		}
		this.poll();
		if (this.nextInterrupt >= this.cpu.cycles) {
			this.cpu.cycles = this.nextInterrupt;
		} else {
			throw "Waiting on interrupt forever.";
		}
		break;
	case 0x0B:
		// CpuSet
		var source = this.cpu.gprs[0];
		var dest = this.cpu.gprs[1];
		var mode = this.cpu.gprs[2];
		var count = mode & 0x000FFFFF;
		var fill = mode & 0x01000000;
		var wordsize = (mode & 0x04000000) ? 4 : 2;
		if (fill) {
			if (wordsize == 4) {
				var word = this.cpu.mmu.load32(source);
				for (var i = 0; i < count; ++i) {
					this.cpu.mmu.store32(dest + (i << 2), word);
				}
			} else {
				var word = this.cpu.mmu.load16(source);
				for (var i = 0; i < count; ++i) {
					this.cpu.mmu.store16(dest + (i << 1), word);
				}
			}
		} else {
			if (wordsize == 4) {
				for (var i = 0; i < count; ++i) {
					var word = this.cpu.mmu.load32(source + (i << 2));
					this.cpu.mmu.store32(dest + (i << 2), word);
				}
			} else {
				var i = 0;
				var word;
				if (source & 0x00000002) {
					word = this.cpu.mmu.load16(source);
					this.cpu.mmu.store16(dest, word);
					++i;
				}
				for (; i + 1 < count; i += 2) {
					word = this.cpu.mmu.load32(source + (i << 1));
					this.cpu.mmu.store32(dest + (i << 1), word);
				}
				if (i < count) {
					word = this.cpu.mmu.load16(source + (i << 1));
					this.cpu.mmu.store16(dest + (i << 1), word);
				}
			}
		}
		return;
	case 0x0C:
		// FastCpuSet
		var source = this.cpu.gprs[0];
		var dest = this.cpu.gprs[1];
		var mode = this.cpu.gprs[2];
		var count = mode & 0x000FFFFF;
		var fill = mode & 0x01000000;
		if (fill) {
			var word = this.cpu.mmu.load32(source);
			for (var i = 0; i < count; ++i) {
				this.cpu.mmu.store32(dest + (i << 2), word);
			}
		} else {
			for (var i = 0; i < count; ++i) {
				var word = this.cpu.mmu.load32(source + (i << 2));
				this.cpu.mmu.store32(dest + (i << 2), word);
			}
		}
		return;
	default:
		throw "Unimplemented software interrupt: 0x" + opcode.toString(16);
	}
};

GameBoyAdvanceInterruptHandler.prototype.masterEnable = function(value) {
	this.enable = value;

	if (this.enable) {
		this.poll();

		if (this.enabledIRQs && this.interruptFlags) {
			this.cpu.raiseIRQ();
		}
	}
};

GameBoyAdvanceInterruptHandler.prototype.setInterruptsEnabled = function(value) {
	this.enabledIRQs = value;

	if (this.enabledIRQs & this.MASK_TIMER0 || this.enabledIRQs & this.MASK_TIMER1 || this.enabledIRQs & this.MASK_TIMER2 || this.enabledIRQs & this.MASK_TIMER3) {
		this.cpu.log('Timing interrupts not implemented');
	}

	if (this.enabledIRQs & this.MASK_SIO) {
		this.cpu.log('Serial I/O interrupts not implemented');
	}

	if (this.enabledIRQs & this.MASK_DMA0 || this.enabledIRQs & this.MASK_DMA1 || this.enabledIRQs & this.MASK_DMA2 || this.enabledIRQs & this.MASK_DMA3) {
		this.cpu.log('DMA interrupts not implemented');
	}

	if (this.enabledIRQs & this.MASK_KEYPAD) {
		this.cpu.log('Keypad interrupts not implemented');
	}

	if (this.enabledIRQs & this.MASK_GAMEPAK) {
		this.cpu.log('Gamepak interrupts not implemented');
	}

	if (this.enable) {
		this.poll();

		if (this.enabledIRQs && this.interruptFlags) {
			this.cpu.raiseIRQ();
		}
	}
};

GameBoyAdvanceInterruptHandler.prototype.poll = function() {
	this.nextInterrupt = 0; // Clear pending interrupt timer--it'll be reset anyway.
	if (this.enabledIRQs & this.MASK_HBLANK && this.video.hblankIRQ) {
		var next = this.video.nextHblank();
		if (next && (next < this.nextInterrupt || !this.nextInterrupt)) {
			this.nextInterrupt = next;
		}
	}
	if (this.enabledIRQs & this.MASK_VBLANK && this.video.vblankIRQ) {
		var next = this.video.nextVblank();
		if (next && (next < this.nextInterrupt || !this.nextInterrupt)) {
			this.nextInterrupt = next;
		}
	}
	if (this.enabledIRQs & this.MASK_VCOUNTER && this.video.vcounterIRQ) {
		var next = this.video.nextVcounter();
		if (next && (next < this.nextInterrupt || !this.nextInterrupt)) {
			this.nextInterrupt = next;
		}
	}
};

GameBoyAdvanceInterruptHandler.prototype.raiseIRQ = function(irqType) {
	this.interruptFlags |= 1 << irqType;
	this.cpu.mmu.io.registers[this.cpu.mmu.io.IF >> 1] = this.interruptFlags;

	if (this.enable && this.enabledIRQs & this.interruptFlags) {
		this.cpu.raiseIRQ();
	}
};

GameBoyAdvanceInterruptHandler.prototype.dismissIRQs = function(irqMask) {
	this.interruptFlags &= ~irqMask;
	this.cpu.mmu.io.registers[this.cpu.mmu.io.IF >> 1] = this.interruptFlags;
};

GameBoyAdvanceInterruptHandler.prototype.dmaSetSourceAddress = function(dma, address) {
	this.dma[dma].source = address & 0xFFFFFFFE;
};

GameBoyAdvanceInterruptHandler.prototype.dmaSetDestAddress = function(dma, address) {
	this.dma[dma].dest = address & 0xFFFFFFFE;
};

GameBoyAdvanceInterruptHandler.prototype.dmaSetWordCount = function(dma, count) {
	this.dma[dma].count = count ? count : (dma == 3 ? 0x10000 : 0x4000);
};

GameBoyAdvanceInterruptHandler.prototype.dmaWriteControl = function(dma, control) {
	var currentDma = this.dma[dma];
	currentDma.dstControl = (control & 0x0060) >> 5;
	currentDma.srcControl = (control & 0x0180) >> 7;
	currentDma.repeat = control & 0x0200;
	currentDma.width = control & 0x0400;
	currentDma.drq = control & 0x0800;
	currentDma.timing = control & 0x3000;
	currentDma.doIrq = control & 0x4000;
	currentDma.enable = control & 0x8000;

	if (currentDma.repeat) {
		this.cpu.log('DMA repeat not implemented');
	}
	if (currentDma.drq) {
		this.cpu.log('DRQ not implemented');
	}
	if (currentDma.timing) {
		this.cpu.log('DMA start timing other than immediate not implemented');
	}
	if (currentDma.doIrq) {
		this.cpu.log('DMA IRQ not implemented');
	}

	if (!currentDma.timing && currentDma.enable) {
		this.cpu.mmu.serviceDma(dma, currentDma);
	}
};

GameBoyAdvanceInterruptHandler.prototype.timerSetReload = function(timer, reload) {
	this.timers[timer].reload = reload;
};

GameBoyAdvanceInterruptHandler.prototype.timerWriteControl = function(timer, control) {
	var currentTimer = this.timers[timer];
	switch (control & 0x0003) {
	case 0x0000:
		currentTimer.prescale = this.FREQUENCY;
		break;
	case 0x0001:
		currentTimer.prescale = this.FREQUENCY / 64;
		break;
	case 0x0002:
		currentTimer.prescale = this.FREQUENCY / 256;
		break;
	case 0x0003:
		currentTimer.prescale = this.FREQUENCY / 1024;
		break;
	}
	currentTimer.countUp = control & 0x0004;
	currentTimer.doIrq = control & 0x0040;
	var wasEnabled = currentTimer.enable;
	currentTimer.enable = ((control & 0x0080) >> 7) << timer;
	this.timersEnabled = (this.timersEnabled & ~(1 << timer)) | currentTimer.enable;
	if (!wasEnabled && currentTimer.enable) {
		currentTimer.lastEvent = this.cpu.cycles;
		currentTimer.nextEvent = this.cpu.cycles + currentTimer.prescale;
		this.cpu.mmu.io.registers[this.cpu.mmu.io.TM0CNT_LO + (timer << 2)] = currentTimer.reload;
	}

	if (currentTimer.countUp) {
		this.cpu.log('Timer count up not implemented');
	}
	if (currentTimer.doIrq) {
		this.cpu.log('Timer IRQ not implemented');
	}
};
<|endoftext|>


<commit_before>

var tableData = function () {
    var that = {};
    var _editTableData = function (item) {
        $.ajax({
            url: "/api/editTableData",
            type: "post",
            data: item,
            success: function (res) {
                console.log(res);
            },
            error: function (err, xhr) {
                console.log(err);
            }
        });
    };
    var _insertTableData = function (item) {
        $.ajax({
            url: "/api/insertTableData",
            type: "post",
            data: item,
            success: function (res) {
                console.log(res);
            },
            error: function (err, xhr) {
                console.log(err);
            }
        });
    };
    var _deleteTableData = function (item) {
        $.ajax({
            url: "/api/deleteTableData",
            type: "post",
            data: item,

            success: function (res) {
                console.log(res);
            },
            error: function (err, xhr) {
                console.log(err);
            }
        });
    };
    var _getTableField = function (data) {
        //debugger;
        var schemaConst = function () {
            return { name: "", type: "text", width: 150, validate: "required" };
        };

        var sampleRow = data[0];
        var schema = {};
        var fieldsArray = [];
        for (var fieldName in sampleRow) {
            schema = new schemaConst();
            schema.name = fieldName;
            if (schema.name == "_id") { delete schema.validate; schema.visible = false; }
            fieldsArray.push(schema)
        }
        fieldsArray.push({ type: "control" });
        return fieldsArray;
    };
    var _loadTable = function () {
        $.ajax({
            url: "/api/tabledata",
            type: "get",
            success: function (result) {
                $("#jsGrid").jsGrid({
                    height: "70%",
                    width: "100%",
                    filtering: true,
                    inserting: true,
                    editing: true,
                    sorting: true,
                    paging: true,
                    autoload: true,
                    pageSize: 10,
                    pageButtonCount: 5,
                    deleteConfirm: "Do you really want to delete this record?",
                    data: result,
                    fields: _getTableField(result),
                    onItemInserted: function (args) {
                        //debugger;
                        // cancel insertion of the item with empty 'name' field
                        if (args.item.name === "") {
                            args.cancel = true;
                            alert("Specify the name of the item!");
                        }
                        _insertTableData(args.item);
                    },
                    onItemUpdating: function (args) {
                        //debugger;
                        // cancel update of the item with empty 'name' field
                        if (args.item.name === "") {
                            args.cancel = true;
                            alert("Specify the name of the item!");
                        }
                        _editTableData(args.item);
                    },
                    onItemDeleted: function (args) {
                        //debugger;
                        // cancel insertion of the item with empty 'name' field
                        if (args.item.name === "") {
                            args.cancel = true;
                            alert("Specify the name of the item!");
                        }
                        _deleteTableData(args.item);
                    }/*,
                    fields: [
                        { name: "TDate", type: "date", width: 50, title: "Date" },
                        { name: "TV", type: "number", width: 50, filtering: false },
                        { name: "Radio", type: "number", width: 50 },
                        { name: "Newspaper", type: "number", width: 50 },
                        { name: "Sales", type: "number", width: 50 }
                    ]*/
                });
            },
            error: function (err, xhr) { }
        });
    };
    var _loadMixModelConsoleData = function () {
        $.ajax({
            url: "/api/modeldata",
            type: "GET",
            success: function (res) {
                //debugger;
                /* Printing summary data */
                $("#mix-model-summary-console tr td[data-attr-data-name]").each(function (index, ele) {
                    var attrName = $(ele).attr("data-attr-data-name");
                    var attrValue = res[0].summary[0].head[attrName];
                    if (attrValue) {
                        if ($(ele).attr("data-value") == "date") {
                            attrValue = new Date(attrValue);
                            attrValue = attrValue.toDateString();
                        } else if ($(ele).attr("data-value") == "time") {
                            attrValue = new Date(attrValue);
                            attrValue = attrValue.toGMTString().split(attrValue.getFullYear())[1].replace(" ", "");
                        }
                        $(ele).html(attrValue);
                    }
                });
                /*End printing summary data*/
                /*Priting Diagn data*/
                $("#mix-model-diagn-console tr td[data-attr-data-name]").each(function (index, ele) {
                    var attrName = $(ele).attr("data-attr-data-name");
                    var attrValue = res[0].summary[2].diagn[attrName];
                    if (attrValue) {
                        if ($(ele).attr("data-value") == "date") {
                            attrValue = new Date(attrValue);
                            attrValue = attrValue.toDateString();
                        } else if ($(ele).attr("data-value") == "time") {
                            attrValue = new Date(attrValue);
                            attrValue = attrValue.toGMTString().split(attrValue.getFullYear())[1].replace(" ", "");
                        }
                        $(ele).html(attrValue);
                    }
                });

            },
            error: function (err, xhr) {
                console.log("error on _loadMixModelConsoleData");
            }
        });
    };
    var _init = function (param) {
        _loadTable();
        _loadMixModelConsoleData();
    }
    that.init = _init;
    return that;
};
var objTableData = new tableData();
objTableData.init();
<commit_msg>Fixed Model data structure issue<commit_after>

var tableData = function () {
    var that = {};
    var _editTableData = function (item) {
        $.ajax({
            url: "/api/editTableData",
            type: "post",
            data: item,
            success: function (res) {
                console.log(res);
            },
            error: function (err, xhr) {
                console.log(err);
            }
        });
    };
    var _insertTableData = function (item) {
        $.ajax({
            url: "/api/insertTableData",
            type: "post",
            data: item,
            success: function (res) {
                console.log(res);
            },
            error: function (err, xhr) {
                console.log(err);
            }
        });
    };
    var _deleteTableData = function (item) {
        $.ajax({
            url: "/api/deleteTableData",
            type: "post",
            data: item,

            success: function (res) {
                console.log(res);
            },
            error: function (err, xhr) {
                console.log(err);
            }
        });
    };
    var _getTableField = function (data) {
        //debugger;
        var schemaConst = function () {
            return { name: "", type: "text", width: 150, validate: "required" };
        };

        var sampleRow = data[0];
        var schema = {};
        var fieldsArray = [];
        for (var fieldName in sampleRow) {
            schema = new schemaConst();
            schema.name = fieldName;
            if (schema.name == "_id") { delete schema.validate; schema.visible = false; }
            fieldsArray.push(schema)
        }
        fieldsArray.push({ type: "control" });
        return fieldsArray;
    };
    var _loadTable = function () {
        $.ajax({
            url: "/api/tabledata",
            type: "get",
            success: function (result) {
                $("#jsGrid").jsGrid({
                    height: "70%",
                    width: "100%",
                    filtering: true,
                    inserting: true,
                    editing: true,
                    sorting: true,
                    paging: true,
                    autoload: true,
                    pageSize: 10,
                    pageButtonCount: 5,
                    deleteConfirm: "Do you really want to delete this record?",
                    data: result,
                    fields: _getTableField(result),
                    onItemInserted: function (args) {
                        //debugger;
                        // cancel insertion of the item with empty 'name' field
                        if (args.item.name === "") {
                            args.cancel = true;
                            alert("Specify the name of the item!");
                        }
                        _insertTableData(args.item);
                    },
                    onItemUpdating: function (args) {
                        //debugger;
                        // cancel update of the item with empty 'name' field
                        if (args.item.name === "") {
                            args.cancel = true;
                            alert("Specify the name of the item!");
                        }
                        _editTableData(args.item);
                    },
                    onItemDeleted: function (args) {
                        //debugger;
                        // cancel insertion of the item with empty 'name' field
                        if (args.item.name === "") {
                            args.cancel = true;
                            alert("Specify the name of the item!");
                        }
                        _deleteTableData(args.item);
                    }/*,
                    fields: [
                        { name: "TDate", type: "date", width: 50, title: "Date" },
                        { name: "TV", type: "number", width: 50, filtering: false },
                        { name: "Radio", type: "number", width: 50 },
                        { name: "Newspaper", type: "number", width: 50 },
                        { name: "Sales", type: "number", width: 50 }
                    ]*/
                });
            },
            error: function (err, xhr) { }
        });
    };
    var _loadMixModelConsoleData = function () {
        $.ajax({
            url: "/api/modeldata",
            type: "GET",
            success: function (res) {
                //debugger;
                /* Printing summary data */
                $("#mix-model-summary-console tr td[data-attr-data-name]").each(function (index, ele) {
                    var attrName = $(ele).attr("data-attr-data-name");
                    var attrValue = res[0].summary.head[attrName];
                    if (attrValue) {
                        if ($(ele).attr("data-value") == "date") {
                            attrValue = new Date(attrValue);
                            attrValue = attrValue.toDateString();
                        } else if ($(ele).attr("data-value") == "time") {
                            attrValue = new Date(attrValue);
                            attrValue = attrValue.toGMTString().split(attrValue.getFullYear())[1].replace(" ", "");
                        }
                        $(ele).html(attrValue);
                    }
                });
                /*End printing summary data*/
                /*Priting Diagn data*/
                $("#mix-model-diagn-console tr td[data-attr-data-name]").each(function (index, ele) {
                    var attrName = $(ele).attr("data-attr-data-name");
                    var attrValue = res[0].summary[2].diagn[attrName];
                    if (attrValue) {
                        if ($(ele).attr("data-value") == "date") {
                            attrValue = new Date(attrValue);
                            attrValue = attrValue.toDateString();
                        } else if ($(ele).attr("data-value") == "time") {
                            attrValue = new Date(attrValue);
                            attrValue = attrValue.toGMTString().split(attrValue.getFullYear())[1].replace(" ", "");
                        }
                        $(ele).html(attrValue);
                    }
                });

            },
            error: function (err, xhr) {
                console.log("error on _loadMixModelConsoleData");
            }
        });
    };
    var _init = function (param) {
        _loadTable();
        _loadMixModelConsoleData();
    }
    that.init = _init;
    return that;
};
var objTableData = new tableData();
objTableData.init();
<|endoftext|>


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

var util            = require('util'),
    filePersistence = require('./file'),
    jive = require('../api');

var persistenceListener = null;

function setListener( listener ) {
    if ( !listener ) {
        throw 'Cannot register an empty persistence listener.';
    }
    persistenceListener = listener;
}

function lazyInit() {
    if ( !persistenceListener ) {
        var persistence = jive.config.fetch()['persistence'];
        setListener( persistence || new filePersistence() );
    }
}

//////////////////////////////////////////////////////////////
// public
//////////////////////////////////////////////////////////////

exports.save = function (collectionID, key, data, callback) {
    lazyInit();
    persistenceListener.save(collectionID, key, data, callback);
};

exports.find = function (collectionID, keyValues, callback) {
    lazyInit();
    persistenceListener.find(collectionID, keyValues, callback);
};

exports.remove = function (collectionID, key, callback) {
    lazyInit();
    persistenceListener.remove(collectionID, key, callback);
};

exports.setListener = setListener;

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

var jive = require('../api');

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Private

var persistenceListener = null;

/**
 * Interrogates configuration for a persistence strategy; if one is not found,
 * set file persistence by default.
 */
function lazyInit() {
    if ( !persistenceListener ) {
        persistenceListener = jive.config.fetch()['persistence'] || new jive.persistence.file();
    }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Public

/**
 * Save data under a key within a named collection, and invoke callback when its done.
 * @param collectionID
 * @param key
 * @param data
 * @param callback
 */
exports.save = function (collectionID, key, data, callback) {
    lazyInit();
    persistenceListener.save(collectionID, key, data, callback);
};

/**
 * Look up a record from within a named collection using key-value pair criteria, and return
 * the resulting array when its done.
 * @param collectionID String
 * @param criteria A JSON key-value structure, eg. { "style": "LIST", "name" : "samplelist" }
 * @param callback Expects a parameter called results eg. function( results ) {..}
 */
exports.find = function (collectionID, criteria, callback) {
    lazyInit();
    persistenceListener.find(collectionID, criteria, callback);
};

/**
 * Remove a record by key from a named collection, and invoke the callback when done.
 * @param collectionID string
 * @param key String
 * @param callback expects no arguments
 */
exports.remove = function (collectionID, key, callback) {
    lazyInit();
    persistenceListener.remove(collectionID, key, callback);
};
<|endoftext|>


<commit_before>/*
 * This is a third-party library module, originally built by the lovely folks at Eris Ltd.
 * SOURCE: https://github.com/eris-ltd/hello-eris/blob/master/js/libs/eris-wrapper.js
 */

var binstring = require('binstring');
var erisC = require('eris-contracts');
var EventEmitter = require('events');
var util = require('util');
var logger = require(__libs+'/eris/eris-logger');

(function () {

    var log = logger.getLogger('eris.wrapper');

    // EventEmitter
    function ErisEvents() {
        EventEmitter.call(this);
    }

    util.inherits(ErisEvents, EventEmitter);

    /*
     Constructor for a Wrapper instance to talk to a specific chain
     */
    function ErisWrapper(host, port, account) {

        //TODO find a better way to easily test
        account = account || require('../../test/chain-config/accounts.json')[__settings.eris.chain.devAccount];

        var self = this;
        self.erisdbURL = 'http://'+host+':'+port+'/rpc';
        self.contractManager = erisC.newContractManagerDev(self.erisdbURL, account);
        self.listen = new ErisEvents();
    }

    ErisWrapper.prototype.events = {}; //TODO to be defined, e.g. contract added event

    ErisWrapper.prototype.createContract = function(abi, address, jsonOutput) {

        //TODO check inputs, check existing contract at name

        if(log.isDebugEnabled()) {
            log.debug('Creating contract factory with ABI '+abi+' at address '+address+'.');
        }
        // instantiate the contract objects using the abi and address
        var contract;
        if(address) {
            contract = this.contractManager.newContractFactory(abi).at(address);
        } else {
            contract = this.contractManager.newContractFactory(abi);
        }
        // Turn on JSON output for bundle contracts
        if(jsonOutput) {
            contract.setOutputFormatter(erisC.outputFormatters.jsonStrings);
        }
        return contract;
    };

    /*
     Wraps the given callback and executes the 'convert' function on the result,
     if there is one, before invoking the callback(error, result).
     */
    var convertibleCallback = function(callback, convert) {
        return function(err, res) {
            callback(err, (res && convert) ? convert(res) : res);
        };
    };

    /* Converts given string to hex */
    var str2hex = function (str) {
        return binstring(str, { in:'binary', out:'hex' });
    };

    /* Converts given hex to string and removes trailing null character */
    var hex2str = function (hexx) {
        return String(Buffer(hexx, 'hex')).replace(/\0/g, '');
    };

    module.exports = {
        'NewWrapper': ErisWrapper,
        'convertibleCallback': convertibleCallback,
        'str2hex': str2hex,
        'hex2str': hex2str
    };

}());
<commit_msg>Stringify the ABI JSON for debug output<commit_after>/*
 * This is a third-party library module, originally built by the lovely folks at Eris Ltd.
 * SOURCE: https://github.com/eris-ltd/hello-eris/blob/master/js/libs/eris-wrapper.js
 */

var binstring = require('binstring');
var erisC = require('eris-contracts');
var EventEmitter = require('events');
var util = require('util');
var logger = require(__libs+'/eris/eris-logger');

(function () {

    var log = logger.getLogger('eris.wrapper');

    // EventEmitter
    function ErisEvents() {
        EventEmitter.call(this);
    }

    util.inherits(ErisEvents, EventEmitter);

    /*
     Constructor for a Wrapper instance to talk to a specific chain
     */
    function ErisWrapper(host, port, account) {

        //TODO find a better way to easily test
        account = account || require('../../test/chain-config/accounts.json')[__settings.eris.chain.devAccount];

        var self = this;
        self.erisdbURL = 'http://'+host+':'+port+'/rpc';
        self.contractManager = erisC.newContractManagerDev(self.erisdbURL, account);
        self.listen = new ErisEvents();
    }

    ErisWrapper.prototype.events = {}; //TODO to be defined, e.g. contract added event

    ErisWrapper.prototype.createContract = function(abi, address, jsonOutput) {

        //TODO check inputs, check existing contract at name

        if(log.isDebugEnabled()) {
            log.debug('Creating contract factory with ABI '+ JSON.stringify(abi) +' at address '+ address +'.');
        }
        // instantiate the contract objects using the abi and address
        var contract;
        if(address) {
            contract = this.contractManager.newContractFactory(abi).at(address);
        } else {
            contract = this.contractManager.newContractFactory(abi);
        }
        // Turn on JSON output for bundle contracts
        if(jsonOutput) {
            contract.setOutputFormatter(erisC.outputFormatters.jsonStrings);
        }
        return contract;
    };

    /*
     Wraps the given callback and executes the 'convert' function on the result,
     if there is one, before invoking the callback(error, result).
     */
    var convertibleCallback = function(callback, convert) {
        return function(err, res) {
            callback(err, (res && convert) ? convert(res) : res);
        };
    };

    /* Converts given string to hex */
    var str2hex = function (str) {
        return binstring(str, { in:'binary', out:'hex' });
    };

    /* Converts given hex to string and removes trailing null character */
    var hex2str = function (hexx) {
        return String(Buffer(hexx, 'hex')).replace(/\0/g, '');
    };

    module.exports = {
        'NewWrapper': ErisWrapper,
        'convertibleCallback': convertibleCallback,
        'str2hex': str2hex,
        'hex2str': hex2str
    };

}());
<|endoftext|>


<commit_before>/* eslint-env mocha */
/* global expect, testContext */
/* eslint-disable prefer-arrow-callback, no-unused-expressions */
import r from '../../../db/connect'
import {withDBCleanup, useFixture} from '../../../test/helpers'

import saveSurveyResponse from '../saveSurveyResponse'

describe(testContext(__filename), function () {
  withDBCleanup()

  useFixture.buildOneQuestionSurvey()

  describe('team relativeContribution questions (like RPC)', function () {
    beforeEach(async function () {
      await this.buildOneQuestionSurvey({
        questionAttrs: {subjectType: 'team', responseType: 'relativeContribution'},
        subjectIds: () => this.teamPlayerIds
      })
      this.currentUserId = this.teamPlayerIds[0]
    })

    it('saves the responses with the right attributes', async function () {
      await saveSurveyResponse({
        respondentId: this.currentUserId,
        questionId: this.question.id,
        surveyId: this.survey.id,
        subjectIds: this.teamPlayerIds,
        values: this.teamPlayerIds.map(subjectId => ({subjectId, value: 25})),
      })

      const responses = await r.table('responses').run()
      expect(responses.map(({subjectId}) => subjectId).sort())
        .to.deep.equal(this.teamPlayerIds.sort())
      responses.forEach(response => {
        expect(response).to.have.property('surveyId', this.survey.id)
        expect(response).to.have.property('questionId', this.question.id)
        expect(response).to.have.property('respondentId', this.currentUserId)
        expect(response).to.have.property('value', 25)
      })
    })

    it('validates the correct number of responses are given', function () {
      return expect(
        saveSurveyResponse({
          respondentId: this.currentUserId,
          questionId: this.question.id,
          surveyId: this.survey.id,
          subjectIds: this.teamPlayerIds,
          values: [{subjectId: this.teamPlayerIds[0], value: 100}],
        })
      ).to.be.rejectedWith('Matching QuestionRef Not Found')
    })

    it('validates percentages add up to 100', function () {
      return expect(
       saveSurveyResponse({
         respondentId: this.currentUserId,
         questionId: this.question.id,
         surveyId: this.survey.id,
         subjectIds: this.teamPlayerIds,
         values: this.teamPlayerIds.map(subjectId => ({subjectId, value: 50})),
       })
      ).to.be.rejectedWith('Percentages must add up to 100%')
    })
  })

  describe('text responseType', function () {
    beforeEach(async function () {
      await this.buildOneQuestionSurvey({
        questionAttrs: {subjectType: 'player', responseType: 'text'},
        subjectIds: () => [this.teamPlayerIds[1]]
      })
      this.currentUserId = this.teamPlayerIds[0]
    })

    it('saves the responses with the right attributes', async function () {
      await saveSurveyResponse({
        respondentId: this.currentUserId,
        questionId: this.question.id,
        surveyId: this.survey.id,
        subjectIds: [this.teamPlayerIds[1]],
        values: [{subjectId: this.teamPlayerIds[1], value: 'Judy is Awesome!'}],
      })

      const responses = await r.table('responses').run()
      expect(responses.length).to.eq(1)
      expect(responses[0]).to.have.property('surveyId', this.survey.id)
      expect(responses[0]).to.have.property('questionId', this.question.id)
      expect(responses[0]).to.have.property('respondentId', this.currentUserId)
      expect(responses[0]).to.have.property('value', 'Judy is Awesome!')
      expect(responses[0].subjectId).to.eq(this.teamPlayerIds[1])
    })
  })

  describe('likert7Agreement responseType', function () {
    beforeEach(async function () {
      await this.buildOneQuestionSurvey({
        questionAttrs: {subjectType: 'player', responseType: 'likert7Agreement'},
        subjectIds: () => [this.teamPlayerIds[1]]
      })
      this.currentUserId = this.teamPlayerIds[0]
    })

    it('saves the responses with the right attributes', async function () {
      await saveSurveyResponse({
        respondentId: this.currentUserId,
        questionId: this.question.id,
        surveyId: this.survey.id,
        subjectIds: [this.teamPlayerIds[1]],
        values: [{subjectId: this.teamPlayerIds[1], value: '6'}],
      })

      const responses = await r.table('responses').run()
      expect(responses.length).to.eq(1)
      expect(responses[0]).to.have.property('surveyId', this.survey.id)
      expect(responses[0]).to.have.property('questionId', this.question.id)
      expect(responses[0]).to.have.property('respondentId', this.currentUserId)
      expect(responses[0]).to.have.property('value', 6)
      expect(responses[0].subjectId).to.eq(this.teamPlayerIds[1])
    })
  })

  describe('single subject relativeContribution questions', function () {
    beforeEach(async function () {
      await this.buildOneQuestionSurvey({
        questionAttrs: {subjectType: 'player', responseType: 'relativeContribution'},
        subjectIds: () => [this.teamPlayerIds[1]]
      })
      this.currentUserId = this.teamPlayerIds[0]
    })

    it('saves the responses with the right attributes', async function () {
      await saveSurveyResponse({
        respondentId: this.currentUserId,
        questionId: this.question.id,
        surveyId: this.survey.id,
        subjectIds: [this.teamPlayerIds[1]],
        values: [{subjectId: this.teamPlayerIds[1], value: '99'}],
      })

      const responses = await r.table('responses').run()
      expect(responses.length).to.eq(1)
      expect(responses[0]).to.have.property('surveyId', this.survey.id)
      expect(responses[0]).to.have.property('questionId', this.question.id)
      expect(responses[0]).to.have.property('respondentId', this.currentUserId)
      expect(responses[0]).to.have.property('value', 99)
      expect(responses[0].subjectId).to.eq(this.teamPlayerIds[1])
    })

    it('validates percentages are not bigger than 100', function () {
      return expect(
        saveSurveyResponse({
          respondentId: this.currentUserId,
          questionId: this.question.id,
          surveyId: this.survey.id,
          subjectIds: [this.teamPlayerIds[1]],
          values: [{subjectId: this.teamPlayerIds[1], value: '110'}],
        })
      ).to.be.rejectedWith('must be less than or equal to 100')
    })
  })
})
<commit_msg>removing deprecated subjectIds param. Improving test description.<commit_after>/* eslint-env mocha */
/* global expect, testContext */
/* eslint-disable prefer-arrow-callback, no-unused-expressions */
import r from '../../../db/connect'
import {withDBCleanup, useFixture} from '../../../test/helpers'

import saveSurveyResponse from '../saveSurveyResponse'

describe(testContext(__filename), function () {
  withDBCleanup()

  useFixture.buildOneQuestionSurvey()

  describe('team relativeContribution questions (like RPC)', function () {
    beforeEach(async function () {
      await this.buildOneQuestionSurvey({
        questionAttrs: {subjectType: 'team', responseType: 'relativeContribution'},
        subjectIds: () => this.teamPlayerIds
      })
      this.currentUserId = this.teamPlayerIds[0]
    })

    it('saves the responses with the right attributes', async function () {
      await saveSurveyResponse({
        respondentId: this.currentUserId,
        questionId: this.question.id,
        surveyId: this.survey.id,
        values: this.teamPlayerIds.map(subjectId => ({subjectId, value: 25})),
      })

      const responses = await r.table('responses').run()
      expect(responses.map(({subjectId}) => subjectId).sort())
        .to.deep.equal(this.teamPlayerIds.sort())
      responses.forEach(response => {
        expect(response).to.have.property('surveyId', this.survey.id)
        expect(response).to.have.property('questionId', this.question.id)
        expect(response).to.have.property('respondentId', this.currentUserId)
        expect(response).to.have.property('value', 25)
      })
    })

    it('validates that the subjectIds + questionId given match a questionRef in the survey', function () {
      const valuesWithOneSubjectMissing = this.teamPlayerIds
        .slice(1)
        .map(subjectId => ({subjectId, value: 25}))

      return expect(
        saveSurveyResponse({
          respondentId: this.currentUserId,
          questionId: this.question.id,
          surveyId: this.survey.id,
          values: valuesWithOneSubjectMissing,
        })
      ).to.be.rejectedWith('Matching QuestionRef Not Found')
    })

    it('validates percentages add up to 100', function () {
      return expect(
       saveSurveyResponse({
         respondentId: this.currentUserId,
         questionId: this.question.id,
         surveyId: this.survey.id,
         values: this.teamPlayerIds.map(subjectId => ({subjectId, value: 50})),
       })
      ).to.be.rejectedWith('Percentages must add up to 100%')
    })
  })

  describe('text responseType', function () {
    beforeEach(async function () {
      await this.buildOneQuestionSurvey({
        questionAttrs: {subjectType: 'player', responseType: 'text'},
        subjectIds: () => [this.teamPlayerIds[1]]
      })
      this.currentUserId = this.teamPlayerIds[0]
    })

    it('saves the responses with the right attributes', async function () {
      await saveSurveyResponse({
        respondentId: this.currentUserId,
        questionId: this.question.id,
        surveyId: this.survey.id,
        values: [{subjectId: this.teamPlayerIds[1], value: 'Judy is Awesome!'}],
      })

      const responses = await r.table('responses').run()
      expect(responses.length).to.eq(1)
      expect(responses[0]).to.have.property('surveyId', this.survey.id)
      expect(responses[0]).to.have.property('questionId', this.question.id)
      expect(responses[0]).to.have.property('respondentId', this.currentUserId)
      expect(responses[0]).to.have.property('value', 'Judy is Awesome!')
      expect(responses[0].subjectId).to.eq(this.teamPlayerIds[1])
    })
  })

  describe('likert7Agreement responseType', function () {
    beforeEach(async function () {
      await this.buildOneQuestionSurvey({
        questionAttrs: {subjectType: 'player', responseType: 'likert7Agreement'},
        subjectIds: () => [this.teamPlayerIds[1]]
      })
      this.currentUserId = this.teamPlayerIds[0]
    })

    it('saves the responses with the right attributes', async function () {
      await saveSurveyResponse({
        respondentId: this.currentUserId,
        questionId: this.question.id,
        surveyId: this.survey.id,
        values: [{subjectId: this.teamPlayerIds[1], value: '6'}],
      })

      const responses = await r.table('responses').run()
      expect(responses.length).to.eq(1)
      expect(responses[0]).to.have.property('surveyId', this.survey.id)
      expect(responses[0]).to.have.property('questionId', this.question.id)
      expect(responses[0]).to.have.property('respondentId', this.currentUserId)
      expect(responses[0]).to.have.property('value', 6)
      expect(responses[0].subjectId).to.eq(this.teamPlayerIds[1])
    })
  })

  describe('single subject relativeContribution questions', function () {
    beforeEach(async function () {
      await this.buildOneQuestionSurvey({
        questionAttrs: {subjectType: 'player', responseType: 'relativeContribution'},
        subjectIds: () => [this.teamPlayerIds[1]]
      })
      this.currentUserId = this.teamPlayerIds[0]
    })

    it('saves the responses with the right attributes', async function () {
      await saveSurveyResponse({
        respondentId: this.currentUserId,
        questionId: this.question.id,
        surveyId: this.survey.id,
        values: [{subjectId: this.teamPlayerIds[1], value: '99'}],
      })

      const responses = await r.table('responses').run()
      expect(responses.length).to.eq(1)
      expect(responses[0]).to.have.property('surveyId', this.survey.id)
      expect(responses[0]).to.have.property('questionId', this.question.id)
      expect(responses[0]).to.have.property('respondentId', this.currentUserId)
      expect(responses[0]).to.have.property('value', 99)
      expect(responses[0].subjectId).to.eq(this.teamPlayerIds[1])
    })

    it('validates percentages are not bigger than 100', function () {
      return expect(
        saveSurveyResponse({
          respondentId: this.currentUserId,
          questionId: this.question.id,
          surveyId: this.survey.id,
          values: [{subjectId: this.teamPlayerIds[1], value: '110'}],
        })
      ).to.be.rejectedWith('must be less than or equal to 100')
    })
  })
})
<|endoftext|>


<commit_before>var User = require('../../../src/js/models/user.js');

describe("User Model", function() {
	it("should be created", function(){
		var options = {id: 1, email: 'foo@bar.com', token: 'tokenfoo'};
		var user = new User(options);
		expect(user.id).toBe(options.id);
		expect(user.email).toBe(options.email);
		expect(user.token).toBe(options.token);
		expect(user.isAuthenticated()).toBeTruthy();
	});
	it("is not authenticated without a token", function() {
		var options = {id: 1, email: 'foo@bar.com'};
		var user = new User(options);
		expect(user.isAuthenticated()).toBeFalsy();
		user.setToken("tokenbar");
		expect(user.token).toBe("tokenbar");
		expect(user.isAuthenticated()).toBeTruthy();
	});
	it("toString()", function() {
		var options = {id: 1, email: 'foo@bar.com', token: 'tokenfoo'};
		var user = new User(options);
		expect(user.toString()).toBe(user.email);
		expect(String(user)).toBe(user.email);
		expect("" + user).toBe(user.email);
	});
	it("toJSON()", function() {
		var options = {id: 1, email: 'foo@bar.com', token: 'tokenfoo'};
		var expected_json = {
			"type": "user",
			"data": {
				"id": options.id,
				"email": options.email
			}
		};
		var user = new User(options);
		expect(user.toJSON()).toEqual(expected_json);
	});
});
<commit_msg>Updated tests.<commit_after>var User = require('../../../src/js/models/user.js');

describe("User Model", function() {
	it("should be created", function(){
		var options = {id: 1, email: 'foo@bar.com', token: 'tokenfoo'};
		var user = new User(options);
		expect(user.id).toBe(options.id);
		expect(user.email).toBe(options.email);
		expect(user.token).toBe(options.token);
		expect(user.isAuthenticated()).toBeTruthy();
	});
	it("is not authenticated without a token", function() {
		var options = {id: 1, email: 'foo@bar.com'};
		var user = new User(options);
		expect(user.isAuthenticated()).toBeFalsy();
		user.update({token:"tokenbar"});
		expect(user.token).toBe("tokenbar");
		expect(user.isAuthenticated()).toBeTruthy();
	});
	it("should be updated", function() {
		var data = { id: 123, email: 'foofoo@barbar.com', token: 'abc123' };
		var user = new User();
		spyOn(user, 'triggerChange');
		expect(user.id).toBeFalsy();
		expect(user.email).toBeFalsy();
		expect(user.token).toBeFalsy();
		expect(user.triggerChange).not.toHaveBeenCalled();

		user.update(data);
		expect(user.id).toBe(data.id);
		expect(user.email).toBe(data.email);
		expect(user.token).toBe(data.token);
		expect(user.triggerChange).toHaveBeenCalled();
	});
	it("toString()", function() {
		var options = {id: 1, email: 'foo@bar.com', token: 'tokenfoo'};
		var user = new User(options);
		expect(user.toString()).toBe(user.email);
		expect(String(user)).toBe(user.email);
		expect("" + user).toBe(user.email);
	});
	it("toJSON()", function() {
		var options = {id: 1, email: 'foo@bar.com', token: 'tokenfoo'};
		var expected_json = {
			"type": "user",
			"data": {
				"id": options.id,
				"email": options.email
			}
		};
		var user = new User(options);
		expect(user.toJSON()).toEqual(expected_json);
	});
});
<|endoftext|>