Example #1
0
 _.each(options.files, function(fileName) {
   var base = fileName.split(".")[0];
   var api = require(options.appOptions.appRoot + "/rest/" + fileName);
   var apiReplacements = {
     name: base,
     methods: []
   };
   replacements.apis.push(apiReplacements);
   _.each(connectRouter.methods, function(verb) {
     if (api[verb]) {
       apiReplacements.methods.push({
         name: verb,
         verb: verb.toUpperCase()
       });
     }
   });            
 });
Example #2
0
 this.runQuery = function (params, callback) {
   
   var query = 'http://' + GOOGLE_HOST + BEACON_PATH + '?';
 
   _.each(params, function (val, key) {
     query += key + '=' + val + '&';
   });
   query = query.slice(0,-1);
 
   request.get(query, function (error, response, body) {
     if (!error && response.statusCode == 200) {
       // console.log(body); 
     }
     return callback(error, response);
   });
 
 };
Example #3
0
JSBot.prototype.emit = function(event) {
    if(event.action in this.events) {
        _.each(this.events[event.action], function(listener) {
            var eventFunc = listener.listener;
            if(_.isFunction(eventFunc) && 
                (_.has(this.ignores, event.user) && _.include(this.ignores[event.user], listener.tag)) == false &&
                (_.has(this.ignores, event.channel) && _.include(this.ignores[event.channel], listener.tag)) == false) {
                try {
                    eventFunc.call(this, event);
                } catch(err) {
                    console.log('ERROR: ' + eventFunc + '\n' + err);
                    console.log(err.stack.split('\n')[1].trim());
                }
            }
        }, this);
    }
};
Example #4
0
 window.addEventListener('message', function(event) {
     console.log('frame -> page: ' + event.data.eventName);
     if (event.source === iframe.contentWindow) {
         if (event.data.eventName === 'ready') {
             self.sendData({
                 type: 'start battle',
                 playerJson: gs.player.toJson(),
                 battleJson: self.battle.toJson(),
                 shipID: self.ship.id
             });
         }
         _.each(self.eventHandlers, function(handler) {
             event.data.frame = self;
             handler(event.data);
         });
     }
 }, false);
Example #5
0
 this.executeSqlFile({file : tableSql}, function(err,tables){
   if(err){
     next(err,null);
   }else{
     _.each(tables, function(table){
       var _table = new Table({
         schema : table.schema,
         name : table.name,
         pk : table.pk,
         db : self
       });
       // This refactoring appears to work well:
       MapTableToNamespace(_table);
     });
     next(null,self);
   }
 });
Example #6
0
  function theFunPart(err){
    utils.chkerr(err).clogok('The Fun Part');
    var toTearDown=this;

    var eventEmitter=new events.EventEmitter();

    dbmonChannel=dbmon.channel({
      driver:'postgresql', monitor: 'insert,update,delete,truncate', method: 'trigger',
      table:'dbmontmp',
      keyfld: { name:'i', type:'integer' },
      driverOpts:{
        postgresql:{
          cli:pgcli
        }
      },
      transports: 'eventEmitter',
      transportsOpts:{
        eventEmitter:{
          eventEmitter:eventEmitter
        }
      }
    });

    _.each(['insert', 'update', 'delete', 'truncate'], function(op){
      eventEmitter.on(op, function(row){
        utils.clogok('EventEmitter on '+op+' called OK, row='+JSON.stringify(row));
        notifications++;
      });
    });

    //Triggering notifications
    setTimeout(function(){
      pgcli.query('insert into dbmontmp values (1, \'one\')', function(){
        //TEST ERROR
        pgcli.query('insert into dbmontmp values (1, \'one\')', function(err){
          assert.ok(err!==null, 'Duplicate values should not be permitted'.red);
        });
      });
      pgcli.query('update dbmontmp set v=\'ZERO\' where i=0');
      pgcli.query('delete from dbmontmp where i=0');
    }, 500);

    //Stop
    setTimeout(toTearDown, 1000);
  },
Example #7
0
			  	_(len).times(function(n){

			  		var report = []

			  		n += 1

					mytrain = filtrain(mytrainset, n, 1)

					async.eachSeries(Object.keys(classifiers), function(classifier, callback1){ 
				  	// _.each(classifiers, function(classifier, name, list){ 
				  		console.log("start trainandTest")
				  		console.log(classifier)
		    			trainAndTest_async(classifiers[classifier], mytrain, test, function(err, stats){
				    		console.log("stop trainandTest")
			   	    		fs.appendFileSync(statusfile, classifier+"\n")
			   	    		fs.appendFileSync(statusfile, JSON.stringify(stats['stats'], null, 4))
			   	    		report.push(stats['stats'])
				    		callback1()
		    			})
			    		
				  	}, function(err){
						fiber.run(report)
					})

					var report1 = Fiber.yield()

			   	    extractGlobal(classifiers, mytrain.length/train[0].length, n,  report1, stat)

			   	    fs.appendFileSync(statusfile, JSON.stringify(stat, null, 4))

			   	    console.log("calc stats")
			   	    fs.appendFileSync(statusfile, setstat(mytrain))
			   	    console.log("stop stats")
			   	    
			   	    var cllist = Object.keys(classifiers)
			   	    var baseline = cllist[0]
			   	    var sotas = cllist.slice(1)

			   	    _.each(sotas, function(sota, key, list){ 
                    	_.each(stat, function(data, param, list){
							plot(fold, param, stat, baseline, sota)
							plot('average', param, stat, baseline, sota)
						})
			   	    }, this)
				})
Example #8
0
	storage.getUsersInRoom(roomId, function(usernameToUser) {
		logger.debug('[broadcastToRoom]', "Raw data from key " + keys.getKey_usersInRoom( roomId ) + ": ", "usernameToUser:"******"\tSENDING TO " + userModel.get('name'));
			var socketId = sessionIdsByKey[ keys.getKey_userInRoom(userModel.get('name'), roomId) ];

			if(socketId){
				//logger.debug('[broadcastToRoom]', "============ SOCKET "+socketId+" ==========================================");
				//logger.debug('[broadcastToRoom]', ioSockets.socket(socketId));
				//logger.debug('[broadcastToRoom]', "============ /SOCKET "+socketId+" ==========================================");

				if( typeof ioSockets.connected[socketId].sessionId  == "undefined"){
					// This happened once (and before this check was here, crashed the server).  Not sure if this is just a normal side-effect of the concurrency or is a legit
					// problem. This logging should help in debugging if this becomes an issue.
					logger.warning('[broadcastToRoom]', "Somehow the client socket for " + userModel.get('name') + " is totally closed but their socketId is still in the hash. Potentially a race-condition?");
					delete sessionIdsByKey[ keys.getKey_userInRoom(userModel.get('name'), roomId) ];
				} else {
					// SWC 20150303 - just noticed this method has been using the global io.sockets instead of the
					// local ioSockets var. That's probably fairly equivalent at the moment... but we should def. use
					// the local var if it is going to exist at all.
					//io.sockets.connected[socketId].json.send(data);
					ioSockets.connected[socketId].json.send(data);
				}
			}
		});

		if(typeof callback == "function"){
			callback();
		}
	});
Example #9
0
        'logError': function(server, err) {
            var stack = err.stack.split('\n').slice(1, dbot.config.debugLevel + 1),
                logChannel = this.config.logChannel[server],
                time = new Date().toUTCString();

            dbot.say(server, logChannel, dbot.t('error_message', {
                'time': time,
                'error': 'Message: ' + err
            })); 

            _.each(stack, function(stackLine, index) {
                dbot.say(server, logChannel, dbot.t('error_message', {
                    'time': time,
                    'error': 'Stack[' + index + ']: ' +
                        stackLine.trim()
                }));
            });
        },
Example #10
0
				_.each(seeds[intent][keyphrase][ngram], function(value, ppdb, list){
					_.each(seeds[intent][keyphrase][ngram][ppdb], function(value, seed, list){
				
						var response = seed
				        var pos = rules.compeletePhrase(input, response)
				        if (pos != -1)
						{
	    					var elem = {}
	    					elem['intent'] = intent
	    					elem['keyphrase'] = keyphrase
	    					elem['ngram'] = ngram
	    					elem['ppdb'] = ppdb
	    					elem['seed'] = seed
	       					elem['position'] = [pos, pos + response.length]
	      					output.push(elem)
	    				}
	    			}, this)
				}, this)
Example #11
0
	_.each(RuleValues, function(values, key1, list1){ 
		data = data.concat(inSentence(sentence, key1, key1))
		_.each(values, function(value, key2, list2){
			if (value instanceof Array)
				data = data.concat(inSentence(sentence, value[0], value[1]))
			else
				data = data.concat(inSentence(sentence, value, value))

			// var found = inSentence(record['input'], value)
			// if (found.length != 0)
				// {
				// data[key]['found'].push([found, value])
				// }
			// if (found == true)
				// data[key]['found'].push(value)

		}, this)
	 }, this) 
app.put('/Contact', function(req, res){
	var editContact = _.find(contacts, function(c){
		return req.body.id == c.id;
	});
	
	editContact.firstname = req.body.firstname;
	editContact.lastname = req.body.lastname;
	if(req.body.phonenumbers){
		editContact.phonenumbers = req.body.phonenumbers;
		_.each(editContact.phonenumbers, function(phonenumber){
			if(!phonenumber.id){
				phonenumber.id = uuid.v1();
			}
		});
	}
	console.log("Update " + JSON.stringify(editContact));
  	res.send(editContact);
});
Example #13
0
        var workWithStack = function (stack) {
            if (stack.route) {

                var route = stack.route,
                    methodsDone = {};
                _.each(route.stack, function (r) {
                    var method = r.method ? r.method.toUpperCase() : null;
                    if (!methodsDone[method] && method) {
                        //apilist.push({method:method, url : basepath+route.path, help:help});
                        debug('[' + method + '] ' + basepath + route.path);

                        methodsDone[method] = true;
                        calls.push({method: method, url: basepath + route.path, headers: {audoku: 'help'}});

                    }
                });
            }
        };
 function completePingResult(from, errors) {
     console.log("updating ping results for " + from);
     _.each(netDb.db, function(discovery) {
         if(_.has(discovery, 'blades')) {
             _.each(discovery.blades, function(blade) {
                 var item = _.find(blade.networks, function(network) {
                     return network.ipv4 === from;
                 });
                 if(item) {
                     console.log("Found blade to update status for");
                     item.pingVerified = errors.length == 0 ? 1 : 0;
                     item.errors = errors;
                     netDb.triggerUpdate();
                 }
             })
         }
     });
 }
Example #15
0
exports.setTerminals = function(terminalsData){
	// validate stations of terminals
	_.each(terminalsData, function(terminalData){
		_.map(terminalData.canExecuteAtStations, function(stationId){
			if(!stations.get(stationId)){
				throw 'Error: tried to add a terminal to an undefined station (terminal #'+terminalData.id+')';
			}
		});
	});


	terminals.reset(terminalsData);

	// set the stations a terminal can execute on
	terminals.each(function(terminal){
		terminal.setStations(stations.getForTerminal(terminal));
	});
};
Example #16
0
    countDiffNodeParents() {
        const parentsHash = {};
        let length;

        _.each(this.nodes, (node) => {
            if (!(node.parentNodeId in parentsHash)) {
                parentsHash[node.parentNodeId] = 1;
            } else {
                parentsHash[node.parentNodeId]++;
            }
        });

        length = _.map(parentsHash, (q) => q);

        length.sort((a,b) => b - a);

        return length.slice(0,5);
    }
Example #17
0
            function(data, res){
                var json = JSON.parse(data),
                    result = {};
                _.each(json['departmentTree']['children'], function(department){
                    _.each(department['children'], function(item){
                        if(item['classes'] == 'user'){
                            var uid = item['loginName'],
                                nick = item['name'],
                                profile = {nick:nick};
                            result[uid] = profile;

                            //save the result in redis
                            redisClient.set(uid, JSON.stringify(profile));
                        }
                    });
                });
                callback(null, res.statusCode, result);
            },
Example #18
0
  shuffle: function (count) {
    var deck, groups, parts = [];

    deck = randomize(_.clone(initialDeck));

    groups = _.groupBy(deck, function (value, index) {
      return index % count;
    });

    _.each(_.values(groups), function (group) {
      var split = _.map(group, function (value) {
        return value.id;
      });
      parts.push(split);
    });

    return parts;
  },
Example #19
0
Info.pack = function(info, mapping){
  var data = _.clone(info);
  var reply = data.reply;
  if(mapping && _.isArray(reply)){
    _.each(reply, function(item, index){
      if(_.isFunction(mapping)){
        item = mapping(item, index, info)
      }else{
        item['title'] = item[ mapping['title'] || 'title']
        item['description'] = item[ mapping['description'] || 'description']
        item['pic'] = item[ mapping['pic'] || 'pic']
        item['url'] = item[ mapping['url'] || 'url']
      }
    })
  }
  var xml = _.template(Info.TEMPLATE_REPLY)(data);
  return xml;
}
Example #20
0
Lobby.prototype.createRoom = function(roomUrl) {
  roomUrl = roomUrl === undefined ? this.createUniqueURL() : roomUrl + this.createUniqueURL();
  if (this.rooms[roomUrl]) {
    this.createRoom(roomUrl);
  }

  // remove any existing empty rooms first
  var thatRooms = this.rooms;
  _.each(this.rooms, function(room, key, rooms) {
    if (room.getClientCount() == 0) {
      delete thatRooms[key];
      // console.log("removed room " + key);
    }
  });

  this.rooms[roomUrl] = new RoomClass.Room(this.io, roomUrl);
  return roomUrl;
};
Example #21
0
  addPages: function (newLinks, sourceUrl) {
    var grapher = this.grapher,
        options = this.options,
        logger  = this.options.logger,
        level   = (this.verified ? 1 : this.level + 1);

    _.each(newLinks, function (newLink) {
      if (!grapher.alreadyUsed(newLink)) {
        if (!grapher.aboveDomainLimit(newLink)) {
            grapher.pages[newLink] = new Page(newLink, grapher, options, sourceUrl, level);
          } else {
            logger.log('excluded above domain limit: ' + newLink);
          }
        }else{
          logger.log('excluded already has a page object: ' + newLink);
      }
    });
  },
Example #22
0
	_.each(files, function(file, key, list){

		var room = XML.parse(fs.readFileSync(file))

		_.each(room["Posts"]["Post"], function(post, key, list){
			var mypost = {}
			mypost["source"] = file
			mypost["user"] = post["user"]
			mypost["input"] = {
								"text": cleanstr(post["_Data"]),
								"original": post["_Data"]
								}
			mypost["output"] = [post["class"]]

			dataset.push(mypost)
		}, this)

	}, this)
Example #23
0
  logFetched: function () {
    var statuses     = _.pluck(this.pages, 'status'),
        fetchedCount = 0;
        errorCount = 0;
        dontFetchedCount = 0,
        logger = this.options.logger;

    _.each(statuses, function (s) {
      fetchedCount += (s === "fetched" ? 1 : 0);
      errorCount += (s === "error" ? 1 : 0);
      dontFetchedCount += (s === "dontfetch" ? 1 : 0);
    });

    logger.info('total pages ' + statuses.length);
    logger.info('total fetched ' + fetchedCount);
    logger.info('total errors ' + errorCount);
    logger.info('total pages outside limits ' + dontFetchedCount);
  }
Example #24
0
 start = function () {
     // Create a grid of quads covering the whole play field
     // Used to filter relevant tail pieces during rendering
     var quad_width = settings.GAME_WIDTH / _trail_quad_resolution;
     var quad_height = settings.GAME_HEIGHT / _trail_quad_resolution;
     _trail_quads = [];
     _.each(_.range(_trail_quad_resolution), function(i) {
             _.each(_.range(_trail_quad_resolution), function(j) {
                 _trail_quads.push(
                     {'x': i * quad_width,
                      'x2' : i == _trail_quad_resolution - 1 ? settings.GAME_WIDTH : (i + 1) * quad_width,
                      'y': j * quad_height,
                      'y2' : j == _trail_quad_resolution - 1 ? settings.GAME_HEIGHT : (j + 1) * quad_height,
                      'trail' : []
                 });
             });
     });
 },
Example #25
0
				this.getRecentLeagueMatches(leagueId, _.bind(function(matches) {
					// winston.info("Found " + matches.length + " matches for league: " + this.leagues[leagueId].name);

					matchCounts[leagueId] = matches.length;

					this.leagues[leagueId].init = false;

					// ugly but I'm too lazy to work out the flow control here.
					if(Object.keys(matchCounts).length==Object.keys(this.activeLeagueIds).length) {
						var out = "";

						_.each(Object.keys(matchCounts), function(k) {
							out += k + ":" + matchCounts[k] + "\t";
						});

						winston.info(this.liveGames.length + " -> " + out + " (states: " + Object.keys(this.states.lobbies).length + ")");
					}
				}, this));
Example #26
0
 $('#' + id + ' :file').change(function () {
     var att = {};
     _.each(this.files, function (f) {
         var reader = new FileReader();
         reader.onloadend = function (ev) {
             var result = ev.target.result;
             var data = result.slice(result.indexOf(',') + 1);
             var obj = {
                 content_type: f.type,
                 length: f.size,
                 data: data
             };
             w.addFile(f.name, obj, options);
         };
         reader.readAsDataURL(f);
     });
     w.updateValue(att, options);
 });
Example #27
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 #28
0
function cleancompare(ar)
// function compare(X,Y)
{

// var elim = []
var elim = ['is', 'are', 'be', 'will', 'let', 'i', 'I', 'no', 'not', 'to', 'you', 'we', 'for',
'i\'ll', 'so', 'the', 'can\'t', 'let\'s', 'only', 'on']

var X = ar[0]
var Y = ar[1]

var compX = cleanposoutput(cleanpos(X))
var compY = cleanposoutput(cleanpos(Y))

if (compY.length == 0) 
	compY = Y.split(" ")

if (compX.length == 0)
	compX = X.split(" ")

compX = lemmatize(compX)
compY = lemmatize(compY)

var compXX = compX
var compYY = compY

_.each(elim, function(value, key, list){ 
	compXX = _.without(compXX,value)
	compYY = _.without(compYY,value)
}, this)

if (compYY.length == 0) 
	compYY = Y.split(" ")
	
if (compXX.length == 0) 
	compXX = X.split(" ")
	
compXX = _.compact(compXX)
compYY = _.compact(compYY)

return [X, Y, compXX, compYY, distance(compXX, compYY)]

}
Example #29
0
	        _.each(item['labels'], function(values, label, list){
	                if (!(label in stats))
	                                stats[label] = {}
	                // _.each(values, function(value, key, list){
	                        if (!(_.isEqual(values,[''])))
	                        // if (values.length > 0)
	                                {
	                                        _.each(values, function(value, key1, list){
	                                                value = value.toLowerCase();
	                                                if (!(value in stats[label]))
	                                                         stats[label][value] = []
	                                                stats[label][value].push(item['sentence'])

	                                        }, this)
	                                }
	                                        // stats[label] = stats[label].concat(values)

	                 // }, this) 
	        }, this)
Example #30
0
	    function (callbackwhilst) {

			// var len = 5
	       	index += (index < 20 ? 2 : 5)

	       	var mytrain = train.slice(0, index)

	       	var mytrainex = (bars.isDialogue(mytrain) ? _.flatten(mytrain) : mytrain)
			var mytestex  = (bars.isDialogue(test) ? _.flatten(test) : test)

			console.log(msg("DEBUGWORKER "+process["pid"]+": index=" + index +
				" train_dialogue="+mytrain.length+" train_turns="+mytrainex.length+
				" test_dialogue="+test.length +" test_turns="+mytestex.length+
				" classifier="+classifier+ " fold="+fold))

		    	stats = trainAndTest_hash(classifiers[classifier], mytrainex, mytestex, false)

		    	var uniqueid = new Date().getTime()

		    	console.log(msg("DEBUGWORKER "+process["pid"]+": traintime="+
		    		stats['traintime']/1000 + " testtime="+ 
		    		stats['testtime']/1000 + " classifier="+classifier + 
		    		" Accuracy="+stats['stats']['Accuracy']+ " fold="+fold))

		    	var stats1 = {}
		    	_.each(stats['stats'], function(value, key, list){ 
		    		if ((key.indexOf("macro") != -1) || (key.indexOf("Accuracy") != -1 ) || (key.indexOf("micro") != -1))
		    			stats1[key] = value
		    	}, this)

				var results = {
					'classifier': classifier,
					'fold': fold,
					'trainsize': mytrain.length,
					'stats': stats1,
					'uniqueid': stats['id']
				}

				console.log(msg("DEBUG:"+JSON.stringify(results, null, 4)))

				process.send(JSON.stringify(results))
		   		callbackwhilst()
    	},