<commit_before>'use strict';

angular.module('confRegistrationWebApp')
  .controller('AdminDataCtrl', function ($scope, registrations, conference, $modal, permissions, $http, uuid, RegistrationCache) {

    $scope.conference = conference;
    $scope.blocks = [];
    $scope.reversesort = false;
    $scope.showAllViewId = 'all';
    $scope.defaultViewId = 'default';
    $scope.activeRegViewId = $scope.defaultViewId;
    $scope.savedState = '';

    // collect completed registrations
    registrations = _.filter(registrations, function (item) { return item.completed !== false; });

    // collect all 'Content' blocks from the conferences' pages
    angular.forEach(conference.registrationPages, function (page) {
      angular.forEach(page.blocks, function (block) {
        if (block.type.indexOf('Content') === -1) {
          block.visible = true;
          $scope.blocks.push(block);
        }
      });
    });

    // get all the registration views for this conference
    $http({method: 'GET',
      url: 'conferences/' + conference.id + '/registration-views'
    }).success(function (data) {
      $scope.registrationViews = _.sortBy(data, 'name');

      var profileBlocks = function (blocks) {
        return _.filter(blocks, function (block) {
          var profileTypes = [ 'EMAIL', 'NAME' ];
          return profileTypes.indexOf(block.profileType) > -1;
        });
      };

      $scope.registrationViewsDropdown = [
        {
          id: $scope.defaultViewId,
          name: '-Default-',
          visibleBlockIds: _.pluck(profileBlocks($scope.blocks), 'id')
        },
        {
          id: $scope.showAllViewId,
          name: '-Show All-',
          visibleBlockIds: _.pluck($scope.blocks, 'id')
        }
      ];

      $scope.registrationViewsDropdown = $scope.registrationViewsDropdown.concat($scope.registrationViews);
      $scope.setRegView();
    });

    // toggle (show/hide) the column and auto save the registration view
    $scope.toggleColumn = function (block) {
      $scope.blocks[block].visible = !$scope.blocks[block].visible;
      $scope.updateRegView();
    };

    // set the registration view as per the active registration view id
    $scope.setRegView = function () {
      $scope.savedState = '';
      if ($scope.activeRegViewId === '') {

      } else {
        var visibleBlocks = _.find($scope.registrationViewsDropdown, { 'id': $scope.activeRegViewId }).visibleBlockIds;
        angular.forEach($scope.blocks, function (block) {
          if (visibleBlocks.indexOf(block.id) !== -1) {
            block.visible = true;
          } else if (block.type.indexOf('Content') === -1) {
            block.visible = false;
          }
        });
      }
    };

    // create a registration view
    $scope.createRegView = function () {
      $modal.open({
        templateUrl: 'views/regViewCreate.html',
        controller: 'CreateDialogCtrl',
        resolve: {
          defaultValue: function () {
            return '';
          }
        }
      }).result.then(function (viewName) {
        if (viewName !== '') {

        var regViewNames = _.pluck($scope.registrationViewsDropdown, 'name');
          if (regViewNames.indexOf(viewName) > -1) {
            var errorModalOptions = {
              templateUrl: 'views/errorModal.html',
              controller: 'genericModal',
              resolve: {
                message: function () {
                  return 'View name "' + viewName + '" already exists. Please provide a different view name.';
                }
              }
            };
            $modal.open(errorModalOptions);

            return;
          }

          var newView = {
            id: uuid(),
            conferenceId: conference.id,
            name: viewName,
            visibleBlockIds: _.pluck(_.filter($scope.blocks, function (item) {
              return item.visible === true;
            }), 'id')
          };

          $http({method: 'POST',
            url: 'conferences/' + conference.id + '/registration-views',
            data: newView
          }).success(function () {
            $scope.registrationViews = $scope.registrationViews.concat(newView);
            $scope.registrationViewsDropdown = $scope.registrationViewsDropdown.concat(newView);
            $scope.activeRegViewId = newView.id;
          }).error(function () {
          });
        }
      });
    };

    // update a registration view
    $scope.updateRegView = function () {

      // don't update predefined view
      if ($scope.isPredefinedView($scope.activeRegViewId))
      {
        return;
      }

      var thisView = {
        id: $scope.activeRegViewId,
        conferenceId: conference.id,
        name: _.find($scope.registrationViewsDropdown, { 'id': $scope.activeRegViewId }).name,
        visibleBlockIds: _.pluck(_.filter($scope.blocks, function (item) {
          return item.visible === true;
        }), 'id')
      };

      $scope.savedState = 'Saving...';
      $http({method: 'PUT',
        url: 'registration-views/' + $scope.activeRegViewId,
        data: thisView
      }).success(function () {
        $scope.registrationViews = _.remove($scope.registrationViews, function (view) { return view.id !== $scope.activeRegViewId; });
        $scope.registrationViewsDropdown = _.remove($scope.registrationViewsDropdown, function (view) {
          return view.id !== $scope.activeRegViewId;
        });
        $scope.registrationViews = $scope.registrationViews.concat(thisView);
        $scope.registrationViewsDropdown = $scope.registrationViewsDropdown.concat(thisView);
        $scope.activeRegViewId = thisView.id;
        $scope.savedState = 'Saved';
      }).error(function () {
      });
    };

    // delete a registration view
    $scope.delRegView = function () {

      // don't delete predefined views
      if ($scope.isPredefinedView($scope.activeRegViewId))
      {
        return;
      }

      $http({method: 'DELETE',
        url: 'registration-views/' + $scope.activeRegViewId
      }).success(function () {
        $scope.registrationViews = _.remove($scope.registrationViews, function (view) { return view.id !== $scope.activeRegViewId; });
        $scope.registrationViewsDropdown = _.remove($scope.registrationViewsDropdown, function (view) {
          return view.id !== $scope.activeRegViewId;
        });

        $scope.activeRegViewId = $scope.defaultViewId;
        $scope.setRegView();

      }).error(function () {
      });
    };

    $scope.findAnswer = function (registration, blockId) {
      return _.find(registration.answers, function (answer) {
        return angular.equals(answer.blockId, blockId);
      });
    };

    $scope.getSelectedCheckboxes = function (choices) {
      return _.keys(_.pick(choices, function (val) {
        return val === true;
      }));
    };

    $scope.answerSort = function (registration) {
      if (angular.isDefined($scope.order)) {
        if (angular.isDefined($scope.findAnswer(registration, $scope.order))) {
          if ($scope.findAnswer(registration, $scope.order).value.text) { //text field
            return $scope.findAnswer(registration, $scope.order).value.text;
          } else if ($scope.getSelectedCheckboxes($scope.findAnswer(registration, $scope.order).value).length > 0) {
            //mc
            return $scope.getSelectedCheckboxes($scope.findAnswer(registration, $scope.order).value).join(' ');
          } else if (typeof $scope.findAnswer(registration, $scope.order).value === 'object') { //name
            return _.values($scope.findAnswer(registration, $scope.order).value).join(' ');
          } else { //radio
            return $scope.findAnswer(registration, $scope.order).value;
          }
        }
      } else {
        return 0;
      }
    };

    $scope.setOrder = function (order) {
      if (order === $scope.order) {
        $scope.reversesort = !$scope.reversesort;
      } else {
        $scope.reversesort = false;
      }
      $scope.order = order;
    };

    $scope.registrations = registrations;
    $scope.permissions = permissions;

    $scope.viewPayments = function (registration) {
      var paymentModalOptions = {
        templateUrl: 'views/paymentsModal.html',
        controller: 'paymentModal',
        backdrop: 'static',
        keyboard: false,
        resolve: {
          data: function () {
            return registration;
          }
        }
      };

      $modal.open(paymentModalOptions).result.then(function (updatedRegistration) {
        var localUpdatedRegistration = _.find(registrations, function (reg){
          return reg.id === updatedRegistration.id;
        });
        localUpdatedRegistration.pastPayments = updatedRegistration.pastPayments;
      });
    };

    $scope.isPredefinedView = function (regViewId) {
      var predefinedViews = [ $scope.showAllViewId, $scope.defaultViewId ];
      return predefinedViews.indexOf(regViewId) > -1;
    };

    $scope.isConferenceCost = function () {
      return conference.conferenceCost > 0;
    };

    // define payment categories
    $scope.paymentCategories = [
      {
        name: 'Show All',
        matches: function () {
          return true;
        }
      },
      {
        name: 'Full',
        matches: function (x, y) {
          return x === y;
        }
      },
      {
        name: 'Partial',
        matches: function (x, y) {
          return x > 0 && x < y;
        }
      },
      {
        name: 'Full/Partial',
        matches: function (x) {
          return x > 0;
        }
      },
      {
        name: 'Not Paid',
        matches: function (x) {
          if (x === null) {
            return true;
          }

          return x <= 0;
        }
      }
    ];

    // set current to first in array
    $scope.currentPaymentCategory = _.first($scope.paymentCategories).name;

    // determine if registration payment status matches current payment category
    $scope.paymentStatus = function (registration) {

      var paymentCategory = _.find($scope.paymentCategories, { 'name': $scope.currentPaymentCategory });

      return paymentCategory.matches(registration.totalPaid, registration.totalDue);
    };

    $scope.paidInFull = function (registration) {
      return registration.totalPaid >= registration.totalDue;
    }
  });
<commit_msg>Update a few more fields on the parent registration to ensure that the adminData view is up to date when the modal closes<commit_after>'use strict';

angular.module('confRegistrationWebApp')
  .controller('AdminDataCtrl', function ($scope, registrations, conference, $modal, permissions, $http, uuid, RegistrationCache) {

    $scope.conference = conference;
    $scope.blocks = [];
    $scope.reversesort = false;
    $scope.showAllViewId = 'all';
    $scope.defaultViewId = 'default';
    $scope.activeRegViewId = $scope.defaultViewId;
    $scope.savedState = '';

    // collect completed registrations
    registrations = _.filter(registrations, function (item) { return item.completed !== false; });

    // collect all 'Content' blocks from the conferences' pages
    angular.forEach(conference.registrationPages, function (page) {
      angular.forEach(page.blocks, function (block) {
        if (block.type.indexOf('Content') === -1) {
          block.visible = true;
          $scope.blocks.push(block);
        }
      });
    });

    // get all the registration views for this conference
    $http({method: 'GET',
      url: 'conferences/' + conference.id + '/registration-views'
    }).success(function (data) {
      $scope.registrationViews = _.sortBy(data, 'name');

      var profileBlocks = function (blocks) {
        return _.filter(blocks, function (block) {
          var profileTypes = [ 'EMAIL', 'NAME' ];
          return profileTypes.indexOf(block.profileType) > -1;
        });
      };

      $scope.registrationViewsDropdown = [
        {
          id: $scope.defaultViewId,
          name: '-Default-',
          visibleBlockIds: _.pluck(profileBlocks($scope.blocks), 'id')
        },
        {
          id: $scope.showAllViewId,
          name: '-Show All-',
          visibleBlockIds: _.pluck($scope.blocks, 'id')
        }
      ];

      $scope.registrationViewsDropdown = $scope.registrationViewsDropdown.concat($scope.registrationViews);
      $scope.setRegView();
    });

    // toggle (show/hide) the column and auto save the registration view
    $scope.toggleColumn = function (block) {
      $scope.blocks[block].visible = !$scope.blocks[block].visible;
      $scope.updateRegView();
    };

    // set the registration view as per the active registration view id
    $scope.setRegView = function () {
      $scope.savedState = '';
      if ($scope.activeRegViewId === '') {

      } else {
        var visibleBlocks = _.find($scope.registrationViewsDropdown, { 'id': $scope.activeRegViewId }).visibleBlockIds;
        angular.forEach($scope.blocks, function (block) {
          if (visibleBlocks.indexOf(block.id) !== -1) {
            block.visible = true;
          } else if (block.type.indexOf('Content') === -1) {
            block.visible = false;
          }
        });
      }
    };

    // create a registration view
    $scope.createRegView = function () {
      $modal.open({
        templateUrl: 'views/regViewCreate.html',
        controller: 'CreateDialogCtrl',
        resolve: {
          defaultValue: function () {
            return '';
          }
        }
      }).result.then(function (viewName) {
        if (viewName !== '') {

        var regViewNames = _.pluck($scope.registrationViewsDropdown, 'name');
          if (regViewNames.indexOf(viewName) > -1) {
            var errorModalOptions = {
              templateUrl: 'views/errorModal.html',
              controller: 'genericModal',
              resolve: {
                message: function () {
                  return 'View name "' + viewName + '" already exists. Please provide a different view name.';
                }
              }
            };
            $modal.open(errorModalOptions);

            return;
          }

          var newView = {
            id: uuid(),
            conferenceId: conference.id,
            name: viewName,
            visibleBlockIds: _.pluck(_.filter($scope.blocks, function (item) {
              return item.visible === true;
            }), 'id')
          };

          $http({method: 'POST',
            url: 'conferences/' + conference.id + '/registration-views',
            data: newView
          }).success(function () {
            $scope.registrationViews = $scope.registrationViews.concat(newView);
            $scope.registrationViewsDropdown = $scope.registrationViewsDropdown.concat(newView);
            $scope.activeRegViewId = newView.id;
          }).error(function () {
          });
        }
      });
    };

    // update a registration view
    $scope.updateRegView = function () {

      // don't update predefined view
      if ($scope.isPredefinedView($scope.activeRegViewId))
      {
        return;
      }

      var thisView = {
        id: $scope.activeRegViewId,
        conferenceId: conference.id,
        name: _.find($scope.registrationViewsDropdown, { 'id': $scope.activeRegViewId }).name,
        visibleBlockIds: _.pluck(_.filter($scope.blocks, function (item) {
          return item.visible === true;
        }), 'id')
      };

      $scope.savedState = 'Saving...';
      $http({method: 'PUT',
        url: 'registration-views/' + $scope.activeRegViewId,
        data: thisView
      }).success(function () {
        $scope.registrationViews = _.remove($scope.registrationViews, function (view) { return view.id !== $scope.activeRegViewId; });
        $scope.registrationViewsDropdown = _.remove($scope.registrationViewsDropdown, function (view) {
          return view.id !== $scope.activeRegViewId;
        });
        $scope.registrationViews = $scope.registrationViews.concat(thisView);
        $scope.registrationViewsDropdown = $scope.registrationViewsDropdown.concat(thisView);
        $scope.activeRegViewId = thisView.id;
        $scope.savedState = 'Saved';
      }).error(function () {
      });
    };

    // delete a registration view
    $scope.delRegView = function () {

      // don't delete predefined views
      if ($scope.isPredefinedView($scope.activeRegViewId))
      {
        return;
      }

      $http({method: 'DELETE',
        url: 'registration-views/' + $scope.activeRegViewId
      }).success(function () {
        $scope.registrationViews = _.remove($scope.registrationViews, function (view) { return view.id !== $scope.activeRegViewId; });
        $scope.registrationViewsDropdown = _.remove($scope.registrationViewsDropdown, function (view) {
          return view.id !== $scope.activeRegViewId;
        });

        $scope.activeRegViewId = $scope.defaultViewId;
        $scope.setRegView();

      }).error(function () {
      });
    };

    $scope.findAnswer = function (registration, blockId) {
      return _.find(registration.answers, function (answer) {
        return angular.equals(answer.blockId, blockId);
      });
    };

    $scope.getSelectedCheckboxes = function (choices) {
      return _.keys(_.pick(choices, function (val) {
        return val === true;
      }));
    };

    $scope.answerSort = function (registration) {
      if (angular.isDefined($scope.order)) {
        if (angular.isDefined($scope.findAnswer(registration, $scope.order))) {
          if ($scope.findAnswer(registration, $scope.order).value.text) { //text field
            return $scope.findAnswer(registration, $scope.order).value.text;
          } else if ($scope.getSelectedCheckboxes($scope.findAnswer(registration, $scope.order).value).length > 0) {
            //mc
            return $scope.getSelectedCheckboxes($scope.findAnswer(registration, $scope.order).value).join(' ');
          } else if (typeof $scope.findAnswer(registration, $scope.order).value === 'object') { //name
            return _.values($scope.findAnswer(registration, $scope.order).value).join(' ');
          } else { //radio
            return $scope.findAnswer(registration, $scope.order).value;
          }
        }
      } else {
        return 0;
      }
    };

    $scope.setOrder = function (order) {
      if (order === $scope.order) {
        $scope.reversesort = !$scope.reversesort;
      } else {
        $scope.reversesort = false;
      }
      $scope.order = order;
    };

    $scope.registrations = registrations;
    $scope.permissions = permissions;

    $scope.viewPayments = function (registration) {
      var paymentModalOptions = {
        templateUrl: 'views/paymentsModal.html',
        controller: 'paymentModal',
        backdrop: 'static',
        keyboard: false,
        resolve: {
          data: function () {
            return registration;
          }
        }
      };

      $modal.open(paymentModalOptions).result.then(function (updatedRegistration) {
        var localUpdatedRegistration = _.find(registrations, function (reg){
          return reg.id === updatedRegistration.id;
        });
        localUpdatedRegistration.pastPayments = updatedRegistration.pastPayments;
        localUpdatedRegistration.totalDue = updatedRegistration.totalDue;
        localUpdatedRegistration.totalPaid = updatedRegistration.totalPaid;
        localUpdatedRegistration.remainingBalance = updatedRegistration.remainingBalance;
      });
    };

    $scope.isPredefinedView = function (regViewId) {
      var predefinedViews = [ $scope.showAllViewId, $scope.defaultViewId ];
      return predefinedViews.indexOf(regViewId) > -1;
    };

    $scope.isConferenceCost = function () {
      return conference.conferenceCost > 0;
    };

    // define payment categories
    $scope.paymentCategories = [
      {
        name: 'Show All',
        matches: function () {
          return true;
        }
      },
      {
        name: 'Full',
        matches: function (x, y) {
          return x === y;
        }
      },
      {
        name: 'Partial',
        matches: function (x, y) {
          return x > 0 && x < y;
        }
      },
      {
        name: 'Full/Partial',
        matches: function (x) {
          return x > 0;
        }
      },
      {
        name: 'Not Paid',
        matches: function (x) {
          if (x === null) {
            return true;
          }

          return x <= 0;
        }
      }
    ];

    // set current to first in array
    $scope.currentPaymentCategory = _.first($scope.paymentCategories).name;

    // determine if registration payment status matches current payment category
    $scope.paymentStatus = function (registration) {

      var paymentCategory = _.find($scope.paymentCategories, { 'name': $scope.currentPaymentCategory });

      return paymentCategory.matches(registration.totalPaid, registration.totalDue);
    };

    $scope.paidInFull = function (registration) {
      return registration.totalPaid >= registration.totalDue;
    }
  });
<|endoftext|>


<commit_before>'use strict';

angular.module('app')
    .controller('rgiAssignAssessmentSupervisorDialogCtrl', function (
        $scope,
        $location,
        $route,
        ngDialog,
        rgiNotifier,
        rgiAssessmentSrvc,
        rgiAssessmentMethodSrvc,
        rgiIdentitySrvc,
        rgiUserSrvc
    ) {
        $scope.current_user = rgiIdentitySrvc.currentUser;

        rgiAssessmentSrvc.get({assessment_ID: $scope.$parent.assessment_update_ID}, function(assessment) {
            $scope.assessment = assessment;

            for(var supervisorIndex in $scope.assessment.supervisor_ID) {
                if($scope.assessment.supervisor_ID.hasOwnProperty(supervisorIndex)) {
                    $scope.assessment.supervisor_ID[supervisorIndex] = $scope.assessment.supervisor_ID[supervisorIndex]._id;
                }
            }

            if($scope.assessment.supervisor_ID.length === 0) {
                $scope.assessment.supervisor_ID.push({});
            }

            rgiUserSrvc.query({role: 'supervisor'}, function(users) {
                $scope.availableUsers = users;
            });
        });

        $scope.addAssignee = function () {
            $scope.assessment.supervisor_ID.push({});
        };

        $scope.removeAssignee = function (index) {
            $scope.assessment.supervisor_ID.splice(index, 1);
        };

        $scope.assignAssessmentSupervisor = function () {
            if ($scope.assessment.supervisor_ID.length < 1) {
                rgiNotifier.error('You must select a supervisor!');
            } else {
                rgiAssessmentMethodSrvc.updateAssessment($scope.assessment)
                    .then(function () {
                        rgiNotifier.notify('Assessment assigned!');
                        $scope.closeThisDialog();
                        $route.reload();
                    }, function (reason) {
                        if (reason) {
                            rgiNotifier.error(reason);
                        } else {
                            rgiNotifier.error('Validation error');
                            $scope.closeThisDialog();
                            $route.reload();
                        }
                    });
            }
        };

        $scope.closeDialog = function () {
            ngDialog.close();
        };
    });
<commit_msg>fix the validation of empty users<commit_after>'use strict';

angular.module('app')
    .controller('rgiAssignAssessmentSupervisorDialogCtrl', function (
        $scope,
        $location,
        $route,
        ngDialog,
        rgiNotifier,
        rgiAssessmentSrvc,
        rgiAssessmentMethodSrvc,
        rgiIdentitySrvc,
        rgiUserSrvc
    ) {
        $scope.current_user = rgiIdentitySrvc.currentUser;

        rgiAssessmentSrvc.get({assessment_ID: $scope.$parent.assessment_update_ID}, function(assessment) {
            $scope.assessment = assessment;

            for(var supervisorIndex in $scope.assessment.supervisor_ID) {
                if($scope.assessment.supervisor_ID.hasOwnProperty(supervisorIndex)) {
                    $scope.assessment.supervisor_ID[supervisorIndex] = $scope.assessment.supervisor_ID[supervisorIndex]._id;
                }
            }

            if($scope.assessment.supervisor_ID.length === 0) {
                $scope.addAssignee();
            }

            rgiUserSrvc.query({role: 'supervisor'}, function(users) {
                $scope.availableUsers = users;
            });
        });

        $scope.addAssignee = function () {
            $scope.assessment.supervisor_ID.push(undefined);
        };

        $scope.removeAssignee = function (index) {
            $scope.assessment.supervisor_ID.splice(index, 1);
        };

        $scope.isAssigneeListEmpty = function() {
            var assigneeNumber = 0;

            if($scope.assessment) {
                $scope.assessment.supervisor_ID.forEach(function(assignee) {
                    if(assignee) {
                        assigneeNumber++;
                    }
                });
            }

            return assigneeNumber < 1;
        };

        $scope.saveAssigneeList = function () {
            if ($scope.isAssigneeListEmpty()) {
                rgiNotifier.error('You must select a supervisor!');
            } else {
                rgiAssessmentMethodSrvc.updateAssessment($scope.assessment)
                    .then(function () {
                        rgiNotifier.notify('Assessment assigned!');
                        $scope.closeThisDialog();
                        $route.reload();
                    }, function (reason) {
                        if (reason) {
                            rgiNotifier.error(reason);
                        } else {
                            rgiNotifier.error('Validation error');
                            $scope.closeThisDialog();
                            $route.reload();
                        }
                    });
            }
        };

        $scope.closeDialog = function () {
            ngDialog.close();
        };
    });
<|endoftext|>


<commit_before>/* File: regleStyle.js
 *
 * Copyright (c) 2014
 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
 * (direction-innovation@cned.fr)
 *
 * GNU Affero General Public License (AGPL) version 3.0 or later version
 *
 * This file is part of a program which is free software: you can
 * redistribute it and/or modify it under the terms of the
 * GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */

/*global cnedApp,Hyphenator, $:false */
'use strict';

cnedApp.directive('regleStyle', ['$rootScope', 'removeHtmlTags', '$compile', function($rootScope, removeHtmlTags, $compile) {
  return {
    restrict: 'EA',
    link: function(scope, element, attrs) {

      var compile = function(newHTML) {
        newHTML = $compile(newHTML)($rootScope);
        element.html('').append(newHTML);

        console.log('ffff compile');
        console.log($(element).attr('data-id'));

        $(element).css({
          'font-weight': $(element).find('p').attr('data-weight'),
          'font-size': $(element).find('p').attr('data-size') + 'px',
          'line-height': $(element).find('p').attr('data-lineheight') + 'px',
          'font-family': $(element).find('p').attr('data-font')
        });

        regleColoration($(element).find('p').attr('data-coloration'), element);

        console.log('adding slide');
        console.log($('.text-slides[data-id="' + $(element).attr('data-id') + '"]').append($(element)));
        // $(element).remove();
        $('.slider slide').append($(element));
      };

      var htmlName = attrs.regleStyle;

      scope.$watch(htmlName, function(newHTML) {
        // the HTML
        if (!newHTML) return;
        compile(newHTML); // Compile
      });

      angular.element(document).ready(function() {
        console.log('document ready');
        console.log(attrs);
      });

      var currentParam = '';
      var currentElementAction = '';
      var hyphenatorSettings = {
        'onhyphenationdonecallback': function() {
          console.log('done ... ');
          syllabeAction(currentParam, currentElementAction);
        },
        hyphenchar: '|',
        displaytogglebox: true,
      };
      Hyphenator.config(hyphenatorSettings);

      var lineAction = function(elementAction) {
        console.log('inside line action');
        var p = $(elementAction);
        var words = p.text().split(' ');
        var text = '';

        $.each(words, function(i, w) {
          if ($.trim(w)) text = text + '' + w + ' ';
        });
        elementAction.html(text);

        $(window).resize(function() {
          var line = 0;
          var prevTop = -15;
          $('span', p).each(function() {
            var word = $(this);
            var top = word.offset().top;
            if (top !== prevTop) {
              prevTop = top;
              if (line === 3) {
                line = 1;
              } else {
                line++;
              }
            }
            word.attr('class', 'line' + line);
          }); //each
        }); //resize
        $(window).resize();

      };

      var wordAction = function(elementAction) {

        var p = $(elementAction);
        var words = p.text().split(' ');
        var text = '';
        $.each(words, function(i, w) {
          if ($.trim(w)) text = text + '' + w + ' ';
        });
        p.html(text);
        $(window).resize(function() {

          var line = 0;
          $('span', p).each(function() {
            var word = $(this);
            if (line !== 3) {
              line++;
            } else {
              line = 1;
            }
            word.attr('class', 'line' + line);
          }); //each
        }); //resize
        $(window).resize();
      };

      var decoupe = function(param, elementAction) {

        var palinText = removeHtmlTags($(elementAction).html());
        $(elementAction).html('');
        elementAction.text(palinText);
        $(elementAction).addClass('hyphenate');
        Hyphenator.toggleHyphenation(3);

        // Hyphenator = new Hyphenator();
        currentParam = param;
        currentElementAction = elementAction;

        Hyphenator.run();

      };

      var syllabeAction = function(param, elementAction) {
        console.log('inside syllab action');
        var p = $(elementAction);
        var words = p.text().split(' ');
        var text = '';
        $.each(words, function(i, w) {
          if ($.trim(w)) {
            if (w.indexOf('|') > -1) {
              var wordss = w.split('|');
              $.each(wordss, function(i, ww) {
                if (i === wordss.length - 1) {
                  text = text + '' + ww + ' ';
                } else {
                  text = text + '' + ww + '';
                }
              });
            } else {
              text = text + '' + w + ' ';
            }
          }
        });

        p.html(text);
        $(window).resize(function() {

          var line = 0;
          $('span', p).each(function() {
            var word = $(this);
            if (line !== 3) {
              line++;
            } else {
              line = 1;
            }
            word.attr('class', 'line' + line);
          }); //each
        }); //resize

        $(window).resize();

        if (param === 'color-syllabes') {
          $(elementAction).css('color', '');
          $(elementAction).find('span').css('color', '');

          $('.line1').css('color', '#D90629');
          $('.line2').css('color', '#066ED9');
          $('.line3').css('color', '#4BD906');
        }

      };

      /* Relges de style Profils */
      $rootScope.$on('reglesStyleChange', function(nv, params) {
        nv.stopPropagation();
        switch (params.operation) {

          case 'interligne':
            $('.' + params.element).css('line-height', params.value + 'px');
            break;

          case 'style':
            $('.' + params.element).css('font-weight', params.value);
            break;

          case 'taille':
            $('.' + params.element).css('font-size', params.value + 'px');
            break;

          case 'police':
            $('.' + params.element).css('font-family', params.value);
            break;

          case 'coloration':
            regleColoration(params.value, $('.' + params.element));
            break;
        }

      });

      function regleColoration(param, elementAction) {
        // console.log(param);
        switch (param) {
          case 'Couleur par défaut':
            $('.line1').css('background-color', '');
            $('.line2').css('background-color', '');
            $('.line3').css('background-color', '');
            $(elementAction).css('color', 'black');
            $(elementAction).find('span').css('color', 'black');
            $(elementAction).text($(elementAction).text());
            break;

          case 'Colorer les lignes':
            lineAction(elementAction);
            $('.line1').css('color', '#D90629');
            $('.line2').css('color', '#066ED9');
            $('.line3').css('color', '#4BD906');
            break;

          case 'Colorer les mots':
            wordAction(elementAction);
            $('.line1').css('background-color', '');
            $('.line2').css('background-color', '');
            $('.line3').css('background-color', '');
            $(elementAction).find('.line1').css('color', '#D90629');
            $(elementAction).find('.line2').css('color', '#066ED9');
            $(elementAction).find('.line3').css('color', '#4BD906');
            break;

          case 'Surligner les mots':
            wordAction(elementAction);
            $(elementAction).find('.line1').css({
              'background-color': '#fffd01',
              'color': '#000'
            });
            $(elementAction).find('.line2').css({
              'background-color': '#04ff04',
              'color': '#000'
            });
            $(elementAction).find('.line3').css({
              'background-color': '#04ffff',
              'color': '#000'
            });
            break;

          case 'Surligner les lignes':
            lineAction(elementAction);
            $(elementAction).css('color', '');
            $(elementAction).find('span').css('color', '');
            $('.line1').css('background-color', '#fffd01');
            $('.line2').css('background-color', '#04ff04');
            $('.line3').css('background-color', '#04ffff');
            break;

          case 'Colorer les syllabes':
            console.log('Colorer les syllabes');
            console.log(elementAction);
            decoupe('color-syllabes', elementAction);
            break;

        }
      }

    }
  };
}]);<commit_msg>Espace   pris en compte lors du coloration et la surligne des mots.<commit_after>/* File: regleStyle.js
 *
 * Copyright (c) 2014
 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
 * (direction-innovation@cned.fr)
 *
 * GNU Affero General Public License (AGPL) version 3.0 or later version
 *
 * This file is part of a program which is free software: you can
 * redistribute it and/or modify it under the terms of the
 * GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */

/*global cnedApp,Hyphenator, $:false */
'use strict';

cnedApp.directive('regleStyle', ['$rootScope', 'removeHtmlTags', '$compile', function($rootScope, removeHtmlTags, $compile) {
  return {
    restrict: 'EA',
    link: function(scope, element, attrs) {

      var compile = function(newHTML) {
        newHTML = $compile(newHTML)($rootScope);
        element.html('').append(newHTML);

        console.log('ffff compile');
        console.log($(element).attr('data-id'));

        $(element).css({
          'font-weight': $(element).find('p').attr('data-weight'),
          'font-size': $(element).find('p').attr('data-size') + 'px',
          'line-height': $(element).find('p').attr('data-lineheight') + 'px',
          'font-family': $(element).find('p').attr('data-font')
        });

        regleColoration($(element).find('p').attr('data-coloration'), element);

        console.log('adding slide');
        console.log($('.text-slides[data-id="' + $(element).attr('data-id') + '"]').append($(element)));
        // $(element).remove();
        $('.slider slide').append($(element));
      };

      var htmlName = attrs.regleStyle;

      scope.$watch(htmlName, function(newHTML) {
        // the HTML
        if (!newHTML) return;
        compile(newHTML); // Compile
      });

      angular.element(document).ready(function() {
        console.log('document ready');
        console.log(attrs);
      });

      var currentParam = '';
      var currentElementAction = '';
      var hyphenatorSettings = {
        'onhyphenationdonecallback': function() {
          console.log('done ... ');
          syllabeAction(currentParam, currentElementAction);
        },
        hyphenchar: '|',
        displaytogglebox: true,
      };
      Hyphenator.config(hyphenatorSettings);

      var lineAction = function(elementAction) {
        console.log('inside line action');
        var p = $(elementAction);
        p.html(p.html().replace(/\ /g,' '));
        var words = p.text().split(' ');
        var text = '';

        $.each(words, function(i, w) {
          if ($.trim(w)) text = text + '' + w + ' ';
        });
        elementAction.html(text);

        $(window).resize(function() {
          var line = 0;
          var prevTop = -15;
          $('span', p).each(function() {
            var word = $(this);
            var top = word.offset().top;
            if (top !== prevTop) {
              prevTop = top;
              if (line === 3) {
                line = 1;
              } else {
                line++;
              }
            }
            word.attr('class', 'line' + line);
          }); //each
        }); //resize
        $(window).resize();

      };

      var wordAction = function(elementAction) {

        var p = $(elementAction);
        p.html(p.html().replace(/\ /g,' '));
        var words = p.text().split(' ');
        var text = '';
        $.each(words, function(i, w) {
          if ($.trim(w)) text = text + '' + w + ' ';
        });
        p.html(text);
        $(window).resize(function() {

          var line = 0;
          $('span', p).each(function() {
            var word = $(this);
            if (line !== 3) {
              line++;
            } else {
              line = 1;
            }
            word.attr('class', 'line' + line);
          }); //each
        }); //resize
        $(window).resize();
      };

      var decoupe = function(param, elementAction) {

        var palinText = removeHtmlTags($(elementAction).html());
        $(elementAction).html('');
        elementAction.text(palinText);
        $(elementAction).addClass('hyphenate');
        Hyphenator.toggleHyphenation(3);

        // Hyphenator = new Hyphenator();
        currentParam = param;
        currentElementAction = elementAction;

        Hyphenator.run();

      };

      var syllabeAction = function(param, elementAction) {
        console.log('inside syllab action');
        var p = $(elementAction);
        var words = p.text().split(' ');
        var text = '';
        $.each(words, function(i, w) {
          if ($.trim(w)) {
            if (w.indexOf('|') > -1) {
              var wordss = w.split('|');
              $.each(wordss, function(i, ww) {
                if (i === wordss.length - 1) {
                  text = text + '' + ww + ' ';
                } else {
                  text = text + '' + ww + '';
                }
              });
            } else {
              text = text + '' + w + ' ';
            }
          }
        });

        p.html(text);
        $(window).resize(function() {

          var line = 0;
          $('span', p).each(function() {
            var word = $(this);
            if (line !== 3) {
              line++;
            } else {
              line = 1;
            }
            word.attr('class', 'line' + line);
          }); //each
        }); //resize

        $(window).resize();

        if (param === 'color-syllabes') {
          $(elementAction).css('color', '');
          $(elementAction).find('span').css('color', '');

          $('.line1').css('color', '#D90629');
          $('.line2').css('color', '#066ED9');
          $('.line3').css('color', '#4BD906');
        }

      };

      /* Relges de style Profils */
      $rootScope.$on('reglesStyleChange', function(nv, params) {
        nv.stopPropagation();
        switch (params.operation) {

          case 'interligne':
            $('.' + params.element).css('line-height', params.value + 'px');
            break;

          case 'style':
            $('.' + params.element).css('font-weight', params.value);
            break;

          case 'taille':
            $('.' + params.element).css('font-size', params.value + 'px');
            break;

          case 'police':
            $('.' + params.element).css('font-family', params.value);
            break;

          case 'coloration':
            regleColoration(params.value, $('.' + params.element));
            break;
        }

      });

      function regleColoration(param, elementAction) {
        // console.log(param);
        switch (param) {
          case 'Couleur par défaut':
            $('.line1').css('background-color', '');
            $('.line2').css('background-color', '');
            $('.line3').css('background-color', '');
            $(elementAction).css('color', 'black');
            $(elementAction).find('span').css('color', 'black');
            $(elementAction).text($(elementAction).text());
            break;

          case 'Colorer les lignes':
            lineAction(elementAction);
            $('.line1').css('color', '#D90629');
            $('.line2').css('color', '#066ED9');
            $('.line3').css('color', '#4BD906');
            break;

          case 'Colorer les mots':
            wordAction(elementAction);
            $('.line1').css('background-color', '');
            $('.line2').css('background-color', '');
            $('.line3').css('background-color', '');
            $(elementAction).find('.line1').css('color', '#D90629');
            $(elementAction).find('.line2').css('color', '#066ED9');
            $(elementAction).find('.line3').css('color', '#4BD906');
            break;

          case 'Surligner les mots':
            wordAction(elementAction);
            $(elementAction).find('.line1').css({
              'background-color': '#fffd01',
              'color': '#000'
            });
            $(elementAction).find('.line2').css({
              'background-color': '#04ff04',
              'color': '#000'
            });
            $(elementAction).find('.line3').css({
              'background-color': '#04ffff',
              'color': '#000'
            });
            break;

          case 'Surligner les lignes':
            lineAction(elementAction);
            $(elementAction).css('color', '');
            $(elementAction).find('span').css('color', '');
            $('.line1').css('background-color', '#fffd01');
            $('.line2').css('background-color', '#04ff04');
            $('.line3').css('background-color', '#04ffff');
            break;

          case 'Colorer les syllabes':
            console.log('Colorer les syllabes');
            console.log(elementAction);
            decoupe('color-syllabes', elementAction);
            break;

        }
      }

    }
  };
}]);<|endoftext|>


<commit_before>var current_allocated_slots = 0;
var current_slots = {};
var tooltip = [
  "
",
  "
",
  "",
  "
Slots
",
  "

",
  "

",
  "

",
  "

",
  "
",
  ].join('');

$.postJSON = function (post_url, to_json, callback) {
    $.ajax({
        url: post_url,
        type: 'POST',
        processData: true,
        data: {result: JSON.stringify(to_json)},
        contentType: 'application/json',
        dataType: 'json',
        success: callback,
    });
};

function updateFromJSON(data) {
  if (data) {
    $(data.data).each(
      function (intIndex,item) {
        $("#id_spin_slot_count_"+item.link_id).val(item.slots);
        current_slots[item.link_id] = {slots: item.slots, locked: item.locked, adjustment: item.adjustment};
        $("#id_locked_slot_"+item.link_id).attr("checked",item.locked);
        $("#id_spin_adjustment_count_"+item.link_id).val(item.adjustment);
      }
    );
    updateOverlay();
  }
}

function retrieveJSON() {
  $.getJSON(RETURN_URL+"?_="+(new Date().getTime()),
    updateFromJSON
  );
}

function reCalculate() {
  url = RETURN_URL+"?_="+(new Date().getTime())
  $.postJSON(url, current_slots, updateFromJSON);
}

function updateOverlay() {
  updateCurrentSlots();
  var remaining_slots = MAX_AVAILABLE_SLOTS - current_allocated_slots;
  $("#p_assigned_slots").html("Assigned slots: "+current_allocated_slots);
  $("#p_remaining_slots").html("Remaining slots: "+remaining_slots);
}

function updateCurrentSlots() {
  current_allocated_slots = 0;
  for (var org_id in current_slots) {
    current_allocated_slots = current_allocated_slots+new Number(current_slots[org_id].slots);
  }
}

function lockSlots (checkbox) {
  var locked = $(checkbox).attr("checked");
  var re = /^id_locked_slot_(\w*)/;
  var org_link_id = checkbox.id.match(re)[1];
  current_slots[org_link_id].locked = locked;
}

function assignSlots (counter) {
  var re = /^id_spin_slot_count_(\w*)/;
  var org_link_id = counter.id.match(re)[1];
  current_slots[org_link_id].slots = $(counter).val();
  updateCurrentSlots();
  updateOverlay();
}

function assignAdjustment (counter) {
  var re = /^id_spin_adjustment_count_(\w*)/;
  var org_link_id = counter.id.match(re)[1];
  current_slots[org_link_id].adjustment = $(counter).val();
}

<commit_msg>Slot allocator Javascript fix. This prevents from calling updateFromJSON function if there is no data.<commit_after>var current_allocated_slots = 0;
var current_slots = {};
var tooltip = [
  "
",
  "
",
  "",
  "
Slots
",
  "

",
  "

",
  "

",
  "

",
  "
",
  ].join('');

$.postJSON = function (post_url, to_json, callback) {
    $.ajax({
        url: post_url,
        type: 'POST',
        processData: true,
        data: {result: JSON.stringify(to_json)},
        contentType: 'application/json',
        dataType: 'json',
        success: callback,
    });
};

function updateFromJSON(data) {
  if (data) {
    $(data.data).each(
      function (intIndex,item) {
        $("#id_spin_slot_count_"+item.link_id).val(item.slots);
        current_slots[item.link_id] = {slots: item.slots, locked: item.locked, adjustment: item.adjustment};
        $("#id_locked_slot_"+item.link_id).attr("checked",item.locked);
        $("#id_spin_adjustment_count_"+item.link_id).val(item.adjustment);
      }
    );
    updateOverlay();
  }
}

function retrieveJSON() {
  $.getJSON(RETURN_URL+"?_="+(new Date().getTime()), function(data) {
    if (data) {
      updateFromJSON(data);
    }
  }
  );
}

function reCalculate() {
  url = RETURN_URL+"?_="+(new Date().getTime())
  $.postJSON(url, current_slots, updateFromJSON);
}

function updateOverlay() {
  updateCurrentSlots();
  var remaining_slots = MAX_AVAILABLE_SLOTS - current_allocated_slots;
  $("#p_assigned_slots").html("Assigned slots: "+current_allocated_slots);
  $("#p_remaining_slots").html("Remaining slots: "+remaining_slots);
}

function updateCurrentSlots() {
  current_allocated_slots = 0;
  for (var org_id in current_slots) {
    current_allocated_slots = current_allocated_slots+new Number(current_slots[org_id].slots);
  }
}

function lockSlots (checkbox) {
  var locked = $(checkbox).attr("checked");
  var re = /^id_locked_slot_(\w*)/;
  var org_link_id = checkbox.id.match(re)[1];
  current_slots[org_link_id].locked = locked;
}

function assignSlots (counter) {
  var re = /^id_spin_slot_count_(\w*)/;
  var org_link_id = counter.id.match(re)[1];
  current_slots[org_link_id].slots = $(counter).val();
  updateCurrentSlots();
  updateOverlay();
}

function assignAdjustment (counter) {
  var re = /^id_spin_adjustment_count_(\w*)/;
  var org_link_id = counter.id.match(re)[1];
  current_slots[org_link_id].adjustment = $(counter).val();
}

<|endoftext|>


<commit_before>///<reference path="../lib/jquery/dist/jquery.js" />
///<reference path="../lib/knockout/dist/knockout.js" />
///<reference path="../lib/moment/moment.js" />

(function (ko, $) {

    var getActivities = $.getJSON("/api/activity");

    function ActivitiesViewModel() {
        this.showOld = ko.observable(false);
        this.activities = ko.observableArray([]);
        this.selectedActivities = ko.computed(function () {
            var self = this;
            return ko.utils.arrayFilter(this.activities(), function (activity) {
                return self.showOld() || moment(activity.EndDateTime).isAfter(moment());
            })
        }, this);
        this.loading = ko.observable(true);
    }
    ActivitiesViewModel.prototype = {
        toggle: function (observable) {
            return function toggleObservable() {
                observable(!observable());
            }
        }
    };

    var viewModel = new ActivitiesViewModel();
    ko.applyBindings(viewModel);

    getActivities.done(function (activities) {
        viewModel.loading(false);
        viewModel.activities(activities);
    });
})(ko, $);<commit_msg>Ensure default sorting of activities by start date ascending.<commit_after>///<reference path="../lib/jquery/dist/jquery.js" />
///<reference path="../lib/knockout/dist/knockout.js" />
///<reference path="../lib/moment/moment.js" />

(function (ko, $) {

    var getActivities = $.getJSON("/api/activity");

    function ActivitiesViewModel() {
        this.showOld = ko.observable(false);
        this.activities = ko.observableArray([]);
        this.selectedActivities = ko.computed(function () {
            var self = this;
            return ko.utils.arrayFilter(this.activities(), function (activity) {
                return self.showOld() || moment(activity.EndDateTime).isAfter(moment());
            })
        }, this);
        this.loading = ko.observable(true);
    }
    ActivitiesViewModel.prototype = {
        toggle: function (observable) {
            return function toggleObservable() {
                observable(!observable());
            }
        }
    };

    var viewModel = new ActivitiesViewModel();
    ko.applyBindings(viewModel);

    getActivities.done(function (activities) {
        viewModel.loading(false);
        activities.sort(function (a1, a2) {
            return moment(a1.StartDateTime).toDate().valueOf() - moment(a2.StartDateTime).toDate().valueOf();
        });
        viewModel.activities(activities);
    });
})(ko, $);<|endoftext|>


<commit_before>Ext.onReady(function()
{
  History = function()
  {

    // need this pointer for event-function
    var finalThis = this;

    var updateDropDownMenu = function()
    {
      var items = finalThis.splitButton.menu.items;

      // only insert if, store has really stored a new element
      if ((items === undefined) || (store.getCount() > items.getCount()))
      {
        finalThis.splitButton.menu.insert(0, {
          text : (store.getAt(0)).data['query'],
          handler : function(b, e)
          {
            Ext.getCmp('queryAnnisQL').setValue(b.text);
          }
        });
      } else
      {
        /**
         * if this query is already in the menu, the menu is cleared. This might
         * be inefficient for big histories.
         *
         */
        finalThis.splitButton.menu.removeAll();

        // count the other way around for ascending sorted menu
        for ( var i = store.getCount() - 1; i >= 0; i--)
        {
          finalThis.splitButton.menu.insert(0, {
            text : (store.getAt(0)).data['query'],
            handler : function(b, e)
            {
              Ext.getCmp('queryAnnisQL').setValue(b.text);
            }
          });
        }
      }

      // delete least added element
      if (items !== undefined && items.getCount() > 5)
        finalThis.splitButton.remove(items.last());

    };

    // initiate GridView for all queries
    var store = new Ext.data.ArrayStore({
      fields : [ {
        name : 'query'
      } ],
      listeners : {
        'add' : updateDropDownMenu
      }
    });

    var grid = new Ext.grid.GridPanel({
      store : store,
      columns : [ {
        header : '#',
        width : 30,
        renderer : function(value, metadata, record, rowIndex, colIndex)
        {
          return (rowIndex + 1);
        }
      }, {
        id : 'query',
        header : 'Query',
        sortable : true,
        width : 330,
        dataIndex : 'query',
        renderer : function(value)
        {
          return "
" + value + "
";
        }
      }, {
        header : "url",
        width : 30,
        dataIndex : "id",
        renderer : function()
        {
          var action = 'getCitationWindow()';
          var linkStart = "";
          return linkStart + conf_context + linkEnd;
        }
      } ],
      sm : new Ext.grid.RowSelectionModel({
        singleSelect : true,
        store : store,
        listeners : {
          'rowselect' : function(row, rowIndex, record)
          {
            Ext.getCmp('queryAnnisQL').setValue(record.get('query'));
          }
        }
      }),
      stripeRows : true,
      width : 400,
      height : 300
    });

    var historyWindow = function()
    {
      new Ext.Window({
        autoDestroy : true,
        title : 'history',
        width : 400,
        height : 300,
        items : grid,
        closeAction : 'hide',
        stateful : true,
        stateId : 'grid'
      }).show();
    };

    this.update = function(lastQuery)
    {
      store.insert(0, new store.recordType({
        query : lastQuery
      }, lastQuery));
      grid.getView().refresh(false);
    };

    this.splitButton = new Ext.SplitButton({
      fieldLabel : 'History',
      text : 'Query History',
      menu : new Ext.menu.Menu(),
      listeners : {
        'click' : historyWindow
      }
    });
  };
});<commit_msg>some bugfixes for drop-down-menu<commit_after>Ext.onReady(function()
{
  History = function()
  {

    // need this pointer for event-function
    var finalThis = this;

    var updateDropDownMenu = function()
    {
      var items = finalThis.splitButton.menu.items;
      const
      MAX_MENU_ITEMS = 5;

      // only insert if, store has really stored a new element
      if ((items === undefined) || (store.getCount() > items.getCount()))
      {
        finalThis.splitButton.menu.insert(0, {
          text : (store.getAt(0)).data['query'],
          handler : function(b, e)
          {
            Ext.getCmp('queryAnnisQL').setValue(b.text);
          }
        });
      } else
      {
        /**
         * if this query is already in the menu, the menu is cleared. This might
         * be inefficient for big histories.
         *
         */
        finalThis.splitButton.menu.removeAll();
        var recordsArray = store.getRange([ 0 ], [ MAX_MENU_ITEMS - 1 ]);
        // count the other way around for ascending sorted menu
        for ( var i = recordsArray.length - 1; i >= 0; i--)
        {
          finalThis.splitButton.menu.insert(0, {
            text : recordsArray[i].data['query'],
            handler : function(b, e)
            {
              Ext.getCmp('queryAnnisQL').setValue(b.text);
            }
          });
        }
      }

      // delete least added element
      if (items !== undefined && items.getCount() > MAX_MENU_ITEMS)
        finalThis.splitButton.menu.remove(items.last());

    };

    // initiate GridView for all queries
    var store = new Ext.data.ArrayStore({
      fields : [ {
        name : 'query'
      } ],
      listeners : {
        'add' : updateDropDownMenu
      }
    });

    var grid = new Ext.grid.GridPanel({
      store : store,
      columns : [ {
        header : '#',
        width : 30,
        renderer : function(value, metadata, record, rowIndex, colIndex)
        {
          return (rowIndex + 1);
        }
      }, {
        id : 'query',
        header : 'Query',
        sortable : true,
        width : 330,
        dataIndex : 'query',
        renderer : function(value)
        {
          return "
" + value + "
";
        }
      }, {
        header : "url",
        width : 30,
        dataIndex : "id",
        renderer : function()
        {
          var action = 'getCitationWindow()';
          var linkStart = "";
          return linkStart + conf_context + linkEnd;
        }
      } ],
      sm : new Ext.grid.RowSelectionModel({
        singleSelect : true,
        store : store,
        listeners : {
          'rowselect' : function(row, rowIndex, record)
          {
            Ext.getCmp('queryAnnisQL').setValue(record.get('query'));
          }
        }
      }),
      stripeRows : true,
      width : 400,
      height : 300
    });

    var historyWindow = function()
    {
      new Ext.Window({
        autoDestroy : true,
        title : 'history',
        width : 400,
        height : 300,
        items : grid,
        closeAction : 'hide',
        stateful : true,
        stateId : 'grid'
      }).show();
    };

    this.update = function(lastQuery)
    {
      // insert query into arraystore and use query for index
      store.insert(0, new store.recordType({
        query : lastQuery
      }, lastQuery));

      grid.getView().refresh(false);
    };

    this.splitButton = new Ext.SplitButton({
      fieldLabel : 'History',
      text : 'Query History',
      menu : new Ext.menu.Menu(),
      listeners : {
        'click' : historyWindow
      }
    });
  };
});<|endoftext|>


<commit_before>/*

THIS IS A WORK IN PROGRESS...

*/
var mingy = require('../lib/mingy')
  , Parser = mingy.Parser
  , Command = mingy.Command
  , WebServer = mingy.WebServer
  , url = require('url')
  , querystring = require('querystring')

var parser = new Parser()

// define commands (which function as routes)
parser.addCommand('home')
.set('syntax', ['<method>'])
.set('logic', function(args, env, system) {

  var output = ''

  if (args.method == 'GET') {

    output += '
Hello World!
'+
              '
Check out the news.
'+
              '
Add Story
'+
              '<form action="/" method="post">'+
              '
Slug: <input type="text" name="slug" />
'+
              '
Title: <input type="text" name="title" />
'+
              '
Body: <textarea name="body"></textarea>
'+
              '
<input type="submit" value="Post" />
'+
              '</form>'
  }
  else if(args.method == 'POST') {

    system.getPost(system.request, function(storyData) {

      env.news[storyData.slug] = {
        "title": storyData.title,
        "body": storyData.body
      }

      output += 'Story added. Check out the news.'

      system.callback(output)
    })
  }

  return output
})

parser.addCommand('news')
.set('syntax', ['GET news', 'GET news <story>'])
.set('logic', function(args, env) {

  var output = ''

  if (args['story']) {

    output += "
" + env.news[args.story].title + "
"
    output += "
" + env.news[args.story].body + "
"
  }
  else {

    output += "
News!
"

    for (var story in env.news) {
      output += "" + env.news[story].title + "
"
    }
  }

  return output
})

// in-memory store of stories
parser.setEnv(
  'news',
  {
    "earthquake": {
      "title": "Horrid Earthquake",
      "body": "The earthquake was depressing."
    },
    "disease": {
      "title": "That Disease isn't such a Problem Anymore",
      "body": "The disease was cured."
    }
  }
)

var web = new WebServer(parser)
.set('port', '8888')
.start()
<commit_msg>Moved some lines around.<commit_after>/*

THIS IS A WORK IN PROGRESS...

*/
var mingy = require('../lib/mingy')
  , Parser = mingy.Parser
  , Command = mingy.Command
  , WebServer = mingy.WebServer
  , url = require('url')
  , querystring = require('querystring')

// in-memory store of stories
parser.setEnv(
  'news',
  {
    "earthquake": {
      "title": "Horrid Earthquake",
      "body": "The earthquake was depressing."
    },
    "disease": {
      "title": "That Disease isn't such a Problem Anymore",
      "body": "The disease was cured."
    }
  }
)

var parser = new Parser()

// define commands (which function as routes)
parser.addCommand('home')
.set('syntax', ['<method>'])
.set('logic', function(args, env, system) {

  var output = ''

  if (args.method == 'GET') {

    output += '
Hello World!
'+
              '
Check out the news.
'+
              '
Add Story
'+
              '<form action="/" method="post">'+
              '
Slug: <input type="text" name="slug" />
'+
              '
Title: <input type="text" name="title" />
'+
              '
Body: <textarea name="body"></textarea>
'+
              '
<input type="submit" value="Post" />
'+
              '</form>'
  }
  else if(args.method == 'POST') {

    system.getPost(system.request, function(storyData) {

      env.news[storyData.slug] = {
        "title": storyData.title,
        "body": storyData.body
      }

      output += 'Story added. Check out the news.'

      system.callback(output)
    })
  }

  return output
})

parser.addCommand('news')
.set('syntax', ['GET news', 'GET news <story>'])
.set('logic', function(args, env) {

  var output = ''

  if (args['story']) {

    output += "
" + env.news[args.story].title + "
"
    output += "
" + env.news[args.story].body + "
"
  }
  else {

    output += "
News!
"

    for (var story in env.news) {
      output += "" + env.news[story].title + "
"
    }
  }

  return output
})

var web = new WebServer(parser)
.set('port', '8888')
.start()
<|endoftext|>


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

import { takeEvery, all, put, select, call } from 'redux-saga/effects';
import { URLS } from 'common/urls';
import {
  showNotification,
  showDefaultErrorNotification,
  NOTIFICATION_TYPES,
} from 'controllers/notification';
import { projectIdSelector } from 'controllers/pages';
import { hideModalAction } from 'controllers/modal';
import { showScreenLockAction, hideScreenLockAction } from 'controllers/screenLock';
import { fetch } from 'common/utils';
import { activeProjectSelector, userIdSelector } from 'controllers/user';
import { setProjectIntegrationsAction } from 'controllers/plugins';
import {
  addFilterAction,
  fetchUserFiltersSuccessAction,
  removeFilterAction,
} from 'controllers/filter';

import {
  UPDATE_DEFECT_SUBTYPE,
  ADD_DEFECT_SUBTYPE,
  DELETE_DEFECT_SUBTYPE,
  UPDATE_NOTIFICATIONS_CONFIG,
  ADD_PATTERN,
  UPDATE_PATTERN,
  DELETE_PATTERN,
  PA_ATTRIBUTE_ENABLED_KEY,
  UPDATE_PA_STATE,
  FETCH_PROJECT,
  FETCH_PROJECT_PREFERENCES,
  FETCH_CONFIGURATION_ATTRIBUTES,
  HIDE_FILTER_ON_LAUNCHES,
  SHOW_FILTER_ON_LAUNCHES,
  UPDATE_PROJECT_FILTER_PREFERENCES,
} from './constants';
import {
  updateDefectSubTypeSuccessAction,
  addDefectSubTypeSuccessAction,
  deleteDefectSubTypeSuccessAction,
  updateProjectNotificationsConfigSuccessAction,
  addPatternSuccessAction,
  updatePatternSuccessAction,
  deletePatternSuccessAction,
  updateConfigurationAttributesAction,
  fetchProjectPreferencesAction,
  fetchProjectSuccessAction,
  fetchProjectPreferencesSuccessAction,
  updateProjectFilterPreferencesAction,
} from './actionCreators';
import { projectNotificationsConfigurationSelector } from './selectors';

function* updateDefectSubType({ payload: subTypes }) {
  try {
    const projectId = yield select(projectIdSelector);
    const data = {
      ids: subTypes,
    };
    yield call(fetch, URLS.projectDefectSubType(projectId), {
      method: 'put',
      data,
    });
    yield put(updateDefectSubTypeSuccessAction(subTypes));
    yield put(
      showNotification({
        messageId: 'updateDefectSubTypeSuccess',
        type: NOTIFICATION_TYPES.SUCCESS,
      }),
    );
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  }
}

function* watchUpdateDefectSubType() {
  yield takeEvery(UPDATE_DEFECT_SUBTYPE, updateDefectSubType);
}

function* addDefectSubType({ payload: subType }) {
  try {
    const projectId = yield select(projectIdSelector);
    const response = yield call(fetch, URLS.projectDefectSubType(projectId), {
      method: 'post',
      data: subType,
    });
    yield put(addDefectSubTypeSuccessAction({ ...response, ...subType }));
    yield put(
      showNotification({
        messageId: 'updateDefectSubTypeSuccess',
        type: NOTIFICATION_TYPES.SUCCESS,
      }),
    );
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  }
}

function* watchAddDefectSubType() {
  yield takeEvery(ADD_DEFECT_SUBTYPE, addDefectSubType);
}

function* deleteDefectSubType({ payload: subType }) {
  try {
    const projectId = yield select(projectIdSelector);
    yield call(fetch, URLS.projectDeleteDefectSubType(projectId, subType.id), {
      method: 'delete',
    });
    yield put(deleteDefectSubTypeSuccessAction(subType));
    yield put(
      showNotification({
        messageId: 'deleteDefectSubTypeSuccess',
        type: NOTIFICATION_TYPES.SUCCESS,
      }),
    );
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  }
}

function* watchDeleteDefectSubType() {
  yield takeEvery(DELETE_DEFECT_SUBTYPE, deleteDefectSubType);
}

function* updateProjectNotificationsConfig({ payload: notificationsConfig }) {
  yield put(showScreenLockAction());
  try {
    const currentConfig = yield select(projectNotificationsConfigurationSelector);
    const projectId = yield select(projectIdSelector);
    const newConfig = { ...currentConfig, ...notificationsConfig };

    yield call(fetch, URLS.projectNotificationConfiguration(projectId), {
      method: 'put',
      data: newConfig,
    });
    yield put(updateProjectNotificationsConfigSuccessAction(newConfig));
    yield put(
      showNotification({
        messageId: 'updateProjectNotificationsConfigurationSuccess',
        type: NOTIFICATION_TYPES.SUCCESS,
      }),
    );
    yield put(hideModalAction());
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  } finally {
    yield put(hideScreenLockAction());
  }
}

function* watchUpdateProjectNotificationsConfig() {
  yield takeEvery(UPDATE_NOTIFICATIONS_CONFIG, updateProjectNotificationsConfig);
}

function* addPattern({ payload: pattern }) {
  try {
    const projectId = yield select(projectIdSelector);
    const response = yield call(fetch, URLS.projectAddPattern(projectId), {
      method: 'post',
      data: pattern,
    });
    yield put(addPatternSuccessAction({ ...pattern, ...response }));
    yield put(
      showNotification({
        messageId: 'addPatternSuccess',
        type: NOTIFICATION_TYPES.SUCCESS,
      }),
    );
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  }
}

function* watchAddPattern() {
  yield takeEvery(ADD_PATTERN, addPattern);
}

function* updatePattern({ payload: pattern }) {
  try {
    const projectId = yield select(projectIdSelector);
    yield call(fetch, URLS.projectUpdatePattern(projectId, pattern.id), {
      method: 'put',
      data: {
        name: pattern.name,
        enabled: pattern.enabled,
      },
    });
    yield put(updatePatternSuccessAction(pattern));
    yield put(
      showNotification({
        messageId: 'updatePatternSuccess',
        type: NOTIFICATION_TYPES.SUCCESS,
      }),
    );
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  }
}

function* watchUpdatePattern() {
  yield takeEvery(UPDATE_PATTERN, updatePattern);
}

function* deletePattern({ payload: pattern }) {
  try {
    const projectId = yield select(projectIdSelector);
    yield call(fetch, URLS.projectUpdatePattern(projectId, pattern.id), { method: 'delete' });
    yield put(deletePatternSuccessAction(pattern));
    yield put(
      showNotification({
        messageId: 'deletePatternSuccess',
        type: NOTIFICATION_TYPES.SUCCESS,
      }),
    );
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  }
}

function* watchDeletePattern() {
  yield takeEvery(DELETE_PATTERN, deletePattern);
}

function* updatePAState({ payload: PAEnabled }) {
  yield put(showScreenLockAction());
  try {
    const projectId = yield select(projectIdSelector);
    const updatedConfig = {
      configuration: {
        attributes: {
          [PA_ATTRIBUTE_ENABLED_KEY]: PAEnabled.toString(),
        },
      },
    };

    yield call(fetch, URLS.project(projectId), {
      method: 'put',
      data: updatedConfig,
    });
    yield put(updateConfigurationAttributesAction(updatedConfig));
    yield put(
      showNotification({
        messageId: 'updatePAStateSuccess',
        type: NOTIFICATION_TYPES.SUCCESS,
      }),
    );
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  } finally {
    yield put(hideScreenLockAction());
  }
}

function* watchUpdatePAState() {
  yield takeEvery(UPDATE_PA_STATE, updatePAState);
}

function* fetchProject({ payload: { projectId, isAdminAccess } }) {
  try {
    const project = yield call(fetch, URLS.project(projectId));
    yield put(fetchProjectSuccessAction(project));
    yield put(setProjectIntegrationsAction(project.integrations));
    if (!isAdminAccess) {
      yield put(fetchProjectPreferencesAction(projectId));
    }
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  }
}

function* watchFetchProject() {
  yield takeEvery(FETCH_PROJECT, fetchProject);
}

function* fetchProjectPreferences({ payload: projectId }) {
  const userId = yield select(userIdSelector);
  const preferences = yield call(fetch, URLS.projectPreferences(projectId, userId));
  yield put(fetchProjectPreferencesSuccessAction(preferences));
  yield put(fetchUserFiltersSuccessAction(preferences.filters));
}

function* watchFetchProjectPreferences() {
  yield takeEvery(FETCH_PROJECT_PREFERENCES, fetchProjectPreferences);
}

function* fetchConfigurationAttributes({ payload: projectId }) {
  const project = yield call(fetch, URLS.project(projectId));
  yield put(updateConfigurationAttributesAction(project));
}

function* watchFetchConfigurationAttributes() {
  yield takeEvery(FETCH_CONFIGURATION_ATTRIBUTES, fetchConfigurationAttributes);
}

function* hideFilterOnLaunches({ payload: filter }) {
  yield put(removeFilterAction(filter.id));
  yield put(updateProjectFilterPreferencesAction(filter.id, 'DELETE'));
}

function* watchHideFilterOnLaunches() {
  yield takeEvery(HIDE_FILTER_ON_LAUNCHES, hideFilterOnLaunches);
}

function* showFilterOnLaunches({ payload: filter }) {
  yield put(addFilterAction(filter));
  yield put(updateProjectFilterPreferencesAction(filter.id, 'PUT'));
}

function* watchShowFilterOnLaunches() {
  yield takeEvery(SHOW_FILTER_ON_LAUNCHES, showFilterOnLaunches);
}

function* updateProjectFilterPreferences({ payload = {} }) {
  const { filterId, method } = payload;
  const activeProject = yield select(activeProjectSelector);
  const userId = yield select(userIdSelector);
  yield call(fetch, URLS.projectPreferences(activeProject, userId, filterId), { method });
}

function* watchUpdateProjectFilterPreferences() {
  yield takeEvery(UPDATE_PROJECT_FILTER_PREFERENCES, updateProjectFilterPreferences);
}

export function* projectSagas() {
  yield all([
    watchUpdateDefectSubType(),
    watchAddDefectSubType(),
    watchDeleteDefectSubType(),
    watchUpdateProjectNotificationsConfig(),
    watchAddPattern(),
    watchUpdatePattern(),
    watchUpdatePAState(),
    watchDeletePattern(),
    watchFetchProject(),
    watchFetchProjectPreferences(),
    watchFetchConfigurationAttributes(),
    watchHideFilterOnLaunches(),
    watchShowFilterOnLaunches(),
    watchUpdateProjectFilterPreferences(),
  ]);
}
<commit_msg>EPMRPP-42200. Enable PA by default when the first pattern is created.<commit_after>/*
 * Copyright 2019 EPAM Systems
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { takeEvery, all, put, select, call } from 'redux-saga/effects';
import { URLS } from 'common/urls';
import {
  showNotification,
  showDefaultErrorNotification,
  NOTIFICATION_TYPES,
} from 'controllers/notification';
import { projectIdSelector } from 'controllers/pages';
import { hideModalAction } from 'controllers/modal';
import { showScreenLockAction, hideScreenLockAction } from 'controllers/screenLock';
import { fetch } from 'common/utils';
import { activeProjectSelector, userIdSelector } from 'controllers/user';
import { setProjectIntegrationsAction } from 'controllers/plugins';
import {
  addFilterAction,
  fetchUserFiltersSuccessAction,
  removeFilterAction,
} from 'controllers/filter';

import {
  UPDATE_DEFECT_SUBTYPE,
  ADD_DEFECT_SUBTYPE,
  DELETE_DEFECT_SUBTYPE,
  UPDATE_NOTIFICATIONS_CONFIG,
  ADD_PATTERN,
  UPDATE_PATTERN,
  DELETE_PATTERN,
  PA_ATTRIBUTE_ENABLED_KEY,
  UPDATE_PA_STATE,
  FETCH_PROJECT,
  FETCH_PROJECT_PREFERENCES,
  FETCH_CONFIGURATION_ATTRIBUTES,
  HIDE_FILTER_ON_LAUNCHES,
  SHOW_FILTER_ON_LAUNCHES,
  UPDATE_PROJECT_FILTER_PREFERENCES,
} from './constants';
import {
  updateDefectSubTypeSuccessAction,
  addDefectSubTypeSuccessAction,
  deleteDefectSubTypeSuccessAction,
  updateProjectNotificationsConfigSuccessAction,
  addPatternSuccessAction,
  updatePatternSuccessAction,
  deletePatternSuccessAction,
  updateConfigurationAttributesAction,
  fetchProjectPreferencesAction,
  fetchProjectSuccessAction,
  fetchProjectPreferencesSuccessAction,
  updateProjectFilterPreferencesAction,
} from './actionCreators';
import { projectNotificationsConfigurationSelector, patternsSelector } from './selectors';

function* updateDefectSubType({ payload: subTypes }) {
  try {
    const projectId = yield select(projectIdSelector);
    const data = {
      ids: subTypes,
    };
    yield call(fetch, URLS.projectDefectSubType(projectId), {
      method: 'put',
      data,
    });
    yield put(updateDefectSubTypeSuccessAction(subTypes));
    yield put(
      showNotification({
        messageId: 'updateDefectSubTypeSuccess',
        type: NOTIFICATION_TYPES.SUCCESS,
      }),
    );
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  }
}

function* watchUpdateDefectSubType() {
  yield takeEvery(UPDATE_DEFECT_SUBTYPE, updateDefectSubType);
}

function* addDefectSubType({ payload: subType }) {
  try {
    const projectId = yield select(projectIdSelector);
    const response = yield call(fetch, URLS.projectDefectSubType(projectId), {
      method: 'post',
      data: subType,
    });
    yield put(addDefectSubTypeSuccessAction({ ...response, ...subType }));
    yield put(
      showNotification({
        messageId: 'updateDefectSubTypeSuccess',
        type: NOTIFICATION_TYPES.SUCCESS,
      }),
    );
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  }
}

function* watchAddDefectSubType() {
  yield takeEvery(ADD_DEFECT_SUBTYPE, addDefectSubType);
}

function* deleteDefectSubType({ payload: subType }) {
  try {
    const projectId = yield select(projectIdSelector);
    yield call(fetch, URLS.projectDeleteDefectSubType(projectId, subType.id), {
      method: 'delete',
    });
    yield put(deleteDefectSubTypeSuccessAction(subType));
    yield put(
      showNotification({
        messageId: 'deleteDefectSubTypeSuccess',
        type: NOTIFICATION_TYPES.SUCCESS,
      }),
    );
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  }
}

function* watchDeleteDefectSubType() {
  yield takeEvery(DELETE_DEFECT_SUBTYPE, deleteDefectSubType);
}

function* updateProjectNotificationsConfig({ payload: notificationsConfig }) {
  yield put(showScreenLockAction());
  try {
    const currentConfig = yield select(projectNotificationsConfigurationSelector);
    const projectId = yield select(projectIdSelector);
    const newConfig = { ...currentConfig, ...notificationsConfig };

    yield call(fetch, URLS.projectNotificationConfiguration(projectId), {
      method: 'put',
      data: newConfig,
    });
    yield put(updateProjectNotificationsConfigSuccessAction(newConfig));
    yield put(
      showNotification({
        messageId: 'updateProjectNotificationsConfigurationSuccess',
        type: NOTIFICATION_TYPES.SUCCESS,
      }),
    );
    yield put(hideModalAction());
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  } finally {
    yield put(hideScreenLockAction());
  }
}

function* watchUpdateProjectNotificationsConfig() {
  yield takeEvery(UPDATE_NOTIFICATIONS_CONFIG, updateProjectNotificationsConfig);
}

function* updatePAState(PAEnabled) {
  const projectId = yield select(projectIdSelector);
  const updatedConfig = {
    configuration: {
      attributes: {
        [PA_ATTRIBUTE_ENABLED_KEY]: PAEnabled.toString(),
      },
    },
  };

  yield call(fetch, URLS.project(projectId), {
    method: 'put',
    data: updatedConfig,
  });
  yield put(updateConfigurationAttributesAction(updatedConfig));
}

function* addPattern({ payload: pattern }) {
  try {
    const projectId = yield select(projectIdSelector);
    const response = yield call(fetch, URLS.projectAddPattern(projectId), {
      method: 'post',
      data: pattern,
    });
    const patterns = yield select(patternsSelector);
    if (!patterns.length) {
      yield call(updatePAState, true);
    }
    yield put(addPatternSuccessAction({ ...pattern, ...response }));
    yield put(
      showNotification({
        messageId: 'addPatternSuccess',
        type: NOTIFICATION_TYPES.SUCCESS,
      }),
    );
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  }
}

function* watchAddPattern() {
  yield takeEvery(ADD_PATTERN, addPattern);
}

function* updatePattern({ payload: pattern }) {
  try {
    const projectId = yield select(projectIdSelector);
    yield call(fetch, URLS.projectUpdatePattern(projectId, pattern.id), {
      method: 'put',
      data: {
        name: pattern.name,
        enabled: pattern.enabled,
      },
    });
    yield put(updatePatternSuccessAction(pattern));
    yield put(
      showNotification({
        messageId: 'updatePatternSuccess',
        type: NOTIFICATION_TYPES.SUCCESS,
      }),
    );
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  }
}

function* watchUpdatePattern() {
  yield takeEvery(UPDATE_PATTERN, updatePattern);
}

function* deletePattern({ payload: pattern }) {
  try {
    const projectId = yield select(projectIdSelector);
    yield call(fetch, URLS.projectUpdatePattern(projectId, pattern.id), { method: 'delete' });
    yield put(deletePatternSuccessAction(pattern));
    yield put(
      showNotification({
        messageId: 'deletePatternSuccess',
        type: NOTIFICATION_TYPES.SUCCESS,
      }),
    );
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  }
}

function* watchDeletePattern() {
  yield takeEvery(DELETE_PATTERN, deletePattern);
}

function* updatePAStateWithNotification({ payload: PAEnabled }) {
  yield put(showScreenLockAction());
  try {
    yield call(updatePAState, PAEnabled);
    yield put(
      showNotification({
        messageId: 'updatePAStateSuccess',
        type: NOTIFICATION_TYPES.SUCCESS,
      }),
    );
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  } finally {
    yield put(hideScreenLockAction());
  }
}

function* watchUpdatePAState() {
  yield takeEvery(UPDATE_PA_STATE, updatePAStateWithNotification);
}

function* fetchProject({ payload: { projectId, isAdminAccess } }) {
  try {
    const project = yield call(fetch, URLS.project(projectId));
    yield put(fetchProjectSuccessAction(project));
    yield put(setProjectIntegrationsAction(project.integrations));
    if (!isAdminAccess) {
      yield put(fetchProjectPreferencesAction(projectId));
    }
  } catch (error) {
    yield put(showDefaultErrorNotification(error));
  }
}

function* watchFetchProject() {
  yield takeEvery(FETCH_PROJECT, fetchProject);
}

function* fetchProjectPreferences({ payload: projectId }) {
  const userId = yield select(userIdSelector);
  const preferences = yield call(fetch, URLS.projectPreferences(projectId, userId));
  yield put(fetchProjectPreferencesSuccessAction(preferences));
  yield put(fetchUserFiltersSuccessAction(preferences.filters));
}

function* watchFetchProjectPreferences() {
  yield takeEvery(FETCH_PROJECT_PREFERENCES, fetchProjectPreferences);
}

function* fetchConfigurationAttributes({ payload: projectId }) {
  const project = yield call(fetch, URLS.project(projectId));
  yield put(updateConfigurationAttributesAction(project));
}

function* watchFetchConfigurationAttributes() {
  yield takeEvery(FETCH_CONFIGURATION_ATTRIBUTES, fetchConfigurationAttributes);
}

function* hideFilterOnLaunches({ payload: filter }) {
  yield put(removeFilterAction(filter.id));
  yield put(updateProjectFilterPreferencesAction(filter.id, 'DELETE'));
}

function* watchHideFilterOnLaunches() {
  yield takeEvery(HIDE_FILTER_ON_LAUNCHES, hideFilterOnLaunches);
}

function* showFilterOnLaunches({ payload: filter }) {
  yield put(addFilterAction(filter));
  yield put(updateProjectFilterPreferencesAction(filter.id, 'PUT'));
}

function* watchShowFilterOnLaunches() {
  yield takeEvery(SHOW_FILTER_ON_LAUNCHES, showFilterOnLaunches);
}

function* updateProjectFilterPreferences({ payload = {} }) {
  const { filterId, method } = payload;
  const activeProject = yield select(activeProjectSelector);
  const userId = yield select(userIdSelector);
  yield call(fetch, URLS.projectPreferences(activeProject, userId, filterId), { method });
}

function* watchUpdateProjectFilterPreferences() {
  yield takeEvery(UPDATE_PROJECT_FILTER_PREFERENCES, updateProjectFilterPreferences);
}

export function* projectSagas() {
  yield all([
    watchUpdateDefectSubType(),
    watchAddDefectSubType(),
    watchDeleteDefectSubType(),
    watchUpdateProjectNotificationsConfig(),
    watchAddPattern(),
    watchUpdatePattern(),
    watchUpdatePAState(),
    watchDeletePattern(),
    watchFetchProject(),
    watchFetchProjectPreferences(),
    watchFetchConfigurationAttributes(),
    watchHideFilterOnLaunches(),
    watchShowFilterOnLaunches(),
    watchUpdateProjectFilterPreferences(),
  ]);
}
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com
 * @author stewdio / http://stewd.io
 */

THREE.ViveController = function( id ) {

	THREE.Object3D.call( this );

	var
	scope = this,
	gamepad,
	axes = [ 0, 0 ],
	thumbpadIsPressed = false,
	triggerIsPressed = false,
	gripsArePressed = false,
	menuIsPressed = false;

	function dispatchViveControllerEvent( name, custom ) {

		var data = {};

		data.id = id;
		data.gamepad = gamepad;
		data.instance = scope;
		if ( custom !== undefined ) Object.assign( data, custom );
		window.dispatchEvent( new CustomEvent( 'viveController' + name, { detail: data } ) );

	}

	this.matrixAutoUpdate = false;
	this.standingMatrix = new THREE.Matrix4();
	this.getGamepad = function() {

		return gamepad;

	}
	this.getButtonState = function( button ) {

		return scope[ button + ( button === 'grips' ? 'ArePressed' : 'IsPressed' ) ];

	}
	this.update = function() {

		var pose;

		gamepad = navigator.getGamepads()[ id ];
		if ( gamepad !== undefined && gamepad.pose !== null ) {

			//  Position and orientation.

			pose = gamepad.pose;
			scope.position.fromArray( pose.position );
			scope.quaternion.fromArray( pose.orientation );
			scope.matrix.compose( scope.position, scope.quaternion, scope.scale );
			scope.matrix.multiplyMatrices( scope.standingMatrix, scope.matrix );
			scope.matrixWorldNeedsUpdate = true;
			scope.visible = true;

			//  Thumbpad and Buttons.

			if ( axes[ 0 ] !== gamepad.axes[ 0 ] ||
				axes[ 1 ] !== gamepad.axes[ 1 ] ) {

				axes[ 0 ] = gamepad.axes[ 0 ];//  X axis: -1 = Left, +1 = Right.
				axes[ 1 ] = gamepad.axes[ 1 ];//  Y axis: -1 = Bottom, +1 = Top.
				dispatchViveControllerEvent( 'AxisChanged', { axes: axes } );

			}
			if ( thumbpadIsPressed !== gamepad.buttons[ 0 ].pressed ) {

				thumbpadIsPressed = gamepad.buttons[ 0 ].pressed;
				dispatchViveControllerEvent( thumbpadIsPressed ? 'ThumbpadPressed' : 'ThumbpadReleased' );

			}
			if ( triggerIsPressed !== gamepad.buttons[ 1 ].pressed ) {

				triggerIsPressed = gamepad.buttons[ 1 ].pressed;
				dispatchViveControllerEvent( triggerIsPressed ? 'TriggerPressed' : 'TriggerReleased' );

			}
			if ( gripsArePressed !== gamepad.buttons[ 2 ].pressed ) {

				gripsArePressed = gamepad.buttons[ 2 ].pressed;
				dispatchViveControllerEvent( gripsArePressed ? 'GripsPressed' : 'GripsReleased' );

			}
			if ( menuIsPressed !== gamepad.buttons[ 3 ].pressed ) {

				menuIsPressed = gamepad.buttons[ 3 ].pressed;
				dispatchViveControllerEvent( menuIsPressed ? 'MenuPressed' : 'MenuReleased' );

			}

		}
		else scope.visible = false;

	}

}
THREE.ViveController.prototype = Object.create( THREE.Object3D.prototype );
THREE.ViveController.prototype.constructor = THREE.ViveController;
<commit_msg>ViveController: Clean up and using DOM like event names.<commit_after>/**
 * @author mrdoob / http://mrdoob.com
 * @author stewdio / http://stewd.io
 */

THREE.ViveController = function ( id ) {

	THREE.Object3D.call( this );

	var scope = this;
	var gamepad;

	var axes = [ 0, 0 ];
	var thumbpadIsPressed = false;
	var triggerIsPressed = false;
	var gripsArePressed = false;
	var menuIsPressed = false;

	this.matrixAutoUpdate = false;
	this.standingMatrix = new THREE.Matrix4();

	this.getGamepad = function () {

		return gamepad;

	};

	this.getButtonState = function ( button ) {

		return scope[ button + ( button === 'grips' ? 'ArePressed' : 'IsPressed' ) ];

	};

	this.update = function () {

		gamepad = navigator.getGamepads()[ id ];

		if ( gamepad !== undefined && gamepad.pose !== null ) {

			//  Position and orientation.

			var pose = gamepad.pose;

			scope.position.fromArray( pose.position );
			scope.quaternion.fromArray( pose.orientation );
			scope.matrix.compose( scope.position, scope.quaternion, scope.scale );
			scope.matrix.multiplyMatrices( scope.standingMatrix, scope.matrix );
			scope.matrixWorldNeedsUpdate = true;
			scope.visible = true;

			//  Thumbpad and Buttons.

			if ( axes[ 0 ] !== gamepad.axes[ 0 ] || axes[ 1 ] !== gamepad.axes[ 1 ] ) {

				axes[ 0 ] = gamepad.axes[ 0 ]; //  X axis: -1 = Left, +1 = Right.
				axes[ 1 ] = gamepad.axes[ 1 ]; //  Y axis: -1 = Bottom, +1 = Top.
				scope.dispatchEvent( { type: 'axischanged', axes: axes } );

			}

			if ( thumbpadIsPressed !== gamepad.buttons[ 0 ].pressed ) {

				thumbpadIsPressed = gamepad.buttons[ 0 ].pressed;
				scope.dispatchEvent( { type: thumbpadIsPressed ? 'thumbpaddown' : 'thumbpadup' } );

			}

			if ( triggerIsPressed !== gamepad.buttons[ 1 ].pressed ) {

				triggerIsPressed = gamepad.buttons[ 1 ].pressed;
				scope.dispatchEvent( { type: triggerIsPressed ? 'triggerdown' : 'triggerup' } );

			}

			if ( gripsArePressed !== gamepad.buttons[ 2 ].pressed ) {

				gripsArePressed = gamepad.buttons[ 2 ].pressed;
				scope.dispatchEvent( { type: gripsArePressed ? 'gripsdown' : 'gripsup' } );

			}

			if ( menuIsPressed !== gamepad.buttons[ 3 ].pressed ) {

				menuIsPressed = gamepad.buttons[ 3 ].pressed;
				scope.dispatchEvent( { type: menuIsPressed ? 'menudown' : 'menuup' } );

			}

		} else {

			scope.visible = false;

		}

	};

};

THREE.ViveController.prototype = Object.create( THREE.Object3D.prototype );
THREE.ViveController.prototype.constructor = THREE.ViveController;
<|endoftext|>


<commit_before>"use strict";

const asTable   = require ('as-table')
    , log       = require ('ololog').noLocate
    , ansi      = require ('ansicolor').nice
    , ccxt      = require ('../../ccxt.js')

let printSupportedExchanges = function () {
    log ('Supported exchanges:', ccxt.exchanges.join (', ').green)
}

let printUsage = function () {
    log ('Usage: node', process.argv[1], 'exchange'.green, 'symbol'.yellow, 'depth'.cyan)
    printSupportedExchanges ()
}

let printOrderBook = async (id, symbol, depth) => {

    // check if the exchange is supported by ccxt
    let exchangeFound = ccxt.exchanges.indexOf (id) > -1
    if (exchangeFound) {

        log ('Instantiating', id.green, 'exchange')

        // instantiate the exchange by id
        let exchange = new ccxt[id] ({ enableRateLimit: true })

        // load all markets from the exchange
        let markets = await exchange.loadMarkets ()

        // // output a list of all market symbols
        // log (id.green, 'has', exchange.symbols.length, 'symbols:', exchange.symbols.join (', ').yellow)

        if (symbol in exchange.markets) {

            const market = exchange.markets[symbol]
            const pricePrecision = market.precision ? market.precision.price : 8
            const amountPrecision = market.precision ? market.precision.amount : 8

            // Object.values (markets).forEach (market => log (market))

            // make a table of all markets
            // const table = asTable.configure ({ delimiter: ' | ' }) (Object.values (markets))
            // log (table)

            const priceVolumeHelper = color => ([price, amount]) => ({
                price: price.toFixed (pricePrecision)[color],
                amount: amount.toFixed (amountPrecision)[color],
            })

            const cursorUp = '\u001b[1A'
            const tableHeight = depth * 2 + 4 // bids + asks + headers

            log (' ') // empty line

            while (true) {

                const orderbook = await exchange.fetchOrderBook (symbol)

                log (symbol.green, exchange.iso8601 (exchange.milliseconds ()))

                log (asTable.configure ({ delimiter: ' | '.dim, right: true }) ([
                    ... orderbook.asks.slice (0, depth).reverse ().map (priceVolumeHelper ('red')),
                    // { price: '--------'.dim, amount: '--------'.dim },
                    ... orderbook.bids.slice (0, depth).map (priceVolumeHelper ('green')),
                ]))

                log (cursorUp.repeat (tableHeight))
            }

        } else {

            log.error ('Symbol', symbol.bright, 'not found')
        }

    } else {

        log ('Exchange ' + id.red + ' not found')
        printSupportedExchanges ()
    }
}

;(async function main () {

    if (process.argv.length > 4) {

        const id = process.argv[2]
        const symbol = process.argv[3].toUpperCase ()
        const depth = parseInt (process.argv[4])
        await printOrderBook (id, symbol, depth)

    } else {

        printUsage ()
    }

    process.exit ()

}) ()<commit_msg>examples/js/live-orderbook.js table fix<commit_after>"use strict";

const asTable   = require ('as-table')
    , log       = require ('ololog').noLocate
    , ansi      = require ('ansicolor').nice
    , ccxt      = require ('../../ccxt.js')

let printSupportedExchanges = function () {
    log ('Supported exchanges:', ccxt.exchanges.join (', ').green)
}

let printUsage = function () {
    log ('Usage: node', process.argv[1], 'exchange'.green, 'symbol'.yellow, 'depth'.cyan)
    printSupportedExchanges ()
}

let printOrderBook = async (id, symbol, depth) => {

    // check if the exchange is supported by ccxt
    let exchangeFound = ccxt.exchanges.indexOf (id) > -1
    if (exchangeFound) {

        log ('Instantiating', id.green, 'exchange')

        // instantiate the exchange by id
        let exchange = new ccxt[id] ({ enableRateLimit: true })

        // load all markets from the exchange
        let markets = await exchange.loadMarkets ()

        // // output a list of all market symbols
        // log (id.green, 'has', exchange.symbols.length, 'symbols:', exchange.symbols.join (', ').yellow)

        if (symbol in exchange.markets) {

            const market = exchange.markets[symbol]
            const pricePrecision = market.precision ? market.precision.price : 8
            const amountPrecision = market.precision ? market.precision.amount : 8

            // Object.values (markets).forEach (market => log (market))

            // make a table of all markets
            // const table = asTable.configure ({ delimiter: ' | ' }) (Object.values (markets))
            // log (table)

            const priceVolumeHelper = color => ([price, amount]) => ({
                price: price.toFixed (pricePrecision)[color],
                amount: amount.toFixed (amountPrecision)[color],
                '  ': '  ',
            })

            const cursorUp = '\u001b[1A'
            const tableHeight = depth * 2 + 4 // bids + asks + headers

            log (' ') // empty line

            while (true) {

                const orderbook = await exchange.fetchOrderBook (symbol)

                log (symbol.green, exchange.iso8601 (exchange.milliseconds ()))

                log (asTable.configure ({ delimiter: ' | '.dim, right: true }) ([
                    ... orderbook.asks.slice (0, depth).reverse ().map (priceVolumeHelper ('red')),
                    // { price: '--------'.dim, amount: '--------'.dim },
                    ... orderbook.bids.slice (0, depth).map (priceVolumeHelper ('green')),
                ]))

                log (cursorUp.repeat (tableHeight))
            }

        } else {

            log.error ('Symbol', symbol.bright, 'not found')
        }

    } else {

        log ('Exchange ' + id.red + ' not found')
        printSupportedExchanges ()
    }
}

;(async function main () {

    if (process.argv.length > 4) {

        const id = process.argv[2]
        const symbol = process.argv[3].toUpperCase ()
        const depth = parseInt (process.argv[4])
        await printOrderBook (id, symbol, depth)

    } else {

        printUsage ()
    }

    process.exit ()

}) ()<|endoftext|>