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

 /* global angular, useOfflineBuffer */
 'use strict';

 function UserSessionService(base64, LocalStorageService, PersistentStorageService, SessionStorageService) {
  var swapTokenBufferTime = 10*60*1000; // 10 minutes in milliseconds
  // When offline isn't enabled, use transient value for latest modified
  var latestModified = {};
  var itemsSynchronized = {};
  var offlineEnabled = false;
  var notifyOwnerCallbacks = {};

  // Sync session storage with local storage.
  function syncWebStorages() {
    if (LocalStorageService.getExpires() && SessionStorageService.getExpires() !== LocalStorageService.getExpires()) {
      setUserSessionStorageData();
    }
  }

  function setUserSessionStorageData() {
    SessionStorageService.setBackendDelta(LocalStorageService.getBackendDelta());
    SessionStorageService.setCollectives(LocalStorageService.getCollectives());
    SessionStorageService.setEmail(LocalStorageService.getEmail());
    SessionStorageService.setExpires(LocalStorageService.getExpires());
    SessionStorageService.setCredentials(LocalStorageService.getCredentials());
    SessionStorageService.setUserType(LocalStorageService.getUserType());
    SessionStorageService.setUserUUID(LocalStorageService.getUserUUID());
    SessionStorageService.setCohort(LocalStorageService.getCohort());
    SessionStorageService.setPreferences(LocalStorageService.getPreferences());
    SessionStorageService.setUserModified(LocalStorageService.getUserModified());
    SessionStorageService.setUserState(LocalStorageService.getUserState());
    SessionStorageService.setLatestModified(LocalStorageService.getLatestModified());
    SessionStorageService.setOffline(LocalStorageService.getOffline());
  }

  function encodeUsernamePassword(username, password) {
    return base64.encode(username + ':' + password);
  }

  function setEmail(email) {
    if (email) {
      SessionStorageService.setEmail(email);
      if (offlineEnabled || LocalStorageService.getReplaceable() !== null) {
        LocalStorageService.setEmail(email);
      }
    }
  }

  function migrateTransportPreferences(transportPreferences) {
    if (transportPreferences) {
      var preferences = {
        onboarded: transportPreferences.onboarded
      };
      if (transportPreferences.ui) {
        preferences.ui = JSON.parse(transportPreferences.ui);
      }
      return preferences;
    } else {
      return {};
    }
  }

  function executeNotifyOwnerCallbacks(userUUID, collectives) {
    for (var id in notifyOwnerCallbacks) {
      notifyOwnerCallbacks[id](userUUID);
      if (collectives){
        for (var uuid in collectives){
          notifyOwnerCallbacks[id](uuid, true);
        }
      }
    }
  }

  return {
    enableOffline: function(bypass) {
      offlineEnabled = true;
      if (bypass){
        // when bypassing store the value to stores
        LocalStorageService.setOffline(true);
        SessionStorageService.setOffline(true);
      }
    },
    isAuthenticated: function() {
      return SessionStorageService.getExpires() || LocalStorageService.getExpires();
    },
    isAuthenticateValid: function() {
      var authenticateCurrentReferenceTime, authenticateValidTime;

      authenticateValidTime = parseInt(SessionStorageService.getExpires() || LocalStorageService.getExpires());
      authenticateCurrentReferenceTime = Date.now() + swapTokenBufferTime;

      if (authenticateValidTime && (authenticateValidTime > authenticateCurrentReferenceTime)) {
        return true;
      }
    },
    isAuthenticateReplaceable: function() {
      var authenticateCurrentReferenceTime, authenticateValidTime;

      if (LocalStorageService.getReplaceable()) {
        authenticateValidTime = LocalStorageService.getReplaceable();
        authenticateCurrentReferenceTime = Date.now() + swapTokenBufferTime;
        if (authenticateValidTime > authenticateCurrentReferenceTime) {
          return true;
        }
      }
    },
    isOfflineEnabled: function() {
      syncWebStorages();
      var storedOffline = SessionStorageService.getOffline();
      if (storedOffline !== undefined){
        offlineEnabled = storedOffline;
      }
      return offlineEnabled;
    },
    clearUser: function() {
      if (offlineEnabled){
        PersistentStorageService.destroyAll();
      }
      if (SessionStorageService.getOffline() === true){
        offlineEnabled = false;
      }
      SessionStorageService.clearUser();
      LocalStorageService.clearUser();
      itemsSynchronized = {};
    },

    // Web storage setters
    setAuthenticateInformation: function(authenticateResponse, email) {
      var backendDelta = Date.now() - authenticateResponse.authenticated;
      var credentials = encodeUsernamePassword('token', authenticateResponse.token);
      var preferences = migrateTransportPreferences(authenticateResponse.preferences);

      SessionStorageService.setBackendDelta(backendDelta);
      SessionStorageService.setCollectives(authenticateResponse.collectives);
      SessionStorageService.setExpires(authenticateResponse.expires + backendDelta);
      SessionStorageService.setCredentials(credentials);
      SessionStorageService.setUserType(authenticateResponse.userType);
      SessionStorageService.setUserUUID(authenticateResponse.userUUID);
      SessionStorageService.setCohort(authenticateResponse.cohort);
      SessionStorageService.setPreferences(preferences);
      SessionStorageService.setUserModified(authenticateResponse.modified);

      if (authenticateResponse.replaceable) {
        LocalStorageService.setBackendDelta(backendDelta);
        LocalStorageService.setExpires(authenticateResponse.expires + backendDelta);
        LocalStorageService.setCollectives(authenticateResponse.collectives);
        LocalStorageService.setCredentials(credentials);
        LocalStorageService.setReplaceable(authenticateResponse.replaceable + backendDelta);
        LocalStorageService.setUserType(authenticateResponse.userType);
        LocalStorageService.setUserUUID(authenticateResponse.userUUID);
        LocalStorageService.setCohort(authenticateResponse.cohort);
        LocalStorageService.setPreferences(preferences);
        LocalStorageService.setUserModified(authenticateResponse.modified);
      }
      if (email) {
        setEmail(email);
      }

      // Notify owner UUID's
      executeNotifyOwnerCallbacks(authenticateResponse.userUUID, authenticateResponse.collectives);
      return credentials;
    },
    setEmail: function(email) {
      setEmail(email);
    },
    setPreference: function(name, value) {
      var preferences = this.getPreferences() || {};
      if (value !== undefined) {
        preferences[name] = value;
      } else if (preferences[name] !== undefined) {
        delete preferences[name];
      }
      this.setPreferences(preferences);
    },
    setUIPreference: function(name, value) {
      var preferences = this.getPreferences() || {};
      if (!preferences.ui) preferences.ui = {};

      if (value !== undefined){
        preferences.ui[name] = value;
      }else if (preferences.ui[name] !== undefined) {
        delete preferences.ui[name];
      }
      this.setPreferences(preferences);
    },
    setPreferences: function(preferences) {
      SessionStorageService.setPreferences(preferences);
      if (offlineEnabled || LocalStorageService.getReplaceable() !== null) {
        LocalStorageService.setPreferences(preferences);
      }
    },
    setTransportPreferences: function(transportPreferences) {
      this.setPreferences(migrateTransportPreferences(transportPreferences));
    },
    setLatestModified: function(modified, ownerUUID) {
      // Only set if given value is larger than set value
      var currentLatestModified = this.getLatestModified(ownerUUID);
      if (!currentLatestModified || (modified && currentLatestModified < modified)) {
        if (offlineEnabled){
          SessionStorageService.setLatestModified(modified, ownerUUID);
          if (offlineEnabled) {
            LocalStorageService.setLatestModified(modified, ownerUUID);
          }
        }else{
          latestModified[ownerUUID] = modified;
        }
      }
    },
    setUserModified: function(modified) {
      SessionStorageService.setUserModified(modified);
      if (offlineEnabled || LocalStorageService.getReplaceable() !== null) {
        LocalStorageService.setUserModified(modified);
      }
    },
    setItemsSynchronized: function(timestamp, ownerUUID) {
      itemsSynchronized[ownerUUID] = timestamp;
    },
    // Web storage getters
    getCollectives: function() {
      syncWebStorages();
      return SessionStorageService.getCollectives();
    },
    getCredentials: function() {
      syncWebStorages();
      return SessionStorageService.getCredentials();
    },
    getBackendDelta: function(){
      syncWebStorages();
      var storedDelta = SessionStorageService.getBackendDelta();
      return storedDelta ? parseInt(storedDelta) : undefined;
    },
    getEmail: function() {
      // Sync only email in Web Storages.
      if (LocalStorageService.getEmail()) {
        SessionStorageService.setEmail(LocalStorageService.getEmail());
      }
      return SessionStorageService.getEmail();
    },
    getUserUUID: function() {
      syncWebStorages();
      return SessionStorageService.getUserUUID();
    },
    getCohort: function() {
      syncWebStorages();
      return SessionStorageService.getCohort();
    },
    getLatestModified: function(ownerUUID) {
      if (offlineEnabled){
        var currentLatestModified = SessionStorageService.getLatestModified(ownerUUID);
        if (currentLatestModified) return parseInt(currentLatestModified);
      }else{
        return latestModified[ownerUUID];
      }
    },
    getItemsSynchronized: function(ownerUUID) {
      return itemsSynchronized[ownerUUID];
    },
    isItemsSynchronized: function(ownerUUID) {
      return itemsSynchronized[ownerUUID] !== undefined;
    },
    getTransportPreferences: function() {
      syncWebStorages();
      var preferences = SessionStorageService.getPreferences();

      var transportPreferences = {};
      for (var property in preferences){
        if (preferences.hasOwnProperty(property)){
          transportPreferences[property] = preferences[property];
        }
      }
      if (transportPreferences.ui) {
        transportPreferences.ui = JSON.stringify(preferences.ui);
      }
      return transportPreferences;
    },
    getPreferences: function() {
      syncWebStorages();
      return SessionStorageService.getPreferences();
    },
    getUIPreference: function(key) {
      syncWebStorages();
      var preferences = SessionStorageService.getPreferences();
      if (preferences && preferences.ui) {
        return preferences.ui[key];
      }
    },
    getRememberByDefault: function() {
      return offlineEnabled;
    },
    getUser: function() {
      syncWebStorages();
      if (SessionStorageService.getUserUUID()) {
        var user = {
          uuid: SessionStorageService.getUserUUID(),
          type: parseInt(SessionStorageService.getUserType()),
          modified: SessionStorageService.getUserModified()
        };
        if (SessionStorageService.getCohort()) {
          user.cohort = parseInt(SessionStorageService.getCohort());
        }
        return user;
      }
    },
    getUserType: function() {
      return parseInt(SessionStorageService.getUserType());
    },
    registerNofifyOwnerCallback: function(callback, id){
      notifyOwnerCallbacks[id] = callback;

      // In case the registration comes after UserSessionService has received owners,
      // notify caller immediately
      var userUUID = this.getUserUUID();
      if (userUUID){
        callback(userUUID);
      }
      var collectives = this.getCollectives();
      if (collectives){
        for (var uuid in collectives){
          callback(uuid, true);
        }
      }
    },
    // NOTE: Here for easier testing!
    executeNotifyOwnerCallbacks: function(userUUID, collectives){
      executeNotifyOwnerCallbacks(userUUID, collectives);
    }
  };
}
UserSessionService['$inject'] = ['base64', 'LocalStorageService', 'PersistentStorageService',
'SessionStorageService'];
angular.module('em.base').factory('UserSessionService', UserSessionService);
<commit_msg>Fixed failing sessionstorage/localstorage sync with wrong function names<commit_after>/* Copyright 2013-2014 Extended Mind Technologies Oy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /* global angular, useOfflineBuffer */
 'use strict';

 function UserSessionService(base64, LocalStorageService, PersistentStorageService, SessionStorageService) {
  var swapTokenBufferTime = 10*60*1000; // 10 minutes in milliseconds
  // When offline isn't enabled, use transient value for latest modified
  var latestModified = {};
  var itemsSynchronized = {};
  var offlineEnabled = false;
  var notifyOwnerCallbacks = {};

  // Sync session storage with local storage.
  function syncWebStorages() {
    if (LocalStorageService.getExpires() && SessionStorageService.getExpires() !== LocalStorageService.getExpires()) {
      setUserSessionStorageData();
    }
  }

  function setUserSessionStorageData() {
    SessionStorageService.setBackendDelta(LocalStorageService.getBackendDelta());
    SessionStorageService.setCollectives(LocalStorageService.getCollectives());
    SessionStorageService.setEmail(LocalStorageService.getEmail());
    SessionStorageService.setExpires(LocalStorageService.getExpires());
    SessionStorageService.setCredentials(LocalStorageService.getCredentials());
    SessionStorageService.setUserType(LocalStorageService.getUserType());
    SessionStorageService.setUserUUID(LocalStorageService.getUserUUID());
    SessionStorageService.setCohort(LocalStorageService.getCohort());
    SessionStorageService.setPreferences(LocalStorageService.getPreferences());
    SessionStorageService.setUserModified(LocalStorageService.getUserModified());
    SessionStorageService.setState(LocalStorageService.getState());
    SessionStorageService.setLatestModified(LocalStorageService.getLatestModified());
    SessionStorageService.setOffline(LocalStorageService.getOffline());
  }

  function encodeUsernamePassword(username, password) {
    return base64.encode(username + ':' + password);
  }

  function setEmail(email) {
    if (email) {
      SessionStorageService.setEmail(email);
      if (offlineEnabled || LocalStorageService.getReplaceable() !== null) {
        LocalStorageService.setEmail(email);
      }
    }
  }

  function migrateTransportPreferences(transportPreferences) {
    if (transportPreferences) {
      var preferences = {
        onboarded: transportPreferences.onboarded
      };
      if (transportPreferences.ui) {
        preferences.ui = JSON.parse(transportPreferences.ui);
      }
      return preferences;
    } else {
      return {};
    }
  }

  function executeNotifyOwnerCallbacks(userUUID, collectives) {
    for (var id in notifyOwnerCallbacks) {
      notifyOwnerCallbacks[id](userUUID);
      if (collectives){
        for (var uuid in collectives){
          notifyOwnerCallbacks[id](uuid, true);
        }
      }
    }
  }

  return {
    enableOffline: function(bypass) {
      offlineEnabled = true;
      if (bypass){
        // when bypassing store the value to stores
        LocalStorageService.setOffline(true);
        SessionStorageService.setOffline(true);
      }
    },
    isAuthenticated: function() {
      return SessionStorageService.getExpires() || LocalStorageService.getExpires();
    },
    isAuthenticateValid: function() {
      var authenticateCurrentReferenceTime, authenticateValidTime;

      authenticateValidTime = parseInt(SessionStorageService.getExpires() || LocalStorageService.getExpires());
      authenticateCurrentReferenceTime = Date.now() + swapTokenBufferTime;

      if (authenticateValidTime && (authenticateValidTime > authenticateCurrentReferenceTime)) {
        return true;
      }
    },
    isAuthenticateReplaceable: function() {
      var authenticateCurrentReferenceTime, authenticateValidTime;

      if (LocalStorageService.getReplaceable()) {
        authenticateValidTime = LocalStorageService.getReplaceable();
        authenticateCurrentReferenceTime = Date.now() + swapTokenBufferTime;
        if (authenticateValidTime > authenticateCurrentReferenceTime) {
          return true;
        }
      }
    },
    isOfflineEnabled: function() {
      syncWebStorages();
      var storedOffline = SessionStorageService.getOffline();
      if (storedOffline !== undefined){
        offlineEnabled = storedOffline;
      }
      return offlineEnabled;
    },
    clearUser: function() {
      if (offlineEnabled){
        PersistentStorageService.destroyAll();
      }
      if (SessionStorageService.getOffline() === true){
        offlineEnabled = false;
      }
      SessionStorageService.clearUser();
      LocalStorageService.clearUser();
      itemsSynchronized = {};
    },

    // Web storage setters
    setAuthenticateInformation: function(authenticateResponse, email) {
      var backendDelta = Date.now() - authenticateResponse.authenticated;
      var credentials = encodeUsernamePassword('token', authenticateResponse.token);
      var preferences = migrateTransportPreferences(authenticateResponse.preferences);

      SessionStorageService.setBackendDelta(backendDelta);
      SessionStorageService.setCollectives(authenticateResponse.collectives);
      SessionStorageService.setExpires(authenticateResponse.expires + backendDelta);
      SessionStorageService.setCredentials(credentials);
      SessionStorageService.setUserType(authenticateResponse.userType);
      SessionStorageService.setUserUUID(authenticateResponse.userUUID);
      SessionStorageService.setCohort(authenticateResponse.cohort);
      SessionStorageService.setPreferences(preferences);
      SessionStorageService.setUserModified(authenticateResponse.modified);

      if (authenticateResponse.replaceable) {
        LocalStorageService.setBackendDelta(backendDelta);
        LocalStorageService.setExpires(authenticateResponse.expires + backendDelta);
        LocalStorageService.setCollectives(authenticateResponse.collectives);
        LocalStorageService.setCredentials(credentials);
        LocalStorageService.setReplaceable(authenticateResponse.replaceable + backendDelta);
        LocalStorageService.setUserType(authenticateResponse.userType);
        LocalStorageService.setUserUUID(authenticateResponse.userUUID);
        LocalStorageService.setCohort(authenticateResponse.cohort);
        LocalStorageService.setPreferences(preferences);
        LocalStorageService.setUserModified(authenticateResponse.modified);
      }
      if (email) {
        setEmail(email);
      }

      // Notify owner UUID's
      executeNotifyOwnerCallbacks(authenticateResponse.userUUID, authenticateResponse.collectives);
      return credentials;
    },
    setEmail: function(email) {
      setEmail(email);
    },
    setPreference: function(name, value) {
      var preferences = this.getPreferences() || {};
      if (value !== undefined) {
        preferences[name] = value;
      } else if (preferences[name] !== undefined) {
        delete preferences[name];
      }
      this.setPreferences(preferences);
    },
    setUIPreference: function(name, value) {
      var preferences = this.getPreferences() || {};
      if (!preferences.ui) preferences.ui = {};

      if (value !== undefined){
        preferences.ui[name] = value;
      }else if (preferences.ui[name] !== undefined) {
        delete preferences.ui[name];
      }
      this.setPreferences(preferences);
    },
    setPreferences: function(preferences) {
      SessionStorageService.setPreferences(preferences);
      if (offlineEnabled || LocalStorageService.getReplaceable() !== null) {
        LocalStorageService.setPreferences(preferences);
      }
    },
    setTransportPreferences: function(transportPreferences) {
      this.setPreferences(migrateTransportPreferences(transportPreferences));
    },
    setLatestModified: function(modified, ownerUUID) {
      // Only set if given value is larger than set value
      var currentLatestModified = this.getLatestModified(ownerUUID);
      if (!currentLatestModified || (modified && currentLatestModified < modified)) {
        if (offlineEnabled){
          SessionStorageService.setLatestModified(modified, ownerUUID);
          if (offlineEnabled) {
            LocalStorageService.setLatestModified(modified, ownerUUID);
          }
        }else{
          latestModified[ownerUUID] = modified;
        }
      }
    },
    setUserModified: function(modified) {
      SessionStorageService.setUserModified(modified);
      if (offlineEnabled || LocalStorageService.getReplaceable() !== null) {
        LocalStorageService.setUserModified(modified);
      }
    },
    setItemsSynchronized: function(timestamp, ownerUUID) {
      itemsSynchronized[ownerUUID] = timestamp;
    },
    // Web storage getters
    getCollectives: function() {
      syncWebStorages();
      return SessionStorageService.getCollectives();
    },
    getCredentials: function() {
      syncWebStorages();
      return SessionStorageService.getCredentials();
    },
    getBackendDelta: function(){
      syncWebStorages();
      var storedDelta = SessionStorageService.getBackendDelta();
      return storedDelta ? parseInt(storedDelta) : undefined;
    },
    getEmail: function() {
      // Sync only email in Web Storages.
      if (LocalStorageService.getEmail()) {
        SessionStorageService.setEmail(LocalStorageService.getEmail());
      }
      return SessionStorageService.getEmail();
    },
    getUserUUID: function() {
      syncWebStorages();
      return SessionStorageService.getUserUUID();
    },
    getCohort: function() {
      syncWebStorages();
      return SessionStorageService.getCohort();
    },
    getLatestModified: function(ownerUUID) {
      if (offlineEnabled){
        var currentLatestModified = SessionStorageService.getLatestModified(ownerUUID);
        if (currentLatestModified) return parseInt(currentLatestModified);
      }else{
        return latestModified[ownerUUID];
      }
    },
    getItemsSynchronized: function(ownerUUID) {
      return itemsSynchronized[ownerUUID];
    },
    isItemsSynchronized: function(ownerUUID) {
      return itemsSynchronized[ownerUUID] !== undefined;
    },
    getTransportPreferences: function() {
      syncWebStorages();
      var preferences = SessionStorageService.getPreferences();

      var transportPreferences = {};
      for (var property in preferences){
        if (preferences.hasOwnProperty(property)){
          transportPreferences[property] = preferences[property];
        }
      }
      if (transportPreferences.ui) {
        transportPreferences.ui = JSON.stringify(preferences.ui);
      }
      return transportPreferences;
    },
    getPreferences: function() {
      syncWebStorages();
      return SessionStorageService.getPreferences();
    },
    getUIPreference: function(key) {
      syncWebStorages();
      var preferences = SessionStorageService.getPreferences();
      if (preferences && preferences.ui) {
        return preferences.ui[key];
      }
    },
    getRememberByDefault: function() {
      return offlineEnabled;
    },
    getUser: function() {
      syncWebStorages();
      if (SessionStorageService.getUserUUID()) {
        var user = {
          uuid: SessionStorageService.getUserUUID(),
          type: parseInt(SessionStorageService.getUserType()),
          modified: SessionStorageService.getUserModified()
        };
        if (SessionStorageService.getCohort()) {
          user.cohort = parseInt(SessionStorageService.getCohort());
        }
        return user;
      }
    },
    getUserType: function() {
      return parseInt(SessionStorageService.getUserType());
    },
    registerNofifyOwnerCallback: function(callback, id){
      notifyOwnerCallbacks[id] = callback;

      // In case the registration comes after UserSessionService has received owners,
      // notify caller immediately
      var userUUID = this.getUserUUID();
      if (userUUID){
        callback(userUUID);
      }
      var collectives = this.getCollectives();
      if (collectives){
        for (var uuid in collectives){
          callback(uuid, true);
        }
      }
    },
    // NOTE: Here for easier testing!
    executeNotifyOwnerCallbacks: function(userUUID, collectives){
      executeNotifyOwnerCallbacks(userUUID, collectives);
    }
  };
}
UserSessionService['$inject'] = ['base64', 'LocalStorageService', 'PersistentStorageService',
'SessionStorageService'];
angular.module('em.base').factory('UserSessionService', UserSessionService);
<|endoftext|>


<commit_before>const parsers = require('../parsers')
const transform = require('../transform')
const request = require('../request')
const { ConnectionFailedError, EmptyParseOutputError } = require('../errors')

async function parse(parser, text) {
  const parsed = await parsers[parser](text)
  if (!parsed) throw new EmptyParseOutputError()
  return transform(parsed)
}

module.exports = async function parseFromQuery({ url, parser }) {
  let content
  try {
    content = (await request(url)).text
  } catch (error) {
    if (error.code === 'ENOTFOUND') {
      throw new ConnectionFailedError(url)
    }
    throw error
  }

  if (parser) {
    return parse(parser, content)
  } else {
    for (let i = 0; i < parsers.keys.length; i++) {
      try {
        return parse(parsers.keys[i], content)
      } catch (error) {
        if (i !== parsers.keys.length - 1) {
          throw error
        }
        continue
      }
    }
  }
}
<commit_msg>fix: Make error handling use full parser list<commit_after>const parsers = require('../parsers')
const transform = require('../transform')
const request = require('../request')
const { ConnectionFailedError, EmptyParseOutputError } = require('../errors')

async function parse(parser, text) {
  const parsed = await parsers[parser](text)
  if (!parsed) throw new EmptyParseOutputError()
  return transform(parsed)
}

module.exports = async function parseFromQuery({ url, parser }) {
  let content
  try {
    content = (await request(url)).text
  } catch (error) {
    if (error.code === 'ENOTFOUND') {
      throw new ConnectionFailedError(url)
    }
    throw error
  }

  if (parser) {
    return parse(parser, content)
  } else {
    for (let i = 0; i < parsers.keys.length; i++) {
      try {
        return await parse(parsers.keys[i], content)
      } catch (error) {
        if (i < parsers.keys.length - 1) {
          continue
        }
        throw error
      }
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

streamaApp.directive('adminEpisode', [
	'uploadService', 'modalService', 'apiService', function (uploadService, modalService, apiService) {
	return {
		restrict: 'AE',
		templateUrl: 'directive--admin-episode.htm',
		scope: {
			episode: '='
		},
		link: function ($scope, $elem, $attrs) {
			$scope.uploadStatus = {};

			$scope.editEpisode = function(episode){
				modalService.videoModal(episode, null, null, function (data) {
					if(data.deleted){
						episode.deleted = true;
					}
				});
			};

			$scope.openFileBrowser = function(){
				modalService.openFileBrowser(function (file) {
					apiService.video.addFile($scope.episode.id, file.id).success(function () {
						$scope.episode.files = $scope.episode.files || [];
						$scope.episode.files.push(file);
					});
				});
			};

			$scope.addFile = function(episode){
				modalService.fileModal(episode);
			};

			$scope.removeFile = function(file){
				alertify.confirm('Are you sure you want to remove the file "'+file.originalFilename+'"?', function (confirmed) {
					if(confirmed){
						apiService.video.removeFile($scope.episode.id, file.id).success(function () {
							file.deleted = true;
						});
					}
				});
			};

			$scope.upload = uploadService.doUpload.bind(uploadService, $scope.uploadStatus, 'video/uploadFile.json?id=' + $scope.episode.id, function (data) {
				$scope.uploadStatus.percentage = null;
				$scope.episode.files = $scope.episode.files || [];
				$scope.episode.files.push(data);
			});
		}
	}
}]);<commit_msg>remove file from $scope array when removing<commit_after>'use strict';

streamaApp.directive('adminEpisode', [
	'uploadService', 'modalService', 'apiService', function (uploadService, modalService, apiService) {
	return {
		restrict: 'AE',
		templateUrl: 'directive--admin-episode.htm',
		scope: {
			episode: '='
		},
		link: function ($scope, $elem, $attrs) {
			$scope.uploadStatus = {};

			$scope.editEpisode = function(episode){
				modalService.videoModal(episode, null, null, function (data) {
					if(data.deleted){
						episode.deleted = true;
					}
				});
			};

			$scope.openFileBrowser = function(){
				modalService.openFileBrowser(function (file) {
					apiService.video.addFile($scope.episode.id, file.id).success(function () {
						$scope.episode.files = $scope.episode.files || [];
						$scope.episode.files.push(file);
					});
				});
			};

			$scope.addFile = function(episode){
				modalService.fileModal(episode);
			};

			$scope.removeFile = function(file){
				alertify.confirm('Are you sure you want to remove the file "'+file.originalFilename+'"?', function (confirmed) {
					if(confirmed){
						apiService.video.removeFile($scope.episode.id, file.id).success(function () {
              _.remove($scope.episode.files, {id: file.id});
						});
					}
				});
			};

			$scope.upload = uploadService.doUpload.bind(uploadService, $scope.uploadStatus, 'video/uploadFile.json?id=' + $scope.episode.id, function (data) {
				$scope.uploadStatus.percentage = null;
				$scope.episode.files = $scope.episode.files || [];
				$scope.episode.files.push(data);
			});
		}
	}
}]);
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import {
    View,
    Text,
    StyleSheet,
    Dimensions
} from 'react-native';
const {width} = Dimensions.get('window');

export default class Header extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return(
            <View style={estilos.corpo}>
                <Text style={estilos.titulo}>{this.props.titulo}</Text>
            </View>
        )
    }
}

Header.PropTypes = {
    titulo: PropTypes.string
}

const estilos = StyleSheet.create({
    corpo : {
        position: 'absolute',
        top: 0,
        width,
        height: 60,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#414649'
    },
    titulo : {
        fontSize: 20,
        color: '#FFFFFF'
    }
})<commit_msg>Correção de bug<commit_after>import React, { Component, PropTypes } from 'react';
import {
    View,
    Text,
    StyleSheet,
    Dimensions
} from 'react-native';
const {width} = Dimensions.get('window');

export default class Header extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return(
            <View style={estilos.corpo}>
                <Text numberOfLines={1} style={estilos.titulo}>{this.props.titulo}</Text>
            </View>
        )
    }
}

Header.PropTypes = {
    titulo: PropTypes.string
}

const estilos = StyleSheet.create({
    corpo : {
        position: 'absolute',
        top: 0,
        width,
        height: 60,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#414649',
        elevation: 3,
        zIndex: 99
    },
    titulo : {
        maxWidth: 250,
        fontSize: 20,
        color: '#FFFFFF'
    }
})<|endoftext|>


<commit_before>/**
 * @module Helix
 * @mail Helix
 *
 * The main entry point for the Helix chartting
 *
 */

var Helix = (function(Helix) {

    Helix.HelixVisualizationController = function($scope, $http) {

        $http.get("http://localhost:8100/clusters")
            .success(function(data) {
                $scope.clusters = data;

            })

        //getInformation of resources /clusters/{clusterName}/resourceGroups/{resourceName}
        $scope.getInformation = function(cluster,resourceName) {
            $http.get("http://localhost:8100/clusters/" + cluster.clusterName + "/resourceGroups/"+resourceName)
                .success(function(data) {
                    $scope.resource = data;
                })
        }

        //list resources
        $scope.listResources = function(clusterName) {
            $http.get("http://localhost:8100/clusters/" + clusterName + "/resourceGroups")
                .success(function(data) {
                    $scope.resources = data;
                })
        }

        //list all instances
        $scope.listInstances = function(clusterName) {
            console.log(cluster.clusterName)
            $http.get("http://localhost:8100/clusters/" + clusterName + "/instances")
                .success(function(data) {
                    $scope.instances = data;
                })
        }

    };

    return Helix;

})(Helix || {});<commit_msg>fix comments<commit_after>/**
 * @module Helix
 * @mail Helix
 *
 * The main entry point for the Helix chartting
 *
 */

var Helix = (function(Helix) {

    Helix.HelixVisualizationController = function($scope, $http) {

        $http.get("http://localhost:8100/clusters")
            .success(function(data) {
                $scope.clusters = data;

            })

        //getInformation of resources /clusters/{clusterName}/resourceGroups/{resourceName}
        $scope.getInformation = function(cluster,resourceName) {
            $http.get("http://localhost:8100/clusters/" + cluster.clusterName + "/resourceGroups/"+resourceName)
                .success(function(data) {
                    $scope.resource = data;
                })
        }

        //list resources
        $scope.listResources = function(clusterName) {
            $http.get("http://localhost:8100/clusters/" + clusterName + "/resourceGroups")
                .success(function(data) {
                    $scope.resources = data;
                })
        }

        //list all instances
        $scope.listInstances = function(clusterName) {

            $http.get("http://localhost:8100/clusters/" + clusterName + "/instances")
                .success(function(data) {
                    $scope.instances = data;
                })
        }

    };

    return Helix;

})(Helix || {});<|endoftext|>


<commit_before>'use strict';

/**
 * Pterodactyl - Daemon
 * Copyright (c) 2015 - 2016 Dane Everitt <dane@daneeveritt.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
const rfr = require('rfr');
const Dockerode = require('dockerode');
const Util = require('util');

const Log = rfr('src/helpers/logger.js');
const LoadConfig = rfr('src/helpers/config.js');

const Config = new LoadConfig();
const DockerController = new Dockerode({
    socketPath: Config.get('docker.socket', '/var/run/docker.sock'),
});

class DockerImage {
    constructor() {
        //
    }

    /**
     * Determines if an image exists.
     * @return boolean
     */
    static exists(img, next) {
        const Image = DockerController.getImage(img);
        Image.inspect(function (err) {
            return next(err);
        });
    }

    /**
     * Pulls an image to the server.
     * @param  string       image
     * @param  {Function}   next
     * @return {Function}
     */
    static pull(image, next) {
        DockerController.pull(image, function (err, stream) {
            function onFinished(streamErr) { return next(streamErr); }
            DockerController.modem.followProgress(stream, onFinished);
        });
    }
}

module.exports = DockerImage;
<commit_msg>change image pulling class due to modem bugs in other files<commit_after>'use strict';

/**
 * Pterodactyl - Daemon
 * Copyright (c) 2015 - 2016 Dane Everitt <dane@daneeveritt.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
const rfr = require('rfr');
const Dockerode = require('dockerode');
const Util = require('util');

const Log = rfr('src/helpers/logger.js');
const LoadConfig = rfr('src/helpers/config.js');

const Config = new LoadConfig();
const DockerController = new Dockerode({
    socketPath: Config.get('docker.socket', '/var/run/docker.sock'),
});

class DockerImage {
    constructor() {
        //
    }

    /**
     * Determines if an image exists.
     * @return boolean
     */
    static exists(img, next) {
        const Image = DockerController.getImage(img);
        Image.inspect(function (err) {
            return next(err);
        });
    }

    /**
     * Pulls an image to the server.
     * @param  string       image
     * @param  {Function}   next
     * @return {Function}
     */
    static pull(image, next) {
        DockerController.pull(image, function (err, stream) {
            if (err) return next(err);
            stream.setEncoding('utf8');
            stream.on('end', function dockerImagePullStreamEnd() {
                return next();
            });
            stream.on('error', function dockerImagePullStreamError(streamErr) {
                return next(streamErr);
            });
        });
    }
}

module.exports = DockerImage;
<|endoftext|>


<commit_before>import {Origin} from 'aurelia-metadata';
import {ObserverLocator, BindingExpression, Binding} from 'aurelia-binding';
import {TaskQueue} from 'aurelia-task-queue';
import {Container} from 'aurelia-dependency-injection';
import {ViewStrategy} from './view-strategy';
import {ViewEngine} from './view-engine';
import {ViewCompiler} from './view-compiler';
import {ContentSelector} from './content-selector';
import {hyphenate} from './util';
import {BindableProperty} from './bindable-property';
import {Controller} from './controller';
import {ViewResources} from './view-resources';
import {ResourceLoadContext, ViewCompileInstruction, BehaviorInstruction} from './instructions';
import {FEATURE, DOM} from 'aurelia-pal';

const contentSelectorViewCreateInstruction = { suppressBind: true, enhance: false };
let lastProviderId = 0;

function nextProviderId() {
  return ++lastProviderId;
}

function doProcessContent() {
  return true;
}

export class HtmlBehaviorResource {
  constructor() {
    this.elementName = null;
    this.attributeName = null;
    this.attributeDefaultBindingMode = undefined;
    this.liftsContent = false;
    this.targetShadowDOM = false;
    this.processContent = doProcessContent;
    this.usesShadowDOM = false;
    this.childBindings = null;
    this.hasDynamicOptions = false;
    this.containerless = false;
    this.properties = [];
    this.attributes = {};
  }

  static convention(name: string, existing?: HtmlBehaviorResource): HtmlBehaviorResource {
    let behavior;

    if (name.endsWith('CustomAttribute')) {
      behavior = existing || new HtmlBehaviorResource();
      behavior.attributeName = hyphenate(name.substring(0, name.length - 15));
    }

    if (name.endsWith('CustomElement')) {
      behavior = existing || new HtmlBehaviorResource();
      behavior.elementName = hyphenate(name.substring(0, name.length - 13));
    }

    return behavior;
  }

  addChildBinding(behavior: BindingExpression): void {
    if (this.childBindings === null) {
      this.childBindings = [];
    }

    this.childBindings.push(behavior);
  }

  initialize(container: Container, target: Function): void {
    let proto = target.prototype;
    let properties = this.properties;
    let attributeName = this.attributeName;
    let attributeDefaultBindingMode = this.attributeDefaultBindingMode;
    let i;
    let ii;
    let current;

    target.__providerId__ = nextProviderId();

    this.observerLocator = container.get(ObserverLocator);
    this.taskQueue = container.get(TaskQueue);

    this.target = target;
    this.usesShadowDOM = this.targetShadowDOM && FEATURE.shadowDOM;
    this.handlesCreated = ('created' in proto);
    this.handlesBind = ('bind' in proto);
    this.handlesUnbind = ('unbind' in proto);
    this.handlesAttached = ('attached' in proto);
    this.handlesDetached = ('detached' in proto);
    this.htmlName = this.elementName || this.attributeName;

    if (attributeName !== null) {
      if (properties.length === 0) { //default for custom attributes
        new BindableProperty({
          name: 'value',
          changeHandler: 'valueChanged' in proto ? 'valueChanged' : null,
          attribute: attributeName,
          defaultBindingMode: attributeDefaultBindingMode
        }).registerWith(target, this);
      }

      current = properties[0];

      if (properties.length === 1 && current.name === 'value') { //default for custom attributes
        current.isDynamic = current.hasOptions = this.hasDynamicOptions;
        current.defineOn(target, this);
      } else { //custom attribute with options
        for (i = 0, ii = properties.length; i < ii; ++i) {
          properties[i].defineOn(target, this);
        }

        current = new BindableProperty({
          name: 'value',
          changeHandler: 'valueChanged' in proto ? 'valueChanged' : null,
          attribute: attributeName,
          defaultBindingMode: attributeDefaultBindingMode
        });

        current.hasOptions = true;
        current.registerWith(target, this);
      }
    } else {
      for (i = 0, ii = properties.length; i < ii; ++i) {
        properties[i].defineOn(target, this);
      }
    }
  }

  register(registry: ViewResources, name?: string): void {
    if (this.attributeName !== null) {
      registry.registerAttribute(name || this.attributeName, this, this.attributeName);
    }

    if (this.elementName !== null) {
      registry.registerElement(name || this.elementName, this);
    }
  }

  load(container: Container, target: Function, viewStrategy?: ViewStrategy, transientView?: boolean, loadContext?: ResourceLoadContext): Promise<HtmlBehaviorResource> {
    let options;

    if (this.elementName !== null) {
      viewStrategy = viewStrategy || this.viewStrategy || ViewStrategy.getDefault(target);
      options = new ViewCompileInstruction(this.targetShadowDOM, true);

      if (!viewStrategy.moduleId) {
        viewStrategy.moduleId = Origin.get(target).moduleId;
      }

      return viewStrategy.loadViewFactory(container.get(ViewEngine), options, loadContext).then(viewFactory => {
        if (!transientView || !this.viewFactory) {
          this.viewFactory = viewFactory;
        }

        return viewFactory;
      });
    }

    return Promise.resolve(this);
  }

  compile(compiler: ViewCompiler, resources: ViewResources, node: Node, instruction: BehaviorInstruction, parentNode?: Node): Node {
    if (this.liftsContent) {
      if (!instruction.viewFactory) {
        let template = DOM.createElement('template');
        let fragment = DOM.createDocumentFragment();
        let cacheSize = node.getAttribute('view-cache');
        let part = node.getAttribute('part');

        node.removeAttribute(instruction.originalAttrName);
        DOM.replaceNode(template, node, parentNode);
        fragment.appendChild(node);
        instruction.viewFactory = compiler.compile(fragment, resources);

        if (part) {
          instruction.viewFactory.part = part;
          node.removeAttribute('part');
        }

        if (cacheSize) {
          instruction.viewFactory.setCacheSize(cacheSize);
          node.removeAttribute('view-cache');
        }

        node = template;
      }
    } else if (this.elementName !== null) { //custom element
      let partReplacements = instruction.partReplacements = {};

      if (this.processContent(compiler, resources, node, instruction) && node.hasChildNodes()) {
        if (this.usesShadowDOM) {
          let currentChild = node.firstChild;
          let nextSibling;
          let toReplace;

          while (currentChild) {
            nextSibling = currentChild.nextSibling;

            if (currentChild.tagName === 'TEMPLATE' && (toReplace = currentChild.getAttribute('replace-part'))) {
              partReplacements[toReplace] = compiler.compile(currentChild, resources);
              DOM.removeNode(currentChild, parentNode);
            }

            currentChild = nextSibling;
          }

          instruction.skipContentProcessing = false;
        } else {
          let fragment = DOM.createDocumentFragment();
          let currentChild = node.firstChild;
          let nextSibling;
          let toReplace;

          while (currentChild) {
            nextSibling = currentChild.nextSibling;

            if (currentChild.tagName === 'TEMPLATE' && (toReplace = currentChild.getAttribute('replace-part'))) {
              partReplacements[toReplace] = compiler.compile(currentChild, resources);
              DOM.removeNode(currentChild, parentNode);
            } else {
              fragment.appendChild(currentChild);
            }

            currentChild = nextSibling;
          }

          instruction.contentFactory = compiler.compile(fragment, resources);
          instruction.skipContentProcessing = true;
        }
      } else {
        instruction.skipContentProcessing = true;
      }
    }

    return node;
  }

  create(container: Container, instruction?: BehaviorInstruction, element?: Element, bindings?: Binding[]): Controller {
    let host;
    let au = null;

    instruction = instruction || BehaviorInstruction.normal;
    element = element || null;
    bindings = bindings || null;

    if (this.elementName !== null && element) {
      if (this.usesShadowDOM) {
        host = element.createShadowRoot();
        container.registerInstance(DOM.boundary, host);
      } else {
        host = element;

        if (this.targetShadowDOM) {
          container.registerInstance(DOM.boundary, host);
        }
      }
    }

    if (element !== null) {
      element.au = au = element.au || {};
    }

    let model = instruction.bindingContext || container.get(this.target);
    let controller = new Controller(this, model, instruction);
    let childBindings = this.childBindings;
    let viewFactory;

    if (this.liftsContent) {
      //template controller
      au.controller = controller;
    } else if (this.elementName !== null) {
      //custom element
      viewFactory = instruction.viewFactory || this.viewFactory;
      container.viewModel = model;

      if (viewFactory) {
        controller.view = viewFactory.create(container, instruction, element);
      }

      if (element !== null) {
        au.controller = controller;

        if (controller.view) {
          if (!this.usesShadowDOM) {
            if (instruction.contentFactory) {
              let contentView = instruction.contentFactory.create(container, contentSelectorViewCreateInstruction);

              ContentSelector.applySelectors(
                contentView,
                controller.view.contentSelectors,
                (contentSelector, group) => contentSelector.add(group)
              );

              controller.contentView = contentView;
            }
          }

          if (instruction.anchorIsContainer) {
            if (childBindings !== null) {
              for (let i = 0, ii = childBindings.length; i < ii; ++i) {
                controller.view.addBinding(childBindings[i].create(host, model));
              }
            }

            controller.view.appendNodesTo(host);
          } else {
            controller.view.insertNodesBefore(host);
          }
        } else if (childBindings !== null) {
          for (let i = 0, ii = childBindings.length; i < ii; ++i) {
            bindings.push(childBindings[i].create(element, model));
          }
        }
      } else if (controller.view) {
        //dynamic element with view
        controller.view.owner = controller;

        if (childBindings !== null) {
          for (let i = 0, ii = childBindings.length; i < ii; ++i) {
            controller.view.addBinding(childBindings[i].create(instruction.host, model));
          }
        }
      } else if (childBindings !== null) {
        //dynamic element without view
        for (let i = 0, ii = childBindings.length; i < ii; ++i) {
          bindings.push(childBindings[i].create(instruction.host, model));
        }
      }
    } else if (childBindings !== null) {
      //custom attribute
      for (let i = 0, ii = childBindings.length; i < ii; ++i) {
        bindings.push(childBindings[i].create(element, model));
      }
    }

    if (au !== null) {
      au[this.htmlName] = controller;
    }

    if (instruction.initiatedByBehavior && viewFactory) {
      controller.view.created();
    }

    return controller;
  }

  ensurePropertiesDefined(instance: Object, lookup: Object) {
    let properties;
    let i;
    let ii;
    let observer;

    if ('__propertiesDefined__' in lookup) {
      return;
    }

    lookup.__propertiesDefined__ = true;
    properties = this.properties;

    for (i = 0, ii = properties.length; i < ii; ++i) {
      observer = properties[i].createObserver(instance);

      if (observer !== undefined) {
        lookup[observer.propertyName] = observer;
      }
    }
  }
}
<commit_msg>fix(html-behavior): child bindings always operate on the light dom element<commit_after>import {Origin} from 'aurelia-metadata';
import {ObserverLocator, BindingExpression, Binding} from 'aurelia-binding';
import {TaskQueue} from 'aurelia-task-queue';
import {Container} from 'aurelia-dependency-injection';
import {ViewStrategy} from './view-strategy';
import {ViewEngine} from './view-engine';
import {ViewCompiler} from './view-compiler';
import {ContentSelector} from './content-selector';
import {hyphenate} from './util';
import {BindableProperty} from './bindable-property';
import {Controller} from './controller';
import {ViewResources} from './view-resources';
import {ResourceLoadContext, ViewCompileInstruction, BehaviorInstruction} from './instructions';
import {FEATURE, DOM} from 'aurelia-pal';

const contentSelectorViewCreateInstruction = { suppressBind: true, enhance: false };
let lastProviderId = 0;

function nextProviderId() {
  return ++lastProviderId;
}

function doProcessContent() {
  return true;
}

export class HtmlBehaviorResource {
  constructor() {
    this.elementName = null;
    this.attributeName = null;
    this.attributeDefaultBindingMode = undefined;
    this.liftsContent = false;
    this.targetShadowDOM = false;
    this.processContent = doProcessContent;
    this.usesShadowDOM = false;
    this.childBindings = null;
    this.hasDynamicOptions = false;
    this.containerless = false;
    this.properties = [];
    this.attributes = {};
  }

  static convention(name: string, existing?: HtmlBehaviorResource): HtmlBehaviorResource {
    let behavior;

    if (name.endsWith('CustomAttribute')) {
      behavior = existing || new HtmlBehaviorResource();
      behavior.attributeName = hyphenate(name.substring(0, name.length - 15));
    }

    if (name.endsWith('CustomElement')) {
      behavior = existing || new HtmlBehaviorResource();
      behavior.elementName = hyphenate(name.substring(0, name.length - 13));
    }

    return behavior;
  }

  addChildBinding(behavior: BindingExpression): void {
    if (this.childBindings === null) {
      this.childBindings = [];
    }

    this.childBindings.push(behavior);
  }

  initialize(container: Container, target: Function): void {
    let proto = target.prototype;
    let properties = this.properties;
    let attributeName = this.attributeName;
    let attributeDefaultBindingMode = this.attributeDefaultBindingMode;
    let i;
    let ii;
    let current;

    target.__providerId__ = nextProviderId();

    this.observerLocator = container.get(ObserverLocator);
    this.taskQueue = container.get(TaskQueue);

    this.target = target;
    this.usesShadowDOM = this.targetShadowDOM && FEATURE.shadowDOM;
    this.handlesCreated = ('created' in proto);
    this.handlesBind = ('bind' in proto);
    this.handlesUnbind = ('unbind' in proto);
    this.handlesAttached = ('attached' in proto);
    this.handlesDetached = ('detached' in proto);
    this.htmlName = this.elementName || this.attributeName;

    if (attributeName !== null) {
      if (properties.length === 0) { //default for custom attributes
        new BindableProperty({
          name: 'value',
          changeHandler: 'valueChanged' in proto ? 'valueChanged' : null,
          attribute: attributeName,
          defaultBindingMode: attributeDefaultBindingMode
        }).registerWith(target, this);
      }

      current = properties[0];

      if (properties.length === 1 && current.name === 'value') { //default for custom attributes
        current.isDynamic = current.hasOptions = this.hasDynamicOptions;
        current.defineOn(target, this);
      } else { //custom attribute with options
        for (i = 0, ii = properties.length; i < ii; ++i) {
          properties[i].defineOn(target, this);
        }

        current = new BindableProperty({
          name: 'value',
          changeHandler: 'valueChanged' in proto ? 'valueChanged' : null,
          attribute: attributeName,
          defaultBindingMode: attributeDefaultBindingMode
        });

        current.hasOptions = true;
        current.registerWith(target, this);
      }
    } else {
      for (i = 0, ii = properties.length; i < ii; ++i) {
        properties[i].defineOn(target, this);
      }
    }
  }

  register(registry: ViewResources, name?: string): void {
    if (this.attributeName !== null) {
      registry.registerAttribute(name || this.attributeName, this, this.attributeName);
    }

    if (this.elementName !== null) {
      registry.registerElement(name || this.elementName, this);
    }
  }

  load(container: Container, target: Function, viewStrategy?: ViewStrategy, transientView?: boolean, loadContext?: ResourceLoadContext): Promise<HtmlBehaviorResource> {
    let options;

    if (this.elementName !== null) {
      viewStrategy = viewStrategy || this.viewStrategy || ViewStrategy.getDefault(target);
      options = new ViewCompileInstruction(this.targetShadowDOM, true);

      if (!viewStrategy.moduleId) {
        viewStrategy.moduleId = Origin.get(target).moduleId;
      }

      return viewStrategy.loadViewFactory(container.get(ViewEngine), options, loadContext).then(viewFactory => {
        if (!transientView || !this.viewFactory) {
          this.viewFactory = viewFactory;
        }

        return viewFactory;
      });
    }

    return Promise.resolve(this);
  }

  compile(compiler: ViewCompiler, resources: ViewResources, node: Node, instruction: BehaviorInstruction, parentNode?: Node): Node {
    if (this.liftsContent) {
      if (!instruction.viewFactory) {
        let template = DOM.createElement('template');
        let fragment = DOM.createDocumentFragment();
        let cacheSize = node.getAttribute('view-cache');
        let part = node.getAttribute('part');

        node.removeAttribute(instruction.originalAttrName);
        DOM.replaceNode(template, node, parentNode);
        fragment.appendChild(node);
        instruction.viewFactory = compiler.compile(fragment, resources);

        if (part) {
          instruction.viewFactory.part = part;
          node.removeAttribute('part');
        }

        if (cacheSize) {
          instruction.viewFactory.setCacheSize(cacheSize);
          node.removeAttribute('view-cache');
        }

        node = template;
      }
    } else if (this.elementName !== null) { //custom element
      let partReplacements = instruction.partReplacements = {};

      if (this.processContent(compiler, resources, node, instruction) && node.hasChildNodes()) {
        if (this.usesShadowDOM) {
          let currentChild = node.firstChild;
          let nextSibling;
          let toReplace;

          while (currentChild) {
            nextSibling = currentChild.nextSibling;

            if (currentChild.tagName === 'TEMPLATE' && (toReplace = currentChild.getAttribute('replace-part'))) {
              partReplacements[toReplace] = compiler.compile(currentChild, resources);
              DOM.removeNode(currentChild, parentNode);
            }

            currentChild = nextSibling;
          }

          instruction.skipContentProcessing = false;
        } else {
          let fragment = DOM.createDocumentFragment();
          let currentChild = node.firstChild;
          let nextSibling;
          let toReplace;

          while (currentChild) {
            nextSibling = currentChild.nextSibling;

            if (currentChild.tagName === 'TEMPLATE' && (toReplace = currentChild.getAttribute('replace-part'))) {
              partReplacements[toReplace] = compiler.compile(currentChild, resources);
              DOM.removeNode(currentChild, parentNode);
            } else {
              fragment.appendChild(currentChild);
            }

            currentChild = nextSibling;
          }

          instruction.contentFactory = compiler.compile(fragment, resources);
          instruction.skipContentProcessing = true;
        }
      } else {
        instruction.skipContentProcessing = true;
      }
    }

    return node;
  }

  create(container: Container, instruction?: BehaviorInstruction, element?: Element, bindings?: Binding[]): Controller {
    let host;
    let au = null;

    instruction = instruction || BehaviorInstruction.normal;
    element = element || null;
    bindings = bindings || null;

    if (this.elementName !== null && element) {
      if (this.usesShadowDOM) {
        host = element.createShadowRoot();
        container.registerInstance(DOM.boundary, host);
      } else {
        host = element;

        if (this.targetShadowDOM) {
          container.registerInstance(DOM.boundary, host);
        }
      }
    }

    if (element !== null) {
      element.au = au = element.au || {};
    }

    let model = instruction.bindingContext || container.get(this.target);
    let controller = new Controller(this, model, instruction);
    let childBindings = this.childBindings;
    let viewFactory;

    if (this.liftsContent) {
      //template controller
      au.controller = controller;
    } else if (this.elementName !== null) {
      //custom element
      viewFactory = instruction.viewFactory || this.viewFactory;
      container.viewModel = model;

      if (viewFactory) {
        controller.view = viewFactory.create(container, instruction, element);
      }

      if (element !== null) {
        au.controller = controller;

        if (controller.view) {
          if (!this.usesShadowDOM) {
            if (instruction.contentFactory) {
              let contentView = instruction.contentFactory.create(container, contentSelectorViewCreateInstruction);

              ContentSelector.applySelectors(
                contentView,
                controller.view.contentSelectors,
                (contentSelector, group) => contentSelector.add(group)
              );

              controller.contentView = contentView;
            }
          }

          if (instruction.anchorIsContainer) {
            if (childBindings !== null) {
              for (let i = 0, ii = childBindings.length; i < ii; ++i) {
                controller.view.addBinding(childBindings[i].create(element, model));
              }
            }

            controller.view.appendNodesTo(host);
          } else {
            controller.view.insertNodesBefore(host);
          }
        } else if (childBindings !== null) {
          for (let i = 0, ii = childBindings.length; i < ii; ++i) {
            bindings.push(childBindings[i].create(element, model));
          }
        }
      } else if (controller.view) {
        //dynamic element with view
        controller.view.owner = controller;

        if (childBindings !== null) {
          for (let i = 0, ii = childBindings.length; i < ii; ++i) {
            controller.view.addBinding(childBindings[i].create(instruction.host, model));
          }
        }
      } else if (childBindings !== null) {
        //dynamic element without view
        for (let i = 0, ii = childBindings.length; i < ii; ++i) {
          bindings.push(childBindings[i].create(instruction.host, model));
        }
      }
    } else if (childBindings !== null) {
      //custom attribute
      for (let i = 0, ii = childBindings.length; i < ii; ++i) {
        bindings.push(childBindings[i].create(element, model));
      }
    }

    if (au !== null) {
      au[this.htmlName] = controller;
    }

    if (instruction.initiatedByBehavior && viewFactory) {
      controller.view.created();
    }

    return controller;
  }

  ensurePropertiesDefined(instance: Object, lookup: Object) {
    let properties;
    let i;
    let ii;
    let observer;

    if ('__propertiesDefined__' in lookup) {
      return;
    }

    lookup.__propertiesDefined__ = true;
    properties = this.properties;

    for (i = 0, ii = properties.length; i < ii; ++i) {
      observer = properties[i].createObserver(instance);

      if (observer !== undefined) {
        lookup[observer.propertyName] = observer;
      }
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

httpVueLoader.parseComponentURL = function(url) {

	var comp = url.match(/(.*?)([^/]+?)\/?(\.vue)?(?:\?|#|$)/);
	return {
		name: comp[2],
		url: comp[1] + comp[2] + (comp[3] === undefined ? '/index.vue' : comp[3])
	}
}

httpVueLoader.scopeStyles = function(styleElt, scopeName) {

	function process() {

		var sheet = styleElt.sheet;
		var rules = sheet.cssRules;

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

			var rule = rules[i];
			if ( rule.type !== 1 )
				continue;

			var scopedSelectors = [];

			rule.selectorText.split(/\s*,\s*/).forEach(function(sel) {

				scopedSelectors.push(scopeName+' '+sel);
				var segments = sel.match(/([^ :]+)(.+)?/);
				scopedSelectors.push(segments[1] + scopeName + (segments[2]||''));
			});

			var scopedRule = scopedSelectors.join(',') + rule.cssText.substr(rule.selectorText.length);
			sheet.deleteRule(i);
			sheet.insertRule(scopedRule, i);
		}
	}

	try {
		// firefox may fail sheet.cssRules with InvalidAccessError
		process();
	} catch (ex) {

		if ( ex instanceof DOMException && ex.code === DOMException.INVALID_ACCESS_ERR ) {

			styleElt.sheet.disabled = true;
			styleElt.addEventListener('load', function onStyleLoaded() {

				styleElt.removeEventListener('load', onStyleLoaded);

				// firefox need this timeout otherwise we have to use document.importNode(style, true)
				setTimeout(function() {

					process();
					styleElt.sheet.disabled = false;
				})
			});
			return;
		}

		throw ex;
	}
}

httpVueLoader.scopeIndex = 0;

httpVueLoader.load = function(url, name) {

	function getRelativeBase(url) {

		var pos = url.lastIndexOf('/');
		return url.substr(0, pos+1);
	}

	function normalizeContent(elt) {

		if ( elt === null || !elt.hasAttribute('src') )
			return Promise.resolve();

		return httpVueLoader.httpRequest(elt.getAttribute('src'))
		.then(function(content) {

			elt.removeAttribute('src');
			elt.innerHTML = content;
		});
	}

	return function(resolve, reject) {

		httpVueLoader.httpRequest(url)
		.then(function(responseText) {

			var templateElt = null;
			var scriptElt = null;
			var styleElts = [];
			var baseURI = getRelativeBase(url);
			var doc = document.implementation.createHTMLDocument('');

			// IE requires the <base> to come with <style>
			doc.body.innerHTML = (baseURI ? '<base href="'+baseURI+'">' : '') + responseText;

			for ( var it = doc.body.firstChild; it; it = it.nextSibling ) {

				switch ( it.nodeName ) {
					case 'TEMPLATE':
						templateElt = it;
						break;
					case 'SCRIPT':
						scriptElt = it;
						break;
					case 'STYLE':
						styleElts.push(it);
						break;
				}
			}

			return Promise.all(Array.prototype.concat(
				normalizeContent(templateElt),
				normalizeContent(scriptElt),
				styleElts.map(function(item) { return normalizeContent(item) })
			))
			.then(function() {

				var module = { exports:{} };

				if ( scriptElt !== null ) {

					var lang = scriptElt.hasAttribute('lang') ? scriptElt.getAttribute('lang').toLowerCase() : 'javascript';
					var script = httpVueLoader.langProcessor[lang](scriptElt.textContent);

					try {
						Function('exports', 'require', 'module', script).call(module.exports, module.exports, httpVueLoader.require, module);
					} catch(ex) {

						if ( !('lineNumber' in ex) ) {

							reject(ex);
							return
						}
						var vueFileData = responseText.replace(/\r?\n/g, '\n');
						var lineNumber = vueFileData.substr(0, vueFileData.indexOf(script)).split('\n').length + ex.lineNumber - 1;
						throw new (ex.constructor)(ex.message, url, lineNumber);
					}

				}

				return Promise.resolve(module.exports)
				.then(function(exports) {

					var headElt = document.head || document.getElementsByTagName('head')[0];

					if ( baseURI ) {

						// firefox and chrome need the <base> to be set while inserting the <style> in the document
						var tmpBaseElt = document.createElement('base');
						tmpBaseElt.href = baseURI;
						headElt.insertBefore(tmpBaseElt, headElt.firstChild);
					}

					var scopeId = '';
					function getScopeId(templateRootElement) {

						if ( scopeId === '' ) {

							scopeId = 'data-s-' + (httpVueLoader.scopeIndex++).toString(36);
							(templateElt.content || templateElt).firstElementChild.setAttribute(scopeId, '');
						}
						return scopeId;
					}

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

						var style = styleElts[i];
						var scoped = style.hasAttribute('scoped');

						if ( scoped ) {

							// no template, no scopable style
							if ( templateElt === null )
								continue;

							// firefox does not tolerate this attribute
							style.removeAttribute('scoped');
						}

						headElt.appendChild(style);

						if ( scoped )
							httpVueLoader.scopeStyles(style, '['+getScopeId()+']');
					}

					if ( baseURI )
						headElt.removeChild(tmpBaseElt);

					if ( templateElt !== null )
						exports.template = templateElt.innerHTML;

					if ( exports.name === undefined )
						if ( name !== undefined )
							exports.name = name;

					return exports;
				});
			});
		})
		.then(resolve, reject);
	}
}

function httpVueLoader(url, name) {

	var comp = httpVueLoader.parseComponentURL(url);
	return httpVueLoader.load(comp.url, name);
}

function httpVueLoaderRegister(Vue, url) {

	var comp = httpVueLoader.parseComponentURL(url);
	Vue.component(comp.name, httpVueLoader.load(comp.url));
}

httpVueLoader.install = function(Vue) {

	Vue.mixin({

		beforeCreate: function () {

			var components = this.$options.components;

			for ( var componentName in components ) {

				if ( typeof(components[componentName]) === 'string' && components[componentName].substr(0, 4) === 'url:' ) {

					var comp = httpVueLoader.parseComponentURL(components[componentName].substr(4));

					if ( isNaN(componentName) )
						components[componentName] = httpVueLoader.load(comp.url, componentName);
					else
						components[componentName] = Vue.component(comp.name, httpVueLoader.load(comp.url, comp.name));
				}
			}
		}
	});
}

httpVueLoader.langProcessor = {

	javascript: function(scriptText) {

		return scriptText;
	}
}

httpVueLoader.httpRequest = function(url) {

	return new Promise(function(resolve, reject) {

		var xhr = new XMLHttpRequest();
		xhr.open('GET', url, false);
		xhr.send(null);
		if ( xhr.status === 200 )
			resolve(xhr.responseText);
		else
			reject(xhr.status);
	});
}

httpVueLoader.require = function(moduleName) {

	return window[moduleName];
}
<commit_msg>:rocket: Update httpRequest to be async<commit_after>'use strict';

httpVueLoader.parseComponentURL = function(url) {

	var comp = url.match(/(.*?)([^/]+?)\/?(\.vue)?(?:\?|#|$)/);
	return {
		name: comp[2],
		url: comp[1] + comp[2] + (comp[3] === undefined ? '/index.vue' : comp[3])
	}
}

httpVueLoader.scopeStyles = function(styleElt, scopeName) {

	function process() {

		var sheet = styleElt.sheet;
		var rules = sheet.cssRules;

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

			var rule = rules[i];
			if ( rule.type !== 1 )
				continue;

			var scopedSelectors = [];

			rule.selectorText.split(/\s*,\s*/).forEach(function(sel) {

				scopedSelectors.push(scopeName+' '+sel);
				var segments = sel.match(/([^ :]+)(.+)?/);
				scopedSelectors.push(segments[1] + scopeName + (segments[2]||''));
			});

			var scopedRule = scopedSelectors.join(',') + rule.cssText.substr(rule.selectorText.length);
			sheet.deleteRule(i);
			sheet.insertRule(scopedRule, i);
		}
	}

	try {
		// firefox may fail sheet.cssRules with InvalidAccessError
		process();
	} catch (ex) {

		if ( ex instanceof DOMException && ex.code === DOMException.INVALID_ACCESS_ERR ) {

			styleElt.sheet.disabled = true;
			styleElt.addEventListener('load', function onStyleLoaded() {

				styleElt.removeEventListener('load', onStyleLoaded);

				// firefox need this timeout otherwise we have to use document.importNode(style, true)
				setTimeout(function() {

					process();
					styleElt.sheet.disabled = false;
				})
			});
			return;
		}

		throw ex;
	}
}

httpVueLoader.scopeIndex = 0;

httpVueLoader.load = function(url, name) {

	function getRelativeBase(url) {

		var pos = url.lastIndexOf('/');
		return url.substr(0, pos+1);
	}

	function normalizeContent(elt) {

		if ( elt === null || !elt.hasAttribute('src') )
			return Promise.resolve();

		return httpVueLoader.httpRequest(elt.getAttribute('src'))
		.then(function(content) {

			elt.removeAttribute('src');
			elt.innerHTML = content;
		});
	}

	return function(resolve, reject) {

		httpVueLoader.httpRequest(url)
		.then(function(responseText) {

			var templateElt = null;
			var scriptElt = null;
			var styleElts = [];
			var baseURI = getRelativeBase(url);
			var doc = document.implementation.createHTMLDocument('');

			// IE requires the <base> to come with <style>
			doc.body.innerHTML = (baseURI ? '<base href="'+baseURI+'">' : '') + responseText;

			for ( var it = doc.body.firstChild; it; it = it.nextSibling ) {

				switch ( it.nodeName ) {
					case 'TEMPLATE':
						templateElt = it;
						break;
					case 'SCRIPT':
						scriptElt = it;
						break;
					case 'STYLE':
						styleElts.push(it);
						break;
				}
			}

			return Promise.all(Array.prototype.concat(
				normalizeContent(templateElt),
				normalizeContent(scriptElt),
				styleElts.map(function(item) { return normalizeContent(item) })
			))
			.then(function() {

				var module = { exports:{} };

				if ( scriptElt !== null ) {

					var lang = scriptElt.hasAttribute('lang') ? scriptElt.getAttribute('lang').toLowerCase() : 'javascript';
					var script = httpVueLoader.langProcessor[lang](scriptElt.textContent);

					try {
						Function('exports', 'require', 'module', script).call(module.exports, module.exports, httpVueLoader.require, module);
					} catch(ex) {

						if ( !('lineNumber' in ex) ) {

							reject(ex);
							return
						}
						var vueFileData = responseText.replace(/\r?\n/g, '\n');
						var lineNumber = vueFileData.substr(0, vueFileData.indexOf(script)).split('\n').length + ex.lineNumber - 1;
						throw new (ex.constructor)(ex.message, url, lineNumber);
					}

				}

				return Promise.resolve(module.exports)
				.then(function(exports) {

					var headElt = document.head || document.getElementsByTagName('head')[0];

					if ( baseURI ) {

						// firefox and chrome need the <base> to be set while inserting the <style> in the document
						var tmpBaseElt = document.createElement('base');
						tmpBaseElt.href = baseURI;
						headElt.insertBefore(tmpBaseElt, headElt.firstChild);
					}

					var scopeId = '';
					function getScopeId(templateRootElement) {

						if ( scopeId === '' ) {

							scopeId = 'data-s-' + (httpVueLoader.scopeIndex++).toString(36);
							(templateElt.content || templateElt).firstElementChild.setAttribute(scopeId, '');
						}
						return scopeId;
					}

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

						var style = styleElts[i];
						var scoped = style.hasAttribute('scoped');

						if ( scoped ) {

							// no template, no scopable style
							if ( templateElt === null )
								continue;

							// firefox does not tolerate this attribute
							style.removeAttribute('scoped');
						}

						headElt.appendChild(style);

						if ( scoped )
							httpVueLoader.scopeStyles(style, '['+getScopeId()+']');
					}

					if ( baseURI )
						headElt.removeChild(tmpBaseElt);

					if ( templateElt !== null )
						exports.template = templateElt.innerHTML;

					if ( exports.name === undefined )
						if ( name !== undefined )
							exports.name = name;

					return exports;
				});
			});
		})
		.then(resolve, reject);
	}
}

function httpVueLoader(url, name) {

	var comp = httpVueLoader.parseComponentURL(url);
	return httpVueLoader.load(comp.url, name);
}

function httpVueLoaderRegister(Vue, url) {

	var comp = httpVueLoader.parseComponentURL(url);
	Vue.component(comp.name, httpVueLoader.load(comp.url));
}

httpVueLoader.install = function(Vue) {

	Vue.mixin({

		beforeCreate: function () {

			var components = this.$options.components;

			for ( var componentName in components ) {

				if ( typeof(components[componentName]) === 'string' && components[componentName].substr(0, 4) === 'url:' ) {

					var comp = httpVueLoader.parseComponentURL(components[componentName].substr(4));

					if ( isNaN(componentName) )
						components[componentName] = httpVueLoader.load(comp.url, componentName);
					else
						components[componentName] = Vue.component(comp.name, httpVueLoader.load(comp.url, comp.name));
				}
			}
		}
	});
}

httpVueLoader.langProcessor = {

	javascript: function(scriptText) {

		return scriptText;
	}
}

httpVueLoader.httpRequest = function(url) {

	return new Promise(function(resolve, reject) {
		var xhr = new XMLHttpRequest();
		xhr.open('GET', url);

		xhr.onreadystatechange = function() {
			if(xhr.readyState === 4) {
				if ( xhr.status === 200 )
				  resolve(xhr.responseText);
				else
				  reject(xhr.status);
			}
		}

		xhr.send(null);
	});
}

httpVueLoader.require = function(moduleName) {

	return window[moduleName];
}
<|endoftext|>


<commit_before>(function(root, definition) {
    if (typeof define === 'function' && define.amd) {
        define(['equation-tokenizer/equation-tokenizer'], definition);
    } else if (typeof exports === 'object') {
        var tokenize = require('../equation-tokenizer/equation-tokenizer');
        module.exports = definition(tokenize);
    } else {
        root.infix2postfix = definition(root.tokenize_equation);
    }
})(this, function(tokenize) {
    var precedences = { '^': 3, '*': 2, '/': 2, '%': 2, '+': 1, '-': 1 };

    function precedence(a, b) {
        if (precedences[a] > precedences[b]) {
            return -1;
        } else if (precedences[b] > precedences[a]) {
            return 1;
        }
        return 0;
    }

    function convert(equation, keep_tokens) {
        var tokens = equation instanceof Array ? equation : tokenize(equation, true);
        var stack = [];
        var postfix = [];

        tokens.forEach(function(token) {
            if (token.type === 'operand') {
                postfix.push(token);
            } else if (token.type === 'operator') {
                if (!stack.length) {
                    stack.push(token);
                } else {
                    var top = stack.pop();
                    var _token = token;
                    while (top && top.value !== '(') {
                        if (precedence(token.value, top.value) < 0) {
                            stack.push(top, token);
                            _token = null;
                            break;
                        }
                        postfix.push(top);
                        top = stack.pop();
                    }
                    if (_token) {
                        stack.push(_token);
                    }
                }
            } else if (token.type === 'group') {
                if (token.value === '(') {
                    stack.push(token);
                } else if (token.value === ')') {
                    var top = stack.pop();
                    while (top && top.value !== '(') {
                        postfix.push(top);
                        top = stack.pop();
                    }
                }
            }
        });

        while (stack.length) {
            postfix.push(stack.pop());
        }

        if (!keep_tokens) {
            var values = [];
            postfix.forEach(function(token) {
                values.push(token.value);
            });
            return values.join(' ');
        }
        return postfix;
    }

    return convert;
});<commit_msg>updated infix to postfix version in demo<commit_after>(function(root, definition) {
    if (typeof define === 'function' && define.amd) {
        define(['equation-tokenizer/equation-tokenizer'], definition);
    } else if (typeof exports === 'object') {
        var tokenize = require('../equation-tokenizer/equation-tokenizer');
        module.exports = definition(tokenize);
    } else {
        root.infix2postfix = definition(root.tokenize_equation);
    }
})(this, function(tokenize) {
    var precedences = { '^': 3, '*': 2, '/': 2, '%': 2, '+': 1, '-': 1 };

    function precedence(a, b) {
        if (precedences[a] > precedences[b]) {
            return -1;
        } else if (precedences[b] > precedences[a]) {
            return 1;
        }
        return 0;
    }

    function convert(equation, keep_tokens) {
        var tokens = equation instanceof Array ? equation : tokenize(equation, true);
        var stack = [];
        var postfix = [];

        tokens.forEach(function(token) {
            if (token.type === 'operand') {
                postfix.push(token);
            } else if (token.type === 'operator') {
                if (!stack.length) {
                    stack.push(token);
                } else {
                    var top = stack.pop();
                    var _token = token;
                    while (top && top.value !== '(') {
                        if (precedence(token.value, top.value) < 0) {
                            stack.push(top, token);
                            _token = null;
                            break;
                        }
                        postfix.push(top);
                        top = stack.pop();
                    }
                    if (top && top.value === '(') {
                        stack.push(top);
                    }
                    if (_token) {
                        stack.push(_token);
                    }
                }
            } else if (token.type === 'group') {
                if (token.value === '(') {
                    stack.push(token);
                } else if (token.value === ')') {
                    var top = stack.pop();
                    while (top && top.value !== '(') {
                        postfix.push(top);
                        top = stack.pop();
                    }
                }
            }
        });

        while (stack.length) {
            postfix.push(stack.pop());
        }

        if (!keep_tokens) {
            var values = [];
            postfix.forEach(function(token) {
                values.push(token.value);
            });
            return values.join(' ');
        }
        return postfix;
    }

    return convert;
});<|endoftext|>


<commit_before>var http = require('http');
var agent = new (http.Agent)({maxSockets: 8});
var tls = require('tls');
var CRLF = '\r\n';
var IncomingMessage = require('./http-incoming');

function getHeadersContent(req) {
	var headers = [req.method + ' ' + req.url + ' HTTP/' + req.httpVersion];
	if (req.headers && !req.headers.Host) {
		req.headers.Host = req.headers.host;
	}
	for (var key in req.headers) {
		var line = req.headers[key];
		if (Array.isArray(line)) {
			line.forEach(function(value) {
				headers.push(key + ': ' + value);
			});
		} else {
			headers.push(key + ': ' + line);
		}
	}
	headers.push(CRLF);

	return headers.join(CRLF);
}

module.exports = function proxy(req, callback) {
	var headers = req.headers;
	var options = req.options;
	var done;

	function execCallback(err, proxyRes) {
		if (!done) {
			callback && callback(err, proxyRes);
			done = true;
		}
	}

	options.method = 'CONNECT';
	options.path = headers.host;
	if (options.agent == null) {
		options.agent = agent;
	}
	options.headers = {
			host : headers.host,
			'proxy-connection': 'keep-alive',
			'user-agent': headers['user-agent']
		};

	http.request(options).on('error', execCallback)
	.on('connect', function (res, socket, head) {
		socket.on('error', execCallback);
	    var proxyReq = tls.connect({
	        rejectUnauthorized: false,
	        socket: socket
	    }, function () {
	        proxyReq.write(getHeadersContent(req));

	        var proxyRes = new IncomingMessage(proxyReq);
	        proxyRes.on('response', function(res) {
		    	execCallback(null, res);
		    });
	        proxyRes.on('error', execCallback);
	    });
	}).end();
};

<commit_msg>https-proxy<commit_after>var http = require('http');
var agent = new (http.Agent)({maxSockets: 8});
var tls = require('tls');
var CRLF = '\r\n';
var IncomingMessage = require('./http-incoming');

function getHeadersContent(req) {
	var headers = [req.method + ' ' + req.url + ' HTTP/' + req.httpVersion];
	if (req.headers && !req.headers.Host) {
		req.headers.Host = req.headers.host;
	}
	for (var key in req.headers) {
		var line = req.headers[key];
		if (Array.isArray(line)) {
			line.forEach(function(value) {
				headers.push(key + ': ' + value);
			});
		} else {
			headers.push(key + ': ' + line);
		}
	}
	headers.push(CRLF);

	return headers.join(CRLF);
}

module.exports = function proxy(req, callback) {
	var headers = req.headers;
	var options = req.options;
	var done, proxyReq;

	function execCallback(err, proxyRes) {
		if (!done) {
			callback && callback(err, proxyRes);
			done = true;
		}
	}

	options.method = 'CONNECT';
	options.path = headers.host;
	if (options.agent == null) {
		options.agent = agent;
	}
	options.headers = {
			host : headers.host,
			'proxy-connection': 'keep-alive',
			'user-agent': headers['user-agent']
		};

	var connect = http.request(options).on('error', execCallback)
	.on('connect', function (res, socket, head) {
		socket.on('error', execCallback);
	    proxyReq = tls.connect({
	        rejectUnauthorized: false,
	        socket: socket
	    }, function () {
	        proxyReq.write(getHeadersContent(req));

	        var proxyRes = new IncomingMessage(proxyReq);
	        proxyRes.on('response', function(res) {
		    	execCallback(null, res);
		    });
	        proxyRes.on('error', execCallback);
	    });
	}).end();

	req.on('error', function() {
		connect.abort();
		proxyReq && proxyReq.destroy();
	});
};

<|endoftext|>


<commit_before>import bluebird from 'bluebird'
let fs = require('fs')
fs = bluebird.promisifyAll(fs)
import nom from 'nomnom'
import path from 'path'
import Mocha, {Test} from 'mocha'
import {expect} from 'chai'

import flatten from 'lodash/flatten'
import junk from 'junk'

import evaluate from '../src/area-tools/evaluate'
import loadStudent from './lib/load-student'

async function testStudent(student, mochaInstance) {
	let {
		areas,
		courses,
		expectation=true,
		filename,
		overrides,
		pending=false,
	} = student

	if (pending) {
		return
	}

	let suiteInstance = Mocha.Suite.create(mochaInstance.suite, path.basename(filename))

	areas.forEach(data => {
		suiteInstance.addTest(new Test(`${expectation ? 'should' : 'should not'} pass ${data.name}`, () => {
			let result = evaluate({courses, overrides}, data)
			expect(result).to.have.property('computed', expectation)
		}))
	})
}

async function loadFile(filepath) {
	return fs.readFileAsync(filepath, 'utf-8')
}

async function loadDir(dirpath) {
	let promises = (await fs.readdirAsync(dirpath))
		.filter(filename => path.extname(filename) === '.json' ||
							path.extname(filename) === '.yaml')
		.filter(junk.not)
		.map(filename => path.resolve(dirpath + filename))
		.map(loadFile)
	return Promise.all(promises)
}

async function loadDirOrFile(path) {
	let stats = await fs.statAsync(path)
	if (stats.isDirectory()) {
		return loadDir(path)
	}
	return loadFile(path)
}

async function loadInput(paths) {
	let filePromises = paths.map(loadDirOrFile)
	let files = flatten(await Promise.all(filePromises))
	let loaded = await Promise.all(files.map(data => loadStudent(data, {isFile: false})))
	return loaded
}

export async function cli() {
	let args = nom()
		.option('input', {
			required: true,
			position: 0,
			list: true,
			default: ['./test/example-students/'],
			help: 'a student file or folder of student files, or stdin',
		})
		.parse()

	let students = await loadInput(args.input)

	let mochaInstance = new Mocha()
	students.forEach(student => testStudent(student, mochaInstance))
	mochaInstance.run()
}
<commit_msg>fix invocation of path.resolve<commit_after>import bluebird from 'bluebird'
let fs = require('fs')
fs = bluebird.promisifyAll(fs)
import nom from 'nomnom'
import path from 'path'
import Mocha, {Test} from 'mocha'
import {expect} from 'chai'

import flatten from 'lodash/flatten'
import junk from 'junk'

import evaluate from '../src/area-tools/evaluate'
import loadStudent from './lib/load-student'

async function testStudent(student, mochaInstance) {
	let {
		areas,
		courses,
		expectation=true,
		filename,
		overrides,
		pending=false,
	} = student

	if (pending) {
		return
	}

	let suiteInstance = Mocha.Suite.create(mochaInstance.suite, path.basename(filename))

	areas.forEach(data => {
		suiteInstance.addTest(new Test(`${expectation ? 'should' : 'should not'} pass ${data.name}`, () => {
			let result = evaluate({courses, overrides}, data)
			expect(result).to.have.property('computed', expectation)
		}))
	})
}

async function loadFile(filepath) {
	return fs.readFileAsync(filepath, 'utf-8')
}

async function loadDir(dirpath) {
	let promises = (await fs.readdirAsync(dirpath))
		.filter(filename => path.extname(filename) === '.json' ||
							path.extname(filename) === '.yaml')
		.filter(junk.not)
		.map(filename => path.resolve(dirpath, filename))
		.map(loadFile)
	return Promise.all(promises)
}

async function loadDirOrFile(path) {
	let stats = await fs.statAsync(path)
	if (stats.isDirectory()) {
		return loadDir(path)
	}
	return loadFile(path)
}

async function loadInput(paths) {
	let filePromises = paths.map(loadDirOrFile)
	let files = flatten(await Promise.all(filePromises))
	let loaded = await Promise.all(files.map(data => loadStudent(data, {isFile: false})))
	return loaded
}

export async function cli() {
	let args = nom()
		.option('input', {
			required: true,
			position: 0,
			list: true,
			default: ['./test/example-students/'],
			help: 'a student file or folder of student files, or stdin',
		})
		.parse()

	let students = await loadInput(args.input)

	let mochaInstance = new Mocha()
	students.forEach(student => testStudent(student, mochaInstance))
	mochaInstance.run()
}
<|endoftext|>


<commit_before>const config = require('../packages/uikit/fonts/config.json');

function convertCode(code) {
  const newString = code.toString(16);
  return '0000'.substr(0, Math.max(4 - newString.length, 0)) + newString;
}

function compareGlyph(a, b) {
  return a.code - b.code;
}

if (!config || !config.name || !Array.isArray(config.glyphs) || config.glyphs.length <= 0) {
  throw new Error('font config not found');
}

const { name, glyphs } = config;

const icons = glyphs
  .map(({ css, code }) => {
    if (css && code) {
      return { css, code };
    }
    return false;
  })
  .filter(val => !!val)
  .sort(compareGlyph)
  .map(({ css, code }) => {
    const baseCode = convertCode(code);
    return {
      icon: css,
      content: `\\${baseCode}`,
      unicode: `0x${baseCode}`,
    };
  });

module.exports = {
  name,
  prefix: config.css_prefix_text.replace(/-$/, ''),
  icons,
};
<commit_msg>style: fix linter error<commit_after>const config = require('../packages/uikit/fonts/config.json');

function convertCode(code) {
  const newString = code.toString(16);
  return '0000'.slice(0, Math.max(4 - newString.length, 0)) + newString;
}

function compareGlyph(a, b) {
  return a.code - b.code;
}

if (!config || !config.name || !Array.isArray(config.glyphs) || config.glyphs.length <= 0) {
  throw new Error('font config not found');
}

const { name, glyphs } = config;

const icons = glyphs
  .map(({ css, code }) => {
    if (css && code) {
      return { css, code };
    }
    return false;
  })
  .filter(val => !!val)
  .sort(compareGlyph)
  .map(({ css, code }) => {
    const baseCode = convertCode(code);
    return {
      icon: css,
      content: `\\${baseCode}`,
      unicode: `0x${baseCode}`,
    };
  });

module.exports = {
  name,
  prefix: config.css_prefix_text.replace(/-$/, ''),
  icons,
};
<|endoftext|>