<commit_before><commit_msg>Added event listeners for observable test<commit_after>describe('riot-view-router observable', function() {
  it('core methods are triggered as intended when referenced', function() {
    let event = ''
    router
      .on('navigate', () => event = 'navigate')
      .on('push', () => event = 'push')
      .on('start', () => event = 'start')
      .on('stop', () => event = 'stop')
      .on('reload', () => event = 'reload')
  })
})
<|endoftext|>


<commit_before><commit_msg>Update<commit_after>function defaultHttpErrorHandler(error, status) {
  if (typeof error !== 'undefined') {
    console.log('Error ' + status, error.message);
  } else {
    console.log('Unknown Error');
  }
}

function toast($mdToast, type, scope) {
  $mdToast.show({
    templateUrl: 'toast-' + type + '.html',
    controller: ['$scope', function ($scope) {
      $scope.action = 'ОК';
      $scope.resolve = function () { $mdToast.hide(); }

      $scope = angular.extend($scope, scope);
    }],
    hideDelay: 15000,
    position: 'bottom right',
    bindToController: true
  });
}<|endoftext|>


<commit_before>define(['app', 'lodash','moment',
  '../../../services/mongo-storage',
], function(app, _,moment) {

  app.factory("scheduleService", ['mongoStorage','$q','$document','$timeout',function(mongoStorage,$q,$document,$timeout) {
        //todovenues will be location or confrences
        var startDay,endDay,day,venue,venues,conference,conferences,conferenceDays,rooms,headersHeight,rowHeight,outerGridWidth,roomColumnEl,scrollGridEl,
        startTime,endTime,timeUnit,intervals,intervalKeys;

        init();
        //============================================================
        //
        //============================================================
        function init() {
          headersHeight='40';
          rowHeight='40';
          timeUnit=900.025;//15 minutes in seconds
          intervals = [];
          intervalKeys = [];
          initConferences().then(function(){
              initRooms().then(function(){
                initRowHeight();
                initHeaderHeight();
                initOuterGridWidth();
              });
          });
        }
        //============================================================
        //
        //============================================================
        function getTimeIntervals(start,end) {
              if(!startTime)startTime=start;
              if(!endTime)endTime=end;
              var seconds = endTime.diff(startTime)/1000;
              var hours = Math.ceil(seconds/3600);
              intervals = [];
              intervalKeys = [];
              var t = moment(startTime);
              var subIntervals = 3600/timeUnit;
              for(var  i=0; i< hours ; i++)
              {   var intervalObj={};
                  intervalObj.subIntervals=[];
                  intervalObj.interval=moment(t);
                  for(var  j=0; j< subIntervals ; j++)
                  {
                     intervalObj.subIntervals.push(moment(t));
                     t=t.add(timeUnit,'seconds');
                  }
                  intervalKeys.push(intervalObj);

              }
              // for(var  i=0; i< seconds; i=Math.floor(timeUnit)+i)
              // {
              //   intervalKeys.push(moment(t));
              //   t=t.add(timeUnit,'seconds');
              // }

              return intervalKeys;

        }//igetTimeIntervals

        //============================================================
        //
        //============================================================
        function getTimeIntervalsHeader(start,end) {
              if(!start && !end) return;

              if(!startTime)startTime=start;
              if(!endTime)endTime=end;
              var seconds = endTime.diff(startTime)/1000;
              var hours = Math.ceil(seconds/3600);
              intervals = [];
              intervalKeys = [];
              var t = moment(startTime);
              for(var  i=0; i< hours ; i++)
              {
                intervalKeys.push(moment(t));
                t=t.add(1,'hours');
              }

              return intervalKeys;

        }//igetTimeIntervals
        //============================================================
        //
        //============================================================
        function initRooms() {
          //todo check if id is conference or venue then load right rooms from right collection
              return mongoStorage.getConferenceRooms(conference._id).then(function(res) {
                rooms = res.data;
              });
        }//initRooms
        //============================================================
        //
        //============================================================
        function initHeaderHeight() {
                  headersHeight='40';
        }//initRooms
        //============================================================
        //
        //============================================================
        function initRowHeight() {
                $document.ready(function(){
                  $timeout(function(){
                    roomColumnEl=$document.find('#room-col');
                    rowHeight=Math.floor(Number(roomColumnEl.height())/rooms.length);
                  });
                });
        }//initRooms
        //============================================================
        //
        //============================================================
        function initOuterGridWidth() {
                $document.ready(function(){
                  $timeout(function(){
                    scrollGridEl=$document.find('#scroll-grid');
                    outerGridWidth=Number(scrollGridEl.width());
                  });
                });
        }//initRooms
        //============================================================
        //
        //============================================================
        function getOuterGridWidth() {

            return outerGridWidth;
        }// getOuterGridWidth

        //============================================================
        //
        //============================================================
        function getHeadersHeight() {

            return headersHeight;
        }// getHeadersHeight
        //============================================================
        //
        //============================================================
        function getRowHeight() {

            return rowHeight;
        }// getrowHeight
        //============================================================
        //
        //============================================================
        function getRooms() {

            var cancelInterval,count=0;
            return $q(function(resolve, reject) {
                      cancelInterval = setInterval(function(){
                          count++;
                          if(rooms && !_.isEmpty(rooms)){
                              clearInterval(cancelInterval);
                              resolve(rooms);
                          }else if(count===20){
                              reject('Failed to get rooms, timed out 2 seconds');
                          }
                      },100);
                   });
        }// getRooms

        //============================================================
        //
        //============================================================
        function getRoom(id) {
            var cancelInterval,count=0;
            return $q(function(resolve, reject) {
                      cancelInterval = setInterval(function(){
                          count++;
                          if(rooms && !_.isEmpty(rooms)){
                              clearInterval(cancelInterval);
                              resolve(_.find(rooms,{'_id':id}));
                          }else if(count===20){
                              reject('Failed to get room, timed out 2 seconds');
                          }
                      },100);
                   });
        }// getRooms

        //============================================================
        //
        //============================================================
        function getVenues() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(venues && !_.isEmpty(venues)){
                            clearInterval(cancelInterval);
                            resolve(venues);
                        }else if(count===20){
                            reject('Failed to get venues, timed out 2 seconds');
                        }
                    },100);
                 });
        }//getVenues()
        //============================================================
        //
        //============================================================
        function getVenue() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(venue && !_.isEmpty(venue)){
                            clearInterval(cancelInterval);
                            resolve(venue);
                        }else if(count===20){
                            reject('Failed to get venue, timed out 2 seconds');
                        }
                    },100);
                 });
        }//getVenue()
        //============================================================
        //
        //============================================================
        function getConferences() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(conferences && !_.isEmpty(conferences)){
                            clearInterval(cancelInterval);
                            resolve(conferences);
                        }else if(count===20){
                            reject('Failed to get venues, timed out 2 seconds');
                        }
                    },100);
                 });
        }//getVenues()
        //============================================================
        //
        //============================================================
        function getConference() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(conference && !_.isEmpty(conference)){
                            clearInterval(cancelInterval);
                            resolve(conference);
                        }else if(count===20){
                            reject('Failed to get venue, timed out 2 seconds');
                        }
                    },100);
                 });
        }//getVenue()
        //============================================================
        //
        //============================================================
        function getConferenceId() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(conference && !_.isEmpty(conference)){
                            clearInterval(cancelInterval);
                            resolve(conference._id);
                        }else if(count===20){
                            reject('Failed to get venueId, , timed out 2 seconds');
                        }
                    },100);
                 });
        }//getVenues()
        //============================================================
        //
        //============================================================
        function getVenueId() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(venue && !_.isEmpty(venue)){
                            clearInterval(cancelInterval);
                            resolve(venue._id);
                        }else if(count===20){
                            reject('Failed to get venueId, , timed out 2 seconds');
                        }
                    },100);
                 });
        }//getVenues()
        //============================================================
        //
        //============================================================
        function initVenues() {
          return mongoStorage.getVenues().then(function(confs) {
            venues = confs.data;
            var lowestEnd = Math.round(new Date().getTime() / 1000);
            var chosenEnd = 0;
            var selectedKey = 0;
            //select the next confrence by default
            _.each(venues, function(meet, key) {
              if (!chosenEnd) chosenEnd = meet.end;
              if (meet.end > lowestEnd && meet.end <= chosenEnd) {
                chosenEnd = meet.end;
                selectedKey = key;
              }
            });
            venues[selectedKey].selected = true;
            venue = venues[selectedKey];
          });
        } //initMeeting
        //============================================================
        //
        //============================================================
        function initConferences() {
          return mongoStorage.getConferences().then(function(confs) {
            conferences = confs.data;
            var lowestEnd = Math.round(new Date().getTime() / 1000);
            var chosenEnd = 0;
            var selectedKey = 0;
            //select the next confrence by default
            _.each(conferences, function(meet, key) {
              if (!chosenEnd) chosenEnd = meet.end;
              if (meet.end > lowestEnd && meet.end <= chosenEnd) {
                chosenEnd = meet.end;
                selectedKey = key;
              }
            });
            conferences[selectedKey].selected = true;
            conference = conferences[selectedKey];
            generateDays();
          });
        } //initMeeting

        //============================================================
        //
        //============================================================
        function generateDays() {
          conferenceDays = [];

          var numDays = Math.floor((Number(conference.end) - Number(conference.start)) / (24 * 60 * 60));
          var seconds = Number(conference.start);
          var date = moment.utc(seconds*1000).startOf('day');

          day = date.format('YYYY-MM-DD');
          startDay = date;

          for (var i = 1; i <= numDays +1; i++) {
            conferenceDays.push(date);
            if (i === numDays +1) {
              endDay = date;
            }
            date=date.add(1,'day');
          }
        }//
        //============================================================
        //
        //============================================================
        function getDay() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(day){
                            clearInterval(cancelInterval);
                            resolve(day);
                        }else if(count===20){
                            reject('Failed to get day, , timed out 2 seconds');
                        }
                    },100);
                 });
        }//
        //============================================================
        //
        //============================================================
        function getConferenceDays() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(conferenceDays && !_.isEmpty(conferenceDays)){
                            clearInterval(cancelInterval);
                            resolve(conferenceDays);
                        }else if(count===20){
                            reject('Failed to get conference Days, timed out 2 seconds');
                        }
                    },100);
                 });
        }//
        //============================================================
        //
        //============================================================
        function getStartDay() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(startDay && !_.isEmpty(startDay)){
                            clearInterval(cancelInterval);
                            resolve(startDay);
                        }else if(count===20){
                            reject('Failed to get conference start day, timed out 2 seconds');
                        }
                    },100);
                 });
        }//
        //============================================================
        //
        //============================================================
        function getEndDay() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(endDay && !_.isEmpty(endDay)){
                            clearInterval(cancelInterval);
                            resolve(endDay);
                        }else if(count===20){
                            reject('Failed to get conference end day, timed out 2 seconds');
                        }
                    },100);
                 });
        }//
        //============================================================
        //
        //============================================================
        function setVenue(venObj) {
              if(_.find(venues,{'_id':venObj._id})){
                  venue=venObj;
                  initRooms();
              }
              else
                throw 'error: setting venue without valid venue obj' ;
        } //setVenue

        return {
          getDay:getDay,
          getStartDay:getStartDay,
          getEndDay:getEndDay,
          getConferenceDays:getConferenceDays,
          getConferenceId:getConferenceId,
          getConference:getConference,
          getConferences:getConferences,
          getTimeIntervalsHeader:getTimeIntervalsHeader,
          getTimeIntervals:getTimeIntervals,
          getOuterGridWidth:getOuterGridWidth,
          getRowHeight:getRowHeight,
          getHeadersHeight:getHeadersHeight,
          getRoom: getRoom,
          getRooms: getRooms,
          getVenues:getVenues,
          getVenue:getVenue,
          getVenueId:getVenueId,
          setVenue:setVenue
        };
  }]);

});<commit_msg>get time intervals by conference and set selected conference<commit_after>define(['app', 'lodash','moment',
  '../../../services/mongo-storage',
], function(app, _,moment) {

  app.factory("scheduleService", ['mongoStorage','$q','$document','$timeout',function(mongoStorage,$q,$document,$timeout) {
        //todovenues will be location or confrences
        var startDay,endDay,day,venue,venues,conference,conferences,conferenceDays,rooms,headersHeight,rowHeight,outerGridWidth,roomColumnEl,scrollGridEl,
        startTime,endTime,timeUnit,intervals,intervalKeys,intervalKeysConference;

        init();
        //============================================================
        //
        //============================================================
        function init() {
          headersHeight='40';
          rowHeight='40';
          timeUnit=900.025;//15 minutes in seconds
          intervals = [];
          intervalKeys = [];
          initConferences().then(function(){
              initRooms().then(function(){
                initRowHeight();
                initHeaderHeight();
                initOuterGridWidth();
              });
          });
        }
        //============================================================
        //
        //============================================================
        function getTimeIntervals(start,end) {
              if(!startTime)startTime=start;
              if(!endTime)endTime=end;
              var seconds = endTime.diff(startTime)/1000;
              var hours = Math.ceil(seconds/3600);
              intervals = [];
              intervalKeys = [];
              var subIntervals = 3600/timeUnit;
              var t = moment(startTime);
              for(var  i=0; i< hours ; i++)
              {   var intervalObj={};
                  intervalObj.subIntervals=[];
                  intervalObj.interval=moment(t);
                  for(var  j=0; j< subIntervals ; j++)
                  {
                     intervalObj.subIntervals.push(moment(t));
                     t=t.add(timeUnit,'seconds');
                  }
                  intervalKeys.push(intervalObj);

              }
              return intervalKeys;
        }//igetTimeIntervals

        //============================================================
        //
        //============================================================
        function getTimeIntervalsConference(start,end) {
              if(!startTime)startTime=start;
              if(!endTime)endTime=end;
              if(startTime.isSame(start) && endTime.isSame(end) && intervalKeysConference && !_.isEmpty(intervalKeysConference))
              {
                    return intervalKeysConference;
              }
              var startHours = moment(startTime).hours();
              var startMinutes = moment(startTime).minutes();
              var diffSeconds =endTime.diff(startTime)/1000;
              intervalKeysConference=[];

              var hoursDiff = Math.ceil(diffSeconds/3600);
              intervals = [];
              intervalKeys = [];
              var subIntervals = 3600/timeUnit;
              var t ;
              _.each(conferenceDays,function(day){
                      t= moment(conferenceDays[0]);
                      t = moment.utc(t.startOf(day).add(startHours,'hours').add(startMinutes,'minutes'));
                      for(var  i=0; i< hoursDiff ; i++)
                      {   var intervalObj={};
                          intervalObj.subIntervals=[];
                          intervalObj.interval=moment.utc(t);
                          for(var  j=0; j< subIntervals ; j++)
                          {
                             intervalObj.subIntervals.push(moment.utc(t));
                             t=t.add(timeUnit,'seconds');
                          }
                          intervalKeysConference.push(intervalObj);
                      }
                      t=moment.utc(moment(conferenceDays[0]).startOf(day).add(1,'day').add(startHours,'hours').add(startMinutes,'minutes'));
              });

              return intervalKeys;
        }//igetTimeIntervals

        //============================================================
        //
        //============================================================
        function getTimeIntervalsHeader(start,end) {
              if(!start && !end) return;

              if(!startTime)startTime=start;
              if(!endTime)endTime=end;
              var seconds = endTime.diff(startTime)/1000;
              var hours = Math.ceil(seconds/3600);
              intervals = [];
              intervalKeys = [];
              var t = moment(startTime);
              for(var  i=0; i< hours ; i++)
              {
                intervalKeys.push(moment(t));
                t=t.add(1,'hours');
              }

              return intervalKeys;

        }//igetTimeIntervals
        //============================================================
        //
        //============================================================
        function initRooms() {
          //todo check if id is conference or venue then load right rooms from right collection
              return mongoStorage.getConferenceRooms(conference._id).then(function(res) {
                rooms = res.data;
              });
        }//initRooms
        //============================================================
        //
        //============================================================
        function initHeaderHeight() {
                  headersHeight='40';
        }//initRooms
        //============================================================
        //
        //============================================================
        function initRowHeight() {
                $document.ready(function(){
                  $timeout(function(){
                    roomColumnEl=$document.find('#room-col');
                    rowHeight=Math.floor(Number(roomColumnEl.height())/rooms.length);
                  });
                });
        }//initRooms
        //============================================================
        //
        //============================================================
        function initOuterGridWidth() {
                $document.ready(function(){
                  $timeout(function(){
                    scrollGridEl=$document.find('#scroll-grid');
                    outerGridWidth=Number(scrollGridEl.width());
                  });
                });
        }//initRooms
        //============================================================
        //
        //============================================================
        function getOuterGridWidth() {

            return outerGridWidth;
        }// getOuterGridWidth

        //============================================================
        //
        //============================================================
        function getHeadersHeight() {

            return headersHeight;
        }// getHeadersHeight
        //============================================================
        //
        //============================================================
        function getRowHeight() {

            return rowHeight;
        }// getrowHeight
        //============================================================
        //
        //============================================================
        function getRooms() {

            var cancelInterval,count=0;
            return $q(function(resolve, reject) {
                      cancelInterval = setInterval(function(){
                          count++;
                          if(rooms && !_.isEmpty(rooms)){
                              clearInterval(cancelInterval);
                              resolve(rooms);
                          }else if(count===20){
                              reject('Failed to get rooms, timed out 2 seconds');
                          }
                      },100);
                   });
        }// getRooms

        //============================================================
        //
        //============================================================
        function getRoom(id) {
            var cancelInterval,count=0;
            return $q(function(resolve, reject) {
                      cancelInterval = setInterval(function(){
                          count++;
                          if(rooms && !_.isEmpty(rooms)){
                              clearInterval(cancelInterval);
                              resolve(_.find(rooms,{'_id':id}));
                          }else if(count===20){
                              reject('Failed to get room, timed out 2 seconds');
                          }
                      },100);
                   });
        }// getRooms

        //============================================================
        //
        //============================================================
        function getVenues() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(venues && !_.isEmpty(venues)){
                            clearInterval(cancelInterval);
                            resolve(venues);
                        }else if(count===20){
                            reject('Failed to get venues, timed out 2 seconds');
                        }
                    },100);
                 });
        }//getVenues()
        //============================================================
        //
        //============================================================
        function getVenue() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(venue && !_.isEmpty(venue)){
                            clearInterval(cancelInterval);
                            resolve(venue);
                        }else if(count===20){
                            reject('Failed to get venue, timed out 2 seconds');
                        }
                    },100);
                 });
        }//getVenue()
        //============================================================
        //
        //============================================================
        function getConferences() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(conferences && !_.isEmpty(conferences)){
                            clearInterval(cancelInterval);
                            resolve(conferences);
                        }else if(count===20){
                            reject('Failed to get venues, timed out 2 seconds');
                        }
                    },100);
                 });
        }//getVenues()
        //============================================================
        //
        //============================================================
        function getConference() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(conference && !_.isEmpty(conference)){
                            clearInterval(cancelInterval);
                            resolve(conference);
                        }else if(count===20){
                            reject('Failed to get venue, timed out 2 seconds');
                        }
                    },100);
                 });
        }//getVenue()
        //============================================================
        //
        //============================================================
        function getConferenceId() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(conference && !_.isEmpty(conference)){
                            clearInterval(cancelInterval);
                            resolve(conference._id);
                        }else if(count===20){
                            reject('Failed to get venueId, , timed out 2 seconds');
                        }
                    },100);
                 });
        }//getVenues()
        //============================================================
        //
        //============================================================
        function getVenueId() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(venue && !_.isEmpty(venue)){
                            clearInterval(cancelInterval);
                            resolve(venue._id);
                        }else if(count===20){
                            reject('Failed to get venueId, , timed out 2 seconds');
                        }
                    },100);
                 });
        }//getVenues()
        //============================================================
        //
        //============================================================
        function initVenues() {
          return mongoStorage.getVenues().then(function(confs) {
            venues = confs.data;
            var lowestEnd = Math.round(new Date().getTime() / 1000);
            var chosenEnd = 0;
            var selectedKey = 0;
            //select the next confrence by default
            _.each(venues, function(meet, key) {
              if (!chosenEnd) chosenEnd = meet.end;
              if (meet.end > lowestEnd && meet.end <= chosenEnd) {
                chosenEnd = meet.end;
                selectedKey = key;
              }
            });
            venues[selectedKey].selected = true;
            venue = venues[selectedKey];
          });
        } //initMeeting
        //============================================================
        //
        //============================================================
        function initConferences() {
          return mongoStorage.getConferences().then(function(confs) {
            conferences = confs.data;
            var lowestEnd = Math.round(new Date().getTime() / 1000);
            var chosenEnd = 0;
            var selectedKey = 0;
            //select the next confrence by default
            _.each(conferences, function(meet, key) {
              if (!chosenEnd) chosenEnd = meet.end;
              if (meet.end > lowestEnd && meet.end <= chosenEnd) {
                chosenEnd = meet.end;
                selectedKey = key;
              }
            });
            conferences[selectedKey].selected = true;
            conference = conferences[selectedKey];
            generateDays();
          });
        } //initMeeting

        //============================================================
        //
        //============================================================
        function generateDays() {
          conferenceDays = [];
          var numDays = Math.floor((Number(conference.end) - Number(conference.start)) / (24 * 60 * 60));
          var seconds = Number(conference.start);
          var date = moment.utc(seconds*1000).startOf('day');

          day = date.format('YYYY-MM-DD');
          startDay = moment(date);

          for (var i = 1; i <= numDays +1; i++) {
            conferenceDays.push(moment(date));
            if (i === numDays +1) {
              endDay = date;
            }
            date=date.add(1,'day');

          }
        }//
        //============================================================
        //
        //============================================================
        function getDay() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(day){
                            clearInterval(cancelInterval);
                            resolve(day);
                        }else if(count===20){
                            reject('Failed to get day, , timed out 2 seconds');
                        }
                    },100);
                 });
        }//
        //============================================================
        //
        //============================================================
        function getConferenceDays() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(conferenceDays && !_.isEmpty(conferenceDays)){
                            clearInterval(cancelInterval);
                            resolve(conferenceDays);
                        }else if(count===20){
                            reject('Failed to get conference Days, timed out 2 seconds');
                        }
                    },100);
                 });
        }//
        //============================================================
        //
        //============================================================
        function getStartDay() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(startDay && !_.isEmpty(startDay)){
                            clearInterval(cancelInterval);
                            resolve(startDay);
                        }else if(count===20){
                            reject('Failed to get conference start day, timed out 2 seconds');
                        }
                    },100);
                 });
        }//
        //============================================================
        //
        //============================================================
        function getEndDay() {
          var cancelInterval,count=0;
          return $q(function(resolve, reject) {
                    cancelInterval = setInterval(function(){
                        count++;
                        if(endDay && !_.isEmpty(endDay)){
                            clearInterval(cancelInterval);
                            resolve(endDay);
                        }else if(count===20){
                            reject('Failed to get conference end day, timed out 2 seconds');
                        }
                    },100);
                 });
        }//
        //============================================================
        //
        //============================================================
        function setVenue(venObj) {
              if(_.find(venues,{'_id':venObj._id})){
                  venue=venObj;
                  initRooms();
              }
              else
                throw 'error: setting venue without valid venue obj' ;
        } //setVenue
        //============================================================
        //
        //============================================================
        function setConference(conf) {
              if(_.find(conferences,{'_id':conf._id})){
                  conference=conf;
                  generateDays();
                  initRooms();
              }
              else
                throw 'error: setting venue without valid venue obj' ;
        } //setVenue

        return {setConference:setConference,
          getTimeIntervalsConference:getTimeIntervalsConference,
          getDay:getDay,
          getStartDay:getStartDay,
          getEndDay:getEndDay,
          getConferenceDays:getConferenceDays,
          getConferenceId:getConferenceId,
          getConference:getConference,
          getConferences:getConferences,
          getTimeIntervalsHeader:getTimeIntervalsHeader,
          getTimeIntervals:getTimeIntervals,
          getOuterGridWidth:getOuterGridWidth,
          getRowHeight:getRowHeight,
          getHeadersHeight:getHeadersHeight,
          getRoom: getRoom,
          getRooms: getRooms,
          getVenues:getVenues,
          getVenue:getVenue,
          getVenueId:getVenueId,
          setVenue:setVenue
        };
  }]);

});<|endoftext|>


<commit_before>import { isObsolete } from '../../lib/catalog'

test('isObsolete should return false if catalog is not defined', () => {
  expect(isObsolete()).toBe(false)
})

test('isObsolete should return false if mostRecentRevisionDate is not defined', () => {
  expect(isObsolete({
    metrics: {}
  })).toBe(false)
})

test('isObsolete should return false if mostRecentRevisionDate is invalid', () => {
  expect(isObsolete({
    metrics: {
      mostRecentRevisionDate: 'not a valid date'
    }
  })).toBe(false)
})

test('isObsolete should return true if mostRecentRevisionDate is too old', () => {
  expect(isObsolete({
    metrics: {
      mostRecentRevisionDate: new Date(2000, 0, 1)
    }
  })).toBe(true)
})

test('isObsolete should return false if mostRecentRevisionDate is recent', () => {
  expect(isObsolete({
    metrics: {
      mostRecentRevisionDate: new Date()
    }
  })).toBe(false)
})

test('isObsolete should also work with strings', () => {
  expect(isObsolete({
    metrics: {
      mostRecentRevisionDate: new Date().toISOString()
    }
  })).toBe(false)
})
<commit_msg>Add tests for catalogs.findCandidates<commit_after>import { isObsolete, findCandidates } from '../../lib/catalog'

describe('isObsolete', () => {
  test('return false if catalog is not defined', () => {
    expect(isObsolete()).toBe(false)
  })

  test('return false if mostRecentRevisionDate is not defined', () => {
    expect(isObsolete({
      metrics: {}
    })).toBe(false)
  })

  test('return false if mostRecentRevisionDate is invalid', () => {
    expect(isObsolete({
      metrics: {
        mostRecentRevisionDate: 'not a valid date'
      }
    })).toBe(false)
  })

  test('return true if mostRecentRevisionDate is too old', () => {
    expect(isObsolete({
      metrics: {
        mostRecentRevisionDate: new Date(2000, 0, 1)
      }
    })).toBe(true)
  })

  test('return false if mostRecentRevisionDate is recent', () => {
    expect(isObsolete({
      metrics: {
        mostRecentRevisionDate: new Date()
      }
    })).toBe(false)
  })

  test('work with strings', () => {
    expect(isObsolete({
      metrics: {
        mostRecentRevisionDate: new Date().toISOString()
      }
    })).toBe(false)
  })
})

describe('findCandidates', () => {
  test('ignore catalogs without open or download data', () => {
    const catalogs = [{}, {}, {}]

    expect(findCandidates(catalogs).length).toBe(0)
  })

  test('excludes catalogs with just open data', () => {
    const catalogs = [{}, {
      metrics: {
        datasets: {
          partitions: { openness: { yes: 1 } }
        }
      }
    }, {}]

    expect(findCandidates(catalogs).length).toBe(0)
  })

  test('excludes catalogs with just download data', () => {
    const catalogs = [{}, {
      metrics: {
        datasets: {
          partitions: { download: { yes: 1 } }
        }
      }
    }, {}]

    expect(findCandidates(catalogs).length).toBe(0)
  })

  test('include catalogs with download and open data', () => {
    const catalogs = [{}, {
      metrics: {
        datasets: {
          partitions: {
            openness: { yes: 1 },
            download: { yes: 1 }
          }
        }
      }
    }, {}]

    expect(findCandidates(catalogs).length).toBe(1)
  })

  test('exclude blacklisted catalogs', () => {
    const catalogs = [{
      id: 1,
      metrics: {
        datasets: {
          partitions: {
            openness: { yes: 1 },
            download: { yes: 1 }
          }
        }
      }
    }, {
      id: 2,
      metrics: {
        datasets: {
          partitions: {
            openness: { yes: 1 },
            download: { yes: 1 }
          }
        }
      }
    }, {}]

    const candidates = findCandidates(catalogs, [1])
    expect(candidates.length).toBe(1)
    expect(candidates[0].id).toBe(2)
  })
})
<|endoftext|>


<commit_before>(function() {
  'use strict';
  angular.module('civic.activity')
    .directive('activityGrid', activityGrid)
    .controller('ActivityGridController', ActivityGridController);

  // @ngInject
  function activityGrid() {
    var directive = {
      restrict: 'E',
      replace: true,
      scope: {
        entity: '=', // site, user, organization
        id: '='
      },
      templateUrl: 'app/views/activity/directives/activityGrid.tpl.html',
      controller: 'ActivityGridController'
    };
    return directive;
  }

  // @ngInject
  function ActivityGridController($log,
                                  $scope,
                                  $state,
                                  $location,
                                  uiGridConstants,
                                  _,
                                  Events) {
    var ctrl = $scope.ctrl = {};

    var maxRows = ctrl.maxRows = 20;

    ctrl.events = $scope.events;

    ctrl.totalItems = Number();
    ctrl.page = $scope.page || 1;
    ctrl.count= maxRows;

    ctrl.filters = [];
    ctrl.sorting = [];

    ctrl.isFiltered = ctrl.filters.length > 0;

    $scope.$watch('ctrl.totalItems', function() {
      ctrl.totalPages = Math.ceil(ctrl.totalItems / maxRows);
    });

    ctrl.gridOptions = {
      enablePaginationControls: false,

      useExternalFiltering: true,
      useExternalSorting: true,
      useExternalPaging: true,

      paginationPageSizes: [maxRows],
      paginationPageSize: maxRows,
      minRowsToShow: maxRows-1,

      enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
      enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER,

      enableFiltering: false,
      enableColumnMenus: false,
      enableSorting: true,
      enableRowSelection: true,
      enableRowHeaderSelection: false,
      multiSelect: false,
      modifierKeysToMultiSelect: false,
      noUnselect: true,
      columnDefs: [
        { name: 'user',
          displayName: 'User',
          type: 'string',
          enableFiltering: true,
          allowCellFocus: false,
          enableSorting: false,
          width: '15%',
          cellTemplate: '
<user-block user="row.entity[col.field]"
',
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        { name: 'role',
          field: 'user.role',
          displayName: 'Role',
          enableFiltering: true,
          allowCellFocus: false,
          enableSorting: false,
          type: 'string',
          width: '8%',
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        { name: 'event_type',
          displayName: 'Event Type',
          enableFiltering: true,
          allowCellFocus: false,
          enableSorting: false,
          type: 'string',
          width: '20%',
          cellTemplate: '
' +
          '{{row.entity[col.field]}}' +
          ' (unlinkable)' +
          '
',
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'gene',
          field: 'state_params.gene.name',
          displayName: 'Gene',
          type: 'string',
          allowCellFocus: false,
          enableFiltering: false,
          enableSorting: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'variant',
          field: 'state_params.variant.name',
          displayName: 'Variant',
          type: 'string',
          width: '15%',
          allowCellFocus: false,
          enableFiltering: false,
          enableSorting: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'entity_id',
          displayName: 'Entity ID',
          type: 'string',
          allowCellFocus: false,
          enableFiltering: false,
          enableSorting: false,
          cellTemplate: 'app/views/activity/directives/entityIdCell.tpl.html',
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'entity_id_tooltip',
          type: 'string',
          allowCellFocus: false,
          enableFiltering: false,
          enableSorting: false,
          visible: false
        },
        {
          name: 'timestamp',
          field: 'timestamp',
          displayName: 'Timestamp',
          type: 'date',
          sort: {direction: uiGridConstants.DESC},
          allowCellFocus: false,
          enableFiltering: false,
          enableSorting: true,
          cellTemplate: '

',
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        }

      ]
    };
    ctrl.gridOptions.onRegisterApi = function(gridApi){
      ctrl.gridApi = gridApi;

      // called from pagination directive when page changes
      ctrl.pageChanged = function() {
        $log.info('page changed: ' + ctrl.page);
        $location.search('page', ctrl.page);
        updateData();
      };

      // reset paging and do some other stuff on filter changes
      gridApi.core.on.filterChanged($scope, function() {
        $log.info('filter changed.');
        // updateData with new filters
        var filteredCols = _.filter(this.grid.columns, function(col) {
          return _.has(col.filter, 'term') && !_.isEmpty(col.filter.term) && _.isString(col.filter.term);
        });
        if (filteredCols.length > 0) {
          ctrl.filters = _.map(filteredCols, function(col) {
            return {
              'field': col.field,
              'term': col.filter.term
            };
          });
        } else {
          ctrl.filters = [];
        }
        ctrl.page = 1;
        updateData();
      });

      gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
        $log.info('sort changed.');
        if (sortColumns.length > 0) {
          ctrl.sorting = _.map(sortColumns, function(col) {
            return {
              'field': col.field,
              'direction': col.sort.direction
            };
          });
        } else {
          ctrl.sorting = [];
        }
        updateData();
      });

      // called when user clicks on a row
      gridApi.selection.on.rowSelectionChanged($scope, function(row){
        var event = row.entity;
        var subjectStates = {
          assertions: 'events.assertions',
          genes: 'events.genes',
          variants: 'events.genes.summary.variants',
          variantgroups: 'events.genes.summary.variantGroups',
          evidenceitems: 'events.genes.summary.variants.summary.evidence',
          sources: 'sources'
        };

        // revision comments require some more logic to determine the proper state
        if(event.subject_type === 'suggestedchanges') {
          var state;
          var type = event.state_params.suggested_change.subject_type;
          if(type === 'evidenceitems') {
            state = 'events.genes.summary.variants.summary.evidence';
          } else if (type === 'variantgroups') {
            state = 'events.genes.summary.variantGroups';
          } else if (type === 'variants') {
            state = 'events.genes.summary.variants';
          } else if (type === 'genes') {
            state = 'events.genes';
          }
          subjectStates.suggestedchanges = state;
        }

        var stateExtension = {
          'commented': '.talk.comments',
          'submitted': '.summary',
          'accepted': '.summary',
          'assertion submitted': '.summary',
          'assertion accepted': '.summary',
          'assertion rejected': '.summary',
          'rejected': '.summary',
          'flagged': '.summary',
          'flag resolved': '.summary',
          'publication suggested': '.summary',
          'change suggested': '.talk.revisions.list.summary',
          'change accepted': '.talk.revisions.list.summary',
          'change rejected': '.talk.revisions.list.summary'
        };

        // revision comments are shown in their revision's summary view, override commented extension
        if(event.subject_type === 'suggestedchanges') {
          stateExtension.commented = '.talk.revisions.list.summary';
        }

        // sources display comments right on their summary page
        if(event.subject_type === 'sources') {
          stateExtension.commented = '.summary';
        }

        var stateParams = {};
        _.each(event.state_params, function(obj, entity) {
          var entityId;
          if(entity === 'suggested_change') {
            entityId = 'revisionId';
          } else if (entity === 'evidence_item') {
            entityId = 'evidenceId';
          } else if (entity === 'variant_group') {
            entityId = 'variantGroupId';
          } else if (entity === 'source') {
            entityId = 'sourceId';
          } else {
            entityId = entity + 'Id';
          }
          stateParams[entityId] = obj.id;
        });

        if (event.unlinkable === false) {
          $state.go(subjectStates[event.subject_type] + stateExtension[event.event_type], stateParams);
        }
      });
    };
    $scope.$watchCollection(function() {
      return Events.data.collection;
    }, function(events) {
      ctrl.gridOptions.data = parseData(events);
    });

    function parseData(events) {
      return _.map(events, function(event) {
        // create Entity column values
        var prefixes =  {
          assertions: 'AID',
          genes: 'GID',
          variants: 'VID',
          variantgroups: 'VGID',
          evidenceitems: 'EID',
          sources: 'SID'
        };
        var entity_prefix = prefixes[event.subject_type];
        event.entity_id = entity_prefix + event.subject_id;

        // create column for entity id tooltip
        var tooltipGenerators =  {
          assertions:function(params) { return params.assertion.name; },
          genes: function(params){ return params.gene.name; },
          variants: function(params){ return params.variant.name; },
          variantgroups: function(params){ return params.variantgroup.name; },
          evidenceitems: function(params){ return params.evidence_item.name; },
          sources: function(params){ return params.source.name; }
        };
        event.entity_id_tooltip = tooltipGenerators[event.subject_type](event.state_params);

        return event;
      });
    }

    function updateData() {
      fetchData(ctrl.count, ctrl.page, ctrl.sorting, ctrl.filters)
        .then(function(response) {
          if(_.isUndefined(response.total) && !_.isUndefined(response._meta)) {
            ctrl.totalItems = response._meta.total_count;
          } else if(!_.isUndefined(response.total)) {
            ctrl.totalItems = response.total;
          }
        });
    }

    function fetchData(count, page, sorting, filters) {
      var request;
      var entity = $scope.entity;
      var queryFunc;

      request= {
        count: count,
        page: page
      };
      if($scope.id) {
        request.id = $scope.id;
      }

      if (filters.length > 0) {
        _.each(filters, function(filter) {
          request['filter[' + filter.field + ']'] = filter.term;
        });
      }

      if (sorting.length > 0) {
        _.each(sorting, function(sort) {
          request['sorting[' + sort.field + ']'] = sort.direction;
        });
      }

      if(entity === 'site') {
        queryFunc = Events.query;
      } else if (entity === 'user') {
        queryFunc = Events.queryUserEvents;
      } else if(entity === 'organization') {
        queryFunc = Events.queryOrganizationEvents;
      } else {
        queryFunc = Events.query;
      }

      return queryFunc(request);
    }

    updateData();

  }

})();
<commit_msg>fixed activity grid bug w/ displaying suggested changes<commit_after>(function() {
  'use strict';
  angular.module('civic.activity')
    .directive('activityGrid', activityGrid)
    .controller('ActivityGridController', ActivityGridController);

  // @ngInject
  function activityGrid() {
    var directive = {
      restrict: 'E',
      replace: true,
      scope: {
        entity: '=', // site, user, organization
        id: '='
      },
      templateUrl: 'app/views/activity/directives/activityGrid.tpl.html',
      controller: 'ActivityGridController'
    };
    return directive;
  }

  // @ngInject
  function ActivityGridController($log,
                                  $scope,
                                  $state,
                                  $location,
                                  uiGridConstants,
                                  _,
                                  Events) {
    var ctrl = $scope.ctrl = {};

    var maxRows = ctrl.maxRows = 20;

    ctrl.events = $scope.events;

    ctrl.totalItems = Number();
    ctrl.page = $scope.page || 1;
    ctrl.count= maxRows;

    ctrl.filters = [];
    ctrl.sorting = [];

    ctrl.isFiltered = ctrl.filters.length > 0;

    $scope.$watch('ctrl.totalItems', function() {
      ctrl.totalPages = Math.ceil(ctrl.totalItems / maxRows);
    });

    ctrl.gridOptions = {
      enablePaginationControls: false,

      useExternalFiltering: true,
      useExternalSorting: true,
      useExternalPaging: true,

      paginationPageSizes: [maxRows],
      paginationPageSize: maxRows,
      minRowsToShow: maxRows-1,

      enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
      enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER,

      enableFiltering: false,
      enableColumnMenus: false,
      enableSorting: true,
      enableRowSelection: true,
      enableRowHeaderSelection: false,
      multiSelect: false,
      modifierKeysToMultiSelect: false,
      noUnselect: true,
      columnDefs: [
        { name: 'user',
          displayName: 'User',
          type: 'string',
          enableFiltering: true,
          allowCellFocus: false,
          enableSorting: false,
          width: '15%',
          cellTemplate: '
<user-block user="row.entity[col.field]"
',
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        { name: 'role',
          field: 'user.role',
          displayName: 'Role',
          enableFiltering: true,
          allowCellFocus: false,
          enableSorting: false,
          type: 'string',
          width: '8%',
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        { name: 'event_type',
          displayName: 'Event Type',
          enableFiltering: true,
          allowCellFocus: false,
          enableSorting: false,
          type: 'string',
          width: '20%',
          cellTemplate: '
' +
          '{{row.entity[col.field]}}' +
          ' (unlinkable)' +
          '
',
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'gene',
          field: 'state_params.gene.name',
          displayName: 'Gene',
          type: 'string',
          allowCellFocus: false,
          enableFiltering: false,
          enableSorting: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'variant',
          field: 'state_params.variant.name',
          displayName: 'Variant',
          type: 'string',
          width: '15%',
          allowCellFocus: false,
          enableFiltering: false,
          enableSorting: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'entity_id',
          displayName: 'Entity ID',
          type: 'string',
          allowCellFocus: false,
          enableFiltering: false,
          enableSorting: false,
          cellTemplate: 'app/views/activity/directives/entityIdCell.tpl.html',
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'entity_id_tooltip',
          type: 'string',
          allowCellFocus: false,
          enableFiltering: false,
          enableSorting: false,
          visible: false
        },
        {
          name: 'timestamp',
          field: 'timestamp',
          displayName: 'Timestamp',
          type: 'date',
          sort: {direction: uiGridConstants.DESC},
          allowCellFocus: false,
          enableFiltering: false,
          enableSorting: true,
          cellTemplate: '

',
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        }

      ]
    };
    ctrl.gridOptions.onRegisterApi = function(gridApi){
      ctrl.gridApi = gridApi;

      // called from pagination directive when page changes
      ctrl.pageChanged = function() {
        $log.info('page changed: ' + ctrl.page);
        $location.search('page', ctrl.page);
        updateData();
      };

      // reset paging and do some other stuff on filter changes
      gridApi.core.on.filterChanged($scope, function() {
        $log.info('filter changed.');
        // updateData with new filters
        var filteredCols = _.filter(this.grid.columns, function(col) {
          return _.has(col.filter, 'term') && !_.isEmpty(col.filter.term) && _.isString(col.filter.term);
        });
        if (filteredCols.length > 0) {
          ctrl.filters = _.map(filteredCols, function(col) {
            return {
              'field': col.field,
              'term': col.filter.term
            };
          });
        } else {
          ctrl.filters = [];
        }
        ctrl.page = 1;
        updateData();
      });

      gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
        $log.info('sort changed.');
        if (sortColumns.length > 0) {
          ctrl.sorting = _.map(sortColumns, function(col) {
            return {
              'field': col.field,
              'direction': col.sort.direction
            };
          });
        } else {
          ctrl.sorting = [];
        }
        updateData();
      });

      // called when user clicks on a row
      gridApi.selection.on.rowSelectionChanged($scope, function(row){
        var event = row.entity;
        var subjectStates = {
          assertions: 'events.assertions',
          genes: 'events.genes',
          variants: 'events.genes.summary.variants',
          variantgroups: 'events.genes.summary.variantGroups',
          evidenceitems: 'events.genes.summary.variants.summary.evidence',
          sources: 'sources'
        };

        // revision comments require some more logic to determine the proper state
        if(event.subject_type === 'suggestedchanges') {
          var state;
          var type = event.state_params.suggested_change.subject_type;
          if(type === 'evidenceitems') {
            state = 'events.genes.summary.variants.summary.evidence';
          } else if (type === 'variantgroups') {
            state = 'events.genes.summary.variantGroups';
          } else if (type === 'variants') {
            state = 'events.genes.summary.variants';
          } else if (type === 'genes') {
            state = 'events.genes';
          }
          subjectStates.suggestedchanges = state;
        }

        var stateExtension = {
          'commented': '.talk.comments',
          'submitted': '.summary',
          'accepted': '.summary',
          'assertion submitted': '.summary',
          'assertion accepted': '.summary',
          'assertion rejected': '.summary',
          'rejected': '.summary',
          'flagged': '.summary',
          'flag resolved': '.summary',
          'publication suggested': '.summary',
          'change suggested': '.talk.revisions.list.summary',
          'change accepted': '.talk.revisions.list.summary',
          'change rejected': '.talk.revisions.list.summary'
        };

        // revision comments are shown in their revision's summary view, override commented extension
        if(event.subject_type === 'suggestedchanges') {
          stateExtension.commented = '.talk.revisions.list.summary';
        }

        // sources display comments right on their summary page
        if(event.subject_type === 'sources') {
          stateExtension.commented = '.summary';
        }

        var stateParams = {};
        _.each(event.state_params, function(obj, entity) {
          var entityId;
          if(entity === 'suggested_change') {
            entityId = 'revisionId';
          } else if (entity === 'evidence_item') {
            entityId = 'evidenceId';
          } else if (entity === 'variant_group') {
            entityId = 'variantGroupId';
          } else if (entity === 'source') {
            entityId = 'sourceId';
          } else {
            entityId = entity + 'Id';
          }
          stateParams[entityId] = obj.id;
        });

        if (event.unlinkable === false) {
          $state.go(subjectStates[event.subject_type] + stateExtension[event.event_type], stateParams);
        }
      });
    };
    $scope.$watchCollection(function() {
      return Events.data.collection;
    }, function(events) {
      ctrl.gridOptions.data = parseData(events);
    });

    function parseData(events) {
      return _.map(events, function(event) {
        // create Entity column values
        var prefixes =  {
          assertions: 'AID',
          genes: 'GID',
          variants: 'VID',
          variantgroups: 'VGID',
          evidenceitems: 'EID',
          sources: 'SID',
          suggestedchanges: 'SC'
        };
        var entity_prefix = prefixes[event.subject_type];
        event.entity_id = entity_prefix + event.subject_id;

        // create column for entity id tooltip
        var tooltipGenerators =  {
          assertions:function(params) { return params.assertion.name; },
          genes: function(params){ return params.gene.name; },
          variants: function(params){ return params.variant.name; },
          variantgroups: function(params){ return params.variantgroup.name; },
          evidenceitems: function(params){ return params.evidence_item.name; },
          sources: function(params){ return params.source.name; },
          suggestedchanges: function(params){
            var id = params.suggested_change.id;
            return 'SC' + id;
          },

        };
        event.entity_id_tooltip = tooltipGenerators[event.subject_type](event.state_params);

        return event;
      });
    }

    function updateData() {
      fetchData(ctrl.count, ctrl.page, ctrl.sorting, ctrl.filters)
        .then(function(response) {
          if(_.isUndefined(response.total) && !_.isUndefined(response._meta)) {
            ctrl.totalItems = response._meta.total_count;
          } else if(!_.isUndefined(response.total)) {
            ctrl.totalItems = response.total;
          }
        });
    }

    function fetchData(count, page, sorting, filters) {
      var request;
      var entity = $scope.entity;
      var queryFunc;

      request= {
        count: count,
        page: page
      };
      if($scope.id) {
        request.id = $scope.id;
      }

      if (filters.length > 0) {
        _.each(filters, function(filter) {
          request['filter[' + filter.field + ']'] = filter.term;
        });
      }

      if (sorting.length > 0) {
        _.each(sorting, function(sort) {
          request['sorting[' + sort.field + ']'] = sort.direction;
        });
      }

      if(entity === 'site') {
        queryFunc = Events.query;
      } else if (entity === 'user') {
        queryFunc = Events.queryUserEvents;
      } else if(entity === 'organization') {
        queryFunc = Events.queryOrganizationEvents;
      } else {
        queryFunc = Events.query;
      }

      return queryFunc(request);
    }

    updateData();

  }

})();
<|endoftext|>


<commit_before>zk.$package("ganttz.resourceload");

ganttz.resourceload.ResourceLoadList = zk.$extends(zk.Widget,{
    $init : function(){
        this.$supers('$init', arguments);
        this.$class.setInstance(this);
    },
    bind_ : function(evt){
        this.$supers('bind_', arguments);
        this.domListen_(jq(window), 'onResize', 'adjustTimeTrackerSize');
        this.domListen_(jq('.rightpanellayout div:first'), 'onScroll', '_listenToScroll');
    },
    unbind_ : function(evt){
        this.domUnlisten_(jq(window), 'onResize', 'adjustTimeTrackerSize');
        this.domUnlisten_(jq('.rightpanellayout div:first'), 'onScroll', '_listenToScroll');
        this.$supers('unbind_', arguments);
    },
    recalculateTimeTrackerHeight : function(){
        var DOMResourceLoadList = jq('.resourceloadlist');
        var DOMfirstWatermarkColumn = jq('.rightpanellayout tr#watermark td :first');

        if ( DOMResourceLoadList != undefined && DOMfirstWatermarkColumn != undefined){
            DOMResourceLoadList.height(
                    Math.max(
                            DOMResourceLoadList.innerHeight() + this.$class.WATERMARK_MARGIN_BOTTOM,
                            this.$class.WATERMARK_MIN_HEIGHT));
        }
    },
    adjustTimeTrackerSize : function(){
        this.recalculateTimeTrackerHeight();

        /*We can't use this.getHeight() as the _height property
         * won't be set for this object and even
         *
         * TODO: maybe create a _height property and update it
         * when it changes (recalculateTimeTrackerHeight) son we avoid
         * using DOM selectors
         * */
        jq('#watermark').height(jq(this.$n()).innerHeight());
        jq('#timetracker').width(jq(this.$n()).innerWidth());

        jq('.resourceloadlist').width(jq('.second_level_ :first'));
    },
    _listenToScroll : function(){
        var scrolledPannelScrollLeft = jq('.rightpanellayout div:first').scrollLeft();
        var scrolledPannelScrollTop = jq('.rightpanellayout div:first').scrollTop();

        jq('canvas.timeplot-canvas').css("left", "-" + scrolledPannelScrollLeft + "px");
        jq('.timetrackergap').css("left", "-" + scrolledPannelScrollLeft + "px");
        jq('.leftpanelgap .z-tree-body').css("top", "-" + scrolledPannelScrollTop + "px");
        jq('.resourcesloadgraph div').scrollLeft(scrolledPannelScrollLeft + "px");
    }
},{ //Class stuff
    WATERMARK_MIN_HEIGHT : 450,
    WATERMARK_MARGIN_BOTTOM : 40,
    setInstance : function(instance){
        this._instance = instance;
    },
    getInstance : function(){
        return this._instance;
    }
});<commit_msg>Added method to ResourceLoadList<commit_after>zk.$package("ganttz.resourceload");

ganttz.resourceload.ResourceLoadList = zk.$extends(zk.Widget,{
    $init : function(){
        this.$supers('$init', arguments);
        this.$class.setInstance(this);
    },
    bind_ : function(evt){
        this.$supers('bind_', arguments);
        this.domListen_(jq(window), 'onResize', 'adjustTimeTrackerSize');
        this.domListen_(jq('.rightpanellayout div:first'), 'onScroll', '_listenToScroll');
    },
    unbind_ : function(evt){
        this.domUnlisten_(jq(window), 'onResize', 'adjustTimeTrackerSize');
        this.domUnlisten_(jq('.rightpanellayout div:first'), 'onScroll', '_listenToScroll');
        this.$supers('unbind_', arguments);
    },
    recalculateTimeTrackerHeight : function(){
        var DOMResourceLoadList = jq('.resourceloadlist');
        var DOMfirstWatermarkColumn = jq('.rightpanellayout tr#watermark td :first');

        if ( DOMResourceLoadList != undefined && DOMfirstWatermarkColumn != undefined){
            DOMResourceLoadList.height(
                    Math.max(
                            DOMResourceLoadList.innerHeight() + this.$class.WATERMARK_MARGIN_BOTTOM,
                            this.$class.WATERMARK_MIN_HEIGHT));
        }
    },
    adjustTimeTrackerSize : function(){
        this.recalculateTimeTrackerHeight();

        /*We can't use this.getHeight() as the _height property
         * won't be set for this object and even
         *
         * TODO: maybe create a _height property and update it
         * when it changes (recalculateTimeTrackerHeight) son we avoid
         * using DOM selectors
         * */
        jq('#watermark').height(jq(this.$n()).innerHeight());
        jq('#timetracker').width(jq(this.$n()).innerWidth());

        /*this.$n() is <div class="resourceloadlist" ...>*/
        jq(this.$n()).width(jq('.second_level_ :first'));
    },
    adjustResourceLoadRows : function(){
        jq('.row_resourceload').each(jq.proxy(function(index, element){
            jq(element).width( jq(this.$n()).innerWidth() );
        }, this));
    },
    _listenToScroll : function(){
        var scrolledPannelScrollLeft = jq('.rightpanellayout div:first').scrollLeft();
        var scrolledPannelScrollTop = jq('.rightpanellayout div:first').scrollTop();

        jq('canvas.timeplot-canvas').css("left", "-" + scrolledPannelScrollLeft + "px");
        jq('.timetrackergap').css("left", "-" + scrolledPannelScrollLeft + "px");
        jq('.leftpanelgap .z-tree-body').css("top", "-" + scrolledPannelScrollTop + "px");
        jq('.resourcesloadgraph div').scrollLeft(scrolledPannelScrollLeft + "px");
    }
},{ //Class stuff
    WATERMARK_MIN_HEIGHT : 450,
    WATERMARK_MARGIN_BOTTOM : 40,
    setInstance : function(instance){
        this._instance = instance;
    },
    getInstance : function(){
        return this._instance;
    }
});<|endoftext|>


<commit_before>var _ = require('underscore');

module.exports = {
  type: 'concave-hull',
  label: _t('editor.layers.analysis-form.concave-hull'),
  parametersDataFields: 'source,type,target_percentage,allow_holes,category_column',

  parse: function (nodeAttrs) {
    if (!nodeAttrs.aggregation_column) {
      nodeAttrs.aggregation_column = 'cartodb_id';
    }
    if (!nodeAttrs.aggregation) {
      nodeAttrs.aggregation = 'count';
    }

    var aggregate = {
      operator: nodeAttrs.aggregation,
      attribute: nodeAttrs.aggregation === 'count' ? '' : nodeAttrs.aggregation_column
    };

    return {
      type: 'concave-hull',
      target_percentage: nodeAttrs.target_percent ? nodeAttrs.target_percent * 100 : 70,
      category_column: nodeAttrs.category_column,
      aggregate: aggregate
    };
  },

  formatAttrs: function (formAttrs) {
    formAttrs = _.pick(formAttrs, ['id'].concat(this.parametersDataFields.split(',')));

    formAttrs.target_percent = formAttrs.target_percentage / 100;
    formAttrs = _.omit(formAttrs, 'target_percentage');

    if (!formAttrs.aggregation_column) {
      formAttrs = _.omit(formAttrs, 'aggregation_column');
    }

    if (!formAttrs.allow_holes) {
      formAttrs = _.omit(formAttrs, 'allow_holes');
    }

    if (!formAttrs.category_column) {
      formAttrs = _.omit(formAttrs, 'category_column');
    }

    return formAttrs;
  }
};

<commit_msg>Fixes zero condition<commit_after>var _ = require('underscore');

module.exports = {
  type: 'concave-hull',
  label: _t('editor.layers.analysis-form.concave-hull'),
  parametersDataFields: 'source,type,target_percentage,allow_holes,category_column',

  parse: function (nodeAttrs) {
    if (!nodeAttrs.aggregation_column) {
      nodeAttrs.aggregation_column = 'cartodb_id';
    }
    if (!nodeAttrs.aggregation) {
      nodeAttrs.aggregation = 'count';
    }

    var aggregate = {
      operator: nodeAttrs.aggregation,
      attribute: nodeAttrs.aggregation === 'count' ? '' : nodeAttrs.aggregation_column
    };

    var target_percentage = 70;

    if (nodeAttrs.target_percent === 0) {
      target_percentage = 0;
    } else if (nodeAttrs.target_percent) {
      target_percentage = nodeAttrs.target_percent * 100;
    }

    return {
      type: 'concave-hull',
      target_percentage: target_percentage,
      category_column: nodeAttrs.category_column,
      aggregate: aggregate
    };
  },

  formatAttrs: function (formAttrs) {
    formAttrs = _.pick(formAttrs, ['id'].concat(this.parametersDataFields.split(',')));

    formAttrs.target_percent = formAttrs.target_percentage / 100;
    formAttrs = _.omit(formAttrs, 'target_percentage');

    if (!formAttrs.aggregation_column) {
      formAttrs = _.omit(formAttrs, 'aggregation_column');
    }

    if (!formAttrs.allow_holes) {
      formAttrs = _.omit(formAttrs, 'allow_holes');
    }

    if (!formAttrs.category_column) {
      formAttrs = _.omit(formAttrs, 'category_column');
    }

    return formAttrs;
  }
};

<|endoftext|>


<commit_before>/*
 * Copyright (c) Novedia Group 2012.
 *
 *     This file is part of Hubiquitus.
 *
 *     Hubiquitus is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     Hubiquitus is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with Hubiquitus.  If not, see <http://www.gnu.org/licenses/>.
 */

var xmpp = require('./xmpp_connector.js');
var clients = {};

//For logging
var path = require('path');
var filename = "[" + path.basename(path.normalize(__filename)) + "]";
var log = require('log4js').getLogger(filename); //Use Case: log.info("Info to be logged");

/**
 * Function to be used to start the connector. Default parameters can be found in options.js
 * @param options overrided options in JSON format. Look at options.js to see possibilities.
 */
exports.startSocketIOConnector = function(opts){
    var io = require('socket.io').listen(opts['socket.io.port']); //Creates the HTTP server

    var logLevels = { DEBUG: 3, INFO: 2, WARN: 1, ERROR: 0 };
    io.set('log level', logLevels[opts['global.loglevel']]);
    log.setLevel(opts['global.loglevel']);

    var channel = io
      .of(opts['socket.io.namespace'])
      .on('connection', function (socket) {
            var id = socket.id;
            clients[id] = {};
            clients[id].socketioConnection = socket;
            clients[id].id = id;
            socket.on('connect', function(data){ connect(clients[id], data); });
            socket.on('disconnect', function(){ disconnect(clients[id]); });
            socket.on('subscribe', function(data){ subscribe(clients[id], data); });
            socket.on('unsubscribe', function(data){ unsubscribe(clients[id], data); });
            socket.on('publish', function(data) { publish(clients[id], data); });
    });
};

/**
 * @param client - Reference to the client
 * @param data - Received data from the server
 */
function connect(client, data){
    log.info("Client ID " + client.id +  " sent data: " + JSON.stringify(data));

    client.xmppConnection = new xmpp.XMPPConnector(data.parameters, function(status){
        client.socketioConnection.emit('status', status); });

    client.xmppConnection.connect(function(message){
        client.socketioConnection.emit('connect', message);
        log.info("Sent to client " + client.id + " : " + message);
    });
};

/**
* @param client - Reference to the client to be disconnected
*/
function disconnect(client){
    log.warn('Disconnecting Client ' + client.id);
    client.xmppConnection.disconnect();
};

/**
 * Subscribes to the node passed in data
 * @param client - Reference to the client that will be subscribed
 * @param data - Contains the node to be subscribed
 */
function subscribe(client, data){
    log.info('Client ID ' + client.id  + ' sent data: ' + JSON.stringify(data));

    if(checkConditions(client, 'subscribe'))
        client.xmppConnection.subscribe(data.nodeName, function(res){
            client.socketioConnection.emit('subscribe', res);
        });
};

/**
 * Unsubscribes from the node passed in data
 * @param client - Reference to the client to be unsubscribed
 * @param data - Contains the node to unsubscribe from and (optionally) the subID.
 */
function unsubscribe(client, data){
    log.info('Client ID ' + client.id  + ' sent data: ' + JSON.stringify(data));

    if(checkConditions(client, 'unsubscribe'))
        client.xmppConnection.unsubscribe(data.nodeName, data.subID, function(res){
            client.socketioConnection.emit('unsubscribe', res);
        });
};

/**
 * Publishes an entry to a node that is passed in data
 * @param client - Reference to the client that will publish
 * @param data - Contains the node and the optionally the entry to publish
 */
function publish(client, data){
    log.info('Client ID ' + client.id  + ' sent data: ' + JSON.stringify(data));

    if(checkConditions(client, 'publish'))
        for(var i in data.items)
            client.xmppConnection.publish(data.nodeName, data.items[i], function(res){
                client.socketioConnection.emit('publish', res);
            });
};

/**
 * Checks if the conditions are correct to execute the actions. A connection must exist and must have been established
 * @param client - Reference to the client to check
 * @param action - Action that wants to be performed
 */
function checkConditions(client, action){
    if(!client.xmppConnection || (client.xmppConnection && client.xmppConnection.status != xmpp.statuses.connected)){
        log.error('Client ID ' + client.id + ' tried to execute ' + action
            + ' , but the client is not connected. Aborting' );
        return false;
    }
    return true;
};<commit_msg>Refactored client<commit_after>/*
 * Copyright (c) Novedia Group 2012.
 *
 *     This file is part of Hubiquitus.
 *
 *     Hubiquitus is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     Hubiquitus is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with Hubiquitus.  If not, see <http://www.gnu.org/licenses/>.
 */

var xmpp = require('./xmpp_connector.js');
var clients = {};

//For logging
var path = require('path');
var filename = "[" + path.basename(path.normalize(__filename)) + "]";
var log = require('log4js').getLogger(filename); //Use Case: log.info("Info to be logged");

/**
 * Function to be used to start the connector. Default parameters can be found in options.js
 * @param options overrided options in JSON format. Look at options.js to see possibilities.
 */
exports.startSocketIOConnector = function(opts){
    var io = require('socket.io').listen(opts['socket.io.port']); //Creates the HTTP server

    var logLevels = { DEBUG: 3, INFO: 2, WARN: 1, ERROR: 0 };
    io.set('log level', logLevels[opts['global.loglevel']]);
    log.setLevel(opts['global.loglevel']);

    var channel = io
      .of(opts['socket.io.namespace'])
      .on('connection', function (socket) {
            var id = socket.id;
            clients[id] = {
                id : id,
                socketioConnection : socket
            };
            socket.on('connect', function(data){ connect(clients[id], data); });
            socket.on('disconnect', function(){ disconnect(clients[id]); });
            socket.on('subscribe', function(data){ subscribe(clients[id], data); });
            socket.on('unsubscribe', function(data){ unsubscribe(clients[id], data); });
            socket.on('publish', function(data) { publish(clients[id], data); });
    });
};

/**
 * @param client - Reference to the client
 * @param data - Received data from the server
 */
function connect(client, data){
    log.info("Client ID " + client.id +  " sent data: " + JSON.stringify(data));

    client.xmppConnection = new xmpp.XMPPConnector(data.parameters, function(status){
        client.socketioConnection.emit('status', status); });

    client.xmppConnection.connect(function(message){
        client.socketioConnection.emit('connect', message);
        log.info("Sent to client " + client.id + " : " + message);
    });
};

/**
* @param client - Reference to the client to be disconnected
*/
function disconnect(client){
    log.warn('Disconnecting Client ' + client.id);
    client.xmppConnection.disconnect();
};

/**
 * Subscribes to the node passed in data
 * @param client - Reference to the client that will be subscribed
 * @param data - Contains the node to be subscribed
 */
function subscribe(client, data){
    log.info('Client ID ' + client.id  + ' sent data: ' + JSON.stringify(data));

    if(checkConditions(client, 'subscribe'))
        client.xmppConnection.subscribe(data.nodeName, function(res){
            client.socketioConnection.emit('subscribe', res);
        });
};

/**
 * Unsubscribes from the node passed in data
 * @param client - Reference to the client to be unsubscribed
 * @param data - Contains the node to unsubscribe from and (optionally) the subID.
 */
function unsubscribe(client, data){
    log.info('Client ID ' + client.id  + ' sent data: ' + JSON.stringify(data));

    if(checkConditions(client, 'unsubscribe'))
        client.xmppConnection.unsubscribe(data.nodeName, data.subID, function(res){
            client.socketioConnection.emit('unsubscribe', res);
        });
};

/**
 * Publishes an entry to a node that is passed in data
 * @param client - Reference to the client that will publish
 * @param data - Contains the node and the optionally the entry to publish
 */
function publish(client, data){
    log.info('Client ID ' + client.id  + ' sent data: ' + JSON.stringify(data));

    if(checkConditions(client, 'publish'))
        for(var i in data.items)
            client.xmppConnection.publish(data.nodeName, data.items[i], function(res){
                client.socketioConnection.emit('publish', res);
            });
};

/**
 * Checks if the conditions are correct to execute the actions. A connection must exist and must have been established
 * @param client - Reference to the client to check
 * @param action - Action that wants to be performed
 */
function checkConditions(client, action){
    if(!client.xmppConnection || (client.xmppConnection && client.xmppConnection.status != xmpp.statuses.connected)){
        log.error('Client ID ' + client.id + ' tried to execute ' + action
            + ' , but the client is not connected. Aborting' );
        return false;
    }
    return true;
};<|endoftext|>