Example #1
0
  //PROTOTYPE - update split.person data
  function updateSplitPerson(options, cb) {
    console.log(' >> START splits.updateSplitPerson');
    if (!_.isFunction(cb)) cb = function(){};
    if (!options) return cb(new Error('No Options Specified'));      

    var splitID = options.splitID;
    var userID = options.userID;
    var successVal;
    var query = {};

    if (options.update && options.update.name) query['people.$.name'] = options.update.name;
    if (options.update && options.update.amount) query['people.$.amount'] = options.update.amount;
    if (options.update && options.update.original_amount) query['people.$.original_amount'] = options.update.original_amount;
    if (options.update && options.update.status) query['people.$.status'] = options.update.status;
    if (options.update.status == 'declined') query['people.$.amount'] = 0;

    if (_.isString(splitID)) splitID = new ObjectID(splitID);
    if (_.isString(userID)) userID = new ObjectID(userID);
    if (!splitID) return cb(new Error('Invalid Split ID'));
    if (!userID) return cb(new Error('Invalid User ID'));

    db.splits.update({_id: splitID, 'people._id': userID}, {$set: query}, function(err){
      if (err) return cb(err);
      console.log(' >> RETURN splits.updateSplitPerson');

      if (options.socket && options.update.status) {
        //broacast to channel splitID
        if (options.update.status == 'approved') {
          options.socket.broadcast.to(splitID.toHexString()).emit('split-person-approved', {splitID: splitID, userID: userID, person: options.update});
        } else if (options.update.status == 'declined') {
          options.socket.broadcast.to(splitID.toHexString()).emit('split-person-declined', {splitID: splitID, userID: userID, person: options.update});
        }

        //fake broadcasts for the rest of the people in this split
        getLast({splitID: splitID}, function(data){
          if (data && data.success && data.split) {
            if (data.split.people.length > 0) {
              var delay = 1000;
              _(data.split.people).forEach(function(person){

                //emit if the person is not the host, and is not the current user who issued this request
                if (person._id.toHexString() !== userID.toHexString() && person.host !== true) {
                  console.log(person);
                  delay += 3000;
                  setTimeout(function(){
                    //broadcast back to the calling socket
                    options.socket.emit('split-person-approved-fake', {splitID: splitID, userID: userID, person: person});
                    //broadcast back to the all other sockets
                    options.socket.broadcast.to(splitID.toHexString()).emit('split-person-approved-fake', {splitID: splitID, person: person});
                  }, delay);
                }
              });
            }
          }
        });        
      }

      return cb({success: true});
    });
  }
Example #2
0
    validate: function(attrs, options) {
        // klass should be Artist
        if(!_.isString(attrs.klass) || attrs.klass != "Artist")
            return "klass property must be 'Artist'.";

        // needs to have either _id or mbid
        if(_.isUndefined(attrs._id) && _.isUndefined(attrs.mbid))
            return "must define either _id or mbid";
        // should have a string _id
        if(!_.isUndefined(attrs._id) && (!_.isString(attrs._id) || attrs._id == ""))
            return "_id property must be a non-empty string.";
        // can have a string mbid that follows rules of _id
        if(!_.isUndefined(attrs.mbid) && (!_.isString(attrs.mbid) || attrs.mbid == ""))
            return "mbid property must be a non-empty string.";
        // should have a string name
        if(_.isUndefined(attrs.name) || !_.isString(attrs.name))
            return "must define name property that is a string.";
        // should have a string url
        if(_.isUndefined(attrs.url) || !_.isString(attrs.url))
            return "must define url property that is a string.";

        // should have images array
        if(_.isUndefined(attrs.images) || !_.isArray(attrs.images))
            return "must define images property that is an array.";
        // images should have valid objects
        if(!_.reduce(attrs.images, function(build, img) {
            return build && _.has(img, "url") && _.has(img, "size") &&
                    _.isString(img.url) && _.isString(img.size);
        }, true))
            return "all images must have url and size properties that are strings.";
    },
Example #3
0
Query.prototype.orderby = function(sort, dir) {
  if (this._soql) {
    throw Error("Cannot set sort for the query which has already built SOQL.");
  }
  if (_.isString(sort) && _.isString(dir)) {
    sort = [ [ sort, dir ] ];
  }
  this._config.sort = sort;
  return this;
};
Example #4
0
Connection.prototype.request = function(request, options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = null;
  }
  options = options || {};
  var self = this;

  // if request is simple string, regard it as url in GET method
  if (_.isString(request)) {
    request = { method: 'GET', url: request };
  }
  // if url is given in relative path, prepend base url or instance url before.
  request.url = this._normalizeUrl(request.url);

  var httpApi = new HttpApi(this, options);

  // log api usage and its quota
  httpApi.on('response', function(response) {
    if (response.headers && response.headers["sforce-limit-info"]) {
      var apiUsage = response.headers["sforce-limit-info"].match(/api\-usage=(\d+)\/(\d+)/);
      if (apiUsage) {
        self.limitInfo = {
          apiUsage: {
            used: parseInt(apiUsage[1], 10),
            limit: parseInt(apiUsage[2], 10)
          }
        };
      }
    }
  });
  return httpApi.request(request).thenCall(callback);
};
Example #5
0
  //PROTOTYPE - resets a Split to default values
  function resetSplit(options, cb) {
    console.log(' >> START splits.resetSplit');
    if (!_.isFunction(cb)) cb = function(){};
    if (!options) return cb(new Error('No Options Specified'));      

    var splitID = options.splitID;
    var successVal;

    if (_.isString(splitID)) splitID = new ObjectID(splitID);
    if (!splitID) return cb(new Error('Invalid Split ID'));

    var defaults = {
      amount: "",
      created: new Date(),
      date: new Date(),
      host_id: "",
      name: "",
      status: "setup",
      people: [{
        "_id": new ObjectID("507dc02da7f5fb75de24328f"),
        host: true,
        name: "Dean Gebert",
        pic: "/images/Dean_Gebert.jpg",
        status: "approved"
      }]
    };

    db.splits.update({_id: splitID}, {$set: defaults}, function(err){
      if (err) return cb(err);
      console.log(' >> RETURN splits.resetSplit');
      return cb({success: true});
    });
  }
Example #6
0
/**
 * @class Action
 * 
 * 动作规则
 * 
 * 执行流程: pattern -> handler -> register reply action
 * 
 * @constructor 动作规则
 * @param {Mixed}  cfg    Action的配置
 * @param {String} [prex] 动作名的前缀
 */
function Action(cfg, prex){
  if(_.isString(cfg)){
    //为字符串时,pattern为通过匹配,handler为直接返回该值
    this.name = prex + '_' + cfg;
    this.description = '发送任意字符,直接返回:' + cfg;
    this.handler = cfg;
  }else if(_.isFunction(cfg)){
    //为函数时,pattern为通过匹配,handler为该函数
    this.name =  prex + '_' + cfg.name;
    this.description = cfg.description || '发送任意字符,直接执行函数并返回';
    this.handler = cfg;
  }else if(_.isArray(cfg)){
    throw new Error('no support cfg type: Array')
  }else if(_.isObject(cfg)){
    /**
     * 匹配这种格式:
     * {
     *   name: 'say_hi', 
     *   description: 'pattern可以用正则表达式匹配,试着发送「hi」',
     *   pattern: /^Hi/i,
     *   handler: function(info) {
     *     //回复的另一种方式
     *     return '你也好哈';
     * }
     * @ignore
     */
    _.extend(this,cfg)
    this.name = cfg.name || prex || cfg.pattern
  }
  if(!this.name) this.name = 'it_is_anonymous_action';
  return this;
};
Example #7
0
var Query = module.exports = function(conn, config, locator) {
  Query.super_.apply(this);
  this.receivable = true;

  this._conn = conn;
  if (config) {
    if (_.isString(config)) { // if query config is string, it is given in SOQL.
      this._soql = config;
    } else {
      this._config = config;
      this.select(config.fields);
      if (config.includes) {
        this.include(config.includes);
      }
    }
  }
  if (locator && locator.indexOf("/") >= 0) { // if locator given in url for next records
    locator = locator.split("/").pop();
  }
  this._locator = locator;
  this._buffer = [];
  this._paused = true;
  this._closed = false;

  this._deferred = Q.defer();
};
Example #8
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 #9
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 #10
0
File: cache.js Project: ADn06/cdnjs
 var $fn = function() {
   var args = Array.prototype.slice.apply(arguments);
   var callback = args.pop();
   if (!_.isFunction(callback)) {
     args.push(callback);
   }
   var key = _.isString(options.key) ? options.key :
             _.isFunction(options.key) ? options.key.apply(scope, args) :
             createCacheKey(options.namespace, args);
   var entry = cache.get(key);
   if (!_.isFunction(callback)) { // if callback is not given in last arg, return cached result (immediate).
     var value = entry.get();
     if (!value) { throw new Error('Function call result is not cached yet.'); }
     if (value.error) { throw value.error; }
     return value.result;
   }
   entry.get(function(value) {
     callback(value.error, value.result);
   });
   if (!entry.fetching) { // only when no other client is calling function
     entry.fetching = true;
     args.push(function(err, result) {
       entry.set({ error: err, result: result });
     });
     fn.apply(scope || this, args);
   }
 };
Example #11
0
 removeAt: function(x, y) {
     'use strict';
     //remove while is not string (is an item or unit)
     while (!(_.isString(this.at(x, y)))) {
         this.remove(this.at(x, y), true);
     }
 },
Example #12
0
var Query = module.exports = function(conn, config, locator) {
  Query.super_.call(this, { objectMode: true });

  this._conn = conn;
  if (config) {
    if (_.isString(config)) { // if query config is string, it is given in SOQL.
      this._soql = config;
    } else {
      this._config = config;
      this.select(config.fields);
      if (config.includes) {
        this.include(config.includes);
      }
    }
  }
  if (locator && locator.indexOf("/") >= 0) { // if locator given in url for next records
    locator = locator.split("/").pop();
  }
  this._locator = locator;

  this._executed = false;
  this._finished = false;
  this._chaining = false;

  this._deferred = Q.defer();

  var self = this;
};
Example #13
0
Connection.prototype.recent = function(type, limit, callback) {
  if (!_.isString(type)) {
    callback = limit;
    limit = type;
    type = undefined;
  }
  if (!_.isNumber(limit)) {
    callback = limit;
    limit = undefined;
  }
  var url;
  if (type) {
    url = [ this._baseUrl(), "sobjects", type ].join('/');
    return this.request(url).then(function(res) {
      return limit ? res.recentItems.slice(0, limit) : res.recentItems;
    }).thenCall(callback);
  } else {
    url = this._baseUrl() + "/recent";
    if (limit) {
      url += "?limit=" + limit;
    }
    return this.request(url).thenCall(callback);
  }

};
Example #14
0
    _.each(args, function(arg) {
      if (_.isNumber(arg) || _.isString(arg)) {
        var criteria = {};
        criteria[self.table.pk] = args[0];
        return self.where(criteria);
      }

      var columns = arg.columns || arg;
      if (_.isArray(columns)) { self.sql = self.sql.replace("*", columns.join(",")); }
      if (_.isString(columns)) { self.sql = self.sql.replace("*", columns); }
      delete arg.columns;

      var where = arg.where || arg;
      if (!_.isArray(where) && _.isObject(where) && _.size(where) > 0) { self.where(where); }

    });
Example #15
0
    var handleResponse = function(response) {
      // Parse Gigya's JSON response
      var json;
      if(_.isString(response)) {
        try {
          json = JSON.parse(response);
        } catch(e) {
          return handleError(new Error('JSON parse error'));
        }
      } else {
        json = response;
      }

      // Look for Gigya error code
      if(json.errorCode != 0) {
        var e = new Error(json.errorDetails);
        e.code = json.errorCode;
        e.callId = json.callId;
        if(!_.isUndefined(json.validationErrors)) {
          e.validationErrors = json.validationErrors;
        }
        return handleError(e, json);
      }

      // No error, pass on response
      if(callback) callback(null, json);
      emitter.emit('response', null, json);
    };
Example #16
0
 function getOne(options, cb) {
   if (!_.isFunction(cb)) cb = function(){};
   if (!options) return cb(new Error('No Options Specified'));
   
   console.log(' - users.getOne');
   
   var defaultOptions = {
     internal: true,
     fields: {avatarpic: 0}
   };
   options = _.extend(defaultOptions, options);
   
   var query = {};
   var fields = options.fields;
   
   if (options.userID) {
     if (_.isString(options.userID)) options.userID = new ObjectID(options.userID);
     if (!isObjectID(options.userID)) return cb(new Error('Invalid User ID'));
     query._id = options.userID;
   }
   
   db.users.findOne(query, fields, function(err, user){
     if (err) return cb(err);
     if (!user) return cb(null, false);
     console.log(' - users.getOne - DONE');
     if (options.internal){
       return cb(null, user);
     } else {
       return cb({success: true, user: user});
     }
   });
 }
Example #17
0
 return function(req, res, next){
   if (!req.body || !req.body.newnickname || !_.isString(req.body.newnickname)) return next(new Error('Invalid Nickname'));
   var nickname = new RegExp('^' + escapeRegExp(req.body.newnickname) + '$', 'i');
   db.users.count({nickname: nickname}, function(err, count){
     if (err) return next(err);
     res.send(!count);
   });
 };
Example #18
0
function prepText(text) {
  if (_.isArray(text)) return text;
  var deduped = _.uniq(tokenizer.tokenize(text));
  if (!this.options.stopwords) return deduped;
  return _.reject(deduped, _.bind(isStopword, null,
      _.isString(this.options.stopwords) ? this.options.stopwords : natural_stopwords
      ));
}
Example #19
0
 _(stepArgs).each(function (argVal, argKey) {
   if (_.isString(argVal)) {
     formattedStepArgs[argKey] = replaceExampleInString(argVal, example);
   }
   if (_.isArray(argVal)) {
     formattedStepArgs[argKey] = replaceExampleInArray(argVal, example);
   }
 });
Example #20
0
Tooling.prototype.completions = function(type, callback) {
  if (!_.isString(type)) {
    callback = type;
    type = 'apex';
  }
  var url = this._baseUrl() + "/completions?type=" + encodeURIComponent(type);
  return this._request(url).thenCall(callback);
};
Example #21
0
 return function(req, res, next){
   if (!req.body || !req.body.newid || !_.isString(req.body.newid)) return next(new Error('Invalid ID'));
   var id = new RegExp('^' + escapeRegExp(req.body.newid) + '$', 'i');
   db.users.count({id: id}, function(err, count){
     if (err) return next(err);
     res.send(!count);
   });
 };
Example #22
0
 function(subObj, subKey) {
   if (_.isString(subKey) && subKey.substr(0, 1) == '_') {
     delete copy[subKey];
   }
   else if (_.isObject(subObj)) {
     copy[subKey] = clientEscape(subObj);
   }
 })
Example #23
0
 //checks whether a user with the specified nickname exists
 function nicknameExists(nickname, cb) {
   if (!_.isFunction(cb)) cb = function(){};
   if (!_.isString(nickname)) cb(new Error('Invalid Nickname'));
   db.users.count({nickname: new RegExp('^' + escapeRegExp(nickname) + '$', 'i')}, function(err, count){
     if (err) return cb(err);
     if (count > 1) return cb(new Error('Multiple users found with the specified nickname: ' + nickname));
     return cb(null, !!count);
   });
 }
Example #24
0
 //checks whether a user with the specified email address exists
 function emailExists(email, cb) {
   if (!_.isFunction(cb)) cb = function(){};
   if (!_.isString(email)) cb(new Error('Invalid Email Address'));
   db.users.count({id: new RegExp('^' + escapeRegExp(email) + '$', 'i')}, function(err, count){
     if (err) return cb(err);
     if (count > 1) return cb(new Error('Multiple users found with the specified email address: ' + email));
     return cb(null, !!count);
   });
 }
Example #25
0
                _.each(properties.validators, function(settings,validatorType)
                {
                    switch(validatorType)
                    {
                        case 'required':
                            if (_.isUndefined(value))
                                addError({ path: makePath(index), type:'required', error:'No value'});
                            break;
                        case 'minLength':
                            if (_.isString(value) && value.length < settings)
                                addError({ path: makePath(index), type:'minLength', error:'Not minimum length'});
                            break;
                        case 'maxLength':
                            if (_.isString(value) && value.length > settings)
                                addError({ path: makePath(index), type:'maxLength', error:'Exceeds maximum length'});
                            break;

                    }
                })
Example #26
0
 _ensureElement : function() {
   if (!this.el) {
     var attrs = this.attributes || {};
     if (this.id) attrs.id = this.id;
     if (this.className) attrs['class'] = this.className;
     this.el = this.make(this.tagName, attrs);
   } else if (_.isString(this.el)) {
     this.el = $(this.el).get(0);
   }
 }
Example #27
0
 self.db_.error(function(err, docs) {
     if (err) throw err;
     err = docs[0] && docs[0].err;
     if (err && _.isString(err)) {
         err = new Error(err);
         err.code = docs[0].code;
         err.ok = docs[0].ok;
     }
     callback(err, val);
 });
Example #28
0
  //PROTOTYPE - removes a person from a Split
  function removePerson(options, cb) {
    console.log(' >> START splits.removePerson');
    if (!_.isFunction(cb)) cb = function(){};
    if (!options) return cb(new Error('No Options Specified'));      

    var splitID = options.splitID;
    var userID = options.userID;
    var successVal;

    if (_.isString(splitID)) splitID = new ObjectID(splitID);
    if (_.isString(userID)) userID = new ObjectID(userID);
    if (!splitID) return cb(new Error('Invalid Split ID'));
    if (!userID) return cb(new Error('Invalid User ID'));

    db.splits.update({_id: splitID, 'people._id': userID}, {$pull: {'people': {'_id': userID}}}, function(err){
      if (err) return cb(err);
      console.log(' >> RETURN splits.removePerson');
      return cb({success: true});
    });
  }
Example #29
0
exports.update = function() {
  var args, next;
  if (_.isString(arguments[0])) {
    args = _.extend(arguments[1], {id: arguments[0]});
    next = arguments[2];
  } else {
    args = arguments[0];
    next = arguments[1];
  }
  this.save('update', args, next);
}
Example #30
0
 langNode.components = _.map(langNode.components, function(component) {
     if (_.isString(component)) {
         return {
             terminal: component
         };
     }
     else if (_.isObject(component)) {
         replaceStringsWithTerminalObjects(component);
         return component;
     }
 });