Example #1
0
 describePost : function ( user, method, path ) {
   var params = {},
   pathComponents = path.split('/');
   if ( __.isEmpty( __.intersection( pathComponents, ['data'] ) ) ) {
     if (  __.isEmpty( __.intersection( pathComponents, ['complaint','nonConformity','task'] ) ) ) {
       params = {
         'reference' : {
           'who'   : user.username,
           'what'  : 'creó un ' + translate( pathComponents[1] ),
           'when' : getOperationDate()
         }
       };
       foward( params );
     } else {
       params = {
         'reference' : {
           'who'   : user.username,
           'what'  : 'creó una ' + translate( pathComponents[1] ),
           'when' : getOperationDate()
         }
       };
       foward( params );
     }
   }
 },
Example #2
0
 emitter.on('end', function() {
     var ndEmpty = _.isEmpty(nodes);
     var wayEmpty = _.isEmpty(ways);
     var relEmpty = _.isEmpty(relations);
     if (ndEmpty && wayEmpty && relEmpty) {
         cb(true);
     } else {
         cb(false, 'not empty'); // todo send debug
     }
 });
Example #3
0
    _.each(pages, function (currPage) {
      var currPageDomain  = urlParser.parse(currPage.url).hostname,
          sameDomainPages = [],
          hasShorterPaths = false,
          currPagePath, currPageDepth;

      sameDomainPages = _.filter(pages, function (page) {
        return currPageDomain === urlParser.parse(page.url).hostname && page.url !== currPage.url;
      });

      if (_.isEmpty(sameDomainPages)) {
        rtnObj[currPage.url] = currPage;
      } else {
        currPagePath = fn.url.removeTrailingSlash(urlParser.parse(currPage.url).path);
        currPageDepth = currPagePath.split('/').length;

        hasShorterPaths = _.any(sameDomainPages, function (page) {
          var pagePath  = fn.url.removeTrailingSlash(urlParser.parse(page.url).path),
              pageDepth = pagePath.split('/').length;

          return pageDepth < currPageDepth;
        });

        if (!hasShorterPaths) {
          rtnObj[currPage.url] = currPage;
        }
      }
    });
    validate: function(attrs) {

      if (!this._schema) return;

      var env = JSV.createEnvironment();
      // Resulting model consists of attributes we already have set and
      // the attributes provided as argument to this function (merged).
      // When an attribute is `unset`, it is passed in `attrs` object,
      // the attribute has special value of `undefined`. To learn how the
      // resulting object will look like, we need to:
      // + merge the already-set attributes with the new ones, and
      // + remove the attributes that are to be unset.
      var obj = _.extend({}, this.attributes, attrs);
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          if ('undefined' === typeof obj[key]) {
            delete obj[key];
          }
        }
      }
      if (_.isEmpty(obj)) {
        return;
      }
      var r = env.validate(obj, this._schema);

      if (0 != r.errors.length) {
        return 'Model schema validation failed: ' + r.errors[0].message
          + '\n  uri: ' + r.errors[0].uri
          + '\n  schemaUri: ' + r.errors[0].schemaUri
          + '\n  attribute: ' + r.errors[0].attribute
          + '\n  details: ' + r.errors[0].details;
      }
    }
Example #5
0
		self.complete = function(){
		
			if (self.requestCount >= self.requestTotal){
				sResponse = self.Config.serverResponse;
				var $response = (self.hasError)?404:200;
				
				sResponse.writeHead($response,{
				    "Content-Type": "application/json",
				    "Expires": "Mon, 26 Jul 1997 05:00:00 GMT",
				    "Cache-Control":"no-cache, must-revalidate"
				});
				if (self.Config.isBatch){
					if ( !u.isEmpty(self.response) ){
						sResponse.write(JSON.stringify(self.response));
						
					}	
				} else{
					sResponse.write(JSON.stringify(self.response[0]));
				}
				
				sResponse.end();
				
				
			}
			else return false;
		}
Example #6
0
exports.find = function(){
  var args = ArgTypes.findArgs(arguments);
  if(_.isFunction(args.conditions)){
    // all we're given is the callback:
    args.next = args.conditions;
  }

  //set default options
  args.options.order || (args.options.order = util.format('"%s"', this.pk));
  args.options.limit || (args.options.limit = "1000");
  args.options.offset || (args.options.offset = "0");
  args.options.columns || (args.options.columns = "*");

  order = " order by " + args.options.order;
  limit = " limit " + args.options.limit;
  offset = " offset " + args.options.offset;

  var sql = util.format("select id, body from %s", this.fullname);
  if (_.isEmpty(args.conditions)) {
    // Find all
    sql += order + limit + offset;
    this.executeDocQuery(sql, [], args.options, args.next);
  } else {
    // Set up the WHERE statement:
    var where = this.getWhereForDoc(args.conditions);
    sql += where.where + order + limit + offset;
    if(where.pkQuery) {
      this.executeDocQuery(sql, where.params, {single:true}, args.next);
    } else {
      this.executeDocQuery(sql, where.params,args.options, args.next);
    }
  }
};
Example #7
0
var queryImages = function(req, res, next, collection, filePath) {
    // Display all images from db
    if (_underscore._.isEmpty(req.query)) {
        DBService.findDocument(null, collection, function(err, docs) {
            renderResponse(req, res, err, docs, null, readAndResponse, filePath);
        });
    }
    // Query images from DB after imdbid 
    else if (req.query.imdbid) {
        var imdbid = req.query.imdbid;
        if (imdbid.substring(0, 2) === "tt") {
            var imdbidNumberOnly = imdbid.substring(2, imdbid.length);
        }
        DBService.findDocument({ "imdbid": new RegExp(imdbidNumberOnly ? imdbidNumberOnly : imdbid) }, collection, function(err, docs) {
            if (err) {
                renderResponse(req, res, err, null, imdbid, readAndResponse, filePath);
            } else {
                renderResponse(req, res, err, docs, imdbid);
            }
        });
    }
    // If all query params are empty then display all images from db
    else {
        DBService.findDocument(null, collection, function(err, docs) {
            renderResponse(req, res, err, docs, null, readAndResponse, filePath);
        });
    }
}
Example #8
0
    _.each(links, function (currUrl) {
      var currUrlHostname   = urlParser.parse(currUrl).hostname,
          sameHostnamePages = [],
          hasShorterPaths   = false,
          currUrlPath, currUrlDepth;

      sameHostnamePages = _.filter(links, function (url) {
        return currUrlHostname === urlParser.parse(url).hostname && url !== currUrl;
      });

      if (_.isEmpty(sameHostnamePages)) {
        rtnArr.push(currUrl);
      } else {
        currUrlPath = fn.url.removeTrailingSlash(urlParser.parse(currUrl).path);
        currUrlDepth = currUrlPath.split('/').length;

        hasShorterPaths = _.any(sameHostnamePages, function (url) {
          var urlPath  = fn.url.removeTrailingSlash(urlParser.parse(url).path),
              urlDepth = urlPath.split('/').length;

          return urlDepth < currUrlDepth;
        });

        if (!hasShorterPaths) {
          rtnArr.push(currUrl);
        }
      }
    });
Example #9
0
exports.validate = function(def, form_data) {
    var missing_fields = [], orig_key, key, data;

    var _isDefined = function(obj) {
        return !_.isUndefined(obj) && !_.isNull(obj);
    };

    _.each(def.fields, function(field, k) {
        orig_key = k;
        key = k.split('.');
        data = form_data;

        while(key.length > 1) {
            data = data[key.shift()];
        }

        key = key[0];

        if (!!field.required) {
            if (
                !data
                || !_isDefined(data[key])
                || (_.isArray(data[key]) && !_isDefined(data[key][0]))
            ) {
                missing_fields.push(orig_key);
            }
        }
    });

    if (!_.isEmpty(missing_fields))
        return [{code: 'sys.missing_fields', fields: missing_fields}];

    if (def.validations) {

        var errors = [];

        for (var k in def.validations) {
            if (typeof def.validations[k] !== 'string')
                continue;
            var ret = eval('('+def.validations[k]+')()');
            // assume string/error message if not object
            if (ret && !_.isObject(ret)) {
                errors.push({
                    code: 'sys.form_invalid_custom',
                    form: def.meta.code,
                    message: ret
                });
            } else if (ret) {
                errors.push(ret);
            }
        };

        if (errors.length !== 0) {
            return errors;
        }
    }

    return [];
};
Example #10
0
		self.done = function(oResult, oReq){
			$oResponse = u.omit(oReq,'method', 'params');
			$oResponse.result = oResult;
			if ( !u.isEmpty(oResult) || !u.isUndefined(oResult)){
				self.response.push($oResponse);
			}
			self.requestCount += 1;
		}
Example #11
0
 self.getMessage( function( err, message ) {
   if ( err ) {
     self.emit('message error', { code : 500, msg : 'Failed to retrieve message.' });
   }
   else {
     if ( !_.isEmpty(message) ) self.emit('message', message[0] );
   }
   if ( self.subscriptionActive ) setTimeout( fetch, interval );
 });
Example #12
0
    function(callbacklocal){
        if (_.isUndefined(string) || _.isNaN(string) || _.isEmpty(string))
	{
			console.vlog("emb: "+string)
			callback(null, [])
	}
        else
        	callbacklocal(null, null);
    },
Example #13
0
        redis.hgetall(key, function(err, data){
            var instance = data;
            err = err || (_.isEmpty(data) && new Error('no build was found for the key ' + key));

            if (!err) {
                instance = new self(data);
            }
            return callback(err, instance);
        });
Example #14
0
 _.min = function(obj, iterator, context) {
   if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
   if (!iterator && _.isEmpty(obj)) return Infinity;
   var result = {computed : Infinity};
   each(obj, function(value, index, list) {
     var computed = iterator ? iterator.call(context, value, index, list) : value;
     computed < result.computed && (result = {value : value, computed : computed});
   });
   return result.value;
 };
Example #15
0
function foward ( params ) {
  if ( !__.isEmpty( params ) ) {
    var bacon = ( function() {
      var url = apiUrl.concat('log/new');
      var request = rest.post( url, { data: params  } );
      return Bacon.fromEventTarget(request, 'complete');
    }() );

    bacon.onValue( function ( data ) {
    });
  }
}
Example #16
0
//my personal approach, not sure whether it is 100% valid but passed some tests
function shortestPath(graph, nodeId) {
    'use strict';
    var shortestEdge,
        smallestGC,
        newlyExploredNode,
        gc;

    if (nodeId in graph.nodes) {//root node
        graph.nodes[nodeId].distance = 0;
        _.each(graph.nodes[nodeId].edges, function(edge) {
            this.frontierEdges[edge.id] = edge;
        }, graph);
    }

    while (!_.isEmpty(graph.frontierEdges)) {
        smallestGC = Infinity;
        shortestEdge = undefined;

        //find the shortest
        _.each(graph.frontierEdges, function(edge) {
            gc = (!_.isUndefined(edge.nodes[0].distance) ? edge.nodes[0].distance :
                    edge.nodes[1].distance) + edge.weight;

            if (gc < smallestGC) {
                smallestGC = gc;
                shortestEdge = edge;
            }
        });

        newlyExploredNode = !_.isUndefined(shortestEdge.nodes[0].distance) ? shortestEdge.nodes[1] :
            shortestEdge.nodes[0];

        newlyExploredNode.distance = smallestGC;

        //all edges which were frontier are gone now but new are introduced
        _.each(newlyExploredNode.edges, function(edge) {
            if (edge.id in graph.frontierEdges) {
                delete graph.frontierEdges[edge.id];
            } else {
                graph.frontierEdges[edge.id] = edge;
            }
        });
    }

    //var ids = [7, 37, 59, 82, 99, 115, 133, 165, 188, 197];
    var ids = [1,2,3,4,5,6,7,8,9,10];

    return _.map(ids, function(nodeId) {
        return graph.nodes[nodeId].distance;
    }).join(',');
}
Example #17
0
Queryable.prototype.find = function(){
  var args = ArgTypes.findArgs(arguments);

  //set default options
  //if our inheriting object defines a primary key use that as the default order
  args.options.order = args.options.order || (this.hasOwnProperty("pk") ? util.format('"%s"', this.pk) : "1");
  args.options.limit = args.options.limit || "1000";
  args.options.offset = args.options.offset || "0";
  args.options.columns = args.options.columns || "*";

  if(_.isFunction(args.conditions)){
    //this is our callback as the only argument, caught by Args.ANY
    args.next = args.conditions;
  }

  var returnSingle = false;
  var where, order, limit, cols="*", offset;

  if(args.options.columns){
    if(_.isArray(args.options.columns)){
      cols = args.options.columns.join(',');
    }else{
      cols = args.options.columns;
    }
  }
  order = " order by " + args.options.order;
  limit = " limit " + args.options.limit;
  offset = " offset " + args.options.offset;

  if(_.isNumber(args.conditions) || isUUID(args.conditions)) {
    //a primary key search
    var newArgs = {};
    newArgs[this.primaryKeyName()] = args.conditions;
    args.conditions = newArgs;
    returnSingle = true;
  }

  where = _.isEmpty(args.conditions) ? {where : " "} : Where.forTable(args.conditions);

  var sql = "select " + cols + " from " + this.delimitedFullName + where.where + order + limit + offset;

  if (args.options.stream) {
    this.db.stream(sql, where.params, null, args.next);
  } else {
    this.db.query(sql, where.params, {single : returnSingle}, args.next);
  }
};
      that.processPage(options, function (err, links) {
        if (err) {
          LOG.error(util.format('[STATUS] [Failure] [%s] [%s] [%s] Processing page failed %s', site, language, url, err));
          return finishPageProcessing(err);
        }

        if (!_.isEmpty(links) && lastUrl !== _.last(links)) {
          lastUrl = _.last(links);
        }
        else {
          pageRepeats = true;

          LOG.info(util.format('[STATUS] [OK] [%s] [%s] Gathering offers finished', site, language, pageNumber));
        }

        return finishPageProcessing();
      });
Example #19
0
 self.client.call( 'ReceiveMessage', reqOptions, function( err, _results ) {
   if ( err ) return fn( err );
   // return if empty
   if ( _.isEmpty(_results['ReceiveMessageResult']['Message']) ) {
     return fn( null, [] );
   }
   var results = [];
   // check types
   if ( _.isArray(_results['ReceiveMessageResult']['Message']) ) {
     results = _results['ReceiveMessageResult']['Message'];
   }
   else if ( _.isObject(_results['ReceiveMessageResult']['Message']) ) {
     results.push( _results['ReceiveMessageResult']['Message'] );
   }
   // return results
   return fn( null, results );
 });
Example #20
0
 neodb.getIndexedNodes("person", "id", identifyPerson(person), function(err, nodePersons) {
    if(err || _.isEmpty(nodePersons)) {
       var nodePersonGlobal = {};
       async.waterfall([
          function(callback) {
             neodb.createNode(objectifyPerson(person)).save(callback);
          },
          function(nodePerson, callback) {
             nodePersonGlobal = nodePerson;
             nodePerson.index("person", "id", identifyPerson(person), callback);
          }
       ], function(err, result) {
          hop(err, nodePersonGlobal);
       });
    } else {
       hop(null, _.first(nodePersons));
    }
 });
Example #21
0
 neodb.getIndexedNodes("movie", "id", identifyMovie(movie), function(err, nodeMovies) {
    if(err || _.isEmpty(nodeMovies)) {
       var nodeMovieGlobal = {};
       async.waterfall([
          function(callback) {
             neodb.createNode(objectifyMovie(movie)).save(callback);
          },
          function(nodeMovie, callback) {
             nodeMovieGlobal = nodeMovie;
             nodeMovie.index("movie", "id", identifyMovie(movie), callback);
          }
       ], function(err, result) {
          hop(err, nodeMovieGlobal);
       });
    } else {
       hop(null, _.first(nodeMovies));
    }
 });
Example #22
0
Queryable.prototype.find = function() {
  var args = ArgTypes.findArgs(arguments, this);

  if (typeof this.primaryKeyName === 'function' && Where.isPkSearch(args.conditions)) {
    var newArgs = {};
    newArgs[this.primaryKeyName()] = args.conditions;
    args.conditions = newArgs;
    args.query.single = true;
  }

  var where = _.isEmpty(args.conditions) ? {where: " "} : Where.forTable(args.conditions);
  var sql = args.query.format(where.where);

  if (args.query.stream) {
    this.db.stream(sql, where.params, args.query, args.next);
  } else {
    this.db.query(sql, where.params, args.query, args.next);
  }
};
Example #23
0
 neodb.getIndexedRelationships("person_movie", "id", identifyRelation(person, movie), function(err, relations) {
    if(err || _.isEmpty(relations)) {
       async.waterfall([
          function(callback) {
             personNode.createRelationshipTo(movieNode, 'beIn', {department: person.department}, callback);
          },
          function(relationship, callback) {
             relationship.save(callback); 
          },
          function(relationship, callback) {
             relationship.index("person_movie", "id", identifyRelation(person, movie), callback);
          }
       ], function(err, result) {
          hop(err, result);
       })
    } else {
       hop(null, _.first(relations));
    }
 });
Example #24
0
 async.map(os, (o, cb)=> {
     if (o.date === _date) {
         let orderTimes = [], ids = _.pluck(_.pluck(_.where(as, {_orderId: o._id}), 'arrTime'), '_id');
         _.each(o.orderTimes, ot=> {
             ot._doc.times = _.reject(ot.times, time=>time < _time);
             if (!_.isEmpty(ot.times) && !_.contains(ids, ot._id)) {
                 orderTimes.push(ot);
             }
         });
         if (!_.isEmpty(orderTimes)) {
             o._doc.orderTimes = orderTimes;
             cb(null, o);
         } else {
             cb(null, null);
         }
     } else {
         cb(null, o);
     }
 }, (err, ret)=> err ? next(err) : res.json(_.compact(ret)));
Example #25
0
Queryable.prototype.count = function() {
  var args;
  var where;

  if (_.isObject(arguments[0])) {
    args = ArgTypes.findArgs(arguments);
    where = _.isEmpty(args.conditions) ? {where : " "} : Where.forTable(args.conditions);
  } else {
    args = ArgTypes.whereArgs(arguments);
    where = {where: " where " + args.where};
  }

  var sql = "select COUNT(1) from " + this.delimitedFullName + where.where;

  this.db.query(sql, where.params || args.params, {single : true}, function(err, res) {
    if (err) args.next(err, null);
    else args.next(null, res.count);
  });
};
Example #26
0
Queue.prototype.sendMessage = function( message, fn ) {
  var self = this;
  
  if ( _.isEmpty(message) || 'function' == typeof message ) {
    return fn( new Error('"Message" required') );
  }

  var reqOptions = {
    MessageBody : JSON.stringify( message )
  };

  self.client.call( 'SendMessage', reqOptions, function( err, _results ) {
    if ( err ) return fn( err );
    var results = _results['SendMessageResult'];
    // return results
    return fn( null, results );
  });

};
Example #27
0
Queryable.prototype.find = function() {
  var args = ArgTypes.findArgs(arguments, this);

  if (typeof this.primaryKeyName === 'function' && Where.isPkSearch(args.conditions)) {
    var newArgs = {};
    newArgs[this.primaryKeyName()] = args.conditions;
    args.conditions = newArgs;
    args.options.single = true;
  }

  var where = _.isEmpty(args.conditions) ? {where: " "} : Where.forTable(args.conditions);

  var sql = "select " + args.options.selectList() + " from " + this.delimitedFullName + where.where + args.options.queryOptions();

  if (args.options.stream) {
    this.db.stream(sql, where.params, args.options, args.next);
  } else {
    this.db.query(sql, where.params, args.options, args.next);
  }
};
Example #28
0
exports.forTable = function () {
  var args = ArgTypes.forArgs(arguments);

  if (_.isEmpty(args.conditions)) {
    return {
      where: args.prefix + 'TRUE',
      params: []
    };
  }

  var result = exports.generate({
    params: [],
    predicates: [],
    offset: args.placeholderOffset
  }, args.conditions, args.generator);

  return {
    where: args.prefix + result.predicates.join(' \nAND '),
    params: result.params
  };
};
Example #29
0
 describeDelete : function ( user, method, path ) {
   if (  __.isEmpty( __.intersection( pathComponents, ['complaint','nonConformity','task'] ) ) ) {
     params = {
       'reference' : {
         'who'   : user.username,
         'what'  : 'eliminó un ' + translate( pathComponents[1] ),
         'when' : getOperationDate()
       }
     };
     foward( params );
   } else {
     params = {
       'reference' : {
         'who'   : user.username,
         'what'  : 'eliminó una ' + translate( pathComponents[1] ),
         'when' : getOperationDate()
       }
     };
     foward( params );
   }
 }
Example #30
0
Queryable.prototype.count = function() {
  var args;
  var where;

  if (_.isObject(arguments[0])) {
    args = ArgTypes.findArgs(arguments, this);
    where = _.isEmpty(args.conditions) ? {where : " "} : Where.forTable(args.conditions);
  } else {
    args = ArgTypes.whereArgs(arguments, this);
    where = {where: " where " + args.where};
  }

  args.query.columns = "COUNT(1)";
  args.query.order = null;
  var sql = args.query.format(where.where);

  this.db.query(sql, where.params || args.params, {single : true}, function(err, res) {
    if (err) args.next(err, null);
    else args.next(null, res.count);
  });
};