<commit_before>"use strict";

var CityTour = CityTour || {};

// Adapted from http://ranmantaru.com/blog/2011/10/08/water-erosion-on-heightmap-terrain/
CityTour.HydraulicErosionGenerator = (function() {
  var lowestAdjacentTerrain = function(terrainCoordinates, x, z) {
    var candidateLandHeight;
    var minTargetLandHeight = Number.POSITIVE_INFINITY;
    var minTargetX, minTargetZ;

    // North
    if (z > 0) {
      candidateLandHeight = terrainCoordinates[x][z - 1].landHeight;
      if (candidateLandHeight < minTargetLandHeight) {
        minTargetLandHeight = candidateLandHeight;
        minTargetX = x;
        minTargetZ = z - 1;
      }
    }

    // South
    if (z < terrainCoordinates[0].length - 1) {
      candidateLandHeight = terrainCoordinates[x][z + 1].landHeight;
      if (candidateLandHeight < minTargetLandHeight) {
        minTargetLandHeight = candidateLandHeight;
        minTargetX = x;
        minTargetZ = z + 1;
      }
    }

    // West
    if (x > 0) {
      candidateLandHeight = terrainCoordinates[x - 1][z].landHeight;
      if (candidateLandHeight < minTargetLandHeight) {
        minTargetLandHeight = candidateLandHeight;
        minTargetX = x - 1;
        minTargetZ = z;
      }
    }

    // East
    if (x < terrainCoordinates.length - 1) {
      candidateLandHeight = terrainCoordinates[x + 1][z].landHeight;
      if (candidateLandHeight < minTargetLandHeight) {
        minTargetLandHeight = candidateLandHeight;
        minTargetX = x + 1;
        minTargetZ = z;
      }
    }

    // Southwest
    if (x > 0 && z < (terrainCoordinates[0].length - 1)) {
      candidateLandHeight = terrainCoordinates[x - 1][z + 1].landHeight;
      if (candidateLandHeight < minTargetLandHeight) {
        minTargetLandHeight = candidateLandHeight;
        minTargetX = x - 1;
        minTargetZ = z + 1;
      }
    }

    // Northeast
    if (x < (terrainCoordinates.length - 1) && z > 0) {
      candidateLandHeight = terrainCoordinates[x + 1][z - 1].landHeight;
      if (candidateLandHeight < minTargetLandHeight) {
        minTargetLandHeight = candidateLandHeight;
        minTargetX = x + 1;
        minTargetZ = z - 1;
      }
    }

    return {
      minTargetLandHeight: minTargetLandHeight,
      minTargetX: minTargetX,
      minTargetZ: minTargetZ,
    };
  };

  var erode = function(terrainCoordinates, iterationCount) {
    var STARTING_WATER_HEIGHT = 5.0;
    var WATER_CARRYING_CAPACITY = 2.5;
    var WATER_EVAPORATION_RATE = 1.0;
    var MAX_EROSION_HEIGHT = 2.5;
    var MAX_SOIL_DEPOSIT_HEIGHT = 2.5;

    var minTargetLandHeight, minTargetX, minTargetZ;
    var i, x, z;
    var lowestAdjacentTerrainAttributes;

    var maxColumnIndex = terrainCoordinates.length - 1;
    var maxRowIndex = terrainCoordinates[0].length - 1;
    var waterAmount;
    var soilAmount, soilDepositHeight;
    var erosionHeight;

    for (i = 0; i < iterationCount; i++) {
      x = CityTour.Math.randomInteger(0, maxColumnIndex);
      z = CityTour.Math.randomInteger(0, maxRowIndex);
      waterAmount = STARTING_WATER_HEIGHT;
      soilAmount = 0.0;

      do {
        lowestAdjacentTerrainAttributes = lowestAdjacentTerrain(terrainCoordinates, x, z);
        minTargetLandHeight = lowestAdjacentTerrainAttributes.minTargetLandHeight;
        minTargetX = lowestAdjacentTerrainAttributes.minTargetX;
        minTargetZ = lowestAdjacentTerrainAttributes.minTargetZ;

        if (soilAmount > WATER_CARRYING_CAPACITY) {
          soilDepositHeight = Math.min(MAX_SOIL_DEPOSIT_HEIGHT, soilAmount);
          terrainCoordinates[x][z].landHeight += soilDepositHeight;
          soilAmount -= soilDepositHeight;
          waterAmount -= WATER_EVAPORATION_RATE;
        }
        else if (terrainCoordinates[x][z].landHeight >= minTargetLandHeight) {
          erosionHeight = Math.min(MAX_EROSION_HEIGHT, (terrainCoordinates[x][z].landHeight - minTargetLandHeight));
          terrainCoordinates[x][z].landHeight -= erosionHeight;
          soilAmount += erosionHeight;
          waterAmount -= WATER_EVAPORATION_RATE;
        }

        x = minTargetX;
        z = minTargetZ;
      } while (waterAmount > 0.0 && minTargetLandHeight <= terrainCoordinates[x][z].landHeight);
    }
  };

  return {
    erode: erode,
  };
})();
<commit_msg>Better variable names<commit_after>"use strict";

var CityTour = CityTour || {};

// Adapted from http://ranmantaru.com/blog/2011/10/08/water-erosion-on-heightmap-terrain/
CityTour.HydraulicErosionGenerator = (function() {
  var lowestAdjacentTerrain = function(terrainCoordinates, x, z) {
    var candidateLandHeight;
    var minAdjacentLandHeight = Number.POSITIVE_INFINITY;
    var minAdjacentX, minAdjacentZ;

    // North
    if (z > 0) {
      candidateLandHeight = terrainCoordinates[x][z - 1].landHeight;
      if (candidateLandHeight < minAdjacentLandHeight) {
        minAdjacentLandHeight = candidateLandHeight;
        minAdjacentX = x;
        minAdjacentZ = z - 1;
      }
    }

    // South
    if (z < terrainCoordinates[0].length - 1) {
      candidateLandHeight = terrainCoordinates[x][z + 1].landHeight;
      if (candidateLandHeight < minAdjacentLandHeight) {
        minAdjacentLandHeight = candidateLandHeight;
        minAdjacentX = x;
        minAdjacentZ = z + 1;
      }
    }

    // West
    if (x > 0) {
      candidateLandHeight = terrainCoordinates[x - 1][z].landHeight;
      if (candidateLandHeight < minAdjacentLandHeight) {
        minAdjacentLandHeight = candidateLandHeight;
        minAdjacentX = x - 1;
        minAdjacentZ = z;
      }
    }

    // East
    if (x < terrainCoordinates.length - 1) {
      candidateLandHeight = terrainCoordinates[x + 1][z].landHeight;
      if (candidateLandHeight < minAdjacentLandHeight) {
        minAdjacentLandHeight = candidateLandHeight;
        minAdjacentX = x + 1;
        minAdjacentZ = z;
      }
    }

    // Southwest
    if (x > 0 && z < (terrainCoordinates[0].length - 1)) {
      candidateLandHeight = terrainCoordinates[x - 1][z + 1].landHeight;
      if (candidateLandHeight < minAdjacentLandHeight) {
        minAdjacentLandHeight = candidateLandHeight;
        minAdjacentX = x - 1;
        minAdjacentZ = z + 1;
      }
    }

    // Northeast
    if (x < (terrainCoordinates.length - 1) && z > 0) {
      candidateLandHeight = terrainCoordinates[x + 1][z - 1].landHeight;
      if (candidateLandHeight < minAdjacentLandHeight) {
        minAdjacentLandHeight = candidateLandHeight;
        minAdjacentX = x + 1;
        minAdjacentZ = z - 1;
      }
    }

    return {
      minAdjacentLandHeight: minAdjacentLandHeight,
      minAdjacentX: minAdjacentX,
      minAdjacentZ: minAdjacentZ,
    };
  };

  var erode = function(terrainCoordinates, iterationCount) {
    var STARTING_WATER_HEIGHT = 5.0;
    var WATER_CARRYING_CAPACITY = 2.5;
    var WATER_EVAPORATION_RATE = 1.0;
    var MAX_EROSION_HEIGHT = 2.5;
    var MAX_SOIL_DEPOSIT_HEIGHT = 2.5;

    var lowestAdjacentLandHeight, lowestAdjacentX, lowestAdjacentZ;
    var lowestAdjacentTerrainAttributes;

    var maxColumnIndex = terrainCoordinates.length - 1;
    var maxRowIndex = terrainCoordinates[0].length - 1;
    var waterAmount;
    var soilAmount, soilDepositHeight;
    var erosionHeight;

    var i, x, z;

    for (i = 0; i < iterationCount; i++) {
      x = CityTour.Math.randomInteger(0, maxColumnIndex);
      z = CityTour.Math.randomInteger(0, maxRowIndex);
      waterAmount = STARTING_WATER_HEIGHT;
      soilAmount = 0.0;

      do {
        lowestAdjacentTerrainAttributes = lowestAdjacentTerrain(terrainCoordinates, x, z);
        lowestAdjacentLandHeight = lowestAdjacentTerrainAttributes.minAdjacentLandHeight;
        lowestAdjacentX = lowestAdjacentTerrainAttributes.minAdjacentX;
        lowestAdjacentZ = lowestAdjacentTerrainAttributes.minAdjacentZ;

        if (soilAmount > WATER_CARRYING_CAPACITY) {
          soilDepositHeight = Math.min(MAX_SOIL_DEPOSIT_HEIGHT, soilAmount);
          terrainCoordinates[x][z].landHeight += soilDepositHeight;
          soilAmount -= soilDepositHeight;
          waterAmount -= WATER_EVAPORATION_RATE;
        }
        else if (terrainCoordinates[x][z].landHeight >= lowestAdjacentLandHeight) {
          erosionHeight = Math.min(MAX_EROSION_HEIGHT, (terrainCoordinates[x][z].landHeight - lowestAdjacentLandHeight));
          terrainCoordinates[x][z].landHeight -= erosionHeight;
          soilAmount += erosionHeight;
          waterAmount -= WATER_EVAPORATION_RATE;
        }

        x = lowestAdjacentX;
        z = lowestAdjacentZ;
      } while (waterAmount > 0.0 && lowestAdjacentLandHeight <= terrainCoordinates[x][z].landHeight);
    }
  };

  return {
    erode: erode,
  };
})();
<|endoftext|>


<commit_before>var execSync = require('child_process').execSync
var stat = require('fs').stat

function exec(command) {
  execSync(command, { stdio: [0, 1, 2] })
}

stat('lib', function (error, stat) {
  if (error || !stat.isDirectory())
    exec('npm run build')
})
<commit_msg>remove post install<commit_after><|endoftext|>


<commit_before>import {BoundingAABB} from "../scene/BoundingAABB";
import {ObjectPool} from "../core/ObjectPool";
import {SceneVisitor} from "../scene/SceneVisitor";
import {MaterialPass} from "../material/MaterialPass";
import {META} from "../Helix";

/**
 * @ignore
 * @constructor
 *
 * @author derschmale <http://www.derschmale.com>
 */
function CascadeShadowCasterCollector()
{
    SceneVisitor.call(this);
    this._renderCameras = null;
    this._bounds = new BoundingAABB();
    this._cullPlanes = null;
    // this._splitPlanes = null;
    this._numCullPlanes = 0;
    this._renderLists = [];
    this._renderItemPool = new ObjectPool(RenderItem);
};

CascadeShadowCasterCollector.prototype = Object.create(SceneVisitor.prototype);

CascadeShadowCasterCollector.prototype.getRenderList = function(index) { return this._renderLists[index]; };

CascadeShadowCasterCollector.prototype.collect = function(camera, scene)
{
    this._collectorCamera = camera;
    this._bounds.clear();
    this._renderItemPool.reset();

    var numCascades = META.OPTIONS.numShadowCascades;
    for (var i = 0; i < numCascades; ++i) {
        this._renderLists[i] = [];
    }

    scene.acceptVisitor(this);
};

CascadeShadowCasterCollector.prototype.getBounds = function()
{
    return this._bounds;
};

CascadeShadowCasterCollector.prototype.setRenderCameras = function(cameras)
{
    this._renderCameras = cameras;
};

CascadeShadowCasterCollector.prototype.setCullPlanes = function(cullPlanes, numPlanes)
{
    this._cullPlanes = cullPlanes;
    this._numCullPlanes = numPlanes;
};

// CascadeShadowCasterCollector.prototype.setSplitPlanes = function(splitPlanes)
// {
//     this._splitPlanes = splitPlanes;
// };

CascadeShadowCasterCollector.prototype.visitModelInstance = function (modelInstance, worldMatrix, worldBounds)
{
    if (modelInstance._castShadows === false) return;

    this._bounds.growToIncludeBound(worldBounds);

    var passIndex = MaterialPass.DIR_LIGHT_SHADOW_MAP_PASS;

    var numCascades = META.OPTIONS.numShadowCascades;
    var numMeshes = modelInstance.numMeshInstances;
    var skeleton = modelInstance.skeleton;
    var skeletonMatrices = modelInstance.skeletonMatrices;

    for (var cascade = 0; cascade < numCascades; ++cascade) {
        var renderList = this._renderLists[cascade];
        var renderCamera = this._renderCameras[cascade];

        var contained = worldBounds.intersectsConvexSolid(renderCamera.frustum.planes, 4);

        if (contained) {
            for (var meshIndex = 0; meshIndex < numMeshes; ++meshIndex) {
                var meshInstance = modelInstance.getMeshInstance(meshIndex);
                var material = meshInstance.material;

                if (material.hasPass(passIndex)) {
                    var renderItem = this._renderItemPool.getItem();
                    renderItem.pass = material.getPass(passIndex);
                    renderItem.meshInstance = meshInstance;
                    renderItem.worldMatrix = worldMatrix;
                    renderItem.camera = renderCamera;
                    renderItem.material = material;
                    renderItem.skeleton = skeleton;
                    renderItem.skeletonMatrices = skeletonMatrices;

                    renderList.push(renderItem);
                }
            }
        }
    }
};

CascadeShadowCasterCollector.prototype.qualifies = function(object)
{
    return object.visible && object.worldBounds.intersectsConvexSolid(this._cullPlanes, this._numCullPlanes);
};

export { CascadeShadowCasterCollector };<commit_msg>Fix import<commit_after>import {BoundingAABB} from "../scene/BoundingAABB";
import {ObjectPool} from "../core/ObjectPool";
import {SceneVisitor} from "../scene/SceneVisitor";
import {MaterialPass} from "../material/MaterialPass";
import {META} from "../Helix";
import {RenderItem} from "./RenderItem";

/**
 * @ignore
 * @constructor
 *
 * @author derschmale <http://www.derschmale.com>
 */
function CascadeShadowCasterCollector()
{
    SceneVisitor.call(this);
    this._renderCameras = null;
    this._bounds = new BoundingAABB();
    this._cullPlanes = null;
    // this._splitPlanes = null;
    this._numCullPlanes = 0;
    this._renderLists = [];
    this._renderItemPool = new ObjectPool(RenderItem);
};

CascadeShadowCasterCollector.prototype = Object.create(SceneVisitor.prototype);

CascadeShadowCasterCollector.prototype.getRenderList = function(index) { return this._renderLists[index]; };

CascadeShadowCasterCollector.prototype.collect = function(camera, scene)
{
    this._collectorCamera = camera;
    this._bounds.clear();
    this._renderItemPool.reset();

    var numCascades = META.OPTIONS.numShadowCascades;
    for (var i = 0; i < numCascades; ++i) {
        this._renderLists[i] = [];
    }

    scene.acceptVisitor(this);
};

CascadeShadowCasterCollector.prototype.getBounds = function()
{
    return this._bounds;
};

CascadeShadowCasterCollector.prototype.setRenderCameras = function(cameras)
{
    this._renderCameras = cameras;
};

CascadeShadowCasterCollector.prototype.setCullPlanes = function(cullPlanes, numPlanes)
{
    this._cullPlanes = cullPlanes;
    this._numCullPlanes = numPlanes;
};

// CascadeShadowCasterCollector.prototype.setSplitPlanes = function(splitPlanes)
// {
//     this._splitPlanes = splitPlanes;
// };

CascadeShadowCasterCollector.prototype.visitModelInstance = function (modelInstance, worldMatrix, worldBounds)
{
    if (modelInstance._castShadows === false) return;

    this._bounds.growToIncludeBound(worldBounds);

    var passIndex = MaterialPass.DIR_LIGHT_SHADOW_MAP_PASS;

    var numCascades = META.OPTIONS.numShadowCascades;
    var numMeshes = modelInstance.numMeshInstances;
    var skeleton = modelInstance.skeleton;
    var skeletonMatrices = modelInstance.skeletonMatrices;

    for (var cascade = 0; cascade < numCascades; ++cascade) {
        var renderList = this._renderLists[cascade];
        var renderCamera = this._renderCameras[cascade];

        var contained = worldBounds.intersectsConvexSolid(renderCamera.frustum.planes, 4);

        if (contained) {
            for (var meshIndex = 0; meshIndex < numMeshes; ++meshIndex) {
                var meshInstance = modelInstance.getMeshInstance(meshIndex);
                var material = meshInstance.material;

                if (material.hasPass(passIndex)) {
                    var renderItem = this._renderItemPool.getItem();
                    renderItem.pass = material.getPass(passIndex);
                    renderItem.meshInstance = meshInstance;
                    renderItem.worldMatrix = worldMatrix;
                    renderItem.camera = renderCamera;
                    renderItem.material = material;
                    renderItem.skeleton = skeleton;
                    renderItem.skeletonMatrices = skeletonMatrices;

                    renderList.push(renderItem);
                }
            }
        }
    }
};

CascadeShadowCasterCollector.prototype.qualifies = function(object)
{
    return object.visible && object.worldBounds.intersectsConvexSolid(this._cullPlanes, this._numCullPlanes);
};

export { CascadeShadowCasterCollector };<|endoftext|>


<commit_before>import delegatesPublicFunctions from "./delegates_public_functions.js"

/*
 * Returns a higher order function version of the component.
 *
 * Adds a ComponentClass() function and an opts() function to the component
 * for accessing the child component and the options argument to the higher
 * order function.
 */
module.exports = function() {
  return function(hocClass) {
    return function(opts) {
      return function(ComponentClass) { //eslint-disable-line react/display-name
        /*
         * Creating a subclass of the higher order component with getters for
         * the component class and opts.
         */
        return (
          @delegatesPublicFunctions(opts)
          class extends hocClass {
            static originalClass = (
              ComponentClass.originalClass || ComponentClass
            )

            ComponentClass() {
              return ComponentClass
            }

            opts() {
              return opts
            }
          }
        )
      }
    }
  }
}
<commit_msg>eslint src/higher_order_components/higher_order_component.js<commit_after>import delegatesPublicFunctions from './delegates_public_functions.js'

/*
 * Returns a higher order function version of the component.
 *
 * Adds a ComponentClass() function and an opts() function to the component
 * for accessing the child component and the options argument to the higher
 * order function.
 */
const HigherOrderComponent = hocClass => opts => ComponentClass =>
  @delegatesPublicFunctions(opts)
  class extends hocClass {
    static originalClass = (
      ComponentClass.originalClass || ComponentClass
    )

    ComponentClass() {
      return ComponentClass
    }

    opts() {
      return opts
    }
  }

export default HigherOrderComponent
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var timeutil = (function() {
  'use strict';

  /**
   * Offset needed to convert event times to Date objects.
   * Updated whenever constants are loaded.
   */
  var timeTickOffset = 0;

  /**
   * Sets the offset used to convert tick counts to dates.
   */
  function setTimeTickOffset(offset) {
    // Note that the subtraction by 0 is to cast to a number (probably a float
    // since the numbers are big).
    timeTickOffset = offset - 0;
  }

  /**
   * The browser gives us times in terms of "time ticks" in milliseconds.
   * This function converts the tick count to a Date() object.
   *
   * @param {String} timeTicks.
   * @returns {Date} The time that |timeTicks| represents.
   */
  function convertTimeTicksToDate(timeTicks) {
    var timeStampMs = timeTickOffset + (timeTicks - 0);
    return new Date(timeStampMs);
  }

  /**
   * Returns the current time.
   *
   * @returns {number} Milliseconds since the Unix epoch.
   */
  function getCurrentTime() {
    return (new Date()).getTime();
  }

  /**
   * Adds an HTML representation of |date| to |parentNode|.
   *
   * @param {DomNode} parentNode
   * @param {Date} date
   * @returns {DomNode} The node containing the date/time.
   */
  function addNodeWithDate(parentNode, date) {
    var span = addNodeWithText(parentNode, 'span', dateToString(date));
    span.title = 't=' + date.getTime();
    return span;
  }

  /**
   * Returns a string representation of |date|.
   *
   * @param {Date} date
   * @returns {String}
   */
  function dateToString(date) {
    var dateStr =
        date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate();

    // Prefix the milliseconds with enough zeros to make it three characters
    // long.
    var paddedMilliseconds = '' + date.getMilliseconds();
    while (paddedMilliseconds.length < 3)
      paddedMilliseconds = '0' + paddedMilliseconds;

    var timeStr =
        date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds() +
        '.' + paddedMilliseconds;

    return '[' + dateStr + '] ' + timeStr;
  }

  return {
    setTimeTickOffset: setTimeTickOffset,
    convertTimeTicksToDate: convertTimeTicksToDate,
    getCurrentTime: getCurrentTime,
    addNodeWithDate: addNodeWithDate,
    dateToString: dateToString
  };
})();
<commit_msg>Tweak date format used on net-internals. Adds zero-padding for minutes/hours/days, removes the brackets, and uses '-' rather than '/' as date separator.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var timeutil = (function() {
  'use strict';

  /**
   * Offset needed to convert event times to Date objects.
   * Updated whenever constants are loaded.
   */
  var timeTickOffset = 0;

  /**
   * Sets the offset used to convert tick counts to dates.
   */
  function setTimeTickOffset(offset) {
    // Note that the subtraction by 0 is to cast to a number (probably a float
    // since the numbers are big).
    timeTickOffset = offset - 0;
  }

  /**
   * The browser gives us times in terms of "time ticks" in milliseconds.
   * This function converts the tick count to a Date() object.
   *
   * @param {String} timeTicks.
   * @returns {Date} The time that |timeTicks| represents.
   */
  function convertTimeTicksToDate(timeTicks) {
    var timeStampMs = timeTickOffset + (timeTicks - 0);
    return new Date(timeStampMs);
  }

  /**
   * Returns the current time.
   *
   * @returns {number} Milliseconds since the Unix epoch.
   */
  function getCurrentTime() {
    return (new Date()).getTime();
  }

  /**
   * Adds an HTML representation of |date| to |parentNode|.
   *
   * @param {DomNode} parentNode
   * @param {Date} date
   * @returns {DomNode} The node containing the date/time.
   */
  function addNodeWithDate(parentNode, date) {
    var span = addNodeWithText(parentNode, 'span', dateToString(date));
    span.title = 't=' + date.getTime();
    return span;
  }

  /**
   * Returns a string representation of |date|.
   *
   * @param {Date} date
   * @returns {String}
   */
  function dateToString(date) {
    var dateStr = date.getFullYear() + '-' +
                  zeroPad_(date.getMonth() + 1, 2) + '-' +
                  zeroPad_(date.getDate(), 2);

    var timeStr = zeroPad_(date.getHours(), 2) + ':' +
                  zeroPad_(date.getMinutes(), 2) + ':' +
                  zeroPad_(date.getSeconds(), 2) + '.' +
                  zeroPad_(date.getMilliseconds(), 3);

    return dateStr + ' ' + timeStr;
  }

  /**
   * Prefixes enough zeros to |num| so that it has length |len|.
   */
  function zeroPad_(num, len) {
    var str = num + '';
    while (str.length < len)
      str = '0' + str;
    return str;
  }

  return {
    setTimeTickOffset: setTimeTickOffset,
    convertTimeTicksToDate: convertTimeTicksToDate,
    getCurrentTime: getCurrentTime,
    addNodeWithDate: addNodeWithDate,
    dateToString: dateToString
  };
})();
<|endoftext|>


<commit_before>var ExpressionResolver;

(function () {

	var ReferenceScout, getKeypath;

	ExpressionResolver = function ( mustache ) {

		var expression, i, len, ref, indexRefs, args;

		this.root = mustache.root;
		this.mustache = mustache;
		this.args = [];
		this.scouts = [];

		expression = mustache.descriptor.x;
		indexRefs = mustache.parentFragment.indexRefs;

		this.str = expression.s;

		// send out scouts for each reference
		len = this.unresolved = ( expression.r ? expression.r.length : 0 );

		if ( !len ) {
			this.init(); // some expressions don't have references. edge case, but, yeah.
		}

		for ( i=0; i<len; i+=1 ) {
			ref = expression.r[i];

			// is this an index ref?
			if ( indexRefs && indexRefs[ ref ] !== undefined ) {
				this.resolveRef( i, true, indexRefs[ ref ].index );
			}

			else {
				this.scouts[ this.scouts.length ] = new ReferenceScout( this, ref, mustache.contextStack, i );
			}
		}
	};

	ExpressionResolver.prototype = {
		init: function () {
			this.keypath = getKeypath( this.str, this.args );
			this.createEvaluator();

			this.mustache.resolve( this.keypath );
		},

		teardown: function () {
			while ( this.scouts.length ) {
				this.scouts.pop().teardown();
			}
		},

		resolveRef: function ( argNum, isIndexRef, value ) {
			this.args[ argNum ] = [ isIndexRef, value ];

			// can we initialise yet?
			if ( --this.unresolved ) {
				// no;
				return;
			}

			this.init();
		},

		createEvaluator: function () {
			// only if it doesn't exist yet!
			if ( !this.root._evaluators[ this.keypath ] ) {
				this.root._evaluators[ this.keypath ] = new Evaluator( this.root, this.keypath, this.str, this.args, this.mustache.priority );
			}
		}
	};

	ReferenceScout = function ( resolver, ref, contextStack, argNum ) {
		var keypath, root;

		root = this.root = resolver.root;

		keypath = resolveRef( root, ref, contextStack );
		if ( keypath ) {
			resolver.resolveRef( argNum, false, keypath );
		} else {
			this.ref = ref;
			this.argNum = argNum;
			this.resolver = resolver;
			this.contextStack = contextStack;

			root._pendingResolution[ root._pendingResolution.length ] = this;
		}
	};

	ReferenceScout.prototype = {
		resolve: function ( keypath ) {
			this.keypath = keypath;
			this.resolver.resolveRef( this.argNum, false, keypath );
		},

		teardown: function () {
			// if we haven't found a keypath yet, we can
			// stop the search now
			if ( !this.keypath ) {
				teardown( this );
			}
		}
	};

	getKeypath = function ( str, args ) {
		var unique;

		// get string that is unique to this expression
		unique = str.replace( /❖([0-9]+)/g, function ( match, $1 ) {
			return args[ $1 ][1];
		});

		// then sanitize by removing any periods or square brackets. Otherwise
		// splitKeypath will go mental!
		return '(' + unique.replace( /[\.\[\]]/g, '-' ) + ')';
	};

}());<commit_msg>trigger refreshes of existing evaluators with new dependants<commit_after>var ExpressionResolver;

(function () {

	var ReferenceScout, getKeypath;

	ExpressionResolver = function ( mustache ) {

		var expression, i, len, ref, indexRefs, args;

		this.root = mustache.root;
		this.mustache = mustache;
		this.args = [];
		this.scouts = [];

		expression = mustache.descriptor.x;
		indexRefs = mustache.parentFragment.indexRefs;

		this.str = expression.s;

		// send out scouts for each reference
		len = this.unresolved = ( expression.r ? expression.r.length : 0 );

		if ( !len ) {
			this.init(); // some expressions don't have references. edge case, but, yeah.
		}

		for ( i=0; i<len; i+=1 ) {
			ref = expression.r[i];

			// is this an index ref?
			if ( indexRefs && indexRefs[ ref ] !== undefined ) {
				this.resolveRef( i, true, indexRefs[ ref ].index );
			}

			else {
				this.scouts[ this.scouts.length ] = new ReferenceScout( this, ref, mustache.contextStack, i );
			}
		}
	};

	ExpressionResolver.prototype = {
		init: function () {
			this.keypath = getKeypath( this.str, this.args );
			this.createEvaluator();

			this.mustache.resolve( this.keypath );
		},

		teardown: function () {
			while ( this.scouts.length ) {
				this.scouts.pop().teardown();
			}
		},

		resolveRef: function ( argNum, isIndexRef, value ) {
			this.args[ argNum ] = [ isIndexRef, value ];

			// can we initialise yet?
			if ( --this.unresolved ) {
				// no;
				return;
			}

			this.init();
		},

		createEvaluator: function () {
			// only if it doesn't exist yet!
			if ( !this.root._evaluators[ this.keypath ] ) {
				this.root._evaluators[ this.keypath ] = new Evaluator( this.root, this.keypath, this.str, this.args, this.mustache.priority );
			}

			else {
				// we need to trigger a refresh of the evaluator, since it
				// will have become de-synced from the model if we're in a
				// reassignment cycle
				this.root._evaluators[ this.keypath ].refresh();
			}
		}
	};

	ReferenceScout = function ( resolver, ref, contextStack, argNum ) {
		var keypath, root;

		root = this.root = resolver.root;

		keypath = resolveRef( root, ref, contextStack );
		if ( keypath ) {
			resolver.resolveRef( argNum, false, keypath );
		} else {
			this.ref = ref;
			this.argNum = argNum;
			this.resolver = resolver;
			this.contextStack = contextStack;

			root._pendingResolution[ root._pendingResolution.length ] = this;
		}
	};

	ReferenceScout.prototype = {
		resolve: function ( keypath ) {
			this.keypath = keypath;
			this.resolver.resolveRef( this.argNum, false, keypath );
		},

		teardown: function () {
			// if we haven't found a keypath yet, we can
			// stop the search now
			if ( !this.keypath ) {
				teardown( this );
			}
		}
	};

	getKeypath = function ( str, args ) {
		var unique;

		// get string that is unique to this expression
		unique = str.replace( /❖([0-9]+)/g, function ( match, $1 ) {
			return args[ $1 ][1];
		});

		// then sanitize by removing any periods or square brackets. Otherwise
		// splitKeypath will go mental!
		return '(' + unique.replace( /[\.\[\]]/g, '-' ) + ')';
	};

}());<|endoftext|>


<commit_before>/*
 * Notifications manages various notification messages
 *
 */
const CommonFunctions = require('../../../_common/common_functions');
const Login           = require('../../../_common/base/login');

const MBNotifications = (() => {
    /*
     * options: Object {
     *     localized_text: {string}  message text to display
     *     uid           : {string}  unique id to prevent duplicating the same message and also used to hide the message
     *     dismissible   : {boolean} dismissible messages can be hidden by client
     * }
     */
    const showErrorMessage = (options) => {
        const $note_wrapper = getContainer();
        const $this_uid     = $note_wrapper.find(`#${options.uid}`);
        const $login_error_container = CommonFunctions.getElementById('login_error_container');
        $login_error_container.setVisibility(0);

        if (/LOGIN_ERROR/.test(options.uid)) {
            $login_error_container.setVisibility(1);
            const login_error_btn_login = CommonFunctions.getElementById('login_error_btn_login');
            login_error_btn_login.removeEventListener('click', loginOnClick);
            login_error_btn_login.addEventListener('click', loginOnClick);
        } else {
            if (!options.uid || $this_uid.length === 0) {
                $note_wrapper.prepend(generateMessage(options));
            } else if ($this_uid.html() !== options.localized_text) {
                $this_uid.replaceWith(generateMessage(options));
            }

            $.scrollTo($note_wrapper, 500, { offset: -5 });
        }

        hideSpinnerShowTrading();
    };

    const generateMessage = (options) => {
        const $message = $(`<div class="notice-msg gr-12 center-text${(options.dismissible ? ' dismissible' : '')}"
            ${(options.uid ? ` id="${options.uid}"` : '')}>${options.localized_text}
                ${(options.dismissible ? '
x
' : '')}

`);

        if (options.dismissible) {
            $message.click(function () { dismissMessage(this); });
        }

        return $message;
    };

    const hideErrorMessage = (uid) => {
        if (uid) {
            getContainer().find(`#${uid}`).remove();
        }
    };

    const dismissMessage = (obj) => {
        $(obj).remove();
    };

    const loginOnClick = (e) => {
        e.preventDefault();
        Login.redirectToLogin();
    };

    const getContainer = () => $('#notifications_wrapper');

    const hideSpinnerShowTrading = () => {
        $('#main_loading').setVisibility(0);
        $('#mb-trading-wrapper').setVisibility(1);
    };

    return {
        hideSpinnerShowTrading,

        show: showErrorMessage,
        hide: hideErrorMessage,
    };
})();

module.exports = MBNotifications;
<commit_msg>fix code style<commit_after>/*
 * Notifications manages various notification messages
 *
 */
const CommonFunctions = require('../../../_common/common_functions');
const Login           = require('../../../_common/base/login');

const MBNotifications = (() => {
    /*
     * options: Object {
     *     localized_text: {string}  message text to display
     *     uid           : {string}  unique id to prevent duplicating the same message and also used to hide the message
     *     dismissible   : {boolean} dismissible messages can be hidden by client
     * }
     */
    const showErrorMessage = (options) => {
        const $note_wrapper          = getContainer();
        const $this_uid              = $note_wrapper.find(`#${options.uid}`);
        const $login_error_container = CommonFunctions.getElementById('login_error_container');
        $login_error_container.setVisibility(0);

        if (/LOGIN_ERROR/.test(options.uid)) {
            $login_error_container.setVisibility(1);
            const login_error_btn_login = CommonFunctions.getElementById('login_error_btn_login');
            login_error_btn_login.removeEventListener('click', loginOnClick);
            login_error_btn_login.addEventListener('click', loginOnClick);
        } else {
            if (!options.uid || $this_uid.length === 0) {
                $note_wrapper.prepend(generateMessage(options));
            } else if ($this_uid.html() !== options.localized_text) {
                $this_uid.replaceWith(generateMessage(options));
            }

            $.scrollTo($note_wrapper, 500, { offset: -5 });
        }

        hideSpinnerShowTrading();
    };

    const generateMessage = (options) => {
        const $message = $(`<div class="notice-msg gr-12 center-text${(options.dismissible ? ' dismissible' : '')}"
            ${(options.uid ? ` id="${options.uid}"` : '')}>${options.localized_text}
                ${(options.dismissible ? '
x
' : '')}

`);

        if (options.dismissible) {
            $message.click(function () { dismissMessage(this); });
        }

        return $message;
    };

    const hideErrorMessage = (uid) => {
        if (uid) {
            getContainer().find(`#${uid}`).remove();
        }
    };

    const dismissMessage = (obj) => {
        $(obj).remove();
    };

    const loginOnClick = (e) => {
        e.preventDefault();
        Login.redirectToLogin();
    };

    const getContainer = () => $('#notifications_wrapper');

    const hideSpinnerShowTrading = () => {
        $('#main_loading').setVisibility(0);
        $('#mb-trading-wrapper').setVisibility(1);
    };

    return {
        hideSpinnerShowTrading,

        show: showErrorMessage,
        hide: hideErrorMessage,
    };
})();

module.exports = MBNotifications;
<|endoftext|>


<commit_before>import React from "react"
import { connect } from "react-redux"
import { ImportByPKeyView } from "../../components/ImportAccount"
import { importNewAccount, throwError, pKeyChange, throwPKeyError, openPkeyModal, closePkeyModal } from "../../actions/accountActions"
import { addressFromPrivateKey } from "../../utils/keys"
import { getTranslate } from 'react-localize-redux'
import {AccountBalanceLayout} from "../../components/Exchange";

@connect((store) => {
  var tokens = store.tokens.tokens
  var supportTokens = []
  Object.keys(tokens).forEach((key) => {
    supportTokens.push(tokens[key])
  })
  return {
    account: store.account,
    ethereum: store.connection.ethereum,
    tokens: supportTokens,
    translate: getTranslate(store.locale),
    analytics: store.global.analytics
  }
})

export default class ImportByPrivateKey extends React.Component {

  openModal() {
    this.props.dispatch(openPkeyModal());
    this.props.analytics.callTrack("trackClickImportAccount", "private_key");
  }

  closeModal() {
    this.props.dispatch(closePkeyModal());
    this.props.analytics.callTrack("trackClickCloseModal", "import private-key");
  }

  inputChange(e) {
    var value = e.target.value
    this.props.dispatch(pKeyChange(value));
  }

  importPrivateKey(privateKey) {
    try {
      if (privateKey.match(/^0[x | X].{3,}$/)) {
          privateKey = privateKey.substring(2)
      }
      let address = addressFromPrivateKey(privateKey)
      this.props.dispatch(closePkeyModal());
      this.props.dispatch(importNewAccount(address,
        "privateKey",
        privateKey,
        this.props.ethereum,
        this.props.tokens, null, null, "Private Key"))
    }
    catch (e) {
      console.log(e)
      this.props.dispatch(throwPKeyError(this.props.translate("error.invalid_private_key") || 'Invalid private key'))
    }

  }

render() {
    return (
      <ImportByPKeyView
        isOnMobile={this.props.isOnMobile}
        importPrivateKey={this.importPrivateKey.bind(this)}
        modalOpen={this.openModal.bind(this)}
        onRequestClose={this.closeModal.bind(this)}
        isOpen={this.props.account.pKey.modalOpen}
        onChange={this.inputChange.bind(this)}
        pKeyError={this.props.account.pKey.error}
        translate={this.props.translate}
        analytics={this.props.analytics}
        {...(this.props.closeParentModal && {
          closeParentModal: this.props.closeParentModal
        })}
      />
    )
  }
}
<commit_msg>Close other modal after importing Private Key successfully<commit_after>import React from "react"
import { connect } from "react-redux"
import { ImportByPKeyView } from "../../components/ImportAccount"
import {
  importNewAccount,
  pKeyChange,
  throwPKeyError,
  openPkeyModal,
  closePkeyModal,
  closeOtherConnectModal
} from "../../actions/accountActions"
import { addressFromPrivateKey } from "../../utils/keys"
import { getTranslate } from 'react-localize-redux'

@connect((store) => {
  var tokens = store.tokens.tokens
  var supportTokens = []
  Object.keys(tokens).forEach((key) => {
    supportTokens.push(tokens[key])
  })
  return {
    account: store.account,
    ethereum: store.connection.ethereum,
    tokens: supportTokens,
    translate: getTranslate(store.locale),
    analytics: store.global.analytics
  }
})

export default class ImportByPrivateKey extends React.Component {
  openModal() {
    this.props.dispatch(openPkeyModal());
    this.props.analytics.callTrack("trackClickImportAccount", "private_key");
  }

  closeModal() {
    this.props.dispatch(closePkeyModal());
    this.props.analytics.callTrack("trackClickCloseModal", "import private-key");
  }

  inputChange(e) {
    var value = e.target.value
    this.props.dispatch(pKeyChange(value));
  }

  importPrivateKey(privateKey) {
    try {
      if (privateKey.match(/^0[x | X].{3,}$/)) {
          privateKey = privateKey.substring(2)
      }
      let address = addressFromPrivateKey(privateKey)

      this.props.dispatch(closePkeyModal());
      this.props.dispatch(closeOtherConnectModal());

      this.props.dispatch(importNewAccount(
        address,
        "privateKey",
        privateKey,
        this.props.ethereum,
        this.props.tokens, null, null, "Private Key"
      ))
    } catch (e) {
      console.log(e)
      this.props.dispatch(throwPKeyError(this.props.translate("error.invalid_private_key") || 'Invalid private key'))
    }
  }

render() {
    return (
      <ImportByPKeyView
        isOnMobile={this.props.isOnMobile}
        importPrivateKey={this.importPrivateKey.bind(this)}
        modalOpen={this.openModal.bind(this)}
        onRequestClose={this.closeModal.bind(this)}
        isOpen={this.props.account.pKey.modalOpen}
        onChange={this.inputChange.bind(this)}
        pKeyError={this.props.account.pKey.error}
        translate={this.props.translate}
        analytics={this.props.analytics}
        {...(this.props.closeParentModal && {
          closeParentModal: this.props.closeParentModal
        })}
      />
    )
  }
}
<|endoftext|>


<commit_before>import { connect } from 'react-redux'
import merge from 'lodash/merge'
import { setEntity } from '../../lib/actions/entityActions'
import { toggleSessionPopup } from '../../UserSession/actions/SessionActions'
import PledgeForm from '../components/PledgeForm'
import updateAction from '../../lib/Form/actions/updateAction'

const mapStateToProps = function(state, ownProps) {
  return {
    availableTags: assembleTags(ownProps.tags),
    currentUser: state.currentUser,
  }
}

function assembleTags(tags) {
  return tags.map(function(tag) {
    return {
      value: tag.id,
      label: tag.name,
    }
  })
}

const mapDispatchToProps = dispatch => ({
  onLinkClick: function(event) {
    event.preventDefault()

    dispatch(toggleSessionPopup())
    window.scrollTo(0, 0)
  },
})

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PledgeForm)
<commit_msg>Use tag name translations in new pledge form<commit_after>import { connect } from 'react-redux'
import merge from 'lodash/merge'
import I18n from 'i18n-js'
import { setEntity } from '../../lib/actions/entityActions'
import { toggleSessionPopup } from '../../UserSession/actions/SessionActions'
import PledgeForm from '../components/PledgeForm'
import updateAction from '../../lib/Form/actions/updateAction'

const mapStateToProps = function(state, ownProps) {
  return {
    availableTags: assembleTags(ownProps.tags),
    currentUser: state.currentUser,
  }
}

function assembleTags(tags) {
  return tags.map(function(tag) {
    return {
      value: tag.id,
      label: I18n.t(`tags.names.${tag.name}`),
    }
  })
}

const mapDispatchToProps = dispatch => ({
  onLinkClick: function(event) {
    event.preventDefault()

    dispatch(toggleSessionPopup())
    window.scrollTo(0, 0)
  },
})

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PledgeForm)
<|endoftext|>


<commit_before>require('../app').controller('MobileStatsController', /* @ngInject */function ($scope, $state, $q, api) {
  var controller = this

  controller.forms = ['birds', 'herptiles', 'mammals', 'plants', 'invertebrates']

  $q.all(controller.forms.map(function (form) {
    return api.stats[form + '_top_stats']().then(function (res) {
      var stats = {}
      stats[form] = res.interesting_species
      return stats
    })
  })).then(function (result) {
    controller.stats = result.reduce(function (res, current) {
      return Object.assign(res, current)
    })
  }).catch(function (err) {
    console.log(err)
  })
})
<commit_msg>fix showing stats on older android devices (#58)<commit_after>require('../app').controller('MobileStatsController', /* @ngInject */function ($scope, $state, $q, api) {
  var controller = this

  controller.forms = ['birds', 'herptiles', 'mammals', 'plants', 'invertebrates']

  $q.all(controller.forms.map(function (form) {
    return api.stats[form + '_top_stats']().then(function (res) {
      var stats = {}
      stats[form] = res.interesting_species
      return stats
    })
  })).then(function (result) {
    controller.stats = result.reduce(function (res, current) {
      for (var key in current) {
        if (!current.hasOwnProperty(key)) continue
        res[key] = current[key]
      }
      return res
    })
  }).catch(function (err) {
    console.log(err)
  })
})
<|endoftext|>


<commit_before>import React, { useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import Button from 'components/Button';
import Modal from 'components/Modal';
import ContentListItem from 'components/ContentListItem';
import LoadMoreButton from 'components/Buttons/LoadMoreButton';
import request from 'axios';
import URL from 'constants/URL';
import Loading from 'components/Loading';
import { objectify } from 'helpers';
import {
  loadContent,
  loadFeeds,
  uploadFeaturedChallenges
} from 'helpers/requestHelpers';
import { queryStringForArray } from 'helpers/stringHelpers';
import { connect } from 'react-redux';

SelectFeaturedChallengesModal.propTypes = {
  dispatch: PropTypes.func.isRequired,
  onHide: PropTypes.func.isRequired,
  onSubmit: PropTypes.func.isRequired
};

function SelectFeaturedChallengesModal({ dispatch, onHide, onSubmit }) {
  const [loadMoreButton, setLoadMoreButton] = useState(false);
  const [challengeObjs, setChallengeObjs] = useState({});
  const [challenges, setChallenges] = useState([]);
  const [selected, setSelected] = useState([]);
  const [loaded, setLoaded] = useState(false);
  const initialSelected = useRef([]);
  useEffect(() => {
    init();
    async function init() {
      const { data: selectedIds } = await request.get(
        `${URL}/content/featured/ids`
      );
      setSelected(selectedIds);
      initialSelected.current = selectedIds;
      const {
        data: { feeds, loadMoreButton: loadMoreShown }
      } = await loadFeeds({
        filter: 'post',
        limit: 10
      });
      const challengesArray = [];
      for (let feed of feeds) {
        const challenge = await loadContent({
          contentId: feed.contentId,
          type: feed.type
        });
        challengesArray.push({ ...feed, ...challenge });
      }
      setChallengeObjs(objectify(challengesArray));
      setChallenges(challengesArray.map(challenge => challenge.id));
      setLoadMoreButton(loadMoreShown);
      setLoaded(true);
    }
  }, []);

  return (
    <Modal large onHide={onHide}>
      Select Featured Subjects

        {loaded ? (
          challenges.map(challengeId => (
            <ContentListItem
              selectable
              selected={selected.indexOf(challengeId) !== -1}
              key={challengeId}
              style={{ width: '100%' }}
              contentObj={challengeObjs[challengeId]}
              onClick={() =>
                selected.indexOf(challengeId) === -1
                  ? setSelected(selected.concat(challengeId))
                  : setSelected(selected.filter(id => id !== challengeId))
              }
            />
          ))
        ) : (
          <Loading />
        )}
        {loadMoreButton && (
          <LoadMoreButton
            style={{ fontSize: '2rem' }}
            transparent
            onClick={handleLoadMore}
          />
        )}

        <Button transparent style={{ marginRight: '0.7rem' }} onClick={onHide}>
          Cancel
        </Button>
        <Button primary onClick={handleSubmit}>
          Done
        </Button>

    </Modal>
  );

  async function handleLoadMore() {
    const {
      data: { feeds, loadMoreButton: loadMoreShown }
    } = await loadFeeds({
      filter: 'post',
      limit: 10,
      shownFeeds: queryStringForArray({
        array: challenges.map(challengeId => challengeObjs[challengeId]),
        originVar: 'feedId',
        destinationVar: 'shownFeeds'
      })
    });
    const challengesArray = [];
    for (let feed of feeds) {
      const challenge = await loadContent({
        contentId: feed.contentId,
        type: feed.type
      });
      challengesArray.push({ ...feed, ...challenge });
    }
    setChallengeObjs({
      ...challengeObjs,
      ...objectify(challengesArray)
    });
    setChallenges(
      challenges.concat(challengesArray.map(challenge => challenge.id))
    );
    setLoadMoreButton(loadMoreShown);
  }

  async function handleSubmit() {
    await uploadFeaturedChallenges({ dispatch, selected });
    const selectedReversed = [...selected];
    selectedReversed.reverse();
    onSubmit(selectedReversed.map(selectedId => challengeObjs[selectedId]));
  }
}

export default connect(
  null,
  dispatch => ({ dispatch })
)(SelectFeaturedChallengesModal);
<commit_msg>minor update<commit_after>import React, { useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import Button from 'components/Button';
import Modal from 'components/Modal';
import ContentListItem from 'components/ContentListItem';
import LoadMoreButton from 'components/Buttons/LoadMoreButton';
import request from 'axios';
import URL from 'constants/URL';
import Loading from 'components/Loading';
import { objectify } from 'helpers';
import {
  loadContent,
  loadFeeds,
  uploadFeaturedChallenges
} from 'helpers/requestHelpers';
import { queryStringForArray } from 'helpers/stringHelpers';
import { connect } from 'react-redux';

SelectFeaturedChallengesModal.propTypes = {
  dispatch: PropTypes.func.isRequired,
  onHide: PropTypes.func.isRequired,
  onSubmit: PropTypes.func.isRequired
};

function SelectFeaturedChallengesModal({ dispatch, onHide, onSubmit }) {
  const [loadMoreButton, setLoadMoreButton] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [challengeObjs, setChallengeObjs] = useState({});
  const [challenges, setChallenges] = useState([]);
  const [selected, setSelected] = useState([]);
  const [loaded, setLoaded] = useState(false);
  const initialSelected = useRef([]);
  useEffect(() => {
    init();
    async function init() {
      const { data: selectedIds } = await request.get(
        `${URL}/content/featured/ids`
      );
      setSelected(selectedIds);
      initialSelected.current = selectedIds;
      const {
        data: { feeds, loadMoreButton: loadMoreShown }
      } = await loadFeeds({
        filter: 'post',
        limit: 10
      });
      const challengesArray = [];
      for (let feed of feeds) {
        const challenge = await loadContent({
          contentId: feed.contentId,
          type: feed.type
        });
        challengesArray.push({ ...feed, ...challenge });
      }
      setChallengeObjs(objectify(challengesArray));
      setChallenges(challengesArray.map(challenge => challenge.id));
      setLoadMoreButton(loadMoreShown);
      setLoaded(true);
    }
  }, []);

  return (
    <Modal large onHide={onHide}>
      Select Featured Subjects

        {loaded ? (
          challenges.map(challengeId => (
            <ContentListItem
              selectable
              selected={selected.indexOf(challengeId) !== -1}
              key={challengeId}
              style={{ width: '100%' }}
              contentObj={challengeObjs[challengeId]}
              onClick={() =>
                selected.indexOf(challengeId) === -1
                  ? setSelected(selected.concat(challengeId))
                  : setSelected(selected.filter(id => id !== challengeId))
              }
            />
          ))
        ) : (
          <Loading />
        )}
        {loadMoreButton && (
          <LoadMoreButton
            style={{ fontSize: '2rem' }}
            transparent
            loading={loadingMore}
            onClick={handleLoadMore}
          />
        )}

        <Button transparent style={{ marginRight: '0.7rem' }} onClick={onHide}>
          Cancel
        </Button>
        <Button primary onClick={handleSubmit}>
          Done
        </Button>

    </Modal>
  );

  async function handleLoadMore() {
    setLoadingMore(true);
    const {
      data: { feeds, loadMoreButton: loadMoreShown }
    } = await loadFeeds({
      filter: 'post',
      limit: 10,
      shownFeeds: queryStringForArray({
        array: challenges.map(challengeId => challengeObjs[challengeId]),
        originVar: 'feedId',
        destinationVar: 'shownFeeds'
      })
    });
    const challengesArray = [];
    for (let feed of feeds) {
      const challenge = await loadContent({
        contentId: feed.contentId,
        type: feed.type
      });
      challengesArray.push({ ...feed, ...challenge });
    }
    setChallengeObjs({
      ...challengeObjs,
      ...objectify(challengesArray)
    });
    setChallenges(
      challenges.concat(challengesArray.map(challenge => challenge.id))
    );
    setLoadingMore(false);
    setLoadMoreButton(loadMoreShown);
  }

  async function handleSubmit() {
    await uploadFeaturedChallenges({ dispatch, selected });
    const selectedReversed = [...selected];
    selectedReversed.reverse();
    onSubmit(selectedReversed.map(selectedId => challengeObjs[selectedId]));
  }
}

export default connect(
  null,
  dispatch => ({ dispatch })
)(SelectFeaturedChallengesModal);
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import AddContractorComponent from './AddContractor.jsx';
import { addContractor } from '../../actions/contractor-info-actions.js';
import { viewTableRows } from '../../actions/view-tables-actions.js';

const mapStateToProps = state => {
  return {
    error: state.contractors.error,
    isLoading: state.main.isLoading,
    tables: state.tables,
    token: state.user.token
  };
};

const mapDispatchToProps = dispatch => {
  return {
    onSubmit: (contractorData, projectData, tableData, callback, token) => {
      dispatch(addContractor(contractorData, projectData, tableData, callback, token));
    },
    viewTables: (token) => {
      dispatch(viewTableRows('skills', token));
      dispatch(viewTableRows('fxrates', token));
      dispatch(viewTableRows('paygrades', token));
      dispatch(viewTableRows('hrroles', token));
      dispatch(viewTableRows('hiringmanagers', token));
      dispatch(viewTableRows('costcenters', token));
    }
  };
};

class AddContractorContainer extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      contractor: {
        firstName: '',
        lastName: '',
        agencySource: '',
        status: 'active'
      },
      projects: [
        this.createDefaultProjectObject()
      ],
      message: '',
      tables: {}
    };
    this.handleTextInput = this.handleTextInput.bind(this);
    this.handleDropdownInput = this.handleDropdownInput.bind(this);
    this.handleDateInput = this.handleDateInput.bind(this);
    this.handleRadioInput = this.handleRadioInput.bind(this);
    this.handleAdd = this.handleAdd.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.resetState = this.resetState.bind(this);

  }

  componentDidMount() {
    this.props.viewTables(this.props.token);
  }

  handleTextInput(event) {
    event.preventDefault();
    const { state } = this;
    if (!event.target.hasAttribute('data-index')) {
      const {contractor} = state;
      contractor[event.target.getAttribute('name')] = event.target.value;
      this.setState(Object.assign(state, {contractor}));
    } else {
      const { projects } = state;
      let dataIndex = parseInt(event.target.getAttribute('data-index'));
      let project = projects[dataIndex];
      project[event.target.getAttribute('name')] = event.target.value;
      this.setState(Object.assign(state, {projects}));
    }
  }

  handleDropdownInput(event) {
    event.preventDefault();
    const { state } = this;
    if (!event.target.hasAttribute('data-index')) {
      const {contractor} = state;
      contractor[event.target.getAttribute('name')] = event.target.value;
    } else {
      const { projects } = state;
      let dataIndex = parseInt(event.target.getAttribute('data-index'));
      let project = projects[dataIndex];
      project[event.target.getAttribute('name')] = event.target.value;
      this.setState(Object.assign(state, {projects}));
    }
  }

  handleDateInput(event) {
    event.preventDefault();
    const { state } = this;
    const { projects } = state;
    let dataIndex = parseInt(event.target.getAttribute('data-index'));
    let project = projects[dataIndex];
    project[event.target.getAttribute('name')] = event.target.value;
    this.setState(Object.assign(state, {projects}));
  }

  handleRadioInput(event) {
    const { state } = this;
    if (!event.target.hasAttribute('data-index')) {
      const { contractor } = state;
      contractor[event.target.getAttribute('name')] = event.target.value;
      this.setState(Object.assign(state, {contractor}));
    } else {
      const { projects } = state;
      let dataIndex = event.target.getAttribute('data-index');
      let project = projects[dataIndex];
      let nameWithIndex = event.target.getAttribute('name');
      let name = nameWithIndex.split("-")[0];
      project[name] = event.target.value;
      this.setState(Object.assign(state, {projects}));
    }
  }

  handleAdd(event) {
    event.preventDefault();
    let projectState = this.state.projects;
    projectState.push(this.createDefaultProjectObject());
    this.setState({projects: projectState})
  }

  handleSubmit(event) {
    event.preventDefault();
    const { contractor } = this.state;
    const { projects } = this.state;
    this.props.onSubmit(contractor, projects, this.props.tables, this.resetState, this.props.token);
  }

  createDefaultProjectObject() {
    return {
        projectName: '',
        reportingmanagers: this.getReportingManagersOptions(),
        hrpositions: this.getHrPositionOptions(),
        ratetypes: this.getRateTypeOptions(),
        paygrades: this.getPayGradeOptions(),
        refnos: 0,
        mainSkills: this.getMainSkillsOptions(),
        costCenters: this.getCostCenterOptions(),
        originalDocumentation: '',
        terminationNum: 0,
        startDate: "2017-01-01",
        endDate: "2017-01-02",
        dailyAllowance:0,
        timeMaterialTerms:0,
        hourlyrate:0
    };
  }

  getDropdownOptions (optionName) {
    switch  (optionName) {
      case "reportingManager":
        return this.getReportingManagersOptions();
      case "hrPosition":
        return this.getHrPositionOptions();
      case "rateType":
        return this.getRateTypeOptions();
      case "payGrade":
        return this.getPayGradeOptions();
      case "refNos":
        return this.getRefNosOptions();
      case "mainSkills":
        return this.getMainSkillsOptions();
      case "costCenters":
        return this.getCostCenterOptions();
      default:
        return [];
    }
  }

  getReportingManagersOptions() {
    //fallbacks
    return ['harry potter', 'luna luvgood'];
  }

  getHrPositionOptions() {
    //fallbacks
    return ['professor', 'dark arts teacher'];
  }

  getRateTypeOptions() {
    //fallbacks
    return ['Monthly', 'Hourly', 'Daily'];
  }

  getPayGradeOptions() {
    //fallbacks
    return ['A', 'B'];
  }

  getMainSkillsOptions() {
    //fall backs
    return ['Databases', 'Languages'];
  }

  getCostCenterOptions() {
    //fallbacks
    return ["Vancouver", "Calgary"];
  }

  resetState() {
    const { props } = this;
    if (props.error) {
      this.setState({ message: props.error });
    } else {
      this.setState({
        contractor: {
          firstName: '',
          surname: '',
          agencySource: ''
        },
        projects: [
          this.createDefaultProjectObject()
        ],
        message: 'Contractor added successfully.'
      });
    }
  }

  render() {
    return <AddContractorComponent
      contractor={this.state.contractor}
      projects={this.state.projects}
      handleTextInput={this.handleTextInput}
      handleDropdownInput={this.handleDropdownInput}
      handleDateInput={this.handleDateInput}
      handleRadioInput={this.handleRadioInput}
      handleAdd={this.handleAdd}
      handleSubmit={this.handleSubmit}
      message={this.state.message}
      tables={this.props.tables}
    />;
  }
}

const AddContractor = connect(
  mapStateToProps,
  mapDispatchToProps
)(AddContractorContainer);

export default AddContractor;
<commit_msg>Updated alert<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import AddContractorComponent from './AddContractor.jsx';
import { addContractor } from '../../actions/contractor-info-actions.js';
import { viewTableRows } from '../../actions/view-tables-actions.js';

const mapStateToProps = state => {
  return {
    error: state.contractors.error,
    isLoading: state.main.isLoading,
    tables: state.tables,
    token: state.user.token
  };
};

const mapDispatchToProps = dispatch => {
  return {
    onSubmit: (contractorData, projectData, tableData, callback, token) => {
      dispatch(addContractor(contractorData, projectData, tableData, callback, token));
    },
    viewTables: (token) => {
      dispatch(viewTableRows('skills', token));
      dispatch(viewTableRows('fxrates', token));
      dispatch(viewTableRows('paygrades', token));
      dispatch(viewTableRows('hrroles', token));
      dispatch(viewTableRows('hiringmanagers', token));
      dispatch(viewTableRows('costcenters', token));
    }
  };
};

class AddContractorContainer extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      contractor: {
        firstName: '',
        lastName: '',
        agencySource: '',
        status: 'active'
      },
      projects: [
        this.createDefaultProjectObject()
      ],
      tables: {}
    };
    this.handleTextInput = this.handleTextInput.bind(this);
    this.handleDropdownInput = this.handleDropdownInput.bind(this);
    this.handleDateInput = this.handleDateInput.bind(this);
    this.handleRadioInput = this.handleRadioInput.bind(this);
    this.handleAdd = this.handleAdd.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.resetState = this.resetState.bind(this);

  }

  componentDidMount() {
    this.props.viewTables(this.props.token);
  }

  handleTextInput(event) {
    event.preventDefault();
    const { state } = this;
    if (!event.target.hasAttribute('data-index')) {
      const {contractor} = state;
      contractor[event.target.getAttribute('name')] = event.target.value;
      this.setState(Object.assign(state, {contractor}));
    } else {
      const { projects } = state;
      let dataIndex = parseInt(event.target.getAttribute('data-index'));
      let project = projects[dataIndex];
      project[event.target.getAttribute('name')] = event.target.value;
      this.setState(Object.assign(state, {projects}));
    }
  }

  handleDropdownInput(event) {
    event.preventDefault();
    const { state } = this;
    if (!event.target.hasAttribute('data-index')) {
      const {contractor} = state;
      contractor[event.target.getAttribute('name')] = event.target.value;
    } else {
      const { projects } = state;
      let dataIndex = parseInt(event.target.getAttribute('data-index'));
      let project = projects[dataIndex];
      project[event.target.getAttribute('name')] = event.target.value;
      this.setState(Object.assign(state, {projects}));
    }
  }

  handleDateInput(event) {
    event.preventDefault();
    const { state } = this;
    const { projects } = state;
    let dataIndex = parseInt(event.target.getAttribute('data-index'));
    let project = projects[dataIndex];
    project[event.target.getAttribute('name')] = event.target.value;
    this.setState(Object.assign(state, {projects}));
  }

  handleRadioInput(event) {
    const { state } = this;
    if (!event.target.hasAttribute('data-index')) {
      const { contractor } = state;
      contractor[event.target.getAttribute('name')] = event.target.value;
      this.setState(Object.assign(state, {contractor}));
    } else {
      const { projects } = state;
      let dataIndex = event.target.getAttribute('data-index');
      let project = projects[dataIndex];
      let nameWithIndex = event.target.getAttribute('name');
      let name = nameWithIndex.split("-")[0];
      project[name] = event.target.value;
      this.setState(Object.assign(state, {projects}));
    }
  }

  handleAdd(event) {
    event.preventDefault();
    let projectState = this.state.projects;
    projectState.push(this.createDefaultProjectObject());
    this.setState({projects: projectState})
  }

  handleSubmit(event) {
    event.preventDefault();
    const { contractor } = this.state;
    const { projects } = this.state;

    this.props.onSubmit(contractor, projects, this.props.tables, this.resetState, this.props.token);
  }

  createDefaultProjectObject() {
    return {
        projectName: '',
        reportingmanagers: this.getReportingManagersOptions(),
        hrpositions: this.getHrPositionOptions(),
        ratetypes: this.getRateTypeOptions(),
        paygrades: this.getPayGradeOptions(),
        refnos: 0,
        mainSkills: this.getMainSkillsOptions(),
        costCenters: this.getCostCenterOptions(),
        originalDocumentation: '',
        terminationNum: 0,
        startDate: "2017-01-01",
        endDate: "2017-01-02",
        dailyAllowance:0,
        timeMaterialTerms:0,
        hourlyrate:0
    };
  }

  getDropdownOptions (optionName) {
    switch  (optionName) {
      case "reportingManager":
        return this.getReportingManagersOptions();
      case "hrPosition":
        return this.getHrPositionOptions();
      case "rateType":
        return this.getRateTypeOptions();
      case "payGrade":
        return this.getPayGradeOptions();
      case "refNos":
        return this.getRefNosOptions();
      case "mainSkills":
        return this.getMainSkillsOptions();
      case "costCenters":
        return this.getCostCenterOptions();
      default:
        return [];
    }
  }

  getReportingManagersOptions() {
    //fallbacks
    return ['harry potter', 'luna luvgood'];
  }

  getHrPositionOptions() {
    //fallbacks
    return ['professor', 'dark arts teacher'];
  }

  getRateTypeOptions() {
    //fallbacks
    return ['Monthly', 'Hourly', 'Daily'];
  }

  getPayGradeOptions() {
    //fallbacks
    return ['A', 'B'];
  }

  getMainSkillsOptions() {
    //fall backs
    return ['Databases', 'Languages'];
  }

  getCostCenterOptions() {
    //fallbacks
    return ["Vancouver", "Calgary"];
  }

  resetState() {
    const { props } = this;
    if (props.error) {
      alert(props.error);
    } else {
      this.setState({
        contractor: {
          firstName: '',
          surname: '',
          agencySource: ''
        },
        projects: [
          this.createDefaultProjectObject()
        ]
      });
      alert('Contractor added Successfully');
    }
  }

  render() {
    return <AddContractorComponent
      contractor={this.state.contractor}
      projects={this.state.projects}
      handleTextInput={this.handleTextInput}
      handleDropdownInput={this.handleDropdownInput}
      handleDateInput={this.handleDateInput}
      handleRadioInput={this.handleRadioInput}
      handleAdd={this.handleAdd}
      handleSubmit={this.handleSubmit}
      message={this.state.message}
      tables={this.props.tables}
    />;
  }
}

const AddContractor = connect(
  mapStateToProps,
  mapDispatchToProps
)(AddContractorContainer);

export default AddContractor;
<|endoftext|>


<commit_before>function coordText(x, y) {
    var x_string = "mouseX: " + Math.floor(mouseX);
    var y_string = "mouseY: " + Math.floor(mouseY);
    var textS = 14;

    noStroke();
    fill(0);
    textSize(textS);
    text(x_string, x, y, textWidth(x_string) + 5, textSize(x_string));
    text(y_string, x, y+16, textWidth(y_string) + 5, textSize(y_string));

    stroke(0);
    strokeWeight(1);
    noFill();
    rect(x - 1, y, textWidth(x_string) + 5, textS+2);
    rect(x - 1, y+16, textWidth(x_string) + 5, textS+2);
}

function pyrand(min, max) {
    return Math.random() * (max-min) + min;
}

function Orb() {
    this.x;
    this.y;
    this.growing = true;
    this.r = pyrand(4, 16);
    this.xoffset = pyrand(-100, 100);
    this.yoffset = pyrand(-100, 100);

    this.relocate = function() {
        this.xoffset = pyrand(-100, 100);
        this.yoffset = pyrand(-100, 100);
    }

    this.grow = function() {
        if (this.growing) {
            this.r++;
        }
    }

    this.show = function() {
        this.x = mouseX + this.xoffset; //pyrand(-100, 100);
        this.y = mouseY + this.yoffset; //pyrand(-100, 100);
        stroke(0);
        strokeWeight(1);
        fill(0, 100);
        ellipse(this.x, this.y, this.r, this.r);
    }
}

var Orbs = [];

function setup() {
    createCanvas(640, 360);

    for (var i = 0; i<100; i++) {
        Orbs[i] = new Orb();
    }
}

function mouseClicked() {
    for (i=0;i<Orbs.length;i++) {
        Orbs[i].relocate();
    }
}

function draw() {
    background(191);

    stroke(0);
    strokeWeight(2);
    line(0, mouseY, width, mouseY);
    line(mouseX, 0, mouseX, height);

    for (i=0;i<Orbs.length;i++) {
        Orbs[i].show();
    }

    coordText(5, 5);
}<commit_msg>sketch 03 toying<commit_after>function coordText(x, y) {
    var x_string = "mouseX: " + Math.floor(mouseX);
    var y_string = "mouseY: " + Math.floor(mouseY);
    var textS = 14;

    noStroke();
    fill(0);
    textSize(textS);
    text(x_string, x, y, textWidth(x_string) + 5, textSize(x_string));
    text(y_string, x, y+16, textWidth(y_string) + 5, textSize(y_string));

    stroke(0);
    strokeWeight(1);
    noFill();
    rect(x - 1, y, textWidth(x_string) + 5, textS+2);
    rect(x - 1, y+16, textWidth(x_string) + 5, textS+2);
}

function pyrand(min, max) {
    return Math.random() * (max-min) + min;
}

function Orb() {
    this.x;
    this.y;
    this.growing = true;
    this.r = pyrand(4, 16);
    this.xoffset = pyrand(-100, 100);
    this.yoffset = pyrand(-100, 100);

    this.relocate = function() {
        this.xoffset = pyrand(-100, 100);
        this.yoffset = pyrand(-100, 100);
    }

    this.grow = function() {
        if (this.growing) {
            this.r++;
        }
    }

    this.show = function() {
        this.x = mouseX + this.xoffset; //pyrand(-100, 100);
        this.y = mouseY + this.yoffset; //pyrand(-100, 100);
        stroke(0);
        strokeWeight(1);
        fill(0, 100);
        ellipse(this.x, this.y, this.r, this.r);

        strokeWeight(4);
        point(this.x, this.y + (this.r / 2) * sin(90));
    }
}

var Orbs = [];

function setup() {
    createCanvas(640, 360);

    for (var i = 0; i<100; i++) {
        Orbs[i] = new Orb();
    }
}

function mouseClicked() {
    for (i=0;i<Orbs.length;i++) {
        Orbs[i].relocate();
    }
}

function draw() {
    background(191);

    stroke(0);
    strokeWeight(2);
    line(0, mouseY, width, mouseY);
    line(mouseX, 0, mouseX, height);

    for (i=0;i<Orbs.length;i++) {
        Orbs[i].show();
    }

    coordText(5, 5);
}<|endoftext|>


<commit_before>(function () {
    "use strict";

    function UsersOverviewController($scope, $location, $timeout, navigationService, localizationService) {

        var vm = this;
        var usersUri = $location.search().subview;
        if (!usersUri) {
            $location.search("subview", "users");
            //exit after this, we don't want to initialize anything further since this
            //is going to change the route
            return;
        }

        //note on the below, we dont assign a view unless it's the right route since if we did that it will load in that controller
        //for the view which is unecessary and will cause extra overhead/requests to occur
        vm.page = {};
        vm.page.labels = {};
        vm.page.name = "";
        vm.page.navigation = [];

        function onInit() {

            loadNavigation();

            setPageName();

            $timeout(function () {
                navigationService.syncTree({ tree: "users", path: "-1" });
            });

        }

        function loadNavigation() {

            var labels = ["sections_users", "general_groups"];

            localizationService.localizeMany(labels).then(function(data){
                vm.page.labels.users = data[0];
                vm.page.labels.groups = data[1];

                vm.page.navigation = [
                    {
                        "name": vm.page.labels.users,
                        "icon": "icon-user",
                        "action": function() {
                          $location.search("subview", "users")
                        },
                        "view": !usersUri || usersUri === "users" ? "views/users/views/users/users.html" : null,
                        "active": !usersUri || usersUri === "users"
                    },
                    {
                        "name": vm.page.labels.groups,
                        "icon": "icon-users",
                        "action": function () {
                          $location.search("subview", "groups")
                        },
                        "view": usersUri === "groups" ? "views/users/views/groups/groups.html" : null,
                        "active": usersUri === "groups"
                    }
                ];
            });
        }

        function setPageName() {
            localizationService.localize("user_userManagement").then(function(data){
                vm.page.name = data;
            })
        }

        onInit();

    }

    angular.module("umbraco").controller("Umbraco.Editors.Users.OverviewController", UsersOverviewController);

})();
<commit_msg>add alias to user subviews to fix broken track by<commit_after>(function () {
    "use strict";

    function UsersOverviewController($scope, $location, $timeout, navigationService, localizationService) {

        var vm = this;
        var usersUri = $location.search().subview;
        if (!usersUri) {
            $location.search("subview", "users");
            //exit after this, we don't want to initialize anything further since this
            //is going to change the route
            return;
        }

        //note on the below, we dont assign a view unless it's the right route since if we did that it will load in that controller
        //for the view which is unecessary and will cause extra overhead/requests to occur
        vm.page = {};
        vm.page.labels = {};
        vm.page.name = "";
        vm.page.navigation = [];

        function onInit() {

            loadNavigation();

            setPageName();

            $timeout(function () {
                navigationService.syncTree({ tree: "users", path: "-1" });
            });

        }

        function loadNavigation() {

            var labels = ["sections_users", "general_groups"];

            localizationService.localizeMany(labels).then(function(data){
                vm.page.labels.users = data[0];
                vm.page.labels.groups = data[1];

                vm.page.navigation = [
                    {
                        "name": vm.page.labels.users,
                        "icon": "icon-user",
                        "action": function() {
                          $location.search("subview", "users")
                        },
                        "view": !usersUri || usersUri === "users" ? "views/users/views/users/users.html" : null,
                        "active": !usersUri || usersUri === "users",
                        "alias": "users"
                    },
                    {
                        "name": vm.page.labels.groups,
                        "icon": "icon-users",
                        "action": function () {
                          $location.search("subview", "groups")
                        },
                        "view": usersUri === "groups" ? "views/users/views/groups/groups.html" : null,
                        "active": usersUri === "groups",
                        "alias": "userGroups"
                    }
                ];
            });
        }

        function setPageName() {
            localizationService.localize("user_userManagement").then(function(data){
                vm.page.name = data;
            })
        }

        onInit();

    }

    angular.module("umbraco").controller("Umbraco.Editors.Users.OverviewController", UsersOverviewController);

})();
<|endoftext|>


<commit_before>(function () {
    "use strict";

    function UsersOverviewController($scope, $location, $timeout, navigationService, localizationService) {

        var vm = this;
        var usersUri = $location.search().subview;
        if (!usersUri) {
          $location.search("subview", "users")
        }

        vm.page = {};
        vm.page.name = "User Management";
        vm.page.navigation = [
            {
                "name": localizationService.localize("sections_users"),
                "icon": "icon-user",
                "action": function() {
                  $location.search("subview", "users")
                },
                "view": "views/users/views/users/users.html",
                "active": !usersUri || usersUri === "users"
            },
            {
                "name": localizationService.localize("general_groups"),
                "icon": "icon-users",
                "action": function () {
                  $location.search("subview", "groups")
                },
                "view": "views/users/views/groups/groups.html",
                "active": usersUri === "groups"
            }
        ];

        function init() {

            $timeout(function () {
                navigationService.syncTree({ tree: "users", path: "-1" });
            });

        }

        init();

    }

    angular.module("umbraco").controller("Umbraco.Editors.Users.OverviewController", UsersOverviewController);

})();
<commit_msg>U4-10346 Whenever you visit either the users or the groups section BOTH controllers: Users and Groups initialize<commit_after>(function () {
    "use strict";

    function UsersOverviewController($scope, $location, $timeout, navigationService, localizationService) {

        var vm = this;
        var usersUri = $location.search().subview;
        if (!usersUri) {
            $location.search("subview", "users");
            //exit after this, we don't want to initialize anything further since this
            //is going to change the route
            return;
        }

        //note on the below, we dont assign a view unless it's the right route since if we did that it will load in that controller
        //for the view which is unecessary and will cause extra overhead/requests to occur
        vm.page = {};
        vm.page.name = "User Management";
        vm.page.navigation = [
            {
                "name": localizationService.localize("sections_users"),
                "icon": "icon-user",
                "action": function() {
                  $location.search("subview", "users")
                },
                "view": !usersUri || usersUri === "users" ? "views/users/views/users/users.html" : null,
                "active": !usersUri || usersUri === "users"
            },
            {
                "name": localizationService.localize("general_groups"),
                "icon": "icon-users",
                "action": function () {
                  $location.search("subview", "groups")
                },
                "view": usersUri === "groups" ? "views/users/views/groups/groups.html" : null,
                "active": usersUri === "groups"
            }
        ];

        function init() {

            $timeout(function () {
                navigationService.syncTree({ tree: "users", path: "-1" });
            });

        }

        init();

    }

    angular.module("umbraco").controller("Umbraco.Editors.Users.OverviewController", UsersOverviewController);

})();
<|endoftext|>