<commit_before>var Player = require("./player");
var redis = require("redis");
var uuid = require("node-uuid");
var Config = require("./config")

var client;

if (![].contains) {
    Object.defineProperty(Array.prototype, 'contains', {
        enumerable: false,
        configurable: true,
        writable: true,
        value: function(searchElement/*, fromIndex*/) {
            if (this === undefined || this === null) {
                throw new TypeError('Cannot convert this value to object');
            }
            var O = Object(this);
            var len = parseInt(O.length) || 0;
            if (len === 0) { return false; }
            var n = parseInt(arguments[1]) || 0;
            if (n >= len) { return false; }
            var k;
            if (n >= 0) {
                k = n;
            } else {
                k = len + n;
                if (k < 0) k = 0;
            }
            while (k < len) {
                var currentElement = O[k];
                if (searchElement === currentElement ||
                    searchElement !== searchElement && currentElement !== currentElement
                ) {
                    return true;
                }
                k++;
            }
            return false;
        }
    });
}

function initClient()
{
    client = redis.createClient();

    client.on("error", function (err) {
        console.log("Error " + err);
    });
}

function makeSequence(possible, length)
{
    var text = "";

    for(var i=0; i < length; i++)
    {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
}

function checkNear(nearIndexes, guessChar, sequence, startPosition)
{
    var nearIndex = sequence.indexOf(guessChar, startPosition);

    if (nearIndex > -1)
    {
        if (!nearIndexes.contains(nearIndex))
        {
            nearIndexes.push(nearIndex);
            return true;
        }
        else if (nearIndex >= sequence.length)
        {
            return false;
        }
        else
        {
            return checkNear(nearIndexes, guessChar, sequence, ++nearIndex);
        }
    }
    else
    {
        return false;
    }
}

function Game(config) {
    this.gameId = "";
    this.config = config || new Config(["R", "G", "B", "Y"], 6, 10, false);
    this.players = [];
    this.sequence = "";
    this.timestamp = Date.now();
    this.solved = false;
};

Game.prototype.init = function(playerName)
{
    this.players.push(new Player(playerName));

    this.gameId = uuid.v1();
    this.sequence = makeSequence(this.config.colors.join(""), this.config.codeLength);
};

Game.prototype.startTurn = function()
{
    this.players.forEach(
        function (player)
        {
            player.turn = true;
        }
    );
}

Game.prototype.guessCode = function(playerName, sequence)
{
    var exactCount = 0;
    var nearCount = 0;
    var nearIndexes = [];
    for (var i = 0; i < sequence.length; i++)
    {
        var guessChar = sequence.charAt(i);

        var sequenceChar = this.sequence.charAt(i);

        if (guessChar == sequenceChar)
        {
            exactCount++;
        }
        else
        {
            if (checkNear(nearIndexes, guessChar, this.sequence, 0))
            {
                nearCount++;
            }
        }
    }

    this.solved = exactCount == this.sequence.length;

    var player = this.getPlayer(playerName);
    player.addGuess(sequence, exactCount, nearCount);
    player.turn = false;
}

Game.prototype.stats = function()
{

}

Game.prototype.getPlayer = function(playerName)
{
    var ret;
    this.players.forEach(function(player)
    {
        if (player.name == playerName)
        {
            ret = player;
        }
    });

    return ret;
}

Game.prototype.addPlayer = function(playerName)
{
    this.players.push(new Player(playerName));
}

Game.methods = {
    save: function(game)
    {
        initClient();
        var gameHash = "game:" + game.gameId;
        client.set(gameHash, JSON.stringify(game), redis.print);
        client.quit();

    },

    load: function(gameId, callback)
    {
        initClient();
        var gameHash = "game:" + gameId;

        client.get(gameHash, function(err, reply)
            {
                var game;

                if (reply)
                {
                    game = JSON.parse(reply);
                }
                else
                {
                    err = "Not found!";
                }

                callback(err, game);
                client.quit();
            }
        )
    }
};

module.exports = Game;<commit_msg>Game stats for checking if players are eligible for another turn<commit_after>var Player = require("./player");
var redis = require("redis");
var uuid = require("node-uuid");
var Config = require("./config")

var client;

if (![].contains) {
    Object.defineProperty(Array.prototype, 'contains', {
        enumerable: false,
        configurable: true,
        writable: true,
        value: function(searchElement/*, fromIndex*/) {
            if (this === undefined || this === null) {
                throw new TypeError('Cannot convert this value to object');
            }
            var O = Object(this);
            var len = parseInt(O.length) || 0;
            if (len === 0) { return false; }
            var n = parseInt(arguments[1]) || 0;
            if (n >= len) { return false; }
            var k;
            if (n >= 0) {
                k = n;
            } else {
                k = len + n;
                if (k < 0) k = 0;
            }
            while (k < len) {
                var currentElement = O[k];
                if (searchElement === currentElement ||
                    searchElement !== searchElement && currentElement !== currentElement
                ) {
                    return true;
                }
                k++;
            }
            return false;
        }
    });
}

function initClient()
{
    client = redis.createClient();

    client.on("error", function (err) {
        console.log("Error " + err);
    });
}

function makeSequence(possible, length)
{
    var text = "";

    for(var i=0; i < length; i++)
    {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
}

function checkNear(nearIndexes, guessChar, sequence, startPosition)
{
    var nearIndex = sequence.indexOf(guessChar, startPosition);

    if (nearIndex > -1)
    {
        if (!nearIndexes.contains(nearIndex))
        {
            nearIndexes.push(nearIndex);
            return true;
        }
        else if (nearIndex >= sequence.length)
        {
            return false;
        }
        else
        {
            return checkNear(nearIndexes, guessChar, sequence, ++nearIndex);
        }
    }
    else
    {
        return false;
    }
}

function Game(config) {
    this.gameId = "";
    this.config = config || new Config(["R", "G", "B", "Y"], 6, 10, false);
    this.players = [];
    this.sequence = "";
    this.timestamp = Date.now();
    this.solved = false;
};

Game.prototype.init = function(playerName)
{
    this.players.push(new Player(playerName));

    this.gameId = uuid.v1();
    this.sequence = makeSequence(this.config.colors.join(""), this.config.codeLength);
};

Game.prototype.startTurn = function()
{
    this.players.forEach(
        function (player)
        {
            player.turn = true;
        }
    );
}

Game.prototype.guessCode = function(playerName, sequence)
{
    var exactCount = 0;
    var nearCount = 0;
    var nearIndexes = [];
    for (var i = 0; i < sequence.length; i++)
    {
        var guessChar = sequence.charAt(i);

        var sequenceChar = this.sequence.charAt(i);

        if (guessChar == sequenceChar)
        {
            exactCount++;
        }
        else
        {
            if (checkNear(nearIndexes, guessChar, this.sequence, 0))
            {
                nearCount++;
            }
        }
    }

    this.solved = exactCount == this.sequence.length;

    var player = this.getPlayer(playerName);
    player.addGuess(sequence, exactCount, nearCount);
    player.turn = false;
}

Game.prototype.stats = function()
{
    var ret = true;
    this.players.forEach(function(player)
    {
        ret = ret && !player.turn;
    });

    return ret;
}

Game.prototype.getPlayer = function(playerName)
{
    var ret;
    this.players.forEach(function(player)
    {
        if (player.name == playerName)
        {
            ret = player;
        }
    });

    return ret;
}

Game.prototype.addPlayer = function(playerName)
{
    this.players.push(new Player(playerName));
}

Game.methods = {
    save: function(game)
    {
        initClient();
        var gameHash = "game:" + game.gameId;
        client.set(gameHash, JSON.stringify(game), redis.print);
        client.quit();

    },

    load: function(gameId, callback)
    {
        initClient();
        var gameHash = "game:" + gameId;

        client.get(gameHash, function(err, reply)
            {
                var game;

                if (reply)
                {
                    game = JSON.parse(reply);
                }
                else
                {
                    err = "Not found!";
                }

                callback(err, game);
                client.quit();
            }
        )
    }
};

module.exports = Game;<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema..Types.ObjectId;

var NoteScheam = new Schema(
	user_id: { type: ObjectId },
	title: { type: String },
	body: { type: String },
	word_count: { type: Number, default: 0 },
	changes_count: { type: Number, default: 0 },
	publish: { type: Boolean, default: false },
	created_at: { type: Date, default: Date.now },
	updated_at: { type: Date, default: Date.now }
);

NoteSchema.index({ user_id: 1, created_at: -1 });

mongoose.model('Note', NoteSchema);<commit_msg>Typo fixes.<commit_after>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var NoteScheam = new Schema(
	user_id: { type: ObjectId },
	title: { type: String },
	body: { type: String },
	word_count: { type: Number, default: 0 },
	changes_count: { type: Number, default: 0 },
	publish: { type: Boolean, default: false },
	created_at: { type: Date, default: Date.now },
	updated_at: { type: Date, default: Date.now }
);

NoteSchema.index({ user_id: 1, created_at: -1 });

mongoose.model('Note', NoteSchema);<|endoftext|>


<commit_before>test
<commit_msg>done testing<commit_after><|endoftext|>


<commit_before>'use strict';

/*
 * Simple wrapper for the PHP action API
 */

var rbUtil = require('../lib/rbUtil');

function ActionService (options) {
    this.apiURITemplate = options.apiURI;
}

ActionService.prototype.apiURI = function(domain) {
    // TODO: use proper templating
    return this.apiURITemplate.replace(/\{domain\}/, domain);
};

function buildQueryResponse(res) {
    if (res.status !== 200) {
        throw rbUtil.httpErrors.server('Unexpected response status (' + res.status + ') from the PHP action API.');
    } else if (!res.body || !res.body.query || !res.body.query.pages) {
        throw rbUtil.httpErrors.server('Missing query pages from the PHP action API response.');
    } else {
        // Rewrite res.body
        // XXX: Rethink!
        var pages = res.body.query.pages;
        var newBody = Object.keys(pages).map(function(key) {
            return pages[key];
        });
        // XXX: Clean this up!
        res.body = {
            items: newBody,
            next: res.body["query-continue"]
        };
        return res;
    }
}

function buildEditResponse(res) {
    if (res.status !== 200) {
        throw rbUtil.httpErrors.server('Unexpected response status (' + res.status + ') from the PHP action API.');
    } else if (!res.body || res.body.error) {
        throw rbUtil.httpErrors.server('Bad return');
    }
    res.body = undefined;
    res.status = 201;
    return res;
}

ActionService.prototype._doRequest = function(restbase, req, defBody, cont) {
    var rp = req.params;
    req.uri = this.apiURI(rp.domain);
    var body = req.body;
    body.action = defBody.action;
    body.format = body.format || defBody.format || 'json';
    body.formatversion = body.formatversion || defBody.formatversion || 1;
    req.method = 'post';
    return restbase[req.method](req).then(cont);
}

ActionService.prototype.query = function(restbase, req) {
    return this._doRequest(restbase, req, {
        action: 'query',
        format: 'json'
    }, buildQueryResponse);
};

ActionService.prototype.edit = function(restbase, req) {
    return this._doRequest(restbase, req, {
        action: 'edit',
        format: 'json',
        formatversion: 2
    }, buildEditResponse);
};

module.exports = function (options) {
    var actionService = new ActionService(options);
    return {
        spec: {
            paths: {
                '/query': {
                    all: {
                        operationId: 'mwApiQuery'
                    }
                },
                '/edit': {
                    post: {
                        operationId: 'mwApiEdit'
                    }
                }
            }
        },
        operations: {
            mwApiQuery: actionService.query.bind(actionService),
            mwApiEdit: actionService.edit.bind(actionService)
        }
    };
};
<commit_msg>Classify MW API error responses and turn them into HTTPError responses<commit_after>'use strict';

/*
 * Simple wrapper for the PHP action API
 */

var rbUtil = require('../lib/rbUtil');

function ActionService (options) {
    this.apiURITemplate = options.apiURI;
}

ActionService.prototype.apiURI = function(domain) {
    // TODO: use proper templating
    return this.apiURITemplate.replace(/\{domain\}/, domain);
};

function apiError(apiErr) {
    var ret;
    apiErr = apiErr || {};
    ret = {
        status: 500,
        body: {
            type: 'server_error',
            title: apiErr.code || 'MW API Error',
            description: apiErr.info || 'Unknown MW API error'
        }
    };
    if(!apiErr.code) {
        return new rbUtil.HTTPError(ret);
    }
    switch(apiErr.code) {
        /* 400 - bad request */
        case 'articleexists':
        case 'badformat':
        case 'badmd5':
        case 'badtoken':
        case 'invalidparammix':
        case 'invalidsection':
        case 'invalidtitle':
        case 'invaliduser':
        case 'missingparam':
        case 'missingtitle':
        case 'nosuchpageid':
        case 'nosuchrcid':
        case 'nosuchrevid':
        case 'nosuchsection':
        case 'nosuchuser':
        case 'notext':
        case 'notitle':
        case 'pagecannotexist':
        case 'revwrongpage':
            ret.status = 400;
            ret.body.type = 'invalid_request';
            break;
        /* 401 - unauthorised */
        case 'cantcreate-anon':
        case 'confirmemail':
        case 'noedit-anon':
        case 'noimageredirect-anon':
        case 'protectedpage':
        case 'readapidenied':
            ret.status = 401;
            ret.body.type = 'unauthorized';
            break;
        /* 403 - access denied */
        case 'autoblocked':
        case 'blocked':
        case 'cantcreate':
        case 'customcssjsprotected':
        case 'customcssprotected':
        case 'customjsprotected':
        case 'emptynewsection':
        case 'emptypage':
        case 'noedit':
        case 'noimageredirect':
        case 'permissiondenied':
        case 'protectednamespace':
        case 'protectednamespace-interface':
        case 'protectedtitle':
        case 'readonly':
        case 'writeapidenied':
            ret.status = 403;
            ret.body.type = 'access_denied#edit';
            break;
        /* 409 - conflict */
        case 'cascadeprotected':
        case 'editconflict':
        case 'pagedeleted':
        case 'spamdetected':
            ret.status = 409;
            ret.body.type = 'conflict';
            break;
        /* 412 - precondition failed */
        case 'filtered':
        case 'hookaborted':
        case 'unsupportednamespace':
            ret.status = 412;
            ret.body.type = 'precondition_fail';
            break;
        /* 413 - body too large */
        case 'contenttoobig':
            ret.status = 413;
            ret.body.type = 'too_large';
            break;
        /* 429 - rate limit exceeded */
        case 'ratelimited':
            ret.status = 429;
            ret.body.type = 'rate_exceeded';
            break;
        /* 501 - not supported */
        case 'editnotsupported':
            ret.status = 501;
            ret.body.type = 'not_supported';
            break;
    }
    return new rbUtil.HTTPError(ret);
}

function buildQueryResponse(res) {
    if (res.status !== 200) {
        throw rbUtil.httpErrors.server('Unexpected response status (' + res.status + ') from the PHP action API.');
    } else if(!res.body || res.body.error) {
        throw apiError((res.body || {}).error);
    } else if (!res.body.query || !res.body.query.pages) {
        throw rbUtil.httpErrors.server('Missing query pages from the PHP action API response.');
    } else {
        // Rewrite res.body
        // XXX: Rethink!
        var pages = res.body.query.pages;
        var newBody = Object.keys(pages).map(function(key) {
            return pages[key];
        });
        // XXX: Clean this up!
        res.body = {
            items: newBody,
            next: res.body["query-continue"]
        };
        return res;
    }
}

function buildEditResponse(res) {
    if (res.status !== 200) {
        throw apiError({info: 'Unexpected response status (' + res.status + ') from the PHP action API.'});
    } else if (!res.body || res.body.error) {
        throw apiError((res.body || {}).error);
    }
    res.body = undefined;
    res.status = 201;
    return res;
}

ActionService.prototype._doRequest = function(restbase, req, defBody, cont) {
    var rp = req.params;
    req.uri = this.apiURI(rp.domain);
    var body = req.body;
    body.action = defBody.action;
    body.format = body.format || defBody.format || 'json';
    body.formatversion = body.formatversion || defBody.formatversion || 1;
    req.method = 'post';
    return restbase[req.method](req).then(cont);
}

ActionService.prototype.query = function(restbase, req) {
    return this._doRequest(restbase, req, {
        action: 'query',
        format: 'json'
    }, buildQueryResponse);
};

ActionService.prototype.edit = function(restbase, req) {
    return this._doRequest(restbase, req, {
        action: 'edit',
        format: 'json',
        formatversion: 2
    }, buildEditResponse);
};

module.exports = function (options) {
    var actionService = new ActionService(options);
    return {
        spec: {
            paths: {
                '/query': {
                    all: {
                        operationId: 'mwApiQuery'
                    }
                },
                '/edit': {
                    post: {
                        operationId: 'mwApiEdit'
                    }
                }
            }
        },
        operations: {
            mwApiQuery: actionService.query.bind(actionService),
            mwApiEdit: actionService.edit.bind(actionService)
        }
    };
};
<|endoftext|>


<commit_before>/**
 *
 * @para {Client} client - The discord.js client.
 *
 */

module.exports = function (client) {
  client.on('message', message => {
    var h = message.author.lastMessage.createdAt
    var nom = message.author.username
    if (message.content === '+help') {
      return message.channel.sendMessage('', {embed: {
        title: 'Commandes:',
        color: 0xff0000,
        description: ':tools: Liste des commandes :tools: \n\n**C\'est quoi mon avatar** : Pour avoir son avatar \n\n**+admin** : Pour savoir si tu as le role Anti-Modo \n\n**+modo** : Pour savoir si tu as le role Modo \n\n**Mentionne moi** : Le bot te mentionneras comme sa tu auras un ami :heart: \n\n**ping/PING/Ping/PONG** : <mystere> \n\n**Diego** : Dedicace aux :100: \n\n**Freez** : Dedicace aux :100: \n\n**Golden** : Dedicace aux :100: \n\n**c pas moi** : te réferencer aux #commandes-comabot pour savoir tout sur cela \n\nD\'autre commandes sont en dévelopement...',
        footer: {
          text: 'Message par ComaBot.'
        }
      }}).catch(console.log(h + ' "help" mis par: ' + nom))
    }
  })
}
<commit_msg>Added Files<commit_after>/**
 *
 * @para {Client} client - The discord.js client.
 *
 */

module.exports = function (client) {
  client.on('message', message => {
    var h = message.author.lastMessage.createdAt
    var nom = message.author.username
    if (message.content === '+help') {
      return message.channel.sendMessage('', {embed: {
        title: 'Commandes:',
        color: 0xff0000,
        description: ':tools: **COMMANDES** :tools:```\n\nCommandes Admin: +help admin \n\nCommandes Fun: +help fun \n\nCommandes Randoms: +help rdm```',
        footer: {
          text: 'Message par ComaBot.'
        }
      }}).catch(console.log(h + ' "help" mis par: ' + nom))
    }
    if (message.content === '+help admin') {
      return message.channel.sendMessage('', {embed: {
        title: 'Commandes:',
        color: 0xff0000,
        description: ':tools: Liste des commandes :tools: \n\n+ban [@(*343535365363*) | Pour ban un membre en ayant le rôle **Mod**\n\n+kick [@(*343535365363*) | Pour kick un membre en ayant le rôle **Mod**\n\nD\'autre commandes sont en dévelopement...',
        footer: {
          text: 'Message par ComaBot.'
        }
      }}).catch(console.log(h + ' "help admin" mis par: ' + nom))
    }
    if (message.content === '+help fun') {
      return message.channel.sendMessage('', {embed: {
        title: 'Commandes:',
        color: 0xff0000,
        description: ':tools: Liste des commandes :tools: \n\n**C\'est quoi mon avatar** : Cela te permet d\'avoir l\'url de ton avatar discord\n\n**ping/PING/Ping/PONG** : <mystere> \n\n**Mentionne moi** : Le bot te mentionneras comme sa tu auras un ami :heart:\n\nD\'autre commandes sont en dévelopement...',
        footer: {
          text: 'Message par ComaBot.'
        }
      }}).catch(console.log(h + ' "help fun" mis par: ' + nom))
    }
    if (message.content === '+help rdm') {
      return message.channel.sendMessage('', {embed: {
        title: 'Commandes:',
        color: 0xff0000,
        description: ':tools: Liste des commandes :tools: \n\n**Les commandes sont en développement...',
        footer: {
          text: 'Message par ComaBot.'
        }
      }}).catch(console.log(h + ' "help rdm" mis par: ' + nom))
    }
  })
}
<|endoftext|>


<commit_before>'use strict';

(function(module) {

  function MyProject (proj) {
    for (let keys in proj) {
      this[keys] = proj[keys]
    }
    //this.name = proj.name;
    //this.filepath = proj.filepath;
    //this.description = proj.description;
    //this.languages = proj.languages;
  }

  MyProject.allProjects = [];

  MyProject.prototype.toHtml = function() {
    var htmlTemplate = $('#template').html();
    var template = Handlebars.compile(htmlTemplate);
    return template(this);
  };

  MyProject.loadAll = function(project) {
    //MyProject.allProjects = proj.map(function(ele) {
      //return new MyProject(ele)
    //});
  //}
    project.forEach(function(currentProj) {
      MyProject.allProjects.push(new MyProject(currentProj));
      return MyProject.allProjects.map(function (currentnewProj) {
        return currentnewProj.name
      })
    });
  }

  MyProject.getAll = function() {
    if (localStorage.projects) {
      var lStorageMyProjects = JSON.parse(localStorage.getItem('projects'));
      MyProject.loadAll(lStorageMyProjects)
    } else {
      $.getJSON('./data/projects.json').then(
        function(data) {
          localStorage.setItem('projects', JSON.stringify(data))
          MyProject.loadAll(data);
        }
      );
    }
  };

  MyProject.getAll();
  module.MyProject = MyProject;
  //MyProject.loadAll();
  //MyProject.allProjects.forEach(function(project) {
    //$('#Projects').append(project.toHtml());
})(window);
<commit_msg>.map seems to be working<commit_after>'use strict';

(function(module) {

  function MyProject (proj) {
    for (let keys in proj) {
      this[keys] = proj[keys]
    }
    //this.name = proj.name;
    //this.filepath = proj.filepath;
    //this.description = proj.description;
    //this.languages = proj.languages;
  }

  MyProject.allProjects = [];

  MyProject.prototype.toHtml = function() {
    var htmlTemplate = $('#template').html();
    var template = Handlebars.compile(htmlTemplate);
    return template(this);
  };

  MyProject.loadAll = function(project) {
    project.map(function(ele) {
      MyProject.allProjects.push(new MyProject(ele))
    });
  //}
    //project.forEach(function(currentProj) {
    //  MyProject.allProjects.push(new MyProject(currentProj));
  //    var namesOnly = MyProject.allProjects.map(function (currentnewProj) {
  //      return currentnewProj.name;
  //    })
  //    console.log(namesOnly)
    //});
  }

  MyProject.getAll = function() {
    if (localStorage.projects) {
      var lStorageMyProjects = JSON.parse(localStorage.getItem('projects'));
      MyProject.loadAll(lStorageMyProjects)
    } else {
      $.getJSON('./data/projects.json').then(
        function(data) {
          localStorage.setItem('projects', JSON.stringify(data))
          MyProject.loadAll(data);
        }
      );
    }
  };

  MyProject.getAll();
  module.MyProject = MyProject;
  //MyProject.loadAll();
  //MyProject.allProjects.forEach(function(project) {
    //$('#Projects').append(project.toHtml());
})(window);
<|endoftext|>


<commit_before>module("ID Changes", {
    setup : function() {
        stop();
        var that = this;
        this.cb = function(e) {
            ok(true, "Scene loaded");
            that.doc = document.getElementById("xml3dframe").contentDocument;
            start();
        };
        loadDocument("scenes/id-changes.xhtml"+window.location.search, this.cb);
    },
    teardown : function() {
        var v = document.getElementById("xml3dframe");
        v.removeEventListener("load", this.cb, true);
    }
});

test("Shader ID changes", function() {
    var xTest = this.doc.getElementById("xml3dTest"),
        glTest = getContextForXml3DElement(xTest), hTest = getHandler(xTest);
    var self = this;

    hTest.draw();

    var upperLeft = XML3DUnit.getPixelValue(glTest, 64, 200);
    var upperRight = XML3DUnit.getPixelValue(glTest, 164, 200);
    var lowerLeft = XML3DUnit.getPixelValue(glTest, 64, 128);
    var lowerRight = XML3DUnit.getPixelValue(glTest, 164, 128);

    deepEqual(upperLeft, [0,0,0,255] , "Upper left rectangle is black");
    deepEqual(upperRight, [255,0,0,255] , "Upper right rectangle is red");
    deepEqual(lowerLeft, [0,0,255,255] , "Lower left rectangle is blue");
    deepEqual(lowerRight, [255,0,0,255] , "Lower right rectangle is red");

    // ---------------------------------------------------------------------

    // change id of #green shader to #green42
    this.doc.getElementById("green").id = "green42";
    hTest.draw();
    ok(true, "Changed id of green shader");

    upperRight = XML3DUnit.getPixelValue(glTest, 164, 200);
    deepEqual(upperRight, [0,255,0,255] , "Upper right rectangle is green");

    // ---------------------------------------------------------------------

    // change id of #black shader to #black23
    this.doc.getElementById("black").id = "black23";
    hTest.draw();
    ok(true, "Changed id of black shader");

    upperLeft = XML3DUnit.getPixelValue(glTest, 64, 200);
    deepEqual(upperLeft, [255,0,0,255] , "Upper left rectangle is red");

    // ---------------------------------------------------------------------

    var newShader = this.doc.createElementNS(XML3D.xml3dNS,"shader");
    var color = this.doc.createElementNS(XML3D.xml3dNS, "float3");
    color.name = "diffuseColor";
    color.textContent = "1 0 1";
    newShader.appendChild(color);
    newShader.script = "urn:xml3d:shader:flat";
    newShader.id = "notThere";
    this.doc.getElementsByTagName("defs")[0].appendChild(newShader);
    hTest.draw();
    ok(true, "Add a new shader of id #notThere");

    lowerRight = XML3DUnit.getPixelValue(glTest, 164, 128);
    deepEqual(lowerRight, [255,0,255,255] , "Lower right rectangle is pink");

});

<commit_msg>Small enhancement in id changes test module.<commit_after>module("ID Changes", {
    setup : function() {
        stop();
        var that = this;
        this.cb = function(e) {
            ok(true, "Scene loaded");
            that.doc = document.getElementById("xml3dframe").contentDocument;
            start();
        };
        loadDocument("scenes/id-changes.xhtml"+window.location.search, this.cb);
    },
    teardown : function() {
        var v = document.getElementById("xml3dframe");
        v.removeEventListener("load", this.cb, true);
    }
});

test("Shader ID changes", function() {
    var xTest = this.doc.getElementById("xml3dTest"),
        glTest = getContextForXml3DElement(xTest), hTest = getHandler(xTest);
    var self = this;

    hTest.draw();

    var upperLeft = XML3DUnit.getPixelValue(glTest, 64, 200);
    var upperRight = XML3DUnit.getPixelValue(glTest, 164, 200);
    var lowerLeft = XML3DUnit.getPixelValue(glTest, 64, 128);
    var lowerRight = XML3DUnit.getPixelValue(glTest, 164, 128);

    deepEqual(upperLeft, [0,0,0,255] , "Upper left rectangle is black");
    deepEqual(upperRight, [255,0,0,255] , "Upper right rectangle is red");
    deepEqual(lowerLeft, [0,0,255,255] , "Lower left rectangle is blue");
    deepEqual(lowerRight, [255,0,0,255] , "Lower right rectangle is red");

    // ---------------------------------------------------------------------

    // change id of #green shader to #green42
    this.doc.getElementById("green").id = "green42";
    hTest.draw();
    ok(true, "Changed id of green shader");

    upperRight = XML3DUnit.getPixelValue(glTest, 164, 200);
    deepEqual(upperRight, [0,255,0,255] , "Upper right rectangle is green");

    // ---------------------------------------------------------------------

    // change id of #black shader to #black23
    this.doc.getElementById("black").id = "black23";
    hTest.draw();
    ok(true, "Changed id of black shader");

    upperLeft = XML3DUnit.getPixelValue(glTest, 64, 200);
    deepEqual(upperLeft, [255,0,0,255] , "Upper left rectangle is red");

    // ---------------------------------------------------------------------

    var newShader = this.doc.createElementNS(XML3D.xml3dNS,"shader");
    var color = this.doc.createElementNS(XML3D.xml3dNS, "float3");
    color.name = "diffuseColor";
    color.textContent = "1 0 1";
    newShader.appendChild(color);
    newShader.id = "notThere";
    newShader.script = "urn:xml3d:shader:flat";
    this.doc.getElementsByTagName("defs")[0].appendChild(newShader);
    hTest.draw();
    ok(true, "Add a new shader of id #notThere");

    lowerRight = XML3DUnit.getPixelValue(glTest, 164, 128);
    deepEqual(lowerRight, [255,0,255,255] , "Lower right rectangle is pink");

});

<|endoftext|>


<commit_before>"use strict"

var settings = require('../config').settings;
var md5 = require('MD5');

exports.module = function() {
	this.onCommand_md5 = function(nick, args) {
		if(args.trim() != "") {
			this.channel.say(md5(args));
		} else {
			this.channel.say("You're doing it wrong.\nUsage: " + settings.defaultCommandTrigger + "md5 <Message>");
		}
	}
}
<commit_msg>Delete md5.js<commit_after><|endoftext|>


<commit_before>'use strict';

const errno = require('errno');
const _gai = require('_gai');
const _socket = require('_socket');
const outil = require('objectutil');

function Socket(domain, type, options) {
    var options = options || {};

    if (options.fd !== undefined && options.fd > -1) {
        this._fd = options.fd;
    } else {
        this._fd = _socket.socket(domain, type);
    }

    this._domain = domain;
    this._type = type;

    this._nonblock = !!options.nonBlocking;
    if (this._nonblock) {
        try {
            _socket.set_nonblocking(this._fd, this._nonblock);
        } catch (e) {
            this.close();
            throw e;
        }
    }

    // set finalizer
    outil.finalizer(this, socketDealloc);

    Object.defineProperty(this, 'fd', {
        get: function() {
            return this._fd;
        }
    });
}

Socket.prototype.accept = function() {
    checkSocket.call(this);
    var fd = _socket.accept(this._fd);
    var options = {fd: fd, nonBlocking: this._nonblock};
    return new Socket(this._domain, this._type, options);
}

Socket.prototype.bind = function(address) {
    checkSocket.call(this);
    _socket.bind(this._fd, normalizeAddress(this._domain, address));
}

Socket.prototype.close = function() {
    if (this._fd !== -1) {
        _socket.close(this._fd);
        this._fd = -1;
    }
}

Socket.prototype.connect = function(address) {
    checkSocket.call(this);
    _socket.connect(this._fd, normalizeAddress(this._domain, address));
}

Socket.prototype.getsockname = function() {
    checkSocket.call(this);
    return _socket.getsockname(this._fd);
}

Socket.prototype.getpeername = function() {
    checkSocket.call(this);
    return _socket.getpeername(this._fd);
}

Socket.prototype.listen = function(backlog) {
    checkSocket.call(this);
    var backlog = (backlog >>> 0) || 128;
    _socket.listen(this._fd, backlog);
}

Socket.prototype.recv = function(nrecv) {
    checkSocket.call(this);
    if (nrecv === undefined || typeof nrecv === 'number') {
        nrecv = (nrecv >>> 0) || 4096;
    }
    // we will validate if the passed argument is a buffer in C
    return _socket.recv(this._fd, nrecv);
}

Socket.prototype.send = function(data) {
    checkSocket.call(this);
    return _socket.send(this._fd, data);
}

Socket.prototype.recvfrom = function(nrecv) {
    checkSocket.call(this);
    if (nrecv === undefined || typeof nrecv === 'number') {
        nrecv = (nrecv >>> 0) || 4096;
    }
    // we will validate if the passed argument is a buffer in C
    return _socket.recvfrom(this._fd, nrecv);
}

Socket.prototype.sendto = function(data, address) {
    checkSocket.call(this);
    return _socket.sendto(this._fd, data, normalizeAddress(this._domain, address));
}

Socket.prototype.shutdown = function(how) {
    checkSocket.call(this);
    _socket.shutdown(this._fd, how);
}

Socket.prototype.setNonBlocking = function(set) {
    checkSocket.call(this);
    _socket.set_nonblocking(this._fd, !!set);
}

Socket.prototype.setsockopt = function(level, option, value) {
    checkSocket.call(this);
    if (typeof value === 'boolean') {
        // convert to integer
        value = +value;
    }
    _socket.setsockopt(this._fd, level, option, value);
}

Socket.prototype.getsockopt = function(level, option, size) {
    checkSocket.call(this);
    return _socket.getsockopt(this._fd, level, option, size);
}

function getaddrinfo(hostname, servname, hints) {
    var hints = hints || {};
    return _gai.getaddrinfo(hostname, servname, hints);
}

function socketpair(domain, type, options) {
    var options = options || {};
    var fds = _socket.socketpair(domain, type);
    var sock1, sock2;
    sock1 = new Socket(domain, type, {fd: fds[0], nonBlocking: !!options.nonBlocking});
    try {
        sock2 = new Socket(domain, type, {fd: fds[1], nonBlocking: !!options.nonBlocking});
    } catch (e) {
        sock1.close();
        throw e;
    }
    return [sock1, sock2];
}

function isIPv4(address) {
    return _socket.inet_pton(_socket.c.AF_INET, address) !== undefined;
}

function isIPv6(address) {
    return _socket.inet_pton(_socket.c.AF_INET6, address) !== undefined;
}

function isIP(address) {
    if (isIPv4(address)) {
        return 4;
    } else if (isIPv6(address)) {
        return 6;
    } else {
        return 0;
    }
}

// - helpers

// finalizer: will get called when a Socket is garbage collected
function socketDealloc(sock) {
    if (sock._fd !== -1) {
        _socket.close(sock._fd);
    }
}

function checkSocket() {
    if (this._fd === -1) {
        const e = new Error('[Errno ' + errno.EBADF + '] ' + errno.strerror(errno.EBADF));
        e.errno = errno.EBADF;
        throw e;
    }
}

function normalizeAddress(domain, address) {
    var addr = address || {};

    if (domain === _socket.c.AF_UNIX) {
        if (typeof addr === 'string') {
            return {domain: _socket.c.AF_UNIX, path: addr};
        } else {
            throw new TypeError('invalid address');
        }
    } else {
        if (typeof addr !== 'object') {
            throw new TypeError('invalid address');
        }

        if (!addr.host) {
            addr.host = domain === _socket.c.AF_INET6 ? '::' : '0.0.0.0';
        }

        var iptype = isIP(addr.host);
        if (iptype === 0) {
            throw new Error('invalid IP address: ' + addr.host);
        } else if (iptype === 4) {
            addr.domain = _socket.c.AF_INET;
            addr.port = addr.port >>> 0;
        } else {
            addr.domain = _socket.c.AF_INET6;
            addr.port = addr.port >>> 0;
            addr.flowinfo = addr.flowinfo >>> 0;
            addr.scopeid = addr.scopeid >>> 0;
        }

        return addr;
    }
}

exports.Socket        = Socket;
exports.socketpair    = socketpair;
exports.getaddrinfo   = getaddrinfo;
exports.gai_strerror  = _gai.gai_strerror;
exports.gai_error_map = new Map();
exports.isIP          = isIP;
exports.isIPv4        = isIPv4;
exports.isIPv6        = isIPv6;

// extract constants
for (var k in _gai.c) {
    var val = _gai.c[k];
    exports[k] = val;
    exports.gai_error_map.set(val, k);
}
for (var k in _socket.c) {
    exports[k] = _socket.c[k];
}
<commit_msg>misc: simplified statements<commit_after>'use strict';

const errno = require('errno');
const _gai = require('_gai');
const _socket = require('_socket');
const outil = require('objectutil');

function Socket(domain, type, options) {
    var options = options || {};

    if (options.fd !== undefined && options.fd > -1) {
        this._fd = options.fd;
    } else {
        this._fd = _socket.socket(domain, type);
    }

    this._domain = domain;
    this._type = type;

    this._nonblock = !!options.nonBlocking;
    if (this._nonblock) {
        try {
            _socket.set_nonblocking(this._fd, this._nonblock);
        } catch (e) {
            this.close();
            throw e;
        }
    }

    // set finalizer
    outil.finalizer(this, socketDealloc);

    Object.defineProperty(this, 'fd', {
        get: function() {
            return this._fd;
        }
    });
}

Socket.prototype.accept = function() {
    checkSocket.call(this);
    var fd = _socket.accept(this._fd);
    var options = {fd: fd, nonBlocking: this._nonblock};
    return new Socket(this._domain, this._type, options);
}

Socket.prototype.bind = function(address) {
    checkSocket.call(this);
    _socket.bind(this._fd, normalizeAddress(this._domain, address));
}

Socket.prototype.close = function() {
    if (this._fd !== -1) {
        _socket.close(this._fd);
        this._fd = -1;
    }
}

Socket.prototype.connect = function(address) {
    checkSocket.call(this);
    _socket.connect(this._fd, normalizeAddress(this._domain, address));
}

Socket.prototype.getsockname = function() {
    checkSocket.call(this);
    return _socket.getsockname(this._fd);
}

Socket.prototype.getpeername = function() {
    checkSocket.call(this);
    return _socket.getpeername(this._fd);
}

Socket.prototype.listen = function(backlog) {
    checkSocket.call(this);
    var backlog = (backlog >>> 0) || 128;
    _socket.listen(this._fd, backlog);
}

Socket.prototype.recv = function(nrecv) {
    checkSocket.call(this);
    if (nrecv === undefined || typeof nrecv === 'number') {
        nrecv = (nrecv >>> 0) || 4096;
    }
    // we will validate if the passed argument is a buffer in C
    return _socket.recv(this._fd, nrecv);
}

Socket.prototype.send = function(data) {
    checkSocket.call(this);
    return _socket.send(this._fd, data);
}

Socket.prototype.recvfrom = function(nrecv) {
    checkSocket.call(this);
    if (nrecv === undefined || typeof nrecv === 'number') {
        nrecv = (nrecv >>> 0) || 4096;
    }
    // we will validate if the passed argument is a buffer in C
    return _socket.recvfrom(this._fd, nrecv);
}

Socket.prototype.sendto = function(data, address) {
    checkSocket.call(this);
    return _socket.sendto(this._fd, data, normalizeAddress(this._domain, address));
}

Socket.prototype.shutdown = function(how) {
    checkSocket.call(this);
    _socket.shutdown(this._fd, how);
}

Socket.prototype.setNonBlocking = function(set) {
    checkSocket.call(this);
    _socket.set_nonblocking(this._fd, !!set);
}

Socket.prototype.setsockopt = function(level, option, value) {
    checkSocket.call(this);
    if (typeof value === 'boolean') {
        // convert to integer
        value = +value;
    }
    _socket.setsockopt(this._fd, level, option, value);
}

Socket.prototype.getsockopt = function(level, option, size) {
    checkSocket.call(this);
    return _socket.getsockopt(this._fd, level, option, size);
}

function getaddrinfo(hostname, servname, hints) {
    var hints = hints || {};
    return _gai.getaddrinfo(hostname, servname, hints);
}

function socketpair(domain, type, options) {
    var options = options || {};
    var fds = _socket.socketpair(domain, type);
    var sock1, sock2;
    sock1 = new Socket(domain, type, {fd: fds[0], nonBlocking: !!options.nonBlocking});
    try {
        sock2 = new Socket(domain, type, {fd: fds[1], nonBlocking: !!options.nonBlocking});
    } catch (e) {
        sock1.close();
        throw e;
    }
    return [sock1, sock2];
}

function isIPv4(address) {
    return _socket.inet_pton(_socket.c.AF_INET, address) !== undefined;
}

function isIPv6(address) {
    return _socket.inet_pton(_socket.c.AF_INET6, address) !== undefined;
}

function isIP(address) {
    if (isIPv4(address)) {
        return 4;
    } else if (isIPv6(address)) {
        return 6;
    } else {
        return 0;
    }
}

// - helpers

// finalizer: will get called when a Socket is garbage collected
function socketDealloc(sock) {
    if (sock._fd !== -1) {
        _socket.close(sock._fd);
    }
}

function checkSocket() {
    if (this._fd === -1) {
        const e = new Error('[Errno ' + errno.EBADF + '] ' + errno.strerror(errno.EBADF));
        e.errno = errno.EBADF;
        throw e;
    }
}

function normalizeAddress(domain, address) {
    var addr = address || {};

    if (domain === _socket.c.AF_UNIX) {
        if (typeof addr === 'string') {
            return {domain: _socket.c.AF_UNIX, path: addr};
        } else {
            throw new TypeError('invalid address');
        }
    } else {
        if (typeof addr !== 'object') {
            throw new TypeError('invalid address');
        }

        if (!addr.host) {
            addr.host = domain === _socket.c.AF_INET6 ? '::' : '0.0.0.0';
        }

        var iptype = isIP(addr.host);
        if (iptype === 0) {
            throw new Error('invalid IP address: ' + addr.host);
        } else if (iptype === 4) {
            addr.domain = _socket.c.AF_INET;
            addr.port >>>= 0;
        } else {
            addr.domain = _socket.c.AF_INET6;
            addr.port >>>= 0;
            addr.flowinfo >>>= 0;
            addr.scopeid >>>= 0;
        }

        return addr;
    }
}

exports.Socket        = Socket;
exports.socketpair    = socketpair;
exports.getaddrinfo   = getaddrinfo;
exports.gai_strerror  = _gai.gai_strerror;
exports.gai_error_map = new Map();
exports.isIP          = isIP;
exports.isIPv4        = isIPv4;
exports.isIPv6        = isIPv6;

// extract constants
for (var k in _gai.c) {
    var val = _gai.c[k];
    exports[k] = val;
    exports.gai_error_map.set(val, k);
}
for (var k in _socket.c) {
    exports[k] = _socket.c[k];
}
<|endoftext|>


<commit_before>const UNICODE_ESCAPE_PATTERN = /\\u([0-9a-f]{4})/gi;

function alias(rule, value) {
  const result = {
    type: "ALIAS",
    content: normalize(rule),
    named: false,
    value: null
  };

  switch (value.constructor) {
    case String:
      result.named = false;
      result.value = value;
      return result;
    case ReferenceError:
      result.named = true;
      result.value = value.symbol.name;
      return result;
    case Object:
      if (typeof value.type === 'string' && value.type === 'SYMBOL') {
        result.named = true;
        result.value = value.name;
        return result;
      }
  }

  throw new Error('Invalid alias value ' + value);
}

function blank() {
  return {
    type: "BLANK"
  };
}

function choice(...elements) {
  return {
    type: "CHOICE",
    members: elements.map(normalize)
  };
}

function optional(value) {
  return choice(value, blank());
}

function prec(number, rule) {
  if (rule == null) {
    rule = number;
    number = 0;
  }

  return {
    type: "PREC",
    value: number,
    content: normalize(rule)
  };
}

prec.left = function(number, rule) {
  if (rule == null) {
    rule = number;
    number = 0;
  }

  return {
    type: "PREC_LEFT",
    value: number,
    content: normalize(rule)
  };
}

prec.right = function(number, rule) {
  if (rule == null) {
    rule = number;
    number = 0;
  }

  return {
    type: "PREC_RIGHT",
    value: number,
    content: normalize(rule)
  };
}

prec.dynamic = function(number, rule) {
  return {
    type: "PREC_DYNAMIC",
    value: number,
    content: normalize(rule)
  };
}

function repeat(rule) {
  return {
    type: "REPEAT",
    content: normalize(rule)
  };
}

function repeat1(rule) {
  return {
    type: "REPEAT1",
    content: normalize(rule)
  };
}

function seq(...elements) {
  return {
    type: "SEQ",
    members: elements.map(normalize)
  };
}

function sym(name) {
  return {
    type: "SYMBOL",
    name: name
  };
}

function token(value) {
  return {
    type: "TOKEN",
    content: normalize(value)
  };
}

token.immediate = function(value) {
  return {
    type: "IMMEDIATE_TOKEN",
    content: normalize(value)
  };
}

function normalize(value) {
  if (typeof value == "undefined")
    throw new Error("Undefined symbol");

  switch (value.constructor) {
    case String:
      return {
        type: 'STRING',
        value
      };
    case RegExp:
      return {
          type: 'PATTERN',
          value: value.source
            .replace(
              UNICODE_ESCAPE_PATTERN,
              (match, group) => String.fromCharCode(parseInt(group, 16))
            )
      };
    case ReferenceError:
      throw value
    default:
      if (typeof value.type === 'string') {
        return value;
      } else {
        throw new TypeError("Invalid rule: " + value.toString());
      }
  }
}

function RuleBuilder(ruleMap) {
  return new Proxy({}, {
    get(target, propertyName) {
      const symbol = {
        type: 'SYMBOL',
        name: propertyName
      };

      if (!ruleMap || ruleMap.hasOwnProperty(propertyName)) {
        return symbol;
      } else {
        const error = new ReferenceError(`Undefined symbol '${propertyName}'`);
        error.symbol = symbol;
        return error;
      }
    }
  })
}

function grammar(baseGrammar, options) {
    if (!options) {
      options = baseGrammar;
      baseGrammar = {
        name: null,
        rules: {},
        extras: [normalize(/\s/)],
        conflicts: [],
        externals: [],
        inline: []
      };
    }

    let externals = baseGrammar.externals;
    if (options.externals) {
      if (typeof options.externals !== "function") {
        throw new Error("Grammar's 'externals' property must be a function.");
      }

      const externalsRuleBuilder = RuleBuilder(null)
      const externalRules = options.externals.call(externalsRuleBuilder, externalsRuleBuilder, baseGrammar.externals);

      if (!Array.isArray(externalRules)) {
        throw new Error("Grammar's 'externals' property must return an array of rules.");
      }

      externals = externalRules.map(normalize);
    }

    const ruleMap = {};
    for (const key in options.rules) {
      ruleMap[key] = true;
    }
    for (const key in baseGrammar.rules) {
      ruleMap[key] = true;
    }
    for (const external of externals) {
      if (typeof external.name === 'string') {
        ruleMap[external.name] = true;
      }
    }

    const ruleBuilder = RuleBuilder(ruleMap);

    const name = options.name;
    if (typeof name !== "string") {
      throw new Error("Grammar's 'name' property must be a string.");
    }

    if (!/^[a-zA-Z_]\w*$/.test(name)) {
      throw new Error("Grammar's 'name' property must not start with a digit and cannot contain non-word characters.");
    }

    let rules = Object.assign({}, baseGrammar.rules);
    if (options.rules) {
      if (typeof options.rules !== "object") {
        throw new Error("Grammar's 'rules' property must be an object.");
      }

      for (const ruleName in options.rules) {
        const ruleFn = options.rules[ruleName];
        if (typeof ruleFn !== "function") {
          throw new Error("Grammar rules must all be functions. '" + ruleName + "' rule is not.");
        }
        rules[ruleName] = normalize(ruleFn.call(ruleBuilder, ruleBuilder, baseGrammar.rules[ruleName]));
      }
    }

    let extras = baseGrammar.extras.slice();
    if (options.extras) {
      if (typeof options.extras !== "function") {
        throw new Error("Grammar's 'extras' property must be a function.");
      }

      extras = options.extras
        .call(ruleBuilder, ruleBuilder, baseGrammar.extras)
        .map(normalize);
    }

    let word = baseGrammar.word;
    if (options.word) {
      word = options.word.call(ruleBuilder, ruleBuilder).name;
      if (typeof word != 'string') {
        throw new Error("Grammar's 'word' property must be a named rule.");
      }
    }

    let conflicts = baseGrammar.conflicts;
    if (options.conflicts) {
      if (typeof options.conflicts !== "function") {
        throw new Error("Grammar's 'conflicts' property must be a function.");
      }

      const baseConflictRules = baseGrammar.conflicts.map(conflict => conflict.map(sym));
      const conflictRules = options.conflicts.call(ruleBuilder, ruleBuilder, baseConflictRules);

      if (!Array.isArray(conflictRules)) {
        throw new Error("Grammar's conflicts must be an array of arrays of rules.");
      }

      conflicts = conflictRules.map(conflictSet => {
        if (!Array.isArray(conflictSet)) {
          throw new Error("Grammar's conflicts must be an array of arrays of rules.");
        }

        return conflictSet.map(symbol => normalize(symbol).name);
      });
    }

    let inline = baseGrammar.inline;
    if (options.inline) {
      if (typeof options.inline !== "function") {
        throw new Error("Grammar's 'inline' property must be a function.");
      }

      const baseInlineRules = baseGrammar.inline.map(sym);
      const inlineRules = options.inline.call(ruleBuilder, ruleBuilder, baseInlineRules);

      if (!Array.isArray(inlineRules)) {
        throw new Error("Grammar's inline must be an array of rules.");
      }

      inline = inlineRules.map(symbol => symbol.name);
    }

    if (Object.keys(rules).length == 0) {
      throw new Error("Grammar must have at least one rule.");
    }

    return {name, word, rules, extras, conflicts, externals, inline};
  }

global.alias = alias;
global.blank = blank;
global.choice = choice;
global.optional = optional;
global.prec = prec;
global.repeat = repeat;
global.repeat1 = repeat1;
global.seq = seq;
global.sym = sym;
global.token = token;
global.grammar = grammar;

const result = require(process.env.TREE_SITTER_GRAMMAR_PATH);
console.log(JSON.stringify(result, null, 2));
<commit_msg>cli: Check that extra rules aren't passed to functions like 'optional'<commit_after>const UNICODE_ESCAPE_PATTERN = /\\u([0-9a-f]{4})/gi;

function alias(rule, value) {
  const result = {
    type: "ALIAS",
    content: normalize(rule),
    named: false,
    value: null
  };

  switch (value.constructor) {
    case String:
      result.named = false;
      result.value = value;
      return result;
    case ReferenceError:
      result.named = true;
      result.value = value.symbol.name;
      return result;
    case Object:
      if (typeof value.type === 'string' && value.type === 'SYMBOL') {
        result.named = true;
        result.value = value.name;
        return result;
      }
  }

  throw new Error('Invalid alias value ' + value);
}

function blank() {
  return {
    type: "BLANK"
  };
}

function choice(...elements) {
  return {
    type: "CHOICE",
    members: elements.map(normalize)
  };
}

function optional(value) {
  checkArguments(arguments.length, optional, 'optional');
  return choice(value, blank());
}

function prec(number, rule) {
  checkArguments(
    arguments.length - 1,
    prec,
    'prec',
    ' and a precedence argument'
  );

  return {
    type: "PREC",
    value: number,
    content: normalize(rule)
  };
}

prec.left = function(number, rule) {
  if (rule == null) {
    rule = number;
    number = 0;
  }

  checkArguments(
    arguments.length - 1,
    prec.left,
    'prec.left',
    ' and an optional precedence argument'
  );

  return {
    type: "PREC_LEFT",
    value: number,
    content: normalize(rule)
  };
}

prec.right = function(number, rule) {
  if (rule == null) {
    rule = number;
    number = 0;
  }

  checkArguments(
    arguments.length - 1,
    prec.right,
    'prec.right',
    ' and an optional precedence argument'
  );

  return {
    type: "PREC_RIGHT",
    value: number,
    content: normalize(rule)
  };
}

prec.dynamic = function(number, rule) {
  checkArguments(
    arguments.length - 1,
    prec.dynamic,
    'prec.dynamic',
    ' and a precedence argument'
  );

  return {
    type: "PREC_DYNAMIC",
    value: number,
    content: normalize(rule)
  };
}

function repeat(rule) {
  checkArguments(arguments.length, repeat, 'repeat');
  return {
    type: "REPEAT",
    content: normalize(rule)
  };
}

function repeat1(rule) {
  checkArguments(arguments.length, repeat1, 'repeat1');
  return {
    type: "REPEAT1",
    content: normalize(rule)
  };
}

function seq(...elements) {
  return {
    type: "SEQ",
    members: elements.map(normalize)
  };
}

function sym(name) {
  return {
    type: "SYMBOL",
    name: name
  };
}

function token(value) {
  return {
    type: "TOKEN",
    content: normalize(value)
  };
}

token.immediate = function(value) {
  return {
    type: "IMMEDIATE_TOKEN",
    content: normalize(value)
  };
}

function normalize(value) {
  if (typeof value == "undefined")
    throw new Error("Undefined symbol");

  switch (value.constructor) {
    case String:
      return {
        type: 'STRING',
        value
      };
    case RegExp:
      return {
          type: 'PATTERN',
          value: value.source
            .replace(
              UNICODE_ESCAPE_PATTERN,
              (match, group) => String.fromCharCode(parseInt(group, 16))
            )
      };
    case ReferenceError:
      throw value
    default:
      if (typeof value.type === 'string') {
        return value;
      } else {
        throw new TypeError("Invalid rule: " + value.toString());
      }
  }
}

function RuleBuilder(ruleMap) {
  return new Proxy({}, {
    get(target, propertyName) {
      const symbol = {
        type: 'SYMBOL',
        name: propertyName
      };

      if (!ruleMap || ruleMap.hasOwnProperty(propertyName)) {
        return symbol;
      } else {
        const error = new ReferenceError(`Undefined symbol '${propertyName}'`);
        error.symbol = symbol;
        return error;
      }
    }
  })
}

function grammar(baseGrammar, options) {
    if (!options) {
      options = baseGrammar;
      baseGrammar = {
        name: null,
        rules: {},
        extras: [normalize(/\s/)],
        conflicts: [],
        externals: [],
        inline: []
      };
    }

    let externals = baseGrammar.externals;
    if (options.externals) {
      if (typeof options.externals !== "function") {
        throw new Error("Grammar's 'externals' property must be a function.");
      }

      const externalsRuleBuilder = RuleBuilder(null)
      const externalRules = options.externals.call(externalsRuleBuilder, externalsRuleBuilder, baseGrammar.externals);

      if (!Array.isArray(externalRules)) {
        throw new Error("Grammar's 'externals' property must return an array of rules.");
      }

      externals = externalRules.map(normalize);
    }

    const ruleMap = {};
    for (const key in options.rules) {
      ruleMap[key] = true;
    }
    for (const key in baseGrammar.rules) {
      ruleMap[key] = true;
    }
    for (const external of externals) {
      if (typeof external.name === 'string') {
        ruleMap[external.name] = true;
      }
    }

    const ruleBuilder = RuleBuilder(ruleMap);

    const name = options.name;
    if (typeof name !== "string") {
      throw new Error("Grammar's 'name' property must be a string.");
    }

    if (!/^[a-zA-Z_]\w*$/.test(name)) {
      throw new Error("Grammar's 'name' property must not start with a digit and cannot contain non-word characters.");
    }

    let rules = Object.assign({}, baseGrammar.rules);
    if (options.rules) {
      if (typeof options.rules !== "object") {
        throw new Error("Grammar's 'rules' property must be an object.");
      }

      for (const ruleName in options.rules) {
        const ruleFn = options.rules[ruleName];
        if (typeof ruleFn !== "function") {
          throw new Error("Grammar rules must all be functions. '" + ruleName + "' rule is not.");
        }
        rules[ruleName] = normalize(ruleFn.call(ruleBuilder, ruleBuilder, baseGrammar.rules[ruleName]));
      }
    }

    let extras = baseGrammar.extras.slice();
    if (options.extras) {
      if (typeof options.extras !== "function") {
        throw new Error("Grammar's 'extras' property must be a function.");
      }

      extras = options.extras
        .call(ruleBuilder, ruleBuilder, baseGrammar.extras)
        .map(normalize);
    }

    let word = baseGrammar.word;
    if (options.word) {
      word = options.word.call(ruleBuilder, ruleBuilder).name;
      if (typeof word != 'string') {
        throw new Error("Grammar's 'word' property must be a named rule.");
      }
    }

    let conflicts = baseGrammar.conflicts;
    if (options.conflicts) {
      if (typeof options.conflicts !== "function") {
        throw new Error("Grammar's 'conflicts' property must be a function.");
      }

      const baseConflictRules = baseGrammar.conflicts.map(conflict => conflict.map(sym));
      const conflictRules = options.conflicts.call(ruleBuilder, ruleBuilder, baseConflictRules);

      if (!Array.isArray(conflictRules)) {
        throw new Error("Grammar's conflicts must be an array of arrays of rules.");
      }

      conflicts = conflictRules.map(conflictSet => {
        if (!Array.isArray(conflictSet)) {
          throw new Error("Grammar's conflicts must be an array of arrays of rules.");
        }

        return conflictSet.map(symbol => normalize(symbol).name);
      });
    }

    let inline = baseGrammar.inline;
    if (options.inline) {
      if (typeof options.inline !== "function") {
        throw new Error("Grammar's 'inline' property must be a function.");
      }

      const baseInlineRules = baseGrammar.inline.map(sym);
      const inlineRules = options.inline.call(ruleBuilder, ruleBuilder, baseInlineRules);

      if (!Array.isArray(inlineRules)) {
        throw new Error("Grammar's inline must be an array of rules.");
      }

      inline = inlineRules.map(symbol => symbol.name);
    }

    if (Object.keys(rules).length == 0) {
      throw new Error("Grammar must have at least one rule.");
    }

    return {name, word, rules, extras, conflicts, externals, inline};
  }

function checkArguments(ruleCount, caller, callerName, suffix = '') {
  if (ruleCount > 1) {
    const error = new Error([
      `The \`${callerName}\` function only takes one rule argument${suffix}.`,
      'You passed multiple rules. Did you mean to call `seq`?\n'
    ].join('\n'));
    Error.captureStackTrace(error, caller);
    throw error
  }
}

global.alias = alias;
global.blank = blank;
global.choice = choice;
global.optional = optional;
global.prec = prec;
global.repeat = repeat;
global.repeat1 = repeat1;
global.seq = seq;
global.sym = sym;
global.token = token;
global.grammar = grammar;

const result = require(process.env.TREE_SITTER_GRAMMAR_PATH);
console.log(JSON.stringify(result, null, 2));
<|endoftext|>


<commit_before>/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/
/*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/
/*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/
(function($) {

    /*
       ======== A Handy Little QUnit Reference ========
       http://docs.jquery.com/QUnit

       Test methods:
       expect(numAssertions)
       stop(increment)
       start(decrement)
       Test assertions:
       ok(value, [message])
       equal(actual, expected, [message])
       notEqual(actual, expected, [message])
       deepEqual(actual, expected, [message])
       notDeepEqual(actual, expected, [message])
       strictEqual(actual, expected, [message])
       notStrictEqual(actual, expected, [message])
       raises(block, [expected], [message])
       */

    module('jQuery#momboBox', {
        setup: function() {
                   this.elems = $('#qunit-fixture').children();
        }
    });

    test('is chainable', 1, function() {
        // Not a bad test to run on collection methods.
        strictEqual(this.elems.momboBox(), this.elems, 'should be chaninable');
    });

    test('is momboBox', 1, function() {
        ok(this.elems.momboBox().get(0).momboBox, 'should be thoroughly momboBox');
    });
    test('only works on input elements', 1, function () {
        raises(function () {
            $('*').momboBox();
        }, 'the momboBox plugin only works on input elements');
    });
    module('with a simple array it', {
        setup: function () {
            this.$elem = $('#qunit-fixture input').momboBox({
                data: ['Blue','Green','Orange','Fusia']
            });
        }
    });

    test('populates data from constructor', 1, function () {
        equal(this.$elem.get(0).momboBox.data.length, 4);
    });

    test('show the menu when the input box receivs focus', function () {
        this.$elem.focus();
        ok($('div.mombomenu').is(':visible'));
    });

    asyncTest('show the menu when the input box receivs a click', function (done) {
        this.$elem.click();
        setTimeout(function () {
            ok($('div.mombomenu').is(':visible'));
            start();
        }, 1);
    });
}(jQuery));
<commit_msg>aranged tests better.<commit_after>/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/
/*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/
/*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/
(function($) {

    /*
       ======== A Handy Little QUnit Reference ========
       http://docs.jquery.com/QUnit

       Test methods:
       expect(numAssertions)
       stop(increment)
       start(decrement)
       Test assertions:
       ok(value, [message])
       equal(actual, expected, [message])
       notEqual(actual, expected, [message])
       deepEqual(actual, expected, [message])
       notDeepEqual(actual, expected, [message])
       strictEqual(actual, expected, [message])
       notStrictEqual(actual, expected, [message])
       raises(block, [expected], [message])
       */

    module('jQuery#momboBox', {
        setup: function() {
                   this.elems = $('#qunit-fixture').children();
        }
    });

    test('is chainable', 1, function() {
        // Not a bad test to run on collection methods.
        strictEqual(this.elems.momboBox(), this.elems, 'should be chaninable');
    });

    test('is momboBox', 1, function() {
        ok(this.elems.momboBox().get(0).momboBox, 'should be thoroughly momboBox');
    });
    test('only works on input elements', 1, function () {
        raises(function () {
            $('*').momboBox();
        }, 'the momboBox plugin only works on input elements');
    });

    module('with a simple array it', {
        setup: function () {
            this.$elem = $('#qunit-fixture input').momboBox({
                data: ['Blue','Green','Orange','Fusia']
            });
        }
    });

    test('populates data from constructor', 1, function () {
        equal(this.$elem.get(0).momboBox.data.length, 4);
    });

    test('show the menu when the input box receivs focus', function () {
        this.$elem.focus();
        ok($('div.mombomenu').is(':visible'));
    });

    asyncTest('show the menu when the input box receivs a click', function (done) {
        this.$elem.click();
        setTimeout(function () {
            ok($('div.mombomenu').is(':visible'));
            start();
        }, 1);
    });
}(jQuery));
<|endoftext|>


<commit_before>export const signIn = (email, password) => {
  return {
    type: 'SIGN_IN',
    email,
    password
  };
};

export const signUp = (firstName, lastName, email, password, phone) => {
  return {
    type: 'SIGN_UP',
    firstName,
    lastName,
    email,
    password,
    phone
  };
};

export const postMessage = (senderId, body, priority, isComment, token) => {
  return {
    type: 'POST_MESSAGE',
    body,
    priority,
    isComment,
    senderId,
    token
  };
};

export const addUser = (email, groupId, adderId, token) => {
  return {
    type: 'ADD_MEMBER',
    email,
    groupId,
    adderId,
    token
  };
};

export const deleteGroup = (ownerId, groupId, token) => {
  return {
    type: 'DELETE_GROUP',
    ownerId,
    groupId,
    token
  };
};

export const createGroup = (creatorId, title, description, initialMembers, token) => {
  return {
    type: 'CREATE_GROUP',
    creatorId,
    title,
    description,
    initialMembers,
    token
  };
};

export const getMessages = (groupId, offset, limit, token) => {
  return {
    type: 'GET_MESSAGES',
    groupId,
    offset,
    limit,
    token
  };
};

export const getGroupMembers = (groupId, offset, limit, token) => {
  return {
    type: 'GET_GROUP_MEMBERS',
    groupId,
    offset,
    limit,
    token
  };
};

export const getPostItMembers = (offset, limit, token) => {
  return {
    type: 'GET_POST_IT_MEMBERS',
    offset,
    limit,
    token
  };
};

export const getAllGroups = (offset, limit, token) => {
  return {
    type: 'GET_ALL_GROUPS',
    offset,
    limit,
    token
  };
};

export const getGroupsForUser = (userId, offset, limit, token) => {
  return {
    type: 'GET_ALL_GROUPS_FOR_A_USER',
    userId,
    offset,
    limit,
    token
  };
};

export const deleteMember = (ownerId, idToDelete, groupId, token) => {
  return {
    type: 'DELETE_MEMBER',
    ownerId,
    idToDelete,
    groupId,
    token
  };
};

export const resetErrorLog = () => {
  return {
    type: 'RESET_ERROR_LOG',
  };
};
<commit_msg>update action that gets members<commit_after>export const signIn = (email, password) => {
  return {
    type: 'SIGN_IN',
    email,
    password
  };
};

export const signUp = (firstName, lastName, email, password, phone) => {
  return {
    type: 'SIGN_UP',
    firstName,
    lastName,
    email,
    password,
    phone
  };
};

export const postMessage = (senderId, body, priority, isComment, token) => {
  return {
    type: 'POST_MESSAGE',
    body,
    priority,
    isComment,
    senderId,
    token
  };
};

export const addUser = (email, groupId, adderId, token) => {
  return {
    type: 'ADD_MEMBER',
    email,
    groupId,
    adderId,
    token
  };
};

export const deleteGroup = (ownerId, groupId, token) => {
  return {
    type: 'DELETE_GROUP',
    ownerId,
    groupId,
    token
  };
};

export const createGroup = (creatorId, title, description, initialMembers, token) => {
  return {
    type: 'CREATE_GROUP',
    creatorId,
    title,
    description,
    initialMembers,
    token
  };
};

export const getMessages = (groupId, offset, limit, token) => {
  return {
    type: 'GET_MESSAGES',
    groupId,
    offset,
    limit,
    token
  };
};

export const getGroupMembers = (groupId, offset, limit, token) => {
  return {
    type: 'GET_GROUP_MEMBERS',
    groupId,
    offset,
    limit,
    token
  };
};

export const getPostItMembers = (token) => {
  return {
    type: 'GET_POST_IT_MEMBERS',
    token
  };
};

export const getAllGroups = (offset, limit, token) => {
  return {
    type: 'GET_ALL_GROUPS',
    offset,
    limit,
    token
  };
};

export const getGroupsForUser = (userId, offset, limit, token) => {
  return {
    type: 'GET_ALL_GROUPS_FOR_A_USER',
    userId,
    offset,
    limit,
    token
  };
};

export const deleteMember = (ownerId, idToDelete, groupId, token) => {
  return {
    type: 'DELETE_MEMBER',
    ownerId,
    idToDelete,
    groupId,
    token
  };
};

export const resetErrorLog = () => {
  return {
    type: 'RESET_ERROR_LOG',
  };
};
<|endoftext|>


<commit_before>import expect from 'expect.js';
import React from 'react/addons';
const { TestUtils } = React.addons;
import TreePane from '../src/TreePane';

describe('TreePane', function () {

    const model = {
        name: 'Tom',
        children: [
            { name: 'Alice'}, { name: 'Jacob'}
        ]
    };

    const treePane = TestUtils.renderIntoDocument(
        <TreePane model={model} />
    );

    it('should render the tree pane', function () {
        new Asserter(treePane);
    });
});

class Asserter {

    constructor(treePane) {
        this.component = TestUtils.findRenderedDOMComponentWithClass(treePane, 'TreePane');
        this.treePane = treePane;
    }

    assertNumberOfChildren() {
        //expect(this.component.props.children.length).to.equal(3);
    }

    findChildren() {
        //return TestUtils.scryRenderedDOMComponentsWithClass(this.component, 'Node');
    }

}

<commit_msg>test framework<commit_after>import expect from 'expect.js';
import React from 'react/addons';
const { TestUtils } = React.addons;
import TreePane from '../src/TreePane';

describe('TreePane', function () {

    const model = {
        name: 'Default',
        children: [
            { name: 'react-tree-pane', children:[
                {name: 'demo', children: [
                    {name: 'bundle.js'},
                    {name: 'Example.js'}
                ]},
                {name: 'src', children: [
                    {name: 'TreePane.js'}
                ]},
                {name: 'test', children: [
                    {name: 'TreePane-test.js'}
                ]},
                {name: 'package.json'}
            ]}
        ]
    };

    const treePane = TestUtils.renderIntoDocument(
        <TreePane model={model} />
    );

    it('should render the tree pane', function () {
        new TreePaneAsserter(treePane);
    });

    it('should render the whole tree expanded', function () {
        new TreePaneAsserter(treePane)
            .findNode().assertValue('Default').assertIsExpanded().assertNumberOfChildren(1)
                .findChildNode('react-tree-pane').assertIsExpanded().assertNumberOfChildren(3)
                    .findChildNode('demo').assertIsExpanded().assertNumberOfChildren(2).end()
                    .findChildNode('src').assertIsExpanded().assertNumberOfChildren(1).end()
                    .findChildNode('test').assertIsExpanded().assertNumberOfChildren(1).end()
        ;
    });
});

class TreePaneAsserter {

    constructor(treePane) {
        this.treePane = treePane;
    }

    findNode() {
        return new NodeAsserter(this);
    }

}

class NodeAsserter {
    constructor(parent) {
        this.parent = parent;
    }

    findCell() {return new CellAsserter(this) }
    assertValue() { return this; }
    assertIsExpanded() { return this; }
    assertIsCollapsed() { return this; }
    assertNumberOfChildren(expected) { return this; }
    findChildNode(value) { return new NodeAsserter(this) }
    end() { return this.parent; }
}

class CellAsserter {
    constructor(parent) {
        this.parent = parent;
    }
    assertValue() { return this; }
    end() { return this.parent; }
}

<|endoftext|>


<commit_before>describe("autolink", function() {
  it("can be called on a string", function() {
    return expect("hi there".autoLink()).toBeDefined();
  });
  it("does not alter a string with no URL present", function() {
    return expect("hi again".autoLink()).toEqual("hi again");
  });
  it("returns the string with the URLs hyperlinked", function() {
    return expect("Check out this search engine http://google.com".autoLink()).toEqual("Check out this search engine " + "http://google.com");
  });
  it("does not hyperlink additional non-URL text", function() {
    return expect("LMSTFY: http://google.com and RTFM".autoLink()).toEqual("LMSTFY: http://google.com and RTFM");
  });
  it("correctly hyperlinks text with multiple URLs", function() {
    return expect("Google is http://google.com and Twitter is http://twitter.com".autoLink()).toEqual("Google is http://google.com and " + "Twitter is http://twitter.com");
  });
  it("correctly hyperlinks URLs, regardless of TLD", function() {
    return expect("Click here http://bit.ly/1337 now".autoLink()).toEqual("Click here http://bit.ly/1337 now");
  });
  it("correctly hyperlinks URLs, regardless of subdomain", function() {
    return expect("Check it: http://some.sub.domain".autoLink()).toEqual("Check it: http://some.sub.domain");
  });
  it("correctly handles punctuation", function() {
    return expect("Go here now http://google.com!".autoLink()).toEqual("Go here now http://google.com!");
  });
  it("correctly handles hash character(#)", function() {
    return expect("Go here now http://google.com/#query=index".autoLink()).toEqual("Go here now http://google.com/#query=index");
  });
  it("correctly handles escaped fragment character(#!)", function() {
    return expect("Go here now http://twitter.com/#!/PostDeskUK".autoLink()).toEqual("Go here now http://twitter.com/#!/PostDeskUK");
  });
  it("correctly handles FTP links", function() {
    return expect("Click here ftp://ftp.google.com".autoLink()).toEqual("Click here ftp://ftp.google.com");
  });
  it("sets link attributes based on the options provided", function() {
    return expect("Google it: http://google.com".autoLink({
      target: "_blank"
    })).toEqual("Google it: " + "http://google.com");
  });
  it("sets multiple link attributes if more than one is given", function() {
    return expect("Google it: http://google.com".autoLink({
      target: "_blank",
      rel: "nofollow"
    })).toEqual("Google it: http://google.com");
  });
  describe("callback option", function() {
    it("can be passed to redefine how link will be rendered", function() {
      return expect("Google it: http://google.com".autoLink({
        callback: function(url) {
          return "[" + url + "](" + url + ")";
        }
      })).toEqual("Google it: [http://google.com](http://google.com)");
    });
    it("can accept other parameters", function() {
      return expect("Google it: http://google.com".autoLink({
        target: "_blank",
        rel: "nofollow",
        callback: function(url) {
          return "" + url + "";
        }
      })).toEqual("Google it: http://google.com");
    });
    return it("can return nothing", function() {
      return expect("Google it: http://google.com".autoLink({
        callback: function(url) {
          if (/\.(gif|png|jpe?g)$/i.test(url)) {
            return "";
          }
        }
      })).toEqual("Google it: http://google.com");
    });
  });
  return describe("html", function() {
    it("will not affect images", function() {
      return expect("Image ".autoLink()).toEqual("Image ");
    });
    it("will not affect anchors", function() {
      return expect("Anchor http://example.com".autoLink()).toEqual("Anchor http://example.com");
    });
    return it("will still work", function() {
      return expect("Anchor http://example.com to http://example.com".autoLink()).toEqual("Anchor http://example.com to http://example.com");
    });
  });
});<commit_msg>Recompiles autolink-spec.coffee with CoffeeScript version 1.4.0<commit_after>// Generated by CoffeeScript 1.4.0
(function() {

  describe("autolink", function() {
    it("can be called on a string", function() {
      return expect("hi there".autoLink()).toBeDefined();
    });
    it("does not alter a string with no URL present", function() {
      return expect("hi again".autoLink()).toEqual("hi again");
    });
    it("returns the string with the URLs hyperlinked", function() {
      return expect("Check out this search engine http://google.com".autoLink()).toEqual("Check out this search engine " + "http://google.com");
    });
    it("does not hyperlink additional non-URL text", function() {
      return expect("LMSTFY: http://google.com and RTFM".autoLink()).toEqual("LMSTFY: http://google.com and RTFM");
    });
    it("correctly hyperlinks text with multiple URLs", function() {
      return expect("Google is http://google.com and Twitter is http://twitter.com".autoLink()).toEqual("Google is http://google.com and " + "Twitter is http://twitter.com");
    });
    it("correctly hyperlinks URLs, regardless of TLD", function() {
      return expect("Click here http://bit.ly/1337 now".autoLink()).toEqual("Click here http://bit.ly/1337 now");
    });
    it("correctly hyperlinks URLs, regardless of subdomain", function() {
      return expect("Check it: http://some.sub.domain".autoLink()).toEqual("Check it: http://some.sub.domain");
    });
    it("correctly handles punctuation", function() {
      return expect("Go here now http://google.com!".autoLink()).toEqual("Go here now http://google.com!");
    });
    it("correctly handles hash character(#)", function() {
      return expect("Go here now http://google.com/#query=index".autoLink()).toEqual("Go here now http://google.com/#query=index");
    });
    it("correctly handles escaped fragment character(#!)", function() {
      return expect("Go here now http://twitter.com/#!/PostDeskUK".autoLink()).toEqual("Go here now http://twitter.com/#!/PostDeskUK");
    });
    it("correctly handles FTP links", function() {
      return expect("Click here ftp://ftp.google.com".autoLink()).toEqual("Click here ftp://ftp.google.com");
    });
    it("sets link attributes based on the options provided", function() {
      return expect("Google it: http://google.com".autoLink({
        target: "_blank"
      })).toEqual("Google it: " + "http://google.com");
    });
    it("sets multiple link attributes if more than one is given", function() {
      return expect("Google it: http://google.com".autoLink({
        target: "_blank",
        rel: "nofollow"
      })).toEqual("Google it: http://google.com");
    });
    describe("callback option", function() {
      it("can be passed to redefine how link will be rendered", function() {
        return expect("Google it: http://google.com".autoLink({
          callback: function(url) {
            return "[" + url + "](" + url + ")";
          }
        })).toEqual("Google it: [http://google.com](http://google.com)");
      });
      it("can accept other parameters", function() {
        return expect("Google it: http://google.com".autoLink({
          target: "_blank",
          rel: "nofollow",
          callback: function(url) {
            return "" + url + "";
          }
        })).toEqual("Google it: http://google.com");
      });
      return it("can return nothing", function() {
        return expect("Google it: http://google.com".autoLink({
          callback: function(url) {
            if (/\.(gif|png|jpe?g)$/i.test(url)) {
              return "";
            }
          }
        })).toEqual("Google it: http://google.com");
      });
    });
    return describe("html", function() {
      it("will not affect images", function() {
        return expect("Image ".autoLink()).toEqual("Image ");
      });
      it("will not affect anchors", function() {
        return expect("Anchor http://example.com".autoLink()).toEqual("Anchor http://example.com");
      });
      return it("will still work", function() {
        return expect("Anchor http://example.com to http://example.com".autoLink()).toEqual("Anchor http://example.com to http://example.com");
      });
    });
  });

}).call(this);
<|endoftext|>


<commit_before>var config = require('config');
var log = require('./client/log')('geocode');
var get = require('./client/request').get;

var southWest = [-123.099060058594, 36.745486924699];
var northEast = [-121.192932128906, 38.182068998322];

/**********tismart **********************/
var dev_amigo_token = "R:3jqO9zmsFuFpdn0BosPJbXpjf82PISOJXqMbwN";
console.log("imprimir key token actual");
console.log(config.realtime_access_token());

/**
 * Geocode
 */

module.exports = geocode;
module.exports.reverse = reverse;
module.exports.suggest = suggest;

/**
 * Geocode
 */

function geocode(address, callback) {
  log('--> geocoding %s', address);
  get('/geocode/' + address, function(err, res) {
    if (err) {
      log('<-- geocoding error %s', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Reverse geocode
 */

function reverse(ll, callback) {
  log('--> reverse geocoding %s', ll);
  get('/geocode/reverse/' + ll[0] + ',' + ll[1], function(err, res) {
    if (err) {
      log('<-- geocoding error %e', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Suggestions!
 */

function suggest(text, callback) {
  var bingSuggestions, nominatimSuggestions, totalSuggestions;
  log('--> getting suggestion for %s', text);

  get('https://www.amigocloud.com/api/v1/me/geocoder/autocomplete?text=' + text +'&token=' + dev_amigo_token, function(err, res) {

    if(err) {
        console.log("Error amigo cloud");
        console.log(err);
    }else{
        console.log("json amigo cloud response");
        console.log(res);
    }
  });

  get('/geocode/suggest/'+ text, function(err, res){

    if (err) {
      log('<-- suggestion error %s', err);
      callback(err, res);
    } else {
      log('<-- got %s suggestions', res.body.length);

	bingSuggestions = res.body;

    console.log("------------API GEOCODE---------------");
    console.log("res ->", res.body);
    console.log("res.body ->", res);

//      callback(null, res.body);
	get('http://nominatim.openstreetmap.org/search' +
	    '?format=json&addressdetails=1&' +
	    'viewbox=' + southWest[0] + ',' +
	    northEast[1] + ',' + northEast[0] + ',' + southWest[1] +
	    '&bounded=1' +
	    'countrycodes=us&q=' + text, function (err, nRes) {
		var inside = false;
	    nominatimSuggestions = [];
            for (var i = 0; i < nRes.body.length; i++) {
//		inside = inside && (nRes.body[i].lng > southWest[0]);
//		inside = inside && (nRes.body[i].lng < northEast[0]);
//		inside = inside && (nRes.body[i].lat > southWest[1]);
//		inside = inside && (nRes.body[i].lat < northEast[1]);
//		if (inside) {
                    nominatimSuggestions.push(nRes.body[i]);
//		}
            }
	    callback(
		null,
		nominatimSuggestions.slice(0,2).
		    concat(bingSuggestions.slice(0,3))
	    );
	});
    }
  });

}
<commit_msg>Mejora en objeto y llamado de amigocloud<commit_after>var config = require('config');
var log = require('./client/log')('geocode');
var get = require('./client/request').get;

var southWest = [-123.099060058594, 36.745486924699];
var northEast = [-121.192932128906, 38.182068998322];

/**********tismart **********************/
var dev_amigo_token = "R:3jqO9zmsFuFpdn0BosPJbXpjf82PISOJXqMbwN";
var amigocloud_response = {"geocoding":{"version":"0.1","attribution":"https://search.mapzen.com/v1/attribution","query":{"text":"539 Alma St, Palo Alto, California","parsed_text":{"name":"539 Alma St","number":"539","street":"Alma St","state":"CA","regions":["Palo Alto"],"admin_parts":"Palo Alto, California"},"size":10,"private":false},"engine":{"name":"Pelias","author":"Mapzen","version":"1.0"},"timestamp":1458156768182},"type":"FeatureCollection","features":[{"type":"Feature","properties":{"id":"5e789adebdc84b9493235fe4efb2d5fa","gid":"oa:address:5e789adebdc84b9493235fe4efb2d5fa","layer":"address","source":"oa","name":"539 Alma Street","housenumber":"539","street":"Alma Street","country_a":"USA","country":"United States","region":"California","region_a":"CA","county":"Santa Clara County","locality":"Palo Alto","neighbourhood":"Downtown","confidence":0.488,"label":"539 Alma Street, Palo Alto, CA"},"geometry":{"type":"Point","coordinates":[-122.162803,37.442859]}}],"bbox":[-122.162803,37.442859,-122.162803,37.442859]};
console.log("amigo cloud response demo");
console.log(amigocloud_response);

/**
 * Geocode
 */

module.exports = geocode;
module.exports.reverse = reverse;
module.exports.suggest = suggest;

/**
 * Geocode
 */

function geocode(address, callback) {
  log('--> geocoding %s', address);
  get('/geocode/' + address, function(err, res) {
    if (err) {
      log('<-- geocoding error %s', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Reverse geocode
 */

function reverse(ll, callback) {
  log('--> reverse geocoding %s', ll);
  get('/geocode/reverse/' + ll[0] + ',' + ll[1], function(err, res) {
    if (err) {
      log('<-- geocoding error %e', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Suggestions!
 */

function suggest(text, callback) {
  var bingSuggestions, nominatimSuggestions, totalSuggestions;
  log('--> getting suggestion for %s', text);

  get('https://www.amigocloud.com/api/v1/me/geocoder/autocomplete?text=' + text +'&token=' + dev_amigo_token, function(err, res) {

    if(err) {
        console.log("Error amigo cloud");
        console.log(err);
    }else{
        console.log("json amigo cloud response");
        console.log(res);
    }
  });

  get('/geocode/suggest/'+ text, function(err, res){

    if (err) {
      log('<-- suggestion error %s', err);
      callback(err, res);
    } else {
      log('<-- got %s suggestions', res.body.length);

	bingSuggestions = res.body;

    bingSuggestions_slice = bingSuggestions.slice(0,3);

    console.log("------------API GEOCODE---------------");
    console.log("res ->", res.body);
    console.log("res.body ->", res);
    console.log("slice ->", bingSuggestions_slice);

//      callback(null, res.body);
	get('http://nominatim.openstreetmap.org/search' +
	    '?format=json&addressdetails=1&' +
	    'viewbox=' + southWest[0] + ',' +
	    northEast[1] + ',' + northEast[0] + ',' + southWest[1] +
	    '&bounded=1' +
	    'countrycodes=us&q=' + text, function (err, nRes) {
		var inside = false;
	    nominatimSuggestions = [];
            for (var i = 0; i < nRes.body.length; i++) {
//		inside = inside && (nRes.body[i].lng > southWest[0]);
//		inside = inside && (nRes.body[i].lng < northEast[0]);
//		inside = inside && (nRes.body[i].lat > southWest[1]);
//		inside = inside && (nRes.body[i].lat < northEast[1]);
//		if (inside) {
                    nominatimSuggestions.push(nRes.body[i]);
//		}
            }

            console.log("resultado openstrep", nominatimSuggestions);
            nominatimSuggestions_slice = nominatimSuggestions.slice(0,2);
            console.log("parametro enviado",nominatimSuggestions_slice.concat(bingSuggestions_slice));
	    callback(
		null,
            nominatimSuggestions_slice.concat(bingSuggestions_slice);
	    );
	});
    }
  });

}
<|endoftext|>