<commit_before>// Dependencies
var Barbe = require("barbe")
  , Fs = require("fs")
  , Path = require("path")
  , MarkDox = require("markdox")
  , IsThere = require("is-there")
  , ReadJson = require("r-json")
  , WriteJson = require("w-json")
  , ParentSearch = require("parent-search")
  , Streamp = require("streamp")
  , Ul = require("ul")
  , SameTime = require("same-time")
  , OneByOne = require("one-by-one")
  , Deffy = require("deffy")
  , Ejs = require("ejs")
  , Ncp = require("ncp")
  ;

// Constants
const BLAH_DIR = ".blah"
    , BLAH_TEMPLATES = ".blah-templates"
    , TEMPLATES = "templates"
    , PACKAGE_JSON = "package.json"
    , DOCUMENTATION_NAME = "DOCUMENTATION.md"
    , DOCUMENTATION_TMPL = "docs.ejs"
    , CONTRIBUTING_TMPL = "CONTRIBUTING.ejs"
    , CONTRIBUTING_NAME = "CONTRIBUTING.md"
    , README_TMPL = "README.ejs"
    , README_NAME = "README.md"
    , LICENSE_NAME = "LICENSE"
    , GITIGNORE = ".gitignore"
    ;

/**
 * Blah
 * Creates a new `Blah` instance.
 *
 * @name Blah
 * @function
 * @param {String} path The Blah working directory (default: `process.cwd()`).
 */
function Blah(path) {

    // Blah working directory
    this.path = Deffy(path, process.cwd());

    // .blah/
    this.blah_dir = Path.join(this.path, BLAH_DIR);

    // ~/.blah-templates
    this.usr_templates = Path.join(Ul.home(), BLAH_TEMPLATES);

    // templates/
    this.lib_templates = Path.join(__dirname, TEMPLATES);

    this.templates = {};
    this.pack = {};
    this.paths = {};
}

/**
 * search
 * Searches a file in the blah directories.
 *
 * @name search
 * @function
 * @param {String} file The relative path to a file to search in the templates
 * directories (in the following order: local `.blah` directory,
 * `~/.blah-templates`, library templates).
 * @param {Function} callback The callback function.
 */
Blah.prototype.search = function (file, callback) {

    if (typeof file === "function") {
        callback = file;
        file = "";
    }

    var self = this
      , tries = [

            // Local .blah/file
            Path.join(self.blah_dir, file)

            // Templates: ~/.blah-templates/file
          , Path.join(self.usr_templates, file)

            // Library templates: templates/file
          , Path.join(self.lib_templates, file)
        ]
      ;

    SameTime(tries.map(function (cPath) {
        return function (cb) {
            IsThere(cPath, function (exists) {
                cb(null, cPath, exists);
            });
        }
    }), function (err, fields, exists) {
        if (err) { return callback(err); }
        for (var i = 0; i < exists.length; ++i) {
            if (exists[i]) {
                return callback(null, fields[i]);
            }
        }
        callback(new Error("Cannot find searched file: " + file));
    });
};

/**
 * prepare
 * Prepares the Blah data.
 *
 * @name prepare
 * @function
 * @param {Function} callback The callback function.
 */
Blah.prototype.prepare = function (callback) {
    var self = this;

    // Find the paths
    //OneByOne([
    //    function (cb) {

    //    }
    //], function (err, data) {

    //});
    SameTime([
        self.search.bind(self, DOCUMENTATION_TMPL)
      , self.search.bind(self, README_TMPL)
      , self.search.bind(self, GITIGNORE)
      , self.search.bind(self, CONTRIBUTING_TMPL)
      , function (cb) {
            ParentSearch(self.path, PACKAGE_JSON, cb.bind(this));
        }
    ], function (err, data) {
        if (err) { return callback(err); }

        self.paths.markdox = data[0];
        self.paths.readme = data[1];
        self.paths.gitignore = data[2];
        self.paths.contributing = data[3];
        self.paths.pack = data[4];

        // Read the template data
        SameTime([
            function (cb) {
                if (!self.paths.pack) {
                    return cb(null, {});
                }
                ReadJson(self.paths.pack, function (err, pack) {
                    pack = Deffy(pack, {});
                    cb(null, pack);
                });
            }
        ], function (err, data) {
            if (err) { return callback(err); }
            self.pack = data[0];
            self.pack.blah = Deffy(self.pack.blah, {});
            self.copyright = {
                fullname: self.pack.author
              , year: new Date().getFullYear()
              , project: self.pack.name
              , description: self.pack.description
            };
            callback();
        });
    });
};

/**
 * init
 * Inits the `.blah` directory in the current project.
 *
 * @name init
 * @function
 * @param {Function} callback The callback function.
 */
Blah.prototype.init = function (callback) {
    var self = this;
    self.prepare(function (err) {
        if (err) { return callback(err); }
        self.search(function (err, path_templates) {
            if (err) { return callback(err); }
            if (path_templates === self.blah_dir) {
                return callback(new Error("Refusing to override existing templates."));
            }
            Ncp(path_templates, self.blah_dir, callback);
        });
    });
};

/**
 * docs
 * Generates the DOCUMENTATION.md file, parsing the input files.
 *
 * @name docs
 * @function
 * @param {String} input Input file name (default: main file from package.json)
 * @param {String} output Output file name (default: `DOCUMENTATION.md`)
 * @param {Boolean} writeFile If `false`, the docs will be returned via the
 * callback function, without writing the output file.
 * @param {Function} callback The callback function.
 */
Blah.prototype.docs = function (input, output, writeFile, callback) {
    var self = this;

    if (typeof writeFile === "function") {
        callback = writeFile;
        writeFile = true;
    }

    if (typeof output === "function") {
        callback = output;
        output = Path.join(self.path, DOCUMENTATION_NAME);
    } else if (typeof output === "boolean") {
        output = null;
        writeFile = true;
    }

    writeFile = Deffy(writeFile, true);

    OneByOne([
        self.prepare.bind(self)
      , function (next) {
            IsThere(input, next.bind(this, null))
        }
      , function (next, exists) {
            if (!exists) {
                if (writeFile) {
                    return next(new Error("The input file does not exist."));
                }
                return next(null, "");
            }
            MarkDox.process(input, {
                template: self.paths.markdox
            }, next);
        }
      , function (next, content) {
            content = content.split("\n").map(function (c) {
                return c.trimRight();
            }).join("\n");
            if (writeFile) {
                Fs.writeFile(output, content, next);
            } else {
                next(null, content);
            }
        }
    ], function (err, result) {
        if (err) { return callback(err); }
        callback(null, result.slice(-1)[0]);
    });
};

/**
 * readme
 * Creates the `README.md` file.
 *
 * @name readme
 * @function
 * @param {Function} callback The callback function
 */
Blah.prototype.readme = function (callback) {

    var self = this;

    OneByOne([
        self.prepare.bind(self)
      , function (next) {
            self.docs(self.pack.main, false, next);
        }
      , function (next, docs) {
            self.render(self.paths.readme, {
                docs: docs
            }, next);
        }
      , function (err, content) {
            Fs.writeFile(
                Path.join(self.path, README_NAME)
              , content.replace(/^\s+|\s+$/g, "").replace(/\n{3,}/g, "\n\n")
              , callback
            );
        }
    ], callback);
};

/**
 * gitignore
 * Creates the `.gitignore` file.
 *
 * @name gitignore
 * @function
 * @param {Function} callback The callback function.
 */
Blah.prototype.gitignore = function (callback) {
    var self = this;
    self.prepare(function (err) {
        if (err) { return callback(err); }
        Ncp(self.paths.gitignore, Path.join(self.path, GITIGNORE), callback);
    });
};

/**
 * license
 * Creates the `LICENSE` file.
 *
 * @name license
 * @function
 * @param {String} license The license name.
 * @param {Function} callback The callback function.
 */
Blah.prototype.license = function (license, callback) {
    var self = this;
    self.prepare(function (err) {
        if (err) { return callback(err); }
        var licensePath = Path.join(__dirname, "/licenses/", license.toLowerCase() + ".txt");
        if (!IsThere(licensePath)) {
            return callback(new Error("There is no license named " + license));
        }
        if (!self.copyright.fullname) {
            return callback(new Error("Cannot find the author name. Is the package.json file missing?"));
        }
        Fs.readFile(licensePath, "utf-8", function (err, content) {
            if (err) { return callback(err); }
            content = Barbe(content, ["[", "]"], self.copyright);
            Fs.writeFile(Path.join(self.path, "LICENSE"), content, callback);
        });
    });
};

/**
 * render
 * Renders a template from file.
 *
 * @name render
 * @function
 * @param {String} path The template path.
 * @param {Object} data Additional data to merge into the template data.
 * @param {Function} callback The callback function.
 */
Blah.prototype.render = function (path, data, callback) {
    var self = this;

    if (typeof data === "function") {
        callback = data;
        data = {};
    }

    Ejs.renderFile(path, Ul.merge({
        _: self
      , require: require
    }, data), callback);
};

/**
 * contributing
 * Generates the `CONTRIBUTING.md` file.
 *
 * @name contributing
 * @function
 * @param {Function} callback The callback function.
 */
Blah.prototype.contributing = function (callback) {
    var self = this;
    self.prepare(function (err) {
        if (err) { return callback(err); }
        self.render(self.paths.contributing, function (err, content) {
            if (err) { return callback(err); }
            Fs.writeFile(
                Path.join(self.path, CONTRIBUTING_NAME)
              , content.replace(/^\s+|\s+$/g, "").replace(/\n{3,}/g, "\n\n")
              , callback
            );
        });
    });
};

/**
 * version
 * Bumps the provided version.
 *
 * @name version
 * @function
 * @param {String} what The version which should be bumped. It takes one of the following values: `"major"`, `"minor"`, `"patch"`. The default is `"patch"`.
 * @param {Function} callback The callback function.
 */
Blah.prototype.version = function (what, callback) {
    var self = this;

    if (typeof what === "function") {
        callback = what;
        what = "patch";
    }

    if (!/^major|minor|patch$/.test(what)) {
        return callback(new Error("Invalid version: " + what));
    }

    self.prepare(function (err) {
        if (err) { return callback(err); }
        var version = self.pack.version;
        if (!version) {
            return callback(new Error("Cannot find the version in the package.json file."));
        }

        version = self.pack.version.split(".").map(function (x) {
            return parseInt(x, 10);
        });

        switch (what) {
            case "major":
                ++version[0];
                version[1] = 0;
                version[2] = 0;
                break;
            case "minor":
                ++version[1];
                version[2] = 0;
                break;
            case "patch":
                ++version[2];
                break;
                break;
        }

        self.pack.version = version.join(".");
        if (!Object.keys(self.pack.blah).length) {
            delete self.pack.blah;
        }

        WriteJson(self.paths.pack, self.pack, callback);
    });
};

module.exports = Blah;
<commit_msg>Only initialize one instance once<commit_after>// Dependencies
var Barbe = require("barbe")
  , Fs = require("fs")
  , Path = require("path")
  , MarkDox = require("markdox")
  , IsThere = require("is-there")
  , ReadJson = require("r-json")
  , WriteJson = require("w-json")
  , ParentSearch = require("parent-search")
  , Streamp = require("streamp")
  , Ul = require("ul")
  , SameTime = require("same-time")
  , OneByOne = require("one-by-one")
  , Deffy = require("deffy")
  , Ejs = require("ejs")
  , Ncp = require("ncp")
  ;

// Constants
const BLAH_DIR = ".blah"
    , BLAH_TEMPLATES = ".blah-templates"
    , TEMPLATES = "templates"
    , PACKAGE_JSON = "package.json"
    , DOCUMENTATION_NAME = "DOCUMENTATION.md"
    , DOCUMENTATION_TMPL = "docs.ejs"
    , CONTRIBUTING_TMPL = "CONTRIBUTING.ejs"
    , CONTRIBUTING_NAME = "CONTRIBUTING.md"
    , README_TMPL = "README.ejs"
    , README_NAME = "README.md"
    , LICENSE_NAME = "LICENSE"
    , GITIGNORE = ".gitignore"
    ;

/**
 * Blah
 * Creates a new `Blah` instance.
 *
 * @name Blah
 * @function
 * @param {String} path The Blah working directory (default: `process.cwd()`).
 */
function Blah(path) {

    // Blah working directory
    this.path = Deffy(path, process.cwd());

    // .blah/
    this.blah_dir = Path.join(this.path, BLAH_DIR);

    // ~/.blah-templates
    this.usr_templates = Path.join(Ul.home(), BLAH_TEMPLATES);

    // templates/
    this.lib_templates = Path.join(__dirname, TEMPLATES);

    this.templates = {};
    this.pack = {};
    this.paths = {};
}

/**
 * search
 * Searches a file in the blah directories.
 *
 * @name search
 * @function
 * @param {String} file The relative path to a file to search in the templates
 * directories (in the following order: local `.blah` directory,
 * `~/.blah-templates`, library templates).
 * @param {Function} callback The callback function.
 */
Blah.prototype.search = function (file, callback) {

    if (typeof file === "function") {
        callback = file;
        file = "";
    }

    var self = this
      , tries = [

            // Local .blah/file
            Path.join(self.blah_dir, file)

            // Templates: ~/.blah-templates/file
          , Path.join(self.usr_templates, file)

            // Library templates: templates/file
          , Path.join(self.lib_templates, file)
        ]
      ;

    SameTime(tries.map(function (cPath) {
        return function (cb) {
            IsThere(cPath, function (exists) {
                cb(null, cPath, exists);
            });
        }
    }), function (err, fields, exists) {
        if (err) { return callback(err); }
        for (var i = 0; i < exists.length; ++i) {
            if (exists[i]) {
                return callback(null, fields[i]);
            }
        }
        callback(new Error("Cannot find searched file: " + file));
    });
};

/**
 * prepare
 * Prepares the Blah data.
 *
 * @name prepare
 * @function
 * @param {Function} callback The callback function.
 */
Blah.prototype.prepare = function (callback) {
    var self = this;

    if (self.initialized) {
        return callback();
    }

    OneByOne([
        SameTime.bind(this, [
            self.search.bind(self, DOCUMENTATION_TMPL)
          , self.search.bind(self, README_TMPL)
          , self.search.bind(self, GITIGNORE)
          , self.search.bind(self, CONTRIBUTING_TMPL)
          , function (cb) {
                ParentSearch(self.path, PACKAGE_JSON, cb);
            }
        ])
      , function (next, data) {
            self.paths.markdox = data[0];
            self.paths.readme = data[1];
            self.paths.gitignore = data[2];
            self.paths.contributing = data[3];
            self.paths.pack = data[4];
            next();
        }
      , function (next) {
            if (!self.paths.pack) {
                return next(null, {});
            }
            ReadJson(self.paths.pack, function (err, pack) {
                pack = Deffy(pack, {});
                next(null, pack);
            });
        }
      , function (next, pack) {
            self.pack = pack;
            self.pack.blah = Deffy(self.pack.blah, {});
            self.copyright = {
                fullname: self.pack.author
              , year: new Date().getFullYear()
              , project: self.pack.name
              , description: self.pack.description
            };
            next();
        }
    ], function (err, data) {
        self.initialized = true;
        callback(err, data);
    });
};

/**
 * init
 * Inits the `.blah` directory in the current project.
 *
 * @name init
 * @function
 * @param {Function} callback The callback function.
 */
Blah.prototype.init = function (callback) {
    var self = this;
    self.prepare(function (err) {
        if (err) { return callback(err); }
        self.search(function (err, path_templates) {
            if (err) { return callback(err); }
            if (path_templates === self.blah_dir) {
                return callback(new Error("Refusing to override existing templates."));
            }
            Ncp(path_templates, self.blah_dir, callback);
        });
    });
};

/**
 * docs
 * Generates the DOCUMENTATION.md file, parsing the input files.
 *
 * @name docs
 * @function
 * @param {String} input Input file name (default: main file from package.json)
 * @param {String} output Output file name (default: `DOCUMENTATION.md`)
 * @param {Boolean} writeFile If `false`, the docs will be returned via the
 * callback function, without writing the output file.
 * @param {Function} callback The callback function.
 */
Blah.prototype.docs = function (input, output, writeFile, callback) {
    var self = this;

    if (typeof writeFile === "function") {
        callback = writeFile;
        writeFile = true;
    }

    if (typeof output === "function") {
        callback = output;
        output = Path.join(self.path, DOCUMENTATION_NAME);
    } else if (typeof output === "boolean") {
        writeFile = output;
        output = null;
    }

    writeFile = Deffy(writeFile, true);

    OneByOne([
        self.prepare.bind(self)
      , function (next) {
            IsThere(input, next.bind(this, null))
        }
      , function (next, exists) {
            if (!exists) {
                if (writeFile) {
                    return next(new Error("The input file does not exist."));
                }
                return next(null, "");
            }
            MarkDox.process(input, {
                template: self.paths.markdox
            }, next);
        }
      , function (next, content) {
            content = content.split("\n").map(function (c) {
                return c.trimRight();
            }).join("\n");
            if (writeFile) {
                Fs.writeFile(output, content, next);
            } else {
                next(null, content);
            }
        }
    ], function (err, result) {
        if (err) { return callback(err); }
        callback(null, result.slice(-1)[0]);
    });
};

/**
 * readme
 * Creates the `README.md` file.
 *
 * @name readme
 * @function
 * @param {Function} callback The callback function
 */
Blah.prototype.readme = function (callback) {

    var self = this;

    OneByOne([
        self.prepare.bind(self)
      , function (next) {
            self.docs(self.pack.main, false, next);
        }
      , function (next, docs) {
            self.render(self.paths.readme, {
                docs: docs
            }, next);
        }
      , function (err, content) {
            Fs.writeFile(
                Path.join(self.path, README_NAME)
              , content.replace(/^\s+|\s+$/g, "").replace(/\n{3,}/g, "\n\n")
              , callback
            );
        }
    ], callback);
};

/**
 * gitignore
 * Creates the `.gitignore` file.
 *
 * @name gitignore
 * @function
 * @param {Function} callback The callback function.
 */
Blah.prototype.gitignore = function (callback) {
    var self = this;
    self.prepare(function (err) {
        if (err) { return callback(err); }
        Ncp(self.paths.gitignore, Path.join(self.path, GITIGNORE), callback);
    });
};

/**
 * license
 * Creates the `LICENSE` file.
 *
 * @name license
 * @function
 * @param {String} license The license name.
 * @param {Function} callback The callback function.
 */
Blah.prototype.license = function (license, callback) {
    var self = this;
    self.prepare(function (err) {
        if (err) { return callback(err); }
        var licensePath = Path.join(__dirname, "/licenses/", license.toLowerCase() + ".txt");
        if (!IsThere(licensePath)) {
            return callback(new Error("There is no license named " + license));
        }
        if (!self.copyright.fullname) {
            return callback(new Error("Cannot find the author name. Is the package.json file missing?"));
        }
        Fs.readFile(licensePath, "utf-8", function (err, content) {
            if (err) { return callback(err); }
            content = Barbe(content, ["[", "]"], self.copyright);
            Fs.writeFile(Path.join(self.path, "LICENSE"), content, callback);
        });
    });
};

/**
 * render
 * Renders a template from file.
 *
 * @name render
 * @function
 * @param {String} path The template path.
 * @param {Object} data Additional data to merge into the template data.
 * @param {Function} callback The callback function.
 */
Blah.prototype.render = function (path, data, callback) {
    var self = this;

    if (typeof data === "function") {
        callback = data;
        data = {};
    }

    Ejs.renderFile(path, Ul.merge({
        _: self
      , require: require
    }, data), callback);
};

/**
 * contributing
 * Generates the `CONTRIBUTING.md` file.
 *
 * @name contributing
 * @function
 * @param {Function} callback The callback function.
 */
Blah.prototype.contributing = function (callback) {
    var self = this;
    self.prepare(function (err) {
        if (err) { return callback(err); }
        self.render(self.paths.contributing, function (err, content) {
            if (err) { return callback(err); }
            Fs.writeFile(
                Path.join(self.path, CONTRIBUTING_NAME)
              , content.replace(/^\s+|\s+$/g, "").replace(/\n{3,}/g, "\n\n")
              , callback
            );
        });
    });
};

/**
 * version
 * Bumps the provided version.
 *
 * @name version
 * @function
 * @param {String} what The version which should be bumped. It takes one of the following values: `"major"`, `"minor"`, `"patch"`. The default is `"patch"`.
 * @param {Function} callback The callback function.
 */
Blah.prototype.version = function (what, callback) {
    var self = this;

    if (typeof what === "function") {
        callback = what;
        what = "patch";
    }

    if (!/^major|minor|patch$/.test(what)) {
        return callback(new Error("Invalid version: " + what));
    }

    self.prepare(function (err) {
        if (err) { return callback(err); }
        var version = self.pack.version;
        if (!version) {
            return callback(new Error("Cannot find the version in the package.json file."));
        }

        version = self.pack.version.split(".").map(function (x) {
            return parseInt(x, 10);
        });

        switch (what) {
            case "major":
                ++version[0];
                version[1] = 0;
                version[2] = 0;
                break;
            case "minor":
                ++version[1];
                version[2] = 0;
                break;
            case "patch":
                ++version[2];
                break;
                break;
        }

        self.pack.version = version.join(".");
        if (!Object.keys(self.pack.blah).length) {
            delete self.pack.blah;
        }

        WriteJson(self.paths.pack, self.pack, callback);
    });
};

module.exports = Blah;
<|endoftext|>


<commit_before>import React from 'react';
import TextField from 'material-ui/lib/text-field';

export default class ZipCodeEntry extends React.Component {
  constructor(props) {
    super(props);
    this.handleEnter = this.handleEnter.bind(this);
  }

  render() {
    return (
      <TextField
        floatingLabelText="Enter a zip code"
        onEnterKeyDown={this.handleEnter}
      />
    );
  }

  handleEnter(event) {
    this.props.newZip(event.target.value);
    event.target.value = '';
  }
}
<commit_msg>Clear value the "right" way with material-ui<commit_after>import React from 'react';
import TextField from 'material-ui/lib/text-field';

export default class ZipCodeEntry extends React.Component {
  constructor(props) {
    super(props);
    this.handleEnter = this.handleEnter.bind(this);
  }

  render() {
    return (
      <TextField
        ref="textField"
        floatingLabelText="Enter a zip code"
        onEnterKeyDown={this.handleEnter}
      />
    );
  }

  handleEnter(event) {
    this.props.newZip(event.target.value);
    this.refs.textField.clearValue();
  }
}
<|endoftext|>


<commit_before>(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // AMD is used - Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        factory(require('jquery'));
    } else {
        // Neither AMD nor CommonJS used. Use global variables.
        if (typeof jQuery === 'undefined') {
            throw 'Gonrin Ref requires jQuery to be loaded first';
        }
        factory(jQuery);
    }
}(function ($) {
	'use strict';
	var GonrinRef = function (element, options) {

		var gonrin = {},
		value,
		text,
		data, //datalist
		dataBound = false,
		textElement = false,
		unset = true,
        input,
        menuTemplate = '

',
        itemTemplate =  '

',
        component = false,
        widget = false,  //dialogView
        keyMap = {
                'up': 38,
                38: 'up',
                'down': 40,
                40: 'down',
                'left': 37,
                37: 'left',
                'right': 39,
                39: 'right',
                'tab': 9,
                9: 'tab',
                'escape': 27,
                27: 'escape',
                'enter': 13,
                13: 'enter',
                //'pageUp': 33,
                //33: 'pageUp',
                //'pageDown': 34,
                //34: 'pageDown',
                //'shift': 16,
                //16: 'shift',
                //'control': 17,
                //17: 'control',
                'space': 32,
                32: 'space',
                //'t': 84,
                //84: 't',
                'delete': 46,
                46: 'delete'
        },
        keyState = {},

        /********************************************************************************
        *
        * Private functions
        *
        ********************************************************************************/
        setupWidget = function () {
			if ((!!options.dataSource) && (typeof options.dataSource === "string")) {

				require([ options.dataSource ], function ( RefView ) {
					widget = new RefView({selectionMode: options.selectionMode});
					options.textField = options.textField || widget.textField;
					options.valueField = options.valueField || widget.valueField;

					if(!!input.val()){
						if(widget.selectionMode === "single"){
							var value = input.val();
			            	var model = widget.model || null;
			            	if(model){
			            		model.set(options.valueField, value);
								model.fetch({
				                    success: function (data) {
				                    	textElement.text(model.get(options.textField));
				                    },
				                    error:function(){},
								});
			            	}
						}
						if(widget.selectionMode === "multiple"){
							var value = $.parseJSON(input.val());
			            	//var model = widget.model || null;

			            	if(value){
			            		$.each(value, function(key, item){
			            			var txt = item[options.textField];
			            			console.log(txt);
			            			$(itemTemplate).html(txt).appendTo(textElement.find("ul"));
			            		})

			            	}
						}

		            }

		    	});
			};

			//show dialog

			return gonrin;
		},
		show = function () {
        	if (input.prop('disabled') || (!options.ignoreReadonly && input.prop('readonly'))) {
                return gonrin;
            };
            if(widget){
            	widget.dialog({
            		success: function(){
            			if((!!widget)&&(!!widget.selectedItems)&&(widget.selectedItems.length > 0)){
            				var seleted = widget.selectedItems;
            				if(widget.selectionMode === "single"){
            					textElement.text(seleted[0][options.textField]);
                				input.val(seleted[0][options.valueField]);
                				input.trigger('change.gonrin');
            				}
            				if(widget.selectionMode === "multiple"){
            					//textElement.html(JSON.stringify(seleted));
            					textElement.find("ul").empty();
    			            	$.each(seleted, function(key, item){
    			            		var txt = item[options.textField];
    			            		$(itemTemplate).html(txt).appendTo(textElement.find("ul"));
    			            	});
    			            	input.val(JSON.stringify(seleted));
    			            	input.trigger('change.gonrin');
            				}
            			}
            		}
            	})
            }
            /*notifyEvent({
                type: 'show.gonui'
            });*/
            return gonrin;
        },
        hide = function(){
            return gonrin;
        },

        toggle = function () {
            /// Shows or hides the widget
            //return (widget.is(':hidden') ? show() : hide());
        	return show();
        },
		attachElementEvents = function () {
            /*input.on({
                'change': change,
                'blur': options.debug ? '' : hide,
                'keydown': keydown,
                'keyup': keyup,
                'focus': options.allowInputToggle ? show : ''
            });*/

            /*if (element.is('input')) {
                input.on({
                    'focus': show
                });
            };*/

            if (component) {
                component.on('click', toggle);
                component.on('mousedown', false);
            }

        },
        detachElementEvents = function () {
            /*input.off({
                'change': change,
                'blur': blur,
                'keydown': keydown,
                'keyup': keyup,
                'focus': options.allowInputToggle ? hide : ''
            });*/

            if (element.is('input')) {
                input.off({
                    'focus': show
                });
            }

            if (component) {
                component.off('click', toggle);
                component.off('mousedown', false);
            }
            if(widget){

            }
        };

		/********************************************************************************
        *
        * Public API functions
        * =====================
        ********************************************************************************/
		gonrin.disable = function () {
            ///Disables the input element, the component is attached to, by adding a disabled="true" attribute to it.
            ///If the widget was visible before that call it is hidden. Possibly emits dp.hide
            hide();
            if (component && component.hasClass('btn')) {
                component.addClass('disabled');
            }
            if (textElement){
            	textElement.prop('disabled', true);
            }
            input.prop('disabled', true);
            return gonrin;
        };
		// initializing element and component attributes
        if (element.is('input') ) {
            input = element;
            value = input.val();

            element.wrap( '');
            var inputGroupSpan = element.parent();
            //inputGroupSpan.css("width", element.outerWidth());
            var componentButton = $('').html('');
            inputGroupSpan.append(componentButton);
            component = componentButton;
            textElement = $('');
            if(options.selectionMode === "multiple"){
            	var selectRender = $(menuTemplate).appendTo(textElement);

            }
            element.before(textElement);
            element.css("display", "none");
        } else {
            throw new Error('Cannot apply to non input element');
        }

    	if (input.is('input'))  {
        	setupWidget();
        	if(!options.placeholder){
        		options.placeholder = input.attr("placeholder");
        	}
        	if(textElement && options.placeholder){
        		textElement.attr("placeholder", options.placeholder);
        	}

        };

        attachElementEvents();
        /*if (input.prop('disabled')) {
        	gonrin.disable();
        }
        if (input.prop('readonly')) {
        	gonrin.readonly();
        }*/

		return gonrin;
	};

	$.fn.gonrinref = function (options) {

        return this.each(function () {
            var $this = $(this);
            if (!$this.data('gonrin')) {
                // create a private copy of the defaults object
                options = $.extend(true, {}, $.fn.gonrinref.defaults, options);
                $this.data('gonrin', GonrinRef($this, options));
            }
        });
    };

    $.fn.gonrinref.defaults = {
    	//template: null,
    	//height: null,
    	/*placeholder: null,
    	ignore_readonly: false,*/
    	selectionMode: "single",
    	debug: false,
    	//hasMany: false,
    	textField: null,
        valueField: null,
        dataSource: null,
        selectedItems: []
    };
}));<commit_msg>gonrinref event trigger<commit_after>(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // AMD is used - Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        factory(require('jquery'));
    } else {
        // Neither AMD nor CommonJS used. Use global variables.
        if (typeof jQuery === 'undefined') {
            throw 'Gonrin Ref requires jQuery to be loaded first';
        }
        factory(jQuery);
    }
}(function ($) {
	'use strict';
	var GonrinRef = function (element, options) {

		var gonrin = {},
		value,
		text,
		data, //datalist
		dataBound = false,
		textElement = false,
		unset = true,
        input,
        menuTemplate = '

',
        itemTemplate =  '

',
        component = false,
        widget = false,  //dialogView
        keyMap = {
                'up': 38,
                38: 'up',
                'down': 40,
                40: 'down',
                'left': 37,
                37: 'left',
                'right': 39,
                39: 'right',
                'tab': 9,
                9: 'tab',
                'escape': 27,
                27: 'escape',
                'enter': 13,
                13: 'enter',
                //'pageUp': 33,
                //33: 'pageUp',
                //'pageDown': 34,
                //34: 'pageDown',
                //'shift': 16,
                //16: 'shift',
                //'control': 17,
                //17: 'control',
                'space': 32,
                32: 'space',
                //'t': 84,
                //84: 't',
                'delete': 46,
                46: 'delete'
        },
        keyState = {},

        /********************************************************************************
        *
        * Private functions
        *
        ********************************************************************************/
        setupWidget = function () {
			if ((!!options.dataSource) && (typeof options.dataSource === "string")) {

				require([ options.dataSource ], function ( RefView ) {
					widget = new RefView({selectionMode: options.selectionMode});
					options.textField = options.textField || widget.textField;
					options.valueField = options.valueField || widget.valueField;

					if(!!input.val()){
						if(widget.selectionMode === "single"){
							var value = input.val();
			            	var model = widget.model || null;
			            	if(model){
			            		model.set(options.valueField, value);
								model.fetch({
				                    success: function (data) {
				                    	textElement.text(model.get(options.textField));
				                    },
				                    error:function(){},
								});
			            	}
						}
						if(widget.selectionMode === "multiple"){
							var value = $.parseJSON(input.val());
			            	//var model = widget.model || null;

			            	if(value){
			            		$.each(value, function(key, item){
			            			var txt = item[options.textField];
			            			$(itemTemplate).html(txt).appendTo(textElement.find("ul"));
			            		})

			            	}
						}

		            }

		    	});
			};

			//show dialog

			return gonrin;
		},
		show = function () {
        	if (input.prop('disabled') || (!options.ignoreReadonly && input.prop('readonly'))) {
                return gonrin;
            };
            if(widget){
            	widget.dialog({
            		success: function(){
            			if((!!widget)&&(!!widget.selectedItems)&&(widget.selectedItems.length > 0)){
            				var seleted = widget.selectedItems;
            				if(widget.selectionMode === "single"){
            					textElement.text(seleted[0][options.textField]);
                				input.val(seleted[0][options.valueField]);
                				//console.log(seleted[0]);
                				notifyEvent({
                					type:"change.gonrin",
                					value : seleted[0]
                				});
                				// trigger here
                				//input.trigger('change.gonrin', seleted[0]);
            				}
            				if(widget.selectionMode === "multiple"){
            					//textElement.html(JSON.stringify(seleted));
            					textElement.find("ul").empty();
    			            	$.each(seleted, function(key, item){
    			            		var txt = item[options.textField];
    			            		$(itemTemplate).html(txt).appendTo(textElement.find("ul"));
    			            	});
    			            	input.val(JSON.stringify(seleted));

    			            	notifyEvent({
                					type:"change.gonrin",
                					value : seleted
                				});
    			            	//input.trigger('change.gonrin');
            				}
            			}
            		}
            	})
            }
            /*notifyEvent({
                type: 'show.gonui'
            });*/
            return gonrin;
        },
        notifyEvent = function (e) {
            if ((e.type === 'change.gonrin')  && ((e.value && (e.value === e.oldValue)) || (!e.value && !e.oldValue))) {
                return;
            }
            element.trigger(e);
        },
        hide = function(){
            return gonrin;
        },

        toggle = function () {
            /// Shows or hides the widget
            //return (widget.is(':hidden') ? show() : hide());
        	return show();
        },
		attachElementEvents = function () {
        	if(options.onChange){
        		element.bind("change.gonrin", options.context !== null ? $.proxy(options.onChange, options.context ) : options.onChange);
        	}

            /*input.on({
                'change': change,
                'blur': options.debug ? '' : hide,
                'keydown': keydown,
                'keyup': keyup,
                'focus': options.allowInputToggle ? show : ''
            });*/

            /*if (element.is('input')) {
                input.on({
                    'focus': show
                });
            };*/

            if (component) {
                component.on('click', toggle);
                component.on('mousedown', false);
            }

        },
        detachElementEvents = function () {
            /*input.off({
                'change': change,
                'blur': blur,
                'keydown': keydown,
                'keyup': keyup,
                'focus': options.allowInputToggle ? hide : ''
            });*/

            if (element.is('input')) {
                input.off({
                    'focus': show
                });
            }

            if (component) {
                component.off('click', toggle);
                component.off('mousedown', false);
            }
            if(widget){

            }
        };

		/********************************************************************************
        *
        * Public API functions
        * =====================
        ********************************************************************************/
		gonrin.disable = function () {
            ///Disables the input element, the component is attached to, by adding a disabled="true" attribute to it.
            ///If the widget was visible before that call it is hidden. Possibly emits dp.hide
            hide();
            if (component && component.hasClass('btn')) {
                component.addClass('disabled');
            }
            if (textElement){
            	textElement.prop('disabled', true);
            }
            input.prop('disabled', true);
            return gonrin;
        };
		// initializing element and component attributes
        if (element.is('input') ) {
            input = element;
            value = input.val();

            element.wrap( '');
            var inputGroupSpan = element.parent();
            //inputGroupSpan.css("width", element.outerWidth());
            var componentButton = $('').html('');
            inputGroupSpan.append(componentButton);
            component = componentButton;
            textElement = $('');
            if(options.selectionMode === "multiple"){
            	var selectRender = $(menuTemplate).appendTo(textElement);

            }
            element.before(textElement);
            element.css("display", "none");
        } else {
            throw new Error('Cannot apply to non input element');
        }

    	if (input.is('input'))  {
        	setupWidget();
        	if(!options.placeholder){
        		options.placeholder = input.attr("placeholder");
        	}
        	if(textElement && options.placeholder){
        		textElement.attr("placeholder", options.placeholder);
        	}

        };

        attachElementEvents();
        /*if (input.prop('disabled')) {
        	gonrin.disable();
        }
        if (input.prop('readonly')) {
        	gonrin.readonly();
        }*/

		return gonrin;
	};

	$.fn.gonrinref = function (options) {

        return this.each(function () {
            var $this = $(this);
            if (!$this.data('gonrin')) {
                // create a private copy of the defaults object
                options = $.extend(true, {}, $.fn.gonrinref.defaults, options);

                console.log(options);
                $this.data('gonrin', GonrinRef($this, options));
            }
        });
    };

    $.fn.gonrinref.defaults = {
    	context: null,
    	//template: null,
    	//height: null,
    	/*placeholder: null,
    	ignore_readonly: false,*/
    	selectionMode: "single",
    	debug: false,
    	//hasMany: false,
    	textField: null,
        valueField: null,
        dataSource: null,
        selectedItems: [],
        onChange : function(){}
    };
}));<|endoftext|>


<commit_before>#!/usr/bin/node

var matrix = require('../data/country_lang.json'),
    country = process.argv[2],
    language = process.argv[3];

switch (country) {
case '-h':
case '--help':
    console.log("Usage: node country-lang.js COUNTRY [LANGUAGE] \nVerifies if the pair country/language is valid.\n\nIf no language is provided it returns a list of languages");
    break;
case undefined:
    console.log("No parameters given. -h or --help for usage instructions.");
    break;
default:
    if (matrix[country] === undefined) {
        console.log("Country not found.");
        break;
    }
    switch (language) {
    case undefined:
        console.log(matrix[country]);
        break;
    default:
        console.log(matrix[country].indexOf(language) > -1 ? true : false);
    }
}

<commit_msg>command line functions body<commit_after>#!/usr/bin/node

var matrix = require('../data/country_lang.json'),
    country = process.argv[2],
    language = process.argv[3];

switch (country) {
case '-h':
case '--help':
    console.log("Usage: node country-lang.js COUNTRY [LANGUAGE] \nVerifies if the pair country/language is valid.\n\nIf no language is provided it returns a list of languages");
    break;
case undefined:
    console.log("No parameters given. -h or --help for usage instructions.");
    break;
default:
    if (matrix.filter(function (x) {
        return x.country === country;
    }).length === 0) {
        console.log("Country not found.");
        break;
    }
    switch (language) {
    case undefined:
        console.log(matrix.filter(function (x) {
            return x.country === country;
        }).shift().languages);
        break;
    default:
        console.log(matrix.filter(function (countries) {
            return countries.country === country;
        }).filter(function (countryLang) {
            return countryLang.languages == language;
        }).length > 0 ? true : false);
    }
}
<|endoftext|>


<commit_before>define(['jquery'], function ($) {
  return function () {
    $('#global-browser-prompt')
    .prepend('
Your browser is unable to display some of the content on this page.
');
  }
});
<commit_msg>Only apply the partial experience message on ie8,7,6<commit_after>define(['jquery'], function ($) {
  return function () {
    if ($('html').hasClass('lte-ie8')) {
      $('#global-browser-prompt')
        .prepend('
Your browser is unable to display some of the content on this page.
');
    }
  }
});
<|endoftext|>


<commit_before><commit_msg>update<commit_after><|endoftext|>


<commit_before>exports = module.exports = function antenna(id) {
  var map = {
    'adapter': './adapter',
    'app': './app',
    'boot/connection': './boot/connection'
  };

  var mid = map[id];
  if (mid) {
    return require(mid);
  }
};

exports.createAdapter = require('./adapter');
exports.createConnectionBootPhase = require('./boot/connection');
<commit_msg>Remove exported create functions.<commit_after>exports = module.exports = function antenna(id) {
  var map = {
    'adapter': './adapter',
    'app': './app',
    'boot/connection': './boot/connection'
  };

  var mid = map[id];
  if (mid) {
    return require(mid);
  }
};
<|endoftext|>


<commit_before>(function () {
    var events = require('events');

    function ircClient(server, port, nick, fullname) {
        this.host = server;
        this.port = port;
        this.nick = nick;
        this.fullname = fullname;
        this.verbosity = 1; // 0 => Silent, 1 => Normal, 2 => Info, 3 => Debug
        this.debug = false;
        events.EventEmitter.call(this);
        return this;
    }

    ircClient.super_ = events.EventEmitter;
    ircClient.prototype = Object.create(events.EventEmitter.prototype);

    ircClient.prototype.connect = function () {
        var that = this,
            net = require('net'),
            client = net.createConnection(that.port, that.host);

        client.addListener('connect', function () {
            client.write('NICK ' + that.nick + '\r\n');
            client.write('USER ' + that.nick + ' 0 * :' + that.fullname + '\r\n');
            that.logger('Client connected', 1);
        });

        client.addListener('data', function (data) {
            if (this.debug) console.log(data.toString());
            that.dispatcher(data.toString());
        });

        client.addListener('close', function (data) {
            that.logger('Disconnected from server', 1);
        });

        this.client = client;
    };

    // FORMALITY HANDLERS

    ircClient.prototype.dispatcher = function (data) {
        var response = data.split('\n'),
            formatResponse,
            preparedResponse,
            sortedResponse,
            i;

        if (data.match('^PING')) {
            this.pingHandler(data);
        } else {
            for (i = response.length; i--;) {
                rawResponse = response[i].split(" ");
                if(rawResponse[1] === '376') { // If MOTD has been written
                    this.emit('ready');
                } else {
                    this.eventHandler(assembleResponse(rawResponse));
                }
            }
        }
    };

    ircClient.prototype.eventHandler = function (data) {
        if (data.method === 'PRIVMSG') {
            data.message = data.message.join(" ");
            data.message = data.message.substring(1, (data.message.length-1));
                if (data.receiver.match(/^#/)) {
                    data.method = 'CHANMSG';
    	              this.emit('CHANMSG', data);
                } else {
    	              this.emit('PRIVMSG', data);
                }
        }
        else if (data.method === 'JOIN') {
            // Remove preceding semi-colon
            data.receiver = data.receiver.substring(0, (data.receiver.length-1));
            this.emit('JOIN', data);
        }
        else if (data.method === 'INVITE') {
            data.message = data.message[0].substring(1, (data.message[0].length-1));
            this.emit('INVITE', data);
        }
        else if (data.method === 'TOPIC') {
            data.message = data.message.join(" ");
            data.message = data.message.substring(1, (data.message.length-1));
            this.emit('TOPIC', data);
        }
        else if (data.method === 'PART') {
            data.receiver = data.receiver.substring(0, (data.receiver.length-1));
            this.emit('PART', data);
        }
        else if (data.method === 'KICK') {
            data.message[1] = data.message.splice(1);
            data.message[1] = data.message[1].join(" ");
            data.message[1] = data.message[1].substring(1, (data.message[1].length-1));
            this.emit('KICK', data);
        }
        else if (data.method === 'QUIT') {
            data.receiver = '';
            this.emit('QUIT', data);
        }
        else if (data.method === 'NICK') {
            data.receiver = data.receiver.substring(1, (data.receiver.length-1));
            this.emit('NICK', data);
        }
    };

    ircClient.prototype.pingHandler = function (response) {
        var splitResponse = [];
        splitResponse = response.split(" ");
        this.logger('PING ' + splitResponse[1], 2);
        this.logger('PONG ' + splitResponse[1], 2);
        this.client.write('PONG ' + splitResponse[1] + '\r\n');
    };

    ircClient.prototype.logger = function (message, level) {
        if ((this.verbosity !== 0) && (this.verbosity >= level)) {
            console.log('Level ' + level + ': ' + message);
        }
    };

    // USER COMMANDS

    ircClient.prototype.join = function (channel) {
        this.logger('JOIN ' + channel, 1);
        this.client.write('JOIN ' + channel + '\r\n');
    };

    ircClient.prototype.quit = function (message) {
        this.logger('QUIT :' + message, 1);
        this.client.write('QUIT :Quit: ' + message + '\r\n');
    };

    ircClient.prototype.part = function (channel) {
        this.logger('PART ' + message, 1);
        this.client.write('PART ' + channel + '\r\n');
    };

    ircClient.prototype.say = function (message) {
        this.logger('PRIVMSG ' + message, 1);
        this.client.write('PRIVMSG ' + message + '\r\n');
    };
    ircClient.prototype.nick = function (nick) {
        this.logger('NICK ' + nick, 1);
        this.client.write('NICK ' + nick + '\r\n');
    };
    ircClient.prototype.mode = function (channel, mode, nick) {
        this.logger('MODE ' + channel + ' ' + mode + ' ' + nick, 1);
        this.client.write('MODE ' + channel + ' ' + mode + ' ' + nick + '\r\n');
    };
    ircClient.prototype.kick = function (channel, user, reason) {
        this.logger('KICK ' + channel + ' ' + nick + ' ' + reason, 1);
        this.client.write('KICK ' + channel + ' ' + nick + ' ' + reason + '\r\n');
    };

    // TOOLBOX
    function trim (string) {
      string = string.replace(/(^\s*)|(\s*$)/gi,"");
      string = string.replace(/[ ]{2,}/gi," ");
      string = string.replace(/\n /,"\n");
      return string;
    }

    function assembleResponse (response) {
        var sender,
            formatUserhost,
            formatNick,
            formattedReturn,
            nick;

        // In case sender is a nick!user@host, parse the nick.
        try {
            formatUserhost = new RegExp(/\b[^]*(.*?)!/);                // :nick!user@host =>
            nick = formatUserhost.exec(response[0]);                    // [n,i,c,k,!] =>
            formatNick = nick.join("");                                 // nick! =>
            sender = (formatNick.substring(0,(formatNick.length-1)));   // nick => Done.
        } catch(e) {
            sender = undefined;
        }

        var returnObject = {
            method: response[1],
            receiver: response[2],
            sender: sender,
            message: response.slice(3)
        };

        return returnObject;
    }

    module.exports = ircClient;
})();
<commit_msg>Fixed say function<commit_after>(function () {
    var events = require('events');

    function ircClient(server, port, nick, fullname) {
        this.host = server;
        this.port = port;
        this.nick = nick;
        this.fullname = fullname;
        this.verbosity = 1; // 0 => Silent, 1 => Normal, 2 => Info, 3 => Debug
        this.debug = false;
        events.EventEmitter.call(this);
        return this;
    }

    ircClient.super_ = events.EventEmitter;
    ircClient.prototype = Object.create(events.EventEmitter.prototype);

    ircClient.prototype.connect = function () {
        var that = this,
            net = require('net'),
            client = net.createConnection(that.port, that.host);

        client.addListener('connect', function () {
            client.write('NICK ' + that.nick + '\r\n');
            client.write('USER ' + that.nick + ' 0 * :' + that.fullname + '\r\n');
            that.logger('Client connected', 1);
        });

        client.addListener('data', function (data) {
            if (this.debug) console.log(data.toString());
            that.dispatcher(data.toString());
        });

        client.addListener('close', function (data) {
            that.logger('Disconnected from server', 1);
        });

        this.client = client;
    };

    // FORMALITY HANDLERS

    ircClient.prototype.dispatcher = function (data) {
        var response = data.split('\n'),
            formatResponse,
            preparedResponse,
            sortedResponse,
            i;

        if (data.match('^PING')) {
            this.pingHandler(data);
        } else {
            for (i = response.length; i--;) {
                rawResponse = response[i].split(" ");
                if(rawResponse[1] === '376') { // If MOTD has been written
                    this.emit('ready');
                } else {
                    this.eventHandler(assembleResponse(rawResponse));
                }
            }
        }
    };

    ircClient.prototype.eventHandler = function (data) {
        if (data.method === 'PRIVMSG') {
            data.message = data.message.join(" ");
            data.message = data.message.substring(1, (data.message.length-1));
                if (data.receiver.match(/^#/)) {
                    data.method = 'CHANMSG';
    	              this.emit('CHANMSG', data);
                } else {
    	              this.emit('PRIVMSG', data);
                }
        }
        else if (data.method === 'JOIN') {
            // Remove preceding semi-colon
            data.receiver = data.receiver.substring(0, (data.receiver.length-1));
            this.emit('JOIN', data);
        }
        else if (data.method === 'INVITE') {
            data.message = data.message[0].substring(1, (data.message[0].length-1));
            this.emit('INVITE', data);
        }
        else if (data.method === 'TOPIC') {
            data.message = data.message.join(" ");
            data.message = data.message.substring(1, (data.message.length-1));
            this.emit('TOPIC', data);
        }
        else if (data.method === 'PART') {
            data.receiver = data.receiver.substring(0, (data.receiver.length-1));
            this.emit('PART', data);
        }
        else if (data.method === 'KICK') {
            data.message[1] = data.message.splice(1);
            data.message[1] = data.message[1].join(" ");
            data.message[1] = data.message[1].substring(1, (data.message[1].length-1));
            this.emit('KICK', data);
        }
        else if (data.method === 'QUIT') {
            data.receiver = '';
            this.emit('QUIT', data);
        }
        else if (data.method === 'NICK') {
            data.receiver = data.receiver.substring(1, (data.receiver.length-1));
            this.emit('NICK', data);
        }
    };

    ircClient.prototype.pingHandler = function (response) {
        var splitResponse = [];
        splitResponse = response.split(" ");
        this.logger('PING ' + splitResponse[1], 2);
        this.logger('PONG ' + splitResponse[1], 2);
        this.client.write('PONG ' + splitResponse[1] + '\r\n');
    };

    ircClient.prototype.logger = function (message, level) {
        if ((this.verbosity !== 0) && (this.verbosity >= level)) {
            console.log('Level ' + level + ': ' + message);
        }
    };

    // USER COMMANDS

    ircClient.prototype.join = function (channel) {
        this.logger('JOIN ' + channel, 1);
        this.client.write('JOIN ' + channel + '\r\n');
    };

    ircClient.prototype.quit = function (message) {
        this.logger('QUIT :' + message, 1);
        this.client.write('QUIT :Quit: ' + message + '\r\n');
    };

    ircClient.prototype.part = function (channel) {
        this.logger('PART ' + message, 1);
        this.client.write('PART ' + channel + '\r\n');
    };

    ircClient.prototype.say = function (receiver, message) {
        this.logger('PRIVMSG ' + receiver + ' ' + message, 1);
        this.client.write('PRIVMSG ' + receiver + ' :' + message + '\r\n');
    };
    ircClient.prototype.nick = function (nick) {
        this.logger('NICK ' + nick, 1);
        this.client.write('NICK ' + nick + '\r\n');
    };
    ircClient.prototype.mode = function (channel, mode, nick) {
        this.logger('MODE ' + channel + ' ' + mode + ' ' + nick, 1);
        this.client.write('MODE ' + channel + ' ' + mode + ' ' + nick + '\r\n');
    };
    ircClient.prototype.kick = function (channel, user, reason) {
        this.logger('KICK ' + channel + ' ' + nick + ' ' + reason, 1);
        this.client.write('KICK ' + channel + ' ' + nick + ' ' + reason + '\r\n');
    };

    // TOOLBOX
    function trim (string) {
      string = string.replace(/(^\s*)|(\s*$)/gi,"");
      string = string.replace(/[ ]{2,}/gi," ");
      string = string.replace(/\n /,"\n");
      return string;
    }

    function assembleResponse (response) {
        var sender,
            formatUserhost,
            formatNick,
            formattedReturn,
            nick;

        // In case sender is a nick!user@host, parse the nick.
        try {
            formatUserhost = new RegExp(/\b[^]*(.*?)!/);                // :nick!user@host =>
            nick = formatUserhost.exec(response[0]);                    // [n,i,c,k,!] =>
            formatNick = nick.join("");                                 // nick! =>
            sender = (formatNick.substring(0,(formatNick.length-1)));   // nick => Done.
        } catch(e) {
            sender = undefined;
        }

        var returnObject = {
            method: response[1],
            receiver: response[2],
            sender: sender,
            message: response.slice(3)
        };

        return returnObject;
    }

    module.exports = ircClient;
})();
<|endoftext|>


<commit_before>var resetCollection = function(collection) {
  collection.find().fetch().forEach(function(obj) {
    collection.remove({_id: obj._id});
  });
};
describe('Entity Unit testing', function () {
  var entityManager;
  var testEntity = {name: 'Vikram', _id:'2233'};
  beforeAll(function() {
    entityManager = new EntityManager();
    var allCollObjs = [{
      obj: entityManager,
      field: 'entities'
    },{
      obj: entityManager.entityInstanceManager,
      field: 'entityInstances'
    }
    ];
    allCollObjs.forEach(collObj => {
      console.log('resetting ' + collObj.field);
      resetCollection(collObj.obj[collObj.field]);
    });
  });
  it('should add entity', function () {
    var caps = new EntityManager();
    caps.addEntity('User');
    expect(caps.allEntities.length).toEqual(1);
  });
  it('should get specific entity', function () {
    var entityObj = entityManager.getEntity('User');
    expect(entityObj).toBeDefined();
  });
  it('should add entity with instance', function () {
    var caps = new EntityManager();
    expect(caps.allEntities.length).toEqual(1);
    caps.addEntityInstance('User', testEntity);
    expect(caps.allEntityInstances.length).toEqual(1);
  });
  it('should get specific entity instance', function() {
    var entityInstance = entityManager.getEntityInstance(testEntity._id);
    expect(entityInstance).toBeDefined();
  });
  it('should add all existing entities and objects in the access matrix', function() {
    var objectLength = entityManager.objectManager.allObjects.length;
    var entityLength = entityManager.allEntities.length;
    var entityInstance = entityManager.getEntityInstance(testEntity._id);
    expect(entityInstance.accessControl).toBeDefined();
    expect(entityInstance.accessControl.length).toEqual(objectLength + entityLength);
  });
  describe('Entity Instance access testing', function() {
    it('should not allow access by default', function() {
      var bool = entityManager.canInstancePerform('User', testEntity, 'edit', 'User', testEntity._id);
      expect(bool).toBeFalsy();
    });
    it('should set capability in db', function() {
      //sets capability such that testEntity can edit all users
      entityManager.setCapabilityOfInstance('User', testEntity._id, 'edit', 'entity', 'User', 'all objects');
      var entity = entityManager.getEntity('User');
      var entityInstance = entityManager.getEntityInstance(testEntity._id);
      var foundEntity = _.findWhere(entityInstance.accessControl, {entity : entity._id});
      var foundRule = foundEntity.rules.edit;
      var allObjectCapability = entityManager.capabilityManager.getCapability('all objects');
      console.log(foundRule);
      console.log(allObjectCapability);
      expect(foundRule.capability).toEqual(allObjectCapability._id);
    });
    it('should allow access for all objects capability', function() {
      var bool = entityManager.canInstancePerform('User', testEntity, 'edit', 'User', testEntity._id);
      expect(bool).toBeTruthy();
    });
  });
});<commit_msg>Wrote tests for setting args, adding entity by collection etc<commit_after>var resetCollection = function(collection) {
  collection.find().fetch().forEach(function(obj) {
    collection.remove({_id: obj._id});
  });
};
describe('Entity Unit testing', function () {
  var entityManager;
  var testEntity = {name: 'Vikram', _id:'2233'};
  beforeAll(function() {
    entityManager = new EntityManager();
    var allCollObjs = [{
      obj: entityManager,
      field: 'entities'
    },{
      obj: entityManager.entityInstanceManager,
      field: 'entityInstances'
    }
    ];
    allCollObjs.forEach(collObj => {
      console.log('resetting ' + collObj.field);
      resetCollection(collObj.obj[collObj.field]);
    });
  });
  it('should add entity', function () {
    var caps = new EntityManager();
    caps.addEntity('User');
    expect(caps.allEntities.length).toEqual(1);
  });
  it('should get specific entity', function () {
    var entityObj = entityManager.getEntity('User');
    expect(entityObj).toBeDefined();
  });
  it('should add entity with instance', function () {
    var caps = new EntityManager();
    expect(caps.allEntities.length).toEqual(1);
    caps.addEntityInstance('User', testEntity);
    expect(caps.allEntityInstances.length).toEqual(1);
  });
  it('should get specific entity instance', function() {
    var entityInstance = entityManager.getEntityInstance(testEntity._id);
    expect(entityInstance).toBeDefined();
  });
  it('should add all existing entities and objects in the access matrix', function() {
    var objectLength = entityManager.objectManager.allObjects.length;
    var entityLength = entityManager.allEntities.length;
    var entityInstance = entityManager.getEntityInstance(testEntity._id);
    expect(entityInstance.accessControl).toBeDefined();
    expect(entityInstance.accessControl.length).toEqual(objectLength + entityLength);
  });
  describe('Entity Instance access testing', function() {
    it('should not allow access by default', function() {
      var bool = entityManager.canInstancePerform('User', testEntity, 'edit', 'User', testEntity._id);
      expect(bool).toBeFalsy();
    });
    it('should set capability in db', function() {
      //sets capability such that testEntity can edit all users
      entityManager.setCapabilityOfInstance('User', testEntity._id, 'edit', 'entity', 'User', 'all objects');
      var entity = entityManager.getEntity('User');
      var entityInstance = entityManager.getEntityInstance(testEntity._id);
      var foundEntity = _.findWhere(entityInstance.accessControl, {entity : entity._id});
      var foundRule = foundEntity.rules.edit;
      var allObjectCapability = entityManager.capabilityManager.getCapability('all objects');
      expect(foundRule.capability).toEqual(allObjectCapability._id);
    });
    it('should allow access for all objects capability', function() {
      var bool = entityManager.canInstancePerform('User', testEntity, 'edit', 'User', testEntity._id);
      expect(bool).toBeTruthy();
    });
    it('should set args with capability in db', function() {
      var args = {objects:[{objId: testEntity._id}]};
      var fakeArgs = {objects:[{objId: 'fake_id'}]};
      entityManager.setCapabilityOfInstance('User', testEntity._id, 'edit', 'entity',
        'User', 'specific objects', args);
      var entity = entityManager.getEntity('User');
      var entityInstance = entityManager.getEntityInstance(testEntity._id);
      var foundEntity = _.findWhere(entityInstance.accessControl, {entity : entity._id});
      var foundRule = foundEntity.rules.edit;
      var allObjectCapability = entityManager.capabilityManager.getCapability('specific objects');
      expect(foundRule.capability).toEqual(allObjectCapability._id);
      expect(foundRule.args).toEqual(args);
    });
    it('should succeed for correct args', function() {
      var bool = entityManager.canInstancePerform('User', testEntity, 'edit',
        'User', testEntity._id);
      expect(bool).toBeTruthy();
    });
    it('should change args', function() {
      entityManager.setCapabilityArgsOfInstance('User', testEntity._id, 'edit', 'entity',
        'User', fakeArgs);
      var entity = entityManager.getEntity('User');
      var entityInstance = entityManager.getEntityInstance(testEntity._id);
      var foundEntity = _.findWhere(entityInstance.accessControl, {entity : entity._id});
      var foundRule = foundEntity.rules.edit;
      expect(foundRule.args).toEqual(fakeArgs);
    });
    it('should fail for incorrect args', function() {
      var bool = entityManager.canInstancePerform('User', testEntity, 'edit',
        'User', testEntity._id);
      expect(bool).toBeFalsy();
    });
  });
});
describe('Entity Unit testing by collection', function() {
  var entityColl;
  beforeAll(function() {
    entityColl = new Meteor.Collection(null);
    entityManager = new EntityManager();
    var allCollObjs = [{
      obj: entityManager,
      field: 'entities'
    },{
      obj: entityManager.entityInstanceManager,
      field: 'entityInstances'
    }
    ];
    allCollObjs.forEach(collObj => {
      console.log('resetting ' + collObj.field);
      resetCollection(collObj.obj[collObj.field]);
    });
  });
  it('should add entity', function () {
    var caps = new EntityManager();
    caps.addEntity('Tester', entityColl);
    expect(caps.allEntities.length).toEqual(1);
  });
  it('should get specific entity', function () {
    var entityObj = entityManager.getEntity('Tester');
    expect(entityObj).toBeDefined();
  });
  it('should add entity instance from DB', function () {
    var caps = new EntityManager();
    expect(caps.allEntities.length).toEqual(1);
    entityColl.insert({name: 'Tester1'});
    expect(caps.allEntityInstances.length).toEqual(1);
  });
  it('should get specific entity instance', function() {
    var entityId = entityColl.findOne({name: 'Tester1'});
    var entityInstance = entityManager.getEntityInstance(entityId);
    expect(entityInstance).toBeDefined();
  });
});<|endoftext|>


<commit_before>iD.modes = {};

iD.modes.AddPlace = {
    id: 'add-place',
    title: '+ Place',

    enter: function() {
        var surface = this.map.surface;

        function click() {
            var node = iD.Node({loc: this.map.mouseCoordinates(), _poi: true});
            this.history.perform(iD.actions.addNode(node));
            this.map.selectEntity(node);
            this.controller.exit();
            this.exit();
        }

        surface.on('click.addplace', click.bind(this));

        this.map.keybinding().on('⎋.exit', function() {
            this.controller.exit();
        }.bind(this));
    },

    exit: function() {
        this.map.surface
            .on('click.addplace', null);
        this.map.keybinding().on('⎋.exit', null);
    }
};

iD.modes.AddRoad = {
    id: 'add-road',
    title: '+ Road',

    enter: function() {
        this.map.dblclickEnable(false);
        var surface = this.map.surface;

        // http://bit.ly/SwUwIL
        // http://bit.ly/WxqGng
        function click() {
            var t = d3.select(d3.event.target),
                node,
                direction = 'forward',
                start = true,
                way = iD.Way({ tags: { highway: 'residential', elastic: 'true' } });

            // connect a way to an existing way
            if (t.datum() && t.datum().type === 'node') {
                // continue an existing way
                var id = t.datum().id;
                var parents = this.history.graph().parents(id);
                if (parents.length) {
                    if (parents[0].nodes[0] === id) {
                        way = parents[0];
                        direction = 'backward';
                        start = false;
                    } else if (_.last(parents[0].nodes) === id) {
                        way = parents[0];
                        start = false;
                    }
                }
                node = t.datum();
            // snap into an existing way
            } else if (t.data() && t.datum() && t.datum().type === 'way') {
                var index = iD.util.geo.chooseIndex(t.datum(), d3.mouse(surface.node()), this.map);
                node = iD.Node({loc: this.map.mouseCoordinates()});
                var connectedWay = this.history.graph().entity(t.datum().id);
                this.history.perform(iD.actions.addWayNode(connectedWay, node, index));
            } else {
                node = iD.Node({loc: this.map.mouseCoordinates()});
            }

            if (start) {
                this.history.perform(iD.actions.startWay(way));
                this.history.perform(iD.actions.addWayNode(way, node));
            }

            this.controller.enter(iD.modes.DrawRoad(way.id, direction));
        }

        surface.on('click.addroad', click.bind(this));

        this.map.keybinding().on('⎋.exit', function() {
            this.controller.exit();
        }.bind(this));
    },
    exit: function() {
        this.map.dblclickEnable(true);
        this.map.surface.on('click.addroad', null);
        this.map.keybinding().on('⎋.exit', null);
        d3.selectAll('#addroad').remove();
    }
};

// user has clicked on the map, started a road, and now needs to click more
// nodes to continue it.
iD.modes.DrawRoad = function(way_id, direction) {
    return {
        enter: function() {
            this.map.dblclickEnable(false);
            this.map.dragEnable(false);

            var index = (direction === 'forward') ? undefined : -1,
                surface = this.map.surface,
                node = iD.Node({loc: this.map.mouseCoordinates()}),
                way = this.history.graph().entity(way_id),
                firstNode = way.nodes[0],
                lastNode = _.last(way.nodes);

            this.history.perform(iD.actions.addWayNode(way, node, index));

            function mousemove() {
                this.history.replace(iD.actions.addWayNode(way, node.update({loc: this.map.mouseCoordinates()}), index));
            }

            function click() {
                d3.event.stopPropagation();

                var t = d3.select(d3.event.target);

                if (t.datum() && t.datum().type === 'node') {
                    if (t.datum().id == firstNode || t.datum().id == lastNode) {
                        // If this is drawing a loop and this is not the drawing
                        // end of the stick, finish the circle
                        if (direction === 'forward' && t.datum().id == firstNode) {
                            this.history.replace(iD.actions.addWayNode(way,
                                this.history.graph().entity(firstNode), index));
                        } else if (direction === 'backward' && t.datum().id == lastNode) {
                            this.history.replace(iD.actions.addWayNode(way,
                                this.history.graph().entity(lastNode), index));
                        }

                        delete way.tags.elastic;
                        this.history.perform(iD.actions.changeTags(way, way.tags));
                        this.map.selectEntity(way);

                        // End by clicking on own tail
                        return this.controller.exit();
                    } else {
                        // connect a way to an existing way
                        this.history.replace(iD.actions.addWayNode(way, t.datum(), index));
                    }
                } else if (t.datum() && t.datum().type === 'way') {
                    node = node.update({loc: this.map.mouseCoordinates()});
                    this.history.replace(iD.actions.addWayNode(way, node, index));

                    var connectedWay = this.history.graph().entity(t.datum().id);
                    var connectedIndex = iD.modes.chooseIndex(t.datum(), d3.mouse(surface.node()), this.map);
                    this.history.perform(iD.actions.addWayNode(connectedWay, node, connectedIndex));
                } else {
                    node = node.update({loc: this.map.mouseCoordinates()});
                    this.history.replace(iD.actions.addWayNode(way, node, index));
                }

                this.controller.enter(iD.modes.DrawRoad(way_id, direction));
            }

            surface.on('mousemove.drawroad', mousemove.bind(this))
                .on('click.drawroad', click.bind(this));

            this.map.keybinding().on('⎋.exit', function() {
                this.controller.exit();
            }.bind(this));
        },

        exit: function() {
            this.map.surface.on('mousemove.drawroad', null)
                .on('click.drawroad', null);
            this.map.keybinding().on('⎋.exit', null);
            window.setTimeout(function() {
                this.map.dblclickEnable(true);
                this.map.dragEnable(true);
            }.bind(this), 1000);
        }
    };
};

iD.modes.AddArea = {
    id: 'add-area',
    title: '+ Area',

    way: function() {
        return iD.Way({
            tags: { building: 'yes', area: 'yes', elastic: 'true' }
        });
    },

    enter: function() {
        this.map.dblclickEnable(false);

        var surface = this.map.surface;

        function click() {
            var t = d3.select(d3.event.target),
                node, way = this.way();

            // connect a way to an existing way
            if (t.datum() && t.datum().type === 'node') {
                node = t.datum();
            } else {
                node = iD.Node({loc: this.map.mouseCoordinates()});
            }

            this.history.perform(iD.actions.startWay(way));
            this.history.perform(iD.actions.addWayNode(way, node));
            this.map.selectEntity(way);
            this.controller.enter(iD.modes.DrawArea(way.id));
        }

        surface.on('click.addarea', click.bind(this));

        this.map.keybinding().on('⎋.exit', function() {
            this.controller.exit();
        }.bind(this));
    },

    exit: function() {
        window.setTimeout(function() {
            this.map.dblclickEnable(true);
        }.bind(this), 1000);
        this.map.surface.on('click.addarea', null);
        this.map.keybinding().on('⎋.exit', null);
    }
};

iD.modes.DrawArea = function(way_id) {
    return {
        enter: function() {
            this.map.dblclickEnable(false);

            var surface = this.map.surface,
                way = this.history.graph().entity(way_id),
                firstnode_id = _.first(way.nodes),
                node = iD.Node({loc: this.map.mouseCoordinates()});

            this.history.perform(iD.actions.addWayNode(way, node));

            function mousemove() {
                this.history.replace(iD.actions.addWayNode(way, node.update({loc: this.map.mouseCoordinates()})));
            }

            function click() {
                d3.event.stopPropagation();

                var t = d3.select(d3.event.target);

                if (t.datum() && t.datum().type === 'node') {
                    if (t.datum().id == firstnode_id) {
                        this.history.replace(iD.actions.addWayNode(way,
                            this.history.graph().entity(way.nodes[0])));

                        delete way.tags.elastic;
                        this.history.perform(iD.actions.changeTags(way, way.tags));

                        // End by clicking on own tail
                        return this.controller.exit();
                    } else {
                        // connect a way to an existing way
                        this.history.replace(iD.actions.addWayNode(way, t.datum()));
                    }
                } else {
                    node = node.update({loc: this.map.mouseCoordinates()});
                    this.history.replace(iD.actions.addWayNode(way, node));
                }

                this.controller.enter(iD.modes.DrawArea(way_id));
            }

            this.map.keybinding().on('⎋.exit', function() {
                this.controller.exit();
            }.bind(this));

            surface.on('click.drawarea', click.bind(this))
                .on('mousemove.drawarea', mousemove.bind(this));
        },

        exit: function() {
            this.map.surface.on('mousemove.drawarea', null)
                .on('click.drawarea', null);
            this.map.keybinding().on('⎋.exit', null);
            window.setTimeout(function() {
                this.map.dblclickEnable(true);
            }.bind(this), 1000);
        }
    };
};

iD.modes.Move = {
    enter: function() { },
    exit: function() { }
};
<commit_msg>Simplify<commit_after>iD.modes = {};

iD.modes.AddPlace = {
    id: 'add-place',
    title: '+ Place',

    enter: function() {
        var surface = this.map.surface;

        function click() {
            var node = iD.Node({loc: this.map.mouseCoordinates(), _poi: true});
            this.history.perform(iD.actions.addNode(node));
            this.map.selectEntity(node);
            this.controller.exit();
            this.exit();
        }

        surface.on('click.addplace', click.bind(this));

        this.map.keybinding().on('⎋.exit', function() {
            this.controller.exit();
        }.bind(this));
    },

    exit: function() {
        this.map.surface
            .on('click.addplace', null);
        this.map.keybinding().on('⎋.exit', null);
    }
};

iD.modes.AddRoad = {
    id: 'add-road',
    title: '+ Road',

    enter: function() {
        this.map.dblclickEnable(false);
        var surface = this.map.surface;

        // http://bit.ly/SwUwIL
        // http://bit.ly/WxqGng
        function click() {
            var datum = d3.select(d3.event.target).datum() || {},
                node,
                direction = 'forward',
                start = true,
                way = iD.Way({ tags: { highway: 'residential', elastic: 'true' } });

            if (datum.type === 'node') {
                // continue an existing way
                node = datum;

                var id = datum.id;
                var parents = this.history.graph().parents(id);
                if (parents.length) {
                    if (parents[0].nodes[0] === id) {
                        way = parents[0];
                        direction = 'backward';
                        start = false;
                    } else if (_.last(parents[0].nodes) === id) {
                        way = parents[0];
                        start = false;
                    }
                }
            } else if (datum.type === 'way') {
                // begin a new way starting from an existing way
                node = iD.Node({loc: this.map.mouseCoordinates()});

                var index = iD.util.geo.chooseIndex(datum, d3.mouse(surface.node()), this.map);
                var connectedWay = this.history.graph().entity(datum.id);
                this.history.perform(iD.actions.addWayNode(connectedWay, node, index));
            } else {
                // begin a new way
                node = iD.Node({loc: this.map.mouseCoordinates()});
            }

            if (start) {
                this.history.perform(iD.actions.startWay(way));
                this.history.perform(iD.actions.addWayNode(way, node));
            }

            this.controller.enter(iD.modes.DrawRoad(way.id, direction));
        }

        surface.on('click.addroad', click.bind(this));

        this.map.keybinding().on('⎋.exit', function() {
            this.controller.exit();
        }.bind(this));
    },
    exit: function() {
        this.map.dblclickEnable(true);
        this.map.surface.on('click.addroad', null);
        this.map.keybinding().on('⎋.exit', null);
        d3.selectAll('#addroad').remove();
    }
};

// user has clicked on the map, started a road, and now needs to click more
// nodes to continue it.
iD.modes.DrawRoad = function(way_id, direction) {
    return {
        enter: function() {
            this.map.dblclickEnable(false);
            this.map.dragEnable(false);

            var index = (direction === 'forward') ? undefined : -1,
                surface = this.map.surface,
                node = iD.Node({loc: this.map.mouseCoordinates()}),
                way = this.history.graph().entity(way_id),
                firstNode = way.nodes[0],
                lastNode = _.last(way.nodes);

            this.history.perform(iD.actions.addWayNode(way, node, index));

            function mousemove() {
                this.history.replace(iD.actions.addWayNode(way, node.update({loc: this.map.mouseCoordinates()}), index));
            }

            function click() {
                d3.event.stopPropagation();

                var datum = d3.select(d3.event.target).datum() || {};

                if (datum.type === 'node') {
                    if (datum.id == firstNode || datum.id == lastNode) {
                        // If this is drawing a loop and this is not the drawing
                        // end of the stick, finish the circle
                        if (direction === 'forward' && datum.id == firstNode) {
                            this.history.replace(iD.actions.addWayNode(way,
                                this.history.graph().entity(firstNode), index));
                        } else if (direction === 'backward' && datum.id == lastNode) {
                            this.history.replace(iD.actions.addWayNode(way,
                                this.history.graph().entity(lastNode), index));
                        }

                        delete way.tags.elastic;
                        this.history.perform(iD.actions.changeTags(way, way.tags));
                        this.map.selectEntity(way);

                        // End by clicking on own tail
                        return this.controller.exit();
                    } else {
                        // connect a way to an existing way
                        this.history.replace(iD.actions.addWayNode(way, datum, index));
                    }
                } else if (datum.type === 'way') {
                    node = node.update({loc: this.map.mouseCoordinates()});
                    this.history.replace(iD.actions.addWayNode(way, node, index));

                    var connectedWay = this.history.graph().entity(datum.id);
                    var connectedIndex = iD.modes.chooseIndex(datum, d3.mouse(surface.node()), this.map);
                    this.history.perform(iD.actions.addWayNode(connectedWay, node, connectedIndex));
                } else {
                    node = node.update({loc: this.map.mouseCoordinates()});
                    this.history.replace(iD.actions.addWayNode(way, node, index));
                }

                this.controller.enter(iD.modes.DrawRoad(way_id, direction));
            }

            surface.on('mousemove.drawroad', mousemove.bind(this))
                .on('click.drawroad', click.bind(this));

            this.map.keybinding().on('⎋.exit', function() {
                this.controller.exit();
            }.bind(this));
        },

        exit: function() {
            this.map.surface.on('mousemove.drawroad', null)
                .on('click.drawroad', null);
            this.map.keybinding().on('⎋.exit', null);
            window.setTimeout(function() {
                this.map.dblclickEnable(true);
                this.map.dragEnable(true);
            }.bind(this), 1000);
        }
    };
};

iD.modes.AddArea = {
    id: 'add-area',
    title: '+ Area',

    way: function() {
        return iD.Way({
            tags: { building: 'yes', area: 'yes', elastic: 'true' }
        });
    },

    enter: function() {
        this.map.dblclickEnable(false);

        var surface = this.map.surface;

        function click() {
            var datum = d3.select(d3.event.target).datum() || {},
                node, way = this.way();

            // connect a way to an existing way
            if (datum.type === 'node') {
                node = datum;
            } else {
                node = iD.Node({loc: this.map.mouseCoordinates()});
            }

            this.history.perform(iD.actions.startWay(way));
            this.history.perform(iD.actions.addWayNode(way, node));
            this.map.selectEntity(way);
            this.controller.enter(iD.modes.DrawArea(way.id));
        }

        surface.on('click.addarea', click.bind(this));

        this.map.keybinding().on('⎋.exit', function() {
            this.controller.exit();
        }.bind(this));
    },

    exit: function() {
        window.setTimeout(function() {
            this.map.dblclickEnable(true);
        }.bind(this), 1000);
        this.map.surface.on('click.addarea', null);
        this.map.keybinding().on('⎋.exit', null);
    }
};

iD.modes.DrawArea = function(way_id) {
    return {
        enter: function() {
            this.map.dblclickEnable(false);

            var surface = this.map.surface,
                way = this.history.graph().entity(way_id),
                firstnode_id = _.first(way.nodes),
                node = iD.Node({loc: this.map.mouseCoordinates()});

            this.history.perform(iD.actions.addWayNode(way, node));

            function mousemove() {
                this.history.replace(iD.actions.addWayNode(way, node.update({loc: this.map.mouseCoordinates()})));
            }

            function click() {
                d3.event.stopPropagation();

                var datum = d3.select(d3.event.target).datum();

                if (datum.type === 'node') {
                    if (datum.id == firstnode_id) {
                        this.history.replace(iD.actions.addWayNode(way,
                            this.history.graph().entity(way.nodes[0])));

                        delete way.tags.elastic;
                        this.history.perform(iD.actions.changeTags(way, way.tags));

                        // End by clicking on own tail
                        return this.controller.exit();
                    } else {
                        // connect a way to an existing way
                        this.history.replace(iD.actions.addWayNode(way, datum));
                    }
                } else {
                    node = node.update({loc: this.map.mouseCoordinates()});
                    this.history.replace(iD.actions.addWayNode(way, node));
                }

                this.controller.enter(iD.modes.DrawArea(way_id));
            }

            this.map.keybinding().on('⎋.exit', function() {
                this.controller.exit();
            }.bind(this));

            surface.on('click.drawarea', click.bind(this))
                .on('mousemove.drawarea', mousemove.bind(this));
        },

        exit: function() {
            this.map.surface.on('mousemove.drawarea', null)
                .on('click.drawarea', null);
            this.map.keybinding().on('⎋.exit', null);
            window.setTimeout(function() {
                this.map.dblclickEnable(true);
            }.bind(this), 1000);
        }
    };
};

iD.modes.Move = {
    enter: function() { },
    exit: function() { }
};
<|endoftext|>


<commit_before>describe("Airport", function() {
  var plane;
  var airport;

  beforeEach(function() {
    plane = new Plane();
    airport = new Airport();
  });

  it("should be empty to start off with", function() {
    expect(airport.isEmpty).toBe(true);
  });

  it("can instruct a plane to take off", function() {
    airport.hanger.push(plane)
    airport.take_off(plane)
    expect(airport.hanger.length).toEqual(0)
  });

  it("can instruct a plane to land", function() {
    airport.land(plane)
    expect(airport.hanger.length).toEqual(1)
  });

  it("can not land plane when full", function() {
    airport.land(plane)
    airport.land(plane)
    airport.land(plane)
    expect(function() {airport.land(plane);
    }).toThrowError("Airport is full.");
  });

  it(" can not relsease plane when empty", function() {
    expect(function() {airport.take_off(plane);
    }).toThrowError("No planes available.");
  });

  it("should reduce plane in array when plane takes off", function () {
    airport.land(plane);
    airport.land(plane);
    airport.take_off(plane);
    expect(airport.hanger.length).toEqual(1);
  });
});
<commit_msg>changed some test names<commit_after>describe("Airport", function() {
  var plane;
  var airport;

  beforeEach(function() {
    plane = new Plane();
    airport = new Airport();
  });

  it("should be empty to start off with", function() {
    expect(airport.isEmpty).toBe(true);
  });

  it("can instruct a plane to take off", function() {
    airport.hanger.push(plane)
    airport.take_off(plane)
    expect(airport.hanger.length).toEqual(0)
  });

  it("can instruct a plane to land", function() {
    airport.land(plane)
    expect(airport.hanger.length).toEqual(1)
  });

  it("can not land plane when full and returns error", function() {
    airport.land(plane)
    airport.land(plane)
    airport.land(plane)
    expect(function() {airport.land(plane);
    }).toThrowError("Airport is full.");
  });

  it("should return error if relseasing plane when airport is empty", function() {
    expect(function() {airport.take_off(plane);
    }).toThrowError("No planes available.");
  });

  it("should reduce plane in array when plane takes off", function () {
    airport.land(plane);
    airport.land(plane);
    airport.take_off(plane);
    expect(airport.hanger.length).toEqual(1);
  });
});
<|endoftext|>


<commit_before><commit_msg>Autocomplete: We no longer need to remove aria attributes on destroy.<commit_after><|endoftext|>