<commit_before>import { SymbolStoreDB } from './symbol-store-db';

/**
 * Lets you get symbol tables and only requests them from the symbol provider once.
 * @class SymbolStore
 * @classdesc A broker that lets you request stuff as often as you want.
 */
export class SymbolStore {
  /**
   * SymbolStore constructor.
   * @param {string} dbNamePrefix   A prefix for the indexedDB database which the SymbolStore
   *                                uses internally (using asyncStorage) to store symbol tables.
   * @param {object} symbolProvider An object with a method 'requestSymbolTable(pdbName, breakpadId)'
   *                                which will be called whenever we need a symbol table. This method
   *                                needs to return a promise of [addr, syms] (the symbol table).
   */
  constructor(dbNamePrefix, symbolProvider) {
    this._symbolProvider = symbolProvider;
    this._db = new SymbolStoreDB(`${dbNamePrefix}-symbol-tables`);

    // A set of strings identifying libraries that we have requested
    // symbols for but gotten an error back.
    this._failedRequests = new Set();

    // A map with one entry for each library that we have requested (but not yet
    // received) symbols for. The keys are strings (libid), and the values are
    // promises.
    this._importingLibs = new Map();
  }

  _ensureLibraryIsInDB(lib) {
    const { pdbName, breakpadId } = lib;
    const libid = `${pdbName}/${breakpadId}`;
    if (this._failedRequests.has(libid)) {
      return Promise.reject(new Error('We\'ve tried to request a symbol table for this library before and failed, so we\'re not trying again.'));
    }
    return this._db.getLibKey(pdbName, breakpadId).catch(() => {
      if (this._importingLibs.has(libid)) {
        // We've already requested a symbol table for this library and are
        // waiting for the result, so just return the promise for the existing
        // request.
        return this._importingLibs.get(libid);
      }

      // Request the symbol table from the symbol provider.
      const symbolTablePromise = this._symbolProvider.requestSymbolTable(lib.pdbName, lib.breakpadId);
      const importPromise = symbolTablePromise.then(symbolTable => {
        this._importingLibs.delete(libid);
        return this._db.importLibrary(pdbName, breakpadId, symbolTable);
      }, error => {
        this._importingLibs.delete(libid);
        console.error(`Failed to symbolicate library ${pdbName}.`);
        throw error;
      });
      this._importingLibs.set(libid, importPromise);
      return importPromise;
    }).catch(error => {
      this._failedRequests.add(libid);
      throw error;
    });
  }

  /**
   * Get the array of symbol addresses for the given library.
   * @param  {object} lib A library object with the properties `pdbName` and `breakpadId`.
   * @return {Promise<Array<Number>>} A promise of the array of addresses.
   */
  getFuncAddressTableForLib(lib) {
    return this._ensureLibraryIsInDB(lib).then(
      libKey => this._db.getFuncAddressTableForLib(libKey));
  }

  /**
   * Get an array of symbol strings for the given symbol indices.
   * @param  {Array<Number>} requestedAddressesIndices An array where each element is the index of the symbol whose string should be looked up.
   * @param  {Object} lib A library object with the properties `pdbName` and `breakpadId`.
   * @return {Promise<Array<String>>} An promise array of strings, in the order as requested.
   */
  getSymbolsForAddressesInLib(requestedAddressesIndices, lib) {
    return this._ensureLibraryIsInDB(lib).then(
      libKey => this._db.getSymbolsForAddressesInLib(requestedAddressesIndices, libKey));
  }
}
<commit_msg>Display the error from the addon when symbolication fails.<commit_after>import { SymbolStoreDB } from './symbol-store-db';

/**
 * Lets you get symbol tables and only requests them from the symbol provider once.
 * @class SymbolStore
 * @classdesc A broker that lets you request stuff as often as you want.
 */
export class SymbolStore {
  /**
   * SymbolStore constructor.
   * @param {string} dbNamePrefix   A prefix for the indexedDB database which the SymbolStore
   *                                uses internally (using asyncStorage) to store symbol tables.
   * @param {object} symbolProvider An object with a method 'requestSymbolTable(pdbName, breakpadId)'
   *                                which will be called whenever we need a symbol table. This method
   *                                needs to return a promise of [addr, syms] (the symbol table).
   */
  constructor(dbNamePrefix, symbolProvider) {
    this._symbolProvider = symbolProvider;
    this._db = new SymbolStoreDB(`${dbNamePrefix}-symbol-tables`);

    // A set of strings identifying libraries that we have requested
    // symbols for but gotten an error back.
    this._failedRequests = new Set();

    // A map with one entry for each library that we have requested (but not yet
    // received) symbols for. The keys are strings (libid), and the values are
    // promises.
    this._importingLibs = new Map();
  }

  _ensureLibraryIsInDB(lib) {
    const { pdbName, breakpadId } = lib;
    const libid = `${pdbName}/${breakpadId}`;
    if (this._failedRequests.has(libid)) {
      return Promise.reject(new Error('We\'ve tried to request a symbol table for this library before and failed, so we\'re not trying again.'));
    }
    return this._db.getLibKey(pdbName, breakpadId).catch(() => {
      if (this._importingLibs.has(libid)) {
        // We've already requested a symbol table for this library and are
        // waiting for the result, so just return the promise for the existing
        // request.
        return this._importingLibs.get(libid);
      }

      // Request the symbol table from the symbol provider.
      const symbolTablePromise = this._symbolProvider.requestSymbolTable(lib.pdbName, lib.breakpadId);
      const importPromise = symbolTablePromise.then(symbolTable => {
        this._importingLibs.delete(libid);
        return this._db.importLibrary(pdbName, breakpadId, symbolTable);
      }, error => {
        this._importingLibs.delete(libid);
        console.error(`Failed to symbolicate library ${pdbName}: ${error}`);
        throw error;
      });
      this._importingLibs.set(libid, importPromise);
      return importPromise;
    }).catch(error => {
      this._failedRequests.add(libid);
      throw error;
    });
  }

  /**
   * Get the array of symbol addresses for the given library.
   * @param  {object} lib A library object with the properties `pdbName` and `breakpadId`.
   * @return {Promise<Array<Number>>} A promise of the array of addresses.
   */
  getFuncAddressTableForLib(lib) {
    return this._ensureLibraryIsInDB(lib).then(
      libKey => this._db.getFuncAddressTableForLib(libKey));
  }

  /**
   * Get an array of symbol strings for the given symbol indices.
   * @param  {Array<Number>} requestedAddressesIndices An array where each element is the index of the symbol whose string should be looked up.
   * @param  {Object} lib A library object with the properties `pdbName` and `breakpadId`.
   * @return {Promise<Array<String>>} An promise array of strings, in the order as requested.
   */
  getSymbolsForAddressesInLib(requestedAddressesIndices, lib) {
    return this._ensureLibraryIsInDB(lib).then(
      libKey => this._db.getSymbolsForAddressesInLib(requestedAddressesIndices, libKey));
  }
}
<|endoftext|>


<commit_before>

  var camera, scene, renderer;
  var mesh;

  var lastVelocity = 0,
      lastTime = false,
      lastPosition = 0;

  init();
  animate();
  initGyro();

  function init() {

    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    //

    camera = new THREE.PerspectiveCamera( 70, window.innerWidth /
      window.innerHeight, 1, 1000 );
      camera.position.z = 600;

      scene = new THREE.Scene();

      var geometry = new THREE.BoxGeometry( 200, 200, 200 );

      var texture = THREE.ImageUtils.loadTexture( 'textures/crate.gif' );
      texture.anisotropy = renderer.getMaxAnisotropy();

      var material = new THREE.MeshBasicMaterial( { map: texture } );

      mesh = new THREE.Mesh( geometry, material );
      scene.add( mesh );

      //

      window.addEventListener( 'resize', onWindowResize, false );

    }

    // acceleration is in (meters/second)^2
    // timestep is in seconds
    function velocity (lastVelocity, acceleration, timeStep) {
      return lastVelocity + (acceleration * timeStep);
    }

    function position (lastPosition, lastVelocity, acceleration, timeStep) {

      return lastPosition + lastVelocity * timeStep +
          (0.5 * acceleration * timeStep * timeStep);
    }

    function initGyro() {
      var listYAccelerations = [];
      console.log("start tracking");
      gyro.frequency = 10;

      // some comments
      gyro.startTracking(function(o) {
        var yNoiseUpper = 0.2,
          yNoiseLower = -0.2;

        var sum, noise = false;

        var yAcceleration = o.y.toFixed(3),
          needsRender = false,
          currentTime = new Date();

// some comments lots of comments
        if (listYAccelerations.length <= 100) {
          listYAccelerations.push(yAcceleration);
        } else if (listYAccelerations.length > 100) {

          if (noise !== false) {
            sum = 0;
            for (var i = 0; i < listYAccelerations.length; i++) {
              sum += parseFloat(listYAccelerations[i]);
            }
            noise = sum / 100;

            console.log("Noise: " + noise);
            console.log(listYAccelerations);
          }

          if (parseFloat(o.y.toFixed(2)) >= yNoiseUpper ||
              parseFloat(o.y.toFixed(2)) <= yNoiseLower) {

            // dividing by 1000 to decrease velocity by 1000 and position by
            // 100000
            // time is in seconds
            // if there is no last time
            // or if last time is greater than frequency
            if (lastTime && lastTime <= (gyro.frequency * 2) / 1000) {
              timeStep = (currentTime - lastTime) / 1000;
              lastTime = currentTime;
            } else {
              lastTime = currentTime;
              timeStep = (currentTime - lastTime) / 1000;
            }

            console.log("lastPosition: " + lastPosition);
            console.log("lastVelocity: " + lastVelocity);
            console.log("timeStep: " + timeStep);
            console.log("acceleration: " + yAcceleration);
            // only do this if acceleration > then noise
            lastVelocity = velocity(lastVelocity, yAcceleration, timeStep);
            lastPosition = position(lastPosition, lastVelocity, yAcceleration,
                timeStep);

            // if (newY <= 400 && newY >= -400) {
            //   mesh.position.y = newY;
            //   needsRender = true;
            // }
            // if (needsRender) {
            //   renderer.render( scene, camera );
            //   console.log(mesh.position.y);
            // }
          }
        }

        if (parseFloat(o.x.toFixed(1)) >= 0.5) {
          console.log("x-acceleration: "  + o.x.toFixed(3));
        }

        if (parseFloat(o.z.toFixed(1)) >= 9.8) {
          console.log("z-acceleration: "  + o.z.toFixed(3));
        }
      });
    }

    function onWindowResize() {

      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();

      renderer.setSize( window.innerWidth, window.innerHeight );

    }

    function animate() {

      requestAnimationFrame( animate );

      renderer.render( scene, camera );

    }
<commit_msg>fixed noise<commit_after>

  var camera, scene, renderer;
  var mesh;

  var lastVelocity = 0,
      lastTime = false,
      lastPosition = 0;

  init();
  animate();
  initGyro();

  function init() {

    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    //

    camera = new THREE.PerspectiveCamera( 70, window.innerWidth /
      window.innerHeight, 1, 1000 );
      camera.position.z = 600;

      scene = new THREE.Scene();

      var geometry = new THREE.BoxGeometry( 200, 200, 200 );

      var texture = THREE.ImageUtils.loadTexture( 'textures/crate.gif' );
      texture.anisotropy = renderer.getMaxAnisotropy();

      var material = new THREE.MeshBasicMaterial( { map: texture } );

      mesh = new THREE.Mesh( geometry, material );
      scene.add( mesh );

      //

      window.addEventListener( 'resize', onWindowResize, false );

    }

    // acceleration is in (meters/second)^2
    // timestep is in seconds
    function velocity (lastVelocity, acceleration, timeStep) {
      return lastVelocity + (acceleration * timeStep);
    }

    function position (lastPosition, lastVelocity, acceleration, timeStep) {

      return lastPosition + lastVelocity * timeStep +
          (0.5 * acceleration * timeStep * timeStep);
    }

    function initGyro() {
      var listYAccelerations = [];
      var noise = false;
      console.log("start tracking");
      gyro.frequency = 10;

      // some comments
      gyro.startTracking(function(o) {
        var yNoiseUpper = 0.2,
          yNoiseLower = -0.2;

        var sum;

        var yAcceleration = o.y.toFixed(3),
          needsRender = false,
          currentTime = new Date();

// some comments lots of comments
        if (listYAccelerations.length <= 100) {
          listYAccelerations.push(yAcceleration);
        } else if (listYAccelerations.length > 100) {

          if (noise !== false) {
            sum = 0;
            for (var i = 0; i < listYAccelerations.length; i++) {
              sum += parseFloat(listYAccelerations[i]);
            }
            noise = sum / 100;

            console.log("Noise: " + noise);
            console.log(listYAccelerations);
          }

          if (parseFloat(o.y.toFixed(2)) >= yNoiseUpper ||
              parseFloat(o.y.toFixed(2)) <= yNoiseLower) {

            // dividing by 1000 to decrease velocity by 1000 and position by
            // 100000
            // time is in seconds
            // if there is no last time
            // or if last time is greater than frequency
            if (lastTime && lastTime <= (gyro.frequency * 2) / 1000) {
              timeStep = (currentTime - lastTime) / 1000;
              lastTime = currentTime;
            } else {
              lastTime = currentTime;
              timeStep = (currentTime - lastTime) / 1000;
            }

            console.log("lastPosition: " + lastPosition);
            console.log("lastVelocity: " + lastVelocity);
            console.log("timeStep: " + timeStep);
            console.log("acceleration: " + yAcceleration);
            // only do this if acceleration > then noise
            lastVelocity = velocity(lastVelocity, yAcceleration, timeStep);
            lastPosition = position(lastPosition, lastVelocity, yAcceleration,
                timeStep);

            // if (newY <= 400 && newY >= -400) {
            //   mesh.position.y = newY;
            //   needsRender = true;
            // }
            // if (needsRender) {
            //   renderer.render( scene, camera );
            //   console.log(mesh.position.y);
            // }
          }
        }

        if (parseFloat(o.x.toFixed(1)) >= 0.5) {
          console.log("x-acceleration: "  + o.x.toFixed(3));
        }

        if (parseFloat(o.z.toFixed(1)) >= 9.8) {
          console.log("z-acceleration: "  + o.z.toFixed(3));
        }
      });
    }

    function onWindowResize() {

      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();

      renderer.setSize( window.innerWidth, window.innerHeight );

    }

    function animate() {

      requestAnimationFrame( animate );

      renderer.render( scene, camera );

    }
<|endoftext|>


<commit_before>import { on, off, createEl, preventDefault } from 'core/util/dom';
import Map from 'map/Map';
import Control from './Control';

/**
 * @property {Object}   options - options
 * @property {String|Object}   [options.position="top-left"]  - position of the zoom control.
 * @property {Boolean}  [options.slider=true]                         - Whether to display the slider
 * @property {Boolean}  [options.zoomLevel=true]                      - Whether to display the text box of zoom level
 * @memberOf control.Zoom
 * @instance
 */
const options = {
    'position': 'top-left',
    'slider': true,
    'zoomLevel': true
};

/**
 * @classdesc
 * A zoom control with buttons to zoomin/zoomout and a slider indicator for the zoom level.
 * @category control
 * @extends control.Control
 * @memberOf control
 * @example
 * var zoomControl = new Zoom({
 *     position : 'top-left',
 *     slider : true,
 *     zoomLevel : false
 * }).addTo(map);
 */
class Zoom extends Control {
    /**
     * method to build DOM of the control
     * @param  {Map} map map to build on
     * @return {HTMLDOMElement}
     */
    buildOn(map) {
        this._map = map;
        const options = this.options;

        const dom = createEl('div', 'maptalks-zoom');

        if (options['zoomLevel']) {
            const levelDOM = createEl('span', 'maptalks-zoom-zoomlevel');
            dom.appendChild(levelDOM);
            this._levelDOM = levelDOM;
        }

        const zoomDOM = createEl('div', 'maptalks-zoom-slider');

        const zoomInButton = createEl('a', 'maptalks-zoom-zoomin');
        zoomInButton.href = 'javascript:;';
        zoomInButton.innerHTML = '+';
        zoomDOM.appendChild(zoomInButton);
        this._zoomInButton = zoomInButton;

        if (options['slider']) {
            const sliderDOM = createEl('div', 'maptalks-zoom-slider-box');
            const ruler = createEl('div', 'maptalks-zoom-slider-ruler');
            const reading = createEl('span', 'maptalks-zoom-slider-reading');
            const dot = createEl('span', 'maptalks-zoom-slider-dot');
            ruler.appendChild(reading);
            ruler.appendChild(dot);
            sliderDOM.appendChild(ruler);
            zoomDOM.appendChild(sliderDOM);
            this._sliderBox = sliderDOM;
            this._sliderRuler = ruler;
            this._sliderReading = reading;
            this._sliderDot = dot;
        }

        const zoomOutButton = createEl('a', 'maptalks-zoom-zoomout');
        zoomOutButton.href = 'javascript:;';
        zoomOutButton.innerHTML = '-';
        zoomDOM.appendChild(zoomOutButton);
        this._zoomOutButton = zoomOutButton;

        dom.appendChild(zoomDOM);

        map.on('_zoomend _zoomstart _spatialreferencechange', this._update, this);

        this._update();
        this._registerDomEvents();

        return dom;
    }

    _update() {
        const map = this.getMap();
        if (this._sliderBox) {
            const pxUnit = 10;
            const totalRange = (map.getMaxZoom() - map.getMinZoom()) * pxUnit;
            this._sliderBox.style.height = totalRange + 6 + 'px';
            this._sliderRuler.style.height = totalRange + 'px';
            const zoomRange = (map.getZoom() - map.getMinZoom()) * pxUnit;
            this._sliderReading.style.height = zoomRange + 'px';
            this._sliderDot.style.bottom = zoomRange + 'px';
        }
        if (this._levelDOM) {
            this._levelDOM.innerHTML = map.getZoom();
        }

    }

    _registerDomEvents() {
        if (this._zoomInButton) {
            on(this._zoomInButton, 'click', this._onZoomInClick, this);
        }
        if (this._zoomOutButton) {
            on(this._zoomOutButton, 'click', this._onZoomOutClick, this);
        }
        //TODO slider dot拖放缩放逻辑还没有实现
    }

    _onZoomInClick(e) {
        preventDefault(e);
        this.getMap().zoomIn();
    }

    _onZoomOutClick(e) {
        preventDefault(e);
        this.getMap().zoomOut();
    }

    onRemove() {
        if (this._zoomInButton) {
            off(this._zoomInButton, 'click', this._onZoomInClick, this);
        }
        if (this._zoomOutButton) {
            off(this._zoomOutButton, 'click', this._onZoomOutClick, this);
        }
    }
}

Zoom.mergeOptions(options);

Map.mergeOptions({
    'zoomControl': false
});

Map.addOnLoadHook(function () {
    if (this.options['zoomControl']) {
        this.zoomControl = new Zoom(this.options['zoomControl']);
        this.addControl(this.zoomControl);
    }
});

export default Zoom;
<commit_msg>toFixed in zoom control<commit_after>import { isInteger } from 'core/util';
import { on, off, createEl, preventDefault } from 'core/util/dom';
import Map from 'map/Map';
import Control from './Control';

/**
 * @property {Object}   options - options
 * @property {String|Object}   [options.position="top-left"]  - position of the zoom control.
 * @property {Boolean}  [options.slider=true]                         - Whether to display the slider
 * @property {Boolean}  [options.zoomLevel=true]                      - Whether to display the text box of zoom level
 * @memberOf control.Zoom
 * @instance
 */
const options = {
    'position': 'top-left',
    'slider': true,
    'zoomLevel': true
};

/**
 * @classdesc
 * A zoom control with buttons to zoomin/zoomout and a slider indicator for the zoom level.
 * @category control
 * @extends control.Control
 * @memberOf control
 * @example
 * var zoomControl = new Zoom({
 *     position : 'top-left',
 *     slider : true,
 *     zoomLevel : false
 * }).addTo(map);
 */
class Zoom extends Control {
    /**
     * method to build DOM of the control
     * @param  {Map} map map to build on
     * @return {HTMLDOMElement}
     */
    buildOn(map) {
        this._map = map;
        const options = this.options;

        const dom = createEl('div', 'maptalks-zoom');

        if (options['zoomLevel']) {
            const levelDOM = createEl('span', 'maptalks-zoom-zoomlevel');
            dom.appendChild(levelDOM);
            this._levelDOM = levelDOM;
        }

        const zoomDOM = createEl('div', 'maptalks-zoom-slider');

        const zoomInButton = createEl('a', 'maptalks-zoom-zoomin');
        zoomInButton.href = 'javascript:;';
        zoomInButton.innerHTML = '+';
        zoomDOM.appendChild(zoomInButton);
        this._zoomInButton = zoomInButton;

        if (options['slider']) {
            const sliderDOM = createEl('div', 'maptalks-zoom-slider-box');
            const ruler = createEl('div', 'maptalks-zoom-slider-ruler');
            const reading = createEl('span', 'maptalks-zoom-slider-reading');
            const dot = createEl('span', 'maptalks-zoom-slider-dot');
            ruler.appendChild(reading);
            ruler.appendChild(dot);
            sliderDOM.appendChild(ruler);
            zoomDOM.appendChild(sliderDOM);
            this._sliderBox = sliderDOM;
            this._sliderRuler = ruler;
            this._sliderReading = reading;
            this._sliderDot = dot;
        }

        const zoomOutButton = createEl('a', 'maptalks-zoom-zoomout');
        zoomOutButton.href = 'javascript:;';
        zoomOutButton.innerHTML = '-';
        zoomDOM.appendChild(zoomOutButton);
        this._zoomOutButton = zoomOutButton;

        dom.appendChild(zoomDOM);

        map.on('_zoomend _zoomstart _spatialreferencechange', this._update, this);

        this._update();
        this._registerDomEvents();

        return dom;
    }

    _update() {
        const map = this.getMap();
        if (this._sliderBox) {
            const pxUnit = 10;
            const totalRange = (map.getMaxZoom() - map.getMinZoom()) * pxUnit;
            this._sliderBox.style.height = totalRange + 6 + 'px';
            this._sliderRuler.style.height = totalRange + 'px';
            const zoomRange = (map.getZoom() - map.getMinZoom()) * pxUnit;
            this._sliderReading.style.height = zoomRange + 'px';
            this._sliderDot.style.bottom = zoomRange + 'px';
        }
        if (this._levelDOM) {
            let zoom = map.getZoom();
            if (!isInteger(zoom)) {
                zoom = zoom.toFixed(1);
            }
            this._levelDOM.innerHTML = zoom;
        }

    }

    _registerDomEvents() {
        if (this._zoomInButton) {
            on(this._zoomInButton, 'click', this._onZoomInClick, this);
        }
        if (this._zoomOutButton) {
            on(this._zoomOutButton, 'click', this._onZoomOutClick, this);
        }
        //TODO slider dot拖放缩放逻辑还没有实现
    }

    _onZoomInClick(e) {
        preventDefault(e);
        this.getMap().zoomIn();
    }

    _onZoomOutClick(e) {
        preventDefault(e);
        this.getMap().zoomOut();
    }

    onRemove() {
        if (this._zoomInButton) {
            off(this._zoomInButton, 'click', this._onZoomInClick, this);
        }
        if (this._zoomOutButton) {
            off(this._zoomOutButton, 'click', this._onZoomOutClick, this);
        }
    }
}

Zoom.mergeOptions(options);

Map.mergeOptions({
    'zoomControl': false
});

Map.addOnLoadHook(function () {
    if (this.options['zoomControl']) {
        this.zoomControl = new Zoom(this.options['zoomControl']);
        this.addControl(this.zoomControl);
    }
});

export default Zoom;
<|endoftext|>


<commit_before>/*
 * L.Control.Zoom is used for the default zoom buttons on the map.
 */

L.Control.Zoom = L.Control.extend({
	options: {
		position: 'topleft',
		zoomInText: '+',
		zoomInTitle: 'Zoom in',
		zoomOutText: '-',
		zoomOutTitle: 'Zoom out'
	},

	onAdd: function (map) {
		var zoomName = 'leaflet-control-zoom',
		    container = L.DomUtil.create('div', zoomName + ' leaflet-bar'),
		    options = this.options;

		this._zoomInButton  = this._createButton(options.zoomInText, options.zoomInTitle,
		        zoomName + '-in',  container, this._zoomIn);
		this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
		        zoomName + '-out', container, this._zoomOut);

		this._updateDisabled();
		map.on('zoomend zoomlevelschange', this._updateDisabled, this);

		return container;
	},

	onRemove: function (map) {
		map.off('zoomend zoomlevelschange', this._updateDisabled, this);
	},

	_zoomIn: function (e) {
		this._map.zoomIn(e.shiftKey ? 3 : 1);
	},

	_zoomOut: function (e) {
		this._map.zoomOut(e.shiftKey ? 3 : 1);
	},

	_createButton: function (html, title, className, container, fn) {
		var link = L.DomUtil.create('a', className, container);
		link.innerHTML = html;
		link.href = '#';
		link.title = title;

		L.DomEvent
		    .on(link, 'mousedown dblclick', L.DomEvent.stopPropagation)
		    .on(link, 'click', L.DomEvent.stop)
		    .on(link, 'click', fn, this)
		    .on(link, 'click', this._refocusOnMap, this);

		return link;
	},

	_updateDisabled: function () {
		var map = this._map,
			className = 'leaflet-disabled';

		L.DomUtil.removeClass(this._zoomInButton, className);
		L.DomUtil.removeClass(this._zoomOutButton, className);

		if (map._zoom === map.getMinZoom()) {
			L.DomUtil.addClass(this._zoomOutButton, className);
		}
		if (map._zoom === map.getMaxZoom()) {
			L.DomUtil.addClass(this._zoomInButton, className);
		}
	}
});

L.Map.mergeOptions({
	zoomControl: true
});

L.Map.addInitHook(function () {
	if (this.options.zoomControl) {
		this.zoomControl = new L.Control.Zoom();
		this.addControl(this.zoomControl);
	}
});

L.control.zoom = function (options) {
	return new L.Control.Zoom(options);
};

<commit_msg>add Control.Zoom disable/enable methods, close #3172<commit_after>/*
 * L.Control.Zoom is used for the default zoom buttons on the map.
 */

L.Control.Zoom = L.Control.extend({
	options: {
		position: 'topleft',
		zoomInText: '+',
		zoomInTitle: 'Zoom in',
		zoomOutText: '-',
		zoomOutTitle: 'Zoom out'
	},

	onAdd: function (map) {
		var zoomName = 'leaflet-control-zoom',
		    container = L.DomUtil.create('div', zoomName + ' leaflet-bar'),
		    options = this.options;

		this._zoomInButton  = this._createButton(options.zoomInText, options.zoomInTitle,
		        zoomName + '-in',  container, this._zoomIn);
		this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
		        zoomName + '-out', container, this._zoomOut);

		this._updateDisabled();
		map.on('zoomend zoomlevelschange', this._updateDisabled, this);

		return container;
	},

	onRemove: function (map) {
		map.off('zoomend zoomlevelschange', this._updateDisabled, this);
	},

	disable: function () {
		this._enabled = false;
		this._updateDisabled();
		return this;
	},

	enable: function () {
		this._enabled = true;
		this._updateDisabled();
		return this;
	},

	_zoomIn: function (e) {
		if (this._enabled) {
			this._map.zoomIn(e.shiftKey ? 3 : 1);
		}
	},

	_zoomOut: function (e) {
		if (this._enabled) {
			this._map.zoomOut(e.shiftKey ? 3 : 1);
		}
	},

	_createButton: function (html, title, className, container, fn) {
		var link = L.DomUtil.create('a', className, container);
		link.innerHTML = html;
		link.href = '#';
		link.title = title;

		L.DomEvent
		    .on(link, 'mousedown dblclick', L.DomEvent.stopPropagation)
		    .on(link, 'click', L.DomEvent.stop)
		    .on(link, 'click', fn, this)
		    .on(link, 'click', this._refocusOnMap, this);

		return link;
	},

	_updateDisabled: function () {
		var map = this._map,
			className = 'leaflet-disabled';

		L.DomUtil.removeClass(this._zoomInButton, className);
		L.DomUtil.removeClass(this._zoomOutButton, className);

		if (!this._enabled || map._zoom === map.getMinZoom()) {
			L.DomUtil.addClass(this._zoomOutButton, className);
		}
		if (!this._enabled || map._zoom === map.getMaxZoom()) {
			L.DomUtil.addClass(this._zoomInButton, className);
		}
	}
});

L.Map.mergeOptions({
	zoomControl: true
});

L.Map.addInitHook(function () {
	if (this.options.zoomControl) {
		this.zoomControl = new L.Control.Zoom();
		this.addControl(this.zoomControl);
	}
});

L.control.zoom = function (options) {
	return new L.Control.Zoom(options);
};

<|endoftext|>


<commit_before>app.controller('ApiListController', ['$scope', 'kdAjax', 'kdToast', 'viewFactory', function ($scope, kdAjax, kdToast, viewFactory) {

    viewFactory.title = 'API List';
    viewFactory.prevUrl = null;

    $scope.formInput = {
        apiName: '',
        requestHost: '',
        requestPath: '',
        upstreamUrl: '',
        preserveHost: true,
        stripRequestPath: false
    };

    $scope.apiList = [];
    $scope.fetchApiList = function (url) {
        kdAjax.get({
            resource: url
        }).then(function (response) {
            $scope.nextUrl = response.data.next || '';

            for (var i=0; i<response.data.data.length; i++ ) {
                $scope.apiList.push(response.data.data[i])
            }

        }, function () {
            kdToast.error('Could not load list of APIs')
        })
    };

    var panelAdd = angular.element('div#panelAdd');
    var apiForm = panelAdd.children('div.panel__body').children('form');

    var table = angular.element('table#apiTable');

    table.on('click', 'i.state-highlight', function (event) {
        var icon = angular.element(event.target);
        var payload = {};
        var attribute = icon.data('attribute');

        payload[attribute] = ((icon.hasClass('success')) ? false : true );

        kdAjax.patch({
            resource: '/apis/' + icon.data('api-id')
        }).then(function () {
            if ( payload[attribute] == true) {
                icon.removeClass('default').addClass('success');

            } else {
                icon.removeClass('success').addClass('default');
            }

            kdToast.success('Attribute ' + attribute + ' set to ' + payload[attribute]);

        }, function () {
            kdToast.error('Unable to update ' + attribute);
        })
    });

    panelAdd.children('div.panel__heading').on('click', function () {
        apiForm.slideToggle(300)
    });

    apiForm.on('submit', function (event) {
        event.preventDefault();

        var payload = {};

        if ($scope.formInput.apiName.trim().length > 1) {
            payload.name = $scope.formInput.apiName;
        }

        if ($scope.formInput.requestHost.trim().length > 1) {
            payload.request_host = $scope.formInput.requestHost;
        }

        if (typeof payload.name === 'undefined' &&
                typeof payload.request_host === 'undefined') {
            apiForm.find('input[name="apiName"]').focus();
            return false;
        }

        if ($scope.formInput.requestPath.trim().length > 1) {
            payload.request_path = $scope.formInput.requestPath;
        }

        if ( typeof payload.request_path === 'undefined' &&
            typeof payload.request_host === 'undefined') {
            apiForm.find('input[name="requestPath"]').focus();
            return false;
        }

        if ($scope.formInput.upstreamUrl.trim().length > 1) {
            payload.upstream_url = $scope.formInput.upstreamUrl;
        } else {
            apiForm.find('input[name="upstreamUrl"]').focus();
            return false;
        }

        payload.strip_request_path = $scope.formInput.stripRequestPath;
        payload.preserve_host = $scope.formInput.preserveHost;

        kdAjax.post({
            resource: '/apis/',
            data: payload
        }).then(function (response) {
            $scope.apiList.push(response.data);

            kdToast.success('New API added')

        }, function (response) {
            kdToast.error(response.data)
        });

        return false
    });

    apiForm.on('click', 'button[name="actionCancel"]', function () {
        apiForm.slideUp(300);
    });

    $scope.fetchApiList('/apis');
}]);<commit_msg>[added] ajax and toast dependency<commit_after>app.controller('ApiListController', ['$scope', 'ajax', 'toast', 'viewFactory', function ($scope, ajax, toast, viewFactory) {

    viewFactory.title = 'API List';
    viewFactory.prevUrl = null;

    $scope.formInput = {
        apiName: '',
        requestHost: '',
        requestPath: '',
        upstreamUrl: '',
        preserveHost: true,
        stripRequestPath: false
    };

    $scope.apiList = [];
    $scope.fetchApiList = function (url) {
        ajax.get({
            resource: url
        }).then(function (response) {
            $scope.nextUrl = response.data.next || '';

            for (var i=0; i<response.data.data.length; i++ ) {
                $scope.apiList.push(response.data.data[i])
            }

        }, function () {
            toast.error('Could not load list of APIs')
        })
    };

    var panelAdd = angular.element('div#panelAdd');
    var apiForm = panelAdd.children('div.panel__body').children('form');

    var table = angular.element('table#apiTable');

    table.on('click', 'i.state-highlight', function (event) {
        var icon = angular.element(event.target);
        var payload = {};
        var attribute = icon.data('attribute');

        payload[attribute] = ((icon.hasClass('success')) ? false : true );

        ajax.patch({
            resource: '/apis/' + icon.data('api-id')
        }).then(function () {
            if ( payload[attribute] == true) {
                icon.removeClass('default').addClass('success');

            } else {
                icon.removeClass('success').addClass('default');
            }

            toast.success('Attribute ' + attribute + ' set to ' + payload[attribute]);

        }, function () {
            toast.error('Unable to update ' + attribute);
        })
    });

    panelAdd.children('div.panel__heading').on('click', function () {
        apiForm.slideToggle(300)
    });

    apiForm.on('submit', function (event) {
        event.preventDefault();

        var payload = {};

        if ($scope.formInput.apiName.trim().length > 1) {
            payload.name = $scope.formInput.apiName;
        }

        if ($scope.formInput.requestHost.trim().length > 1) {
            payload.request_host = $scope.formInput.requestHost;
        }

        if (typeof payload.name === 'undefined' &&
                typeof payload.request_host === 'undefined') {
            apiForm.find('input[name="apiName"]').focus();
            return false;
        }

        if ($scope.formInput.requestPath.trim().length > 1) {
            payload.request_path = $scope.formInput.requestPath;
        }

        if ( typeof payload.request_path === 'undefined' &&
            typeof payload.request_host === 'undefined') {
            apiForm.find('input[name="requestPath"]').focus();
            return false;
        }

        if ($scope.formInput.upstreamUrl.trim().length > 1) {
            payload.upstream_url = $scope.formInput.upstreamUrl;
        } else {
            apiForm.find('input[name="upstreamUrl"]').focus();
            return false;
        }

        payload.strip_request_path = $scope.formInput.stripRequestPath;
        payload.preserve_host = $scope.formInput.preserveHost;

        ajax.post({
            resource: '/apis/',
            data: payload
        }).then(function (response) {
            $scope.apiList.push(response.data);

            toast.success('New API added')

        }, function (response) {
            toast.error(response.data)
        });

        return false
    });

    apiForm.on('click', 'button[name="actionCancel"]', function () {
        apiForm.slideUp(300);
    });

    $scope.fetchApiList('/apis');
}]);<|endoftext|>


<commit_before>(function() {

    Ext.define('Hatimeria.core.form.UserSwitch', {
        extend: 'Ext.form.ComboBox',
        mixins: {
            translationable: 'Hatimeria.core.mixins.Translationable'
        },
        transDomain: 'HatimeriaExtJSBundle',
        transNS: 'switch',

        constructor: function(cfg)
        {
            var config = {
                fieldLabel: this.__("action"),
                queryMode: 'remote',
                displayField: 'username',
                valueField: 'username',
                listeners: {
                    scope: this,
                    select: function(field, record) {
                        location.href = Routing.generate('homepage') + '?_switch_user=' + record[0].get('username');
                    }
                }
            };

            Ext.apply(config, cfg || {});

            this.callParent([config]);
        }
    });

})();
<commit_msg>user switch now extends hatimeria combo box<commit_after>(function() {

    Ext.define('Hatimeria.core.form.UserSwitch', {
        extend: 'Hatimeria.core.field.ComboBox',
        mixins: {
            translationable: 'Hatimeria.core.mixins.Translationable'
        },
        transDomain: 'HatimeriaExtJSBundle',
        transNS: 'switch',

        constructor: function(cfg)
        {
            var config = {
                fieldLabel: this.__("action"),
                queryMode: 'remote',
                displayField: 'username',
                valueField: 'username',
                listeners: {
                    scope: this,
                    select: function(field, record) {
                        location.href = Routing.generate('homepage') + '?_switch_user=' + record[0].get('username');
                    }
                }
            };

            Ext.apply(config, cfg || {});

            this.callParent([config]);
        }
    });

})();
<|endoftext|>


<commit_before>/* @flow */

import { warn } from '../util/index'
import { hasSymbol } from 'core/util/env'
import { defineReactive, observerState } from '../observer/index'
import { hasOwn } from 'shared/util'

export function initProvide (vm: Component) {
  const provide = vm.$options.provide
  if (provide) {
    vm._provided = typeof provide === 'function'
      ? provide.call(vm)
      : provide
  }
}

export function initInjections (vm: Component) {
  const result = resolveInject(vm.$options.inject, vm)
  if (result) {
    observerState.shouldConvert = false
    Object.keys(result).forEach(key => {
      /* istanbul ignore else */
      if (process.env.NODE_ENV !== 'production') {
        defineReactive(vm, key, result[key], () => {
          warn(
            `Avoid mutating an injected value directly since the changes will be ` +
            `overwritten whenever the provided component re-renders. ` +
            `injection being mutated: "${key}"`,
            vm
          )
        })
      } else {
        defineReactive(vm, key, result[key])
      }
    })
    observerState.shouldConvert = true
  }
}

export function resolveInject (inject: any, vm: Component): ?Object {
  if (inject) {
    // inject is :any because flow is not smart enough to figure out cached
    const result = Object.create(null)
    const keys = hasSymbol
      ? Reflect.ownKeys(inject).filter(key => {
        /* istanbul ignore next */
        return Object.getOwnPropertyDescriptor(inject, key).enumerable
      })
      : Object.keys(inject)

    for (let i = 0; i < keys.length; i++) {
      const key = keys[i]
      const provideKey = inject[key].from
      let source = vm
      while (source) {
        if (source._provided && hasOwn(source._provided, provideKey)) {
          result[key] = source._provided[provideKey]
          break
        }
        source = source.$parent
      }
      if (!source) {
        if ('default' in inject[key]) {
          const provideDefault = inject[key].default
          result[key] = typeof provideDefault === 'function'
            ? provideDefault.call(vm)
            : provideDefault
        } else if (process.env.NODE_ENV !== 'production') {
          warn(`Injection "${key}" not found`, vm)
        }
      }
    }
    return result
  }
}
<commit_msg>chore: merge imports (#7762)<commit_after>/* @flow */

import { warn, hasSymbol } from '../util/index'
import { defineReactive, observerState } from '../observer/index'
import { hasOwn } from 'shared/util'

export function initProvide (vm: Component) {
  const provide = vm.$options.provide
  if (provide) {
    vm._provided = typeof provide === 'function'
      ? provide.call(vm)
      : provide
  }
}

export function initInjections (vm: Component) {
  const result = resolveInject(vm.$options.inject, vm)
  if (result) {
    observerState.shouldConvert = false
    Object.keys(result).forEach(key => {
      /* istanbul ignore else */
      if (process.env.NODE_ENV !== 'production') {
        defineReactive(vm, key, result[key], () => {
          warn(
            `Avoid mutating an injected value directly since the changes will be ` +
            `overwritten whenever the provided component re-renders. ` +
            `injection being mutated: "${key}"`,
            vm
          )
        })
      } else {
        defineReactive(vm, key, result[key])
      }
    })
    observerState.shouldConvert = true
  }
}

export function resolveInject (inject: any, vm: Component): ?Object {
  if (inject) {
    // inject is :any because flow is not smart enough to figure out cached
    const result = Object.create(null)
    const keys = hasSymbol
      ? Reflect.ownKeys(inject).filter(key => {
        /* istanbul ignore next */
        return Object.getOwnPropertyDescriptor(inject, key).enumerable
      })
      : Object.keys(inject)

    for (let i = 0; i < keys.length; i++) {
      const key = keys[i]
      const provideKey = inject[key].from
      let source = vm
      while (source) {
        if (source._provided && hasOwn(source._provided, provideKey)) {
          result[key] = source._provided[provideKey]
          break
        }
        source = source.$parent
      }
      if (!source) {
        if ('default' in inject[key]) {
          const provideDefault = inject[key].default
          result[key] = typeof provideDefault === 'function'
            ? provideDefault.call(vm)
            : provideDefault
        } else if (process.env.NODE_ENV !== 'production') {
          warn(`Injection "${key}" not found`, vm)
        }
      }
    }
    return result
  }
}
<|endoftext|>


<commit_before>// = encapsulating textarea, jQuery plugin =
//
// * author: Marek 'saji' Augustynowicz
// * license: MIT (LICENSE.md file should be distributed with the code)
// * http://github.com/marek-saji/jquery.encapsulating
//
// == USAGE ==
// {{{
// <link rel="stylesheet" type="text/cxx" href="jquery.encapsulating.css" />
// <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
// <script type="text/javascript" src="jquery.encapsulating.js"></script>
// <script type="text/javascript">
//    $(function(){
//        $('textarea.foo').encapsulating();
//
//        // you may also specify settings here
//        $('textarea.bar').encapsulating({
//            editTitle: 'click to edit this tag'
//        });
//    });
// </script>
//
// You can also specify settings with data-encapsulating attribute:
//
// <textarea data-encapsulating='{"debug": true}'>
//     first tag, 2nd tag
//     last tag
// </textarea>
//
// }}}
//
// == TODO ==
// * make it work in IE
// * make it work with autoexpandable
// * make it possible to choose separator other than comma

(function($){ // context scope begin

    // == {{{default_settings}}} ==
    var default_settings = {
        // text to display at "delete item" buttom
        removeText: '×',
        // value of "delete item" buttom title attribute
        removeTitle: '',
        // vaue of item title attribute
        editTitle: '',
        // in debug mode, textarea element is visible,
        debug: false
    };

    // == {{{toolbox}}} ==
    // some utility functions
    var toolbox = {

        // === {{{toolbox.transEventKey}}} ===
        // translate event object into easier switchable string
        // e.g. "keypress:shift+meta+97
        transEventKey: function(e) {
            var key = e.type + ':';
            var modifiers = ['alt','shift','ctrl','meta'];
            for (var i in modifiers)
                e[modifiers[i]+'Key'] && (key += modifiers[i]+'+');
            key += e.keyCode;

            return key;
        }, // toolbox.transEventKey

        // === {{{toolbox.cursorAtStart}}} ===
        // checks whether cursor is at the begining of given input
        //
        // Params:
        // * input (DOM or jQuery object)
        cursorAtStart: function(input) {
            if (input instanceof $)
                input = [0];

            if (!input.createTextRange)
            {
                var start = input.selectionStart;
            }
            else
            {
                var r = document.selection.createRange().duplicate();
                r.moveEnd('character', input.value.length);
                if (r.text == '')
                    var start = input.value.length;
                else
                    var start = input.value.lastIndexOf(r.text);
            }
            return 0 == start;
        }, // toolbox.cursorAtStart

        // === {{{toolbox.cursorAtEnd}}} ===
        // checks whether cursor is at the end of given input
        //
        // Params:
        // * input (DOM or jQuery object)
        cursorAtEnd: function(input) {
            if (input instanceof $)
                input = [0];

            if (!input.createTextRange)
            {
                var end = input.selectionEnd;
            }
            else
            {
                var r = document.selection.createRange().duplicate();
                r.moveStart('character', -this.value.length);
                var end = r.text.length;
            }
            return input.value.length == end;
        } // toolbox.cursorAtEnd

    }; // var toolbox

    // == {{{encapsulating}}} ==
    // function called with {{{$(selector).encapsulating()}}},
    // {{{this}}} is a set of matched elements
    $.fn.encapsulating = function(user_settings){

        var invoke_settings = {};

        // merge default and user settings
        $.extend(invoke_settings, default_settings, user_settings);

        return this.each(function(){

            var settings = {};

            // === original textarea ===
            var $textarea = $(this),
                had_focus = false;

            // Snizzle does not support this on IE
            try {
                had_focus = $textarea.is(':focus');
            } catch(e) {}

            // merge-in settings specified in `data-encapsulating` attribute
            $.extend(settings, invoke_settings, $textarea.data('encapsulating'));

            // === textarea replacement ===
            var $area = $('<label />', {
                    width: $textarea.width(),
                    height: $textarea.height(),
                    'class': 'encapsulating-textarea '
                             + $textarea.attr('class')
                             + (settings.debug ? ' debug' : ''),
                    // inherit textarea-specific css properties
                    css: {
                        resize: $textarea.css('resize')
                    }
                })
                // ==== sync encapsulated items to hidden textarea ====
                .bind('syncToTextarea.encapsulating', function(){
                    var $area = $(this);
                    var new_val = [];
                    $area.find('a > .text').each(function(){
                        new_val.push($(this).text());
                    });
                    $textarea.val(new_val.join("\n"));
                }) // syncToTextarea.encapsulating event
                // ==== encapsulate textarea contents ====
                .bind('syncFromTextarea.encapsulating', function(){
                    var $area = $(this);
                    $area.children('a').remove();
                    $area.trigger('push.encapsulating', [$textarea.val().split(/[\n\r,]+/)]);
                }) // syncFromTextarea.encapsulating event
                // ==== encapsulate an item ====
                // Params:
                //  * e (Event): event object
                //  * el (string, array, DOM, jQuery)
                //  ** string to encapsulate
                //  ** DOMor jQuery with input to encapsulate, it will be emptied afterwards and moved at the end of the area
                //  ** array with any of the above
                .bind('push.encapsulating', function(e, el){
                    var $area = $(this);
                    if ($.type(el) == 'string')
                        var val = el;
                    else if ($.type(el) == 'array')
                    {
                        for (var idx in el)
                            $area.trigger('push.encapsulating', [el[idx]]);
                        return;
                    }
                    else
                    {
                        var $el = $(el);
                        switch ($el.length)
                        {
                            case 0:
                                return;
                            case 1:
                                break;
                            default:
                                $el.each(function(){
                                    $area.trigger('push.encapsulating', [this]);
                                });
                                return;
                        }

                        var val = $el.val();
                        $el.val('');
                    }

                    // trim whitespaces
                    val = val.replace(/^\s+|\s+$/g, '');

                    // create new item
                    if (val)
                    {
                        var $item = $('<a />', {
                            href: '#'
                        });

                        $('<span />', {
                            'class': 'text',
                            text: val,
                            title: settings.editLabel
                        }).appendTo($item);

                        $('<span />', {
                            'class': 'remove',
                            text: settings.removeText,
                            title: settings.removeLabel,
                        })
                        .appendTo($item);

                        $item.insertBefore($input);
                    }

                    $input
                        .detach()
                        .width('')
                        .appendTo($area);

                    // scroll to left bottom
                    $area
                        .scrollLeft(0)
                        .scrollTop(2*$area[0].scrollHeight);

                    // update hidden textarea contents
                    $area.trigger('syncToTextarea.encapsulating');
                }); // push.encapsulating event

            // === input field ===
            var $input = $('<input />')
                .data('encapsulating', {})
                // ==== input keypress ====
                .bind('keypress.encapsulating keydown.encapsulating', function(e){
                    var key = toolbox.transEventKey(e);

                    switch (key)
                    {
                        // ===== space =====
                        // drop spaces at the begining of input
                        case 'keypress:32':
                            var $input = $(this);
                            if (!$input.val())
                                e.preventDefault();
                            break;
                        // ===== comma (,), right, tab, enter, escape =====
                        // edit next item
                        case 'keypress:188': // ,
                            e.preventDefault();
                        case 'keydown:39': // right
                            if (!toolbox.cursorAtEnd(this))
                                break;
                        case 'keypress:9': // tab
                        case 'keypress:13': // enter
                        case 'keydown:27': // esc
                            var $input = $(this),
                                $next = $input.next();

                            // tabe key and input was at the end
                            // allow normally focus next item on page
                            if (9 == e.keyCode && !$next.length)
                                break;

                            e.preventDefault();

                            if (27 == e.keyCode)
                                $input.val($input.data('encapsulating').prevVal);

                            if (!$input.val())
                                break;

                            $area.trigger('push.encapsulating', [$input]);

                            // tab or right key and input was not at the end
                            if ($next.length && (e.keyCode == 9 || e.keyCode == 39))
                            {
                                $next.focus();
                            }
                            else
                            {
                                // comma and input was not at the end
                                if ($next.length && key == 188)
                                {
                                    $input
                                        .detach()
                                        .insertBefore($next);
                                }
                                $input.focus();
                            }

                            break;

                        // ===== left, shift+tab, backspace =====
                        // edit previous item
                        case 'keydown:37': // left
                            if (!toolbox.cursorAtStart(this))
                                break;
                        case 'shift9': // shift + tab
                            e.preventDefault();
                            var $input = $(this),
                                $prev = $input.prev();
                            $input.blur();
                            $prev.focus();
                            break;

                        case 'keydown:8': // backspace
                            if (toolbox.cursorAtStart(this))
                            {
                                e.preventDefault();
                                var $input = $(this),
                                    $prev = $input.prev();
                                /*
                                $input.val($prev.text());
                                $prev.remove();
                                */
                                $input.blur();
                                $prev.click();
                            }
                            break;

                    }
                }) // input keypress
                // ==== input focus ====
                // store previous value
                .bind('focus.encapsulating', function(e){
                    var $input = $(this);
                    $input
                        .addClass('focus')
                        .data('encapsulating').prevVal = $input.val();
                }) // input focus
                // ==== input blur ====
                // encapsulate current value
                .bind('blur.encapsulating', function(e){
                    e.preventDefault();
                    var $input = $(this);
                    $input.removeClass('focus');
                    $area.trigger('push.encapsulating', [$input]);

                }); // input blur

            // === place in DOM ===
            if (settings.debug)
                $textarea.css('opacity', .5);
            else
                $textarea.hide();
            $textarea.bind('change', function(e){
                $area.trigger('syncFromTextarea.encapsulating');
            });
            $area.insertAfter($textarea);
            $input.appendTo($area);

            // === encapsulated item ===
            // bind events to all future created items

            $('a', $area[0])
                // ==== encapsulated item edit ====
                .live('click.encapsulating edit.encapsulating', function(e){
                    e.preventDefault();
                    var $this = $(this);
                    $input
                            .detach()
                            .width($this.width())
                            .val($this.children('.text').text())
                            .insertAfter($this)
                            .focus();
                    if ($.browser.msie)
                    {
                        // HACK apparently IE really needs to focus
                        $input.focus();
                    }
                    $this.remove();
                }) // a edit
                // ==== encapsulating item keypress ====
                .live('keypress.encapsulating keydown.encapsulating', function(e){
                    var key = toolbox.transEventKey(e);

                    switch (key)
                    {
                        case 'keypress:shift+9': // shift+8
                        case 'keydown:37': // left
                            e.preventDefault();
                            $(this).prev().focus();
                            break;
                        case 'keypress:9': // tab
                        case 'keydown:39': // right
                            e.preventDefault();
                            $(this).next().focus();
                            break;
                        case 'keydown:113': // F2
                            e.preventDefault();
                            $(this).click();
                            break;
                        case 'keydown:8': // backspace
                        case 'keydown:46': // del
                            e.preventDefault();
                            $(this)
                                .next()
                                    .focus()
                                .end()
                                .remove();
                    }
                }); // a keypress

            // ==== encapsulated item remove ====
            $('a > .remove', $area[0])
                .live('click.encapsulating', function(e){
                    e.preventDefault();
                    var $item = $(this).parent();
                    $item.remove();
                    $area.trigger('syncToTextarea.encapsulating');
                    return false;
                }); // a > .remove click

            // === encapsulate existing textarea contents ===
            $area.trigger('syncFromTextarea.encapsulating');

            // === focus input field ===
            // if textarea had focus
            if (had_focus)
                $input.focus();

        }); // return each this

    }; // $.fn.encapsulating

})(jQuery); // context scope end

<commit_msg>TODO list moved to github issues.<commit_after>// = encapsulating textarea, jQuery plugin =
//
// * author: Marek 'saji' Augustynowicz
// * license: MIT (LICENSE.md file should be distributed with the code)
// * http://github.com/marek-saji/jquery.encapsulating
//
// == USAGE ==
// {{{
// <link rel="stylesheet" type="text/cxx" href="jquery.encapsulating.css" />
// <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
// <script type="text/javascript" src="jquery.encapsulating.js"></script>
// <script type="text/javascript">
//    $(function(){
//        $('textarea.foo').encapsulating();
//
//        // you may also specify settings here
//        $('textarea.bar').encapsulating({
//            editTitle: 'click to edit this tag'
//        });
//    });
// </script>
//
// You can also specify settings with data-encapsulating attribute:
//
// <textarea data-encapsulating='{"debug": true}'>
//     first tag, 2nd tag
//     last tag
// </textarea>
//
// }}}

(function($){ // context scope begin

    // == {{{default_settings}}} ==
    var default_settings = {
        // text to display at "delete item" buttom
        removeText: '×',
        // value of "delete item" buttom title attribute
        removeTitle: '',
        // vaue of item title attribute
        editTitle: '',
        // in debug mode, textarea element is visible,
        debug: false
    };

    // == {{{toolbox}}} ==
    // some utility functions
    var toolbox = {

        // === {{{toolbox.transEventKey}}} ===
        // translate event object into easier switchable string
        // e.g. "keypress:shift+meta+97
        transEventKey: function(e) {
            var key = e.type + ':';
            var modifiers = ['alt','shift','ctrl','meta'];
            for (var i in modifiers)
                e[modifiers[i]+'Key'] && (key += modifiers[i]+'+');
            key += e.keyCode;

            return key;
        }, // toolbox.transEventKey

        // === {{{toolbox.cursorAtStart}}} ===
        // checks whether cursor is at the begining of given input
        //
        // Params:
        // * input (DOM or jQuery object)
        cursorAtStart: function(input) {
            if (input instanceof $)
                input = [0];

            if (!input.createTextRange)
            {
                var start = input.selectionStart;
            }
            else
            {
                var r = document.selection.createRange().duplicate();
                r.moveEnd('character', input.value.length);
                if (r.text == '')
                    var start = input.value.length;
                else
                    var start = input.value.lastIndexOf(r.text);
            }
            return 0 == start;
        }, // toolbox.cursorAtStart

        // === {{{toolbox.cursorAtEnd}}} ===
        // checks whether cursor is at the end of given input
        //
        // Params:
        // * input (DOM or jQuery object)
        cursorAtEnd: function(input) {
            if (input instanceof $)
                input = [0];

            if (!input.createTextRange)
            {
                var end = input.selectionEnd;
            }
            else
            {
                var r = document.selection.createRange().duplicate();
                r.moveStart('character', -this.value.length);
                var end = r.text.length;
            }
            return input.value.length == end;
        } // toolbox.cursorAtEnd

    }; // var toolbox

    // == {{{encapsulating}}} ==
    // function called with {{{$(selector).encapsulating()}}},
    // {{{this}}} is a set of matched elements
    $.fn.encapsulating = function(user_settings){

        var invoke_settings = {};

        // merge default and user settings
        $.extend(invoke_settings, default_settings, user_settings);

        return this.each(function(){

            var settings = {};

            // === original textarea ===
            var $textarea = $(this),
                had_focus = false;

            // Snizzle does not support this on IE
            try {
                had_focus = $textarea.is(':focus');
            } catch(e) {}

            // merge-in settings specified in `data-encapsulating` attribute
            $.extend(settings, invoke_settings, $textarea.data('encapsulating'));

            // === textarea replacement ===
            var $area = $('<label />', {
                    width: $textarea.width(),
                    height: $textarea.height(),
                    'class': 'encapsulating-textarea '
                             + $textarea.attr('class')
                             + (settings.debug ? ' debug' : ''),
                    // inherit textarea-specific css properties
                    css: {
                        resize: $textarea.css('resize')
                    }
                })
                // ==== sync encapsulated items to hidden textarea ====
                .bind('syncToTextarea.encapsulating', function(){
                    var $area = $(this);
                    var new_val = [];
                    $area.find('a > .text').each(function(){
                        new_val.push($(this).text());
                    });
                    $textarea.val(new_val.join("\n"));
                }) // syncToTextarea.encapsulating event
                // ==== encapsulate textarea contents ====
                .bind('syncFromTextarea.encapsulating', function(){
                    var $area = $(this);
                    $area.children('a').remove();
                    $area.trigger('push.encapsulating', [$textarea.val().split(/[\n\r,]+/)]);
                }) // syncFromTextarea.encapsulating event
                // ==== encapsulate an item ====
                // Params:
                //  * e (Event): event object
                //  * el (string, array, DOM, jQuery)
                //  ** string to encapsulate
                //  ** DOMor jQuery with input to encapsulate, it will be emptied afterwards and moved at the end of the area
                //  ** array with any of the above
                .bind('push.encapsulating', function(e, el){
                    var $area = $(this);
                    if ($.type(el) == 'string')
                        var val = el;
                    else if ($.type(el) == 'array')
                    {
                        for (var idx in el)
                            $area.trigger('push.encapsulating', [el[idx]]);
                        return;
                    }
                    else
                    {
                        var $el = $(el);
                        switch ($el.length)
                        {
                            case 0:
                                return;
                            case 1:
                                break;
                            default:
                                $el.each(function(){
                                    $area.trigger('push.encapsulating', [this]);
                                });
                                return;
                        }

                        var val = $el.val();
                        $el.val('');
                    }

                    // trim whitespaces
                    val = val.replace(/^\s+|\s+$/g, '');

                    // create new item
                    if (val)
                    {
                        var $item = $('<a />', {
                            href: '#'
                        });

                        $('<span />', {
                            'class': 'text',
                            text: val,
                            title: settings.editLabel
                        }).appendTo($item);

                        $('<span />', {
                            'class': 'remove',
                            text: settings.removeText,
                            title: settings.removeLabel,
                        })
                        .appendTo($item);

                        $item.insertBefore($input);
                    }

                    $input
                        .detach()
                        .width('')
                        .appendTo($area);

                    // scroll to left bottom
                    $area
                        .scrollLeft(0)
                        .scrollTop(2*$area[0].scrollHeight);

                    // update hidden textarea contents
                    $area.trigger('syncToTextarea.encapsulating');
                }); // push.encapsulating event

            // === input field ===
            var $input = $('<input />')
                .data('encapsulating', {})
                // ==== input keypress ====
                .bind('keypress.encapsulating keydown.encapsulating', function(e){
                    var key = toolbox.transEventKey(e);

                    switch (key)
                    {
                        // ===== space =====
                        // drop spaces at the begining of input
                        case 'keypress:32':
                            var $input = $(this);
                            if (!$input.val())
                                e.preventDefault();
                            break;
                        // ===== comma (,), right, tab, enter, escape =====
                        // edit next item
                        case 'keypress:188': // ,
                            e.preventDefault();
                        case 'keydown:39': // right
                            if (!toolbox.cursorAtEnd(this))
                                break;
                        case 'keypress:9': // tab
                        case 'keypress:13': // enter
                        case 'keydown:27': // esc
                            var $input = $(this),
                                $next = $input.next();

                            // tabe key and input was at the end
                            // allow normally focus next item on page
                            if (9 == e.keyCode && !$next.length)
                                break;

                            e.preventDefault();

                            if (27 == e.keyCode)
                                $input.val($input.data('encapsulating').prevVal);

                            if (!$input.val())
                                break;

                            $area.trigger('push.encapsulating', [$input]);

                            // tab or right key and input was not at the end
                            if ($next.length && (e.keyCode == 9 || e.keyCode == 39))
                            {
                                $next.focus();
                            }
                            else
                            {
                                // comma and input was not at the end
                                if ($next.length && key == 188)
                                {
                                    $input
                                        .detach()
                                        .insertBefore($next);
                                }
                                $input.focus();
                            }

                            break;

                        // ===== left, shift+tab, backspace =====
                        // edit previous item
                        case 'keydown:37': // left
                            if (!toolbox.cursorAtStart(this))
                                break;
                        case 'shift9': // shift + tab
                            e.preventDefault();
                            var $input = $(this),
                                $prev = $input.prev();
                            $input.blur();
                            $prev.focus();
                            break;

                        case 'keydown:8': // backspace
                            if (toolbox.cursorAtStart(this))
                            {
                                e.preventDefault();
                                var $input = $(this),
                                    $prev = $input.prev();
                                /*
                                $input.val($prev.text());
                                $prev.remove();
                                */
                                $input.blur();
                                $prev.click();
                            }
                            break;

                    }
                }) // input keypress
                // ==== input focus ====
                // store previous value
                .bind('focus.encapsulating', function(e){
                    var $input = $(this);
                    $input
                        .addClass('focus')
                        .data('encapsulating').prevVal = $input.val();
                }) // input focus
                // ==== input blur ====
                // encapsulate current value
                .bind('blur.encapsulating', function(e){
                    e.preventDefault();
                    var $input = $(this);
                    $input.removeClass('focus');
                    $area.trigger('push.encapsulating', [$input]);

                }); // input blur

            // === place in DOM ===
            if (settings.debug)
                $textarea.css('opacity', .5);
            else
                $textarea.hide();
            $textarea.bind('change', function(e){
                $area.trigger('syncFromTextarea.encapsulating');
            });
            $area.insertAfter($textarea);
            $input.appendTo($area);

            // === encapsulated item ===
            // bind events to all future created items

            $('a', $area[0])
                // ==== encapsulated item edit ====
                .live('click.encapsulating edit.encapsulating', function(e){
                    e.preventDefault();
                    var $this = $(this);
                    $input
                            .detach()
                            .width($this.width())
                            .val($this.children('.text').text())
                            .insertAfter($this)
                            .focus();
                    if ($.browser.msie)
                    {
                        // HACK apparently IE really needs to focus
                        $input.focus();
                    }
                    $this.remove();
                }) // a edit
                // ==== encapsulating item keypress ====
                .live('keypress.encapsulating keydown.encapsulating', function(e){
                    var key = toolbox.transEventKey(e);

                    switch (key)
                    {
                        case 'keypress:shift+9': // shift+8
                        case 'keydown:37': // left
                            e.preventDefault();
                            $(this).prev().focus();
                            break;
                        case 'keypress:9': // tab
                        case 'keydown:39': // right
                            e.preventDefault();
                            $(this).next().focus();
                            break;
                        case 'keydown:113': // F2
                            e.preventDefault();
                            $(this).click();
                            break;
                        case 'keydown:8': // backspace
                        case 'keydown:46': // del
                            e.preventDefault();
                            $(this)
                                .next()
                                    .focus()
                                .end()
                                .remove();
                    }
                }); // a keypress

            // ==== encapsulated item remove ====
            $('a > .remove', $area[0])
                .live('click.encapsulating', function(e){
                    e.preventDefault();
                    var $item = $(this).parent();
                    $item.remove();
                    $area.trigger('syncToTextarea.encapsulating');
                    return false;
                }); // a > .remove click

            // === encapsulate existing textarea contents ===
            $area.trigger('syncFromTextarea.encapsulating');

            // === focus input field ===
            // if textarea had focus
            if (had_focus)
                $input.focus();

        }); // return each this

    }; // $.fn.encapsulating

})(jQuery); // context scope end

<|endoftext|>


<commit_before>// app.module.js

(function() {
  "use strict";

  angular.module("MyApp", []);
})();
<commit_msg>Change module name<commit_after>// app.module.js

(function() {
  "use strict";

  angular.module("ShoppingListCheckOff", []);
})();
<|endoftext|>


<commit_before>class BankAccount {
  constructor(name, currency, inB = 0, tod = 0, fut = 0) {
    this._name = name
    this._currency = currency
    this._amount = [
      {"amount": inB, "label" : "Bank"},
      {"amount": tod, "label" : "Today"},
      {"amount": fut, "label" : "Future"}
    ]
  }

  get name(){
    return this._name
  }

  get currency(){
    return this._currency
  }

  get inBank(){
    return this._amount[0].amount
  }

  get today(){
    return this._amount[1].amount
  }

  get future(){
    return this._amount[2].amount
  }

  get amount(){
    return this._amount
  }

  set name(value){
    this.name = value
  }

  set currency(value){
    this._currency = value
  }

  set inBank(value){
    this._amount[0].amount = value
  }
  set today(value){
    this._amount[1].amount = value
  }
  set future(value){
    this._amount[2].amount = value
  }

  render(where){
    const list = $(where)
    list.append(
      $('<article>')
      .addClass("card notification is-dark is-paddingless")
      .attr('id',this.name)
      .append(
        $('<div>').addClass('card-header')
        .append(
          $('<div>').addClass('card-header-icon')
          .append(
            $('<span>').addClass("icon")
            .append(
              $('<i>').addClass('fa fa-bank')
            )
          )
        )
        .append(
          $('<div>').addClass('card-header-title')
          .text(this.name)
        )
        .append(
          $('<button></button>').addClass("delete")
          .attr({
            onclick: "deleteAccount(this)",
            data: this.name
          })
        )
      )
      .append(
        $('<div>').addClass("card-content")
        .append(
          $('<div>').addClass("content is-paddingless is-marginless")
          .append(
            $('<small>').append(
              $('<p>').text('Bank : ')
              .append(
                $('<span>').addClass("amount").attr('id','inBank')
                .text(this.inBank.toFixed(2)+" ")
                .append(
                  $('<span>').addClass("icon is-small")
                  .append(
                    $('<i>').addClass("fa fa-"+this.currency)
                  )              )
              )
            )
            .append(
              $('<p>').text('Today : ')
              .append(
                $('<span>').addClass("amount").attr('id','inToday')
                .text(this.today.toFixed(2)+" ")
                .append(
                  $('<span>').addClass("icon is-small")
                  .append(
                    $('<i>').addClass("fa fa-"+this.currency)
                  )              )
              )
            )
            .append(
              $('<p>').text('Future : ')
              .append(
                $('<span>').addClass("amount").attr('id','inFuture')
                .text(this.future.toFixed(2)+" ")
                .append(
                  $('<span>').addClass("icon is-small")
                  .append(
                    $('<i>').addClass("fa fa-"+this.currency)
                  )
                )
              )
            )
          )
        )
      )

    )
  }

  static clone(obj){
    return new BankAccount(obj.name, obj.currency, obj.inBank,obj.today,obj.future)
  }
}
<commit_msg>:lipstick: Add red text in negative amount<commit_after>class BankAccount {
  constructor(name, currency, inB = 0, tod = 0, fut = 0) {
    this._name = name
    this._currency = currency
    this._amount = [
      {"amount": inB, "label" : "Bank"},
      {"amount": tod, "label" : "Today"},
      {"amount": fut, "label" : "Future"}
    ]
  }

  get name(){
    return this._name
  }

  get currency(){
    return this._currency
  }

  get inBank(){
    return this._amount[0].amount
  }

  get today(){
    return this._amount[1].amount
  }

  get future(){
    return this._amount[2].amount
  }

  get amount(){
    return this._amount
  }

  set name(value){
    this.name = value
  }

  set currency(value){
    this._currency = value
  }

  set inBank(value){
    this._amount[0].amount = value
  }
  set today(value){
    this._amount[1].amount = value
  }
  set future(value){
    this._amount[2].amount = value
  }

  render(where){
    const list = $(where)
    list.append(
      $('<article>')
      .addClass("card notification is-dark is-paddingless")
      .attr('id',this.name)
      .append(
        $('<div>').addClass('card-header')
        .append(
          $('<div>').addClass('card-header-icon')
          .append(
            $('<span>').addClass("icon")
            .append(
              $('<i>').addClass('fa fa-bank')
            )
          )
        )
        .append(
          $('<div>').addClass('card-header-title')
          .text(this.name)
        )
        .append(
          $('<button></button>').addClass("delete")
          .attr({
            onclick: "deleteAccount(this)",
            data: this.name
          })
        )
      )
      .append(
        $('<div>').addClass("card-content")
        .append(
          $('<div>').addClass("content is-paddingless is-marginless")
          .append(
            $('<small>').append(
              $('<p>').text('Bank : ')
              .append(
                $('<span>').addClass("amount"+(this.inBank <=0 ? ' has-text-danger':'')).attr('id','inBank')
                .text(this.inBank.toFixed(2)+" ")
                .append(
                  $('<span>').addClass("icon is-small")
                  .append(
                    $('<i>').addClass("fa fa-"+this.currency)
                  )              )
              )
            )
            .append(
              $('<p>').text('Today : ')
              .append(
                $('<span>').addClass("amount"+(this.today <=0 ? ' has-text-danger':'')).attr('id','inToday')
                .text(this.today.toFixed(2)+" ")
                .append(
                  $('<span>').addClass("icon is-small")
                  .append(
                    $('<i>').addClass("fa fa-"+this.currency)
                  )              )
              )
            )
            .append(
              $('<p>').text('Future : ')
              .append(
                $('<span>').addClass("amount"+(this.future <=0 ? ' has-text-danger':'')).attr('id','inFuture')
                .text(this.future.toFixed(2)+" ")
                .append(
                  $('<span>').addClass("icon is-small")
                  .append(
                    $('<i>').addClass("fa fa-"+this.currency)
                  )
                )
              )
            )
          )
        )
      )

    )
  }

  static clone(obj){
    return new BankAccount(obj.name, obj.currency, obj.inBank,obj.today,obj.future)
  }
}
<|endoftext|>


<commit_before>var fs = require('fs');

var book1 = '../../_data/book1.txt';
var book2 = '../../_data/book2.txt';
var destination = '../../_out/book1_new.txt';

var readBook = function (bookName, callback) {
    console.log('readBook() - start');

    fs.readFile(bookName, function (err, data) {
        console.log('readBook() -> fs.readFile - start');

        if (err) {
            console.log(err);
            throw err;
        }

        callback(data);

        console.log('readBook() -> fs.readFile - end');
    });

    console.log('readBook() - end');
};

var writeBook = function (bookName, bookContent) {
    console.log('writeBook() - start');

    fs.writeFile(bookName, bookContent, function (err) {
        console.log('writeBook() -> fs.writeFile - start');

        if (err) {
            console.log(err);
            throw err;
        }
        console.log('writeBook() : ' + bookName + ' saved!');

        console.log('writeBook() -> fs.writeFile - end');
    });

    console.log('writeBook() - end');
};

readBook(book1, function (data) {
    console.log('readBook(book1, callback) = ');

    var data1 = data;
    console.log(data1);

    readBook(book2, function (data) {
        console.log('readBook(book2, callback)');

        var data2 = data;
        console.log(data2);

        var data3 = data1 + data2;
        writeBook(destination, data3);
    })
});
<commit_msg>Fixed JSHint issue<commit_after>var fs = require('fs');

var book1 = '../../_data/book1.txt';
var book2 = '../../_data/book2.txt';
var destination = '../../_out/book1_new.txt';

var readBook = function (bookName, callback) {
    console.log('readBook() - start');

    fs.readFile(bookName, function (err, data) {
        console.log('readBook() -> fs.readFile - start');

        if (err) {
            console.log(err);
            throw err;
        }

        callback(data);

        console.log('readBook() -> fs.readFile - end');
    });

    console.log('readBook() - end');
};

var writeBook = function (bookName, bookContent) {
    console.log('writeBook() - start');

    fs.writeFile(bookName, bookContent, function (err) {
        console.log('writeBook() -> fs.writeFile - start');

        if (err) {
            console.log(err);
            throw err;
        }
        console.log('writeBook() : ' + bookName + ' saved!');

        console.log('writeBook() -> fs.writeFile - end');
    });

    console.log('writeBook() - end');
};

readBook(book1, function (data) {
    console.log('readBook(book1, callback) = ');

    var data1 = data;
    console.log(data1);

    readBook(book2, function (data) {
        console.log('readBook(book2, callback)');

        var data2 = data;
        console.log(data2);

        var data3 = data1 + data2;
        writeBook(destination, data3);
    });
});
<|endoftext|>


<commit_before>/**
 * Dimension Widget
 */
Humble( function () {

    var C_BUDGET_ACCOUNT = 'humble-dvc-subfunction',
        T_BUDGET_ACCOUNT = '

';

    var BudgetAccount = function (node, model) {

        this.parentNode = node;
        this.node = $(T_BUDGET_ACCOUNT);
        this.model = model;
        this.dataSource = this.buildDataSource();

        this.render();
    }

    BudgetAccount.prototype = {

        render : function () {
            this.parentNode.append(this.node);
            this.bind();
        },

        bind : function () {

            var that = this;

            Humble.Event.bind('humble:dvc:dimensionDetail', function (e, key, show) {
                that.dataSource.request({
                    success : function () {
                        console.log('request made!');
                    }
                });

            });
        },

        buildDataSource : function () {

            var dataSource, options;

            options = {
                url  : 'http://www.whatwepayfor.com/api/getBudgetAccount'
            };

            dataSource = new Humble.DataSource(options);

            return dataSource;
        }
    }

    Humble.DVC.BudgetAccount = BudgetAccount;
});

<commit_msg>Made to use BudgetModel.<commit_after>/**
 * Dimension Widget
 */
Humble( function () {

    var C_BUDGET_ACCOUNT = 'humble-dvc-subfunction',
        T_BUDGET_ACCOUNT = '

';

    var BudgetAccount = function (node, model) {

        this.parentNode = node;
        this.node = $(T_BUDGET_ACCOUNT);
        this.model = model;
        this.budgetAccountModel = this._buildModel();

        this.render();
    }

    BudgetAccount.prototype = {

        render : function () {
            this.parentNode.append(this.node);
            this.bind();
        },

        bind : function () {

            var that = this;

            Humble.Event.bind('humble:dvc:dimensionDetail', function (e, key, show) {
                var id = that.model.get(key, 'dimensionID'),
                    income = that.model.getIncome(),
                    data = {'function' : id, income : income};
                that.budgetAccountModel.setData(data);
            });
        },

        renderAccounts : function () {

        },

        _buildModel : function () {

            var model, options;

            options = {
                url  : Humble.Config.DVZ.url+'getBudgetAccount'
            };

            model = new Humble.DVC.BudgetAggregateModel(options);

            return model;
        }
    }

    Humble.DVC.BudgetAccount = BudgetAccount;
});
<|endoftext|>


<commit_before>var wompt = require("../includes"),
Util = wompt.util;

function SearchController(app){
	var express = app.express,
	self = this;

	this.register = function(){
		express.get("/rooms/search", resultsHandler);
		express.get("/search", searchPage);
	}

	function resultsHandler(req, res){
		var terms = req.query && req.query.term,
				limit = req.query && req.query.limit,
				results = search(terms, limit);
		res.writeHead(200, {"Content-Type":"application/json"});
		res.end(JSON.stringify(results));
	}

	function searchPage(req, res){
		var terms = req.query && req.query.q;

		res.render('search',{
			locals: app.standard_page_vars(req, {
				query: terms,
				resultsJSON: JSON.stringify(search(terms)),
				jquery: true,
				hide_top_query: true,
				page_js: 'search',
				page_name:'search'
			})
		});
	}

	function search(term, max_results){
		var results = [], terms;
		max_results = max_results > 0 ? Math.min(max_results, 100) : 100;

		term = term ? term.toLowerCase() : null;

		if(term){
			// Limit length, split on spaces, remove blank terms, enforce maximum term count
			terms = term.substr(0,50)
				.split(' ')
				.filter(function(t){return t.length > 0;})
				.slice(0,5);

			if(terms.length > 1){
				app.channels.each(function(channel){
					var name = channel.name;
					if(terms.every(function(term){return name.indexOf(term) >= 0;}))
						results.push(channel);
					if(results.length >= max_results) return true;
				});
			} else if(term = terms[0]){
				app.channels.each(function(channel){
					if(channel.name.indexOf(term) >= 0)
						results.push(channel);
					if(results.length >= max_results) return true;
				});
			}
		} else {
			results = app.popular_channels.sorted_list;
		}

		return results.map(function(channel){
			return {n:channel.name, u:channel.clients.count}
		});
	}
}

module.exports = SearchController;
<commit_msg>Convert Search to an asynchronous process<commit_after>var wompt = require("../includes"),
Util = wompt.util;

function SearchController(app){
	var express = app.express,
	self = this;

	this.register = function(){
		express.get("/rooms/search", resultsHandler);
		express.get("/search", searchPage);
	}

	function resultsHandler(req, res){
		var terms = req.query && req.query.term,
		limit = req.query && req.query.limit;

		search(terms, limit, function(results){
			res.writeHead(200, {"Content-Type":"application/json"});
			res.end(JSON.stringify(results));
		});
	}

	function searchPage(req, res){
		var terms = req.query && req.query.q;
		search(terms, null, function(results){
			res.render('search', {
				locals: app.standard_page_vars(req, {
					query: terms,
					resultsJSON: JSON.stringify(results),
					jquery: true,
					hide_top_query: true,
					page_js: 'search',
					page_name:'search'
				})
			});
		});
	}

	function search(term, max_results, callback){
		var results = [],
		terms;
		max_results = max_results > 0 ? Math.min(max_results, 100) : 100;

		term = term ? term.toLowerCase() : null;

		if(term){
			// Limit length, split on spaces, remove blank terms, enforce maximum term count
			terms = term.substr(0,50)
				.split(' ')
				.filter(function(t){return t.length > 0;})
				.slice(0,5);

			if(terms.length > 1){
				app.channels.each(function(channel){
					var name = channel.name;
					if(terms.every(function(term){return name.indexOf(term) >= 0;}))
						results.push(channel);
					if(results.length >= max_results) return true;
				});
			} else if(term = terms[0]){
				app.channels.each(function(channel){
					if(channel.name.indexOf(term) >= 0)
						results.push(channel);
					if(results.length >= max_results) return true;
				});
			}
		} else {
			results = app.popular_channels.sorted_list;
		}

		callback(results.map(function(channel){
			return {n:channel.name, u:channel.clients.count}
		}));
	}
}

module.exports = SearchController;
<|endoftext|>