<commit_before>var log = require("/api/Log");
var utils = require("/api/Utils");
var os = Ti.Platform.osname;
var tishadow_version = Ti.version.replace(/tishadow_?/,"").replace(/\./g,"");
var _ = require("/lib/underscore");

if (os === "android") {
  var density_orientation = (Ti.Gesture.orientation === Ti.UI.LANDSCAPE_LEFT) ? "land" : "port",
      density_folders = (function () {

        var folders = [],
            ratio = ((Ti.Platform.displayCaps.platformWidth / Ti.Platform.displayCaps.platformHeight) < ((density_orientation === "land") ? (320 / 240) : (240 / 320))) ? "long" : "notlong",
            logicalDensityFactor = Ti.Platform.displayCaps.logicalDensityFactor,
            density;

        if (logicalDensityFactor <= 0.75) {
          density = "ldpi";
        } else if (logicalDensityFactor <= 1.0) {
          density = "mdpi";
        } else if (logicalDensityFactor <= 1.5) {
          density = "hdpi";
        } else {
          density = "xhdpi";
        }

        folders.push("res-" + ratio + "-%ORIENTATION%-" + density);
        folders.push("res-%ORIENTATION%-" + density);
        folders.push("res-" + density);

        if (density === "ldpi") {
          folders.push("low");
        } else if (density === "mdpi") {
          folders.push("medium");
        } else if (density === "hdpi") {
          folders.push("high");
        }

        folders.push("res-mdpi");
        folders.push("");

        return folders;
  })();

  Ti.Gesture.addEventListener("orientationchange", function (e) {
    density_orientation = (e.orientation === Ti.UI.LANDSCAPE_LEFT) ? "land" : "port";
  });
}

var cache={};
function custom_require(file) {
  try {
    log.info("Requiring: " + file);
    var rfile = Ti.Filesystem.getFile(file + ".js");
    var contents = rfile.read().text;
    return eval("(function(exports){var __OXP=exports;var module={'exports':exports};" + contents + ";if(module.exports !== __OXP){return module.exports;}return exports;})({})");
  } catch(e) {
    e.file=file;
    log.error(utils.extractExceptionData(e));
  }
}

exports.require = function(extension) {
  try {
    // Full Path
    var path = exports.file(extension);
    // Assuming that it is a native module if the path does not exist
    if (!Ti.Filesystem.getFile(path + ".js").exists()) {
      log.debug("Native module:" + extension);
      return require(extension);
    }
    // Is the CommonJS module in the cache
    if (cache[path]) {
      return cache[path];
    }
    var mod = custom_require(path);
    cache[path] = mod;
    return mod;
  } catch(e) {
    log.error(utils.extractExceptionData(e));
  }
};

exports.include = function(context) {
  try {
    // Full Path
    for (var i = 1, length = arguments.length; i< length; i++) {
      var path = exports.file(arguments[i]);
      var ifile = Ti.Filesystem.getFile(path);
      var contents = ifile.read().text;
      eval.call(context, contents);
    }
  } catch(e) {
    log.error(utils.extractExceptionData(e));
  }
};

function injectSuffix(file, suffix) {
  var file_parts = file.split(".");
  var ext = file_parts.pop();
  return file_parts.join(".") + suffix + "." + ext;
}

//density files only for png files
function densityFile(file) {
  //iOS Retina Check
  if ((os === "ipad" || os === "iphone")) {
    if (Ti.Filesystem.getFile(file).exists()) {
      return file;
    }
    var ret_file_name = injectSuffix(file, "@2x");
    if (Ti.Filesystem.getFile(ret_file_name).exists() && Ti.Platform.displayCaps.density === "high") {
      return ret_file_name;
    }
  } else if (os === "android") {
    var d_file_name = file.replace("android//images/", "android//images/%FOLDER%/"),
        do_file_name,
        i;
    for (i in density_folders) {
      do_file_name = d_file_name.replace("%FOLDER%", density_folders[i].replace('%ORIENTATION%', density_orientation));
      do9_file_name = injectSuffix(do_file_name, '.9');
      if (Ti.Filesystem.getFile(do_file_name).exists() || Ti.Filesystem.getFile(do9_file_name).exists()) {
        return do_file_name;
      }
    }
  }
  return null;
}
exports.file = function(extension) {
  if (typeof extension !== "string") {
    return extension;
  }
  extension = extension.replace(/^\//, '');
  var base = Ti.Filesystem.applicationDataDirectory + "/" + require("/api/TiShadow").currentApp + "/";
  var path = base + extension,
      platform_path =  base + (os === "android" ? "android" : "iphone") + "/" + extension;
  var extension_parts = extension.split("/");
  var needsJS = extension_parts[extension_parts.length-1].indexOf(".") === -1;
  var isPNG = extension.toLowerCase().match("\\.png$");
  if (!isPNG) {
    var file = Ti.Filesystem.getFile(platform_path + (needsJS ? ".js" : ""));
    if (file.exists()) {
      return platform_path;
    }
  } else {
    var platform_dense = densityFile(platform_path);
    if (null !== platform_dense) {
      return platform_dense;
    }
  }

	if (Ti.Filesystem.getFile(path + (needsJS ? ".js" : "")).exists()) {
		return path;
	}
	return extension;
};

// if a list of files is provided it will selectively clear the cache
exports.clearCache = function (list) {
  if (_.isArray(list)) {
    list.forEach(function(file) {
      if (file.match(".js$")) {
        cache[exports.file(file.replace(/.js$/,""))] = null;
        cache[exports.file("/" + file.replace(/.js$/,""))] = null;
      }
    });
  } else {
    cache = {};
  }
};
<commit_msg>Fixes regression caused by #124<commit_after>var log = require("/api/Log");
var utils = require("/api/Utils");
var os = Ti.Platform.osname;
var tishadow_version = Ti.version.replace(/tishadow_?/,"").replace(/\./g,"");
var _ = require("/lib/underscore");

if (os === "android") {
  var density_orientation = (Ti.Gesture.orientation === Ti.UI.LANDSCAPE_LEFT) ? "land" : "port",
      density_folders = (function () {

        var folders = [],
            ratio = ((Ti.Platform.displayCaps.platformWidth / Ti.Platform.displayCaps.platformHeight) < ((density_orientation === "land") ? (320 / 240) : (240 / 320))) ? "long" : "notlong",
            logicalDensityFactor = Ti.Platform.displayCaps.logicalDensityFactor,
            density;

        if (logicalDensityFactor <= 0.75) {
          density = "ldpi";
        } else if (logicalDensityFactor <= 1.0) {
          density = "mdpi";
        } else if (logicalDensityFactor <= 1.5) {
          density = "hdpi";
        } else {
          density = "xhdpi";
        }

        folders.push("res-" + ratio + "-%ORIENTATION%-" + density);
        folders.push("res-%ORIENTATION%-" + density);
        folders.push("res-" + density);

        if (density === "ldpi") {
          folders.push("low");
        } else if (density === "mdpi") {
          folders.push("medium");
        } else if (density === "hdpi") {
          folders.push("high");
        }

        folders.push("res-mdpi");
        folders.push("");

        return folders;
  })();

  Ti.Gesture.addEventListener("orientationchange", function (e) {
    density_orientation = (e.orientation === Ti.UI.LANDSCAPE_LEFT) ? "land" : "port";
  });
}

var cache={};
function custom_require(file) {
  try {
    log.info("Requiring: " + file);
    var rfile = Ti.Filesystem.getFile(file + ".js");
    var contents = rfile.read().text;
    return eval("(function(exports){var __OXP=exports;var module={'exports':exports};" + contents + ";if(module.exports !== __OXP){return module.exports;}return exports;})({})");
  } catch(e) {
    e.file=file;
    log.error(utils.extractExceptionData(e));
  }
}

exports.require = function(extension) {
  try {
    // Full Path
    var path = exports.file(extension);
    // Assuming that it is a native module if the path does not exist
    if (!Ti.Filesystem.getFile(path + ".js").exists()) {
      log.debug("Native module:" + extension);
      return require(extension);
    }
    // Is the CommonJS module in the cache
    if (cache[path]) {
      return cache[path];
    }
    var mod = custom_require(path);
    cache[path] = mod;
    return mod;
  } catch(e) {
    log.error(utils.extractExceptionData(e));
  }
};

exports.include = function(context) {
  try {
    // Full Path
    for (var i = 1, length = arguments.length; i< length; i++) {
      var path = exports.file(arguments[i]);
      var ifile = Ti.Filesystem.getFile(path);
      var contents = ifile.read().text;
      eval.call(context, contents);
    }
  } catch(e) {
    log.error(utils.extractExceptionData(e));
  }
};

function injectSuffix(file, suffix) {
  var file_parts = file.split(".");
  var ext = file_parts.pop();
  return file_parts.join(".") + suffix + "." + ext;
}

//density files only for png files
function densityFile(file) {
  //iOS Retina Check
  if ((os === "ipad" || os === "iphone")) {
    if (Ti.Filesystem.getFile(file).exists()) {
      return file;
    }
    var ret_file_name = injectSuffix(file, "@2x");
    if (Ti.Filesystem.getFile(ret_file_name).exists() && Ti.Platform.displayCaps.density === "high") {
      return ret_file_name;
    }
  } else if (os === "android") {
    var d_file_name = file.replace("android/images/", "android/images/%FOLDER%/"),
        do_file_name,
        i;
    for (i in density_folders) {
      do_file_name = d_file_name.replace("%FOLDER%", density_folders[i].replace('%ORIENTATION%', density_orientation));
      do9_file_name = injectSuffix(do_file_name, '.9');
      if (Ti.Filesystem.getFile(do_file_name).exists() || Ti.Filesystem.getFile(do9_file_name).exists()) {
        return do_file_name;
      }
    }
  }
  return null;
}
exports.file = function(extension) {
  if (typeof extension !== "string") {
    return extension;
  }
  extension = extension.replace(/^\//, '');
  var base = Ti.Filesystem.applicationDataDirectory + "/" + require("/api/TiShadow").currentApp + "/";
  var path = base + extension,
      platform_path =  base + (os === "android" ? "android" : "iphone") + "/" + extension;
  var extension_parts = extension.split("/");
  var needsJS = extension_parts[extension_parts.length-1].indexOf(".") === -1;
  var isPNG = extension.toLowerCase().match("\\.png$");
  if (!isPNG) {
    var file = Ti.Filesystem.getFile(platform_path + (needsJS ? ".js" : ""));
    if (file.exists()) {
      return platform_path;
    }
  } else {
    var platform_dense = densityFile(platform_path);
    if (null !== platform_dense) {
      return platform_dense;
    }
  }

	if (Ti.Filesystem.getFile(path + (needsJS ? ".js" : "")).exists()) {
		return path;
	}
	return extension;
};

// if a list of files is provided it will selectively clear the cache
exports.clearCache = function (list) {
  if (_.isArray(list)) {
    list.forEach(function(file) {
      if (file.match(".js$")) {
        cache[exports.file(file.replace(/.js$/,""))] = null;
        cache[exports.file("/" + file.replace(/.js$/,""))] = null;
      }
    });
  } else {
    cache = {};
  }
};
<|endoftext|>


<commit_before>const botgram = require("botgram");
const { json } = require("req");
const bot = botgram(process.argv[2]);
const rants = require("./rants.json");
const feature = "This feature is either under construction or i'm too retarded to implement it";

bot.text(function (msg, reply, next) {
    const text = msg.text.toLowerCase();
    if(text.includes("linux") && !text.includes("gnu"))
		    reply.reply(msg).text(rants.linux[Math.floor(Math.random()*rants.linux.length)]);
    if(text.includes("raphy") && !text.includes("faggot"))
		    reply.reply(msg).text(rants.raphy[Math.floor(Math.random()*rants.raphy.length)]);
    if(text.includes("fighting games"))
        reply.reply(msg).text("fuck off with your gay fighting games nigger");
});

bot.command("start", function (msg, reply, next) {
    reply.text("fuck off");
});

bot.command("price", function (msg, reply, next) {
    const coin = msg.args();
    let crap;
    json("https://api.coinmarketcap.com/v1/ticker/")
        .then(data => crap = data)
        .then(()=> {
            let balls = crap.find(obj => obj.symbol === coin.toUpperCase());
            if(balls == undefined)
                reply.text("give me a valid symbol retard");
            reply.text(balls.name + ": " + balls.price_usd + "$");
        });
});

bot.command("weather", function (msg, reply, next) { //api.openweathermap.org/data/2.5/weather?q={city name},{country code} to be added
    reply.text(feature);
  /*const city = msg.args();
    let ass;
    json("api.openweathermap.org/data/2.5/weather?q=" + city)
        .then(data => ass = data)
        .then(()=> {
            */
});
<commit_msg>weather command temporarily stolen from nignogbot<commit_after>const botgram = require("botgram");
const { json } = require("req");
const bot = botgram(process.argv[2]);
const rants = require("./rants.json");
const feature = "This feature is either under construction or i'm too retarded to implement it";

bot.text(function (msg, reply, next) {
    const text = msg.text.toLowerCase();
    if(text.includes("linux") && !text.includes("gnu"))
		    reply.reply(msg).text(rants.linux[Math.floor(Math.random()*rants.linux.length)]);
    if(text.includes("raphy") && !text.includes("faggot"))
		    reply.reply(msg).text(rants.raphy[Math.floor(Math.random()*rants.raphy.length)]);
    if(text.includes("fighting games"))
        reply.reply(msg).text("fuck off with your gay fighting games nigger");
    if(text.includes("😂"))
        reply.reply(msg).text("fuck off faggot");
});

bot.command("start", function (msg, reply, next) {
    reply.text("fuck off");
});

bot.command("price", function (msg, reply, next) {
    const coin = msg.args();
    let crap;
    json("https://api.coinmarketcap.com/v1/ticker/")
        .then(data => crap = data)
        .then(()=> {
            let balls = crap.find(obj => obj.symbol === coin.toUpperCase());
            if(balls == undefined)
                reply.text("give me a valid symbol retard");
            reply.text(balls.name + ": " + balls.price_usd + "$");
        });
});

bot.command("weather", function (msg, reply, next) {
    const K = 273.15;
    const city = msg.args();
    let link = `http://api.openweathermap.org/data/2.5/weather?q=${city}&APPID=1566ed87c9944f0df94332da29ee817c`;
    let ass;
    json(link)
        .then(data => {
            if (data.cod !== 200)
                reply.text(`gay error:\n${data.cod}: ${data.message}`);
            reply.text(`Weather in ${data.name}, ${data.sys.country}: ${Math.floor(data.main.temp - K)}°C, ${data.weather[0].description}
Max: ${Math.floor(data.main.temp_max - K)}°C
Min: ${Math.floor(data.main.temp_min - K)}°C
Humidity: ${Math.floor(data.main.humidity)}%
Air pressure: ${Math.floor(data.main.pressure)} hPa
`);
});
});
<|endoftext|>


<commit_before>/**
 * @name ngmReportHubApp.factory:ngmUser
 * @description
 * # ngmAccess
 * Manages browser local storage
 *
 * @name ngmReportHubApp.factory:ngmUser
 * @description
 * # ngmAccess
 * Manages browser local storage
 *
 */
angular.module('ngmReportHub')
	.factory('ngmUser', function() {

		return {

			// get user from storage
			get: function() {
				return localStorage.getObject( 'auth_token' );
			},

			// set user to storage
			set: function( val ) {
				// JSON stringify result
				localStorage.setObject( 'auth_token', val );
			},

			// unset user from storage
			unset: function() {
				// remove lists / user
				localStorage.removeItem( 'lists' );
				localStorage.removeItem( 'auth_token' );
			},

			// check user role
			hasRole: function( role ) {
				// get from storage
				var user = localStorage.getObject( 'auth_token' );
				// if no user
				if ( !user ) return false;
				// else has role?
				return angular.uppercase( user.roles ).indexOf( angular.uppercase( role ) ) >= 0;
			},

			// match any role
			hasAnyRole: function( roles ) {
				var user = localStorage.getObject( 'auth_token' );
				return !!user.roles.filter(function( role ) {
					return angular.uppercase( roles ).indexOf( angular.uppercase( role ) ) >= 0;
				}).length;
			}

		};
	})
	.factory('ngmAuth', ['$q', '$route', '$http', '$location', '$interval', 'ngmUser', function( $q, $route, $http, $location, $interval, ngmUser ) {

		// auth
		var ngmAuth = {

			OK: 200,
			UNAUTHORIZED: 401,
			FORBIDDEN: 403,
			APP: $location.path().split('/')[1],

			// guest
			GUEST: {
				adminRpcode: 'HQ',
				adminRname: 'Global',
				admin0pcode: 'ALL',
				admin0name: 'All',
				guest: true,
				visits: 1,
				cluster_id: 'health',
				organization: 'public',
				username: 'welcome',
				email: 'public'
			},

			// register
			register: function( user ) {

				// set the $http object
				var register = $http({
					method: 'POST',
					url: 'http://' + $location.host() + '/api/create',
					data: user
				});

				// register success
				register.success( function( result ) {

					// unset guest
					ngmUser.unset();
					// set localStorage
					ngmUser.set( result );

					// manage session
					// ngmAuth.setSessionTimeout( true, result );
					ngmAuth.setSessionTimeout( result );

				});

				return register;
			},

			// login
			login: function(user) {

				// set the $http object
				var login = $http({
					method: 'POST',
					url: 'http://' + $location.host() + '/api/login',
					data: user
				});

				// on success store in localStorage
				login.success( function( result ) {

					// unset guest
					ngmUser.unset();
					// set user last_logged_in
					result.last_logged_in = moment();
					// set localStorage
					ngmUser.set( result );

					// manage session
					// ngmAuth.setSessionTimeout( true, result );
					ngmAuth.setSessionTimeout( result );

				});

				return login;
			},

			passwordResetSend: function( user ) {

				var reset = $http({
					method: 'POST',
					url: 'http://' + $location.host() + '/api/send-email',
					data: user
				});

				return reset;
			},

			passwordReset: function(user) {

				// set the $http object
				var reset = $http({
					method: 'POST',
					url: 'http://' + $location.host() + '/api/password-reset',
					data: user
				});

				// on success store in localStorage
				reset.success( function( result ) {
					// unset guest
					ngmUser.unset();
					// set user
					ngmUser.set( result );
				});

				return reset;
			},

			logout: function() {

				// rotate icon
				$('.ngm-profile-icon').toggleClass('rotate');
				// set class
				$('.ngm-profile').toggleClass('active');
				$('.ngm-profile-menu-content').toggleClass('active');
				// toggle menu dropdown
				$('.ngm-profile-menu-content').slideToggle();

				// unset token, backend dosnt care about logouts
				ngmUser.unset();
				$location.path( '/' + $location.$$path.split('/')[1] + '/login' );

			},

			// Manages client session timeout
			setSessionTimeout: function( user ) {

				//
				console.log( user.last_logged_in )

				// tmp fix
				if ( !user.last_logged_in ) {
						// unset localStorage
						ngmUser.unset();
				} else {
					// get minutes since last login
					var minutes =
								moment.duration( moment().diff( user.last_logged_in ) ).asMinutes();

					// ( 24 * 60 ) = 1440 minutes
					if ( minutes > ( 24 * 60 ) ) {

						// unset localStorage
						ngmUser.unset();

						// redirect to login
						$location.path( '/' + ngmAuth.APP + '/login' );

					}
				}

			},

			// setup a public user
			grantPublicAccess: function( role ) {

				var deferred = $q.defer();

				// if no user exists
				if ( !ngmUser.get() ) {
					// set guest to localStorage
					ngmUser.set( ngmAuth.GUEST );
				}

				// resolve ok
				deferred.resolve( ngmAuth.OK );

				return deferred.promise;
			},

			// has role
			hasRole: function( role ) {

				var deferred = $q.defer();

				if ( ngmUser.hasRole( role ) ) {
					deferred.resolve(ngmAuth.OK );
				} else if ( ngmUser.get().guest ) {
					deferred.reject( ngmAuth.UNAUTHORIZED );
				} else {
					deferred.reject( ngmAuth.FORBIDDEN );
				}

				return deferred.promise;
			},

			// has any role
			hasAnyRole: function( roles ) {

				var deferred = $q.defer();

				if ( ngmUser.hasAnyRole( roles ) ) {
					deferred.resolve( ngmAuth.OK );
				} else if ( ngmUser.get().guest ) {
					deferred.reject( ngmAuth.UNAUTHORIZED );
				} else {
					deferred.reject( ngmAuth.FORBIDDEN );
				}

				return deferred.promise;
			},

			// anonymous
			isAnonymous: function() {

				var deferred = $q.defer();

				if ( !ngmUser.get() || ngmUser.get().guest ) {
					deferred.resolve( ngmAuth.OK );
				} else {
					deferred.reject( ngmAuth.FORBIDDEN );
				}

				return deferred.promise;
			},

			// authenticated
			isAuthenticated: function() {

				var deferred = $q.defer();

				if ( ngmUser.get() && !ngmUser.get().guest ) {
					deferred.resolve( ngmAuth.OK );
				} else {
					deferred.reject( ngmAuth.UNAUTHORIZED );
				}

				return deferred.promise;
			}

		};

		return ngmAuth;

	}])
	.factory('ngmAuthInterceptor', ['$q', '$injector', function($q, $injector) {

		// get user
		var ngmUser = $injector.get( 'ngmUser' );

		return {
			request: function( config ) {

				var token;

				// cover external APIs
				if ( ngmUser.get() && !config.externalApi ) {
					token = ngmUser.get().token;
				}
				if (token) {
					config.headers.Authorization = 'Bearer ' + token;
				}

				return config;
			}
		};

	}])
	.config( function( $httpProvider ) {
		$httpProvider.interceptors.push( 'ngmAuthInterceptor' );
	});
<commit_msg>ngm - check for last_logged_in user attributed, if not then unset()<commit_after>/**
 * @name ngmReportHubApp.factory:ngmUser
 * @description
 * # ngmAccess
 * Manages browser local storage
 *
 * @name ngmReportHubApp.factory:ngmUser
 * @description
 * # ngmAccess
 * Manages browser local storage
 *
 */
angular.module('ngmReportHub')
	.factory('ngmUser', function() {

		return {

			// get user from storage
			get: function() {
				return localStorage.getObject( 'auth_token' );
			},

			// set user to storage
			set: function( val ) {
				// JSON stringify result
				localStorage.setObject( 'auth_token', val );
			},

			// unset user from storage
			unset: function() {
				// remove lists / user
				localStorage.removeItem( 'lists' );
				localStorage.removeItem( 'auth_token' );
			},

			// check user role
			hasRole: function( role ) {
				// get from storage
				var user = localStorage.getObject( 'auth_token' );
				// if no user
				if ( !user ) return false;
				// else has role?
				return angular.uppercase( user.roles ).indexOf( angular.uppercase( role ) ) >= 0;
			},

			// match any role
			hasAnyRole: function( roles ) {
				var user = localStorage.getObject( 'auth_token' );
				return !!user.roles.filter(function( role ) {
					return angular.uppercase( roles ).indexOf( angular.uppercase( role ) ) >= 0;
				}).length;
			}

		};
	})
	.factory('ngmAuth', ['$q', '$route', '$http', '$location', '$interval', 'ngmUser', function( $q, $route, $http, $location, $interval, ngmUser ) {

		// auth
		var ngmAuth = {

			OK: 200,
			UNAUTHORIZED: 401,
			FORBIDDEN: 403,
			APP: $location.path().split('/')[1],

			// guest
			GUEST: {
				adminRpcode: 'HQ',
				adminRname: 'Global',
				admin0pcode: 'ALL',
				admin0name: 'All',
				guest: true,
				visits: 1,
				cluster_id: 'health',
				organization: 'public',
				username: 'welcome',
				email: 'public'
			},

			// register
			register: function( user ) {

				// set the $http object
				var register = $http({
					method: 'POST',
					url: 'http://' + $location.host() + '/api/create',
					data: user
				});

				// register success
				register.success( function( result ) {

					// unset guest
					ngmUser.unset();
					// set localStorage
					ngmUser.set( result );

					// manage session
					// ngmAuth.setSessionTimeout( true, result );
					ngmAuth.setSessionTimeout( result );

				});

				return register;
			},

			// login
			login: function(user) {

				// set the $http object
				var login = $http({
					method: 'POST',
					url: 'http://' + $location.host() + '/api/login',
					data: user
				});

				// on success store in localStorage
				login.success( function( result ) {

					// unset guest
					ngmUser.unset();
					// set user last_logged_in
					result.last_logged_in = moment();
					// set localStorage
					ngmUser.set( result );

					// manage session
					// ngmAuth.setSessionTimeout( true, result );
					ngmAuth.setSessionTimeout( result );

				});

				return login;
			},

			passwordResetSend: function( user ) {

				var reset = $http({
					method: 'POST',
					url: 'http://' + $location.host() + '/api/send-email',
					data: user
				});

				return reset;
			},

			passwordReset: function(user) {

				// set the $http object
				var reset = $http({
					method: 'POST',
					url: 'http://' + $location.host() + '/api/password-reset',
					data: user
				});

				// on success store in localStorage
				reset.success( function( result ) {
					// unset guest
					ngmUser.unset();
					// set user
					ngmUser.set( result );
				});

				return reset;
			},

			logout: function() {

				// rotate icon
				$('.ngm-profile-icon').toggleClass('rotate');
				// set class
				$('.ngm-profile').toggleClass('active');
				$('.ngm-profile-menu-content').toggleClass('active');
				// toggle menu dropdown
				$('.ngm-profile-menu-content').slideToggle();

				// unset token, backend dosnt care about logouts
				ngmUser.unset();
				$location.path( '/' + $location.$$path.split('/')[1] + '/login' );

			},

			// Manages client session timeout
			setSessionTimeout: function( user ) {

				//
				console.log( user )

				// tmp fix
				if ( !user.last_logged_in ) {
						// unset localStorage
						ngmUser.unset();
				} else {
					// get minutes since last login
					var minutes =
								moment.duration( moment().diff( user.last_logged_in ) ).asMinutes();

					// ( 24 * 60 ) = 1440 minutes
					if ( minutes > ( 24 * 60 ) ) {

						// unset localStorage
						ngmUser.unset();

						// redirect to login
						$location.path( '/' + ngmAuth.APP + '/login' );

					}
				}

			},

			// setup a public user
			grantPublicAccess: function( role ) {

				var deferred = $q.defer();

				// if no user exists
				if ( !ngmUser.get() ) {
					// set guest to localStorage
					ngmUser.set( ngmAuth.GUEST );
				}

				// resolve ok
				deferred.resolve( ngmAuth.OK );

				return deferred.promise;
			},

			// has role
			hasRole: function( role ) {

				var deferred = $q.defer();

				if ( ngmUser.hasRole( role ) ) {
					deferred.resolve(ngmAuth.OK );
				} else if ( ngmUser.get().guest ) {
					deferred.reject( ngmAuth.UNAUTHORIZED );
				} else {
					deferred.reject( ngmAuth.FORBIDDEN );
				}

				return deferred.promise;
			},

			// has any role
			hasAnyRole: function( roles ) {

				var deferred = $q.defer();

				if ( ngmUser.hasAnyRole( roles ) ) {
					deferred.resolve( ngmAuth.OK );
				} else if ( ngmUser.get().guest ) {
					deferred.reject( ngmAuth.UNAUTHORIZED );
				} else {
					deferred.reject( ngmAuth.FORBIDDEN );
				}

				return deferred.promise;
			},

			// anonymous
			isAnonymous: function() {

				var deferred = $q.defer();

				if ( !ngmUser.get() || ngmUser.get().guest ) {
					deferred.resolve( ngmAuth.OK );
				} else {
					deferred.reject( ngmAuth.FORBIDDEN );
				}

				return deferred.promise;
			},

			// authenticated
			isAuthenticated: function() {

				var deferred = $q.defer();

				if ( ngmUser.get() && !ngmUser.get().guest ) {
					deferred.resolve( ngmAuth.OK );
				} else {
					deferred.reject( ngmAuth.UNAUTHORIZED );
				}

				return deferred.promise;
			}

		};

		return ngmAuth;

	}])
	.factory('ngmAuthInterceptor', ['$q', '$injector', function($q, $injector) {

		// get user
		var ngmUser = $injector.get( 'ngmUser' );

		return {
			request: function( config ) {

				var token;

				// cover external APIs
				if ( ngmUser.get() && !config.externalApi ) {
					token = ngmUser.get().token;
				}
				if (token) {
					config.headers.Authorization = 'Bearer ' + token;
				}

				return config;
			}
		};

	}])
	.config( function( $httpProvider ) {
		$httpProvider.interceptors.push( 'ngmAuthInterceptor' );
	});
<|endoftext|>


<commit_before>/*******************************************************************************
 * Nome: QuizziPedia::Front-End::Controllers::AppController;
 * Description: questa classe permette di gestire la lingua dell'applicazione e
 * tiene aggiornate le direttive di BreadBarDirective, MenuBarDirective;
 * Creation data: 30-04-2016;
 * Author: Matteo Granzotto;
 * License: MIT.
 ********************************************************************************
 * Updates history
 *-------------------------------------------------------------------------------
 * ID: AppController_20160502;
 * Update data: 02-05-2016;
 * Description: Scritta la gestione dell'autorizzazione dell'utente;
 * Author: Matteo Granzotto.
 *-------------------------------------------------------------------------------
 * ID: AppController_20160430;
 * Update data: 30-04-2016;
 * Description: Scritta la classe;
 * Author: Matteo Granzotto.
 *-------------------------------------------------------------------------------
 *******************************************************************************/

app.controller('AppController', AppController);

AppController.$inject = ['$scope','$rootScope', '$mdDialog', '$location', '$routeParams', 'UserDetailsModel', 'AuthService', 'LangModel', 'LangService', 'MenuBarModel'];
function AppController ($scope, $rootScope, $mdDialog, $location, $routeParams, UserDetailsModel, AuthService, LangModel, LangService, MenuBarModel) {
    var lang;
    if(AuthService.isLogged() === "true" && $rootScope.userLogged === undefined) {
        AuthService.giveMe($routeParams.lang)
            .then(function(result){
                if(result.data != false) {
                    console.log(result.data);
                    $rootScope.userLogged = new UserDetailsModel(result.data.name, result.data.surname, result.data.email, "", result.data.username, "" , result.data.experienceLevel, result.data.privilege, result.data._id);
                    $rootScope.directivesChoose= MenuBarModel.getDirectives(location, $rootScope.userLogged.getPrivilege());
                    $rootScope.$broadcast("userDownloaded", true);
                }
                else{
                    $rootScope.error = new ErrorInfoModel("6", result.message, "Errore Login");
                    AuthService.resetCookies();
                    $rootScope.$broadcast("userDownloaded", false);
                }
            } ,function (err){
                $rootScope.error = new ErrorInfoModel("1", "Errore nella Login", "Login non effettuata");
            });
    }

    checkUrl($location.path());

    if($rootScope.userLogged != undefined) {
        $rootScope.directivesChoose= MenuBarModel.getDirectives(location, $rootScope.userLogged.getPrivilege());
    }

    if($rootScope.systemLang === undefined) {
        $rootScope.systemLang=$routeParams.lang;
        lang = getLang($routeParams.lang);
        lang.then(function(data){
            $rootScope.listOfKeys= data.getListOfKeys();
        });
    }

    function getLang (lang) {
        var setOfKeywords = LangService.getKeywords(lang);
        return setOfKeywords.then(function(data){
            return new LangModel(lang, data);
        });
    }

    function checkUrl(path) {
        var pathLocal = path+ '';
        var variableOfPath= pathLocal.split("/");
        var combination = "noAuth";
        if((variableOfPath.indexOf("login") != -1 || variableOfPath.indexOf("signup") != -1) && $rootScope.userLogged != undefined && $rootScope.userLogged.getPrivilege() != "")
        {
            console.log("Redirect to home");
            //$location.path('/'+$routeParams.lang+'/home');
        }
    }

}
<commit_msg>aggiunto evento<commit_after>/*******************************************************************************
 * Nome: QuizziPedia::Front-End::Controllers::AppController;
 * Description: questa classe permette di gestire la lingua dell'applicazione e
 * tiene aggiornate le direttive di BreadBarDirective, MenuBarDirective;
 * Creation data: 30-04-2016;
 * Author: Matteo Granzotto;
 * License: MIT.
 ********************************************************************************
 * Updates history
 *-------------------------------------------------------------------------------
 * ID: AppController_20160502;
 * Update data: 02-05-2016;
 * Description: Scritta la gestione dell'autorizzazione dell'utente;
 * Author: Matteo Granzotto.
 *-------------------------------------------------------------------------------
 * ID: AppController_20160430;
 * Update data: 30-04-2016;
 * Description: Scritta la classe;
 * Author: Matteo Granzotto.
 *-------------------------------------------------------------------------------
 *******************************************************************************/

app.controller('AppController', AppController);

AppController.$inject = ['$scope','$rootScope', '$mdDialog', '$location', '$routeParams', 'UserDetailsModel', 'AuthService', 'LangModel', 'LangService', 'MenuBarModel'];
function AppController ($scope, $rootScope, $mdDialog, $location, $routeParams, UserDetailsModel, AuthService, LangModel, LangService, MenuBarModel) {
    var lang;
    if(AuthService.isLogged() === "true" && $rootScope.userLogged === undefined) {
        AuthService.giveMe($routeParams.lang)
            .then(function(result){
                if(result.data != false) {
                    console.log(result.data);
                    $rootScope.userLogged = new UserDetailsModel(result.data.name, result.data.surname, result.data.email, "", result.data.username, "" , result.data.experienceLevel, result.data.privilege, result.data._id);
                    $rootScope.directivesChoose= MenuBarModel.getDirectives(location, $rootScope.userLogged.getPrivilege());
                    //$rootScope.$emit("userDownloaded", true);
                    $rootScope.$broadcast("userDownloaded", true);
                }
                else{
                    $rootScope.error = new ErrorInfoModel("6", result.message, "Errore Login");
                    AuthService.resetCookies();
                    //$rootScope.$emit("userDownloaded", false);
                    $rootScope.$broadcast("userDownloaded", false);
                }
            } ,function (err){
                $rootScope.error = new ErrorInfoModel("1", "Errore nella Login", "Login non effettuata");
            });
    }

    checkUrl($location.path());

    if($rootScope.userLogged != undefined) {
        $rootScope.directivesChoose= MenuBarModel.getDirectives(location, $rootScope.userLogged.getPrivilege());
    }

    if($rootScope.systemLang === undefined) {
        $rootScope.systemLang=$routeParams.lang;
        lang = getLang($routeParams.lang);
        lang.then(function(data){
            $rootScope.listOfKeys= data.getListOfKeys();
        });
    }

    function getLang (lang) {
        var setOfKeywords = LangService.getKeywords(lang);
        return setOfKeywords.then(function(data){
            return new LangModel(lang, data);
        });
    }

    function checkUrl(path) {
        var pathLocal = path+ '';
        var variableOfPath= pathLocal.split("/");
        var combination = "noAuth";
        if((variableOfPath.indexOf("login") != -1 || variableOfPath.indexOf("signup") != -1) && $rootScope.userLogged != undefined && $rootScope.userLogged.getPrivilege() != "")
        {
            console.log("Redirect to home");
            //$location.path('/'+$routeParams.lang+'/home');
        }
    }

}
<|endoftext|>


<commit_before>/**
 * Loads a Wavefront .mtl file specifying materials
 *
 * @author angelxuanchang
 */

THREE.MTLLoader = function ( manager ) {

	THREE.Loader.call( this, manager );

};

THREE.MTLLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {

	constructor: THREE.MTLLoader,

	/**
	 * Loads and parses a MTL asset from a URL.
	 *
	 * @param {String} url - URL to the MTL file.
	 * @param {Function} [onLoad] - Callback invoked with the loaded object.
	 * @param {Function} [onProgress] - Callback for download progress.
	 * @param {Function} [onError] - Callback for download errors.
	 *
	 * @see setPath setResourcePath
	 *
	 * @note In order for relative texture references to resolve correctly
	 * you must call setResourcePath() explicitly prior to load.
	 */
	load: function ( url, onLoad, onProgress, onError ) {

		var scope = this;

		var path = ( this.path === '' ) ? THREE.LoaderUtils.extractUrlBase( url ) : this.path;

		var loader = new THREE.FileLoader( this.manager );
		loader.setPath( this.path );
		loader.load( url, function ( text ) {

			onLoad( scope.parse( text, path ) );

		}, onProgress, onError );

	},

	setMaterialOptions: function ( value ) {

		this.materialOptions = value;
		return this;

	},

	/**
	 * Parses a MTL file.
	 *
	 * @param {String} text - Content of MTL file
	 * @return {THREE.MTLLoader.MaterialCreator}
	 *
	 * @see setPath setResourcePath
	 *
	 * @note In order for relative texture references to resolve correctly
	 * you must call setResourcePath() explicitly prior to parse.
	 */
	parse: function ( text, path ) {

		var lines = text.split( '\n' );
		var info = {};
		var delimiter_pattern = /\s+/;
		var materialsInfo = {};

		for ( var i = 0; i < lines.length; i ++ ) {

			var line = lines[ i ];
			line = line.trim();

			if ( line.length === 0 || line.charAt( 0 ) === '#' ) {

				// Blank line or comment ignore
				continue;

			}

			var pos = line.indexOf( ' ' );

			var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
			key = key.toLowerCase();

			var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
			value = value.trim();

			if ( key === 'newmtl' ) {

				// New material

				info = { name: value };
				materialsInfo[ value ] = info;

			} else {

				if ( key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke' ) {

					var ss = value.split( delimiter_pattern, 3 );
					info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];

				} else {

					info[ key ] = value;

				}

			}

		}

		var materialCreator = new THREE.MTLLoader.MaterialCreator( this.resourcePath || path, this.materialOptions );
		materialCreator.setCrossOrigin( this.crossOrigin );
		materialCreator.setManager( this.manager );
		materialCreator.setMaterials( materialsInfo );
		return materialCreator;

	}

} );

/**
 * Create a new THREE-MTLLoader.MaterialCreator
 * @param baseUrl - Url relative to which textures are loaded
 * @param options - Set of options on how to construct the materials
 *                  side: Which side to apply the material
 *                        THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
 *                  wrap: What type of wrapping to apply for textures
 *                        THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
 *                  normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
 *                                Default: false, assumed to be already normalized
 *                  ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
 *                                  Default: false
 * @constructor
 */

THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {

	this.baseUrl = baseUrl || '';
	this.options = options;
	this.materialsInfo = {};
	this.materials = {};
	this.materialsArray = [];
	this.nameLookup = {};

	this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
	this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;

};

THREE.MTLLoader.MaterialCreator.prototype = {

	constructor: THREE.MTLLoader.MaterialCreator,

	crossOrigin: 'anonymous',

	setCrossOrigin: function ( value ) {

		this.crossOrigin = value;
		return this;

	},

	setManager: function ( value ) {

		this.manager = value;

	},

	setMaterials: function ( materialsInfo ) {

		this.materialsInfo = this.convert( materialsInfo );
		this.materials = {};
		this.materialsArray = [];
		this.nameLookup = {};

	},

	convert: function ( materialsInfo ) {

		if ( ! this.options ) return materialsInfo;

		var converted = {};

		for ( var mn in materialsInfo ) {

			// Convert materials info into normalized form based on options

			var mat = materialsInfo[ mn ];

			var covmat = {};

			converted[ mn ] = covmat;

			for ( var prop in mat ) {

				var save = true;
				var value = mat[ prop ];
				var lprop = prop.toLowerCase();

				switch ( lprop ) {

					case 'kd':
					case 'ka':
					case 'ks':

						// Diffuse color (color under white light) using RGB values

						if ( this.options && this.options.normalizeRGB ) {

							value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];

						}

						if ( this.options && this.options.ignoreZeroRGBs ) {

							if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {

								// ignore

								save = false;

							}

						}

						break;

					default:

						break;

				}

				if ( save ) {

					covmat[ lprop ] = value;

				}

			}

		}

		return converted;

	},

	preload: function () {

		for ( var mn in this.materialsInfo ) {

			this.create( mn );

		}

	},

	getIndex: function ( materialName ) {

		return this.nameLookup[ materialName ];

	},

	getAsArray: function () {

		var index = 0;

		for ( var mn in this.materialsInfo ) {

			this.materialsArray[ index ] = this.create( mn );
			this.nameLookup[ mn ] = index;
			index ++;

		}

		return this.materialsArray;

	},

	create: function ( materialName ) {

		if ( this.materials[ materialName ] === undefined ) {

			this.createMaterial_( materialName );

		}

		return this.materials[ materialName ];

	},

	createMaterial_: function ( materialName ) {

		// Create material

		var scope = this;
		var mat = this.materialsInfo[ materialName ];
		var params = {

			name: materialName,
			side: this.side

		};

		function resolveURL( baseUrl, url ) {

			if ( typeof url !== 'string' || url === '' )
				return '';

			// Absolute URL
			if ( /^https?:\/\//i.test( url ) ) return url;

			return baseUrl + url;

		}

		function setMapForType( mapType, value ) {

			if ( params[ mapType ] ) return; // Keep the first encountered texture

			var texParams = scope.getTextureParams( value, params );
			var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );

			map.repeat.copy( texParams.scale );
			map.offset.copy( texParams.offset );

			map.wrapS = scope.wrap;
			map.wrapT = scope.wrap;

			params[ mapType ] = map;

		}

		for ( var prop in mat ) {

			var value = mat[ prop ];
			var n;

			if ( value === '' ) continue;

			switch ( prop.toLowerCase() ) {

				// Ns is material specular exponent

				case 'kd':

					// Diffuse color (color under white light) using RGB values

					params.color = new THREE.Color().fromArray( value );

					break;

				case 'ks':

					// Specular color (color when light is reflected from shiny surface) using RGB values
					params.specular = new THREE.Color().fromArray( value );

					break;

				case 'ke':

					// Emissive using RGB values
					params.emissive = new THREE.Color().fromArray( value );

					break;

				case 'map_kd':

					// Diffuse texture map

					setMapForType( "map", value );

					break;

				case 'map_ks':

					// Specular map

					setMapForType( "specularMap", value );

					break;

				case 'map_ke':

					// Emissive map

					setMapForType( "emissiveMap", value );

					break;

				case 'norm':

					setMapForType( "normalMap", value );

					break;

				case 'map_bump':
				case 'bump':

					// Bump texture map

					setMapForType( "bumpMap", value );

					break;

				case 'map_d':

					// Alpha map

					setMapForType( "alphaMap", value );
					params.transparent = true;

					break;

				case 'ns':

					// The specular exponent (defines the focus of the specular highlight)
					// A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.

					params.shininess = parseFloat( value );

					break;

				case 'd':
					n = parseFloat( value );

					if ( n < 1 ) {

						params.opacity = n;
						params.transparent = true;

					}

					break;

				case 'tr':
					n = parseFloat( value );

					if ( this.options && this.options.invertTrProperty ) n = 1 - n;

					if ( n > 0 ) {

						params.opacity = 1 - n;
						params.transparent = true;

					}

					break;

				default:
					break;

			}

		}

		this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
		return this.materials[ materialName ];

	},

	getTextureParams: function ( value, matParams ) {

		var texParams = {

			scale: new THREE.Vector2( 1, 1 ),
			offset: new THREE.Vector2( 0, 0 )

		 };

		var items = value.split( /\s+/ );
		var pos;

		pos = items.indexOf( '-bm' );

		if ( pos >= 0 ) {

			matParams.bumpScale = parseFloat( items[ pos + 1 ] );
			items.splice( pos, 2 );

		}

		pos = items.indexOf( '-s' );

		if ( pos >= 0 ) {

			texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
			items.splice( pos, 4 ); // we expect 3 parameters here!

		}

		pos = items.indexOf( '-o' );

		if ( pos >= 0 ) {

			texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
			items.splice( pos, 4 ); // we expect 3 parameters here!

		}

		texParams.url = items.join( ' ' ).trim();
		return texParams;

	},

	loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {

		var texture;
		var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
		var loader = manager.getHandler( url );

		if ( loader === null ) {

			loader = new THREE.TextureLoader( manager );

		}

		if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
		texture = loader.load( url, onLoad, onProgress, onError );

		if ( mapping !== undefined ) texture.mapping = mapping;

		return texture;

	}

};<commit_msg>Smooth mesh lighting<commit_after>/**
 * Loads a Wavefront .mtl file specifying materials
 *
 * @author angelxuanchang
 */

THREE.MTLLoader = function ( manager ) {

	THREE.Loader.call( this, manager );

};

THREE.MTLLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {

	constructor: THREE.MTLLoader,

	/**
	 * Loads and parses a MTL asset from a URL.
	 *
	 * @param {String} url - URL to the MTL file.
	 * @param {Function} [onLoad] - Callback invoked with the loaded object.
	 * @param {Function} [onProgress] - Callback for download progress.
	 * @param {Function} [onError] - Callback for download errors.
	 *
	 * @see setPath setResourcePath
	 *
	 * @note In order for relative texture references to resolve correctly
	 * you must call setResourcePath() explicitly prior to load.
	 */
	load: function ( url, onLoad, onProgress, onError ) {

		var scope = this;

		var path = ( this.path === '' ) ? THREE.LoaderUtils.extractUrlBase( url ) : this.path;

		var loader = new THREE.FileLoader( this.manager );
		loader.setPath( this.path );
		loader.load( url, function ( text ) {

			onLoad( scope.parse( text, path ) );

		}, onProgress, onError );

	},

	setMaterialOptions: function ( value ) {

		this.materialOptions = value;
		return this;

	},

	/**
	 * Parses a MTL file.
	 *
	 * @param {String} text - Content of MTL file
	 * @return {THREE.MTLLoader.MaterialCreator}
	 *
	 * @see setPath setResourcePath
	 *
	 * @note In order for relative texture references to resolve correctly
	 * you must call setResourcePath() explicitly prior to parse.
	 */
	parse: function ( text, path ) {

		var lines = text.split( '\n' );
		var info = {};
		var delimiter_pattern = /\s+/;
		var materialsInfo = {};

		for ( var i = 0; i < lines.length; i ++ ) {

			var line = lines[ i ];
			line = line.trim();

			if ( line.length === 0 || line.charAt( 0 ) === '#' ) {

				// Blank line or comment ignore
				continue;

			}

			var pos = line.indexOf( ' ' );

			var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
			key = key.toLowerCase();

			var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
			value = value.trim();

			if ( key === 'newmtl' ) {

				// New material

				info = { name: value };
				materialsInfo[ value ] = info;

			} else {

				if ( key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke' ) {

					var ss = value.split( delimiter_pattern, 3 );
					info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];

				} else {

					info[ key ] = value;

				}

			}

		}

		var materialCreator = new THREE.MTLLoader.MaterialCreator( this.resourcePath || path, this.materialOptions );
		materialCreator.setCrossOrigin( this.crossOrigin );
		materialCreator.setManager( this.manager );
		materialCreator.setMaterials( materialsInfo );
		return materialCreator;

	}

} );

/**
 * Create a new THREE-MTLLoader.MaterialCreator
 * @param baseUrl - Url relative to which textures are loaded
 * @param options - Set of options on how to construct the materials
 *                  side: Which side to apply the material
 *                        THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
 *                  wrap: What type of wrapping to apply for textures
 *                        THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
 *                  normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
 *                                Default: false, assumed to be already normalized
 *                  ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
 *                                  Default: false
 * @constructor
 */

THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {

	this.baseUrl = baseUrl || '';
	this.options = options;
	this.materialsInfo = {};
	this.materials = {};
	this.materialsArray = [];
	this.nameLookup = {};

	this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
	this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;

};

THREE.MTLLoader.MaterialCreator.prototype = {

	constructor: THREE.MTLLoader.MaterialCreator,

	crossOrigin: 'anonymous',

	setCrossOrigin: function ( value ) {

		this.crossOrigin = value;
		return this;

	},

	setManager: function ( value ) {

		this.manager = value;

	},

	setMaterials: function ( materialsInfo ) {

		this.materialsInfo = this.convert( materialsInfo );
		this.materials = {};
		this.materialsArray = [];
		this.nameLookup = {};

	},

	convert: function ( materialsInfo ) {

		if ( ! this.options ) return materialsInfo;

		var converted = {};

		for ( var mn in materialsInfo ) {

			// Convert materials info into normalized form based on options

			var mat = materialsInfo[ mn ];

			var covmat = {};

			converted[ mn ] = covmat;

			for ( var prop in mat ) {

				var save = true;
				var value = mat[ prop ];
				var lprop = prop.toLowerCase();

				switch ( lprop ) {

					case 'kd':
					case 'ka':
					case 'ks':

						// Diffuse color (color under white light) using RGB values

						if ( this.options && this.options.normalizeRGB ) {

							value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];

						}

						if ( this.options && this.options.ignoreZeroRGBs ) {

							if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {

								// ignore

								save = false;

							}

						}

						break;

					default:

						break;

				}

				if ( save ) {

					covmat[ lprop ] = value;

				}

			}

		}

		return converted;

	},

	preload: function () {

		for ( var mn in this.materialsInfo ) {

			this.create( mn );

		}

	},

	getIndex: function ( materialName ) {

		return this.nameLookup[ materialName ];

	},

	getAsArray: function () {

		var index = 0;

		for ( var mn in this.materialsInfo ) {

			this.materialsArray[ index ] = this.create( mn );
			this.nameLookup[ mn ] = index;
			index ++;

		}

		return this.materialsArray;

	},

	create: function ( materialName ) {

		if ( this.materials[ materialName ] === undefined ) {

			this.createMaterial_( materialName );

		}

		return this.materials[ materialName ];

	},

	createMaterial_: function ( materialName ) {

		// Create material

		var scope = this;
		var mat = this.materialsInfo[ materialName ];
		var params = {

			name: materialName,
			side: this.side

		};

		function resolveURL( baseUrl, url ) {

			if ( typeof url !== 'string' || url === '' )
				return '';

			// Absolute URL
			if ( /^https?:\/\//i.test( url ) ) return url;

			return baseUrl + url;

		}

		function setMapForType( mapType, value ) {

			if ( params[ mapType ] ) return; // Keep the first encountered texture

			var texParams = scope.getTextureParams( value, params );
			var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );

			map.repeat.copy( texParams.scale );
			map.offset.copy( texParams.offset );

			map.wrapS = scope.wrap;
			map.wrapT = scope.wrap;

			params[ mapType ] = map;

		}

		for ( var prop in mat ) {

			var value = mat[ prop ];
			var n;

			if ( value === '' ) continue;

			switch ( prop.toLowerCase() ) {

				// Ns is material specular exponent

				case 'kd':

					// Diffuse color (color under white light) using RGB values

					params.color = new THREE.Color().fromArray( value );

					break;

				case 'ks':

					// Specular color (color when light is reflected from shiny surface) using RGB values
					// params.specular = new THREE.Color().fromArray( value );

					break;

				case 'ke':

					// Emissive using RGB values
					params.emissive = new THREE.Color().fromArray( value );

					break;

				case 'map_kd':

					// Diffuse texture map

					setMapForType( "map", value );

					break;

				case 'map_ks':

					// Specular map

					setMapForType( "specularMap", value );

					break;

				case 'map_ke':

					// Emissive map

					setMapForType( "emissiveMap", value );

					break;

				case 'norm':

					setMapForType( "normalMap", value );

					break;

				case 'map_bump':
				case 'bump':

					// Bump texture map

					setMapForType( "bumpMap", value );

					break;

				case 'map_d':

					// Alpha map

					setMapForType( "alphaMap", value );
					params.transparent = true;

					break;

				case 'ns':

					// The specular exponent (defines the focus of the specular highlight)
					// A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.

					// params.shininess = parseFloat( value );

					break;

				case 'd':
					n = parseFloat( value );

					if ( n < 1 ) {

						params.opacity = n;
						params.transparent = true;

					}

					break;

				case 'tr':
					n = parseFloat( value );

					if ( this.options && this.options.invertTrProperty ) n = 1 - n;

					if ( n > 0 ) {

						params.opacity = 1 - n;
						params.transparent = true;

					}

					break;

				default:
					break;

			}

		}

		this.materials[ materialName ] = new THREE.MeshBasicMaterial( params );
		return this.materials[ materialName ];

	},

	getTextureParams: function ( value, matParams ) {

		var texParams = {

			scale: new THREE.Vector2( 1, 1 ),
			offset: new THREE.Vector2( 0, 0 )

		 };

		var items = value.split( /\s+/ );
		var pos;

		pos = items.indexOf( '-bm' );

		if ( pos >= 0 ) {

			matParams.bumpScale = parseFloat( items[ pos + 1 ] );
			items.splice( pos, 2 );

		}

		pos = items.indexOf( '-s' );

		if ( pos >= 0 ) {

			texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
			items.splice( pos, 4 ); // we expect 3 parameters here!

		}

		pos = items.indexOf( '-o' );

		if ( pos >= 0 ) {

			texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
			items.splice( pos, 4 ); // we expect 3 parameters here!

		}

		texParams.url = items.join( ' ' ).trim();
		return texParams;

	},

	loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {

		var texture;
		var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
		var loader = manager.getHandler( url );

		if ( loader === null ) {

			loader = new THREE.TextureLoader( manager );

		}

		if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
		texture = loader.load( url, onLoad, onProgress, onError );

		if ( mapping !== undefined ) texture.mapping = mapping;

		return texture;

	}

};<|endoftext|>


<commit_before>module.exports(){

	'configGRIFFINclover': function(index, suppressors){
		var names = [],
			MSC = [],
			masterChan = (index<9) ? 0 : 1,
			firstCollectorChan = ((index-1)%8)*2, //ie, collector channel of first (of 2) GRIF16s used for this clover.
			collectorChan,
			ADC,
			name, address,
			crystalPrefix = 'GRG' + ((index<10) ? '0'+index : index),
			color = ['B', 'G', 'R', 'W'],
			crystalSuffix = ['N00A', 'N00B'],
			vetoPrefix = 'GRS' + ((index<10) ? '0'+index : index),
			i,j,k;

		if(suppressors){
			//HPGe
			for(i=0; i<crystalSuffix.length; i++){
				for(j=0; j<color.length; j++){
					name = crystalPrefix + color[j] + crystalSuffix[i];

					collectorChan = firstCollectorChan + i;
					ADC = j;
					address = (masterChan << 12) | (collectorChan << 8) | ADC;

					names.push(name);
					MSC.push(address);
				}
			}

			//BGO
			for(j=0; j<color.length; j++){
				for(i=0; i<5; i++){
					name = vetoPrefix + color[j] + 'N0' + i + 'X';

					collectorChan = firstCollectorChan + ((j<2) ? 0 : 1);
					ADC = 5 + (j%2)*5+i;
					address = (masterChan << 12) | (collectorChan << 8) | ADC;

					names.push(name);
					MSC.push(address);
				}
			}

		} else{
			for(i=0; i<crystalSuffix.length; i++){
				for(j=0; j<color.length; j++){
					name = crystalPrefix + color[j] + crystalSuffix[i];

					collectorChan = firstCollectorChan;
					ADC = j + 4*i;
					address = (masterChan << 12) | (collectorChan << 8) | ADC;

					names.push(name);
					MSC.push(address);
				}
			}
		}

		return [names, MSC];
	}

	'configSCEPTAR': function(US, DS, ZDS){
		var names = [],
			MSC = [],
			i;

		if(DS){
			for(i=1; i<11; i++){
				names.push('SEP' + ((i<10) ? '0'+i : i) + 'XN00X');
				MSC.push((2 << 12) | ( (4+Math.floor((i-1)/4)) << 8) | (i-1)%4);
			}
		} else if(ZDS){
			names.push('ZDS01XN00X');
			MSC.push(0x2601);
			names.push('ZDS01XT00X');
			MSC.push(0x2208);
		}

		if(US){
			for(i=11; i<21; i++){
				names.push('SEP' + i + 'XN00X');
				MSC.push((2 << 12) | ( ( 6 + Math.floor((i - 11 + 2)/4) ) << 8) | (i+3)%4);
			}
		}

		return [names, MSC];
	}

	'configDANTE': function(US, DS){
		var names = [],
			MSC = [],
			i, j, min, max, suppressorMSC;

		if(!US && !DS) return [names, MSC]; //do nothing

		if(DS)
			min = 0;
		else
			min = 4;

		if(US)
			max = 8;
		else
			max = 4;

		//LaBr - energy
		for(i=min; i<max; i++){
			names.push('DAL0'+(1+i)+'XN00X');
			MSC.push((2 << 12) | ( 1 << 8) | i);
		}
		//LaBr - TAC
		for(i=min; i<max; i++){
			names.push('DAL0'+(1+i)+'XT00X');
			MSC.push((2 << 12) | ( 2 << 8) | i);
		}
		//Suppressors
		for(i=min; i<max; i++){
			for(j=0; j<3; j++){
				names.push('DAS0'+(1+i)+'XN0'+j+'X');
				//first 8 go in the bottom of 0x2100
				if(i<2 || (i==2 && j<2))
					MSC.push((2 << 12) | ( 1 << 8) | (3*i+j + 8) );
				//rest stack up in 0x2300
				else
					MSC.push((2 << 12) | ( 3 << 8) | (3*i+j - 8) );
			}
		}

		return [names, MSC];

	}

	'configPACES': function(){
		var names = ['PAC01XN00X', 'PAC02XN00X', 'PAC03XN00X', 'PAC04XN00X', 'PAC05XN00X'],
			MSC = [0x2000, 0x2001, 0x2002, 0x2003, 0x2004];

			return [names, MSC];
	}

	'configSPICE': function(){
		var names = [],
			MSC = [],
			i, index;

		for(i=0; i<120; i++){
			index = i;
			if(index < 10) index = '00'+index;
			else if(index < 100) index = '0'+index;

			names.push('SPI00XN'+index);
			MSC.push(0x4000 + 256*Math.floor(i/16) + (i%16) );
		}

		return [names, MSC];
	}

	'configS2S3': function(type){
		var names = [],
			MSC = [],
			radial = 24, azimuthal, typeCode,
			i;

		if(type == 2){
			typeCode = 'E';
			azimuthal = 16;
		} else if(type == 3){
			typeCode = 'Z';
			azimuthal = 32;
		}
		//radial first: first 8 finishes off last digitizer, other 16 fill the next; then azimuthal channels fill 1 or 2 more grif16s
		for(i=0; i<radial; i++){
			names.push('SP'+typeCode+'00DP'+((i<10)? '0'+i : i)+'X');

			if(i<8){
				MSC.push(0x4708 + i);
			} else{
				MSC.push(0x4800 + i-8);
			}
		}

		for(i=0; i<azimuthal; i++){
			names.push('SP'+typeCode+'00DN'+((i<10)? '0'+i : i)+'X');

			MSC.push(0x4900 + Math.floor(i/16)*0x100 + (i%16) );
		}

		return [names, MSC];
	}

	'configDESCANT': function(){
		var names = [],
			MSC = [],
			cableBundles = [],
			i, j;

		//weird ordering 'thanks' to cable bundling constraints:
		cableBundles = [
			[46, 65, 66, 67],
			[13, 27, 26, 45],
			[28, 47, 48, 68],
			[5, 14, 15, 29],
			[0, 49, 69],
			[1, 6, 30],
			[16, 31, 50, 51],
			[7, 17, 18, 32],
			[33, 52, 53, 54],

			[43, 44, 63, 64],
			[25, 42, 62],
			[4, 11, 12, 24],
			[23, 41, 40, 61],
			[10, 22, 39, 60],
			[2, 3, 8, 9],
			[21, 38, 59],
			[20, 37, 57, 58],
			[19, 36, 56],
			[34, 35, 55]
		]

		for(i=0; i<cableBundles.length; i++){
			for(j=0; j<cableBundles[i].length; j++){
				names.push('DSC' + ((cableBundles[i][j] < 10) ? '0'+cableBundles[i][j] : cableBundles[i][j]) + 'XN00X');

				//first three cable bundles are on collector 0x2, rest are on 0x3
				if(i<3){
					MSC.push(0x2000 | ((9+i)<<8) | j )
				} else{
					MSC.push(0x3000 | ((i-3)<<8) | j )
				}
			}
		}

		return [names, MSC];
	}

}<commit_msg>refactoring MSC construction<commit_after>module.exports = {

	'configGRIFFINclover': function(index, suppressors){
		var names = [],
			MSC = [],
			masterChan = (index<9) ? 0 : 1,
			firstCollectorChan = ((index-1)%8)*2, //ie, collector channel of first (of 2) GRIF16s used for this clover.
			collectorChan,
			ADC,
			name, address,
			crystalPrefix = 'GRG' + ((index<10) ? '0'+index : index),
			color = ['B', 'G', 'R', 'W'],
			crystalSuffix = ['N00A', 'N00B'],
			vetoPrefix = 'GRS' + ((index<10) ? '0'+index : index),
			i,j,k;

		if(suppressors){
			//HPGe
			for(i=0; i<crystalSuffix.length; i++){
				for(j=0; j<color.length; j++){
					name = crystalPrefix + color[j] + crystalSuffix[i];

					collectorChan = firstCollectorChan + i;
					ADC = j;
					address = (masterChan << 12) | (collectorChan << 8) | ADC;

					names.push(name);
					MSC.push(address);
				}
			}

			//BGO
			for(j=0; j<color.length; j++){
				for(i=0; i<5; i++){
					name = vetoPrefix + color[j] + 'N0' + i + 'X';

					collectorChan = firstCollectorChan + ((j<2) ? 0 : 1);
					ADC = 5 + (j%2)*5+i;
					address = (masterChan << 12) | (collectorChan << 8) | ADC;

					names.push(name);
					MSC.push(address);
				}
			}

		} else{
			for(i=0; i<crystalSuffix.length; i++){
				for(j=0; j<color.length; j++){
					name = crystalPrefix + color[j] + crystalSuffix[i];

					collectorChan = firstCollectorChan;
					ADC = j + 4*i;
					address = (masterChan << 12) | (collectorChan << 8) | ADC;

					names.push(name);
					MSC.push(address);
				}
			}
		}

		return [names, MSC];
	}

	'configSCEPTAR': function(US, DS, ZDS){
		var names = [],
			MSC = [],
			i;

		if(DS){
			for(i=1; i<11; i++){
				names.push('SEP' + ((i<10) ? '0'+i : i) + 'XN00X');
				MSC.push((2 << 12) | ( (4+Math.floor((i-1)/4)) << 8) | (i-1)%4);
			}
		} else if(ZDS){
			names.push('ZDS01XN00X');
			MSC.push(0x2601);
			names.push('ZDS01XT00X');
			MSC.push(0x2208);
		}

		if(US){
			for(i=11; i<21; i++){
				names.push('SEP' + i + 'XN00X');
				MSC.push((2 << 12) | ( ( 6 + Math.floor((i - 11 + 2)/4) ) << 8) | (i+3)%4);
			}
		}

		return [names, MSC];
	}

	'configDANTE': function(US, DS){
		var names = [],
			MSC = [],
			i, j, min, max, suppressorMSC;

		if(!US && !DS) return [names, MSC]; //do nothing

		if(DS)
			min = 0;
		else
			min = 4;

		if(US)
			max = 8;
		else
			max = 4;

		//LaBr - energy
		for(i=min; i<max; i++){
			names.push('DAL0'+(1+i)+'XN00X');
			MSC.push((2 << 12) | ( 1 << 8) | i);
		}
		//LaBr - TAC
		for(i=min; i<max; i++){
			names.push('DAL0'+(1+i)+'XT00X');
			MSC.push((2 << 12) | ( 2 << 8) | i);
		}
		//Suppressors
		for(i=min; i<max; i++){
			for(j=0; j<3; j++){
				names.push('DAS0'+(1+i)+'XN0'+j+'X');
				//first 8 go in the bottom of 0x2100
				if(i<2 || (i==2 && j<2))
					MSC.push((2 << 12) | ( 1 << 8) | (3*i+j + 8) );
				//rest stack up in 0x2300
				else
					MSC.push((2 << 12) | ( 3 << 8) | (3*i+j - 8) );
			}
		}

		return [names, MSC];

	}

	'configPACES': function(){
		var names = ['PAC01XN00X', 'PAC02XN00X', 'PAC03XN00X', 'PAC04XN00X', 'PAC05XN00X'],
			MSC = [0x2000, 0x2001, 0x2002, 0x2003, 0x2004];

			return [names, MSC];
	}

	'configSPICE': function(){
		var names = [],
			MSC = [],
			i, index;

		for(i=0; i<120; i++){
			index = i;
			if(index < 10) index = '00'+index;
			else if(index < 100) index = '0'+index;

			names.push('SPI00XN'+index);
			MSC.push(0x4000 + 256*Math.floor(i/16) + (i%16) );
		}

		return [names, MSC];
	}

	'configS2S3': function(type){
		var names = [],
			MSC = [],
			radial = 24, azimuthal, typeCode,
			i;

		if(type == 2){
			typeCode = 'E';
			azimuthal = 16;
		} else if(type == 3){
			typeCode = 'Z';
			azimuthal = 32;
		}
		//radial first: first 8 finishes off last digitizer, other 16 fill the next; then azimuthal channels fill 1 or 2 more grif16s
		for(i=0; i<radial; i++){
			names.push('SP'+typeCode+'00DP'+((i<10)? '0'+i : i)+'X');

			if(i<8){
				MSC.push(0x4708 + i);
			} else{
				MSC.push(0x4800 + i-8);
			}
		}

		for(i=0; i<azimuthal; i++){
			names.push('SP'+typeCode+'00DN'+((i<10)? '0'+i : i)+'X');

			MSC.push(0x4900 + Math.floor(i/16)*0x100 + (i%16) );
		}

		return [names, MSC];
	}

	'configDESCANT': function(){
		var names = [],
			MSC = [],
			cableBundles = [],
			i, j;

		//weird ordering 'thanks' to cable bundling constraints:
		cableBundles = [
			[46, 65, 66, 67],
			[13, 27, 26, 45],
			[28, 47, 48, 68],
			[5, 14, 15, 29],
			[0, 49, 69],
			[1, 6, 30],
			[16, 31, 50, 51],
			[7, 17, 18, 32],
			[33, 52, 53, 54],

			[43, 44, 63, 64],
			[25, 42, 62],
			[4, 11, 12, 24],
			[23, 41, 40, 61],
			[10, 22, 39, 60],
			[2, 3, 8, 9],
			[21, 38, 59],
			[20, 37, 57, 58],
			[19, 36, 56],
			[34, 35, 55]
		]

		for(i=0; i<cableBundles.length; i++){
			for(j=0; j<cableBundles[i].length; j++){
				names.push('DSC' + ((cableBundles[i][j] < 10) ? '0'+cableBundles[i][j] : cableBundles[i][j]) + 'XN00X');

				//first three cable bundles are on collector 0x2, rest are on 0x3
				if(i<3){
					MSC.push(0x2000 | ((9+i)<<8) | j )
				} else{
					MSC.push(0x3000 | ((i-3)<<8) | j )
				}
			}
		}

		return [names, MSC];
	}

}<|endoftext|>


<commit_before>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const stickerPackSchema = Schema({
	name: String,
	key: {type: String, unique: true},
	installs: {type: Number, default: 0},
	creator: {type: Schema.Types.ObjectId, ref: 'User'},
	stickers: [{
		name: String,
		url: String,
		uses: Number,
		createdAt: Date
	}]
});

let StickerPack = mongoose.model('StickerPack', stickerPackSchema);

module.exports = StickerPack;
<commit_msg>Update sticker-pack model<commit_after>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const stickerPackSchema = Schema({
	name: String,
	key: {type: String, unique: true},
	installs: {type: Number, default: 0},
	creatorId: {type: String, required: true},
	stickers: [{
		name: String,
		url: String,
		uses: {type: Number, default: 0},
		creatorId: {type: String, required: true, default: 'unknown'},
		createdAt: {type: Date, default: Date.now},
		createdVia: {type: String, required: true, default: 'website'},
		groupType: {type: String, required: true, default: 'sticker-pack'},
		groupId: {type: String, required: true, default: 'unknown'}
	}]
});

const StickerPack = mongoose.model('StickerPack', stickerPackSchema);

module.exports = StickerPack;
<|endoftext|>


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

  angular
    .module('porttare.controllers')
    .controller('OfficesController', OfficesController);

  function OfficesController($scope,
                             $ionicPopup,
                             $ionicLoading,
                             APP,
                             OfficesService,
                             ModalService,
                             ErrorHandlerService) {

    var officesVm = this;
    officesVm.showNewOffice = showNewOffice;
    officesVm.closeModal = closeModal;
    officesVm.submitOffice = submitOffice;
    getOffices();

    function getOffices() {
      OfficesService.getOffices().then(function(results){
        officesVm.offices = results.provider_offices; //jshint ignore:line
      }, ErrorHandlerService.handleCommonErrorGET);
    }

    function showNewOffice() {
      officesVm.office = buildNewOffice();
      ModalService.showModal({
        parentScope: $scope,
        fromTemplateUrl: 'templates/offices/new-edit.html'
      });
    }

    function buildNewOffice(){
      var newOffice = {
        weekdays_attributes: buildWeekdays() // jshint ignore:line
      };
      angular.forEach(APP.weekdays, function (wday){
        newOffice.weekdays_attributes.push({
          day: wday
        });
      });
      console.log(newOffice);
      // TODO why was this here?
      // newOffice.enabled = false;
      return newOffice;
    }

    function closeModal() {
      ModalService.closeModal();
      officesVm.messages = {};
    }

    function submitOffice(){
      if(officesVm.form.$valid){
        $ionicLoading.show({
          template: '{{::("globals.saving"|translate)}}'
        });
        OfficesService.createOffice(
          officesVm.office
        ).then(function success(resp){
          $ionicLoading.hide().then(function(){
            officesVm.offices.push(resp.provider_office); //jshint ignore:line
            $ionicPopup.alert({
              title: 'Éxito',
              template: '{{::("office.officeSuccessSave"|translate)}}'
            }).then(function(){
              closeModal();
            });
          });
        }, function(response){
          officesVm.messages = response.status===422 ? response.data.errors:undefined;
          $ionicLoading.hide();
        });
      }
    }
  }
})();
<commit_msg>fucking fix rebase<commit_after>(function () {
'use strict';

  angular
    .module('porttare.controllers')
    .controller('OfficesController', OfficesController);

  function OfficesController($scope,
                             $ionicPopup,
                             $ionicLoading,
                             APP,
                             OfficesService,
                             ModalService,
                             ErrorHandlerService) {

    var officesVm = this;
    officesVm.showNewOffice = showNewOffice;
    officesVm.closeModal = closeModal;
    officesVm.submitOffice = submitOffice;
    getOffices();

    function getOffices() {
      OfficesService.getOffices().then(function(results){
        officesVm.offices = results.provider_offices; //jshint ignore:line
      }, ErrorHandlerService.handleCommonErrorGET);
    }

    function showNewOffice() {
      officesVm.office = buildNewOffice();
      ModalService.showModal({
        parentScope: $scope,
        fromTemplateUrl: 'templates/offices/new-edit.html'
      });
    }

    function buildNewOffice(){
      var newOffice = {
        weekdays_attributes: buildWeekdays() // jshint ignore:line
      };
      return newOffice;
    }

    function buildWeekdays(){
       return APP.weekdays.map(function (wday){
         return { day: wday };
       });
     }

    function closeModal() {
      ModalService.closeModal();
      officesVm.messages = {};
    }

    function submitOffice(){
      if(officesVm.form.$valid){
        $ionicLoading.show({
          template: '{{::("globals.saving"|translate)}}'
        });
        OfficesService.createOffice(
          officesVm.office
        ).then(function success(resp){
          $ionicLoading.hide().then(function(){
            officesVm.offices.push(resp.provider_office); //jshint ignore:line
            $ionicPopup.alert({
              title: 'Éxito',
              template: '{{::("office.officeSuccessSave"|translate)}}'
            }).then(function(){
              closeModal();
            });
          });
        }, function(response){
          officesVm.messages = response.status===422 ? response.data.errors:undefined;
          $ionicLoading.hide();
        });
      }
    }
  }
})();
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { Origin } from 'redux-tooltip';
import ProfileTooltip from './ProfileTooltip';

export default class ProfileTooltipOrigin extends Component {
  static contextTypes = {
    store: PropTypes.object,
  };

  constructor(props) {
    super(props);
  }

  shouldComponentUpdate(nextProps) {
    return nextProps.username !== this.props.username;
  }

  render() {
    return (
      <Origin
        name="userProfile"
        content={<ProfileTooltip username={this.props.username} store={this.context.store} />}
        delay
      >
        { this.props.children }
      </Origin>
    );
  }
}
<commit_msg>add delay also for appearance of tooltip<commit_after>import React, { Component, PropTypes } from 'react';
import { Origin } from 'redux-tooltip';
import ProfileTooltip from './ProfileTooltip';

export default class ProfileTooltipOrigin extends Component {
  static contextTypes = {
    store: PropTypes.object,
  };

  constructor(props) {
    super(props);
  }

  shouldComponentUpdate(nextProps) {
    return nextProps.username !== this.props.username;
  }

  render() {
    return (
      <Origin
        name="userProfile"
        content={<ProfileTooltip username={this.props.username} store={this.context.store} />}
        delay
        delayOn="both"
      >
        { this.props.children }
      </Origin>
    );
  }
}
<|endoftext|>


<commit_before>var app = angular.module('attendance', []);

app.service('Attendance', ['$http', '$window', function($http) {
  var attendOrUnattend = function(path, game) {
    if (!game.busy) {
      game.busy = true;
      setTimeout(function() {
        $http.put('/' + path + '/' + game.id).
        success(function(newGame) {
          game.attended = newGame.attended;
          game.busy = false;
        }).
        error(function(data, status, headers, config) {
          game.busy = false;
          $window.alert("This game could not be updated: " + status)
        });
      }, 5000);
    }
  };
  var service = {
    attendGame: _.partial(attendOrUnattend, 'attend'),
    unattendGame: _.partial(attendOrUnattend, 'unattend')
  };
  return service;
}]);<commit_msg>Remove timeout<commit_after>var app = angular.module('attendance', []);

app.service('Attendance', ['$http', '$window', function($http) {
  var attendOrUnattend = function(path, game) {
    if (!game.busy) {
      game.busy = true;
      $http.put('/' + path + '/' + game.id).
        success(function(newGame) {
        game.attended = newGame.attended;
        game.busy = false;
      }).
      error(function(data, status, headers, config) {
        game.busy = false;
        $window.alert("This game could not be updated: " + status)
      });
    }
  };
  var service = {
    attendGame: _.partial(attendOrUnattend, 'attend'),
    unattendGame: _.partial(attendOrUnattend, 'unattend')
  };
  return service;
}]);<|endoftext|>