<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import Timer from '../Timer';
import ButtonsGroup from '../ButtonsGroup';
import Spinner from '../../layout/Spinner';
import { formatDate, formatTime } from '../../../helpers';
import Input from './Input';

class Task extends React.Component {
  state = {
    editName: '',
    showInput: false,
    showTimer: false,
    spinner: false,
    categoryID: '',
  };

  componentWillMount() {
    this.setState({ categoryID: this.props.projectId });
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps) {
      this.setState({ spinner: false });
    }
  }

  showTimer = () => {
    this.setState(state => ({
      showTimer: !state.showTimer,
    }));
  };

  handleNameInput = e => {
    this.setState({ editName: e.target.value });
  };

  handleShowInput = name => {
    this.setState({
      showInput: !this.state.showInput,
      editName: name,
    });
  };

  handleRenaming = (id, name, categoryID) => {
    this.props.handleRename(id, name, categoryID);
    this.setState({
      showInput: false,
      spinner: true,
    });
  };

  handleEnterButton = (id, name) => {
    this.props.handleRename(id, name);
    this.setState({
      showInput: false,
      spinner: true,
    });
  };

  changeSelect = e => {
    this.setState({
      categoryID: e.target.value,
    });
  };

  shouldShowTimer = () => {
    const { id, name, projectId, handleAddingTimeLog } = this.props;
    const myProps = Object.assign(
      {},
      { id, name, projectId, handleAddingTimeLog }
    );
    if (this.state.showTimer) {
      return <Timer key={`timer${id}`} {...myProps} />;
    }
    return null;
  };

  shouldShowInput = () => {
    const { editName, categoryID } = this.state;
    const inputProps = Object.assign({}, this.props, {
      editName,
      categoryID,
      changeSelect: this.changeSelect,
      handleNameInput: this.handleNameInput,
    });
    if (this.state.showInput) {
      return <Input {...inputProps} />;
    }
    return null;
  };

  showDateString = () => {
    const newDate = this.props.updated ? formatDate(this.props.updated) : '';
    const dateString = this.props.updated ? 'Done:' : '';
    if (dateString !== '') {
      return (

          {dateString}
          {newDate}

      );
    }
    return null;
  };

  render() {
    const { editName, showInput, categoryID } = this.state;
    const { id, name, done } = this.props;

    const doneButtonValue = done ? 'undone' : 'done';
    const doneClass = done ? 'tasks__list-item--done' : 'tasks__list-item';
    const hideOrNot = showInput ? 'none' : '';

    if (this.state.spinner) {
      return <Spinner />;
    }

    return (
      <li className={`${doneClass}`}>

          {name}

            {formatTime(this.props.timeSpent)}

        {this.showDateString()}
        {this.shouldShowInput()}

        <ButtonsGroup
          {...this.props}
          {...this.state}
          showTimer={this.showTimer}
          handleShowInput={this.handleShowInput}
          handleRenaming={() => this.handleRenaming(id, editName, categoryID)}
          doneButtonValue={doneButtonValue}
        />
        {this.shouldShowTimer()}

    );
  }
}

Task.defaultProps = {
  updated: undefined,
  projectId: '',
  handleAddingTimeLog: null,
};

Task.propTypes = {
  name: PropTypes.string.isRequired,
  handleDelete: PropTypes.func.isRequired,
  handleRename: PropTypes.func.isRequired,
  taskDone: PropTypes.func.isRequired,
  done: PropTypes.bool.isRequired,
  id: PropTypes.string.isRequired,
  updated: PropTypes.string,
  timeSpent: PropTypes.number.isRequired,
  projects: PropTypes.array.isRequired,
  handleAddingTimeLog: PropTypes.func,
  projectId: PropTypes.string,
};

export default Task;
<commit_msg>bugfix: wrong prop names<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import Timer from '../Timer';
import ButtonsGroup from '../ButtonsGroup';
import Spinner from '../../layout/Spinner';
import { formatDate, formatTime } from '../../../helpers';
import Input from './Input';

class Task extends React.Component {
  state = {
    editName: '',
    showInput: false,
    showTimer: false,
    spinner: false,
    categoryID: '',
  };

  componentWillMount() {
    this.setState({ categoryID: this.props.projectId });
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps) {
      this.setState({ spinner: false });
    }
  }

  showTimer = () => {
    this.setState(state => ({
      showTimer: !state.showTimer,
    }));
  };

  handleNameInput = e => {
    this.setState({ editName: e.target.value });
  };

  handleShowInput = name => {
    this.setState({
      showInput: !this.state.showInput,
      editName: name,
    });
  };

  handleRenaming = (id, name, categoryID) => {
    this.props.handleRename(id, name, categoryID);
    this.setState({
      showInput: false,
      spinner: true,
    });
  };

  handleEnterButton = (id, name) => {
    this.props.handleRename(id, name);
    this.setState({
      showInput: false,
      spinner: true,
    });
  };

  changeSelect = e => {
    this.setState({
      categoryID: e.target.value,
    });
  };

  shouldShowTimer = () => {
    const { id, name, projectId, handleAddingTimeLog } = this.props;
    const myProps = Object.assign(
      {},
      { id, taskName: name, project: projectId, handleAddingTimeLog }
    );
    if (this.state.showTimer) {
      return <Timer key={`timer${id}`} {...myProps} />;
    }
    return null;
  };

  shouldShowInput = () => {
    const { editName, categoryID } = this.state;
    const inputProps = Object.assign({}, this.props, {
      editName,
      categoryID,
      changeSelect: this.changeSelect,
      handleNameInput: this.handleNameInput,
    });
    if (this.state.showInput) {
      return <Input {...inputProps} />;
    }
    return null;
  };

  showDateString = () => {
    const newDate = this.props.updated ? formatDate(this.props.updated) : '';
    const dateString = this.props.updated ? 'Done:' : '';
    if (dateString !== '') {
      return (

          {dateString}
          {newDate}

      );
    }
    return null;
  };

  render() {
    const { editName, showInput, categoryID } = this.state;
    const { id, name, done } = this.props;

    const doneButtonValue = done ? 'undone' : 'done';
    const doneClass = done ? 'tasks__list-item--done' : 'tasks__list-item';
    const hideOrNot = showInput ? 'none' : '';

    if (this.state.spinner) {
      return <Spinner />;
    }

    return (
      <li className={`${doneClass}`}>

          {name}

            {formatTime(this.props.timeSpent)}

        {this.showDateString()}
        {this.shouldShowInput()}

        <ButtonsGroup
          {...this.props}
          {...this.state}
          showTimer={this.showTimer}
          handleShowInput={this.handleShowInput}
          handleRenaming={() => this.handleRenaming(id, editName, categoryID)}
          doneButtonValue={doneButtonValue}
        />
        {this.shouldShowTimer()}

    );
  }
}

Task.defaultProps = {
  updated: undefined,
  projectId: '',
  handleAddingTimeLog: null,
};

Task.propTypes = {
  name: PropTypes.string.isRequired,
  handleDelete: PropTypes.func.isRequired,
  handleRename: PropTypes.func.isRequired,
  taskDone: PropTypes.func.isRequired,
  done: PropTypes.bool.isRequired,
  id: PropTypes.string.isRequired,
  updated: PropTypes.string,
  timeSpent: PropTypes.number.isRequired,
  projects: PropTypes.array.isRequired,
  handleAddingTimeLog: PropTypes.func,
  projectId: PropTypes.string,
};

export default Task;
<|endoftext|>


<commit_before>app.controller('AuthCtrl', function ($scope, $http, $element, authService, close) {
  $scope.action = 'Log in';
  $scope.signupText = false;
  $scope.isLoading = false;

  function closeModal(rval) {
    //  Manually hide the modal using bootstrap.
    $element.modal('hide');
    //  Now close as normal, but give 500ms for bootstrap to animate
    close(rval, 500);
  };

  $scope.toggleAction=function(){
    if($scope.action ==='Log in'){
      $scope.action = 'Sign up';
    }
    else{
      $scope.action ='Log in'
    }
  };

  $scope.submit=function(){
    $scope.isLoading = true;
    if($scope.action === 'Log in'){
      authService.logIn($scope.auth)
      .then(function(session){
          console.log(session);
          $scope.isLoading = false;
          closeModal(session);
      },function(error){
        $scope.isLoading = false;
        $scope.errormessage=error;
      });
    }
    else{
      authService.signUp($scope.auth)
      .then(function(session){
          $scope.isLoading = false;
          $scope.signupText = true;
      },function(error){
        $scope.isLoading = false;
        $scope.errormessage=error;
      });
    }
  }
});

app.directive("compareTo", function() {
  return {
      require: "ngModel",
      scope: {
          otherModelValue: "=compareTo"
      },
      link: function(scope, element, attributes, ctrl) {
          ctrl.$validators.compareTo = function(modelValue) {
              return modelValue === scope.otherModelValue;
          };
      }
  };
});
<commit_msg>stop logging session key<commit_after>app.controller('AuthCtrl', function ($scope, $http, $element, authService, close) {
  $scope.action = 'Log in';
  $scope.signupText = false;
  $scope.isLoading = false;

  function closeModal(rval) {
    //  Manually hide the modal using bootstrap.
    $element.modal('hide');
    //  Now close as normal, but give 500ms for bootstrap to animate
    close(rval, 500);
  };

  $scope.toggleAction=function(){
    if($scope.action ==='Log in'){
      $scope.action = 'Sign up';
    }
    else{
      $scope.action ='Log in'
    }
  };

  $scope.submit=function(){
    $scope.isLoading = true;
    if($scope.action === 'Log in'){
      authService.logIn($scope.auth)
      .then(function(session){
          $scope.isLoading = false;
          closeModal(session);
      },function(error){
        $scope.isLoading = false;
        $scope.errormessage=error;
      });
    }
    else{
      authService.signUp($scope.auth)
      .then(function(session){
          $scope.isLoading = false;
          $scope.signupText = true;
      },function(error){
        $scope.isLoading = false;
        $scope.errormessage=error;
      });
    }
  }
});

app.directive("compareTo", function() {
  return {
      require: "ngModel",
      scope: {
          otherModelValue: "=compareTo"
      },
      link: function(scope, element, attributes, ctrl) {
          ctrl.$validators.compareTo = function(modelValue) {
              return modelValue === scope.otherModelValue;
          };
      }
  };
});
<|endoftext|>


<commit_before>app.controller('UserCtrl', function ($scope, $http, ModalService, authService, mediaService, toastr) {
  $scope.expand = false;
  $scope.searchResults = [];
  $scope.isSearching = false;
  $scope.isLoading = false;
  $scope.playlists={
    'Default':{
      Name:"Default", Active:true, Contents:[]
    }
  };
  $scope.playlistName="Default";
  $scope.inQueue=false;
  $scope.queue =[];
  $scope.isAdding = false;
  $scope.userData;
  fetch_playlist();

  function fetch_playlist(){
    if(!authService.getUser()){
      return;
    }
    $http.get('/api/playlists').then(function(res){
      var data = res.data;
      if(data.Success){
        $scope.playlists = data.Playlists;
        for(pl in data.Playlists){
          if(data.Playlists[pl].Active){
            $scope.playlistName = data.Playlists[pl].Name;
            break;
          }
        }
      }
      else{
        toastr.error(data.Error, 'Problem retrieving playlist');
      }
    }, function(err){
      toastr.error(err, 'Problem retrieving playlist');
    });
  }

  function addToQueue(callback){
    $scope.isAdding = true;
    if($scope.playlists[$scope.playlistName].Contents.length <1){
      $scope.isAdding = false;
      toastr.error('No song in selected playlist');
      $scope.inQueue = false;
      return;
    }
    if(checkPresence()){
      $scope.isAdding = false;
      return;
    }
    $http.post('/api/radio/queue')
    .then(function(res){
      var data = res.data;
      if(data.Success){
        $scope.isAdding = false;
        return callback();
      }
      else{
        $scope.isAdding = false;
        $scope.inQueue=false;
        toastr.error(data.Error, 'Could not join Queue');
        return callback(data.Error);
      }
    }, function(err){
      $scope.isAdding = false;
      $scope.inQueue=false;
      return callback(err);
    });
  }

  function checkPresence(){
    var uname = (authService.getUser() || {Username:null}).Username;
    if(!uname){
      return false;
    }
    return ($scope.queue.indexOf(uname) > -1);
  }

  $scope.$on('queue_updated', function(event, queue){
    $scope.queue = queue;
    if(!$scope.inQueue || $scope.isAdding){
      return;
    }
    addToQueue(function(err){
      if(err){
        console.log(err);
      }
      return;
    });
  });

  mediaService.on('nextSong_fetch', function(){
    var vidinfo = $scope.playlists[$scope.playlistName].Contents.shift();
    mediaService.emit('nextSong_response', vidinfo);
    $scope.playlists[$scope.playlistName].Contents.push(vidinfo);
    $http.post('/api/playlists/update', $scope.playlists[$scope.playlistName]).then(function(res){
      var data = res.data;
      if(data.Success){}
      else{
        console.log(data.Error);
      }
    },function(err){
      console.log(err);
    });
  });

  /*
  * Client Methods
  */
  $scope.search=function(){
    $scope.isSearching=true;
    $scope.isLoading = true;
    console.log('searching for ', $scope.searchCriteria.query);
    var cleancrit = encodeURIComponent($scope.searchCriteria.query)
    $http.get('/api/search/'+cleancrit)
    .then(function(res){
      var data = res.data;
      if(data.Success){
        $scope.searchResults = data.Videos;
      }
      $scope.isLoading = false;
    },function(error){
      $scope.isLoading = false;
      console.log(error);
    });
  }

  $scope.viewPlaylist=function(name){
    var oldpl = null;
    if($scope.playlistName && $scope.playlistName!==name){
      $scope.playlists[$scope.playlistName].Active=false;
      oldpl = $scope.playlistName;
    }
    $scope.playlistName=name;
    $scope.playlists[$scope.playlistName].Active=true;
    $scope.isSearching = false;
    $http.post('/api/playlists/update', $scope.playlists[$scope.playlistName]).then(function(res){
      var data = res.data;
      if(data.Success){
        console.log('new playlist activated')
        if(oldpl){
          $http.post('/api/playlists/update', $scope.playlists[oldpl]).then(function(res){
            var data = res.data;
            if(data.Success){
              console.log('old playlist deactivated');
            }
            else{
              console.log(data.Error);
            }
          });
        }
      }
      else{
        console.log(data.Error);
      }
    });
  }

  $scope.addToPlaylist=function(vidinfo){
    if(!vidinfo){
      return;
    }
    if($scope.playlists[$scope.playlistName].Contents.indexOf(vidinfo) > -1){
      toastr.error('Song already exists in playlist');
      return;
    }
    toastr.success('Song Added to Playlist: ' + $scope.playlistName);
    $scope.playlists[$scope.playlistName].Contents.unshift(vidinfo);
    $http.post('/api/playlists/update', $scope.playlists[$scope.playlistName]).then(function(res){
      if(res.data.Success){
        console.log('playlist updated');
      }
      else{
        console.log(res.data.Error);
      }
    }, function(err){
      console.log(err);
    });
  }

  $scope.removeFromPlaylist=function(ind){
    var item = $scope.playlists[$scope.playlistName].Contents.splice(ind, 1)[0];
    $http.post('/api/playlists/removeItem', {PlaylistName: $scope.playlistName, VideoID: item.ID}).then(function(res){
      var data = res.data;
      if(data.Success){
        console.log('Playlist updated');
      }
      else{
        console.log(data.Error);
      }
    }, function(err){
      console.log(err);
    });
  }

  $scope.moveUp=function(ind){
    var item = $scope.playlists[$scope.playlistName].Contents[ind];
    $scope.playlists[$scope.playlistName].Contents.splice(ind, 1);
    $scope.playlists[$scope.playlistName].Contents.unshift(item);
    $http.post('/api/playlists/update', $scope.playlists[$scope.playlistName]).then(function(res){
      var data = res.data;
      if(data.Success){
        console.log('Playlist updated');
      }
      else{
        console.log(data.Error);
      }
    }, function(err){
      console.log(err);
    });
  }

  $scope.moveDown=function(ind){
    var item = $scope.playlists[$scope.playlistName].Contents[ind];
    $scope.playlists[$scope.playlistName].Contents.splice(ind, 1);
    $scope.playlists[$scope.playlistName].Contents.push(item);
    $http.post('/api/playlists/update', $scope.playlists[$scope.playlistName]).then(function(res){
      var data = res.data;
      if(data.Success){
        console.log('Playlist updated');
      }
      else{
        console.log(data.Error);
      }
    }, function(err){
      console.log(err);
    });
  }

  $scope.joinLeaveQueue=function(){
    if($scope.inQueue){
      $scope.inQueue = false;
      var user = authService.getUser();
      if(user){
        console.log('exiting queue');
        $http.delete('/api/radio/queue/'+user.Username).then(function(res){
          var data = res.data;
          if(data.Success){
            return;
          }
          else{
            console.log(data.Error);
            return;
          }
        }, function(err){
          console.log(err);
          return;
        });
      }
    }
    else{
      $scope.inQueue = true;
      addToQueue(function(err){
        if(err){
          console.log(err);
        }
      });
    }
  }

  $scope.login=function(){
    ModalService.showModal({
      templateUrl: "views/auth.html",
      controller: "AuthCtrl"
    }).then(function(modal) {
      modal.element.modal();
      modal.close.then(function(result) {
        fetch_playlist();
      });
    });
  };

  $scope.logOut=function(){
    authService.logOut();
  }

  $scope.getUser=function(){
    return authService.getUser();
  }

  $scope.$on('session_resume', function(){
    console.log('resuming session in progress');
    fetch_playlist();
  });

});
<commit_msg>Don't celebrate too early<commit_after>app.controller('UserCtrl', function ($scope, $http, ModalService, authService, mediaService, toastr) {
  $scope.expand = false;
  $scope.searchResults = [];
  $scope.isSearching = false;
  $scope.isLoading = false;
  $scope.playlists={
    'Default':{
      Name:"Default", Active:true, Contents:[]
    }
  };
  $scope.playlistName="Default";
  $scope.inQueue=false;
  $scope.queue =[];
  $scope.isAdding = false;
  $scope.userData;
  fetch_playlist();

  function fetch_playlist(){
    if(!authService.getUser()){
      return;
    }
    $http.get('/api/playlists').then(function(res){
      var data = res.data;
      if(data.Success){
        $scope.playlists = data.Playlists;
        for(pl in data.Playlists){
          if(data.Playlists[pl].Active){
            $scope.playlistName = data.Playlists[pl].Name;
            break;
          }
        }
      }
      else{
        toastr.error(data.Error, 'Problem retrieving playlist');
      }
    }, function(err){
      toastr.error(err, 'Problem retrieving playlist');
    });
  }

  function addToQueue(callback){
    $scope.isAdding = true;
    if($scope.playlists[$scope.playlistName].Contents.length <1){
      $scope.isAdding = false;
      toastr.error('No song in selected playlist');
      $scope.inQueue = false;
      return;
    }
    if(checkPresence()){
      $scope.isAdding = false;
      return;
    }
    $http.post('/api/radio/queue')
    .then(function(res){
      var data = res.data;
      if(data.Success){
        $scope.isAdding = false;
        return callback();
      }
      else{
        $scope.isAdding = false;
        $scope.inQueue=false;
        toastr.error(data.Error, 'Could not join Queue');
        return callback(data.Error);
      }
    }, function(err){
      $scope.isAdding = false;
      $scope.inQueue=false;
      return callback(err);
    });
  }

  function checkPresence(){
    var uname = (authService.getUser() || {Username:null}).Username;
    if(!uname){
      return false;
    }
    return ($scope.queue.indexOf(uname) > -1);
  }

  $scope.$on('queue_updated', function(event, queue){
    $scope.queue = queue;
    if(!$scope.inQueue || $scope.isAdding){
      return;
    }
    addToQueue(function(err){
      if(err){
        console.log(err);
      }
      return;
    });
  });

  mediaService.on('nextSong_fetch', function(){
    var vidinfo = $scope.playlists[$scope.playlistName].Contents.shift();
    mediaService.emit('nextSong_response', vidinfo);
    $scope.playlists[$scope.playlistName].Contents.push(vidinfo);
    $http.post('/api/playlists/update', $scope.playlists[$scope.playlistName]).then(function(res){
      var data = res.data;
      if(data.Success){}
      else{
        console.log(data.Error);
      }
    },function(err){
      console.log(err);
    });
  });

  /*
  * Client Methods
  */
  $scope.search=function(){
    $scope.isSearching=true;
    $scope.isLoading = true;
    console.log('searching for ', $scope.searchCriteria.query);
    var cleancrit = encodeURIComponent($scope.searchCriteria.query)
    $http.get('/api/search/'+cleancrit)
    .then(function(res){
      var data = res.data;
      if(data.Success){
        $scope.searchResults = data.Videos;
      }
      $scope.isLoading = false;
    },function(error){
      $scope.isLoading = false;
      console.log(error);
    });
  }

  $scope.viewPlaylist=function(name){
    var oldpl = null;
    if($scope.playlistName && $scope.playlistName!==name){
      $scope.playlists[$scope.playlistName].Active=false;
      oldpl = $scope.playlistName;
    }
    $scope.playlistName=name;
    $scope.playlists[$scope.playlistName].Active=true;
    $scope.isSearching = false;
    $http.post('/api/playlists/update', $scope.playlists[$scope.playlistName]).then(function(res){
      var data = res.data;
      if(data.Success){
        console.log('new playlist activated')
        if(oldpl){
          $http.post('/api/playlists/update', $scope.playlists[oldpl]).then(function(res){
            var data = res.data;
            if(data.Success){
              console.log('old playlist deactivated');
            }
            else{
              console.log(data.Error);
            }
          });
        }
      }
      else{
        console.log(data.Error);
      }
    });
  }

  $scope.addToPlaylist=function(vidinfo){
    if(!vidinfo){
      return;
    }
    if($scope.playlists[$scope.playlistName].Contents.indexOf(vidinfo) > -1){
      toastr.error('Song already exists in playlist');
      return;
    }
    $scope.playlists[$scope.playlistName].Contents.unshift(vidinfo);
    $http.post('/api/playlists/update', $scope.playlists[$scope.playlistName]).then(function(res){
      if(res.data.Success){
        toastr.success('Song Added to Playlist: ' + $scope.playlistName);
        console.log('playlist updated');
      }
      else{
        console.log(res.data.Error);
      }
    }, function(err){
      console.log(err);
    });
  }

  $scope.removeFromPlaylist=function(ind){
    var item = $scope.playlists[$scope.playlistName].Contents.splice(ind, 1)[0];
    $http.post('/api/playlists/removeItem', {PlaylistName: $scope.playlistName, VideoID: item.ID}).then(function(res){
      var data = res.data;
      if(data.Success){
        console.log('Playlist updated');
      }
      else{
        console.log(data.Error);
      }
    }, function(err){
      console.log(err);
    });
  }

  $scope.moveUp=function(ind){
    var item = $scope.playlists[$scope.playlistName].Contents[ind];
    $scope.playlists[$scope.playlistName].Contents.splice(ind, 1);
    $scope.playlists[$scope.playlistName].Contents.unshift(item);
    $http.post('/api/playlists/update', $scope.playlists[$scope.playlistName]).then(function(res){
      var data = res.data;
      if(data.Success){
        console.log('Playlist updated');
      }
      else{
        console.log(data.Error);
      }
    }, function(err){
      console.log(err);
    });
  }

  $scope.moveDown=function(ind){
    var item = $scope.playlists[$scope.playlistName].Contents[ind];
    $scope.playlists[$scope.playlistName].Contents.splice(ind, 1);
    $scope.playlists[$scope.playlistName].Contents.push(item);
    $http.post('/api/playlists/update', $scope.playlists[$scope.playlistName]).then(function(res){
      var data = res.data;
      if(data.Success){
        console.log('Playlist updated');
      }
      else{
        console.log(data.Error);
      }
    }, function(err){
      console.log(err);
    });
  }

  $scope.joinLeaveQueue=function(){
    if($scope.inQueue){
      $scope.inQueue = false;
      var user = authService.getUser();
      if(user){
        console.log('exiting queue');
        $http.delete('/api/radio/queue/'+user.Username).then(function(res){
          var data = res.data;
          if(data.Success){
            return;
          }
          else{
            console.log(data.Error);
            return;
          }
        }, function(err){
          console.log(err);
          return;
        });
      }
    }
    else{
      $scope.inQueue = true;
      addToQueue(function(err){
        if(err){
          console.log(err);
        }
      });
    }
  }

  $scope.login=function(){
    ModalService.showModal({
      templateUrl: "views/auth.html",
      controller: "AuthCtrl"
    }).then(function(modal) {
      modal.element.modal();
      modal.close.then(function(result) {
        fetch_playlist();
      });
    });
  };

  $scope.logOut=function(){
    authService.logOut();
  }

  $scope.getUser=function(){
    return authService.getUser();
  }

  $scope.$on('session_resume', function(){
    console.log('resuming session in progress');
    fetch_playlist();
  });

});
<|endoftext|>


<commit_before>(function (ng, app) {
    app.config(['$stateProvider', function ($stateProvider) {
        $stateProvider.state('it-project.edit.status-goal.modal', {
            url: '/modal/:goalId',
            onEnter: ['$state', '$stateParams', '$modal', 'goalTypes', 'project',
                function ($state, $stateParams, $modal, goalTypes, project) {
                    $modal.open({
                        size: 'lg',
                        templateUrl: 'partials/it-project/modal-goal-edit.html',
                        // fade in instead of slide from top, fixes strange cursor placement in IE
                        // http://stackoverflow.com/questions/25764824/strange-cursor-placement-in-modal-when-using-autofocus-in-internet-explorer
                        windowClass: 'modal fade in',
                        resolve: {
                            goalId: function() {
                                return $stateParams.goalId;
                            },
                            // workaround to get data inherited from parent state
                            goalTypes: function() {
                                return goalTypes;
                            },
                            // workaround to get data inherited from parent state
                            project: function () {
                                return project;
                            },
                            goal: ['$http', function($http) {
                                var id = $stateParams.goalId;
                                if (id) {
                                    return $http.get('api/goal/' + id)
                                        .then(function(result) {
                                            return result.data.response;
                                        });
                                }
                                return null;
                            }]
                        },
                        controller: 'project.statusGoalModalCtrl'
                    }).result.then(function () {
                        // OK
                        // GOTO parent state and reload
                        $state.go('^', null, { reload: true });
                    }, function () {
                        // Cancel
                        // GOTO parent state
                        $state.go('^');
                    });
                }
            ]
        });
    }]);

    app.controller('project.statusGoalModalCtrl',
    ['$scope', '$http', 'autofocus', 'goal', 'notify', 'goalId', 'goalTypes', 'project',
        function ($scope, $http, autofocus, goal, notify, goalId, goalTypes, project) {
            var isNewGoal = goal == null;

            // set to empty object if falsy
            $scope.goal = goal ? goal : {};
            $scope.goalTypes = goalTypes;

            // if new set required goal type to first so it's a valid form
            if (isNewGoal)
                $scope.goal.goalTypeId = _.first(goalTypes).id;

            autofocus();

            $scope.opened = {};
            $scope.open = function ($event, datepicker) {
                $event.preventDefault();
                $event.stopPropagation();

                $scope.opened[datepicker] = true;
            };

            $scope.dismiss = function () {
                $scope.$dismiss();
            };

            $scope.save = function () {
                var payload = $scope.goal;
                payload.goalStatusId = project.goalStatus.id,
                delete payload.id;
                delete payload.objectOwnerId;
                delete payload.objectOwner;

                var msg = notify.addInfoMessage("Gemmer ændringer...", false);
                $http({
                    method: isNewGoal ? 'POST' : 'PATCH',
                    url: 'api/goal/' + goalId,
                    data: payload
                }).success(function () {
                    msg.toSuccessMessage("Ændringerne er gemt!");
                    $scope.$close(true);
                }).error(function () {
                    msg.toErrorMessage("Ændringerne kunne ikke gemmes!");
                });
            };
        }]);
})(angular, app);
<commit_msg>Cleared default value<commit_after>(function (ng, app) {
    app.config(['$stateProvider', function ($stateProvider) {
        $stateProvider.state('it-project.edit.status-goal.modal', {
            url: '/modal/:goalId',
            onEnter: ['$state', '$stateParams', '$modal', 'goalTypes', 'project',
                function ($state, $stateParams, $modal, goalTypes, project) {
                    $modal.open({
                        size: 'lg',
                        templateUrl: 'partials/it-project/modal-goal-edit.html',
                        // fade in instead of slide from top, fixes strange cursor placement in IE
                        // http://stackoverflow.com/questions/25764824/strange-cursor-placement-in-modal-when-using-autofocus-in-internet-explorer
                        windowClass: 'modal fade in',
                        resolve: {
                            goalId: function() {
                                return $stateParams.goalId;
                            },
                            // workaround to get data inherited from parent state
                            goalTypes: function() {
                                return goalTypes;
                            },
                            // workaround to get data inherited from parent state
                            project: function () {
                                return project;
                            },
                            goal: ['$http', function($http) {
                                var id = $stateParams.goalId;
                                if (id) {
                                    return $http.get('api/goal/' + id)
                                        .then(function(result) {
                                            return result.data.response;
                                        });
                                }
                                return null;
                            }]
                        },
                        controller: 'project.statusGoalModalCtrl'
                    }).result.then(function () {
                        // OK
                        // GOTO parent state and reload
                        $state.go('^', null, { reload: true });
                    }, function () {
                        // Cancel
                        // GOTO parent state
                        $state.go('^');
                    });
                }
            ]
        });
    }]);

    app.controller('project.statusGoalModalCtrl',
    ['$scope', '$http', 'autofocus', 'goal', 'notify', 'goalId', 'goalTypes', 'project',
        function ($scope, $http, autofocus, goal, notify, goalId, goalTypes, project) {
            var isNewGoal = goal == null;

            // set to empty object if falsy
            $scope.goal = goal ? goal : {};
            $scope.goalTypes = goalTypes;

            autofocus();

            $scope.opened = {};
            $scope.open = function ($event, datepicker) {
                $event.preventDefault();
                $event.stopPropagation();

                $scope.opened[datepicker] = true;
            };

            $scope.dismiss = function () {
                $scope.$dismiss();
            };

            $scope.save = function () {
                var payload = $scope.goal;
                payload.goalStatusId = project.goalStatus.id,
                delete payload.id;
                delete payload.objectOwnerId;
                delete payload.objectOwner;

                var msg = notify.addInfoMessage("Gemmer ændringer...", false);
                $http({
                    method: isNewGoal ? 'POST' : 'PATCH',
                    url: 'api/goal/' + goalId,
                    data: payload
                }).success(function () {
                    msg.toSuccessMessage("Ændringerne er gemt!");
                    $scope.$close(true);
                }).error(function () {
                    msg.toErrorMessage("Ændringerne kunne ikke gemmes!");
                });
            };
        }]);
})(angular, app);
<|endoftext|>


<commit_before>Handlebars.registerHelper('getHostName', function() {
    var a = document.createElement('a');
    a.href = '/';
    var host = a.host;
    $(a).remove();
    return host; // a.hostname === 'localhost' ? a.hostname+':3000' : a.hostname;
});

Handlebars.registerHelper('pluralize', function(n, thing) {
    if (n === 0) return '0 ' + thing;
    else if (n === 1) return '1 ' + thing;
    else return n + ' ' + thing + 's'
});<commit_msg>update getHostName helper<commit_after>Handlebars.registerHelper('getHostName', function() {
    return window.location.host;
});

Handlebars.registerHelper('pluralize', function(n, thing) {
    if (n === 0) return '0 ' + thing;
    else if (n === 1) return '1 ' + thing;
    else return n + ' ' + thing + 's'
});<|endoftext|>


<commit_before>(function () {
    var Cat = (function () {
        var Animal = require('./animal')(),

            ALLOWED_COLORS = ['red', 'white', 'purple'],

            _color;

        function Constructor(name, age, color) {
            Animal.call(this, name, age);
            this.color = color;
        }

        Constructor.prototype = Object.create(Animal.prototype);
        Constructor.prototype.toString = function () {
            var result = Animal.prototype.toString.call(this);
            return result + ' ' + _color;
        };

        Object.defineProperty(Constructor.prototype, 'color', {
            get: function () {
                return _color;
            },
            set: function (color) {
                if (validateColor(color)) {
                    _color = color;
                }
            }
        });

        function validateColor(color) {
            if (ALLOWED_COLORS.indexOf(color) >= 0) {
                return true;
            } else {
                throw new Error();
            }
        }

        return Constructor;
    } ());

    module.exports = Cat;
} ());

(function () {
    var Cat = require('./cat');
    var kittu = new Cat('name', 14, 'red');
    console.log(kittu.toString());
} ());<commit_msg>update<commit_after>(function (parent) {
    var Cat = (function (parent) {
        var ALLOWED_COLORS = ['red', 'white', 'purple'],

            _color;

        function Constructor(name, age, color) {
            parent.call(this, name, age);
            this.color = color;
        }

        Constructor.prototype = Object.create(parent.prototype);
        Constructor.prototype.toString = function () {
            var result = parent.prototype.toString.call(this);
            return result + ' ' + _color;
        };

        Object.defineProperty(Constructor.prototype, 'color', {
            get: function () {
                return _color;
            },
            set: function (color) {
                if (validateColor(color)) {
                    _color = color;
                }
            }
        });

        function validateColor(color) {
            if (ALLOWED_COLORS.indexOf(color) >= 0) {
                return true;
            } else {
                throw new Error();
            }
        }

        return Constructor;
    } (parent));

    module.exports = Cat;
} (require('./animal')()));

(function () {
    var Cat = require('./cat');
    var kittu = new Cat('name', 14, 'red');
    console.log(kittu.toString());
} ());<|endoftext|>


<commit_before>"use strict"; // strict mode syntax

// Takes an array of arrays and constructs an ArrayCollection with multiple ArrayInfo objects
function ArrayCollection(array){
  this.collection = [];

  //array is an array of arrays
  for(var i = 1; i < array.length; i++){
    this.collection.push(new ArrayInfo(array[i]));
  }
  this.calcMinMax();
}

// Set the collection equal to another collection
ArrayCollection.prototype.setCollection = function(nCollection) {
  this.collection = nCollection;

  this.calcMinMax();
}

// calculates the mim and max values for a collection and sets them in this.min and this.max
ArrayCollection.prototype.calcMinMax = function() {
  this.min = Number.MAX_VALUE;
  this.max = Number.MIN_VALUE;

  for(var i = 0; i < this.collection.length; i++) {
    this.min = ((this.collection[i].trend.min < this.min) ? this.collection[i].trend.min : this.min);
    this.max = ((this.collection[i].trend.max > this.max) ? this.collection[i].trend.max : this.max);
  }
}

// adds a line into the collection
ArrayCollection.prototype.addLine = function(newInfo) {
  this.collection.push(new ArrayInfo(newInfo));
  this.calcMinMax();
}

// updates a single line in the arrayCollection
ArrayCollection.prototype.changeLine = function(line, index, change) {
  this.collection[line][index] = change;
  this.collection[line].trend = this.collection[line].calcTrends();
  this.calcMinMax();
}
<commit_msg>Fixed the audio<commit_after>"use strict"; // strict mode syntax

// Takes an array of arrays and constructs an ArrayCollection with multiple ArrayInfo objects
function ArrayCollection(array){
  this.collection = [];

  //array is an array of arrays
  for(var i = 1; i < array.length; i++){
    this.collection.push(new ArrayInfo(array[i]));
  }
  this.calcMinMax();
}

// Set the collection equal to another collection
ArrayCollection.prototype.setCollection = function(nCollection) {
  this.collection = nCollection;

  this.calcMinMax();
}

// calculates the mim and max values for a collection and sets them in this.min and this.max
ArrayCollection.prototype.calcMinMax = function() {
  this.min = Number.MAX_VALUE;
  this.max = Number.MIN_VALUE;

  for(var i = 0; i < this.collection.length; i++) {
    this.min = ((this.collection[i].trend.min < this.min) ? this.collection[i].trend.min : this.min);
    this.max = ((this.collection[i].trend.max > this.max) ? this.collection[i].trend.max : this.max);
  }
}

// adds a line into the collection
ArrayCollection.prototype.addLine = function(newInfo) {
  this.collection.push(new ArrayInfo(newInfo));
  this.calcMinMax();
}

// updates a single line in the arrayCollection
ArrayCollection.prototype.changeLine = function(line, index, change) {
  this.collection[line].array[index] = change;
  this.collection[line].trend = this.collection[line].calcTrends();
  this.calcMinMax();
}
<|endoftext|>


<commit_before>/*
 * See: https://developer.mozilla.org/fr/docs/Web/JavaScript/Guide/Nombres_et_dates#L%27objet_Date
 */

var time = new Date();
var hours   = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();

print(time)
print(hours, minutes, seconds)
<commit_msg>Add a link.<commit_after>/*
 * See: https://developer.mozilla.org/fr/docs/Web/JavaScript/Guide/Nombres_et_dates#L%27objet_Date
 *      https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date
 */

var time = new Date();
var hours   = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();

print(time)
print(hours, minutes, seconds)
<|endoftext|>


<commit_before>import { Communicator, ReactivityProvider } from '/client/imports/facades';
import { SessionManager, ErrorHandler, Notification, Enums, Querying } from '/client/imports/modules';
import { CollectionAdd, CollectionValidationRules, CollectionRename, CollectionFilter, CollectionConversion, Connection } from '/client/imports/ui';
import Helper from '/client/imports/helpers/helper';
import $ from 'jquery';

const CollectionUtil = function () {

};

const specifyActiveClass = function (selector, name) {
  selector.find('li').each((index, li) => {
    const liObject = $(li);
    if (liObject[0].textContent.trim() === name) liObject.addClass('active');
    else liObject.removeClass('active');
  });
};

const getCollectionNameFromContextMenu = function (clickedItem) {
  if (clickedItem && clickedItem.context && clickedItem.context.innerText) return clickedItem.context.innerText.trim();
};

const deactivateListItems = function (selector) {
  selector.find('li').each((index, li) => {
    $(li).removeClass('active');
  });
};

CollectionUtil.prototype = {
  setSessionForNavigation(name) {
    specifyActiveClass($('#listCollectionNames'), name);
    specifyActiveClass($('#listSystemCollections'), name);

    SessionManager.set(SessionManager.strSessionSelectedCollection, name);
  },

  dropDatabase() {
    Notification.modal({
      title: 'are-you-sure',
      text: 'recover-not-possible',
      type: 'warning',
      callback: (isConfirm) => {
        if (isConfirm) {
          Communicator.call({
            methodName: 'dropDB',
            callback: (err, result) => {
              if (err || result.error) ErrorHandler.showMeteorFuncError(err, result);
              else {
                SessionManager.clear();
                Notification.success('database-dropped-successfully');
              }
            }
          });
        }
      }
    });
  },

  dropAllCollections() {
    Notification.modal({
      title: 'are-you-sure',
      text: 'all-collections-will-be-dropped',
      type: 'warning',
      callback: (isConfirm) => {
        if (isConfirm) {
          Communicator.call({
            methodName: 'dropAllCollections',
            callback: (err, result) => {
              if (err || result.error) ErrorHandler.showMeteorFuncError(err, result);
              else {
                Connection.connect(false);
                Notification.success('dropped-all-collections-successfully');
              }
            }
          });
        }
      }
    });
  },

  dropCollection(selectedCollection) {
    Notification.modal({
      title: 'are-you-sure',
      text: 'collection-will-be-dropped',
      textTranslateOptions: { selectedCollection },
      type: 'warning',
      callback: (isConfirm) => {
        if (isConfirm) {
          Communicator.call({
            methodName: 'dropCollection',
            args: { selectedCollection },
            callback: (err, result) => {
              if (err || result.error) ErrorHandler.showMeteorFuncError(err, result);
              else {
                Connection.connect(false);
                Notification.success('collection-dropped-successfully', null, { selectedCollection });
              }
            }
          });
        }
      }
    });
  },

  cloneCollection(selectedCollection) {
    Notification.modal({
      title: 'collection_name',
      text: 'collection_name',
      type: 'input',
      closeOnConfirm: false,
      inputPlaceholder: 'collection_name',
      inputValue: selectedCollection,
      callback: (inputValue) => {
        if (!inputValue) {
          Notification.showModalInputError('name-required');
          return false;
        }

        Notification.modal({ title: 'creating', text: 'please-wait', type: 'info' });

        Communicator.call({
          methodName: 'aggregate',
          args: { selectedCollection, pipeline: [{ $match: {} }, { $out: inputValue }] },
          callback: (err, result) => {
            if (err || result.error) ErrorHandler.showMeteorFuncError(err, result);
            else {
              Connection.connect(true, 'collection-cloned-successfully', { selectedCollection, name: inputValue });
              Notification.closeModal();
            }
          }
        });
      }
    });
  },

  showMongoBinaryInfo() {
    if (!localStorage.getItem(Enums.LOCAL_STORAGE_KEYS.MONGO_BINARY_INFO)) {
      Notification.modal({
        title: 'mongo-tools',
        text: 'mongo-tools-info',
        type: 'info',
        confirmButtonText: 'dont_show_again',
        callback: (isConfirm) => {
          if (isConfirm) localStorage.setItem(Enums.LOCAL_STORAGE_KEYS.MONGO_BINARY_INFO, 'true');
        }
      });
    }
  },

  clearCollection(selectedCollection) {
    Notification.modal({
      title: 'are-you-sure',
      text: 'collection-will-be-wiped',
      textTranslateOptions: { selectedCollection },
      type: 'warning',
      callback: (isConfirm) => {
        if (isConfirm) {
          Communicator.call({
            methodName: 'delete',
            args: { selectedCollection },
            callback: (err, result) => {
              if (err || result.error) ErrorHandler.showMeteorFuncError(err, result);
              else Notification.success('collection-cleared-successfully', null, { selectedCollection });
            }
          });
        }
      }
    });
  },

  handleNavigationAndSessions() {
    deactivateListItems($('#listCollectionNames'));
    deactivateListItems($('#listSystemCollections'));

    SessionManager.set(SessionManager.strSessionSelectedCollection, null);
    SessionManager.set(SessionManager.strSessionSelectedQuery, null);
    SessionManager.set(SessionManager.strSessionSelectedOptions, null);

    $('#cmbQueries').val('').trigger('chosen:updated');
    $('#cmbAdminQueries').val('').trigger('chosen:updated');
  },

  prepareContextMenuItems(addCollectionModal, convertToCappedModal, renameModal, validationRulesModal, filterModal) {
    const self = this;
    return {
      manage_collection: {
        name: Helper.translate({ key: 'manage' }),
        icon: 'fa-pencil',
        items: {
          view_collection: {
            name: Helper.translate({ key: 'show_coll_view_info' }),
            icon: 'fa-book',
            callback() {
              const collectionName = getCollectionNameFromContextMenu($(this));
              if (collectionName) {
                addCollectionModal.data('is-view', collectionName);
                addCollectionModal.modal({
                  backdrop: 'static',
                  keyboard: false,
                });
              }
            },
          },

          convert_to_capped: {
            icon: 'fa-level-down',
            name: Helper.translate({ key: 'convert_to_capped' }),
            callback() {
              const collectionName = getCollectionNameFromContextMenu($(this));
              convertToCappedModal.data('collection', collectionName);
              convertToCappedModal.modal('show');
            },
          },

          rename_collection: {
            icon: 'fa-pencil-square-o',
            name: Helper.translate({ key: 'rename' }),
            callback() {
              const collectionName = getCollectionNameFromContextMenu($(this));
              renameModal.data('collection', collectionName);
              renameModal.modal('show');
            },
          },

          clone_collection: {
            icon: 'fa-clone',
            name: Helper.translate({ key: 'clone' }),
            callback() {
              const collectionName = getCollectionNameFromContextMenu($(this));
              self.cloneCollection(collectionName);
            }
          },

          validation_rules: {
            icon: 'fa-check-circle',
            name: Helper.translate({ key: 'edit_validation_rules' }),
            callback() {
              const collectionName = getCollectionNameFromContextMenu($(this));
              validationRulesModal.data('collection', collectionName);
              validationRulesModal.modal('show');
            },
          },

          clear_collection: {
            name: Helper.translate({ key: 'clear_collection' }),
            icon: 'fa-remove',
            callback() {
              const collectionName = getCollectionNameFromContextMenu($(this));
              if (collectionName) self.clearCollection(collectionName);
              else Notification.warning('select_collection');
            }
          }
        }
      },

      add_collection: {
        name: Helper.translate({ key: 'add_coll_view' }),
        icon: 'fa-plus',
        callback() {
          addCollectionModal.data('is-view', '');
          addCollectionModal.modal({
            backdrop: 'static',
            keyboard: false,
          });
        },
      },
      filter_collections: {
        name: Helper.translate({ key: 'filter' }),
        icon: 'fa-filter',
        callback() {
          filterModal.modal('show');
        },
      },
      clear_filter: {
        name: Helper.translate({ key: 'clear_filter' }),
        icon: 'fa-minus-circle',
        callback() {
          CollectionFilter.excludedCollectionsByFilter.set([]);
          CollectionFilter.filterRegex.set('');
        },
      },
      refresh_collections: {
        name: Helper.translate({ key: 'refresh_collections' }),
        icon: 'fa-refresh',
        callback() {
          Connection.connect(true);
        },
      },
      drop_collection: {
        name: Helper.translate({ key: 'drop_collection' }),
        icon: 'fa-trash',
        callback() {
          const collectionName = getCollectionNameFromContextMenu($(this));
          if (collectionName) self.dropCollection(collectionName);
          else Notification.warning('select_collection');
        },
      },
      drop_collections: {
        name: Helper.translate({ key: 'drop_all_collections' }),
        icon: 'fa-ban',
        callback() {
          self.dropAllCollections();
        },
      },
    };
  },

  getCollectionInformation() {
    const settings = ReactivityProvider.findOne(ReactivityProvider.types.Settings);

    setTimeout(() => {
      const btnExecuteQuery = document.querySelector('#btnExecuteQuery');
      if (!settings || !btnExecuteQuery) return;

      Notification.start('#btnExecuteQuery');
      const selectedCollection = SessionManager.get(SessionManager.strSessionSelectedCollection);

      // get distinct field keys for auto complete on every collection change.
      Querying.getDistinctKeysForAutoComplete(selectedCollection);

      Communicator.call({
        methodName: 'stats',
        args: { selectedCollection },
        callback: (err, result) => {
          if (err || result.error) {
            const errorMessage = Helper.translate({ key: 'fetch_stats_error' });
            $('#divCollectionInfo').html(`<div class="row"><div class="col-lg-7"><b>${errorMessage}</b></div><div class="col-lg-5">${ErrorHandler.getErrorMessage(err, result)}</div></div>`);
          } else this.populateCollectionInfo(result.result, settings);
          Notification.stop();
        }
      });
    }, 150);
  },

  populateCollectionInfo(statsResult, settings) {
    const { scale, text } = Helper.getScaleAndText(settings.scale);

    // we are manually doing the scale to prevent showing 0 MB for sizes 0.7, 0.8, 0.9 etc. MBs as mongodb does.
    let resultString = `<div class="row"><div class="col-lg-7"><b>${Helper.translate({ key: 'count' })}:</b></div><div class="col-lg-5">${statsResult.count}</div></div>`;
    resultString += `<div class="row"><div class="col-lg-7"><b>${Helper.translate({ key: 'index_count' })}:</b></div><div class="col-lg-5">${statsResult.nindexes}</div></div>`;

    const size = Number.isNaN(Number(statsResult.size / scale)) ? '0.00' : Number(statsResult.size / scale).toFixed(2);
    resultString += `<div class="row"><div class="col-lg-7"><b>${Helper.translate({ key: 'size' })}:</b></div><div class="col-lg-5">${size} ${text}</div></div>`;

    const totalIndexSize = Number.isNaN(Number(statsResult.totalIndexSize / scale)) ? '0.00' : Number(statsResult.totalIndexSize / scale).toFixed(2);
    resultString += `<div class="row"><div class="col-lg-7"><b>${Helper.translate({ key: 'total_index_size' })}:</b></div><div class="col-lg-5">${totalIndexSize} ${text}</div></div>`;

    const avgObjSize = Number.isNaN(Number(statsResult.avgObjSize / scale)) ? '0.00' : Number(statsResult.avgObjSize / scale).toFixed(2);
    resultString += `<div class="row"><div class="col-lg-7"><b>${Helper.translate({ key: 'avg_obj_size' })}:</b></div><div class="col-lg-5">${avgObjSize} ${text}</div></div>`;
    resultString += `<div class="row"><div class="col-lg-7"><b>${Helper.translate({ key: 'is_capped' })}:</b></div><div class="col-lg-5">${statsResult.capped}</div></div>`;

    $('#divCollectionInfo').html(resultString);
  },

  prepareContextMenuModals() {
    const filterModal = $('#collectionFilterModal');
    filterModal.on('shown.bs.modal', () => {
      CollectionFilter.initializeFilterTable();
    });

    const addCollectionModal = $('#collectionAddModal');
    addCollectionModal.on('shown.bs.modal', () => {
      CollectionAdd.resetForm();
      if (addCollectionModal.data('is-view')) CollectionAdd.initializeForm(addCollectionModal.data('is-view'));
    });

    const convertToCappedModal = $('#convertToCappedModal');
    convertToCappedModal.on('shown.bs.modal', () => {
      CollectionConversion.resetForm();
    });

    const renameModal = $('#renameCollectionModal');
    renameModal.on('shown.bs.modal', () => {
      CollectionRename.resetForm();
    });

    const validationRulesModal = $('#validationRulesModal');
    validationRulesModal.on('shown.bs.modal', () => {
      CollectionValidationRules.resetForm();
    });

    return { filterModal, addCollectionModal, convertToCappedModal, renameModal, validationRulesModal };
  },

  getCollectionNames(isSystem) {
    const collectionNames = SessionManager.get(SessionManager.strSessionCollectionNames);
    if (collectionNames) {
      const result = [];
      collectionNames.forEach((collectionName) => {
        if (CollectionFilter.filterRegex.get() && !collectionName.name.match(new RegExp(CollectionFilter.filterRegex.get(), 'i'))) return;
        if ($.inArray(collectionName.name, CollectionFilter.excludedCollectionsByFilter.get()) !== -1) return;

        if (isSystem && collectionName.name.startsWith('system')) result.push(collectionName);
        else if (!isSystem && !collectionName.name.startsWith('system')) result.push(collectionName);
      });

      return result;
    }

    return collectionNames;
  }
};

export default new CollectionUtil();
<commit_msg>fixed getting name from navigation bar<commit_after>import { Communicator, ReactivityProvider } from '/client/imports/facades';
import { SessionManager, ErrorHandler, Notification, Enums, Querying } from '/client/imports/modules';
import { CollectionAdd, CollectionValidationRules, CollectionRename, CollectionFilter, CollectionConversion, Connection } from '/client/imports/ui';
import Helper from '/client/imports/helpers/helper';
import $ from 'jquery';

const CollectionUtil = function () {

};

const specifyActiveClass = function (selector, name) {
  selector.find('li').each((index, li) => {
    const liObject = $(li);
    if (liObject[0].textContent.trim() === name) liObject.addClass('active');
    else liObject.removeClass('active');
  });
};

const getCollectionNameFromContextMenu = function (clickedItem) {
  if (clickedItem && clickedItem.context && clickedItem.context.innerText) return clickedItem.context.innerText.trim().split(' ')[0];
};

const deactivateListItems = function (selector) {
  selector.find('li').each((index, li) => {
    $(li).removeClass('active');
  });
};

CollectionUtil.prototype = {
  setSessionForNavigation(name) {
    specifyActiveClass($('#listCollectionNames'), name);
    specifyActiveClass($('#listSystemCollections'), name);

    SessionManager.set(SessionManager.strSessionSelectedCollection, name);
  },

  dropDatabase() {
    Notification.modal({
      title: 'are-you-sure',
      text: 'recover-not-possible',
      type: 'warning',
      callback: (isConfirm) => {
        if (isConfirm) {
          Communicator.call({
            methodName: 'dropDB',
            callback: (err, result) => {
              if (err || result.error) ErrorHandler.showMeteorFuncError(err, result);
              else {
                SessionManager.clear();
                Notification.success('database-dropped-successfully');
              }
            }
          });
        }
      }
    });
  },

  dropAllCollections() {
    Notification.modal({
      title: 'are-you-sure',
      text: 'all-collections-will-be-dropped',
      type: 'warning',
      callback: (isConfirm) => {
        if (isConfirm) {
          Communicator.call({
            methodName: 'dropAllCollections',
            callback: (err, result) => {
              if (err || result.error) ErrorHandler.showMeteorFuncError(err, result);
              else {
                Connection.connect(false);
                Notification.success('dropped-all-collections-successfully');
              }
            }
          });
        }
      }
    });
  },

  dropCollection(selectedCollection) {
    Notification.modal({
      title: 'are-you-sure',
      text: 'collection-will-be-dropped',
      textTranslateOptions: { selectedCollection },
      type: 'warning',
      callback: (isConfirm) => {
        if (isConfirm) {
          Communicator.call({
            methodName: 'dropCollection',
            args: { selectedCollection },
            callback: (err, result) => {
              if (err || result.error) ErrorHandler.showMeteorFuncError(err, result);
              else {
                Connection.connect(false);
                Notification.success('collection-dropped-successfully', null, { selectedCollection });
              }
            }
          });
        }
      }
    });
  },

  cloneCollection(selectedCollection) {
    Notification.modal({
      title: 'collection_name',
      text: 'collection_name',
      type: 'input',
      closeOnConfirm: false,
      inputPlaceholder: 'collection_name',
      inputValue: selectedCollection,
      callback: (inputValue) => {
        if (!inputValue) {
          Notification.showModalInputError('name-required');
          return false;
        }

        Notification.modal({ title: 'creating', text: 'please-wait', type: 'info' });

        Communicator.call({
          methodName: 'aggregate',
          args: { selectedCollection, pipeline: [{ $match: {} }, { $out: inputValue }] },
          callback: (err, result) => {
            if (err || result.error) ErrorHandler.showMeteorFuncError(err, result);
            else {
              Connection.connect(true, 'collection-cloned-successfully', { selectedCollection, name: inputValue });
              Notification.closeModal();
            }
          }
        });
      }
    });
  },

  showMongoBinaryInfo() {
    if (!localStorage.getItem(Enums.LOCAL_STORAGE_KEYS.MONGO_BINARY_INFO)) {
      Notification.modal({
        title: 'mongo-tools',
        text: 'mongo-tools-info',
        type: 'info',
        confirmButtonText: 'dont_show_again',
        callback: (isConfirm) => {
          if (isConfirm) localStorage.setItem(Enums.LOCAL_STORAGE_KEYS.MONGO_BINARY_INFO, 'true');
        }
      });
    }
  },

  clearCollection(selectedCollection) {
    Notification.modal({
      title: 'are-you-sure',
      text: 'collection-will-be-wiped',
      textTranslateOptions: { selectedCollection },
      type: 'warning',
      callback: (isConfirm) => {
        if (isConfirm) {
          Communicator.call({
            methodName: 'delete',
            args: { selectedCollection },
            callback: (err, result) => {
              if (err || result.error) ErrorHandler.showMeteorFuncError(err, result);
              else Notification.success('collection-cleared-successfully', null, { selectedCollection });
            }
          });
        }
      }
    });
  },

  handleNavigationAndSessions() {
    deactivateListItems($('#listCollectionNames'));
    deactivateListItems($('#listSystemCollections'));

    SessionManager.set(SessionManager.strSessionSelectedCollection, null);
    SessionManager.set(SessionManager.strSessionSelectedQuery, null);
    SessionManager.set(SessionManager.strSessionSelectedOptions, null);

    $('#cmbQueries').val('').trigger('chosen:updated');
    $('#cmbAdminQueries').val('').trigger('chosen:updated');
  },

  prepareContextMenuItems(addCollectionModal, convertToCappedModal, renameModal, validationRulesModal, filterModal) {
    const self = this;
    return {
      manage_collection: {
        name: Helper.translate({ key: 'manage' }),
        icon: 'fa-pencil',
        items: {
          view_collection: {
            name: Helper.translate({ key: 'show_coll_view_info' }),
            icon: 'fa-book',
            callback() {
              const collectionName = getCollectionNameFromContextMenu($(this));
              if (collectionName) {
                addCollectionModal.data('is-view', collectionName);
                addCollectionModal.modal({
                  backdrop: 'static',
                  keyboard: false,
                });
              }
            },
          },

          convert_to_capped: {
            icon: 'fa-level-down',
            name: Helper.translate({ key: 'convert_to_capped' }),
            callback() {
              const collectionName = getCollectionNameFromContextMenu($(this));
              convertToCappedModal.data('collection', collectionName);
              convertToCappedModal.modal('show');
            },
          },

          rename_collection: {
            icon: 'fa-pencil-square-o',
            name: Helper.translate({ key: 'rename' }),
            callback() {
              const collectionName = getCollectionNameFromContextMenu($(this));
              renameModal.data('collection', collectionName);
              renameModal.modal('show');
            },
          },

          clone_collection: {
            icon: 'fa-clone',
            name: Helper.translate({ key: 'clone' }),
            callback() {
              const collectionName = getCollectionNameFromContextMenu($(this));
              self.cloneCollection(collectionName);
            }
          },

          validation_rules: {
            icon: 'fa-check-circle',
            name: Helper.translate({ key: 'edit_validation_rules' }),
            callback() {
              const collectionName = getCollectionNameFromContextMenu($(this));
              validationRulesModal.data('collection', collectionName);
              validationRulesModal.modal('show');
            },
          },

          clear_collection: {
            name: Helper.translate({ key: 'clear_collection' }),
            icon: 'fa-remove',
            callback() {
              const collectionName = getCollectionNameFromContextMenu($(this));
              if (collectionName) self.clearCollection(collectionName);
              else Notification.warning('select_collection');
            }
          }
        }
      },

      add_collection: {
        name: Helper.translate({ key: 'add_coll_view' }),
        icon: 'fa-plus',
        callback() {
          addCollectionModal.data('is-view', '');
          addCollectionModal.modal({
            backdrop: 'static',
            keyboard: false,
          });
        },
      },
      filter_collections: {
        name: Helper.translate({ key: 'filter' }),
        icon: 'fa-filter',
        callback() {
          filterModal.modal('show');
        },
      },
      clear_filter: {
        name: Helper.translate({ key: 'clear_filter' }),
        icon: 'fa-minus-circle',
        callback() {
          CollectionFilter.excludedCollectionsByFilter.set([]);
          CollectionFilter.filterRegex.set('');
        },
      },
      refresh_collections: {
        name: Helper.translate({ key: 'refresh_collections' }),
        icon: 'fa-refresh',
        callback() {
          Connection.connect(true);
        },
      },
      drop_collection: {
        name: Helper.translate({ key: 'drop_collection' }),
        icon: 'fa-trash',
        callback() {
          const collectionName = getCollectionNameFromContextMenu($(this));
          if (collectionName) self.dropCollection(collectionName);
          else Notification.warning('select_collection');
        },
      },
      drop_collections: {
        name: Helper.translate({ key: 'drop_all_collections' }),
        icon: 'fa-ban',
        callback() {
          self.dropAllCollections();
        },
      },
    };
  },

  getCollectionInformation() {
    const settings = ReactivityProvider.findOne(ReactivityProvider.types.Settings);

    setTimeout(() => {
      const btnExecuteQuery = document.querySelector('#btnExecuteQuery');
      if (!settings || !btnExecuteQuery) return;

      Notification.start('#btnExecuteQuery');
      const selectedCollection = SessionManager.get(SessionManager.strSessionSelectedCollection);

      // get distinct field keys for auto complete on every collection change.
      Querying.getDistinctKeysForAutoComplete(selectedCollection);

      Communicator.call({
        methodName: 'stats',
        args: { selectedCollection },
        callback: (err, result) => {
          if (err || result.error) {
            const errorMessage = Helper.translate({ key: 'fetch_stats_error' });
            $('#divCollectionInfo').html(`<div class="row"><div class="col-lg-7"><b>${errorMessage}</b></div><div class="col-lg-5">${ErrorHandler.getErrorMessage(err, result)}</div></div>`);
          } else this.populateCollectionInfo(result.result, settings);
          Notification.stop();
        }
      });
    }, 150);
  },

  populateCollectionInfo(statsResult, settings) {
    const { scale, text } = Helper.getScaleAndText(settings.scale);

    // we are manually doing the scale to prevent showing 0 MB for sizes 0.7, 0.8, 0.9 etc. MBs as mongodb does.
    let resultString = `<div class="row"><div class="col-lg-7"><b>${Helper.translate({ key: 'count' })}:</b></div><div class="col-lg-5">${statsResult.count}</div></div>`;
    resultString += `<div class="row"><div class="col-lg-7"><b>${Helper.translate({ key: 'index_count' })}:</b></div><div class="col-lg-5">${statsResult.nindexes}</div></div>`;

    const size = Number.isNaN(Number(statsResult.size / scale)) ? '0.00' : Number(statsResult.size / scale).toFixed(2);
    resultString += `<div class="row"><div class="col-lg-7"><b>${Helper.translate({ key: 'size' })}:</b></div><div class="col-lg-5">${size} ${text}</div></div>`;

    const totalIndexSize = Number.isNaN(Number(statsResult.totalIndexSize / scale)) ? '0.00' : Number(statsResult.totalIndexSize / scale).toFixed(2);
    resultString += `<div class="row"><div class="col-lg-7"><b>${Helper.translate({ key: 'total_index_size' })}:</b></div><div class="col-lg-5">${totalIndexSize} ${text}</div></div>`;

    const avgObjSize = Number.isNaN(Number(statsResult.avgObjSize / scale)) ? '0.00' : Number(statsResult.avgObjSize / scale).toFixed(2);
    resultString += `<div class="row"><div class="col-lg-7"><b>${Helper.translate({ key: 'avg_obj_size' })}:</b></div><div class="col-lg-5">${avgObjSize} ${text}</div></div>`;
    resultString += `<div class="row"><div class="col-lg-7"><b>${Helper.translate({ key: 'is_capped' })}:</b></div><div class="col-lg-5">${statsResult.capped}</div></div>`;

    $('#divCollectionInfo').html(resultString);
  },

  prepareContextMenuModals() {
    const filterModal = $('#collectionFilterModal');
    filterModal.on('shown.bs.modal', () => {
      CollectionFilter.initializeFilterTable();
    });

    const addCollectionModal = $('#collectionAddModal');
    addCollectionModal.on('shown.bs.modal', () => {
      CollectionAdd.resetForm();
      if (addCollectionModal.data('is-view')) CollectionAdd.initializeForm(addCollectionModal.data('is-view'));
    });

    const convertToCappedModal = $('#convertToCappedModal');
    convertToCappedModal.on('shown.bs.modal', () => {
      CollectionConversion.resetForm();
    });

    const renameModal = $('#renameCollectionModal');
    renameModal.on('shown.bs.modal', () => {
      CollectionRename.resetForm();
    });

    const validationRulesModal = $('#validationRulesModal');
    validationRulesModal.on('shown.bs.modal', () => {
      CollectionValidationRules.resetForm();
    });

    return { filterModal, addCollectionModal, convertToCappedModal, renameModal, validationRulesModal };
  },

  getCollectionNames(isSystem) {
    const collectionNames = SessionManager.get(SessionManager.strSessionCollectionNames);
    if (collectionNames) {
      const result = [];
      collectionNames.forEach((collectionName) => {
        if (CollectionFilter.filterRegex.get() && !collectionName.name.match(new RegExp(CollectionFilter.filterRegex.get(), 'i'))) return;
        if ($.inArray(collectionName.name, CollectionFilter.excludedCollectionsByFilter.get()) !== -1) return;

        if (isSystem && collectionName.name.startsWith('system')) result.push(collectionName);
        else if (!isSystem && !collectionName.name.startsWith('system')) result.push(collectionName);
      });

      return result;
    }

    return collectionNames;
  }
};

export default new CollectionUtil();
<|endoftext|>


<commit_before>function skipWitespace(program) {
  const nonWhitespaceCharacter = program.search(/\S/);
  return program.substring(nonWhitespaceCharacter);
}

function parseExpression(program) {
  program = skipWitespace(program);

  const stringValue = /^"([^"]*)"/.exec(program);
  if (stringValue) {
    return {
      expression: {
        type: 'string',
        value: stringValue[1]
      },
      // +2 for the quote chars ("(something)")
      program: program.substr(stringValue[1].length + 2)
    }
  }

  const numberValue = /^(\d+)/.exec(program);
  if (numberValue) {
    return {
      expression: {
        type: 'integer',
        value: parseInt(numberValue[1], 10)
      },
      program: program.substr(numberValue[1].length)
    }
  }

  const word = /^([^\(\),\s]+)/.exec(program);

  if (word) {
    program = skipWitespace(program.substr(word[1].length));

    if (program[0] === '(') {
      return parseApply(word[1], program.substr(1))
    }

    return {
      expression: {
        type: 'word',
        value: word[1]
      },
      program
    }
  }

  throw new Error(`Token not recognized: ${program}`);
}

function parseApply(applyToken, program) {
  if (program[0] === '(') {
    // When we call ourselves for returning functions that are immediatly called
    program = program.substr(1);
  }

  const args = [];

  for (; ;) {
    const result = parseExpression(program);

    let expression = result.expression;
    program = result.program;

    args.push(expression);

    program = skipWitespace(program);

    if (program[0] === ')') {
      break;
    }

    if (program[0] === ',') {
      program = skipWitespace(program.substr(1));
    } else {
      throw new Error(`Failed, expected comma as argument separator: ${program} ${JSON.stringify(expression)}`);
    }
  }

  const expression = {
    type: 'apply',
    name: applyToken,
    args
  };

  // Advance beyond ')'
  program = skipWitespace(program.substr(1));
  if (program[0] === '(') {
    // When interpreting, check if name is of type apply
    return parseApply(expression, program)
  }

  return {
    expression,
    program
  }
}

// ***********************
// TESTS
// ***********************
function prettyPrint(expression) {
  console.log(JSON.stringify(expression, null, 2));
}

function testSingleExpression() {
  prettyPrint(parseExpression("   \"yaya\""));
  prettyPrint(parseExpression("   1234"));
  prettyPrint(parseExpression("   a,b"));
  prettyPrint(parseExpression("   a,   b"));
}

function testParseApply() {
  prettyPrint(parseExpression("do(if(true, +(1,2), false))"));
  prettyPrint(parseExpression("multiplier(2)(1)"));
}

testSingleExpression();
testParseApply();<commit_msg>Adding an enviroment in preparation for the apply phase<commit_after>function skipWitespace(program) {
  const nonWhitespaceCharacter = program.search(/\S/);
  return program.substring(nonWhitespaceCharacter);
}

function parseExpression(program) {
  program = skipWitespace(program);

  const stringValue = /^"([^"]*)"/.exec(program);
  if (stringValue) {
    return {
      expression: {
        type: 'string',
        value: stringValue[1]
      },
      // +2 for the quote chars ("something")
      program: program.substr(stringValue[1].length + 2)
    }
  }

  const numberValue = /^(\d+)/.exec(program);
  if (numberValue) {
    return {
      expression: {
        type: 'integer',
        value: parseInt(numberValue[1], 10)
      },
      program: program.substr(numberValue[1].length)
    }
  }

  const word = /^([^\(\),\s]+)/.exec(program);

  if (word) {
    program = skipWitespace(program.substr(word[1].length));

    if (program[0] === '(') {
      return parseApply(word[1], program.substr(1))
    }

    return {
      expression: {
        type: 'word',
        value: word[1]
      },
      program
    }
  }

  throw new Error(`Token not recognized: ${program}`);
}

function parseApply(applyToken, program) {
  if (program[0] === '(') {
    // When we call ourselves for returning functions that are immediatly called
    program = program.substr(1);
  }

  const args = [];

  for (; ;) {
    const result = parseExpression(program);

    let expression = result.expression;
    program = result.program;

    args.push(expression);

    program = skipWitespace(program);

    if (program[0] === ')') {
      break;
    }

    if (program[0] === ',') {
      program = skipWitespace(program.substr(1));
    } else {
      throw new Error(`Failed, expected comma as argument separator: ${program} ${JSON.stringify(expression)}`);
    }
  }

  const expression = {
    type: 'apply',
    name: applyToken,
    args
  };

  // Advance beyond ')'
  program = skipWitespace(program.substr(1));
  if (program[0] === '(') {
    // When interpreting, check if name is of type apply
    return parseApply(expression, program)
  }

  return {
    expression,
    program
  }
}

// Define an enviroment
const topEnviroment = {
  '+': (a, b) => a + b,
};

function setEnv(env, args) {
  if (args.length % 2 !== 0) {
    console.error("Arguments to set! not in even pairs");
  }

  args
    .reduce((accumulator, item) => {
      if (accumulator[accumulator.length - 1].length === 2) {
        accumulator.push([item]);
      } else {
        accumulator[accumulator.length - 1].push(item);
      }

      return accumulator;
    }, [[]])
    .forEach(([variable, value]) => {
      if (variable.type !== 'word') {
        console.error("Can only set variables");
      }

      env[variable.value] = value.value;
    });

  // Return last argument since everything is an expression
  return args[args.length - 1];
}

// ***********************
// TESTS
// ***********************
function prettyPrint(expression) {
  console.log(JSON.stringify(expression, null, 2));
}

function testSingleExpression() {
  prettyPrint(parseExpression("   \"yaya\""));
  prettyPrint(parseExpression("   1234"));
  prettyPrint(parseExpression("   a,b"));
  prettyPrint(parseExpression("   a,   b"));
}

function testParseApply() {
  prettyPrint(parseExpression("do(if(true, +(1,2), false))"));
  prettyPrint(parseExpression("multiplier(2)(1)"));
}

function testSetEnv() {
  const env = {};
  const args = ['a', '1', 'b', '2'].map(item => parseExpression(item).expression);
  setEnv(env, args);
  console.log(env);
}
<|endoftext|>


<commit_before>Square = Class.create(Enemy, {
  initialize: function(x, y) {
    Sprite.call(this, 50, 50);
    this.image = game.assets['images/square_glow.png'];

    this.x = x;
    this.y = y;

    this.scoreValue = 20;

    this.speed = 5;
    this.currentPathController = "followPlayer";
    this.frame = 0;

    this.moveChoices = [
      [ "moveRandom", 45 ],
      [ "followPlayer", 70 ]
    ];
    this.moveChoicesTotalWeight = 0;
    for (var i = 0; i < this.moveChoices.length; i++)
      this.moveChoicesTotalWeight += this.moveChoices[i][1];
  },

  onenterframe: function() {
    this.collisionDetect();

    // Every 30 steps, choose random direction or follow
    if (!(this.age % 30 === 0)) return this[this.currentPathController]();

    var random = Math.floor(Math.random() * this.moveChoicesTotalWeight);
    var i, cumulativeWeight = 0;

    for (i = 0; i < this.moveChoices.length; i++) {
      cumulativeWeight += this.moveChoices[i][1];

      if (random < cumulativeWeight) {
        this.currentPathController = this.moveChoices[i][0];
        break;
      }
    }

    return this[this.currentPathController]();
  },

  moveRandom: function() {
    if (this.age % 30 === 0) {
      this.randomX = Math.floor(Math.random() * (game.width - (this.width / 2)));
      this.randomY = Math.floor(Math.random() * (game.height - (this.height / 2)));
      this.randomAngle = Math.atan2(this.randomX, this.randomY);
    }

    this.randomXSpeed = this.speed * Math.cos(this.randomAngle);
    this.randomYSpeed = this.speed * Math.sin(this.randomAngle);

    if (this.randomXSpeed === 0 && this.randomYSpeed === 0)
      this.randomXSpeed = 1;

    this.x += this.randomXSpeed;
    this.y += this.randomYSpeed;

    if (this.y < 0) this.y = 0;
    if (this.x < 0) this.x = 0;
    if (this.x + this.width > game.width) this.x = game.width - this.width;
    if (this.y + this.height > game.height) this.y = game.height - this.height;
  },

  followPlayer: function() {
    this.xVector = (newPlayer.x + (newPlayer.width / 2)) - (this.x + (this.width / 2));
    this.yVector = (newPlayer.y + (newPlayer.height / 2)) - (this.y + (this.height / 2));
    this.angle = Math.atan2(this.yVector, this.xVector);

    this.xSpeed = this.speed * Math.cos(this.angle);
    this.ySpeed = this.speed * Math.sin(this.angle);

    if (this.xSpeed === 0 && this.ySpeed === 0)
      this.xSpeed = 1;

    this.x += this.xSpeed;
    this.y += this.ySpeed;
  }
});
<commit_msg>remove unneeded followPlayer from Square<commit_after>Square = Class.create(Enemy, {
  initialize: function(x, y) {
    Sprite.call(this, 50, 50);
    this.image = game.assets['images/square_glow.png'];

    this.x = x;
    this.y = y;

    this.scoreValue = 20;

    this.speed = 5;
    this.currentPathController = "followPlayer";
    this.frame = 0;

    this.moveChoices = [
      [ "moveRandom", 45 ],
      [ "followPlayer", 70 ]
    ];
    this.moveChoicesTotalWeight = 0;
    for (var i = 0; i < this.moveChoices.length; i++)
      this.moveChoicesTotalWeight += this.moveChoices[i][1];
  },

  onenterframe: function() {
    this.collisionDetect();

    // Every 30 steps, choose random direction or follow
    if (!(this.age % 30 === 0)) return this[this.currentPathController]();

    var random = Math.floor(Math.random() * this.moveChoicesTotalWeight);
    var i, cumulativeWeight = 0;

    for (i = 0; i < this.moveChoices.length; i++) {
      cumulativeWeight += this.moveChoices[i][1];

      if (random < cumulativeWeight) {
        this.currentPathController = this.moveChoices[i][0];
        break;
      }
    }

    return this[this.currentPathController]();
  },

  moveRandom: function() {
    if (this.age % 30 === 0) {
      this.randomX = Math.floor(Math.random() * (game.width - (this.width / 2)));
      this.randomY = Math.floor(Math.random() * (game.height - (this.height / 2)));
      this.randomAngle = Math.atan2(this.randomX, this.randomY);
    }

    this.randomXSpeed = this.speed * Math.cos(this.randomAngle);
    this.randomYSpeed = this.speed * Math.sin(this.randomAngle);

    if (this.randomXSpeed === 0 && this.randomYSpeed === 0)
      this.randomXSpeed = 1;

    this.x += this.randomXSpeed;
    this.y += this.randomYSpeed;

    if (this.y < 0) this.y = 0;
    if (this.x < 0) this.x = 0;
    if (this.x + this.width > game.width) this.x = game.width - this.width;
    if (this.y + this.height > game.height) this.y = game.height - this.height;
  }
});
<|endoftext|>