Example #1
0
		roomManager.getOrCreate(gameSlug, function(data) {
			console.log(data);
			var room = data;
			if(room) {
				if (!_.isUndefined(user.role) && user.role === 'student') {
					// student = author
					console.log(user.userName + ' is an author');
					// remove current user first
					roomAuthors = _.reject(room.authors, function(el) { return el.userName === user.userName; });
					if(roomAuthors.length < 4) {
						// max 4 authors per room
						user.socketId = socket.id;
					 	roomAuthors.push(user);
					 	room.authors = roomAuthors;
						socket.join(gameSlug);
						roomManager.setRoom(gameSlug, JSON.stringify(room), function(err, reply) {
			                console.log('Room updated');
				            socket.broadcast.to(gameSlug).emit('author:joined:room', {
						        user: user,
		        				socketId: socket.id
		      				});
			            });
					} else {
						//room.full
						room = null;
					}
				} else if (!_.isUndefined(user.role) && user.role === 'teacher') {
					// teacher
				}
			}
			// return room data to callback function	
			fn(room);
		});
Example #2
0
    from_lastfm: function(attrs) {
        var mapped = {};

        if(!_.isUndefined(attrs.mbid))
            mapped._id = attrs.mbid;
        if(!_.isUndefined(attrs._id))
            mapped._id = attrs._id;
        if(!_.isUndefined(attrs.name))
            mapped.name = attrs.name;
        if(!_.isUndefined(attrs.url))
            mapped.url = attrs.url;
        if(!_.isUndefined(attrs.image))
            mapped.images = _.map(attrs.image, function(img) {
                return { url: img["#text"], size: img.size };
            });
        if(!_.isUndefined(attrs.artist) && !_.isUndefined(attrs.artist.mbid))
            mapped.artist = attrs.artist.mbid;
        if(!_.isUndefined(attrs.duration))
            mapped.duration = parseInt(attrs.duration);
        if(!_.isUndefined(attrs.playcount))
            mapped.playcount = parseInt(attrs.playcount);
        if(!_.isUndefined(attrs.listeners))
            mapped.listeners = parseInt(attrs.listeners);

        return mapped; 
    }
Example #3
0
function DXHTTPRequest(resource, data, method, headers) {
  if (underscore.isUndefined(resource)) {
    throw new Error("resource argument is required");
  }
  if (underscore.isUndefined(SECURITY_CONTEXT)) {
    throw new Error("SECURITY_CONTEXT must be set");
  }
  if (underscore.isUndefined(data)) {
    data = {};
  }
  if (underscore.isUndefined(method)) {
    method = 'POST';
  }
  if (underscore.isUndefined(headers)) {
    headers = {};
  }
  headers['Authorization'] = SECURITY_CONTEXT.auth_token_type + ' ' + SECURITY_CONTEXT.auth_token;
  headers['Content-Type'] = 'application/json';

  var request = new http.ClientRequest(APISERVER_HOST + ':' + APISERVER_PORT + resource);
  request.method = method;
  request.header(headers);
  request.post = JSON.stringify(data);

  response = request.send(false);
  if (response.status != 200) {
    throw new Error("Code " + response.status + ", " + response.data.toString('utf-8') + " TODO: make me a DXError");
  }
  return JSON.parse(response.data.toString('utf-8'));
}
Example #4
0
  correctPathSync: function(filePath,parent){
      if(parent.folder === null || _.isUndefined(filePath) || _.isUndefined(parent.folder) || (filePath.substring(0, 7) == "mailto:") || (filePath.substring(0, 7) == "http://") || (filePath.substring(0, 8) == "https://")){
        return filePath;    
      } 
      else if(filePath === ".."){

          var mixedPath = path.normalize(parent.folder +"../index.js");
          mixedPath = mixedPath.replace(/\\/g,"\/" ).replace("//", "/"); 


          return mixedPath;
      }
      else if(filePath.slice(-3) === "/.."){

          filePath = filePath+"/index.js";
          var mixedPath = path.normalize(parent.folder +"/"+ filePath);
          mixedPath = mixedPath.replace(/\\/g,"\/" ).replace("//", "/"); 


          return mixedPath;

      }
      else{
        var mixedPath = path.normalize(parent.folder +"/"+ filePath);
        mixedPath = mixedPath.replace(/\\/g,"\/" ).replace("//", "/"); 
        return mixedPath; 
      }
  },
Example #5
0
 client.deleteMulti(['foobar'], function(response){
   assert(!_.isUndefined(response));
   assert(!_.isUndefined(response.foobar));
   assert(_.isObject(response.foobar.error));
   assert(_.isNull(response.foobar.data));
   done();
 });
Example #6
0
 client.saveMulti(postData, function(response){
   assert(!_.isUndefined(response));
   assert(!_.isUndefined(response.foobar));
   assert(_.isObject(response.foobar.error));
   assert(_.isNull(response.foobar.data));
   done();
 });
Example #7
0
        'interpolatedQuote': function(server, channel, key, quoteTree) {
            if(!_.isUndefined(quoteTree) && quoteTree.indexOf(key) != -1) { 
                return ''; 
            } else if(_.isUndefined(quoteTree)) { 
                quoteTree = [];
            }

            var index = _.random(0, this.quotes[key].length - 1);
            var quoteString = this.quotes[key][index];

            // Parse quote interpolations
            var quoteRefs = quoteString.match(/~~([\d\w\s-]*)~~/g);
            var thisRef;

            while(quoteRefs && (thisRef = quoteRefs.shift()) !== undefined) {
                var cleanRef = dbot.cleanNick(thisRef.replace(/^~~/,'').replace(/~~$/,'').trim());
                if(cleanRef === '-nicks-') {
                    var randomNick = dbot.api.users.getRandomChannelUser(server, channel);
                    quoteString = quoteString.replace("~~" + cleanRef + "~~", randomNick);
                    quoteTree.pop();
                } else if(_.has(this.quotes, cleanRef)) {
                    quoteTree.push(key);
                    quoteString = quoteString.replace("~~" + cleanRef + "~~", 
                            this.internalAPI.interpolatedQuote(server, channel, cleanRef, quoteTree.slice()));
                    quoteTree.pop();
                }
            }

            return quoteString;
        }.bind(this),
Example #8
0
 sync: function(method, model, options) {
     // make the database's url explicit
     if(!_.isUndefined(options) && !_.isUndefined(options.url))
         options.url = url.resolve(config.database.url(), options.url);
     else if(_.result(model, 'url'))
         options.url = url.resolve(config.database.url(), _.result(model, 'url'));
     return Backbone.sync.apply(this, [method, model, options]);
 }
Example #9
0
            _.each(schema, function (properties, index)
            {
                var realProperties = properties.index ? schema[properties.index] : properties;
                var realIndex = properties.index ? properties.index : index;

                if (options.all !== true && properties.type != 'object' && properties.type != 'array' &&
                    ((properties.invisible || (properties.toObject == 'never' && options.nevers !== false)
                    || (properties.toObject == 'changed' && (options.changed === false || !self.tracking.hasChanged(realIndex)))
                    || (properties.type == 'alias' && !options.alias === false)
                    || (properties.toObject == 'hasValue' &&
                        ((_.isUndefined(self[index]) && options.undefineds === false) ||
                        (_.isNull(self[index]) && options.nulls == false) ||
                        options.hasValues === false))
                    || (properties.toObject == 'always' && options.always === false)
                    || (properties.toObject == 'hasValue' && ((_.isNull(self[index]) && !options.nulls === false) || options.hasValues === false))) ))
                {
                    return;
                }

                // Fetch value from self[index] to route through getter.
                var value = self[index];
                if ((_.isNull(value) && !options.includeNull) || (_.isUndefined(value) && !options.includeUndefined))
                    return;

                // If value does not need to be cloned, place in index.
                if ((value === undefined || value === null)
                || properties.type !== 'object' && properties.type !== 'array' && properties.type !== 'date')
                {
                    getObj[index] = value;
                    // Clone Object
                } else if (properties.type === 'object')
                {
                    // Call toObject() method if defined (this allows us to return primitive objects instead of SchemaObjects).
                    if (_.isFunction(value.toObject))
                    {
                        getObj[index] = value.toObject(options);
                        // If is non-SchemaType object, shallow clone so that properties modification don't have an affect on the original object.
                    } else if (_.isObject(value))
                    {
                        getObj[index] = _.clone(value);
                    }

                    // Clone Array
                } else if (properties.type === 'array')
                {
                    // Built in method to clone array to native type
                    getObj[index] = value.toArray();

                    // Clone Date object.
                } else if (properties.type === 'date')
                {
                    // https://github.com/documentcloud/underscore/pull/863
                    // _.clone doesn't work on Date object.
                    getObj[index] = new Date(value.getTime());
                }
            });
Example #10
0
 'galleryInfoString': function(galData) {
     var info = '';
     if(!_.isUndefined(galData) && _.has(galData, 'data') && !_.isUndefined(galData.data.is_album)) {
         if(galData.data.is_album === true) {
             info = this.internalAPI.albumInfoString(galData);
         } else {
             info = this.internalAPI.infoString(galData);
         }
     }
     return info;
 }.bind(this)
Example #11
0
 K.bind('assetchange', function(asset) {
   
   if (_.isUndefined(K.sockets)) return;
   if (_.isUndefined(K.sockets.assets)) {
     
     return;
   }
   K.sockets.assets.emit('reload', [{
     href: '/css/style.css'
   }], 'styles');
 });
Example #12
0
	isValidMatch: function(results) {
		// takes the object returned from processMatchDetails, and returns
		// true/false depending on whether it's a "real" match.
		if((results.teams[0].kills + results.teams[1].kills)==0 || results.duration <= 410) {
			return false;
		} else if(_.isUndefined(results.teams[0].name) || _.isUndefined(results.teams[1].name)) {
			return false;
		} else {
			return true;
		}
	},
Example #13
0
var getter = function(value, properties) {
  // Most calculations happen within the typecast and the value passed is typically the value we want to use.
  // Typically, the getter just returns the value.
  // Modifications to the value within the getter are not written to the object.

  // Return default value if present & current value is undefined -- do not write to object
  if(_.isUndefined(value) && !_.isUndefined(properties.default)) {
    value = typecast.call(this, (_.isFunction(properties.default) ? properties.default.call(this) : properties.default), value, properties);
  }

  return value;
};
Example #14
0
 parse: function(node,parent){
     var newNode = {};
     newNode.name = "";
     if(!_.isUndefined(node.source) && node.source !== null){
         newNode.group = "js-export";
         newNode.rawName = node.source.value;
         newNode.name = parsersHelper.correctPathSync(node.source.value,parent);
         if(!_.isUndefined(node)){
             newNode.data = JSON.stringify(node);
         }
     }                          
     return newNode;
 }
Example #15
0
	title: function(node){
		//console.log(node);
		//return node.rawName;
		var name = node.rawName;
			name = "+"+name;
			if(!_.isUndefined(node.rawType) && node.rawType !== null){
				name = name+" : object";
			}
			if(!_.isUndefined(node.rawValue) && node.rawValue !=="" && node.rawValue !== null && node.rawValue !== "NULL"){
				name = name+" = "+parsersHelper.removeSpecialChar(parsersHelper.reduceLength(node.rawValue,15));
			}
			return name;
	}
Example #16
0
			_.each(Object.keys(this.activeLeagueIds), _.bind(function(leagueId) {
				var league = this.leagues[leagueId];

				// short circuit the whole loop if we're missing a league.
				// if(missingLeague) return;

				if(_.isUndefined(league)) {
					winston.error("League is not defined for " + leagueId);
					// Not really sure what to do in this case.
					// really we need to create a new entry in this list, but I'm not sure
					// what it should have in it.

					// OH I know what happened. The patch hit, new tickets went out, and
					// we didn't have them in the list. I think we need to do a full league
					// update operation.

					// this is a little error prone. The update league listing takes time,
					// and if league is undefined, the next check is DEFINITELY going to fail.
					// really we want to update the league listing, wait for that to execute
					// and then return to this proces. 
					// this.updateLeagueListing();
					// missingLeague = true;
					return;
				}

				if(_.isUndefined(league.lastSeenMatchIds)) {
					winston.info("Found un-initialized league: " + league.name);
					league.lastSeenMatchIds = [];
					league.init = true;
				}

				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));
			}, this));
Example #17
0
 ioChannel.on('connection', function(socket) {
   
   storage[channelId] = storage[channelId] || {};
   storage[channelId][socket.id] = {
     'name': _.uniqueId('User ')
   };
   
   if (!_.isUndefined(channel.on) && !_.isUndefined(channel.on.channel)) _.each(channel.on.server || (channel.on.server = {}), function(callback, eventName) {
     socket.on(eventName, callback);
     S.channels[eventName] = {};
   });
   
   
   K.sockets[channelId] = socket;
 });
Example #18
0
 '~syt': function(event) {
     var lastLink = dbot.modules.link.links[event.channel.name];
     if(!_.isUndefined(event.params[1])) {
         lastLink = event.params[1];
     }
     
     if(lastLink.match(this.youtubeRegex)) {
         dbot.api.link.getTitle(lastLink, function(title) {
             name = title.replace(' - YouTube', '');        
             this.api.spotifySearch(name, function(body, t) {
                 if(body) {
                     event.reply(dbot.t('found', {
                         'artist': _.map(body.tracks[0].artists, 
                             function(a) { return a.name }).join(', '), 
                         'album': body.tracks[0].album.name, 
                         'track': body.tracks[0].name, 
                         'url': t
                     }));
                 } else {
                     event.reply(dbot.t('not-found'));
                 }
             }.bind(this));
         }.bind(this));
     } else {
         event.reply('That\'s not a YouTube link');
     }
 }
Example #19
0
 this.api.getUserIgnores(event.rUser, function(err, ignores) {
     if(err || !ignores || _.isUndefined(module)) {
         if(ignores) {
             event.reply(dbot.t('unignore_usage', {
                 'user': event.user, 
                 'modules': ignores.ignores.join(', ')
             }));
         } else {
             event.reply(dbot.t('empty_unignore_usage', {
                 'user': event.user
             }));
         }
     } else {
         if(_.include(ignores.ignores, module)) {
             ignores.ignores = _.without(ignores.ignores, module);
             this.db.save('ignores', event.rUser.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));
Example #20
0
exports.extender = function() {
  var K = this;
  if (_.isUndefined(K.app)) 
    return;

  
  

  K.bind('newcontent', function(CE) {
    
    watch.call(K, CE.absPath());
  });
  
  K.bind('extended', function() {
    

    
    _.each(K.assets, function(type, typeName) {
      _.each(type, function(asset, clientPath){
        if (_.isUndefined(asset.filepath)) return;
        
        watch.call(K, asset.filepath);
      });
    });
  });
};
Example #21
0
File: imdb.js Project: Rob-pw/dbot
 }, function(error, response, body) {
     if(_.isObject(body) && !_.isUndefined(body[0])) {
         event.reply(this.internalAPI.formatLink(body[0]));
     } else {
         event.reply(dbot.t('imdb_noresults'));
     }
 }.bind(this));
Example #22
0
	removeSpecialChar: function(str){
	    	if(str !== null && _.isUndefined(str) === false){
		    	var str = str.replace(/\\n/g, "\\n")
	                      .replace(/\\'/g, "\\'")
	                      .replace(/\\"/g, '\\"')
	                      .replace(/\\&/g, "\\&")
	                      .replace(/\\r/g, "\\r")
	                      .replace(/\\t/g, "\\t")
	                      .replace(/\\b/g, "\\b")
	                      .replace(/\\f/g, "\\f")
	                      .replace(/\\\//g, "/")
	                      .replace( /([^\x00-\xFF]|\s)*$/g, '')
	                    //  .replace(/[`~!@$%^&*|+=?;'"<>\\\/]/gi, '');
	                      .replace(/[`~!@#$%^&*()_|=?;'",\{\}.<>\\\/]/gi, '')
	                      .replace(/\W/g, '');
            }



            //.replace(/\W/g, '');


            	                      //.replace(/[`~!@$%^&*_|+\-=?;'"<>]/gi, '');
	                      //.replace(/[`~!@$%^&#.*_|+\-=?;'"<>]/gi, '');
            return str;
	},
Example #23
0
 url: function() {
     if(_.isNull(this.event) || _.isUndefined(this.event)) {
         return "session/permalink";
     } else {
         return this.event.url() + "/sessions";
     }
 }
Example #24
0
    getSockKey: function() {
        if(_.isUndefined(this.get("sock-key"))) {
            this.set("sock-key", exports.generateSockKey(this.id));
        }

        return this.get("sock-key");
    },
Example #25
0
	writeErr: function(type, message) {
		if(_.isUndefined(message)) {
			this.write(type + "-err");
		} else {
			this.write(type + "-err", {message:message});
		}
	},
Example #26
0
exports.sexp = function(obj) {
    if (_.isNull(obj) || _.isUndefined(obj)) {
        return 'nil';
    } else if (obj.toSexp) {
        return obj.toSexp();
    } else if (obj.lispType) {
        switch (obj.lispType) {
        case 'string': return exports.string(obj);
        case 'symbol': return exports.symbol(obj);
        case 'keyword': return exports.keyword(obj);
        case 'list': return exports.list(obj);
        case 'vector': return exports.vector(obj);
        } 
        throw new Error("Unrecognized lispType: " + util.inspect(obj.lispType));
    } else if (_.isString(obj)) {
        return exports.string(obj);
    } else if (_.isArray(obj))  {
        return exports.list(obj);
    } else if (_.isBoolean(obj)) {
        return exports.bool(obj);
    } else if (_.isNumber(obj)) {
        return exports.number(obj);
    } else {
        return exports.alist(obj);
    }
};
Example #27
0
	featureLookupTable.featureIndexToFeatureName.forEach(function(featureName) {
		if (_.isUndefined(featureName)) 
			arff += "@attribute undefined {0,1}"+"\n";
		else if (!_.isString(featureName))
			throw new Error("Expected featureName to be a string, but found "+JSON.stringify(featureName));
		else arff += "@attribute "+featureName.replace(/[^a-zA-Z0-9]/g, "_")+" "+"{0,1}"+"\n";
	});
Example #28
0
		_.each(source, function(obj, key, source) {
			if (_.isUndefined(map[key])) {
				delete source[key];
			} else {
				filter( obj, map[key]);
			}
		});
Example #29
0
 function handleRes(res){
   if(!_.isUndefined(analysePart.messagesSoFar)){
     if(analysePart.status === "analysing"){
       callback(null, "ok")
       var updating = new helper.ResponseBean();
       updating.status = "ok";
       updating.msg = "analysing";
       updating.id = archiveInfo._id;
       sendJSON(request, response, updating);
     }else if(analysePart.status === "done" && res._rev.split("-")[0]==2){
       db.get("config", function(err, res){
         var analyseTime = (new Date().getTime()- ptime.getTime());
         var tweet = "after "+helper.convertMilliseconds(analyseTime).clock+" is #twapperlyzer done with "+analysePart.archive_info.keyword
         if (res) {
           tweet+=" see http://"+res.standardUrl+"/#page-"+analysePart._id;
         }
         if(exist(request.query.mention) && request.query.mention !== "" ){
           tweet = "@"+request.query.mention+" "+tweet
         }
         if(conf.twapperlyzer.sendTweets === true ){
           oAuth.post("http://api.twitter.com/1/statuses/update.json", conf.twitter.accessToken, 
           conf.twitter.accessTokenSecret, {"status":tweet}, function(error, data) {
             if(error) console.log(require('sys').inspect(error));
           }); 
         }else{
           console.log("tweet",tweet);
         }
       });
     }
   }else{
     callback(null, "ok");
   }
 }
Example #30
0
        'setconfig': function(event) {
            var configPathString = event.params[1],
                configKey = _.last(configPathString.split('.')),
                newOption = event.params[2];

            if(!_.include(noChangeConfig, configKey)) {
                var configPath = getCurrentConfig(configPathString);

                if(configPath == false || _.isUndefined(configPath.value)) {
                    event.reply("Config key doesn't exist bro");
                    return;
                }
                var currentOption = configPath.value;

                // Convert to boolean type if config item boolean
                if(_.isBoolean(currentOption)) {
                    newOption = (newOption == "true");
                }

                if(_.isArray(currentOption)) {
                    event.reply("Config option is an array. Try 'pushconfig'.");
                }
                
                event.reply(configPathString + ": " + currentOption + " -> " + newOption);
                configPath['user'][configKey] = newOption;
                dbot.reloadModules();
            } else {
                event.reply("This config option cannot be altered while the bot is running.");
            }
        },