Example #1
0
        function regexScanner(langNode, j) {
            logger.functions("regexScanner");
            logger.functions(JSON.stringify(langNode));
            var alwaysEmittedNode, matchEmittedNode, inputSlice, modifiedComponent;
            var component = langNode.components[langNode.parseData.atComponent];
            if(j < input.length) {//TODO: Use incremental regexs here to rule out input that can't possibly match.
                alwaysEmittedNode = Object.create(langNode);
                alwaysEmittedNode.parseData = _.clone(langNode.parseData);//Can I use Object.create here? Iff parseData is static?
                alwaysEmittedNode.parseData.stringIdx++;
                statePools[j+1].emit('add', alwaysEmittedNode);
            }

            inputSlice = input.slice(j - langNode.parseData.stringIdx, j);
            if(component.compiledRegExp.test(inputSlice)) {
                matchEmittedNode = Object.create(langNode);
                matchEmittedNode.parseData = _.clone(langNode.parseData);//Can I use Object.create here?
                //shallow copy interpretations:
                matchEmittedNode.interpretations = matchEmittedNode.interpretations.map(function(x){ return x; });
                //shallow copy component array:
                matchEmittedNode.interpretations[0] = matchEmittedNode.interpretations[0].map(function(x){ return x; });
                modifiedComponent = _.clone(component);//TODO: modify chart rendering so I can use Object.create here?
                modifiedComponent.match = inputSlice;
                matchEmittedNode.interpretations[0][matchEmittedNode.parseData.atComponent] = modifiedComponent;
                matchEmittedNode.parseData.atComponent++;
                matchEmittedNode.parseData.stringIdx = 0;
                statePools[j].emit('add', matchEmittedNode);
            }
            statePools[j].emit('done');
        }
Example #2
0
      response.on('end', function() {
        var bufferOk = true;
        self.$_.raw = body;
        delete self.$_['document'];
        delete self.$_['json'];
        failCount++;
        if (response.statusCode >= 200 && response.statusCode < 300 && _.isJSON(self.$_.headers)) {
          failCount = 0;
          self.$_.json = JSON.parse(body);
        } else if ((undefined === doAuth) && response.statusCode == 401 && self.$_.auth) {
          // new auth
          if (undefined !== response.headers['www-authenticate']) {
            var authType = response.headers['www-authenticate'].split(' ')[0].toLowerCase();
            self.doReq(verb, urlStr, cb, authType, _.clone(response));
          }
        } else if (failCount < 2 && response.statusCode == 401 && self.$_.auth && doAuth) {
          // auth changed
          digestPersistent.HA1 = null;
          self.doReq(
              verb,
              urlStr,
              cb,
              response.headers['www-authenticate'].split(' ')[0].toLowerCase(),
              _.clone(response)
          );
        }

        if (self.$_.printResponse) {
          bufferOk = wsutil.responsePrinter(self.$_, response);
        }

        _.extend(result, {raw: self.$_.raw, headers: self.$_.headers, statusCode: self.$_.status, json: self.$_.json});
        result.finalize();
        if (cb) {
          cb(self.$_); // TODO
        }
        if (bufferOk) {
          self.web_repl.displayPrompt();
        } else {
          self.web_repl.displayPromptOnDrain = true;
        }

        // remove this client from pending requests
        delete self.$_.pendingRequests[response.client.seq];
        self.$_.pendingRequests._count--;

        // check to see if there are enqueued requests
        if (self.$_.enqueuedRequests.length > 0) {
          var request = self.$_.enqueuedRequests.shift();
          self.web_repl.outputAndPrompt(
            stylize(request.result.verb, 'blue') + ' ' + request.result.url
            + stylize(' #' + request.seq + ' (dequeued)', 'grey')
          );
          self.$_.pendingRequests[request.seq] = request.result;
          self.$_.pendingRequests._count++;
          request.end();

        }
      });
Example #3
0
  setState: function(state) {
    this.position         = _.clone(state.position);
    this.velocity         = _.clone(state.velocity);
    this.angularVelocity  = _.clone(state.angularVelocity);

    quaternion = _.clone(state.quaternion);

    this.quaternion.x     = quaternion.x;
    this.quaternion.y     = quaternion.y;
    this.quaternion.z     = quaternion.z;
    this.quaternion.w     = quaternion.w;
  },
Example #4
0
function packageWidgetCss(options, callback) {
  
  var packageInfo = _.extend(_.clone(options), {
    template: '<link rel="stylesheet" type="text/css" href="${href}" />',
    cacheName:  path.relative(options.appOptions.publicRoot, path.resolve(options.appOptions.publicRoot, options.request.page)) + '.css',
    hrefPrefix: "",
    contentType: "text/css",
    files: []
  });

  options.widgetClassRegistry.each(function(widgetClass) {
    var widgetCssFiles = [];
    if (widgetClass.classDef && !widgetClass.classDef.prototype.serverOnly) {
      packageInfo.files.push({
        path: widgetClass.clientCssHrefPath,
        prefix: options.appOptions.publicRoot
      });
      // Include any other css files in the widget's folder.
      widgetCssFiles = _.filter(fs.readdirSync(path.join(options.appOptions.publicRoot, widgetClass.widgetRoot)), function(filename) {
        return path.extname(filename) === ".css" && filename !== path.basename(widgetClass.clientCssHrefPath);
      });

      _.each(widgetCssFiles, function(widgetCssFile) {
        packageInfo.files.push({
          path: widgetClass.widgetRoot + widgetCssFile,
          prefix: options.appOptions.publicRoot
        });
      });
    }
  });
  exports.packageResources(packageInfo, callback);
}
Example #5
0
function packageWidgetJs(options, callback) {
  var packageInfo = _.extend(_.clone(options), {
    template: '<clientscript type="text/javascript" src="${href}"></clientscript>',
    cacheName: path.relative(options.appOptions.publicRoot, path.resolve(options.appOptions.publicRoot, options.request.page)) + '.js',
    hrefPrefix: "",
    contentType: "text/javascript",
    files: []
  });
  
  options.widgetClassRegistry.each(function(widgetClass) {
    var widgetJsFiles = [];
    if (widgetClass.classDef && !widgetClass.classDef.prototype.serverOnly) {
      packageInfo.files.push({
        path: widgetClass.clientHrefPath,
        prefix: options.appOptions.publicRoot
      });

      // Include any other js files in the widget's folder.
      widgetJsFiles = _.filter(fs.readdirSync(path.join(options.appOptions.publicRoot, widgetClass.widgetRoot)), function(filename) {
        return path.extname(filename) === ".js" 
                && filename !== path.basename(widgetClass.clientHrefPath) 
                && filename !== (widgetClass.widgetName + '.server.js');
      });

      _.each(widgetJsFiles, function(widgetJsFile) {
        packageInfo.files.push({
          path: widgetClass.widgetRoot + widgetJsFile,
          prefix: options.appOptions.publicRoot
        });
      });
    }
  });
  exports.packageResources(packageInfo, callback, true);
}
Example #6
0
 async.map(exports.PATHS, exports.loadFile, function (err, results) {
     var defaults = _.clone(exports.DEFAULTS);
     var settings = results.reduce(function (merged, r) {
         return exports.merge(merged, r);
     }, defaults);
     callback(null, settings);
 });
Example #7
0
var reset = function() {
  if(config.filters && config.filters.html && config.filters.html.vars) {
    templateVars = _.clone(config.filters.html.vars);
  } else {
    templateVars = {};
  }
};
Example #8
0
  defineAttribute: function(name, options) {
    var attribute = _.clone(options);
    if (options.type) {
      attribute.type = normalizeType[options.type] || options.type;
      this.addTypeValidator(name, attribute.type);
    }
    //sys.log(this.className + " defineAttribute " + name);

    // The properties hash will be used to define properties on each instantiated object.
    var property = {
      configurable: false,
      enumerable: true,
      get: function() {
        //sys.log("Get attribute " + name + " => " + this.attrs[name]);
        return this.attrs[name];
      }
    };
    if (! options.readonly) {
      property.set = function(v) {
        //sys.log("Set attribute " + name + " => " + v);
        return this.attrs[name] = v;
      };
    }
    this.defineProperty(name, property);

    // Remember the default value (if assigned)
    if (options['default']) {
      this.defaults[name] = options['default'];
    }

    // Remember this attribute.
    this.attributes[name] = attribute;
    //sys.log(this.className + " attributes." + name + " = " + sys.inspect(attribute));
  },
Example #9
0
    return function(cb) {
      var id = record.Id;
      if (!id) {
        cb({ message : 'Record id is not found in record.' });
        return;
      }
      var sobjectType = type || (record.attributes && record.attributes.type) || record.type;
      if (!sobjectType) {
        cb({ message : 'No SObject Type defined in record' });
        return;
      }
      record = _.clone(record);
      delete record.Id;
      delete record.type;
      delete record.attributes;

      var url = [ self.urls.rest.base, "sobjects", sobjectType, id ].join('/');
      self._request({
        method : 'PATCH',
        url : url,
        body : JSON.stringify(record),
        headers : {
          "Content-Type" : "application/json"
        }
      }, cb, {
        noContentResponse: { id : id, success : true, errors : [] }
      });
    };
Example #10
0
File: rand.js Project: moos/wordpos
/**
 * rand() - for all Index files
 * @returns Promise
 */
function randAll(opts, callback) {

  if (typeof opts === 'function') {
    callback = opts;
    opts = {};
  } else {
    opts = _.clone(opts || {});
  }

  var
    profile = this.options.profile,
    start = profile && new Date(),
    results = [],
    startsWith = opts && opts.startsWith || '',
    count = opts && opts.count || 1,
    args = [null, startsWith],
    parts = 'Noun Verb Adjective Adverb'.split(' '),
    self = this;



  return new Promise(function(resolve, reject) {
    // select at random a POS to look at
    var doParts = _.sample(parts, parts.length);
    tryPart();

    function tryPart() {
      var part = doParts.pop(),
        rand = 'rand' + part,
        factor = POS_factor[part],
        weight = factor / POS_factor.Total;

      // pick count according to relative weight
      opts.count = Math.ceil(count * weight * 1.1); // guard against dupes
      self[rand](opts, partCallback);
    }

    function partCallback(result) {
      if (result) {
        results = _.uniq(results.concat(result));  // make sure it's unique!
      }

      if (results.length < count && doParts.length) {
        return tryPart();
      }

      // final random and trim excess
      results = _.sample(results, count);
      done();
    }

    function done() {
      profile && (args.push(new Date() - start));
      args[0] = results;
      callback && callback.apply(null, args);
      resolve(results);
    }

  }); // Promise
}
Example #11
0
Info.pack = function(info, mapping){
  var data = _.clone(info);
  var reply = data.reply;

  //log('packing reply: ', reply);

  // 具备图文消息的特征
  if (_.isObject(reply) && !_.isArray(reply) && !reply.type) {
    reply = data.reply = [reply];
  }
  if (_.isArray(reply)) {
    if (_.isFunction(mapping)) {
      reply = reply.map(function(item, i) {
        return mapping.call(reply, item, i, info);
      });
    } else if (mapping) {
      reply.forEach(function(item, index){
        item['title'] = item[ mapping['title'] || 'title'];
        item['description'] = item[ mapping['description'] || 'description'];
        item['pic'] = item[ mapping['picUrl'] || 'picUrl'] || item[ mapping['pic'] || 'pic'];
        item['url'] = item[ mapping['url'] || 'url'];
      });
    }
  }
  data.reply = reply;

  var xml = _.template(Info.TEMPLATE_REPLY)(data);

  return xml;
};
Example #12
0
 createRecord:function (data, callback) {
     // hash the password
     var user = _.clone(data)
     user.salt = _User.makeSalt()
     user.hashed_password = _User.encryptPassword(user.password, user.salt)
     _User.validateUniqueUsername(user.username, function (err, valid) {
         if (err || !valid) {
             if (err) {
                 console.log(err)
             }
             callback(err?err:'An account already exists for the username provided', user)
         }
         else {
             _User.validateUniqueEmail(user.email, function (err, valid) {
                 if (err || !valid) {
                     if (err) {
                         console.log(err)
                     }
                     callback(err?err:'An account already exists for the email address provided', user)
                 }
                 else {
                     dbutils.dataCreate(_User.meta(), user, callback)
                 }
             })
         }
     })
 },
Example #13
0
 cb && publisher.once("itemAdded:" + key, function(item) {
   var _item = item;
   if (readOnlyItems[key]) {
     _item = _.clone(item);
   }
   cb(null, _item);
 });
Example #14
0
kern.registerAssets = function() {
  K = K || this;
  
  
  K.app.get('/kern.templates.js', function(req, res, next) {
    
    if (_.isString(req.query.name)) return res.send(K.getTemplate(req.query.name));
    return res.send(K.assets.templates);
  });
  
  for (var t in _.clone(K.assets)) {
    if (t == 'templates') continue;
    var type = K.assets[t];
    
    for (var a in type) {
      (function(info){
        var asset = _.extend({
          type: t,
          path: typeof info.path == 'string' ? info.path : a
        }, info);
        
        if (!_.isFunction(asset.callback) && !_.isString(asset.filepath)) return;
        var cb = typeof asset.callback == 'function' ? asset.callback : kern.sendAsset;
        
        
        K.app.get(asset.path, function(req, res, next) {
          
          cb.call(K, asset, req, res, next);
        });
      })(type[a]);
    }
  }
};
Example #15
0
function addFileToSearch(file){
  var path = [];

  // File / class
  searchToc.push({
    name: file.name,
    type: file.kind,
    ref: file.url,
    path: _.clone(path)
  });

  path.push(file.name)

  // Methods
  file.sections.forEach(function (section) {
    section.methods.forEach(function (method) {
      var ref = method.implementations[0].doxygen_ref;
      searchToc.push({
        name: method.implementations[0].name,
        type: method.implementations[0].info.kind,
        ref: file.url + "#" + ref,
        path: _.clone(path)
      })
    });
  });

  // Inner classes recursive add
  file.classes.forEach(function (innerclass) {
    innerclass.url = file.url;
    addFileToSearch(innerclass);
  });
}
Example #16
0
    _.map(records, function(record) {
      var id = record.Id;
      if (!id) {
        throw new Error('Record id is not found in record.');
      }
      var sobjectType = type || (record.attributes && record.attributes.type) || record.type;
      if (!sobjectType) {
        throw new Error('No SObject Type defined in record');
      }
      record = _.clone(record);
      delete record.Id;
      delete record.type;
      delete record.attributes;

      var url = [ self._baseUrl(), "sobjects", sobjectType, id ].join('/');
      return self.request({
        method : 'PATCH',
        url : url,
        body : JSON.stringify(record),
        headers : _.defaults(options.headers || {}, {
          "Content-Type" : "application/json"
        })
      }, {
        noContentResponse: { id : id, success : true, errors : [] }
      });
    })
Example #17
0
 addConnectedParticipant: function(user) {
     var participants = _.clone(this.get("connectedParticipants"));
     if (!_.findWhere(participants, { id: user.id }) && participants.length < 10) {
         participants.push(user);
         return this.setConnectedParticipants(participants);
     }
     return false;
 },
Example #18
0
	toJSON: function() {
		var attrs = _.clone(this.attributes);
		delete attrs["sock-key"];
		delete attrs["sock"];
		delete attrs["curEvent"];
		delete attrs["isBlurred"];
		return attrs;
	},
Example #19
0
 calculateAuth: function (u) {
   var currentHost = u.protocol + (u.slashes ? '//' : '') + u.hostname + ":" + u.port;
   var changed = false;
   if (
     undefined !== this.$_.auth
     && undefined !== this.$_.auth.host
     && this.$_.auth.host !== currentHost
   ) {
     delete(this.$_.auth);
     changed = true;
   }
   if (u.auth) {
     var auth = u.auth.split(':');
     if (undefined === this.$_.auth) {
       this.$_.auth = {
         user: auth[0],
         host: currentHost,
       };
       if (undefined !== auth[1]) {
         this.$_.auth.pass = auth[1];
       }
       changed = true;
     } else {
       if (undefined === this.$_.auth.user || this.$_.auth.user !== auth[0]) {
         changed = true;
         this.$_.auth.user = auth[0];
       }
       if (undefined !== auth[1]) {
         if (this.$_.auth.pass !== auth[1]) {
           changed = true;
           this.$_.auth.pass = auth[1];
         }
       }
     }
     if (changed) {
       digestPersistent = _.clone(digestPersistentCopy); // reset digest
       this.$_.auth.rerequested = false;
       console.log(stylize('Changed $_.auth to ' + this.$_.auth.user + ':' + this.$_.auth.pass, 'blue'));
     }
   } else {
     if (changed) {
       digestPersistent = _.clone(digestPersistentCopy); // reset digest
       console.log(stylize('Unset $_.auth', 'blue'));
     }
   }
 },
Example #20
0
CouchDB.prototype.instanceURL = function (dburl) {
    dburl = dburl || _.clone(this.instance);
    var parsed = (typeof dburl === "object") ? dburl: url.parse(dburl);
    delete parsed.pathname;
    delete parsed.query;
    delete parsed.search;
    return url.format(parsed);
};
Example #21
0
	dataset.forEach(function(datum) {
		var datumArff = _.clone(datum.input, {});
		for (var i=0; i<datum.output.length; ++i)
			datumArff[datum.output[i]]=1;
		//console.dir(datumArff);
		var array = featureLookupTable.hashToArray(datumArff);
		arff += array + "\n";
	});
RecordReference.prototype.update = function(record, options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = {};
  }
  record = _.clone(record);
  record.Id = this.id;
  return this._conn.update(this.type, record, options, callback);
};
Example #23
0
			_.each(dataset, function(value, key, list){
				if (value.output.length - 1 >= n)
					{
						value1 = _.clone(value)
						value1['output'] = value.output[n]
						data.push(value1)
					}

			 },this)
Example #24
0
 section.methods.forEach(function (method) {
   var ref = method.implementations[0].doxygen_ref;
   searchToc.push({
     name: method.implementations[0].name,
     type: method.implementations[0].info.kind,
     ref: file.url + "#" + ref,
     path: _.clone(path)
   })
 });
Example #25
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 #26
0
    parse: function(resp, options) {
        var orig = Backbone.Model.parse.apply(this, [resp, options]);
        var result = _.clone(orig);
        // build collections
        result.tracks = this.tracks;
        result.tracks.add(orig.tracks);
        result.tracks.fetch();

        return result;
    },
Example #27
0
Batch.prototype.send = function(record) {
  record = _.clone(record);
  if (this.job.operation === "insert") {
    delete record.Id;
  } else if (this.job.operation === "delete") {
    record = { Id: record.Id };
  }
  delete record.type;
  delete record.attributes;
  return this._csvStream.send(record);
};
Example #28
0
 'search': function(term, callback) {
     var qs = _.clone(this.params);
     request.get(this.ApiRoot + '/videos', {
         'qs': _.extend(qs, { 
             'q': term,
             'max-results': 1
         }),
         'json': true
     }, function(error, response, body) {
         callback(body); 
     }.bind(this));
 }
Example #29
0
  _.each(this, function(element) {
    // Call toObject() method if defined (this allows us to return primitive objects instead of SchemaObjects).
    if(_.isObject(element) && _.isFunction(element.toObject)) {
      element = element.toObject();

    // If is non-SchemaType object, shallow clone so that properties modification don't have an affect on the original object.
    } else if(_.isObject(element)) {
      element = _.clone(element);
    }

    array.push(element);
  });
Example #30
0
exports.addSubject = function(subjectData){
	if(typeof subjectData.id !== 'number' || isNaN(subjectData.id)){
		return false;
	}
	if(subjects.get(subjectData.id)){
		return false;
	}

	subjects.add(subjectData);
	vent.trigger('subject:added', _.clone(subjectData));
	return true;
};