<commit_before>var app = require('app');
var ipc = require('ipc');
var BrowserWindow = require('browser-window');
var Menu = require('menu');

var window = null;

app.commandLine.appendSwitch('js-flags', '--expose_gc');

ipc.on('message', function() {
  ipc.send.apply(this, arguments);
});

ipc.on('console.log', function(pid, rid, args) {
  console.log.apply(console, args);
});

ipc.on('console.error', function(pid, rid, args) {
  console.log.apply(console, args);
});

ipc.on('process.exit', function(pid, rid, code) {
  process.exit(code);
});

ipc.on('eval', function(ev, pid, rid, script) {
  ev.returnValue = eval(script);
});

ipc.on('echo', function(ev, pid, rid, msg) {
  ev.returnValue = msg;
});

process.on('uncaughtException', function() {
  window.openDevTools();
});

app.on('window-all-closed', function() {
  app.terminate();
});

app.on('finish-launching', function() {
  var template = [
    {
      label: 'File',
      submenu: [
        {
          label: 'Open',
          accelerator: 'Command+O',
        },
        {
          label: 'Close',
          accelerator: 'Command+W',
          click: function(item, window) { window.close(); }
        },
      ]
    },
    {
      label: 'View',
      submenu: [
        {
          label: 'Reload',
          accelerator: 'Command+R',
          click: function(item, window) { window.restart(); }
        },
        {
          label: 'Enter Fullscreen',
          click: function(item, window) { window.setFullScreen(true); }
        },
        {
          label: 'Toggle DevTools',
          accelerator: 'Alt+Command+I',
          click: function(item, window) { window.toggleDevTools(); }
        },
      ]
    },
  ];

  var menu = Menu.buildFromTemplate(template);
  app.setApplicationMenu(menu);

  // Test if using protocol module would crash.
  require('protocol').registerProtocol('test-if-crashes', function() {});

  window = new BrowserWindow({
    title: 'atom-shell tests',
    show: false,
    width: 800,
    height: 600
  });
  window.loadUrl('file://' + __dirname + '/index.html');
});
<commit_msg>Add 'Quit' to spec window's menu.<commit_after>var app = require('app');
var ipc = require('ipc');
var BrowserWindow = require('browser-window');
var Menu = require('menu');

var window = null;

app.commandLine.appendSwitch('js-flags', '--expose_gc');

ipc.on('message', function() {
  ipc.send.apply(this, arguments);
});

ipc.on('console.log', function(pid, rid, args) {
  console.log.apply(console, args);
});

ipc.on('console.error', function(pid, rid, args) {
  console.log.apply(console, args);
});

ipc.on('process.exit', function(pid, rid, code) {
  process.exit(code);
});

ipc.on('eval', function(ev, pid, rid, script) {
  ev.returnValue = eval(script);
});

ipc.on('echo', function(ev, pid, rid, msg) {
  ev.returnValue = msg;
});

process.on('uncaughtException', function() {
  window.openDevTools();
});

app.on('window-all-closed', function() {
  app.terminate();
});

app.on('finish-launching', function() {
  var template = [
    {
      label: 'Atom',
      submenu: [
        {
          label: 'Quit',
          accelerator: 'Command+Q',
          click: function(item, window) { app.quit(); }
        },
      ],
    },
    {
      label: 'Window',
      submenu: [
        {
          label: 'Open',
          accelerator: 'Command+O',
        },
        {
          label: 'Close',
          accelerator: 'Command+W',
          click: function(item, window) { window.close(); }
        },
      ]
    },
    {
      label: 'View',
      submenu: [
        {
          label: 'Reload',
          accelerator: 'Command+R',
          click: function(item, window) { window.restart(); }
        },
        {
          label: 'Enter Fullscreen',
          click: function(item, window) { window.setFullScreen(true); }
        },
        {
          label: 'Toggle DevTools',
          accelerator: 'Alt+Command+I',
          click: function(item, window) { window.toggleDevTools(); }
        },
      ]
    },
  ];

  var menu = Menu.buildFromTemplate(template);
  app.setApplicationMenu(menu);

  // Test if using protocol module would crash.
  require('protocol').registerProtocol('test-if-crashes', function() {});

  window = new BrowserWindow({
    title: 'atom-shell tests',
    show: false,
    width: 800,
    height: 600
  });
  window.loadUrl('file://' + __dirname + '/index.html');
});
<|endoftext|>


<commit_before>openerp.suvit_web_diagram = function(instance, local) {

  var QWeb = instance.web.qweb;

  instance.web.DiagramView.include({

    save_coords: function(fig, node_obj){
        var NodeModel = new instance.web.Model(this.node);
        var coords = node_obj.get_pos();
        coords['x'] = coords['x'] - 50;
        coords['y'] = coords['y'] - 50;
        NodeModel.call('write', [node_obj.id, coords]);
    },

    draw_diagram: function(result) {
        var self = this;
        var res_nodes  = result['nodes'];
        var res_edges  = result['conn'];
        this.parent_field = result.parent_field;
        this.$el.find('h3.oe_diagram_title').text(result.name);

        var id_to_node = {};

        var style = {
            edge_color: "#A0A0A0",
            edge_label_color: "#555",
            edge_label_font_size: 10,
            edge_width: 2,
            edge_spacing: 100,
            edge_loop_radius: 100,

            node_label_color: "#333",
            node_label_font_size: 12,
            node_outline_color: "#333",
            node_outline_width: 1,
            node_selected_color: "#0097BE",
            node_selected_width: 2,
            node_size_x: 110,
            node_size_y: 80,
            connector_active_color: "#FFF",
            connector_radius: 4,

            close_button_radius: 8,
            close_button_color: "#333",
            close_button_x_color: "#FFF",

            gray: "#DCDCDC",
            white: "#FFF",

            viewport_margin: 50
        };

        // remove previous diagram
        var canvas = self.$el.find('div.oe_diagram_diagram')
                             .empty().get(0);

        var r  = new Raphael(canvas, '100%','100%');

        var graph  = new CuteGraph(r,style,canvas.parentNode);

        _.each(res_nodes, function(node) {
            var n = new CuteNode(
                graph,
                node.x + 50,  //FIXME the +50 should be in the layout algorithm
                node.y + 50,
                CuteGraph.wordwrap(node.name, 14),
                node.shape === 'rectangle' ? 'rect' : 'circle',
                node.color === 'white' ? style.white : style.gray);

            n.id = node.id;
            id_to_node[node.id] = n;

            function save_coords(){
              self.save_coords(this, n);
            }

            var fig = n.get_fig();
            fig.drag(null, null, save_coords);
        });

        _.each(res_edges, function(edge) {
            var e =  new CuteEdge(
                graph,
                CuteGraph.wordwrap(edge.signal, 32),
                id_to_node[edge.s_id],
                id_to_node[edge.d_id] || id_to_node[edge.s_id]  );  //WORKAROUND
            e.id = edge.id;
        });

        CuteNode.double_click_callback = function(cutenode){
            self.edit_node(cutenode.id);
        };
        var i = 0;
        CuteNode.destruction_callback = function(cutenode){
            if(!confirm(_t("Deleting this node cannot be undone.\nIt will also delete all connected transitions.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new instance.web.DataSet(self,self.node).unlink([cutenode.id]);
        };
        CuteEdge.double_click_callback = function(cuteedge){
            self.edit_connector(cuteedge.id);
        };

        CuteEdge.creation_callback = function(node_start, node_end){
            return {label: ''};
        };
        CuteEdge.new_edge_callback = function(cuteedge){
            self.add_connector(cuteedge.get_start().id,
                               cuteedge.get_end().id,
                               cuteedge);
        };
        CuteEdge.destruction_callback = function(cuteedge){
            if(!confirm(_t("Deleting this transition cannot be undone.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new instance.web.DataSet(self,self.connector).unlink([cuteedge.id]);
        };

    }

  });

};
<commit_msg>remove named function, remove pass fig param<commit_after>openerp.suvit_web_diagram = function(instance, local) {

  var QWeb = instance.web.qweb;

  instance.web.DiagramView.include({

    save_coords: function(node_obj){
        var NodeModel = new instance.web.Model(this.node);
        var coords = node_obj.get_pos();
        coords['x'] = coords['x'] - 50;
        coords['y'] = coords['y'] - 50;
        NodeModel.call('write', [node_obj.id, coords]);
    },

    draw_diagram: function(result) {
        var self = this;
        var res_nodes  = result['nodes'];
        var res_edges  = result['conn'];
        this.parent_field = result.parent_field;
        this.$el.find('h3.oe_diagram_title').text(result.name);

        var id_to_node = {};

        var style = {
            edge_color: "#A0A0A0",
            edge_label_color: "#555",
            edge_label_font_size: 10,
            edge_width: 2,
            edge_spacing: 100,
            edge_loop_radius: 100,

            node_label_color: "#333",
            node_label_font_size: 12,
            node_outline_color: "#333",
            node_outline_width: 1,
            node_selected_color: "#0097BE",
            node_selected_width: 2,
            node_size_x: 110,
            node_size_y: 80,
            connector_active_color: "#FFF",
            connector_radius: 4,

            close_button_radius: 8,
            close_button_color: "#333",
            close_button_x_color: "#FFF",

            gray: "#DCDCDC",
            white: "#FFF",

            viewport_margin: 50
        };

        // remove previous diagram
        var canvas = self.$el.find('div.oe_diagram_diagram')
                             .empty().get(0);

        var r  = new Raphael(canvas, '100%','100%');

        var graph  = new CuteGraph(r,style,canvas.parentNode);

        _.each(res_nodes, function(node) {
            var n = new CuteNode(
                graph,
                node.x + 50,  //FIXME the +50 should be in the layout algorithm
                node.y + 50,
                CuteGraph.wordwrap(node.name, 14),
                node.shape === 'rectangle' ? 'rect' : 'circle',
                node.color === 'white' ? style.white : style.gray);

            n.id = node.id;
            id_to_node[node.id] = n;

            var fig = n.get_fig();
            fig.drag(null, null, function(){
              self.save_coords(n);
            });
        });

        _.each(res_edges, function(edge) {
            var e =  new CuteEdge(
                graph,
                CuteGraph.wordwrap(edge.signal, 32),
                id_to_node[edge.s_id],
                id_to_node[edge.d_id] || id_to_node[edge.s_id]  );  //WORKAROUND
            e.id = edge.id;
        });

        CuteNode.double_click_callback = function(cutenode){
            self.edit_node(cutenode.id);
        };
        var i = 0;
        CuteNode.destruction_callback = function(cutenode){
            if(!confirm(_t("Deleting this node cannot be undone.\nIt will also delete all connected transitions.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new instance.web.DataSet(self,self.node).unlink([cutenode.id]);
        };
        CuteEdge.double_click_callback = function(cuteedge){
            self.edit_connector(cuteedge.id);
        };

        CuteEdge.creation_callback = function(node_start, node_end){
            return {label: ''};
        };
        CuteEdge.new_edge_callback = function(cuteedge){
            self.add_connector(cuteedge.get_start().id,
                               cuteedge.get_end().id,
                               cuteedge);
        };
        CuteEdge.destruction_callback = function(cuteedge){
            if(!confirm(_t("Deleting this transition cannot be undone.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new instance.web.DataSet(self,self.connector).unlink([cuteedge.id]);
        };

    }

  });

};
<|endoftext|>


<commit_before>/* global mocha, chai, sinon, before, beforeEach, afterEach, after */
define(function(require) {
	'use strict';

	require('src/freeform');

	window.expect = chai.expect;

	mocha.setup('bdd');

	mocha.loaded = function() {
		mocha.checkLeaks();
		mocha.run();

		var $fixtures = $('#fixtures');

		var setFixtures = function () {
			_.each(arguments, function (content) {
				$fixtures.append(content);
			});
		};

		var clearFixtures = function () {
			$fixtures.empty();
		};

		var originalHash = window.location.hash;

		before(function() {
			this.setFixtures = setFixtures;
			this.clearFixtures = clearFixtures;
		});

		beforeEach(function () {
			this.sinon = sinon.sandbox.create();
		});

		afterEach(function () {
			this.sinon.restore();
			this.clearFixtures();
			window.location.hash = originalHash;
			Backbone.history.stop();
			Backbone.history.handlers.length = 0;
		});

		after(function() {
			var stats = $('#mocha-stats');
			var count = + stats.find('.failures em').text();
			if (count > 0) stats.addClass('failed');
			stats.find('.progress').on('click', function() {
				window.location = '/spec/';
			});

			stats.show();

		});
	};

});<commit_msg>fix for back link on spec page<commit_after>/* global mocha, chai, sinon, before, beforeEach, afterEach, after */
define(function(require) {
	'use strict';

	require('src/freeform');

	window.expect = chai.expect;

	mocha.setup('bdd');

	mocha.loaded = function() {
		mocha.checkLeaks();
		mocha.run();

		var $fixtures = $('#fixtures');

		var setFixtures = function () {
			_.each(arguments, function (content) {
				$fixtures.append(content);
			});
		};

		var clearFixtures = function () {
			$fixtures.empty();
		};

		var originalHash = window.location.hash;

		before(function() {
			this.setFixtures = setFixtures;
			this.clearFixtures = clearFixtures;
		});

		beforeEach(function () {
			this.sinon = sinon.sandbox.create();
		});

		afterEach(function () {
			this.sinon.restore();
			this.clearFixtures();
			window.location.hash = originalHash;
			Backbone.history.stop();
			Backbone.history.handlers.length = 0;
		});

		after(function() {
			var stats = $('#mocha-stats');
			var count = + stats.find('.failures em').text();
			if (count > 0) stats.addClass('failed');
			stats.find('.progress').on('click', function() {
				var url = window.location.href.replace(/\/spec\/?.*/,'/spec');
				window.location = url;
			});

			stats.show();

		});
	};

});<|endoftext|>


<commit_before>/* global VERSION */
import React from 'react';
import App from '../components/app';
import Header from '../components/header';
import Avatar from './components/avatar';
import Autocomplete from './components/autocomplete';
import Button from './components/button';
import Card from './components/card';
import Checkbox from './components/checkbox';
import Dialog from './components/dialog';
import Drawer from './components/drawer';
import Dropdown from './components/dropdown';
import IconMenu from './components/icon_menu';
import Input from './components/input';
import List from './components/list';
import Media from './components/media';
import Menu from './components/menu';
import Progress from './components/progress';
import Radio from './components/radio';
import Snackbar from './components/snackbar';
import Slider from './components/slider';
import Switch from './components/switch';
import Table from './components/table';
import Tabs from './components/tabs';
import Tooltip from './components/tooltip';
import style from './app.css';

const _hrefProject = () => {
  window.href = 'http://react-toolbox';
};

const Root = () => (
  <App className={style.app}>

React Atlas Spec {VERSION}

    <Autocomplete />
    <Avatar />
    <Button />
    <Card />
    <Checkbox />
    <Dialog />
    <Drawer />
    <Dropdown />
    <IconMenu />
    <Input />
    <List />
    <Media />
    <Menu />
    <Progress />
    <Radio />
    <Slider />
    <Snackbar />
    <Switch />

    <Tabs />
    <Tooltip />
  </App>
);

export default Root;
<commit_msg>removing app from spec<commit_after>/* global VERSION */
import React from 'react';
import Header from '../components/header';
import Avatar from './components/avatar';
import Autocomplete from './components/autocomplete';
import Button from './components/button';
import Card from './components/card';
import Checkbox from './components/checkbox';
import Dialog from './components/dialog';
import Drawer from './components/drawer';
import Dropdown from './components/dropdown';
import IconMenu from './components/icon_menu';
import Input from './components/input';
import List from './components/list';
import Media from './components/media';
import Menu from './components/menu';
import Progress from './components/progress';
import Radio from './components/radio';
import Snackbar from './components/snackbar';
import Slider from './components/slider';
import Switch from './components/switch';
import Table from './components/table';
import Tabs from './components/tabs';
import Tooltip from './components/tooltip';
import style from './app.css';

const _hrefProject = () => {
  window.href = 'http://react-toolbox';
};

const Root = () => (

React Atlas Spec {VERSION}

    <Autocomplete />
    <Avatar />
    <Button />
    <Card />
    <Checkbox />
    <Dialog />
    <Drawer />
    <Dropdown />
    <IconMenu />
    <Input />
    <List />
    <Media />
    <Menu />
    <Progress />
    <Radio />
    <Slider />
    <Snackbar />
    <Switch />

    <Tabs />
    <Tooltip />

);

export default Root;
<|endoftext|>


<commit_before>var Discord = require("discord.js");
var fs = require("fs");
var cron = require("node-cron");
var bot = new Discord.Client();
var readyCount = 0;
var watchlist = './watchlist.json';
const prefix = "~";
const friendList = {};

cron.schedule('*/25 * * * *', () => {
    console.log("Keeping SelfBot process alive");
});

bot.on("ready", () => {
    readyCount++;
    console.log("AFlaw is ready");
    console.log(`ID: ${bot.user.id}`);
    console.log(`Username: ${bot.user.username}`);
    // console.log(bot.presences);
    // console.log(bot.user.friends);
    checkFriendsStatuses(readyCount);
    // watchForFriendPresenceUpdate(readyCount);
});

process.on('SIGTERM', () => {
    console.log("AFlaw is exiting");
});

bot.on("message", msg => {
    if (msg.author.id != bot.user.id || msg.content.substring(0, 1) != prefix) return;

    let messageContent = msg.content.split(" ");
    let command = messageContent[0].slice(prefix.length);
    let fromBotChannel = msg.channel.id == process.env.BOT_TEST_ID;

    if (command === "watch") {
        // console.log("Watch command");
        // console.log(`Is someone mentioned: ${msg.mentions.users.size!=0}`);
        // console.log(messageContent[1]);
        let user = msg.mentions.users.size!=0 ? msg.mentions.users.first() : messageContent[1];
        if (!fromBotChannel) msg.delete();
        watch(msg.mentions.users.size!=0 ? user.username : user);
        sendStatusMessage(`Watching ${msg.mentions.users.size!=0 ? user.username : user}`);
    }

    if (command === "unwatch") {
        let user = msg.mentions.users.size!=0 ? msg.mentions.users.first() : messageContent[1];
        if (msg.channel.id != process.env.BOT_TEST_ID) msg.delete();
        unwatch(msg.mentions.users.size!=0 ? user.username : user);
        sendStatusMessage(`No longer watching ${msg.mentions.users.size!=0 ? user.username : user}`);
    }

    if (command === "testDM") {
        sendStatusMessage("This is a Test DM");
        // console.log(`Sending test message`);
    }
});

bot.on("presenceUpdate", (oldUser, newUser) => {
    try {
        //  if (oldUser.client.user.id in bot.user.friends.keys) return;
        var userObject = JSON.parse(process.env.WATCHLIST);
        if (userObject[oldUser.user.username.replace(/\s/g, '')]) {
            if ((oldUser.presence.status != "online") && (newUser.presence.status != "offline")) {
                 console.log(`presenceUpdate: ${oldUser.client.user.username}`);
                 sendStatusMessage(`${oldUser.user.username} is ${newUser.presence.status}`);
             }
        }
    } catch (error) {
        console.error(error);
    }
});

bot.login(process.env.USER_TOKEN).catch(err => console.error(err));

function watch(user) {
    try {
        let userObject = JSON.parse(process.env.WATCHLIST);
        userObject[user] = user;
        console.log(userObject);
        process.env.WATCHLIST = JSON.stringify(userObject);
    } catch (error) {
        console.error(error);
    }
}

function unwatch(user) {
    try {
        let userObject = JSON.parse(process.env.WATCHLIST);
        delete userObject[user];
        console.log(userObject);
            process.env.WATCHLIST = JSON.stringify(userObject);
    } catch (error) {
        console.error(error);
    }
}

function checkFriendsStatuses(count) {
    if (count > 1) return;
    let friendPresences = bot.presences;
    // console.log(friendPresences.keyArray().toString());
    friendPresences.keyArray().forEach((val, index, presences) => {
        friendList[friendPresences.keyArray()[index]] = friendPresences.get(val)["status"];
    });
    console.log(bot.user.friends);
}

// function watchForFriendPresenceUpdate(count) {
//     if (count > 1) return;
//     while(true) {
//         // let friendPresences = bot.presences;
//         // let friends = bot.user.friends;
//         // let friendPresencesKeys = friendPresences.keys;
//         // let friendKeys = friends.keys;
//         // let guilds = bot.guilds;
//         for ()
//     }
// }

function sendStatusMessage(msg) {
     bot.channels.get(process.env.BOT_TEST_ID).sendMessage(msg)
    .then(message => {
        console.log(message.content);
         message.delete();
    })
    .catch(console.error);
}<commit_msg>log more things<commit_after>var Discord = require("discord.js");
var fs = require("fs");
var cron = require("node-cron");
var bot = new Discord.Client();
var readyCount = 0;
var watchlist = './watchlist.json';
const prefix = "~";
const friendList = {};

cron.schedule('*/25 * * * *', () => {
    console.log("Keeping SelfBot process alive");
});

bot.on("ready", () => {
    readyCount++;
    console.log("AFlaw is ready");
    console.log(`ID: ${bot.user.id}`);
    console.log(`Username: ${bot.user.username}`);
    // console.log(bot.presences);
    // console.log(bot.user.friends);
    checkFriendsStatuses(readyCount);
    // watchForFriendPresenceUpdate(readyCount);
});

process.on('SIGTERM', () => {
    console.log("AFlaw is exiting");
});

bot.on("message", msg => {
    if (msg.author.id != bot.user.id || msg.content.substring(0, 1) != prefix) return;

    let messageContent = msg.content.split(" ");
    let command = messageContent[0].slice(prefix.length);
    let fromBotChannel = msg.channel.id == process.env.BOT_TEST_ID;

    if (command === "watch") {
        // console.log("Watch command");
        // console.log(`Is someone mentioned: ${msg.mentions.users.size!=0}`);
        // console.log(messageContent[1]);
        let user = msg.mentions.users.size!=0 ? msg.mentions.users.first() : messageContent[1];
        if (!fromBotChannel) msg.delete();
        watch(msg.mentions.users.size!=0 ? user.username : user);
        sendStatusMessage(`Watching ${msg.mentions.users.size!=0 ? user.username : user}`);
    }

    if (command === "unwatch") {
        let user = msg.mentions.users.size!=0 ? msg.mentions.users.first() : messageContent[1];
        if (msg.channel.id != process.env.BOT_TEST_ID) msg.delete();
        unwatch(msg.mentions.users.size!=0 ? user.username : user);
        sendStatusMessage(`No longer watching ${msg.mentions.users.size!=0 ? user.username : user}`);
    }

    if (command === "testDM") {
        sendStatusMessage("This is a Test DM");
        // console.log(`Sending test message`);
    }
});

bot.on("presenceUpdate", (oldUser, newUser) => {
    try {
        //  if (oldUser.client.user.id in bot.user.friends.keys) return;
        var userObject = JSON.parse(process.env.WATCHLIST);
        if (userObject[oldUser.user.username.replace(/\s/g, '')]) {
            if ((oldUser.presence.status != "online") && (newUser.presence.status != "offline")) {
                 console.log(`presenceUpdate: ${oldUser.client.user.username}`);
                 sendStatusMessage(`${oldUser.user.username} is ${newUser.presence.status}`);
             }
        }
    } catch (error) {
        console.error(error);
    }
});

bot.login(process.env.USER_TOKEN).catch(err => console.error(err));

function watch(user) {
    try {
        let userObject = JSON.parse(process.env.WATCHLIST);
        userObject[user] = user;
        console.log(userObject);
        process.env.WATCHLIST = JSON.stringify(userObject);
    } catch (error) {
        console.error(error);
    }
}

function unwatch(user) {
    try {
        let userObject = JSON.parse(process.env.WATCHLIST);
        delete userObject[user];
        console.log(userObject);
            process.env.WATCHLIST = JSON.stringify(userObject);
    } catch (error) {
        console.error(error);
    }
}

function checkFriendsStatuses(count) {
    if (count > 1) return;
    let friendPresences = bot.presences;
    // console.log(friendPresences.keyArray().toString());
    friendPresences.keyArray().forEach((val, index, presences) => {
        friendList[friendPresences.keyArray()[index]] = friendPresences.get(val)["status"];
    });
    console.log(bot.user.friends);
    console.log(friendPresences);
}

// function watchForFriendPresenceUpdate(count) {
//     if (count > 1) return;
//     while(true) {
//         // let friendPresences = bot.presences;
//         // let friends = bot.user.friends;
//         // let friendPresencesKeys = friendPresences.keys;
//         // let friendKeys = friends.keys;
//         // let guilds = bot.guilds;
//         for ()
//     }
// }

function sendStatusMessage(msg) {
     bot.channels.get(process.env.BOT_TEST_ID).sendMessage(msg)
    .then(message => {
        console.log(message.content);
         message.delete();
    })
    .catch(console.error);
}<|endoftext|>


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

goog.require('shaka.asserts');
goog.require('shaka.polyfill.CustomEvent');
goog.require('shaka.polyfill.Promise');

/**
 * Capture a Promise's status and attach it to the Promise.
 * @param {!Promise} promise
 */
function capturePromiseStatus(promise) {
  promise.status = 'pending';
  promise.then(function() {
    promise.status = 'resolved';
  }, function() {
    promise.status = 'rejected';
  });
}

/**
 * Returns a Promise which is resolved after the given delay.
 *
 * @param {number} seconds The delay in seconds.
 * @return {!Promise}
 */
function delay(seconds) {
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, seconds * 1000.0);
  });
}

/**
 * Replace shaka.asserts and console.assert with a version which hooks into
 * jasmine.  This converts all failed assertions into failed tests.
 */
var assertsToFailures = {
  uninstall: function() {
    shaka.asserts = assertsToFailures.originalShakaAsserts_;
    console.assert = assertsToFailures.originalConsoleAssert_;
  },

  install: function() {
    assertsToFailures.originalShakaAsserts_ = shaka.asserts;
    assertsToFailures.originalConsoleAssert_ = console.assert;

    var realAssert = console.assert.bind(console);

    var jasmineAssert = function(condition, opt_message) {
      realAssert(condition, opt_message);
      if (!condition) {
        var message = opt_message || 'Assertion failed.';
        try {
          throw new Error(message);
        } catch (exception) {
          fail(message);
        }
      }
    };

    shaka.asserts = {
      assert: function(condition, opt_message) {
        jasmineAssert(condition, opt_message);
      },
      notImplemented: function() {
        jasmineAssert(false, 'Not implemented.');
      },
      unreachable: function() {
        jasmineAssert(false, 'Unreachable reached.');
      }
    };

    console.assert = jasmineAssert;
  }
};

// Make sure assertions are converted into failures for all tests.
beforeEach(assertsToFailures.install);
afterEach(assertsToFailures.uninstall);

// The library cannot function without certain browser features, and therefore
// neither can many of our tests.  If needed, install the Promise and
// CustomEvent polyfills.  In particular, this is needed on IE11.
beforeAll(function() {
  shaka.polyfill.Promise.install();
  shaka.polyfill.CustomEvent.install();
});
<commit_msg>Always log assertions to the console in tests<commit_after>/**
 * @license
 * Copyright 2015 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

goog.require('shaka.asserts');
goog.require('shaka.polyfill.CustomEvent');
goog.require('shaka.polyfill.Promise');

/**
 * Capture a Promise's status and attach it to the Promise.
 * @param {!Promise} promise
 */
function capturePromiseStatus(promise) {
  promise.status = 'pending';
  promise.then(function() {
    promise.status = 'resolved';
  }, function() {
    promise.status = 'rejected';
  });
}

/**
 * Returns a Promise which is resolved after the given delay.
 *
 * @param {number} seconds The delay in seconds.
 * @return {!Promise}
 */
function delay(seconds) {
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, seconds * 1000.0);
  });
}

/**
 * Replace shaka.asserts and console.assert with a version which hooks into
 * jasmine.  This converts all failed assertions into failed tests.
 */
var assertsToFailures = {
  uninstall: function() {
    shaka.asserts = assertsToFailures.originalShakaAsserts_;
    console.assert = assertsToFailures.originalConsoleAssert_;
  },

  install: function() {
    assertsToFailures.originalShakaAsserts_ = shaka.asserts;
    assertsToFailures.originalConsoleAssert_ = console.assert;

    var realAssert = console.assert.bind(console);

    var jasmineAssert = function(condition, opt_message) {
      realAssert(condition, opt_message);
      if (!condition) {
        var message = opt_message || 'Assertion failed.';
        console.error(message);
        try {
          throw new Error(message);
        } catch (exception) {
          fail(message);
        }
      }
    };

    shaka.asserts = {
      assert: function(condition, opt_message) {
        jasmineAssert(condition, opt_message);
      },
      notImplemented: function() {
        jasmineAssert(false, 'Not implemented.');
      },
      unreachable: function() {
        jasmineAssert(false, 'Unreachable reached.');
      }
    };

    console.assert = jasmineAssert;
  }
};

// Make sure assertions are converted into failures for all tests.
beforeEach(assertsToFailures.install);
afterEach(assertsToFailures.uninstall);

// The library cannot function without certain browser features, and therefore
// neither can many of our tests.  If needed, install the Promise and
// CustomEvent polyfills.  In particular, this is needed on IE11.
beforeAll(function() {
  shaka.polyfill.Promise.install();
  shaka.polyfill.CustomEvent.install();
});
<|endoftext|>


<commit_before>/**
 * This module implements the viewer's specification (tests).
 *
 */

define(['viewerjs'], function(viewerjs) {

  describe('viewerjs', function() {

    window.jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000;

    var fileObjArr = [{url: 'volumes/nii/s34654_df.nii', name: 's34654_df.nii',
      remote: true}];

    // append a container for the whole viewer
    var container = $('

');
    $(document.body).append(container);

    var view; // viewer

    describe('viewerjs Initialization', function() {

      beforeEach(function() {

        // Create a new viewerjs.Viewer object
        view = new viewerjs.Viewer('viewercontainer');
      });

      afterEach(function() {

        // Destroy viewer
        view.destroy();
      });

      it('viewerjs.Viewer.prototype.addTrash adds a trash to the viewer',

        function() {

          view.addTrash();
          expect($('.view-trash', view.container).length).toEqual(1);
          expect(view.trash.length).toEqual(1);
        }
      );

      it('viewerjs.Viewer.prototype.addRenderersBox adds a renderers box to' +
        ' the viewer',

        function() {

          view.container.sortable();
          view.addRenderersBox();
          expect($('.view-renderers', view.container).length).toEqual(1);
          expect(view.rBox.container.length).toEqual(1);
        }
      );

      it('viewerjs.Viewer.prototype.addToolBar adds a toolbar to the viewer',

        function() {

          view.container.sortable();
          view.addRenderersBox(); // a renderers box must be added first
          view.addToolBar();
          expect($('.view-toolbar', view.container).length).toEqual(1);
          expect(view.toolBar.container.length).toEqual(1);
        }
      );

      it('viewerjs.Viewer.prototype.init initializes the viewer html',

        function() {

          view.init();
          expect(view.container.length).toEqual(1);
          expect(view.rBox.container.length).toEqual(1);
          expect(view.toolBar.container.length).toEqual(1);
        }
      );

      it('viewerjs.Viewer.prototype.buildImgFileArr builds viewer main data' +
        ' structure: view.imgFileArr',

        function() {

          var imgFileArr = view.buildImgFileArr(fileObjArr);

          expect(imgFileArr[0]).toEqual({
            id: 0,
            baseUrl: 'volumes/nii/',
            imgType: 'vol',
            files: [{url: 'volumes/nii/s34654_df.nii', name: 's34654_df.nii', remote: true}],
          });
        }
      );

      it('rendererjs.Renderer.prototype.addThumbnailsBar adds a new thumbnails' +
        ' bar to the viewer',

        function(done) {

          view.init();

          view.addThumbnailsBar(view.buildImgFileArr(fileObjArr), function() {

            expect($('.view-thumbnailsbar', view.container).length).toEqual(1);
            expect(view.thBars[0].container.length).toEqual(1);
            done();
          });
        }
      );

      it('rendererjs.Renderer.prototype.addData adds new data to the viewer',

        function(done) {

          view.init();

          view.addData(fileObjArr, function() {

            expect(view.imgFileArr[0]).toEqual({
              id: 0,
              thBarId: 0,
              baseUrl: 'volumes/nii/',
              imgType: 'vol',
              files: [{url: 'volumes/nii/s34654_df.nii', name: 's34654_df.nii', remote: true}],
            });

            expect($('.view-thumbnailsbar', view.container).length).toEqual(1);
            expect(view.thBars[0].container.length).toEqual(1);

            done();
          });
        }
      );
    });

    describe('viewerjs Behaviour', function() {

      beforeEach(function(done) {

        view = new viewerjs.Viewer('viewercontainer');

        view.init();

        view.addData(fileObjArr, function() {

          done();
        });
      });

      afterEach(function() {

        view.destroy();
      });

      it('viewerjs.Viewer.prototype.getImgFileObject(id) returns image file object given its id',

        function() {

          expect(view.getImgFileObject(0).id).toEqual(0);
        }
      );
    });
  });
});
<commit_msg>Added specs for 3 viewerjs.Viewer's methods: removeData, addRenderer and getThumbnailsBarObject<commit_after>/**
 * This module implements the viewer's specification (tests).
 *
 */

define(['viewerjs'], function(viewerjs) {

  describe('viewerjs', function() {

    window.jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000;

    var fileObjArr = [{url: 'volumes/nii/s34654_df.nii', name: 's34654_df.nii',
      remote: true}];

    // append a container for the whole viewer
    var container = $('

');
    $(document.body).append(container);

    var view; // viewer

    describe('viewerjs Initialization', function() {

      beforeEach(function() {

        // Create a new viewerjs.Viewer object
        view = new viewerjs.Viewer('viewercontainer');
      });

      afterEach(function() {

        // Destroy viewer
        view.destroy();
      });

      it('viewerjs.Viewer.prototype.addTrash adds a trash to the viewer',

        function() {

          view.addTrash();
          expect($('.view-trash', view.container).length).toEqual(1);
          expect(view.trash.length).toEqual(1);
        }
      );

      it('viewerjs.Viewer.prototype.addRenderersBox adds a renderers box to' +
        ' the viewer',

        function() {

          view.container.sortable();
          view.addRenderersBox();
          expect($('.view-renderers', view.container).length).toEqual(1);
          expect(view.rBox.container.length).toEqual(1);
        }
      );

      it('viewerjs.Viewer.prototype.addToolBar adds a toolbar to the viewer',

        function() {

          view.container.sortable();
          view.addRenderersBox(); // a renderers box must be added first
          view.addToolBar();
          expect($('.view-toolbar', view.container).length).toEqual(1);
          expect(view.toolBar.container.length).toEqual(1);
        }
      );

      it('viewerjs.Viewer.prototype.init initializes the viewer html',

        function() {

          view.init();
          expect(view.container.length).toEqual(1);
          expect(view.rBox.container.length).toEqual(1);
          expect(view.toolBar.container.length).toEqual(1);
        }
      );

      it('viewerjs.Viewer.prototype.buildImgFileArr builds viewer main data' +
        ' structure: view.imgFileArr',

        function() {

          var imgFileArr = view.buildImgFileArr(fileObjArr);

          expect(imgFileArr[0]).toEqual({
            id: 0,
            baseUrl: 'volumes/nii/',
            imgType: 'vol',
            files: [{url: 'volumes/nii/s34654_df.nii', name: 's34654_df.nii', remote: true}],
          });
        }
      );

      it('rendererjs.Renderer.prototype.addThumbnailsBar adds a new thumbnails' +
        ' bar to the viewer',

        function(done) {

          view.init();

          view.addThumbnailsBar(view.buildImgFileArr(fileObjArr), function() {

            expect($('.view-thumbnailsbar', view.container).length).toEqual(1);
            expect(view.thBars[0].container.length).toEqual(1);
            done();
          });
        }
      );

      it('rendererjs.Renderer.prototype.addData adds new data to the viewer',

        function(done) {

          view.init();

          view.addData(fileObjArr, function() {

            expect(view.imgFileArr[0]).toEqual({
              id: 0,
              thBarId: 0,
              baseUrl: 'volumes/nii/',
              imgType: 'vol',
              files: [{url: 'volumes/nii/s34654_df.nii', name: 's34654_df.nii', remote: true}],
            });

            expect($('.view-thumbnailsbar', view.container).length).toEqual(1);
            expect(view.thBars[0].container.length).toEqual(1);

            done();
          });
        }
      );
    });

    describe('viewerjs Behaviour', function() {

      beforeEach(function(done) {

        view = new viewerjs.Viewer('viewercontainer');

        view.init();

        view.addData(fileObjArr, function() {

          done();
        });
      });

      afterEach(function() {

        view.destroy();
      });

      it('rendererjs.Renderer.prototype.removeData removes data from the viewer',

        function() {

          view.removeData(0); // remove imgFileObj with id=0

          expect(view.imgFileArr[0]).toBeNull();
          expect(view.thBars[0]).toBeNull();
        }
      );

      it('rendererjs.Renderer.prototype.addRenderer adds a renderer to the' +
        ' viewer renderers box',

        function(done) {

          view.addRenderer(view.imgFileArr[0], function(rndr) {

            expect(view.rBox.renderers[0]).toBe(rndr);
            expect(rndr.selected).toEqual(true);

            done();
          });
        }
      );

      it('viewerjs.Viewer.prototype.getImgFileObject(id) returns image file object given its id',

        function() {

          expect(view.getImgFileObject(0).id).toEqual(0);
        }
      );

      it('viewerjs.Viewer.prototype.getThumbnailsBarObject(id) returns the' +
        'corresponding thumbnails bar object ',

        function() {

          expect(view.getThumbnailsBarObject(0)).toBe(view.thBars[0]);
        }
      );
    });
  });
});
<|endoftext|>


<commit_before>var Fresh = require('../build/fresh.js');

describe("Fresh.url", function() {

  beforeEach(function() {
    global.window = {location: {search: '?component=List&data=users.json'}};
  });
  afterEach(function() {
    delete global.window;
  });

  it(".getParams should extract the query string from the URL", function() {
    expect(Fresh.url.getParams()).toEqual({
      component: 'List',
      data: 'users.json'
    });
  });

});
<commit_msg>Remove whitespace #1<commit_after>var Fresh = require('../build/fresh.js');

describe("Fresh.url", function() {

  beforeEach(function() {
    global.window = {location: {search: '?component=List&data=users.json'}};
  });
  afterEach(function() {
    delete global.window;
  });

  it(".getParams should extract the query string from the URL", function() {
    expect(Fresh.url.getParams()).toEqual({
      component: 'List',
      data: 'users.json'
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Selman Kahya, 2013
 * See project's Github page for usage details.
 * https://github.com/Selmanh
 */

// Takes nested mysql result array as a parameter,
// converts it to a nested object
exports.convertToNested = function (rows, nestingOptions) {

    if (rows == null || nestingOptions == null)
        return rows;

    var levels = nestingOptions;

    // Put similar objects in the same bucket (by table name)
    var buckets = new Array();

    for (var i = 0; i < levels.length; i++) {
        var result = new Array();

        var level = levels[i];
        var key = level.key;
        var tableName = level.tableName;

        for (var j = 0; j < rows.length; j++) {
            var object = rows[j][tableName];

            // check if object has key property
            if (object == null){
                console.log("Error: couldn't find " + tableName + " property in mysql result set")
                continue;
            }

            // iterate result array check if object exist
            // if object is already in result array then do nothing
            // otherwise add it to result array
            if(!isExist(result, key, object[key]))
                result.push(object);
        }
        buckets.push(result);
    }

    // We have similar objects in the same bucket
    // Now, move lower level objects into related upper level objects
    for (var i = buckets.length-1; i >= 1; i--) {
        var relationKey = levels[i-1].key;
        var relationTable = levels[i].tableName;
        var objects = buckets[i];

        for (var j = 0; j < objects.length; j++) {

            var value, indexes = null;
            var object = objects[j];

            // IF lower level table doesn't have upper level table's primary column as foreign key
            // THEN lower level table has key to upper table
            // if couldn't find foreign key value in upper level, look to upper levels
            var targetBucket, a = 1;
            while(indexes == null && (i-a) >= 0){
                targetBucket = buckets[i-a];

                if(levels[i].hasOwnProperty('hasForeignKeyToUpperTable') && !levels[i].hasForeignKeyToUpperTable)
                    relationKey = levels[i].key;
                else
                    relationKey = levels[i-a].key;

                value = object[relationKey];
                indexes = getIndexes(targetBucket, relationKey, value);
                a++;
            }

            // relation to upper object not found - ignore this object
            if(indexes == null || indexes.length == 0)
                continue;

            for(var z = 0; z < indexes.length; z++){
                if(!targetBucket[indexes[z]][relationTable])
                    targetBucket[indexes[z]][relationTable] = new Array();

                targetBucket[indexes[z]][relationTable].push(object);
            }
        }
    }

    // at the end, we have all the nested objects in the first bucket
    return buckets[0];
};

// Returns indexes of an object that has given key and value in objects array
var getIndexes = function(objects, key, value){

    if (objects == null || key == null || value == null)
        return null;

    var result = new Array();

    for (var i = 0; i < objects.length; i++) {
        if(objects[i][key] == value){
            result.push(i);
        }
    }

    return result;
}

// Checks if key and value exists in one of the objects in given array
var isExist = function(array, key, value){

    for (var i = 0; i < array.length; i++) {
        if(array[i][key] == value)
            return true;
    }

    return false;
}<commit_msg>modified comments in func.js<commit_after>/**
 * Selman Kahya, 2013
 * See project's Github page for usage details.
 * https://github.com/Selmanh
 */

/**
 * takes nested mysql result array as a parameter,
 * converts it to a nested object
 *
 * @param {Array} rows
 * @param {Array} nestingOptions
 * @return {Object}
 */
exports.convertToNested = function (rows, nestingOptions) {

    if (rows == null || nestingOptions == null)
        return rows;

    var levels = nestingOptions;

    // put similar objects in the same bucket (by table name)
    var buckets = new Array();

    for (var i = 0; i < levels.length; i++) {
        var result = new Array();

        var level = levels[i];
        var key = level.key;
        var tableName = level.tableName;

        for (var j = 0; j < rows.length; j++) {
            var object = rows[j][tableName];

            // check if object has key property
            if (object == null){
                console.log("Error: couldn't find " + tableName + " property in mysql result set")
                continue;
            }

            // if object isn't in result array, then push it
            if(!isExist(result, key, object[key]))
                result.push(object);
        }
        buckets.push(result);
    }

    // we have similar objects in the same bucket
    // now, move lower level objects into related upper level objects
    for (var i = buckets.length-1; i >= 1; i--) {
        var relationKey = levels[i-1].key;
        var relationTable = levels[i].tableName;
        var objects = buckets[i];

        for (var j = 0; j < objects.length; j++) {

            var value, indexes = null;
            var object = objects[j];

            // if couldn't find foreign key value in upper level, look to upper levels
            var targetBucket, a = 1;
            while(indexes == null && (i-a) >= 0){
                targetBucket = buckets[i-a];

                // if lower level table doesn't have upper level table's primary column as foreign key
                // then upper table has a foreign key to lower table
                if(levels[i].hasOwnProperty('hasForeignKeyToUpperTable') && !levels[i].hasForeignKeyToUpperTable)
                    relationKey = levels[i].key;
                else
                    relationKey = levels[i-a].key;

                value = object[relationKey];
                indexes = getIndexes(targetBucket, relationKey, value);
                a++;
            }

            // relation to upper object(s) not found - ignore this object
            if(indexes == null || indexes.length == 0)
                continue;

            for(var z = 0; z < indexes.length; z++){
                if(!targetBucket[indexes[z]][relationTable])
                    targetBucket[indexes[z]][relationTable] = new Array();

                targetBucket[indexes[z]][relationTable].push(object);
            }
        }
    }

    // at the end, we have all the nested objects in the first bucket
    return buckets[0];
};

/**
 * returns indexes of the object that has given key property,
 * and the value of that property equals to given value
 *
 * @param {Array} objects
 * @param {String} key
 * @param {String} value
 * @return {Array}
 */
var getIndexes = function(objects, key, value){

    if (objects == null || key == null || value == null)
        return null;

    var result = new Array();

    for (var i = 0; i < objects.length; i++) {
        if(objects[i][key] == value){
            result.push(i);
        }
    }

    return result;
}

/**
 * checks if one of the objects in an array has the given property,
 * and the value of that property equals to given value
 *
 * @param {Array} array
 * @param {String} key
 * @param {String} value
 * @return {Array}
 */
//
var isExist = function(array, key, value){

    for (var i = 0; i < array.length; i++) {
        if(array[i][key] == value)
            return true;
    }

    return false;
}<|endoftext|>


<commit_before>'use strict'

/**
 * FUSEBOX
 *
 * Client & Server compiler / bundler / watcher
 */

const _ = require('lodash')
const Promise = require('bluebird')
const colors = require('colors/safe')
const fs = Promise.promisifyAll(require('fs-extra'))
const fsbx = require('fuse-box')
const nodemon = require('nodemon')
const path = require('path')
const uglify = require('uglify-js')

// ======================================================
// Parse cmd arguments
// ======================================================

const args = require('yargs')
  .option('d', {
    alias: 'dev',
    describe: 'Start in Developer mode',
    type: 'boolean'
  })
  .option('c', {
    alias: 'dev-configure',
    describe: 'Start in Configure Developer mode',
    type: 'boolean'
  })
  .help('h')
  .alias('h', 'help')
  .argv

let mode = 'build'
if (args.d) {
  console.info(colors.bgWhite.black(' Starting Fuse in DEVELOPER mode... '))
  mode = 'dev'
} else if (args.c) {
  console.info(colors.bgWhite.black(' Starting Fuse in CONFIGURE DEVELOPER mode... '))
  mode = 'dev-configure'
} else {
  console.info(colors.bgWhite.black(' Starting Fuse in BUILD mode... '))
}

// ======================================================
// Define aliases / shims
// ======================================================

const ALIASES = {
  'brace-ext-modelist': 'brace/ext/modelist.js',
  'simplemde': 'simplemde/dist/simplemde.min.js',
  'socket.io-client': 'socket.io-client/dist/socket.io.min.js',
  'vue': 'vue/dist/vue.min.js'
}
const SHIMS = {
  jquery: {
    source: 'node_modules/jquery/dist/jquery.js',
    exports: '$'
  }
}

// ======================================================
// Global Tasks
// ======================================================

console.info(colors.white('└── ') + colors.green('Running global tasks...'))

let globalTasks = Promise.mapSeries([
  () => {
    fs.accessAsync('./assets/js/ace').then(() => {
      console.info(colors.white('  └── ') + colors.magenta('ACE modes directory already exists. Task aborted.'))
      return true
    }).catch(err => {
      if (err.code === 'ENOENT') {
        console.info(colors.white('  └── ') + colors.green('Copy + Minify ACE modes to assets...'))
        return fs.ensureDirAsync('./assets/js/ace').then(() => {
          return fs.readdirAsync('./node_modules/brace/mode').then(modeList => {
            return Promise.map(modeList, mdFile => {
              console.info(colors.white('      mode-' + mdFile))
              let result = uglify.minify(path.join('./node_modules/brace/mode', mdFile), { output: { 'max_line_len': 1000000 } })
              return fs.writeFileAsync(path.join('./assets/js/ace', 'mode-' + mdFile), result.code)
            })
          })
        })
      } else {
        throw err
      }
    })
  }
], f => { return f() })

// ======================================================
// Fuse Tasks
// ======================================================

let fuse

globalTasks.then(() => {
  switch (mode) {
    // =============================================
    // DEVELOPER MODE
    // =============================================
    case 'dev':
      // Client

      fuse = fsbx.FuseBox.init({
        homeDir: './client',
        outFile: './assets/js/bundle.min.js',
        alias: ALIASES,
        shim: SHIMS,
        plugins: [
          [ fsbx.SassPlugin({ includePaths: ['../core'] }), fsbx.CSSPlugin() ],
          fsbx.BabelPlugin({ comments: false, presets: ['es2015'] }),
          fsbx.JSONPlugin()
        ],
        debug: false,
        log: true
      })

      fuse.devServer('>index.js', {
        port: 4444,
        httpServer: false,
        hmr: false
      })

      // Server

      _.delay(() => {
        nodemon({
          script: './server.js',
          args: [],
          ignore: ['assets/', 'client/', 'data/', 'repo/', 'tests/'],
          ext: 'js json',
          watch: [
            'controllers',
            'libs',
            'locales',
            'middlewares',
            'models',
            'agent.js',
            'server.js'
          ],
          env: { 'NODE_ENV': 'development' }
        })
      }, 1000)
      break
    // =============================================
    // CONFIGURE - DEVELOPER MODE
    // =============================================
    case 'dev-configure':
      // Client

      fuse = fsbx.FuseBox.init({
        homeDir: './client',
        outFile: './assets/js/configure.min.js',
        alias: ALIASES,
        shim: SHIMS,
        plugins: [
          [ fsbx.SassPlugin({ includePaths: ['../core'] }), fsbx.CSSPlugin() ],
          fsbx.BabelPlugin({ comments: false, presets: ['es2015'] }),
          fsbx.JSONPlugin()
        ],
        debug: false,
        log: true
      })

      fuse.devServer('>configure.js', {
        port: 4444,
        httpServer: false
      })

      // Server

      _.delay(() => {
        nodemon({
          exec: 'node wiki configure',
          ignore: ['assets/', 'client/', 'data/', 'repo/', 'tests/'],
          ext: 'js json',
          watch: [
            'configure.js'
          ],
          env: { 'NODE_ENV': 'development' }
        })
      }, 1000)
      break
    // =============================================
    // BUILD ONLY MODE
    // =============================================
    case 'build':
      fuse = fsbx.FuseBox.init({
        homeDir: './client',
        alias: ALIASES,
        shim: SHIMS,
        plugins: [
          fsbx.EnvPlugin({ NODE_ENV: 'production' }),
          [ fsbx.SassPlugin({ outputStyle: 'compressed', includePaths: ['./node_modules/requarks-core'] }), fsbx.CSSPlugin() ],
          fsbx.BabelPlugin({
            config: {
              comments: false,
              presets: ['es2015']
            }
          }),
          fsbx.JSONPlugin(),
          fsbx.UglifyJSPlugin({
            compress: { unused: false },
            output: { 'max_line_len': 1000000 }
          })
        ],
        debug: false,
        log: true
      })

      fuse.bundle({
        './assets/js/bundle.min.js': '>index.js',
        './assets/js/configure.min.js': '>configure.js'
      }).then(() => {
        console.info(colors.green.bold('\nAssets compilation + bundling completed.'))
      }).catch(err => {
        console.error(colors.red(' X Bundle compilation failed! ' + err.message))
        process.exit(1)
      })
      break
  }
})
<commit_msg>Fixed Fuse global tasks<commit_after>'use strict'

/**
 * FUSEBOX
 *
 * Client & Server compiler / bundler / watcher
 */

const _ = require('lodash')
const Promise = require('bluebird')
const colors = require('colors/safe')
const fs = Promise.promisifyAll(require('fs-extra'))
const fsbx = require('fuse-box')
const nodemon = require('nodemon')
const path = require('path')
const uglify = require('uglify-js')

// ======================================================
// Parse cmd arguments
// ======================================================

const args = require('yargs')
  .option('d', {
    alias: 'dev',
    describe: 'Start in Developer mode',
    type: 'boolean'
  })
  .option('c', {
    alias: 'dev-configure',
    describe: 'Start in Configure Developer mode',
    type: 'boolean'
  })
  .help('h')
  .alias('h', 'help')
  .argv

let mode = 'build'
if (args.d) {
  console.info(colors.bgWhite.black(' Starting Fuse in DEVELOPER mode... '))
  mode = 'dev'
} else if (args.c) {
  console.info(colors.bgWhite.black(' Starting Fuse in CONFIGURE DEVELOPER mode... '))
  mode = 'dev-configure'
} else {
  console.info(colors.bgWhite.black(' Starting Fuse in BUILD mode... '))
}

// ======================================================
// Define aliases / shims
// ======================================================

const ALIASES = {
  'brace-ext-modelist': 'brace/ext/modelist.js',
  'simplemde': 'simplemde/dist/simplemde.min.js',
  'socket.io-client': 'socket.io-client/dist/socket.io.min.js',
  'vue': 'vue/dist/vue.min.js'
}
const SHIMS = {
  jquery: {
    source: 'node_modules/jquery/dist/jquery.js',
    exports: '$'
  }
}

// ======================================================
// Global Tasks
// ======================================================

console.info(colors.white('└── ') + colors.green('Running global tasks...'))

let globalTasks = Promise.mapSeries([
  () => {
    return fs.accessAsync('./assets/js/ace').then(() => {
      console.info(colors.white('  └── ') + colors.magenta('ACE modes directory already exists. Task aborted.'))
      return true
    }).catch(err => {
      if (err.code === 'ENOENT') {
        console.info(colors.white('  └── ') + colors.green('Copy + Minify ACE modes to assets...'))
        return fs.ensureDirAsync('./assets/js/ace').then(() => {
          return fs.readdirAsync('./node_modules/brace/mode').then(modeList => {
            return Promise.map(modeList, mdFile => {
              console.info(colors.white('      mode-' + mdFile))
              let result = uglify.minify(path.join('./node_modules/brace/mode', mdFile), { output: { 'max_line_len': 1000000 } })
              return fs.writeFileAsync(path.join('./assets/js/ace', 'mode-' + mdFile), result.code)
            })
          })
        })
      } else {
        throw err
      }
    })
  }
], f => { return f() })

// ======================================================
// Fuse Tasks
// ======================================================

let fuse

globalTasks.then(() => {
  switch (mode) {
    // =============================================
    // DEVELOPER MODE
    // =============================================
    case 'dev':
      // Client

      fuse = fsbx.FuseBox.init({
        homeDir: './client',
        outFile: './assets/js/bundle.min.js',
        alias: ALIASES,
        shim: SHIMS,
        plugins: [
          [ fsbx.SassPlugin({ includePaths: ['../core'] }), fsbx.CSSPlugin() ],
          fsbx.BabelPlugin({ comments: false, presets: ['es2015'] }),
          fsbx.JSONPlugin()
        ],
        debug: false,
        log: true
      })

      fuse.devServer('>index.js', {
        port: 4444,
        httpServer: false,
        hmr: false
      })

      // Server

      _.delay(() => {
        nodemon({
          script: './server.js',
          args: [],
          ignore: ['assets/', 'client/', 'data/', 'repo/', 'tests/'],
          ext: 'js json',
          watch: [
            'controllers',
            'libs',
            'locales',
            'middlewares',
            'models',
            'agent.js',
            'server.js'
          ],
          env: { 'NODE_ENV': 'development' }
        })
      }, 1000)
      break
    // =============================================
    // CONFIGURE - DEVELOPER MODE
    // =============================================
    case 'dev-configure':
      // Client

      fuse = fsbx.FuseBox.init({
        homeDir: './client',
        outFile: './assets/js/configure.min.js',
        alias: ALIASES,
        shim: SHIMS,
        plugins: [
          [ fsbx.SassPlugin({ includePaths: ['../core'] }), fsbx.CSSPlugin() ],
          fsbx.BabelPlugin({ comments: false, presets: ['es2015'] }),
          fsbx.JSONPlugin()
        ],
        debug: false,
        log: true
      })

      fuse.devServer('>configure.js', {
        port: 4444,
        httpServer: false
      })

      // Server

      _.delay(() => {
        nodemon({
          exec: 'node wiki configure',
          ignore: ['assets/', 'client/', 'data/', 'repo/', 'tests/'],
          ext: 'js json',
          watch: [
            'configure.js'
          ],
          env: { 'NODE_ENV': 'development' }
        })
      }, 1000)
      break
    // =============================================
    // BUILD ONLY MODE
    // =============================================
    case 'build':
      fuse = fsbx.FuseBox.init({
        homeDir: './client',
        alias: ALIASES,
        shim: SHIMS,
        plugins: [
          fsbx.EnvPlugin({ NODE_ENV: 'production' }),
          [ fsbx.SassPlugin({ outputStyle: 'compressed', includePaths: ['./node_modules/requarks-core'] }), fsbx.CSSPlugin() ],
          fsbx.BabelPlugin({
            config: {
              comments: false,
              presets: ['es2015']
            }
          }),
          fsbx.JSONPlugin(),
          fsbx.UglifyJSPlugin({
            compress: { unused: false },
            output: { 'max_line_len': 1000000 }
          })
        ],
        debug: false,
        log: true
      })

      fuse.bundle({
        './assets/js/bundle.min.js': '>index.js',
        './assets/js/configure.min.js': '>configure.js'
      }).then(() => {
        console.info(colors.green.bold('\nAssets compilation + bundling completed.'))
      }).catch(err => {
        console.error(colors.red(' X Bundle compilation failed! ' + err.message))
        process.exit(1)
      })
      break
  }
})
<|endoftext|>


<commit_before>"use strict";

// regex matches if current player is 1 move away from winning & supplies winning move
var winningMovePatterns = [
                           [(/ OO....../),0],[(/O..O.. ../),6],[(/......OO /),8],
                           [(/.. ..O..O/),2],[(/ ..O..O../),0],[(/...... OO/),6],
                           [(/..O..O.. /),8],[(/OO ....../),2],[(/ ...O...O/),0],
                           [(/..O.O. ../),6],[(/O...O... /),8],[(/.. .O.O../),2],
                           [(/O O....../),1],[(/O.. ..O../),3],[(/......O O/),7],
                           [(/..O.. ..O/),5],[(/. ..O..O./),1],[(/... OO.../),3],
                           [(/.O..O.. ./),7],[(/...OO .../),5]
                          ];

// regex matches if opponent is 1 move away from winning & supplies blocking move
var blockingPatterns = [
                        [(/  X . X  /),1],[(/ XX....../),0],[(/X..X.. ../),6],
                        [(/......XX /),8],[(/.. ..X..X/),2],[(/ ..X..X../),0],
                        [(/...... XX/),6],[(/..X..X.. /),8],[(/XX ....../),2],
                        [(/.. .X...X/),2],[(/..X.X. ../),6],[(/X...X... /),8],
                        [(/.. .X.X../),2],[(/X X....../),1],[(/X.. ..X../),3],
                        [(/......X X/),7],[(/..X.. ..X/),5],[(/. ..X..X./),1],
                        [(/... XX.../),3],[(/.X..X.. ./),7],[(/...XX .../),5],
                        [(/ X X.. ../),0],[(/ ..X.. X /),6],[(/.. ..X X /),8],
                        [(/ X ..X.. /),2],[(/  XX.. ../),0],[(/X.. .. X /),6],
                        [(/.. .XX   /),8],[(/X  ..X.. /),2],[(/ X  ..X../),0],
                        [(/ ..X..  X/),6],[(/..X..  X /),8],[(/X  ..X.. /),2]
                       ];

// regex matches if a player has won & supplies the winning player
var hasWonPatterns = [
                      [(/OOO....../),'O'],[(/...OOO.../),'O'],[(/......OOO/),'O'],
                      [(/O..O..O../),'O'],[(/.O..O..O./),'O'],[(/..O..O..O/),'O'],
                      [(/O...O...O/),'O'],[(/..O.O.O../),'O'],[(/XXX....../),'X'],
                      [(/...XXX.../),'X'],[(/......XXX/),'X'],[(/X..X..X../),'X'],
                      [(/.X..X..X./),'X'],[(/..X..X..X/),'X'],[(/X...X...X/),'X'],
                      [(/..X.X.X../),'X']
                     ];

var board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '];
var player1 = 'X';
var player2 = 'O';
var currentTurn = player1;

// this searches winningMovePatterns then blockingPatterns and if there is no
// match run firstMove()
var findNextMove = function(){
  var nextPos = makeWinningMove(board);
  if(nextPos === -1){
    nextPos = makeBlockingMove(board);
    if(nextPos === -1){
      nextPos = firstMove();
    }
  }
  makeMove(nextPos,player2);
};

var makeMove = function(pos, player){
  if(player != currentTurn){return false;}
  if(+pos >= 0 && +pos <= 8 && !isNaN(+pos) && board[+pos] === ' '){
    board.splice(+pos, 1, player);
    currentTurn = (player === player1) ? player2 : player1;
    return true;
  }
  return false;
};

var board_display = function(){
  return ' '+board[0]+' |'+' '+board[1]+' |'+' '+board[2]+'\n===+===+===\n'+' '+
             board[3]+' |'+' '+board[4]+' |'+' '+board[5]+'\n===+===+===\n'+' '+
             board[6]+' |'+' '+board[7]+' |'+' '+board[8];
};

var logBoardToConsole = function(){
  console.log(board_display());
};

// return true if the board is filled
var isBoardFilled = function(){
  if(board.indexOf(' ') === -1){
    logBoardToConsole();
    console.log('Game over');
    return true;
  }
  return false;
};

// if the board matches a pattern from hasWonPatterns, return the winner
var hasSomeoneWon = function(board){
  var board_string = board.join('');
  var theWinner = null;
  for(var i = 0;i < hasWonPatterns.length;i++){
    var array = board_string.match(hasWonPatterns[i][0]);
    if(array){
      theWinner = hasWonPatterns[i][1];
    }
  }
  if(theWinner){
    logBoardToConsole();
    console.log('Game over');
    // console.log('Game over.', the_winner, 'is the winner!') Add this after tests
    return [true, theWinner];
  }
  return [false, null];
};

// return the next move by matching a pattern from winningMovePatterns and returning the number
// (the second value in the array)
var makeWinningMove = function(board){
  var board_string = board.join('');
  for(var i = 0;i < winningMovePatterns.length;i++){
    var array = board_string.match(winningMovePatterns[i][0]);
    if(array){ // this is only truthy when someone wins
      return winningMovePatterns[i][1];
    }
  }
  return -1;
};

// return the next move by matching a pattern from winningMovePatterns and returning the number
// (the second value in the array)
var makeBlockingMove = function(board){
  var board_string = board.join('');
  for(var i = 0;i < blockingPatterns.length;i++){
    var array = board_string.match(blockingPatterns[i][0]);
      if(array){return blockingPatterns[i][1];}
  }
  return -1;
};

// if the center of board is free, go there, if not go to position 0
var firstMove = function(){
  return board[4] === ' ' ? 4 : board.indexOf(' ');
};

var endGame = function(){
  process.exit();
};

var startGame = function(){
  logBoardToConsole();
  console.log("Enter [0-8]:");
  process.openStdin().on('data',function(res){
    if(makeMove(res, player1)){
      if(hasSomeoneWon(board)[0] || isBoardFilled()) {
        endGame();
      } else {
        findNextMove();
        if (hasSomeoneWon(board)[0] || isBoardFilled()) {
          endGame();
        } else {
          logBoardToConsole();
        }
      }
    }
  });
};

startGame();

// exports needed for tests
module.exports = {
  makeWinningMove : makeWinningMove,
  makeBlockingMove : makeBlockingMove,
  hasSomeoneWon : hasSomeoneWon
};
<commit_msg>Add "its a draw" message when the board is full and there is no winner.<commit_after>"use strict";

// regex matches if current player is 1 move away from winning & supplies winning move
var winningMovePatterns = [
                           [(/ OO....../),0],[(/O..O.. ../),6],[(/......OO /),8],
                           [(/.. ..O..O/),2],[(/ ..O..O../),0],[(/...... OO/),6],
                           [(/..O..O.. /),8],[(/OO ....../),2],[(/ ...O...O/),0],
                           [(/..O.O. ../),6],[(/O...O... /),8],[(/.. .O.O../),2],
                           [(/O O....../),1],[(/O.. ..O../),3],[(/......O O/),7],
                           [(/..O.. ..O/),5],[(/. ..O..O./),1],[(/... OO.../),3],
                           [(/.O..O.. ./),7],[(/...OO .../),5]
                          ];

// regex matches if opponent is 1 move away from winning & supplies blocking move
var blockingPatterns = [
                        [(/  X . X  /),1],[(/ XX....../),0],[(/X..X.. ../),6],
                        [(/......XX /),8],[(/.. ..X..X/),2],[(/ ..X..X../),0],
                        [(/...... XX/),6],[(/..X..X.. /),8],[(/XX ....../),2],
                        [(/.. .X...X/),2],[(/..X.X. ../),6],[(/X...X... /),8],
                        [(/.. .X.X../),2],[(/X X....../),1],[(/X.. ..X../),3],
                        [(/......X X/),7],[(/..X.. ..X/),5],[(/. ..X..X./),1],
                        [(/... XX.../),3],[(/.X..X.. ./),7],[(/...XX .../),5],
                        [(/ X X.. ../),0],[(/ ..X.. X /),6],[(/.. ..X X /),8],
                        [(/ X ..X.. /),2],[(/  XX.. ../),0],[(/X.. .. X /),6],
                        [(/.. .XX   /),8],[(/X  ..X.. /),2],[(/ X  ..X../),0],
                        [(/ ..X..  X/),6],[(/..X..  X /),8],[(/X  ..X.. /),2]
                       ];

// regex matches if a player has won & supplies the winning player
var hasWonPatterns = [
                      [(/OOO....../),'O'],[(/...OOO.../),'O'],[(/......OOO/),'O'],
                      [(/O..O..O../),'O'],[(/.O..O..O./),'O'],[(/..O..O..O/),'O'],
                      [(/O...O...O/),'O'],[(/..O.O.O../),'O'],[(/XXX....../),'X'],
                      [(/...XXX.../),'X'],[(/......XXX/),'X'],[(/X..X..X../),'X'],
                      [(/.X..X..X./),'X'],[(/..X..X..X/),'X'],[(/X...X...X/),'X'],
                      [(/..X.X.X../),'X']
                     ];

var board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '];
var player1 = 'X';
var player2 = 'O';
var currentTurn = player1;

// this searches winningMovePatterns then blockingPatterns and if there is no
// match run firstMove()
var findNextMove = function(){
  var nextPos = makeWinningMove(board);
  if(nextPos === -1){
    nextPos = makeBlockingMove(board);
    if(nextPos === -1){
      nextPos = firstMove();
    }
  }
  makeMove(nextPos,player2);
};

var makeMove = function(pos, player){
  if(player != currentTurn){return false;}
  if(+pos >= 0 && +pos <= 8 && !isNaN(+pos) && board[+pos] === ' '){
    board.splice(+pos, 1, player);
    currentTurn = (player === player1) ? player2 : player1;
    return true;
  }
  return false;
};

var board_display = function(){
  return ' '+board[0]+' |'+' '+board[1]+' |'+' '+board[2]+'\n===+===+===\n'+' '+
             board[3]+' |'+' '+board[4]+' |'+' '+board[5]+'\n===+===+===\n'+' '+
             board[6]+' |'+' '+board[7]+' |'+' '+board[8];
};

var logBoardToConsole = function(){
  console.log(board_display());
};

// return true if the board is filled
var isBoardFilled = function(){
  if(board.indexOf(' ') === -1){
    logBoardToConsole();
    console.log("Game over, it's a draw!");
    return true;
  }
  return false;
};

// if the board matches a pattern from hasWonPatterns, return the winner
var hasSomeoneWon = function(board){
  var board_string = board.join('');
  var theWinner = null;
  for(var i = 0;i < hasWonPatterns.length;i++){
    var array = board_string.match(hasWonPatterns[i][0]);
    if(array){
      theWinner = hasWonPatterns[i][1];
    }
  }
  if(theWinner){
    logBoardToConsole();
    console.log('Game over');
    // console.log('Game over.', the_winner, 'is the winner!') Add this after tests
    return [true, theWinner];
  }
  return [false, null];
};

// return the next move by matching a pattern from winningMovePatterns and returning the number
// (the second value in the array)
var makeWinningMove = function(board){
  var board_string = board.join('');
  for(var i = 0;i < winningMovePatterns.length;i++){
    var array = board_string.match(winningMovePatterns[i][0]);
    if(array){ // this is only truthy when someone wins
      return winningMovePatterns[i][1];
    }
  }
  return -1;
};

// return the next move by matching a pattern from winningMovePatterns and returning the number
// (the second value in the array)
var makeBlockingMove = function(board){
  var board_string = board.join('');
  for(var i = 0;i < blockingPatterns.length;i++){
    var array = board_string.match(blockingPatterns[i][0]);
      if(array){return blockingPatterns[i][1];}
  }
  return -1;
};

// if the center of board is free, go there, if not go to position 0
var firstMove = function(){
  return board[4] === ' ' ? 4 : board.indexOf(' ');
};

var endGame = function(){
  process.exit();
};

var startGame = function(){
  logBoardToConsole();
  console.log("Enter [0-8]:");
  process.openStdin().on('data',function(res){
    if(makeMove(res, player1)){
      if(hasSomeoneWon(board)[0] || isBoardFilled()) {
        endGame();
      } else {
        findNextMove();
        if (hasSomeoneWon(board)[0] || isBoardFilled()) {
          endGame();
        } else {
          logBoardToConsole();
        }
      }
    }
  });
};

startGame();

// exports needed for tests
module.exports = {
  makeWinningMove : makeWinningMove,
  makeBlockingMove : makeBlockingMove,
  hasSomeoneWon : hasSomeoneWon
};
<|endoftext|>


<commit_before>// TODO COPYRIGHT
/*jslint nomen:true, white:true, node:true */
/*globals describe,it */
"use strict";

var libpath = require('path'),
    expect = require('chai').expect,
    BundleLocator = require(process.env.COVER_LOCATOR? '../../artifacts/lib-cov/bundleLocator.js' : '../../lib/bundleLocator.js'),
    Bundle = require(process.env.COVER_LOCATOR? '../../artifacts/lib-cov/bundle.js' : '../../lib/bundle.js'),
    fixturesPath = libpath.join(__dirname, '../fixtures');

function compareObjects(have, want) {
    expect(typeof have).to.equal(typeof want);
    if ('object' === typeof want) {
        // order of keys doesn't matter
        if (Object.keys(want).length) {
            expect(have).to.have.keys(Object.keys(want));
        }
        if (Object.keys(have).length) {
            expect(want).to.have.keys(Object.keys(have));
        }

        Object.keys(want).forEach(function(key) {
            compareObjects(have[key], want[key]);
        });
    } else {
        expect(have).to.deep.equal(want);
    }
}

describe('BundleLocator', function() {

    describe('locateBundles', function() {

        it('mojito-newsboxes', function(next) {
            var fixture = libpath.join(fixturesPath, 'mojito-newsboxes'),
                locator = new BundleLocator(),
                options = {};
            locator.locateBundles(fixture, options, function(err) {
                if (err) {
                    throw err;
                }
                var have = locator.getRootBundle();
                var want = require(fixture + '/expected-locator.js');
                compareObjects(have, want);
                next();
            });
        });

        it('touchdown-simple', function(next) {
            var fixture = libpath.join(fixturesPath, 'touchdown-simple'),
                locator = new BundleLocator(),
                options = {};
            locator.locateBundles(fixture, options, function(err) {
                if (err) {
                    throw err;
                }
                var have = locator.getRootBundle();
                var want = require(fixture + '/expected-locator.js');
                compareObjects(have, want);
                next();
            });
        });

    });

});

<commit_msg>delinted<commit_after>// TODO COPYRIGHT
/*jslint nomen:true, white:true, node:true */
/*globals describe,it */
"use strict";

var libpath = require('path'),
    expect = require('chai').expect,
    BundleLocator = require(process.env.COVER_LOCATOR? '../../artifacts/lib-cov/bundleLocator.js' : '../../lib/bundleLocator.js'),
    Bundle = require(process.env.COVER_LOCATOR? '../../artifacts/lib-cov/bundle.js' : '../../lib/bundle.js'),
    fixturesPath = libpath.join(__dirname, '../fixtures');

function compareObjects(have, want) {
    expect(typeof have).to.equal(typeof want);
    if ('object' === typeof want) {
        // order of keys doesn't matter
        if (Object.keys(want).length) {
            expect(have).to.have.keys(Object.keys(want));
        }
        if (Object.keys(have).length) {
            expect(want).to.have.keys(Object.keys(have));
        }

        Object.keys(want).forEach(function(key) {
            compareObjects(have[key], want[key]);
        });
    } else {
        expect(have).to.deep.equal(want);
    }
}

describe('BundleLocator', function() {

    describe('locateBundles', function() {

        it('mojito-newsboxes', function(next) {
            var fixture = libpath.join(fixturesPath, 'mojito-newsboxes'),
                locator = new BundleLocator(),
                options = {};
            locator.locateBundles(fixture, options, function(err) {
                var have, want;
                if (err) {
                    throw err;
                }
                have = locator.getRootBundle();
                want = require(fixture + '/expected-locator.js');
                compareObjects(have, want);
                next();
            });
        });

        it('touchdown-simple', function(next) {
            var fixture = libpath.join(fixturesPath, 'touchdown-simple'),
                locator = new BundleLocator(),
                options = {};
            locator.locateBundles(fixture, options, function(err) {
                var have, want;
                if (err) {
                    throw err;
                }
                have = locator.getRootBundle();
                want = require(fixture + '/expected-locator.js');
                compareObjects(have, want);
                next();
            });
        });

    });

});

<|endoftext|>


<commit_before>'use strict';

const Botkit = require('botkit');
const apiai = require('apiai');

const uuid = require('node-uuid');
const Entities = require('html-entities').XmlEntities;
const decoder = new Entities();

module.exports = function (apiaiToken) {
    return createApiAiProcessing(apiaiToken);
};

function isDefined(obj) {
    if (typeof obj == 'undefined') {
        return false;
    }

    if (!obj) {
        return false;
    }

    return obj != null;
}

function createApiAiProcessing(token) {
    let worker = {};

    worker.apiaiService = apiai(token, "subscription_key");
    worker.sessionIds = {};

    worker.actionCallbacks = {};
    worker.allCallback = [];

    worker.action = function (action, callback) {
        if (worker.actionCallbacks[action]) {
            worker.actionCallbacks[action].push(callback);
        } else {
            worker.actionCallbacks[action] = [callback];
        }

        return worker;
    };

    worker.all = function (callback) {
        worker.allCallback.push(callback);
        return worker;
    };

    worker.process = function (message, bot) {
        try {
            if (message.type == 'message') {
                if (message.user == bot.identity.id) {
                    // message from bot can be skipped
                }
                else if (message.text.indexOf("<@U") == 0 && message.text.indexOf(bot.identity.id) == -1) {
                    // skip other users direct mentions
                }
                else {
                    let requestText = decoder.decode(message.text);
                    requestText = requestText.replace("’", "'");

                    let channel = message.channel;
                    let messageType = message.event;
                    let botId = '<@' + bot.identity.id + '>';

                    if (requestText.indexOf(botId) > -1) {
                        requestText = requestText.replace(botId, '');
                    }

                    if (!(channel in worker.sessionIds)) {
                        worker.sessionIds[channel] = uuid.v1();
                    }

                    let request = worker.apiaiService.textRequest(requestText,
                        {
                            sessionId: worker.sessionIds[channel]
                        });

                    request.on('response', (response) => {

                        worker.allCallback.forEach((callback) => {
                            callback(message, response, bot);
                        });

                        if (isDefined(response.result)) {
                            let action = response.result.action;

                            if (isDefined(action)) {
                                if (worker.actionCallbacks[action]) {
                                    worker.actionCallbacks[action].forEach((callback) => {
                                        callback(message, response, bot);
                                    });
                                }
                            }
                        }
                    });

                    request.on('error', (error) => {
                        console.error(error);
                    });

                    request.end();

                }
            }
        } catch (err) {
            console.error(err);
        }
    };

    return worker;
}<commit_msg>Use new uuid module<commit_after>'use strict';

const Botkit = require('botkit');
const apiai = require('apiai');

const uuidV4 = require('uuid/v4');
const Entities = require('html-entities').XmlEntities;
const decoder = new Entities();

module.exports = function (apiaiToken) {
    return createApiAiProcessing(apiaiToken);
};

function isDefined(obj) {
    if (typeof obj == 'undefined') {
        return false;
    }

    if (!obj) {
        return false;
    }

    return obj != null;
}

function createApiAiProcessing(token) {
    let worker = {};

    worker.apiaiService = apiai(token, "subscription_key");
    worker.sessionIds = {};

    worker.actionCallbacks = {};
    worker.allCallback = [];

    worker.action = function (action, callback) {
        if (worker.actionCallbacks[action]) {
            worker.actionCallbacks[action].push(callback);
        } else {
            worker.actionCallbacks[action] = [callback];
        }

        return worker;
    };

    worker.all = function (callback) {
        worker.allCallback.push(callback);
        return worker;
    };

    worker.process = function (message, bot) {
        try {
            if (message.type == 'message') {
                if (message.user == bot.identity.id) {
                    // message from bot can be skipped
                }
                else if (message.text.indexOf("<@U") == 0 && message.text.indexOf(bot.identity.id) == -1) {
                    // skip other users direct mentions
                }
                else {
                    let requestText = decoder.decode(message.text);
                    requestText = requestText.replace("’", "'");

                    let channel = message.channel;
                    let messageType = message.event;
                    let botId = '<@' + bot.identity.id + '>';

                    if (requestText.indexOf(botId) > -1) {
                        requestText = requestText.replace(botId, '');
                    }

                    if (!(channel in worker.sessionIds)) {
                        worker.sessionIds[channel] = uuidV4();
                    }

                    let request = worker.apiaiService.textRequest(requestText,
                        {
                            sessionId: worker.sessionIds[channel]
                        });

                    request.on('response', (response) => {

                        worker.allCallback.forEach((callback) => {
                            callback(message, response, bot);
                        });

                        if (isDefined(response.result)) {
                            let action = response.result.action;

                            if (isDefined(action)) {
                                if (worker.actionCallbacks[action]) {
                                    worker.actionCallbacks[action].forEach((callback) => {
                                        callback(message, response, bot);
                                    });
                                }
                            }
                        }
                    });

                    request.on('error', (error) => {
                        console.error(error);
                    });

                    request.end();

                }
            }
        } catch (err) {
            console.error(err);
        }
    };

    return worker;
}<|endoftext|>