<commit_before>/*
* Copyright 2014 Space Dynamics Laboratory - Utah State University Research Foundation.
*
* 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.
*/
'use strict';

/*global MOCKDATA2, jQuery, confirm, triggerError*/

app.controller('UserProfileCtrl', ['$scope', 'business', '$rootScope', '$location', '$timeout', function($scope, Business, $rootScope, $location, $timeout) {

  //////////////////////////////////////////////////////////////////////////////
  // Variables
  //////////////////////////////////////////////////////////////////////////////
  $scope.total            = {};
  $scope._scopename       = 'userprofile';
  $scope.pageTitle        = 'DI2E Storefront Catalog';
  $scope.defaultTitle     = 'Browse Categories';
  $scope.review           = null;
  $scope.user             = {};
  $scope.nav              = {
    'current': null,
    'bars': [
      //
      { 'title': 'User Profile', 'include': 'views/userprofiletab.html' },
      { 'title': 'Watches', 'include': 'views/watchestab.html' },
      { 'title': 'Component Reviews', 'include': 'views/feedbacktab.html' }
    //
    ]
  };

  Business.userservice.getCurrentUserProfile().then(function(result){
    if (result) {
      $scope.user.info = result;
      // console.log('result', result);

    }
  });

  $scope.log = $rootScope.log;

  $scope.old = $scope.nav.current;
  $scope.$watch('nav', function(){
    if ($scope.old && $scope.nav.current !== $scope.old) {
      $rootScope.sendPageView('Modal-ProfileModal-tabSwitchTo-'+$scope.nav.current);
    }
    $scope.old = $scope.nav.current;
  }, true);

  Business.componentservice.getComponentDetails().then(function(result) {
    if (result) {
      $scope.total = result;
    } else {
      $scope.total = null;
    }
    resetData();
  });

  // TODO: Set this up so it is actually calling with the user's username.
  $scope.getReviews = function() {
    Business.userservice.getReviews('ANONYMOUS').then(function(result){
      if (result) {
        console.log('result', result);

        $scope.username = 'ANONYMOUS';
        $scope.reviews = result;
      } else {
        $scope.reviews = null;
      }
    });
  }
  $scope.getReviews();
  $scope.$on('$newReview', function(){
    $scope.getReviews();
  })

  Business.userservice.getReviews('ANONYMOUS').then(function(result){
    if (result) {
      console.log('result', result);

      $scope.username = 'ANONYMOUS';
      $scope.reviews = result;
    } else {
      $scope.reviews = null;
    }
  });
  Business.lookupservice.getExpertise().then(function(result){
    if (result) {
      $scope.expertise = result;
    } else {
      $scope.expertise = [];
    }
  });
  Business.lookupservice.getUserTypeCodes().then(function(result){
    if (result) {
      $scope.userTypeCodes = result;
    } else {
      $scope.userTypeCodes = [];
    }
    loadUserProfile();
  });
  Business.getProsConsList().then(function(result) {
    if (result) {
      $scope.prosConsList = result;
    } else {
      $scope.prosConsList = null;
    }
  });

  $scope.EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*$/i;

  //////////////////////////////////////////////////////////////////////////////
  // Functions
  //////////////////////////////////////////////////////////////////////////////

  /***************************************************************
  * This function converts a timestamp to a displayable date
  ***************************************************************/
  $scope.getDate = function(date){
    if (date)
    {
      var d = new Date(date);
      var currDate = d.getDate();
      var currMonth = d.getMonth();
      var currYear = d.getFullYear();
      return ((currMonth + 1) + '/' + currDate + '/' + currYear);
    }
    return null;
  };

  /***************************************************************
  * This function adds a component to the watch list and toggles the buttons
  ***************************************************************/
  $scope.goToFullPage = function(id){
    var url = $location.absUrl().substring(0, $location.absUrl().length - $location.url().length);
    url = url + '/single?id=' + id;
    window.open(url, 'Component ' + id, 'scrollbars');
  };

  /***************************************************************
  * This function converts a timestamp to a displayable date
  ***************************************************************/
  $scope.isNewer = function(updateDate, viewDate){
    return parseInt(updateDate) > parseInt(viewDate);
  };

  /***************************************************************
  * This function converts a timestamp to a displayable date
  ***************************************************************/
  $scope.setNotify = function(id, value){
    _.find($scope.watches, {'componentId': id}).notifyFlg = value;
  };

  $scope.toggleCollapse = function(id){
    $('#' + id).collapse('toggle');
  };

  /***************************************************************
  * This function takes the watch list, and the total data we got back, and
  * grabs the data items that are really on the watch list. This will change
  * once we actually have a database to query from.
  ***************************************************************/
  var resetData = function() {
    $scope.data = [];
    _.each($scope.watches, function(watch) {
      var component = _.find($scope.total, {'componentId': watch.componentId});
      if (component) {
        component.watched = watch.watched;
        $scope.data.push(component);
      }
    });
  };

  $scope.cancelUserProfile = function() {

    Business.userservice.getCurrentUserProfile().then(function(profile) {
      $scope.userProfile = profile;
      $scope.userProfileForm = angular.copy(profile);

      _.each($scope.userTypeCodes, function(element, index, list) { /*jshint unused:false*/
        if (element.code === $scope.userProfileForm.userTypeCode) {
          $scope.userProfileForm.userRole = element;
        }
      });
    });
  };

  /***************************************************************
  * Load the User profile
  ***************************************************************/
  var loadUserProfile = function() {
    //show load mask on form
    Business.userservice.getCurrentUserProfile().then(function(profile) {
      $scope.userProfile = profile;
      $scope.userProfileForm = angular.copy(profile);

      _.each($scope.userTypeCodes, function(element, index, list) { /*jshint unused:false*/
        if (element.code === $scope.userProfileForm.userTypeCode) {
          $scope.userProfileForm.userRole = element;
        }
      });
      //hide load mask
    });
  };

  /***************************************************************
  * Save the user profile
  ***************************************************************/
  $scope.saveUserProfile = function() {
    // myCheckValue
    // mask form
    $scope.$emit('$TRIGGERLOAD', 'userLoad');

    $scope.mySwitch = false;

    //validate form
    $scope.userProfileForm.userTypeCode = $scope.userProfileForm.userRole.code;

    // Business.userservice.saveCurrentUserProfile($scope.userProfileForm, success, failure);
    Business.userservice.saveCurrentUserProfile($scope.userProfileForm).then(
      function(data, status, headers, config){ /* jshint unused:false */
        //SUCCESS:: data = return value
        $scope.$emit('$TRIGGERUNLOAD', 'userLoad');
        $scope.$emit('$triggerEvent', '$RESETUSER');
      },
      function(value){ //FAILURE:: value = reason why it failed
        triggerError(value);
        $scope.$emit('$TRIGGERUNLOAD', 'userLoad');
      });
  };

  /***************************************************************
  * This function saves the profile changes in the scope by copying them from
  * the user variable into the backup variable (this function would be where
  * you send the saved data to the database to store it)
  ***************************************************************/ //
  $scope.saveProfileChanges = function() {
    $scope.userBackup = jQuery.extend(true, {}, $scope.user);
  };

  /***************************************************************
  * This function reverts the changes in the profile form by just copying back
  * the details in the backup. This function most likely won't change when
  * we get a database to work with.
  ***************************************************************/
  $scope.revertProfileChanges = function() {
    $scope.user = jQuery.extend(true, {}, $scope.userBackup);
  };

  $scope.deleteReview = function(reviewId, componentId) {
    console.log('reviewId', reviewId);
    Business.componentservice.deleteReview(componentId, reviewId).then(function(result) {
      $scope.$emit('$TRIGGEREVENT', '$detailsUpdated', componentId);
      $scope.$emit('$TRIGGEREVENT', '$newReview');
    });
  };

  /***************************************************************
  * This function removes a watch from the watch list. It probably won't change
  * when we get a database to work with.
  * params: id -- the id of the component we want to take off our watch list.
  ***************************************************************/
  $scope.removeFromWatches = function(id){
    var answer = confirm ('You are about to remove a component from your watch list. Are you sure you want to do this?');
    if (answer) {
      if ($scope.watches && $scope.watches.length > 0) {
        var watch = _.find($scope.watches, {componentId: id});
        if ($scope.user.info && watch.watchId) {
          Business.userservice.removeWatch($scope.user.info.username, watch.watchId).then(null, function(result){
            $scope.$emit('$TRIGGEREVENT', '$updatedWatches');
            $scope.$emit('$TRIGGEREVENT', '$detailsUpdated', id);
          });
        }
      }
    }
  };

  $scope.updateWatch = function(watch){
    var watchId = watch.watchId;
    delete watch.componentName;
    delete watch.lastUpdateDts;
    delete watch.watchId;
    delete watch.createDts;
    delete watch.$$hashKey;
    console.log('watch', watch);
    if ($scope.user.info) {
      Business.userservice.saveWatch($scope.user.info.username, watch, watchId).then(function(result){
        if (result) {
          $scope.$emit('$TRIGGEREVENT', '$updatedWatches');
          $scope.$emit('$TRIGGEREVENT', '$detailsUpdated', watch.componentId);
        }
      });
    }
  }

  $scope.$on('$includeContentLoaded', function(){
    $timeout(function() {
      $('[data-toggle=\'tooltip\']').tooltip();
    }, 300);
  });

  $scope.resetWatches = function(hard) {
    if ($scope.user.info) {
      Business.userservice.getWatches($scope.user.info.username, hard).then(function(result){
        if (result) {
          $scope.watches = result;
          $scope.watches = _.sortBy($scope.watches, function(item) {
            return item.componentName;
          });
        } else {
          $scope.watches = null;
        }
      });
    } else {
      Business.userservice.getCurrentUserProfile().then(function(result){
        if (result) {
          Business.userservice.getWatches(result.username, hard).then(function(result){
            if (result) {
              if (!$scope.user) {
                $scope.user = {};
              }
              if (!$scope.user.info) {
                $scope.user.info = result;
              }
              $scope.watches = result;
              $scope.watches = _.sortBy($scope.watches, function(item) {
                return item.componentName;
              });
            } else {
              $scope.watches = null;
            }
          });
        } else {
          $scope.watches = null;
        }
      })
    }
  };
  $scope.resetWatches(false);
  $scope.$on('$updatedWatches', function(event){/*jshint unused:false*/
    $scope.resetWatches(true);
    resetData();
  });

  //////////////////////////////////////////////////////////////////////////////
  // Event Watches
  //////////////////////////////////////////////////////////////////////////////
  $rootScope.$on('$profileModal', function(event) { /*jshint unused: false*/
    $scope.old = null;
    if ($rootScope.current) {
      $scope.nav.current = $rootScope.current;
    } else {
      $scope.nav.current = 'User Profile';
    }
    resetData();
    // we re-initialize anything else here
  });

}]);

<commit_msg>Fixed the date compare for the client watches list.<commit_after>/*
* Copyright 2014 Space Dynamics Laboratory - Utah State University Research Foundation.
*
* 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.
*/
'use strict';

/*global MOCKDATA2, jQuery, confirm, triggerError*/

app.controller('UserProfileCtrl', ['$scope', 'business', '$rootScope', '$location', '$timeout', function($scope, Business, $rootScope, $location, $timeout) {

  //////////////////////////////////////////////////////////////////////////////
  // Variables
  //////////////////////////////////////////////////////////////////////////////
  $scope.total            = {};
  $scope._scopename       = 'userprofile';
  $scope.pageTitle        = 'DI2E Storefront Catalog';
  $scope.defaultTitle     = 'Browse Categories';
  $scope.review           = null;
  $scope.user             = {};
  $scope.nav              = {
    'current': null,
    'bars': [
      //
      { 'title': 'User Profile', 'include': 'views/userprofiletab.html' },
      { 'title': 'Watches', 'include': 'views/watchestab.html' },
      { 'title': 'Component Reviews', 'include': 'views/feedbacktab.html' }
    //
    ]
  };

  Business.userservice.getCurrentUserProfile().then(function(result){
    if (result) {
      $scope.user.info = result;
      // console.log('result', result);

    }
  });

  $scope.log = $rootScope.log;

  $scope.old = $scope.nav.current;
  $scope.$watch('nav', function(){
    if ($scope.old && $scope.nav.current !== $scope.old) {
      $rootScope.sendPageView('Modal-ProfileModal-tabSwitchTo-'+$scope.nav.current);
    }
    $scope.old = $scope.nav.current;
  }, true);

  Business.componentservice.getComponentDetails().then(function(result) {
    if (result) {
      $scope.total = result;
    } else {
      $scope.total = null;
    }
    resetData();
  });

  // TODO: Set this up so it is actually calling with the user's username.
  $scope.getReviews = function() {
    Business.userservice.getReviews('ANONYMOUS').then(function(result){
      if (result) {
        console.log('result', result);

        $scope.username = 'ANONYMOUS';
        $scope.reviews = result;
      } else {
        $scope.reviews = null;
      }
    });
  }
  $scope.getReviews();
  $scope.$on('$newReview', function(){
    $scope.getReviews();
  })

  Business.userservice.getReviews('ANONYMOUS').then(function(result){
    if (result) {
      console.log('result', result);

      $scope.username = 'ANONYMOUS';
      $scope.reviews = result;
    } else {
      $scope.reviews = null;
    }
  });
  Business.lookupservice.getExpertise().then(function(result){
    if (result) {
      $scope.expertise = result;
    } else {
      $scope.expertise = [];
    }
  });
  Business.lookupservice.getUserTypeCodes().then(function(result){
    if (result) {
      $scope.userTypeCodes = result;
    } else {
      $scope.userTypeCodes = [];
    }
    loadUserProfile();
  });
  Business.getProsConsList().then(function(result) {
    if (result) {
      $scope.prosConsList = result;
    } else {
      $scope.prosConsList = null;
    }
  });

  $scope.EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*$/i;

  //////////////////////////////////////////////////////////////////////////////
  // Functions
  //////////////////////////////////////////////////////////////////////////////

  /***************************************************************
  * This function converts a timestamp to a displayable date
  ***************************************************************/
  $scope.getDate = function(date){
    if (date)
    {
      var d = new Date(date);
      var currDate = d.getDate();
      var currMonth = d.getMonth();
      var currYear = d.getFullYear();
      return ((currMonth + 1) + '/' + currDate + '/' + currYear);
    }
    return null;
  };

  /***************************************************************
  * This function adds a component to the watch list and toggles the buttons
  ***************************************************************/
  $scope.goToFullPage = function(id){
    var url = $location.absUrl().substring(0, $location.absUrl().length - $location.url().length);
    url = url + '/single?id=' + id;
    window.open(url, 'Component ' + id, 'scrollbars');
  };

  /***************************************************************
  * This function converts a timestamp to a displayable date
  ***************************************************************/
  $scope.isNewer = function(updateDate, viewDate){
    var update = new Date(updateDate);
    var view = new Date(viewDate);
    return view < update;
  };

  /***************************************************************
  * This function converts a timestamp to a displayable date
  ***************************************************************/
  $scope.setNotify = function(id, value){
    _.find($scope.watches, {'componentId': id}).notifyFlg = value;
  };

  $scope.toggleCollapse = function(id){
    $('#' + id).collapse('toggle');
  };

  /***************************************************************
  * This function takes the watch list, and the total data we got back, and
  * grabs the data items that are really on the watch list. This will change
  * once we actually have a database to query from.
  ***************************************************************/
  var resetData = function() {
    $scope.data = [];
    _.each($scope.watches, function(watch) {
      var component = _.find($scope.total, {'componentId': watch.componentId});
      if (component) {
        component.watched = watch.watched;
        $scope.data.push(component);
      }
    });
  };

  $scope.cancelUserProfile = function() {

    Business.userservice.getCurrentUserProfile().then(function(profile) {
      $scope.userProfile = profile;
      $scope.userProfileForm = angular.copy(profile);

      _.each($scope.userTypeCodes, function(element, index, list) { /*jshint unused:false*/
        if (element.code === $scope.userProfileForm.userTypeCode) {
          $scope.userProfileForm.userRole = element;
        }
      });
    });
  };

  /***************************************************************
  * Load the User profile
  ***************************************************************/
  var loadUserProfile = function() {
    //show load mask on form
    Business.userservice.getCurrentUserProfile().then(function(profile) {
      $scope.userProfile = profile;
      $scope.userProfileForm = angular.copy(profile);

      _.each($scope.userTypeCodes, function(element, index, list) { /*jshint unused:false*/
        if (element.code === $scope.userProfileForm.userTypeCode) {
          $scope.userProfileForm.userRole = element;
        }
      });
      //hide load mask
    });
  };

  /***************************************************************
  * Save the user profile
  ***************************************************************/
  $scope.saveUserProfile = function() {
    // myCheckValue
    // mask form
    $scope.$emit('$TRIGGERLOAD', 'userLoad');

    $scope.mySwitch = false;

    //validate form
    $scope.userProfileForm.userTypeCode = $scope.userProfileForm.userRole.code;

    // Business.userservice.saveCurrentUserProfile($scope.userProfileForm, success, failure);
    Business.userservice.saveCurrentUserProfile($scope.userProfileForm).then(
      function(data, status, headers, config){ /* jshint unused:false */
        //SUCCESS:: data = return value
        $scope.$emit('$TRIGGERUNLOAD', 'userLoad');
        $scope.$emit('$triggerEvent', '$RESETUSER');
      },
      function(value){ //FAILURE:: value = reason why it failed
        triggerError(value);
        $scope.$emit('$TRIGGERUNLOAD', 'userLoad');
      });
  };

  /***************************************************************
  * This function saves the profile changes in the scope by copying them from
  * the user variable into the backup variable (this function would be where
  * you send the saved data to the database to store it)
  ***************************************************************/ //
  $scope.saveProfileChanges = function() {
    $scope.userBackup = jQuery.extend(true, {}, $scope.user);
  };

  /***************************************************************
  * This function reverts the changes in the profile form by just copying back
  * the details in the backup. This function most likely won't change when
  * we get a database to work with.
  ***************************************************************/
  $scope.revertProfileChanges = function() {
    $scope.user = jQuery.extend(true, {}, $scope.userBackup);
  };

  $scope.deleteReview = function(reviewId, componentId) {
    console.log('reviewId', reviewId);
    Business.componentservice.deleteReview(componentId, reviewId).then(function(result) {
      $scope.$emit('$TRIGGEREVENT', '$detailsUpdated', componentId);
      $scope.$emit('$TRIGGEREVENT', '$newReview');
    });
  };

  /***************************************************************
  * This function removes a watch from the watch list. It probably won't change
  * when we get a database to work with.
  * params: id -- the id of the component we want to take off our watch list.
  ***************************************************************/
  $scope.removeFromWatches = function(id){
    var answer = confirm ('You are about to remove a component from your watch list. Are you sure you want to do this?');
    if (answer) {
      if ($scope.watches && $scope.watches.length > 0) {
        var watch = _.find($scope.watches, {componentId: id});
        if ($scope.user.info && watch.watchId) {
          Business.userservice.removeWatch($scope.user.info.username, watch.watchId).then(null, function(result){
            $scope.$emit('$TRIGGEREVENT', '$updatedWatches');
            $scope.$emit('$TRIGGEREVENT', '$detailsUpdated', id);
          });
        }
      }
    }
  };

  $scope.updateWatch = function(watch){
    var watchId = watch.watchId;
    delete watch.componentName;
    delete watch.lastUpdateDts;
    delete watch.watchId;
    delete watch.createDts;
    delete watch.$$hashKey;
    console.log('watch', watch);
    if ($scope.user.info) {
      Business.userservice.saveWatch($scope.user.info.username, watch, watchId).then(function(result){
        if (result) {
          $scope.$emit('$TRIGGEREVENT', '$updatedWatches');
          $scope.$emit('$TRIGGEREVENT', '$detailsUpdated', watch.componentId);
        }
      });
    }
  }

  $scope.$on('$includeContentLoaded', function(){
    $timeout(function() {
      $('[data-toggle=\'tooltip\']').tooltip();
    }, 300);
  });

  $scope.resetWatches = function(hard) {
    if ($scope.user.info) {
      Business.userservice.getWatches($scope.user.info.username, hard).then(function(result){
        if (result) {
          $scope.watches = result;
          $scope.watches = _.sortBy($scope.watches, function(item) {
            return item.componentName;
          });
        } else {
          $scope.watches = null;
        }
      });
    } else {
      Business.userservice.getCurrentUserProfile().then(function(result){
        if (result) {
          Business.userservice.getWatches(result.username, hard).then(function(result){
            if (result) {
              if (!$scope.user) {
                $scope.user = {};
              }
              if (!$scope.user.info) {
                $scope.user.info = result;
              }
              $scope.watches = result;
              $scope.watches = _.sortBy($scope.watches, function(item) {
                return item.componentName;
              });
            } else {
              $scope.watches = null;
            }
          });
        } else {
          $scope.watches = null;
        }
      })
    }
  };
  $scope.resetWatches(false);
  $scope.$on('$updatedWatches', function(event){/*jshint unused:false*/
    $scope.resetWatches(true);
    resetData();
  });

  //////////////////////////////////////////////////////////////////////////////
  // Event Watches
  //////////////////////////////////////////////////////////////////////////////
  $rootScope.$on('$profileModal', function(event) { /*jshint unused: false*/
    $scope.old = null;
    if ($rootScope.current) {
      $scope.nav.current = $rootScope.current;
    } else {
      $scope.nav.current = 'User Profile';
    }
    resetData();
    // we re-initialize anything else here
  });

}]);

<|endoftext|>


<commit_before>/**
 * @flow
 */

import fs from 'fs';
import hasbin from 'hasbin';
import mkdirp from 'mkdirp';
import ncp from 'ncp';
import spawnAsync from '@exponent/spawn-async';
import path from 'path';

import Config from './Config';
import * as Env from './Env';
import ErrorCode from './ErrorCode';
import Logger from './Logger';
import NotificationCode from './NotificationCode';
import UserSettings from './UserSettings';
import XDLError from './XDLError';

let runas; // Crashes on windows, so load this lazily
let hasSourcedBashLoginScripts = false;

export const OSX_SOURCE_PATH = path.join(__dirname, '..', 'binaries', 'osx');
const INSTALL_PATH = '/usr/local/bin';

export function ncpAsync(source: string, dest: string, options: any = {}) {
  return new Promise((resolve, reject) => {
    ncp(source, dest, options, (err) => {
      if (err) {
        reject();
      } else {
        resolve();
      }
    });
  });
}

function _hasbinAsync(name) {
  return new Promise((resolve, reject) => {
    hasbin(name, (result) => {
      resolve(result);
    });
  });
}

async function _binaryInstalledAsync(name) {
  try {
    let result = await spawnAsync('which', [name]);
    // We add watchman to PATH when starting packager, so make sure we're not using that version
    return (result.stdout && result.stdout.length > 1 && !result.stdout.includes(OSX_SOURCE_PATH));
  } catch (e) {
    console.log(e.toString());
    return false;
  }
}

function _exponentBinaryDirectory() {
  let dotExponentHomeDirectory = UserSettings.dotExponentHomeDirectory();
  let dir = path.join(dotExponentHomeDirectory, 'bin');
  mkdirp.sync(dir);
  return dir;
}

async function _installBinaryAsync(name) {
  if (await _binaryInstalledAsync(name)) {
    return false;
  }

  try {
    if (!runas) {
      runas = require('runas');
    }
    let result = runas('/bin/ln', ['-s', path.join(_exponentBinaryDirectory(), name), path.join(INSTALL_PATH, name)], {
      admin: true,
    });

    return result === 0;
  } catch (e) {
    Logger.notifications.error({code: NotificationCode.INSTALL_SHELL_COMMANDS_RESULT}, `Error installing ${name}: ${e.message}`);
    throw e;
  }
}

export async function installShellCommandsAsync() {
  await sourceBashLoginScriptsAsync();

  if (process.platform !== 'darwin') {
    throw new XDLError(ErrorCode.PLATFORM_NOT_SUPPORTED, 'Platform not supported.');
  }

  await ncpAsync(OSX_SOURCE_PATH, _exponentBinaryDirectory());

  let binaries = ['adb', 'watchman'];
  let installedBinaries = [];
  for (let i = 0; i < binaries.length; i++) {
    if (await _installBinaryAsync(binaries[i])) {
      installedBinaries.push(binaries[i]);
    }
  }

  if (installedBinaries.length === 0) {
    Logger.notifications.warn({code: NotificationCode.INSTALL_SHELL_COMMANDS_RESULT}, `Shell commands ${binaries.join(', ')} are already installed`);
  } else {
    Logger.notifications.info({code: NotificationCode.INSTALL_SHELL_COMMANDS_RESULT}, `Installed ${installedBinaries.join(', ')} to your shell`);
  }
}

export function getBinariesPath(): string {
  if (process.platform === 'darwin') {
    return path.join(__dirname, '..', 'binaries', 'osx');
  } else if (process.platform === 'win32') {
    return path.join(__dirname, '..', 'binaries', 'windows');
  } else if (process.platform === 'linux') {
    return path.join(__dirname, '..', 'binaries', 'linux');
  } else {
    throw new XDLError(ErrorCode.PLATFORM_NOT_SUPPORTED, 'Platform not supported.');
  }
}

export async function addToPathAsync(name: string) {
  await sourceBashLoginScriptsAsync();

  if (await _hasbinAsync(name)) {
    return;
  }

  if (!process.env.PATH) {
    process.env.PATH = '';
  }

  let binariesPath = getBinariesPath();
  let delimiter = process.platform === 'win32' ? ';' : ':';
  process.env.PATH = `${process.env.PATH}${delimiter}${binariesPath}`;
}

function _exponentRCFileExists() {
  try {
    return fs.statSync(path.join(Env.home(), '.exponent', 'bashrc')).isFile();
  } catch (e) {
    return false;
  }
}

export async function sourceBashLoginScriptsAsync() {
  if (hasSourcedBashLoginScripts || process.platform === 'win32') {
    return;
  }

  if (Config.developerTool === 'exp') {
    return;
  }

  hasSourcedBashLoginScripts = true;
  let currentPath = process.env.PATH ? process.env.PATH : '';

  try {
    if (_exponentRCFileExists()) {
      // User has a ~/.exponent/bashrc. Run that and grab PATH.
      let result = await spawnAsync(path.join(getBinariesPath(), `get-path-bash`), {
        env: {
          PATH: '',
        },
      });

      if (result.stderr) {
        Logger.global.debug(`Error sourcing ~/.exponent/bashrc script: ${result.stderr}`);
      }

      if (result.stdout) {
        if (currentPath.length > 0) {
          currentPath = `${currentPath}:`;
        }

        currentPath = `${currentPath}${result.stdout}`;
      }
    } else {
      // No ~/.exponent/bashrc file found. Run `env` in process.env.SHELL.
      let result;
      if (/t?csh$/.test(process.env.SHELL)) {
        // csh
        result = await spawnAsync(process.env.SHELL, ['-d', '-c', 'env']);
      } else {
        // bash, zsh, fish
        result = await spawnAsync(process.env.SHELL, ['-l', '-c', 'env']);
      }

      if (result.stderr) {
        Logger.global.debug(`Error sourcing shell startup scripts: ${result.stderr}`);
      }

      if (result.stdout) {
        let regexResult = result.stdout.match(/(^|\n)PATH=(.+)/);

        if (regexResult.length >= 3) {
          if (currentPath.length > 0) {
            currentPath = `${currentPath}:`;
          }

          currentPath = `${currentPath}${regexResult[2]}`;
        } else {
          Logger.global.debug(`Error parsing shell startup scripts output: ${result.stderr}`);
        }
      }
    }
  } catch (e) {
    Logger.global.debug(`Error sourcing shell startup scripts: ${e.stderr}`);
  }

  process.env.PATH = currentPath;
}
<commit_msg>Fix PATH on zsh<commit_after>/**
 * @flow
 */

import fs from 'fs';
import hasbin from 'hasbin';
import mkdirp from 'mkdirp';
import ncp from 'ncp';
import spawnAsync from '@exponent/spawn-async';
import path from 'path';

import Config from './Config';
import * as Env from './Env';
import ErrorCode from './ErrorCode';
import Logger from './Logger';
import NotificationCode from './NotificationCode';
import UserSettings from './UserSettings';
import XDLError from './XDLError';

let runas; // Crashes on windows, so load this lazily
let hasSourcedBashLoginScripts = false;

export const OSX_SOURCE_PATH = path.join(__dirname, '..', 'binaries', 'osx');
const INSTALL_PATH = '/usr/local/bin';

export function ncpAsync(source: string, dest: string, options: any = {}) {
  return new Promise((resolve, reject) => {
    ncp(source, dest, options, (err) => {
      if (err) {
        reject();
      } else {
        resolve();
      }
    });
  });
}

function _hasbinAsync(name) {
  return new Promise((resolve, reject) => {
    hasbin(name, (result) => {
      resolve(result);
    });
  });
}

async function _binaryInstalledAsync(name) {
  try {
    let result = await spawnAsync('which', [name]);
    // We add watchman to PATH when starting packager, so make sure we're not using that version
    return (result.stdout && result.stdout.length > 1 && !result.stdout.includes(OSX_SOURCE_PATH));
  } catch (e) {
    console.log(e.toString());
    return false;
  }
}

function _exponentBinaryDirectory() {
  let dotExponentHomeDirectory = UserSettings.dotExponentHomeDirectory();
  let dir = path.join(dotExponentHomeDirectory, 'bin');
  mkdirp.sync(dir);
  return dir;
}

async function _installBinaryAsync(name) {
  if (await _binaryInstalledAsync(name)) {
    return false;
  }

  try {
    if (!runas) {
      runas = require('runas');
    }
    let result = runas('/bin/ln', ['-s', path.join(_exponentBinaryDirectory(), name), path.join(INSTALL_PATH, name)], {
      admin: true,
    });

    return result === 0;
  } catch (e) {
    Logger.notifications.error({code: NotificationCode.INSTALL_SHELL_COMMANDS_RESULT}, `Error installing ${name}: ${e.message}`);
    throw e;
  }
}

export async function installShellCommandsAsync() {
  await sourceBashLoginScriptsAsync();

  if (process.platform !== 'darwin') {
    throw new XDLError(ErrorCode.PLATFORM_NOT_SUPPORTED, 'Platform not supported.');
  }

  await ncpAsync(OSX_SOURCE_PATH, _exponentBinaryDirectory());

  let binaries = ['adb', 'watchman'];
  let installedBinaries = [];
  for (let i = 0; i < binaries.length; i++) {
    if (await _installBinaryAsync(binaries[i])) {
      installedBinaries.push(binaries[i]);
    }
  }

  if (installedBinaries.length === 0) {
    Logger.notifications.warn({code: NotificationCode.INSTALL_SHELL_COMMANDS_RESULT}, `Shell commands ${binaries.join(', ')} are already installed`);
  } else {
    Logger.notifications.info({code: NotificationCode.INSTALL_SHELL_COMMANDS_RESULT}, `Installed ${installedBinaries.join(', ')} to your shell`);
  }
}

export function getBinariesPath(): string {
  if (process.platform === 'darwin') {
    return path.join(__dirname, '..', 'binaries', 'osx');
  } else if (process.platform === 'win32') {
    return path.join(__dirname, '..', 'binaries', 'windows');
  } else if (process.platform === 'linux') {
    return path.join(__dirname, '..', 'binaries', 'linux');
  } else {
    throw new XDLError(ErrorCode.PLATFORM_NOT_SUPPORTED, 'Platform not supported.');
  }
}

export async function addToPathAsync(name: string) {
  await sourceBashLoginScriptsAsync();

  if (await _hasbinAsync(name)) {
    return;
  }

  if (!process.env.PATH) {
    process.env.PATH = '';
  }

  let binariesPath = getBinariesPath();
  let delimiter = process.platform === 'win32' ? ';' : ':';
  process.env.PATH = `${process.env.PATH}${delimiter}${binariesPath}`;
}

function _exponentRCFileExists() {
  try {
    return fs.statSync(path.join(Env.home(), '.exponent', 'bashrc')).isFile();
  } catch (e) {
    return false;
  }
}

export async function sourceBashLoginScriptsAsync() {
  if (hasSourcedBashLoginScripts || process.platform === 'win32') {
    return;
  }

  if (Config.developerTool === 'exp') {
    return;
  }

  hasSourcedBashLoginScripts = true;
  let currentPath = process.env.PATH ? process.env.PATH : '';

  try {
    if (_exponentRCFileExists()) {
      // User has a ~/.exponent/bashrc. Run that and grab PATH.
      let result = await spawnAsync(path.join(getBinariesPath(), `get-path-bash`), {
        env: {
          PATH: '',
        },
      });

      if (result.stderr) {
        Logger.global.debug(`Error sourcing ~/.exponent/bashrc script: ${result.stderr}`);
      }

      if (result.stdout) {
        if (currentPath.length > 0) {
          currentPath = `${currentPath}:`;
        }

        currentPath = `${currentPath}${result.stdout}`;
      }
    } else {
      // No ~/.exponent/bashrc file found. Run `env` in process.env.SHELL.
      let result;
      if (/t?csh$/.test(process.env.SHELL)) {
        // csh
        result = await spawnAsync(process.env.SHELL, ['-d', '-c', 'env']);
      } else if (/zsh$/.test(process.env.SHELL)) {
        // zsh
        result = await spawnAsync(process.env.SHELL, ['-l', '-c', '-i', 'env']);
      } else {
        // bash, fish
        result = await spawnAsync(process.env.SHELL, ['-l', '-c', 'env']);
      }

      if (result.stderr) {
        Logger.global.debug(`Error sourcing shell startup scripts: ${result.stderr}`);
      }

      if (result.stdout) {
        let regexResult = result.stdout.match(/(^|\n)PATH=(.+)/);

        if (regexResult.length >= 3) {
          if (currentPath.length > 0) {
            currentPath = `${currentPath}:`;
          }

          currentPath = `${currentPath}${regexResult[2]}`;
        } else {
          Logger.global.debug(`Error parsing shell startup scripts output: ${result.stderr}`);
        }
      }
    }
  } catch (e) {
    Logger.global.debug(`Error sourcing shell startup scripts: ${e.stderr}`);
  }

  process.env.PATH = currentPath;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2008 Google Inc.
 *
 * 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.
 */

/**
 * @fileoverview Definitions for W3C's event specification.
 *  The whole file has been fully type annotated.
 *  Created from
 *   http://www.w3.org/TR/DOM-Level-2-Events/ecma-script-binding.html
 *
 * @externs
 */

/**
 * @interface
 */
function EventTarget() {}

/**
 * @param {string} type
 * @param {EventListener|function(Event):(boolean|undefined)} listener
 * @param {boolean} useCapture
 * @return {undefined}
 */
EventTarget.prototype.addEventListener = function(type, listener, useCapture) {};

/**
 * @param {string} type
 * @param {EventListener|function(Event):(boolean|undefined)} listener
 * @param {boolean} useCapture
 * @return {undefined}
 */
EventTarget.prototype.removeEventListener = function(type, listener, useCapture) {};

/**
 * @param {Event} evt
 * @return {boolean}
 */
EventTarget.prototype.dispatchEvent = function(evt) {};

/**
 * @constructor
 */
function EventListener() {}

/**
 * @param {Event} evt
 * @return {undefined}
 */
EventListener.prototype.handleEvent = function(evt) {};

/**
 * @constructor
 */
function Event() {}

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-2-Events/ecma-script-binding.html
 */
Event.AT_TARGET;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-2-Events/ecma-script-binding.html
 */
Event.BUBBLING_PHASE;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-2-Events/ecma-script-binding.html
 */
Event.CAPTURING_PHASE;

/** @type {string} */
Event.prototype.type;

/** @type {EventTarget} */
Event.prototype.target;

/** @type {EventTarget} */
Event.prototype.currentTarget;

/** @type {number} */
Event.prototype.eventPhase;

/** @type {boolean} */
Event.prototype.bubbles;

/** @type {boolean} */
Event.prototype.cancelable;

/** @type {number} */
Event.prototype.timeStamp;

/** @type {Object} */
Event.prototype.state;

/**
 * @return {undefined}
 */
Event.prototype.stopPropagation = function() {};

/**
 * @return {undefined}
 */
Event.prototype.preventDefault = function() {};

/**
 * @param {string} eventTypeArg
 * @param {boolean} canBubbleArg
 * @param {boolean} cancelableArg
 * @return {undefined}
 */
Event.prototype.initEvent = function(eventTypeArg, canBubbleArg, cancelableArg) {};

/**
 * @constructor
 * @extends {Event}
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-CustomEvent
 */
function CustomEvent() {}

/**
 * @param {string} eventType
 * @param {boolean} bubbles
 * @param {boolean} cancelable
 * @param {*} detail
 */
CustomEvent.prototype.initCustomEvent = function(
    eventType, bubbles, cancelable, detail) {};

/**
 * @type {*}
 */
CustomEvent.prototype.detail;

/**
 * @constructor
 */
function DocumentEvent() {}

/**
 * @param {string} eventType
 * @return {Event}
 */
DocumentEvent.prototype.createEvent = function(eventType) {};

/**
 * @constructor
 * @extends {Event}
 */
function UIEvent() {}

/** @type {number} */
UIEvent.prototype.detail;

///**
// * @param {string} typeArg
// * @param {boolean} canBubbleArg
// * @param {boolean} cancelableArg
// * @param {AbstractView} viewArg
// * @param {number} detailArg
// * @return undefined
// */
//UIEvent.prototype.initUIEvent = function (typeArg, canBubbleArg, cancelableArg, viewArg, detailArg) {};

/**
 * @constructor
 * @extends {UIEvent}
 */
function MouseEvent() {}

/** @type {number} */
MouseEvent.prototype.screenX;

/** @type {number} */
MouseEvent.prototype.screenY;

/** @type {number} */
MouseEvent.prototype.clientX;

/** @type {number} */
MouseEvent.prototype.clientY;

/** @type {boolean} */
MouseEvent.prototype.ctrlKey;

/** @type {boolean} */
MouseEvent.prototype.shiftKey;

/** @type {boolean} */
MouseEvent.prototype.altKey;

/** @type {boolean} */
MouseEvent.prototype.metaKey;

/** @type {number} */
MouseEvent.prototype.button;

/** @type {EventTarget} */
MouseEvent.prototype.relatedTarget;

/**
 * @constructor
 * @extends {Event}
 */
function MutationEvent() {}

/** @type {Node} */
MutationEvent.prototype.relatedNode;

/** @type {string} */
MutationEvent.prototype.prevValue;

/** @type {string} */
MutationEvent.prototype.newValue;

/** @type {string} */
MutationEvent.prototype.attrName;

/** @type {number} */
MutationEvent.prototype.attrChange;

/**
 * @param {string} typeArg
 * @param {boolean} canBubbleArg
 * @param {boolean} cancelableArg
 * @param {Node} relatedNodeArg
 * @param {string} prevValueArg
 * @param {string} newValueArg
 * @param {string} attrNameArg
 * @param {number} attrChangeArg
 * @return {undefined}
 */
MutationEvent.prototype.initMutationEvent = function(typeArg, canBubbleArg, cancelableArg, relatedNodeArg, prevValueArg, newValueArg, attrNameArg, attrChangeArg) {};

// DOM3
/**
 * @constructor
 * @extends {UIEvent}
 */
function KeyboardEvent() {}

/** @type {string} */
KeyboardEvent.prototype.keyIdentifier;

/** @type {boolean} */
KeyboardEvent.prototype.ctrlKey;

/** @type {boolean} */
KeyboardEvent.prototype.shiftKey;

/** @type {boolean} */
KeyboardEvent.prototype.altKey;

/** @type {boolean} */
KeyboardEvent.prototype.metaKey;

/**
 * @param {string} keyIdentifierArg
 * @return {boolean}
 */
KeyboardEvent.prototype.getModifierState = function(keyIdentifierArg) {};
<commit_msg><commit_after>/*
 * Copyright 2008 Google Inc.
 *
 * 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.
 */

/**
 * @fileoverview Definitions for W3C's event specification.
 *  The whole file has been fully type annotated.
 *  Created from
 *   http://www.w3.org/TR/DOM-Level-2-Events/ecma-script-binding.html
 *
 * @externs
 */

/**
 * @interface
 */
function EventTarget() {}

/**
 * @param {string} type
 * @param {EventListener|function(Event):(boolean|undefined)} listener
 * @param {boolean} useCapture
 * @return {undefined}
 */
EventTarget.prototype.addEventListener = function(type, listener, useCapture) {};

/**
 * @param {string} type
 * @param {EventListener|function(Event):(boolean|undefined)} listener
 * @param {boolean} useCapture
 * @return {undefined}
 */
EventTarget.prototype.removeEventListener = function(type, listener, useCapture) {};

/**
 * @param {Event} evt
 * @return {boolean}
 */
EventTarget.prototype.dispatchEvent = function(evt) {};

/**
 * @interface
 */
function EventListener() {}

/**
 * @param {Event} evt
 * @return {undefined}
 */
EventListener.prototype.handleEvent = function(evt) {};

/**
 * @constructor
 */
function Event() {}

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-2-Events/ecma-script-binding.html
 */
Event.AT_TARGET;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-2-Events/ecma-script-binding.html
 */
Event.BUBBLING_PHASE;

/**
 * @type {number}
 * @see http://www.w3.org/TR/DOM-Level-2-Events/ecma-script-binding.html
 */
Event.CAPTURING_PHASE;

/** @type {string} */
Event.prototype.type;

/** @type {EventTarget} */
Event.prototype.target;

/** @type {EventTarget} */
Event.prototype.currentTarget;

/** @type {number} */
Event.prototype.eventPhase;

/** @type {boolean} */
Event.prototype.bubbles;

/** @type {boolean} */
Event.prototype.cancelable;

/** @type {number} */
Event.prototype.timeStamp;

/** @type {Object} */
Event.prototype.state;

/**
 * @return {undefined}
 */
Event.prototype.stopPropagation = function() {};

/**
 * @return {undefined}
 */
Event.prototype.preventDefault = function() {};

/**
 * @param {string} eventTypeArg
 * @param {boolean} canBubbleArg
 * @param {boolean} cancelableArg
 * @return {undefined}
 */
Event.prototype.initEvent = function(eventTypeArg, canBubbleArg, cancelableArg) {};

/**
 * @constructor
 * @extends {Event}
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-CustomEvent
 */
function CustomEvent() {}

/**
 * @param {string} eventType
 * @param {boolean} bubbles
 * @param {boolean} cancelable
 * @param {*} detail
 */
CustomEvent.prototype.initCustomEvent = function(
    eventType, bubbles, cancelable, detail) {};

/**
 * @type {*}
 */
CustomEvent.prototype.detail;

/**
 * @constructor
 */
function DocumentEvent() {}

/**
 * @param {string} eventType
 * @return {Event}
 */
DocumentEvent.prototype.createEvent = function(eventType) {};

/**
 * @constructor
 * @extends {Event}
 */
function UIEvent() {}

/** @type {number} */
UIEvent.prototype.detail;

///**
// * @param {string} typeArg
// * @param {boolean} canBubbleArg
// * @param {boolean} cancelableArg
// * @param {AbstractView} viewArg
// * @param {number} detailArg
// * @return undefined
// */
//UIEvent.prototype.initUIEvent = function (typeArg, canBubbleArg, cancelableArg, viewArg, detailArg) {};

/**
 * @constructor
 * @extends {UIEvent}
 */
function MouseEvent() {}

/** @type {number} */
MouseEvent.prototype.screenX;

/** @type {number} */
MouseEvent.prototype.screenY;

/** @type {number} */
MouseEvent.prototype.clientX;

/** @type {number} */
MouseEvent.prototype.clientY;

/** @type {boolean} */
MouseEvent.prototype.ctrlKey;

/** @type {boolean} */
MouseEvent.prototype.shiftKey;

/** @type {boolean} */
MouseEvent.prototype.altKey;

/** @type {boolean} */
MouseEvent.prototype.metaKey;

/** @type {number} */
MouseEvent.prototype.button;

/** @type {EventTarget} */
MouseEvent.prototype.relatedTarget;

/**
 * @constructor
 * @extends {Event}
 */
function MutationEvent() {}

/** @type {Node} */
MutationEvent.prototype.relatedNode;

/** @type {string} */
MutationEvent.prototype.prevValue;

/** @type {string} */
MutationEvent.prototype.newValue;

/** @type {string} */
MutationEvent.prototype.attrName;

/** @type {number} */
MutationEvent.prototype.attrChange;

/**
 * @param {string} typeArg
 * @param {boolean} canBubbleArg
 * @param {boolean} cancelableArg
 * @param {Node} relatedNodeArg
 * @param {string} prevValueArg
 * @param {string} newValueArg
 * @param {string} attrNameArg
 * @param {number} attrChangeArg
 * @return {undefined}
 */
MutationEvent.prototype.initMutationEvent = function(typeArg, canBubbleArg, cancelableArg, relatedNodeArg, prevValueArg, newValueArg, attrNameArg, attrChangeArg) {};

// DOM3
/**
 * @constructor
 * @extends {UIEvent}
 */
function KeyboardEvent() {}

/** @type {string} */
KeyboardEvent.prototype.keyIdentifier;

/** @type {boolean} */
KeyboardEvent.prototype.ctrlKey;

/** @type {boolean} */
KeyboardEvent.prototype.shiftKey;

/** @type {boolean} */
KeyboardEvent.prototype.altKey;

/** @type {boolean} */
KeyboardEvent.prototype.metaKey;

/**
 * @param {string} keyIdentifierArg
 * @return {boolean}
 */
KeyboardEvent.prototype.getModifierState = function(keyIdentifierArg) {};
<|endoftext|>


<commit_before>var yaml = require('js-yaml');
var fs = require('fs');
var pdf = require('html-pdf');
var path = require('path');

fs.readFile('static/monorail-2.0.yaml', { encoding: 'utf8'}, function(err, swaggerData) {
    if (err) return console.log(err);

    var swaggerDef = yaml.safeLoad(swaggerData);
    require('bootprint')
    .load(require('bootprint-swagger'))
    .build('static/monorail-2.0.yaml', 'build/swagger-doc')
    .generate()
    .done(function(data) {
        var html = fs.readFileSync(data[0], 'utf-8');
        var options = {
            base: 'file://' + path.resolve(data[0]),
            format: 'Letter'
        };
        var pdfFile = 'build/swagger-doc/rackhd-api-' + swaggerDef.info.version + '.pdf';

        pdf.create(html, options)
        .toFile(pdfFile, function(err, res) {
            if (err) return console.log(err);
            console.log(res);
        });
    });
});
<commit_msg>Added Redfish pdf file generation<commit_after>// Copyright 2016, EMC, Inc.

'use strict';

var yaml = require('js-yaml');
var fs = require('fs');
var pdf = require('html-pdf');
var path = require('path');

var swaggerFiles = [
    'static/monorail-2.0.yaml',
    'static/redfish.yaml'
];

swaggerFiles.forEach(function(currentFile) {
    generatePdf(currentFile);
});

function generatePdf(swaggerFile) {
    fs.readFile(swaggerFile, {encoding: 'utf8'}, function (err, swaggerData) {
        if (err) {
            return console.log(err);
        }

        var docDir = 'build/swagger-doc';
        var swaggerDef = yaml.safeLoad(swaggerData);
        var swaggerTitle = swaggerDef.info.title.replace(/ /g, '-');
        var workDir = docDir + swaggerTitle + swaggerDef.info.version;
        require('bootprint')
            .load(require('bootprint-swagger'))
            .build(swaggerFile, workDir)
            .generate()
            .done(function (data) {
                var html = fs.readFileSync(data[0], 'utf-8');
                var options = {
                    base: 'file://' + path.resolve(data[0]),
                    format: 'Letter'
                };
                var pdfFile = docDir +
                    '/rackhd-api-' +
                    swaggerTitle +
                    '-' +
                    swaggerDef.info.version +
                    '.pdf';

                pdf.create(html, options)
                    .toFile(pdfFile, function (err, res) {
                        if (err) {
                            return console.log(err);
                        }
                        console.log(res);
                    });
            });
    });
}
<|endoftext|>


<commit_before>window._fs = require("fs");

window.addJS = function(path) {
    console.log(path);
    var customJS = window._fs.readFileSync(path, "utf-8");
    // console.log(customJS);
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.innerHTML = customJS;
    document.head.appendChild(script);
};

window.addJQuery = function(jqueryPath){
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.innerHTML = "window.$ = window.jQuery = require('"+jqueryPath+"');";
    document.head.appendChild(script);
}

window.addJQuery(window.jQueryPath);
window.addJS(window.injectablePath);<commit_msg>Modified injector so it will now fetch script from latest github commit. No need to run installer for each version released on github<commit_after>(function() {
    // https://www.tomas-dvorak.cz/posts/nodejs-request-without-dependencies/
    const getContent = function(host, path, isSecure) {
        // return new pending promise
        return new Promise((resolve, reject) => {
            // select http or https module, depending on reqested url
            const lib = isSecure ? require('https') : require('http');

            const options = {
                hostname: host,
                path: path,
                headers: {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
                }
            };

            const request = lib.get(options, (response) => {
                // handle http errors
                if (response.statusCode < 200 || response.statusCode > 299) {
                    reject(new Error('Failed to load page, status code: ' + response.statusCode));
                }
                // temporary data holder
                const body = [];
                // on every content chunk, push it to the data array
                response.on('data', (chunk) => body.push(chunk));
                // we are done, resolve promise with those joined chunks
                response.on('end', () => resolve(body.join('')));
            });
            // handle connection errors of the request
            request.on('error', (err) => reject(err))
        })
    };

    // Add custom javascript to execute
    const addJS = function(customJS) {
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.innerHTML = customJS;
        document.head.appendChild(script);
    };

    const loadScripts = function() {
        // Skip loading if already loaded
        if (window.better_emojis && window.better_emojis.loaded) {
            return;
        }

        window.better_emojis = {};

        // Get information about latest commit
        getContent("api.github.com", "/repos/TrueLecter/BetterDiscordEmojis/git/refs/heads/master", true)
            .then((json) => {
                const commitId = JSON.parse(json).object.sha;
                // Get jquery from latest github commit
                getContent("cdn.rawgit.com", "/TrueLecter/BetterDiscordEmojis/" + commitId + "/jquery.js", true)
                    .then((js) => {
                        // Add jquery code to page if not done yet
                        if (!window.better_emojis.jquery) {
                            addJS(js);
                            window.better_emojis.jquery = true;
                        }

                        // Get main script from latest commit
                        getContent("cdn.rawgit.com", "/TrueLecter/BetterDiscordEmojis/" + commitId + "/better-emojis.js", true)
                            .then((js) => {
                                // Add main script if not done yet
                                if (!window.better_emojis.be) {
                                    addJS(js);
                                    window.better_emojis.be = true;
                                }
                                window.better_emojis.loaded = true;
                            })
                            .catch((err) => {
                                console.log("Error loading Better Emojis");
                                console.log(err);
                                console.log("Retrying in 5 seconds...");
                                setTimeout(loadScripts, 5000);
                            })
                            // End Better Emojis loader promise
                    })
                    .catch((err) => {
                        console.log("Error loading jQuery");
                        console.log(err);
                        console.log("Retrying in 5 seconds...");
                        setTimeout(loadScripts, 5000);
                    })
                    // End jQuery loader promise
            })
            .catch((err) => {
                console.log("Error getting commit info");
                console.log(err);
                console.log("Retrying in 5 seconds...");
                setTimeout(loadScripts, 5000);
            })
            // End github info getter promise;
    }

    loadScripts();

}())
<|endoftext|>


<commit_before>var SerialPort = require('serialport');

function SerialRequestResponseTransport(options, protocol) {
    this.options = options;
    this.protocol = protocol;
    this.serialConnected = false;
    this.serialComm = undefined;

    this.requestTimer = null;
    this.stopRequests = false;
    this.currentData = null;
    this.messageTimeoutTimer = null;

    if (!this.options.transportSerialBaudrate) this.options.transportSerialBaudrate = 300;
    if (!this.options.transportSerialDataBits) this.options.transportSerialDataBits = 7;
    if (!this.options.transportSerialStopBits) this.options.transportSerialStopBits = 1;
    if (!this.options.transportSerialParity) this.options.transportSerialParity = 'even';
    if (!this.options.transportSerialMaxBufferSize) this.options.transportSerialMaxBufferSize = 300000;
    if (!this.options.transportSerialMessageTimeout) this.options.transportSerialMessageTimeout = 60000;
}

SerialRequestResponseTransport.prototype.init = function init() {
    this.protocol.initState(); // init State from protocol instance

    if (!this.serialComm) {
        this.serialComm = new SerialPort(this.options.transportSerialPort, {
            autoOpen:   false,
            baudrate:   this.options.transportSerialBaudrate,
            databits:   this.options.transportSerialDataBits,
            stopbits:   this.options.transportSerialStopBits,
            parity:     this.options.transportSerialParity,
            buffersize: 2048
        });
        if (this.options.debug === 2) this.options.logger('CREATE SERIALPORT: ' + this.options.transportSerialBaudrate + ' '  + this.options.transportSerialDataBits + ' '  + this.options.transportSerialStopBits + ' '  + this.options.transportSerialParity);
    }
    var self = this;
    this.serialComm.on('data', function (data) {
        if (! self.currentData) {
            self.currentData = data;
        }
        else {
            self.currentData = Buffer.concat([self.currentData, data]);
        }
        if (self.protocol.checkMessage(self.currentData)) {
            if (self.messageTimeoutTimer) clearTimeout(self.messageTimeoutTimer);

            self.currentData = self.protocol.handleMessage(self.currentData);
            if (!self.protocol.isProcessComplete()) {
                var messagesToSend = self.protocol.messagesToSend();
                if (self.options.debug === 2) self.options.logger('MESSAGES TO SEND: ' + messagesToSend);
                for (var i = 0; i< messagesToSend; i++) {
                    var nextData = self.protocol.getNextMessage(this);
                    if (typeof nextData === 'string' || typeof nextData === 'object') {
                        if (nextData.length > 0) this.write(nextData);
                        self.serialComm.flush();
                    }
                }
                if (self.options.debug === 2) self.options.logger('SET MESSAGE TIMEOUT TIMER: ' + self.options.transportSerialMessageTimeout);
                self.messageTimeoutTimer = setTimeout(function() {
                    self.handleSerialTimeout();
                }, self.options.transportSerialMessageTimeout);
            }
            if (self.protocol.isProcessComplete()) {
                if (self.messageTimeoutTimer) clearTimeout(self.messageTimeoutTimer);
                if (self.options.debug === 2) self.options.logger('SCHEDULE NEXT RUN IN ' + self.options.requestInterval + 's');
                this.close();
                if (!self.stopRequests) {
                    self.requestTimer = setTimeout(function() {
                        self.protocol.initState(); // reset Protocol instance because it will be a new session
                        self.process(); // and open port again
                    }, self.options.requestInterval*1000);
                }
            }
            if (self.options.debug === 2 && self.currentData) self.options.logger('REMAINING DATA AFTER MESSAGE HANDLING: ' + self.currentData.toString());
        }
        else if (self.currentData.length > self.options.transportSerialMaxBufferSize) {
            throw Error('Maximal Buffer size reached without matching message : ' + self.currentData.toString());
        }
    });

    this.serialComm.on('error', function (msg) {
        if (self.options.debug !== 0) self.options.logger('SERIALPORT ERROR: ' + msg);
        self.serialConnected = false;
        self.currentData = null;
    });

    this.serialComm.on('open', function () {
        if (self.options.debug === 2) self.options.logger('SERIALPORT OPEN');
        self.serialConnected = true;
        self.currentData = null;
    });

    this.serialComm.on('disconnect', function (err) {
        if (self.options.debug !== 0) self.options.logger('SERIALPORT DISCONNECTED: ' + err);
        self.serialConnected = false;
        self.currentData = null;
    });

    this.serialComm.on('close', function () {
        if (self.options.debug === 2) self.options.logger('SERIALPORT CLOSE');
        self.serialConnected = false;
        self.currentData = null;
        if (this.stopRequests) {
            self.serialComm.removeAllListeners();
        }
    });

    this.currentData = null;
};

SerialRequestResponseTransport.prototype.process = function process(callback) {
    this.protocol.initState();
    this.currentData = null;
    var self = this;
    this.serialComm.open(function() {
        if (self.options.debug === 2) self.options.logger('SERIALPORT RESET BAUDRATE TO ' + self.options.transportSerialBaudrate);
        self.serialComm.update({baudrate: self.options.transportSerialBaudrate}, function() {
            var messagesToSend = self.protocol.messagesToSend();
            if (self.options.debug === 2) self.options.logger('INITIAL MESSAGES TO SEND: ' + messagesToSend);
            for (var i = 0; i< messagesToSend; i++) {
                self.serialComm.write(self.protocol.getNextMessage());
                self.serialComm.flush();
            }
            if (self.messageTimeoutTimer) clearTimeout(self.messageTimeoutTimer);
            if (self.options.debug === 2) self.options.logger('SET MESSAGE TIMEOUT TIMER: ' + self.options.transportSerialMessageTimeout);
            self.messageTimeoutTimer = setTimeout(function() {
                self.handleSerialTimeout();
            }, self.options.transportSerialMessageTimeout);
        });
    });
};

SerialRequestResponseTransport.prototype.stop = function stop() {
    this.stopRequests = true;
    if (this.requestTimer) clearTimeout(this.requestTimer);
    if (this.messageTimeoutTimer) clearTimeout(this.messageTimeoutTimer);
    var self = this;
    if (this.serialComm) {
        this.serialComm.close(function() {
            self.serialComm = null;
        });
    }
};

SerialRequestResponseTransport.prototype.handleSerialTimeout = function handleSerialTimeout() {
    if (this.options.debug === 2) this.options.logger('MESSAGE TIMEOUT TRIGGERED');
    this.stop();
    throw new Error('No answer from Serial Device after last request.');
};

module.exports = SerialRequestResponseTransport;
<commit_msg>add debugging for ssend messages<commit_after>var SerialPort = require('serialport');

function SerialRequestResponseTransport(options, protocol) {
    this.options = options;
    this.protocol = protocol;
    this.serialConnected = false;
    this.serialComm = undefined;

    this.requestTimer = null;
    this.stopRequests = false;
    this.currentData = null;
    this.messageTimeoutTimer = null;

    if (!this.options.transportSerialBaudrate) this.options.transportSerialBaudrate = 300;
    if (!this.options.transportSerialDataBits) this.options.transportSerialDataBits = 7;
    if (!this.options.transportSerialStopBits) this.options.transportSerialStopBits = 1;
    if (!this.options.transportSerialParity) this.options.transportSerialParity = 'even';
    if (!this.options.transportSerialMaxBufferSize) this.options.transportSerialMaxBufferSize = 300000;
    if (!this.options.transportSerialMessageTimeout) this.options.transportSerialMessageTimeout = 60000;
}

SerialRequestResponseTransport.prototype.init = function init() {
    this.protocol.initState(); // init State from protocol instance

    if (!this.serialComm) {
        this.serialComm = new SerialPort(this.options.transportSerialPort, {
            autoOpen:   false,
            baudrate:   this.options.transportSerialBaudrate,
            databits:   this.options.transportSerialDataBits,
            stopbits:   this.options.transportSerialStopBits,
            parity:     this.options.transportSerialParity,
            buffersize: 2048
        });
        if (this.options.debug === 2) this.options.logger('CREATE SERIALPORT: ' + this.options.transportSerialBaudrate + ' '  + this.options.transportSerialDataBits + ' '  + this.options.transportSerialStopBits + ' '  + this.options.transportSerialParity);
    }
    var self = this;
    this.serialComm.on('data', function (data) {
        if (! self.currentData) {
            self.currentData = data;
        }
        else {
            self.currentData = Buffer.concat([self.currentData, data]);
        }
        if (self.protocol.checkMessage(self.currentData)) {
            if (self.messageTimeoutTimer) clearTimeout(self.messageTimeoutTimer);

            self.currentData = self.protocol.handleMessage(self.currentData);
            if (!self.protocol.isProcessComplete()) {
                var messagesToSend = self.protocol.messagesToSend();
                if (self.options.debug === 2) self.options.logger('MESSAGES TO SEND: ' + messagesToSend);
                for (var i = 0; i< messagesToSend; i++) {
                    var nextData = self.protocol.getNextMessage(this);
                    if (self.options.debug === 2) self.options.logger('TO SEND ' + i + ': ' + nextData);
                    if (typeof nextData === 'string' || typeof nextData === 'object') {
                        if (nextData.length > 0) this.write(nextData);
                        self.serialComm.flush();
                    }
                }
                if (self.options.debug === 2) self.options.logger('SET MESSAGE TIMEOUT TIMER: ' + self.options.transportSerialMessageTimeout);
                self.messageTimeoutTimer = setTimeout(function() {
                    self.handleSerialTimeout();
                }, self.options.transportSerialMessageTimeout);
            }
            if (self.protocol.isProcessComplete()) {
                if (self.messageTimeoutTimer) clearTimeout(self.messageTimeoutTimer);
                if (self.options.debug === 2) self.options.logger('SCHEDULE NEXT RUN IN ' + self.options.requestInterval + 's');
                this.close();
                if (!self.stopRequests) {
                    self.requestTimer = setTimeout(function() {
                        self.protocol.initState(); // reset Protocol instance because it will be a new session
                        self.process(); // and open port again
                    }, self.options.requestInterval*1000);
                }
            }
            if (self.options.debug === 2 && self.currentData) self.options.logger('REMAINING DATA AFTER MESSAGE HANDLING: ' + self.currentData.toString());
        }
        else if (self.currentData.length > self.options.transportSerialMaxBufferSize) {
            throw Error('Maximal Buffer size reached without matching message : ' + self.currentData.toString());
        }
    });

    this.serialComm.on('error', function (msg) {
        if (self.options.debug !== 0) self.options.logger('SERIALPORT ERROR: ' + msg);
        self.serialConnected = false;
        self.currentData = null;
    });

    this.serialComm.on('open', function () {
        if (self.options.debug === 2) self.options.logger('SERIALPORT OPEN');
        self.serialConnected = true;
        self.currentData = null;
    });

    this.serialComm.on('disconnect', function (err) {
        if (self.options.debug !== 0) self.options.logger('SERIALPORT DISCONNECTED: ' + err);
        self.serialConnected = false;
        self.currentData = null;
    });

    this.serialComm.on('close', function () {
        if (self.options.debug === 2) self.options.logger('SERIALPORT CLOSE');
        self.serialConnected = false;
        self.currentData = null;
        if (this.stopRequests) {
            self.serialComm.removeAllListeners();
        }
    });

    this.currentData = null;
};

SerialRequestResponseTransport.prototype.process = function process(callback) {
    this.protocol.initState();
    this.currentData = null;
    var self = this;
    this.serialComm.open(function() {
        if (self.options.debug === 2) self.options.logger('SERIALPORT RESET BAUDRATE TO ' + self.options.transportSerialBaudrate);
        self.serialComm.update({baudrate: self.options.transportSerialBaudrate}, function() {
            var messagesToSend = self.protocol.messagesToSend();
            if (self.options.debug === 2) self.options.logger('INITIAL MESSAGES TO SEND: ' + messagesToSend);
            for (var i = 0; i< messagesToSend; i++) {
                self.serialComm.write(self.protocol.getNextMessage());
                self.serialComm.flush();
            }
            if (self.messageTimeoutTimer) clearTimeout(self.messageTimeoutTimer);
            if (self.options.debug === 2) self.options.logger('SET MESSAGE TIMEOUT TIMER: ' + self.options.transportSerialMessageTimeout);
            self.messageTimeoutTimer = setTimeout(function() {
                self.handleSerialTimeout();
            }, self.options.transportSerialMessageTimeout);
        });
    });
};

SerialRequestResponseTransport.prototype.stop = function stop() {
    this.stopRequests = true;
    if (this.requestTimer) clearTimeout(this.requestTimer);
    if (this.messageTimeoutTimer) clearTimeout(this.messageTimeoutTimer);
    var self = this;
    if (this.serialComm) {
        this.serialComm.close(function() {
            self.serialComm = null;
        });
    }
};

SerialRequestResponseTransport.prototype.handleSerialTimeout = function handleSerialTimeout() {
    if (this.options.debug === 2) this.options.logger('MESSAGE TIMEOUT TRIGGERED');
    this.stop();
    throw new Error('No answer from Serial Device after last request.');
};

module.exports = SerialRequestResponseTransport;
<|endoftext|>


<commit_before>(function($,v){
v=xe.getApp('validator')[0];if(!v)return;

v.cast('ADD_FILTER',['condition', {'greeting1':{required:true},'greeting2':{'if':[{test:'$greeting1 == \'Hello\'', attr:'required', value:'true'}]}}]);
v.cast('ADD_MESSAGE',['isnull','%s 값은 필수입니다.']);
v.cast('ADD_MESSAGE',['outofrange','%s의 글자 수를 맞추어 주세요.']);
v.cast('ADD_MESSAGE',['equalto','%s이(가) 잘못되었습니다.']);
v.cast('ADD_MESSAGE',['invalid','%s의 값이 올바르지 않습니다.']);
v.cast('ADD_MESSAGE',['invalid_email','%s의 값은 올바른 메일 주소가 아닙니다.']);
v.cast('ADD_MESSAGE',['invalid_userid','%s의 값은 영문, 숫자, _만 가능하며 첫 글자는 영문이어야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_user_id','%s의 값은 영문, 숫자, _만 가능하며 첫 글자는 영문이어야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_homepage','%s의 형식이 잘못되었습니다.(예: https://www.rhymix.org/)']);
v.cast('ADD_MESSAGE',['invalid_url','%s의 형식이 잘못되었습니다.(예: https://www.rhymix.org/)']);
v.cast('ADD_MESSAGE',['invalid_korean','%s의 형식이 잘못되었습니다. 한글로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_korean_number','%s의 형식이 잘못되었습니다. 한글과 숫자로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_alpha','%s의 형식이 잘못되었습니다. 영문으로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_alpha_number','%s의 형식이 잘못되었습니다. 영문과 숫자로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_mid','%s의 형식이 잘못되었습니다. 첫 글자는 영문으로 시작해야 하며 \'영문+숫자+_\'로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_number','%s의 형식이 잘못되었습니다. 숫자로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_extension','%s의 형식이 잘못되었습니다. *.* 나 *.jpg;*.gif; 처럼 입력해야 합니다.']);
})(jQuery);
<commit_msg>Fix unit test for Validator class<commit_after>(function($,v){
v=xe.getApp('validator')[0];if(!v)return;

v.cast('ADD_FILTER',['condition', {'greeting1':{required:true},'greeting2':{'if':[{test:'$greeting1 == \'Hello\'', attr:'required', value:'true'}]}}]);
v.cast('ADD_MESSAGE',['isnull','%s 값은 필수입니다.']);
v.cast('ADD_MESSAGE',['outofrange','%s의 글자 수를 맞추어 주세요.']);
v.cast('ADD_MESSAGE',['equalto','%s이(가) 잘못되었습니다.']);
v.cast('ADD_MESSAGE',['invalid','%s의 값이 올바르지 않습니다.']);
v.cast('ADD_MESSAGE',['invalid_email','%s의 값은 올바른 메일 주소가 아닙니다.']);
v.cast('ADD_MESSAGE',['invalid_userid','%s의 값은 영문, 숫자, _만 가능하며 첫 글자는 영문이어야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_user_id','%s의 값은 영문, 숫자, _만 가능하며 첫 글자는 영문이어야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_homepage','%s의 형식이 잘못되었습니다.(예: https://www.rhymix.org/)']);
v.cast('ADD_MESSAGE',['invalid_url','%s의 형식이 잘못되었습니다.(예: https://www.rhymix.org/)']);
v.cast('ADD_MESSAGE',['invalid_korean','%s의 형식이 잘못되었습니다. 한글로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_korean_number','%s의 형식이 잘못되었습니다. 한글과 숫자로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_alpha','%s의 형식이 잘못되었습니다. 영문으로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_alpha_number','%s의 형식이 잘못되었습니다. 영문과 숫자로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_mid','%s의 형식이 잘못되었습니다. 첫 글자는 영문으로 시작해야 하며 \'영문+숫자+_\'로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_number','%s의 형식이 잘못되었습니다. 숫자로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_float','%s의 형식이 잘못되었습니다. 숫자로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_extension','%s의 형식이 잘못되었습니다. *.* 나 *.jpg;*.gif; 처럼 입력해야 합니다.']);
})(jQuery);
<|endoftext|>


<commit_before>'use strict';

var path = require('path'),
  async = require('async'),
  traceService = require('../services/trace'),
  transportEventService = require('../services/transport_event'),
  orderService = require('../services/order');

function getOrderTraces(orderId, callback) {
  orderService.getDriverChildrenOrders(orderId, function (err, driverOrders) {
    if (err) {
      return callback(err);
    }
    traceService.getTracesByOrders(driverOrders)
      .then(function (result) {
        return callback(null, result);
      }, function (err) {
        return callback(err);
      });
  });

}

exports.getOrderDriverTraces = function (req, res, next) {
  var curentOrder = req.currentOrder;
  getOrderTraces(curentOrder._id, function (err, driverTraces) {
    if (err) {
      return res.send(err);
    }
    return res.send(driverTraces);
  });
};

exports.getSingleOrderInfo = function (req, res, next) {
  var order = req.currentOrder;
  orderService.getOrderAssignedInfoByOrderId(order, function (err, companyOrders) {
    if (err) {
      return res.send(err);
    }
    return res.send({currentOrder: order, assignedCompanyOrders: companyOrders});
  });
};

exports.getSingleOrderEvent = function (req, res, next) {
  var order = req.currentOrder;

  orderService.getDriverChildrenOrderIds(order._id, function (err, driverOrderIds) {
    if (err) {
      return res.send(err);
    }

    transportEventService.getEventByOrder(driverOrderIds, function (err, transportEvents) {
      if (err) {
        return res.send(err);
      }

      return res.send({
        order: {
          createUserNickname: order.create_user.nickname,
          createUserPhone: order.create_user.phone,
          createUsername: order.create_user.username,
          create_time: order.created,
          pickup_time: order.pickup_time,
          delivery_time: order.delivery_time
        }, events: transportEvents
      });
    });
  });
};
exports.getSingleOrderTrace = function (req, res, next) {
  var order = req.currentOrder;

  orderService.getDriverChildrenOrders(order._id, function (err, driverOrders) {
    if (err) {
      return res.send(err);
    }
    traceService.getTracesByOrders(driverOrders)
      .then(function (result) {
        return res.send(result);
      }, function (err) {
        return res.send(err);
      });
  });
};<commit_msg>Update order single event<commit_after>'use strict';

var path = require('path'),
  async = require('async'),
  traceService = require('../services/trace'),
  transportEventService = require('../services/transport_event'),
  orderService = require('../services/order');

function getOrderTraces(orderId, callback) {
  orderService.getDriverChildrenOrders(orderId, function (err, driverOrders) {
    if (err) {
      return callback(err);
    }
    traceService.getTracesByOrders(driverOrders)
      .then(function (result) {
        return callback(null, result);
      }, function (err) {
        return callback(err);
      });
  });

}

exports.getOrderDriverTraces = function (req, res, next) {
  var curentOrder = req.currentOrder;
  getOrderTraces(curentOrder._id, function (err, driverTraces) {
    if (err) {
      return res.send(err);
    }
    return res.send(driverTraces);
  });
};

exports.getSingleOrderInfo = function (req, res, next) {
  var order = req.currentOrder;
  orderService.getOrderAssignedInfoByOrderId(order, function (err, companyOrders) {
    if (err) {
      return res.send(err);
    }
    return res.send({currentOrder: order, assignedCompanyOrders: companyOrders});
  });
};

exports.getSingleOrderEvent = function (req, res, next) {
  var order = req.currentOrder;

  transportEventService.getEventByOrder([req.currentOrder._id], function (err, transportEvents) {
    if (err) {
      return res.send(err);
    }

    return res.send({
      order: {
        createUserNickname: order.create_user.nickname,
        createUserPhone: order.create_user.phone,
        createUsername: order.create_user.username,
        create_time: order.created,
        pickup_time: order.pickup_time,
        delivery_time: order.delivery_time
      }, events: transportEvents
    });
  });
};
exports.getSingleOrderTrace = function (req, res, next) {
  var order = req.currentOrder;

  orderService.getDriverChildrenOrders(order._id, function (err, driverOrders) {
    if (err) {
      return res.send(err);
    }
    traceService.getTracesByOrders(driverOrders)
      .then(function (result) {
        return res.send(result);
      }, function (err) {
        return res.send(err);
      });
  });
};<|endoftext|>


<commit_before>
var Calendar = FC.Calendar = Class.extend(EmitterMixin, {

	view: null, // current View object
	viewsByType: null, // holds all instantiated view instances, current or not
	currentDate: null, // unzoned moment. private (public API should use getDate instead)
	theme: null,
	loadingLevel: 0, // number of simultaneous loading tasks

	constructor: function(el, overrides) {

		// declare the current calendar instance relies on GlobalEmitter. needed for garbage collection.
		// unneeded() is called in destroy.
		GlobalEmitter.needed();

		this.el = el;
		this.viewsByType = {};
		this.viewSpecCache = {};

		this.initOptionsInternals(overrides);
		this.initMomentInternals(); // needs to happen after options hash initialized
		this.initCurrentDate();
		this.initEventManager();

		EventManager.call(this); // needs options immediately
	},

	// Public API
	// -----------------------------------------------------------------------------------------------------------------

	getView: function() {
		return this.view;
	},

	publiclyTrigger: function(name, triggerInfo) {
		var optHandler = this.opt(name);
		var context;
		var args;

		if ($.isPlainObject(triggerInfo)) {
			context = triggerInfo.context;
			args = triggerInfo.args;
		}
		else if ($.isArray(triggerInfo)) {
			args = triggerInfo;
		}

		if (context == null) {
			context = this.el[0]; // fallback context
		}

		if (!args) {
			args = [];
		}

		this.triggerWith(name, context, args); // Emitter's method

		if (optHandler) {
			return optHandler.apply(context, args);
		}
	},

	hasPublicHandlers: function(name) {
		return this.hasHandlers(name) ||
			this.opt(name); // handler specified in options
	},

	// View
	// -----------------------------------------------------------------------------------------------------------------

	// Given a view name for a custom view or a standard view, creates a ready-to-go View object
	instantiateView: function(viewType) {
		var spec = this.getViewSpec(viewType);

		return new spec['class'](this, spec);
	},

	// Returns a boolean about whether the view is okay to instantiate at some point
	isValidViewType: function(viewType) {
		return Boolean(this.getViewSpec(viewType));
	},

	changeView: function(viewName, dateOrRange) {

		if (dateOrRange) {

			if (dateOrRange.start && dateOrRange.end) { // a range
				this.recordOptionOverrides({ // will not rerender
					visibleRange: dateOrRange
				});
			}
			else { // a date
				this.currentDate = this.moment(dateOrRange).stripZone(); // just like gotoDate
			}
		}

		this.renderView(viewName);
	},

	// Forces navigation to a view for the given date.
	// `viewType` can be a specific view name or a generic one like "week" or "day".
	zoomTo: function(newDate, viewType) {
		var spec;

		viewType = viewType || 'day'; // day is default zoom
		spec = this.getViewSpec(viewType) || this.getUnitViewSpec(viewType);

		this.currentDate = newDate.clone();
		this.renderView(spec ? spec.type : null);
	},

	// Current Date
	// -----------------------------------------------------------------------------------------------------------------

	initCurrentDate: function() {
		var defaultDateInput = this.opt('defaultDate');

		// compute the initial ambig-timezone date
		if (defaultDateInput != null) {
			this.currentDate = this.moment(defaultDateInput).stripZone();
		}
		else {
			this.currentDate = this.getNow(); // getNow already returns unzoned
		}
	},

	reportViewDatesChanged: function(view, dateProfile) {
		this.currentDate = dateProfile.date; // might have been constrained by view dates
		this.setToolbarsTitle(view.title);
		this.updateToolbarButtons();
	},

	prev: function() {
		var prevInfo = this.view.buildPrevDateProfile(this.currentDate);

		if (prevInfo.isValid) {
			this.currentDate = prevInfo.date;
			this.renderView();
		}
	},

	next: function() {
		var nextInfo = this.view.buildNextDateProfile(this.currentDate);

		if (nextInfo.isValid) {
			this.currentDate = nextInfo.date;
			this.renderView();
		}
	},

	prevYear: function() {
		this.currentDate.add(-1, 'years');
		this.renderView();
	},

	nextYear: function() {
		this.currentDate.add(1, 'years');
		this.renderView();
	},

	today: function() {
		this.currentDate = this.getNow(); // should deny like prev/next?
		this.renderView();
	},

	gotoDate: function(zonedDateInput) {
		this.currentDate = this.moment(zonedDateInput).stripZone();
		this.renderView();
	},

	incrementDate: function(delta) {
		this.currentDate.add(moment.duration(delta));
		this.renderView();
	},

	// for external API
	getDate: function() {
		return this.applyTimezone(this.currentDate); // infuse the calendar's timezone
	},

	// Loading Triggering
	// -----------------------------------------------------------------------------------------------------------------

	// Should be called when any type of async data fetching begins
	pushLoading: function() {
		if (!(this.loadingLevel++)) {
			this.publiclyTrigger('loading', [ true, this.view ]);
		}
	},

	// Should be called when any type of async data fetching completes
	popLoading: function() {
		if (!(--this.loadingLevel)) {
			this.publiclyTrigger('loading', [ false, this.view ]);
		}
	},

	// Selection
	// -----------------------------------------------------------------------------------------------------------------

	// this public method receives start/end dates in any format, with any timezone
	select: function(zonedStartInput, zonedEndInput) {
		this.view.select(
			this.buildSelectFootprint.apply(this, arguments)
		);
	},

	unselect: function() { // safe to be called before renderView
		if (this.view) {
			this.view.unselect();
		}
	},

	// Given arguments to the select method in the API, returns a span (unzoned start/end and other info)
	buildSelectFootprint: function(zonedStartInput, zonedEndInput) {
		var start = this.moment(zonedStartInput).stripZone();
		var end;

		if (zonedEndInput) {
			end = this.moment(zonedEndInput).stripZone();
		}
		else if (start.hasTime()) {
			end = start.clone().add(this.defaultTimedEventDuration);
		}
		else {
			end = start.clone().add(this.defaultAllDayEventDuration);
		}

		return new ComponentFootprint(
			new UnzonedRange(start, end),
			!start.hasTime()
		);
	},

	// Misc
	// -----------------------------------------------------------------------------------------------------------------

	// will return `null` if invalid range
	parseUnzonedRange: function(rangeInput) {
		var start = null;
		var end = null;

		if (rangeInput.start) {
			start = this.moment(rangeInput.start).stripZone();
		}

		if (rangeInput.end) {
			end = this.moment(rangeInput.end).stripZone();
		}

		if (!start && !end) {
			return null;
		}

		if (start && end && end.isBefore(start)) {
			return null;
		}

		return new UnzonedRange(start, end);
	},

	rerenderEvents: function() { // API method. destroys old events if previously rendered.
		if (this.elementVisible()) {
			this.view.flash('displayingEvents');
		}
	},

	initEventManager: function() {
		var _this = this;
		var eventManager = new EventManager(this);
		var rawSources = this.opt('eventSources') || [];
		var singleRawSource = this.opt('events');

		this.eventManager = eventManager;

		if (singleRawSource) {
			rawSources.unshift(singleRawSource);
		}

		eventManager.on('release', function(eventsPayload) {
			_this.trigger('eventsReset', eventsPayload);
		});

		eventManager.freeze();

		rawSources.forEach(function(rawSource) {
			var source = EventSourceParser.parse(rawSource, _this);

			if (source) {
				eventManager.addSource(source);
			}
		});

		eventManager.thaw();
	},

	requestEvents: function(start, end) {
		return this.eventManager.requestEvents(
			start,
			end,
			this.opt('timezone'),
			this.opt('lazyFetching')
		);
	}

});
<commit_msg>remove unnecessary EventManager init!?<commit_after>
var Calendar = FC.Calendar = Class.extend(EmitterMixin, {

	view: null, // current View object
	viewsByType: null, // holds all instantiated view instances, current or not
	currentDate: null, // unzoned moment. private (public API should use getDate instead)
	theme: null,
	loadingLevel: 0, // number of simultaneous loading tasks

	constructor: function(el, overrides) {

		// declare the current calendar instance relies on GlobalEmitter. needed for garbage collection.
		// unneeded() is called in destroy.
		GlobalEmitter.needed();

		this.el = el;
		this.viewsByType = {};
		this.viewSpecCache = {};

		this.initOptionsInternals(overrides);
		this.initMomentInternals(); // needs to happen after options hash initialized
		this.initCurrentDate();
		this.initEventManager();
	},

	// Public API
	// -----------------------------------------------------------------------------------------------------------------

	getView: function() {
		return this.view;
	},

	publiclyTrigger: function(name, triggerInfo) {
		var optHandler = this.opt(name);
		var context;
		var args;

		if ($.isPlainObject(triggerInfo)) {
			context = triggerInfo.context;
			args = triggerInfo.args;
		}
		else if ($.isArray(triggerInfo)) {
			args = triggerInfo;
		}

		if (context == null) {
			context = this.el[0]; // fallback context
		}

		if (!args) {
			args = [];
		}

		this.triggerWith(name, context, args); // Emitter's method

		if (optHandler) {
			return optHandler.apply(context, args);
		}
	},

	hasPublicHandlers: function(name) {
		return this.hasHandlers(name) ||
			this.opt(name); // handler specified in options
	},

	// View
	// -----------------------------------------------------------------------------------------------------------------

	// Given a view name for a custom view or a standard view, creates a ready-to-go View object
	instantiateView: function(viewType) {
		var spec = this.getViewSpec(viewType);

		return new spec['class'](this, spec);
	},

	// Returns a boolean about whether the view is okay to instantiate at some point
	isValidViewType: function(viewType) {
		return Boolean(this.getViewSpec(viewType));
	},

	changeView: function(viewName, dateOrRange) {

		if (dateOrRange) {

			if (dateOrRange.start && dateOrRange.end) { // a range
				this.recordOptionOverrides({ // will not rerender
					visibleRange: dateOrRange
				});
			}
			else { // a date
				this.currentDate = this.moment(dateOrRange).stripZone(); // just like gotoDate
			}
		}

		this.renderView(viewName);
	},

	// Forces navigation to a view for the given date.
	// `viewType` can be a specific view name or a generic one like "week" or "day".
	zoomTo: function(newDate, viewType) {
		var spec;

		viewType = viewType || 'day'; // day is default zoom
		spec = this.getViewSpec(viewType) || this.getUnitViewSpec(viewType);

		this.currentDate = newDate.clone();
		this.renderView(spec ? spec.type : null);
	},

	// Current Date
	// -----------------------------------------------------------------------------------------------------------------

	initCurrentDate: function() {
		var defaultDateInput = this.opt('defaultDate');

		// compute the initial ambig-timezone date
		if (defaultDateInput != null) {
			this.currentDate = this.moment(defaultDateInput).stripZone();
		}
		else {
			this.currentDate = this.getNow(); // getNow already returns unzoned
		}
	},

	reportViewDatesChanged: function(view, dateProfile) {
		this.currentDate = dateProfile.date; // might have been constrained by view dates
		this.setToolbarsTitle(view.title);
		this.updateToolbarButtons();
	},

	prev: function() {
		var prevInfo = this.view.buildPrevDateProfile(this.currentDate);

		if (prevInfo.isValid) {
			this.currentDate = prevInfo.date;
			this.renderView();
		}
	},

	next: function() {
		var nextInfo = this.view.buildNextDateProfile(this.currentDate);

		if (nextInfo.isValid) {
			this.currentDate = nextInfo.date;
			this.renderView();
		}
	},

	prevYear: function() {
		this.currentDate.add(-1, 'years');
		this.renderView();
	},

	nextYear: function() {
		this.currentDate.add(1, 'years');
		this.renderView();
	},

	today: function() {
		this.currentDate = this.getNow(); // should deny like prev/next?
		this.renderView();
	},

	gotoDate: function(zonedDateInput) {
		this.currentDate = this.moment(zonedDateInput).stripZone();
		this.renderView();
	},

	incrementDate: function(delta) {
		this.currentDate.add(moment.duration(delta));
		this.renderView();
	},

	// for external API
	getDate: function() {
		return this.applyTimezone(this.currentDate); // infuse the calendar's timezone
	},

	// Loading Triggering
	// -----------------------------------------------------------------------------------------------------------------

	// Should be called when any type of async data fetching begins
	pushLoading: function() {
		if (!(this.loadingLevel++)) {
			this.publiclyTrigger('loading', [ true, this.view ]);
		}
	},

	// Should be called when any type of async data fetching completes
	popLoading: function() {
		if (!(--this.loadingLevel)) {
			this.publiclyTrigger('loading', [ false, this.view ]);
		}
	},

	// Selection
	// -----------------------------------------------------------------------------------------------------------------

	// this public method receives start/end dates in any format, with any timezone
	select: function(zonedStartInput, zonedEndInput) {
		this.view.select(
			this.buildSelectFootprint.apply(this, arguments)
		);
	},

	unselect: function() { // safe to be called before renderView
		if (this.view) {
			this.view.unselect();
		}
	},

	// Given arguments to the select method in the API, returns a span (unzoned start/end and other info)
	buildSelectFootprint: function(zonedStartInput, zonedEndInput) {
		var start = this.moment(zonedStartInput).stripZone();
		var end;

		if (zonedEndInput) {
			end = this.moment(zonedEndInput).stripZone();
		}
		else if (start.hasTime()) {
			end = start.clone().add(this.defaultTimedEventDuration);
		}
		else {
			end = start.clone().add(this.defaultAllDayEventDuration);
		}

		return new ComponentFootprint(
			new UnzonedRange(start, end),
			!start.hasTime()
		);
	},

	// Misc
	// -----------------------------------------------------------------------------------------------------------------

	// will return `null` if invalid range
	parseUnzonedRange: function(rangeInput) {
		var start = null;
		var end = null;

		if (rangeInput.start) {
			start = this.moment(rangeInput.start).stripZone();
		}

		if (rangeInput.end) {
			end = this.moment(rangeInput.end).stripZone();
		}

		if (!start && !end) {
			return null;
		}

		if (start && end && end.isBefore(start)) {
			return null;
		}

		return new UnzonedRange(start, end);
	},

	rerenderEvents: function() { // API method. destroys old events if previously rendered.
		if (this.elementVisible()) {
			this.view.flash('displayingEvents');
		}
	},

	initEventManager: function() {
		var _this = this;
		var eventManager = new EventManager(this);
		var rawSources = this.opt('eventSources') || [];
		var singleRawSource = this.opt('events');

		this.eventManager = eventManager;

		if (singleRawSource) {
			rawSources.unshift(singleRawSource);
		}

		eventManager.on('release', function(eventsPayload) {
			_this.trigger('eventsReset', eventsPayload);
		});

		eventManager.freeze();

		rawSources.forEach(function(rawSource) {
			var source = EventSourceParser.parse(rawSource, _this);

			if (source) {
				eventManager.addSource(source);
			}
		});

		eventManager.thaw();
	},

	requestEvents: function(start, end) {
		return this.eventManager.requestEvents(
			start,
			end,
			this.opt('timezone'),
			this.opt('lazyFetching')
		);
	}

});
<|endoftext|>


<commit_before>ace.define("ace/snippets/csharp",["require","exports","module"], function(require, exports, module) {
"use strict";

exports.snippetText =undefined;
exports.scope = "csharp";

});
<commit_msg>Update tmp/bower_components/ace-builds/src-noconflict/snippets/csharp.js<commit_after><|endoftext|>