<commit_before>'use strict';

(function() {

  angular.module('ncsaas')
    .controller('InitialDataController',
    ['usersService',
     'servicesService',
     'baseControllerClass',
     'customersService',
     'projectsService',
     'plansService',
     'currentStateService',
     'joinService',
     '$q',
     '$rootScope',
     '$state',
     'ENV',
     'ncUtils',
     InitialDataController]);

  function InitialDataController(
    usersService,
    servicesService,
    baseControllerClass,
    customersService,
    projectsService,
    plansService,
    currentStateService,
    joinService,
    $q,
    $rootScope,
    $state,
    ENV,
    ncUtils) {
    var controllerScope = this;
    var Controller = baseControllerClass.extend({
      user: {},
      customer: {},
      services: {},
      project: {},
      chosenService: null,
      chosenServices: [],
      currentProcess: null,

      init: function() {
        this._super();
        this.activate();
      },
      activate: function() {
        var vm = this;
        this.getUser();
        this.getServices();
        this.getFreePlan();
        currentStateService.getCustomer().then(function(customer) {
          vm.customer = customer;
          currentStateService.getProject().then(function(project) {
            vm.project = project;
          })
        });
      },
      getUser: function() {
        var vm = this;
        usersService.getCurrentUser().then(function(response) {
          vm.user = response;
          // By default customer name is equal to user name
          vm.customer.name = 'My Organization';
        });
      },
      getFreePlan: function() {
        var vm = this;
        plansService.getFreePlan().then(function(plan) {
          vm.customer.plan = plan;
        })
      },
      getServices: function() {
        if (ENV.featuresVisible || ENV.toBeFeatures.indexOf('providers') == -1) {
          var vm = this;
          servicesService.getServicesOptions().then(function(service_options) {
            vm.service_options = service_options;
            vm.addChosenService('Amazon');
            vm.addChosenService('DigitalOcean');
          });
        }
      },
      getPrettyQuotaName: function(name, count) {
        return ncUtils.getPrettyQuotaName(name) + (count > 1 ? 's' : '');
      },
      addChosenService: function(name) {
        if (!name) {
          name = this.chosenService;
        }
        if (!name) {
          return;
        }
        var service = this.service_options[name];
        if (!service) {
          return;
        }
        service.saved = false;
        service.status = 'Offline';
        this.chosenServices.push(angular.copy(service));
      },
      removeService: function(service) {
        var index = this.chosenServices.lastIndexOf(service);
        if (index + 1) {
          this.chosenServices.splice(index, 1);
        }
      },
      saveServices: function() {
        var vm = this;
        var unsavedServices = this.chosenServices.filter(function(service) {
          service.errors = {};
          return !service.saved;
        });
        vm.currentProcess = 'saving services..';
        // return successfully if no services require creation
        if (unsavedServices.length < 1) {
            return true;
        }
        var promises = unsavedServices.map(function(service) {
          var instance = joinService.$create(service.url);
          for (var i = 0; i < service.options.length; i++) {
            var option = service.options[i];
            if (option.value) {
              instance[option.key] = option.value;
            }
          }
          instance.customer = vm.customer.url;
          instance.name = service.name;
          var deferred = $q.defer();
          service.status = 'Processing';
          instance.$save().then(function() {
            service.saved = true;
            service.errors = {};
            service.status = 'Online';
            deferred.resolve();
          }, function(errors) {
            service.errors = errors;
            service.status = 'Erred';
            deferred.reject(errors);
          });
          return deferred.promise;
        });
        return $q.all(promises);
      },
      saveUser: function() {
        var vm = this;
        vm.currentProcess = 'saving user..';
        return vm.user.$update(function() {
          usersService.currentUser = null;
        }, function(response) {
          vm.user.errors = response.data;
        });
      },
      saveCustomer: function() {
        var vm = this;
        if (vm.customer.uuid) {
          return $q.defer().resolve();
        }
        vm.currentProcess = 'saving customer..';
        var customer = customersService.$create();
        customer.name = vm.customer.name;
        return customer.$save().then(function(model) {
          vm.customer = model;
          currentStateService.setCustomer(model);
          $rootScope.$broadcast('refreshCustomerList', {model: model, new: true, current: true});
        });
      },
      saveProject: function() {
        var vm = this;
        if (vm.project.uuid) {
          return $q.defer().resolve();
        }
        vm.currentProcess = 'saving project..';
        var project = projectsService.$create();
        project.customer = vm.customer.url;
        project.name = 'Default';
        return project.$save().then(function(model) {
          vm.project = model;
          currentStateService.setProject(vm.project);
          $rootScope.$broadcast('refreshProjectList', {
            model: vm.project, new: true, current: true
          });
        });
      },
      gotoDashboard: function() {
        $state.go('dashboard.index');
      },
      save: function() {
        var vm = this;
        if (!vm.user.email) {
          vm.user.errors = {email: 'This field is required'};
          return $q.reject();
        }
        if (!vm.customer.name) {
          vm.customer.errors = {name: 'This field is required'};
          return $q.reject();
        }
        return vm.saveUser()
                 .then(vm.saveCustomer.bind(vm))
                 .then(vm.saveServices.bind(vm))
                 .then(vm.saveProject.bind(vm))
                 .then(vm.gotoDashboard);
      },

      getClass: function(state) {
        var cls = ENV.servicesStateColorClasses[state];
        if (cls == 'processing') {
          return 'icon refresh spin';
        } else {
          return 'status-circle ' + cls;
        }
      }
    });

    controllerScope.__proto__ = new Controller();
  }

})();<commit_msg>Fix term usage<commit_after>'use strict';

(function() {

  angular.module('ncsaas')
    .controller('InitialDataController',
    ['usersService',
     'servicesService',
     'baseControllerClass',
     'customersService',
     'projectsService',
     'plansService',
     'currentStateService',
     'joinService',
     '$q',
     '$rootScope',
     '$state',
     'ENV',
     'ncUtils',
     InitialDataController]);

  function InitialDataController(
    usersService,
    servicesService,
    baseControllerClass,
    customersService,
    projectsService,
    plansService,
    currentStateService,
    joinService,
    $q,
    $rootScope,
    $state,
    ENV,
    ncUtils) {
    var controllerScope = this;
    var Controller = baseControllerClass.extend({
      user: {},
      customer: {},
      services: {},
      project: {},
      chosenService: null,
      chosenServices: [],
      currentProcess: null,

      init: function() {
        this._super();
        this.activate();
      },
      activate: function() {
        var vm = this;
        this.getUser();
        this.getServices();
        this.getFreePlan();
        currentStateService.getCustomer().then(function(customer) {
          vm.customer = customer;
          currentStateService.getProject().then(function(project) {
            vm.project = project;
          })
        });
      },
      getUser: function() {
        var vm = this;
        usersService.getCurrentUser().then(function(response) {
          vm.user = response;
          // By default customer name is equal to user name
          vm.customer.name = 'My Organization';
        });
      },
      getFreePlan: function() {
        var vm = this;
        plansService.getFreePlan().then(function(plan) {
          vm.customer.plan = plan;
        })
      },
      getServices: function() {
        if (ENV.featuresVisible || ENV.toBeFeatures.indexOf('providers') == -1) {
          var vm = this;
          servicesService.getServicesOptions().then(function(service_options) {
            vm.service_options = service_options;
            vm.addChosenService('Amazon');
            vm.addChosenService('DigitalOcean');
          });
        }
      },
      getPrettyQuotaName: function(name, count) {
        return ncUtils.getPrettyQuotaName(name) + (count > 1 ? 's' : '');
      },
      addChosenService: function(name) {
        if (!name) {
          name = this.chosenService;
        }
        if (!name) {
          return;
        }
        var service = this.service_options[name];
        if (!service) {
          return;
        }
        service.saved = false;
        service.status = 'Offline';
        this.chosenServices.push(angular.copy(service));
      },
      removeService: function(service) {
        var index = this.chosenServices.lastIndexOf(service);
        if (index + 1) {
          this.chosenServices.splice(index, 1);
        }
      },
      saveServices: function() {
        var vm = this;
        var unsavedServices = this.chosenServices.filter(function(service) {
          service.errors = {};
          return !service.saved;
        });
        vm.currentProcess = 'saving providers..';
        // return successfully if no services require creation
        if (unsavedServices.length < 1) {
            return true;
        }
        var promises = unsavedServices.map(function(service) {
          var instance = joinService.$create(service.url);
          for (var i = 0; i < service.options.length; i++) {
            var option = service.options[i];
            if (option.value) {
              instance[option.key] = option.value;
            }
          }
          instance.customer = vm.customer.url;
          instance.name = service.name;
          var deferred = $q.defer();
          service.status = 'Processing';
          instance.$save().then(function() {
            service.saved = true;
            service.errors = {};
            service.status = 'Online';
            deferred.resolve();
          }, function(errors) {
            service.errors = errors;
            service.status = 'Erred';
            deferred.reject(errors);
          });
          return deferred.promise;
        });
        return $q.all(promises);
      },
      saveUser: function() {
        var vm = this;
        vm.currentProcess = 'saving user..';
        return vm.user.$update(function() {
          usersService.currentUser = null;
        }, function(response) {
          vm.user.errors = response.data;
        });
      },
      saveCustomer: function() {
        var vm = this;
        if (vm.customer.uuid) {
          return $q.defer().resolve();
        }
        vm.currentProcess = 'saving customer..';
        var customer = customersService.$create();
        customer.name = vm.customer.name;
        return customer.$save().then(function(model) {
          vm.customer = model;
          currentStateService.setCustomer(model);
          $rootScope.$broadcast('refreshCustomerList', {model: model, new: true, current: true});
        });
      },
      saveProject: function() {
        var vm = this;
        if (vm.project.uuid) {
          return $q.defer().resolve();
        }
        vm.currentProcess = 'saving project..';
        var project = projectsService.$create();
        project.customer = vm.customer.url;
        project.name = 'Default';
        return project.$save().then(function(model) {
          vm.project = model;
          currentStateService.setProject(vm.project);
          $rootScope.$broadcast('refreshProjectList', {
            model: vm.project, new: true, current: true
          });
        });
      },
      gotoDashboard: function() {
        $state.go('dashboard.index');
      },
      save: function() {
        var vm = this;
        if (!vm.user.email) {
          vm.user.errors = {email: 'This field is required'};
          return $q.reject();
        }
        if (!vm.customer.name) {
          vm.customer.errors = {name: 'This field is required'};
          return $q.reject();
        }
        return vm.saveUser()
                 .then(vm.saveCustomer.bind(vm))
                 .then(vm.saveServices.bind(vm))
                 .then(vm.saveProject.bind(vm))
                 .then(vm.gotoDashboard);
      },

      getClass: function(state) {
        var cls = ENV.servicesStateColorClasses[state];
        if (cls == 'processing') {
          return 'icon refresh spin';
        } else {
          return 'status-circle ' + cls;
        }
      }
    });

    controllerScope.__proto__ = new Controller();
  }

})();
<|endoftext|>


<commit_before>'use strict';

angular.module('stormpathIdpApp')
  .directive('passwordPolicyValidation', function (Stormpath) {
    return {
      restrict: 'A',
      link: function postLink(scope) {
        scope.errors = {
          minLength: false,
          maxLength: false,
          requireLowerCase: false,
          requireUpperCase: false,
          requireNumeric: false,
          requireDiacritical: false
        };
        scope.errorCount = function(){
          return Object.keys(scope.errors).filter(function(k){
            return scope.errors[k];
          }).length;
        };
        scope.validate = function(element){
          scope.clearErrors();
          var v = element.val();

          var tests =  [
            ['minLength' , function(){return v.length < Stormpath.idSiteModel.passwordPolicy.minLength;}],
            ['maxLength' , function(){ return v.length > Stormpath.idSiteModel.passwordPolicy.maxLength;}],
            ['requireLowerCase' , function(){ return Stormpath.idSiteModel.passwordPolicy.requireLowerCase && !(/[a-z]/).test(v);}],
            ['requireUpperCase' , function(){ return Stormpath.idSiteModel.passwordPolicy.requireUpperCase && !(/[A-Z]/).test(v);}],
            ['requireNumeric' , function(){ return Stormpath.idSiteModel.passwordPolicy.requireNumeric && !(/[0-9]/).test(v);}],
            ['requireDiacritical' , function(){ return Stormpath.idSiteModel.passwordPolicy.requireDiacritical && !(/[\u00C0-\u017F]/).test(v);}]
          ];

          for(var i=0;i<tests.length;i++){
            scope.errors[tests[i][0]] = tests[i][1](v);
            if(scope.errorCount()>0){
              break;
            }
          }

          scope.validationError = scope.errorCount() > 0 ;
          return scope.validationError;
        };
      }
    };
  });
<commit_msg>Don’t read password policy if it doesn’t exist<commit_after>'use strict';

angular.module('stormpathIdpApp')
  .directive('passwordPolicyValidation', function (Stormpath) {
    return {
      restrict: 'A',
      link: function postLink(scope) {
        scope.errors = {
          minLength: false,
          maxLength: false,
          requireLowerCase: false,
          requireUpperCase: false,
          requireNumeric: false,
          requireDiacritical: false
        };
        scope.errorCount = function(){
          return Object.keys(scope.errors).filter(function(k){
            return scope.errors[k];
          }).length;
        };
        scope.validate = function(element){
          scope.clearErrors();
          var v = element.val();

          if (!Stormpath.idSiteModel.passwordPolicy) {
            return;
          }

          var tests =  [
            ['minLength' , function(){return v.length < Stormpath.idSiteModel.passwordPolicy.minLength;}],
            ['maxLength' , function(){ return v.length > Stormpath.idSiteModel.passwordPolicy.maxLength;}],
            ['requireLowerCase' , function(){ return Stormpath.idSiteModel.passwordPolicy.requireLowerCase && !(/[a-z]/).test(v);}],
            ['requireUpperCase' , function(){ return Stormpath.idSiteModel.passwordPolicy.requireUpperCase && !(/[A-Z]/).test(v);}],
            ['requireNumeric' , function(){ return Stormpath.idSiteModel.passwordPolicy.requireNumeric && !(/[0-9]/).test(v);}],
            ['requireDiacritical' , function(){ return Stormpath.idSiteModel.passwordPolicy.requireDiacritical && !(/[\u00C0-\u017F]/).test(v);}]
          ];

          for(var i=0;i<tests.length;i++){
            scope.errors[tests[i][0]] = tests[i][1](v);
            if(scope.errorCount()>0){
              break;
            }
          }

          scope.validationError = scope.errorCount() > 0 ;
          return scope.validationError;
        };
      }
    };
  });
<|endoftext|>


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

  angular.module('dimApp')
    .factory('dimSettingsService', SettingsService);

  SettingsService.$inject = ['$rootScope', 'SyncService', '$window', '$translate'];

  /**
   * The settings service provides a settings object which contains
   * all DIM settings as properties. To observe changes in settings,
   * add a $watch on one or more of the settings, or just use it in a
   * template (where watches are automatic!). To save settings, call
   * "save()" on the settings object.
   *
   * Settings will start out with default values and asynchronously
   * load in the user's actual settings, so it is a good sidea to
   * always watch the settings you are using.
   */
  function SettingsService($rootScope, SyncService, $window, $translate) {
    var _loaded = false;

    const destinyLanguages = ['de', 'en', 'fr', 'es', 'it', 'ja', 'pt-br'];

    // Try to pick a nice default language
    function defaultLanguage() {
      const browserLang = ($window.navigator.language || 'en').toLowerCase();
      return _.find(destinyLanguages, (lang) => browserLang.startsWith(lang)) || 'en';
    }

    var settings = {
      // Hide items that don't match the current search
      hideFilteredItems: false,
      // Show full details in item popup
      itemDetails: false,
      // Show item quality percentages
      itemQuality: false,
      // Show new items with an overlay
      showNewItems: false,
      // Show animation of new item overlay on new items
      showNewAnimation: true,
      // Show elemental damage icons
      showElements: false,
      // Sort characters (mostRecent, mostRecentReverse, fixed)
      characterOrder: 'mostRecent',
      // Sort items in buckets (primaryStat, rarityThenPrimary,
      // rarity, quality)
      itemSort: 'primaryStat',
      // How many columns to display character buckets
      charCol: 3,
      // How many columns to display vault buckets
      vaultMaxCol: 999,
      // How big in pixels to draw items
      itemSize: 44,
      // Which categories or buckets should be collapsed?
      collapsedSections: {},
      // Predefined item tags. Maybe eventually allow to add more (also i18n?)
      itemTags: [
        { type: undefined, label: 'Tag Item' },
        { type: 'favorite', label: 'Favorite', hotkey: '!', icon: 'star' },
        { type: 'keep', label: 'Keep', hotkey: '@', icon: 'tag' },
        { type: 'delete', label: 'Delete', hotkey: '#', icon: 'ban' },
        { type: 'infuse', label: 'Infuse', hotkey: '$', icon: 'bolt' },
      ],

      language: defaultLanguage(),

      save: function() {
        if (!_loaded) {
          throw new Error("Settings haven't loaded - they can't be saved.");
        }
        $rootScope.$evalAsync(function() {
          SyncService.set({
            'settings-v1.0': _.omit(settings, 'save')
          });
        });
      }
    };

    // Load settings async
    SyncService.get().then(function(data) {
      var savedSettings = data['settings-v1.0'] || {};

      // self destruct timer for quality, hope we can remove this some day...
      savedSettings.disableQuality = new Date('9/19/2016') <= new Date();

      // for now just override itemTags. eventually let users create own?
      savedSettings.itemTags = [
        { type: undefined, label: 'Tag Item' },
        { type: 'favorite', label: 'Favorite', hotkey: '!', icon: 'star' },
        { type: 'keep', label: 'Keep', hotkey: '@', icon: 'tag' },
        { type: 'delete', label: 'Delete', hotkey: '#', icon: 'ban' },
        { type: 'infuse', label: 'Infuse', hotkey: '$', icon: 'bolt' },
      ];

      _loaded = true;
      $rootScope.$evalAsync(function() {
        angular.extend(settings, savedSettings);
        $translate.use(settings.language);
        $translate.fallbackLanguage('en');
      });
    });

    return settings;
  }
})();
<commit_msg>why didn't eslint auto fix that >_><commit_after>(function() {
  'use strict';

  angular.module('dimApp')
    .factory('dimSettingsService', SettingsService);

  SettingsService.$inject = ['$rootScope', 'SyncService', '$window', '$translate'];

  /**
   * The settings service provides a settings object which contains
   * all DIM settings as properties. To observe changes in settings,
   * add a $watch on one or more of the settings, or just use it in a
   * template (where watches are automatic!). To save settings, call
   * "save()" on the settings object.
   *
   * Settings will start out with default values and asynchronously
   * load in the user's actual settings, so it is a good sidea to
   * always watch the settings you are using.
   */
  function SettingsService($rootScope, SyncService, $window, $translate) {
    var _loaded = false;

    const destinyLanguages = ['de', 'en', 'fr', 'es', 'it', 'ja', 'pt-br'];

    // Try to pick a nice default language
    function defaultLanguage() {
      const browserLang = ($window.navigator.language || 'en').toLowerCase();
      return _.find(destinyLanguages, (lang) => browserLang.startsWith(lang)) || 'en';
    }

    var settings = {
      // Hide items that don't match the current search
      hideFilteredItems: false,
      // Show full details in item popup
      itemDetails: false,
      // Show item quality percentages
      itemQuality: false,
      // Show new items with an overlay
      showNewItems: false,
      // Show animation of new item overlay on new items
      showNewAnimation: true,
      // Show elemental damage icons
      showElements: false,
      // Sort characters (mostRecent, mostRecentReverse, fixed)
      characterOrder: 'mostRecent',
      // Sort items in buckets (primaryStat, rarityThenPrimary,
      // rarity, quality)
      itemSort: 'primaryStat',
      // How many columns to display character buckets
      charCol: 3,
      // How many columns to display vault buckets
      vaultMaxCol: 999,
      // How big in pixels to draw items
      itemSize: 44,
      // Which categories or buckets should be collapsed?
      collapsedSections: {},
      // Predefined item tags. Maybe eventually allow to add more (also i18n?)
      itemTags: [
        { type: undefined, label: 'Tag Item' },
        { type: 'favorite', label: 'Favorite', hotkey: '!', icon: 'star' },
        { type: 'keep', label: 'Keep', hotkey: '@', icon: 'tag' },
        { type: 'delete', label: 'Delete', hotkey: '#', icon: 'ban' },
        { type: 'infuse', label: 'Infuse', hotkey: '$', icon: 'bolt' }
      ],

      language: defaultLanguage(),

      save: function() {
        if (!_loaded) {
          throw new Error("Settings haven't loaded - they can't be saved.");
        }
        $rootScope.$evalAsync(function() {
          SyncService.set({
            'settings-v1.0': _.omit(settings, 'save')
          });
        });
      }
    };

    // Load settings async
    SyncService.get().then(function(data) {
      var savedSettings = data['settings-v1.0'] || {};

      // self destruct timer for quality, hope we can remove this some day...
      savedSettings.disableQuality = new Date('9/19/2016') <= new Date();

      // for now just override itemTags. eventually let users create own?
      savedSettings.itemTags = [
        { type: undefined, label: 'Tag Item' },
        { type: 'favorite', label: 'Favorite', hotkey: '!', icon: 'star' },
        { type: 'keep', label: 'Keep', hotkey: '@', icon: 'tag' },
        { type: 'delete', label: 'Delete', hotkey: '#', icon: 'ban' },
        { type: 'infuse', label: 'Infuse', hotkey: '$', icon: 'bolt' }
      ];

      _loaded = true;
      $rootScope.$evalAsync(function() {
        angular.extend(settings, savedSettings);
        $translate.use(settings.language);
        $translate.fallbackLanguage('en');
      });
    });

    return settings;
  }
})();
<|endoftext|>


<commit_before>import path from 'path';
import ScssProcessor from './scss-processor';
import CssModulesProcessor from './css-modules-processor';
import pluginOptions from './options';
import plugins from './postcss-plugins';
import getOutputPath from './get-output-path';

export default class CssModulesBuildPlugin {
	processFilesForTarget(files) {
		const allFiles = createAllFilesMap(files);
		const globalVariablesCode = getGlobalVariables(pluginOptions, plugins);
		compileScssFiles.call(this, files);
		compileCssModules.call(this, files);

		function getGlobalVariables(options, plugins) {
			if (options.extractSimpleVars === false) return;

			const findSimpleVarsPlugin = R.findIndex(plugin=>plugin.postcss && plugin.postcss.postcssPlugin === 'postcss-simple-vars');
			const pluginIndex = findSimpleVarsPlugin(plugins);

			if (pluginIndex === -1) return;
			const variables = plugins[pluginIndex].options.variables;
			const convertJsonVariablesToScssVariables = R.compose(R.reduce((variables, pair)=>variables + `$${pair[0]}: ${pair[1]};\n`, ''), R.toPairs);
			return convertJsonVariablesToScssVariables(variables);
		}

		function compileScssFiles(files) {
			const processor = new ScssProcessor('./', allFiles);
			const isScssRoot = (file)=>isScss(file) && isRoot(file);
			const compileFile = compileScssFile.bind(this);
			files.filter(isScssRoot).forEach(compileFile);
			console.log(`scss files: ${files.filter(isScssRoot).length}`);
			function isScss(file) {
				const extension = path.extname(file.getPathInPackage()).substring(1);
				return ['scss', 'sass'].indexOf(extension) !== -1;
			}

			function isRoot(inputFile) {
				const fileOptions = inputFile.getFileOptions();
				if (fileOptions.hasOwnProperty('isImport')) {
					return !fileOptions.isImport;
				}
				return !hasUnderscore(inputFile.getPathInPackage());
			}

			function compileScssFile(file) {
				const contents = file.contents = file.getContentsAsString();
				if (contents && contents.length)
					file.contents = `${globalVariablesCode}\n\n${contents}`;

				file.getContentsAsString = function getContentsAsStringWithGlobalVariables() {
					return file.contents;
				};

				const source = {
					path: ImportPathHelpers.getImportPathInPackage(file),
					contents: file.getContentsAsString(),
					file
				};

				let result;
				try {
					result = processor.process(file, source, './', allFiles);
				} catch (err) {
					file.error({
						message: `CSS modules SCSS compiler error: ${JSON.stringify(err, Object.getOwnPropertyNames(err))}\n`,
						sourcePath: file.getDisplayPath()
					});
					return null;
				}

				file.getContentsAsString = function getContentsAsString() {
					//console.log(`\n\n\n!!!!!!!!!!\n${source.path}`)
					//console.dir(processor.fileCache)
					return result.source;
				};
			}
		}

		function compileCssModules(files) {
			const processor = new CssModulesProcessor('./');
			const compileFile = processFile.bind(this);
			files.forEach(compileFile);

			function processFile(file) {
				const source = {
					path: ImportPathHelpers.getImportPathInPackage(file),
					contents: file.getContentsAsString()
				};
				return processor.process(source, './', allFiles)
					.then(result => {
						if (result.source)
							file.addStylesheet({
								data: result.source,
								//path: 'yikes.css',//getOutputPath(file.getPathInPackage(), pluginOptions.outputCssFilePath) + '.css',
								path: getOutputPath(file.getPathInPackage(), pluginOptions.outputCssFilePath) + '.css',
								sourceMap: JSON.stringify(result.sourceMap)
							});
						//console.log(getOutputPath(file.getPathInPackage(), pluginOptions.outputJsFilePath) + '.js')
						if (result.tokens)
							file.addJavaScript({
								data: Babel.compile('' +
									`const styles = ${JSON.stringify(result.tokens)};
							 export { styles as default, styles };`).code,
								path: getOutputPath(file.getPathInPackage(), pluginOptions.outputJsFilePath) + '.js',
								//sourcePath: 'test'
							});
					}).await();
			}
		}

		function hasUnderscore(file) {
			return path.basename(file)[0] === '_';
		}
	}
};

function processFiles(files) {

}

function createAllFilesMap(files) {
	const allFiles = new Map();
	files.forEach((inputFile) => {
		const importPath = ImportPathHelpers.getImportPathInPackage(inputFile);
		allFiles.set(importPath, inputFile);
	});
	return allFiles;
}
<commit_msg>handle empty global variables and scss files<commit_after>import path from 'path';
import ScssProcessor from './scss-processor';
import CssModulesProcessor from './css-modules-processor';
import pluginOptions from './options';
import plugins from './postcss-plugins';
import getOutputPath from './get-output-path';

export default class CssModulesBuildPlugin {
	processFilesForTarget(files) {
		const allFiles = createAllFilesMap(files);
		const globalVariablesCode = getGlobalVariables(pluginOptions, plugins);
		compileScssFiles.call(this, files);
		compileCssModules.call(this, files);

		function getGlobalVariables(options, plugins) {
			if (options.extractSimpleVars === false) return;

			const findSimpleVarsPlugin = R.findIndex(plugin=>plugin.postcss && plugin.postcss.postcssPlugin === 'postcss-simple-vars');
			const pluginIndex = findSimpleVarsPlugin(plugins);

			if (pluginIndex === -1) return;
			const variables = plugins[pluginIndex].options.variables;
			const convertJsonVariablesToScssVariables = R.compose(R.reduce((variables, pair)=>variables + `$${pair[0]}: ${pair[1]};\n`, ''), R.toPairs);
			return convertJsonVariablesToScssVariables(variables);
		}

		function compileScssFiles(files) {
			const processor = new ScssProcessor('./', allFiles);
			const isScssRoot = (file)=>isScss(file) && isRoot(file);
			const compileFile = compileScssFile.bind(this);
			files.filter(isScssRoot).forEach(compileFile);
			console.log(`scss files: ${files.filter(isScssRoot).length}`);
			function isScss(file) {
				const extension = path.extname(file.getPathInPackage()).substring(1);
				return ['scss', 'sass'].indexOf(extension) !== -1;
			}

			function isRoot(inputFile) {
				const fileOptions = inputFile.getFileOptions();
				if (fileOptions.hasOwnProperty('isImport')) {
					return !fileOptions.isImport;
				}
				return !hasUnderscore(inputFile.getPathInPackage());
			}

			function compileScssFile(file) {
				const contents = file.contents = file.getContentsAsString();
				file.contents = `${globalVariablesCode || ''}\n\n${contents || ''}`;

				file.getContentsAsString = function getContentsAsStringWithGlobalVariables() {
					return file.contents;
				};

				const source = {
					path: ImportPathHelpers.getImportPathInPackage(file),
					contents: file.getContentsAsString(),
					file
				};

				let result;
				try {
					result = processor.process(file, source, './', allFiles);
				} catch (err) {
					file.error({
						message: `CSS modules SCSS compiler error: ${JSON.stringify(err, Object.getOwnPropertyNames(err))}\n`,
						sourcePath: file.getDisplayPath()
					});
					return null;
				}

				file.getContentsAsString = function getContentsAsString() {
					//console.log(`\n\n\n!!!!!!!!!!\n${source.path}`)
					//console.dir(processor.fileCache)
					return result.source;
				};
			}
		}

		function compileCssModules(files) {
			const processor = new CssModulesProcessor('./');
			const compileFile = processFile.bind(this);
			files.forEach(compileFile);

			function processFile(file) {
				const source = {
					path: ImportPathHelpers.getImportPathInPackage(file),
					contents: file.getContentsAsString()
				};
				return processor.process(source, './', allFiles)
					.then(result => {
						if (result.source)
							file.addStylesheet({
								data: result.source,
								//path: 'yikes.css',//getOutputPath(file.getPathInPackage(), pluginOptions.outputCssFilePath) + '.css',
								path: getOutputPath(file.getPathInPackage(), pluginOptions.outputCssFilePath) + '.css',
								sourceMap: JSON.stringify(result.sourceMap)
							});
						//console.log(getOutputPath(file.getPathInPackage(), pluginOptions.outputJsFilePath) + '.js')
						if (result.tokens)
							file.addJavaScript({
								data: Babel.compile('' +
									`const styles = ${JSON.stringify(result.tokens)};
							 export { styles as default, styles };`).code,
								path: getOutputPath(file.getPathInPackage(), pluginOptions.outputJsFilePath) + '.js',
								//sourcePath: 'test'
							});
					}).await();
			}
		}

		function hasUnderscore(file) {
			return path.basename(file)[0] === '_';
		}
	}
};

function processFiles(files) {

}

function createAllFilesMap(files) {
	const allFiles = new Map();
	files.forEach((inputFile) => {
		const importPath = ImportPathHelpers.getImportPathInPackage(inputFile);
		allFiles.set(importPath, inputFile);
	});
	return allFiles;
}
<|endoftext|>


<commit_before>//
//  The code to drive the interactive page
//
var Lab = {
  //
  //  Defaults for the options
  //
  defaults: {
    collapse: true,
    width: 100,
    overflow: false,
    walker: "dummy",
    highlight: "none",
    background: "blue",
    foreground: "black"
  },
  //
  //  The TeX code for the examples menu
  //
  Examples: [],
  //
  //  Typeset the math from the text area
  //
  Typeset: function () {
    if (this.jax) {
      var math = this.input.value;
      MathJax.Hub.Queue(
        ["Disable",this.SMML],
        ["Text",this.jax[0],math],
        ["Enable",this.SMML],
        ["Text",this.jax[1],math],
        ["ShowMathML",this],
        ["CollapseWideMath",MathJax.Extension.Collapse]
      );
    }
  },
  //
  //  Encode the TeX and add it to the URL so that reloading the page
  //  keeps the same TeX in place (so when you edit the code, you don't
  //  have to retype the TeX to view it again).
  //
  Keep: function () {
    window.location =
      String(window.location).replace(/\?.*/,"")+"?"
        +[this.example.value, this.width.value,
          this.collapse, this.overflow, this.explorer.walker, this.explorer.highlight,
          this.explorer.background, this.explorer.foreground, ""].join(';')
        +escape(this.input.value);
  },
  //
  //  Select a specific example equation
  //
  Select: function (n) {
    if (n === "-" || n === "?") return;
    this.input.value = this.Examples[n];
    this.Typeset();
  },
  //
  //  Show the enhanced MathML
  //
  ShowMathML: function () {
    this.mathml.innerHTML = "";
    MathJax.HTML.addText(this.mathml,this.jax[1].root.toMathML().replace(/data-semantic-/g,""));
  },
  //
  //  Check for RETURN with any meta key as an alternative to clicking
  //  the TYPESET button
  //
  CheckKey: function (event) {
    if (!event) event = window.event;
    var code = event.which || event.keyCode;
    if ((event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) &&
        (code === 13 || code === 10)) {
      if (event.preventDefault) event.preventDefault();
      event.returnValue = false;
      this.Typeset();
    }
  },
  //
  //  Set the width of the output div
  //
  setWidth: function (width,skipHandler) {
    this.container.style.width = width+"%";
    document.getElementById("range_output").innerHTML = width+"%";
    if (!skipHandler) MathJax.Extension.Collapse.resizeHandler({});
  },
  //
  //  The collapse toggle
  //
  collapse: true,
  setCollapse: function (type,skipUpdate) {
    this.collapse = type;
    MathJax.Extension.Collapse[type ? "Enable" : "Disable"]();
    if (!skipUpdate) {
      MathJax.Hub.Queue(
        ["Reprocess",this.jax[1]],
        ["ShowMathML",this],
        ["CollapseWideMath",MathJax.Extension.Collapse]
      );
    }
  },
  //
  //  The overflow toggle
  //
  overflow: false,
  setOverflow: function (type,skipUpdate) {
    this.overflow = type;
    if (!skipUpdate) MathJax.Hub.Queue(["Rerender",MathJax.Hub]);
  },
  NewMath: function (message) {
    if (!this.overflow) return;
    var jax = MathJax.Hub.getJaxFor(message[1]);
    if (jax.root.Get("display") === "block") {
      var div = jax.SourceElement().previousSibling;
      div.style.overflow = "auto";
      div.style.minHeight = (div.offsetHeight+1) + "px"; // force height to be big enough
    }
  },
  //
  //  The static highlight selection
  //
  explorer: {
      walker: "dummy",
      highlight: "none",
      background: "blue",
      foreground: "black"
    },
  setExplorerOption: function(key, value) {
    if (this.explorer[key] === value) return;
    this.explorer[key] = value;
    MathJax.Extension.Explorer.Reset();
  },
  //
  //  Directly select a specific test equation
  //
  DirectSelect: function (n) {
    (n < 1 && (this.Current = this.Examples.length)) ||
      (n > this.Examples.length && (this.Current = 1)) ||
      (this.Current = parseInt(n));
    this.input.value = this.Examples[this.Current - 1];
    this.example.value = this.Current;
    this.Typeset();
  },
  //
  // Current test equation.
  //
  Current: 0,
  //
  // Select next test equation.
  //
  Next: function() {
    this.DirectSelect(this.Current + 1);
  },
  //
  // Select previous test equation.
  //
  Prev: function() {
    this.DirectSelect(this.Current - 1);
  }

};

//
//  Hook into "New Math" signal to set overflow
//
MathJax.Hub.Register.MessageHook("New Math",["NewMath",Lab]);

//
//  Initialize everything once MathJax has run the first time
//
MathJax.Hub.Queue(function () {
  var defaults = [null,"0",
    String(Lab.defaults.width),
    String(Lab.defaults.collapse),
    String(Lab.defaults.overflow),
    Lab.defaults.walker,
    Lab.defaults.highlight,
    Lab.defaults.background,
    Lab.defaults.foreground,
    "",
  ];
  Lab.SMML = MathJax.Extension.SemanticMathML;
  Lab.jax = MathJax.Hub.getAllJax();
  Lab.input = document.getElementById("input");
  Lab.container = document.getElementById("container");
  Lab.enriched = document.getElementById("enriched");
  Lab.mathml = document.getElementById("mathml");
  Lab.example = document.getElementById("example");
  Lab.width = document.getElementById("width");
  if (window.location.search.length > 1)
    defaults = window.location.search.match(
        /^\?(.*?);(.*?);(.*?);(.*?);(.*?);(.*?);(.*?);(.*?);(.*)$/);
  Lab.example.value = defaults[1];
  Lab.Current = parseInt(defaults[1]);
  Lab.width.value = defaults[2];
  Lab.enriched.style.width = defaults[2];
  Lab.setWidth(Lab.width.value,true);
  Lab.collapse = document.getElementById("collapse").checked = (defaults[3] === "true");
  Lab.setCollapse(Lab.collapse,true);
  Lab.overflow = document.getElementById("overflow").checked = (defaults[4] === "true");
  Lab.setOverflow(Lab.overflow,true);
  Lab.setExplorerOption("walker", document.getElementById("walker").value = defaults[5]);
  Lab.setExplorerOption("highlight", document.getElementById("highlight").value = defaults[6]);
  Lab.setExplorerOption("background", document.getElementById("background").value = defaults[7]);
  Lab.setExplorerOption("foreground", document.getElementById("foreground").value = defaults[8]);
  Lab.input.value = unescape(defaults[9]);
  if (Lab.input.value !== "") Lab.Typeset();
});
<commit_msg>Appends CSS rule that solves highlighting issue in HTML-CSS.<commit_after>//
//  The code to drive the interactive page
//
var Lab = {
  //
  //  Defaults for the options
  //
  defaults: {
    collapse: true,
    width: 100,
    overflow: false,
    walker: "dummy",
    highlight: "none",
    background: "blue",
    foreground: "black"
  },
  //
  //  The TeX code for the examples menu
  //
  Examples: [],
  //
  //  Typeset the math from the text area
  //
  Typeset: function () {
    if (this.jax) {
      var math = this.input.value;
      MathJax.Hub.Queue(
        ["Disable",this.SMML],
        ["Text",this.jax[0],math],
        ["Enable",this.SMML],
        ["Text",this.jax[1],math],
        ["ShowMathML",this],
        ["CollapseWideMath",MathJax.Extension.Collapse]
      );
    }
  },
  //
  //  Encode the TeX and add it to the URL so that reloading the page
  //  keeps the same TeX in place (so when you edit the code, you don't
  //  have to retype the TeX to view it again).
  //
  Keep: function () {
    window.location =
      String(window.location).replace(/\?.*/,"")+"?"
        +[this.example.value, this.width.value,
          this.collapse, this.overflow, this.explorer.walker, this.explorer.highlight,
          this.explorer.background, this.explorer.foreground, ""].join(';')
        +escape(this.input.value);
  },
  //
  //  Select a specific example equation
  //
  Select: function (n) {
    if (n === "-" || n === "?") return;
    this.input.value = this.Examples[n];
    this.Typeset();
  },
  //
  //  Show the enhanced MathML
  //
  ShowMathML: function () {
    this.mathml.innerHTML = "";
    MathJax.HTML.addText(this.mathml,this.jax[1].root.toMathML().replace(/data-semantic-/g,""));
  },
  //
  //  Check for RETURN with any meta key as an alternative to clicking
  //  the TYPESET button
  //
  CheckKey: function (event) {
    if (!event) event = window.event;
    var code = event.which || event.keyCode;
    if ((event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) &&
        (code === 13 || code === 10)) {
      if (event.preventDefault) event.preventDefault();
      event.returnValue = false;
      this.Typeset();
    }
  },
  //
  //  Set the width of the output div
  //
  setWidth: function (width,skipHandler) {
    this.container.style.width = width+"%";
    document.getElementById("range_output").innerHTML = width+"%";
    if (!skipHandler) MathJax.Extension.Collapse.resizeHandler({});
  },
  //
  //  The collapse toggle
  //
  collapse: true,
  setCollapse: function (type,skipUpdate) {
    this.collapse = type;
    MathJax.Extension.Collapse[type ? "Enable" : "Disable"]();
    if (!skipUpdate) {
      MathJax.Hub.Queue(
        ["Reprocess",this.jax[1]],
        ["ShowMathML",this],
        ["CollapseWideMath",MathJax.Extension.Collapse]
      );
    }
  },
  //
  //  The overflow toggle
  //
  overflow: false,
  setOverflow: function (type,skipUpdate) {
    this.overflow = type;
    if (!skipUpdate) MathJax.Hub.Queue(["Rerender",MathJax.Hub]);
  },
  NewMath: function (message) {
    if (!this.overflow) return;
    var jax = MathJax.Hub.getJaxFor(message[1]);
    if (jax.root.Get("display") === "block") {
      var div = jax.SourceElement().previousSibling;
      div.style.overflow = "auto";
      div.style.minHeight = (div.offsetHeight+1) + "px"; // force height to be big enough
    }
  },
  //
  //  The static highlight selection
  //
  explorer: {
      walker: "dummy",
      highlight: "none",
      background: "blue",
      foreground: "black"
    },
  setExplorerOption: function(key, value) {
    if (this.explorer[key] === value) return;
    this.explorer[key] = value;
    MathJax.Extension.Explorer.Reset();
  },
  //
  //  Directly select a specific test equation
  //
  DirectSelect: function (n) {
    (n < 1 && (this.Current = this.Examples.length)) ||
      (n > this.Examples.length && (this.Current = 1)) ||
      (this.Current = parseInt(n));
    this.input.value = this.Examples[this.Current - 1];
    this.example.value = this.Current;
    this.Typeset();
  },
  //
  // Current test equation.
  //
  Current: 0,
  //
  // Select next test equation.
  //
  Next: function() {
    this.DirectSelect(this.Current + 1);
  },
  //
  // Select previous test equation.
  //
  Prev: function() {
    this.DirectSelect(this.Current - 1);
  },
  //
  // Change positioning for highlighting of HTML-CSS
  //
  AddStyleRule: function() {
    if (MathJax.Hub.outputJax['jax/mml'][0].id !== 'HTML-CSS') return;
    var cssRuleCode = document.all ? 'rules' : 'cssRules';
    var length = document.styleSheets.length;
    var cssSheet = document.styleSheets[length - 1][cssRuleCode];
    var index = cssSheet ? cssSheet.length : 0;
    document.styleSheets[length - 1].insertRule(
      '.MathJax span { position: relative; }', index);
  }
};

//
//  Hook into "New Math" signal to set overflow
//
MathJax.Hub.Register.MessageHook("New Math",["NewMath",Lab]);

//
//  Initialize everything once MathJax has run the first time
//
MathJax.Hub.Queue(function () {
  var defaults = [null,"0",
    String(Lab.defaults.width),
    String(Lab.defaults.collapse),
    String(Lab.defaults.overflow),
    Lab.defaults.walker,
    Lab.defaults.highlight,
    Lab.defaults.background,
    Lab.defaults.foreground,
    "",
  ];
  Lab.SMML = MathJax.Extension.SemanticMathML;
  Lab.jax = MathJax.Hub.getAllJax();
  Lab.input = document.getElementById("input");
  Lab.container = document.getElementById("container");
  Lab.enriched = document.getElementById("enriched");
  Lab.mathml = document.getElementById("mathml");
  Lab.example = document.getElementById("example");
  Lab.width = document.getElementById("width");
  if (window.location.search.length > 1)
    defaults = window.location.search.match(
        /^\?(.*?);(.*?);(.*?);(.*?);(.*?);(.*?);(.*?);(.*?);(.*)$/);
  Lab.example.value = defaults[1];
  Lab.Current = parseInt(defaults[1]);
  Lab.width.value = defaults[2];
  Lab.enriched.style.width = defaults[2];
  Lab.setWidth(Lab.width.value,true);
  Lab.collapse = document.getElementById("collapse").checked = (defaults[3] === "true");
  Lab.setCollapse(Lab.collapse,true);
  Lab.overflow = document.getElementById("overflow").checked = (defaults[4] === "true");
  Lab.setOverflow(Lab.overflow,true);
  Lab.setExplorerOption("walker", document.getElementById("walker").value = defaults[5]);
  Lab.setExplorerOption("highlight", document.getElementById("highlight").value = defaults[6]);
  Lab.setExplorerOption("background", document.getElementById("background").value = defaults[7]);
  Lab.setExplorerOption("foreground", document.getElementById("foreground").value = defaults[8]);
  Lab.input.value = unescape(defaults[9]);
  if (Lab.input.value !== "") Lab.Typeset();
  Lab.AddStyleRule();
});
<|endoftext|>


<commit_before>'use strict';

/* Services */

<%= angularAppName %>.factory('LanguageService', function ($http, $translate, LANGUAGES) {
        return {
            getBy: function(language) {
                if (language == undefined) {
                    language = $translate.storage().get('NG_TRANSLATE_LANG_KEY');
                }
                if (language == undefined) {
                    language = 'en';
                }

                var promise =  $http.get('i18n/' + language + '.json').then(function(response) {
                    return LANGUAGES;
                });
                return promise;
            }
        };
    });

<%= angularAppName %>.factory('Register', function ($resource) {
        return $resource('app/rest/register', {}, {
        });
    });

<%= angularAppName %>.factory('Activate', function ($resource) {
        return $resource('app/rest/activate', {}, {
            'get': { method: 'GET', params: {}, isArray: false}
        });
    });

<%= angularAppName %>.factory('Account', function ($resource) {
        return $resource('app/rest/account', {}, {
        });
    });

<%= angularAppName %>.factory('Password', function ($resource) {
        return $resource('app/rest/account/change_password', {}, {
        });
    });

<%= angularAppName %>.factory('Sessions', function ($resource) {
        return $resource('app/rest/account/sessions/:series', {}, {
            'get': { method: 'GET', isArray: true}
        });
    });

<%= angularAppName %>.factory('MetricsService',function ($http) {
    		return {
            get: function() {
                var promise = $http.get('metrics/metrics').then(function(response){
                    return response.data;
                });
                return promise;
            }
        };
    });

<%= angularAppName %>.factory('ThreadDumpService', function ($http) {
        return {
            dump: function() {
                var promise = $http.get('dump').then(function(response){
                    return response.data;
                });
                return promise;
            }
        };
    });

<%= angularAppName %>.factory('HealthCheckService', function ($rootScope, $http) {
        return {
            check: function() {
                var promise = $http.get('health').then(function(response){
                    return response.data;
                });
                return promise;
            }
        };
    });

<%= angularAppName %>.factory('ConfigurationService', function ($rootScope, $http) {
    return {
        get: function() {
            var promise = $http.get('configprops').then(function(response){
                var properties = [];
                angular.forEach(response.data, function(data) {
                    properties.push(data);
                });
                return properties;
            });
            return promise;
        }
    };
});

<%= angularAppName %>.factory('LogsService', function ($resource) {
        return $resource('app/rest/logs', {}, {
            'findAll': { method: 'GET', isArray: true},
            'changeLevel':  { method: 'PUT'}
        });
    });

<%= angularAppName %>.factory('AuditsService', function ($http) {
        return {
            findAll: function() {
                var promise = $http.get('app/rest/audits/all').then(function (response) {
                    return response.data;
                });
                return promise;
            },
            findByDates: function(fromDate, toDate) {
                var promise = $http.get('app/rest/audits/byDates', {params: {fromDate: fromDate, toDate: toDate}}).then(function (response) {
                    return response.data;
                });
                return promise;
            }
        }
    });

<%= angularAppName %>.factory('Session', function () {
        this.create = function (login, firstName, lastName, email, userRoles) {
            this.login = login;
            this.firstName = firstName;
            this.lastName = lastName;
            this.email = email;
            this.userRoles = userRoles;
        };
        this.invalidate = function () {
            this.login = null;
            this.firstName = null;
            this.lastName = null;
            this.email = null;
            this.userRoles = null;
        };
        return this;
    });

<%= angularAppName %>.factory('AuthenticationSharedService', function ($rootScope, $http, authService, Session, Account<% if (authenticationType == 'token') { %>, Base64Service, AccessToken<% } %>) {
        return {
            login: function (param) {<% if (authenticationType == 'cookie') { %>
                var data ="j_username=" + encodeURIComponent(param.username) +"&j_password=" + encodeURIComponent(param.password) +"&_spring_security_remember_me=" + param.rememberMe +"&submit=Login";
                $http.post('app/authentication', data, {
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    ignoreAuthModule: 'ignoreAuthModule'
                }).success(function (data, status, headers, config) {
                    Account.get(function(data) {
                        Session.create(data.login, data.firstName, data.lastName, data.email, data.roles);
                        $rootScope.account = Session;
                        authService.loginConfirmed(data);
                    });
                }).error(function (data, status, headers, config) {
                    $rootScope.authenticationError = true;
                    Session.invalidate();
                });<% } %><% if (authenticationType == 'token') { %>
                var data = "username=" + param.username + "&password=" + param.password + "&grant_type=password&scope=read%20write&client_secret=mySecretOAuthSecret&client_id=<%= baseName%>app";
                $http.post('oauth/token', data, {
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded",
                        "Accept": "application/json",
                        "Authorization": "Basic " + Base64Service.encode("<%= baseName%>app" + ':' + "mySecretOAuthSecret")
                    },
                    ignoreAuthModule: 'ignoreAuthModule'
                }).success(function (data, status, headers, config) {
                    httpHeaders.common['Authorization'] = 'Bearer ' + data.access_token;
                    AccessToken.set(data);

                    Account.get(function(data) {
                        Session.create(data.login, data.firstName, data.lastName, data.email, data.roles);
                        $rootScope.account = Session;
                        authService.loginConfirmed(data);
                    });
                }).error(function (data, status, headers, config) {
                    $rootScope.authenticated = false;
                    Session.invalidate();
                    AccessToken.remove();
                    delete httpHeaders.common['Authorization'];

                    if (!$rootScope.isAuthorized(authorizedRoles)) {
                        $rootScope.$broadcast('event:auth-loginRequired', data);
                    }
                });<% } %>
            },
            valid: function (authorizedRoles) {<% if (authenticationType == 'token') { %>
                if(AccessToken.get() !== null) {
                    httpHeaders.common['Authorization'] = 'Bearer ' + AccessToken.get();
                }<% } %>

                $http.get('protected/authentication_check.gif', {
                    ignoreAuthModule: 'ignoreAuthModule'
                }).success(function (data, status, headers, config) {
                    if (!Session.login<% if (authenticationType == 'token') { %> || AccessToken.get() != undefined<% } %>) {<% if (authenticationType == 'token') { %>
                        if (AccessToken.get() == undefined || AccessToken.expired()) {
                            $rootScope.$broadcast("event:auth-loginRequired");
                            return;
                        }<% } %>
                        Account.get(function(data) {
                            Session.create(data.login, data.firstName, data.lastName, data.email, data.roles);
                            $rootScope.account = Session;
                            if (!$rootScope.isAuthorized(authorizedRoles)) {
                                // user is not allowed
                               $rootScope.$broadcast("event:auth-notAuthorized");
                            } else {
                                $rootScope.$broadcast("event:auth-loginConfirmed");
                            }
                        });
                    }else{
                        if (!$rootScope.isAuthorized(authorizedRoles)) {
                                // user is not allowed
                                $rootScope.$broadcast("event:auth-notAuthorized");
                        } else {
                                $rootScope.$broadcast("event:auth-loginConfirmed");
                        }
                    }
                }).error(function (data, status, headers, config) {
                    if (!$rootScope.isAuthorized(authorizedRoles)) {
                        $rootScope.$broadcast('event:auth-loginRequired', data);
                    }
                });
            },
            isAuthorized: function (authorizedRoles) {
                if (!angular.isArray(authorizedRoles)) {
                    if (authorizedRoles == '*') {
                        return true;
                    }

                    authorizedRoles = [authorizedRoles];
                }

                var isAuthorized = false;
                angular.forEach(authorizedRoles, function(authorizedRole) {
                    var authorized = (!!Session.login &&
                        Session.userRoles.indexOf(authorizedRole) !== -1);

                    if (authorized || authorizedRole == '*') {
                        isAuthorized = true;
                    }
                });

                return isAuthorized;
            },
            logout: function () {
                $rootScope.authenticationError = false;
                $rootScope.authenticated = false;
                $rootScope.account = null;<% if (authenticationType == 'token') { %>
                AccessToken.remove();<% } %>

                $http.get('app/logout');
                Session.invalidate();<% if (authenticationType == 'token') { %>
                delete httpHeaders.common['Authorization'];<% } %>
                authService.loginCancelled();
            }
        };
    });
<commit_msg>Ordered properties by prefix<commit_after>'use strict';

/* Services */

<%= angularAppName %>.factory('LanguageService', function ($http, $translate, LANGUAGES) {
        return {
            getBy: function(language) {
                if (language == undefined) {
                    language = $translate.storage().get('NG_TRANSLATE_LANG_KEY');
                }
                if (language == undefined) {
                    language = 'en';
                }

                var promise =  $http.get('i18n/' + language + '.json').then(function(response) {
                    return LANGUAGES;
                });
                return promise;
            }
        };
    });

<%= angularAppName %>.factory('Register', function ($resource) {
        return $resource('app/rest/register', {}, {
        });
    });

<%= angularAppName %>.factory('Activate', function ($resource) {
        return $resource('app/rest/activate', {}, {
            'get': { method: 'GET', params: {}, isArray: false}
        });
    });

<%= angularAppName %>.factory('Account', function ($resource) {
        return $resource('app/rest/account', {}, {
        });
    });

<%= angularAppName %>.factory('Password', function ($resource) {
        return $resource('app/rest/account/change_password', {}, {
        });
    });

<%= angularAppName %>.factory('Sessions', function ($resource) {
        return $resource('app/rest/account/sessions/:series', {}, {
            'get': { method: 'GET', isArray: true}
        });
    });

<%= angularAppName %>.factory('MetricsService',function ($http) {
    		return {
            get: function() {
                var promise = $http.get('metrics/metrics').then(function(response){
                    return response.data;
                });
                return promise;
            }
        };
    });

<%= angularAppName %>.factory('ThreadDumpService', function ($http) {
        return {
            dump: function() {
                var promise = $http.get('dump').then(function(response){
                    return response.data;
                });
                return promise;
            }
        };
    });

<%= angularAppName %>.factory('HealthCheckService', function ($rootScope, $http) {
        return {
            check: function() {
                var promise = $http.get('health').then(function(response){
                    return response.data;
                });
                return promise;
            }
        };
    });

<%= angularAppName %>.factory('ConfigurationService', function ($rootScope, $filter, $http) {
    return {
        get: function() {
            var promise = $http.get('configprops').then(function(response){
                var properties = [];
                angular.forEach(response.data, function(data) {
                    properties.push(data);
                });
                var orderBy = $filter('orderBy');
                return orderBy(properties, 'prefix');;
            });
            return promise;
        }
    };
});

<%= angularAppName %>.factory('LogsService', function ($resource) {
        return $resource('app/rest/logs', {}, {
            'findAll': { method: 'GET', isArray: true},
            'changeLevel':  { method: 'PUT'}
        });
    });

<%= angularAppName %>.factory('AuditsService', function ($http) {
        return {
            findAll: function() {
                var promise = $http.get('app/rest/audits/all').then(function (response) {
                    return response.data;
                });
                return promise;
            },
            findByDates: function(fromDate, toDate) {
                var promise = $http.get('app/rest/audits/byDates', {params: {fromDate: fromDate, toDate: toDate}}).then(function (response) {
                    return response.data;
                });
                return promise;
            }
        }
    });

<%= angularAppName %>.factory('Session', function () {
        this.create = function (login, firstName, lastName, email, userRoles) {
            this.login = login;
            this.firstName = firstName;
            this.lastName = lastName;
            this.email = email;
            this.userRoles = userRoles;
        };
        this.invalidate = function () {
            this.login = null;
            this.firstName = null;
            this.lastName = null;
            this.email = null;
            this.userRoles = null;
        };
        return this;
    });

<%= angularAppName %>.factory('AuthenticationSharedService', function ($rootScope, $http, authService, Session, Account<% if (authenticationType == 'token') { %>, Base64Service, AccessToken<% } %>) {
        return {
            login: function (param) {<% if (authenticationType == 'cookie') { %>
                var data ="j_username=" + encodeURIComponent(param.username) +"&j_password=" + encodeURIComponent(param.password) +"&_spring_security_remember_me=" + param.rememberMe +"&submit=Login";
                $http.post('app/authentication', data, {
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    ignoreAuthModule: 'ignoreAuthModule'
                }).success(function (data, status, headers, config) {
                    Account.get(function(data) {
                        Session.create(data.login, data.firstName, data.lastName, data.email, data.roles);
                        $rootScope.account = Session;
                        authService.loginConfirmed(data);
                    });
                }).error(function (data, status, headers, config) {
                    $rootScope.authenticationError = true;
                    Session.invalidate();
                });<% } %><% if (authenticationType == 'token') { %>
                var data = "username=" + param.username + "&password=" + param.password + "&grant_type=password&scope=read%20write&client_secret=mySecretOAuthSecret&client_id=<%= baseName%>app";
                $http.post('oauth/token', data, {
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded",
                        "Accept": "application/json",
                        "Authorization": "Basic " + Base64Service.encode("<%= baseName%>app" + ':' + "mySecretOAuthSecret")
                    },
                    ignoreAuthModule: 'ignoreAuthModule'
                }).success(function (data, status, headers, config) {
                    httpHeaders.common['Authorization'] = 'Bearer ' + data.access_token;
                    AccessToken.set(data);

                    Account.get(function(data) {
                        Session.create(data.login, data.firstName, data.lastName, data.email, data.roles);
                        $rootScope.account = Session;
                        authService.loginConfirmed(data);
                    });
                }).error(function (data, status, headers, config) {
                    $rootScope.authenticated = false;
                    Session.invalidate();
                    AccessToken.remove();
                    delete httpHeaders.common['Authorization'];

                    if (!$rootScope.isAuthorized(authorizedRoles)) {
                        $rootScope.$broadcast('event:auth-loginRequired', data);
                    }
                });<% } %>
            },
            valid: function (authorizedRoles) {<% if (authenticationType == 'token') { %>
                if(AccessToken.get() !== null) {
                    httpHeaders.common['Authorization'] = 'Bearer ' + AccessToken.get();
                }<% } %>

                $http.get('protected/authentication_check.gif', {
                    ignoreAuthModule: 'ignoreAuthModule'
                }).success(function (data, status, headers, config) {
                    if (!Session.login<% if (authenticationType == 'token') { %> || AccessToken.get() != undefined<% } %>) {<% if (authenticationType == 'token') { %>
                        if (AccessToken.get() == undefined || AccessToken.expired()) {
                            $rootScope.$broadcast("event:auth-loginRequired");
                            return;
                        }<% } %>
                        Account.get(function(data) {
                            Session.create(data.login, data.firstName, data.lastName, data.email, data.roles);
                            $rootScope.account = Session;
                            if (!$rootScope.isAuthorized(authorizedRoles)) {
                                // user is not allowed
                               $rootScope.$broadcast("event:auth-notAuthorized");
                            } else {
                                $rootScope.$broadcast("event:auth-loginConfirmed");
                            }
                        });
                    }else{
                        if (!$rootScope.isAuthorized(authorizedRoles)) {
                                // user is not allowed
                                $rootScope.$broadcast("event:auth-notAuthorized");
                        } else {
                                $rootScope.$broadcast("event:auth-loginConfirmed");
                        }
                    }
                }).error(function (data, status, headers, config) {
                    if (!$rootScope.isAuthorized(authorizedRoles)) {
                        $rootScope.$broadcast('event:auth-loginRequired', data);
                    }
                });
            },
            isAuthorized: function (authorizedRoles) {
                if (!angular.isArray(authorizedRoles)) {
                    if (authorizedRoles == '*') {
                        return true;
                    }

                    authorizedRoles = [authorizedRoles];
                }

                var isAuthorized = false;
                angular.forEach(authorizedRoles, function(authorizedRole) {
                    var authorized = (!!Session.login &&
                        Session.userRoles.indexOf(authorizedRole) !== -1);

                    if (authorized || authorizedRole == '*') {
                        isAuthorized = true;
                    }
                });

                return isAuthorized;
            },
            logout: function () {
                $rootScope.authenticationError = false;
                $rootScope.authenticated = false;
                $rootScope.account = null;<% if (authenticationType == 'token') { %>
                AccessToken.remove();<% } %>

                $http.get('app/logout');
                Session.invalidate();<% if (authenticationType == 'token') { %>
                delete httpHeaders.common['Authorization'];<% } %>
                authService.loginCancelled();
            }
        };
    });
<|endoftext|>


<commit_before>/**
@license
topojson - https://github.com/mbostock/topojson

Copyright (c) 2012, Michael Bostock
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* The name Michael Bostock may not be used to endorse or promote products
  derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*global define*/
define(function() {

var topojson = (function() {

  function merge(topology, arcs) {
    var arcsByEnd = {},
        fragmentByStart = {},
        fragmentByEnd = {};

    arcs.forEach(function(i) {
      var e = ends(i);
      (arcsByEnd[e[0]] || (arcsByEnd[e[0]] = [])).push(i);
      (arcsByEnd[e[1]] || (arcsByEnd[e[1]] = [])).push(~i);
    });

    arcs.forEach(function(i) {
      var e = ends(i),
          start = e[0],
          end = e[1],
          f, g;

      if (f = fragmentByEnd[start]) {
        delete fragmentByEnd[f.end];
        f.push(i);
        f.end = end;
        if (g = fragmentByStart[end]) {
          delete fragmentByStart[g.start];
          var fg = g === f ? f : f.concat(g);
          fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg;
        } else if (g = fragmentByEnd[end]) {
          delete fragmentByStart[g.start];
          delete fragmentByEnd[g.end];
          var fg = f.concat(g.map(function(i) { return ~i; }).reverse());
          fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.start] = fg;
        } else {
          fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
        }
      } else if (f = fragmentByStart[end]) {
        delete fragmentByStart[f.start];
        f.unshift(i);
        f.start = start;
        if (g = fragmentByEnd[start]) {
          delete fragmentByEnd[g.end];
          var gf = g === f ? f : g.concat(f);
          fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf;
        } else if (g = fragmentByStart[start]) {
          delete fragmentByStart[g.start];
          delete fragmentByEnd[g.end];
          var gf = g.map(function(i) { return ~i; }).reverse().concat(f);
          fragmentByStart[gf.start = g.end] = fragmentByEnd[gf.end = f.end] = gf;
        } else {
          fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
        }
      } else if (f = fragmentByStart[start]) {
        delete fragmentByStart[f.start];
        f.unshift(~i);
        f.start = end;
        if (g = fragmentByEnd[end]) {
          delete fragmentByEnd[g.end];
          var gf = g === f ? f : g.concat(f);
          fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf;
        } else if (g = fragmentByStart[end]) {
          delete fragmentByStart[g.start];
          delete fragmentByEnd[g.end];
          var gf = g.map(function(i) { return ~i; }).reverse().concat(f);
          fragmentByStart[gf.start = g.end] = fragmentByEnd[gf.end = f.end] = gf;
        } else {
          fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
        }
      } else if (f = fragmentByEnd[end]) {
        delete fragmentByEnd[f.end];
        f.push(~i);
        f.end = start;
        if (g = fragmentByEnd[start]) {
          delete fragmentByStart[g.start];
          var fg = g === f ? f : f.concat(g);
          fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg;
        } else if (g = fragmentByStart[start]) {
          delete fragmentByStart[g.start];
          delete fragmentByEnd[g.end];
          var fg = f.concat(g.map(function(i) { return ~i; }).reverse());
          fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.start] = fg;
        } else {
          fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
        }
      } else {
        f = [i];
        fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f;
      }
    });

    function ends(i) {
      var arc = topology.arcs[i], p0 = arc[0], p1 = [0, 0];
      arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; });
      return [p0, p1];
    }

    var fragments = [];
    for (var k in fragmentByEnd) fragments.push(fragmentByEnd[k]);
    return fragments;
  }

  function mesh(topology, o, filter) {
    var arcs = [];

    if (arguments.length > 1) {
      var geomsByArc = [],
          geom;

      function arc(i) {
        if (i < 0) i = ~i;
        (geomsByArc[i] || (geomsByArc[i] = [])).push(geom);
      }

      function line(arcs) {
        arcs.forEach(arc);
      }

      function polygon(arcs) {
        arcs.forEach(line);
      }

      function geometry(o) {
        if (o.type === "GeometryCollection") o.geometries.forEach(geometry);
        else if (o.type in geometryType) {
          geom = o;
          geometryType[o.type](o.arcs);
        }
      }

      var geometryType = {
        LineString: line,
        MultiLineString: polygon,
        Polygon: polygon,
        MultiPolygon: function(arcs) { arcs.forEach(polygon); }
      };

      geometry(o);

      geomsByArc.forEach(arguments.length < 3
          ? function(geoms, i) { arcs.push(i); }
          : function(geoms, i) { if (filter(geoms[0], geoms[geoms.length - 1])) arcs.push(i); });
    } else {
      for (var i = 0, n = topology.arcs.length; i < n; ++i) arcs.push(i);
    }

    return object(topology, {type: "MultiLineString", arcs: merge(topology, arcs)});
  }

  function featureOrCollection(topology, o) {
    return o.type === "GeometryCollection" ? {
      type: "FeatureCollection",
      features: o.geometries.map(function(o) { return feature(topology, o); })
    } : feature(topology, o);
  }

  function feature(topology, o) {
    var f = {
      type: "Feature",
      id: o.id,
      properties: o.properties || {},
      geometry: object(topology, o)
    };
    if (o.id == null) delete f.id;
    return f;
  }

  function object(topology, o) {
    var tf = topology.transform,
        kx = tf.scale[0],
        ky = tf.scale[1],
        dx = tf.translate[0],
        dy = tf.translate[1],
        arcs = topology.arcs;

    function arc(i, points) {
      if (points.length) points.pop();
      for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length, x = 0, y = 0, p; k < n; ++k) points.push([
        (x += (p = a[k])[0]) * kx + dx,
        (y += p[1]) * ky + dy
      ]);
      if (i < 0) reverse(points, n);
    }

    function point(coordinates) {
      return [coordinates[0] * kx + dx, coordinates[1] * ky + dy];
    }

    function line(arcs) {
      var points = [];
      for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points);
      if (points.length < 2) points.push(points[0]);
      return points;
    }

    function ring(arcs) {
      var points = line(arcs);
      while (points.length < 4) points.push(points[0]);
      return points;
    }

    function polygon(arcs) {
      return arcs.map(ring);
    }

    function geometry(o) {
      var t = o.type;
      return t === "GeometryCollection" ? {type: t, geometries: o.geometries.map(geometry)}
          : t in geometryType ? {type: t, coordinates: geometryType[t](o)}
          : null;
    }

    var geometryType = {
      Point: function(o) { return point(o.coordinates); },
      MultiPoint: function(o) { return o.coordinates.map(point); },
      LineString: function(o) { return line(o.arcs); },
      MultiLineString: function(o) { return o.arcs.map(line); },
      Polygon: function(o) { return polygon(o.arcs); },
      MultiPolygon: function(o) { return o.arcs.map(polygon); }
    };

    return geometry(o);
  }

  function reverse(array, n) {
    var t, j = array.length, i = j - n; while (i < --j) t = array[i], array[i++] = array[j], array[j] = t;
  }

  function bisect(a, x) {
    var lo = 0, hi = a.length;
    while (lo < hi) {
      var mid = lo + hi >>> 1;
      if (a[mid] < x) lo = mid + 1;
      else hi = mid;
    }
    return lo;
  }

  function neighbors(objects) {
    var indexesByArc = {}, // arc index -> array of object indexes
        neighbors = objects.map(function() { return []; });

    function line(arcs, i) {
      arcs.forEach(function(a) {
        if (a < 0) a = ~a;
        var o = indexesByArc[a];
        if (o) o.push(i);
        else indexesByArc[a] = [i];
      });
    }

    function polygon(arcs, i) {
      arcs.forEach(function(arc) { line(arc, i); });
    }

    function geometry(o, i) {
      if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); });
      else if (o.type in geometryType) geometryType[o.type](o.arcs, i);
    }

    var geometryType = {
      LineString: line,
      MultiLineString: polygon,
      Polygon: polygon,
      MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); }
    };

    objects.forEach(geometry);

    for (var i in indexesByArc) {
      for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) {
        for (var k = j + 1; k < m; ++k) {
          var ij = indexes[j], ik = indexes[k], n;
          if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik);
          if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij);
        }
      }
    }

    return neighbors;
  }

  return {
    version: "1.1.4",
    mesh: mesh,
    feature: featureOrCollection,
    neighbors: neighbors
  };
})();

return topojson;
});<commit_msg>Upgrade topojson to 1.6.8<commit_after>!function() {
  var topojson = {
    version: "1.6.8",
    mesh: function(topology) { return object(topology, meshArcs.apply(this, arguments)); },
    meshArcs: meshArcs,
    merge: function(topology) { return object(topology, mergeArcs.apply(this, arguments)); },
    mergeArcs: mergeArcs,
    feature: featureOrCollection,
    neighbors: neighbors,
    presimplify: presimplify
  };

  function stitchArcs(topology, arcs) {
    var stitchedArcs = {},
        fragmentByStart = {},
        fragmentByEnd = {},
        fragments = [],
        emptyIndex = -1;

    // Stitch empty arcs first, since they may be subsumed by other arcs.
    arcs.forEach(function(i, j) {
      var arc = topology.arcs[i < 0 ? ~i : i], t;
      if (arc.length < 3 && !arc[1][0] && !arc[1][1]) {
        t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t;
      }
    });

    arcs.forEach(function(i) {
      var e = ends(i),
          start = e[0],
          end = e[1],
          f, g;

      if (f = fragmentByEnd[start]) {
        delete fragmentByEnd[f.end];
        f.push(i);
        f.end = end;
        if (g = fragmentByStart[end]) {
          delete fragmentByStart[g.start];
          var fg = g === f ? f : f.concat(g);
          fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg;
        } else {
          fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
        }
      } else if (f = fragmentByStart[end]) {
        delete fragmentByStart[f.start];
        f.unshift(i);
        f.start = start;
        if (g = fragmentByEnd[start]) {
          delete fragmentByEnd[g.end];
          var gf = g === f ? f : g.concat(f);
          fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf;
        } else {
          fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
        }
      } else {
        f = [i];
        fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f;
      }
    });

    function ends(i) {
      var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1;
      if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; });
      else p1 = arc[arc.length - 1];
      return i < 0 ? [p1, p0] : [p0, p1];
    }

    function flush(fragmentByEnd, fragmentByStart) {
      for (var k in fragmentByEnd) {
        var f = fragmentByEnd[k];
        delete fragmentByStart[f.start];
        delete f.start;
        delete f.end;
        f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; });
        fragments.push(f);
      }
    }

    flush(fragmentByEnd, fragmentByStart);
    flush(fragmentByStart, fragmentByEnd);
    arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); });

    return fragments;
  }

  function meshArcs(topology, o, filter) {
    var arcs = [];

    if (arguments.length > 1) {
      var geomsByArc = [],
          geom;

      function arc(i) {
        var j = i < 0 ? ~i : i;
        (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom});
      }

      function line(arcs) {
        arcs.forEach(arc);
      }

      function polygon(arcs) {
        arcs.forEach(line);
      }

      function geometry(o) {
        if (o.type === "GeometryCollection") o.geometries.forEach(geometry);
        else if (o.type in geometryType) geom = o, geometryType[o.type](o.arcs);
      }

      var geometryType = {
        LineString: line,
        MultiLineString: polygon,
        Polygon: polygon,
        MultiPolygon: function(arcs) { arcs.forEach(polygon); }
      };

      geometry(o);

      geomsByArc.forEach(arguments.length < 3
          ? function(geoms) { arcs.push(geoms[0].i); }
          : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); });
    } else {
      for (var i = 0, n = topology.arcs.length; i < n; ++i) arcs.push(i);
    }

    return {type: "MultiLineString", arcs: stitchArcs(topology, arcs)};
  }

  function mergeArcs(topology, objects) {
    var polygonsByArc = {},
        polygons = [],
        components = [];

    objects.forEach(function(o) {
      if (o.type === "Polygon") register(o.arcs);
      else if (o.type === "MultiPolygon") o.arcs.forEach(register);
    });

    function register(polygon) {
      polygon.forEach(function(ring) {
        ring.forEach(function(arc) {
          (polygonsByArc[arc = arc < 0 ? ~arc : arc] || (polygonsByArc[arc] = [])).push(polygon);
        });
      });
      polygons.push(polygon);
    }

    function exterior(ring) {
      return cartesianRingArea(object(topology, {type: "Polygon", arcs: [ring]}).coordinates[0]) > 0; // TODO allow spherical?
    }

    polygons.forEach(function(polygon) {
      if (!polygon._) {
        var component = [],
            neighbors = [polygon];
        polygon._ = 1;
        components.push(component);
        while (polygon = neighbors.pop()) {
          component.push(polygon);
          polygon.forEach(function(ring) {
            ring.forEach(function(arc) {
              polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) {
                if (!polygon._) {
                  polygon._ = 1;
                  neighbors.push(polygon);
                }
              });
            });
          });
        }
      }
    });

    polygons.forEach(function(polygon) {
      delete polygon._;
    });

    return {
      type: "MultiPolygon",
      arcs: components.map(function(polygons) {
        var arcs = [];

        // Extract the exterior (unique) arcs.
        polygons.forEach(function(polygon) {
          polygon.forEach(function(ring) {
            ring.forEach(function(arc) {
              if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) {
                arcs.push(arc);
              }
            });
          });
        });

        // Stitch the arcs into one or more rings.
        arcs = stitchArcs(topology, arcs);

        // If more than one ring is returned,
        // at most one of these rings can be the exterior;
        // this exterior ring has the same winding order
        // as any exterior ring in the original polygons.
        if ((n = arcs.length) > 1) {
          var sgn = exterior(polygons[0][0]);
          for (var i = 0, t; i < n; ++i) {
            if (sgn === exterior(arcs[i])) {
              t = arcs[0], arcs[0] = arcs[i], arcs[i] = t;
              break;
            }
          }
        }

        return arcs;
      })
    };
  }

  function featureOrCollection(topology, o) {
    return o.type === "GeometryCollection" ? {
      type: "FeatureCollection",
      features: o.geometries.map(function(o) { return feature(topology, o); })
    } : feature(topology, o);
  }

  function feature(topology, o) {
    var f = {
      type: "Feature",
      id: o.id,
      properties: o.properties || {},
      geometry: object(topology, o)
    };
    if (o.id == null) delete f.id;
    return f;
  }

  function object(topology, o) {
    var absolute = transformAbsolute(topology.transform),
        arcs = topology.arcs;

    function arc(i, points) {
      if (points.length) points.pop();
      for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length, p; k < n; ++k) {
        points.push(p = a[k].slice());
        absolute(p, k);
      }
      if (i < 0) reverse(points, n);
    }

    function point(p) {
      p = p.slice();
      absolute(p, 0);
      return p;
    }

    function line(arcs) {
      var points = [];
      for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points);
      if (points.length < 2) points.push(points[0].slice());
      return points;
    }

    function ring(arcs) {
      var points = line(arcs);
      while (points.length < 4) points.push(points[0].slice());
      return points;
    }

    function polygon(arcs) {
      return arcs.map(ring);
    }

    function geometry(o) {
      var t = o.type;
      return t === "GeometryCollection" ? {type: t, geometries: o.geometries.map(geometry)}
          : t in geometryType ? {type: t, coordinates: geometryType[t](o)}
          : null;
    }

    var geometryType = {
      Point: function(o) { return point(o.coordinates); },
      MultiPoint: function(o) { return o.coordinates.map(point); },
      LineString: function(o) { return line(o.arcs); },
      MultiLineString: function(o) { return o.arcs.map(line); },
      Polygon: function(o) { return polygon(o.arcs); },
      MultiPolygon: function(o) { return o.arcs.map(polygon); }
    };

    return geometry(o);
  }

  function reverse(array, n) {
    var t, j = array.length, i = j - n; while (i < --j) t = array[i], array[i++] = array[j], array[j] = t;
  }

  function bisect(a, x) {
    var lo = 0, hi = a.length;
    while (lo < hi) {
      var mid = lo + hi >>> 1;
      if (a[mid] < x) lo = mid + 1;
      else hi = mid;
    }
    return lo;
  }

  function neighbors(objects) {
    var indexesByArc = {}, // arc index -> array of object indexes
        neighbors = objects.map(function() { return []; });

    function line(arcs, i) {
      arcs.forEach(function(a) {
        if (a < 0) a = ~a;
        var o = indexesByArc[a];
        if (o) o.push(i);
        else indexesByArc[a] = [i];
      });
    }

    function polygon(arcs, i) {
      arcs.forEach(function(arc) { line(arc, i); });
    }

    function geometry(o, i) {
      if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); });
      else if (o.type in geometryType) geometryType[o.type](o.arcs, i);
    }

    var geometryType = {
      LineString: line,
      MultiLineString: polygon,
      Polygon: polygon,
      MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); }
    };

    objects.forEach(geometry);

    for (var i in indexesByArc) {
      for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) {
        for (var k = j + 1; k < m; ++k) {
          var ij = indexes[j], ik = indexes[k], n;
          if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik);
          if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij);
        }
      }
    }

    return neighbors;
  }

  function presimplify(topology, triangleArea) {
    var absolute = transformAbsolute(topology.transform),
        relative = transformRelative(topology.transform),
        heap = minAreaHeap(),
        maxArea = 0,
        triangle;

    if (!triangleArea) triangleArea = cartesianTriangleArea;

    topology.arcs.forEach(function(arc) {
      var triangles = [];

      arc.forEach(absolute);

      for (var i = 1, n = arc.length - 1; i < n; ++i) {
        triangle = arc.slice(i - 1, i + 2);
        triangle[1][2] = triangleArea(triangle);
        triangles.push(triangle);
        heap.push(triangle);
      }

      // Always keep the arc endpoints!
      arc[0][2] = arc[n][2] = Infinity;

      for (var i = 0, n = triangles.length; i < n; ++i) {
        triangle = triangles[i];
        triangle.previous = triangles[i - 1];
        triangle.next = triangles[i + 1];
      }
    });

    while (triangle = heap.pop()) {
      var previous = triangle.previous,
          next = triangle.next;

      // If the area of the current point is less than that of the previous point
      // to be eliminated, use the latter's area instead. This ensures that the
      // current point cannot be eliminated without eliminating previously-
      // eliminated points.
      if (triangle[1][2] < maxArea) triangle[1][2] = maxArea;
      else maxArea = triangle[1][2];

      if (previous) {
        previous.next = next;
        previous[2] = triangle[2];
        update(previous);
      }

      if (next) {
        next.previous = previous;
        next[0] = triangle[0];
        update(next);
      }
    }

    topology.arcs.forEach(function(arc) {
      arc.forEach(relative);
    });

    function update(triangle) {
      heap.remove(triangle);
      triangle[1][2] = triangleArea(triangle);
      heap.push(triangle);
    }

    return topology;
  };

  function cartesianRingArea(ring) {
    var i = -1,
        n = ring.length,
        a,
        b = ring[n - 1],
        area = 0;

    while (++i < n) {
      a = b;
      b = ring[i];
      area += a[0] * b[1] - a[1] * b[0];
    }

    return area * .5;
  }

  function cartesianTriangleArea(triangle) {
    var a = triangle[0], b = triangle[1], c = triangle[2];
    return Math.abs((a[0] - c[0]) * (b[1] - a[1]) - (a[0] - b[0]) * (c[1] - a[1]));
  }

  function compareArea(a, b) {
    return a[1][2] - b[1][2];
  }

  function minAreaHeap() {
    var heap = {},
        array = [],
        size = 0;

    heap.push = function(object) {
      up(array[object._ = size] = object, size++);
      return size;
    };

    heap.pop = function() {
      if (size <= 0) return;
      var removed = array[0], object;
      if (--size > 0) object = array[size], down(array[object._ = 0] = object, 0);
      return removed;
    };

    heap.remove = function(removed) {
      var i = removed._, object;
      if (array[i] !== removed) return; // invalid request
      if (i !== --size) object = array[size], (compareArea(object, removed) < 0 ? up : down)(array[object._ = i] = object, i);
      return i;
    };

    function up(object, i) {
      while (i > 0) {
        var j = ((i + 1) >> 1) - 1,
            parent = array[j];
        if (compareArea(object, parent) >= 0) break;
        array[parent._ = i] = parent;
        array[object._ = i = j] = object;
      }
    }

    function down(object, i) {
      while (true) {
        var r = (i + 1) << 1,
            l = r - 1,
            j = i,
            child = array[j];
        if (l < size && compareArea(array[l], child) < 0) child = array[j = l];
        if (r < size && compareArea(array[r], child) < 0) child = array[j = r];
        if (j === i) break;
        array[child._ = i] = child;
        array[object._ = i = j] = object;
      }
    }

    return heap;
  }

  function transformAbsolute(transform) {
    if (!transform) return noop;
    var x0,
        y0,
        kx = transform.scale[0],
        ky = transform.scale[1],
        dx = transform.translate[0],
        dy = transform.translate[1];
    return function(point, i) {
      if (!i) x0 = y0 = 0;
      point[0] = (x0 += point[0]) * kx + dx;
      point[1] = (y0 += point[1]) * ky + dy;
    };
  }

  function transformRelative(transform) {
    if (!transform) return noop;
    var x0,
        y0,
        kx = transform.scale[0],
        ky = transform.scale[1],
        dx = transform.translate[0],
        dy = transform.translate[1];
    return function(point, i) {
      if (!i) x0 = y0 = 0;
      var x1 = (point[0] - dx) / kx | 0,
          y1 = (point[1] - dy) / ky | 0;
      point[0] = x1 - x0;
      point[1] = y1 - y0;
      x0 = x1;
      y0 = y1;
    };
  }

  function noop() {}

  if (typeof define === "function" && define.amd) define(topojson);
  else if (typeof module === "object" && module.exports) module.exports = topojson;
  else this.topojson = topojson;
}();
<|endoftext|>


<commit_before>import React from 'react';
import { Link } from 'react-router-dom';
import { API_PATH } from '../api/_entrypoint';

export function itemToLinks(items) {
  return Array.isArray(items) ? items.map(item => createLink(item)) : createLink(items);
}

function createLink(item) {
  if (typeof(item) === 'string' && item.includes(API_PATH) > 0) {
    let route = null;
    const routeTest = item.replace(API_PATH, '');
    if( routeTest[0] === '/') {
      route = item.replace(API_PATH, '').split('/')[1];
    } else {
      route = item.replace(API_PATH, '').split('/')[0];
    }
    return (

        <Link to={`/${route}/show/${encodeURIComponent(item)}`}>
          {item}
        </Link>

    );
  }
  return {item}
;
}

export function paginationRoute(item) {
  return '/' + item.split('/').splice(-1,1);
}
<commit_msg>[react] Improve utils<commit_after>import React from 'react';
import { Link } from 'react-router-dom';
import { API_PATH } from '../api/_entrypoint';

export function itemToLinks(items) {
  return Array.isArray(items) ? items.map(item => createLink(item)) : createLink(items);
}

function createLink(item) {
  if ('string' !== typeof(item) || !item.includes(API_PATH)) {
    return {item}
;
  }

  const routeWithoutPrefix = item.replace(API_PATH, '');
  const splittedRoute = routeWithoutPrefix.split('/');
  const route = '/' === routeWithoutPrefix[0] ? splittedRoute[1] : splittedRoute[0];

  return <Link key={item} to={`/${route}/show/${encodeURIComponent(item)}`}>{item}</Link>
;
}

export function paginationRoute(item) {
  return '/' + item.split('/').splice(-1, 1);
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name            Static Google
// @description     Google search interface always visible on screen, and some additional changes for more compact layout.
// @author          tumpio
// @oujs:author     tumpio
// @namespace       tumpio@sci.fi
// @homepageURL     https://openuserjs.org/scripts/tumpio/DuckDuckGo_Extended
// @supportURL      https://github.com/tumpio/gmscripts
// @source          https://userstyles.org/styles/99153
// @icon            https://raw.githubusercontent.com/tumpio/gmscripts/master/Static_Google/large.png
// @resource        css http://userstyles.org/styles/99153.css#md5=cc035d8beb1114c99826212c0dfaab86
// @include         http://www.google.*
// @include         https://www.google.*
// @match           https://encrypted.google.com/*
// @noframes
// @run-at          document-start
// @grant           GM_addStyle
// @grant           GM_getResourceText
// @version         1.9.3
// ==/UserScript==

// Static css, from userstyle.org, remove @-moz-document
var css = GM_getResourceText("css").replace(/@-moz-document.*{([^]+)}/, "$1");

// Fix for Scriptish issue #90
// https://github.com/scriptish/scriptish/issues/90
if (document.head) // Greasemonkey
    GM_addStyle(css);
else { // Scriptish
    document.onreadystatechange = function () {
        GM_addStyle(css);
    };
}
<commit_msg>Fix homepage<commit_after>// ==UserScript==
// @name            Static Google
// @description     Google search interface always visible on screen, and some additional changes for more compact layout.
// @author          tumpio
// @oujs:author     tumpio
// @namespace       tumpio@sci.fi
// @homepageURL     https://openuserjs.org/scripts/tumpio/Static_Google
// @supportURL      https://github.com/tumpio/gmscripts
// @source          https://userstyles.org/styles/99153
// @icon            https://raw.githubusercontent.com/tumpio/gmscripts/master/Static_Google/large.png
// @resource        css http://userstyles.org/styles/99153.css#md5=cc035d8beb1114c99826212c0dfaab86
// @include         http://www.google.*
// @include         https://www.google.*
// @match           https://encrypted.google.com/*
// @noframes
// @run-at          document-start
// @grant           GM_addStyle
// @grant           GM_getResourceText
// @version         1.9.4
// ==/UserScript==

// Static css, from userstyle.org, remove @-moz-document
var css = GM_getResourceText("css").replace(/@-moz-document.*{([^]+)}/, "$1");

// Fix for Scriptish issue #90
// https://github.com/scriptish/scriptish/issues/90
if (document.head) // Greasemonkey
    GM_addStyle(css);
else { // Scriptish
    document.onreadystatechange = function () {
        GM_addStyle(css);
    };
}
<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var Item = function(desc) {
  return this;
};

describe('shopping basket', function() {
  describe('item', function() {
    it('exists', function() {
      assert(new Item('description'));
    });

    it('has a description', function() {
      var item = new Item('banana');
      assert.equal('banana', item.description);
    });
  });
});
<commit_msg>now the test passes<commit_after>"use strict";

var assert = require('assert');

var Item = function(desc) {
  this.description = desc;
  return this;
};

describe('shopping basket', function() {
  describe('item', function() {
    it('exists', function() {
      assert(new Item('description'));
    });

    it('has a description', function() {
      var item = new Item('banana');
      assert.equal('banana', item.description);
    });
  });
});
<|endoftext|>