<commit_before>/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
           ______     ______     ______   __  __     __     ______
          /\  == \   /\  __ \   /\__  _\ /\ \/ /    /\ \   /\__  _\
          \ \  __<   \ \ \/\ \  \/_/\ \/ \ \  _"-.  \ \ \  \/_/\ \/
           \ \_____\  \ \_____\    \ \_\  \ \_\ \_\  \ \_\    \ \_\
            \/_____/   \/_____/     \/_/   \/_/\/_/   \/_/     \/_/

This is a sample Slack bot built with Botkit.

This bot demonstrates many of the core features of Botkit:

* Connect to Slack using the real time API
* Receive messages based on "spoken" patterns
* Reply to messages
* Use the conversation system to ask questions
* Use the built in storage system to store and retrieve information
  for a user.

# RUN THE BOT:

  Get a Bot token from Slack:

    -> http://my.slack.com/services/new/bot

  Run your bot from the command line:

    token=<MY TOKEN> node slack_bot.js

# USE THE BOT:

  Find your bot inside Slack to send it a direct message.

  Say: "Hello"

  The bot will reply "Hello!"

  Say: "who are you?"

  The bot will tell you its name, where it is running, and for how long.

  Say: "Call me <nickname>"

  Tell the bot your nickname. Now you are friends.

  Say: "who am I?"

  The bot will tell you your nickname, if it knows one for you.

  Say: "shutdown"

  The bot will ask if you are sure, and then shut itself down.

  Make sure to invite your bot into other channels using /invite @<my bot>!

# EXTEND THE BOT:

  Botkit has many features for building cool and useful bots!

  Read all about it here:

    -> http://howdy.ai/botkit

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

if (!process.env.token) {
    console.log('Error: Specify token in environment');
    process.exit(1);
}

var Botkit = require('./lib/Botkit.js');
var os = require('os');

var controller = Botkit.slackbot({
    debug: true,
});

var bot = controller.spawn({
    token: process.env.token
});

function start_rtm() {
  bot.startRTM(function(err,bot,payload) {
  if (err) {
    console.log('Failed to start RTM')
    return setTimeout(start_rtm, 30 * 1000);
  }
    console.log("RTM started!");
  });
}

start_rtm();
controller.on('rtm_close', start_rtm());

var initiateConversationStrings = ['des', 'de si', 'oo', 'ooo', 'oooo', 'ooooo', 'desi', 'alo', 'e', 'ee', 'eee'];
var firstSentanceStrings = ['Deste momci?', 'Svi na okupu a?', 'Deste smekeri?'];
var secondSentanceStrings = ['Radimo a?', 'Tu toma a?', 'Tu sofija a?', 'Tu milos a?', 'Tu igor a?'];
var finalSentanceStrings = ['Tu sam ja', 'Idem do tome nesto, sad cu ja'];

function getSentance (sentance) {
  return sentance[ Math.floor(Math.random() * sentance.length) ];
}

controller.hears(initiateConversationStrings, 'direct_message,direct_mention,mention', function(bot, message) {
  bot.startConversation(message, function(err, convo) {
    if (!err) {
      convo.say('Ooooo');
      var firstSentance = getSentance(firstSentanceStrings);
      var secondSentance = getSentance(secondSentanceStrings);
      convo.ask(firstSentance + " " + secondSentance, function(response, convo) {
        convo.say("Vazi, vazi");
        convo.stop();
      });
      convo.on('end', function(convo) {
        var finalSentance = getSentance(finalSentanceStrings);
        convo.say(finalSentance);
      });
    }
  });
});

controller.hears(['hello', 'hi'], 'direct_message,direct_mention,mention', function(bot, message) {

    bot.api.reactions.add({
        timestamp: message.ts,
        channel: message.channel,
        name: 'robot_face',
    }, function(err, res) {
        if (err) {
            bot.botkit.log('Failed to add emoji reaction :(', err);
        }
    });

    controller.storage.users.get(message.user, function(err, user) {
        if (user && user.name) {
            bot.reply(message, 'Hello ' + user.name + '!!');
        } else {
            bot.reply(message, 'Hello.');
        }
    });
});

controller.hears(['call me (.*)', 'my name is (.*)'], 'direct_message,direct_mention,mention', function(bot, message) {
    var name = message.match[1];
    controller.storage.users.get(message.user, function(err, user) {
        if (!user) {
            user = {
                id: message.user,
            };
        }
        user.name = name;
        controller.storage.users.save(user, function(err, id) {
            bot.reply(message, 'Got it. I will call you ' + user.name + ' from now on.');
        });
    });
});

controller.hears(['what is my name', 'who am i'], 'direct_message,direct_mention,mention', function(bot, message) {

    controller.storage.users.get(message.user, function(err, user) {
        if (user && user.name) {
            bot.reply(message, 'Your name is ' + user.name);
        } else {
            bot.startConversation(message, function(err, convo) {
                if (!err) {
                    convo.say('I do not know your name yet!');
                    convo.ask('What should I call you?', function(response, convo) {
                        convo.ask('You want me to call you `' + response.text + '`?', [
                            {
                                pattern: 'yes',
                                callback: function(response, convo) {
                                    // since no further messages are queued after this,
                                    // the conversation will end naturally with status == 'completed'
                                    convo.next();
                                }
                            },
                            {
                                pattern: 'no',
                                callback: function(response, convo) {
                                    // stop the conversation. this will cause it to end with status == 'stopped'
                                    convo.stop();
                                }
                            },
                            {
                                default: true,
                                callback: function(response, convo) {
                                    convo.repeat();
                                    convo.next();
                                }
                            }
                        ]);

                        convo.next();

                    }, {'key': 'nickname'}); // store the results in a field called nickname

                    convo.on('end', function(convo) {
                        if (convo.status == 'completed') {
                            bot.reply(message, 'OK! I will update my dossier...');

                            controller.storage.users.get(message.user, function(err, user) {
                                if (!user) {
                                    user = {
                                        id: message.user,
                                    };
                                }
                                user.name = convo.extractResponse('nickname');
                                controller.storage.users.save(user, function(err, id) {
                                    bot.reply(message, 'Got it. I will call you ' + user.name + ' from now on.');
                                });
                            });

                        } else {
                            // this happens if the conversation ended prematurely for some reason
                            bot.reply(message, 'OK, nevermind!');
                        }
                    });
                }
            });
        }
    });
});

controller.hears(['shutdown'], 'direct_message,direct_mention,mention', function(bot, message) {

    bot.startConversation(message, function(err, convo) {

        convo.ask('Are you sure you want me to shutdown?', [
            {
                pattern: bot.utterances.yes,
                callback: function(response, convo) {
                    convo.say('Bye!');
                    convo.next();
                    setTimeout(function() {
                        process.exit();
                    }, 3000);
                }
            },
        {
            pattern: bot.utterances.no,
            default: true,
            callback: function(response, convo) {
                convo.say('*Phew!*');
                convo.next();
            }
        }
        ]);
    });
});

controller.hears(['uptime', 'identify yourself', 'who are you', 'what is your name'],
    'direct_message,direct_mention,mention', function(bot, message) {

        var hostname = os.hostname();
        var uptime = formatUptime(process.uptime());

        bot.reply(message,
            ':robot_face: I am a bot named <@' + bot.identity.name +
             '>. I have been running for ' + uptime + ' on ' + hostname + '.');

    });

function formatUptime(uptime) {
    var unit = 'second';
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'minute';
    }
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'hour';
    }
    if (uptime != 1) {
        unit = unit + 's';
    }

    uptime = uptime + ' ' + unit;
    return uptime;
}
<commit_msg>Add tomaze response<commit_after>/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
           ______     ______     ______   __  __     __     ______
          /\  == \   /\  __ \   /\__  _\ /\ \/ /    /\ \   /\__  _\
          \ \  __<   \ \ \/\ \  \/_/\ \/ \ \  _"-.  \ \ \  \/_/\ \/
           \ \_____\  \ \_____\    \ \_\  \ \_\ \_\  \ \_\    \ \_\
            \/_____/   \/_____/     \/_/   \/_/\/_/   \/_/     \/_/

This is a sample Slack bot built with Botkit.

This bot demonstrates many of the core features of Botkit:

* Connect to Slack using the real time API
* Receive messages based on "spoken" patterns
* Reply to messages
* Use the conversation system to ask questions
* Use the built in storage system to store and retrieve information
  for a user.

# RUN THE BOT:

  Get a Bot token from Slack:

    -> http://my.slack.com/services/new/bot

  Run your bot from the command line:

    token=<MY TOKEN> node slack_bot.js

# USE THE BOT:

  Find your bot inside Slack to send it a direct message.

  Say: "Hello"

  The bot will reply "Hello!"

  Say: "who are you?"

  The bot will tell you its name, where it is running, and for how long.

  Say: "Call me <nickname>"

  Tell the bot your nickname. Now you are friends.

  Say: "who am I?"

  The bot will tell you your nickname, if it knows one for you.

  Say: "shutdown"

  The bot will ask if you are sure, and then shut itself down.

  Make sure to invite your bot into other channels using /invite @<my bot>!

# EXTEND THE BOT:

  Botkit has many features for building cool and useful bots!

  Read all about it here:

    -> http://howdy.ai/botkit

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

if (!process.env.token) {
    console.log('Error: Specify token in environment');
    process.exit(1);
}

var Botkit = require('./lib/Botkit.js');
var os = require('os');

var controller = Botkit.slackbot({
    debug: true,
});

var bot = controller.spawn({
    token: process.env.token
}).startRTM();

function start_rtm() {
  bot.startRTM(function(err,bot,payload) {
  if (err) {
    console.log('Failed to start RTM')
    return setTimeout(start_rtm, 30 * 1000);
  }
    console.log("RTM started!");
  });
}

start_rtm();
controller.on('rtm_close', start_rtm());

var initiateConversationStrings = ['des', 'de si', 'oo', 'ooo', 'oooo', 'ooooo', 'desi', 'alo', 'e', 'ee', 'eee'];
var firstSentanceStrings = ['Deste momci?', 'Svi na okupu a?', 'Deste smekeri?'];
var secondSentanceStrings = ['Radimo a?', 'Tu toma a?', 'Tu sofija a?', 'Tu milos a?', 'Tu igor a?'];
var finalSentanceStrings = ['Tu sam ja', 'Idem do tome nesto, sad cu ja'];

function getSentance (sentance) {
  return sentance[ Math.floor(Math.random() * sentance.length) ];
}

controller.hears(initiateConversationStrings, 'direct_message,direct_mention,mention', function(bot, message) {
  bot.startConversation(message, function(err, convo) {
    if (!err) {
      convo.say('Ooooo');
      var firstSentance = getSentance(firstSentanceStrings);
      var secondSentance = getSentance(secondSentanceStrings);
      convo.ask(firstSentance + " " + secondSentance, function(response, convo) {
        convo.say("Vazi, vazi");
        convo.stop();
      });
      convo.on('end', function(convo) {
        var finalSentance = getSentance(finalSentanceStrings);
        convo.say(finalSentance);
      });
    }
  });
});

controller.hears(['hello', 'hi'], 'direct_message,direct_mention,mention', function(bot, message) {

    bot.api.reactions.add({
        timestamp: message.ts,
        channel: message.channel,
        name: 'robot_face',
    }, function(err, res) {
        if (err) {
            bot.botkit.log('Failed to add emoji reaction :(', err);
        }
    });

    controller.storage.users.get(message.user, function(err, user) {
        if (user && user.name) {
            bot.reply(message, 'Hello ' + user.name + '!!');
        } else {
            bot.reply(message, 'Hello.');
        }
    });
});

controller.hears(['call me (.*)', 'my name is (.*)'], 'direct_message,direct_mention,mention', function(bot, message) {
    var name = message.match[1];
    controller.storage.users.get(message.user, function(err, user) {
        if (!user) {
            user = {
                id: message.user,
            };
        }
        user.name = name;
        controller.storage.users.save(user, function(err, id) {
            bot.reply(message, 'Got it. I will call you ' + user.name + ' from now on.');
        });
    });
});

controller.hears(['what is my name', 'who am i'], 'direct_message,direct_mention,mention', function(bot, message) {

    controller.storage.users.get(message.user, function(err, user) {
        if (user && user.name) {
            bot.reply(message, 'Your name is ' + user.name);
        } else {
            bot.startConversation(message, function(err, convo) {
                if (!err) {
                    convo.say('I do not know your name yet!');
                    convo.ask('What should I call you?', function(response, convo) {
                        convo.ask('You want me to call you `' + response.text + '`?', [
                            {
                                pattern: 'yes',
                                callback: function(response, convo) {
                                    // since no further messages are queued after this,
                                    // the conversation will end naturally with status == 'completed'
                                    convo.next();
                                }
                            },
                            {
                                pattern: 'no',
                                callback: function(response, convo) {
                                    // stop the conversation. this will cause it to end with status == 'stopped'
                                    convo.stop();
                                }
                            },
                            {
                                default: true,
                                callback: function(response, convo) {
                                    convo.repeat();
                                    convo.next();
                                }
                            }
                        ]);

                        convo.next();

                    }, {'key': 'nickname'}); // store the results in a field called nickname

                    convo.on('end', function(convo) {
                        if (convo.status == 'completed') {
                            bot.reply(message, 'OK! I will update my dossier...');

                            controller.storage.users.get(message.user, function(err, user) {
                                if (!user) {
                                    user = {
                                        id: message.user,
                                    };
                                }
                                user.name = convo.extractResponse('nickname');
                                controller.storage.users.save(user, function(err, id) {
                                    bot.reply(message, 'Got it. I will call you ' + user.name + ' from now on.');
                                });
                            });

                        } else {
                            // this happens if the conversation ended prematurely for some reason
                            bot.reply(message, 'OK, nevermind!');
                        }
                    });
                }
            });
        }
    });
});

controller.hears(['shutdown'], 'direct_message,direct_mention,mention', function(bot, message) {

    bot.startConversation(message, function(err, convo) {

        convo.ask('Are you sure you want me to shutdown?', [
            {
                pattern: bot.utterances.yes,
                callback: function(response, convo) {
                    convo.say('Bye!');
                    convo.next();
                    setTimeout(function() {
                        process.exit();
                    }, 3000);
                }
            },
        {
            pattern: bot.utterances.no,
            default: true,
            callback: function(response, convo) {
                convo.say('*Phew!*');
                convo.next();
            }
        }
        ]);
    });
});

controller.hears(['uptime', 'identify yourself', 'who are you', 'what is your name'],
    'direct_message,direct_mention,mention', function(bot, message) {

        var hostname = os.hostname();
        var uptime = formatUptime(process.uptime());

        bot.reply(message,
            ':robot_face: I am a bot named <@' + bot.identity.name +
             '>. I have been running for ' + uptime + ' on ' + hostname + '.');

    });

function formatUptime(uptime) {
    var unit = 'second';
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'minute';
    }
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'hour';
    }
    if (uptime != 1) {
        unit = unit + 's';
    }

    uptime = uptime + ' ' + unit;
    return uptime;
}
<|endoftext|>


<commit_before>/** AutoMarkings Plugin for flot
 * https://github.com/kcdr/flot-autoMarkings/edit/master/README.md
 *
 * Copyright (c) 2015 kcdr
 *
 * Licensed under the MIT license.
 *
 * Version v0.2.2
 *
 */

(function ($) {
    function init(plot) {

        function autoMarkingsFunction(plot, offset) {
        	plot.getOptions().grid.markings = new Array();
        	$(plot.getData()).each(function(){
        		if (this.autoMarkings && this.autoMarkings.enabled === true) {
                    if( plot.getOptions().grid.markings==null ) plot.getOptions().grid.markings = new Array();

                    if( this.autoMarkings.showMinMax === true || this.autoMarkings.showAvg === true )
                    {
	                    if( this.autoMarkings.min==null || this.autoMarkings.max==null || this.autoMarkings.avg==null ){
	        				var min=Number.MAX_VALUE;
	        				var max=0;
	        				var sum = 0;
	        				var count = 0;
	        				$(this.data).each(function(){
	        					if( this[1] < min) min=this[1];
	        					if( this[1] > max) max=this[1];
	        					count++;
	        					sum += this[1];
	        				});
	        				if( this.autoMarkings.min==null ) this.autoMarkings.min = min;
	        				if( this.autoMarkings.max==null ) this.autoMarkings.max = max;
	        				if( this.autoMarkings.avg==null ) this.autoMarkings.avg = sum/count;
	        			}
                    }

                    var seriesColor = this.autoMarkings.color || this.color;
                    var avgseriesColor = this.autoMarkings.avgcolor || this.color;

                    var axis = "y"+(this.yaxis.n>1?this.yaxis.n:"")+"axis";

	        		if( this.autoMarkings.showMinMax === true && this.autoMarkings.min!=Number.MAX_VALUE && this.autoMarkings.max!=0 )
	        		{
	        			var marking = { color: seriesColor.replace('rgb(','rgba(').replace(')',','+this.autoMarkings.minMaxAlpha+')') };
	        			marking[axis] = { from: this.autoMarkings.min, to: this.autoMarkings.max };
	        			plot.getOptions().grid.markings.push(marking);
	        		}
	        		if( this.autoMarkings.showAvg === true && this.autoMarkings.avg!=Number.NaN)
	        		{
	        			var marking = { color: avgseriesColor };
	        			marking[axis] = { from: this.autoMarkings.avg, to: this.autoMarkings.avg };
	        			plot.getOptions().grid.markings.push(marking);
	        		}
        		}
        	});
        }

        plot.hooks.processOffset.push(autoMarkingsFunction);
    }

    var options = {series: { autoMarkings: {enabled: false, minMaxAlpha:0.2}}};

    /** Options
     * enabled
     * color
     * avgcolor
     * showMinMax
     * minMaxAlpha
     * showAvg
     * min
     * max
     * avg
     */

    $.plot.plugins.push({
        init: init,
        options: options,
        name: "autoMarkings",
        version: "0.2.2"
    });
})(jQuery);
<commit_msg>Update jquery.flot.autoMarkings.js<commit_after>/** AutoMarkings Plugin for flot
 * https://github.com/kcdr/flot-autoMarkings/edit/master/README.md
 *
 * Copyright (c) 2015 kcdr
 *
 * Licensed under the MIT license.
 *
 * Version v0.2.2
 *
 */

(function ($) {
    function init(plot) {

        function autoMarkingsFunction(plot, offset) {
        	plot.getOptions().grid.markings = new Array();
        	$(plot.getData()).each(function(){
        		if (this.autoMarkings && this.autoMarkings.enabled === true) {
                    if( plot.getOptions().grid.markings==null ) plot.getOptions().grid.markings = new Array();

                    if( this.autoMarkings.showMinMax === true || this.autoMarkings.showAvg === true )
                    {
	                    if( this.autoMarkings.min==null || this.autoMarkings.max==null || this.autoMarkings.avg==null ){
				var min=Number.MAX_VALUE;
				var max=0;
				var sum = 0;
				var count = 0;
				$(this.data).each(function(){
					if( this[1] < min) min=this[1];
					if( this[1] > max) max=this[1];
					count++;
					sum += this[1];
				});
				if( this.autoMarkings.min==null ) this.autoMarkings.min = min;
				if( this.autoMarkings.max==null ) this.autoMarkings.max = max;
				if( this.autoMarkings.avg==null ) this.autoMarkings.avg = sum/count;
			}
			if( this.autoMarkings.lineWidth ){
				plot.getOptions().grid.markingsLineWidth = parseInt( this.autoMarkings.lineWidth );
			}
                    }

                    var seriesColor = this.autoMarkings.color || this.color;
                    var avgseriesColor = this.autoMarkings.avgcolor || this.color;

                    var axis = "y"+(this.yaxis.n>1?this.yaxis.n:"")+"axis";

	        		if( this.autoMarkings.showMinMax === true && this.autoMarkings.min!=Number.MAX_VALUE && this.autoMarkings.max!=0 )
	        		{
	        			var marking = { color: seriesColor.replace('rgb(','rgba(').replace(')',','+this.autoMarkings.minMaxAlpha+')') };
	        			marking[axis] = { from: this.autoMarkings.min, to: this.autoMarkings.max };
	        			plot.getOptions().grid.markings.push(marking);
	        		}
	        		if( this.autoMarkings.showAvg === true && this.autoMarkings.avg!=Number.NaN)
	        		{
	        			var marking = { color: avgseriesColor };
	        			marking[axis] = { from: this.autoMarkings.avg, to: this.autoMarkings.avg };
	        			plot.getOptions().grid.markings.push(marking);
	        		}
        		}
        	});
        }

        plot.hooks.processOffset.push(autoMarkingsFunction);
    }

    var options = {series: { autoMarkings: {enabled: false, minMaxAlpha: 0.2, lineWidth: 2}}};

    /** Options
     * enabled
     * color
     * avgcolor
     * showMinMax
     * minMaxAlpha
     * showAvg
     * min
     * max
     * avg
     */

    $.plot.plugins.push({
        init: init,
        options: options,
        name: "autoMarkings",
        version: "0.2.2"
    });
})(jQuery);
<|endoftext|>


<commit_before>function __processArg(obj, key) {
    var arg = null;
    if (obj) {
        arg = obj[key] || null;
        delete obj[key];
    }
    return arg;
}

function Controller() {
    function searchItem(items, id) {
        var item = null;
        for (var i in items) {
            if ("object" != typeof items[i]) continue;
            if (isNaN(parseInt(i))) {
                item = searchItem(items[i], id);
                if (item) return item;
            } else if (items[i].id && items[i].id == id) return items[i];
        }
        return null;
    }
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "accommodations";
    if (arguments[0]) {
        __processArg(arguments[0], "__parentSymbol");
        __processArg(arguments[0], "$model");
        __processArg(arguments[0], "__itemTemplate");
    }
    var $ = this;
    var exports = {};
    $.__views.accommodations = Ti.UI.createWindow({
        id: "accommodations"
    });
    $.__views.accommodations && $.addTopLevelView($.__views.accommodations);
    exports.destroy = function() {};
    _.extend($, $.__views);
    arguments[0] || {};
    var data = require("data"), eventData = data.get("eventData"), windowReference = data.get("windowReference");
    var accommodationOnclick = function(id) {
        data.set("accommodationItem", searchItem(eventData.agenda, id));
        var detailWindow = Alloy.createController("accommodationDetail").getView();
        "android" == Titanium.Platform.osname ? detailWindow.open({
            modal: true
        }) : windowReference.openWindow(detailWindow, {
            animated: true
        });
    };
    var accommodationNavigation = require("listNavigation");
    accommodationNavigation.add(eventData.accommodations_label, eventData.accommodations, accommodationOnclick, windowReference, eventData.styles.background, $.accommodations);
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;<commit_msg>Accommodation detail was using agenda items.<commit_after>function __processArg(obj, key) {
    var arg = null;
    if (obj) {
        arg = obj[key] || null;
        delete obj[key];
    }
    return arg;
}

function Controller() {
    function searchItem(items, id) {
        var item = null;
        for (var i in items) {
            if ("object" != typeof items[i]) continue;
            if (isNaN(parseInt(i))) {
                item = searchItem(items[i], id);
                if (item) return item;
            } else if (items[i].id && items[i].id == id) return items[i];
        }
        return null;
    }
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "accommodations";
    if (arguments[0]) {
        __processArg(arguments[0], "__parentSymbol");
        __processArg(arguments[0], "$model");
        __processArg(arguments[0], "__itemTemplate");
    }
    var $ = this;
    var exports = {};
    $.__views.accommodations = Ti.UI.createWindow({
        id: "accommodations"
    });
    $.__views.accommodations && $.addTopLevelView($.__views.accommodations);
    exports.destroy = function() {};
    _.extend($, $.__views);
    arguments[0] || {};
    var data = require("data"), eventData = data.get("eventData"), windowReference = data.get("windowReference");
    var accommodationOnclick = function(id) {
        data.set("accommodationItem", searchItem(eventData.accommodations, id));
        var detailWindow = Alloy.createController("accommodationDetail").getView();
        "android" == Titanium.Platform.osname ? detailWindow.open({
            modal: true
        }) : windowReference.openWindow(detailWindow, {
            animated: true
        });
    };
    var accommodationNavigation = require("listNavigation");
    accommodationNavigation.add(eventData.accommodations_label, eventData.accommodations, accommodationOnclick, windowReference, eventData.styles.background, $.accommodations);
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;<|endoftext|>


<commit_before>/*
    utils:
        Various utility functions for all modes.
*/

var getUrlParameter = function (sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1));
    var sURLVariables = sPageURL.split('&');

    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};

var arrayContains = function(array, needle) {
   for (var index in array) {
      if (needle == array[index]) {
         return true;
      }
   }
   return false;
};

/**
 * This method allow us to verify if the current value is primitive. A primitive is a string or a number or boolean
 * (any value that can be safely compared
 * @param obj The object to check if it is a primitive or not
 * @return {boolean} true if object is primitive, false otherwise
 */
function isPrimitive(obj)
{
    return (obj !== Object(obj));
}

/**
 * THis function allow us to compare two objects. Do not call with {@code null} or {@code undefined}
 * Be careful! Do not use this with circular objects.
 * @param obj1 The first object to compare
 * @param obj2 The second object to compare
 * @return {boolean} true if objects are equals, false otherwise.
 */
function deepEqual(obj1, obj2) {

    if (obj1 === obj2) // it's just the same object. No need to compare.
        return true;

    // if one is primitive and not the other, then we can return false. If both are primitive, then the up
    // comparison can return true
    if (isPrimitive(obj1) || isPrimitive(obj2))
        return false;

    if (Object.keys(obj1).length !== Object.keys(obj2).length)
        return false;

    // compare objects with same number of keys
    for (var key in obj1)
    {
        if (!(key in obj2)) return false; //other object doesn't have this prop
        if (!deepEqual(obj1[key], obj2[key])) return false;
    }

    return true;
}

var highlightPause = false;

function resetFormElement(e) {
  e.wrap('<form>').closest('form').get(0).reset();
  e.unwrap();

  // Prevent form submission
  //e.stopPropagation();
  //e.preventDefault();
}

// from http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format
// where they got it from the stackoverflow-code itself ("formatUnicorn")
if (!String.prototype.format) {
   String.prototype.format = function() {
      var str = this.toString();
      if (!arguments.length)
         return str;
      var args = typeof arguments[0],
          args = (("string" == args || "number" == args) ? arguments : arguments[0]);
      for (var arg in args) {
         str = str.replace(RegExp("\\{" + arg + "\\}", "gi"), args[arg]);
      }
      return str;
   }
}

function showModal(id) {
   var el = '#' + id;
   $(el).show();
}
function closeModal(id) {
   var el = '#' + id;
   $(el).hide();
}

// Merges arrays by values
// (Flat-Copy only)
function mergeIntoArray(into, other) {
   for (var iOther in other) {
      var intoContains = false;

      for (var iInto in into) {
         if (other[iOther] == into[iInto]) {
            intoContains = true;
         }
      }

      if (!intoContains) {
         into.push(other[iOther]);
      }
   }
}

// Merges objects into each other similar to $.extend, but
// merges Arrays differently (see above)
// (Deep-Copy only)
function mergeIntoObject(into, other) {
   for (var property in other) {
      if (other[property] instanceof Array) {
         if (!(into[property] instanceof Array)) {
            into[property] = [];
         }
         mergeIntoArray(into[property], other[property]);
      }
      if (other[property] instanceof Object) {
         if (!(into[property] instanceof Object)) {
            into[property] = {};
         }
         mergeIntoObject(into[property], other[property]);
      }
      into[property] = other[property];
   }
}

/*
{ shared: { field1: X }, easy: { field2: Y } } becomes { field1: X, field2: Y } if the current level is easy
{ shared: [X, Y], easy: [Z] }  becomes [X, Y, Z] if the current level is easy
{ easy: X, medium: Y, hard: Z}  becomes X if the current level is easy
*/

function testLevelSpecific() {
   var tests = [
      {
         in: { field1: "X", field2: "Y" },
         out: { field1: "X", field2: "Y" }
      },
      {
            in: { easy: "X", medium: "Y", hard: "Z"},
            out: "X"
      },
      {
          in: { shared: { field1: "X" }, easy: { field2: "Y" } },
          out: { field1: "X", field2: "Y" }
      },
      {
            in: { shared: ["X", "Y"], easy: ["Z"] },
            out: ["X", "Y", "Z"]
      }
   ];
   for (var iTest = 0; iTest < tests.length; iTest++) {
      var res = extractLevelSpecific(tests[iTest].in, "easy");
      if (JSON.stringify(res) != JSON.stringify(tests[iTest].out)) { // TODO better way to compare two objects
         console.error("Test " + iTest + " failed: returned " + JSON.stringify(res));
      }
   }
}

// We need to be able to clean all events

if (Node && Node.prototype.addEventListenerBase == undefined) {
   // IE11 doesn't have EventTarget
   if(typeof EventTarget === 'undefined') {
      var targetPrototype = Node.prototype;
   } else {
      var targetPrototype = EventTarget.prototype;
   }
   targetPrototype.addEventListenerBase = targetPrototype.addEventListener;
   targetPrototype.addEventListener = function(type, listener)
   {
       if(!this.EventList) { this.EventList = []; }
       this.addEventListenerBase.apply(this, arguments);
       if(!this.EventList[type]) { this.EventList[type] = []; }
       var list = this.EventList[type];
       for(var index = 0; index != list.length; index++)
       {
           if(list[index] === listener) { return; }
       }
       list.push(listener);
   };

   targetPrototype.removeEventListenerBase = targetPrototype.removeEventListener;
   targetPrototype.removeEventListener = function(type, listener)
   {
       if(!this.EventList) { this.EventList = []; }
       if(listener instanceof Function) { this.removeEventListenerBase.apply(this, arguments); }
       if(!this.EventList[type]) { return; }
       var list = this.EventList[type];
       for(var index = 0; index != list.length;)
       {
           var item = list[index];
           if(!listener)
           {
               this.removeEventListenerBase(type, item);
               list.splice(index, 1); continue;
           }
           else if(item === listener)
           {
               list.splice(index, 1); break;
           }
           index++;
       }
       if(list.length == 0) { delete this.EventList[type]; }
   };
}

function debounce(fn, threshold, wait) {
   var timeout;
   return function debounced() {
      if (timeout) {
         if(wait) {
            clearTimeout(timeout);
         } else {
            return;
         }
      }
      function delayed() {
         fn();
         timeout = null;
      }
      timeout = setTimeout(delayed, threshold || 100);
   }
}

function addInSet(l, val) {
   // Add val to list l if not already present
   if(l.indexOf(val) == -1) {
      l.push(val);
   }
}

// From w3schools.com
function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "-header")) {
    // if present, the header is where you move the DIV from:
    document.getElementById(elmnt.id + "-header").onmousedown = dragMouseDown;
  } else {
    // otherwise, move the DIV from anywhere inside the DIV:
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

window.SrlLogger = {
   active: false,
   version: 0
   };

SrlLogger.load = function() {
   SrlLogger.active = true;

   SrlLogger.logMouseInit();
   SrlLogger.logKeyboardInit();
};

SrlLogger.logMouseInit = function() {
   if(SrlLogger.logMouseInitialized) { return; }

   SrlLogger.mouseButtons = {'left': false, 'right': false};

   window.addEventListener('mousedown', SrlLogger.logMouse);
   window.addEventListener('mousemove', SrlLogger.logMouse);
   window.addEventListener('mouseup', SrlLogger.logMouse);

   SrlLogger.logMouseInitialized = true;
};

SrlLogger.logMouse = function(e) {
   if(!SrlLogger.active) { return; }
   if(e.type == 'mousemove' && SrlLogger.mouseMoveIgnore) { return; }

   var state = 'aucun';

   if(e.type == 'mousedown' || e.type == 'mouseup') {
      var newval = e.type == 'mousedown';
      if(e.button === 0) {
         var btn = 'left';
      } else if(e.button === 2) {
         var btn = 'right';
      } else {
         return;
      }
      SrlLogger.mouseButtons[btn] = newval;

      state = btn == 'left' ? 'clic gauche' : 'clic droit';
   }

   if(e.type == 'mousemove') {
      // Throttle mousemove events
      SrlLogger.mouseMoveIgnore = true;
      setTimeout(function () { SrlLogger.mouseMoveIgnore = false; }, 100);

      if(SrlLogger.mouseButtons['left'] || SrlLogger.mouseButtons['right']) {
         state = 'drag';
      }
   }

   var zone = 'task';
   var target = $(e.target);
   var targetParent = null;
   if((targetParent = target.parents('#blocklyLibContent')).length) {
      zone = 'editor';
   } else if((targetParent = target.parents('#gridContainer')).length) {
      zone = 'grid';
   } else if((targetParent = target.parents('.speedControls')).length) {
      zone = 'controls';
   } else {
      targetParent = null;
   }

   var tpx = e.pageX;
   var tpy = e.pageY;

   var win = $(window);
   var winw = win.width();
   var winh = win.height();
   var tpw = winw;
   var tph = winh;
   if(targetParent) {
      var tpo = targetParent.offset();
      tpx -= Math.floor(tpo.left);
      tpy -= Math.floor(tpo.top);
      tpw = Math.floor(targetParent.width());
      tph = Math.floor(targetParent.height());
   }
   var data = {
      'reference': 'souris',
      'version': SrlLogger.version,
      'zone': zone,
      'etat': state,
      'coordonnees_ecran_x': e.screenX,
      'coordonnees_ecran_y': e.screenY,
      'coordonnees_page_x': e.pageX,
      'coordonnees_page_y': e.pageY,
      'coordonnees_zone_x': tpx,
      'coordonnees_zone_y': tpy,
      'dimension_zone_longueur': tpw,
      'dimension_zone_hauteur': tph,
      'dimension_page_longueur': win.width(),
      'dimension_page_hauteur': win.height()
      };

   platform.log(['srl', data]);
};

SrlLogger.logKeyboardInit = function() {
   if(SrlLogger.logKeyboardInitialized) { return; }

   window.addEventListener('keydown', SrlLogger.logKeyboard);

   SrlLogger.logKeyboardInitialized = true;
};

SrlLogger.logKeyboard = function(e) {
   if(!SrlLogger.active) { return; }

   var text = e.key;
   var data = {
      'reference': 'clavier',
      'version': SrlLogger.version,
      'touche': text
      };
   platform.log(['srl', data]);
};

SrlLogger.stepByStep = function(subtask, type) {
   if(!SrlLogger.active) { return; }

   var srlType = '';
   if(type == 'play') {
      srlType = subtask.context.actionDelay == 0 ? 'Aller à la fin' : 'Exécution automatique';
   } else if(type == 'step') {
      srlType = 'Exécution Manuelle';
   } else if(type == 'stop') {
      srlType = 'Revenir au début';
   }

   var data = {
      reference: 'pas_a_pas',
      version: SrlLogger.version,
      action: srlType,
      vitesse: subtask.context.infos.actionDelay
      };
   platform.log(['srl', data]);
};

SrlLogger.navigation = function(type) {
   if(!SrlLogger.active) { return; }

   var data = {
      reference: 'navigation',
      version: SrlLogger.version,
      module: type
      };
   platform.log(['srl', data]);
};

SrlLogger.levelLoaded = function(level) {
   if(!SrlLogger.active || SrlLogger.lastLevelLoaded == level) { return; }

   SrlLogger.lastLevelLoaded = level;

   var defaultLevelsRanks = { basic: 1, easy: 2, medium: 3, hard: 4 };
   var version = defaultLevelsRanks[level];
   if(!version) { version = 5; }

   if(version == SrlLogger.version) { return; }

   SrlLogger.version = version;
   SrlLogger.navigation('Exercice');
};

SrlLogger.validation = function(score, error, experimentation) {
   if(!SrlLogger.active) { return; }

   if(error == 'code') {
      error = 'Erreur de prérequis';
   } else if(error == 'execution') {
      error = 'Erreur de solution';
   } else {
      error = 'Aucune';
   }
   var data = {
      reference: 'validation',
      version: SrlLogger.version,
      score: score,
      experimentation: experimentation,
      'type_erreur': error
      };
   platform.log(['srl', data]);
};

SrlLogger.modification = function(len, error) {
   if(!SrlLogger.active) { return; }

   if(error == 'code') {
      error = 'Erreur de prérequis';
   } else if(error == 'execution') {
      error = 'Erreur de solution';
   } else {
      error = 'Aucune';
   }
   var data = {
      reference: 'modification',
      version: SrlLogger.version,
      'taille_reponse': len,
      erreur: error
      };
   platform.log(['srl', data]);
};

window.iOSDetected = (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) || (navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform));

(function() {
   var detectTouch = null;
   detectTouch = function() {
      window.touchDetected = true;
      window.removeEventListener('touchstart', detectTouch);
      }
   window.addEventListener('touchstart', detectTouch);
})();
<commit_msg>quickAlgo-SRL: Capture all events properly<commit_after>/*
    utils:
        Various utility functions for all modes.
*/

var getUrlParameter = function (sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1));
    var sURLVariables = sPageURL.split('&');

    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};

var arrayContains = function(array, needle) {
   for (var index in array) {
      if (needle == array[index]) {
         return true;
      }
   }
   return false;
};

/**
 * This method allow us to verify if the current value is primitive. A primitive is a string or a number or boolean
 * (any value that can be safely compared
 * @param obj The object to check if it is a primitive or not
 * @return {boolean} true if object is primitive, false otherwise
 */
function isPrimitive(obj)
{
    return (obj !== Object(obj));
}

/**
 * THis function allow us to compare two objects. Do not call with {@code null} or {@code undefined}
 * Be careful! Do not use this with circular objects.
 * @param obj1 The first object to compare
 * @param obj2 The second object to compare
 * @return {boolean} true if objects are equals, false otherwise.
 */
function deepEqual(obj1, obj2) {

    if (obj1 === obj2) // it's just the same object. No need to compare.
        return true;

    // if one is primitive and not the other, then we can return false. If both are primitive, then the up
    // comparison can return true
    if (isPrimitive(obj1) || isPrimitive(obj2))
        return false;

    if (Object.keys(obj1).length !== Object.keys(obj2).length)
        return false;

    // compare objects with same number of keys
    for (var key in obj1)
    {
        if (!(key in obj2)) return false; //other object doesn't have this prop
        if (!deepEqual(obj1[key], obj2[key])) return false;
    }

    return true;
}

var highlightPause = false;

function resetFormElement(e) {
  e.wrap('<form>').closest('form').get(0).reset();
  e.unwrap();

  // Prevent form submission
  //e.stopPropagation();
  //e.preventDefault();
}

// from http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format
// where they got it from the stackoverflow-code itself ("formatUnicorn")
if (!String.prototype.format) {
   String.prototype.format = function() {
      var str = this.toString();
      if (!arguments.length)
         return str;
      var args = typeof arguments[0],
          args = (("string" == args || "number" == args) ? arguments : arguments[0]);
      for (var arg in args) {
         str = str.replace(RegExp("\\{" + arg + "\\}", "gi"), args[arg]);
      }
      return str;
   }
}

function showModal(id) {
   var el = '#' + id;
   $(el).show();
}
function closeModal(id) {
   var el = '#' + id;
   $(el).hide();
}

// Merges arrays by values
// (Flat-Copy only)
function mergeIntoArray(into, other) {
   for (var iOther in other) {
      var intoContains = false;

      for (var iInto in into) {
         if (other[iOther] == into[iInto]) {
            intoContains = true;
         }
      }

      if (!intoContains) {
         into.push(other[iOther]);
      }
   }
}

// Merges objects into each other similar to $.extend, but
// merges Arrays differently (see above)
// (Deep-Copy only)
function mergeIntoObject(into, other) {
   for (var property in other) {
      if (other[property] instanceof Array) {
         if (!(into[property] instanceof Array)) {
            into[property] = [];
         }
         mergeIntoArray(into[property], other[property]);
      }
      if (other[property] instanceof Object) {
         if (!(into[property] instanceof Object)) {
            into[property] = {};
         }
         mergeIntoObject(into[property], other[property]);
      }
      into[property] = other[property];
   }
}

/*
{ shared: { field1: X }, easy: { field2: Y } } becomes { field1: X, field2: Y } if the current level is easy
{ shared: [X, Y], easy: [Z] }  becomes [X, Y, Z] if the current level is easy
{ easy: X, medium: Y, hard: Z}  becomes X if the current level is easy
*/

function testLevelSpecific() {
   var tests = [
      {
         in: { field1: "X", field2: "Y" },
         out: { field1: "X", field2: "Y" }
      },
      {
            in: { easy: "X", medium: "Y", hard: "Z"},
            out: "X"
      },
      {
          in: { shared: { field1: "X" }, easy: { field2: "Y" } },
          out: { field1: "X", field2: "Y" }
      },
      {
            in: { shared: ["X", "Y"], easy: ["Z"] },
            out: ["X", "Y", "Z"]
      }
   ];
   for (var iTest = 0; iTest < tests.length; iTest++) {
      var res = extractLevelSpecific(tests[iTest].in, "easy");
      if (JSON.stringify(res) != JSON.stringify(tests[iTest].out)) { // TODO better way to compare two objects
         console.error("Test " + iTest + " failed: returned " + JSON.stringify(res));
      }
   }
}

// We need to be able to clean all events

if (Node && Node.prototype.addEventListenerBase == undefined) {
   // IE11 doesn't have EventTarget
   if(typeof EventTarget === 'undefined') {
      var targetPrototype = Node.prototype;
   } else {
      var targetPrototype = EventTarget.prototype;
   }
   targetPrototype.addEventListenerBase = targetPrototype.addEventListener;
   targetPrototype.addEventListener = function(type, listener)
   {
       if(!this.EventList) { this.EventList = []; }
       this.addEventListenerBase.apply(this, arguments);
       if(!this.EventList[type]) { this.EventList[type] = []; }
       var list = this.EventList[type];
       for(var index = 0; index != list.length; index++)
       {
           if(list[index] === listener) { return; }
       }
       list.push(listener);
   };

   targetPrototype.removeEventListenerBase = targetPrototype.removeEventListener;
   targetPrototype.removeEventListener = function(type, listener)
   {
       if(!this.EventList) { this.EventList = []; }
       if(listener instanceof Function) { this.removeEventListenerBase.apply(this, arguments); }
       if(!this.EventList[type]) { return; }
       var list = this.EventList[type];
       for(var index = 0; index != list.length;)
       {
           var item = list[index];
           if(!listener)
           {
               this.removeEventListenerBase(type, item);
               list.splice(index, 1); continue;
           }
           else if(item === listener)
           {
               list.splice(index, 1); break;
           }
           index++;
       }
       if(list.length == 0) { delete this.EventList[type]; }
   };
}

function debounce(fn, threshold, wait) {
   var timeout;
   return function debounced() {
      if (timeout) {
         if(wait) {
            clearTimeout(timeout);
         } else {
            return;
         }
      }
      function delayed() {
         fn();
         timeout = null;
      }
      timeout = setTimeout(delayed, threshold || 100);
   }
}

function addInSet(l, val) {
   // Add val to list l if not already present
   if(l.indexOf(val) == -1) {
      l.push(val);
   }
}

// From w3schools.com
function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "-header")) {
    // if present, the header is where you move the DIV from:
    document.getElementById(elmnt.id + "-header").onmousedown = dragMouseDown;
  } else {
    // otherwise, move the DIV from anywhere inside the DIV:
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

window.SrlLogger = {
   active: false,
   version: 0
   };

SrlLogger.load = function() {
   SrlLogger.active = true;

   SrlLogger.logMouseInit();
   SrlLogger.logKeyboardInit();
};

SrlLogger.logMouseInit = function() {
   if(SrlLogger.logMouseInitialized) { return; }

   SrlLogger.mouseButtons = {'left': false, 'right': false};

   window.addEventListener('mousedown', SrlLogger.logMouse, true);
   window.addEventListener('mousemove', SrlLogger.logMouse, true);
   window.addEventListener('mouseup', SrlLogger.logMouse, true);

   SrlLogger.logMouseInitialized = true;
};

SrlLogger.logMouse = function(e) {
   if(!SrlLogger.active) { return; }
   if(e.type == 'mousemove' && SrlLogger.mouseMoveIgnore) { return; }

   var state = 'aucun';

   if(e.type == 'mousedown' || e.type == 'mouseup') {
      var newval = e.type == 'mousedown';
      if(e.button === 0) {
         var btn = 'left';
      } else if(e.button === 2) {
         var btn = 'right';
      } else {
         return;
      }
      SrlLogger.mouseButtons[btn] = newval;

      state = btn == 'left' ? 'clic gauche' : 'clic droit';
   }

   if(e.type == 'mousemove') {
      // Throttle mousemove events
      SrlLogger.mouseMoveIgnore = true;
      setTimeout(function () { SrlLogger.mouseMoveIgnore = false; }, 100);

      if(SrlLogger.mouseButtons['left'] || SrlLogger.mouseButtons['right']) {
         state = 'drag';
      }
   }

   var zone = 'task';
   var target = $(e.target);
   var targetParent = null;
   if((targetParent = target.parents('#blocklyLibContent')).length) {
      zone = 'editor';
   } else if((targetParent = target.parents('#gridContainer')).length) {
      zone = 'grid';
   } else if((targetParent = target.parents('.speedControls')).length) {
      zone = 'controls';
   } else {
      targetParent = null;
   }

   var tpx = e.pageX;
   var tpy = e.pageY;

   var win = $(window);
   var winw = win.width();
   var winh = win.height();
   var tpw = winw;
   var tph = winh;
   if(targetParent) {
      var tpo = targetParent.offset();
      tpx -= Math.floor(tpo.left);
      tpy -= Math.floor(tpo.top);
      tpw = Math.floor(targetParent.width());
      tph = Math.floor(targetParent.height());
   }
   var data = {
      'reference': 'souris',
      'version': SrlLogger.version,
      'zone': zone,
      'etat': state,
      'coordonnees_ecran_x': e.screenX,
      'coordonnees_ecran_y': e.screenY,
      'coordonnees_page_x': e.pageX,
      'coordonnees_page_y': e.pageY,
      'coordonnees_zone_x': tpx,
      'coordonnees_zone_y': tpy,
      'dimension_zone_longueur': tpw,
      'dimension_zone_hauteur': tph,
      'dimension_page_longueur': win.width(),
      'dimension_page_hauteur': win.height()
      };

   platform.log(['srl', data]);
};

SrlLogger.logKeyboardInit = function() {
   if(SrlLogger.logKeyboardInitialized) { return; }

   window.addEventListener('keydown', SrlLogger.logKeyboard, true);

   SrlLogger.logKeyboardInitialized = true;
};

SrlLogger.logKeyboard = function(e) {
   if(!SrlLogger.active) { return; }

   var text = e.key;
   var data = {
      'reference': 'clavier',
      'version': SrlLogger.version,
      'touche': text
      };
   platform.log(['srl', data]);
};

SrlLogger.stepByStep = function(subtask, type) {
   if(!SrlLogger.active) { return; }

   var srlType = '';
   if(type == 'play') {
      srlType = subtask.context.actionDelay == 0 ? 'Aller à la fin' : 'Exécution automatique';
   } else if(type == 'step') {
      srlType = 'Exécution Manuelle';
   } else if(type == 'stop') {
      srlType = 'Revenir au début';
   }

   var data = {
      reference: 'pas_a_pas',
      version: SrlLogger.version,
      action: srlType,
      vitesse: subtask.context.infos.actionDelay
      };
   platform.log(['srl', data]);
};

SrlLogger.navigation = function(type) {
   if(!SrlLogger.active) { return; }

   var data = {
      reference: 'navigation',
      version: SrlLogger.version,
      module: type
      };
   platform.log(['srl', data]);
};

SrlLogger.levelLoaded = function(level) {
   if(!SrlLogger.active || SrlLogger.lastLevelLoaded == level) { return; }

   SrlLogger.lastLevelLoaded = level;

   var defaultLevelsRanks = { basic: 1, easy: 2, medium: 3, hard: 4 };
   var version = defaultLevelsRanks[level];
   if(!version) { version = 5; }

   if(version == SrlLogger.version) { return; }

   SrlLogger.version = version;
   SrlLogger.navigation('Exercice');
};

SrlLogger.validation = function(score, error, experimentation) {
   if(!SrlLogger.active) { return; }

   if(error == 'code') {
      error = 'Erreur de prérequis';
   } else if(error == 'execution') {
      error = 'Erreur de solution';
   } else {
      error = 'Aucune';
   }
   var data = {
      reference: 'validation',
      version: SrlLogger.version,
      score: score,
      experimentation: experimentation,
      'type_erreur': error
      };
   platform.log(['srl', data]);
};

SrlLogger.modification = function(len, error) {
   if(!SrlLogger.active) { return; }

   if(error == 'code') {
      error = 'Erreur de prérequis';
   } else if(error == 'execution') {
      error = 'Erreur de solution';
   } else {
      error = 'Aucune';
   }
   var data = {
      reference: 'modification',
      version: SrlLogger.version,
      'taille_reponse': len,
      erreur: error
      };
   platform.log(['srl', data]);
};

window.iOSDetected = (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) || (navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform));

(function() {
   var detectTouch = null;
   detectTouch = function() {
      window.touchDetected = true;
      window.removeEventListener('touchstart', detectTouch);
      }
   window.addEventListener('touchstart', detectTouch);
})();
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';
import createReactNativeComponentClass from 'react-native/Libraries/Renderer/src/renderers/native/createReactNativeComponentClass';
import {ImageAttributes} from '../lib/attributes';
import {numberProp, touchableProps, responderProps} from '../lib/props';
import Shape from './Shape';
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';
import {meetOrSliceTypes, alignEnum} from './ViewBox';
const spacesRegExp = /\s+/;

class Image extends Shape {
    static displayName = 'Image';
    static propTypes = {
        ...responderProps,
        ...touchableProps,
        x: numberProp,
        y: numberProp,
        width: numberProp.isRequired,
        height: numberProp.isRequired,
        href: PropTypes.oneOfType([
            PropTypes.number,
            function(props, propName, componentName) {
                if (Object.keys(props[propName]).length != 1 ||
                    !/^\s*data:\/\/data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,[a-z0-9\!\$\&\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i.test(props[propName].uri)) {
                    return new Error(
                        'Invalid prop `' + propName + '` supplied to' +
                        ' `' + componentName + '`. Validation failed.'
                    );
                }
            }
        ]).isRequired,
        preserveAspectRatio: PropTypes.string
    };

    static defaultProps = {
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        preserveAspectRatio: 'xMidYMid meet'
    };

    setNativeProps = (...args) => {
        this.root.setNativeProps(...args);
    };

    render() {
        let {props} = this;
        let modes = props.preserveAspectRatio.trim().split(spacesRegExp);
        let meetOrSlice = meetOrSliceTypes[modes[1]] || 0;
        let align = alignEnum[modes[0]] || 'xMidYMid';

        return <RNSVGImage
            ref={ele => {this.root = ele;}}
            {...this.extractProps({...props, x: null, y: null}, {responder: true, transform: true})}
            x={props.x.toString()}
            y={props.y.toString()}
            width={props.width.toString()}
            height={props.height.toString()}
            meetOrSlice={meetOrSlice}
            align={align}
            src={resolveAssetSource(props.href)}
        />;
    }
}

const RNSVGImage = createReactNativeComponentClass({
    validAttributes: ImageAttributes,
    uiViewClassName: 'RNSVGImage'
});

export default Image;
<commit_msg>revert data://<commit_after>import React, {PropTypes} from 'react';
import createReactNativeComponentClass from 'react-native/Libraries/Renderer/src/renderers/native/createReactNativeComponentClass';
import {ImageAttributes} from '../lib/attributes';
import {numberProp, touchableProps, responderProps} from '../lib/props';
import Shape from './Shape';
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';
import {meetOrSliceTypes, alignEnum} from './ViewBox';
const spacesRegExp = /\s+/;

class Image extends Shape {
    static displayName = 'Image';
    static propTypes = {
        ...responderProps,
        ...touchableProps,
        x: numberProp,
        y: numberProp,
        width: numberProp.isRequired,
        height: numberProp.isRequired,
        href: PropTypes.oneOfType([
            PropTypes.number,
            function(props, propName, componentName) {
                if (Object.keys(props[propName]).length != 1 ||
                    !/^\s*data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,[a-z0-9\!\$\&\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i.test(props[propName].uri)) {
                    return new Error(
                        'Invalid prop `' + propName + '` supplied to' +
                        ' `' + componentName + '`. Validation failed.'
                    );
                }
            }
        ]).isRequired,
        preserveAspectRatio: PropTypes.string
    };

    static defaultProps = {
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        preserveAspectRatio: 'xMidYMid meet'
    };

    setNativeProps = (...args) => {
        this.root.setNativeProps(...args);
    };

    render() {
        let {props} = this;
        let modes = props.preserveAspectRatio.trim().split(spacesRegExp);
        let meetOrSlice = meetOrSliceTypes[modes[1]] || 0;
        let align = alignEnum[modes[0]] || 'xMidYMid';

        return <RNSVGImage
            ref={ele => {this.root = ele;}}
            {...this.extractProps({...props, x: null, y: null}, {responder: true, transform: true})}
            x={props.x.toString()}
            y={props.y.toString()}
            width={props.width.toString()}
            height={props.height.toString()}
            meetOrSlice={meetOrSlice}
            align={align}
            src={resolveAssetSource(props.href)}
        />;
    }
}

const RNSVGImage = createReactNativeComponentClass({
    validAttributes: ImageAttributes,
    uiViewClassName: 'RNSVGImage'
});

export default Image;
<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
import { borderSpacing, borderSpacingPropTypes } from '../../utils'

/**
 * The only true Button component.
 */
const Button = styled.button`{
  font-family: 'Nunito Sans', sans-serif;
  font-weight: 800;
  font-size: 13px;
  text-align: center;
  line-height: 1.15;
  height: 38px;
  border-radius: 100px;
  padding: 0 25px;
  min-width: 192px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  cursor: pointer;
  outline: none;

  border: none;
  box-shadow: 1px 2px 7px 5px rgba(0, 0, 0, 0.08);
  background-color: #ff0099;
  color: #fff;
  &:hover {
    background-color: #e2058a;
  }
  &:active {
    background-color: #b4006c;
  }

  ${props => (props.light || props.dark) && css`
    background: none;
    box-shadow: none;
    border: solid 1px;
    &:active {
      background: none;
      border-color: #ee0099;
      color: #ee0099;
    }
    &:hover {
      background: none;
    }
  `}

  ${props => props.light && css`
    color: #000;
    border-color: #000;
    &:hover {
      border-color: #545252;
      color: #545252;
    }
  `}

  ${props => props.dark && css`
    color: #fff;
    border-color: #fff;
    &:hover {
      border-color: #bebebe;
      color: #bebebe;
    }
    &:active {
      border-color: #ee0099;
      color: #ee0099;
    }
  `}

  ${props => props.disabled && `
    cursor: default;
    background-color: #d1cdd2;
    box-shadow: none;
    &:hover { background-color: #d1cdd2 }
    &:active { background-color: #d1cdd2 }
  `}

  ${props => props.flat && `
    background-color: transparent;
    border-color: transparent;
    color: #000000;
    box-shadow: none;
    min-width: 88px;

    &:hover {
      background-color: transparent;
      color: #424242;
    }
    &:active {
      background-color: transparent;
      color: #9b9b9b;
    }

    ${props.disabled && `
      color: #aaaaaa;
      &:hover { color: #aaaaaa }
      &:active { color: #aaaaaa }
    `}

    ${props.dark && `
      color: #fff;

      &:hover {
        border-color: transparent;
        color: #bebebe;
      }
      &:active {
        border-color: transparent;
        color: #ee0099;
      }
    `}
  `}

  ${props => props.color && `
    color: ${props.color};
  `}

  ${props => props.margin && borderSpacing('margin', props.margin)}
}`

const { node, bool, string } = PropTypes

Button.propTypes = {
  /** Children nodes. */
  children: node,
  /** Disable button. */
  disabled: bool,
  /** Dark button style. */
  dark: bool,
  /** Light button style. */
  light: bool,
  /** Flat button style. */
  flat: bool,
  /** Button text color. */
  color: string,
  /** Button type. */
  type: string,
  margin: borderSpacingPropTypes,
}

Button.defaultProps = {
  type: 'button',
  margin: {}
}

Button.displayName = 'Button'

/* @component */
export default Button
<commit_msg>fix(styleguide): flat button dark style<commit_after>import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
import { borderSpacing, borderSpacingPropTypes } from '../../utils'

/**
 * The only true Button component.
 */
const Button = styled.button`{
  font-family: 'Nunito Sans', sans-serif;
  font-weight: 800;
  font-size: 13px;
  text-align: center;
  line-height: 1.15;
  height: 38px;
  border-radius: 100px;
  padding: 0 25px;
  min-width: 192px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  cursor: pointer;
  outline: none;

  border: none;
  box-shadow: 1px 2px 7px 5px rgba(0, 0, 0, 0.08);
  background-color: #ff0099;
  color: #fff;
  &:hover {
    background-color: #e2058a;
  }
  &:active {
    background-color: #b4006c;
  }

  ${props => (props.light || props.dark) && css`
    background: none;
    box-shadow: none;
    border: solid 1px;
    &:active {
      background: none;
      border-color: #ee0099;
      color: #ee0099;
    }
    &:hover {
      background: none;
    }
  `}

  ${props => props.light && css`
    color: #000;
    border-color: #000;
    &:hover {
      border-color: #545252;
      color: #545252;
    }
  `}

  ${props => props.dark && css`
    color: #fff;
    border-color: #fff;
    &:hover {
      border-color: #bebebe;
      color: #bebebe;
    }
    &:active {
      border-color: #ee0099;
      color: #ee0099;
    }
  `}

  ${props => props.disabled && `
    cursor: default;
    background-color: #d1cdd2;
    box-shadow: none;
    &:hover { background-color: #d1cdd2 }
    &:active { background-color: #d1cdd2 }
  `}

  ${props => props.flat && `
    background-color: transparent;
    border-color: transparent;
    color: #000000;
    box-shadow: none;
    min-width: 88px;

    &:hover {
      background-color: transparent;
      color: #424242;
    }
    &:active {
      background-color: transparent;
      color: #9b9b9b;
    }
  `}

  ${props => props.flat && props.dark && `
    color: #fff;

    &:hover {
      border-color: transparent;
      color: #bebebe;
    }
    &:active {
      border-color: transparent;
      color: #ee0099;
    }
  `}

  ${props => props.flat && props.disabled && `
    color: #aaaaaa;
    &:hover { color: #aaaaaa }
    &:active { color: #aaaaaa }
  `}

  ${props => props.color && `
    color: ${props.color};
  `}

  ${props => props.margin && borderSpacing('margin', props.margin)}
}`

const { node, bool, string } = PropTypes

Button.propTypes = {
  /** Children nodes. */
  children: node,
  /** Disable button. */
  disabled: bool,
  /** Dark button style. */
  dark: bool,
  /** Light button style. */
  light: bool,
  /** Flat button style. */
  flat: bool,
  /** Button text color. */
  color: string,
  /** Button type. */
  type: string,
  margin: borderSpacingPropTypes,
}

Button.defaultProps = {
  type: 'button',
  margin: {}
}

Button.displayName = 'Button'

/* @component */
export default Button
<|endoftext|>


<commit_before>/**
 *    _____ __
 *   / ___// /_  _____
 *   \__ \/ / / / / _ \
 *  ___/ / / /_/ /  __/
 * /____/_/\__, /\___/
 *       /____/
 *       Copyright 2017 Slye Development Team. All Rights Reserved.
 *       Licence: MIT License
 */

global.quotations   = global.quotations || [];

// Define replaceBetween function to replace a substring between two indices
String.prototype.replaceBetween = function(start, end, what) {
	return this.substring(0, start) + what + this.substring(end);
};

function encode(code){
	const quotation_signs   = ['"', "'", '`'];
	var quotations  = [];
	var in_q    = false;
	var l_q     = ''; // Either one of " or '
	var bs      = false; // Check for backspace
	var start   = 0; // Start offset
	var comment = '';
	var open_comments   = 0;
	var close_comments  = 0;
	for(var offset = 0; offset < code.length; offset++){
		var l = code[offset];
		if(in_q){
			if(!bs) {
				if (l == l_q) {
					in_q = false;
					quotations.push([start, offset]);
					continue;
				}
				if(l == '\\'){
					bs  = true;
				}
			}else {
				bs = false;
			}
		}else {
			if(quotation_signs.indexOf(l) > -1){
				comment = (l == '/' && code[offset + 1] && code[offset + 1] == '*');
				if(comment)
					open_comments++;
				if(open_comments == close_comments){
					// It's start of a quotation
					start   = offset;
					l_q     = l;
					in_q    = true;
				}
				if(l == '/' && code[offset - 1] && code[offset - 1] == '*')
					close_comments++;
			}
		}
	}
	var f   = 0;
	for(var indices of quotations){
		var s   = indices[0],
			e   = indices[1],
			i   = global.quotations.length,
			c   = `\\q{${i.toString(36)}}`;
		global.quotations[i]    = code.substring(s, e + 1);
		code = code.replaceBetween(s - f, e + 1 - f, c);
		f   += ((e + 1) - s) - c.length;
	}
	return code;
}

module.exports = {
	encode: encode,
	get: i => global.quotations[i]
};<commit_msg>Fix code.substring offsets<commit_after>/**
 *    _____ __
 *   / ___// /_  _____
 *   \__ \/ / / / / _ \
 *  ___/ / / /_/ /  __/
 * /____/_/\__, /\___/
 *       /____/
 *       Copyright 2017 Slye Development Team. All Rights Reserved.
 *       Licence: MIT License
 */

global.quotations   = global.quotations || [];

// Define replaceBetween function to replace a substring between two indices
String.prototype.replaceBetween = function(start, end, what) {
	return this.substring(0, start) + what + this.substring(end);
};

function encode(code){
	const quotation_signs   = ['"', "'", '`'];
	var quotations  = [];
	var in_q    = false;
	var l_q     = ''; // Either one of " or '
	var bs      = false; // Check for backspace
	var start   = 0; // Start offset
	var comment = '';
	var open_comments   = 0;
	var close_comments  = 0;
	for(var offset = 0; offset < code.length; offset++){
		var l = code[offset];
		if(in_q){
			if(!bs) {
				if (l == l_q) {
					in_q = false;
					quotations.push([start, offset]);
					continue;
				}
				if(l == '\\'){
					bs  = true;
				}
			}else {
				bs = false;
			}
		}else {
			if(quotation_signs.indexOf(l) > -1){
				comment = (l == '/' && code[offset + 1] && code[offset + 1] == '*');
				if(comment)
					open_comments++;
				if(open_comments == close_comments){
					// It's start of a quotation
					start   = offset;
					l_q     = l;
					in_q    = true;
				}
				if(l == '/' && code[offset - 1] && code[offset - 1] == '*')
					close_comments++;
			}
		}
	}
	var f   = 0;
	for(var indices of quotations){
		var s   = indices[0],
			e   = indices[1],
			i   = global.quotations.length,
			c   = `\\q{${i.toString(36)}}`;
		global.quotations[i]    = code.substring(s - f, e + 1 - f);
		code = code.replaceBetween(s - f, e + 1 - f, c);
		f   += ((e + 1) - s) - c.length;
	}
	return code;
}

module.exports = {
	encode: encode,
	get: i => global.quotations[i]
};<|endoftext|>


<commit_before>app.controller('MainController', ['$scope', '$http', function($scope, $http){
  $scope.cats='meiow'
  $scope.bets={}
  $scope.getallbets = function(){ $http.get('/bets').success(function(response){
    $scope.bets = response;
    console.log($scope.bets)
  })};

  //Post route to make a new bet. You're welcome drew
  $scope.newBet = {}
  $scope.post = function(){
    var newbetcopy = angular.copy($scope.newBet)
    $http.post('/bets', newbetcopy).success(function(response){console.log(response)})
  };

  //drews 'I fergot how to use ng-show' code
  $scope.mobileMenu = function(){
    $scope.listDate = true;
  }

  // PUT JQUERY INSIDE CONTROLLER CALL IN IMMEDIATLLY...
  // JQUERY UI--SLIDER
    $scope.initJqueryUi = function(){
      $(function() {
    // Slider on login page...
        $( "#slider" ).slider({
          range: "max",
          min: 1,
          max: 5,
          value: 1,
          slide: function( event, ui ) {
            $( "#homeBetAmount" ).val( ui.value );
          },
          stop: function(event, ui){
            console.log(ui.value)}
        }) //end of slider

      // JQUERY UI--DATEPICKER
         $( "#datepicker" ).datepicker({
            minDate: 0
          }) //end of dp

         $scope.getallbets()
      }) // end of ready function
    } // END OF initJquery

    // call ui function
    $scope.initJqueryUi();

}]) // end of controller...
<commit_msg>some stuff<commit_after>app.controller('MainController', ['$scope', '$http', function($scope, $http){
  $scope.cats='meiow'
  $scope.bets={}
  $scope.getallbets = function(){ $http.get('/bets').success(function(response){
    $scope.bets = response;
    console.log($scope.bets)
  })};

  //Post route to make a new bet. You're welcome drew
  $scope.newBet = {}
  $scope.post = function(){
    var newbetcopy = angular.copy($scope.newBet)
    $http.post('/bets', newbetcopy).success(function(response){
      console.log(response)})
  };

  //drews 'I fergot how to use ng-show' code
  $scope.mobileMenu = function(){
    $scope.listDate = true;
  }

  // PUT JQUERY INSIDE CONTROLLER CALL IN IMMEDIATLLY...
  // JQUERY UI--SLIDER
    $scope.initJqueryUi = function(){
      $(function() {
    // Slider on login page...
        $( "#slider" ).slider({
          range: "max",
          min: 1,
          max: 5,
          value: 1,
          slide: function( event, ui ) {
            $( "#homeBetAmount" ).val( ui.value );
          },
          stop: function(event, ui){
            console.log(ui.value)}
        }) //end of slider

      // JQUERY UI--DATEPICKER
         $( "#datepicker" ).datepicker({
            minDate: 0
          }) //end of dp

         $scope.getallbets()
      }) // end of ready function
    } // END OF initJquery

    // call ui function
    $scope.initJqueryUi();

}]) // end of controller...
<|endoftext|>


<commit_before>/* jshint node:true */

(function () {
    "use strict";

    var DOMAIN_NAME = "hirseUngit";

    var childProcess = require("child_process");

    var _domainManager;
    var child;

    function start() {
        child = childProcess.exec("node node_modules/ungit/bin/ungit --no-b", {
            cwd: __dirname
        });
        child.stdout.on("data", function (data) {
            _domainManager.emitEvent(DOMAIN_NAME, "out", data);
        });
        child.stderr.on("data", function (data) {
            _domainManager.emitEvent(DOMAIN_NAME, "stderr", data);
        });
        child.on("error", function (code) {
            _domainManager.emitEvent(DOMAIN_NAME, "error", code);
        });
        child.on("close", function (code) {
            child = null;
            _domainManager.emitEvent(DOMAIN_NAME, "close", code);
        });
    }

    function kill() {
        if (child) {
            if (/^win/.test(process.platform)) {
                childProcess.spawn("taskkill", ["/pid", child.pid, "/t", "/f"]);
            } else {
                child.kill();
            }
        }
    }

    function init(domainManager) {
        _domainManager = domainManager;
        if (!domainManager.hasDomain(DOMAIN_NAME)) {
            domainManager.registerDomain(DOMAIN_NAME, {
                major: 0,
                minor: 1
            });
        }
        domainManager.registerCommand(
            DOMAIN_NAME, // domain name
            "start", // command name
            start, // command handler function
            false, // this command is synchronous in Node
            "Starts the ungit process"
        );
        domainManager.registerCommand(
            DOMAIN_NAME, // domain name
            "kill", // command name
            kill, // command handler function
            false, // this command is synchronous in Node
            "Kills the ungit process"
        );

        domainManager.registerEvent(
            DOMAIN_NAME, // domain name
            "out", // event name
            [{
                name: "mesage",
                type: "string",
                description: "Message body"
            }]
        );

        domainManager.registerEvent(
            DOMAIN_NAME, // domain name
            "stderr", // event name
            [{
                name: "mesage",
                type: "string",
                description: "message body"
            }]
        );

        domainManager.registerEvent(
            DOMAIN_NAME, // domain name
            "error", // event name
            [{
                name: "code",
                type: "string",
                description: "Exit code"
            }]
        );

        domainManager.registerEvent(
            DOMAIN_NAME, // domain name
            "close", // event name
            [{
                name: "code",
                type: "string",
                description: "Exit code"
            }]
        );
    }

    exports.init = init;
}());
<commit_msg>Use fork instead of exec to create child_process<commit_after>/* jshint node:true */

(function () {
    "use strict";

    var DOMAIN_NAME = "hirseUngit";

    var childProcess = require("child_process");

    var _domainManager;
    var child;

    function start() {
        child = childProcess.fork("node_modules/ungit/bin/ungit", ["--no-b"], {
            cwd: __dirname,
            silent: true
        });
        child.stdout.on("data", function (buffer) {
            _domainManager.emitEvent(DOMAIN_NAME, "out", buffer.toString());
        });
        child.stderr.on("data", function (buffer) {
            _domainManager.emitEvent(DOMAIN_NAME, "stderr", buffer.toString());
        });
        child.on("error", function (code) {
            _domainManager.emitEvent(DOMAIN_NAME, "error", code);
        });
        child.on("close", function (code) {
            child = null;
            _domainManager.emitEvent(DOMAIN_NAME, "close", code);
        });
    }

    function kill() {
        if (child) {
            if (/^win/.test(process.platform)) {
                childProcess.spawn("taskkill", ["/pid", child.pid, "/t", "/f"]);
            } else {
                child.kill();
            }
        }
    }

    function init(domainManager) {
        _domainManager = domainManager;
        if (!domainManager.hasDomain(DOMAIN_NAME)) {
            domainManager.registerDomain(DOMAIN_NAME, {
                major: 0,
                minor: 1
            });
        }
        domainManager.registerCommand(
            DOMAIN_NAME, // domain name
            "start", // command name
            start, // command handler function
            false, // this command is synchronous in Node
            "Starts the ungit process"
        );
        domainManager.registerCommand(
            DOMAIN_NAME, // domain name
            "kill", // command name
            kill, // command handler function
            false, // this command is synchronous in Node
            "Kills the ungit process"
        );

        domainManager.registerEvent(
            DOMAIN_NAME, // domain name
            "out", // event name
            [{
                name: "mesage",
                type: "string",
                description: "Message body"
            }]
        );

        domainManager.registerEvent(
            DOMAIN_NAME, // domain name
            "stderr", // event name
            [{
                name: "mesage",
                type: "string",
                description: "message body"
            }]
        );

        domainManager.registerEvent(
            DOMAIN_NAME, // domain name
            "error", // event name
            [{
                name: "code",
                type: "string",
                description: "Exit code"
            }]
        );

        domainManager.registerEvent(
            DOMAIN_NAME, // domain name
            "close", // event name
            [{
                name: "code",
                type: "string",
                description: "Exit code"
            }]
        );
    }

    exports.init = init;
}());
<|endoftext|>


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

var database = process.env.NODE_ENV == 'development' ? 'test' : 'production';
mongoose.connect('mongodb://localhost/' + database);

<commit_msg>Added export to module<commit_after>var mongoose = require('mongoose');

var database = process.env.NODE_ENV == 'development' ? 'test' : 'production';
mongoose.connect('mongodb://localhost/' + database);

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