<commit_before>/* global describe */
/* global beforeEach */
/* global it */
/* global inject */
/* global expect */
/* global spyOn */
/* global xit */

'use strict';

describe('Specification for app ', function() {
  var event;
  var toState;
  var toParams;
  var fromState;
  var fromParams;
  var $scope;
  var $httpBackend;
  var $rootScope;
  var $location;
  var LanguageService;
  var $state;

  describe('metadatamanagementApp run function', function() {
    beforeEach(function() {
      inject(function(_$rootScope_, _$location_,
        _$httpBackend_, _LanguageService_, _$state_) {
        $rootScope = _$rootScope_;
        $scope = _$rootScope_.$new();
        $location = _$location_;
        $httpBackend = _$httpBackend_;
        $state = _$state_;
        LanguageService = _LanguageService_;
      });
      localStorage.clear();
      var globalJson = new RegExp('i18n\/.*\/global.json');
      var searchJson = new RegExp(
        'i18n\/.*\/search.management.json');
      var dataSetJson = new RegExp(
        'i18n\/.*\/dataSet.management.json');
      var variableJson = new RegExp(
        'i18n\/.*\/variable.management.json');
      var questionJson = new RegExp(
        'i18n\/.*\/question.management.json');
      var dataAcquisitionProjectJson =
        new RegExp(
          'i18n\/.*\/dataAcquisitionProject.management.json');
      $httpBackend.whenGET(globalJson).respond({});
      $httpBackend.whenGET(searchJson).respond({});
      $httpBackend.whenGET(dataSetJson).respond({});
      $httpBackend.whenGET(dataAcquisitionProjectJson).respond({});
      $httpBackend.whenGET(variableJson).respond({});
      $httpBackend.whenGET(questionJson).respond({});
      $httpBackend.
      expectGET(/scripts\/searchmanagement\/views\/search.html.tmpl/).
      respond(200, '');
    });
    it('should set LanguageService to en ', function() {
      $location.path('/en/');
      $rootScope.$apply();
      expect(LanguageService.getCurrentInstantly()).toBe('en');
    });
    // TODO should be changed, because we use $transitons
    xdescribe('run functions', function() {
      xdescribe('on stateChangeStart', function() {
        it('should call stateChangeStart function', function() {
          spyOn($rootScope, '$broadcast');
          $rootScope.$broadcast('$stateChangeStart', event,
            toState, toParams);
          expect($scope.$broadcast).toHaveBeenCalledWith(
            '$stateChangeStart', event, toState, toParams
          );
        });
      });
      xdescribe('on stateChangeSuccess', function() {
        beforeEach(function() {
          fromState = {
            name: 'disclosure',
            parent: 'site',
            url: '/disclosure'
          };
          fromParams = {
            name: 'testParams'
          };
          toState = {
            name: 'search',
            parent: 'site',
            url: '/'
          };
          toParams = {
            name: 'search'
          };
          $rootScope.toState = toState;
          $rootScope.previousStateName =
            'previousStateName';
          $rootScope.toState = toState;
          $rootScope.fromState = fromState;
          $rootScope.toParams = toParams;
          $rootScope.fromParams = fromParams;
          event = {
            currentScope: $rootScope,
            defaultPrevented: true,
            name: 'disclosure',
            data: {
              authorities: [],
              pageTitle: 'global.title'
            }
          };
          spyOn($rootScope, '$broadcast').and.callThrough();
          $rootScope.$broadcast('$stateChangeSuccess',
            event,
            toState, toParams, fromState, fromParams);
        });
        xit('should call stateChangeSuccess function', function() {
          expect($scope.$broadcast).toHaveBeenCalledWith(
            '$stateChangeSuccess', event, toState,
            toParams, fromState, fromParams);
        });
        xit('should set previousStateParams to testState ',
          function() {
            expect($rootScope.previousStateParams.name).toBe(
              'disclosure');
          });
      });
    });
  });
  xdescribe('back function', function() {
    it('should call back function', function() {
      spyOn($scope, 'back').and.callThrough();
      spyOn($state, 'go').and.callThrough();
      $scope.previousStateName = 'activate';
      $scope.back();
      expect($scope.back).toHaveBeenCalled();
      expect($state.go).toHaveBeenCalled();
    });
    it('should call back function', function() {
      fromState = {};
      fromParams = {};
      toState = {};
      toParams = {};
      $rootScope.toState = toState;
      $rootScope.previousStateName = 'previousStateName';
      $rootScope.fromState = fromState;
      $rootScope.toParams = toParams;
      $rootScope.fromParams = fromParams;
      spyOn($scope, 'back').and.callThrough();
      spyOn($state, 'go').and.callThrough();
      $scope.previousStateName = 'activate';
      $scope.back();
      expect($scope.back).toHaveBeenCalled();
      expect($state.go).toHaveBeenCalledWith('search', {
        lang: 'en'
      });
    });
  });
  describe('metadatamanagementApp configuration ', function() {
    var $urlMatcherFactory;
    beforeEach(function() {
      module(function(_$urlMatcherFactoryProvider_) {
        $urlMatcherFactory = _$urlMatcherFactoryProvider_;
        spyOn($urlMatcherFactory, 'type').and.callThrough();
      });
      inject();
    });
    xit('should call back function', function() {
      expect($urlMatcherFactory.type('boolean')
        .decode('true')).toBe(true);
      expect($urlMatcherFactory.type('boolean')
        .decode('false')).toBe(false);
      expect($urlMatcherFactory.type('boolean')
        .decode('test')).toBe(false);
      expect($urlMatcherFactory.type('boolean')
        .decode(true)).toBe(true);
      expect($urlMatcherFactory.type('boolean')
        .decode(false)).toBe(false);
      expect($urlMatcherFactory.type('boolean')
        .encode('test')).toBe(1);
      expect($urlMatcherFactory.type('boolean')
        .encode('0')).toBe(1);
      expect($urlMatcherFactory.type('boolean')
        .encode('1')).toBe(1);
      expect($urlMatcherFactory.type('boolean')
        .encode()).toBe(0);
      expect($urlMatcherFactory.type('boolean')
        .equals(1, 2)).toBe(false);
      expect($urlMatcherFactory.type('boolean').is(1)).toBe(true);
    });
  });
});
<commit_msg>Fix test<commit_after>/* global describe */
/* global beforeEach */
/* global it */
/* global inject */
/* global expect */
/* global spyOn */
/* global xit */

'use strict';

describe('Specification for app ', function() {
  var event;
  var toState;
  var toParams;
  var fromState;
  var fromParams;
  var $scope;
  var $httpBackend;
  var $rootScope;
  var $location;
  var LanguageService;
  var $state;

  describe('metadatamanagementApp run function', function() {
    beforeEach(function() {
      inject(function(_$rootScope_, _$location_,
        _$httpBackend_, _LanguageService_, _$state_) {
        $rootScope = _$rootScope_;
        $scope = _$rootScope_.$new();
        $location = _$location_;
        $httpBackend = _$httpBackend_;
        $state = _$state_;
        LanguageService = _LanguageService_;
      });
      localStorage.clear();
      var globalJson = new RegExp('i18n\/.*\/global.json');
      var searchJson = new RegExp(
        'i18n\/.*\/search.management.json');
      var dataSetJson = new RegExp(
        'i18n\/.*\/dataSet.management.json');
      var variableJson = new RegExp(
        'i18n\/.*\/variable.management.json');
      var questionJson = new RegExp(
        'i18n\/.*\/question.management.json');
      var dataAcquisitionProjectJson =
        new RegExp(
          'i18n\/.*\/dataAcquisitionProject.management.json');
      $httpBackend.whenGET(globalJson).respond({});
      $httpBackend.whenGET(searchJson).respond({});
      $httpBackend.whenGET(dataSetJson).respond({});
      $httpBackend.whenGET(dataAcquisitionProjectJson).respond({});
      $httpBackend.whenGET(variableJson).respond({});
      $httpBackend.whenGET(questionJson).respond({});
      $httpBackend.
      expectGET(/scripts\/start\/views\/start.html.tmpl/).
      respond(200, '');
    });
    it('should set LanguageService to en ', function() {
      $location.path('/en/');
      $rootScope.$apply();
      expect(LanguageService.getCurrentInstantly()).toBe('en');
    });
    // TODO should be changed, because we use $transitons
    xdescribe('run functions', function() {
      xdescribe('on stateChangeStart', function() {
        it('should call stateChangeStart function', function() {
          spyOn($rootScope, '$broadcast');
          $rootScope.$broadcast('$stateChangeStart', event,
            toState, toParams);
          expect($scope.$broadcast).toHaveBeenCalledWith(
            '$stateChangeStart', event, toState, toParams
          );
        });
      });
      xdescribe('on stateChangeSuccess', function() {
        beforeEach(function() {
          fromState = {
            name: 'disclosure',
            parent: 'site',
            url: '/disclosure'
          };
          fromParams = {
            name: 'testParams'
          };
          toState = {
            name: 'search',
            parent: 'site',
            url: '/'
          };
          toParams = {
            name: 'search'
          };
          $rootScope.toState = toState;
          $rootScope.previousStateName =
            'previousStateName';
          $rootScope.toState = toState;
          $rootScope.fromState = fromState;
          $rootScope.toParams = toParams;
          $rootScope.fromParams = fromParams;
          event = {
            currentScope: $rootScope,
            defaultPrevented: true,
            name: 'disclosure',
            data: {
              authorities: [],
              pageTitle: 'global.title'
            }
          };
          spyOn($rootScope, '$broadcast').and.callThrough();
          $rootScope.$broadcast('$stateChangeSuccess',
            event,
            toState, toParams, fromState, fromParams);
        });
        xit('should call stateChangeSuccess function', function() {
          expect($scope.$broadcast).toHaveBeenCalledWith(
            '$stateChangeSuccess', event, toState,
            toParams, fromState, fromParams);
        });
        xit('should set previousStateParams to testState ',
          function() {
            expect($rootScope.previousStateParams.name).toBe(
              'disclosure');
          });
      });
    });
  });
  xdescribe('back function', function() {
    it('should call back function', function() {
      spyOn($scope, 'back').and.callThrough();
      spyOn($state, 'go').and.callThrough();
      $scope.previousStateName = 'activate';
      $scope.back();
      expect($scope.back).toHaveBeenCalled();
      expect($state.go).toHaveBeenCalled();
    });
    it('should call back function', function() {
      fromState = {};
      fromParams = {};
      toState = {};
      toParams = {};
      $rootScope.toState = toState;
      $rootScope.previousStateName = 'previousStateName';
      $rootScope.fromState = fromState;
      $rootScope.toParams = toParams;
      $rootScope.fromParams = fromParams;
      spyOn($scope, 'back').and.callThrough();
      spyOn($state, 'go').and.callThrough();
      $scope.previousStateName = 'activate';
      $scope.back();
      expect($scope.back).toHaveBeenCalled();
      expect($state.go).toHaveBeenCalledWith('search', {
        lang: 'en'
      });
    });
  });
  describe('metadatamanagementApp configuration ', function() {
    var $urlMatcherFactory;
    beforeEach(function() {
      module(function(_$urlMatcherFactoryProvider_) {
        $urlMatcherFactory = _$urlMatcherFactoryProvider_;
        spyOn($urlMatcherFactory, 'type').and.callThrough();
      });
      inject();
    });
    xit('should call back function', function() {
      expect($urlMatcherFactory.type('boolean')
        .decode('true')).toBe(true);
      expect($urlMatcherFactory.type('boolean')
        .decode('false')).toBe(false);
      expect($urlMatcherFactory.type('boolean')
        .decode('test')).toBe(false);
      expect($urlMatcherFactory.type('boolean')
        .decode(true)).toBe(true);
      expect($urlMatcherFactory.type('boolean')
        .decode(false)).toBe(false);
      expect($urlMatcherFactory.type('boolean')
        .encode('test')).toBe(1);
      expect($urlMatcherFactory.type('boolean')
        .encode('0')).toBe(1);
      expect($urlMatcherFactory.type('boolean')
        .encode('1')).toBe(1);
      expect($urlMatcherFactory.type('boolean')
        .encode()).toBe(0);
      expect($urlMatcherFactory.type('boolean')
        .equals(1, 2)).toBe(false);
      expect($urlMatcherFactory.type('boolean').is(1)).toBe(true);
    });
  });
});
<|endoftext|>


<commit_before>/*global Polymer, Cosmoz*/

(function () {

	'use strict';

	Polymer({

		is: 'cosmoz-bottom-bar-view',

		behaviors: [
			Cosmoz.ViewInfoBehavior,
			Polymer.IronResizableBehavior
		],

		properties: {

			overflowing: {
				type: Boolean,
				value: false,
				reflectToAttribute: true
			},

			scroller: {
				type: Object
			}
		},

		listeners: {
			'iron-resize': '_onResize'
		},

		attached: function () {
			this.scroller = this.$.scroller;
		},

		_onResize: function () {
			var scrollerSizer = this.$.scrollerSizer;

			// HACK(pasleq): ensure scrollerSizer is sized correctly.
			scrollerSizer.style.minHeight = '';
			this.async(function () {
				if (scrollerSizer.scrollHeight > scrollerSizer.offsetHeight) {
					scrollerSizer.style.minHeight = scrollerSizer.scrollHeight + 'px';
				}
			});

		},

		_getPadding: function (desktop) {
			// if (desktop) {
			// 	return;
			// }
			return 'padding-bottom: ' + this.$.bar.barHeight + 'px';
		},

		_getBarHeight: function (desktop) {
			return 'min-height: ' + this.$.bar.barHeight + 'px';
		}
	});
}());<commit_msg>Fix bug where the placeholder would flex out<commit_after>/*global Polymer, Cosmoz*/

(function () {

	'use strict';

	Polymer({

		is: 'cosmoz-bottom-bar-view',

		behaviors: [
			Cosmoz.ViewInfoBehavior,
			Polymer.IronResizableBehavior
		],

		properties: {

			overflowing: {
				type: Boolean,
				value: false,
				reflectToAttribute: true
			},

			scroller: {
				type: Object
			}
		},

		listeners: {
			'iron-resize': '_onResize'
		},

		attached: function () {
			this.scroller = this.$.scroller;
		},

		_onResize: function () {
			var scrollerSizer = this.$.scrollerSizer;

			// HACK(pasleq): ensure scrollerSizer is sized correctly.
			scrollerSizer.style.minHeight = '';
			this.async(function () {
				if (scrollerSizer.scrollHeight > scrollerSizer.offsetHeight) {
					scrollerSizer.style.minHeight = scrollerSizer.scrollHeight + 'px';
				}
			});

		},

		_getPadding: function (desktop) {
			// if (desktop) {
			// 	return;
			// }
			return 'padding-bottom: ' + this.$.bar.barHeight + 'px';
		},

		_getBarHeight: function (desktop) {
			var height = this.$.bar.barHeight;
			return [
				'max-height: ' + height + 'px',
				'min-height: ' + height + 'px'
			].join(';');
		}
	});
}());<|endoftext|>


<commit_before>import Component from '@ember/component';
import { computed, get, observer, set } from '@ember/object';
import { equal } from '@ember/object/computed';
import { on } from '@ember/object/evented';
import { isEmpty } from '@ember/utils';
import Semver from 'semver';
import layout from './template';

const OS_TYPES = [
  { value: 'Linux', },
  { value: 'Windows', }
];

const OS_DISK_TYPES = [
  { value: 'Ephemeral' },
  { value: 'Managed' }
]

export default Component.extend({
  layout,

  cluster:                         null,
  nodePool:                        null,
  vmSizes:                         null,
  vmOs:                            OS_TYPES,
  diskTypes:                       OS_DISK_TYPES,
  upgradeVersion:                  false,
  showNodeUpgradePreventionReason: false,

  isSystemType: equal('nodePool.mode', 'System'),

  updateNodeVersion: on('init', observer('cluster.aksConfig.kubernetesVersion', 'upgradeVersion', 'upgradeAvailable', function() {
    const {
      cluster, upgradeAvailable, nodePool, upgradeVersion
    } = this;

    if (upgradeAvailable && upgradeVersion) {
      set(nodePool, 'orchestratorVersion', cluster.aksConfig.kubernetesVersion);
    }
  })),

  originalClusterVersion: computed('cluster.aksConfig.kubernetesVersion', 'originalCluster.aksConfig.kubernetesVersion', 'originalCluster.aksConfig.upstreamSpec.kubernetesVersion', function() {
    if (!isEmpty(get(this, 'originalCluster.aksConfig.kubernetesVersion'))) {
      return get(this, 'originalCluster.aksConfig.kubernetesVersion');
    }

    if (!isEmpty(get(this, 'originalCluster.aksConfig.upstreamSpec.kubernetesVersion'))) {
      return get(this, 'originalCluster.aksConfig.upstreamSpec.kubernetesVersion');
    }

    return '';
  }),

  upgradeAvailable: computed('cluster.aksConfig.kubernetesVersion', 'mode', 'model.version', 'nodePool.orchestratorVersion', 'originalClusterVersion', 'showNodeUpgradePreventionReason', function() {
    const originalClusterVersion = get(this, 'originalClusterVersion');
    const clusterVersion         = get(this, 'cluster.aksConfig.kubernetesVersion');
    const nodeVersion            = get(this, 'nodePool.orchestratorVersion');
    const mode                   = get(this, 'mode');

    const initalClusterMinorVersion = parseInt(Semver.minor(Semver.coerce(clusterVersion)), 10);
    const initalNodeMinorVersion   = parseInt(Semver.minor(Semver.coerce(nodeVersion)), 10);
    const diff                     = initalClusterMinorVersion - initalNodeMinorVersion;

    if (mode === 'edit') {
      // we must upgrade the cluster first
      if (originalClusterVersion !== clusterVersion) {
        set(this, 'showNodeUpgradePreventionReason', true);

        return false;
      }
    }

    if (diff === 0 && get(this, 'showNodeUpgradePreventionReason')) {
      set(this, 'showNodeUpgradePreventionReason', false);
    }

    // return diff === 1;
    if (isEmpty(clusterVersion) || isEmpty(nodeVersion)) {
      return false;
    }

    const nodeIsLess = Semver.lt(nodeVersion, clusterVersion, { includePrerelease: true });

    if (nodeIsLess) {
      return true;
    }

    return false;
  }),

  machineSizes: computed('vmSizes.[]', function() {
    return ( this?.vmSizes || [] ).map((vm) => {
      return { value: vm };
    });
  }),

  isNewNodePool: computed('nodePool.isNew', function() {
    return this?.nodePool?.isNew ?? false;
  }),

  displayZones: computed('nodePool.availabilityZones.[]', function() {
    return (this?.nodePool?.availabilityZones || []).slice().join(', ');
  }),

  primaryPool: computed('cluster.aksConfig.nodePools.[]', 'cluster.aksConfig.nodePools.@each.mode', 'isSystemType', function() {
    const { nodePools } = this.cluster?.aksConfig;

    if (nodePools.length === 1) {
      return true;
    }

    if (nodePools.length > 1) {
      const systemPools = nodePools.filterBy('mode', 'System');

      if (systemPools.length === 1 && this.isSystemType) {
        return true;
      } else if (systemPools.length > 1) {
        return false;
      }
    }

    return false;
  }),

});
<commit_msg>fix is new node pool check<commit_after>import Component from '@ember/component';
import { computed, get, observer, set } from '@ember/object';
import { equal } from '@ember/object/computed';
import { on } from '@ember/object/evented';
import { isEmpty } from '@ember/utils';
import Semver from 'semver';
import layout from './template';

const OS_TYPES = [
  { value: 'Linux', },
  { value: 'Windows', }
];

const OS_DISK_TYPES = [
  { value: 'Ephemeral' },
  { value: 'Managed' }
]

export default Component.extend({
  layout,

  cluster:                         null,
  nodePool:                        null,
  vmSizes:                         null,
  vmOs:                            OS_TYPES,
  diskTypes:                       OS_DISK_TYPES,
  upgradeVersion:                  false,
  showNodeUpgradePreventionReason: false,

  isSystemType: equal('nodePool.mode', 'System'),

  updateNodeVersion: on('init', observer('cluster.aksConfig.kubernetesVersion', 'upgradeVersion', 'upgradeAvailable', 'isNewNodePool', function() {
    const {
      cluster, upgradeAvailable, nodePool, upgradeVersion, isNewNodePool
    } = this;

    if (upgradeAvailable && upgradeVersion || isNewNodePool) {
      set(nodePool, 'orchestratorVersion', cluster.aksConfig.kubernetesVersion);
    }
  })),

  originalClusterVersion: computed('cluster.aksConfig.kubernetesVersion', 'originalCluster.aksConfig.kubernetesVersion', 'originalCluster.aksConfig.upstreamSpec.kubernetesVersion', function() {
    if (!isEmpty(get(this, 'originalCluster.aksConfig.kubernetesVersion'))) {
      return get(this, 'originalCluster.aksConfig.kubernetesVersion');
    }

    if (!isEmpty(get(this, 'originalCluster.aksConfig.upstreamSpec.kubernetesVersion'))) {
      return get(this, 'originalCluster.aksConfig.upstreamSpec.kubernetesVersion');
    }

    return '';
  }),

  upgradeAvailable: computed('cluster.aksConfig.kubernetesVersion', 'isNewNodePool', 'mode', 'model.version', 'nodePool.orchestratorVersion', 'originalClusterVersion', 'showNodeUpgradePreventionReason', function() {
    const originalClusterVersion = get(this, 'originalClusterVersion');
    const clusterVersion        = get(this, 'cluster.aksConfig.kubernetesVersion');
    let   nodeVersion           = get(this, 'nodePool.orchestratorVersion');
    const mode                  = get(this, 'mode');
    const isNewNodePool         = get(this, 'isNewNodePool');

    if (isNewNodePool && isEmpty(nodeVersion)) {
      set(this, 'nodePool.orchestratorVersion', clusterVersion);
      // nodeVersion = clusterVersion;
      return false;
    }

    const initalClusterMinorVersion = parseInt(Semver.minor(Semver.coerce(clusterVersion)), 10);
    const initalNodeMinorVersion   = parseInt(Semver.minor(Semver.coerce(nodeVersion)), 10);
    const diff                     = initalClusterMinorVersion - initalNodeMinorVersion;

    if (mode === 'edit') {
      // we must upgrade the cluster first
      if (originalClusterVersion !== clusterVersion) {
        set(this, 'showNodeUpgradePreventionReason', true);

        return false;
      }
    }

    if (diff === 0 && get(this, 'showNodeUpgradePreventionReason')) {
      set(this, 'showNodeUpgradePreventionReason', false);
    }

    // return diff === 1;
    if (isEmpty(clusterVersion) || isEmpty(nodeVersion)) {
      return false;
    }

    const nodeIsLess = Semver.lt(nodeVersion, clusterVersion, { includePrerelease: true });

    if (nodeIsLess) {
      return true;
    }

    return false;
  }),

  machineSizes: computed('vmSizes.[]', function() {
    return ( this?.vmSizes || [] ).map((vm) => {
      return { value: vm };
    });
  }),

  isNewNodePool: computed('nodePool.isNew', function() {
    return this?.nodePool?.isNew ?? false;
  }),

  displayZones: computed('nodePool.availabilityZones.[]', function() {
    return (this?.nodePool?.availabilityZones || []).slice().join(', ');
  }),

  primaryPool: computed('cluster.aksConfig.nodePools.[]', 'cluster.aksConfig.nodePools.@each.mode', 'isSystemType', function() {
    const { nodePools } = this.cluster?.aksConfig;

    if (nodePools.length === 1) {
      return true;
    }

    if (nodePools.length > 1) {
      const systemPools = nodePools.filterBy('mode', 'System');

      if (systemPools.length === 1 && this.isSystemType) {
        return true;
      } else if (systemPools.length > 1) {
        return false;
      }
    }

    return false;
  }),

});
<|endoftext|>


<commit_before>var express = require('express');
var url = require('url');
var net = require('net');
var path = require('path');
var fs = require('fs');
var EventEmitter = require('events').EventEmitter;
var exnted = require('util')._extend;
var util = require('../util');
var EventEmitter = require('events').EventEmitter;
var rules = require('./rules');
var rulesUtil = require('./rules/util');
var connect = require('./proxy/connect');
var config = util.config;

function tunnelProxy(server, proxy) {

	server.on('connect', function(req, reqSocket, head) {//ws, wss, https proxy
		var tunnelUrl = req.url = util.setProtocol(req.url, true);
		var options = parseUrl();
		var resSocket, proxySocket;

		if (!options.hostname) {
			tunnelUrl = req.url = util.setProtocol(req.headers.host, true);
			parseUrl();
		}
		abortIfUnavailable(reqSocket);
		function emitError(err) {
			resSocket && resSocket.destroy();
			proxySocket && proxySocket.destroy();
			reqSocket.destroy();
		}

		function abortIfUnavailable(socket) {
			socket.on('error', emitError).on('close', emitError);
		}

		function parseUrl(_tunnelUrl, port) {
			_tunnelUrl = _tunnelUrl || tunnelUrl;
			options = req.options = url.parse(_tunnelUrl);
			options.port = options.port || port || 443;
			return options;
		}

		function sendEstablished() {
			reqSocket.write('HTTP/1.1 200 Connection Established\r\nProxy-Agent: ' + config.name + '\r\n\r\n');
			return reqSocket;
		}

		function tunnel() {
			rules.resolveHost(tunnelUrl, function(err, ip) {
				req.host = ip;
				if (!util.isLocalAddress(ip) || options.port != proxy.uisslport) {
					proxy.emit('tunnel', req);
				} else {
					options.port = proxy.uisslport;
				}

				if (err) {
					emitError(err);
					return;
				}

				resSocket = net.connect(options.port, ip || options.hostname, function() {
					sendEstablished();
		            resSocket.pipe(reqSocket).pipe(resSocket);
		        });
				abortIfUnavailable(resSocket);
			});
		}

		var _rules = rules.resolveRules(removeDefaultPort(tunnelUrl));
		var proxyUrl = util.rule.getMatcher(_rules.proxy);
		if (proxyUrl) {
			var _tunnelUrl = 'https:' + util.removeProtocol(proxyUrl);
			rules.resolveHost(_tunnelUrl, function(err, ip) {
				req.host = ip;
				parseUrl(_tunnelUrl, config.port);
				if (!err && util.isLocalAddress(ip) && options.port == config.port) {
					parseUrl();
					return tunnel();
				}
				proxy.emit('tunnelProxy', req);
				if (err) {
					emitError(err);
					return;
				}
				options.host = ip;
				connect(req, function(err, _proxySocket) {
					if (err) {
						return emitError();
					}
					proxySocket = _proxySocket;
					abortIfUnavailable(_proxySocket);
					sendEstablished().pipe(_proxySocket).pipe(reqSocket);
				});
			});
		} else {
			tunnel();
		}
    });

	return server;
}

function removeDefaultPort(url) {
	var index = url.lastIndexOf(':');
	if (index != -1 && url.substring(index + 1) == '443') {
		url = url.substring(0, index);
	}

	return url;
}

process.on('uncaughtException', function(err){
	  fs.writeFileSync(path.join(process.cwd(), config.name + '-log.log'), err.stack + '\r\n', {flag: 'a'});
	  console.error(err);
	  process.exit(1);
});

function proxy(port, middlewares, _config) {
	if (Array.isArray(port)) {
		_config = middlewares;
		middlewares = port;
	} else if (!Array.isArray(middlewares)) {
		middlewares = [];
	}

	exnted(config, _config);
	var proxyEvents = new EventEmitter();
	var app = express();

	var server = app.listen(proxyEvents.port = port || config.port);
	server.on('clientError', util.noop); //ignore，防止keepalive的socket发生error时，出现crash
	middlewares = ['./init',
	               '../biz']
				   .concat(require('./inspectors'))
				   .concat(middlewares)
	               .concat(['../biz/tianma'])
	               .concat(require('./handlers'));

	middlewares.forEach(function(mw) {
		app.use((typeof mw == 'string' ? require(mw) : mw).bind(proxyEvents));
	});
	exportInterfaces(proxyEvents);
	tunnelProxy(server, proxyEvents);
	require('./proxy');
	return proxyEvents;
}

function exportInterfaces(obj) {
	obj.rules = rules;
	obj.util = util;
	obj.rulesUtil = rulesUtil;
	return obj;
}

module.exports = exportInterfaces(proxy);<commit_msg>emit error<commit_after>var express = require('express');
var url = require('url');
var net = require('net');
var path = require('path');
var fs = require('fs');
var EventEmitter = require('events').EventEmitter;
var exnted = require('util')._extend;
var util = require('../util');
var rules = require('./rules');
var rulesUtil = require('./rules/util');
var connect = require('./proxy/connect');
var config = util.config;

function tunnelProxy(server, proxy) {

	server.on('connect', function(req, reqSocket, head) {//ws, wss, https proxy
		var tunnelUrl = req.url = util.setProtocol(req.url, true);
		var options = parseUrl();
		var resSocket, proxySocket;

		if (!options.hostname) {
			tunnelUrl = req.url = util.setProtocol(req.headers.host, true);
			parseUrl();
		}
		abortIfUnavailable(reqSocket);
		function emitError(err) {
			resSocket && resSocket.destroy();
			proxySocket && proxySocket.destroy();
			reqSocket.destroy();
		}

		function abortIfUnavailable(socket) {
			socket.on('error', emitError).on('close', emitError);
		}

		function parseUrl(_tunnelUrl, port) {
			_tunnelUrl = _tunnelUrl || tunnelUrl;
			options = req.options = url.parse(_tunnelUrl);
			options.port = options.port || port || 443;
			return options;
		}

		function sendEstablished() {
			reqSocket.write('HTTP/1.1 200 Connection Established\r\nProxy-Agent: ' + config.name + '\r\n\r\n');
			return reqSocket;
		}

		function tunnel() {
			rules.resolveHost(tunnelUrl, function(err, ip) {
				req.host = ip;
				if (!util.isLocalAddress(ip) || options.port != proxy.uisslport) {
					proxy.emit('tunnel', req);
				} else {
					options.port = proxy.uisslport;
				}

				if (err) {
					emitError(err);
					return;
				}

				resSocket = net.connect(options.port, ip || options.hostname, function() {
					sendEstablished();
		            resSocket.pipe(reqSocket).pipe(resSocket);
		        });
				abortIfUnavailable(resSocket);
			});
		}

		var _rules = rules.resolveRules(removeDefaultPort(tunnelUrl));
		var proxyUrl = util.rule.getMatcher(_rules.proxy);
		if (proxyUrl) {
			var _tunnelUrl = 'https:' + util.removeProtocol(proxyUrl);
			rules.resolveHost(_tunnelUrl, function(err, ip) {
				req.host = ip;
				parseUrl(_tunnelUrl, config.port);
				if (!err && util.isLocalAddress(ip) && options.port == config.port) {
					parseUrl();
					return tunnel();
				}
				proxy.emit('tunnelProxy', req);
				if (err) {
					emitError(err);
					return;
				}
				options.host = ip;
				connect(req, function(err, _proxySocket) {
					if (err) {
						return emitError();
					}
					proxySocket = _proxySocket;
					abortIfUnavailable(_proxySocket);
					sendEstablished().pipe(_proxySocket).pipe(reqSocket);
				});
			});
		} else {
			tunnel();
		}
    });

	return server;
}

function removeDefaultPort(url) {
	var index = url.lastIndexOf(':');
	if (index != -1 && url.substring(index + 1) == '443') {
		url = url.substring(0, index);
	}

	return url;
}

process.on('uncaughtException', function(err){
	  fs.writeFileSync(path.join(process.cwd(), config.name + '-log.log'), err.stack + '\r\n', {flag: 'a'});
	  console.error(err);
	  process.exit(1);
});

function proxy(port, middlewares, _config) {
	if (Array.isArray(port)) {
		_config = middlewares;
		middlewares = port;
	} else if (!Array.isArray(middlewares)) {
		middlewares = [];
	}

	exnted(config, _config);
	var proxyEvents = new EventEmitter();
	var app = express();

	var server = app.listen(proxyEvents.port = port || config.port);
	server.on('clientError', util.noop); //ignore，防止keepalive的socket发生error时，出现crash
	middlewares = ['./init',
	               '../biz']
				   .concat(require('./inspectors'))
				   .concat(middlewares)
	               .concat(['../biz/tianma'])
	               .concat(require('./handlers'));

	middlewares.forEach(function(mw) {
		app.use((typeof mw == 'string' ? require(mw) : mw).bind(proxyEvents));
	});
	exportInterfaces(proxyEvents);
	tunnelProxy(server, proxyEvents);
	require('./proxy');
	return proxyEvents;
}

function exportInterfaces(obj) {
	obj.rules = rules;
	obj.util = util;
	obj.rulesUtil = rulesUtil;
	return obj;
}

module.exports = exportInterfaces(proxy);<|endoftext|>


<commit_before>// Karma configuration
// Generated on Mon Dec 14 2015 13:37:20 GMT-0500 (Eastern Standard Time)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    baseUrl: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine', 'requirejs'],

    // list of files / patterns to load in the browser
    files: [
		{pattern: 'Source/**/*', included: false, served: true},
		{pattern: 'Specs/**/*', included: false, served: true},

		'Specs/test-main.js'
    ],

    proxies: {
    },

    // list of files to exclude
    exclude: [
        'Specs/Widgets/**/*.js',
        'Specs/Scene/**/*.js',
        'Specs/DataSources/**/*.js',
        'Specs/Renderer/**/*.js'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['spec'],
    specReporter: {
      maxLogLines: 10,
      suppressErrorSummary: true,
      suppressFailed: false,
      suppressPassed: true,  // do not print information about passed tests
      suppressSkipped: true  // do not print information about skipped tests
    },

    // web server port
    port: 8080,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Firefox'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultanous
    concurrency: Infinity
  });
};
<commit_msg>configured enabled webgl in firefox<commit_after>// Karma configuration
// Generated on Mon Dec 14 2015 13:37:20 GMT-0500 (Eastern Standard Time)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    baseUrl: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine', 'requirejs'],

    // list of files / patterns to load in the browser
    files: [
		{pattern: 'Source/**/*', included: false, served: true},
		{pattern: 'Specs/**/*', included: false, served: true},

		'Specs/test-main.js'
    ],

    proxies: {
    },

    // list of files to exclude
    exclude: [
        'Specs/Widgets/**/*.js',
        'Specs/Scene/**/*.js',
        'Specs/DataSources/**/*.js',
        'Specs/Renderer/**/*.js'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['spec'],
    specReporter: {
      maxLogLines: 10,
      suppressErrorSummary: true,
      suppressFailed: false,
      suppressPassed: true,  // do not print information about passed tests
      suppressSkipped: true  // do not print information about skipped tests
    },

    // web server port
    port: 8080,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['FirefoxWithWebGL'],

    customLaunchers: {
      FirefoxWithWebGL: {
        base: 'Firefox',
        prefs: {
          'webgl.force-enabled': true
        }
      }
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultanous
    concurrency: Infinity
  });
};
<|endoftext|>


<commit_before>var should = require("should")
var bbb = require("../lib/babelsberg")
var bbb_cassowary = require("babelsbergjs-cassowary")

function prepared_always(ctx,callback) {
  ctx = ctx || {};
  return bbb.always({
    solver: new bbb_cassowary.ClSimplexSolver(),
    ctx: ctx
  }, callback);
}

describe('bbb', function() {

  describe('properties', function() {
    it('contain empty solvers.', function() {
      bbb.should.have.property('defaultSolvers').with.lengthOf(0);
    });

    it('contain empty callbacks.', function() {
      bbb.should.have.property('callbacks').with.lengthOf(0);
    });
  });

  describe('#always()', function() {
    it('is Function Object.', function() {
      bbb.should.have.property('always').which.is.a.Function;
    });

    it('was declared in Babelsberg blass.', function() {
      bbb.always.should.property('declaredClass')
          .which.is.exactly("Babelsberg");
    });
  });

  it('can disable constraints temporarily.', function() {
    var obj = {a: 8};
    var c = prepared_always({obj: obj}, function () {
        return obj.a >= 100;
    });
    obj.a = 110;
    (function(){
      obj.a = 90
    }).should.throw(/^\(ExCLRequiredFailure\).*/);
    c.disable();
    obj.a = 90;
    obj.a.should.be.exactly(90);
    c.enable();
    obj.a.should.be.exactly(100);
    (function(){
        obj.a = 90;
    }).should.throw(/^\(ExCLRequiredFailure\).*/);
  });
});
<commit_msg>Moved constraint tests to cassowary as it is bound to it even stronger.<commit_after>var should = require("should")
var bbb = require("../lib/babelsberg")
var bbb_cassowary = require("babelsbergjs-cassowary")

describe('bbb', function() {
  describe('properties', function() {
    it('contain empty solvers.', function() {
      bbb.should.have.property('defaultSolvers').with.lengthOf(0);
    });

    it('contain empty callbacks.', function() {
      bbb.should.have.property('callbacks').with.lengthOf(0);
    });
  });

  describe('#always()', function() {
    it('is Function Object.', function() {
      bbb.should.have.property('always').which.is.a.Function;
    });

    it('was declared in Babelsberg blass.', function() {
      bbb.always.should.property('declaredClass')
          .which.is.exactly("Babelsberg");
    });
  });

  it('can use solver for simple reassignment solving.', function() {
    obj = {a: 1, b: 2};
    return bbb.always({
      solver: new bbb_cassowary.ClSimplexSolver(),
      ctx: {obj: obj}
    }, function () {
      return obj.a + 7 <= obj.b;
    });
    obj.a = 10;
    (obj.a + 7).should.not.be.greaterThan(obj.b);
  });
});
<|endoftext|>


<commit_before>/*
 * Gruntfile.js
 * Copyright(c) 2016 Bitergia
 * Author: Bitergia <fiware-testing@bitergia.com>
 * MIT Licensed
 *
 * Gruntfile configuration
 *
 */

// jshint node: true, camelcase: false, maxlen: false
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers, maximumLineLength

'use strict';

module.exports = function(grunt) {

  // configuration
  grunt.initConfig({

    // Run shell commands
    shell: {

      hooks: {
        // setup pre-commit git hook
        command: 'ln -sf ../../git-hooks/pre-commit ../.git/hooks/'
      },

      test_env_on: {
        // start clean containers for testing
        command: './setup-test-env.sh start'
      },

      test_env_off: {
        // stop testing containers
        command: './setup-test-env.sh stop'
      },

      tests: {
        // execute jasmine_node tests inside testing container
        command: 'docker exec -u tourguide tests_tourguide_1 bash -c "cd ~/tutorials.TourGuide-App/server ; grunt do-test"'
      }

    },

    srcfiles: ['*.js', 'routes/*.js','feeders/*.js', 'idas/*.js'],
    testfiles: ['spec/*.js'],

    jshint: {
      src: ['<%= srcfiles %>','<%= testfiles %>']
    },

    jscs: {
      src: ['<%= srcfiles %>','<%= testfiles %>']
    },

    jasmine_node: {
      options: {
        forceExit: true,
        match: '.',
        matchall: false,
        extensions: 'js',
        specNameMatcher: 'spec',
        specFolders: ['spec']
      },
      all: ['<%= srcfiles %>']
    }

  });

  // load tasks
  grunt.loadNpmTasks('grunt-jscs');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-jasmine-node');
  grunt.loadNpmTasks('grunt-shell');
  grunt.loadNpmTasks('grunt-continue');

  // define tasks
  grunt.registerTask('lint', 'Check source code style', ['jshint:src', 'jscs:src']);
  grunt.registerTask('do-test', 'Run jasmine tests', ['jasmine_node:all']);
  // Clean the .git/hooks/pre-commit file then copy in the latest version
  grunt.registerTask('setup-git-hooks', ['shell:hooks']);
  grunt.registerTask(
    'test',
    'Run tests on a clean docker-compose environment',
    [
      'shell:test_env_on',
      'continue:on',
      'shell:tests',
      'continue:off',
      'shell:test_env_off',
      'continue:fail-on-warning'
    ]);

  // default task
  grunt.registerTask('default', ['lint', 'test']);
};
<commit_msg>Add new paths to lint check.<commit_after>/*
 * Gruntfile.js
 * Copyright(c) 2016 Bitergia
 * Author: Bitergia <fiware-testing@bitergia.com>
 * MIT Licensed
 *
 * Gruntfile configuration
 *
 */

// jshint node: true, camelcase: false, maxlen: false
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers, maximumLineLength

'use strict';

module.exports = function(grunt) {

  // configuration
  grunt.initConfig({

    // Run shell commands
    shell: {

      hooks: {
        // setup pre-commit git hook
        command: 'ln -sf ../../git-hooks/pre-commit ../.git/hooks/'
      },

      test_env_on: {
        // start clean containers for testing
        command: './setup-test-env.sh start'
      },

      test_env_off: {
        // stop testing containers
        command: './setup-test-env.sh stop'
      },

      tests: {
        // execute jasmine_node tests inside testing container
        command: 'docker exec -u tourguide tests_tourguide_1 bash -c "cd ~/tutorials.TourGuide-App/server ; grunt do-test"'
      }

    },

    srcfiles: ['*.js', 'routes/*.js','feeders/*.js', 'idas/*.js', 'auth/*.js', 'misc/*.js'],
    testfiles: ['spec/*.js'],

    jshint: {
      src: ['<%= srcfiles %>','<%= testfiles %>']
    },

    jscs: {
      src: ['<%= srcfiles %>','<%= testfiles %>']
    },

    jasmine_node: {
      options: {
        forceExit: true,
        match: '.',
        matchall: false,
        extensions: 'js',
        specNameMatcher: 'spec',
        specFolders: ['spec']
      },
      all: ['<%= srcfiles %>']
    }

  });

  // load tasks
  grunt.loadNpmTasks('grunt-jscs');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-jasmine-node');
  grunt.loadNpmTasks('grunt-shell');
  grunt.loadNpmTasks('grunt-continue');

  // define tasks
  grunt.registerTask('lint', 'Check source code style', ['jshint:src', 'jscs:src']);
  grunt.registerTask('do-test', 'Run jasmine tests', ['jasmine_node:all']);
  // Clean the .git/hooks/pre-commit file then copy in the latest version
  grunt.registerTask('setup-git-hooks', ['shell:hooks']);
  grunt.registerTask(
    'test',
    'Run tests on a clean docker-compose environment',
    [
      'shell:test_env_on',
      'continue:on',
      'shell:tests',
      'continue:off',
      'shell:test_env_off',
      'continue:fail-on-warning'
    ]);

  // default task
  grunt.registerTask('default', ['lint', 'test']);
};
<|endoftext|>


<commit_before>//configuration object

var config = {
    title:"Nepal Earthquake Shelter Cluster Gap Maps",
    description:"Shelter Cluster dashboard showing shelter activities in the 14 priority districts in response to Nepal 2015 Earthquakes. Select a district on the map to view gap maps for the VDCs. Data can be downloaded from HDX.  Click here to view the activities dashboard.",
    data:"data/data.json",
    whoFieldName:"#org+implementing",
    whatFieldName:"#activity+description",
    whereFieldName:"#adm4+code",
    statusFieldName:"#status",h
    groupFieldName:"#reached+households",
    districtlevelFieldName:"#indicator+parent",
    geo:"data/nepal_adm3.json",
    joinAttribute:"HLCIT_CODE",
    nameAttribute:"VDC_NAME",
    color:"#B78C8D",
    colors:["#DDDDDD","#CAB4B5","#B78C8D","#A46465","#913C3D","#7F1416"],
    colors2:["#CAB4B5","#B78C8D","#A46465","#913C3D","#7F1416"]
};

function initDash(config,geom){

    $('#title').html(config.title);
    $('#description').html(config.description);
    loadDatatable();
    map = L.map('rc-3W-where',{});

    /*L.tileLayer('https://a.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);

    L.tileLayer('https://c.tiles.mapbox.com/v3/examples.map-szwdot65/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(map);*/

    var baselayer = new L.StamenTileLayer("toner");

    map.addLayer(baselayer);

    overlay = L.geoJson(geom,{
        style: function(f){
            if(f.properties.HUB=='West'){
                var color = '#7F1416';
            } else if (f.properties.HUB=='Central') {
                var color = '#A46465';
            } else {
                var color = '#CAB4B5';
            }
            return {
            fillColor: color,
            color: "#7F1416",
            weight: 3,
            opacity: 1,
            fillOpacity: 0.5};
        },
        onEachFeature: onEachFeature
    }).addTo(map);

    var info = L.control();

    info.onAdd = function (map) {
        div = L.DomUtil.create('div', 'hdx-3w-info');
            return div;
        };

    info.addTo(map);

    $('.hdx-3w-info').html('Click a district to see district level data');
    $('#switch_att').click(function(){
        switchAtt();
    })

    map.scrollWheelZoom.disable();
    zoomToGeom(geom);
}

function onEachFeature(feature, layer) {
    layer.on('click', function (e){
            zoomToADM4(e.target.feature.properties.DISTRICT,e.target.feature.properties.HLCIT_CODE);
    });

    layer.on('mouseover', function(e){
        $('.hdx-3w-info').html('Click to view '+e.target.feature.properties.DISTRICT);
        $('.adm'+e.target.feature.properties['HLCIT_CODE'].replace(/ /g,'_')).addClass('highlight');
    })

    layer.on('mouseout', function(e){
        $('.hdx-3w-info').html('Click a district to see district level data');
        $('.adm'+e.target.feature.properties['HLCIT_CODE'].replace(/ /g,'_')).removeClass('highlight');
    })
}

function zoomToADM4(districtName,districtCode){
        $('#modal').modal('show');
        attName = districtName;
        attCode = districtCode;
        //suspect e.target.feature.properties.DISTRICT will not work on multi-polygons
        if(att=='er'){
            var text = 'Emergency Response (Tarps and Tents) Gap';
        } else {
            var text = 'Recovery (CGI and Cash) Gap';
        }
        $('#district_name').html(districtName + ' - ' + text);
        //var url = 'http://beta.proxy.hxlstandard.org/data.json?filter_count=7&url=https%3A//docs.google.com/spreadsheets/d/1Z4YWDKWnrSJPcyFEyHawRck0SrXg6R0hBriH7gBZuqA/export%3Fformat%3Dcsv%26id%3D1Z4YWDKWnrSJPcyFEyHawRck0SrXg6R0hBriH7gBZuqA%26gid%3D0&strip-headers=on&format=html&filter01=cut&cut-include-tags01=%23adm3%2Bcode%2C%23adm4%2Bcode%2C%23org%2Bimplementing%2C%23activity%2Bdescription%2C%23status%2C%23reached%2Buse%2C%23indicator&cut-exclude-tags01=&filter02=select&force=1&select-query02-01=adm3%2Bcode%3D'+e.target.feature.properties.HLCIT_CODE
        var url = 'https://proxy.hxlstandard.org/data.json?filter01=select&strip-headers=on&url=https%3A//docs.google.com/spreadsheets/d/1Z4YWDKWnrSJPcyFEyHawRck0SrXg6R0hBriH7gBZuqA/pub%3Fgid%3D1857051232%26single%3Dtrue%26output%3Dcsv&force=1&select-query01-01=adm3%2Bcode%3D'+districtCode;
        var dataCall = $.ajax({
            type: 'GET',
            url: url,
            dataType: 'json',
            error:function(e,exception){
                console.log(exception);
            }
        });
        overlay.setStyle({
            fillColor: "#7F1416",
            color: "#7F1416",
            weight: 3,
            opacity: 1,
            fillOpacity: 0
        });

        //load geometry

        var geomCall = $.ajax({
            type: 'GET',
            url: 'data/'+districtName+'.json',
            dataType: 'json',
        });

        $.when(dataCall, geomCall).then(function(dataArgs, geomArgs){
            /*$('#leftcolumn').removeClass('col-sm-12');
            $('#leftcolumn').addClass('col-sm-8');
            $('#rightcolumn').removeClass('col-sm-0');
            $('#rightcolumn').addClass('col-sm-4');*/
            $('#overviewtable').hide();
            map.invalidateSize();
            $('#info_row').show();
            var data = hxlProxyToJSON(dataArgs[0])
            var geom = topojson.feature(geomArgs[0],geomArgs[0].objects[districtName]);
            $('#modal').modal('hide');
            geom = joinDataToADM4(geom,data);

            if(legendon==false){
                legendon=true;
                var legend = L.control({position: 'bottomright'});

                legend.onAdd = function (map) {

                    var div = L.DomUtil.create('div', 'info legend'),
                        labels = ['0','1% - 40%','41% - 70%','70% - 99%','100%'];

                    div.innerHTML = 'Percent (%) of
shelter need reached
';
                    for (var i = 0; i < labels.length; i++) {
                        div.innerHTML +=
                            ' ' + labels[i] +'
';
                    }

                    return div;
                };

                legend.addTo(map);
            }

            generateGapComponent(config,data,geom,map);
        });
}

function generateGapComponent(config,data,geom,map){

    if(overlay2!=''){
        map.removeLayer(overlay2);
    }

    overlay2 = L.geoJson(geom,{
        style: function(f){
            if(f.properties[att]>=1){
                var color = colors[4];
            } else if (f.properties[att]>0.7) {
                var color = colors[3];
            } else if (f.properties[att]>0.4) {
                var color = colors[2];
            } else if (f.properties[att]>0) {
                var color = colors[1];
            } else {
                var color = colors[0];
            }
            return {
            fillColor: color,
            color: "#7F1416",
            weight: 2,
            opacity: 1,
            fillOpacity: 0.5};
        },
        onEachFeature: onEachFeature
    }).addTo(map);

    zoomToGeom(geom);

    function onEachFeature(feature,layer){
        layer.on('mouseover',function(e){
            $('.hdx-3w-info').html(e.target.feature.properties.VDC_NAME+' - '+d3.format("%")(e.target.feature.properties[att]));
        })
        layer.on('mouseout',function(e){
            $('.hdx-3w-info').html('Hover VDC for gap info');
        })
    }
}

function zoomToGeom(geom){
    var bounds = d3.geo.bounds(geom);
    map.fitBounds([[bounds[0][1],bounds[0][0]],[bounds[1][1],bounds[1][0]]]);
}

function genLookupVDCCodeToName(geojson,config){
    var lookup = {};
    geojson.features.forEach(function(e){
        lookup[e.properties[config.joinAttribute]] = String(e.properties[config.nameAttribute]);
    });
    return lookup;
}

function joinDataToADM4(geom,data){
    geom.features.forEach(function(f){
        f.properties[att] = 0;
        data.forEach(function(d){
            if(d['#adm4+code'] == f.properties['HLCIT_CODE']){
                f.properties[att] = d['#reached+'+att];
            }
        })
    });
    return geom;
}

function switchAtt(){
    if(att=='er'){
        att = 'recovery';
        $('#switch_att').html('Switch to Emergency Response Gap Map');
    } else {
        att = 'er';
        $('#switch_att').html('Switch to Recovery Gap Map');
    }
    zoomToADM4(attName,attCode);
}

function hxlProxyToJSON(input){
    var input = stripIfNull(input);
    var output = [];
    var keys=[]
    input.forEach(function(e,i){
        if(i==0){
            keys = e;
        } else {
            var row = {};
            e.forEach(function(e2,i2){
                row[keys[i2]] = e2;
            });
            output.push(row);
        }
    });
    return output;
}

function stripIfNull(input){
    if(input[0][0]==null){
        input.shift();
        return input;
    }
    return input;
}

function loadDatatable(){
    var activityurl = 'https://beta.proxy.hxlstandard.org/data.json?filter_count=7&url=https%3A//docs.google.com/spreadsheets/d/1Z4YWDKWnrSJPcyFEyHawRck0SrXg6R0hBriH7gBZuqA/pub%3Fgid%3D0%26single%3Dtrue%26output%3Dcsv&strip-headers=on&format=html&filter01=cut&cut-include-tags01=adm3%2Bcode%2Creached%2Bhouseholds%2Cactivity%2Bdescription&cut-exclude-tags01=&filter02=count&count-tags02=%23adm3%2Bcode%2C%23activity%2Bdescription&count-aggregate-tag02=%23reached%2Bhouseholds&filter03=&filter04=&filter05=&filter06=&filter07=';
    var damageurl ='https://beta.proxy.hxlstandard.org/data.json?filter_count=7&strip-headers=on&url=https%3A//docs.google.com/spreadsheets/d/1Z4YWDKWnrSJPcyFEyHawRck0SrXg6R0hBriH7gBZuqA/pub%3Fgid%3D975313202%26single%3Dtrue%26output%3Dcsv&format=html';

    var activityCall = $.ajax({
            type: 'GET',
            url: activityurl,
            dataType: 'json',
            error:function(e,exception){
                console.log(exception);
            }
        });

        //load geometry

        var damageCall = $.ajax({
            type: 'GET',
            url: damageurl,
            dataType: 'json',
        });

    $.when(damageCall, activityCall).then(function(damageArgs, activityArgs){
        var damage = hxlProxyToJSON(damageArgs[0]);
        var activitycf = crossfilter(hxlProxyToJSON(activityArgs[0]));
        var activityDimension = activitycf.dimension(function(d){return d['#activity+description'];});
        var geoDimension = activitycf.dimension(function(d){ return d['#adm3+code']});
        var activityGroup = activityDimension.group().reduceSum(function(d){return d['#meta+sum'];});
        var table = '

	Damage	';
        var activitylist = [];
        activityGroup.top(5).forEach(function(d){
            if(d.value>0){
                activitylist.push(d.key)
                table+=''+d.key+'	';
            }
        });
        table +='
';

        geom.features.forEach(function(f){
            table+='
'+f.properties.DISTRICT+'	';
            var damagevalue = 0;
            damage.forEach(function(d){
                if(d['#adm3+code']==f.properties['HLCIT_CODE']){
                    damagevalue = Math.round(d['#affected+households']);
                }
            })
            table+=''+damagevalue+'	';

            geoDimension.filter(f.properties['HLCIT_CODE']);
            activitylist.forEach(function(k){
                var value = 0;
                activityGroup.top(Infinity).forEach(function(d){
                    if(d.key==k){
                        value =Math.round(d.value);
                    }
                });
                table +=''+value+'	';
            });
            table+='
';
        });
        table +='
';
        $('#overviewtable').html(table);
    });
}
//load 3W data
var map;
var lookUpVDCCodeToName;
var data;
var overlay2 = '';
var geom = topojson.feature(nepal_adm3,nepal_adm3.objects.nepal_adm3);
var overlay;
var att = 'recovery';
var atttName = '';
var attCode = '';
var colors = ['#FFFFFF','#DFC4C4','#BF898A','#9F4E50','#7F1416'];
var legendon = false;
geom.features.forEach(function(e){
    e.properties[config.joinAttribute] = String(e.properties[config.joinAttribute]);
});
$('#info_row').hide();
initDash(config,geom);
<commit_msg>Update gap.js<commit_after>//configuration object

var config = {
    title:"Nepal Earthquake Shelter Cluster Gap Maps",
    description:"Shelter Cluster dashboard showing shelter activities in the 14 priority districts in response to Nepal 2015 Earthquakes. Select a district on the map to view gap maps for the VDCs. Data can be downloaded from HDX.  Click here to view the activities dashboard.",
    data:"data/data.json",
    whoFieldName:"#org+implementing",
    whatFieldName:"#activity+description",
    whereFieldName:"#adm4+code",
    statusFieldName:"#status",
    groupFieldName:"#reached+households",
    districtlevelFieldName:"#indicator+parent",
    geo:"data/nepal_adm3.json",
    joinAttribute:"HLCIT_CODE",
    nameAttribute:"VDC_NAME",
    color:"#B78C8D",
    colors:["#DDDDDD","#CAB4B5","#B78C8D","#A46465","#913C3D","#7F1416"],
    colors2:["#CAB4B5","#B78C8D","#A46465","#913C3D","#7F1416"]
};

function initDash(config,geom){

    $('#title').html(config.title);
    $('#description').html(config.description);
    loadDatatable();
    map = L.map('rc-3W-where',{});

    /*L.tileLayer('https://a.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);

    L.tileLayer('https://c.tiles.mapbox.com/v3/examples.map-szwdot65/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(map);*/

    var baselayer = new L.StamenTileLayer("toner");

    map.addLayer(baselayer);

    overlay = L.geoJson(geom,{
        style: function(f){
            if(f.properties.HUB=='West'){
                var color = '#7F1416';
            } else if (f.properties.HUB=='Central') {
                var color = '#A46465';
            } else {
                var color = '#CAB4B5';
            }
            return {
            fillColor: color,
            color: "#7F1416",
            weight: 3,
            opacity: 1,
            fillOpacity: 0.5};
        },
        onEachFeature: onEachFeature
    }).addTo(map);

    var info = L.control();

    info.onAdd = function (map) {
        div = L.DomUtil.create('div', 'hdx-3w-info');
            return div;
        };

    info.addTo(map);

    $('.hdx-3w-info').html('Click a district to see district level data');
    $('#switch_att').click(function(){
        switchAtt();
    })

    map.scrollWheelZoom.disable();
    zoomToGeom(geom);
}

function onEachFeature(feature, layer) {
    layer.on('click', function (e){
            zoomToADM4(e.target.feature.properties.DISTRICT,e.target.feature.properties.HLCIT_CODE);
    });

    layer.on('mouseover', function(e){
        $('.hdx-3w-info').html('Click to view '+e.target.feature.properties.DISTRICT);
        $('.adm'+e.target.feature.properties['HLCIT_CODE'].replace(/ /g,'_')).addClass('highlight');
    })

    layer.on('mouseout', function(e){
        $('.hdx-3w-info').html('Click a district to see district level data');
        $('.adm'+e.target.feature.properties['HLCIT_CODE'].replace(/ /g,'_')).removeClass('highlight');
    })
}

function zoomToADM4(districtName,districtCode){
        $('#modal').modal('show');
        attName = districtName;
        attCode = districtCode;
        //suspect e.target.feature.properties.DISTRICT will not work on multi-polygons
        if(att=='er'){
            var text = 'Emergency Response (Tarps and Tents) Gap';
        } else {
            var text = 'Recovery (CGI and Cash) Gap';
        }
        $('#district_name').html(districtName + ' - ' + text);
        //var url = 'http://beta.proxy.hxlstandard.org/data.json?filter_count=7&url=https%3A//docs.google.com/spreadsheets/d/1Z4YWDKWnrSJPcyFEyHawRck0SrXg6R0hBriH7gBZuqA/export%3Fformat%3Dcsv%26id%3D1Z4YWDKWnrSJPcyFEyHawRck0SrXg6R0hBriH7gBZuqA%26gid%3D0&strip-headers=on&format=html&filter01=cut&cut-include-tags01=%23adm3%2Bcode%2C%23adm4%2Bcode%2C%23org%2Bimplementing%2C%23activity%2Bdescription%2C%23status%2C%23reached%2Buse%2C%23indicator&cut-exclude-tags01=&filter02=select&force=1&select-query02-01=adm3%2Bcode%3D'+e.target.feature.properties.HLCIT_CODE
        var url = 'https://proxy.hxlstandard.org/data.json?filter01=select&strip-headers=on&url=https%3A//docs.google.com/spreadsheets/d/1Z4YWDKWnrSJPcyFEyHawRck0SrXg6R0hBriH7gBZuqA/pub%3Fgid%3D1857051232%26single%3Dtrue%26output%3Dcsv&force=1&select-query01-01=adm3%2Bcode%3D'+districtCode;
        var dataCall = $.ajax({
            type: 'GET',
            url: url,
            dataType: 'json',
            error:function(e,exception){
                console.log(exception);
            }
        });
        overlay.setStyle({
            fillColor: "#7F1416",
            color: "#7F1416",
            weight: 3,
            opacity: 1,
            fillOpacity: 0
        });

        //load geometry

        var geomCall = $.ajax({
            type: 'GET',
            url: 'data/'+districtName+'.json',
            dataType: 'json',
        });

        $.when(dataCall, geomCall).then(function(dataArgs, geomArgs){
            /*$('#leftcolumn').removeClass('col-sm-12');
            $('#leftcolumn').addClass('col-sm-8');
            $('#rightcolumn').removeClass('col-sm-0');
            $('#rightcolumn').addClass('col-sm-4');*/
            $('#overviewtable').hide();
            map.invalidateSize();
            $('#info_row').show();
            var data = hxlProxyToJSON(dataArgs[0])
            var geom = topojson.feature(geomArgs[0],geomArgs[0].objects[districtName]);
            $('#modal').modal('hide');
            geom = joinDataToADM4(geom,data);

            if(legendon==false){
                legendon=true;
                var legend = L.control({position: 'bottomright'});

                legend.onAdd = function (map) {

                    var div = L.DomUtil.create('div', 'info legend'),
                        labels = ['0','1% - 40%','41% - 70%','70% - 99%','100%'];

                    div.innerHTML = 'Percent (%) of
shelter need reached
';
                    for (var i = 0; i < labels.length; i++) {
                        div.innerHTML +=
                            ' ' + labels[i] +'
';
                    }

                    return div;
                };

                legend.addTo(map);
            }

            generateGapComponent(config,data,geom,map);
        });
}

function generateGapComponent(config,data,geom,map){

    if(overlay2!=''){
        map.removeLayer(overlay2);
    }

    overlay2 = L.geoJson(geom,{
        style: function(f){
            if(f.properties[att]>=1){
                var color = colors[4];
            } else if (f.properties[att]>0.7) {
                var color = colors[3];
            } else if (f.properties[att]>0.4) {
                var color = colors[2];
            } else if (f.properties[att]>0) {
                var color = colors[1];
            } else {
                var color = colors[0];
            }
            return {
            fillColor: color,
            color: "#7F1416",
            weight: 2,
            opacity: 1,
            fillOpacity: 0.5};
        },
        onEachFeature: onEachFeature
    }).addTo(map);

    zoomToGeom(geom);

    function onEachFeature(feature,layer){
        layer.on('mouseover',function(e){
            $('.hdx-3w-info').html(e.target.feature.properties.VDC_NAME+' - '+d3.format("%")(e.target.feature.properties[att]));
        })
        layer.on('mouseout',function(e){
            $('.hdx-3w-info').html('Hover VDC for gap info');
        })
    }
}

function zoomToGeom(geom){
    var bounds = d3.geo.bounds(geom);
    map.fitBounds([[bounds[0][1],bounds[0][0]],[bounds[1][1],bounds[1][0]]]);
}

function genLookupVDCCodeToName(geojson,config){
    var lookup = {};
    geojson.features.forEach(function(e){
        lookup[e.properties[config.joinAttribute]] = String(e.properties[config.nameAttribute]);
    });
    return lookup;
}

function joinDataToADM4(geom,data){
    geom.features.forEach(function(f){
        f.properties[att] = 0;
        data.forEach(function(d){
            if(d['#adm4+code'] == f.properties['HLCIT_CODE']){
                f.properties[att] = d['#reached+'+att];
            }
        })
    });
    return geom;
}

function switchAtt(){
    if(att=='er'){
        att = 'recovery';
        $('#switch_att').html('Switch to Emergency Response Gap Map');
    } else {
        att = 'er';
        $('#switch_att').html('Switch to Recovery Gap Map');
    }
    zoomToADM4(attName,attCode);
}

function hxlProxyToJSON(input){
    var input = stripIfNull(input);
    var output = [];
    var keys=[]
    input.forEach(function(e,i){
        if(i==0){
            keys = e;
        } else {
            var row = {};
            e.forEach(function(e2,i2){
                row[keys[i2]] = e2;
            });
            output.push(row);
        }
    });
    return output;
}

function stripIfNull(input){
    if(input[0][0]==null){
        input.shift();
        return input;
    }
    return input;
}

function loadDatatable(){
    var activityurl = 'https://beta.proxy.hxlstandard.org/data.json?filter_count=7&url=https%3A//docs.google.com/spreadsheets/d/1Z4YWDKWnrSJPcyFEyHawRck0SrXg6R0hBriH7gBZuqA/pub%3Fgid%3D0%26single%3Dtrue%26output%3Dcsv&strip-headers=on&format=html&filter01=cut&cut-include-tags01=adm3%2Bcode%2Creached%2Bhouseholds%2Cactivity%2Bdescription&cut-exclude-tags01=&filter02=count&count-tags02=%23adm3%2Bcode%2C%23activity%2Bdescription&count-aggregate-tag02=%23reached%2Bhouseholds&filter03=&filter04=&filter05=&filter06=&filter07=';
    var damageurl ='https://beta.proxy.hxlstandard.org/data.json?filter_count=7&strip-headers=on&url=https%3A//docs.google.com/spreadsheets/d/1Z4YWDKWnrSJPcyFEyHawRck0SrXg6R0hBriH7gBZuqA/pub%3Fgid%3D975313202%26single%3Dtrue%26output%3Dcsv&format=html';

    var activityCall = $.ajax({
            type: 'GET',
            url: activityurl,
            dataType: 'json',
            error:function(e,exception){
                console.log(exception);
            }
        });

        //load geometry

        var damageCall = $.ajax({
            type: 'GET',
            url: damageurl,
            dataType: 'json',
        });

    $.when(damageCall, activityCall).then(function(damageArgs, activityArgs){
        var damage = hxlProxyToJSON(damageArgs[0]);
        var activitycf = crossfilter(hxlProxyToJSON(activityArgs[0]));
        var activityDimension = activitycf.dimension(function(d){return d['#activity+description'];});
        var geoDimension = activitycf.dimension(function(d){ return d['#adm3+code']});
        var activityGroup = activityDimension.group().reduceSum(function(d){return d['#meta+sum'];});
        var table = '

	Damage	';
        var activitylist = [];
        activityGroup.top(5).forEach(function(d){
            if(d.value>0){
                activitylist.push(d.key)
                table+=''+d.key+'	';
            }
        });
        table +='
';

        geom.features.forEach(function(f){
            table+='
'+f.properties.DISTRICT+'	';
            var damagevalue = 0;
            damage.forEach(function(d){
                if(d['#adm3+code']==f.properties['HLCIT_CODE']){
                    damagevalue = Math.round(d['#affected+households']);
                }
            })
            table+=''+damagevalue+'	';

            geoDimension.filter(f.properties['HLCIT_CODE']);
            activitylist.forEach(function(k){
                var value = 0;
                activityGroup.top(Infinity).forEach(function(d){
                    if(d.key==k){
                        value =Math.round(d.value);
                    }
                });
                table +=''+value+'	';
            });
            table+='
';
        });
        table +='
';
        $('#overviewtable').html(table);
    });
}
//load 3W data
var map;
var lookUpVDCCodeToName;
var data;
var overlay2 = '';
var geom = topojson.feature(nepal_adm3,nepal_adm3.objects.nepal_adm3);
var overlay;
var att = 'recovery';
var atttName = '';
var attCode = '';
var colors = ['#FFFFFF','#DFC4C4','#BF898A','#9F4E50','#7F1416'];
var legendon = false;
geom.features.forEach(function(e){
    e.properties[config.joinAttribute] = String(e.properties[config.joinAttribute]);
});
$('#info_row').hide();
initDash(config,geom);
<|endoftext|>


<commit_before>'use strict';

var gi;
try {
    gi = require('../build/Release/node-gtk');
} catch(e) {
    gi = require('../build/Debug/node-gtk');
}

const _ = require('lodash');
// The bootstrap from C here contains functions and methods for each object,
// namespaced with underscores. See gi.cc for more information.
var GIRepository = gi.Bootstrap();

// The GIRepository API is fairly poor, and contains methods on classes,
// methods on objects, and what should be methods interpreted as functions,
// because the scanner does not interpret methods on typedefs correctly.

// We extend this bootstrap'd repo to define all flags / enums, which
// are all we need to start declaring objects.
(function() {
    var repo = GIRepository.Repository_get_default();
    var ns = "GIRepository";

    // First, grab InfoType so we can find enums / flags.
    var InfoType = makeEnum(GIRepository.Repository_find_by_name.call(repo, ns, "InfoType"));

    // Now, define all enums / flags.
    var nInfos = GIRepository.Repository_get_n_infos.call(repo, ns);
    for (var i = 0; i < nInfos; i++) {
        var info = GIRepository.Repository_get_info.call(repo, ns, i);
        var name = GIRepository.BaseInfo_get_name.call(info);
        var type = GIRepository.BaseInfo_get_type.call(info);
        if (type === InfoType.ENUM || type === InfoType.FLAGS)
            GIRepository[name] = makeEnum(info);
    }
})();

function declareFunction(obj, info) {
    var func = gi.MakeFunction(info);
    var name = GIRepository.BaseInfo_get_name.call(info);
    var flags = GIRepository.function_info_get_flags(info);
    var target = (flags & GIRepository.FunctionInfoFlags.IS_METHOD)
        ? obj.prototype
        : obj;
    var jsName = _.camelCase(name);
    Object.defineProperty(target, jsName, {
        configurable: true,
        writable: true,
        value: func
    });
}

function propertyGetter(propertyName) {
    return function() {
        return gi.ObjectPropertyGetter(this, propertyName);
    };
}

function propertySetter(propertyName) {
    return function(value) {
        return gi.ObjectPropertySetter(this, propertyName, value);
    };
}

/**
 * Defines a GObject property on obj.
 * @param {Object} obj
 * @param {GIPropertyInfo} property
 */
function addProperty(obj, property) {
    var propertyName = getName(property);
    var name = _.camelCase(propertyName);
    Object.defineProperty(obj, name, {
        get: propertyGetter(propertyName),
        set: propertySetter(propertyName),
    });
}

function getName(info) {
    return GIRepository.BaseInfo_get_name.call(info);
}

function getType (info) {
    return GIRepository.BaseInfo_get_type.call(info);
}

function Value(info) {
    Object.defineProperty(this, '_name', {value: getName(info)});
    Object.defineProperty(this, '_NAME', {value: this._name.toUpperCase()});
    Object.defineProperty(this, '_value',{value: GIRepository.value_info_get_value(info)});
}
Value.prototype.valueOf = function () {
    return this._value;
};
Value.prototype.toString = function () {
    return this._NAME;
};

function makeEnum(info) {
    var obj = {};
    var props = {};

    var n_values = GIRepository.enum_info_get_n_values(info);
    for (var i = 0; i < n_values; i++) {
        var valueInfo  = GIRepository.enum_info_get_value(info, i);
        var v = new Value(valueInfo);
        var name = getName(valueInfo);
        var NAME = name.toUpperCase();
        var val = GIRepository.value_info_get_value(valueInfo);
        props[NAME] = {enumerable: true, value: val};
        props[name] = {value: v};
        props[val]  = {value: NAME};
    }
    Object.defineProperties(obj, props);

    var n_methods = GIRepository.enum_info_get_n_methods(info);
    for (var i = 0; i < n_methods; i++) {
        var m_info  = GIRepository.enum_info_get_method(info, i);
        var m_func = gi.MakeFunction(m_info);
        var m_name = _.camelCase(getName(m_info));
        Object.defineProperty(obj, m_name, {
            configurable: true, writable: true, value: m_func
        });
    }

    return obj;
}

function makeConstant(info) {
    return gi.GetConstantValue(info);
}

function makeFunction(info) {
    return gi.MakeFunction(info);
}

function makeObject(info) {
    var constructor = gi.MakeClass(info);

    var n_properties = GIRepository.object_info_get_n_properties(info);
    for (var i = 0; i < n_properties; i++) {
        var propertyInfo = GIRepository.object_info_get_property(info, i);
        addProperty(constructor.prototype, propertyInfo);
    }

    constructor.implements = [];

    var n_interfaces = GIRepository.object_info_get_n_interfaces(info);
    for (var i = 0; i < n_interfaces; i++) {
        var i_info = GIRepository.object_info_get_interface(info, i);
        i_info.name = getName(i_info);
        constructor.implements.push(i_info);
        /*var i_properties = GIRepository.interface_info_get_n_properties(i_info);
        for (var i = 0; i < i_properties; i++) {
            var propertyInfo = GIRepository.interface_info_get_property(i_info, i);
            addProperty(constructor.prototype, propertyInfo);
        }
        */
    }

    var n_constants = GIRepository.object_info_get_n_constants(info);
    for (var i = 0; i < n_constants; i++) {
        var constantInfo = GIRepository.object_info_get_constant(info, i);
        var constantName = getName(constantInfo);
        var jsName = _.toUpper(constantName);
        Object.defineProperty(constructor, jsName, {
            writable: false,
            enumerable: true,
            configurable: false,
            value: makeConstant(constantInfo)
        });
    }

    return constructor;
}

function makeBoxed (info) {
    var constructor = gi.MakeBoxedClass(info);
    //info.methods = {};
    //info.fields  = {};
    //var n_methods = GIRepository.struct_info_get_n_methods(info);
    //for (var i = 0; i < n_methods; i++) {
        //var methodInfo = GIRepository.struct_info_get_method(info, i);
        //var methodName = getName(methodInfo);
        //info.methods[methodName] = methodInfo;
    //}
    //var n_fields = GIRepository.union_info_get_n_fields(info);
    //for (var i = 0; i < n_fields; i++) {
        //var fieldInfo = GIRepository.union_info_get_field(info, i);
        //var fieldName = getName(fieldInfo);
        //info.fields[fieldName] = fieldInfo;
    //}
    //var n_fields = GIRepository.struct_info_get_n_fields(info);
    //for (var i = 0; i < n_fields; i++) {
        //var fieldInfo = GIRepository.struct_info_get_field(info, i);
        //var fieldName = GIRepository.BaseInfo_get_name.call(fieldInfo);
        //info.fields[fieldName] = fieldInfo;
    //}

    return constructor;
}

function makeInfo(info) {
    var type = info.getType();
    switch (type) {
        // INVALID
        // CALLBACK
        case GIRepository.InfoType.FUNCTION:
            return makeFunction(info);

        case GIRepository.InfoType.STRUCT:
            if (GIRepository.struct_info_is_gtype_struct(info))
                return null; // Not needed
            // else fallthrough
        case GIRepository.InfoType.BOXED:
        case GIRepository.InfoType.UNION:
            return makeBoxed(info);

        case GIRepository.InfoType.ENUM:
        case GIRepository.InfoType.FLAGS:
            return makeEnum(info);

        case GIRepository.InfoType.OBJECT:
            return makeObject(info);

        case GIRepository.InfoType.INTERFACE: // FIXME
            return;

        case GIRepository.InfoType.CONSTANT:
            return makeConstant(info);

        // INVALID_0

        // case GIRepository.InfoType.VALUE:
        // SIGNAL
        // VFUNC
        // PROPERTY
        // FIELD
        // ARG
        // TYPE
        // UNRESOLVED
    }

}

function importNS(ns, version) {
    var module = {};

    var repo = GIRepository.Repository_get_default();
    GIRepository.Repository_require.call(repo, ns, version || null, 0);

    var nInfos = GIRepository.Repository_get_n_infos.call(repo, ns);
    for (var i = 0; i < nInfos; i++) {
        var info = GIRepository.Repository_get_info.call(repo, ns, i);
        var name = getName(info);
        var info_res = makeInfo(info);
        if (info_res !== null && info_res !== undefined)
            module[name] = info_res;
    }

    var override;
    try {
        override = require('./overrides/' + ns);
    } catch (e) {
        // No override
    }

    if (override)
        override.apply(module);

    return module;
}

exports.c = gi;
exports.GIRepository = GIRepository;
exports.InfoType = GIRepository.InfoType;

// Used to avoid exporting same module every time it's required
var cache = Object.create(null);
exports.importNS = function(ns, version) {
    var module = cache[ns] || (cache[ns] = {});
    var ver    = version   || '*';
    return module[ver] || (module[ver] = importNS(ns, version));
};

exports.startLoop = function() {
    gi.StartLoop();
};
<commit_msg>add helpers, layout BaseInfo object<commit_after>'use strict';

var gi;
try {
    gi = require('../build/Release/node-gtk');
} catch(e) {
    gi = require('../build/Debug/node-gtk');
}

const _ = require('lodash');
// The bootstrap from C here contains functions and methods for each object,
// namespaced with underscores. See gi.cc for more information.
var GIRepository = gi.Bootstrap();

// The GIRepository API is fairly poor, and contains methods on classes,
// methods on objects, and what should be methods interpreted as functions,
// because the scanner does not interpret methods on typedefs correctly.

// We extend this bootstrap'd repo to define all flags / enums, which
// are all we need to start declaring objects.
(function() {
    var repo = GIRepository.Repository_get_default();
    var ns = "GIRepository";

    // First, grab InfoType so we can find enums / flags.
    var InfoType = makeEnum(GIRepository.Repository_find_by_name.call(repo, ns, "InfoType"));

    // Now, define all enums / flags.
    var nInfos = GIRepository.Repository_get_n_infos.call(repo, ns);
    for (var i = 0; i < nInfos; i++) {
        var info = GIRepository.Repository_get_info.call(repo, ns, i);
        var name = GIRepository.BaseInfo_get_name.call(info);
        var type = GIRepository.BaseInfo_get_type.call(info);
        if (type === InfoType.ENUM || type === InfoType.FLAGS)
            GIRepository[name] = makeEnum(info);
    }
})();

function declareFunction(obj, info) {
    var func = gi.MakeFunction(info);
    var name = getName(info);
    var jsName = _.camelCase(name);
    var flags = GIRepository.function_info_get_flags(info);
    var is_method = ((flags & GIRepository.FunctionInfoFlags.IS_METHOD) != 0 &&
                     (flags & GIRepository.FunctionInfoFlags.IS_CONSTRUCTOR) == 0);
    var target = (is_method) ? obj.prototype : obj;
    Object.defineProperty(target, jsName, {
        configurable: true,
        writable: true,
        value: func
    });
}

function fieldGetter(fieldInfo) {
    return function() {
        return gi.StructFieldGetter(this, fieldInfo);
    };
}

function fieldSetter(fieldInfo) {
    return function(value) {
        return gi.StructFieldSetter(this, fieldInfo, value);
    };
}

function addField(obj, fieldInfo) {
    var fieldName = getName(fieldInfo);
    var name = _.camelCase(fieldName);
    Object.defineProperty(obj, name, {
        configurable: true,
        get: fieldGetter(fieldInfo),
        set: fieldSetter(fieldInfo)
    });
}

function propertyGetter(propertyName) {
    return function() {
        return gi.ObjectPropertyGetter(this, propertyName);
    };
}

function propertySetter(propertyName) {
    return function(value) {
        return gi.ObjectPropertySetter(this, propertyName, value);
    };
}

/**
 * Defines a GObject property on obj.
 * @param {Object} obj
 * @param {GIPropertyInfo} property
 */
function addProperty(obj, property) {
    var propertyName = getName(property);
    var name = _.camelCase(propertyName);
    Object.defineProperty(obj, name, {
        get: propertyGetter(propertyName),
        set: propertySetter(propertyName),
    });
}

function getName(info) {
    return GIRepository.BaseInfo_get_name.call(info);
}

function getType (info) {
    return GIRepository.BaseInfo_get_type.call(info);
}

function Value(info) {
    Object.defineProperty(this, '_name', {value: getName(info)});
    Object.defineProperty(this, '_NAME', {value: this._name.toUpperCase()});
    Object.defineProperty(this, '_value',{value: GIRepository.value_info_get_value(info)});
}
Value.prototype.valueOf = function () {
    return this._value;
};
Value.prototype.toString = function () {
    return this._NAME;
};

function makeConstant(info) {
    return gi.GetConstantValue(info);
}

function makeFunction(info) {
    return gi.MakeFunction(info);
}

function makeEnum(info) {
    var obj = {};
    var props = {};

    var n_values = GIRepository.enum_info_get_n_values(info);
    for (var i = 0; i < n_values; i++) {
        var valueInfo  = GIRepository.enum_info_get_value(info, i);
        var v = new Value(valueInfo);
        var name = getName(valueInfo);
        var NAME = name.toUpperCase();
        var val = GIRepository.value_info_get_value(valueInfo);
        props[NAME] = {enumerable: true, value: val};
        props[name] = {value: v};
        props[val]  = {value: NAME};
    }
    Object.defineProperties(obj, props);

    var n_methods = GIRepository.enum_info_get_n_methods(info);
    for (var i = 0; i < n_methods; i++) {
        var m_info  = GIRepository.enum_info_get_method(info, i);
        var m_func = gi.MakeFunction(m_info);
        var m_name = _.camelCase(getName(m_info));
        Object.defineProperty(obj, m_name, {
            configurable: true, writable: true, value: m_func
        });
    }

    return obj;
}

function makeObject(info) {
    var constructor = gi.MakeObjectClass(info);

    var n_methods = GIRepository.object_info_get_n_methods(info);
    for (var i = 0; i < n_methods; i++) {
        var methodInfo = GIRepository.object_info_get_method(info, i);
        declareFunction(constructor, methodInfo);
    }

    var n_properties = GIRepository.object_info_get_n_properties(info);
    for (var i = 0; i < n_properties; i++) {
        var propertyInfo = GIRepository.object_info_get_property(info, i);
        addProperty(constructor.prototype, propertyInfo);
    }

    constructor.implements = [];

    var n_interfaces = GIRepository.object_info_get_n_interfaces(info);
    for (var i = 0; i < n_interfaces; i++) {
        var i_info = GIRepository.object_info_get_interface(info, i);
        i_info.name = getName(i_info);
        constructor.implements.push(i_info);

        var i_methods = GIRepository.interface_info_get_n_methods(i_info);
        for (var j = 0; j < i_methods; j++) {
            var methodInfo = GIRepository.interface_info_get_method(i_info, j);
            declareFunction(constructor, methodInfo);
        }
    }

    var n_constants = GIRepository.object_info_get_n_constants(info);
    for (var i = 0; i < n_constants; i++) {
        var constantInfo = GIRepository.object_info_get_constant(info, i);
        var constantName = getName(constantInfo);
        var jsName = _.toUpper(constantName);
        Object.defineProperty(constructor, jsName, {
            writable: false,
            enumerable: true,
            configurable: false,
            value: makeConstant(constantInfo)
        });
    }

    return constructor;
}

function makeBoxed (info) {
    var constructor = gi.MakeBoxedClass(info);

    if (getType(info) == GIRepository.InfoType.UNION) {
        if (!global.unions)
            global.unions = [];
        global.unions.push(info);

        var n_methods = GIRepository.union_info_get_n_methods(info);
        for (var i = 0; i < n_methods; i++) {
            var methodInfo = GIRepository.union_info_get_method(info, i);
            declareFunction(constructor, methodInfo);
        }

        var n_fields = GIRepository.union_info_get_n_fields(info);
        for (var i = 0; i < n_fields; i++) {
            var fieldInfo = GIRepository.union_info_get_field(info, i);
            addField(constructor.prototype, fieldInfo);
        }

    } else {
        var n_methods = GIRepository.struct_info_get_n_methods(info);
        for (var i = 0; i < n_methods; i++) {
            var methodInfo = GIRepository.struct_info_get_method(info, i);
            declareFunction(constructor, methodInfo);
        }
        var n_fields = GIRepository.struct_info_get_n_fields(info);
        for (var i = 0; i < n_fields; i++) {
            var fieldInfo = GIRepository.struct_info_get_field(info, i);
            addField(constructor.prototype, fieldInfo);
        }
    }

    return constructor;
}

function makeInterface(info) {
    var constructor = function () {};
    constructor.info = info;
    constructor.gtype = GIRepository.registered_type_info_get_g_type(info);
    constructor.properties = Object.create(null);

    var n_properties = GIRepository.interface_info_get_n_properties(info);
    for (var i = 0; i < n_properties; i++) {
        var propertyInfo = GIRepository.interface_info_get_property(info, i);
        var p_name = getName(propertyInfo);
        constructor.properties[p_name] = propertyInfo;
    }

    if (!global.interfaces)
        global.interfaces = [];
    global.interfaces.push(constructor);

    return constructor;
}

function makeInfo(info) {
    var type = getType(info);
    switch (type) {
        // INVALID
        // CALLBACK
        case GIRepository.InfoType.FUNCTION:
            return makeFunction(info);

        case GIRepository.InfoType.STRUCT:
            if (GIRepository.struct_info_is_gtype_struct(info))
                return null; // Not needed
            // else fallthrough
        case GIRepository.InfoType.BOXED:
        case GIRepository.InfoType.UNION:
            return makeBoxed(info);

        case GIRepository.InfoType.ENUM:
        case GIRepository.InfoType.FLAGS:
            return makeEnum(info);

        case GIRepository.InfoType.OBJECT:
            return makeObject(info);

        case GIRepository.InfoType.INTERFACE: // FIXME
            return makeInterface(info);

        case GIRepository.InfoType.CONSTANT:
            return makeConstant(info);

        // INVALID_0
        // case GIRepository.InfoType.VALUE:
        // SIGNAL
        // VFUNC
        // PROPERTY
        // FIELD
        // ARG
        // TYPE
        // UNRESOLVED
    }
}

function importNS(ns, version) {
    var module = {};

    var repo = GIRepository.Repository_get_default();
    GIRepository.Repository_require.call(repo, ns, version || null, 0);

    var nInfos = GIRepository.Repository_get_n_infos.call(repo, ns);
    for (var i = 0; i < nInfos; i++) {
        var info = GIRepository.Repository_get_info.call(repo, ns, i);
        var name = getName(info);
        var info_res = makeInfo(info);

        if (info_res !== null && info_res !== undefined)
            module[name] = info_res;
    }

    var override;
    try {
        override = require('./overrides/' + ns);
    } catch (e) {
        // No override
    }

    if (override)
        override.apply(module);

    return module;
}

exports.c = gi;
exports.GIRepository = GIRepository;
exports.InfoType = GIRepository.InfoType;

// Used to avoid exporting same module every time it's required
var cache = Object.create(null);
exports.importNS = function(ns, version) {
    var module = cache[ns] || (cache[ns] = {});
    var ver    = version   || '*';
    return module[ver] || (module[ver] = importNS(ns, version));
};

exports.startLoop = function() {
    gi.StartLoop();
};
<|endoftext|>