Example #1
0
 leaveGroup: function(client, groupName, bypassErrors) {
   var me = this;
   if (!me.options.allowGroups) {
     !bypassErrors && me.error(
       client,
       errorTypes.GROUPS_NOT_ALLOWED
     );
   } else {
     var group = me.groups[groupName];
     if (!group) {
       !bypassErrors && me.error(
         client,
         errorTypes.INVALID_GROUP,
         {groupName: groupName}
       );
     } else {
       if (me.groups[groupName].clients.indexOf(client) == -1) {
         !bypassErrors && me.error(
           client,
           errorTypes.NOT_GROUP_MEMBER,
           {groupName: groupName}
         );
       } else {
         //send :leave: message to all members, including self, but report 1 less member
         var _uuid = me.clientUUIDs[client.id];
         var len = group.clients.length - 1;
         _.each(group.clients, function(_client) {
           if (_client.id !== me.channelClient.id) {
             _client.json.send({
               type: "channel",
               channelId: me.id,
               message: "group:" + groupName + ":leave:",
               data: {
                 clientId: _uuid,
                 memberCount: len
               }
             });
           }
         });
         group.clients = _.without(group.clients, client);
       }
     }
   }
 },
Example #2
0
 }, function(err) {
     if(category) {
         if(category.quotes.indexOf(quote) != -1) {
             category.quotes = _.without(category.quotes, quote);
             if(category.quotes.length == 0) {
                 this.db.del('quote_category', category.id, quoteRemoved);
             } else {
                 this.db.save('quote_category', category.id, category, quoteRemoved);
             }
         } else {
             event.reply(dbot.t('q_not_exist_under', {
                 'category': key, 
                 'quote': quote
             }));
         }
     } else {
         event.reply(dbot.t('category_not_found', { 'category': key }));
     }
 }.bind(this));
Example #3
0
 this.api.getUserIgnores(event.server, event.user, function(err, user, ignores) {
     if(err || !ignores || _.isUndefined(module)) {
         event.reply(dbot.t('unignore_usage', {
             'user': event.user, 
             'modules': ignores.ignores.join(', ')
         }));
     } else {
         if(_.include(ignores.ignores, module)) {
             ignores.ignores = _.without(ignores.ignores, module);
             this.db.save('ignores', user.id, ignores, function(err) {
                 if(!err) {
                     dbot.instance.removeIgnore(event.user, module)
                     event.reply(dbot.t('unignored', {
                         'user': event.user, 
                         'module': module
                     }));
                 }
             });
         } else {
             event.reply(dbot.t('invalid_unignore', { 'user': event.user }));
         }
     }
 }.bind(this));
TreebankWordTokenizer.prototype.tokenize = function(text) {
    contractions2.forEach(function(regexp) {
	text = text.replace(regexp,"$1 $2");
    });
    
    contractions3.forEach(function(regexp) {
	text = text.replace(regexp,"$1 $2 $3");
    });

    // most punctuation
    text = text.replace(/([^\w\.\'\-\/\+\<\>,&])/g, " $1 ");

    // commas if followed by space
    text = text.replace(/(,\s)/g, " $1");

    // single quotes if followed by a space
    text = text.replace(/('\s)/g, " $1");

    // periods before newline or end of string
    text = text.replace(/\. *(\n|$)/g, " . ");
    
    return  _.without(text.split(/\s+/), '');	
}
Example #5
0
            this.api.resolveUser(event.server, newPrimary, function(user) {
                if(user && user.primaryNick != newPrimary) {
                    var newAlias = user.primaryNick;
                    user.primaryNick = newPrimary;
                    user.aliases = _.without(user.aliases, newPrimary);
                    user.aliases.push(newAlias);

                    this.db.save('users', user.id, user, function(err) {
                        if(!err) {
                            event.reply(dbot.t('aliasparentset', {
                                'newParent': newPrimary,
                                'newAlias': newAlias
                            }));
                            dbot.api.event.emit('~setaliasparent', {
                                'server': event.server,
                                'alias': newAlias 
                            });
                        } 
                    });
                } else {
                    event.reply(dbot.t('unknown_alias', { 'alias': newPrimary }));
                }
            }.bind(this));
Example #6
0
 scriptLoader.on('command', ['urltitle'], function (event) {
     if (event.user.isAdmin()) {
         var chan = event.channel.getName(),
             net = event.channel.connection.config.id;
         if (_.has(database.disabled, net)) {
             if (database.disabled[net].indexOf(chan) > -1) {
                 database.disabled[net] = _.without(database.disabled[net], chan);
                 if (database.disabled[net].length === 0) {
                     delete database.disabled[net];
                 }
                 event.user.notice('urltitle enabled for %s on %s', chan, net);
             } else {
                 database.disabled[net].push(chan);
                 event.user.notice('urltitle disabled for %s on %s', chan, net);
             }
         } else {
             database.disabled[net] = [chan];
             event.user.notice('urltitle disabled for %s on %s', chan, net);
         }
         database.save();
     } else {
         event.user.notice('You don\'t have the permissions to use this command.');
     }
 });
Example #7
0
 this.api.getUserIgnores(user, function(err, ignores) {
     if(err || !ignores) {
         event.reply(dbot.t('invalid_unban', {
             'user': event.user,
             'banned': nick 
         }));
     } else {
         if(_.include(ignores.bans, item)) {
             ignores.bans = _.without(ignores.bans, item); 
             this.db.save('ignores', user.id, ignores, function(err) {
                 event.reply(dbot.t('unbanned_success', {
                     'user': event.user,
                     'banned': nick,
                     'module': item
                 }));
             });
         } else {
             event.reply(dbot.t('invalid_unban', {
                 'user': event.user,
                 'banned': nick
             }));
         }
     }
 }.bind(this));
Example #8
0
function purge(s, action) {
	/*
	The action will determine how we deal with the room/user removal.
	These are the following scenarios:
	if the user is the owner and (s)he:
		1) disconnects (i.e. leaves the whole server)
			- advise users
		 	- delete user from people object
			- delete room from rooms object
			- delete chat history
			- remove all users from room that is owned by disconnecting user
		2) removes the room
			- same as above except except not removing user from the people object
		3) leaves the room
			- same as above
	if the user is not an owner and (s)he's in a room:
		1) disconnects
			- delete user from people object
			- remove user from room.people object
		2) removes the room
			- produce error message (only owners can remove rooms)
		3) leaves the room
			- same as point 1 except not removing user from the people object
	if the user is not an owner and not in a room:
		1) disconnects
			- same as above except not removing user from room.people object
		2) removes the room
			- produce error message (only owners can remove rooms)
		3) leaves the room
			- n/a
	*/
	//console.log(rooms);
	if (people[s.id].inroom) { //user is in a room
		var room = rooms[people[s.id].inroom]; //check which room user is in.
		if (s.id === room.owner) { //user in room and owns room
			if (action === "disconnect") {
				/*
				io.sockets.in(s.room).emit("update", "The owner (" +people[s.id].name + ") has left the server. The room is removed and you have been disconnected from it as well.");
				var socketids = [];
				for (var i=0; i<sockets.length; i++) {
					socketids.push(sockets[i].id);
					if(_.contains((socketids)), room.people) {
						sockets[i].leave(room.name);
					}
				}

				if(_.contains((room.people)), s.id) {
					for (var i=0; i<room.people.length; i++) {
						people[room.people[i]].inroom = null;
					}
				}
				room.people = _.without(room.people, s.id); //remove people from the room:people{}collection
				delete rooms[people[s.id].owns]; //delete the room
				delete people[s.id]; //delete user from people collection
				delete chatHistory[room.name]; //delete the chat history
				
				*/
				var roomId = people[s.id].owns;
				
				io.sockets.in(s.room).emit("update", "The owner (" +people[s.id].name + ") has left the server. Searching new owner.");
				room.people = _.without(room.people, s.id);
				//находим тех кто в комнате
				var socketids = [];
				for (var i=0; i<sockets.length; i++) {
					if(_.contains((sockets[i].id)), room.people) {
						socketids.push(sockets[i].id);
					}
				}
				//console.log('LEN'+room.people.length);
				//console.log('SocketsIds'+socketids);
				if(room.people.length == 0){
					room.people = _.without(room.people, s.id); //remove people from the room:people{}collection
					delete rooms[people[s.id].owns]; //delete the room
					delete people[s.id]; //delete user from people collection
					delete chatHistory[room.name]; //delete the chat history
					return;
				}
				//console.log('LEN:'+socketids.length);
				if(socketids.length > 1){
					//console.log('search new');
					//выбираем рандомного
					var newOwner = _.sample(room.people);
					//назначаем главным
					//console.log('newOwner:'+newOwner);
					for (var i=0; i<sockets.length; i++) {
						if(sockets[i].id == newOwner){
							//назначаем нового главного румы
							rooms[people[s.id].owns].owner = sockets[i].id;
							people[sockets[i].id].owns = people[s.id].owns;
							io.sockets.in(s.room).emit("update", "The new owner room is "+people[sockets[i].id].name+" ");
						}else{
							//console.log('cant find owner?');
						}
					}
					
					delete people[s.id]; //удаляем из народа
				}else{
					//console.log('delete room');
					
					 //delete the room
					delete rooms[roomId];
					room.people = _.without(room.people, s.id); //remove people from the room:people{}collection
					
					delete people[s.id]; //delete user from people collection
					delete chatHistory[room.name]; //delete the chat history
					return;
				}
				
				sizePeople = _.size(people);
				sizeRooms = _.size(rooms);
				io.sockets.emit("update-people", {people: people, count: sizePeople});
				io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
				var o = _.findWhere(sockets, {'id': s.id});
				sockets = _.without(sockets, o);
			} else if (action === "removeRoom") { //room owner removes room
				io.sockets.in(s.room).emit("update", "The owner (" +people[s.id].name + ") has removed the room. The room is removed and you have been disconnected from it as well.");
				var socketids = [];
				for (var i=0; i<sockets.length; i++) {
					socketids.push(sockets[i].id);
					if(_.contains((socketids)), room.people) {
						sockets[i].leave(room.name);
					}
				}

				if(_.contains((room.people)), s.id) {
					for (var i=0; i<room.people.length; i++) {
						people[room.people[i]].inroom = null;
					}
				}
				delete rooms[people[s.id].owns];
				people[s.id].owns = null;
				room.people = _.without(room.people, s.id); //remove people from the room:people{}collection
				delete chatHistory[room.name]; //delete the chat history
				sizeRooms = _.size(rooms);
				io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
			} else if (action === "leaveRoom") { //room owner leaves room
				io.sockets.in(s.room).emit("update", "The owner (" +people[s.id].name + ") has left the room. The room is removed and you have been disconnected from it as well.");
				var socketids = [];
				for (var i=0; i<sockets.length; i++) {
					socketids.push(sockets[i].id);
					if(_.contains((socketids)), room.people) {
						sockets[i].leave(room.name);
					}
				}

				if(_.contains((room.people)), s.id) {
					for (var i=0; i<room.people.length; i++) {
						people[room.people[i]].inroom = null;
					}
				}
				delete rooms[people[s.id].owns];
				people[s.id].owns = null;
				room.people = _.without(room.people, s.id); //remove people from the room:people{}collection
				delete chatHistory[room.name]; //delete the chat history
				sizeRooms = _.size(rooms);
				io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
			}
		} else {//user in room but does not own room
			//console.log('i not owner');
			if (action === "disconnect") {
				io.sockets.emit("update", people[s.id].name + " has disconnected from the server.");
				if (_.contains((room.people), s.id)) {
					var personIndex = room.people.indexOf(s.id);
					room.people.splice(personIndex, 1);
					s.leave(room.name);
				}
				delete people[s.id];
				sizePeople = _.size(people);
				io.sockets.emit("update-people", {people: people, count: sizePeople});
				var o = _.findWhere(sockets, {'id': s.id});
				sockets = _.without(sockets, o);
			} else if (action === "removeRoom") {
				s.emit("update", "Only the owner can remove a room.");
			} else if (action === "leaveRoom") {
				if (_.contains((room.people), s.id)) {
					var personIndex = room.people.indexOf(s.id);
					room.people.splice(personIndex, 1);
					people[s.id].inroom = null;
					io.sockets.emit("update", people[s.id].name + " has left the room.");
					s.leave(room.name);
				}
			}
		}	
	} else {
		//The user isn't in a room, but maybe he just disconnected, handle the scenario:
		if (action === "disconnect") {
			io.sockets.emit("update", people[s.id].name + " has disconnected from the server.");
			delete people[s.id];
			sizePeople = _.size(people);
			io.sockets.emit("update-people", {people: people, count: sizePeople});
			var o = _.findWhere(sockets, {'id': s.id});
			sockets = _.without(sockets, o);
		}		
	}
}
Example #9
0
 _.each(results, function(value, key, list){ 
 	if (value[4] == 1)
 		keyph = _.without(keyph, value[1])
 }, this)
Example #10
0
exports.moveToTop = function (url) {
    exports._dashboard_urls = _.without(exports._dashboard_urls, url)
    exports.add(url);
};
Example #11
0
function purge(s, action) {
	/*
	The action will determine how we deal with the room/user removal.
	These are the following scenarios:
	if the user is the owner and (s)he:
		1) disconnects (i.e. leaves the whole server)
			- advise users
		 	- delete user from people object
			- delete room from rooms object
			- delete chat history
			- remove all users from room that is owned by disconnecting user
		2) removes the room
			- same as above except except not removing user from the people object
		3) leaves the room
			- same as above
	if the user is not an owner and (s)he's in a room:
		1) disconnects
			- delete user from people object
			- remove user from room.people object
		2) removes the room
			- produce error message (only owners can remove rooms)
		3) leaves the room
			- same as point 1 except not removing user from the people object
	if the user is not an owner and not in a room:
		1) disconnects
			- same as above except not removing user from room.people object
		2) removes the room
			- produce error message (only owners can remove rooms)
		3) leaves the room
			- n/a
	*/
	if (people[s.id].inroom) { //user is in a room
		var room = rooms[people[s.id].inroom]; //check which room user is in.
		if (s.id === room.owner) { //user in room and owns room
			if (action === "disconnect") {
				io.sockets.in(s.room).emit("update", "The owner (" +people[s.id].name + ") has left the server. The room is removed and you have been disconnected from it as well.");
				var socketids = [];
				for (var i=0; i<sockets.length; i++) {
					socketids.push(sockets[i].id);
					if(_.contains((socketids)), room.people) {
						sockets[i].leave(room.name);
					}
				}

				if(_.contains((room.people)), s.id) {
					for (var i=0; i<room.people.length; i++) {
						people[room.people[i]].inroom = null;
					}
				}
				room.people = _.without(room.people, s.id); //remove people from the room:people{}collection
				delete rooms[people[s.id].owns]; //delete the room
				delete people[s.id]; //delete user from people collection
				delete chatHistory[room.name]; //delete the chat history
				sizePeople = _.size(people);
				sizeRooms = _.size(rooms);
				io.sockets.emit("update-people", {people: people, count: sizePeople});
				io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
				var o = _.findWhere(sockets, {'id': s.id});
				sockets = _.without(sockets, o);
			} else if (action === "removeRoom") { //room owner removes room
				io.sockets.in(s.room).emit("update", "The owner (" +people[s.id].name + ") has removed the room. The room is removed and you have been disconnected from it as well.");
				var socketids = [];
				for (var i=0; i<sockets.length; i++) {
					socketids.push(sockets[i].id);
					if(_.contains((socketids)), room.people) {
						sockets[i].leave(room.name);
					}
				}

				if(_.contains((room.people)), s.id) {
					for (var i=0; i<room.people.length; i++) {
						people[room.people[i]].inroom = null;
					}
				}
				delete rooms[people[s.id].owns];
				people[s.id].owns = null;
				room.people = _.without(room.people, s.id); //remove people from the room:people{}collection
				delete chatHistory[room.name]; //delete the chat history
				sizeRooms = _.size(rooms);
				io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
			} else if (action === "leaveRoom") { //room owner leaves room
				io.sockets.in(s.room).emit("update", "The owner (" +people[s.id].name + ") has left the room. The room is removed and you have been disconnected from it as well.");
				var socketids = [];
				for (var i=0; i<sockets.length; i++) {
					socketids.push(sockets[i].id);
					if(_.contains((socketids)), room.people) {
						sockets[i].leave(room.name);
					}
				}

				if(_.contains((room.people)), s.id) {
					for (var i=0; i<room.people.length; i++) {
						people[room.people[i]].inroom = null;
					}
				}
				delete rooms[people[s.id].owns];
				people[s.id].owns = null;
				room.people = _.without(room.people, s.id); //remove people from the room:people{}collection
				delete chatHistory[room.name]; //delete the chat history
				sizeRooms = _.size(rooms);
				io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
			}
		} else {							//user in room but does not own room
			if (action === "disconnect") {
				io.sockets.emit("update", people[s.id].name + " has disconnected from the server.");
				if (_.contains((room.people), s.id)) {
					var personIndex = room.people.indexOf(s.id);
					room.people.splice(personIndex, 1);
					s.leave(room.name);
				}
				delete people[s.id];
				sizePeople = _.size(people);
				io.sockets.emit("update-people", {people: people, count: sizePeople});
				var o = _.findWhere(sockets, {'id': s.id});
				sockets = _.without(sockets, o);
			} else if (action === "removeRoom") {
				s.emit("update", "Only the owner can remove a room.");
			} else if (action === "leaveRoom") {
				if (_.contains((room.people), s.id)) {
					var personIndex = room.people.indexOf(s.id);
					room.people.splice(personIndex, 1);
					people[s.id].inroom = null;
					io.sockets.emit("update", people[s.id].name + " has left the room.");
					s.leave(room.name);
				}
			}
		}	
	} else {
		//The user isn't in a room, but maybe he just disconnected, handle the scenario:
		if (action === "disconnect") {
			io.sockets.emit("update", people[s.id].name + " has disconnected from the server.");
			delete people[s.id];
			sizePeople = _.size(people);
			io.sockets.emit("update-people", {people: people, count: sizePeople});
			var o = _.findWhere(sockets, {'id': s.id});
			sockets = _.without(sockets, o);
		}		
	}
}
Example #12
0
var _ = require('underscore')._; 
var fs = require('fs');
var natural = require('natural');
var utils = require('./utils');
var async = require('async');
var Fiber = require('fibers');

var outstats = []
var keyphrases = JSON.parse(fs.readFileSync("../test_aggregate_keyphases/keyphases.08.2014.json"))
var stats = utils.formkeyphrases(keyphrases)
var keyph = _.without(Object.keys(stats['Offer']), "default intent")
var size = _.reduce(stats['Offer'], function(memo, num){ return memo + num.length; }, 0);
size = size - stats['Offer']["default intent"].length

var tocomp = utils.crosslist(keyph)


var f = Fiber(function() {
  var fiber = Fiber.current;

  async.mapSeries(tocomp, utils.compare, function(err,results){
   fiber.run(results);
  })

  var results = Fiber.yield();

  _.each(results, function(value, key, list){ 
  	if (value[4] == 1)
  		keyph = _.without(keyph, value[1])
  }, this)
Example #13
0
    client.on("message", function(data, flags) {
        var parseData = data.split("|@|", 2);
        if (parseData[0] == "command") { //命令数据格式:"command|@|init|uid|channelA","command|@|enter|uid|channelA"....
            console.log("has a command message");
            var userInfo = parseData[1];
            var commandAction = userInfo.split("|")[0];
            var uid = userInfo.split("|")[1];
            var channelname = userInfo.split("|")[2];
            if (!userInfo || !commandAction || !uid || !channelname) {
                console.log("command is lawless..");
                return;
            }

            if (!clientConns.hasOwnProperty(uid) && commandAction != "init") { //如果cli没有被收集、没有init
                //利用isInit和lastSendTime可以定时检测长时间没有init的cli
                clientConns[uid] = {
                    client: client,
                    lastSendTime: new Date().getTime(),
                    isInit: false
                };
                console.log("plase init it in time,otherwise will close");
                return;
            } else if (clientConns[uid] && !clientConns[uid].isInit && commandAction != "init") { //如果cli被收集但是没有init
                console.log("has not init,plase init");
                return;
            }

            switch (commandAction) {
                case "init": //初始化客户端链接信息并验证合法性
                    if (!verifyCli(data)) {
                        return;
                    }
                    clientConns[uid] = {
                        client: client,
                        lastSendTime: new Date().getTime(),
                        isInit: true
                    };
                    client.send("ok");
                    console.log(uid + " has inited succ");

                    break;
                case "enter": //进入频道
                    if (channels.hasOwnProperty(channelname)) {
                        channels[channelname].push(uid);
                        RedisCliPub.lrange("channelA", 0, configs.maxMesageNum - 1, function(err, message) { //得到缓存的频道信息
                            client.send(JSON.stringify(message));
                        });
                        client.send("ok");
                        Logger.info(uid + " has enter " + channelname);
                    } else {
                        client.send("has not the channel:" + channelname);
                    }
                    break;
                case "create": //创建频道
                    if (channels.hasOwnProperty) {
                        RedisCliSub.subscribe
                        client.send("no");
                        Logger.info(uid + " create channel fail, the channel:" + channelname + " has exist");
                    } else {
                        channels[channelname] = [];
                        client.send("ok");
                        Logger.info(udi + " create channel succ:" + channelname);
                        RedisCliSub.subscribe(channelname);
                    }
                    break;
                case "quit": //退出频道
                    if (channels.hasOwnProperty(channelname)) {
                        channels[channelname] = _.without(channels[channelname], uid);
                        Logger.info(channels[channelname]);
                        client.send("ok");
                        Logger.info(uid + " has exit chanel:" + channelname + " succ");
                        if (channels[channelname].length < 1) {
                            RedisCliSub.unsubscribe(channelname);
                        }

                    } else {
                        client.send("no");
                        Logger.info("the channel:" + channelname + " has not exist");
                    }
                    break;
                default:
            }
        } else if (parseData[0] == "message") { //频道消息数据格式:"message|@|channelA|uid|hellword" 发送给个人的消息需要进一步区分格式
            var channelname = parseData[1].split("|")[0];
            var uid = parseData[1].split("|")[1];
            var message = parseData[1].split("|")[2];

            console.log(message + "===>" + channelname);
            if (forbiddenUids.indexOf(uid) == -1) { //检测是否被禁言
                RedisCliPub.publish(channelname, filterCharacter(parseData[1].split("|")[2])); //脏字符过滤并发布出去

                RedisCliPub.lpush(channelname, message); //更新频道缓存
                RedisCliPub.llen(channelname, function(err, n) {
                    console.log(n);
                    if (n > configs.maxMesageNum) {
                        RedisCliPub.ltrim(channelname, 0, configs.maxMesageNum - 1);
                        console.log(n);
                    }
                });
            } else {
                console.log("has been forbided..");
            }
        } else if (parseData[0] == "messageA") { //管理员发消息,活动公告等,消息数据格式:"messageA|@|channelA|uid|hellword"
            var channelname = parseData[1].split("|")[0];
            var uid = parseData[1].split("|")[1];
            var message = parseData[1].split("|")[2];
            if (administrators.indexOf(uid) != -1) { //检测是否为管理员
                console.log("administrator " + uid + " send a message");
                RedisCliPub.publish(channelname, filterCharacter(parseData[1].split("|")[2])); //发布出去
            } else {
                console.warn("some people want feign administrator...");
            }
        }
    });
Example #14
0
    function onDisconnect() {
        if (typeof players[socket.id] !== 'undefined')

        if (players[socket.id].ingame) {
            var game = games[players[socket.id].ingame];
            if (socket.id === game.owner) {
                var socketids = [];
                for (var i = 0; i < sockets.length; i++) {
                    socketids.push(sockets[i].id);
                    if (_.contains((socketids)), game.playeringame) {
                        sockets[i].leave(game.name);
                    }
                }
                if (_.contains((game.players)), socket.id) {
                    for (var i = 0; i < game.playeringame.length; i++) {
                        players[game.playeringame[i]].ingame = null;
                        players[game.playeringame[i]].gamename = null;
                    }
                }
                game.playeringame = 0;
                delete games[players[socket.id].owns];
                delete players[socket.id];

               totalPlayerOnline = _.size(players);
                io.sockets.emit('count:player', {
                    count: totalPlayerOnline
                });
                io.sockets.emit('list:games', games);
                var o = _.findWhere(sockets, {
                    'id': socket.id
                });
                sockets = _.without(sockets, o);

                } else {
                if (_.contains((game.playeringame), socket.id)) {
                    var playerIndex = game.playeringame.indexOf(socket.id);
                    game.playeringame.splice(playerIndex, 1);
                    socket.leave(game.name);
                }
                delete players[socket.id];
                totalPlayerOnline = _.size(players);

                io.sockets.emit('count:player', {
                    count: totalPlayerOnline
                });
                io.sockets.emit('list:games', games);
                var o = _.findWhere(sockets, {
                    'id': socket.id
                });
                sockets = _.without(sockets, o);

            }

        } else {
            delete players[socket.id];
            totalPlayerOnline = _.size(players);
            io.sockets.emit('count:player', {
                count: totalPlayerOnline
            });
            io.sockets.emit('list:games', games);
            var o = _.findWhere(sockets, {
                'id': socket.id
            });
            sockets = _.without(sockets, o);
        }
    }
Example #15
0
function validate(obj, config) {  
  
  var errors = newErrors();
  var defaultMessages = config.defaultMessages || {};
  _.without(validation_types, 'required').forEach(function(validation_type) {
    if (!defaultMessages[validation_type]) defaultMessages[validation_type] = {};
  });

  function test_and_add_error_message(prop_name, prop_config, validation_type, value, subtype) {
    if (!prop_config[validation_type]) return;
    var valid_func, compare_to, interpolation_scope_extractor;
    if (subtype) {
      if (prop_config[validation_type][subtype] == undefined) return;
      valid_func = valid_funcs[validation_type][subtype];
      compare_to = prop_config[validation_type][subtype];
      if (interpolation_scope_extractors[validation_type]) 
        interpolation_scope_extractor = interpolation_scope_extractors[validation_type][subtype];
    } else { 
      valid_func = valid_funcs[validation_type];
      compare_to = prop_config[validation_type];
      interpolation_scope_extractor = interpolation_scope_extractors[validation_type];
    }
    if (!valid_func(value, compare_to)) {
      var msg = prop_config.message;
      if (subtype) {
        msg = msg  || defaultMessages[validation_type][subtype] || 
                globalDefaultMessages[validation_type][subtype];
      } else {
        msg = msg  || defaultMessages[validation_type] || 
                globalDefaultMessages[validation_type];
      }
      var vars;
      if (interpolation_scope_extractor)
        vars = interpolation_scope_extractor(value);
      errors.add(prop_name, interpolate_msg(msg, prop_name, value, compare_to, vars));
      return false;
    } else {
      return true;
    }
  }
  
  _.forEach(config.properties, function(prop_config, prop_name) {
    var value = obj[prop_name];
    if (prop_config.object) {
      // recurse
      errors.add(prop_name, validate(value, prop_config.object));
      return; // no other validation types should apply if validation type is 'object'
    }
    for (var i = 0; i < validation_types.length; i++) {
      var validation_type = validation_types[i];
      if (!prop_config[validation_type]) continue;
      if (validation_type != 'required' && 
          (value === undefined || value === null )) 
          continue;
      if (typeof valid_funcs[validation_type] == 'function') {
        var is_valid = test_and_add_error_message(prop_name, prop_config, 
                         validation_type, value);
        if (!is_valid && validation_type == 'required') break;
      } else {
        _.keys(valid_funcs[validation_type]).forEach(function(subtype) {
          test_and_add_error_message(prop_name, prop_config, validation_type, 
            value, subtype);
        });        
      }
    }
  });
  if (!errors.isEmpty()) return errors;
}
Example #16
0
            dbot.api.nickserv.getUserHost(event.server, banee, function(host) {
                // Add host record entry
                if(host) {
                    this.hosts[event.server][banee] = host;

                    // Create notify string
                    if(!_.isUndefined(timeout)) {
                        timeout = parseFloat(timeout.trim());
                        
                        var msTimeout = new Date(new Date().getTime() + (timeout * 3600000));
                        if(!_.has(this.tempBans, event.server)) this.tempBans[event.server] = {};
                        this.tempBans[event.server][banee] = msTimeout;
                        this.internalAPI.addTempBan(event.server, banee, msTimeout);

                        var notifyString = dbot.t('tbanned', {
                            'network': network,
                            'banner': banner,
                            'banee': banee,
                            'hours': timeout,
                            'reason': reason
                        });
                    } else {
                        var notifyString = dbot.t('nbanned', {
                            'network': network,
                            'banner': banner,
                            'banee': banee,
                            'reason': reason
                        });
                    }

                    // Add qutoe category documenting ban
                    if(this.config.document_bans) {
                        var id = uuid.v4();
                        var banRecord = {
                            'id': id,
                            'time': new Date().getTime(),
                            'server': server,
                            'banee': banee,
                            'banner': banner,
                            'host': host,
                            'reason': reason
                        };
                        this.db.save('nbans', id, banRecord, function() {});
                    }

                    // Notify moderators, banee
                    if(!_.isUndefined(adminChannel)) {
                        channels = _.without(channels, adminChannel);
                    } else {
                        adminChannel = event.channel.name;
                    }

                    dbot.api.report.notify('ban', server, event.rUser, adminChannel, notifyString);
                    dbot.say(event.server, adminChannel, notifyString);

                    if(!_.isUndefined(timeout)) {
                        dbot.say(event.server, banee, dbot.t('tbanned_notify', {
                            'network': network,
                            'banner': banner,
                            'reason': reason,
                            'hours': timeout,
                            'admin_channel': adminChannel 
                        }));
                    } else {
                        dbot.say(event.server, banee, dbot.t('nbanned_notify', {
                            'network': network,
                            'banner': banner,
                            'reason': reason,
                            'hours': timeout,
                            'admin_channel': adminChannel 
                        }));
                    }
                    
                    // err
                    dbot.say(event.server, 'NickServ', 'FREEZE ' + banee + ' ON ' + reason);

                    // Ban the user from all channels
                    var i = 0;
                    var banChannel = function(channels) {
                        if(i >= channels.length) return;
                        var channel = channels[i];
                        this.api.ban(server, host, channel);
                        this.api.kick(server, banee, channel, reason + 
                            ' (network-wide ban requested by ' + banner + ')');
                        setTimeout(function() {
                            i++; banChannel(channels);
                        }, 1000);
                    }.bind(this);
                    banChannel(channels);
                } else {
                    event.reply(dbot.t('no_user', { 'user': banee }));
                }
            }.bind(this));
function strip(arr) {
  return _.without(arr.map(function (s) { return s.trim(); }), '');
}
Example #18
0
	_.each(elim, function(value, key, list){ 
		strcontentlemma = _.without(strcontentlemma,value)
	}, this)
Example #19
0
function purge(s, action) {
	if (people[s.id].inroom) { //user is in a room
		var room = rooms[people[s.id].inroom]; //check which room user is in.
		if (s.id === room.owner) { //user in room and owns room
			if (action === "disconnect") {
				io.sockets.in(s.room).emit("update", "The owner (" +people[s.id].name + ") has left the server. The room is removed and you have been disconnected from it as well.");
				var socketids = [];
				for (var i=0; i<sockets.length; i++) {
					socketids.push(sockets[i].id);
					if(_.contains((socketids)), room.people) {
						sockets[i].leave(room.name);
					}
				}

				if(_.contains((room.people)), s.id) {
					for (var i=0; i<room.people.length; i++) {
						people[room.people[i]].inroom = null;
					}
				}
				room.people = _.without(room.people, s.id); //remove people from the room:people{}collection
				delete rooms[people[s.id].owns]; //delete the room
				delete people[s.id]; //delete user from people collection
				delete chatHistory[room.name]; //delete the chat history
				sizePeople = _.size(people);
				sizeRooms = _.size(rooms);
				io.sockets.emit("update-people", {people: people, count: sizePeople});
				io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
				var o = _.findWhere(sockets, {'id': s.id});
				sockets = _.without(sockets, o);
			} else if (action === "removeRoom") { //room owner removes room
				io.sockets.in(s.room).emit("update", "The owner (" +people[s.id].name + ") has removed the room. The room is removed and you have been disconnected from it as well.");
				var socketids = [];
				for (var i=0; i<sockets.length; i++) {
					socketids.push(sockets[i].id);
					if(_.contains((socketids)), room.people) {
						sockets[i].leave(room.name);
					}
				}

				if(_.contains((room.people)), s.id) {
					for (var i=0; i<room.people.length; i++) {
						people[room.people[i]].inroom = null;
					}
				}
				delete rooms[people[s.id].owns];
				people[s.id].owns = null;
				room.people = _.without(room.people, s.id); //remove people from the room:people{}collection
				delete chatHistory[room.name]; //delete the chat history
				sizeRooms = _.size(rooms);
				io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
			} else if (action === "leaveRoom") { //room owner leaves room
				io.sockets.in(s.room).emit("update", "The owner (" +people[s.id].name + ") has left the room. The room is removed and you have been disconnected from it as well.");
				var socketids = [];
				for (var i=0; i<sockets.length; i++) {
					socketids.push(sockets[i].id);
					if(_.contains((socketids)), room.people) {
						sockets[i].leave(room.name);
					}
				}

				if(_.contains((room.people)), s.id) {
					for (var i=0; i<room.people.length; i++) {
						people[room.people[i]].inroom = null;
					}
				}
				delete rooms[people[s.id].owns];
				people[s.id].owns = null;
				room.people = _.without(room.people, s.id); //remove people from the room:people{}collection
				delete chatHistory[room.name]; //delete the chat history
				sizeRooms = _.size(rooms);
				io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
			}
		} else {//user in room but does not own room
			if (action === "disconnect") {
				io.sockets.emit("update", people[s.id].name + " has disconnected from the server.");
				if (_.contains((room.people), s.id)) {
					var personIndex = room.people.indexOf(s.id);
					room.people.splice(personIndex, 1);
					s.leave(room.name);
				}
				delete people[s.id];
				sizePeople = _.size(people);
				io.sockets.emit("update-people", {people: people, count: sizePeople});
				var o = _.findWhere(sockets, {'id': s.id});
				sockets = _.without(sockets, o);
			} else if (action === "removeRoom") {
				s.emit("update", "Only the owner can remove a room.");
			} else if (action === "leaveRoom") {
				if (_.contains((room.people), s.id)) {
					var personIndex = room.people.indexOf(s.id);
					room.people.splice(personIndex, 1);
					people[s.id].inroom = null;
					io.sockets.emit("update", people[s.id].name + " has left the room.");
					s.leave(room.name);
				}
			}
		}	
	} else {
		//The user isn't in a room, but maybe he just disconnected, handle the scenario:
		if (action === "disconnect") {
			io.sockets.emit("update", people[s.id].name + " has disconnected from the server.");
			delete people[s.id];
			sizePeople = _.size(people);
			io.sockets.emit("update-people", {people: people, count: sizePeople});
			var o = _.findWhere(sockets, {'id': s.id});
			sockets = _.without(sockets, o);
		}		
	}
}
Example #20
0
                dbot.api.atheme.getChannelFlags(server, cName, function(err, flags) {
                    var ops = _.map(flags, function(f, k) {
                                   var staff = (f.indexOf('O') !== -1);
                                   if(this.config.notifyVoice && !staff) {
                                        staff = (f.indexOf('V') !== -1);
                                   }
                                   if(staff) {
                                        return k;
                                   }
                               }.bind(this));
		ops = _.without(ops, undefined);
console.log(ops);
                    this.db.read('nunsubs', cName + '.' + server, function(err, nunsubs) {
                        if(nunsubs) {
                            _.each(nunsubs.users, function(user) {
                                var uPart = user.split('.')[0];
                                if(_.include(ops, uPart)) {
console.log('removing ' + uPart);
                                    ops = _.without(ops, uPart);
                                }
                            });
                        }

                        var offlineOps = {};
                        async.each(ops, function(op, done) {
                            dbot.api.users.isOnline(server, cName, op, function(err, user, online) {
				if(user) {
                                if(!err && !online) offlineOps[op] = user;
                                if(user.currentNick !== op) {
                                    ops = _.without(ops, op);
                                    ops.push(user.currentNick);
                                }
				}
                                done();
                            });
                        }, function() {
                            // Queue notifies for offline ops
                            if(!_.include(this.config.noMissingChans, cName)) {
                                _.each(offlineOps, function(op) {
                                    if(!this.pending[op.id]) this.pending[op.id] = [];
                                    this.pending[op.id].push({
                                        'time': new Date().getTime(),
                                        'channel': cName,
                                        'user': user.id,
                                        'message': message
                                    });
                                    this.pNotify[op.id] = true;
                                }, this);
                            }

                            // Send notifies to online ops
                            ops = _.difference(ops, _.keys(offlineOps));
                            message = this.internalAPI.formatNotify(type, server,
                                        user, cName, message);
                            this.internalAPI.notify(server, ops, message);
                            if(_.has(this.config.chan_redirs, cName)) {
                                dbot.say(server, this.config.chan_redirs[cName], message);
                            }
                        }.bind(this));
                    }.bind(this));
                }.bind(this));
Example #21
0
//finds right socket connection of current user and removes it
function findSocketAndRemove(s){
	var o = underScore.findWhere(sockets, {'id': s.id});
	sockets = underScore.without(sockets, o);
}
Example #22
0
_.each(elim, function(value, key, list){ 
	compXX = _.without(compXX,value)
	compYY = _.without(compYY,value)
}, this)
Example #23
0
function inSentence(sentence, keyphrase, goldLable)
{
	// var goldLable = keyphrase
	// console.log(sentence)
	keyphrase = keyphrase.toLowerCase()
	// var sentencelist = sentence.split(" ")
	// var output = []

	// var sentenceList = sentence.split(" ")

	// _.each(sentenceList, function(element, key, list){
	// 	if (element == keyphrase)
	// 		output.push(key)
	// }, this)

	var listToFind = []
	var output = []

	listToFind.push(keyphrase)
	listToFind = _.unique(listToFind.concat(keyphrase.split(" ")))

	// remove "with" from labels
	listToFind = _.without(listToFind,'with')
	listToFind = _.without(listToFind,'without')
	listToFind = _.without(listToFind,'working')
	listToFind = _.without(listToFind,'no')
	listToFind = _.without(listToFind,'usd')

	// process.exit(0)
	var alreadycared = false

	_.each(listToFind, function(phrase, key, list){ 
		// console.log(phrase)
		var index = compeletePhrase(sentence, phrase)
		// console.log(index)
		if (index != -1)
			{
			if ((goldLable == 'Leased Car') && (alreadycared == false))

				{
				alreadycared = true
				var negation = truth_utils.negation(sentence.replace('without','no'),['agreement'], truth_filename)
				if (negation == true)
					{
						// output.push([-1,-1,'No agreement',''])
						output.push(['No agreement','no agreement',getWords(sentence,"no agreement"), whatinSentence(sentence,['no agreement'])])
					}
				else
					{	
					var negation1 = truth_utils.negation(sentence.replace('without','no'),['car','lease'], truth_filename)
					if (negation1 == true)
						output.push(['Without leased car','car',getWords(sentence,"car"), whatinSentence(sentence,['car','leased'])])
					else
						output.push(['With leased car','car',getWords(sentence,"car"), whatinSentence(sentence,['car','leased'])])
					}
				}	
			output.push([goldLable, sentence.slice(index, index + phrase.length), getWords(sentence, phrase), [index, index + phrase.length]])
			}
		// else
			// res = false
	}, this)



	// if (sentence == "i agree to with leased @ 8 hours with slow promotion track")
		// {
			// console.log(output)
			// console.log(goldLable)
		// }
	// process.exit(0)
	return output
}