Example #1
0
 _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
   var initial = arguments.length > 2;
   if (obj == null) obj = [];
   if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
     if (context) iterator = _.bind(iterator, context);
     return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
   }
   var reversed = _.toArray(obj).reverse();
   if (context && !initial) iterator = _.bind(iterator, context);
   return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);
 };
Example #2
0
  setTimeout(function() {
    var statusTab = _.map(status.services, function(value, key) { return value; });
    status.summarize = {};
    status.summarize.lastupdate = status.lastupdate;
    status.summarize.up = _.reduce(_.select(status.services, function(data){ return data.status == 'up'; }), function(memo, num){ return memo + 1; }, 0);
    status.summarize.critical = _.reduce(_.select(status.services, function(data){ return data.status == 'critical'; }), function(memo, num){ return memo + 1; }, 0);
    status.summarize.down = _.reduce(_.select(status.services, function(data){ return data.status == 'down'; }), function(memo, num){ return memo + 1; }, 0);
    status.summarize.unknown = _.reduce(_.select(status.services, function(data){ return data.status == 'unknown'; }), function(memo, num){ return memo + 1; }, 0);

    controller.emit("refresh", status);
  }, settings.serviceDelay);
Example #3
0
    .on ("end", function (){

      // add EOF offset
      offsets[lastKey].push(eofKey);
      offsets[eofKey] = [endOffset, null];

      var size = _.size(buckets),
        sum = _.reduce(buckets, function(memo, num){ return memo + num; }, 0),
        sorted = _.sortBy(buckets, function(val){ return val }),
        median = sorted[Math.floor(size/2)],
        max =  sorted[sorted.length-1], // _.max(buckets),
        maxkey = _.reduce(buckets, function(memo, val, key){ return memo + (val == max ? key :  '') }, ''),
        avg = (sum/size).toFixed(2),
        info = util.format('buckets %d, max %d at %s, sum %d, avg %d, median %d', size, max, maxkey, sum, avg, median);

      console.log(basename, info);

      if (stats) {
        // distribution in groups of 10
        var grouped = _.groupBy(buckets, function(num){ return 1 + 10*(Math.floor((num-1)/10) ) });
        _(grouped).each(function(arr, key, list){
              list[key] = arr.length;
            });
        str = '';
        _.each(grouped, function(value, key){ str += key+"\t"+value+"\n" });
        fs.writeFileSync(countFile, '#'+info+'\n'
            + '#bucket_size (1-10, 11-20, etc.) \t #buckets\n'
            + str, 'utf8');
      }

      // offset data
      var data = {
          firstKey: firstKey,
          keyLength: KEY_LENGTH,
          version: WNdb.version,
          name: basename,
          stats: {
            buckets: size,
            words: sum,
            biggest: max,
            avg: avg,
            median: median
          },
          offsets: offsets
      };

      fs.writeFileSync(jsonFile, JSON.stringify(data), 'utf8');
      console.log('  wrote %s\n', jsonFile);
    })
  _.each(conditions, function(value, key) {
    var condition = exports.parseKey(key);

    if (condition.field === 'or') {
      if (!_.isArray(value)) { value = [value]; }

      var groupResult = _.reduce(value, function (acc, v) {
        // assemble predicates for each subgroup in this 'or' array
        var subResult = exports.generate({
          params: [],
          predicates: [],
          offset: result.params.length + acc.offset   // ensure the offset from predicates outside the subgroup is counted
        }, v, generator);

        // encapsulate and join the individual predicates with AND to create the complete subgroup predicate
        acc.predicates.push(util.format('(%s)', subResult.predicates.join(' AND ')));
        acc.params = acc.params.concat(subResult.params);
        acc.offset += subResult.params.length;

        return acc;
      }, {
        params: [],
        predicates: [],
        offset: result.offset
      });

      // join the compiled subgroup predicates with OR, encapsulate, and push the
      // complex predicate ("((x = $1 AND y = $2) OR (z = $3))") onto the result object
      result.params = result.params.concat(groupResult.params);
      result.predicates.push(util.format('(%s)', groupResult.predicates.join(' OR ')));
    } else {
      // no special behavior, just add this predicate and modify result in-place
      result = exports[generator](result, condition, value, conditions);
    }
  });
Example #5
0
exports.front_page = function (head, req) {
    start({code: 200, headers: {'Content-Type': 'text/html'}});
    var current_category = req.query.category;

    var row, categories = [];
    while (row = getRow()) {
        categories.push({
            key: row.key[0],
            name: utils.toSentenceCase(row.key[0]),
            count: row.value
        });
    }

    var total_packages = _.reduce(categories, function (count, c) {
        return count + c.count;
    }, 0);

    events.once('afterResponse', function (info, req, res) {
        ui.category_cache = categories;
        ui.addTopSubmitters(req, 10, '#top_submitters');
        ui.addLatestUpdates(req, 10, '#latest_updates');
        ui.addMostDependedOn(req, 10, '#most_depended_on');
        //ui.addCategories(req, '#categories');
    });

    return {
        title: 'Packages',
        content: templates.render('front_page.html', req, {
            categories: categories,
            total_packages: total_packages,
            current_category: current_category
        })
    };
};
Example #6
0
File: pages.js Project: Rob-pw/dbot
            this.db.read('poll', key, function(err, poll) {
                if(!err) {
                console.log(poll);
                    var totalVotes = _.reduce(poll.votes, function(memo, option) {
                        return memo += option;
                    }, 0);

                    var voterNicks = [];
                    async.each(_.keys(poll.votees), function(id, done) {
                        dbot.api.users.getUser(id, function(user) {
                            voterNicks.push(user.primaryNick);
                            done();
                        });
                    }, function() {
                        res.render('polls', { 
                            'name': dbot.config.name, 
                            'description': poll.description, 
                            'votees': voterNicks,
                            'options': poll.votes,
                            'totalVotes': totalVotes, 
                            locals: { 
                                'url_regex': RegExp.prototype.url_regex() 
                            }
                        });

                    });
                } else {
                    res.render('error', { 
                        'name': dbot.config.name, 
                        'message': 'No polls under that key.' 
                    });
                }
            });
Example #7
0
 redisClient.mget(uids, function(err, reply){
     var parsedProfiles = _.reduce(_.object(uids, reply), function(profiles, item, uid){
         if(item) profiles[uid] = JSON.parse(item);
         return profiles;
     }, {});
     callback(err, parsedProfiles);
 });
Example #8
0
db.addFridge = function(json, callback) {
    var hasId = json.id;
    var hasIds = true;
    _.each(json.words, function(word) {
        if (!word.id) hasIds = false;
        if (!word.fridgeid) {
            word.fridgeid = json.id;
        }
    });
    if (!hasId || !hasIds) {
        return callback("Make sure everything has an id!");
    }

    function reduceFn(m, p, k) {
        !_.isArray(p) && (m[k] = p);
        return m;
    }
    var fridgeData = _.reduce(json, reduceFn, {});
    client.multi()
        .sadd('fridgeids', json.id)
        .hmset('fridge:'+json.id, fridgeData)
        .exec(function(err, replies) {
            if (err) return callback(err);
            async.map(json.words, db.setWord, callback);
        });
};
Example #9
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 #10
0
Query.prototype.queryOptions = function () {
  if (_.isArray(this.order)) {
    var orderBody = this.orderBody;

    this.order = _.reduce(this.order, function (acc, val) {
      val.direction = val.direction || "asc";

      if (orderBody) {
        val.field = util.format("body->>'%s'", val.field);
      }

      if (val.type) {
        acc.push(util.format("(%s)::%s %s", val.field, val.type, val.direction));
      } else {
        acc.push(util.format("%s %s", val.field, val.direction));
      }

      return acc;
    }, []).join(",");
  }

  var sql = "";

  if (this.order) { sql = " order by " + this.order; }
  if (this.offset) { sql += " offset " + this.offset; }
  if (this.limit || this.single) { sql += " limit " + (this.limit || "1"); }

  return sql;
};
Example #11
0
 _.flatten = function(array, shallow) {
   return _.reduce(array, function(memo, value) {
     if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
     memo[memo.length] = value;
     return memo;
   }, []);
 };
exports.filterNonAscii = function (s) {
	return _.reduce(s, function(str, c, i) {
		if (s.charCodeAt(i) !== 0) {
			str += c;
		}
		return str;
	},'');
};
exports.purify = function(obj) {
	return clean(_.reduce(obj, function(pure, value, key) {
		if (obj.hasOwnProperty(key)) {
			pure[key] = value;
		}
		return pure;
	},{}));
};
Example #14
0
function BalMult(target, substitute, context) {
  
  if (context.length > 0)
    context = _.filter(context, function(num){ return num.length>0 });
 
  var prod = _.reduce(context, function(memo, num){ return memo * pcosine_distance(substitute, num) }, 1);

  return Math.pow(prod * Math.pow(pcosine_distance(substitute, target), context.length), 2 * context.length)
}
exports.filterCharCodes = function(s) {
	// replace newlines and carriage returns with a space. then filter the non-ascii
	return _.reduce(s.replace(/\n/g, ' ').replace(/\r/g, ' '), function(result, x, i) {
		if (s.charCodeAt(i) < 256) {
			result += s[i];
		}
		return result;
	}, '');
};
Example #16
0
function BalAdd(target, substitute, context) {
 
  if (context.length > 0)
    context = _.filter(context, function(num){ return num.length>0 });
  
  var sum = _.reduce(context, function(memo, num){ return memo + cosine_distance(substitute, num) }, 0);
   
  return (cosine_distance(substitute, target) * context.length + sum)/(2*context.length )
}
Example #17
0
 Postprocessor.prototype.process = function (text) {
     // wrap line numbers and content together
     var postprocessed = this.lineify(text.split(/\n/g), [], []);
     return _.reduce(postprocessed, function (fold, content) {
         return {
             line: fold.line + 1,
             content: fold.content + '<div class="line"><div class="line-number">' + fold.line + '</div>' + content + '</div>'
         };
     }, { line: 1, content: '' }).content;
 };
Example #18
0
function readData () {
    var fileNames = fs.readdirSync('./');
    return _.reduce(fileNames, function (memo, filename) {
        var stat = fs.statSync(filename);
        if (stat.isFile()) {
            memo[filename] = fs.readFileSync(filename, 'utf8');
        }
        return memo;
    }, {});
}
Example #19
0
EmbeddedList.prototype.validate = function (doc, value, raw) {
    var type = this.type;

    // don't validate empty fields, but check if required
    if (this.isEmpty(value, raw)) {
        if (this.required) {
            return [ new Error('Required field') ];
        }
        return [];
    }

    // check all values are objects
    var non_objects = _.filter(value, function (v) {

        /* Workaround for interpreter bug:
            Saving embedList() data throws an error when running in a
            CouchDB linked against js-1.8.0. We encounter a situation where
            typeof(v) === 'object', but the 'v instanceof Object' test
            incorrectly returns false. We suspect an interpreter bug.
            Please revisit this using a CouchDB linked against js-1.8.5.
            We don't currently have the infrastructure for a test case. */
        
        /* Before: return !(v instanceof Object) || _.isArray(v); */
        return (typeof(v) !== 'object' || _.isArray(v));
    });
    if (non_objects.length) {
        return _.map(non_objects, function (v) {
            return new Error(v + ' is not an object');
        });
    }

    // check for missing ids
    var missing = this.missingIDs(value);
    if (missing.length) {
        return missing;
    }

    // check for duplicate ids
    var duplicates = this.duplicateIDs(value);
    if (duplicates.length) {
        return duplicates;
    }

    // run type validation against each embedded document
    return _.reduce(value, function (errs, v, i) {
        var r = raw ? raw[i]: undefined;
        return errs.concat(
            _.map(type.validate(v, r), function (err) {
                err.field = [i].concat(err.field || []);
                return err;
            })
        );
    }, []);
};
Example #20
0
function output(results) {
  var str;
  if (program.count && cmd != 'lookup') {
    var label = program.brief ? '' : _.flatten(['#', _.values(POS), 'Parsed\n']).join(' ');
    str = (cmd == 'get' && (label + _.reduce(POS, function(memo, v){
      return memo + ((results[v] && results[v].length) || 0) +" ";
    },''))) + nWords;
  } else {
    str = sprint(results);
  }
  console.log(str);
}
Example #21
0
 _.uniq = _.unique = function(array, isSorted, iterator) {
   var initial = iterator ? _.map(array, iterator) : array;
   var result = [];
   _.reduce(initial, function(memo, el, i) {
     if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
       memo[memo.length] = el;
       result[result.length] = array[i];
     }
     return memo;
   }, []);
   return result;
 };
Example #22
0
exports.validate = function (fields, doc, values, raw, path, extra) {
    values = values || {};
    fields = fields || {};
    raw = raw || {};

    // Expecting sub-object, not a value
    if (typeof values !== 'object') {
        var e = new Error('Unexpected property - validation 1');
        e.field = path;
        e.has_field = false;
        return [e];
    }

    // Ensure we walk through all paths of both fields and values by combining
    // the keys of both. Otherwise, we might miss out checking for missing
    // required fields, or may not detect the presence of extra fields.

    var keys = _.uniq(_.keys(fields).concat(_.keys(values)));
    var fields_module = require('./fields');

    return _.reduce(keys, function (errs, k) {
        var f = fields[k];
        if (f === undefined) {
            // Extra value with no associated field detected
            if (!extra) {
                // ignore system properties
                if (!(path.length === 0 && k.charAt(0) === '_')) {
                    var e = new Error('Unexpected property - validation 2');
                    e.field = path.concat([k]);
                    e.has_field = false;
                    errs.push(e);
                }
            }
            return errs;
        }
        var val = values[k];
        var fn = exports.validate;
        if (f instanceof fields_module.Field ||
            f instanceof fields_module.Embedded ||
            f instanceof fields_module.EmbeddedList) {
            fn = exports.validateField;
        }
        if (f instanceof fields_module.AttachmentField) {
            val = utils.attachmentsBelowPath(doc, path.concat([k]));
        }
        return errs.concat(
            fn.call(this, f, doc, val, raw[k], path.concat([k]), extra)
        );
    }, []);
};
Example #23
0
function sprint(results) {
  if (program.json) {
    return util.format('%j',results);
  } else if (program.full) {
    return util.inspect(results,false,10, true);
  }
  var sep = program.brief ? ' ' : '\n';

  switch (cmd) {
  case 'lookup':
    return _.reduce(results, function(memo, v, k){
      return memo + (v.length && util.format('%s (%s)\n%s\n', k, rawCmd, print_def(v)) || '');
    }, '');
  default:
    return _.reduce(results, function(memo, v, k){
      var pre = program.brief ? '' : util.format('# %s %d:%s', k,  v.length, sep),
        res = v.length ? v.join(sep) : '';
      return memo + (v.length && util.format('%s%s%s\n', pre, res, sep) || '');
    }, '');
  }

  function print_def(defs) {
    var proc = {
      def: _.property(program.brief ? 'def' : 'gloss'),
      syn: function(res){
        return res.synonyms.join(', ');
      },
      exp: function(res) {
        return '"' + res.exp.join('", "') + '"';
      }
    }[ rawCmd ];

    return _.reduce(defs, function(memo, v, k){
      return memo + util.format('  %s: %s\n', v.pos, proc(v));
    },'');
  }
}
Example #24
0
EmbeddedList.prototype.authorize = function (nDoc, oDoc, nVal, oVal, user) {
    var type = this.type;
    var perms = this.permissions;

    nVal = nVal || [];
    oVal = oVal || [];

    // a unique list of embedded ids from both the old and new document
    var ids = _.uniq(_.pluck(nVal, '_id').concat(_.pluck(oVal, '_id')));

    return _.reduce(ids, function (errs, id, i) {

        var curr_errs = [];
        var nd = _.detect(nVal, function (v) {
            return v && v._id === id;
        });
        nd = nd || {_deleted: true};
        var od = _.detect(oVal, function (v) {
            return v && v._id === id;
        });
        var args = [nDoc, oDoc, nd, od, user];

        if (_.isFunction(perms)) {
            curr_errs = utils.getErrors(perms, args);
        }
        var fn;
        // on add
        if (nd && !od) {
            fn = perms.add;
        }
        // on remove
        else if (nd._deleted) {
            fn = perms.remove;
        }
        // on update
        else if (JSON.stringify(nd) !== JSON.stringify(od)) {
            fn = perms.update;
        }
        if (fn) {
            curr_errs = curr_errs.concat(utils.getErrors(fn, args));
        }
        curr_errs = _.map(curr_errs, function (e) {
            e.field = [i].concat(e.field || []);
            return e;
        });
        return errs.concat(curr_errs);

    }, []);
};
Example #25
0
exports.createDefaults = function (fields, req, doc, path) {
    path = path || [];
    var fields_module = require('./fields');
    return _.reduce(_.keys(fields), function (result, k) {
        var f = fields[k];
        if (f instanceof fields_module.AttachmentField) {
            if (f.hasOwnProperty('default_value')) {
                var val,
                    dir = path.concat([k]).join('/');
                if (_.isFunction(f.default_value)) {
                    val = f.default_value(req);
                }
                else {
                    val = f.default_value;
                }
                var d = doc || result;
                if (!d._attachments) {
                    d._attachments = {};
                }
                for (var ak in val) {
                    d._attachments[dir + '/' + ak] = val[ak];
                }
            }
        }
        else if (f instanceof fields_module.Field ||
                 f instanceof fields_module.Embedded ||
                 f instanceof fields_module.EmbeddedList) {

            if (f.hasOwnProperty('default_value')) {
                if (_.isFunction(f.default_value)) {
                    result[k] = f.default_value(req);
                }
                else {
                    result[k] = f.default_value;
                }
            }
        }
        else if (f instanceof Object) {
            result[k] = exports.createDefaults(
                f, req, doc || result, path.concat([k])
            );
        } else {
            throw new Error(
                'The field type `' + (typeof f) + '` is not supported.'
            );
        }
        return result;
    }, {});
};
Example #26
0
  function print_def(defs) {
    var proc = {
      def: _.property(program.brief ? 'def' : 'gloss'),
      syn: function(res){
        return res.synonyms.join(', ');
      },
      exp: function(res) {
        return '"' + res.exp.join('", "') + '"';
      }
    }[ rawCmd ];

    return _.reduce(defs, function(memo, v, k){
      return memo + util.format('  %s: %s\n', v.pos, proc(v));
    },'');
  }
Example #27
0
        dashboard_core.getMarkets(function(err, data) {
            var dash_url = window.location.protocol + '//' + window.location.host + '/' + $('.container[role="main"]').data('dashboardurl');
            data = _.reduce(data, function(memo, market) {
                if (memo[market.url]) {
                    if (memo[market.url].indexOf('http') === 0) {
                        memo[market.url] = market.name;
                    }
                } else memo[market.url] = market.name;
                return memo;
            },  {}   );
            data = _.map(data, function(market, url){
                url = url + '?dashboard=' + dash_url;
                return {name: market, url: url};
            });

            $('ul.gardens').html(handlebars.templates['garden_details.html'](data, {}));
        })
Example #28
0
 '~qcount': function(event) {
     var input = event.message.valMatch(/^~qcount ([\d\w\s-]*)/, 2);
     if(input) { // Give quote count for named category
         var key = input[1].trim().toLowerCase();
         if(_.has(quotes, key)) {
             event.reply(dbot.t('quote_count', {
                 'category': key, 
                 'count': quotes[key].length
             }));
         } else {
             event.reply(dbot.t('no_quotes', { 'category': key }));
         }
     } else { // Give total quote count
         var totalQuoteCount = _.reduce(quotes, function(memo, category) {
             return memo + category.length;
         }, 0);
         event.reply(dbot.t('total_quotes', { 'count': totalQuoteCount }));
     }
 },
Example #29
0
    validate: function(attrs, options) {
        // klass should be Track
        if(!_.isString(attrs.klass) || attrs.klass != "Track")
            return "klass property must be 'Track'."

        // 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 a string artist
        if(_.isUndefined(attrs.artist) || !_.isString(attrs.artist))
            return "must define artist property that is a string.";
        // should have an integer duration
        if(_.isUndefined(attrs.duration) || !_.isNumber(attrs.duration))
            return "must define duration property that is a number.";
        // should have an integer playcount
        if(_.isUndefined(attrs.playcount) || !_.isNumber(attrs.playcount))
            return "must define playcount property that is a number.";
        // should have an integer listeners
        if(_.isUndefined(attrs.listeners) || !_.isNumber(attrs.listeners))
            return "must define listeners property that is a number.";

        // 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 #30
0
module.exports.generateSchema = function ( name, inputs ) {
  if ( __.indexOf( __.keys( mongoose.models ), name ) > 0 ) {
    return mongoose.model( name );
  }

  var schemaConstructor = __.reduce( inputs, function ( inputsObject, input, index ) {
    var key = utils.toSnakeCase( input.label ) + index;
    if ( input.required ) {
      inputsObject[key] = { type: String, required: true };
    } else {
      inputsObject[key] = { type: String };
    }

    return inputsObject;
  }, {});

  var newSchema = new Schema( schemaConstructor );

  return mongoose.model( name, newSchema );
};