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

    angular.module("mfl.facility_mgmt.controllers", [
        "mfl.facility_mgmt.services",
        "mfl.auth.services"
    ])

    .controller("mfl.facility_mgmt.controllers.facility_list",
        ["$scope", function ($scope) {
            $scope.title = {
                "name": "Facility Management"
            };
        }]
    )

    .controller("mfl.facility_mgmt.controllers.facility_edit",
        ["$scope", "$log", "$stateParams", "mfl.facility_mgmt.services.wrappers",
        "mfl.auth.services.login",
        function ($scope, $log, $stateParams, wrappers, loginService) {
            $scope.title = {
                "name": "Edit Facility"
            };
            $scope.facility_id = $stateParams.facility_id;
            wrappers.facility_detail.get($scope.facility_id)
                .success(function(data){
                    $scope.facility = data;
                })
                .error(function (data) {
                    $log.error(data);
                });
            $scope.login_user = loginService.getUser();
            $scope.action = [
                {
                    func: "require-permission='facilities.add_facilityapproval' " +
                          "ng-if='!facility.is_approved || facility.has_edits' " +
                          "ui-sref='facilities.facility_edit({facility_id: facility.id})'",
                    class: "action-btn action-btn-md action-btn-info",
                    icon: "fa-check",
                    tipmsg: "Approve"
                },
                {
                    func: "require-permission='facilities.change_facility' " +
                          "ng-if='login_user.is_national' " +
                          "ui-sref='facilities.facility_edit({facility_id: facility.id})'",
                    class: "action-btn action-btn-md action-btn-info",
                    icon: "fa-upload",
                    tipmsg: "Publish"
                },
                {
                    func: "require-permission='facilities.add_facilityregulationstatus' " +
                          "ng-if='login_user.regulator' " +
                          "ui-sref='facilities.facility_edit({facility_id: facility.id})'",
                    class: "action-btn action-btn-md action-btn-info",
                    icon: "fa-legal",
                    tipmsg: "Regulate"
                }
            ];
        }]
    )

    .controller("mfl.facility_mgmt.controllers.facility_edit.basic",
        ["$scope", "$log", "$stateParams", "mfl.facility_mgmt.services.wrappers",
        function ($scope, $log, $stateParams, wrappers) {
            wrappers.facility_owners.filter({page_size: 100, "ordering": "name"})
            .success(function(data) {
                $scope.facility_owners = data.results;
            })
            .error(function(data) {
                $log.error(data);
            });

            wrappers.facility_types.filter({page_size: 100, "ordering": "name"})
            .success(function(data) {
                $scope.facility_types = data.results;
            })
            .error(function(data) {
                $log.error(data);
            });

            wrappers.wards.filter(
                {page_size: 500, "ordering": "name", "county": $scope.login_user.county})
            .success(function (data) {
                $scope.wards = data.results;
            })
            .error(function (data) {
                $log.error(data);
            });

            wrappers.towns.filter({page_size: 50000, "ordering": "name"})
            .success(function (data) {
                $scope.towns = data.results;
            })
            .error(function (data) {
                $log.error(data);
            });

            $scope.save = function () {};
        }]
    )

    .controller("mfl.facility_mgmt.controllers.facility_edit.contacts", [angular.noop])
    .controller("mfl.facility_mgmt.controllers.facility_edit.services", [angular.noop])
    .controller("mfl.facility_mgmt.controllers.facility_edit.units", [angular.noop])
    .controller("mfl.facility_mgmt.controllers.facility_edit.officers", [angular.noop])
    .controller("mfl.facility_mgmt.controllers.facility_edit.setup", [angular.noop])
;

})(angular);
<commit_msg>Add upgrade & downgrade context actions in facility detail view<commit_after>(function(angular){
    "use strict";

    angular.module("mfl.facility_mgmt.controllers", [
        "mfl.facility_mgmt.services",
        "mfl.auth.services"
    ])

    .controller("mfl.facility_mgmt.controllers.facility_list",
        ["$scope", function ($scope) {
            $scope.title = {
                "name": "Facility Management"
            };
        }]
    )

    .controller("mfl.facility_mgmt.controllers.facility_edit",
        ["$scope", "$log", "$stateParams", "mfl.facility_mgmt.services.wrappers",
        "mfl.auth.services.login",
        function ($scope, $log, $stateParams, wrappers, loginService) {
            $scope.title = {
                "name": "Edit Facility"
            };
            $scope.facility_id = $stateParams.facility_id;
            wrappers.facility_detail.get($scope.facility_id)
                .success(function(data){
                    $scope.facility = data;
                })
                .error(function (data) {
                    $log.error(data);
                });
            $scope.login_user = loginService.getUser();
            $scope.action = [
                {
                    func: "require-permission='facilities.add_facilityapproval' " +
                          "ng-if='!facility.is_approved || facility.has_edits' " +
                          "ui-sref='facilities.facility_edit({facility_id: facility.id})'",
                    class: "action-btn action-btn-md action-btn-primary",
                    icon: "fa-check",
                    tipmsg: "Approve"
                },
                {
                    func: "require-permission='facilities.change_facility' " +
                          "ng-if='login_user.is_national' " +
                          "ui-sref='facilities.facility_edit({facility_id: facility.id})'",
                    class: "action-btn action-btn-md action-btn-primary",
                    icon: "fa-upload",
                    tipmsg: "Publish"
                },
                {
                    func: "require-permission='facilities.add_facilityregulationstatus' " +
                          "ng-if='login_user.regulator' " +
                          "ui-sref='facilities.facility_edit({facility_id: facility.id})'",
                    class: "action-btn action-btn-md action-btn-primary",
                    icon: "fa-legal",
                    tipmsg: "Regulate"
                },
                {
                    func: "ui-sref='facilities.facility_edit({facility_id: facility.id})'",
                    class: "action-btn action-btn-md action-btn-primary",
                    icon: "fa-level-up",
                    tipmsg: "Upgrade"
                },
                {
                    func: "ui-sref='facilities.facility_edit({facility_id: facility.id})'",
                    class: "action-btn action-btn-md action-btn-primary",
                    icon: "fa-level-down",
                    tipmsg: "Downgrade"
                }
            ];
        }]
    )

    .controller("mfl.facility_mgmt.controllers.facility_edit.basic",
        ["$scope", "$log", "$stateParams", "mfl.facility_mgmt.services.wrappers",
        function ($scope, $log, $stateParams, wrappers) {
            wrappers.facility_owners.filter({page_size: 100, "ordering": "name"})
            .success(function(data) {
                $scope.facility_owners = data.results;
            })
            .error(function(data) {
                $log.error(data);
            });

            wrappers.facility_types.filter({page_size: 100, "ordering": "name"})
            .success(function(data) {
                $scope.facility_types = data.results;
            })
            .error(function(data) {
                $log.error(data);
            });

            wrappers.wards.filter(
                {page_size: 500, "ordering": "name", "county": $scope.login_user.county})
            .success(function (data) {
                $scope.wards = data.results;
            })
            .error(function (data) {
                $log.error(data);
            });

            wrappers.towns.filter({page_size: 50000, "ordering": "name"})
            .success(function (data) {
                $scope.towns = data.results;
            })
            .error(function (data) {
                $log.error(data);
            });

            $scope.save = function () {};
        }]
    )

    .controller("mfl.facility_mgmt.controllers.facility_edit.contacts", [angular.noop])
    .controller("mfl.facility_mgmt.controllers.facility_edit.services", [angular.noop])
    .controller("mfl.facility_mgmt.controllers.facility_edit.units", [angular.noop])
    .controller("mfl.facility_mgmt.controllers.facility_edit.officers", [angular.noop])
    .controller("mfl.facility_mgmt.controllers.facility_edit.setup", [angular.noop])
;

})(angular);
<|endoftext|>


<commit_before>define( [ "EmberData" ], function( DS ) {

	return DS.RESTSerializer.extend({
		modelNameFromPayloadKey: function() {
			return "githubReleases";
		},

		normalizePayload: function( payload ) {
			return {
				githubReleases: payload
			};
		}
	});

});
<commit_msg>Also use new Serializer API on ReleasesSerializer<commit_after>define( [ "EmberData" ], function( DS ) {

	return DS.RESTSerializer.extend({
		modelNameFromPayloadKey: function() {
			return "githubReleases";
		},

		normalizeResponse: function( store, primaryModelClass, payload, id, requestType ) {
			payload = {
				githubReleases: payload
			};

			return this._super( store, primaryModelClass, payload, id, requestType );
		}
	});

});
<|endoftext|>


<commit_before>import PlayerPrefab from '../prefabs/world/player.prefab';
import MovementDetectorHelper from '../helpers/movement_detector.helper';

const DIRECTION_LEFT = 'left',
DIRECTION_RIGHT = 'right',
DIRECTION_UP = 'up',
DIRECTION_DOWN = 'down';

class PlayerGroup extends Phaser.Group {

  constructor(game, name) {
    super(game, game.world, name);
    this.movementDetectorHelper = new MovementDetectorHelper();
    this.currentUser = game.di.sessionService.currentUser;
    this.currentPlayer = null;
    this.enableBody = true;
    this.ws = this.game.di.ws;
    this.joinWebSocketChannels();
  }

  findPlayer(userId) {
    for(var i in this.children) {
      var player = this.children[i];
      if(player.properties.user_id == userId)
        return player;
    }
  }

  joinWebSocketChannels() {
    this.movementSubscription = this.ws.joinChannel('MovementChannel',(data)=>{
      var player = this.findPlayer(data.user_id);
      if(player){
        player.movementDetectorHelper = player.movementDetectorHelper || new MovementDetectorHelper();
        if(this.movementDetectorHelper.validateTimestamp(data)) {
          var remoteX = parseInt(data.x, 10);
          var remoteY = parseInt(data.y, 10);
          var localX = parseInt(player.x, 10);
          var localY = parseInt(player.y, 10);
          if(Math.abs(remoteX - localX) == 20)
            player.x = remoteX;
          if(Math.abs(remoteY - localY) == 20)
            player.y = remoteY;
          player.changeMovement(data.direction, data.move);
          this.movementDetectorHelper.updateTimestamp(data);
        }
      }
    });
  }

  removePlayer(userId) {
    var player = this.findPlayer(userId);
    player.kill();
    this.children.pop(player);
  }

}

export default PlayerGroup;
<commit_msg>change condition<commit_after>import PlayerPrefab from '../prefabs/world/player.prefab';
import MovementDetectorHelper from '../helpers/movement_detector.helper';

const DIRECTION_LEFT = 'left',
DIRECTION_RIGHT = 'right',
DIRECTION_UP = 'up',
DIRECTION_DOWN = 'down';

class PlayerGroup extends Phaser.Group {

  constructor(game, name) {
    super(game, game.world, name);
    this.movementDetectorHelper = new MovementDetectorHelper();
    this.currentUser = game.di.sessionService.currentUser;
    this.currentPlayer = null;
    this.enableBody = true;
    this.ws = this.game.di.ws;
    this.joinWebSocketChannels();
  }

  findPlayer(userId) {
    for(var i in this.children) {
      var player = this.children[i];
      if(player.properties.user_id == userId)
        return player;
    }
  }

  joinWebSocketChannels() {
    this.movementSubscription = this.ws.joinChannel('MovementChannel',(data)=>{
      var player = this.findPlayer(data.user_id);
      if(player){
        player.movementDetectorHelper = player.movementDetectorHelper || new MovementDetectorHelper();
        if(this.movementDetectorHelper.validateTimestamp(data)) {
          var remoteX = parseInt(data.x, 10);
          var remoteY = parseInt(data.y, 10);
          var localX = parseInt(player.x, 10);
          var localY = parseInt(player.y, 10);
          if(Math.abs(remoteX - localX) > 20)
            player.x = remoteX;
          if(Math.abs(remoteY - localY) > 20)
            player.y = remoteY;
          player.changeMovement(data.direction, data.move);
          this.movementDetectorHelper.updateTimestamp(data);
        }
      }
    });
  }

  removePlayer(userId) {
    var player = this.findPlayer(userId);
    player.kill();
    this.children.pop(player);
  }

}

export default PlayerGroup;
<|endoftext|>


<commit_before>module.exports = {
  description: '',

  // locals: function(options) {
  //   // Return custom template variables here.
  //   return {
  //     foo: options.entity.options.foo
  //   };
  // }

  afterInstall: function(options) {
    var that = this;

    return this.addBowerPackageToProject('markdown').then(function() {
        return that.addBowerPackageToProject('to-markdown');
    });
  }
};
<commit_msg>Blueprint and bower package requirements.<commit_after>module.exports = {
  description: '',

  normalizeEntityName: function() {},

  // locals: function(options) {
  //   // Return custom template variables here.
  //   return {
  //     foo: options.entity.options.foo
  //   };
  // }

  afterInstall: function() {
    var that = this;

    return that.addBowerPackageToProject('markdown').then(function() {
      return that.addBowerPackageToProject('to-markdown');
    });
  }
};
<|endoftext|>


<commit_before>var Lang = A.Lang,
	now = Lang.now,

	AArray = A.Array;

var TaskManager = {
	clearInterval: function(id) {
		var instance = TaskManager;

		instance.unregister(true, id);
	},

	clearTimeout: function(id) {
		var instance = TaskManager;

		instance.unregister(false, id);
	},

	intervalTime: function(newInterval) {
		var instance = this;

		if (arguments.length) {
			instance._INTERVAL = newInterval;
		}

		return instance._INTERVAL;
	},

	isRepeatable: function(task) {
		var instance = TaskManager;

		return task.repeats;
	},

	setTimeout: function(fn, ms, context) {
		var instance = TaskManager;

		var args = AArray(arguments, 3, true);

		return instance.register(false, fn, ms, context, args);
	},

	setInterval: function(fn, ms, context) {
		var instance = TaskManager;

		var args = AArray(arguments, 3, true);

		return instance.register(true, fn, ms, context, args);
	},

	register: function(repeats, fn, ms, context, args) {
		var instance = TaskManager;

		var id = (++A.Env._uidx);

		args = args || [];

		args.unshift(fn, context);

		instance._TASKS[id] = instance._create(repeats, instance._getNearestInterval(ms), A.rbind.apply(A, args));

		instance._taskLength += 1;

		instance._lazyInit();

		return id;
	},

	run: function(task) {
		var instance = this;

		task.lastRunTime = now();

		return task.fn();
	},

	unregister: function(repeats, id) {
		var instance = TaskManager;

		var tasks = instance._TASKS;

		var task = tasks[id];

		instance._taskLength -= 1;

		instance._lazyDestroy();

		return task && task.repeats === repeats && delete tasks[id];
	},

	_create: function(repeats, ms, fn) {
		var instance = TaskManager;

		return {
			fn: fn,
			lastRunTime: now(),
			next: ms,
			repeats: repeats,
			timeout: ms
		};
	},

	_decrementNextRunTime: function(task) {
		var instance = TaskManager;

		return task.next -= now() - task.lastRunTime;
	},

	_getNearestInterval: function(num) {
		var instance = TaskManager;

		var interval = instance._INTERVAL;

		var delta = num % interval;

		var nearestInterval;

		if (delta < interval / 2) {
			nearestInterval = num - delta;
		}
		else {
			nearestInterval = num + interval - delta;
		}

		return nearestInterval;
	},

	_lazyDestroy: function() {
		var instance = TaskManager;

		if (instance._initialized && !instance._taskLength) {
			clearTimeout(instance._globalIntervalId);

			instance._initialized = false;
		}
	},

	_lazyInit: function() {
		var instance = TaskManager;

		if (!instance._initialized && instance._taskLength) {
			instance._lastRunTime = now();

			instance._globalIntervalId = setTimeout(instance._runner, instance._INTERVAL);

			instance._initialized = true;
		}
	},

	_loop: function(i, pendingTasks, length) {
		var instance = TaskManager;

		var interval = instance._INTERVAL;
		var tasks = instance._TASKS;

		for (var start = now(); i < length && now() - start < 50; i++) {
			var taskId = pendingTasks[i];
			var task = tasks[taskId];

			if (task && instance._decrementNextRunTime(task) < interval / 2) {
				instance.run(task);

				if (instance.isRepeatable(task)) {
					instance._resetNextRunTime(task);
				}
				else {
					instance.unregister(false, taskId);
				}
			}
		}

		if (instance._initialized) {
			if (i < length) {
				instance._globalIntervalId = setTimeout(instance._loop, 10);
			}
			else {
				instance._globalIntervalId = setTimeout(instance._runner, interval);
			}
		}
	},

	_runner: function() {
		var instance = TaskManager;

		var i = 0;
		var pendingTasks = A.Object.keys(instance._TASKS);
		var length = pendingTasks.length;

		instance._loop(i, pendingTasks, length);
	},

	_resetNextRunTime: function(task) {
		var instance = TaskManager;

		return task.next = task.timeout;
	},

	_INTERVAL: 50,
	_TASKS: {},

	_lastRunTime: 0,
	_globalIntervalId: 0,
	_initialized: false,
	_taskLength: 0
};

A.clearInterval = TaskManager.clearInterval;
A.clearTimeout = TaskManager.clearTimeout;
A.setInterval = TaskManager.setInterval;
A.setTimeout = TaskManager.setTimeout;

A.TaskManager = TaskManager;<commit_msg>AUI-492 - TaskManager will not initialize if clearInterval is called before any tasks are added<commit_after>var Lang = A.Lang,
	now = Lang.now,

	AArray = A.Array;

var TaskManager = {
	clearInterval: function(id) {
		var instance = TaskManager;

		instance.unregister(true, id);
	},

	clearTimeout: function(id) {
		var instance = TaskManager;

		instance.unregister(false, id);
	},

	intervalTime: function(newInterval) {
		var instance = this;

		if (arguments.length) {
			instance._INTERVAL = newInterval;
		}

		return instance._INTERVAL;
	},

	isRepeatable: function(task) {
		var instance = TaskManager;

		return task.repeats;
	},

	setTimeout: function(fn, ms, context) {
		var instance = TaskManager;

		var args = AArray(arguments, 3, true);

		return instance.register(false, fn, ms, context, args);
	},

	setInterval: function(fn, ms, context) {
		var instance = TaskManager;

		var args = AArray(arguments, 3, true);

		return instance.register(true, fn, ms, context, args);
	},

	register: function(repeats, fn, ms, context, args) {
		var instance = TaskManager;

		var id = (++A.Env._uidx);

		args = args || [];

		args.unshift(fn, context);

		instance._TASKS[id] = instance._create(repeats, instance._getNearestInterval(ms), A.rbind.apply(A, args));

		instance._taskLength += 1;

		instance._lazyInit();

		return id;
	},

	run: function(task) {
		var instance = this;

		task.lastRunTime = now();

		return task.fn();
	},

	unregister: function(repeats, id) {
		var instance = TaskManager;

		var tasks = instance._TASKS;

		var task = tasks[id];

		if (instance._taskLength) {
			instance._taskLength -= 1;
		}

		instance._lazyDestroy();

		return task && task.repeats === repeats && delete tasks[id];
	},

	_create: function(repeats, ms, fn) {
		var instance = TaskManager;

		return {
			fn: fn,
			lastRunTime: now(),
			next: ms,
			repeats: repeats,
			timeout: ms
		};
	},

	_decrementNextRunTime: function(task) {
		var instance = TaskManager;

		return task.next -= now() - task.lastRunTime;
	},

	_getNearestInterval: function(num) {
		var instance = TaskManager;

		var interval = instance._INTERVAL;

		var delta = num % interval;

		var nearestInterval;

		if (delta < interval / 2) {
			nearestInterval = num - delta;
		}
		else {
			nearestInterval = num + interval - delta;
		}

		return nearestInterval;
	},

	_lazyDestroy: function() {
		var instance = TaskManager;

		if (instance._initialized && !instance._taskLength) {
			clearTimeout(instance._globalIntervalId);

			instance._initialized = false;
		}
	},

	_lazyInit: function() {
		var instance = TaskManager;

		if (!instance._initialized && instance._taskLength) {
			instance._lastRunTime = now();

			instance._globalIntervalId = setTimeout(instance._runner, instance._INTERVAL);

			instance._initialized = true;
		}
	},

	_loop: function(i, pendingTasks, length) {
		var instance = TaskManager;

		var interval = instance._INTERVAL;
		var tasks = instance._TASKS;

		for (var start = now(); i < length && now() - start < 50; i++) {
			var taskId = pendingTasks[i];
			var task = tasks[taskId];

			if (task && instance._decrementNextRunTime(task) < interval / 2) {
				instance.run(task);

				if (instance.isRepeatable(task)) {
					instance._resetNextRunTime(task);
				}
				else {
					instance.unregister(false, taskId);
				}
			}
		}

		if (instance._initialized) {
			if (i < length) {
				instance._globalIntervalId = setTimeout(instance._loop, 10);
			}
			else {
				instance._globalIntervalId = setTimeout(instance._runner, interval);
			}
		}
	},

	_runner: function() {
		var instance = TaskManager;

		var i = 0;
		var pendingTasks = A.Object.keys(instance._TASKS);
		var length = pendingTasks.length;

		instance._loop(i, pendingTasks, length);
	},

	_resetNextRunTime: function(task) {
		var instance = TaskManager;

		return task.next = task.timeout;
	},

	_INTERVAL: 50,
	_TASKS: {},

	_lastRunTime: 0,
	_globalIntervalId: 0,
	_initialized: false,
	_taskLength: 0
};

A.clearInterval = TaskManager.clearInterval;
A.clearTimeout = TaskManager.clearTimeout;
A.setInterval = TaskManager.setInterval;
A.setTimeout = TaskManager.setTimeout;

A.TaskManager = TaskManager;<|endoftext|>


<commit_before>"use strict";

module.exports = function(nce){
  if(!nce) throw new Error("You have to specify the nce object");

//# Mandantory Setup:
  var ext = nce.createExtension({package: require("./package.json")});

  ext.on("install", function(event){ // set options, but don't run or make available in nce
    //# Seting extension-config:
    ext.config.route = ext.config.route || "/"+ext.name;
    /* nce-mongoose-store
    ext.config.modelName = ext.config.modelName || ext.name;
    */
    /* nce-winston
    ext.config.logger = ext.config.logger || {};
    */

    //# Declarations and settings:
    /* nce-winston
    ext.logger = nce.getExtension("winston").createLogger(ext.name, ext.config.logger);
    */

    /* nce-mongoose-store
    var store = nce.getExtension("mongoose-store");
    var schema = store.createSchema({});
    schema.methods.xy = function(){};
    schema.statics.xy = function(cb){cb();};
    ext.model = store.createModel(ext.config.modelName, schema);
    */
  });

  ext.on("uninstall", function(event){ // undo installation
    //# Undeclare:
    /* nce-winston
    nce.getExtension("winston").removeLogger(ext.name);
    */
    /* nce-mongoose-store
    store.removeModel(ext.config.modelName);
    delete ext.model;
    */
  });

  ext.on("activate", function(event){ // don't set options, just run, make available in nce or register.
	  if(nce.requestMiddlewares.indexOf(router) === -1) {
		  nce.requestMiddlewares.push(router);
	  }
  });

  ext.on("deactivate", function(event){ // undo activation
	  if(nce.requestMiddlewares.indexOf(router) !== -1) {
		  nce.requestMiddlewares.splice(nce.requestMiddlewares.indexOf(router), 1);
	  }
  });

//# Private declarations:
  var router = function(req, res, next){
    var backend = nce.getExtension("backend");
    if(req.url.substr(0, backend.config.route.length+ext.config.subRoute.length) === backend.config.route+ext.config.subRoute) {
      try{throw new Error("Dummy extension");} catch(e){console.error(e)};
    }

    return next();
  };

//# Public declarations and exports:
  ext.dummy = function(opts, cb){
    // a dummy method here...
  }

  return ext;
}<commit_msg>Delete logger on uninstallation<commit_after>"use strict";

module.exports = function(nce){
  if(!nce) throw new Error("You have to specify the nce object");

//# Mandantory Setup:
  var ext = nce.createExtension({package: require("./package.json")});

  ext.on("install", function(event){ // set options, but don't run or make available in nce
    //# Seting extension-config:
    ext.config.route = ext.config.route || "/"+ext.name;
    /* nce-mongoose-store
    ext.config.modelName = ext.config.modelName || ext.name;
    */
    /* nce-winston
    ext.config.logger = ext.config.logger || {};
    */

    //# Declarations and settings:
    /* nce-winston
    ext.logger = nce.getExtension("winston").createLogger(ext.name, ext.config.logger);
    */

    /* nce-mongoose-store
    var store = nce.getExtension("mongoose-store");
    var schema = store.createSchema({});
    schema.methods.xy = function(){};
    schema.statics.xy = function(cb){cb();};
    ext.model = store.createModel(ext.config.modelName, schema);
    */
  });

  ext.on("uninstall", function(event){ // undo installation
    //# Undeclare:
    /* nce-winston
    nce.getExtension("winston").removeLogger(ext.name);
    delete ext.logger;
    */
    /* nce-mongoose-store
    store.removeModel(ext.config.modelName);
    delete ext.model;
    */
  });

  ext.on("activate", function(event){ // don't set options, just run, make available in nce or register.
	  if(nce.requestMiddlewares.indexOf(router) === -1) {
		  nce.requestMiddlewares.push(router);
	  }
  });

  ext.on("deactivate", function(event){ // undo activation
	  if(nce.requestMiddlewares.indexOf(router) !== -1) {
		  nce.requestMiddlewares.splice(nce.requestMiddlewares.indexOf(router), 1);
	  }
  });

//# Private declarations:
  var router = function(req, res, next){
    var backend = nce.getExtension("backend");
    if(req.url.substr(0, backend.config.route.length+ext.config.subRoute.length) === backend.config.route+ext.config.subRoute) {
      try{throw new Error("Dummy extension");} catch(e){console.error(e)};
    }

    return next();
  };

//# Public declarations and exports:
  ext.dummy = function(opts, cb){
    // a dummy method here...
  }

  return ext;
}<|endoftext|>


<commit_before>import { withPluginApi } from 'discourse/lib/plugin-api';

// resetBumpClicked is run when the "Reset Bump To Here" button is clicked.
function resetBumpClicked()
{
	alert('The button was clicked!');
}

// resetBumpButtonDecorateCallback sets the "Reset Bump To Here" buttons icon and label, and gives it an internal name.
// Note that this callback is not called until the menu is shown, and is called each time it is shown. The callback is
// stored but not called during initialization.
function resetBumpButtonDecorateCallback(dec)
{
	// buttonAttr seems to need to be a "var" local variable, or an inline argument
	// to the function (most plugin code uses the latter, but I'm splitting it out
	// to make things more simple and explicit). If it's a non-var global variable
	// then the menu breaks or has nothing added to it. I am not sure why. I guess
	// the map that is passed in has something destructive done to it so it only
	// works the first time it is used, or something.
	var buttonAttr =
	{
		icon: 'calendar-times-o',			// Find icon names here: http://fontawesome.io/icons/ Remove an "fa" prefix.
		label: 'reset_bump.button_label',	// Name of translated string from (if English): config/locales/client.en.yml
		action: 'actionResetBump'			// Internal name, used to refer to the button in subsequent code.
	}

	// dec is a DecoratorHelper object passed in from Discourse when it calls us.
	// dec.attach adds a new button, in this case with type 'post-admin-menu-button' and the attributes above.
	return dec.attach('post-admin-menu-button', buttonAttr);
}

function apiInitCallback(api)
{
	// Add a new button to the bottom of the Post Admin Menu. resetBumpButtonDecorateCallback (above) is called to do this.
	// resetBumpButtonDecorateCallback gives the new button the internal name "actionResetBump".
	api.decorateWidget('post-admin-menu:after', resetBumpButtonDecorateCallback);
	// Using the internal name "actionResetBump" to find the new button again, make it so clicking the button calls resetBumpClicked.
	api.attachWidgetAction('post-admin-menu', 'actionResetBump', resetBumpClicked);
}

// Discourse will call our initializer by importing our defualt object and calling the initialize function inside it.
// It does this for all .js.es6 files in the initializers folder this one is in.
export default
{
	// The name attribute has to be unique. Beyond that I don't know what it is used for.
	name: 'init-reset-bump',

	// Discourse will call this when the client side starts.
	initialize(container)
	{
		// If the plugin is disabled or the user isn't 'staff', do nothing.
		// This only hides the button from people who aren't allowed to used it.
		// We need to enforce the staff check on the server side as well, since nothing
		// stops a client faking the ajax requests even if the button is hidden.
		// Since we check this at initialization, if the plugin is enabled or disabled
		// it won't take effect in someone's existing session until they reload js app/page.
		// That's normal and fine; the ability to disable plugins is really just there in case
		// they start causing problems and need to be quickly turned off without a server restart.
		const siteSettings = container.lookup('site-settings:main');
		const currentUser = container.lookup('current-user:main');
		if (!siteSettings.reset_bump_enabled || !currentUser || !currentUser.staff)
		{
			return;
		}

		// withPluginApi is imported from Discourse itself, and provides a versioned plugin API
		// which should help future-proof plugins against API changes, or at least make them harmless
		// if the API has to be broken. 0.7 is the current API level as of 5/Feb/2017.
		// We pass withPluginApi our callback function, which is given the api object to set things up.
		// Our callback may not be called at all if the version we are requesting is no longer supported one day.
		// See: https://meta.discourse.org/t/a-new-versioned-api-for-client-side-plugins/40051
		// See: https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/lib/plugin-api.js.es6
		withPluginApi('0.7', apiInitCallback);
	}
};
<commit_msg>Tidy up some basics.<commit_after>import { withPluginApi } from 'discourse/lib/plugin-api';

// resetBumpClicked is run when the "Reset Bump To Here" button is clicked.
function resetBumpClicked()
{
	alert('The button was clicked!');
}

// resetBumpButtonDecorateCallback sets the "Reset Bump To Here" button's icon, label, and internal name.
// This callback is not called until the menu is shown, and is called each time it is shown.
// The callback is stored but not called during initialization.
function resetBumpButtonDecorateCallback(dec)
{
	// buttonAttr seems to need to be a var or const local variable, or an inline argument
	// to the function. (Most plugin code uses an inline argument, but I'm splitting things
	// out to make everything more simple and explicit). If buttonAttr iss declared without
	// "var" or "const" (or maybe "let") then the menu breaks or has nothing added to it.
	// I am not sure why. Something to do with how it is stored for later use, I guess.
	const buttonAttr =
	{
		icon: 'calendar-times-o',			// Find icon names here: http://fontawesome.io/icons/
		label: 'reset_bump.button_label',	// Name of string in e.g. config/locales/client.en.yml
		action: 'actionResetBump'			// Internal name, used to refer to the button below.
	}

	// dec is a DecoratorHelper object passed in from Discourse when it calls us.
	// We use dec.attach to add a new button of type 'post-admin-menu-button' and the attributes above.
	return dec.attach('post-admin-menu-button', buttonAttr);
}

function apiInitCallback(api)
{
	// If the plugin is disabled, do nothing.
	// Since we check this at initialization, if the plugin is enabled or disabled
	// it won't take effect in someone's existing session until they reload js app/page.
	// That's normal and fine; the ability to disable plugins is really just there in case
	// they start causing problems and need to be quickly turned off without a server restart.
	const siteSettings = api.container.lookup('site-settings:main');

	if (!siteSettings.reset_bump_enabled)
	{
		return;
	}

	// If there is no user, or they are not "staff", do nothing.
	// This only hides the button from people who aren't allowed to used it.
	// We need to enforce the staff check on the server side as well, since nothing
	// stops a client faking the ajax requests even if the button is hidden.
	const currentUser = api.getCurrentUser();

	if (!currentUser || !currentUser.staff)
	{
		return;
	}

	// Add a new button to the bottom of the Post Admin Menu. resetBumpButtonDecorateCallback (above) is
	// called to do this, and will give the new button the internal name "actionResetBump".
	api.decorateWidget('post-admin-menu:after', resetBumpButtonDecorateCallback);

	// Find the button again, using the name we gave it, and make it run resetBumpClicked when clicked.
	api.attachWidgetAction('post-admin-menu', 'actionResetBump', resetBumpClicked);
}

// Discourse will call our initializer by importing our defualt object and calling our initialize function.
// It does this for all .js.es6 files in the initializers folder.
export default
{
	// The name here has to be unique. Not sure what it's used for exactly.
	name: 'init-reset-bump',

	// Discourse will call initialize when the client side starts.
	// Plugins for older versions also take a "container" argument but it's also given to us
	// via the "api" object passed to our apiInitCallback callback, so we ignore it here.
	initialize()
	{
		// withPluginApi is imported from Discourse itself, and provides a versioned plugin API
		// which should help future-proof plugins against API changes, or at least make them harmless
		// if the API has to be broken. 0.7 is the current API level as of 5/Feb/2017.
		// We pass withPluginApi our callback function, which is given the api object to set things up.
		// Our callback may not be called at all if the version we are requesting becomes unsupported.
		// See: https://meta.discourse.org/t/a-new-versioned-api-for-client-side-plugins/40051
		// See: https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/lib/plugin-api.js.es6
		withPluginApi('0.7', apiInitCallback);
	}
};
<|endoftext|>


<commit_before>/**
 * Dashboard PageSpeed Widget component.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import Tab from '@material/react-tab';
import TabBar from '@material/react-tab-bar';

/**
 * WordPress dependencies
 */
import { Fragment, useCallback, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import DeviceSizeTabBar from '../../../components/DeviceSizeTabBar';
import ProgressBar from '../../../components/progress-bar';
import Layout from '../../../components/layout/layout';
import LabReportMetrics from './LabReportMetrics';
import FieldReportMetrics from './FieldReportMetrics';
import { STORE_NAME as CORE_FORMS } from '../../../googlesitekit/datastore/forms/constants';
import { STORE_NAME as CORE_SITE } from '../../../googlesitekit/datastore/site/constants';
import {
	STORE_NAME,
	STRATEGY_MOBILE,
	STRATEGY_DESKTOP,
	DATA_SRC_FIELD,
	DATA_SRC_LAB,
	FORM_DASH_WIDGET,
} from '../datastore/constants';

const { useSelect, useDispatch } = Data;

export default function DashboardPageSpeed() {
	// TODO: replace global with selector.
	const permalink = global._googlesitekitLegacyData.permaLink;
	const referenceURL = useSelect( ( select ) => select( CORE_SITE ).getReferenceSiteURL() );
	const url = permalink || referenceURL;
	const reportMobile = useSelect( ( select ) => select( STORE_NAME ).getReport( url, STRATEGY_MOBILE ) );
	const reportDesktop = useSelect( ( select ) => select( STORE_NAME ).getReport( url, STRATEGY_DESKTOP ) );
	const strategy = useSelect( ( select ) => select( CORE_FORMS ).getValue( FORM_DASH_WIDGET, 'strategy' ) ) || STRATEGY_MOBILE;
	const dataSrc = useSelect( ( select ) => select( CORE_FORMS ).getValue( FORM_DASH_WIDGET, 'dataSrc' ) );

	const { setValues } = useDispatch( CORE_FORMS );
	const setStrategyMobile = useCallback( () => setValues( FORM_DASH_WIDGET, { strategy: STRATEGY_MOBILE } ), [] );
	const setStrategyDesktop = useCallback( () => setValues( FORM_DASH_WIDGET, { strategy: STRATEGY_DESKTOP } ), [] );
	const setDataSrcField = useCallback( () => setValues( FORM_DASH_WIDGET, { dataSrc: DATA_SRC_FIELD } ), [] );
	const setDataSrcLab = useCallback( () => setValues( FORM_DASH_WIDGET, { dataSrc: DATA_SRC_LAB } ), [] );

	// Update the active tab for "In the Lab" or "In The Field".
	const updateActiveTab = useCallback( ( dataSrcIndex ) => {
		if ( dataSrcIndex === 0 ) {
			setDataSrcLab();
		} else {
			setDataSrcField();
		}
	}, [] );
	// Update the active tab for "mobile" or "desktop".
	const updateActiveDeviceSize = useCallback( ( strategyIndex ) => {
		if ( strategyIndex === 1 ) {
			setStrategyDesktop();
		} else {
			setStrategyMobile();
		}
	}, [] );

	// Set the default data source based on report data.
	useEffect( () => {
		if ( ! reportMobile || ! reportDesktop ) {
			return;
		}
		if ( reportMobile?.loadingExperience?.metrics && reportDesktop?.loadingExperience?.metrics ) {
			setDataSrcField();
		} else {
			setDataSrcLab();
		}
	}, [ reportMobile, reportDesktop ] );

	if ( ! reportMobile || ! reportDesktop || ! dataSrc ) {
		return <ProgressBar />;
	}

	const reportData = strategy === STRATEGY_MOBILE ? reportMobile : reportDesktop;

	return (
		<Fragment>
			<Layout className="googlesitekit-pagespeed-widget">

						<TabBar
							activeIndex={ dataSrc === DATA_SRC_FIELD ? 1 : 0 }
							handleActiveIndexUpdate={ updateActiveTab }
						>
							<Tab aria-label="in the lab">
								{ __( 'In the Lab', 'google-site-kit' ) }
							</Tab>
							<Tab aria-label="in the field">
								{ __( 'In the Field', 'google-site-kit' ) }
							</Tab>
						</TabBar>

						<DeviceSizeTabBar
							activeIndex={ strategy === STRATEGY_DESKTOP ? 1 : 0 }
							handleDeviceSizeUpdate={ updateActiveDeviceSize }
						/>

					{ dataSrc === DATA_SRC_LAB && <LabReportMetrics data={ reportData } /> }
					{ dataSrc === DATA_SRC_FIELD && <FieldReportMetrics data={ reportData } /> }

			</Layout>
		</Fragment>
	);
}
<commit_msg>Remove unnecessary wrapping Fragment.<commit_after>/**
 * Dashboard PageSpeed Widget component.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import Tab from '@material/react-tab';
import TabBar from '@material/react-tab-bar';

/**
 * WordPress dependencies
 */
import { useCallback, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import DeviceSizeTabBar from '../../../components/DeviceSizeTabBar';
import ProgressBar from '../../../components/progress-bar';
import Layout from '../../../components/layout/layout';
import LabReportMetrics from './LabReportMetrics';
import FieldReportMetrics from './FieldReportMetrics';
import { STORE_NAME as CORE_FORMS } from '../../../googlesitekit/datastore/forms/constants';
import { STORE_NAME as CORE_SITE } from '../../../googlesitekit/datastore/site/constants';
import {
	STORE_NAME,
	STRATEGY_MOBILE,
	STRATEGY_DESKTOP,
	DATA_SRC_FIELD,
	DATA_SRC_LAB,
	FORM_DASH_WIDGET,
} from '../datastore/constants';

const { useSelect, useDispatch } = Data;

export default function DashboardPageSpeed() {
	// TODO: replace global with selector.
	const permalink = global._googlesitekitLegacyData.permaLink;
	const referenceURL = useSelect( ( select ) => select( CORE_SITE ).getReferenceSiteURL() );
	const url = permalink || referenceURL;
	const reportMobile = useSelect( ( select ) => select( STORE_NAME ).getReport( url, STRATEGY_MOBILE ) );
	const reportDesktop = useSelect( ( select ) => select( STORE_NAME ).getReport( url, STRATEGY_DESKTOP ) );
	const strategy = useSelect( ( select ) => select( CORE_FORMS ).getValue( FORM_DASH_WIDGET, 'strategy' ) ) || STRATEGY_MOBILE;
	const dataSrc = useSelect( ( select ) => select( CORE_FORMS ).getValue( FORM_DASH_WIDGET, 'dataSrc' ) );

	const { setValues } = useDispatch( CORE_FORMS );
	const setStrategyMobile = useCallback( () => setValues( FORM_DASH_WIDGET, { strategy: STRATEGY_MOBILE } ), [] );
	const setStrategyDesktop = useCallback( () => setValues( FORM_DASH_WIDGET, { strategy: STRATEGY_DESKTOP } ), [] );
	const setDataSrcField = useCallback( () => setValues( FORM_DASH_WIDGET, { dataSrc: DATA_SRC_FIELD } ), [] );
	const setDataSrcLab = useCallback( () => setValues( FORM_DASH_WIDGET, { dataSrc: DATA_SRC_LAB } ), [] );

	// Update the active tab for "In the Lab" or "In The Field".
	const updateActiveTab = useCallback( ( dataSrcIndex ) => {
		if ( dataSrcIndex === 0 ) {
			setDataSrcLab();
		} else {
			setDataSrcField();
		}
	}, [] );
	// Update the active tab for "mobile" or "desktop".
	const updateActiveDeviceSize = useCallback( ( strategyIndex ) => {
		if ( strategyIndex === 1 ) {
			setStrategyDesktop();
		} else {
			setStrategyMobile();
		}
	}, [] );

	// Set the default data source based on report data.
	useEffect( () => {
		if ( ! reportMobile || ! reportDesktop ) {
			return;
		}
		if ( reportMobile?.loadingExperience?.metrics && reportDesktop?.loadingExperience?.metrics ) {
			setDataSrcField();
		} else {
			setDataSrcLab();
		}
	}, [ reportMobile, reportDesktop ] );

	if ( ! reportMobile || ! reportDesktop || ! dataSrc ) {
		return <ProgressBar />;
	}

	const reportData = strategy === STRATEGY_MOBILE ? reportMobile : reportDesktop;

	return (
		<Layout className="googlesitekit-pagespeed-widget">

					<TabBar
						activeIndex={ dataSrc === DATA_SRC_FIELD ? 1 : 0 }
						handleActiveIndexUpdate={ updateActiveTab }
					>
						<Tab aria-label="in the lab">
							{ __( 'In the Lab', 'google-site-kit' ) }
						</Tab>
						<Tab aria-label="in the field">
							{ __( 'In the Field', 'google-site-kit' ) }
						</Tab>
					</TabBar>

					<DeviceSizeTabBar
						activeIndex={ strategy === STRATEGY_DESKTOP ? 1 : 0 }
						handleDeviceSizeUpdate={ updateActiveDeviceSize }
					/>

				{ dataSrc === DATA_SRC_LAB && <LabReportMetrics data={ reportData } /> }
				{ dataSrc === DATA_SRC_FIELD && <FieldReportMetrics data={ reportData } /> }

		</Layout>
	);
}
<|endoftext|>


<commit_before>var moment = require('moment');
var _ = require('lodash');

module.exports = {
    birth: {
        src: 'dateDeNaissance',
        fn: function(dateDeNaissance) {
            return moment(dateDeNaissance).format('YYYY-MM-DD');
        }
    },
    age: {
        src: 'dateDeNaissance',
        fn: function (dateDeNaissance, individu, situation) {
            return moment(situation.dateDeValeur).diff(moment(dateDeNaissance), 'years');
        }
    },
    age_en_mois: {
        src: 'dateDeNaissance',
        fn: function (dateDeNaissance, individu, situation) {
            return moment(situation.dateDeValeur).diff(moment(dateDeNaissance), 'months');
        }
    },
    statmarit: {
        src: 'statutMarital',
        values: {
            seul: 2,
            mariage: 1,
            pacs: 5,
            relation_libre: 2
        }
    },
    id: '_id',
    enceinte: 'enceinte',
    ass_precondition_remplie: 'assPreconditionRemplie',
    activite: {
        src: 'situationsPro',
        fn: function(value) {
            var returnValue;
            _.forEach({
                demandeur_emploi: 1,
                etudiant: 2,
                retraite: 3
            }, function(v, k) {
                if (_.find(value, { situation: k })) returnValue = v;
            });
            return returnValue;
        }
    },
    invalide: {
        src: 'situationsPro',
        fn: function(situationsPro) {
            return !!_.find(situationsPro, { situation: 'handicap' }) ? 1 : 0;
        }
    },
    taux_invalidite: {
        src: 'tauxInvalidite',
        values: {
            nul: 0,
            moins50: 30,
            moins80: 70,
            plus80: 90
        }
    },
    inapte_travail: {
        src: 'situationsPro',
        fn: function(situationsPro) {
            return !!_.find(situationsPro, { situation: 'inapte_travail' }) ? 1 : 0;
        }
    },
    etu: {
        src: 'situationsPro',
        fn: function(situationsPro) {
            return !!_.find(situationsPro, { situation: 'etudiant' }) ? 1 : 0;
        }
    },
    boursier: 'boursier',
    scolarite: {
        fn: function(individu) {
            var values = {
                'inconnue': 0,
                'college': 1,
                'lycee': 2
            };
            return values[individu.scolarite];
        }
    },
    coloc: {
        fn: function(individu, situation) {
            var test = individu.role === 'demandeur' && 'locataire' === situation.logement.type && situation.logement.colocation;
            return test ? 1 : null;
        }
    },
    logement_chambre: {
        fn: function(individu, situation) {
            var test = individu.role === 'demandeur' && 'locataire' === situation.logement.type && situation.logement.isChambre;
            return test ? 1 : null;
        }
    },
    alt: 'gardeAlternee',

    /* Revenus du patrimoine */
    interets_epargne_sur_livrets: {
        src: 'epargneSurLivret',
        fn: function(value) {
            return {
                '2012-01': 0.01 * value || 0
            };
        }
    },
    epargne_non_remuneree: {
        src: 'epargneSansRevenus',
        fn: function (value) {
            return {
                '2012-01': value || 0
            };
        }
    },
    valeur_locative_immo_non_loue: {
        src: 'valeurLocativeImmoNonLoue',
        fn: function (value) {
            return {
                '2012-01': value || 0
            };
        }
    },
    valeur_locative_terrains_non_loue: {
        src: 'valeurLocativeTerrainNonLoue',
        fn: function (value) {
            return {
                '2012-01': value || 0
            };
        }
    },

    /* Activités non-salarié */
    tns_autres_revenus: 'autresRevenusTns',
    tns_employe: 'autresRevenusTnsEmployes',
    tns_autres_revenus_chiffre_affaires : 'caAutresRevenusTns',
    tns_autres_revenus_type_activite: 'autresRevenusTnsActiviteType',
    tns_auto_entrepreneur_chiffre_affaires: 'caAutoEntrepreneur',
    tns_micro_entreprise_chiffre_affaires: 'caMicroEntreprise',
    tns_auto_entrepreneur_type_activite: 'autoEntrepreneurActiviteType',
    tns_micro_entreprise_type_activite: 'microEntrepriseActiviteType',
    tns_benefice_exploitant_agricole: 'revenusAgricolesTns'
};
<commit_msg>Change taux_invalidite format<commit_after>var moment = require('moment');
var _ = require('lodash');

module.exports = {
    birth: {
        src: 'dateDeNaissance',
        fn: function(dateDeNaissance) {
            return moment(dateDeNaissance).format('YYYY-MM-DD');
        }
    },
    age: {
        src: 'dateDeNaissance',
        fn: function (dateDeNaissance, individu, situation) {
            return moment(situation.dateDeValeur).diff(moment(dateDeNaissance), 'years');
        }
    },
    age_en_mois: {
        src: 'dateDeNaissance',
        fn: function (dateDeNaissance, individu, situation) {
            return moment(situation.dateDeValeur).diff(moment(dateDeNaissance), 'months');
        }
    },
    statmarit: {
        src: 'statutMarital',
        values: {
            seul: 2,
            mariage: 1,
            pacs: 5,
            relation_libre: 2
        }
    },
    id: '_id',
    enceinte: 'enceinte',
    ass_precondition_remplie: 'assPreconditionRemplie',
    activite: {
        src: 'situationsPro',
        fn: function(value) {
            var returnValue;
            _.forEach({
                demandeur_emploi: 1,
                etudiant: 2,
                retraite: 3
            }, function(v, k) {
                if (_.find(value, { situation: k })) returnValue = v;
            });
            return returnValue;
        }
    },
    invalide: {
        src: 'situationsPro',
        fn: function(situationsPro) {
            return !!_.find(situationsPro, { situation: 'handicap' }) ? 1 : 0;
        }
    },
    taux_invalidite: {
        src: 'tauxInvalidite',
        values: {
            nul: 0,
            moins50: 0.3,
            moins80: 0.7,
            plus80: 0.9
        }
    },
    inapte_travail: {
        src: 'situationsPro',
        fn: function(situationsPro) {
            return !!_.find(situationsPro, { situation: 'inapte_travail' }) ? 1 : 0;
        }
    },
    etu: {
        src: 'situationsPro',
        fn: function(situationsPro) {
            return !!_.find(situationsPro, { situation: 'etudiant' }) ? 1 : 0;
        }
    },
    boursier: 'boursier',
    scolarite: {
        fn: function(individu) {
            var values = {
                'inconnue': 0,
                'college': 1,
                'lycee': 2
            };
            return values[individu.scolarite];
        }
    },
    coloc: {
        fn: function(individu, situation) {
            var test = individu.role === 'demandeur' && 'locataire' === situation.logement.type && situation.logement.colocation;
            return test ? 1 : null;
        }
    },
    logement_chambre: {
        fn: function(individu, situation) {
            var test = individu.role === 'demandeur' && 'locataire' === situation.logement.type && situation.logement.isChambre;
            return test ? 1 : null;
        }
    },
    alt: 'gardeAlternee',

    /* Revenus du patrimoine */
    interets_epargne_sur_livrets: {
        src: 'epargneSurLivret',
        fn: function(value) {
            return {
                '2012-01': 0.01 * value || 0
            };
        }
    },
    epargne_non_remuneree: {
        src: 'epargneSansRevenus',
        fn: function (value) {
            return {
                '2012-01': value || 0
            };
        }
    },
    valeur_locative_immo_non_loue: {
        src: 'valeurLocativeImmoNonLoue',
        fn: function (value) {
            return {
                '2012-01': value || 0
            };
        }
    },
    valeur_locative_terrains_non_loue: {
        src: 'valeurLocativeTerrainNonLoue',
        fn: function (value) {
            return {
                '2012-01': value || 0
            };
        }
    },

    /* Activités non-salarié */
    tns_autres_revenus: 'autresRevenusTns',
    tns_employe: 'autresRevenusTnsEmployes',
    tns_autres_revenus_chiffre_affaires : 'caAutresRevenusTns',
    tns_autres_revenus_type_activite: 'autresRevenusTnsActiviteType',
    tns_auto_entrepreneur_chiffre_affaires: 'caAutoEntrepreneur',
    tns_micro_entreprise_chiffre_affaires: 'caMicroEntreprise',
    tns_auto_entrepreneur_type_activite: 'autoEntrepreneurActiviteType',
    tns_micro_entreprise_type_activite: 'microEntrepriseActiviteType',
    tns_benefice_exploitant_agricole: 'revenusAgricolesTns'
};
<|endoftext|>


<commit_before>( function( pub ) {
    var parseToStructure = function( data ) {
        var parsedData = {}, currentSource, currentTarget, returnData = [], path;
        data.forEach( function( d ) {
            currentSource = d.source; currentTarget = d.target;

            if ( currentSource.id && currentSource.id !== 'no:match' && !parsedData[ currentSource.id ] ) {
                path = currentSource.path.split( ' | ' ).join( '.' );
                parsedData[ currentSource.id ] = { name: path, path: path, eolId: currentSource.id, preys: [] };
            }

            if ( parsedData[ currentSource.id ] && currentTarget.id !== 'no:match' ) {
                path = currentTarget.path.split( ' | ' ).join( '.' );
                parsedData[ currentSource.id ].preys.push( path );
            }
        } );

        for ( var id in parsedData ) {
            if ( parsedData.hasOwnProperty( id ) ) {
                returnData.push( parsedData[ id ] );
            }
        }

        return returnData;
    };

    var _buildBundles = function( json, canvasDimension ) {
        var diameter = canvasDimension.height * 2,
            radius = diameter / 2,
            innerRadius = radius - 120;

        var cluster = d3.layout.cluster()
            .size([360, innerRadius])
            .sort(function(a, b) { return d3.ascending(a.key, b.key); })
            .value(function(d) { return d.size; });

        var bundle = d3.layout.bundle();

        var line = d3.svg.line.radial()
            .interpolate("bundle")
            .tension(0.85)
            .radius(function(d) { return d.y; })
            .angle(function(d) { return d.x / 180 * Math.PI; });

        var svg = d3.select("#bundle-container").append("svg")
            .attr( 'viewBox', '0 0 ' + canvasDimension.width * 2 + ' ' + canvasDimension.height * 2 )
//            .attr("width", diameter)
//            .attr("height", diameter)
            .append("g")
            .attr("transform", "translate(" + canvasDimension.width + "," + radius + ")");

        var link = svg.append("g").selectAll(".bundl-link"),
            node = svg.append("g").selectAll(".bundl-node");

//        d3.json("bundleinteraction.json", function(error, classes) {

            classes = parseToStructure( json );

            var nodes = cluster.nodes(taxonHierarchy(classes) ),
                links = taxonPreys(nodes);

            link = link
                .data(bundle(links))
                .enter().append("path")
                .each(function(d) { d.source = d[0], d.target = d[d.length - 1]; })
                .attr("class", "bundl-link")
                .attr("d", line);

            node = node
                .data(nodes.filter(function(n) { return !n.children; }))
                .enter().append("text")
                .attr("class", "bundle-node")
                .attr("dx", function(d) { return d.x < 180 ? 8 : -8; })
                .attr("dy", ".31em")
                .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")" + (d.x < 180 ? "" : "rotate(180)"); })
                .style("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })
                .style("cursor", "pointer")
                .text(function(d) { return d.key; })
                .on("mouseover", mouseovered)
                .on("mouseout", mouseouted)
                .append("title").text( function( d ) { return d.eolId + ' ' + d.path} )
            ;
//        });

        function mouseovered(d) {
            node
                .each(function(n) { n.target = n.source = false; });

            link
                .classed("link--target", function(l) { if (l.target === d) return l.source.source = true; })
                .classed("link--source", function(l) { if (l.source === d) return l.target.target = true; })
                .filter(function(l) { return l.target === d || l.source === d; })
                .each(function() { this.parentNode.appendChild(this); });

            node
                .classed("node--target", function(n) { return n.target; })
                .classed("node--source", function(n) { return n.source; });
        }

        function mouseouted(d) {
            link
                .classed("link--target", false)
                .classed("link--source", false);

            node
                .classed("node--target", false)
                .classed("node--source", false);
        }

        d3.select(self.frameElement).style("height", diameter + "px");

        // Lazily construct the package hierarchy from class names.
        function taxonHierarchy(classes) {
            var map = {};var j = 0;

            function find(name, data) {
                var node = map[name], i;
                if (!node) {
                    node = map[name] = data || {name: name, children: []};

                    if (name.length) {
                        node.parent = find(name.substring(0, i = name.lastIndexOf(".")));
                        if ( !node.parent.children ) {
                            node.parent.children = [];
                        }
                        node.parent.children.push(node);
                        node.key = name.substring(i + 1);
                    }
                }
                return node;
            }

            classes.forEach(function(d) {
                find(d.name, d);
            });
            return map[""];
        }

        // Return a list of preys for the given array of nodes.
        function taxonPreys(nodes) {
            var map = {},
                preys = [];

            // Compute a map from name to node.
            nodes.forEach(function(d) {
                map[d.name] = d;
            });
            // For each import, construct a link from the source to target node.
            nodes.forEach(function(d) {
                if (d.preys) d.preys.forEach(function(i) {
                    if ( map[ i ] ) {
                        preys.push({source: map[d.name], target: map[i]});
                    }
                });
            });
            return preys;
        }
    };

    pub.buildBundles = _buildBundles;
} )( window );
<commit_msg>[BUGFIX] Add prey only taxons to parsed data in bundle view<commit_after>( function( pub ) {
    var parseToStructure = function( data ) {
        var parsedData = {}, currentSource, currentTarget, returnData = [], path;
        data.forEach( function( d ) {
            currentSource = d.source; currentTarget = d.target;

            if ( currentSource.id && currentSource.id !== 'no:match' && !parsedData[ currentSource.id ] ) {
                path = currentSource.path.split( ' | ' ).join( '.' );
                parsedData[ currentSource.id ] = { name: path, path: path, eolId: currentSource.id, preys: [] };
            }

            if ( parsedData[ currentSource.id ] && currentTarget.id !== 'no:match' ) {
                path = currentTarget.path.split( ' | ' ).join( '.' );
                parsedData[ currentSource.id ].preys.push( path );
            }

            if ( currentTarget.id && currentTarget.id !== 'no:match' && !parsedData[ currentTarget.id ] ) {
                path = currentTarget.path.split( ' | ' ).join( '.' );
                parsedData[ currentTarget.id ] = { name: path, path: path, eolId: currentTarget.id, preys: [] };
            }
        } );

        for ( var id in parsedData ) {
            if ( parsedData.hasOwnProperty( id ) ) {
                returnData.push( parsedData[ id ] );
            }
        }

        return returnData;
    };

    var _buildBundles = function( json, canvasDimension ) {
        var diameter = canvasDimension.height * 2,
            radius = diameter / 2,
            innerRadius = radius - 120;

        var cluster = d3.layout.cluster()
            .size([360, innerRadius])
            .sort(function(a, b) { return d3.ascending(a.key, b.key); })
            .value(function(d) { return d.size; });

        var bundle = d3.layout.bundle();

        var line = d3.svg.line.radial()
            .interpolate("bundle")
            .tension(0.85)
            .radius(function(d) { return d.y; })
            .angle(function(d) { return d.x / 180 * Math.PI; });

        var svg = d3.select("#bundle-container").append("svg")
            .attr( 'viewBox', '0 0 ' + canvasDimension.width * 2 + ' ' + canvasDimension.height * 2 )
            .append("g")
            .attr("transform", "translate(" + canvasDimension.width + "," + radius + ")");

        var link = svg.append("g").selectAll(".bundl-link"),
            node = svg.append("g").selectAll(".bundl-node");

//        d3.json("bundleinteraction.json", function(error, classes) {

            classes = parseToStructure( json );

            var nodes = cluster.nodes(taxonHierarchy(classes) ),
                links = taxonPreys(nodes);

            link = link
                .data(bundle(links))
                .enter().append("path")
                .each(function(d) { d.source = d[0], d.target = d[d.length - 1]; })
                .attr("class", "bundl-link")
                .attr("d", line);

            node = node
                .data(nodes.filter(function(n) { return !n.children; }))
                .enter().append("text")
                .attr("class", "bundle-node")
                .attr("dx", function(d) { return d.x < 180 ? 8 : -8; })
                .attr("dy", ".31em")
                .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")" + (d.x < 180 ? "" : "rotate(180)"); })
                .style("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })
                .style("cursor", "pointer")
                .text(function(d) { return d.key; })
                .on("mouseover", mouseovered)
                .on("mouseout", mouseouted)
                .append("title").text( function( d ) { return d.eolId + ' ' + d.path} )
            ;
//        });

        function mouseovered(d) {
            node
                .each(function(n) { n.target = n.source = false; });

            link
                .classed("link--target", function(l) { if (l.target === d) return l.source.source = true; })
                .classed("link--source", function(l) { if (l.source === d) return l.target.target = true; })
                .filter(function(l) { return l.target === d || l.source === d; })
                .each(function() { this.parentNode.appendChild(this); });

            node
                .classed("node--target", function(n) { return n.target; })
                .classed("node--source", function(n) { return n.source; });
        }

        function mouseouted(d) {
            link
                .classed("link--target", false)
                .classed("link--source", false);

            node
                .classed("node--target", false)
                .classed("node--source", false);
        }

        function taxonHierarchy(classes) {
            var map = {};var j = 0;

            function find(name, data) {
                var node = map[name], i;
                if (!node) {
                    node = map[name] = data || {name: name, children: []};

                    if (name.length) {
                        node.parent = find(name.substring(0, i = name.lastIndexOf(".")));
                        if ( !node.parent.children ) {
                            node.parent.children = [];
                        }
                        node.parent.children.push(node);
                        node.key = name.substring(i + 1);
                    }
                }
                return node;
            }

            classes.forEach(function(d) {
                find(d.name, d);
            });
            return map[""];
        }

        // Return a list of preys for the given array of nodes.
        function taxonPreys(nodes) {
            var map = {},
                preys = [];

            // Compute a map from name to node.
            nodes.forEach(function(d) {
                map[d.name] = d;
            });
            // For each import, construct a link from the source to target node.
            nodes.forEach(function(d) {
                if (d.preys) d.preys.forEach(function(i) {
                    if ( map[ i ] ) {
                        preys.push({source: map[d.name], target: map[i]});
                    }
                });
            });
            return preys;
        }
    };

    pub.buildBundles = _buildBundles;
} )( window );
<|endoftext|>


<commit_before>(function(angular){
    'use strict';

    var app = angular.module('activities.controllers', ['ngSanitize']);

    app.controller('PHPCtrl', ['$scope', '$sce', 'Progress',
        function ($scope, $sce, Progress) {

            $scope.disableResultTab = true;
            $scope.cm_refresh = 0;
            $scope.iframeRefresh = 0;

            $scope.refresh  = function() {
                $scope.cm_refresh += 1;
            };

            $scope.answer.$promise.finally(function() {
                if (!$scope.answer.id) {
                    $scope.answer.given = $scope.currentActivity.data;
                }
                $scope.answer.given[0].active = true;
                $scope.refresh();
            });

             $scope.sendPhpAnswer = function() {
                 $scope.answer.activity = $scope.currentActivity.id;
                 $scope.answer.$update({activityId: $scope.answer.activity}, function () {
                     $scope.disableResultTab = false;
                     $scope.resultUrl = $sce.trustAsResourceUrl('http://php' + $scope.answer.user_id + '.timtec.com.br/');
                     $scope.iframeRefresh += 1;
                 }).then(function(d){
//                    ga('send', 'event', 'activity', 'result', '', d.correct);
                     return Progress.getProgressByUnitId($scope.currentUnit.id);
                 }).then(function(progress){
                     $scope.currentUnit.progress = progress;
                 });
//                ga('send', 'event', 'activity', 'submit');

            };

            $scope.codemirrorLoaded = function(cm){
                // FIXME refactor this.
                var pid = setInterval(function(){
                    if ($scope.cm_refresh < 20) {
                        $scope.refresh();
                    } else
                        clearInterval(pid);
                }, 500);
            };

            $scope.codemirrorConfig = {
                        lineNumbers:true,
                        theme:'monokai',
                        matchTags: {bothTags: true},
                        matchBrackets: true,
                        extraKeys: {'Ctrl-J': 'toMatchingTag',
                                    'Ctrl-Space': 'autocomplete'},
                        mode:'php',
                        onLoad : $scope.codemirrorLoaded
            };
        }
    ]);

    app.controller('RelationshipCtrl', ['$scope',
        function ($scope) {

            function compareNumbers(a, b) {
              return a - b;
            }

            $scope.$watch('currentActivity', function(currentActivity) {
                $scope.possibleAnswers = currentActivity.expected.slice(0);
                $scope.possibleAnswers.sort(compareNumbers);
            });

            $scope.possibleAnswers = $scope.currentActivity.expected.slice(0);
            $scope.possibleAnswers.sort(compareNumbers);
        }
    ]);

    app.controller('DiscussionActivityCtrl', [
      '$scope',
      '$sce',
      '$routeParams',
      '$location',
      '$anchorScroll',
      'uiTinymceConfig',
      'Forum',
      'Topic',
      'Comment',
      'TopicLike',
      'TopicFile',
      'CommentLike',
      'CommentFile',
      'Progress',
      'ClassActivity',
      'CurrentUser',
      function ($scope, $sce, $routeParams, $location, $anchorScroll, uiTinymceConfig, Forum, Topic, Comment, TopicLike, TopicFile, CommentLike, CommentFile, Progress, ClassActivity, CurrentUser) {
        $scope.activity_open = true;
        $scope.activity_expired = false;
        var now = Date.now();

        $scope.user = CurrentUser;

        // Decide the current state of the activity
        if(now < $scope.currentActivity.data.start_date){
          // The Activity is not open yet
          $scope.activity_open = false;
        } else if(now > $scope.currentActivity.data.end_date){
          // The Activity is already expired
          $scope.activity_expired = true;
        }

        uiTinymceConfig.automatic_uploads = true;

        // If there is not an answer yet, create topic instance
        $scope.topic = new Topic();
        $scope.topic.title = 'Resposta de atividade';
        $scope.topic.forum = $scope.currentActivity.data.forum;

        // Check if there is an answer to this activity
        if ($scope.answer.$promise) {
            $scope.answer.$promise.then(function(answer) {
                // if there is, show the corresponding topic that holds this answer and its comments
                $scope.show_answer = true;
                $scope.topic = Topic.get({id: answer.given.topic, activity: true});
            });
        }

        // if there is no answer, show the text editor and prepare to save it
        $scope.show_answer = false;
        $scope.edit_topic = false;

        $scope.save_answer = function() {
            // if there is no content, the edit form must not disappear from screen
            if($scope.topic.content === undefined || $scope.topic.content === ""){
              return;
            }
            $scope.sending = true;
            var topic_files = $scope.topic.files;
            if ($scope.topic.id)
                $scope.topic.$update({activity: true}, function(topic) {
                    angular.forEach(topic_files, function(topic_file) {
                        if (!topic_file.hasOwnProperty('topic') || !topic_file.topic) {
                            topic_file.topic = topic.id;
                            delete topic_file.file;
                            topic_file.$patch().then(function(comment_file_complete) {
                                topic.files.push(comment_file_complete);
                            });
                        }
                    });
                });
            else
                $scope.topic.$save(function(topic) {
                    $scope.answer.given = {topic: topic.id};
                    $scope.answer.activity = $scope.currentActivity.id;
                    $scope.answer.$save().then(function(answer) {
                        $scope.currentUnit.progress = Progress.complete($scope.currentUnit.id);
                    });
                    angular.forEach(topic_files, function(topic_file) {
                        if (!topic_file.hasOwnProperty('topic') || !topic_file.topic) {
                            topic_file.topic = topic.id;
                            delete topic_file.file;
                            topic_file.$patch().then(function(comment_file_complete) {
                                topic.files.push(comment_file_complete);
                            });
                        }
                    });
                });
            $scope.edit_topic = true;
            $scope.show_answer = true;
        };

        // Bootstrap functions for new comments and replies
        $scope.new_comment = function(){
            var comment = new Comment();
            comment.topic = $scope.topic;
            return comment;
        };

        $scope.uploadTopicFiles = function (file, topic) {
            if (file) {
                TopicFile.upload(file).then(function (response) {
                    var comment_file = new TopicFile(response.data);
                    if (topic.files === undefined)
                        topic.files = [];
                    topic.files.push(comment_file);
                    return {location: comment_file.file};
                }, function(error){

                }, function(evt){
                    topic.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
                });
            }
        };

        $scope.uploadCommentFiles = function (file, comment) {

            if (file) {
                CommentFile.upload(file).then(function (response) {
                    var comment_file = new CommentFile(response.data);

                    if (comment.files === undefined)
                        comment.files = [];
                    comment.files.push(comment_file);
                    return {location: comment_file.file};
                }, function (response) {
                    if (response.status > 0) {
                        $scope.errorMsg = response.status + ': ' + response.data;
                    }
                }, function (evt) {
                    comment.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
                });
            }
        }

        var my_topic_activity = null;
        $scope.my_answer = true;
        // Load the given answer from other student on screen
        $scope.viewAnswer = function(activity_topic){
            if(my_topic_activity === null)
                my_topic_activity = $scope.topic;
            $scope.my_answer = false;
            $scope.topic = activity_topic;
            $scope.show_answer = true;

            setTimeout(function() {
                $(document.body).animate({
                  'scrollTop':   $('#answer').position().top
                }, 500);
            }, 100);
        };

        $scope.viewMyAnswer = function(){
            $scope.topic = my_topic_activity;
            $scope.my_answer = true;
            // If the user still hasn't created an answer, the editor must be reactivated too
            if(!$scope.topic.hasOwnProperty('id')){
              $scope.show_answer = false;
            }
        };

        // Load other students activities
        $scope.classes_activities = ClassActivity.query({
            activity: $scope.currentActivity.id,
            course: $scope.lesson.course,
            ordering: '-last_activity_at',
            exclude_cur_user: true,
          }, function(response){
                // Check if there are any activities to show
                var acticvities = false;
                for (var i = 0; i < response.length; i++) {
                    if(response[i].activity_answers.length > 0){
                      acticvities = true;
                      break;
                    }
                }
                $scope.activities_loaded = acticvities;
            }
        );

        $scope.topic_like = function(topic) {
            if (topic.user_like) {
                TopicLike.delete({id:topic.user_like});
                topic.user_like = 0;
                topic.count_likes -=1;
            } else {
                // Change this before promisse so the user sees the action take effect.
                topic.user_like = -1;

                  TopicLike.save({topic:topic.id}, function(topic_like){
                    topic.user_like = topic_like.id;
                });
                topic.count_likes +=1
            }
        };

        $scope.save_comment = function(comment, parent_comment) {
            if (parent_comment) {
                comment.parent = parent_comment.id;
                parent_comment.comment_replies.push(comment);
            } else {
                comment.topic.comments.push(comment);
            }
            // Store files to be saved after the comment
            var files = [];
            angular.copy(comment.files, files);
            delete comment.files;

            // Turn the topic object into an id for JSON parsing
            comment.topic = comment.topic.id;

            // Send the comment data to be saved by the API
            comment.$save().then(function(comment) {
                angular.forEach(files, function(comment_file) {
                    comment_file.comment = comment.id;
                    delete comment_file.file;
                    comment_file.$patch().then(function(comment_file_complete) {
                        comment.files.push(comment_file_complete);
                    });
                });
            });
        };

        $scope.update_comment = function(changed_comment) {
            var comment_files = changed_comment.files;

            // Get the correct comment instance from the server
            Comment.get({id: changed_comment.id}, function(comment){
              comment.text = changed_comment.text;
              angular.copy(comment, changed_comment);
              comment.$update().then(function(comment) {
                  angular.forEach(comment_files, function(comment_file) {
                        if(comment_file instanceof CommentFile){ // Prepare only new files for store in the topic
                          comment_file.comment = comment.id;
                          delete comment_file.file;
                          comment_file.$patch().then(function(comment_file_complete) {
                              changed_comment.files.push(comment_file_complete);
                          });
                      }
                  });
              });
            });
        };

        $scope.comment_like = function(comment) {
            if (comment.user_like) {
                CommentLike.delete({id:comment.user_like});
                comment.user_like = 0;
                comment.count_likes -=1;
            } else {
                // Change this before promisse so the user sees the action take effect.
                comment.user_like = -1;

                CommentLike.save({comment:comment.id}, function(comment_like){
                    comment.user_like = comment_like.id;
                });
                comment.count_likes +=1;
            }
        };

        $scope.get_as_safe_html = function(html_content) {
            return $sce.trustAsHtml(html_content);
        };

      }
    ]);

    app.controller('PresentationActivityCtrl', [
      '$scope',
      '$sce',
      'uiTinymceConfig',
      function ($scope, $sce, uiTinymceConfig) {
        uiTinymceConfig.automatic_uploads = true;

        $scope.getReadingActivityHtml = function() {
            return $sce.trustAsHtml($scope.currentActivity.comment);
        };

      }
    ]);
})(angular);
<commit_msg>When an answer is viewed, the frontend tries to mark a corresponding notification as read (refs hacklabr/paralapraca#287)<commit_after>(function(angular){
    'use strict';

    var app = angular.module('activities.controllers', ['ngSanitize']);

    app.controller('PHPCtrl', ['$scope', '$sce', 'Progress',
        function ($scope, $sce, Progress) {

            $scope.disableResultTab = true;
            $scope.cm_refresh = 0;
            $scope.iframeRefresh = 0;

            $scope.refresh  = function() {
                $scope.cm_refresh += 1;
            };

            $scope.answer.$promise.finally(function() {
                if (!$scope.answer.id) {
                    $scope.answer.given = $scope.currentActivity.data;
                }
                $scope.answer.given[0].active = true;
                $scope.refresh();
            });

             $scope.sendPhpAnswer = function() {
                 $scope.answer.activity = $scope.currentActivity.id;
                 $scope.answer.$update({activityId: $scope.answer.activity}, function () {
                     $scope.disableResultTab = false;
                     $scope.resultUrl = $sce.trustAsResourceUrl('http://php' + $scope.answer.user_id + '.timtec.com.br/');
                     $scope.iframeRefresh += 1;
                 }).then(function(d){
//                    ga('send', 'event', 'activity', 'result', '', d.correct);
                     return Progress.getProgressByUnitId($scope.currentUnit.id);
                 }).then(function(progress){
                     $scope.currentUnit.progress = progress;
                 });
//                ga('send', 'event', 'activity', 'submit');

            };

            $scope.codemirrorLoaded = function(cm){
                // FIXME refactor this.
                var pid = setInterval(function(){
                    if ($scope.cm_refresh < 20) {
                        $scope.refresh();
                    } else
                        clearInterval(pid);
                }, 500);
            };

            $scope.codemirrorConfig = {
                        lineNumbers:true,
                        theme:'monokai',
                        matchTags: {bothTags: true},
                        matchBrackets: true,
                        extraKeys: {'Ctrl-J': 'toMatchingTag',
                                    'Ctrl-Space': 'autocomplete'},
                        mode:'php',
                        onLoad : $scope.codemirrorLoaded
            };
        }
    ]);

    app.controller('RelationshipCtrl', ['$scope',
        function ($scope) {

            function compareNumbers(a, b) {
              return a - b;
            }

            $scope.$watch('currentActivity', function(currentActivity) {
                $scope.possibleAnswers = currentActivity.expected.slice(0);
                $scope.possibleAnswers.sort(compareNumbers);
            });

            $scope.possibleAnswers = $scope.currentActivity.expected.slice(0);
            $scope.possibleAnswers.sort(compareNumbers);
        }
    ]);

    app.controller('DiscussionActivityCtrl', [
      '$scope',
      '$sce',
      '$routeParams',
      '$location',
      '$anchorScroll',
      'uiTinymceConfig',
      'Forum',
      'Topic',
      'Comment',
      'TopicLike',
      'TopicFile',
      'CommentLike',
      'CommentFile',
      'Progress',
      'ClassActivity',
      'CurrentUser',
      'AnswerNotification',
      function ($scope, $sce, $routeParams, $location, $anchorScroll, uiTinymceConfig, Forum, Topic, Comment, TopicLike, TopicFile, CommentLike, CommentFile, Progress, ClassActivity, CurrentUser, AnswerNotification) {
        $scope.activity_open = true;
        $scope.activity_expired = false;
        var now = Date.now();

        $scope.user = CurrentUser;

        // Decide the current state of the activity
        if(now < $scope.currentActivity.data.start_date){
          // The Activity is not open yet
          $scope.activity_open = false;
        } else if(now > $scope.currentActivity.data.end_date){
          // The Activity is already expired
          $scope.activity_expired = true;
        }

        uiTinymceConfig.automatic_uploads = true;

        // If there is not an answer yet, create topic instance
        $scope.topic = new Topic();
        $scope.topic.title = 'Resposta de atividade';
        $scope.topic.forum = $scope.currentActivity.data.forum;

        // Check if there is an answer to this activity
        if ($scope.answer.$promise) {
            $scope.answer.$promise.then(function(answer) {
                // if there is, show the corresponding topic that holds this answer and its comments
                $scope.show_answer = true;
                $scope.topic = Topic.get({id: answer.given.topic, activity: true});
            });
        }

        // if there is no answer, show the text editor and prepare to save it
        $scope.show_answer = false;
        $scope.edit_topic = false;

        $scope.save_answer = function() {
            // if there is no content, the edit form must not disappear from screen
            if($scope.topic.content === undefined || $scope.topic.content === ""){
              return;
            }
            $scope.sending = true;
            var topic_files = $scope.topic.files;
            if ($scope.topic.id)
                $scope.topic.$update({activity: true}, function(topic) {
                    angular.forEach(topic_files, function(topic_file) {
                        if (!topic_file.hasOwnProperty('topic') || !topic_file.topic) {
                            topic_file.topic = topic.id;
                            delete topic_file.file;
                            topic_file.$patch().then(function(comment_file_complete) {
                                topic.files.push(comment_file_complete);
                            });
                        }
                    });
                });
            else
                $scope.topic.$save(function(topic) {
                    $scope.answer.given = {topic: topic.id};
                    $scope.answer.activity = $scope.currentActivity.id;
                    $scope.answer.$save().then(function(answer) {
                        $scope.currentUnit.progress = Progress.complete($scope.currentUnit.id);
                    });
                    angular.forEach(topic_files, function(topic_file) {
                        if (!topic_file.hasOwnProperty('topic') || !topic_file.topic) {
                            topic_file.topic = topic.id;
                            delete topic_file.file;
                            topic_file.$patch().then(function(comment_file_complete) {
                                topic.files.push(comment_file_complete);
                            });
                        }
                    });
                });
            $scope.edit_topic = true;
            $scope.show_answer = true;
        };

        // Bootstrap functions for new comments and replies
        $scope.new_comment = function(){
            var comment = new Comment();
            comment.topic = $scope.topic;
            return comment;
        };

        $scope.uploadTopicFiles = function (file, topic) {
            if (file) {
                TopicFile.upload(file).then(function (response) {
                    var comment_file = new TopicFile(response.data);
                    if (topic.files === undefined)
                        topic.files = [];
                    topic.files.push(comment_file);
                    return {location: comment_file.file};
                }, function(error){

                }, function(evt){
                    topic.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
                });
            }
        };

        $scope.uploadCommentFiles = function (file, comment) {

            if (file) {
                CommentFile.upload(file).then(function (response) {
                    var comment_file = new CommentFile(response.data);

                    if (comment.files === undefined)
                        comment.files = [];
                    comment.files.push(comment_file);
                    return {location: comment_file.file};
                }, function (response) {
                    if (response.status > 0) {
                        $scope.errorMsg = response.status + ': ' + response.data;
                    }
                }, function (evt) {
                    comment.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
                });
            }
        }

        var my_topic_activity = null;
        $scope.my_answer = true;
        // Load the given answer from other student on screen
        $scope.viewAnswer = function(activity_topic){
            if(my_topic_activity === null)
                my_topic_activity = $scope.topic;
            $scope.my_answer = false;
            $scope.topic = activity_topic;
            $scope.show_answer = true;

            AnswerNotification.update({topic: activity_topic.id, is_read: true});

            setTimeout(function() {
                $(document.body).animate({
                  'scrollTop':   $('#answer').position().top
                }, 500);
            }, 100);
        };

        $scope.viewMyAnswer = function(){
            $scope.topic = my_topic_activity;
            $scope.my_answer = true;
            // If the user still hasn't created an answer, the editor must be reactivated too
            if(!$scope.topic.hasOwnProperty('id')){
              $scope.show_answer = false;
            }
        };

        // Load other students activities
        $scope.classes_activities = ClassActivity.query({
            activity: $scope.currentActivity.id,
            course: $scope.lesson.course,
            ordering: '-last_activity_at',
            exclude_cur_user: true,
          }, function(response){
                // Check if there are any activities to show
                var acticvities = false;
                for (var i = 0; i < response.length; i++) {
                    if(response[i].activity_answers.length > 0){
                      acticvities = true;
                      break;
                    }
                }
                $scope.activities_loaded = acticvities;
            }
        );

        $scope.topic_like = function(topic) {
            if (topic.user_like) {
                TopicLike.delete({id:topic.user_like});
                topic.user_like = 0;
                topic.count_likes -=1;
            } else {
                // Change this before promisse so the user sees the action take effect.
                topic.user_like = -1;

                  TopicLike.save({topic:topic.id}, function(topic_like){
                    topic.user_like = topic_like.id;
                });
                topic.count_likes +=1
            }
        };

        $scope.save_comment = function(comment, parent_comment) {
            if (parent_comment) {
                comment.parent = parent_comment.id;
                parent_comment.comment_replies.push(comment);
            } else {
                comment.topic.comments.push(comment);
            }
            // Store files to be saved after the comment
            var files = [];
            angular.copy(comment.files, files);
            delete comment.files;

            // Turn the topic object into an id for JSON parsing
            comment.topic = comment.topic.id;

            // Send the comment data to be saved by the API
            comment.$save().then(function(comment) {
                angular.forEach(files, function(comment_file) {
                    comment_file.comment = comment.id;
                    delete comment_file.file;
                    comment_file.$patch().then(function(comment_file_complete) {
                        comment.files.push(comment_file_complete);
                    });
                });
            });
        };

        $scope.update_comment = function(changed_comment) {
            var comment_files = changed_comment.files;

            // Get the correct comment instance from the server
            Comment.get({id: changed_comment.id}, function(comment){
              comment.text = changed_comment.text;
              angular.copy(comment, changed_comment);
              comment.$update().then(function(comment) {
                  angular.forEach(comment_files, function(comment_file) {
                        if(comment_file instanceof CommentFile){ // Prepare only new files for store in the topic
                          comment_file.comment = comment.id;
                          delete comment_file.file;
                          comment_file.$patch().then(function(comment_file_complete) {
                              changed_comment.files.push(comment_file_complete);
                          });
                      }
                  });
              });
            });
        };

        $scope.comment_like = function(comment) {
            if (comment.user_like) {
                CommentLike.delete({id:comment.user_like});
                comment.user_like = 0;
                comment.count_likes -=1;
            } else {
                // Change this before promisse so the user sees the action take effect.
                comment.user_like = -1;

                CommentLike.save({comment:comment.id}, function(comment_like){
                    comment.user_like = comment_like.id;
                });
                comment.count_likes +=1;
            }
        };

        $scope.get_as_safe_html = function(html_content) {
            return $sce.trustAsHtml(html_content);
        };

      }
    ]);

    app.controller('PresentationActivityCtrl', [
      '$scope',
      '$sce',
      'uiTinymceConfig',
      function ($scope, $sce, uiTinymceConfig) {
        uiTinymceConfig.automatic_uploads = true;

        $scope.getReadingActivityHtml = function() {
            return $sce.trustAsHtml($scope.currentActivity.comment);
        };

      }
    ]);
})(angular);
<|endoftext|>