<commit_before>'use strict';

const frontMatter = require('front-matter');

const splitterExpression = '<!---(.*)--->';
function process(fileContents, opts, { bodySplitter }) {
  if (opts.isDirectory) {
    return fileContents;
  }
  const data = frontMatter(fileContents);
  const splitted = bodySplitter(data.body, splitterExpression);
  return {
    meta: data.attributes,
    content: splitted,
  };
}

const type = 'file';
const name = 'html';
const extensions = ['.html', '.htm'];
function registration(register) {
  register(type, name, extensions, process);
}

module.exports = registration;
<commit_msg>fix the splitter regexp for html<commit_after>'use strict';

const frontMatter = require('front-matter');

const splitterExpression = '<!-(.*)-->';
function process(fileContents, opts, { bodySplitter }) {
  if (opts.isDirectory) {
    return fileContents;
  }
  const data = frontMatter(fileContents);
  const splitted = bodySplitter(data.body, splitterExpression);
  return {
    meta: data.attributes,
    content: splitted,
  };
}

const type = 'file';
const name = 'html';
const extensions = ['.html', '.htm'];
function registration(register) {
  register(type, name, extensions, process);
}

module.exports = registration;
<|endoftext|>


<commit_before>angular.module('views')
  .controller('mainController', ['$rootScope', '$scope', '$state', '$stateParams', '$location', 'RestService', 'SocketService',
    function($rootScope, $scope, $state, $stateParams, $location, RestService, SocketService) {

      $scope.$on('$stateNotFound', function(event, unfoundState, fromState, fromParams) {
        event.preventDefault();

        $scope.changeState('main.home');
      });

      $scope.changeState = function(state, data) {
        if (!data) {
          data = {};
        }
        $state.go(state, data, {
          location: true
        }).then(function() {});
      };

      var agents = { <% _.each(moduleNames.agents, function(agentName, index) { %> '<%- agentName %>': '/<%- agentName %>' <%
          if (index != moduleNames.agents.length - 1) { %> , <%
          }
        }); %>
      }

      $scope.activeAgent = null;

      for (agent in agents) {
        if (agents[agent] == $state.current.url) {
          $scope.activeAgent = agents[agent];
          break;
        }
      }
      if (!$scope.activeAgent) {
        console.log('stop all conversations');
      }
    }
  ]);
<commit_msg>adding a couple useful functions to scope.<commit_after>angular.module('views')
  .controller('mainController', ['$rootScope', '$scope', '$state', '$stateParams', '$location', 'RestService', 'SocketService',
    function($rootScope, $scope, $state, $stateParams, $location, RestService, SocketService) {

      $scope.$on('$stateNotFound', function(event, unfoundState, fromState, fromParams) {
        event.preventDefault();

        $scope.changeState('main.home');
      });

      $scope.changeState = function(state, data) {
        if (!data) {
          data = {};
        }
        $state.go(state, data, {
          location: true
        }).then(function() {});
      };

      $scope.objectFindByKey = function(array, key, value) {
        for (var i = 0; i < array.length; i++) {
          if (array[i][key] == value) {
            return array[i];
          }
        }
        return null;
      };

      var agents = { <% _.each(moduleNames.agents, function(agentName, index) { %> '<%- agentName %>': '/<%- agentName %>' <%
          if (index != moduleNames.agents.length - 1) { %> , <%
          }
        }); %>
      }

      $scope.MergeRecursive = function(obj1, obj2) {
        for (var p in obj2) {
          try {
            if ( obj2[p].constructor==Object ) {
              obj1[p] = MergeRecursive(obj1[p], obj2[p]);
            } else {
              obj1[p] = obj2[p];
            }
          } catch(e) {
            obj1[p] = obj2[p];
          }
        }
        return obj1;
      };

      $scope.activeAgent = null;

      for (agent in agents) {
        if (agents[agent] == $state.current.url) {
          $scope.activeAgent = agents[agent];
          break;
        }
      }
      if (!$scope.activeAgent) {
        console.log('stop all conversations');
      }
    }
  ]);
<|endoftext|>


<commit_before>/**
 *
 * @returns {_L6.Anonym$1}
 */
define([

], function (

) {

    'use strict';

    var getWaveDataFromServer = function getWaveDataFromServerFunction() {

    };

    var drawWave = function drawWaveFunction() {

    };

    var getAudioContext = function getAudioContextFunction() {

        var AudioContext = window.AudioContext || window.webkitAudioContext;

        var audioContext = new AudioContext();

        return audioContext;

    };

    var initialize = function initializeFunction() {

    };

    return {
        init: initialize
    };

});<commit_msg>server analyzer update<commit_after>/**
 *
 * @returns {_L6.Anonym$1}
 */
define([

], function (

) {

    'use strict';

    var getWaveDataFromServer = function getWaveDataFromServerFunction() {

    };

    var drawWave = function drawWaveFunction() {

    };

    var audioContext;

    var getAudioContext = function getAudioContextFunction() {

        var AudioContext = window.AudioContext || window.webkitAudioContext;

        audioContext = new AudioContext();

    };

    var initialize = function initializeFunction() {

        getAudioContext();

    };

    return {
        init: initialize
    };

});<|endoftext|>


<commit_before>'use strict';

var P = require('bluebird');
var hrtime = require('../swissarmyknife/hrtime');

/**
 *
 * @param {module:primus/Spark} spark primus (client) or spark (server) object
 * @param {String} namespace
 * @param {int} [channels=10] Amount of multiplex channels, requires primus-multiplex.
 *         Use 0 to disable in which case primus-multiplex is not needed.
 *         If primus-multiplex is not available the default for this param is 0 instead of 10.
 *         Make sure both client and server pass exactly the same value for this parameter.
 * @constructor
 */
function Resource(spark, namespace, channels)
{
        this.primus = spark && (spark.primus || spark);
        this.spark = spark;
        this.namespace = namespace;
        this.channelSparks = [];
        this.listenNames = [];
        this._acquireQueue = []; // promises that want a channel. {promise: Promise, exclusive: boolean}
        /** While handling an rpc request, this parameter
         * contains channel data for the duration of the RPC method.
         * @type {Object} contains a key "channelSpark", other keys are for your own use
         */
        this.currentChannelData = null;

        if (spark)
        {
                this._setupMultiplexing(channels);
        }

        this._acquireDisposer = this._acquireDisposer.bind(this);
}

module.exports = Resource;

Resource.debugLogging = false;

Resource.prototype._setupMultiplexing = function(channels)
{
        var primus = this.primus;
        var spark = this.spark;
        var i;

        if (channels === undefined)
        {
                if  (!primus.channel)
                {
                        // primus-multiplex is not available and "channels" is not given
                        return;
                }

                channels = 10;
        }

        if (channels &&
            !primus.channel)
        {
                throw Error('channels argument is set, however primus-multiplex is not plugged in');
        }

        if (!channels)
        {
                return;
        }

        this.channelSparks = new Array(channels);

        if (spark.primus) // server-side spark
        {
                // channel must be created on the primus, not on the spark
                if (!primus._ResourceChannels)
                {
                        primus._ResourceChannels = Object.create(null);
                }

                for (i = 0; i < this.channelSparks.length; ++i)
                {
                        var channelName = this.namespace + '$' + i;
                        var channel = primus._ResourceChannels[channelName];

                        if (!channel)
                        {
                                channel = primus.channel();
                                primus._ResourceChannels[channelName] = channel;
                        }
                }

                // ugh...
                spark.on('subscribe', function(channel, channelSpark)
                {
                        var nameSplit = channel.name.split('$');

                        if (nameSplit.length !== 2 ||
                            nameSplit[0] !== this.namespace)
                        {
                                return;
                        }

                        var index = nameSplit[1];

                        this.channelSparks[index] = channelSpark;
                        this.getChannelSparkData(channelSpark).index = index;

                        this.listenNames.forEach(function(name)
                        {
                                var fullname = this.namespace + '/' + name;
                                channelSpark.on(fullname, this._rpcHandler(channelSpark, name));
                        }, this);

                }.bind(this));

        }
        else // client side
        {
                for (i = 0; i < this.channelSparks.length; ++i)
                {
                        var channelSpark = primus.channel(this.namespace + '$' + i);
                        this.channelSparks[i] = channelSpark;
                        this.getChannelSparkData(channelSpark).index = i;
                }
        }
};

/**
 * Get the data for a channel spark (if multiplexing is enabled) or for a regular spark.
 * @param {module:primus/Spark|module:primus-multiplex/Spark} channelSpark
 * @returns {{index: int, acquired: int}}
 */
Resource.prototype.getChannelSparkData = function(channelSpark)
{
        if (!channelSpark._ResourceChannelData)
        {
                var data = {
                        // index is -1 if this is a regular spark instead of a channel spark
                        index: -1,
                        acquired: 0,
                        exclusive: false,
                        subClassData: Object.create(null) // passed as the last argument to rpc handlers
                };
                data.subClassData.channelSpark = channelSpark;

                channelSpark._ResourceChannelData = data;
                return data;
        }

        return channelSpark._ResourceChannelData;
};

Resource.prototype._acquireDisposer = function(channelSpark)
{
        var channelSparkData = this.getChannelSparkData(channelSpark);
        channelSparkData.acquired--;
        channelSparkData.exclusive = false;

        if (this._acquireQueue.length)
        {
                if (this._acquireQueue[0].exclusive &&
                    channelSparkData.acquired)
                {
                        // next in queue wants exclusive access, however this channel still has stuff pending
                        return;
                }

                var queueItem = this._acquireQueue.shift();
                channelSparkData.acquired++;
                channelSparkData.exclusive = queueItem.exclusive;
                queueItem.resolve(channelSpark);
        }
};

/**
 * Acquire a channel spark for sending data. If there are multiple channels, the least busy channel will be chosen.
 * @param {boolean} [exclusive=false] If true, acquire the channel spark in exclusive mode, no other channel sparks will be able to acquire it until you are done.
 * @returns {module:bluebird/Disposer<module:primus/Spark|module:primus-multiplex/Spark>} A disposer promise. see bluebird#using
 */
Resource.prototype.acquireChannelSparkForSending = function(exclusive)
{
        exclusive = !!exclusive;
        if (!this.spark)
        {
                return P.reject(Error('This resource has been instantiated without a primus spark'));
        }

        if (!this.channelSparks.length)
        {
                // not using primus-multiplex
                var data = this.getChannelSparkData(this.spark);

                if (data.exclusive ||  // exclusive channel that is busy
                    (exclusive && data.acquired)) // exclusive access is requested and this channel is already in use
                {
                        return new P(function(resolve, reject)
                        {
                                this._acquireQueue.push({
                                        resolve: resolve,
                                        reject: reject,
                                        exclusive: exclusive
                                });
                        }.bind(this)).disposer(this._acquireDisposer);
                }

                data.exclusive = exclusive;
                data.acquired++;
                return P.resolve(this.spark).disposer(this._acquireDisposer);
        }

        var bestSparkChannel = null;
        var lowestAcquired = 0;

        for (var i = 0; i < this.channelSparks.length; ++i)
        {
                var channel = this.channelSparks[i];
                if (!channel)
                {
                        // subscribe event has not fired yet
                        continue;
                }

                var channelSparkData = this.getChannelSparkData(channel);

                if (channelSparkData.exclusive)
                {
                        // exclusive channel that is busy
                        continue;
                }

                if (exclusive &&
                    channelSparkData.acquired)
                {
                        // exclusive access is requested and this channel is already in use
                        continue;
                }

                if (!bestSparkChannel ||
                    channelSparkData.acquired < lowestAcquired)
                {
                        lowestAcquired = channelSparkData.acquired;
                        bestSparkChannel = channel;
                }
        }

        if (bestSparkChannel)
        {
                var bestData = this.getChannelSparkData(bestSparkChannel);
                bestData.exclusive = exclusive;
                bestData.acquired++;
                return P.resolve(bestSparkChannel).disposer(this._acquireDisposer);
        }

        return new P(function(resolve, reject)
        {
                this._acquireQueue.push({
                        resolve: resolve,
                        reject: reject,
                        exclusive: exclusive
                });
        }.bind(this)).disposer(this._acquireDisposer);
};

/**
 * Call a method on the other end (client/server). The other end must explicitly listen
 * for this method call by calling .listen() in its constructor.
 * @param {String} name Name of the method to call on the other end.
 *        The other end must listen for this method name explicitly using .listen(name)
 * @param {...*} arg Any (e)json encodable value
 * @returns {Promise} Containing the rejected error or resolved return value
 */
Resource.prototype.rpc = function(name, arg)
{
        var args = new Array(arguments.length+1);
        for (var ai = 0; ai < arguments.length; ++ai) { args[ai+1] = arguments[ai]; }

        return P.using(this.acquireChannelSparkForSending(), function(channelSpark)
        {
                args[0] = channelSpark;
                return this.channelRpc.apply(this, args);

        }.bind(this)).bind(this); // (the last bind is for the handlers of the promise)
};

/**
 * Call a method on the other end (client/server). The other end must explicitly listen
 * for this method call by calling .listen() in its constructor.
 * @param {module:primus/Spark|module:primus-multiplex/Spark} channelSpark
 * @param {String} name Name of the method to call on the other end.
 *        The other end must listen for this method name explicitly using .listen(name)
 * @param {...*} arg Any (e)json encodable value
 * @returns {Promise} Containing the rejected error or resolved return value
 */
Resource.prototype.channelRpc = function(channelSpark, name, arg)
{
        if (!this.spark)
        {
                throw Error('This resource has been instantiated without a primus spark');
        }

        var start = Resource.debugLogging && hrtime();
        var fullname = this.namespace + '/' + name;

        var args = new Array(arguments.length-2);
        for (var ai = 2; ai < arguments.length; ++ai) { args[ai-2] = arguments[ai]; }

        var channelSparkData = this.getChannelSparkData(channelSpark);

        return new P(function(resolve, reject)
        {
                if (Resource.debugLogging)
                {
                        console.log('RPC >', channelSparkData.index, channelSparkData.acquired, fullname, args);
                }

                channelSpark.send(fullname, args, function (data)
                {
                        var end = Resource.debugLogging && hrtime();
                        if (Resource.debugLogging)
                        {
                                console.log('RPC <', fullname, ':', end - start, 'ms');
                        }

                        if (data[0])
                        {
                                reject(Error('Error from server: ' + data[0]));
                        }
                        else
                        {
                                resolve(data[1]);
                        }
                });

                // todo: reject after timeout?
        }).bind(this); // (this bind is for the handlers of the promise);
};

Resource.prototype._rpcHandler = function(channelSpark, name)
{
        var channelSparkData = this.getChannelSparkData(channelSpark);

        return function(args, result)
        {
                var resultPromise;

                if (Resource.debugLogging)
                {
                        console.log('< RPC', channelSparkData.index, this.namespace, name, args);
                }
                // use P.resolve to make sure this is a bluebird promise
                // and not one from a database or orm library.

                try
                {
                        this.currentChannelData = channelSparkData.subClassData;
                        resultPromise = P.resolve(this[name].apply(this, args));
                        this.currentChannelData = null;
                }
                catch(err)
                {
                        resultPromise = P.reject(err);
                }

                resultPromise
                .catch(function(err)
                {
                        console.error('Error during RPC', err, err.stack);

                        if (result)
                        {
                                result([err.toString(), null]);
                                result = null;
                        }
                })
                .then(function(ret)
                {
                        if (result)
                        {
                                result([null, ret]);
                                result = null;
                        }
                })
                .done();
        }.bind(this);
};

/**
 * Start listening for one or more rpc calls
 * @param names The name to listen for, the method with
 *        the same name on "this" is called whenever .rpc() is invoked on the other end.
 */
Resource.prototype.listen = function(names)
{
        var spark = this.spark;
        var ns = this.namespace;

        if (!Array.isArray(names))
        {
                names = [names];
        }

        names.forEach(function(name)
        {
                var fullname = ns + '/' + name;

                if (typeof this[name] !== 'function')
                {
                        throw Error(name + ' is not a Resource method');
                }

                if (!spark) // null spark = just check if the listeners are valid
                {
                        return;
                }

                this.listenNames.push(name);

                this.channelSparks.forEach(function(channel)
                {
                        channel.on(fullname, this._rpcHandler(channel, name));
                }, this);

        }, this);
};
<commit_msg>Resource bug fixes<commit_after>'use strict';

var P = require('bluebird');
var hrtime = require('../swissarmyknife/hrtime');

/**
 *
 * @param {module:primus/Spark} spark primus (client) or spark (server) object
 * @param {String} namespace
 * @param {int} [channels=10] Amount of multiplex channels, requires primus-multiplex.
 *         Use 0 to disable in which case primus-multiplex is not needed.
 *         If primus-multiplex is not available the default for this param is 0 instead of 10.
 *         Make sure both client and server pass exactly the same value for this parameter.
 * @constructor
 */
function Resource(spark, namespace, channels)
{
        this.primus = spark && (spark.primus || spark);
        this.spark = spark;
        this.namespace = namespace;
        this.channelSparks = [];
        this.listenNames = [];
        this._acquireQueue = []; // promises that want a channel. {promise: Promise, exclusive: boolean}
        /** While handling an rpc request, this parameter
         * contains channel data for the duration of the RPC method.
         * @type {Object} contains a key "channelSpark", other keys are for your own use
         */
        this.currentChannelData = null;

        if (spark)
        {
                this._setupMultiplexing(channels);
        }

        this._acquireDisposer = this._acquireDisposer.bind(this);
}

module.exports = Resource;

Resource.debugLogging = false;

Resource.prototype._setupMultiplexing = function(channels)
{
        var primus = this.primus;
        var spark = this.spark;
        var i;

        if (channels === undefined)
        {
                if  (!primus.channel)
                {
                        // primus-multiplex is not available and "channels" is not given
                        return;
                }

                channels = 10;
        }

        if (channels &&
            !primus.channel)
        {
                throw Error('channels argument is set, however primus-multiplex is not plugged in');
        }

        if (!channels)
        {
                return;
        }

        this.channelSparks = new Array(channels);

        if (spark.primus) // server-side spark
        {
                // channel must be created on the primus, not on the spark
                if (!primus._ResourceChannels)
                {
                        primus._ResourceChannels = Object.create(null);
                }

                for (i = 0; i < this.channelSparks.length; ++i)
                {
                        var channelName = this.namespace + '$' + i;
                        var channel = primus._ResourceChannels[channelName];

                        if (!channel)
                        {
                                channel = primus.channel(channelName);
                                primus._ResourceChannels[channelName] = channel;

                                if (Resource.debugLogging)
                                {
                                        console.log('Create channel', channel.name);
                                }
                        }

                        // Existing subscriptions...
                        /* jshint -W083 */ // Don't make functions within a loop
                        Object.keys(channel.connections).forEach(function(key)
                        {
                                var channelSpark = channel.connections[key];
                                if (channelSpark)
                                {
                                        this._subscribeToChannel(channel, channelSpark);
                                }
                        }, this);
                        /* jshint +W083 */
                }

                // New subscriptions
                spark.on('subscribe', this._subscribeToChannel.bind(this));

        }
        else // client side
        {
                for (i = 0; i < this.channelSparks.length; ++i)
                {
                        var channelSpark = primus.channel(this.namespace + '$' + i);
                        this.channelSparks[i] = channelSpark;
                        this.getChannelSparkData(channelSpark).index = i;
                }
        }
};

Resource.prototype._subscribeToChannel = function(channel, channelSpark)
{
        var primus = this.primus;

        var nameSplit = channel.name.split('$');

        if (nameSplit.length !== 2 ||
            nameSplit[0] !== this.namespace)
        {
                return;
        }

        // make sure we are tracking it
        primus._ResourceChannels[channel.name] = channel;

        /*if (Resource.debugLogging)
        {
                console.log('Channel subscribe', channel.name, channelSpark.id);
        }*/

        var index = nameSplit[1];

        this.channelSparks[index] = channelSpark;
        this.getChannelSparkData(channelSpark).index = index;

        this.listenNames.forEach(function(name)
        {
                var fullname = this.namespace + '/' + name;
                channelSpark.on(fullname, this._rpcHandler(channelSpark, name));
        }, this);
};

/**
 * Get the data for a channel spark (if multiplexing is enabled) or for a regular spark.
 * @param {module:primus/Spark|module:primus-multiplex/Spark} channelSpark
 * @returns {{index: int, acquired: int}}
 */
Resource.prototype.getChannelSparkData = function(channelSpark)
{
        if (!channelSpark._ResourceChannelData)
        {
                var data = {
                        // index is -1 if this is a regular spark instead of a channel spark
                        index: -1,
                        acquired: 0,
                        exclusive: false,
                        subClassData: Object.create(null) // passed as the last argument to rpc handlers
                };
                data.subClassData.channelSpark = channelSpark;

                channelSpark._ResourceChannelData = data;
                return data;
        }

        return channelSpark._ResourceChannelData;
};

Resource.prototype._acquireDisposer = function(channelSpark)
{
        var channelSparkData = this.getChannelSparkData(channelSpark);
        channelSparkData.acquired--;
        channelSparkData.exclusive = false;

        if (this._acquireQueue.length)
        {
                if (this._acquireQueue[0].exclusive &&
                    channelSparkData.acquired)
                {
                        // next in queue wants exclusive access, however this channel still has stuff pending
                        return;
                }

                var queueItem = this._acquireQueue.shift();
                channelSparkData.acquired++;
                channelSparkData.exclusive = queueItem.exclusive;
                queueItem.resolve(channelSpark);
        }
};

/**
 * Acquire a channel spark for sending data. If there are multiple channels, the least busy channel will be chosen.
 * @param {boolean} [exclusive=false] If true, acquire the channel spark in exclusive mode, no other channel sparks will be able to acquire it until you are done.
 * @returns {module:bluebird/Disposer<module:primus/Spark|module:primus-multiplex/Spark>} A disposer promise. see bluebird#using
 */
Resource.prototype.acquireChannelSparkForSending = function(exclusive)
{
        exclusive = !!exclusive;
        if (!this.spark)
        {
                return P.reject(Error('This resource has been instantiated without a primus spark'));
        }

        if (!this.channelSparks.length)
        {
                // not using primus-multiplex
                var data = this.getChannelSparkData(this.spark);

                if (data.exclusive ||  // exclusive channel that is busy
                    (exclusive && data.acquired)) // exclusive access is requested and this channel is already in use
                {
                        return new P(function(resolve, reject)
                        {
                                this._acquireQueue.push({
                                        resolve: resolve,
                                        reject: reject,
                                        exclusive: exclusive
                                });
                        }.bind(this)).disposer(this._acquireDisposer);
                }

                data.exclusive = exclusive;
                data.acquired++;
                return P.resolve(this.spark).disposer(this._acquireDisposer);
        }

        var bestSparkChannel = null;
        var lowestAcquired = 0;

        for (var i = 0; i < this.channelSparks.length; ++i)
        {
                var channel = this.channelSparks[i];
                if (!channel)
                {
                        // subscribe event has not fired yet
                        continue;
                }

                var channelSparkData = this.getChannelSparkData(channel);

                if (channelSparkData.exclusive)
                {
                        // exclusive channel that is busy
                        continue;
                }

                if (exclusive &&
                    channelSparkData.acquired)
                {
                        // exclusive access is requested and this channel is already in use
                        continue;
                }

                if (!bestSparkChannel ||
                    channelSparkData.acquired < lowestAcquired)
                {
                        lowestAcquired = channelSparkData.acquired;
                        bestSparkChannel = channel;
                }
        }

        if (bestSparkChannel)
        {
                var bestData = this.getChannelSparkData(bestSparkChannel);
                bestData.exclusive = exclusive;
                bestData.acquired++;
                return P.resolve(bestSparkChannel).disposer(this._acquireDisposer);
        }

        return new P(function(resolve, reject)
        {
                this._acquireQueue.push({
                        resolve: resolve,
                        reject: reject,
                        exclusive: exclusive
                });
        }.bind(this)).disposer(this._acquireDisposer);
};

/**
 * Call a method on the other end (client/server). The other end must explicitly listen
 * for this method call by calling .listen() in its constructor.
 * @param {String} name Name of the method to call on the other end.
 *        The other end must listen for this method name explicitly using .listen(name)
 * @param {...*} arg Any (e)json encodable value
 * @returns {Promise} Containing the rejected error or resolved return value
 */
Resource.prototype.rpc = function(name, arg)
{
        var args = new Array(arguments.length+1);
        for (var ai = 0; ai < arguments.length; ++ai) { args[ai+1] = arguments[ai]; }

        return P.using(this.acquireChannelSparkForSending(), function(channelSpark)
        {
                args[0] = channelSpark;
                return this.channelRpc.apply(this, args);

        }.bind(this)).bind(this); // (the last bind is for the handlers of the promise)
};

/**
 * Call a method on the other end (client/server). The other end must explicitly listen
 * for this method call by calling .listen() in its constructor.
 * @param {module:primus/Spark|module:primus-multiplex/Spark} channelSpark
 * @param {String} name Name of the method to call on the other end.
 *        The other end must listen for this method name explicitly using .listen(name)
 * @param {...*} arg Any (e)json encodable value
 * @returns {Promise} Containing the rejected error or resolved return value
 */
Resource.prototype.channelRpc = function(channelSpark, name, arg)
{
        if (!this.spark)
        {
                throw Error('This resource has been instantiated without a primus spark');
        }

        var start = Resource.debugLogging && hrtime();
        var fullname = this.namespace + '/' + name;

        var args = new Array(arguments.length-2);
        for (var ai = 2; ai < arguments.length; ++ai) { args[ai-2] = arguments[ai]; }

        var channelSparkData = this.getChannelSparkData(channelSpark);

        return new P(function(resolve, reject)
        {
                if (Resource.debugLogging)
                {
                        console.log('RPC >', channelSparkData.index, channelSparkData.acquired, fullname, args);
                }

                channelSpark.send(fullname, args, function (data)
                {
                        var end = Resource.debugLogging && hrtime();
                        if (Resource.debugLogging)
                        {
                                console.log('RPC <', fullname, ':', end - start, 'ms');
                        }

                        if (data[0])
                        {
                                reject(Error('Error from server: ' + data[0]));
                        }
                        else
                        {
                                resolve(data[1]);
                        }
                });

                // todo: reject after timeout?
        }).bind(this); // (this bind is for the handlers of the promise);
};

Resource.prototype._rpcHandler = function(channelSpark, name)
{
        var channelSparkData = this.getChannelSparkData(channelSpark);

        return function(args, result)
        {
                var resultPromise;

                if (Resource.debugLogging)
                {
                        console.log('< RPC', channelSparkData.index, this.namespace, name, args);
                }
                // use P.resolve to make sure this is a bluebird promise
                // and not one from a database or orm library.

                try
                {
                        this.currentChannelData = channelSparkData.subClassData;
                        resultPromise = P.resolve(this[name].apply(this, args));
                        this.currentChannelData = null;
                }
                catch(err)
                {
                        resultPromise = P.reject(err);
                }

                resultPromise
                .catch(function(err)
                {
                        console.error('Error during RPC', err, err.stack);

                        if (result)
                        {
                                result([err.toString(), null]);
                                result = null;
                        }
                })
                .then(function(ret)
                {
                        if (result)
                        {
                                result([null, ret]);
                                result = null;
                        }
                })
                .done();
        }.bind(this);
};

/**
 * Start listening for one or more rpc calls
 * @param names The name to listen for, the method with
 *        the same name on "this" is called whenever .rpc() is invoked on the other end.
 */
Resource.prototype.listen = function(names)
{
        var spark = this.spark;
        var ns = this.namespace;

        if (!Array.isArray(names))
        {
                names = [names];
        }

        names.forEach(function(name)
        {
                var fullname = ns + '/' + name;

                if (typeof this[name] !== 'function')
                {
                        throw Error(name + ' is not a Resource method');
                }

                if (!spark) // null spark = just check if the listeners are valid
                {
                        return;
                }

                this.listenNames.push(name);

                this.channelSparks.forEach(function(channel)
                {
                        channel.on(fullname, this._rpcHandler(channel, name));
                }, this);

        }, this);
};
<|endoftext|>


<commit_before>/* jshint globalstrict:false, strict:false, unused : false */
/* global assertTrue, assertFalse, assertEqual */
// //////////////////////////////////////////////////////////////////////////////
// / @brief tests for transactions
// /
// / @file
// /
// / DISCLAIMER
// /
// / Copyright 2010-2012 triagens GmbH, Cologne, Germany
// /
// / Licensed under the Apache License, Version 2.0 (the "License")
// / you may not use this file except in compliance with the License.
// / You may obtain a copy of the License at
// /
// /     http://www.apache.org/licenses/LICENSE-2.0
// /
// / Unless required by applicable law or agreed to in writing, software
// / distributed under the License is distributed on an "AS IS" BASIS,
// / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// / See the License for the specific language governing permissions and
// / limitations under the License.
// /
// / Copyright holder is triAGENS GmbH, Cologne, Germany
// /
// / @author Jan Steemann
// / @author Copyright 2013, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////

var db = require('@arangodb').db;
var internal = require('internal');
var jsunity = require('jsunity');

function runSetup () {
  'use strict';
  internal.debugClearFailAt();

  db._drop('UnitTestsRecovery');
  var c = db._create('UnitTestsRecovery'), i;
  internal.wal.flush(true, true);
  internal.wal.properties({ throttleWait: 1000, throttleWhenPending: 1000 });

  internal.debugSetFailAt('CollectorThreadProcessQueuedOperations');
  for (i = 0; i < 10000; ++i) {
    c.save({ _key: 'test' + i, value1: 'test' + i, value2: i });
  }

  internal.wal.flush(true, false);

  // now let the write throttling become active
  internal.wait(7);
  try {
    c.save({ _key: 'foo' });
  } catch (err) {}

  internal.debugSegfault('crashing server');
}

// //////////////////////////////////////////////////////////////////////////////
// / @brief test suite
// //////////////////////////////////////////////////////////////////////////////

function recoverySuite () {
  'use strict';
  jsunity.jsUnity.attachAssertions();

  return {
    setUp: function () {},
    tearDown: function () {},

    // //////////////////////////////////////////////////////////////////////////////
    // / @brief test whether we can restore the data
    // //////////////////////////////////////////////////////////////////////////////

    testWriteThrottling: function () {
      var i, c = db._collection('UnitTestsRecovery');

      let count = c.count();
      // we either have this many or that many documents... it doesn't matter, as
      // long as _at least_ 10000 documents are there
      assertTrue(count === 10000 || count === 10001);
      for (i = 0; i < 10000; ++i) {
        var doc = c.document('test' + i);

        assertEqual('test' + i, doc.value1);
        assertEqual(i, doc.value2);
      }

      assertFalse(c.exists('foo'));
    }

  };
}

// //////////////////////////////////////////////////////////////////////////////
// / @brief executes the test suite
// //////////////////////////////////////////////////////////////////////////////

function main (argv) {
  'use strict';
  if (argv[1] === 'setup') {
    runSetup();
    return 0;
  } else {
    jsunity.run(recoverySuite);
    return jsunity.writeDone().status ? 0 : 1;
  }
}
<commit_msg>next attempt for fixing unreliable test<commit_after>/* jshint globalstrict:false, strict:false, unused : false */
/* global assertTrue, assertFalse, assertEqual */
// //////////////////////////////////////////////////////////////////////////////
// / @brief tests for transactions
// /
// / @file
// /
// / DISCLAIMER
// /
// / Copyright 2010-2012 triagens GmbH, Cologne, Germany
// /
// / Licensed under the Apache License, Version 2.0 (the "License")
// / you may not use this file except in compliance with the License.
// / You may obtain a copy of the License at
// /
// /     http://www.apache.org/licenses/LICENSE-2.0
// /
// / Unless required by applicable law or agreed to in writing, software
// / distributed under the License is distributed on an "AS IS" BASIS,
// / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// / See the License for the specific language governing permissions and
// / limitations under the License.
// /
// / Copyright holder is triAGENS GmbH, Cologne, Germany
// /
// / @author Jan Steemann
// / @author Copyright 2013, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////

var db = require('@arangodb').db;
var internal = require('internal');
var jsunity = require('jsunity');

function runSetup () {
  'use strict';
  internal.debugClearFailAt();

  db._drop('UnitTestsRecovery');
  var c = db._create('UnitTestsRecovery'), i;
  internal.wal.flush(true, true);
  internal.wal.properties({ throttleWait: 1000, throttleWhenPending: 1000 });

  internal.debugSetFailAt('CollectorThreadProcessQueuedOperations');
  for (i = 0; i < 10000; ++i) {
    c.save({ _key: 'test' + i, value1: 'test' + i, value2: i });
  }

  internal.wal.flush(true, false);

  // now let the write throttling become active
  internal.wait(7);
  try {
    c.save({ _key: 'foo' });
  } catch (err) {}

  internal.debugSegfault('crashing server');
}

// //////////////////////////////////////////////////////////////////////////////
// / @brief test suite
// //////////////////////////////////////////////////////////////////////////////

function recoverySuite () {
  'use strict';
  jsunity.jsUnity.attachAssertions();

  return {
    setUp: function () {},
    tearDown: function () {},

    // //////////////////////////////////////////////////////////////////////////////
    // / @brief test whether we can restore the data
    // //////////////////////////////////////////////////////////////////////////////

    testWriteThrottling: function () {
      var i, c = db._collection('UnitTestsRecovery');

      let count = c.count();
      // we either have this many or that many documents... it doesn't matter, as
      // long as _at least_ 10000 documents are there
      assertTrue(count === 10000 || count === 10001);
      for (i = 0; i < 10000; ++i) {
        var doc = c.document('test' + i);

        assertEqual('test' + i, doc.value1);
        assertEqual(i, doc.value2);
      }
    }

  };
}

// //////////////////////////////////////////////////////////////////////////////
// / @brief executes the test suite
// //////////////////////////////////////////////////////////////////////////////

function main (argv) {
  'use strict';
  if (argv[1] === 'setup') {
    runSetup();
    return 0;
  } else {
    jsunity.run(recoverySuite);
    return jsunity.writeDone().status ? 0 : 1;
  }
}
<|endoftext|>


<commit_before>
var jaro = require( './jaro' )

/**
 * The Jaro–Winkler distance is a measure of similarity between two strings.
 * It is a variant of the Jaro distance metric and mainly used in the area
 * of record linkage (duplicate detection).
 *
 * The higher the Jaro–Winkler distance for two strings is,
 * the more similar the strings are.
 *
 * The Jaro–Winkler distance metric is designed and best suited
 * for short strings such as person names.
 * The score is normalized such that 0 equates
 * to no similarity and 1 is an exact match.
 *
 * @param  {String} s1
 * @param  {String} s2
 * @param  {Number} p
 * @return {Number}
 */
function jaro_winkler( s1, s2, p ) {

  // `p` is a constant scaling factor for how much
  // the score is adjusted upwards for having common prefixes.
  // `p` should not exceed 0.25, otherwise the distance
  // can become larger than 1. The standard value for
  // this constant in Winkler's work is `p = 0.1`
  p = p || 0.1

  if( p > 0.25 ) {
    throw new Error( 'p should not exceed 0.25' )
  }

  // Compute the Jaro distance
  var dj = jaro( s1, s2 )

  // `l` is the length of common prefix at the start
  // of the string up to a maximum of 4 characters
  var l = 0
  var c = Math.min( s1.length, s2.length, 4 )

  for( var i = 0; i < c; i++ ) {
    if( s1[i] === s2[i] ) { l++ }
  }

  return dj + ( l * p * ( 1 - dj ))

}

module.exports = jaro_winkler
<commit_msg>Updated distance/jaro-winkler: Early loop var init<commit_after>
var jaro = require( './jaro' )

/**
 * The Jaro–Winkler distance is a measure of similarity between two strings.
 * It is a variant of the Jaro distance metric and mainly used in the area
 * of record linkage (duplicate detection).
 *
 * The higher the Jaro–Winkler distance for two strings is,
 * the more similar the strings are.
 *
 * The Jaro–Winkler distance metric is designed and best suited
 * for short strings such as person names.
 * The score is normalized such that 0 equates
 * to no similarity and 1 is an exact match.
 *
 * @param  {String} s1
 * @param  {String} s2
 * @param  {Number} p
 * @return {Number}
 */
function jaro_winkler( s1, s2, p ) {

  // `p` is a constant scaling factor for how much
  // the score is adjusted upwards for having common prefixes.
  // `p` should not exceed 0.25, otherwise the distance
  // can become larger than 1. The standard value for
  // this constant in Winkler's work is `p = 0.1`
  p = p || 0.1

  if( p > 0.25 ) {
    throw new Error( 'p should not exceed 0.25' )
  }

  // Compute the Jaro distance
  var dj = jaro( s1, s2 )

  // `l` is the length of common prefix at the start
  // of the string up to a maximum of 4 characters
  var i, l = 0
  var c = Math.min( s1.length, s2.length, 4 )

  for( i = 0; i < c; i++ ) {
    if( s1[i] === s2[i] ) { l++ }
  }

  return dj + ( l * p * ( 1 - dj ))

}

module.exports = jaro_winkler
<|endoftext|>


<commit_before>/*
=================
PlaneTarget
    Entity, that represents target, followed by camera.
=================
*/
Objects.prototype.PlaneTarget = function ( camera ) {
    if ( !(this instanceof Objects.prototype.PlaneTarget) ) {
        return new Objects.prototype.PlaneTarget( camera );
    }
    Objects.prototype.PlaneTarget.super.constructor.call( this, camera );

    this.omega = DOA.Settings.mouseSensitivity;  // radial speed
    this.dv = 0; // delta * velocity
    this.velocity = 500; // movement speed
    this.radius = 500;
    this.theta = -90;
    this.phi = 45;

    this.x = 0;
    this.y = 0;
    this.z = 0;

    this.look = function ( wx, wy ) {
        /* See http://mathworld.wolfram.com/SphericalCoordinates.html
         *    z             y
         *    |__ y  ==>    |__ x
         * x /           z /
         *   x = r * cos(theta) * sin(phi)
         *   y = r * sin(theta) * sin(phi)
         *   z = r * cos(phi)
         */
        this.theta -= wx * this.omega;
        this.theta %= 360;
        this.phi += wy * this.omega;
        this.phi = Math.max( DOA.Settings.minLook, Math.min( DOA.Settings.midLook, this.phi ) );

        camera.position.x = this.x + this.radius * Math.cos( THREE.Math.degToRad( this.theta ) )
                                                 * Math.sin( THREE.Math.degToRad( this.phi ) );
        camera.position.y = this.y + this.radius * Math.cos( THREE.Math.degToRad( this.phi ) );
        camera.position.z = this.z + this.radius * Math.sin( THREE.Math.degToRad( this.theta ) )
                                                 * Math.sin( THREE.Math.degToRad( this.phi ) );
        this.updateMesh();

        this.camera.lookAt( new THREE.Vector3( this.x, this.y, this.z ) );
    };

    this.moveTop = function () {
        this.calcDelta();
        camera.position.delta.x = -camera.position.delta.x;
        camera.position.delta.z = -camera.position.delta.z;
        this.updatePlane();
    };

    this.moveBottom = function () {
        this.calcDelta();
        this.updatePlane();
    };

    this.moveLeft = function () {
        var deg = THREE.Math.degToRad( this.theta ) + Math.PI_2;
        camera.position.delta.x = this.dv * Math.cos( deg );
        camera.position.delta.z = this.dv * Math.sin( deg );
        this.updatePlane();
    };

    this.moveRight = function () {
        var deg = THREE.Math.degToRad( this.theta ) - Math.PI_2;
        camera.position.delta.x = this.dv * Math.cos( deg );
        camera.position.delta.z = this.dv * Math.sin( deg );
        this.updatePlane();
    };

    this.calcDelta = function () {
        camera.position.delta.x = this.dv * Math.cos( THREE.Math.degToRad( this.theta ) );
        camera.position.delta.z = this.dv * Math.sin( THREE.Math.degToRad( this.theta ) );
    };

    this.updateDelta = function ( delta ) {
        this.dv = this.delta * this.velocity;
    }

    this.updateMesh = function () {
        if ( this.enabled ) {
            this.mesh.position.x = this.x;
            this.mesh.position.y = this.y;
            this.mesh.position.z = this.z;
        }
    };

    this.updatePlane = function () {
        camera.position.x += camera.position.delta.x;
        camera.position.z += camera.position.delta.z;

        this.x += camera.position.delta.x;
        this.z += camera.position.delta.z;
    };
};
extend( Objects.prototype.PlaneTarget, Objects.prototype.Target );
<commit_msg>Update PlaneTarget comments.<commit_after>/*
=================
PlaneTarget
    Entity, that represents target, followed by camera.
    Proper work with the target includes three steps:
    1. Set time delta for the animation frame;
    2. Add actions;
    3. Run animate() method. It will optimize calculations and reset all data.
    Method look() is handled separately.
=================
*/
Objects.prototype.PlaneTarget = function ( camera ) {
    if ( !(this instanceof Objects.prototype.PlaneTarget) ) {
        return new Objects.prototype.PlaneTarget( camera );
    }
    Objects.prototype.PlaneTarget.super.constructor.call( this, camera );

    var that = this; // variable for 'private' methods

    this.omega = DOA.Settings.mouseSensitivity;  // radial speed
    this.velocity = 500; // movement speed
    this.radius = 500;
    this.theta = -90;
    this.phi = 45;

    this.x = 0;
    this.y = 0;
    this.z = 0;

    var dv = 0; // delta * velocity
    var flags = 0; // binary data 1111 11 11
                   // 1 - top, 2 - bottom, 4 - left, 8 - right
                   // 16 - rotate left, 32 - rotate right
                   // 64 - tilt top, 128 - tilt bottom

    this.look = function ( wx, wy ) {
        /* See http://mathworld.wolfram.com/SphericalCoordinates.html
         *    z             y
         *    |__ y  ==>    |__ x
         * x /           z /
         *   x = r * cos(theta) * sin(phi)
         *   y = r * sin(theta) * sin(phi)
         *   z = r * cos(phi)
         */
        this.theta -= wx * this.omega;
        this.theta %= 360;
        this.phi += wy * this.omega;
        this.phi = Math.max( DOA.Settings.minLook, Math.min( DOA.Settings.midLook, this.phi ) );

        camera.position.x = this.x + this.radius * Math.cos( THREE.Math.degToRad( this.theta ) )
                                                 * Math.sin( THREE.Math.degToRad( this.phi ) );
        camera.position.y = this.y + this.radius * Math.cos( THREE.Math.degToRad( this.phi ) );
        camera.position.z = this.z + this.radius * Math.sin( THREE.Math.degToRad( this.theta ) )
                                                 * Math.sin( THREE.Math.degToRad( this.phi ) );
        this.updateMesh();

        this.camera.lookAt( new THREE.Vector3( this.x, this.y, this.z ) );
    };

    this.moveTop = function () {
        this.calcDelta();
        camera.position.delta.x = -camera.position.delta.x;
        camera.position.delta.z = -camera.position.delta.z;
        this.updatePlane();
    };

    this.moveBottom = function () {
        this.calcDelta();
        this.updatePlane();
    };

    this.moveLeft = function () {
        var deg = THREE.Math.degToRad( this.theta ) + Math.PI_2;
        camera.position.delta.x = dv * Math.cos( deg );
        camera.position.delta.z = dv * Math.sin( deg );
        this.updatePlane();
    };

    this.moveRight = function () {
        var deg = THREE.Math.degToRad( this.theta ) - Math.PI_2;
        camera.position.delta.x = dv * Math.cos( deg );
        camera.position.delta.z = dv * Math.sin( deg );
        this.updatePlane();
    };

    this.calcDelta = function () {
        camera.position.delta.x = dv * Math.cos( THREE.Math.degToRad( this.theta ) );
        camera.position.delta.z = dv * Math.sin( THREE.Math.degToRad( this.theta ) );
    };

    this.updateDelta = function ( delta ) {
        dv = this.delta * this.velocity;
    }

    this.updateMesh = function () {
        if ( this.enabled ) {
            this.mesh.position.x = this.x;
            this.mesh.position.y = this.y;
            this.mesh.position.z = this.z;
        }
    };

    this.updatePlane = function () {
        camera.position.x += camera.position.delta.x;
        camera.position.z += camera.position.delta.z;

        this.x += camera.position.delta.x;
        this.z += camera.position.delta.z;
    };
};
extend( Objects.prototype.PlaneTarget, Objects.prototype.Target );
<|endoftext|>


<commit_before>
var restify = require('restify');
var clients = require('restify/lib/clients');
var es = require('event-stream');
var fs = require('fs');
var mimeStream = require('mime-multipart-stream');
var http = require('http');
function defaultContent ( ) {
  var fileOne = es.readArray(["dummy content hello world text"]);
  var fileTwo = fs.createReadStream('./README.markdown');
  var content = {fileOne: fileOne, fileTwo: fileTwo};
  return content;
}
function testContent (T) {
  var content = defaultContent( );
  var pre = "====";
  var boundary =  pre + pre + pre + "TIDEPOOL" + "TESTBOUNDARY" + "EOF";
  var stream = mimeStream({boundary: boundary, type: 'form-data'});
  function make (name, part) {
    var o = {
      disposition: 'form-data; name="' + name + '"; filename="'+ name + '"'
    , type: 'text/plain; charset=UTF-8'
    , transferEncoding: 'quoted-printable'
    , body: part
    };
    return o;
  }
  stream.add(make('testfileOne', content.fileOne));
  stream.add(make('testfileTwo', content.fileTwo));
  function message(m) {
    var o = {
      disposition: 'form-data; name="message";'
    , type: 'x-www-form-urlencoded'
    , transferEncoding: 'quoted-printable'
    , body: es.readArray([m])
    };
    stream.add(o);
  }
  stream.message = message;
  return stream;
}
function createClient (opts) {
  var client = restify.createJsonClient(opts);
  function help (fn) {
    return client.get('/help', fn);
  }
  function status (fn) {
    return client.get('/status', fn);
  }
  function userInfo (name, fn) {
    return client.get('/users/' + name, fn);
  }
  function updateUser (name, update, fn) {
    var url = '/users/' + name;
    return client.post(url, update, fn);
  }
  function createUser (name, update, fn) {
    var params = '?name=' + update.handle;
               + '&email=' + update.email;
    var url = '/users/' + name + '/create' + params;
    return client.post(url, update, fn);
  }
  function download (url, fn) {
    console.log("DOWNLOADING", url);
    url = url.replace('http://localhost', '');
    url = url.replace('http:/localhost', '');
    console.log("URL", url);
    client.get(url, function (err, res, req, body) {
      console.log("DOWNLOADING", url, body);
      fn(err, body);
    });
  }
  function uploadContent (profile, content, fn) {
    var name = profile.handle;
    var url = '/repos/' + name + '/test/upload';
    var config = {
      'content-type': 'multipart/form-data'
    , path: url
    // , url: url
    , method: 'POST'
    };
    // options.
    // var mimes = testContent(content);
    var mimes = defaultContent(content);
    var fopts = {
      url: 'http://localhost:6776/'
    }
    var ropts = {
        method: 'POST'
      , uri: 'http://localhost/' + url
      //, uri: url
      , path: url
      // , socketPath: opts.socketPath
      // , host: 'localhost'
      // , port: 6776
      , socketPath: opts.socketPath
      // , headers: { //'content-type': 'multipart/form-data' }

    };
    /*
    var req = http.request(ropts, function up (res) {
    es.pipeline(mimes, req, es.writeArray(function (err, buffers) {
      console.log('INTER B', req);
      req.end( );
    }));
      es.pipeline(res, es.writeArray(done));
    });
    mimes.message('this is a personalized commit message');
    // mimes.pipe(req);
    // req.end( );
    req.on('error', done);
    return;
    */
    var request = require('request');
    var req = request.post(ropts, start);
    var form = req.form( );
    form.append("message", "this is my commit message");
    form.append('fileOne', mimes.fileOne, {filename: 'fileOne', knownLength: 30, contentType: 'text/plain'});
    form.append('fileTwo', mimes.fileTwo);
    function start (err, res, body) {
      console.log("UPLOADED BODY", err, body);
      fn(err, JSON.parse(body));
    }
    return;
    function done (err, result) {
      fn(err, JSON.parse(result[0]));

    }

  }
  function xxdownload (url) {

  }
  function downloadContent (content) {
  }
  client.help = help;
  client.status = status;
  client.userInfo = userInfo;
  client.createUser = createUser;
  client.updateUser = updateUser;
  client.uploadContent = uploadContent;
  client.download = download;
  return client;
}
module.exports.before = function ( ) {
}
describe("restify-git-json server", function ( ) {
  var Server = require('../server');
  var server, client;
  var opts = {
    base: './out'
  , socketPath: '/tmp/test-restify-git-json.sock'
  };
  this.profile = { };
  after(function (done) {
    server.close( );
    done( );
  });
  it('should initialize ok', function (done) {
    server = Server(opts);
    server.listen(opts.socketPath, function ( ) {
      client = createClient(opts);
      client.status(function (err, req, res, body) {
        console.log("STATUS", body);
        body.should.startWith("OK");
        done( );
      });
    });
  });
  it('should respond to help', function (done) {
    client.help(function (err, req, res, body) {
      console.log("HELP", arguments);
      body.length.should.be.above(1);
      done( );
    });
  });
  var profile;
  describe("users api", function ( ) {
    var my = { };
    this.profile = my;
    var foobarUser = { handle: 'fooTestUser'
      , user: { name: 'Foo Test User', email: 'test@tidepool.io' }
    };
    var client = createClient(opts);

    it('should create a new user', function (done) {
      testCreateUser(client, foobarUser, function (err, result) {
        my.profile = result;
        this.profile = result;
        done( );
      });
    });

    it('should not allow repeated user creation', function (done) {
      var name = my.profile.handle;
      client.createUser(name, my.profile, function (err, req, res, result) {
        console.log('REFUSAL', result);
        err.statusCode.should.equal(405);
        result.old.should.be.ok;
        done( );
      });
    });

    function validFetchUser (client, name, fn) {
      client.userInfo(client, name, function (err, req, res, body) {
        console.log("userInfo", body);
        body.should.be.ok;
        body.user.name.should.be.ok;
        my.profile = body;
        this.profile = body;
        console.log(this.profile);
        fn(err, body);
      });
    }

    it('should then update', function ( ) {
      console.log('should then update');
      testUpdateUser(done);
      function done (err, result) {
      }
    });

    it('should then upload', function (done) {
      testUploadContent(my.profile, finish);
      function finish (err, result) {
        console.log("DONE DONE", result);
        console.log("DONE ERR", err);
        result.body.should.exist;
        result.body.ref.should.exist;
        result.body.content.should.exist;
        console.log("DONE OK", result.body.head.tree);
        my.upload = result;
        done( );
      }
    });

    it('should then download content', function () {
      it('should then sync content', function (done) {
        console.log("DOWNLOAD", my.upload);
        downloadContent(my.upload, function (err, results) {
          done( );
        });
      });
    });

    it('should dereference urls', function (done) {
      var downloads;
      var urls = [ my.upload.body.head.url , my.upload.body.url ];
      downloads = walkDownload(more, finish);
      urls.forEach(downloads.write);
      downloads.end( );
      function finish (err, results) {
        done( );
      }
      function more (err, results) {
        console.log("MORE", results);
        if (results.result) {
          if (results.result.body) {
            var body = results.result.body;
            if (results.result.body && results.result.body.url) {
              downloads.write(body.url);
            }
            if (results.result.type == 'tree') {
              console.log('FOUND TREE', results, Object.keys(result.result));
              body = result.result;
            }

            var keys = Object.keys(body);
            console.log("MORE FOUND", body);
            keys.forEach(function (i, k) {
              if (body[i].url) {
                console.log("MORE URLS", body[i].url);
                downloads.write(body[i].url);
              }
            });
          }
        }
      }
    });
    function walkDownload (visit, fn) {
      // var urls = [ upload.body.head.url , upload.body.url ];
      var tr = es.through(write);
      function write(url) {
        var self = this;
        client.download(url, function (err, result) {
          var m = {err:err, url: url, result: result};
          crawl(err, m);
          self.emit('data', m);
        });
      }
      function down (url, next) {
        client.download(url, function (err, result) {
          var m = {err:err, url: url, result: result};
          crawl(err, m);
          next(null, m);
        });
      }
      function crawl (err, result) {
        console.log("CRAWL CRAWL", result);
        if (visit) {
          visit(err, result);
        }
      }
                    // es.readArray(urls),
      var stream = es.pipeline( tr, es.writeArray(done));
      function done(err, results) {
        fn(err, results);
      }
      return stream;
    }

    function downloadContent (download, fn) {

      es.pipeline(es.readArray(download.body.content)
        , es.map(fetch)
        , es.writeArray(done)
        );

      function fetch (url, next) {
        console.log("FETCH URL", url);
        url = url.replace("http:/localhost", "");
        url = url.replace("http://localhost", "");
        console.log("FETCH URL", url);
        client.get(url, function (err, req, res, body) {
          // console.log("FETCH FETCH", arguments);
          res.body.should.be.ok;
          next(null, res.body);
        });
      }

      function done (err, results) {
        download.downloaded = results;
        fn(err, results);
      }
    }

    function testUpdateUser (finish) {
      console.log("XXXXX");
      // it('should update user', function (done) {
        console.log("PROFILE FOR UPDATE", my.profile, this.profile);
        var update = JSON.parse(JSON.stringify(my.profile));
        var author = { name: "Bar Update", email: "updated@tidepool.io" };
        update.user.user = author;
        update.user.author = author;
        update.user.data = { custom: 'property' };
        update.user.user = JSON.parse(JSON.stringify(update.user))
        name = update.name;
        client.updateUser(name, update.user, function (err, req, res, result) {
          // console.log("UPDATED", result);
          result.name.should.equal(name);
          result.user.name.should.equal(update.user.name)
          result.user.data.should.be.ok;
          result.user.data.custom.should.equal(update.user.data.custom);
          if (finish) { finish(result); }
          // done( );
        });
      // });
    }

    function testUploadContent (profile, fn) {
    // describe("uploaded content", function ( ) {
        console.log("YYYY");
        // it('user should be able to upload content into git', function ( ) {
        client.uploadContent(profile, 'test', function (err, results) {
          console.log("UPLOADED", results);
          fn(err, results);
        });
        //});
    // });
    }

    it('should 404 non-existent users', function (done) {
      client.userInfo('xx-no-exist', function (err, req, res, body) {
        // console.log("404 ERR", 'error', err, 'body', body);
        // console.log("404 REQ", req);
        // console.log("404 RES", res);
        // body.should.be.ok;
        err.statusCode.should.equal(404);
        done( );
      });
    });
    describe("user creation REST api", function ( ) {
      var update = { };
      var client = createClient(opts);
      testCreateUser(client, null, function (err, result) {
        result.should.be.ok;
        // done( );
      });
    });
  });

});
function testCreateUser (client, update, fn) {
  update = update || ({ handle: 'testUser'
    , user: { name: 'Test User', email: 'test@tidepool.io' }
  });
  var left = 2;
  var R = { };
  function finish (err, result) {
    if (--left == 0) {
      console.log('LEFT', left, R);
      fn(R.err, R.result);
    }
  }
  // describe("user creation REST api", function ( ) {
    // it('should create a user', function (done) {
      var name = update.handle;
      client.createUser(name, update, function (err, req, res, result) {
        console.log('CREATED', result);
        result.handle.should.equal(name);
        result.user.name.should.equal(update.user.name);
        result.user.email.should.equal(update.user.email);
        result.should.be.ok;
        R.err = err;
        R.result = result;
        fn(err, result);
        // after( );
        // finish(err, result);
        // done( );
      });
    // });
    function after ( ) {
    describe("repeated creation", function ( ) {
    it('should not allow repeated user creation', function (done) {
      var name = my.profile.handle;
      client.createUser(name, update, function (err, req, res, result) {
        console.log('REFUSAL', result);
        err.statusCode.should.equal(405);
        result.old.should.be.ok;
        // fn(err, result);
        // finish(err, result);
      });
      done( );
    });
    });
    }
  // });
}
<commit_msg>increase test coverage by adding list of urls to fetch<commit_after>
var restify = require('restify');
var clients = require('restify/lib/clients');
var es = require('event-stream');
var fs = require('fs');
var mimeStream = require('mime-multipart-stream');
var http = require('http');
function defaultContent ( ) {
  var fileOne = es.readArray(["dummy content hello world text"]);
  var fileTwo = fs.createReadStream('./README.markdown');
  var content = {fileOne: fileOne, fileTwo: fileTwo};
  return content;
}
function testContent (T) {
  var content = defaultContent( );
  var pre = "====";
  var boundary =  pre + pre + pre + "TIDEPOOL" + "TESTBOUNDARY" + "EOF";
  var stream = mimeStream({boundary: boundary, type: 'form-data'});
  function make (name, part) {
    var o = {
      disposition: 'form-data; name="' + name + '"; filename="'+ name + '"'
    , type: 'text/plain; charset=UTF-8'
    , transferEncoding: 'quoted-printable'
    , body: part
    };
    return o;
  }
  stream.add(make('testfileOne', content.fileOne));
  stream.add(make('testfileTwo', content.fileTwo));
  function message(m) {
    var o = {
      disposition: 'form-data; name="message";'
    , type: 'x-www-form-urlencoded'
    , transferEncoding: 'quoted-printable'
    , body: es.readArray([m])
    };
    stream.add(o);
  }
  stream.message = message;
  return stream;
}
function createClient (opts) {
  var client = restify.createJsonClient(opts);
  function help (fn) {
    return client.get('/help', fn);
  }
  function status (fn) {
    return client.get('/status', fn);
  }
  function userInfo (name, fn) {
    return client.get('/users/' + name, fn);
  }
  function updateUser (name, update, fn) {
    var url = '/users/' + name;
    return client.post(url, update, fn);
  }
  function createUser (name, update, fn) {
    var params = '?name=' + update.handle;
               + '&email=' + update.email;
    var url = '/users/' + name + '/create' + params;
    return client.post(url, update, fn);
  }
  function download (url, fn) {
    console.log("DOWNLOADING", url);
    url = url.replace('http://localhost', '');
    url = url.replace('http:/localhost', '');
    console.log("URL", url);
    client.get(url, function (err, res, req, body) {
      console.log("DOWNLOADING", url, body);
      fn(err, body);
    });
  }
  function uploadContent (profile, content, fn) {
    var name = profile.handle;
    var url = '/repos/' + name + '/test/upload';
    var config = {
      'content-type': 'multipart/form-data'
    , path: url
    // , url: url
    , method: 'POST'
    };
    // options.
    // var mimes = testContent(content);
    var mimes = defaultContent(content);
    var fopts = {
      url: 'http://localhost:6776/'
    }
    var ropts = {
        method: 'POST'
      , uri: 'http://localhost/' + url
      //, uri: url
      , path: url
      // , socketPath: opts.socketPath
      // , host: 'localhost'
      // , port: 6776
      , socketPath: opts.socketPath
      // , headers: { //'content-type': 'multipart/form-data' }

    };
    /*
    var req = http.request(ropts, function up (res) {
    es.pipeline(mimes, req, es.writeArray(function (err, buffers) {
      console.log('INTER B', req);
      req.end( );
    }));
      es.pipeline(res, es.writeArray(done));
    });
    mimes.message('this is a personalized commit message');
    // mimes.pipe(req);
    // req.end( );
    req.on('error', done);
    return;
    */
    var request = require('request');
    var req = request.post(ropts, start);
    var form = req.form( );
    form.append("message", "this is my commit message");
    form.append('fileOne', mimes.fileOne, {filename: 'fileOne', knownLength: 30, contentType: 'text/plain'});
    form.append('fileTwo', mimes.fileTwo);
    function start (err, res, body) {
      console.log("UPLOADED BODY", err, body);
      fn(err, JSON.parse(body));
    }
    return;
    function done (err, result) {
      fn(err, JSON.parse(result[0]));

    }

  }
  function xxdownload (url) {

  }
  function downloadContent (content) {
  }
  client.help = help;
  client.status = status;
  client.userInfo = userInfo;
  client.createUser = createUser;
  client.updateUser = updateUser;
  client.uploadContent = uploadContent;
  client.download = download;
  return client;
}
module.exports.before = function ( ) {
}
describe("restify-git-json server", function ( ) {
  var Server = require('../server');
  var server, client;
  var opts = {
    base: './out'
  , socketPath: '/tmp/test-restify-git-json.sock'
  };
  this.profile = { };
  after(function (done) {
    server.close( );
    done( );
  });
  it('should initialize ok', function (done) {
    server = Server(opts);
    server.listen(opts.socketPath, function ( ) {
      client = createClient(opts);
      client.status(function (err, req, res, body) {
        console.log("STATUS", body);
        body.should.startWith("OK");
        done( );
      });
    });
  });
  it('should respond to help', function (done) {
    client.help(function (err, req, res, body) {
      console.log("HELP", arguments);
      body.length.should.be.above(1);
      done( );
    });
  });
  var profile;
  describe("users api", function ( ) {
    var my = { };
    this.profile = my;
    var foobarUser = { handle: 'fooTestUser'
      , user: { name: 'Foo Test User', email: 'test@tidepool.io' }
    };
    var client = createClient(opts);

    it('should create a new user', function (done) {
      testCreateUser(client, foobarUser, function (err, result) {
        my.profile = result;
        this.profile = result;
        done( );
      });
    });

    it('should not allow repeated user creation', function (done) {
      var name = my.profile.handle;
      client.createUser(name, my.profile, function (err, req, res, result) {
        console.log('REFUSAL', result);
        err.statusCode.should.equal(405);
        result.old.should.be.ok;
        done( );
      });
    });

    function validFetchUser (client, name, fn) {
      client.userInfo(client, name, function (err, req, res, body) {
        console.log("userInfo", body);
        body.should.be.ok;
        body.user.name.should.be.ok;
        my.profile = body;
        this.profile = body;
        console.log(this.profile);
        fn(err, body);
      });
    }

    it('should then update', function ( ) {
      console.log('should then update');
      testUpdateUser(done);
      function done (err, result) {
      }
    });

    it('should then upload', function (done) {
      testUploadContent(my.profile, finish);
      function finish (err, result) {
        console.log("DONE DONE", result);
        console.log("DONE ERR", err);
        result.body.should.exist;
        result.body.ref.should.exist;
        result.body.content.should.exist;
        console.log("DONE OK", result.body.head.tree);
        my.upload = result;
        done( );
      }
    });

    it('should then download content', function (done) {
        console.log("DOWNLOAD", my.upload);
        downloadContent(my.upload, function (err, results) {
          done( );
        });
    });

    it('should dereference urls', function (done) {
      var downloads;
      var urls = [ my.upload.body.head.url , my.upload.body.url ];
      urls.push(['/repos', my.profile.handle + 'xxx', 'create'].join('/'));
      urls.push(['/repos', my.profile.handle, 'test/git/refs'].join('/'));
      urls.push(['/repos', my.profile.handle, 'test/git/refs/'].join('/'));
      urls.push(['/repos', my.profile.handle, '/test'].join('/'));
      urls.push(['/repos', my.profile.handle].join('/'));
      downloads = walkDownload(more, finish);
      urls.forEach(downloads.write);
      downloads.end( );
      function finish (err, results) {
        done( );
      }
      function more (err, results) {
        console.log("MORE", results);
        if (results.result) {
          if (results.result.body) {
            var body = results.result.body;
            if (results.result.body && results.result.body.url) {
              downloads.write(body.url);
            }
            if (results.result.type == 'tree') {
              console.log('FOUND TREE', results, Object.keys(result.result));
              body = result.result;
            }

            var keys = Object.keys(body);
            console.log("MORE FOUND", body);
            keys.forEach(function (i, k) {
              if (body[i].url) {
                console.log("MORE URLS", body[i].url);
                downloads.write(body[i].url);
              }
            });
          }
        }
      }
    });
    function walkDownload (visit, fn) {
      // var urls = [ upload.body.head.url , upload.body.url ];
      var tr = es.through(write);
      function write(url) {
        var self = this;
        client.download(url, function (err, result) {
          var m = {err:err, url: url, result: result};
          crawl(err, m);
          self.emit('data', m);
        });
      }
      function down (url, next) {
        client.download(url, function (err, result) {
          var m = {err:err, url: url, result: result};
          crawl(err, m);
          next(null, m);
        });
      }
      function crawl (err, result) {
        console.log("CRAWL CRAWL", result);
        if (visit) {
          visit(err, result);
        }
      }
                    // es.readArray(urls),
      var stream = es.pipeline( tr, es.writeArray(done));
      function done(err, results) {
        fn(err, results);
      }
      return stream;
    }

    function downloadContent (download, fn) {

      es.pipeline(es.readArray(download.body.content)
        , es.map(fetch)
        , es.writeArray(done)
        );

      function fetch (url, next) {
        console.log("FETCH URL", url);
        url = url.replace("http:/localhost", "");
        url = url.replace("http://localhost", "");
        console.log("FETCH URL", url);
        client.get(url, function (err, req, res, body) {
          // console.log("FETCH FETCH", arguments);
          res.body.should.be.ok;
          next(null, res.body);
        });
      }

      function done (err, results) {
        download.downloaded = results;
        fn(err, results);
      }
    }

    function testUpdateUser (finish) {
      console.log("XXXXX");
      // it('should update user', function (done) {
        console.log("PROFILE FOR UPDATE", my.profile, this.profile);
        var update = JSON.parse(JSON.stringify(my.profile));
        var author = { name: "Bar Update", email: "updated@tidepool.io" };
        update.user.user = author;
        update.user.author = author;
        update.user.data = { custom: 'property' };
        update.user.user = JSON.parse(JSON.stringify(update.user))
        name = update.name;
        client.updateUser(name, update.user, function (err, req, res, result) {
          // console.log("UPDATED", result);
          result.name.should.equal(name);
          result.user.name.should.equal(update.user.name)
          result.user.data.should.be.ok;
          result.user.data.custom.should.equal(update.user.data.custom);
          if (finish) { finish(result); }
          // done( );
        });
      // });
    }

    function testUploadContent (profile, fn) {
    // describe("uploaded content", function ( ) {
        console.log("YYYY");
        // it('user should be able to upload content into git', function ( ) {
        client.uploadContent(profile, 'test', function (err, results) {
          console.log("UPLOADED", results);
          fn(err, results);
        });
        //});
    // });
    }

    it('should 404 non-existent users', function (done) {
      client.userInfo('xx-no-exist', function (err, req, res, body) {
        // console.log("404 ERR", 'error', err, 'body', body);
        // console.log("404 REQ", req);
        // console.log("404 RES", res);
        // body.should.be.ok;
        err.statusCode.should.equal(404);
        done( );
      });
    });
    describe("user creation REST api", function ( ) {
      var update = { };
      var client = createClient(opts);
      testCreateUser(client, null, function (err, result) {
        result.should.be.ok;
        // done( );
      });
    });
  });

});
function testCreateUser (client, update, fn) {
  update = update || ({ handle: 'testUser'
    , user: { name: 'Test User', email: 'test@tidepool.io' }
  });
  var left = 2;
  var R = { };
  function finish (err, result) {
    if (--left == 0) {
      console.log('LEFT', left, R);
      fn(R.err, R.result);
    }
  }
  // describe("user creation REST api", function ( ) {
    // it('should create a user', function (done) {
      var name = update.handle;
      client.createUser(name, update, function (err, req, res, result) {
        console.log('CREATED', result);
        result.handle.should.equal(name);
        result.user.name.should.equal(update.user.name);
        result.user.email.should.equal(update.user.email);
        result.should.be.ok;
        R.err = err;
        R.result = result;
        fn(err, result);
        // after( );
        // finish(err, result);
        // done( );
      });
    // });
    function after ( ) {
    describe("repeated creation", function ( ) {
    it('should not allow repeated user creation', function (done) {
      var name = my.profile.handle;
      client.createUser(name, update, function (err, req, res, result) {
        console.log('REFUSAL', result);
        err.statusCode.should.equal(405);
        result.old.should.be.ok;
        // fn(err, result);
        // finish(err, result);
      });
      done( );
    });
    });
    }
  // });
}
<|endoftext|>


<commit_before>var Value = require('basis.data').Value;
var Popup = require('basis.ui.popup').Popup;
var getColoredSource = require('./remote.js').getRemoteMethod('getColoredSource');
var sourceLoc = new Value();
var source = new Value({ value: '' });

sourceLoc.as(function(loc) {
  if (loc && getColoredSource.available) {
    getColoredSource(loc, function(result) {
      if (loc === sourceLoc.value) {
        source.set(result);
        popup.realign();
      }
    });
  }

  source.set('');
});

var popup = new Popup({
  loc: sourceLoc,

  dir: 'top left bottom left',
  autorotate: [
    'bottom left top left',
    'top right top left'
  ],
  template: resource('./template/js-source-popup.tmpl'),
  binding: {
    isOpenFileSupported: basis.fn.$const(true), // FIXME: use real value
    loc: sourceLoc.as(function(loc) {
      return (loc || '').replace(/(:\d+){1,4}$/, '');
    }),
    source: source
  },

  setZIndex: function() {
    this.element.style.zIndex = 65000;
  }
});

source.link(popup, function(source) {
  if (source) {
    this.show();
  } else {
    this.hide();
  }
});

module.exports = popup;
<commit_msg>fix popup alignment<commit_after>var Value = require('basis.data').Value;
var Popup = require('basis.ui.popup').Popup;
var getColoredSource = require('./remote.js').getRemoteMethod('getColoredSource');
var sourceLoc = new Value();
var source = new Value({ value: '' });

sourceLoc.as(function(loc) {
  if (loc && getColoredSource.available) {
    getColoredSource(loc, function(result) {
      if (loc === sourceLoc.value) {
        source.set(result);
        popup.realign();
      }
    });
  }

  source.set('');
});

var popup = new Popup({
  loc: sourceLoc,

  dir: 'top left bottom left',
  autorotate: [
    'bottom left top left'
  ],
  template: resource('./template/js-source-popup.tmpl'),
  binding: {
    isOpenFileSupported: basis.fn.$const(true), // FIXME: use real value
    loc: sourceLoc.as(function(loc) {
      return (loc || '').replace(/(:\d+){1,4}$/, '');
    }),
    source: source
  },

  setZIndex: function() {
    this.element.style.zIndex = 65000;
  }
});

source.link(popup, function(source) {
  if (source) {
    this.show();
  } else {
    this.hide();
  }
});

module.exports = popup;
<|endoftext|>