<commit_before>(function (window, $, undefined) {
  'use strict';
  var Capestatus;
  Capestatus = function Capestatus(cockpit) {
    var self = this;
    console.log('Loading Capestatus plugin in the browser.');
    // Instance variables
    self.cockpit = cockpit;
    self.lastPing = null;

    self.bindingModel = {
      cockpit: self.cockpit,
      theLocaltime: ko.observable("localtime"),
      formattedRunTime: ko.observable('runtime'),
      currentCpuUsage: ko.observable(''),
      currentVoltage: ko.observable(0),
      currentCurrent: ko.observable(''),
      isConnected: ko.observable(false),
      brightnessLevel: ko.observable('level0'),
      servoAngle: ko.observable(0),
      batteryLevel: self.batteryLevel
    };

    // Add required UI elements
    var jsFileLocation = urlOfJsFile('capestatus.js');
    $('body').append('

')
    $('#capestatus-templates').load(jsFileLocation + '../ui-templates.html', function () {
      $('#footercontent').prepend('

');
      ko.applyBindings(self.bindingModel, document.getElementById('capestatus_footercontent'));

      // these don't belong here IMHO as the rovPilot controls them
      $('#servoTilt').attr("data-bind", "template: { name: 'template_capestatus_servotilt' }");
      $('#navtoolbar').append('

');
      ko.applyBindings(self.bindingModel, document.getElementById('brightnessIndicator'));
      ko.applyBindings(self.bindingModel, document.getElementById('servoTilt'));

    });

    // Register the various event handlers
    self.listen();
    setInterval(function () {
      self.updateConnectionStatus();
      self.bindingModel.theLocaltime(new Date().toLocaleTimeString());
    }, 1000);

  };
  //This pattern will hook events in the cockpit and pull them all back
  //so that the reference to this instance is available for further processing
  Capestatus.prototype.listen = function listen() {
    var capes = this;
    this.cockpit.socket.on('status', function (data) {
      capes.UpdateStatusIndicators(data);
    });
  };
  Capestatus.prototype.batteryLevel = function batteryLevel(voltage) {
    if (voltage < 9)
      return 'level1';
    if (voltage < 10)
      return 'level2';
    if (voltage < 10.5)
      return 'level3';
    if (voltage < 11.5)
      return 'level4';
    return 'level5';
  };
  Capestatus.prototype.UpdateStatusIndicators = function UpdateStatusIndicators(data) {
    var self = this;
    if ('time' in data) {
      self.bindingModel.formattedRunTime(msToTime(data.time));
    }

    if ('vout' in data) {
      self.bindingModel.currentVoltage(data.vout.toFixed(1));
    }

    if ('iout' in data)
      self.bindingModel.currentCurrent(data.iout.toFixed(3) + 'A');

    if ('servo' in data) {
      var angle = 90 / 500 * data.servo * -1 - 90;
      self.bindingModel.servoAngle(angle);
      console.log('servo angle: ' + angle);
    }

    if ('cpuUsage' in data)
      self.bindingModel.currentCpuUsage((data.cpuUsage * 100).toFixed(0) + '%');

    if ('LIGP' in data)
      self.bindingModel.brightnessLevel('level' + Math.ceil(data.LIGP * 10));

    this.lastPing = new Date();
  };
  Capestatus.prototype.updateConnectionStatus = function () {
    var self = this;
    var now = new Date();
    var delay = now - this.lastPing;

    self.bindingModel.isConnected(delay <= 3000);
  };
  window.Cockpit.plugins.push(Capestatus);

}(window, jQuery));<commit_msg>Cleanup<commit_after>(function (window, $, undefined) {
  'use strict';
  var Capestatus;
  Capestatus = function Capestatus(cockpit) {
    var self = this;
    console.log('Loading Capestatus plugin in the browser.');
    self.cockpit = cockpit;
    self.lastPing = null;

    self.bindingModel = {
      cockpit: self.cockpit,
      theLocaltime: ko.observable("localtime"),
      formattedRunTime: ko.observable('runtime'),
      currentCpuUsage: ko.observable(''),
      currentVoltage: ko.observable(0),
      currentCurrent: ko.observable(''),
      isConnected: ko.observable(false),
      brightnessLevel: ko.observable('level0'),
      servoAngle: ko.observable(0),
      batteryLevel: self.batteryLevel
    };

    // Add required UI elements
    var jsFileLocation = urlOfJsFile('capestatus.js');
    $('body').append('

');
    $('#capestatus-templates').load(jsFileLocation + '../ui-templates.html', function () {
      $('#footercontent').prepend('

');
      ko.applyBindings(self.bindingModel, document.getElementById('capestatus_footercontent'));

      // these don't belong here IMHO as the rovPilot controls them
      $('#servoTilt').attr("data-bind", "template: { name: 'template_capestatus_servotilt' }");
      $('#navtoolbar').append('

');
      ko.applyBindings(self.bindingModel, document.getElementById('brightnessIndicator'));
      ko.applyBindings(self.bindingModel, document.getElementById('servoTilt'));
    });

    // Register the various event handlers
    self.listen();
    setInterval(function () {
      self.updateConnectionStatus();
      self.bindingModel.theLocaltime(new Date().toLocaleTimeString());
    }, 1000);

  };
  //This pattern will hook events in the cockpit and pull them all back
  //so that the reference to this instance is available for further processing
  Capestatus.prototype.listen = function listen() {
    var capes = this;
    this.cockpit.socket.on('status', function (data) {
      capes.UpdateStatusIndicators(data);
    });
  };
  Capestatus.prototype.batteryLevel = function batteryLevel(voltage) {
    if (voltage < 9)
      return 'level1';
    if (voltage < 10)
      return 'level2';
    if (voltage < 10.5)
      return 'level3';
    if (voltage < 11.5)
      return 'level4';
    return 'level5';
  };
  Capestatus.prototype.UpdateStatusIndicators = function UpdateStatusIndicators(data) {
    var self = this;
    if ('time' in data) {
      self.bindingModel.formattedRunTime(msToTime(data.time));
    }

    if ('vout' in data) {
      self.bindingModel.currentVoltage(data.vout.toFixed(1));
    }

    if ('iout' in data)
      self.bindingModel.currentCurrent(data.iout.toFixed(3) + 'A');

    if ('servo' in data) {
      var angle = 90 / 500 * data.servo * -1 - 90;
      self.bindingModel.servoAngle(angle);
      console.log('servo angle: ' + angle);
    }

    if ('cpuUsage' in data)
      self.bindingModel.currentCpuUsage((data.cpuUsage * 100).toFixed(0) + '%');

    if ('LIGP' in data)
      self.bindingModel.brightnessLevel('level' + Math.ceil(data.LIGP * 10));

    this.lastPing = new Date();
  };
  Capestatus.prototype.updateConnectionStatus = function () {
    var self = this;
    var now = new Date();
    var delay = now - this.lastPing;

    self.bindingModel.isConnected(delay <= 3000);
  };
  window.Cockpit.plugins.push(Capestatus);

}(window, jQuery));<|endoftext|>


<commit_before>'use strict';

const sinon = require('sinon');
const assert = require('assert');
const mongodb = require('mongodb');
const features = require('../src');

const runFetchToMongoTask = features.runFetchToMongoTask;
const MockServer = require('./utils/mockServer');

describe('runFetchToMongoTask', function () {

    let collection;
    let mockServer = null;

    const wait = time => new Promise((resolve) => {
        setTimeout(resolve, time);
    });

    before(function (done) {
        return mongodb.connect('mongodb://127.0.0.1:27017/featuresJsTests', null, (err, db) => {
            collection = db.collection('featuresCollection');
            mockServer = new MockServer(5000, done);
        });
    });

    beforeEach(function () {
        return collection.remove();
    });

    afterEach((done) => {
        mockServer.reset(done);
    });

    after((done) => {
        mockServer.close(done);
    });

    it('should run task properly, fetch data and store them into DB', function () {

        const sourceUrl = 'http://localhost:5000';
        const sourcePath = '/api/features';
        const taskOptions = { sourceUrl: sourceUrl + sourcePath, collection, lifetime: 1 };
        let taskStopObject = null;
        let featureService = null;

        const definitionChange = sinon.spy();

        mockServer.handleNext(sourcePath, (req, res) => {
            res.json({ feature1: true });
        });

        return runFetchToMongoTask(taskOptions)
            .then((stopObject) => {
                taskStopObject = stopObject;
                return wait(100);
            })
            .then(() => taskStopObject.stopFetchToMongoTask())
            .then(() => {

                featureService = new features.Features({
                    provider: features.mongoProviderFactory(collection),
                    onDefinitionsChange: definitionChange
                });

                return featureService.getReadyPromise();
            })
            .then(() => {
                assert(featureService.enabled('feature1', '58dab243332f920e00b6cd17') === true, 'Feature should be true when document is loaded by task and service is initialized.');
                assert(definitionChange.called);
            });
    });

    it('should run task properly, fetch data from multiple urls and store them into DB', function () {

        const sourcePath = '/api/features';
        const sourceUrls = () => Promise.resolve({
            null: `http://localhost:5000${sourcePath}`,
            a1: `http://localhost:5000${sourcePath}?a=1`,
            a2: `http://localhost:5000${sourcePath}?a=2`
        });
        const taskOptions = { sourceUrl: sourceUrls, collection, lifetime: 1 };
        let taskStopObject = null;
        let featureService = null;

        const definitionChange = sinon.spy();

        mockServer
            .handleNext(sourcePath, (req, res) => {
                // todo check the query
                res.json({
                    nullFeature: true,
                    a1Feature: false,
                    a2Feature: false
                });
            })
            .handleNext(sourcePath, (req, res) => {
                // todo check the query
                res.json({
                    nullFeature: false,
                    a1Feature: true,
                    a2Feature: false
                });
            })
            .handleNext(sourcePath, (req, res) => {
                // todo check the query
                res.json({
                    nullFeature: false,
                    a1Feature: false,
                    a2Feature: true
                });
            });

        return runFetchToMongoTask(taskOptions)
            .then((stopObject) => {
                taskStopObject = stopObject;
                return wait(100);
            })
            .then(() => taskStopObject.stopFetchToMongoTask())
            .then(() => {

                featureService = new features.Features({
                    provider: features.mongoProviderFactory(collection),
                    onDefinitionsChange: definitionChange
                });

                return featureService.getReadyPromise();
            })
            .then(() => {
                assert.equal(featureService.enabled('nullFeature'), true);
                assert.equal(featureService.enabled('a1Feature'), false);
                assert.equal(featureService.enabled('a2Feature'), false);
                assert.equal(featureService.enabled('nullFeature', 'a1'), false);
                assert.equal(featureService.enabled('a1Feature', 'a1'), true);
                assert.equal(featureService.enabled('a2Feature', 'a1'), false);
                assert.equal(featureService.enabled('nullFeature', 'a2'), false);
                assert.equal(featureService.enabled('a1Feature', 'a2'), false);
                assert.equal(featureService.enabled('a2Feature', 'a2'), true);

                assert(definitionChange.called);
            });
    });
});
<commit_msg>fixed tests<commit_after>'use strict';

const sinon = require('sinon');
const assert = require('assert');
const mongodb = require('mongodb');
const features = require('../src');

const runFetchToMongoTask = features.runFetchToMongoTask;
const MockServer = require('./utils/mockServer');

describe('runFetchToMongoTask', function () {

    let collection;
    let mockServer = null;

    const wait = time => new Promise((resolve) => {
        setTimeout(resolve, time);
    });

    before(function (done) {
        return mongodb.connect('mongodb://127.0.0.1:27017/featuresJsTests', null, (err, db) => {
            collection = db.collection('featuresCollection');
            mockServer = new MockServer(5000, done);
        });
    });

    beforeEach(function () {
        return collection.remove();
    });

    afterEach((done) => {
        mockServer.reset(done);
    });

    after((done) => {
        mockServer.close(done);
    });

    it('should run task properly, fetch data and store them into DB', function () {

        const sourceUrl = 'http://localhost:5000';
        const sourcePath = '/api/features';
        const taskOptions = { sourceUrl: sourceUrl + sourcePath, collection, lifetime: 1 };
        let taskStopObject = null;
        let featureService = null;

        const definitionChange = sinon.spy();

        mockServer.handleNext(sourcePath, (req, res) => {
            res.json({ feature1: true });
        });

        return runFetchToMongoTask(taskOptions)
            .then((stopObject) => {
                taskStopObject = stopObject;
                return wait(100);
            })
            .then(() => taskStopObject.stopFetchToMongoTask())
            .then(() => {

                featureService = new features.Features({
                    provider: features.mongoProviderFactory(collection),
                    onDefinitionsChange: definitionChange
                });

                return featureService.getReadyPromise();
            })
            .then(() => {
                assert(featureService.enabled('feature1', '58dab243332f920e00b6cd17') === true, 'Feature should be true when document is loaded by task and service is initialized.');
                assert(definitionChange.called);
            });
    });

    it('should run task properly, fetch data from multiple urls and store them into DB', function () {

        const sourcePath = '/api/features';
        const sourceUrls = () => Promise.resolve({
            null: `http://localhost:5000${sourcePath}`,
            a1: `http://localhost:5000${sourcePath}?a=1`,
            a2: `http://localhost:5000${sourcePath}?a=2`
        });
        const taskOptions = { sourceUrl: sourceUrls, collection, lifetime: -100 };
        let taskStopObject = null;
        let featureService = null;

        const definitionChange = sinon.spy();

        mockServer
            .handleNext(sourcePath, (req, res) => {
                // todo check the query
                res.json({
                    nullFeature: true,
                    a1Feature: false,
                    a2Feature: false
                });
            })
            .handleNext(sourcePath, (req, res) => {
                // todo check the query
                res.json({
                    nullFeature: false,
                    a1Feature: true,
                    a2Feature: false
                });
            })
            .handleNext(sourcePath, (req, res) => {
                // todo check the query
                res.json({
                    nullFeature: false,
                    a1Feature: false,
                    a2Feature: true
                });
            });

        return runFetchToMongoTask(taskOptions)
            .then((stopObject) => {
                taskStopObject = stopObject;
                return wait(100);
            })
            .then(() => taskStopObject.stopFetchToMongoTask())
            .then(() => {

                featureService = new features.Features({
                    provider: features.mongoProviderFactory(collection),
                    onDefinitionsChange: definitionChange
                });

                return featureService.getReadyPromise();
            })
            .then(() => {
                assert.equal(featureService.enabled('nullFeature'), true);
                assert.equal(featureService.enabled('a1Feature'), false);
                assert.equal(featureService.enabled('a2Feature'), false);
                assert.equal(featureService.enabled('nullFeature', 'a1'), false);
                assert.equal(featureService.enabled('a1Feature', 'a1'), true);
                assert.equal(featureService.enabled('a2Feature', 'a1'), false);
                assert.equal(featureService.enabled('nullFeature', 'a2'), false);
                assert.equal(featureService.enabled('a1Feature', 'a2'), false);
                assert.equal(featureService.enabled('a2Feature', 'a2'), true);

                assert(definitionChange.called);
            });
    });
});
<|endoftext|>


<commit_before>import $ from 'jquery';

function BaseApp(zafClient) {
  this.zafClient = zafClient;
  this.bindEvents();

  var onCreated = this.events['app.created'];
  if (onCreated) {
    (_.isFunction(onCreated) ? onCreated : this[onCreated]).call(this);
  }
}

function resolveHandler(app, name) {
  var handler = app.events[name];
  return handler ? (_.isFunction(handler) ? handler.bind(app) : app[handler].bind(app)) : function() {};
}

BaseApp.prototype = {
  // These are public APIs of the framework that we are shimming to make it
  // easier to migrate existing apps
  events: {},
  requests: {},

  bindEvents: function() {
    _.each(this.events, function(func, key) {
      var splitted_key = key.split(' '),
          event = splitted_key[0],
          element = splitted_key[1],
          isDomEvent = !!element;

      func = resolveHandler(this, key);

      if (isDomEvent) {
        this.$(document).on(event, element, func);
      } else {
        this.zafClient.on(event, func);
      }
    }.bind(this));
  },

  ajax: function(name) {
    var req = this.requests[name],
        doneCallback = resolveHandler(this, name + '.done'),
        failCallback = resolveHandler(this, name + '.fail'),
        alwaysCallback = resolveHandler(this, name + '.always'),
        options = _.isFunction(req) ? req.apply(this, Array.prototype.slice.call(arguments, 1)) : req;

    return this.zafClient.request(options)
                         .then(doneCallback, failCallback)
                         .then(alwaysCallback, alwaysCallback);
  },

  renderTemplate: function(name, data) {
    var template = require(`../templates/${name}.hdbs`);
    return template(data);
  },

  switchTo: function(name, data) {
    this.$('[data-main]').html(this.renderTemplate(name, data));
  },

  $: function() {
    return $.apply($, arguments);
  }
}

export default BaseApp;
<commit_msg>moved some code around<commit_after>import $ from 'jquery';

function noop() {}

function resolveHandler(app, name) {
  var handler = app.events[name];
  if (!handler) { return noop; }
  return _.isFunction(handler) ? handler.bind(app) : app[handler].bind(app);
}

function bindEvents(app) {
  _.each(app.events, function(fn, key) {
    var splittedKey = key.split(' '),
        event = splittedKey[0],
        element = splittedKey[1],
        isDomEvent = !!element,
        func = resolveHandler(app, key);

    if (isDomEvent) {
      $(document).on(event, element, func);
    } else {
      app.zafClient.on(event, func);
    }
  }.bind(app));
}

function BaseApp(zafClient) {
  this.zafClient = zafClient;
  this.bindEvents();

  var onCreated = resolveHandler(this, 'app.created');
  onCreated();
}

BaseApp.prototype = {
  // These are public APIs of the framework that we are shimming to make it
  // easier to migrate existing apps
  events: {},
  requests: {},

  bindEvents: function() {
    bindEvents(this);
  },

  ajax: function(name) {
    var req = this.requests[name],
        doneCallback = resolveHandler(this, name + '.done'),
        failCallback = resolveHandler(this, name + '.fail'),
        alwaysCallback = resolveHandler(this, name + '.always'),
        options = _.isFunction(req) ? req.apply(this, Array.prototype.slice.call(arguments, 1)) : req;

    return this.zafClient.request(options)
                         .then(doneCallback, failCallback)
                         .then(alwaysCallback, alwaysCallback);
  },

  renderTemplate: function(name, data) {
    var template = require(`../templates/${name}.hdbs`);
    return template(data);
  },

  switchTo: function(name, data) {
    this.$('[data-main]').html(this.renderTemplate(name, data));
  },

  $: function() {
    var args = Array.prototype.slice.call(arguments, 0);
    if (!args.length) return $('body');
    return $.apply($, arguments);
  }
}

export default BaseApp;
<|endoftext|>


<commit_before>import { BoxGeometry, MeshPhongMaterial } from 'three'
import Mesh from '../../core/Mesh'

// base class for Geometry and Material behaviors
export default
class BaseMeshBehavior {
    constructor(element) {

        this.checkedElementIsMesh = false
        this.elementIsMesh = false

        // records the initial size of the geometry, so that we have a
        // reference for how much scale to apply when accepting new sizes from
        // the user.
        this.initialSize = null;

        this.isMeshPromise = null
        this.resolveIsMeshPromise = null
        // TODO cancellable promise, or it may leak

        if ( element.nodeName.includes('-') ) {
            this.isMeshPromise = new Promise(r => this.resolveIsMeshPromise = r)
            customElements.whenDefined(element.nodeName.toLowerCase())
            .then(() => {
                if (element instanceof Mesh) this.resolveIsMeshPromise(true)
                else this.resolveIsMeshPromise(false)
            })
        }
        else this.isMeshPromise = Promise.resolve(false)
    }

    async checkElementIsMesh(element) {
        this.elementIsMesh = await this.isMeshPromise
        this.checkedElementIsMesh = true

        if ( ! this.elementIsMesh ) {
            console.warn( `${this.constructor.name} is only for use on elements of type Mesh, otherwise it won't do anything. You element was:`, element )
        }
    }

    setMeshComponent(element, name, newComponent) {
        if ( element.threeObject3d[ name ] )
            element.threeObject3d[ name ].dispose()

        element.threeObject3d[name] = newComponent
    }

    setDefaultComponent( element, name ) {
        this.setMeshComponent( element, name, this.makeDefaultComponent( element, name ) )
    }

    makeDefaultComponent( element, name ) {
        if (name == 'geometry') {
            return new BoxGeometry(
                element.calculatedSize.x,
                element.calculatedSize.y,
                element.calculatedSize.z,
            )
        }
        else if (name == 'material') {
            return new MeshPhongMaterial( { color: 0xff6600 } )
        }
    }
}
<commit_msg>No need to store this variable on 'this'<commit_after>import { BoxGeometry, MeshPhongMaterial } from 'three'
import Mesh from '../../core/Mesh'

// base class for Geometry and Material behaviors, not to be used directly
export default
class BaseMeshBehavior {
    constructor(element) {

        this.checkedElementIsMesh = false
        this.elementIsMesh = false

        // records the initial size of the geometry, so that we have a
        // reference for how much scale to apply when accepting new sizes from
        // the user.
        this.initialSize = null;

        this.isMeshPromise = null
        let resolveIsMeshPromise = null
        // TODO cancellable promise, or it may leak

        if ( element.nodeName.includes('-') ) {
            this.isMeshPromise = new Promise(r => resolveIsMeshPromise = r)
            customElements.whenDefined(element.nodeName.toLowerCase())
            .then(() => {
                if (element instanceof Mesh) resolveIsMeshPromise(true)
                else resolveIsMeshPromise(false)
            })
        }
        else this.isMeshPromise = Promise.resolve(false)
    }

    async checkElementIsMesh(element) {
        this.elementIsMesh = await this.isMeshPromise
        this.checkedElementIsMesh = true

        if ( ! this.elementIsMesh ) {
            console.warn( `${this.constructor.name} is only for use on elements of type Mesh, otherwise it won't do anything. You element was:`, element )
        }
    }

    setMeshComponent(element, name, newComponent) {
        if ( element.threeObject3d[ name ] )
            element.threeObject3d[ name ].dispose()

        element.threeObject3d[name] = newComponent
    }

    setDefaultComponent( element, name ) {
        this.setMeshComponent( element, name, this.makeDefaultComponent( element, name ) )
    }

    makeDefaultComponent( element, name ) {
        if (name == 'geometry') {
            return new BoxGeometry(
                element.calculatedSize.x,
                element.calculatedSize.y,
                element.calculatedSize.z,
            )
        }
        else if (name == 'material') {
            return new MeshPhongMaterial( { color: 0xff6600 } )
        }
    }
}
<|endoftext|>


<commit_before>require('classtool');

function ClassSpec(b) {
  var assert = require('assert');
  var fs = require('fs');
  var Block = require('bitcore/Block').class();
  var Deserialize = require('bitcore/Deserialize');
  var Parser = require('bitcore/util/BinaryParser').class();
  var coinUtil = require('bitcore/util/util');

  function HeaderDB(b) {
    this.network = b.network;
    this.fd = null;
    this.blocks = {};
    this.byHeight = [];
    this.bestBlock = null;
    this.cached_size = 0;
  }

  HeaderDB.prototype.size = function() {
    this.cached_size = Object.keys(this.blocks).length;
    return this.cached_size;
  };

  HeaderDB.prototype.locator = function(block) {
    if (!block)
      block = this.bestBlock;

    var step = 1;
    var start = 0;
    var loc = [];
    // see https://en.bitcoin.it/wiki/Protocol_specification#getblocks
    for (var i = block.height; i > 0; i -= step, ++start) {
      if (start >= 10)
        step *= 2;
      loc.push(this.byHeight[i]);
    }
    assert.equal(this.byHeight[0].toString(),
          this.network.genesisBlock.hash.toString());
    loc.push(this.byHeight[0]);
    //console.log('Requesting more headers. Current height: ' + block.height );
    return loc;
  };

  HeaderDB.prototype.add = function(block) {
    var hash = block.calcHash();
    block.hash = hash;
    var curWork = Deserialize.intFromCompact(block.bits);

    if (hash in this.blocks) {
            var old  =  this.blocks[hash];
      throw new Error('duplicate block (was at height ' + old.height  + ')');
       }

    var bestChain = false;

    var reorg = {
      oldBest: null,
      conn: 0,
      disconn: 0,
    };

    if (this.cached_size == 0) {
      if (this.network.genesisBlock.hash.toString() !=
          hash.toString())
        throw new Error('Invalid genesis block');

      block.height = 0;
      block.work = curWork;
      bestChain = true;
            this.cached_size++;
    } else {
      var prevBlock = this.blocks[block.prev_hash];
      if (!prevBlock)
        throw new Error('orphan block; prev not found');

      block.height = prevBlock.height + 1;
      block.work = prevBlock.work + curWork;
            this.cached_size++;

      if (block.work > this.bestBlock.work)
        bestChain = true;
    }

    // add to by-hash index
    this.blocks[hash] = block;

    if (bestChain) {
      var oldBest = this.bestBlock;
      var newBest = block;

      reorg.oldBest = oldBest;

      // likely case: new best chain has greater height
      if (!oldBest) {
        while (newBest) {
          newBest = this.blocks[newBest.prev_hash];
          reorg.conn++;
        }
      } else {
        while (newBest &&
               (newBest.height > oldBest.height)) {
          newBest = this.blocks[newBest.prev_hash];
          reorg.conn++;
        }
      }

      // unlikely: old best chain has greater height
      while (oldBest && newBest &&
             (oldBest.height > newBest.height)) {
        oldBest = this.blocks[oldBest.prev_hash];
        reorg.disconn++;
      }

      // height matches, but still walking parallel
      while (oldBest && newBest && (oldBest != newBest)) {
        newBest = this.blocks[newBest.prev_hash];
        reorg.conn++;

        oldBest = this.blocks[oldBest.prev_hash];
        reorg.disconn++;
      }

      var shuf = (reorg.conn > reorg.disconn) ?
           reorg.conn : reorg.disconn;

      // reorg analyzed, updated best-chain pointer
      this.bestBlock = block;

      // update by-height index
      var ptr = block;
      var updated = [];
      for (var idx = block.height;
           idx > (block.height - shuf); idx--) {
        if (idx < 0)
          break;
        var update = [ idx, ptr ];
        updated.push(update);
        ptr = this.blocks[ptr.prev_hash];
      }

      updated.reverse();

      for (var i = 0; i < updated.length; i++) {
        var update = updated[i];
        var idx = update[0];
        var ptr = update[1];

        if (idx < this.byHeight.length)
          this.byHeight[idx] = ptr.hash;
        else
          this.byHeight.push(ptr.hash);
      }
    }
    return reorg;
  };

  HeaderDB.prototype.addBuf = function(buf) {
    var block = new Block();
    var parser = new Parser(buf);
    block.parse(parser, true);
    this.add(block);

  };

  HeaderDB.prototype.readFile = function(filename) {
    var fd = fs.openSync(filename, 'r');
    var stats = fs.fstatSync(fd);
    if (stats.size % 80 != 0)
      throw new Error('Corrupted header db');

    while (1) {
      var buf = new Buffer(80);
      var bread = fs.readSync(fd, buf, 0, 80, null);
      if (bread < 80)
        break;

      this.addBuf(buf);

            if ( ! ( this.cached_size % 1000 )) {
                console.log('\tblock...' +  this.cached_size ) ;
            }
    }

    fs.closeSync(fd);
  };

  HeaderDB.prototype.writeFile = function(filename) {
    var block = this.bestBlock;
    var data = [];
    while (block) {
      var s = block.getHeader();
      data.push(s);
      block = this.blocks[block.prev_hash];
    }

    data.reverse();

    var fd = fs.openSync(filename, 'w');

    data.forEach(function(datum) {
      fs.writeSync(fd, datum, 0, 80, null);
    });

    fs.closeSync(fd);
  };

  return HeaderDB;
};
module.defineClass(ClassSpec);

<commit_msg>remove HeaderDB.js old file<commit_after><|endoftext|>


<commit_before>var google = {
    maps : {
        OverlayView : function () {
        },
        Marker : function () {
            return {
                setMap: function() {}
            };
        },
        InfoWindow : function () {
        },
        LatLng: function(lat, lng) {
            return [lat, lng];
        },
        LatLngBounds: function(sw, ne) {
            return {
                extend: function() {}
            };
        },
        Map: function(obj) {
            return {
                getStreetView: function () {
                    return {
                        setOptions: function () {

                        }
                    };
                }
            };
        },
        MapTypeControlStyle: {
            HORIZONTAL_BAR: 1
        },
        ControlPosition: {
            BOTTOM_RIGHT: 1
        }
    }
};<commit_msg>Added fitBounds mock<commit_after>var google = {
    maps : {
        OverlayView : function () {
        },
        Marker : function () {
            return {
                setMap: function() {}
            };
        },
        InfoWindow : function () {
        },
        LatLng: function(lat, lng) {
            return [lat, lng];
        },
        LatLngBounds: function(sw, ne) {
            return {
                extend: function() {}
            };
        },
        Map: function(obj) {
            return {
                getStreetView: function () {
                    return {
                        setOptions: function () {

                        }
                    };
                },
                fitBounds: function (bounds) {
                    return true;
                }
            };
        },
        MapTypeControlStyle: {
            HORIZONTAL_BAR: 1
        },
        ControlPosition: {
            BOTTOM_RIGHT: 1
        }
    }
};
<|endoftext|>


<commit_before>describe('RequestHandler', function() {
    var RH = require('../../lib/utils/RequestHandler.js');

    var nock = require('nock');
    // nock.recorder.rec();

    it('gives a session', function(done) {
        nock('http://127.0.0.1:4444')
            .post('/wd/hub/session', {"desiredCapabilities":{"browserName":"chrome"}})
            .reply(200, "{\"status\":0,\"sessionId\":\"6656c65b-a84b-4919-870e-ce9d725f3170\",\"value\":{\"platform\":\"LINUX\",\"acceptSslCerts\":true,\"javascriptEnabled\":true,\"browserName\":\"chrome\",\"chrome\":{\"userDataDir\":\"/tmp/.org.chromium.Chromium.DHRpAQ\"},\"rotatable\":false,\"locationContextEnabled\":true,\"webdriver.remote.sessionid\":\"6656c65b-a84b-4919-870e-ce9d725f3170\",\"version\":\"32.0.1700.77\",\"takesHeapSnapshot\":true,\"cssSelectorsEnabled\":true,\"databaseEnabled\":false,\"handlesAlerts\":true,\"browserConnectionEnabled\":false,\"nativeEvents\":true,\"webStorageEnabled\":true,\"applicationCacheEnabled\":false,\"takesScreenshot\":true},\"state\":null,\"class\":\"org.openqa.selenium.remote.Response\",\"hCode\":1376091878}", { date: 'Mon, 20 Jan 2014 22:35:27 GMT',
            server: 'Jetty/5.1.x (Linux/3.12.7-2-ARCH amd64 java/1.7.0_51',
            expires: 'Thu, 01 Jan 1970 00:00:00 GMT',
            'cache-control': 'no-cache',
            'content-type': 'application/json;charset=UTF-8',
            'content-length': '673' });

        var rh = new RH();
        rh.create('/session', {
            desiredCapabilities: {
                browserName: 'chrome'
            }
        }, function(err, res) {
            assert.equal(null, err);
            assert.equal(res.sessionId, '6656c65b-a84b-4919-870e-ce9d725f3170');
            assert.equal(rh.sessionID, '6656c65b-a84b-4919-870e-ce9d725f3170');
            done();
        });
    });
});<commit_msg>improved requesthandler mocking<commit_after>describe('RequestHandler', function() {
    var RH = require('../../lib/utils/RequestHandler.js'),
        nock = require('nock'),
        noOps = function(){};

    it('gives a session', function(done) {
        nock('http://127.0.0.1:4444')
            .post('/wd/hub/session', {"desiredCapabilities":{"browserName":"chrome"}})
            .reply(200, "{\"status\":0,\"sessionId\":\"6656c65b-a84b-4919-870e-ce9d725f3170\",\"value\":{\"platform\":\"LINUX\",\"acceptSslCerts\":true,\"javascriptEnabled\":true,\"browserName\":\"chrome\",\"chrome\":{\"userDataDir\":\"/tmp/.org.chromium.Chromium.DHRpAQ\"},\"rotatable\":false,\"locationContextEnabled\":true,\"webdriver.remote.sessionid\":\"6656c65b-a84b-4919-870e-ce9d725f3170\",\"version\":\"32.0.1700.77\",\"takesHeapSnapshot\":true,\"cssSelectorsEnabled\":true,\"databaseEnabled\":false,\"handlesAlerts\":true,\"browserConnectionEnabled\":false,\"nativeEvents\":true,\"webStorageEnabled\":true,\"applicationCacheEnabled\":false,\"takesScreenshot\":true},\"state\":null,\"class\":\"org.openqa.selenium.remote.Response\",\"hCode\":1376091878}", { date: 'Mon, 20 Jan 2014 22:35:27 GMT',
            server: 'Jetty/5.1.x (Linux/3.12.7-2-ARCH amd64 java/1.7.0_51',
            expires: 'Thu, 01 Jan 1970 00:00:00 GMT',
            'cache-control': 'no-cache',
            'content-type': 'application/json;charset=UTF-8',
            'content-length': '673' });

        var options = {
            eventHandler: { emit: noOps },
            options: {},
            logger: { log: noOps }
        }

        var rh = new RH(options);
        rh.create('/session', {
            desiredCapabilities: {
                browserName: 'chrome'
            }
        }, function(err, res) {
            assert.equal(null, err);
            assert.equal(res.sessionId, '6656c65b-a84b-4919-870e-ce9d725f3170');
            assert.equal(rh.sessionID, '6656c65b-a84b-4919-870e-ce9d725f3170');
            done();
        });
    });
});<|endoftext|>


<commit_before>'use strict';

describe('ngStaticFilter', function() {

});<commit_msg>test(staticFilter): add unit test<commit_after>'use strict';

describe('ngStaticFilter', function() {

  //mock files
  var mockFiles = {};
  //helper
  function bindKeys(object) {
   return extend(mockFiles, object);
  }

  beforeEach(module('ng.static.filter', function($provide) {
    $provide.value('ngStatic', {
      get: function(key) {
        return mockFiles[key] || mockFiles;
      }
    });
  }));

  it('should be defined', inject(function(staticFilter) {
    expect(staticFilter).toBeDefined();
  }));

  it('should get key and file name and return the value', inject(
    function(staticFilter) {
      //bind some keys to mock
      bindKeys({
        login: { manager: 'hello manager', employee: 'hello employee' },
        logout: { msg: { employee: 'c ya employee' } }
      });
      //expectation
      expect(staticFilter('manager', 'login')).toBe('hello manager');
      expect(staticFilter('employee', 'login')).toBe('hello employee');

      expect(staticFilter('msg.employee', 'logout')).toBe('c ya employee');
    }
  ));

  it('should return the given key if the value is undefined', inject(
    function(staticFilter) {
      expect(staticFilter('employer', 'file')).toBe('employer');
      expect(staticFilter('employer.btn', 'file')).toBe('employer.btn');
    }
  ));

});
<|endoftext|>


<commit_before>/**
 * @module deep
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 * TODO : adding events on :
 * 		modes : changed
 *
 */
if (typeof define !== 'function') {
	var define = require('amdefine')(module);
}
define([
	"require",
	"./lib/utils",
	"./lib/query",
	"./lib/dq-protocol",
	"./lib/compose",
	"./lib/collider",
	"./lib/compiler",
	"./lib/classes",
	"./lib/interpret",
	"./lib/emitter",
	"./lib/errors",
	"./lib/rql",
	"./lib/promise",
	"./lib/context",
	"./lib/nodes",
	"./lib/logs",
	"./lib/deep-load",
	"./lib/deep-equal",
	"./lib/ocm",
	"./lib/traversal",
	"./lib/flatten",
	"./lib/protocol",
	"./lib/sheet",
	"./lib/deep-sheeter",
	"./lib/deep-chain",
	"./lib/restrictions",
	"./lib/validator"
	//"./lib/schema"
], function(require, utils,  query, dq, composer, collider, compiler, classes, interpret, emitter, errors, rql,promise, context, nodes, logs,  deepLoader, deepEqual, ocm, traversal, flattener, protocol, sheets, Sheeter, deepChain, restrictions, Validator) {

	if (typeof deep !== 'undefined') {
		console.log("***********************************************************************************");
		console.warn("You trying to load deepjs modules two times (maybe from two differents node_modules (or bower) module)");
		console.warn("It could be voluntary. If not : you should think it twice. Protocols and context are local to deep instances (by examples).");
		console.log("***********************************************************************************");
	}

	var deep = function(obj, schema, options) {
		// console.log("CHAIN START ", obj)
		options = options || {};
		var h = new deep.Chain(options._state || null, options),
			d;
		try {
			if (typeof obj === 'string')
				obj = deep.get(obj, options);

			if (typeof schema === 'string')
				schema = deep.get(schema, options);

			if (!schema && obj && (obj.then || obj.promise))
				d = deep.when(obj)
					.done(function(res) {
						h._init(res);
						h.resolve();
					});
			if (schema && (schema.then || schema.promise))
				if (obj && (obj.then || obj.promise))
					d = deep.all([obj, schema])
						.done(function(res) {
							h._init(res[0], res[1]);
							h.resolve();
						});
				else
					d = deep.when(schema)
						.done(function(res) {
							h._init(null, res);
							h.resolve();
						});
			if (d)
				d.fail(function(error) {
					h.reject(error);
				});
			else {
				h._init(obj, schema);
				h.resolve();
			}
		} catch (error) {
			//console.log("internal chain start error : ", error);
			h.reject(error);
		}
		return h;
	};

	deep.utils = utils;

	deep.transformers = {};

	deep.log = logs.log;
	deep.warn = logs.warn;
	deep.error = logs.error;

	/**
	 * are you on nodejs or not
	 * @static
	 * @property isNode
	 * @type {Boolean}
	 */
	deep.isNode = (typeof process !== 'undefined' && process.versions && process.versions.node);

	/**
	 * where to place YOUR globals (deep does'nt have any globals)
	 * @static
	 * @property globals
	 */
	deep.globals = {};

	/**
	 * where to place YOUR globals headers to set on each store call (deep does'nt have any globals)
	 * @static
	 * @property globals
	 */
	deep.globalHaders = {};

	//require("./lib/utils")(deep);
	deep.errors = errors;
	deep.rql = rql;
	deep.collider = collider;
	for (var i in traversal)
		deep[i] = traversal[i];

	deep.nodes = nodes;
	deep.deepLoad = function(entry, context, destructive, excludeFunctions) {
		return deep(entry).deepLoad(context, destructive, excludeFunctions);
	};
	/**
	 * final namespace for deepjs/query
	 * @static
	 * @property Querier
	 * @type {DeepQuery}
	 */
	var Querier = deep.Querier = query;
	/**
	 * perform a (synched) query query
	 * @example
	 *
	 * deep.query({ hello:"world", test:1 }, "/*?=world"); // will return ["world"]
	 *
	 * @method query
	 * @param {Object} object any object to query
	 * @param {String} query the query
	 * @static
	 * @return {Array} the result aray
	 */
	deep.query = Querier.query;

	deep.ui = {};
	deep.client = {};

	for (var i in compiler)
		deep[i] = compiler[i];
	for (var i in classes)
		deep[i] = classes[i];

	deep.compose = composer.compose;
	deep.Composition = composer.Composition;
	deep.Composer = composer.Composer;
	deep.compose.Classes = deep.Classes;		// for backward compatibility
	deep.compose.ClassFactory = deep.ClassFactory;	// for backward compatibility
	deep.Arguments = deep.compose.Arguments;

	//deep.extendsChilds = flatten.extendsChilds;
	//deep.extendsBackgrounds = flatten.extendsBackgrounds;
	//utils.flatten = deep.flatten = flatten.flatten;

	deep.protocol = protocol.protocol;
	deep.protocols = protocol.protocols;
	deep.get = protocol.get;
	deep.getAll = protocol.getAll;

	deep.ocm = ocm;
	deep.Modes = ocm.Modes;
	deep.Roles = ocm.Roles;
	deep.modes = ocm.modes;
	deep.roles = ocm.roles;
	deep.getModes = ocm.getModes;

	deep.Event = emitter.Event;
	deep.Emitter = emitter.Emitter;

	for (var i in sheets)
		deep[i] = sheets[i];

	for (var i in promise)
		deep[i] = promise[i];

	deep.Chain = deepChain;

	deep.Sheeter = Sheeter;

	deep.delay = function(ms) {
		return deep({}).delay(ms);
	}

	for (var i in restrictions)
		deep[i] = restrictions[i];

	//_________________________________________________________________________________

	deep.contextualise = context.contextualise;
	deep.fromContext = context.fromContext;
	deep.context = context.context;

	deep.flatten = flattener.flatten;

	/**
	 * the deep schema validator
	 * @static
	 * @property Validator
	 */
	deep.Validator = Validator;
	/**
	 * perform a schema validation
	 * @static
	 * @method validate
	 * @param object the object to validate
	 * @param schema the schema
	 * @return {deep.validate.Report} the validation report
	 */
	deep.validate = Validator.validate;
	/**
	 * perform a schema partial validation (only on certain field)
	 * @static
	 * @method partialValidation
	 * @param object the object to validate
	 * @param fields the array of properties paths to validate
	 * @param schema the schema
	 * @return {deep.validate.Report} the validation report
	 */
	deep.partialValidation = Validator.partialValidation;

	deep.coreUnits = deep.coreUnits || [];
	deep.coreUnits.push(
		"js::deepjs/units/equals",
		"js::deepjs/units/queries",
		"js::deepjs/units/collisions",
		"js::deepjs/units/colliders",
		"js::deepjs/units/compositions",
		"js::deepjs/units/protocols",
		"js::deepjs/units/flatten",
		"js::deepjs/units/promises",
		"js::deepjs/units/chain",
		"js::deepjs/units/replace",
		"js::deepjs/units/remove",
		"js::deepjs/units/interpret",
		"js::deepjs/units/relations",
		"js::deepjs/units/context",
		"js::deepjs/units/ocm",
		"js::deepjs/units/sheets",
		"js::deepjs/units/shared",
		"js::deepjs/units/parcours",
		"js::deepjs/units/deepload",
		"js::deepjs/units/utils",
		"js::deepjs/units/restrictions",
		"js::deepjs/units/custom-chain"
	);
	//_________________________________________________________________________________
	return deep;
});<commit_msg>remove restrictions units from core<commit_after>/**
 * @module deep
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 * TODO : adding events on :
 * 		modes : changed
 *
 */
if (typeof define !== 'function') {
	var define = require('amdefine')(module);
}
define([
	"require",
	"./lib/utils",
	"./lib/query",
	"./lib/dq-protocol",
	"./lib/compose",
	"./lib/collider",
	"./lib/compiler",
	"./lib/classes",
	"./lib/interpret",
	"./lib/emitter",
	"./lib/errors",
	"./lib/rql",
	"./lib/promise",
	"./lib/context",
	"./lib/nodes",
	"./lib/logs",
	"./lib/deep-load",
	"./lib/deep-equal",
	"./lib/ocm",
	"./lib/traversal",
	"./lib/flatten",
	"./lib/protocol",
	"./lib/sheet",
	"./lib/deep-sheeter",
	"./lib/deep-chain",
	"./lib/restrictions",
	"./lib/validator"
	//"./lib/schema"
], function(require, utils,  query, dq, composer, collider, compiler, classes, interpret, emitter, errors, rql,promise, context, nodes, logs,  deepLoader, deepEqual, ocm, traversal, flattener, protocol, sheets, Sheeter, deepChain, restrictions, Validator) {

	if (typeof deep !== 'undefined') {
		console.log("***********************************************************************************");
		console.warn("You trying to load deepjs modules two times (maybe from two differents node_modules (or bower) module)");
		console.warn("It could be voluntary. If not : you should think it twice. Protocols and context are local to deep instances (by examples).");
		console.log("***********************************************************************************");
	}

	var deep = function(obj, schema, options) {
		// console.log("CHAIN START ", obj)
		options = options || {};
		var h = new deep.Chain(options._state || null, options),
			d;
		try {
			if (typeof obj === 'string')
				obj = deep.get(obj, options);

			if (typeof schema === 'string')
				schema = deep.get(schema, options);

			if (!schema && obj && (obj.then || obj.promise))
				d = deep.when(obj)
					.done(function(res) {
						h._init(res);
						h.resolve();
					});
			if (schema && (schema.then || schema.promise))
				if (obj && (obj.then || obj.promise))
					d = deep.all([obj, schema])
						.done(function(res) {
							h._init(res[0], res[1]);
							h.resolve();
						});
				else
					d = deep.when(schema)
						.done(function(res) {
							h._init(null, res);
							h.resolve();
						});
			if (d)
				d.fail(function(error) {
					h.reject(error);
				});
			else {
				h._init(obj, schema);
				h.resolve();
			}
		} catch (error) {
			//console.log("internal chain start error : ", error);
			h.reject(error);
		}
		return h;
	};

	deep.utils = utils;

	deep.transformers = {};

	deep.log = logs.log;
	deep.warn = logs.warn;
	deep.error = logs.error;

	/**
	 * are you on nodejs or not
	 * @static
	 * @property isNode
	 * @type {Boolean}
	 */
	deep.isNode = (typeof process !== 'undefined' && process.versions && process.versions.node);

	/**
	 * where to place YOUR globals (deep does'nt have any globals)
	 * @static
	 * @property globals
	 */
	deep.globals = {};

	/**
	 * where to place YOUR globals headers to set on each store call (deep does'nt have any globals)
	 * @static
	 * @property globals
	 */
	deep.globalHaders = {};

	//require("./lib/utils")(deep);
	deep.errors = errors;
	deep.rql = rql;
	deep.collider = collider;
	for (var i in traversal)
		deep[i] = traversal[i];

	deep.nodes = nodes;
	deep.deepLoad = function(entry, context, destructive, excludeFunctions) {
		return deep(entry).deepLoad(context, destructive, excludeFunctions);
	};
	/**
	 * final namespace for deepjs/query
	 * @static
	 * @property Querier
	 * @type {DeepQuery}
	 */
	var Querier = deep.Querier = query;
	/**
	 * perform a (synched) query query
	 * @example
	 *
	 * deep.query({ hello:"world", test:1 }, "/*?=world"); // will return ["world"]
	 *
	 * @method query
	 * @param {Object} object any object to query
	 * @param {String} query the query
	 * @static
	 * @return {Array} the result aray
	 */
	deep.query = Querier.query;

	deep.ui = {};
	deep.client = {};

	for (var i in compiler)
		deep[i] = compiler[i];
	for (var i in classes)
		deep[i] = classes[i];

	deep.compose = composer.compose;
	deep.Composition = composer.Composition;
	deep.Composer = composer.Composer;
	deep.compose.Classes = deep.Classes;		// for backward compatibility
	deep.compose.ClassFactory = deep.ClassFactory;	// for backward compatibility
	deep.Arguments = deep.compose.Arguments;

	//deep.extendsChilds = flatten.extendsChilds;
	//deep.extendsBackgrounds = flatten.extendsBackgrounds;
	//utils.flatten = deep.flatten = flatten.flatten;

	deep.protocol = protocol.protocol;
	deep.protocols = protocol.protocols;
	deep.get = protocol.get;
	deep.getAll = protocol.getAll;

	deep.ocm = ocm;
	deep.Modes = ocm.Modes;
	deep.Roles = ocm.Roles;
	deep.modes = ocm.modes;
	deep.roles = ocm.roles;
	deep.getModes = ocm.getModes;

	deep.Event = emitter.Event;
	deep.Emitter = emitter.Emitter;

	for (var i in sheets)
		deep[i] = sheets[i];

	for (var i in promise)
		deep[i] = promise[i];

	deep.Chain = deepChain;

	deep.Sheeter = Sheeter;

	deep.delay = function(ms) {
		return deep({}).delay(ms);
	}

	for (var i in restrictions)
		deep[i] = restrictions[i];

	//_________________________________________________________________________________

	deep.contextualise = context.contextualise;
	deep.fromContext = context.fromContext;
	deep.context = context.context;

	deep.flatten = flattener.flatten;

	/**
	 * the deep schema validator
	 * @static
	 * @property Validator
	 */
	deep.Validator = Validator;
	/**
	 * perform a schema validation
	 * @static
	 * @method validate
	 * @param object the object to validate
	 * @param schema the schema
	 * @return {deep.validate.Report} the validation report
	 */
	deep.validate = Validator.validate;
	/**
	 * perform a schema partial validation (only on certain field)
	 * @static
	 * @method partialValidation
	 * @param object the object to validate
	 * @param fields the array of properties paths to validate
	 * @param schema the schema
	 * @return {deep.validate.Report} the validation report
	 */
	deep.partialValidation = Validator.partialValidation;

	deep.coreUnits = deep.coreUnits || [];
	deep.coreUnits.push(
		"js::deepjs/units/equals",
		"js::deepjs/units/queries",
		"js::deepjs/units/collisions",
		"js::deepjs/units/colliders",
		"js::deepjs/units/compositions",
		"js::deepjs/units/protocols",
		"js::deepjs/units/flatten",
		"js::deepjs/units/promises",
		"js::deepjs/units/chain",
		"js::deepjs/units/replace",
		"js::deepjs/units/remove",
		"js::deepjs/units/interpret",
		"js::deepjs/units/relations",
		"js::deepjs/units/context",
		"js::deepjs/units/ocm",
		"js::deepjs/units/sheets",
		"js::deepjs/units/shared",
		"js::deepjs/units/parcours",
		"js::deepjs/units/deepload",
		"js::deepjs/units/utils",
		"js::deepjs/units/custom-chain"
	);

	//_________________________________________________________________________________
	return deep;
});<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

// MODULES //

var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
var isnan = require( '@stdlib/math/base/assert/is-nan' );

// MAIN //

/**
* Returns an accumulator function which incrementally computes a moving arithmetic mean.
*
* @param {PositiveInteger} W - window size
* @throws {TypeError} must provide a positive integer
* @returns {Function} accumulator function
*
* @example
* var accumulator = incrmmean( 3 );
*/
function incrmmean( W ) {
	var delta;
	var buf;
	var mu;
	var N;
	var i;
	if ( !isPositiveInteger( W ) ) {
		throw new TypeError( 'invalid input argument. Must provide a positive integer. Value: `' + W + '`.' );
	}
	buf = new Array( W );
	mu = 0.0;
	i = -1;
	N = 0;

	return accumulator;

	/**
	* If provided a value, the accumulator function returns an updated mean. If not provided a value, the accumulator function returns the current mean.
	*
	* @private
	* @param {number} [x] - input value
	* @returns {(number|null)} mean or null
	*
	* @example
	* var mu = accumulator();
	* // returns null
	*
	* mu = accumulator( 2.0 );
	* // returns 2.0
	*
	* mu = accumulator( -5.0 );
	* // returns -1.5
	*
	* mu = accumulator( 3.0 );
	* // returns 0.0
	*
	* mu = accumulator( 5.0 );
	* // returns 1.0
	*
	* mu = accumulator();
	* // returns 1.0
	*/
	function accumulator( x ) {
		var k;
		if ( arguments.length === 0 ) {
			if ( N === 0 ) {
				return null;
			}
			return mu;
		}
		// Update the index for managing the circular buffer:
		i = (i+1) % W;

		// Case: incoming value is NaN, the sliding mean is automatically NaN...
		if ( isnan( x ) ) {
			mu = NaN;
		}
		// Case: initial window...
		else if ( N < W ) {
			N += 1;
			delta = x - mu;
			mu += delta / N;
		}
		// Case: outgoing value is NaN, and, thus, we need to compute the sample mean...
		else if ( isnan( buf[ i ] ) ) {
			N = 1;
			mu = x;
			for ( k = 0; k < W; k++ ) {
				if ( k !== i ) {
					if ( isnan( buf[ k ] ) ) {
						mu = NaN;
						break; // mean is automatically NaN, so no need to continue
					}
					N += 1;
					delta = buf[ k ] - mu;
					mu += delta / N;
				}
			}
		}
		// Case: neither the current mean nor the incoming value are NaN, so we need to update the sample mean...
		else if ( isnan( mu ) === false ) {
			delta = x - buf[ i ];
			mu += delta / W;
		}
		// Case: the current mean is NaN, so nothing to do until the buffer no longer contains NaN values...

		buf[ i ] = x;
		return mu;
	}
}

// EXPORTS //

module.exports = incrmmean;
<commit_msg>Fix bug due to failure to reset variable involved in subsequent condition<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

// MODULES //

var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
var isnan = require( '@stdlib/math/base/assert/is-nan' );

// MAIN //

/**
* Returns an accumulator function which incrementally computes a moving arithmetic mean.
*
* @param {PositiveInteger} W - window size
* @throws {TypeError} must provide a positive integer
* @returns {Function} accumulator function
*
* @example
* var accumulator = incrmmean( 3 );
*/
function incrmmean( W ) {
	var delta;
	var buf;
	var mu;
	var N;
	var i;
	if ( !isPositiveInteger( W ) ) {
		throw new TypeError( 'invalid input argument. Must provide a positive integer. Value: `' + W + '`.' );
	}
	buf = new Array( W );
	mu = 0.0;
	i = -1;
	N = 0;

	return accumulator;

	/**
	* If provided a value, the accumulator function returns an updated mean. If not provided a value, the accumulator function returns the current mean.
	*
	* @private
	* @param {number} [x] - input value
	* @returns {(number|null)} mean or null
	*
	* @example
	* var mu = accumulator();
	* // returns null
	*
	* mu = accumulator( 2.0 );
	* // returns 2.0
	*
	* mu = accumulator( -5.0 );
	* // returns -1.5
	*
	* mu = accumulator( 3.0 );
	* // returns 0.0
	*
	* mu = accumulator( 5.0 );
	* // returns 1.0
	*
	* mu = accumulator();
	* // returns 1.0
	*/
	function accumulator( x ) {
		var k;
		if ( arguments.length === 0 ) {
			if ( N === 0 ) {
				return null;
			}
			return mu;
		}
		// Update the index for managing the circular buffer:
		i = (i+1) % W;

		// Case: incoming value is NaN, the sliding mean is automatically NaN...
		if ( isnan( x ) ) {
			N = W; // explicitly set to avoid `N < W` branch
			mu = NaN;
		}
		// Case: initial window...
		else if ( N < W ) {
			N += 1;
			delta = x - mu;
			mu += delta / N;
		}
		// Case: outgoing value is NaN, and, thus, we need to compute the sample mean...
		else if ( isnan( buf[ i ] ) ) {
			N = 1;
			mu = x;
			for ( k = 0; k < W; k++ ) {
				if ( k !== i ) {
					if ( isnan( buf[ k ] ) ) {
						N = W; // explicitly set to avoid `N < W` branch
						mu = NaN;
						break; // mean is automatically NaN, so no need to continue
					}
					N += 1;
					delta = buf[ k ] - mu;
					mu += delta / N;
				}
			}
		}
		// Case: neither the current mean nor the incoming value are NaN, so we need to update the sample mean...
		else if ( isnan( mu ) === false ) {
			delta = x - buf[ i ];
			mu += delta / W;
		}
		// Case: the current mean is NaN, so nothing to do until the buffer no longer contains NaN values...

		buf[ i ] = x;
		return mu;
	}
}

// EXPORTS //

module.exports = incrmmean;
<|endoftext|>


<commit_before>(function ($) {
var Map = function(element, options) {
    var self = this;
    this.options = $.extend({}, new $.fn.mapQuery.defaults.map(), options);

    this.element = element;
    // TODO vmx 20110609: do proper options building
    var olMapOptions = $.extend({}, this.options);
    delete olMapOptions.layers;

    this.olMap = new OpenLayers.Map(this.element[0], olMapOptions);
    this.defaultProjection = new OpenLayers.Projection(
        this.options.defaultProjection);
    // Keep IDs of vector layer for select feature control
    this.vectorLayers = [];
    this.selectFeatureControl = null;
    // Counts up to create unique IDs
    this.idCounter = 0;

    element.data('mapQuery', this);
    this.layersList = {};

    // To bind and trigger jQuery events
    this.events = $({});
    // create triggers for all OpenLayers map events
    var events = {};
    $.each(this.olMap.EVENT_TYPES, function(i, evt) {
        events[evt] = function() {
            self.events.trigger(evt, arguments);
        };
    });
    this.olMap.events.on(events);

    // Add layers to the map
    if (this.options.layers!==undefined) {
        this.layers(this.options.layers);
    }
};

Map.prototype = {
    layers: function(options) {
        //var o = $.extend({}, options);
        var self = this;
        switch(arguments.length) {
        case 0:
            return this._allLayers();
        case 1:
            if (!$.isArray(options)) {
                return this._addLayer(options);
            }
            else {
                return $.map(options, function(layer) {
                    return self._addLayer(layer);
                });
            }
        default:
            throw('wrong argument number');
        };
    },
    // Returns all layers as an array, sorted by there order in the map. First
    // element in the array is the topmost layer
    _allLayers: function() {
        var layers = [];
        $.each(this.layersList, function(id, layer) {
            var item = [layer.position(), layer];
            layers.push(item);
        });
        var sorted = layers.sort( function compare(a, b) {
            return a[0] - b[0];
        });
        var result = $.map(sorted, function(item) {
            return item[1];
        });
        return result.reverse();
    },
    _addLayer: function(options) {
        var id = this._createId();
        var layer = new Layer(this, id, options);
        this.layersList[id] = layer;
        if (layer.isVector) {
            this.vectorLayers.push(id);
        }
        this._updateSelectFeatureControl(this.vectorLayers);
        return layer;
    },
    // Creates a new unique ID for a layer
    _createId: function() {
        return 'mapquery' + this.idCounter++;
    },
    _removeLayer: function(id) {
        // remove id from vectorlayer if it is there list
        this.vectorLayers = $.grep(this.vectorLayers, function(elem) {
            return elem != id;
        });
        this._updateSelectFeatureControl(this.vectorLayers);
        delete this.layersList[id];
        // XXX vmx: shouldn't the layer be destroyed() properly?
        return this;
    },
    //This WILL NOT work without a baseLayer or allOverlays == true
    center: function(x, y, z){
        var mapProjection;
        var point = new OpenLayers.LonLat(x, y);

        if( !isNaN(x + y + z)) {
            mapProjection = this.olMap.getProjectionObject();
            if (!mapProjection.equals(this.defaultProjection)) {
                point.transform(this.defaultProjection, mapProjection);
            }
            else {
                point = new OpenLayers.LonLat(x, y);
            }
            this.olMap.setCenter(point, z);
        }
        return this;
    },
    _updateSelectFeatureControl: function(layerIds) {
        var vectorLayers = [];
        var layersList = this.layersList;
        if (this.selectFeatureControl!==null) {
            this.selectFeatureControl.deactivate();
            this.selectFeatureControl.destroy();
        }
        $.each(layerIds, function() {
            vectorLayers.push(layersList[this].olLayer);
        });
        this.selectFeatureControl = new OpenLayers.Control.SelectFeature(
            vectorLayers);
        this.olMap.addControl(this.selectFeatureControl);
        this.selectFeatureControl.activate();
    },
    bind: function() {
        this.events.bind.apply(this.events, arguments);
    },
    one: function() {
        this.events.one.apply(this.events, arguments);
    },
    destroy: function() {
        this.olMap.destroy();
        this.element.removeData('mapQuery');
    }
};

var Layer = function(map, id, options) {
    var self = this;
    // apply default options that are not specific to a layer

    this.id = id;
    this.label = options.label || this.id;
    // a reference to the map object is needed as it stores e.g. the list
    // of all layers (and we need to keep track of it, if we delete a
    // layer)
    this.map = map;

    // true if this layer is a vector layer
    this.isVector = false;

    // to bind and trigger jQuery events
    this.events = $({});

    // create the actual layer based on the options
    // Returns layer and final options for the layer (for later re-use,
    // e.g. zoomToMaxExtent).
    var res = Layer.types[options.type.toLowerCase()].call(this, options);
    this.olLayer = res.layer;
    options = res.options;

    // create triggers for all OpenLayers layer events
    var events = {};
    $.each(this.olLayer.EVENT_TYPES, function(i, evt) {
        events[evt] = function() {
            self.events.trigger(evt, arguments);
        };
    });
    this.olLayer.events.on(events);

    this.map.olMap.addLayer(this.olLayer);
    if (options.zoomToMaxExtent) {
        this.map.olMap.zoomToMaxExtent();
    }
};

$.extend(Layer, {
    types: {
        wms: function(options) {
            var o = $.fn.mapQuery.defaults.layer.all;
            $.extend(true, o, $.fn.mapQuery.defaults.layer.raster);
            $.extend(true, o, options);
            var params = {
                layers: o.layers,
                transparent: o.transparent
            };
            return {
                layer: new OpenLayers.Layer.WMS(o.label, o.url, params),
                options: o
            };
        },
        json: function(options) {
            var o = $.fn.mapQuery.defaults.layer.all;
            $.extend(true, o, $.fn.mapQuery.defaults.layer.vector);
            $.extend(true, o, options);
            this.isVector = true;
            var strategies = [];
            for (var i in o.strategies) {
                switch(o.strategies[i].toLowerCase()) {
                case 'bbox':
                    strategies.push(new OpenLayers.Strategy.BBOX()); break;
                case 'cluster':
                    strategies.push(new OpenLayers.Strategy.Cluster()); break;
                case 'filter':
                    strategies.push(new OpenLayers.Strategy.Filter()); break;
                case 'fixed':
                    strategies.push(new OpenLayers.Strategy.Fixed()); break;
                case 'paging':
                    strategies.push(new OpenLayers.Strategy.Paging()); break;
                case 'refresh':
                    strategies.push(new OpenLayers.Strategy.Refresh()); break;
                case 'save':
                    strategies.push(new OpenLayers.Strategy.Save()); break;
                }
            }
            var params = {
                maxExtent: new OpenLayers.Bounds.fromArray(o.maxExtent),
                protocol: new OpenLayers.Protocol.HTTP({
                    url: o.url,
                    format: new OpenLayers.Format.GeoJSON()
                }),
                strategies: strategies
            };
            return {
                layer: new OpenLayers.Layer.Vector(o.label, params),
                options: o
            };
        },
        osm: function(options) {
            var o = $.fn.mapQuery.defaults.layer.all;
            $.extend(true, o, $.fn.mapQuery.defaults.layer.osm);
            $.extend(true, o, options);
            return {
                layer: new OpenLayers.Layer.OSM(options),
                options: o
            };
        },
        wmts: function(options) {
            var o = $.fn.mapQuery.defaults.layer.all;
            $.extend(true, o, $.fn.mapQuery.defaults.layer.wmts);
            if (options.sphericalMercator===true) {
                $.extend(true, o, {
                    maxExtent: new OpenLayers.Bounds(
                        -128 * 156543.0339, -128 * 156543.0339,
                        128 * 156543.0339, 128 * 156543.0339),
                    maxResolution: 156543.0339,
                    numZoomLevels: 19,
                    projection: 'EPSG:900913',
                    units: 'm'
                });
            }
            $.extend(true, o, options);
            // use by default all options that were passed in for the final
            // openlayers layer consrtuctor
            var params = $.extend(true, {}, o);

            // remove trailing slash
            if (params.url.charAt(params.url.length-1)==='/') {
                params.url = params.url.slice(0, params.url.length-1);
            }
            // if no options that influence the URL where set, extract them
            // from the given URL
            if (o.layer===undefined && o.matrixSet===undefined &&
                    o.style===undefined) {
                var url = $.MapQuery.util.parseUri(params.url);
                var urlParts = url.path.split('/');
                var wmtsPath = urlParts.slice(urlParts.length-3);
                params.url = url.protocol ? url.protocol + '://' : '';
                params.url += url.authority +
                    // remove WMTS version (1.0.0) as well
                    urlParts.slice(0, urlParts.length-4).join('/');
                params.layer = wmtsPath[0];
                params.style = wmtsPath[1];
                params.matrixSet = wmtsPath[2];
            }
            return {
                layer: new OpenLayers.Layer.WMTS(params),
                options: o
            };
        },
        //Not sure this one is worth pursuing works with ecwp:// & jpip:// urls
        //See ../lib/NCSOpenLayersECWP.js
        ecwp: function(options) {
            var o = $.fn.mapQuery.defaults.layer.all;
            $.extend(true, o, $.fn.mapQuery.defaults.layer.raster);
            $.extend(true, o, options);
            return {
                layer: new OpenLayers.Layer.ECWP(o.label, o.url, o),
                options: o
            };
        }
    }
});

Layer.prototype = {
    down: function(delta) {
        delta = delta || 1;
        this.map.olMap.raiseLayer(this.olLayer, -delta);
        return this;
    },
    // NOTE vmx: this would be pretty cool, but it's not easily possible
    // you could use $.each($.geojq.layer())) instead, this is for pure
    // convenience.
    each: function () {},
    hide: function() {
        this.olLayer.setVisibility(false);
        return this;
    },
    // will return the map object
    remove: function() {
        this.map.olMap.removeLayer(this.olLayer);
        // remove references to this layer that are stored in the
        // map object
        return this.map._removeLayer();
    },
    position: function(pos) {
        if (pos===undefined) {
            return this.map.olMap.getLayerIndex(this.olLayer);
        }
        else {
            return this.map.olMap.setLayerIndex(this.olLayer, pos);
        }
    },
    show: function() {
        this.olLayer.setVisibility(true);
        return this;
    },
    up: function(delta) {
        delta = delta || 1;
        this.map.olMap.raiseLayer(this.olLayer, delta);
        return this;
    },
    visible: function() {
        return this.olLayer.getVisibility();
    },
    // every event gets the layer passed in
    bind: function() {
        this.events.bind.apply(this.events, arguments);
    },
    one: function() {
        this.events.one.apply(this.events, arguments);
    }
};

$.fn.mapQuery = function(options) {
    return this.each(function() {
        var instance = $.data(this, 'mapQuery');
        if (!instance) {
            $.data(this, 'mapQuery', new Map($(this), options));
        }
    });
};

// default options for the map and layers
$.fn.mapQuery.defaults = {
    // The controls for the map are per instance, therefore it need to
    // be an function that can be initiated per instance
    map: function() {
        return {
            // Remove quirky moveTo behavior, probably not a good idea in the
            // long run
            allOverlays: true,
            controls: [
                new OpenLayers.Control.Navigation({documentDrag: true}),
                new OpenLayers.Control.TouchNavigation({
                dragPanOptions: {
                    interval: 1,
                    enableKinetic: true
                }
            }),
                new OpenLayers.Control.ArgParser(),
                new OpenLayers.Control.Attribution()
            ],
            format: 'image/png',
            // input (e.g. for .center()) will be automatically transformed
            // if map has a different projection (from this proejction to the
            // one of the map)
            defaultProjection: 'EPSG:900913',
            sphericalMercator: false
        };
    },
    layer: {
        all: {
            zoomToMaxExtent: true
        },
        raster: {
            // options for raster layers
            transparent: true
        },
        vector: {
            // options for vector layers
            strategies: ['fixed']
        },
        osm: {
            isBaseLayer: false,
            transitionEffect: 'resize'
        },
        wmts: {
            format: 'image/jpeg',
            requestEncoding: 'REST',
            sphericalMercator: false
        }
    }
};

// Some utility functions

$.MapQuery = {};
$.MapQuery.util = {};
// http://blog.stevenlevithan.com/archives/parseuri (2010-12-18)
// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
$.MapQuery.util.parseUri = function (str) {
    var o = $.MapQuery.util.parseUri.options,
        m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
        uri = {},
        i = 14;

    while (i--) uri[o.key[i]] = m[i] || "";

    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
    });

    return uri;
};
$.MapQuery.util.parseUri.options = {
    strictMode: false,
    key: ["source", "protocol", "authority", "userInfo", "user",
            "password", "host", "port", "relative", "path", "directory",
            "file", "query", "anchor"],
    q: {
        name: "queryKey",
        parser: /(?:^|&)([^&=]*)=?([^&]*)/g
    },
    parser: {
        strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
        loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
        }
};
})(jQuery);
<commit_msg>fixed touchnav and shift-drag thanks to crschmidt<commit_after>(function ($) {
var Map = function(element, options) {
    var self = this;
    this.options = $.extend({}, new $.fn.mapQuery.defaults.map(), options);

    this.element = element;
    // TODO vmx 20110609: do proper options building
    var olMapOptions = $.extend({}, this.options);
    delete olMapOptions.layers;

    this.olMap = new OpenLayers.Map(this.element[0], olMapOptions);
    this.defaultProjection = new OpenLayers.Projection(
        this.options.defaultProjection);
    // Keep IDs of vector layer for select feature control
    this.vectorLayers = [];
    this.selectFeatureControl = null;
    // Counts up to create unique IDs
    this.idCounter = 0;

    element.data('mapQuery', this);
    this.layersList = {};

    // To bind and trigger jQuery events
    this.events = $({});
    // create triggers for all OpenLayers map events
    var events = {};
    $.each(this.olMap.EVENT_TYPES, function(i, evt) {
        events[evt] = function() {
            self.events.trigger(evt, arguments);
        };
    });
    this.olMap.events.on(events);

    // Add layers to the map
    if (this.options.layers!==undefined) {
        this.layers(this.options.layers);
    }
};

Map.prototype = {
    layers: function(options) {
        //var o = $.extend({}, options);
        var self = this;
        switch(arguments.length) {
        case 0:
            return this._allLayers();
        case 1:
            if (!$.isArray(options)) {
                return this._addLayer(options);
            }
            else {
                return $.map(options, function(layer) {
                    return self._addLayer(layer);
                });
            }
        default:
            throw('wrong argument number');
        };
    },
    // Returns all layers as an array, sorted by there order in the map. First
    // element in the array is the topmost layer
    _allLayers: function() {
        var layers = [];
        $.each(this.layersList, function(id, layer) {
            var item = [layer.position(), layer];
            layers.push(item);
        });
        var sorted = layers.sort( function compare(a, b) {
            return a[0] - b[0];
        });
        var result = $.map(sorted, function(item) {
            return item[1];
        });
        return result.reverse();
    },
    _addLayer: function(options) {
        var id = this._createId();
        var layer = new Layer(this, id, options);
        this.layersList[id] = layer;
        if (layer.isVector) {
            this.vectorLayers.push(id);
        }
        this._updateSelectFeatureControl(this.vectorLayers);
        return layer;
    },
    // Creates a new unique ID for a layer
    _createId: function() {
        return 'mapquery' + this.idCounter++;
    },
    _removeLayer: function(id) {
        // remove id from vectorlayer if it is there list
        this.vectorLayers = $.grep(this.vectorLayers, function(elem) {
            return elem != id;
        });
        this._updateSelectFeatureControl(this.vectorLayers);
        delete this.layersList[id];
        // XXX vmx: shouldn't the layer be destroyed() properly?
        return this;
    },
    //This WILL NOT work without a baseLayer or allOverlays == true
    center: function(x, y, z){
        var mapProjection;
        var point = new OpenLayers.LonLat(x, y);

        if( !isNaN(x + y + z)) {
            mapProjection = this.olMap.getProjectionObject();
            if (!mapProjection.equals(this.defaultProjection)) {
                point.transform(this.defaultProjection, mapProjection);
            }
            else {
                point = new OpenLayers.LonLat(x, y);
            }
            this.olMap.setCenter(point, z);
        }
        return this;
    },
    _updateSelectFeatureControl: function(layerIds) {
        var vectorLayers = [];
        var layersList = this.layersList;
        if (this.selectFeatureControl!==null) {
            this.selectFeatureControl.deactivate();
            this.selectFeatureControl.destroy();
        }
        $.each(layerIds, function() {
            vectorLayers.push(layersList[this].olLayer);
        });
        this.selectFeatureControl = new OpenLayers.Control.SelectFeature(
            vectorLayers);
        this.olMap.addControl(this.selectFeatureControl);
        this.selectFeatureControl.activate();
    },
    bind: function() {
        this.events.bind.apply(this.events, arguments);
    },
    one: function() {
        this.events.one.apply(this.events, arguments);
    },
    destroy: function() {
        this.olMap.destroy();
        this.element.removeData('mapQuery');
    }
};

var Layer = function(map, id, options) {
    var self = this;
    // apply default options that are not specific to a layer

    this.id = id;
    this.label = options.label || this.id;
    // a reference to the map object is needed as it stores e.g. the list
    // of all layers (and we need to keep track of it, if we delete a
    // layer)
    this.map = map;

    // true if this layer is a vector layer
    this.isVector = false;

    // to bind and trigger jQuery events
    this.events = $({});

    // create the actual layer based on the options
    // Returns layer and final options for the layer (for later re-use,
    // e.g. zoomToMaxExtent).
    var res = Layer.types[options.type.toLowerCase()].call(this, options);
    this.olLayer = res.layer;
    options = res.options;

    // create triggers for all OpenLayers layer events
    var events = {};
    $.each(this.olLayer.EVENT_TYPES, function(i, evt) {
        events[evt] = function() {
            self.events.trigger(evt, arguments);
        };
    });
    this.olLayer.events.on(events);

    this.map.olMap.addLayer(this.olLayer);
    if (options.zoomToMaxExtent) {
        this.map.olMap.zoomToMaxExtent();
    }
};

$.extend(Layer, {
    types: {
        wms: function(options) {
            var o = $.fn.mapQuery.defaults.layer.all;
            $.extend(true, o, $.fn.mapQuery.defaults.layer.raster);
            $.extend(true, o, options);
            var params = {
                layers: o.layers,
                transparent: o.transparent
            };
            return {
                layer: new OpenLayers.Layer.WMS(o.label, o.url, params),
                options: o
            };
        },
        json: function(options) {
            var o = $.fn.mapQuery.defaults.layer.all;
            $.extend(true, o, $.fn.mapQuery.defaults.layer.vector);
            $.extend(true, o, options);
            this.isVector = true;
            var strategies = [];
            for (var i in o.strategies) {
                switch(o.strategies[i].toLowerCase()) {
                case 'bbox':
                    strategies.push(new OpenLayers.Strategy.BBOX()); break;
                case 'cluster':
                    strategies.push(new OpenLayers.Strategy.Cluster()); break;
                case 'filter':
                    strategies.push(new OpenLayers.Strategy.Filter()); break;
                case 'fixed':
                    strategies.push(new OpenLayers.Strategy.Fixed()); break;
                case 'paging':
                    strategies.push(new OpenLayers.Strategy.Paging()); break;
                case 'refresh':
                    strategies.push(new OpenLayers.Strategy.Refresh()); break;
                case 'save':
                    strategies.push(new OpenLayers.Strategy.Save()); break;
                }
            }
            var params = {
                maxExtent: new OpenLayers.Bounds.fromArray(o.maxExtent),
                protocol: new OpenLayers.Protocol.HTTP({
                    url: o.url,
                    format: new OpenLayers.Format.GeoJSON()
                }),
                strategies: strategies
            };
            return {
                layer: new OpenLayers.Layer.Vector(o.label, params),
                options: o
            };
        },
        osm: function(options) {
            var o = $.fn.mapQuery.defaults.layer.all;
            $.extend(true, o, $.fn.mapQuery.defaults.layer.osm);
            $.extend(true, o, options);
            return {
                layer: new OpenLayers.Layer.OSM(options),
                options: o
            };
        },
        wmts: function(options) {
            var o = $.fn.mapQuery.defaults.layer.all;
            $.extend(true, o, $.fn.mapQuery.defaults.layer.wmts);
            if (options.sphericalMercator===true) {
                $.extend(true, o, {
                    maxExtent: new OpenLayers.Bounds(
                        -128 * 156543.0339, -128 * 156543.0339,
                        128 * 156543.0339, 128 * 156543.0339),
                    maxResolution: 156543.0339,
                    numZoomLevels: 19,
                    projection: 'EPSG:900913',
                    units: 'm'
                });
            }
            $.extend(true, o, options);
            // use by default all options that were passed in for the final
            // openlayers layer consrtuctor
            var params = $.extend(true, {}, o);

            // remove trailing slash
            if (params.url.charAt(params.url.length-1)==='/') {
                params.url = params.url.slice(0, params.url.length-1);
            }
            // if no options that influence the URL where set, extract them
            // from the given URL
            if (o.layer===undefined && o.matrixSet===undefined &&
                    o.style===undefined) {
                var url = $.MapQuery.util.parseUri(params.url);
                var urlParts = url.path.split('/');
                var wmtsPath = urlParts.slice(urlParts.length-3);
                params.url = url.protocol ? url.protocol + '://' : '';
                params.url += url.authority +
                    // remove WMTS version (1.0.0) as well
                    urlParts.slice(0, urlParts.length-4).join('/');
                params.layer = wmtsPath[0];
                params.style = wmtsPath[1];
                params.matrixSet = wmtsPath[2];
            }
            return {
                layer: new OpenLayers.Layer.WMTS(params),
                options: o
            };
        },
        //Not sure this one is worth pursuing works with ecwp:// & jpip:// urls
        //See ../lib/NCSOpenLayersECWP.js
        ecwp: function(options) {
            var o = $.fn.mapQuery.defaults.layer.all;
            $.extend(true, o, $.fn.mapQuery.defaults.layer.raster);
            $.extend(true, o, options);
            return {
                layer: new OpenLayers.Layer.ECWP(o.label, o.url, o),
                options: o
            };
        }
    }
});

Layer.prototype = {
    down: function(delta) {
        delta = delta || 1;
        this.map.olMap.raiseLayer(this.olLayer, -delta);
        return this;
    },
    // NOTE vmx: this would be pretty cool, but it's not easily possible
    // you could use $.each($.geojq.layer())) instead, this is for pure
    // convenience.
    each: function () {},
    hide: function() {
        this.olLayer.setVisibility(false);
        return this;
    },
    // will return the map object
    remove: function() {
        this.map.olMap.removeLayer(this.olLayer);
        // remove references to this layer that are stored in the
        // map object
        return this.map._removeLayer();
    },
    position: function(pos) {
        if (pos===undefined) {
            return this.map.olMap.getLayerIndex(this.olLayer);
        }
        else {
            return this.map.olMap.setLayerIndex(this.olLayer, pos);
        }
    },
    show: function() {
        this.olLayer.setVisibility(true);
        return this;
    },
    up: function(delta) {
        delta = delta || 1;
        this.map.olMap.raiseLayer(this.olLayer, delta);
        return this;
    },
    visible: function() {
        return this.olLayer.getVisibility();
    },
    // every event gets the layer passed in
    bind: function() {
        this.events.bind.apply(this.events, arguments);
    },
    one: function() {
        this.events.one.apply(this.events, arguments);
    }
};

$.fn.mapQuery = function(options) {
    return this.each(function() {
        var instance = $.data(this, 'mapQuery');
        if (!instance) {
            $.data(this, 'mapQuery', new Map($(this), options));
        }
    });
};

// default options for the map and layers
$.fn.mapQuery.defaults = {
    // The controls for the map are per instance, therefore it need to
    // be an function that can be initiated per instance
    map: function() {
        return {
            // Remove quirky moveTo behavior, probably not a good idea in the
            // long run
            allOverlays: true,
            controls: [
                new OpenLayers.Control.Navigation({documentDrag: true, dragPanOptions: {
                    interval: 1,
                    enableKinetic: true
                }}),

                new OpenLayers.Control.ArgParser(),
                new OpenLayers.Control.Attribution()
            ],
            format: 'image/png',
            // input (e.g. for .center()) will be automatically transformed
            // if map has a different projection (from this proejction to the
            // one of the map)
            defaultProjection: 'EPSG:900913',
            sphericalMercator: false
        };
    },
    layer: {
        all: {
            zoomToMaxExtent: true
        },
        raster: {
            // options for raster layers
            transparent: true
        },
        vector: {
            // options for vector layers
            strategies: ['fixed']
        },
        osm: {
            isBaseLayer: false,
            transitionEffect: 'resize'
        },
        wmts: {
            format: 'image/jpeg',
            requestEncoding: 'REST',
            sphericalMercator: false
        }
    }
};

// Some utility functions

$.MapQuery = {};
$.MapQuery.util = {};
// http://blog.stevenlevithan.com/archives/parseuri (2010-12-18)
// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
$.MapQuery.util.parseUri = function (str) {
    var o = $.MapQuery.util.parseUri.options,
        m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
        uri = {},
        i = 14;

    while (i--) uri[o.key[i]] = m[i] || "";

    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
    });

    return uri;
};
$.MapQuery.util.parseUri.options = {
    strictMode: false,
    key: ["source", "protocol", "authority", "userInfo", "user",
            "password", "host", "port", "relative", "path", "directory",
            "file", "query", "anchor"],
    q: {
        name: "queryKey",
        parser: /(?:^|&)([^&=]*)=?([^&]*)/g
    },
    parser: {
        strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
        loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
        }
};
})(jQuery);
<|endoftext|>


<commit_before>import {
  TEMP_PATH
} from '../constants'

import {
  warpPlusSuccessCallback,
  warpPlusErrorCallback,
  getFileName
} from '../util'

export function compressVideo (options, callbackId) {
  const dst = `${TEMP_PATH}/compressed/${Date.now()}_${getFileName(options.src)}`
  const successCallback = warpPlusSuccessCallback(callbackId, 'compressVideo')
  const errorCallback = warpPlusErrorCallback(callbackId, 'compressVideo')
  plus.zip.compressVideo(Object.assign({}, options, {
    dst
  }), successCallback, errorCallback)
}
<commit_msg>fix(App): compressVideo filename<commit_after>import {
  TEMP_PATH
} from '../constants'

import {
  warpPlusSuccessCallback,
  warpPlusErrorCallback,
  getFileName
} from '../util'

export function compressVideo (options, callbackId) {
  const filename = `${TEMP_PATH}/compressed/${Date.now()}_${getFileName(options.src)}`
  const successCallback = warpPlusSuccessCallback(callbackId, 'compressVideo')
  const errorCallback = warpPlusErrorCallback(callbackId, 'compressVideo')
  plus.zip.compressVideo(Object.assign({}, options, {
    filename
  }), successCallback, errorCallback)
}
<|endoftext|>