Example #1
0
/*
A ResultSet with methods tailored to the values returned by the CandidateDetails Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/

var CandidateDetailsResultSet = function(resultStream) {
    CandidateDetailsResultSet.super_.call(this, resultStream);    
        /*
        Retrieve the value for the "Response" output from this Choreo execution. (The response from the NY Times API corresponds to the setting (json, or xml) entered in the ResponseFormat variable.  Default is set to json.)
        */
        this.get_Response = function() {
            return this.getResult("Response");
        }
}

util.inherits(CandidateDetails, choreography.Choreography);
util.inherits(CandidateDetailsInputSet, choreography.InputSet);
util.inherits(CandidateDetailsResultSet, choreography.ResultSet);
exports.CandidateDetails = CandidateDetails;


/*
    CandidateLeadersByCategory
    Retrieve a list of the 20 top candidates in terms of contributions received.
*/


var CandidateLeadersByCategory = function(session) {
    /*
        Create a new instance of the CandidateLeadersByCategory Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
Example #2
0
  , inherits = require('util').inherits
  , EventEmitter = require('events').EventEmitter

var DummyDataProvider = function DummyDataProvider(directoryPath) {
  EventEmitter.call(this);
  // Save the path
  this.directoryPath = directoryPath;

  // Read in the content of all json files for random dispersion
  this.dataFiles = fs.readdirSync(directoryPath)
    .filter(function(file) { return file.match(/.json/) != null; })
    .map(function(file) { return directoryPath + "/" + file; })
    .map(function(file) { console.log("reading in file :: " + file); return JSON.parse(fs.readFileSync(file, 'utf8')); });
}

inherits(DummyDataProvider, EventEmitter);

DummyDataProvider.prototype.start = function start(callback) {
  var self = this;
  // Start interval send data
  setInterval(function() {
    // var randomIndex = Math.round((self.dataFiles.length + 1) * Math.random()) % self.dataFiles.length;
    // var object = self.dataFiles[randomIndex];

    var object = null;
    // Locate the iostat doc
    for(var i = 0; i < self.dataFiles.length; i++) {
      if(self.dataFiles[i].info.agent == 'iostat' && self.dataFiles[i].info.platform == 'linux') {
        object = self.dataFiles[i];
        break;
      }
Example #3
0
  ;

module.exports = Route;

/**
 * Represents a compiled list of functions that will be executed sequentially
 *
 * @return Route
 */

function Route () {
  if (!(this instanceof Route)) return new Route();
  events.EventEmitter.call(this);
}

util.inherits(Route, events.EventEmitter);

/**
 * executes the list of functions, sequentially given the message or an array of args to be passed in
 *
 * @param {Message/Array} message * Could be a Message or an Array with the first item as the message
 * @param {function} done
 */

Route.prototype.process = function (message, done) {/* done() is for testing */
  var self = this, params = [];

  //prepare our input
  if (typeof message === 'object' && 
      message instanceof Array && 
      typeof message[0] === 'object' &&
Example #4
0
var Report = Bozuko.require('core/report'),
    inherits = require('util').inherits,
    inspect = require('util').inspect,
    crypto = require('crypto'),
    async = require('async'),
    merge = Bozuko.require('util/functions').merge,
    DateUtil = Bozuko.require('util/date')
    ;
    
var CountsReport = module.exports = function(options){
    Report.apply(this, arguments);
};
inherits( CountsReport, Report );

/**
 * Options:
 *
 *  end             Date
 *  interval        'Minute', 'Hour', 'Day', 'Week', 'Month', 'Year'
 *  length          Number
 *  unit            'Second', 'Minute', 'Hour', 'Day', 'Week', 'Month', 'Year'
 * 
 */
CountsReport.prototype.run = function run(callback){
    
    var opts = this.options,
        interval = opts.interval,
        unit = opts.unit,
        unitInterval = opts.unitInterval || 1,
        timeField = opts.timeField || 'timestamp',
        query = opts.query || {},
'use strict';
var path = require('path');
var util = require('util');
var ScriptBase = require('../script-base.js');
var angularUtils = require('../util.js');
 

var Generator = module.exports = function Generator() {
  ScriptBase.apply(this, arguments);
  this.hookFor('angular-ui-router:controller');
  this.hookFor('angular-ui-router:view');
};

util.inherits(Generator, ScriptBase);

Generator.prototype.rewriteAppJs = function () {
  var stateName = this.name.split('/').join('.');
  if (this.env.options.coffee) {
    angularUtils.rewriteFile({
      file: path.join(this.env.options.appPath, 'scripts/app.coffee'),
      needle: '.otherwise',
      splicable: [
        '.state \''+stateName + '\',',
        '  templateUrl: \'views/' + this.name + '.html\',',
        '  controller: \'' + this._.classify(this.name) + 'Ctrl\''
      ]
    });
  }
  else {
    angularUtils.rewriteFile({
      file: path.join(this.env.options.appPath, 'scripts/app.js'),
Example #6
0
    OBJECT_IDENTIFIER: 'UNIVERSAL-primative-6',
    SEQUENCE: 'UNIVERSAL-constructed-10',
    BMPString: 'UNIVERSAL-primative-1e',
    CONTEXT_CONSTRUCTED_0: 'context-constructed-0',
    CONTEXT_PRIMATIVE_0: 'context-primative-0',
    
    dumpBuffer: dumpBuffer
};

function Decoder(options) {
    EventEmitter.call(this);
    options = options || {};
    this.formatter = options.formatter || Der.defaultFormatter;
}

util.inherits(Decoder, EventEmitter);

Decoder.prototype.parse = function(buffer) {
    var cumulative = [];
    var cursor = new Cursor(buffer);
    while (cursor) {
        var next = cursor.next();
        
        this.formatter.format(next.element);        
        this.emit('element', next.element);
        cumulative.push(next.element);
        
        cursor = next.cursor;
    }
    this.emit('end', cumulative);
    return cumulative;
Example #7
0
define(function (require, exports, module) {
/*
 * grunt
 * http://gruntjs.com/
 *
 * Copyright (c) 2014 "Cowboy" Ben Alman
 * Licensed under the MIT license.
 * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
 */

'use strict';

// Nodejs libs.
var util = require('util');

// External libs.
var hooker = require('hooker');
// Requiring this here modifies the String prototype!
var colors = require('colors');
// The upcoming lodash 2.5+ should remove the need for underscore.string.
var _ = require('lodash');
_.str = require('underscore.string');
_.mixin(_.str.exports());
// TODO: ADD CHALK

function Log(options) {
  // This property always refers to the "base" logger.
  this.always = this;
  // Extend options.
  this.options = _.extend({}, {
    // Show colors in output?
    color: true,
    // Enable verbose-mode logging?
    verbose: false,
    // Enable debug logging statement?
    debug: false,
    // Where should messages be output?
    outStream: process.stdout,
    // NOTE: the color, verbose, debug options will be ignored if the
    // "grunt" option is specified! See the Log.prototype.option and
    // the Log.prototype.error methods for more info.
    grunt: null,
    // Where should output wrap? If null, use legacy Grunt defaults.
    maxCols: null,
    // Should logger start muted?
    muted: false,
  }, options);
  // True once anything has actually been logged.
  this.hasLogged = false;

  // Related verbose / notverbose loggers.
  this.verbose = new VerboseLog(this, true);
  this.notverbose = new VerboseLog(this, false);
  this.verbose.or = this.notverbose;
  this.notverbose.or = this.verbose;

  // Apparently, people have using grunt.log in interesting ways. Just bind
  // all methods so that "this" is irrelevant.
  if (this.options.grunt) {
    _.bindAll(this);
    _.bindAll(this.verbose);
    _.bindAll(this.notverbose);
  }
}
exports.Log = Log;

// Am I doing it wrong? :P
function VerboseLog(parentLog, verbose) {
  // Keep track of the original, base "Log" instance.
  this.always = parentLog;
  // This logger is either verbose (true) or notverbose (false).
  this._isVerbose = verbose;
}
util.inherits(VerboseLog, Log);

VerboseLog.prototype._write = function() {
  // Abort if not in correct verbose mode.
  if (Boolean(this.option('verbose')) !== this._isVerbose) { return; }
  // Otherwise... log!
  return VerboseLog.super_.prototype._write.apply(this, arguments);
};

// Create read/write accessors that prefer the parent log's properties (in
// the case of verbose/notverbose) to the current log's properties.
function makeSmartAccessor(name, isOption) {
  Object.defineProperty(Log.prototype, name, {
    enumerable: true,
    configurable: true,
    get: function() {
      return isOption ? this.always._options[name] : this.always['_' + name];
    },
    set: function(value) {
      if (isOption) {
        this.always._options[name] = value;
      } else {
        this.always['_' + name] = value;
      }
    },
  });
}
makeSmartAccessor('options');
makeSmartAccessor('hasLogged');
makeSmartAccessor('muted', true);

// Disable colors if --no-colors was passed.
Log.prototype.initColors = function() {
  if (this.option('no-color')) {
    // String color getters should just return the string.
    colors.mode = 'none';
    // Strip colors from strings passed to console.log.
    hooker.hook(console, 'log', function() {
      var args = _.toArray(arguments);
      return hooker.filter(this, args.map(function(arg) {
        return typeof arg === 'string' ? colors.stripColors(arg) : arg;
      }));
    });
  }
};

// Check for color, verbose, debug options through Grunt if specified,
// otherwise defer to options object properties.
Log.prototype.option = function(name) {
  if (this.options.grunt && this.options.grunt.option) {
    return this.options.grunt.option(name);
  }
  var no = name.match(/^no-(.+)$/);
  return no ? !this.options[no[1]] : this.options[name];
};

// Parse certain markup in strings to be logged.
Log.prototype._markup = function(str) {
  str = str || '';
  // Make _foo_ underline.
  str = str.replace(/(\s|^)_(\S|\S[\s\S]+?\S)_(?=[\s,.!?]|$)/g, '$1' + '$2'.underline);
  // Make *foo* bold.
  str = str.replace(/(\s|^)\*(\S|\S[\s\S]+?\S)\*(?=[\s,.!?]|$)/g, '$1' + '$2'.bold);
  return str;
};

// Similar to util.format in the standard library, however it'll always
// convert the first argument to a string and treat it as the format string.
Log.prototype._format = function(args) {
  args = _.toArray(args);
  if (args.length > 0) {
    args[0] = String(args[0]);
  }
  return util.format.apply(util, args);
};

Log.prototype._write = function(msg) {
  // Abort if muted.
  if (this.muted) { return; }
  // Actually write output.
  this.hasLogged = true;
  msg = msg || '';
  // Users should probably use the colors-provided methods, but if they
  // don't, this should strip extraneous color codes.
  if (this.option('no-color')) { msg = colors.stripColors(msg); }
  // Actually write to stdout.
  this.options.outStream.write(this._markup(msg));
};

Log.prototype._writeln = function(msg) {
  // Write blank line if no msg is passed in.
  this._write((msg || '') + '\n');
};

// Write output.
Log.prototype.write = function() {
  this._write(this._format(arguments));
  return this;
};

// Write a line of output.
Log.prototype.writeln = function() {
  this._writeln(this._format(arguments));
  return this;
};

Log.prototype.warn = function() {
  var msg = this._format(arguments);
  if (arguments.length > 0) {
    this._writeln('>> '.red + _.trim(msg).replace(/\n/g, '\n>> '.red));
  } else {
    this._writeln('ERROR'.red);
  }
  return this;
};
Log.prototype.error = function() {
  if (this.options.grunt && this.options.grunt.fail) {
    this.options.grunt.fail.errorcount++;
  }
  this.warn.apply(this, arguments);
  return this;
};
Log.prototype.ok = function() {
  var msg = this._format(arguments);
  if (arguments.length > 0) {
    this._writeln('>> '.green + _.trim(msg).replace(/\n/g, '\n>> '.green));
  } else {
    this._writeln('OK'.green);
  }
  return this;
};
Log.prototype.errorlns = function() {
  var msg = this._format(arguments);
  this.error(this.wraptext(this.options.maxCols || 77, msg));
  return this;
};
Log.prototype.oklns = function() {
  var msg = this._format(arguments);
  this.ok(this.wraptext(this.options.maxCols || 77, msg));
  return this;
};
Log.prototype.success = function() {
  var msg = this._format(arguments);
  this._writeln(msg.green);
  return this;
};
Log.prototype.fail = function() {
  var msg = this._format(arguments);
  this._writeln(msg.red);
  return this;
};
Log.prototype.header = function() {
  var msg = this._format(arguments);
  // Skip line before header, but not if header is the very first line output.
  if (this.hasLogged) { this._writeln(); }
  this._writeln(msg.underline);
  return this;
};
Log.prototype.subhead = function() {
  var msg = this._format(arguments);
  // Skip line before subhead, but not if subhead is the very first line output.
  if (this.hasLogged) { this._writeln(); }
  this._writeln(msg.bold);
  return this;
};
// For debugging.
Log.prototype.debug = function() {
  var msg = this._format(arguments);
  if (this.option('debug')) {
    this._writeln('[D] ' + msg.magenta);
  }
  return this;
};

// Write a line of a table.
Log.prototype.writetableln = function(widths, texts) {
  this._writeln(this.table(widths, texts));
  return this;
};

// Wrap a long line of text.
Log.prototype.writelns = function() {
  var msg = this._format(arguments);
  this._writeln(this.wraptext(this.options.maxCols || 80, msg));
  return this;
};

// Display flags in verbose mode.
Log.prototype.writeflags = function(obj, prefix) {
  var wordlist;
  if (Array.isArray(obj)) {
    wordlist = this.wordlist(obj);
  } else if (typeof obj === 'object' && obj) {
    wordlist = this.wordlist(Object.keys(obj).map(function(key) {
      var val = obj[key];
      return key + (val === true ? '' : '=' + JSON.stringify(val));
    }));
  }
  this._writeln((prefix || 'Flags') + ': ' + (wordlist || '(none)'.cyan));
  return this;
};

// Static methods.

// Pretty-format a word list.
Log.prototype.wordlist = exports.wordlist = function(arr, options) {
  options = _.defaults(options || {}, {
    separator: ', ',
    color: 'cyan'
  });
  return arr.map(function(item) {
    return options.color ? String(item)[options.color] : item;
  }).join(options.separator);
};

// Return a string, uncolored (suitable for testing .length, etc).
Log.prototype.uncolor = exports.uncolor = function(str) {
  return str.replace(/\x1B\[\d+m/g, '');
};

// Word-wrap text to a given width, permitting ANSI color codes.
Log.prototype.wraptext = exports.wraptext = function(width, text) {
  // notes to self:
  // grab 1st character or ansi code from string
  // if ansi code, add to array and save for later, strip from front of string
  // if character, add to array and increment counter, strip from front of string
  // if width + 1 is reached and current character isn't space:
  //  slice off everything after last space in array and prepend it to string
  //  etc

  // This result array will be joined on \n.
  var result = [];
  var matches, color, tmp;
  var captured = [];
  var charlen = 0;

  while (matches = text.match(/(?:(\x1B\[\d+m)|\n|(.))([\s\S]*)/)) {
    // Updated text to be everything not matched.
    text = matches[3];

    // Matched a color code?
    if (matches[1]) {
      // Save last captured color code for later use.
      color = matches[1];
      // Capture color code.
      captured.push(matches[1]);
      continue;

    // Matched a non-newline character?
    } else if (matches[2]) {
      // If this is the first character and a previous color code was set, push
      // that onto the captured array first.
      if (charlen === 0 && color) { captured.push(color); }
      // Push the matched character.
      captured.push(matches[2]);
      // Increment the current charlen.
      charlen++;
      // If not yet at the width limit or a space was matched, continue.
      if (charlen <= width || matches[2] === ' ') { continue; }
      // The current charlen exceeds the width and a space wasn't matched.
      // "Roll everything back" until the last space character.
      tmp = captured.lastIndexOf(' ');
      text = captured.slice(tmp === -1 ? tmp : tmp + 1).join('') + text;
      captured = captured.slice(0, tmp);
    }

    // The limit has been reached. Push captured string onto result array.
    result.push(captured.join(''));

    // Reset captured array and charlen.
    captured = [];
    charlen = 0;
  }

  result.push(captured.join(''));
  return result.join('\n');
};

// Format output into columns, wrapping words as-necessary.
Log.prototype.table = exports.table = function(widths, texts) {
  var rows = [];
  widths.forEach(function(width, i) {
    var lines = this.wraptext(width, texts[i]).split('\n');
    lines.forEach(function(line, j) {
      var row = rows[j];
      if (!row) { row = rows[j] = []; }
      row[i] = line;
    });
  }, this);

  var lines = [];
  rows.forEach(function(row) {
    var txt = '';
    var column;
    for (var i = 0; i < row.length; i++) {
      column = row[i] || '';
      txt += column;
      var diff = widths[i] - this.uncolor(column).length;
      if (diff > 0) { txt += _.repeat(' ', diff); }
    }
    lines.push(txt);
  }, this);

  return lines.join('\n');
};

});
var TcpPackage = require('../systemData/tcpPackage');
var TcpCommand = require('../systemData/tcpCommand');
var TcpFlags = require('../systemData/tcpFlags');
var BufferSegment = require('../common/bufferSegment');
var InspectionDecision = require('../systemData/inspectionDecision');
var InspectionResult = require('./../systemData/inspectionResult');
var results = require('../results');
var VolatileEventStoreSubscription = require('../volatileEventStoreConnection');

function VolatileSubscriptionOperation(
    log, cb, streamId, resolveLinkTos, userCredentials, eventAppeared,
    subscriptionDropped, verboseLogging, getConnection
) {
  SubscriptionOperation.call(this, log, cb, streamId, resolveLinkTos, userCredentials, eventAppeared, subscriptionDropped, verboseLogging, getConnection);
}
util.inherits(VolatileSubscriptionOperation, SubscriptionOperation);

VolatileSubscriptionOperation.prototype._createSubscriptionPackage = function() {
  var dto = new ClientMessage.SubscribeToStream(this._streamId, this._resolveLinkTos);
  return new TcpPackage(TcpCommand.SubscribeToStream,
      this._userCredentials != null ? TcpFlags.Authenticated : TcpFlags.None,
      this._correlationId,
      this._userCredentials != null ? this._userCredentials.username : null,
      this._userCredentials != null ? this._userCredentials.password : null,
      new BufferSegment(dto.toBuffer()));
};

VolatileSubscriptionOperation.prototype._inspectPackage = function(pkg) {
  try {
    if (pkg.command == TcpCommand.SubscriptionConfirmation) {
      var dto = ClientMessage.SubscriptionConfirmation.decode(pkg.data.toBuffer());
Example #9
0
        it('should call all the functions necessary to resolve by the correct order', function (next) {
            var resolver;

            function DummyResolver() {
                Resolver.apply(this, arguments);
                this._stack = [];
            }

            util.inherits(DummyResolver, Resolver);

            DummyResolver.prototype.getStack = function () {
                return this._stack;
            };

            DummyResolver.prototype.resolve = function () {
                this._stack = [];
                return Resolver.prototype.resolve.apply(this, arguments);
            };

            DummyResolver.prototype._createTempDir = function () {
                this._stack.push('before _createTempDir');
                return Resolver.prototype._createTempDir.apply(this, arguments)
                .then(function (val) {
                    this._stack.push('after _createTempDir');
                    return val;
                }.bind(this));
            };
            DummyResolver.prototype._resolve = function () {};
            DummyResolver.prototype._readJson = function () {
                this._stack.push('before _readJson');
                return Resolver.prototype._readJson.apply(this, arguments)
                .then(function (val) {
                    this._stack.push('after _readJson');
                    return val;
                }.bind(this));
            };
            DummyResolver.prototype._applyPkgMeta = function () {
                this._stack.push('before _applyPkgMeta');
                return Resolver.prototype._applyPkgMeta.apply(this, arguments)
                .then(function (val) {
                    this._stack.push('after _applyPkgMeta');
                    return val;
                }.bind(this));
            };
            DummyResolver.prototype._savePkgMeta = function () {
                this._stack.push('before _savePkgMeta');
                return Resolver.prototype._savePkgMeta.apply(this, arguments)
                .then(function (val) {
                    this._stack.push('after _savePkgMeta');
                    return val;
                }.bind(this));
            };

            resolver = new DummyResolver({ source: 'foo'}, defaultConfig, logger);

            resolver.resolve()
            .then(function () {
                expect(resolver.getStack()).to.eql([
                    'before _createTempDir',
                    'after _createTempDir',
                    'before _readJson',
                    'after _readJson',
                    // Both below are called in parallel
                    'before _applyPkgMeta',
                    'after _applyPkgMeta',
                    'before _savePkgMeta',
                    'after _savePkgMeta'
                ]);
                next();
            })
             .done();
        });
Example #10
0
var readline = require('readline');
var fs = require('fs');
var settings = require('../settings.js');
var path = require('path');

var extend = require('xtend');
var util = require('util');
var BaseCommand = require("./BaseCommand.js");

var ExampleCommand = function (cli, options) {
    ExampleCommand.super_.call(this, cli, options);
    this.options = extend({}, this.options, options);

    this.init();
};
util.inherits(ExampleCommand, BaseCommand);
ExampleCommand.prototype = extend(BaseCommand.prototype, {
    options: null,
    //name: "example",
    //description: "example description to show in help",

    init: function () {
        //this.addOption("list", this.listCores.bind(this));
        //this.addOption(null, this.helpCommand.bind(this));
    },


    _: null
});

module.exports = ExampleCommand;
Example #11
0
var util = require('util');
var webutil = require('../util/web');
var Tab = require('../client/tab').Tab;
var Amount = ripple.Amount;
var Currency = ripple.Currency;

var TradeTab = function ()
{
  Tab.call(this);
};

util.inherits(TradeTab, Tab);

TradeTab.prototype.tabName = 'trade';
TradeTab.prototype.mainMenu = 'exchange';

TradeTab.prototype.generateHtml = function ()
{
  return require('../../jade/tabs/trade.jade')();
};

TradeTab.prototype.angularDeps = Tab.prototype.angularDeps.concat(['books']);

TradeTab.prototype.extraRoutes = [
  { name: '/trade/:first/:second' }
];

TradeTab.prototype.angular = function(module)
{
  module.controller('TradeCtrl', ['rpBooks', '$scope', 'rpId', 'rpNetwork',
                                  '$routeParams', '$location', '$filter',
Example #12
0
  , EventEmitter = require('events').EventEmitter
  , makeError = require('makeerror')

/**
 * To walk a directory. It's complicated (but it's async, so it must be fast).
 *
 * @param root {String} the directory to start with
 */
function Walker(root) {
  if (!(this instanceof Walker)) return new Walker(root)
  EventEmitter.call(this)
  this._pending = 0
  this._filterDir = function() { return true }
  this.go(root)
}
util.inherits(Walker, EventEmitter)

/**
 * Errors of this type are thrown when the type of a file could not be
 * determined.
 */
var UnknownFileTypeError = Walker.UnknownFileTypeError = makeError(
  'UnknownFileTypeError',
  'The type of this file could not be determined.'
)

/**
 * Setup a function to filter out directory entries.
 *
 * @param fn {Function} a function that will be given a directory name, which
 * if returns true will include the directory and it's children
Example #13
0
var _ = require('underscore');

var SideEffectStep = require('./SideEffectStep');
var SimpleTraverser = require('../../SimpleTraverser');
var SingleIterator = require('../../util/SingleIterator');
var TraverserIterator = require('../../util/TraverserIterator');

var TraverserSource = require('../../graph/marker/TraverserSource');


function StartStep(traversal, start) {
  this.start = start || null;
  SideEffectStep.call(this, traversal);
}

util.inherits(StartStep, SideEffectStep);
_.extend(StartStep.prototype, TraverserSource.prototype, SideEffectStep.prototype);


StartStep.prototype.clear = function() {
  this.starts.clear();
};

StartStep.prototype.generateTraverserIterator = function(trackPaths) {
  if (this.start !== null) { // this.start is an ElementTraversal or a VertexPropertyTraversal
    this.starts.clear();

    if (typeof this.start.next === 'function') { // mimic check for instanceof Iterator
      var iterator = new TraverserIterator(this, trackPaths, this.start);

      this.starts.add(iterator);
Example #14
0
    CreateAlbumResultSet.super_.call(this, resultStream);    
        /*
        Retrieve the value for the "Response" output from this Choreo execution. (The response from Facebook. Corresponds to the ResponseFormat input. Defaults to JSON.)
        */
        this.get_Response = function() {
            return this.getResult("Response");
        }
    /*
    Get the ID of the object that has been created
    */
    this.getFacebookObjectId = function()  {
    	return JSON.parse(this.getResult('Response'))["id"];
    }
}

util.inherits(CreateAlbum, choreography.Choreography);
util.inherits(CreateAlbumInputSet, choreography.InputSet);
util.inherits(CreateAlbumResultSet, choreography.ResultSet);
exports.CreateAlbum = CreateAlbum;


/*
    CreateCheckin
    Creates a checkin at a location represented by a Page.
*/


var CreateCheckin = function(session) {
    /*
        Create a new instance of the CreateCheckin Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
Example #15
0
    return new CLBuffer(context, flags, ptr.length, ptr);
};

CLBuffer.wrap = function (context, hostPtr) {
    return CLBuffer._wrap(context, null, hostPtr);
};

CLBuffer.wrapReadOnly = function (context, hostPtr) {
    return CLBuffer._wrap(context, "readOnly", hostPtr);
};

CLBuffer.wrapWriteOnly = function (context, hostPtr) {
    return CLBuffer._wrap(context, "writeOnly", hostPtr);
};

util.inherits(CLBuffer, CLMemory);

Object.defineProperties(CLBuffer.prototype, {
    offset: {
        get: function () {
            this._throwIfReleased();
            return this._getInfo("size_t", this.cl.defs.CL_MEM_OFFSET);
        }
    },
    superBuffer: {
        get: function () {
            this._throwIfReleased();
            var subHandle = this._getInfo(this.cl.types.Mem, this.cl.defs.CL_MEM_ASSOCIATED_MEMOBJECT);
            return new CLBuffer(subHandle);
        }
    }
Example #16
0
    
    function addComponent(entity, type, component) {
        
    }
    
    function removeComponent() {
        
    }
    
    function getComponentsByType() {
    }
    
    function getComponent() {
        
    }
    
    this.getComponentsFor = function() {
        
    };
    
    this.deleted = function(entity) {
        deleted.push(entity);
    };
    
    function clean() {
        
    }
};

util.inherits(ComponentManager, Manager);
Example #17
0
      reqOpts: {
        method: 'PUT'
      }
    }
  };

  common.ServiceObject.call(this, {
    parent: resource,
    baseUrl: '/projects',
    id: id,
    createMethod: resource.createProject.bind(resource),
    methods: methods
  });
}

util.inherits(Project, common.ServiceObject);

/**
 * Restore a project.
 *
 * **This method only works if you are authenticated as yourself, e.g. using the
 * gcloud SDK.**
 *
 * @resource [projects: undelete API Documentation]{@link https://cloud.google.com/resource-manager/reference/rest/v1/projects/undelete}
 *
 * @param {function=} callback - The callback function.
 * @param {?error} callback.err - An error returned while making this request.
 * @param {object} callback.apiResponse - Raw API response.
 *
 * @example
 * project.restore(function(err, apiResponse) {
Example #18
0
var Readable = require('readable-stream').Readable
var inherits = require('util').inherits

var test = require('tap').test
var concat = require('concat-stream')

var server = require('./lib/server.js')
var common = require('./lib/common.js')
var client = common.freshClient()

function OneA () {
  Readable.call(this)
  this.push('A')
  this.push(null)
}
inherits(OneA, Readable)

function nop () {}

var URI = 'http://*****:*****@izs.me'
var AUTH = {
  username: USERNAME,
  password: PASSWORD,
  email: EMAIL
}
var PARAMS = { auth: AUTH }

test('request call contract', function (t) {
Example #19
0
/**
 * Cutter for buffer
 * @param  {Number}      headLength
 * @param  {Function}    getLength
 */
var Cutter = function(headLength, getLength) {
  assert(typeof getLength === 'function', 'getLength must be type of Function!');
  assert(typeof headLength === 'number', 'headLength must be type of Number!');
  EventEmitter.call(this);
  this.getLength = getLength;
  this.headLength = headLength;
  this.buf = null;
}

util.inherits(Cutter, EventEmitter);

/**
 * handle data events
 * @param  {Buffer} data
 */
Cutter.prototype.handleData = function (data) {
  assert(data instanceof Buffer, 'data should be a buffer');
  if (!this.buf) {
    this.buf = data;
  } else {
    var length = this.buf.length + data.length;
    this.buf = Buffer.concat([this.buf, data], length);
  }
  this.handlePacket();
};
// the License.

var util = require('util'),
    events = require('events'),
    helpers = require('../helpers/helpers.js'),
    request = require('request');

const commandHelper = require('./helper.js');
const checkForDatabaseCreated = commandHelper.checkForDatabaseCreated;

function CheckForDatabaseCreated () {
  events.EventEmitter.call(this);
}

// inherit from node's event emitter
util.inherits(CheckForDatabaseCreated, events.EventEmitter);

CheckForDatabaseCreated.prototype.command = function (databaseName, timeout) {
  const couchUrl = this.client.options.db_url;

  if (!timeout) {
    timeout = helpers.maxWaitTime;
  }

  checkForDatabaseCreated(couchUrl, databaseName, timeout, () => {
    this.emit('complete');
  });

  return this;
};
Example #21
0
File: index.js Project: jden/nali
  this._state = {}
  this._instances = {}

  this.parentContainer = null
  this.childContainers = []

  EventEmitter.call(this)
  this.setMaxListeners(1000)
  // var self = this
  // Object.keys(EventEmitter.prototype).forEach(function (key) {
  //   if (typeof self[key] === 'function') {
  //     self[key] = self[key].bind(self)
  //   }
  // })
}
util.inherits(Nali, EventEmitter)

Nali.prototype.use = function (behavior) {
  this.behaviors.push(behavior)
  return this
}

Nali.prototype.dispose = function () {
  this.services.forEach(function (service) {
    service.dispose()
  })

  clear(this.instances)
  clear(this.services)
  this.removeAllListeners()
  this.childContainers.forEach(function (childContainer) {
Example #22
0
 * @example
 * // import the error into a controller
 * const Forbidden = require('lib/errors/Forbidden');
 *
 * // use the error in either a promise chain or directly via next()
 * return next(new Forbidden('Some description...'));
 *
 * @constructor
 */
function Forbidden(description) {
  'use strict';

  // make sure we have a working stack trace
  Error.captureStackTrace(this, this.constructor);

  // HTTP status code
  this.status = 403;

  // bhima status code (for $translation)
  this.code = 'ERRORS.FORBIDDEN';

  // default to an empty string if no description passed in
  this.description = description || '';
}

// prototypically inherit from the global error object
util.inherits(Forbidden, Error);

// expose the function to an external controller
module.exports = Forbidden;
Example #23
0
module.exports = function(app) {
    //Root Application
    var ApplicationController = app.getLib('appController'),
        User = app.getModel('User'),
        defaultToken = app.getConfig('auth').defaultToken;

    function UserController() {
        ApplicationController.call(this);
    }

    util.inherits(UserController, ApplicationController);

    /*
     * Route => GET /api/users
     */

    UserController.prototype.index = function index(req, res, next) {
        User.find({}).select('-accessToken').exec(function(err, users) {
            if (err) {
                return next(err);
            }
            if (!users) {
                return next(new Error('No Users!'));
            }
            return res.sendResponse(200, users);
        });
    };

    /*
     * Route => POST /api/users/login
     */

    UserController.prototype.login = function login(req, res, next) {
        if (req.body.hasOwnProperty('accessToken') && req.body.accessToken.length > 0) {
            User.findOne({
                accessToken: req.body.accessToken
            }).exec(function(err, user) {
                if (err) {
                    return next(err);
                }
                if (!user) {
                    if (req.body.accessToken === defaultToken) {
                        return res.sendResponse(200, {
                            accessToken: req.body.accessToken
                        });
                    } else {
                        return next(new Error('User not found!'));
                    }
                }
                return res.sendResponse(200, {
                    accessToken: user.accessToken
                });
            });
        } else {
            User.findOne({
                username: req.body.username
            }).exec(function(err, user) {
                if (err) {
                    return next(err);
                }
                if (!user) {
                    return next(new Error('User not found!'));
                }
                if (!user.checkPassword(req.body.password)) {
                    return next(new Error('Invalid password!'));
                }
                return res.sendResponse(200, {
                    accessToken: user.accessToken
                });
            });
        }
    };

    /*
     * Route => POST /api/users
     */

    UserController.prototype.create = function create(req, res, next) {
        //Create
        var userData = {};
        //Populate
        userData.username = req.body.username;
        userData.password = req.body.password;
        //Create Instance
        var user = new User(userData);
        //Save
        user.save(function(err) {
            if (err) {
                return next(err);
            }
            //Send message
            res.sendResponse(200, {
                msg: 'User created successfully!',
                user: {
                    _id: user._id,
                    username: user.username,
                    accessToken: user.accessToken
                }
            });
        });
    };

    /*
     * Route => PUT /api/users/
     */

    UserController.prototype.update = function update(req, res, next) {
        //Update
        User.findOne({
            _id: req.user._id
        }).exec(function(err, user) {
            if (err) {
                return next(err);
            }
            if (!user) {
                return next('User not found!');
            }
            //Create
            var userData = {};
            //Populate
            if (req.body.hasOwnProperty('username') && req.body.username !== '') {
                userData.username = req.body.username;
            }
            if (req.body.hasOwnProperty('password') && req.body.password !== '') {
                userData.password = req.body.password;
            }
            if (!userData) {
                return next('You made ​​no changes!');
            }
            //Extend
            _.extend(user, userData);
            //Save
            user.save(function(err) {
                if (err) {
                    return next(err);
                }
                //Send message
                res.sendResponse(200, {
                    msg: 'User ' + user.username + ' updated successfully!'
                });
            });
        });
    };

    /*
     * Route => PUT /api/users/regenerate
     */

    UserController.prototype.regenerateToken = function regenerateToken(req, res, next) {
        //Update
        User.findOne({
            _id: req.user._id
        }).exec(function(err, user) {
            if (err) {
                return next(err);
            }
            if (!user) {
                return next('User not found!');
            }
            //Generate new token
            var token = app.getService('utilsService').uid(16);
            user.accessToken = token;
            //Save
            user.save(function(err) {
                if (err) {
                    return next(err);
                }
                //Send message
                res.sendResponse(200, {
                    msg: 'Access token regenerated successfully!',
                    accessToken: token
                });
            });
        });
    };

    /*
     * Route => DELETE /api/users/:id
     */

    UserController.prototype.remove = function remove(req, res, next) {
        User.remove({
            _id: req.params.id
        }).exec(function(err) {
            if (err) {
                return next(err);
            }
            //Send message
            res.sendResponse(200, {
                msg: 'User removed successfully!'
            });
        });
    };

    return UserController;
};
Example #24
0
        try {
            self.emit('next', msg);
        } finally {
            // Continue parsing before next IO, we can't use nextTick
            // cause it may sometimes execute after next IO...
            msg = {};
            curFieldPos = 0;
            parse();
        }
    };


    /**
     * Feed parser with more data
     */
    this.feed = function(data) {

        ensureBuffer(data.length);

        data.copy(buffer, b);
        b += data.length;

        parse();
    };

};

/* Inherit EventEmitter */
util.inherits(Parser, EventEmitter);

Example #25
0
var util = require('util'),
    webutil = require('../util/web'),
    Tab = require('../client/tab').Tab,
    Amount = ripple.Amount,
    Base = ripple.Base,
    Currency = ripple.Currency;

var ExchangeTab = function ()
{
  Tab.call(this);
};

util.inherits(ExchangeTab, Tab);

ExchangeTab.prototype.tabName = 'exchange';
ExchangeTab.prototype.mainMenu = 'exchange';

ExchangeTab.prototype.generateHtml = function ()
{
  return require('../../jade/tabs/exchange.jade')();
};

ExchangeTab.prototype.angular = function (module)
{
  module.controller('ExchangeCtrl', ['$scope', '$timeout', '$routeParams',
    'rpId', 'rpNetwork', 'rpTracker', 'rpKeychain', '$rootScope',
    function ($scope, $timeout, $routeParams, $id, $network, $rpTracker, keychain, $rootScope)
    {
      if (!$id.loginStatus) return $id.goId();

      var timer, pf;
var EventEmitter = require('events').EventEmitter;
var util = require('util');


var Loop = function (collection) {
    if (!collection || !Array.isArray(collection)) {
        throw new Error('please pass an array to the constructor ');
    }

    this.i = -1;
    this.collection = collection;
    this.isDone = false;

};

util.inherits(Loop, EventEmitter);

var L = Loop.prototype;

L.next = function ( /*args*/ ) {
    if (this.isDone) {
        return;
    }
    if (this.i < this.collection.length - 1) {
        this.i += 1;
        return this.emit.bind(this, 'next', this.collection[this.i], this.i, this.collection)
            .apply(this, arguments);

    }
    this.done.apply(this, arguments);
 * @param {string} [baseUri] - The base URI of the service.
 *
 * @param {object} [options] - The parameter options
 *
 * @param {Array} [options.filters] - Filters to be added to the request pipeline
 *
 * @param {object} [options.requestOptions] - Options for the underlying request object
 * {@link https://github.com/request/request#requestoptions-callback Options doc}
 *
 * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy
 *
 */
function AutoRestSwaggerBATHeaderService(baseUri, options) {

  if (!options) options = {};

  AutoRestSwaggerBATHeaderService['super_'].call(this, null, options);
  this.baseUri = baseUri;
  if (!this.baseUri) {
    this.baseUri = 'http://localhost';
  }

  this.header = new operations.Header(this);
  this.models = models;
  msRest.addSerializationMixin(this);
}

util.inherits(AutoRestSwaggerBATHeaderService, ServiceClient);

module.exports = AutoRestSwaggerBATHeaderService;
Example #28
0
var util = require('util'),
    _ = require('underscore'),
    errors = require('../errors'),
    extendWithGettersAndSetters = require('../util/extendWithGettersAndSetters'),
    Text = require('./Text'),
    AssetGraph = require('../AssetGraph');

function SrcSet(config) {
    Text.call(this, config);
    if (!this._parseTree && !('_text' in this)) {
        throw new Error("SrcSet: Either parseTree or text must be specified");
    }
}

util.inherits(SrcSet, Text);

extendWithGettersAndSetters(SrcSet.prototype, {
    type: 'SrcSet',

    contentType: null, // Avoid reregistering application/octet-stream

    supportedExtensions: [],

    get parseTree() {
        if (!this._parseTree) {
            this._parseTree = [];
            this.text.split(/,/).forEach(function (entryStr) {
                entryStr = entryStr.replace(/^\s+|\s+$/g, '');
                var matchEntryStr = entryStr.match(/^([^\s]+)(.*)$/);
                if (matchEntryStr) {
                    var extraTokens = matchEntryStr[2].split(/\s+/).filter(function (extraToken) {
Example #29
0
	opts || (opts = {});

	this.port = opts.port || 13854;
	this.host = opts.host || 'localhost';

  var enableRawOutput = !!opts.enableRawOutput;

	this.config = {
		enableRawOutput: enableRawOutput,
		format: "Json"
	};

	events.EventEmitter.call(this);
};

util.inherits(ThinkGearClient, events.EventEmitter);

ThinkGearClient.prototype.connect = function() {
	var self = this;

	var client = this.client = net.connect(this.port, this.host, function() {
		client.write(JSON.stringify(self.config));
	});

	client.on('data',function(data){
    try {
      var json = JSON.parse(data.toString());
      if(json['rawEeg']) {
        self.emit('raw_data', json);
      } else if(json['blinkStrength']) {
        self.emit('blink_data', json);
Example #30
0
var util = require('util')
  , stream = require('stream')

var Arrayify = function () {
  stream.Transform.call(this, { objectMode: true })
  this.first = true
}

util.inherits(Arrayify, stream.Transform)

Arrayify.prototype._transform = function (chunk, encoding, next) {
  if (this.first) {
    this.push('[' + JSON.stringify(chunk))
    this.first = false
  } else {
    this.push(',' + JSON.stringify(chunk))
  }
  next()
}

Arrayify.prototype._flush = function (done) {
  this.push(']')
  done()
}

module.exports = Arrayify