<commit_before>/*
 * Copyright (c) 2016 Kagilum SAS.
 *
 * This file is part of iceScrum.
 *
 * iceScrum 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.
 *
 * iceScrum is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with iceScrum.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *
 * Vincent Barrier (vbarrier@kagilum.com)
 * Nicolas Noullet (nnoullet@kagilum.com)
 * Colin Bontemps (cbontemps@kagilum.com)
 *
 */

extensibleController('taskBoardCtrl', ['$scope', '$state', '$filter', 'UserService', 'StoryService', 'TaskService', 'SprintService', 'Session', 'SprintStatesByName', 'StoryStatesByName', 'TaskStatesByName', 'TaskTypesByName', 'project', 'sprint', 'releases', function($scope, $state, $filter, UserService, StoryService, TaskService, SprintService, Session, SprintStatesByName, StoryStatesByName, TaskStatesByName, TaskTypesByName, project, sprint, releases) {
    $scope.viewName = 'taskBoard';
    // Functions
    $scope.isSelected = function(selectable) {
        if (selectable.class == "Story") {
            return $state.params.storyId ? $state.params.storyId == selectable.id : false;
        } else {
            return $state.params.taskId ? $state.params.taskId == selectable.id : false;
        }
    };
    $scope.hasSelected = function() {
        return $state.params.taskId != undefined;
    };
    $scope.isSortableTaskBoard = function(sprint) {
        return Session.authenticated() && sprint.state < SprintStatesByName.DONE;
    };
    $scope.isSortableStory = function(story) {
        return story.state < StoryStatesByName.DONE;
    };
    $scope.openSprintUrl = function(sprint, keepDetails) {
        var stateName = 'taskBoard';
        if (keepDetails && $state.current.name == 'taskBoard.details' || !keepDetails && $state.current.name != 'taskBoard.details') {
            stateName += '.details';
        }
        return $state.href(stateName, {sprintId: sprint.id});
    };
    $scope.openNewTaskByStory = function(story) {
        $state.go('taskBoard.task.new', {taskCategory: _.pick(story, ['id', 'name', 'class'])});
    };
    $scope.openNewTaskByType = function(type) {
        $state.go('taskBoard.task.new', {taskCategory: {id: type, name: $filter('i18n')(type, 'TaskTypes')}});
    };
    $scope.copyRecurrentTasks = function(sprint) {
        SprintService.copyRecurrentTasks(sprint, project);
    };
    $scope.applySearchFilterToTasksByTypeByState = function() {
        // Search filter must be applied to model because of https://github.com/a5hik/ng-sortable/issues/184
        $scope.tasksByTypeByStateAndSearchFiltered = _.mapValues($scope.tasksByTypeByState, function(tasksByState) {
            return _.mapValues(tasksByState, function(tasks) {
                return $filter('search')(tasks);
            })
        });
    };
    $scope.refreshTasks = function() {
        if (!$scope.sprint) {
            return;
        }
        var tasks;
        tasks = $scope.sprint.tasks;
        $scope.taskCountByState = _.countBy(tasks, 'state');
        $scope.taskCountByType = _.countBy(tasks, 'type');
        $scope.countByFilter();
        switch ($scope.sprint.state) {
            case SprintStatesByName.TODO:
                $scope.sprintTaskStates = [TaskStatesByName.TODO];
                break;
            case SprintStatesByName.IN_PROGRESS:
                $scope.sprintTaskStates = $scope.taskStates;
                break;
            case SprintStatesByName.DONE:
                $scope.sprintTaskStates = [TaskStatesByName.DONE];
                break;
        }
        var partitionedTasks = _.partition(tasks, function(task) {
            return _.isNull(task.parentStory);
        });
        var groupByStateAndSort = function(tasksDictionnary) {
            return _.mapValues(tasksDictionnary, function(tasks) {
                return _.mapValues(_.groupBy(tasks, 'state'), function(tasks) {
                    return _.sortBy(_.filter(tasks, $scope.currentSprintFilter.filter), 'rank');
                });
            });
        };
        $scope.tasksByTypeByState = groupByStateAndSort(_.groupBy(partitionedTasks[0], 'type'));
        $scope.tasksByStoryByState = groupByStateAndSort(_.groupBy(partitionedTasks[1], 'parentStory.id'));
        var sprintStoriesIds = _.map($scope.sprint.stories, 'id');
        var allStoriesIds = _.union(sprintStoriesIds, _.map(partitionedTasks[1], 'parentStory.id'));
        var ghostStoriesIds = _.difference(allStoriesIds, sprintStoriesIds);
        if (ghostStoriesIds) {
            StoryService.getMultiple(ghostStoriesIds, project.id).then(function(ghostStories) {
                $scope.ghostStories = ghostStories;
            });
        }
        var fillGapsInDictionnary = function(dictionnary, firstLevelKeys, secondLevelKeys) {
            _.each(firstLevelKeys, function(firstLevelKey) {
                if (!dictionnary[firstLevelKey]) {
                    dictionnary[firstLevelKey] = {};
                }
                _.each(secondLevelKeys, function(secondLevelKey) {
                    if (!dictionnary[firstLevelKey][secondLevelKey]) {
                        dictionnary[firstLevelKey][secondLevelKey] = [];
                    }
                });
            });
        };
        fillGapsInDictionnary($scope.tasksByTypeByState, $scope.taskTypes, $scope.sprintTaskStates);
        fillGapsInDictionnary($scope.tasksByStoryByState, allStoriesIds, $scope.sprintTaskStates);
        $scope.applySearchFilterToTasksByTypeByState();
    };
    $scope.changeSprintFilter = function(sprintFilter) {
        $scope.currentSprintFilter = sprintFilter;
        $scope.refreshTasks();
        var editableUser = angular.copy(Session.user);
        editableUser.preferences.filterTask = sprintFilter.id;
        UserService.update(editableUser).then(function() {
            Session.user.preferences.filterTask = sprintFilter.id;
        });
    };
    $scope.storyFilter = function(story) {
        return $scope.currentSprintFilter.id == 'allTasks' ||
               _.some($scope.tasksByStoryByState[story.id], function(tasks) {
                   return tasks.length > 0;
               });
    };
    $scope.openStoryUrl = function(storyId) {
        return '#/' + $scope.viewName + ($state.params.sprintId ? '/' + $state.params.sprintId : '') + '/story/' + storyId;
    };
    $scope.selectStory = function(event, storyId) {
        if (angular.element(event.target).closest('.action, button, a').length == 0) {
            $state.go('taskBoard.story.details' + ($state.params.storyTabId ? '.tab' : ''), {storyId: storyId});
        }
    };
    $scope.tasksShown = function(taskState, typeOrStory, fromStoryGhost) {
        var taskLimit = 5;
        if (taskState == TaskStatesByName.DONE && $scope.sprint.state < SprintStatesByName.DONE) {
            if (_.isObject(typeOrStory)) {
                var story = typeOrStory;
                if (story.state === StoryStatesByName.DONE || fromStoryGhost) {
                    return $scope.tasksShownByTypeOrStory.stories[story.id];
                } else {
                    return $scope.tasksByStoryByState[story.id][taskState].length < taskLimit || $scope.tasksShownByTypeOrStory.stories[story.id];
                }
            } else {
                var type = typeOrStory;
                return $scope.tasksByTypeByState[type][taskState].length < taskLimit || $scope.tasksShownByTypeOrStory[type];
            }
        } else {
            return true;
        }
    };
    $scope.tasksHidden = function(taskState, typeOrStory, fromStoryGhost) {
        var taskLimit = 5;
        if (taskState == TaskStatesByName.DONE && $scope.sprint.state < SprintStatesByName.DONE) {
            if (_.isObject(typeOrStory)) {
                var story = typeOrStory;
                if (story.state === StoryStatesByName.DONE || fromStoryGhost) {
                    return $scope.tasksShownByTypeOrStory.stories[story.id];
                } else {
                    return $scope.tasksByStoryByState[story.id][taskState].length >= taskLimit && $scope.tasksShownByTypeOrStory.stories[story.id];
                }
            } else {
                var type = typeOrStory;
                return $scope.tasksByTypeByState[type][taskState].length >= taskLimit && $scope.tasksShownByTypeOrStory[type];
            }
        } else {
            return false;
        }
    };
    $scope.showTasks = function(typeOrStory, show) {
        if (_.isObject(typeOrStory)) {
            $scope.tasksShownByTypeOrStory.stories[typeOrStory.id] = show;
        } else {
            $scope.tasksShownByTypeOrStory[typeOrStory] = show;
        }
    };
    $scope.sprintRemainingTime = function(sprint) {
        return _.sumBy(sprint.tasks, 'estimation');
    };
    $scope.scrollToActiveSprint = function(open) {
        if (open) {
            var dropdown = angular.element('.planning-dropdown');
            var ele = dropdown.find("li>a.active");
            var list = dropdown.find('.planning-menu');
            var posi = list.scrollTop() + ele.offset().top - ele.innerHeight();
            list.animate({
                scrollTop: posi - 60
            }, 200);
        }
    };
    $scope.initSprintFilter = function() {
        var sprintFilter = Session.authenticated() ? Session.user.preferences.filterTask : 'allTasks';
        var filter = _.find($scope.sprintFilters, {id: sprintFilter});
        $scope.currentSprintFilter = filter ? filter : _.find($scope.sprintFilters, {id: 'allTasks'});
    };
    $scope.countByFilter = function() {
        _.each($scope.sprintFilters, function(sprintFilter) {
            sprintFilter.count = _.filter($scope.sprint.tasks, sprintFilter.filter).length;
        });
    };
    // Init
    $scope.project = project;
    $scope.taskSortableOptions = {
        itemMoved: function(event) {
            var destScope = event.dest.sortableScope;
            var task = event.source.itemScope.modelValue;
            if (event.dest.index == 0) {
                task.rank = 1;
            } else {
                var previousTask = destScope.modelValue[event.dest.index - 1];
                task.rank = previousTask.rank + 1;
            }
            task.state = destScope.taskState;
            if (destScope.story) {
                task.parentStory = {id: destScope.story.id};
                task.type = null;
            } else {
                task.type = destScope.taskType;
                task.parentStory = null;
            }
            TaskService.update(task).catch(function() {
                $scope.revertSortable(event);
            });
        },
        orderChanged: function(event) {
            var task = event.source.itemScope.modelValue;
            var destScope = event.dest.sortableScope;
            if (event.dest.index == 0) {
                task.rank = 1;
            } else {
                var previousTask = destScope.modelValue[event.dest.index - 1];
                if (event.dest.index > event.source.index) {
                    task.rank = previousTask.rank;
                } else {
                    task.rank = previousTask.rank + 1;
                }
            }
            TaskService.update(task).catch(function() {
                $scope.revertSortable(event);
            });
        },
        accept: function(sourceItemHandleScope, destSortableScope) {
            var sameSortable = sourceItemHandleScope.itemScope.sortableScope.sortableId === destSortableScope.sortableId;
            var isSortableDest = destSortableScope.story ? $scope.isSortableStory(destSortableScope.story) : true;
            return sameSortable && isSortableDest;
        }
    };
    $scope.selectableOptions = {
        notSelectableSelector: '.action, button, a, .story-container',
        allowMultiple: false,
        selectionUpdated: function(selectedIds) {
            switch (selectedIds.length) {
                case 0:
                    if (!_.isUndefined($state.params.taskId)) {
                        $state.go($scope.viewName);
                    }
                    break;
                case 1:
                    $state.go($scope.viewName + '.task.details' + ($state.params.taskTabId ? '.tab' : ''), {taskId: selectedIds});
                    break;
            }
        }
    };
    $scope.sprintFilters = [
        {id: 'allTasks', name: $scope.message('is.ui.sprintPlan.toolbar.filter.allTasks'), filter: {}},
        {id: 'myTasks', name: $scope.message('is.ui.sprintPlan.toolbar.filter.myTasks'), filter: {responsible: {id: Session.user.id}}},
        {id: 'freeTasks', name: $scope.message('is.ui.sprintPlan.toolbar.filter.freeTasks'), filter: {responsible: null}},
        {id: 'blockedTasks', name: $scope.message('is.ui.sprintPlan.toolbar.filter.blockedTasks'), filter: {blocked: true}}
    ];
    $scope.initSprintFilter();
    $scope.sortableId = 'taskBoard';
    $scope.sprint = sprint;
    $scope.tasksByTypeByState = {};
    $scope.tasksByTypeByStateAndSearchFiltered = {};
    $scope.tasksByStoryByState = {};
    $scope.taskCountByState = {};
    $scope.taskStatesByName = TaskStatesByName;
    $scope.sprintStatesByName = SprintStatesByName;
    $scope.taskTypesByName = TaskTypesByName;
    $scope.ghostStories = [];
    var refreshIfNotEqual = function(oldValue, newValue) {
        if (!_.isEqual(oldValue, newValue)) {
            $scope.refreshTasks();
        }
    };
    $scope.$watch('sprint.tasks', refreshIfNotEqual, true);
    $scope.$watchCollection('sprint.stories', refreshIfNotEqual);
    $scope.$watch('sprint.state', refreshIfNotEqual); // To generate the proper $scope.sprintTaskStates when changing state
    $scope.refreshTasks();
    $scope.$watch('application.search', $scope.applySearchFilterToTasksByTypeByState);
    $scope.sprintEntries = [];
    _.each(_.sortBy(releases, 'orderNumber'), function(release) {
        if (release.sprints && release.sprints.length > 0) {
            if ($scope.sprintEntries.length > 0) {
                $scope.sprintEntries.push({type: 'divider'});
            }
            $scope.sprintEntries.push({type: 'release', item: release});
            _.each(_.sortBy(release.sprints, 'orderNumber'), function(sprint) {
                $scope.sprintEntries.push({type: 'sprint', item: sprint})
            });
        }
    });
    $scope.tasksShownByTypeOrStory = {'stories': {}};
}]);
<commit_msg>Fix error when pushed planning of story with tasks in task board<commit_after>/*
 * Copyright (c) 2016 Kagilum SAS.
 *
 * This file is part of iceScrum.
 *
 * iceScrum 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.
 *
 * iceScrum is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with iceScrum.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *
 * Vincent Barrier (vbarrier@kagilum.com)
 * Nicolas Noullet (nnoullet@kagilum.com)
 * Colin Bontemps (cbontemps@kagilum.com)
 *
 */

extensibleController('taskBoardCtrl', ['$scope', '$state', '$filter', 'UserService', 'StoryService', 'TaskService', 'SprintService', 'Session', 'SprintStatesByName', 'StoryStatesByName', 'TaskStatesByName', 'TaskTypesByName', 'project', 'sprint', 'releases', function($scope, $state, $filter, UserService, StoryService, TaskService, SprintService, Session, SprintStatesByName, StoryStatesByName, TaskStatesByName, TaskTypesByName, project, sprint, releases) {
    $scope.viewName = 'taskBoard';
    // Functions
    $scope.isSelected = function(selectable) {
        if (selectable.class == "Story") {
            return $state.params.storyId ? $state.params.storyId == selectable.id : false;
        } else {
            return $state.params.taskId ? $state.params.taskId == selectable.id : false;
        }
    };
    $scope.hasSelected = function() {
        return $state.params.taskId != undefined;
    };
    $scope.isSortableTaskBoard = function(sprint) {
        return Session.authenticated() && sprint.state < SprintStatesByName.DONE;
    };
    $scope.isSortableStory = function(story) {
        return story.state < StoryStatesByName.DONE;
    };
    $scope.openSprintUrl = function(sprint, keepDetails) {
        var stateName = 'taskBoard';
        if (keepDetails && $state.current.name == 'taskBoard.details' || !keepDetails && $state.current.name != 'taskBoard.details') {
            stateName += '.details';
        }
        return $state.href(stateName, {sprintId: sprint.id});
    };
    $scope.openNewTaskByStory = function(story) {
        $state.go('taskBoard.task.new', {taskCategory: _.pick(story, ['id', 'name', 'class'])});
    };
    $scope.openNewTaskByType = function(type) {
        $state.go('taskBoard.task.new', {taskCategory: {id: type, name: $filter('i18n')(type, 'TaskTypes')}});
    };
    $scope.copyRecurrentTasks = function(sprint) {
        SprintService.copyRecurrentTasks(sprint, project);
    };
    $scope.applySearchFilterToTasksByTypeByState = function() {
        // Search filter must be applied to model because of https://github.com/a5hik/ng-sortable/issues/184
        $scope.tasksByTypeByStateAndSearchFiltered = _.mapValues($scope.tasksByTypeByState, function(tasksByState) {
            return _.mapValues(tasksByState, function(tasks) {
                return $filter('search')(tasks);
            })
        });
    };
    $scope.refreshTasks = function() {
        if (!$scope.sprint) {
            return;
        }
        var tasks;
        tasks = $scope.sprint.tasks;
        $scope.taskCountByState = _.countBy(tasks, 'state');
        $scope.taskCountByType = _.countBy(tasks, 'type');
        $scope.countByFilter();
        switch ($scope.sprint.state) {
            case SprintStatesByName.TODO:
                $scope.sprintTaskStates = [TaskStatesByName.TODO];
                break;
            case SprintStatesByName.IN_PROGRESS:
                $scope.sprintTaskStates = $scope.taskStates;
                break;
            case SprintStatesByName.DONE:
                $scope.sprintTaskStates = [TaskStatesByName.DONE];
                break;
        }
        var partitionedTasks = _.partition(tasks, function(task) {
            return task.parentStory == null;
        });
        var groupByStateAndSort = function(tasksDictionnary) {
            return _.mapValues(tasksDictionnary, function(tasks) {
                return _.mapValues(_.groupBy(tasks, 'state'), function(tasks) {
                    return _.sortBy(_.filter(tasks, $scope.currentSprintFilter.filter), 'rank');
                });
            });
        };
        $scope.tasksByTypeByState = groupByStateAndSort(_.groupBy(partitionedTasks[0], 'type'));
        $scope.tasksByStoryByState = groupByStateAndSort(_.groupBy(partitionedTasks[1], 'parentStory.id'));
        var sprintStoriesIds = _.map($scope.sprint.stories, 'id');
        var allStoriesIds = _.union(sprintStoriesIds, _.map(partitionedTasks[1], 'parentStory.id'));
        var ghostStoriesIds = _.difference(allStoriesIds, sprintStoriesIds);
        if (ghostStoriesIds) {
            StoryService.getMultiple(ghostStoriesIds, project.id).then(function(ghostStories) {
                $scope.ghostStories = ghostStories;
            });
        }
        var fillGapsInDictionnary = function(dictionnary, firstLevelKeys, secondLevelKeys) {
            _.each(firstLevelKeys, function(firstLevelKey) {
                if (!dictionnary[firstLevelKey]) {
                    dictionnary[firstLevelKey] = {};
                }
                _.each(secondLevelKeys, function(secondLevelKey) {
                    if (!dictionnary[firstLevelKey][secondLevelKey]) {
                        dictionnary[firstLevelKey][secondLevelKey] = [];
                    }
                });
            });
        };
        fillGapsInDictionnary($scope.tasksByTypeByState, $scope.taskTypes, $scope.sprintTaskStates);
        fillGapsInDictionnary($scope.tasksByStoryByState, allStoriesIds, $scope.sprintTaskStates);
        $scope.applySearchFilterToTasksByTypeByState();
    };
    $scope.changeSprintFilter = function(sprintFilter) {
        $scope.currentSprintFilter = sprintFilter;
        $scope.refreshTasks();
        var editableUser = angular.copy(Session.user);
        editableUser.preferences.filterTask = sprintFilter.id;
        UserService.update(editableUser).then(function() {
            Session.user.preferences.filterTask = sprintFilter.id;
        });
    };
    $scope.storyFilter = function(story) {
        return $scope.currentSprintFilter.id == 'allTasks' ||
               _.some($scope.tasksByStoryByState[story.id], function(tasks) {
                   return tasks.length > 0;
               });
    };
    $scope.openStoryUrl = function(storyId) {
        return '#/' + $scope.viewName + ($state.params.sprintId ? '/' + $state.params.sprintId : '') + '/story/' + storyId;
    };
    $scope.selectStory = function(event, storyId) {
        if (angular.element(event.target).closest('.action, button, a').length == 0) {
            $state.go('taskBoard.story.details' + ($state.params.storyTabId ? '.tab' : ''), {storyId: storyId});
        }
    };
    $scope.tasksShown = function(taskState, typeOrStory, fromStoryGhost) {
        var taskLimit = 5;
        if (taskState == TaskStatesByName.DONE && $scope.sprint.state < SprintStatesByName.DONE) {
            if (_.isObject(typeOrStory)) {
                var story = typeOrStory;
                if (story.state === StoryStatesByName.DONE || fromStoryGhost) {
                    return $scope.tasksShownByTypeOrStory.stories[story.id];
                } else {
                    return $scope.tasksByStoryByState[story.id][taskState].length < taskLimit || $scope.tasksShownByTypeOrStory.stories[story.id];
                }
            } else {
                var type = typeOrStory;
                return $scope.tasksByTypeByState[type][taskState].length < taskLimit || $scope.tasksShownByTypeOrStory[type];
            }
        } else {
            return true;
        }
    };
    $scope.tasksHidden = function(taskState, typeOrStory, fromStoryGhost) {
        var taskLimit = 5;
        if (taskState == TaskStatesByName.DONE && $scope.sprint.state < SprintStatesByName.DONE) {
            if (_.isObject(typeOrStory)) {
                var story = typeOrStory;
                if (story.state === StoryStatesByName.DONE || fromStoryGhost) {
                    return $scope.tasksShownByTypeOrStory.stories[story.id];
                } else {
                    return $scope.tasksByStoryByState[story.id][taskState].length >= taskLimit && $scope.tasksShownByTypeOrStory.stories[story.id];
                }
            } else {
                var type = typeOrStory;
                return $scope.tasksByTypeByState[type][taskState].length >= taskLimit && $scope.tasksShownByTypeOrStory[type];
            }
        } else {
            return false;
        }
    };
    $scope.showTasks = function(typeOrStory, show) {
        if (_.isObject(typeOrStory)) {
            $scope.tasksShownByTypeOrStory.stories[typeOrStory.id] = show;
        } else {
            $scope.tasksShownByTypeOrStory[typeOrStory] = show;
        }
    };
    $scope.sprintRemainingTime = function(sprint) {
        return _.sumBy(sprint.tasks, 'estimation');
    };
    $scope.scrollToActiveSprint = function(open) {
        if (open) {
            var dropdown = angular.element('.planning-dropdown');
            var ele = dropdown.find("li>a.active");
            var list = dropdown.find('.planning-menu');
            var posi = list.scrollTop() + ele.offset().top - ele.innerHeight();
            list.animate({
                scrollTop: posi - 60
            }, 200);
        }
    };
    $scope.initSprintFilter = function() {
        var sprintFilter = Session.authenticated() ? Session.user.preferences.filterTask : 'allTasks';
        var filter = _.find($scope.sprintFilters, {id: sprintFilter});
        $scope.currentSprintFilter = filter ? filter : _.find($scope.sprintFilters, {id: 'allTasks'});
    };
    $scope.countByFilter = function() {
        _.each($scope.sprintFilters, function(sprintFilter) {
            sprintFilter.count = _.filter($scope.sprint.tasks, sprintFilter.filter).length;
        });
    };
    // Init
    $scope.project = project;
    $scope.taskSortableOptions = {
        itemMoved: function(event) {
            var destScope = event.dest.sortableScope;
            var task = event.source.itemScope.modelValue;
            if (event.dest.index == 0) {
                task.rank = 1;
            } else {
                var previousTask = destScope.modelValue[event.dest.index - 1];
                task.rank = previousTask.rank + 1;
            }
            task.state = destScope.taskState;
            if (destScope.story) {
                task.parentStory = {id: destScope.story.id};
                task.type = null;
            } else {
                task.type = destScope.taskType;
                task.parentStory = null;
            }
            TaskService.update(task).catch(function() {
                $scope.revertSortable(event);
            });
        },
        orderChanged: function(event) {
            var task = event.source.itemScope.modelValue;
            var destScope = event.dest.sortableScope;
            if (event.dest.index == 0) {
                task.rank = 1;
            } else {
                var previousTask = destScope.modelValue[event.dest.index - 1];
                if (event.dest.index > event.source.index) {
                    task.rank = previousTask.rank;
                } else {
                    task.rank = previousTask.rank + 1;
                }
            }
            TaskService.update(task).catch(function() {
                $scope.revertSortable(event);
            });
        },
        accept: function(sourceItemHandleScope, destSortableScope) {
            var sameSortable = sourceItemHandleScope.itemScope.sortableScope.sortableId === destSortableScope.sortableId;
            var isSortableDest = destSortableScope.story ? $scope.isSortableStory(destSortableScope.story) : true;
            return sameSortable && isSortableDest;
        }
    };
    $scope.selectableOptions = {
        notSelectableSelector: '.action, button, a, .story-container',
        allowMultiple: false,
        selectionUpdated: function(selectedIds) {
            switch (selectedIds.length) {
                case 0:
                    if (!_.isUndefined($state.params.taskId)) {
                        $state.go($scope.viewName);
                    }
                    break;
                case 1:
                    $state.go($scope.viewName + '.task.details' + ($state.params.taskTabId ? '.tab' : ''), {taskId: selectedIds});
                    break;
            }
        }
    };
    $scope.sprintFilters = [
        {id: 'allTasks', name: $scope.message('is.ui.sprintPlan.toolbar.filter.allTasks'), filter: {}},
        {id: 'myTasks', name: $scope.message('is.ui.sprintPlan.toolbar.filter.myTasks'), filter: {responsible: {id: Session.user.id}}},
        {id: 'freeTasks', name: $scope.message('is.ui.sprintPlan.toolbar.filter.freeTasks'), filter: {responsible: null}},
        {id: 'blockedTasks', name: $scope.message('is.ui.sprintPlan.toolbar.filter.blockedTasks'), filter: {blocked: true}}
    ];
    $scope.initSprintFilter();
    $scope.sortableId = 'taskBoard';
    $scope.sprint = sprint;
    $scope.tasksByTypeByState = {};
    $scope.tasksByTypeByStateAndSearchFiltered = {};
    $scope.tasksByStoryByState = {};
    $scope.taskCountByState = {};
    $scope.taskStatesByName = TaskStatesByName;
    $scope.sprintStatesByName = SprintStatesByName;
    $scope.taskTypesByName = TaskTypesByName;
    $scope.ghostStories = [];
    var refreshIfNotEqual = function(oldValue, newValue) {
        if (!_.isEqual(oldValue, newValue)) {
            $scope.refreshTasks();
        }
    };
    $scope.$watch('sprint.tasks', refreshIfNotEqual, true);
    $scope.$watchCollection('sprint.stories', refreshIfNotEqual);
    $scope.$watch('sprint.state', refreshIfNotEqual); // To generate the proper $scope.sprintTaskStates when changing state
    $scope.refreshTasks();
    $scope.$watch('application.search', $scope.applySearchFilterToTasksByTypeByState);
    $scope.sprintEntries = [];
    _.each(_.sortBy(releases, 'orderNumber'), function(release) {
        if (release.sprints && release.sprints.length > 0) {
            if ($scope.sprintEntries.length > 0) {
                $scope.sprintEntries.push({type: 'divider'});
            }
            $scope.sprintEntries.push({type: 'release', item: release});
            _.each(_.sortBy(release.sprints, 'orderNumber'), function(sprint) {
                $scope.sprintEntries.push({type: 'sprint', item: sprint})
            });
        }
    });
    $scope.tasksShownByTypeOrStory = {'stories': {}};
}]);
<|endoftext|>


<commit_before>/* global beforeEach, availity, afterEach, expect, module, describe, it */
/**
 * Inspiration https://github.com/mgcrea/angular-strap/blob/v0.7.8/test/unit/directives/datepickerSpec.js
 */
describe('avDatepicker', function() {

  'use strict';

  beforeEach(function() {
    module('availity');
    module('availity.ui');
  });

  availity.mock.directiveSpecHelper();
  var $el;

  // jscs: disable
  var fixtures = {
    'default': '<input data-ng-model="selectedDate" name="date" type="text" data-av-datepicker>',
    'formatted-alt': '<input data-ng-model="selectedDate" name="date" type="text" data-av-datepicker data-format="\'dd-mm-yyyy\'">',
    'addon': '<input type="text" ng-model="selectedDate" data-av-datepicker> <button class="btn btn-default" type="button"></button>',
    'date-only': '<input data-ng-model="selectedDate" name="date" type="text" data-av-datepicker data-date-only="true">',
    'date-only-formatted': '<input data-ng-model="selectedDate" name="date" type="text" data-av-datepicker data-date-only="true" data-date-only-format="\'DD/MM/YYYY\'">'
  };
  // jscs: enable

  afterEach(function() {
    $el.data('datepicker').picker.remove();
  });

  it('should open on click', function() {
    availity.mock.$scope.selectedDate = null;
    $el = availity.mock.compileDirective(fixtures['default']);

    expect($el.data('datepicker').picker.is(':visible')).toBe(false);
    $el.focus().focus().click(); // Yes call focus twice for IE8
    expect($el.data('datepicker').picker.is(':visible')).toBe(true);
  });

  it('should correctly initialize date from MODEL', function() {
    availity.mock.$scope.selectedDate = new Date(1986, 0, 22);
    $el = availity.mock.compileDirective(fixtures['default']);

    expect($el.val()).toBe('01/22/1986');
  });

  it('should correctly initialize ISO 8601 date from MODEL', function() {
    availity.mock.$scope.selectedDate = '1986-01-22T06:00:00.000+0000';
    $el = availity.mock.compileDirective(fixtures['default']);

    expect($el.val()).toBe('01/22/1986');
  });

  it('should correctly ignore undefined date from MODEL', function() {
    availity.mock.$scope.selectedDate = undefined;
    $el = availity.mock.compileDirective(fixtures['default']);

    expect($el.val()).toBe('');
  });

  it('should correctly ignore null date from MODEL', function() {
    availity.mock.$scope.selectedDate = null;
    $el = availity.mock.compileDirective(fixtures['default']);

    expect($el.val()).toBe('');
  });

  it('should correctly ignore empty date from MODEL', function() {
    availity.mock.$scope.selectedDate = '';
    $el = availity.mock.compileDirective(fixtures['default']);

    expect($el.val()).toBe('');
  });

  it('should correctly parse formatted date from VIEW', function() {
    availity.mock.$scope.selectedDate = null;
    $el = availity.mock.compileDirective(fixtures['default']);

    var ngModel = $el.data('$ngModelController');
    ngModel.$setViewValue('01/20/1987');

    var date = availity.mock.$scope.selectedDate;

    expect(date instanceof Date).toBe(true);
    expect(date.getFullYear()).toBe(1987);
    expect(date.getMonth()).toBe(0);
    expect(date.getDate()).toBe(20);
  });

  it('should correctly parse ALTERNATE formatted date', function() {
    availity.mock.$scope.selectedDate = null;
    $el = availity.mock.compileDirective(fixtures['formatted-alt']);

    var ngModel = $el.data('$ngModelController');
    ngModel.$setViewValue('13-01-1978');

    var date = availity.mock.$scope.selectedDate;

    expect(date instanceof Date).toBe(true);
    expect(date.getFullYear()).toBe(1978);
    expect(date.getMonth()).toBe(0);
    expect(date.getDate()).toBe(13);
  });

  it('should correctly parse formatted date from VIEW with date only', function() {
    availity.mock.$scope.selectedDate = null;
    $el = availity.mock.compileDirective(fixtures['date-only']);

    var ngModel = $el.data('$ngModelController');
    ngModel.$setViewValue('01/20/1987');

    var date = availity.mock.$scope.selectedDate;

    expect(typeof date === 'string').toBe(true);
    expect(date).toBe('1987-01-20');
  });

  it('should correctly parse ALTERNATE formatted date with date only', function() {
    availity.mock.$scope.selectedDate = null;
    $el = availity.mock.compileDirective(fixtures['date-only-formatted']);

    var ngModel = $el.data('$ngModelController');
    ngModel.$setViewValue('01/20/1987');

    var date = availity.mock.$scope.selectedDate;

    expect(typeof date === 'string').toBe(true);
    expect(date).toBe('20/01/1987');
  });

  it('should not default to current date when input is invalid', function() {

    availity.mock.$scope.selectedDate = null;
    $el = availity.mock.compileDirective(fixtures['formatted-alt']);

    var ngModel = $el.data('$ngModelController');
    $el.focus().focus().click(); // Yes call focus twice for IE8
    ngModel.$setViewValue('apple');
    $el.blur().blur().click();
    var date = ngModel.$viewValue;
    expect(date).toBe('apple');
  });

});
<commit_msg>Cleaned up test names<commit_after>/* global beforeEach, availity, afterEach, expect, module, describe, it */
/**
 * Inspiration https://github.com/mgcrea/angular-strap/blob/v0.7.8/test/unit/directives/datepickerSpec.js
 */
describe('avDatepicker', function() {

  'use strict';

  beforeEach(function() {
    module('availity');
    module('availity.ui');
  });

  availity.mock.directiveSpecHelper();
  var $el;

  // jscs: disable
  var fixtures = {
    'default': '<input data-ng-model="selectedDate" name="date" type="text" data-av-datepicker>',
    'formatted-alt': '<input data-ng-model="selectedDate" name="date" type="text" data-av-datepicker data-format="\'dd-mm-yyyy\'">',
    'addon': '<input type="text" ng-model="selectedDate" data-av-datepicker> <button class="btn btn-default" type="button"></button>',
    'date-only': '<input data-ng-model="selectedDate" name="date" type="text" data-av-datepicker data-date-only="true">',
    'date-only-formatted': '<input data-ng-model="selectedDate" name="date" type="text" data-av-datepicker data-date-only="true" data-date-only-format="\'DD/MM/YYYY\'">'
  };
  // jscs: enable

  afterEach(function() {
    $el.data('datepicker').picker.remove();
  });

  it('should open on click', function() {
    availity.mock.$scope.selectedDate = null;
    $el = availity.mock.compileDirective(fixtures['default']);

    expect($el.data('datepicker').picker.is(':visible')).toBe(false);
    $el.focus().focus().click(); // Yes call focus twice for IE8
    expect($el.data('datepicker').picker.is(':visible')).toBe(true);
  });

  it('should correctly initialize date from MODEL', function() {
    availity.mock.$scope.selectedDate = new Date(1986, 0, 22);
    $el = availity.mock.compileDirective(fixtures['default']);

    expect($el.val()).toBe('01/22/1986');
  });

  it('should correctly initialize ISO 8601 date from MODEL', function() {
    availity.mock.$scope.selectedDate = '1986-01-22T06:00:00.000+0000';
    $el = availity.mock.compileDirective(fixtures['default']);

    expect($el.val()).toBe('01/22/1986');
  });

  it('should correctly ignore undefined date from MODEL', function() {
    availity.mock.$scope.selectedDate = undefined;
    $el = availity.mock.compileDirective(fixtures['default']);

    expect($el.val()).toBe('');
  });

  it('should correctly ignore null date from MODEL', function() {
    availity.mock.$scope.selectedDate = null;
    $el = availity.mock.compileDirective(fixtures['default']);

    expect($el.val()).toBe('');
  });

  it('should correctly ignore empty date from MODEL', function() {
    availity.mock.$scope.selectedDate = '';
    $el = availity.mock.compileDirective(fixtures['default']);

    expect($el.val()).toBe('');
  });

  it('should correctly write date-only values to the model', function() {
    availity.mock.$scope.selectedDate = null;
    $el = availity.mock.compileDirective(fixtures['default']);

    var ngModel = $el.data('$ngModelController');
    ngModel.$setViewValue('01/20/1987');

    var date = availity.mock.$scope.selectedDate;

    expect(date instanceof Date).toBe(true);
    expect(date.getFullYear()).toBe(1987);
    expect(date.getMonth()).toBe(0);
    expect(date.getDate()).toBe(20);
  });

  it('should correctly write date-only values to the model with optional formatting', function() {
    availity.mock.$scope.selectedDate = null;
    $el = availity.mock.compileDirective(fixtures['formatted-alt']);

    var ngModel = $el.data('$ngModelController');
    ngModel.$setViewValue('13-01-1978');

    var date = availity.mock.$scope.selectedDate;

    expect(date instanceof Date).toBe(true);
    expect(date.getFullYear()).toBe(1978);
    expect(date.getMonth()).toBe(0);
    expect(date.getDate()).toBe(13);
  });

  it('should correctly parse formatted date from VIEW with date only', function() {
    availity.mock.$scope.selectedDate = null;
    $el = availity.mock.compileDirective(fixtures['date-only']);

    var ngModel = $el.data('$ngModelController');
    ngModel.$setViewValue('01/20/1987');

    var date = availity.mock.$scope.selectedDate;

    expect(typeof date === 'string').toBe(true);
    expect(date).toBe('1987-01-20');
  });

  it('should correctly parse ALTERNATE formatted date with date only', function() {
    availity.mock.$scope.selectedDate = null;
    $el = availity.mock.compileDirective(fixtures['date-only-formatted']);

    var ngModel = $el.data('$ngModelController');
    ngModel.$setViewValue('01/20/1987');

    var date = availity.mock.$scope.selectedDate;

    expect(typeof date === 'string').toBe(true);
    expect(date).toBe('20/01/1987');
  });

  it('should not default to current date when input is invalid', function() {

    availity.mock.$scope.selectedDate = null;
    $el = availity.mock.compileDirective(fixtures['formatted-alt']);

    var ngModel = $el.data('$ngModelController');
    $el.focus().focus().click(); // Yes call focus twice for IE8
    ngModel.$setViewValue('apple');
    $el.blur().blur().click();
    var date = ngModel.$viewValue;
    expect(date).toBe('apple');
  });

});
<|endoftext|>


<commit_before>var Ascend = (function() {

	return func = function() {
		console.log(arguments[0]);

		if (!this.controller) {
			this.controller = new Leap.Controller({ enableGestures: true });
			this.controller.on('animationFrame', function(frame){
				if (frame.id%10 === 0) {
					if (frame.pointables.length) {
						// $(options.element).trigger('pointables', frame);
					} else {
						// $(options.element).trigger('pointablesout', frame);
					}
					if (frame.hands.length) {
						// $(options.element).trigger('hands', frame);
					} else {
						// $(options.element).trigger('handsout', frame);
					}
					if (frame.fingers.length) {
						// $(options.element).trigger('fingers', frame);
					} else {
						// $(options.element).trigger('fingersout', frame);
					}
					if (frame.tools.length) {
						console.log('Tool '+frame.tools[0].id+' Detected');
						// $(options.element).trigger('tools', frame);
					} else {
						// $(options.element).trigger('toolsout', frame);
					}
					if (frame.gestures.length > 0) {
						// $(options.element).trigger('gesture', frame);
						frame.gestures.forEach(function(gesture) {
							// $(options.element).trigger(gesture.type, gesture);
							// $(options.element).trigger(
							// 	gesture.type + gesture.state,
							// 	gesture
							// );
						});
					}
				}
			});

			//Lets monitor the default things for LeapJS
			this.controller.on('connect', function(){
				this.trigger('connect');
			})

			this.controller.connect();
		}

		function bind(eventType, listener) {
			if(!this._listeners) {
				 this._listeners = {};
			}
			if(!(eventType in this._listeners)) {
				this._listeners[eventType] = [];
			}
			var arr = this._listeners[eventType];
			if(arrIndexOf(arr, listener) === -1) {
				arr.push(listener);
			}
			return;
		};

		function unbind(eventType, listener) {
			if(!(this._listeners && (eventType in this._listeners))) {
				return;
			}
			var arr = this._listeners[eventType];
			var idx = arrIndexOf(arr, listener);
			if (idx !== -1) {
				if(arr.length > 1) {
					this._listeners[eventType] = arr.slice(0, idx).concat( arr.slice(idx+1) );
				} else {
					delete this._listeners[eventType];
				}
				return;
			}
			return;
		};

		function trigger(event) {
			var t = event.type;
			var args = Array.prototype.slice.call(arguments, 0);
			if (this['on'+t]) {
				this['on'+t].apply(this, args);
			}
			if (this._listeners && t in this._listeners) {
				for(var i=0; i < this._listeners[t].length; i++) {
					this._listeners[t][i].apply(this, args);
				}
			}
		};

		function arrIndexOf(arr, obj) {
			for(var i=0; i < arr.length; i++){
				if(arr[i] === obj){
					return i;
				}
			}
			return -1;
		}

		return {
			controller: this.controller,
			bind: bind,
			unbind: unbind,
			trigger: trigger,
			swipe: function(callback) {

			},
			punch: function() {

			}
		};
	}

})();<commit_msg>fixing namespacing<commit_after>var Ascend = (function() {

	return func = function() {
		console.log(arguments[0]);

		if (!this.controller) {
			this.controller = new Leap.Controller({ enableGestures: true });
			this.controller.on('animationFrame', function(frame){
				if (frame.id%10 === 0) {
					if (frame.pointables.length) {
						// $(options.element).trigger('pointables', frame);
					} else {
						// $(options.element).trigger('pointablesout', frame);
					}
					if (frame.hands.length) {
						// $(options.element).trigger('hands', frame);
					} else {
						// $(options.element).trigger('handsout', frame);
					}
					if (frame.fingers.length) {
						// $(options.element).trigger('fingers', frame);
					} else {
						// $(options.element).trigger('fingersout', frame);
					}
					if (frame.tools.length) {
						console.log('Tool '+frame.tools[0].id+' Detected');
						// $(options.element).trigger('tools', frame);
					} else {
						// $(options.element).trigger('toolsout', frame);
					}
					if (frame.gestures.length > 0) {
						// $(options.element).trigger('gesture', frame);
						frame.gestures.forEach(function(gesture) {
							// $(options.element).trigger(gesture.type, gesture);
							// $(options.element).trigger(
							// 	gesture.type + gesture.state,
							// 	gesture
							// );
						});
					}
				}
			});

			//Lets monitor the default things for LeapJS
			this.controller.on('connect', function(){
				trigger('connect');
			})

			this.controller.connect();
		}

		function bind(eventType, listener) {
			if(!this._listeners) {
				 this._listeners = {};
			}
			if(!(eventType in this._listeners)) {
				this._listeners[eventType] = [];
			}
			var arr = this._listeners[eventType];
			if(arrIndexOf(arr, listener) === -1) {
				arr.push(listener);
			}
			return;
		};

		function unbind(eventType, listener) {
			if(!(this._listeners && (eventType in this._listeners))) {
				return;
			}
			var arr = this._listeners[eventType];
			var idx = arrIndexOf(arr, listener);
			if (idx !== -1) {
				if(arr.length > 1) {
					this._listeners[eventType] = arr.slice(0, idx).concat( arr.slice(idx+1) );
				} else {
					delete this._listeners[eventType];
				}
				return;
			}
			return;
		};

		function trigger(event) {
			var t = event.type;
			var args = Array.prototype.slice.call(arguments, 0);
			if (this['on'+t]) {
				this['on'+t].apply(this, args);
			}
			if (this._listeners && t in this._listeners) {
				for(var i=0; i < this._listeners[t].length; i++) {
					this._listeners[t][i].apply(this, args);
				}
			}
		};

		function arrIndexOf(arr, obj) {
			for(var i=0; i < arr.length; i++){
				if(arr[i] === obj){
					return i;
				}
			}
			return -1;
		}

		return {
			controller: this.controller,
			bind: bind,
			unbind: unbind,
			trigger: trigger,
			swipe: function(callback) {

			},
			punch: function() {

			}
		};
	}

})();<|endoftext|>


<commit_before>const packageJson = require('../package.json');
const electronBuilder = require('electron-builder');
const path = require('path');
const rimraf = require('rimraf');
const fs = require('fs');
const buildTask = require('./build');

const PLATFORM_MAP = {
  darwin: 'mac',
  linux: 'linux',
  win32: 'win',
};

// Start package if ran from CLI
if (require.main === module) {
  process.nextTick(async () => {
    try {
      await buildTask.start();
      await module.exports.start();
    } catch (err) {
      console.log('[package] ERROR:', err);
      process.exit(1);
    }
  });
}

module.exports.start = async function() {
  console.log('[package] Removing existing directories');

  if (process.env.KEEP_DIST_FOLDER !== 'yes') {
    await emptyDir('../dist/*');
  }

  console.log('[package] Packaging app');
  await pkg('../.electronbuilder');

  console.log('[package] Complete!');
};

async function pkg(relConfigPath) {
  const configPath = path.resolve(__dirname, relConfigPath);

  // Replace some things
  const rawConfig = fs
    .readFileSync(configPath, 'utf8')
    .replace('__APP_ID__', packageJson.app.appId)
    .replace('__ICON_URL__', packageJson.app.icon)
    .replace('__EXECUTABLE_NAME__', packageJson.app.executableName)
    .replace('__SYNOPSIS__', packageJson.app.synopsis);

  // console.log(`[package] Using electron-builder config\n${rawConfig}`);

  const config = JSON.parse(rawConfig);
  const targetPlatform = PLATFORM_MAP[process.platform];

  const target = process.env.BUILD_TARGETS
    ? process.env.BUILD_TARGETS.split(',')
    : config[targetPlatform].target;

  return electronBuilder.build({
    config,
    [targetPlatform]: target,
  });
}

async function emptyDir(relPath) {
  return new Promise((resolve, reject) => {
    const dir = path.resolve(__dirname, relPath);
    rimraf(dir, err => {
      if (err) {
        reject(err);
      } else {
        resolve();
      }
    });
  });
}
<commit_msg>Hack publish parameter for snap<commit_after>const packageJson = require('../package.json');
const electronBuilder = require('electron-builder');
const path = require('path');
const rimraf = require('rimraf');
const fs = require('fs');
const buildTask = require('./build');

const PLATFORM_MAP = {
  darwin: 'mac',
  linux: 'linux',
  win32: 'win',
};

// Start package if ran from CLI
if (require.main === module) {
  process.nextTick(async () => {
    try {
      await buildTask.start();
      await module.exports.start();
    } catch (err) {
      console.log('[package] ERROR:', err);
      process.exit(1);
    }
  });
}

module.exports.start = async function() {
  console.log('[package] Removing existing directories');

  if (process.env.KEEP_DIST_FOLDER !== 'yes') {
    await emptyDir('../dist/*');
  }

  console.log('[package] Packaging app');
  await pkg('../.electronbuilder');

  console.log('[package] Complete!');
};

async function pkg(relConfigPath) {
  const configPath = path.resolve(__dirname, relConfigPath);

  // Replace some things
  const rawConfig = fs
    .readFileSync(configPath, 'utf8')
    .replace('__APP_ID__', packageJson.app.appId)
    .replace('__ICON_URL__', packageJson.app.icon)
    .replace('__EXECUTABLE_NAME__', packageJson.app.executableName)
    .replace('__SYNOPSIS__', packageJson.app.synopsis);

  // console.log(`[package] Using electron-builder config\n${rawConfig}`);

  const config = JSON.parse(rawConfig);
  const targetPlatform = PLATFORM_MAP[process.platform];

  const target = process.env.BUILD_TARGETS
    ? process.env.BUILD_TARGETS.split(',')
    : config[targetPlatform].target;

  // NOTE: This is likely a bug in electron-builder. Always tries to
  //   publish snap even when set to null.
  if (target.length === 0 && target[0] === 'snap') {
    config.publish = 'never';
  }

  return electronBuilder.build({
    config,
    [targetPlatform]: target,
  });
}

async function emptyDir(relPath) {
  return new Promise((resolve, reject) => {
    const dir = path.resolve(__dirname, relPath);
    rimraf(dir, err => {
      if (err) {
        reject(err);
      } else {
        resolve();
      }
    });
  });
}
<|endoftext|>


<commit_before>define(function () {
  // Lower Sorbian
  var charsWords = ['znamuško', 'znamušce', 'znamuška','znamuškow'];
  var itemsWords = ['zapisk', 'zapiska', 'zapiski','zapiskow'];

  var pluralWord = function pluralWord(numberOfChars, words) {
    if (numberOfChars === 1) {
        return words[0];
    } else if (numberOfChars === 2) {
      return words[1];
    }  else if (numberOfChars > 2 && numberOfChars <= 4) {
      return words[2];
    } else if (numberOfChars >= 5) {
      return words[3];
    }
  };

  return {
    errorLoading: function () {
      return 'Wuslědki njejsu se dali zacytaś.';
    },
    inputTooLong: function (args) {
      var overChars = args.input.length - args.maximum;

      return 'Pšosym lašuj ' + overChars + ' ' + pluralWord(overChars, charsWords);
    },
    inputTooShort: function (args) {
      var remainingChars = args.minimum - args.input.length;

      return 'Pšosym zapódaj nanejmjenjej ' + remainingChars + ' ' +
        pluralWord(remainingChars, charsWords);
    },
    loadingMore: function () {
      return 'Dalšne wuslědki se zacytaju…';
    },
    maximumSelected: function (args) {
      return 'Móžoš jano ' + args.maximum + ' ' +
        pluralWord(args.maximum, itemsWords) + 'wubraś.';
    },
    noResults: function () {
      return 'Žedne wuslědki namakane';
    },
    searching: function () {
      return 'Pyta se…';
    }
  };
});
<commit_msg>Delete dsb.js<commit_after><|endoftext|>


<commit_before>/* See license.txt for terms of usage */
FBL.ns( function()
{
    with (FBL)
    {
        Firebug.ShortcutsModel = extend(Firebug.Module, {

            initializeUI: function()
            {
                this.initShortcuts();
            },

            initShortcuts : function() {
                var branch = prefs.getBranch("extensions.firebug.key.shortcut.");
                var shortcutNames = branch.getChildList("", {});
                shortcutNames.forEach(this.initShortcut);
            },

            initShortcut : function(element, index, array) {
                var branch = prefs.getBranch("extensions.firebug.key.");
                var shortcut = branch.getCharPref("shortcut." + element);
                var tokens = shortcut.split(' ');
                var key = tokens.pop();
                var modifiers = tokens.join(',')
                var keyElem = document.getElementById("key_" + element);
                if (!keyElem)
                {
                    //if key is not defined in xul, add it
                    keyElem = document.createElement('key');
                    keyElem.className = "fbOnlyKey";
                    keyElem.id = "key_" + element;
                    keyElem.command = "cmd_" + element;
                    $('mainKeyset').appendChild(keyElem);
                }

                //choose between key or keycode attribute
                if (key.length == 1)
                {
                    keyElem.setAttribute('modifiers', modifiers);
                    keyElem.setAttribute('key', key);
                    keyElem.removeAttribute('keycode');
                }
                else if (KeyEvent['DOM_' + key]) //only set valid keycodes
                {
                    keyElem.setAttribute('modifiers', modifiers);
                    keyElem.setAttribute('keycode', key);
                    keyElem.removeAttribute('key'); //in case default shortcut uses key rather than keycode
                }
            }
        });
        Firebug.registerModule(Firebug.ShortcutsModel);
    }
});<commit_msg>add dispatchName for tracing<commit_after>/* See license.txt for terms of usage */
FBL.ns( function()
{
    with (FBL)
    {
        Firebug.ShortcutsModel = extend(Firebug.Module, {

            dispatchName: "shortcuts",

            initializeUI: function()
            {
                this.initShortcuts();
            },

            initShortcuts : function() {
                var branch = prefs.getBranch("extensions.firebug.key.shortcut.");
                var shortcutNames = branch.getChildList("", {});
                shortcutNames.forEach(this.initShortcut);
            },

            initShortcut : function(element, index, array) {
                var branch = prefs.getBranch("extensions.firebug.key.");
                var shortcut = branch.getCharPref("shortcut." + element);
                var tokens = shortcut.split(' ');
                var key = tokens.pop();
                var modifiers = tokens.join(',')
                var keyElem = document.getElementById("key_" + element);
                if (!keyElem)
                {
                    //if key is not defined in xul, add it
                    keyElem = document.createElement('key');
                    keyElem.className = "fbOnlyKey";
                    keyElem.id = "key_" + element;
                    keyElem.command = "cmd_" + element;
                    $('mainKeyset').appendChild(keyElem);
                }

                //choose between key or keycode attribute
                if (key.length == 1)
                {
                    keyElem.setAttribute('modifiers', modifiers);
                    keyElem.setAttribute('key', key);
                    keyElem.removeAttribute('keycode');
                }
                else if (KeyEvent['DOM_' + key]) //only set valid keycodes
                {
                    keyElem.setAttribute('modifiers', modifiers);
                    keyElem.setAttribute('keycode', key);
                    keyElem.removeAttribute('key'); //in case default shortcut uses key rather than keycode
                }
            }
        });
        Firebug.registerModule(Firebug.ShortcutsModel);
    }
});<|endoftext|>


<commit_before>/*
 *  Init code for legacy compatibility.
 *
 *  Compatibility properties / wrapper functions here allow Duktape to remain
 *  compatible for user code when core features are changed, without burdening
 *  the main C code with compatibility stuff.
 */

(function(D) {
    function def(name, value) {
        Object.defineProperty(D, name, {
            value: value,
            writable: true,
            enumerable: false,
            configurable: true
        });
    }
    def('build', '');  // removed in Duktape 0.9.0
})(Duktape);
<commit_msg>add legacy setFinalizer/getFinalizer values for now<commit_after>/*
 *  Init code for legacy compatibility.
 *
 *  Compatibility properties / wrapper functions here allow Duktape to remain
 *  compatible for user code when core features are changed, without burdening
 *  the main C code with compatibility stuff.
 */

(function(D) {
    function def(name, value) {
        Object.defineProperty(D, name, {
            value: value,
            writable: true,
            enumerable: false,
            configurable: true
        });
    }
    def('build', '');                 // removed in Duktape 0.9.0
    def('setFinalizer', D.setFin);    // renamed in Duktape 0.9.0
    def('getFinalizer', D.getFin);    // renamed in Duktape 0.9.0
})(Duktape);
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import {
  View
} from 'react-native';
import {
  Surface,
  Shape,
  Path
} from 'ReactNativeART';

export class DynamicButton extends Component {
  render() {
    const width = this.props.style.width;
    const height = this.props.style.height;
    const padding = this.props.padding;
    const d = Path()
    .moveTo(width / 3 - padding, padding)
    .lineTo(width - padding, height / 2)
    .lineTo(width / 3 - padding, height - padding)
    .close();
    return (
      <View>
        <Surface width={width} height={height}>
          <Shape stroke={this.props.strokeColor} strokeWidth={this.props.strokeWidth} d = {d} />
        </Surface>
      </View>
    );
  }
}

DynamicButton.propTypes = {
  strokeColor: PropTypes.string,
  strokeWidth: PropTypes.number,
  padding: PropTypes.number,
};

DynamicButton.defaultProps = {
  strokeColor: '#9FABFF',
  strokeWidth: 8,
  padding: 40,
};<commit_msg>Add Style enum<commit_after>import React, { Component, PropTypes } from 'react';
import {
  View
} from 'react-native';
import {
  Surface,
  Shape,
  Path
} from 'ReactNativeART';

export DynamicButtonType = {
	'Play': 'play',
	'Pause': 'pause',
	'Stop': 'stop',
};

export class DynamicButton extends Component {

  currentPath() {
	const width = this.props.style.width;
    const height = this.props.style.height;
    const padding = this.props.padding;
    const type = this.props.type;
    if (type == DynamicButtonType.Play) {
	  const d = Path()
		.moveTo(width / 3 - padding, padding)
		.lineTo(width - padding, height / 2)
		.lineTo(width / 3 - padding, height - padding)
		.close();
	  return d;
	} else if (type == DynamicButtonType.Pause) {
	  const d = Path()
		.moveTo(width / 3 - padding, padding)
		.lineTo(width - padding, height / 2)
		.lineTo(width / 3 - padding, height - padding)
		.close();
	  return d;
	}
  }

  render() {
    return (
      <View>
        <Surface width={width} height={height}>
          <Shape stroke={this.props.strokeColor} strokeWidth={this.props.strokeWidth} d = {this.state.d} />
        </Surface>
      </View>
    );
  }
}

DynamicButton.propTypes = {
  strokeColor: PropTypes.string,
  strokeWidth: PropTypes.number,
  padding: PropTypes.number,
  type: PropTypes.oneOf([DynamicButtonType.Play, DynamicButtonType.Pause, DynamicButtonType.Stop]),
};

DynamicButton.defaultProps = {
  strokeColor: '#9FABFF',
  strokeWidth: 8,
  padding: 40,
  type: {DynamicButtonType.Play},
};<|endoftext|>


<commit_before>prettyPrint();

// sidebar navigation
$(function() {
  var loc = window.location.href; // returns the full URL
  if(/overview/.test(loc)) {
    $('.overview-nav').addClass('active');
  }
  else if(/code_index/.test(loc)) {
    $('.code-index-nav').addClass('active');
  }
  else if(/smells_index/.test(loc)) {
    $('.smells-index-nav').addClass('active');
  }
});

var turbulenceData = turbulenceData || [];
var COLOR = {
  'A' : '#00B50E',
  'B': '#53D700',
  'C': '#FDF400',
  'D': '#FF6C00',
  'F': '#C40009'
};
$("#churn-vs-complexity-graph-container").highcharts({
  chart: {
    type: "scatter",
    zoomType: "xy"
  },
  title: {
    text: "Churn vs Complexity"
  },
  xAxis: {
    title: {
      enabled: true,
      text: "Churn"
    },
    floor: 0,
    startOnTick: true,
    endOnTick: true
  },
  yAxis: {
    title: {
      text: "Complexity"
    },
    floor: 0,
    startOnTick: true,
    endOnTick: true
  },
  plotOptions: {
    series: {
      turboThreshold: 1500
    },
    scatter: {
      marker: {
        radius: 5,
        states: {
          hover: {
            enabled: true,
            lineColor: "rgb(100,100,100)"
          }
        }
      },
      tooltip: {
        headerFormat: "{point.key}
",
        pointFormat: "Committed {point.x} times, with Flog score of {point.y}"
      }
    }
  },
  series: [{
    showInLegend: false,
    color: "steelblue",
    data: getMappedTurbulenceData()
  }]
});

function getMappedTurbulenceData(){
  var dataWithColorInformation = turbulenceData.map(function(data){
    data.color = COLOR[data.rating];
    return data;
  });
  return dataWithColorInformation;
};

$(function() {
  $("#gpa-chart").highcharts(
    {
      chart: {
        type: 'pie',
        events: {
            load: addTitle,
            redraw: addTitle,
        },
      },
      title: {
        text: "",
        useHTML: true
      },
      plotOptions: {
        pie: {
          shadow: false
        }
      },
      tooltip: {
        formatter: function() {
          return ''+ this.point.name +': '+ this.y +' %';
        }
      },
      series: [{
        name: 'Browsers',
        data: getGpaData(),
        size: '90%',
        innerSize: '65%',
        showInLegend:true,
        dataLabels: {
          enabled: false
        }
      }]
    });
});

function addTitle() {
    if (this.title) {
        this.title.destroy();
    }
    var r = this.renderer,
        x = this.series[0].center[0] + this.plotLeft,
        y = this.series[0].center[1] + this.plotTop;
    this.title = r.label(''+score.toFixed(2)+'/100', 0, 0, "", 0, 0, true)
        .css({
        color: 'black'
    }).hide().add();
    var bbox = this.title.getBBox();
    this.title.attr({
        x: x - (bbox.width / 2),
        y: y
    }).show();
    this.title.useHTML = true;
};

function getGpaData(){
  var ratingACount = getRatingWiseCount("A");
  var ratingBCount = getRatingWiseCount("B");
  var ratingCCount = getRatingWiseCount("C");
  var ratingDCount = getRatingWiseCount("D");
  var ratingFCount = getRatingWiseCount("F");
  var total = ratingACount + ratingBCount + ratingCCount + ratingDCount + ratingFCount;
  return [
    {name: 'A', y: parseFloat(calculatePercentage(ratingACount, total).toFixed(2)), color: COLOR['A']},
    {name: 'B', y: parseFloat(calculatePercentage(ratingBCount, total).toFixed(2)), color: COLOR['B']},
    {name: 'C', y: parseFloat(calculatePercentage(ratingCCount, total).toFixed(2)), color: COLOR['C']},
    {name: 'D', y: parseFloat(calculatePercentage(ratingDCount, total).toFixed(2)), color: COLOR['D']},
    {name: 'F', y: parseFloat(calculatePercentage(ratingFCount, total).toFixed(2)), color: COLOR['F']},
  ];
};

function calculatePercentage(gradeCount, total){
  return (gradeCount/total)*100;
};

function getRatingWiseCount(rating){
  var count = 0;
  turbulenceData.forEach(function(data, index){
    if(data.rating === rating){
      count++;
    }
  });
  return count;
};

function emphasizeLineFromFragment() {
  emphasizeLine(window.location.hash)
}

$(".js-file-code").on("click", ".js-smell-location", emphasizeLineFromHref);

function emphasizeLineFromHref(event) {
  if (hrefTargetIsOnCurrentPage(this) && !event.ctrlKey) {
    $(".js-file-code li").removeClass("highlight");
    var lineId = "#" + this.href.split("#")[1];
    emphasizeLine(lineId);
    return false;
  }
}

function hrefTargetIsOnCurrentPage(aTag) {
  return (window.location.pathname === aTag.pathname);
}

function emphasizeLine(lineReference) {
  scrollToTarget(lineReference);
  highlightLine(lineReference);
}

function scrollToTarget(lineReference) {
  window.location.hash = lineReference;
  $.scrollTo(lineReference, {
    duration: 300,
    easing: "linear",
    offset: {top: -87},
    axis: 'y'
  });
}

function highlightLine(lineReference) {
  $(lineReference).addClass("highlight");
}

$("#toggle-code").on("click", showCode);
$("#toggle-smells").on("click", showSmells);

function showCode() {
  $('#toggle-code').parent('li').addClass('active');
  $('#toggle-smells').parent('li').removeClass('active');
  $(".smells").hide();
}

function showSmells() {
  $('#toggle-code').parent('li').removeClass('active');
  $('#toggle-smells').parent('li').addClass('active');
  $(".smells").show();
}

$("#codeTable")
  .tablesorter({          // Sort the table
    sortList: [[0,1]]
  });

$("#js-index-table")
  .tablesorter({          // Sort the table
    sortList: [[0,0]]
  });

$(".js-timeago").timeago();

$(function(){
  $('.table-header').click(function(){
    $('.table-header').not(this).each(function(){
      $(this).removeClass('active');
      $(this).find('.sort-type').removeClass('table-header-asc');
      $(this).find('.sort-type').removeClass('table-header-desc');
    });
    if($(this).hasClass('active')){
      $(this).find('.sort-type').toggleClass('table-header-asc table-header-desc');
    }
    else{
      $(this).addClass('active');
      $(this).find('.sort-type').addClass('table-header-asc');
    }
  });
});

function assignIdsToCodeLines(){
  $($('.linenums')[1]).children().each(function(index){
    $(this).attr('id', "L" + index)
  });
};

$(document).ready(function(){
  assignIdsToCodeLines();
  emphasizeLineFromFragment();
  initTableFilters();
});

var initTableFilters = function() {
  $("#codeTable").filterTable({ignoreColumns: [2], placeholder: 'Filter by Name'});
  $("#js-index-table").filterTable({ignoreColumns: [2, 3, 4, 5], placeholder: 'Filter by Smell or Location', inputSelector: 'form-control'});
}
<commit_msg>Updating the threshold to 0<commit_after>prettyPrint();

// sidebar navigation
$(function() {
  var loc = window.location.href; // returns the full URL
  if(/overview/.test(loc)) {
    $('.overview-nav').addClass('active');
  }
  else if(/code_index/.test(loc)) {
    $('.code-index-nav').addClass('active');
  }
  else if(/smells_index/.test(loc)) {
    $('.smells-index-nav').addClass('active');
  }
});

var turbulenceData = turbulenceData || [];
var COLOR = {
  'A' : '#00B50E',
  'B': '#53D700',
  'C': '#FDF400',
  'D': '#FF6C00',
  'F': '#C40009'
};
$("#churn-vs-complexity-graph-container").highcharts({
  chart: {
    type: "scatter",
    zoomType: "xy"
  },
  title: {
    text: "Churn vs Complexity"
  },
  xAxis: {
    title: {
      enabled: true,
      text: "Churn"
    },
    floor: 0,
    startOnTick: true,
    endOnTick: true
  },
  yAxis: {
    title: {
      text: "Complexity"
    },
    floor: 0,
    startOnTick: true,
    endOnTick: true
  },
  plotOptions: {
    series: {
      turboThreshold: 0
    },
    scatter: {
      marker: {
        radius: 5,
        states: {
          hover: {
            enabled: true,
            lineColor: "rgb(100,100,100)"
          }
        }
      },
      tooltip: {
        headerFormat: "{point.key}
",
        pointFormat: "Committed {point.x} times, with Flog score of {point.y}"
      }
    }
  },
  series: [{
    showInLegend: false,
    color: "steelblue",
    data: getMappedTurbulenceData()
  }]
});

function getMappedTurbulenceData(){
  var dataWithColorInformation = turbulenceData.map(function(data){
    data.color = COLOR[data.rating];
    return data;
  });
  return dataWithColorInformation;
};

$(function() {
  $("#gpa-chart").highcharts(
    {
      chart: {
        type: 'pie',
        events: {
            load: addTitle,
            redraw: addTitle,
        },
      },
      title: {
        text: "",
        useHTML: true
      },
      plotOptions: {
        pie: {
          shadow: false
        }
      },
      tooltip: {
        formatter: function() {
          return ''+ this.point.name +': '+ this.y +' %';
        }
      },
      series: [{
        name: 'Browsers',
        data: getGpaData(),
        size: '90%',
        innerSize: '65%',
        showInLegend:true,
        dataLabels: {
          enabled: false
        }
      }]
    });
});

function addTitle() {
    if (this.title) {
        this.title.destroy();
    }
    var r = this.renderer,
        x = this.series[0].center[0] + this.plotLeft,
        y = this.series[0].center[1] + this.plotTop;
    this.title = r.label(''+score.toFixed(2)+'/100', 0, 0, "", 0, 0, true)
        .css({
        color: 'black'
    }).hide().add();
    var bbox = this.title.getBBox();
    this.title.attr({
        x: x - (bbox.width / 2),
        y: y
    }).show();
    this.title.useHTML = true;
};

function getGpaData(){
  var ratingACount = getRatingWiseCount("A");
  var ratingBCount = getRatingWiseCount("B");
  var ratingCCount = getRatingWiseCount("C");
  var ratingDCount = getRatingWiseCount("D");
  var ratingFCount = getRatingWiseCount("F");
  var total = ratingACount + ratingBCount + ratingCCount + ratingDCount + ratingFCount;
  return [
    {name: 'A', y: parseFloat(calculatePercentage(ratingACount, total).toFixed(2)), color: COLOR['A']},
    {name: 'B', y: parseFloat(calculatePercentage(ratingBCount, total).toFixed(2)), color: COLOR['B']},
    {name: 'C', y: parseFloat(calculatePercentage(ratingCCount, total).toFixed(2)), color: COLOR['C']},
    {name: 'D', y: parseFloat(calculatePercentage(ratingDCount, total).toFixed(2)), color: COLOR['D']},
    {name: 'F', y: parseFloat(calculatePercentage(ratingFCount, total).toFixed(2)), color: COLOR['F']},
  ];
};

function calculatePercentage(gradeCount, total){
  return (gradeCount/total)*100;
};

function getRatingWiseCount(rating){
  var count = 0;
  turbulenceData.forEach(function(data, index){
    if(data.rating === rating){
      count++;
    }
  });
  return count;
};

function emphasizeLineFromFragment() {
  emphasizeLine(window.location.hash)
}

$(".js-file-code").on("click", ".js-smell-location", emphasizeLineFromHref);

function emphasizeLineFromHref(event) {
  if (hrefTargetIsOnCurrentPage(this) && !event.ctrlKey) {
    $(".js-file-code li").removeClass("highlight");
    var lineId = "#" + this.href.split("#")[1];
    emphasizeLine(lineId);
    return false;
  }
}

function hrefTargetIsOnCurrentPage(aTag) {
  return (window.location.pathname === aTag.pathname);
}

function emphasizeLine(lineReference) {
  scrollToTarget(lineReference);
  highlightLine(lineReference);
}

function scrollToTarget(lineReference) {
  window.location.hash = lineReference;
  $.scrollTo(lineReference, {
    duration: 300,
    easing: "linear",
    offset: {top: -87},
    axis: 'y'
  });
}

function highlightLine(lineReference) {
  $(lineReference).addClass("highlight");
}

$("#toggle-code").on("click", showCode);
$("#toggle-smells").on("click", showSmells);

function showCode() {
  $('#toggle-code').parent('li').addClass('active');
  $('#toggle-smells').parent('li').removeClass('active');
  $(".smells").hide();
}

function showSmells() {
  $('#toggle-code').parent('li').removeClass('active');
  $('#toggle-smells').parent('li').addClass('active');
  $(".smells").show();
}

$("#codeTable")
  .tablesorter({          // Sort the table
    sortList: [[0,1]]
  });

$("#js-index-table")
  .tablesorter({          // Sort the table
    sortList: [[0,0]]
  });

$(".js-timeago").timeago();

$(function(){
  $('.table-header').click(function(){
    $('.table-header').not(this).each(function(){
      $(this).removeClass('active');
      $(this).find('.sort-type').removeClass('table-header-asc');
      $(this).find('.sort-type').removeClass('table-header-desc');
    });
    if($(this).hasClass('active')){
      $(this).find('.sort-type').toggleClass('table-header-asc table-header-desc');
    }
    else{
      $(this).addClass('active');
      $(this).find('.sort-type').addClass('table-header-asc');
    }
  });
});

function assignIdsToCodeLines(){
  $($('.linenums')[1]).children().each(function(index){
    $(this).attr('id', "L" + index)
  });
};

$(document).ready(function(){
  assignIdsToCodeLines();
  emphasizeLineFromFragment();
  initTableFilters();
});

var initTableFilters = function() {
  $("#codeTable").filterTable({ignoreColumns: [2], placeholder: 'Filter by Name'});
  $("#js-index-table").filterTable({ignoreColumns: [2, 3, 4, 5], placeholder: 'Filter by Smell or Location', inputSelector: 'form-control'});
}
<|endoftext|>


<commit_before>var p = require('path')
  , logger = require('ezseed-logger')()
  , fs = require('fs')
  , i18n = require('i18n')
  , config = require('../config/config-sample')
  , config_path = p.join(p.resolve(__dirname, '../config'), 'config.js')
  , helper = require('./helpers/promise')

module.exports = function(opts) {
  if(opts.new) {
    require('./helpers/ascii').print()
    console.log('Welcome to ezseed!')
  }

  //ask configuration questions
  require('./inquirer/lang')()
  .then(function(lang) {

    i18n.setLocale(lang)

    return helper.condition(!opts.skipconfig, require('./inquirer/config'))

  })
  .then(function(answers) {

    var server

    if(answers) {
      for(var answer in answers) {
        config[answer] = answers[answer]
      }

      server = '127.0.0.1:'+answers.port
    }

    return helper.condition(!opts.skipserver, require('./commands/install').server(server))
  })
  .catch(helper.exit(i18n.__('Server installation')))

  //ask client questions
  .then(function() {
    return helper.condition(!opts.skipclient, require('./inquirer/client'))
  })
  .then(function(client) {
    //if opts.skipclient
    if(client === undefined || opts.skipclient)
      client = {install_client: false}

    return helper.condition(client.install_client, require('./commands/install').client(client.client))
  })
  .catch(helper.exit(i18n.__('Client installation')))

  //Write configuration
  .then(function() {

    if(!opts.skipconfig) {

      if(fs.existsSync(config_path)) {
        if(!opts.force) {
          logger.warn(i18n.__('%s already exists - use force to replace, skipping', config_path))
          return helper.next()
        } else {
          logger.warn(i18n.__('Overriding %s', config_path))
        }
      }

      fs.writeFileSync(config_path, 'module.exports = '+JSON.stringify(config, undefined, 2), {mode: 775})
      logger.info(i18n.__('Configuration saved in %s', config_path))

    }

    return helper.next()
  })
  //Write pm2 json configuration
  .then(function() {

    if(!opts.skipconfig) {
      var root = p.resolve(__dirname, '../')

      var json = {
        apps: [{
          name: 'ezseed',
          script: p.join(root, 'server.js'),
          out_file: '/usr/local/opt/ezseed/logs/ezseed-out.log',
          error_file: '/usr/local/opt/ezseed/logs/ezseed-error.log',
          exec_mode: 'fork_mode'
        },
        {
          name: 'watcher',
          script: p.join(root, 'watcher.js'),
          out_file: '/usr/local/opt/ezseed/logs/watcher-out.log',
          error_file: '/usr/local/opt/ezseed/logs/wathcer-error.log',
          exec_mode: 'fork_mode'
        }]
      }

      fs.writeFileSync(p.join(root, 'ezseed.json'), JSON.stringify(json, undefined, 2), {mode: 775})

      logger.info(i18n.__('Ezseed json declaration saved'))
    }

    return helper.next()
  })

  .then(function() {
     if(opts.new) {
      logger.info(i18n.__('Installation complete!'))
      logger.info(i18n.__('Please run "ezseed useradd username" to add a user'))
      logger.info(i18n.__('To launch ezseed run "ezseed start"'))
      return helper.exit('Installation')(0)
    } else {
      return helper.exit('Configuration')(0)
    }
  })
  .catch(helper.exit(opts.new ? 'Installation' : 'Configuration'))

}
<commit_msg>fix(install): ezseed json already exists, lang<commit_after>var p = require('path')
  , logger = require('ezseed-logger')()
  , fs = require('fs')
  , i18n = require('i18n')
  , config = require('../config/config-sample')
  , config_path = p.join(p.resolve(__dirname, '../config'), 'config.js')
  , helper = require('./helpers/promise')

module.exports = function(opts) {
  if(opts.new) {
    require('./helpers/ascii').print()
    console.log('Welcome to ezseed!')
  }

  //ask configuration questions
  require('./inquirer/lang')()
  .then(function(lang) {

    i18n.setLocale(lang)
    config['lang'] = lang

    return helper.condition(!opts.skipconfig, require('./inquirer/config'))

  })
  .then(function(answers) {

    var server

    if(answers) {
      for(var answer in answers) {
        config[answer] = answers[answer]
      }

      server = '127.0.0.1:'+answers.port
    }

    return helper.condition(!opts.skipserver, require('./commands/install').server(server))
  })
  .catch(helper.exit(i18n.__('Server installation')))

  //ask client questions
  .then(function() {
    return helper.condition(!opts.skipclient, require('./inquirer/client'))
  })
  .then(function(client) {
    //if opts.skipclient
    if(client === undefined || opts.skipclient)
      client = {install_client: false}

    return helper.condition(client.install_client, require('./commands/install').client(client.client))
  })
  .catch(helper.exit(i18n.__('Client installation')))

  //Write configuration
  .then(function() {

    if(!opts.skipconfig) {

      if(fs.existsSync(config_path)) {
        if(!opts.force) {
          logger.warn(i18n.__('%s already exists - use force to replace, skipping', config_path))
          return helper.next()
        } else {
          logger.warn(i18n.__('Overriding %s', config_path))
        }
      }

      fs.writeFileSync(config_path, 'module.exports = '+JSON.stringify(config, undefined, 2), {mode: 775})
      logger.info(i18n.__('Configuration saved in %s', config_path))

    }

    return helper.next()
  })
  //Write pm2 json configuration
  .then(function() {

    if(!opts.skipconfig) {

      var root = p.resolve(__dirname, '../'),
        ezseed_pm2 = p.join(root, 'ezseed.json')

      if(fs.existsSync(ezseed_pm2) && !opts.force) {
        logger.warn(i18n.__('%s already exists - use force to replace, skipping', p.join(root, 'ezseed.json')))
        return helper.next()
      }

      var json = {
        apps: [{
          name: 'ezseed',
          script: p.join(root, 'server.js'),
          out_file: '/usr/local/opt/ezseed/logs/ezseed-out.log',
          error_file: '/usr/local/opt/ezseed/logs/ezseed-error.log',
          exec_mode: 'fork_mode'
        },
        {
          name: 'watcher',
          script: p.join(root, 'watcher.js'),
          out_file: '/usr/local/opt/ezseed/logs/watcher-out.log',
          error_file: '/usr/local/opt/ezseed/logs/wathcer-error.log',
          exec_mode: 'fork_mode'
        }]
      }

      fs.writeFileSync(ezseed_pm2, JSON.stringify(json, undefined, 2))

      logger.info(i18n.__('Ezseed json declaration saved'))
    }

    return helper.next()
  })

  .then(function() {
     if(opts.new) {
      logger.info(i18n.__('Installation complete!'))
      logger.info(i18n.__('Please run "ezseed useradd username" to add a user'))
      logger.info(i18n.__('To launch ezseed run "ezseed start"'))
      return helper.exit('Installation')(0)
    } else {
      return helper.exit('Configuration')(0)
    }
  })
  .catch(helper.exit(opts.new ? 'Installation' : 'Configuration'))

}
<|endoftext|>


<commit_before>var fs = require('fs');
var MongoClient = require('mongodb').MongoClient;

var config = require('../front/config.json');

MongoClient.connect(config.mongodb, function(err, db) {
    if (err) {
        throw new Error(err);
    }
    var talks = db.collection('talks');
    talks.find({}).toArray(function(err, docs) {
        if (err) {
            throw new Error(err);
        }
        docs.forEach(function(el) {
            var outputFilename = "./data/talks/" + el.id + ".json";
            fs.writeFile(outputFilename, JSON.stringify(el, null, 4), function(err) {
                if (err) {
                    throw new Error(err);
                }
            });
        });
        db.close();
    });
});
<commit_msg>Load configuration from current directory<commit_after>var fs = require('fs');
var MongoClient = require('mongodb').MongoClient;

var config = require('./config.json');

MongoClient.connect(config.mongodb, function(err, db) {
    if (err) {
        throw new Error(err);
    }
    var talks = db.collection('talks');
    talks.find({}).toArray(function(err, docs) {
        if (err) {
            throw new Error(err);
        }
        docs.forEach(function(el) {
            var outputFilename = "./data/talks/" + el.id + ".json";
            fs.writeFile(outputFilename, JSON.stringify(el, null, 4), function(err) {
                if (err) {
                    throw new Error(err);
                }
            });
        });
        db.close();
    });
});
<|endoftext|>


<commit_before>ZBase.registerView((function() {

  var kBasePath = "/a/logviewer/";

  var query_mgr;
  var logfiles;
  var default_end_time = (new Date()).getTime() * 1000;
  var next_page_time;
  var pagination_history = [];

  var init = function(params) {
    $.showLoader();
    query_mgr = EventSourceHandler();

    $.httpGet("/api/v1/logfiles", function(r) {
      if (r.status == 200) {
        logfiles = JSON.parse(r.response).logfile_definitions;
        render();
        updateQuery(params.path);
      } else {
        render();
        renderError("Server Error");
      }

      $.hideLoader();
    });
  };

  var destroy = function() {
    query_mgr.closeAll();
  };

  var updateQuery = function(url) {
    setQueryParams(url);
    executeQuery();
  }

  var executeQuery = function() {
    showLoadingBar(0);

    var params = getQueryParams();
    params.limit = 100;

    var url = "/api/v1/logfiles/scan?" + $.buildQueryString(params);
    var query = query_mgr.get("logfile_query", url);

    query.addEventListener("message", function(e) {
      var data = JSON.parse(e.data);
      var result = data.result;

      if (result.length > 0) {
        showLoadingBar(data.rows_scanned);
        renderResult(result);
      }

      if (data.status == "finished") {
        query_mgr.close("logfile_query");
        hideLoadingBar();

        next_page_time = result[result.length - 1].time;
      }
    });

    query.addEventListener("error", function(e) {
      query_mgr.close("logfile_query");
      hideLoadingBar();
    });
  };

  var getQueryParams = function() {
    var params = {};

    // param: logfile
    params.logfile = $(".zbase_logviewer z-dropdown.logfile_control").getValue();

    // param: time
    var time_control = $(".zbase_logviewer .time_control");
    var time = time_control.getAttribute("data-timestamp");
    if (time != default_end_time) {
      params.time = time;
    }

    // param: filter
    params.filter_type = $(".zbase_logviewer .filter_type_control").getValue();
    params.filter = $(".zbase_logviewer .filter_control").getValue();

    // param: columns
    params.columns = $(".zbase_logviewer .columns_control").getValue();

    return params;
  };

  var setQueryParams = function(url) {
    // param: logfile
    var logfile = UrlUtil.getPath(url).substr(kBasePath.length);
    setLogfileParam(logfile);
    setLogfileName(logfile);

    // param: end time
    var end_time = UrlUtil.getParamValue(url, "time");
    setTimeParam(end_time);

    // param: filter type
    var filter_type = UrlUtil.getParamValue(url, "filter_type");
    var filter = UrlUtil.getParamValue(url, "filter");
    setFilterParam(filter_type, filter);

    // param: columns
    var columns = UrlUtil.getParamValue(url, "columns");
    setColumnsParam(logfile, columns);

    // param: raw
    var raw = UrlUtil.getParamValue(url, "raw");

    //pagination
    setPagination();

    // "showing historic data" hint
    var is_historical = end_time && end_time != default_end_time;
    setHistoricalDataHint(is_historical);
  };

  var setLogfileParam = function(logfile) {
    var items = [];
    logfiles.forEach(function(logfile) {
      var item = document.createElement("z-dropdown-item");
      item.innerHTML = logfile.name;
      item.setAttribute("data-value", logfile.name);
      items.push(item);
    });

    var dropdown = $(".zbase_logviewer z-dropdown.logfile_control");
    dropdown.setDropdownItems(items);
    dropdown.setValue([logfile]);
  };

  var setTimeParam = function(end_time) {
    if (typeof end_time == "string") {
      end_time = parseInt(end_time, 10);
    }

    if (!end_time) {
      end_time = default_end_time;
    }

    var time_control = $(".zbase_logviewer .time_control");
    time_control.setAttribute("data-timestamp", end_time);
    time_control.value = DateUtil.printTimestamp(end_time);
  };

  var setFilterParam = function(filter_type, filter) {
    if (!filter_type) {
      filter_type = "sql";
    }

    $(".zbase_logviewer .filter_type_control").setValue([filter_type]);
    $(".zbase_logviewer .filter_control").setValue(filter);
  }

  var setColumnsParam = function(logfile, columns_str) {
    if (!columns_str) {
      columns_str = "__raw__";
    }

    var columns = listLogfileColumns(logfile);
    var items = [];

    {
      var item = document.createElement("z-dropdown-item");
      item.innerHTML = "<z-checkbox></z-checkbox> " + "Raw Logline";
      item.setAttribute("data-value", "__raw__");
      items.push(item);
    }

    columns.forEach(function(column) {
      var item = document.createElement("z-dropdown-item");
      item.innerHTML = "<z-checkbox></z-checkbox> " + column;
      item.setAttribute("data-value", column);
      items.push(item);
    });

    var dropdown = $(".zbase_logviewer .columns_control");
    dropdown.setDropdownItems(items);
    dropdown.setValue(columns_str.split(","));
  }

  var setLogfileName = function(logfile) {
    $(".zbase_logviewer .logfile_name_crumb").innerHTML = logfile;
  }

  var setPagination = function() {
    var prev_elem = $(".zbase_logviewer .z-pager .prev");

    if (pagination_history.length == 0) {
      prev_elem.setAttribute("data-disabled", true);
    } else {
      prev_elem.removeAttribute("data-disabled");
    }
  }

  var setHistoricalDataHint = function(is_historic) {
    var elem = $(".zbase_logviewer .go_to_recent");
    if (is_historic) {
      elem.classList.remove("hidden");
    } else {
      elem.classList.add("hidden");
    }
  }

  var getQueryURL = function(params) {
    var url = kBasePath + params.logfile;
    delete params.logfile;
    url += "?" + $.buildQueryString(params);
    return url;
  }

  var submitControls = function() {
    next_page_time = null;
    pagination_history = [];

    var url = getQueryURL(getQueryParams());
    $.navigateTo(url);
  }

  var goToMostRecentPage = function() {
    next_page_time = null;
    pagination_history = [];
    default_end_time = (new Date()).getTime() * 1000;
    setTimeParam(default_end_time);

    var params = getQueryParams();
    var url = getQueryURL(params);

    $.navigateTo(url);
  }

  var goToNextPage = function() {
    if (!next_page_time) {
      return;
    }

    var params = getQueryParams();
    params.time = next_page_time;
    var url = getQueryURL(params);

    pagination_history.push(url);
    $.navigateTo(url);
  };

  var goToPreviousPage = function() {
    var url = pagination_history.pop();

    if (url) {
      $.navigateTo(url);
    }
  };

  var findLogfileDefinition = function(logfile_name) {
    for (var i = 0; i < logfiles.length; ++i) {
      if (logfiles[i].name == logfile_name) {
        return logfiles[i];
      }
    }

    return null;
  }

  var listLogfileColumns = function(logfile_name) {
    var logfile_def = findLogfileDefinition(logfile_name);
    if (!logfile_def) {
      $.fatalError();
      return null;
    }

    var columns = [];
    for (var i = 0; i < logfile_def.source_fields.length; ++i) {
      columns.push(logfile_def.source_fields[i].name);
    }

    for (var i = 0; i < logfile_def.row_fields.length; ++i) {
      columns.push(logfile_def.row_fields[i].name);
    }

    return columns;
  }

  var render = function() {
    var page = $.getTemplate("views/logviewer", "zbase_logviewer_main_tpl");

    $(".logfile_control", page).addEventListener("change", submitControls);
    $(".filter_type_control", page).addEventListener("change", submitControls);
    $(".columns_control", page).addEventListener("change", submitControls);
    $(".time_control", page).addEventListener("change", submitControls);
    $(".z-pager .next", page).addEventListener("click", goToNextPage);
    $(".z-pager .prev", page).addEventListener("click", goToPreviousPage);
    $(".go_to_recent a", page).addEventListener("click", goToMostRecentPage);
    $(".filter_control", page).addEventListener("change", submitControls);
    $(".time_control", page).addEventListener(
      "z-datetimepicker-change", submitControls);
    $(".filter_control", page).addEventListener("keyup", function(e) {
      if (e.keyCode == 13) submitControls();
    });

    $.handleLinks(page);
    $.replaceViewport(page);
    initDatePicker();
  };

  var renderResult = function(result) {
    var logtable = LogfileTable(result);
    logtable.render($(".zbase_logviewer .table_container"));
  }

  var renderError = function(error) {
    var error_msg = $.getTemplate(
        "views/logviewer",
        "zbase_logviewer_error_msg_tpl");

    $(".error_text", error_msg).innerHTML = error;
    $.replaceContent($(".zbase_logviewer .table_container"), error_msg);
  }

  var showLoadingBar = function(num_rows) {
    $(".zbase_logviewer").classList.add("loading");
    var elem = $(".zbase_logviewer .loglines_loading_bar");
    elem.classList.remove("hidden");
    $(".loading_bar_info", elem).style.visibility =
        (num_rows > 0 ? "visible" : "hidden");
    $(".num_rows", elem).innerHTML = num_rows;
  };

  var hideLoadingBar = function() {
    $(".zbase_logviewer").classList.remove("loading");
    $(".zbase_logviewer .loglines_loading_bar").classList.add("hidden");
  };

  var initDatePicker = function() {
    var datepicker = new DateTimePicker($(".zbase_logviewer .time_control"));
  };

  return {
    name: "logviewer",
    loadView: init,
    unloadView: destroy,
    handleNavigationChange: updateQuery
  };

})());
<commit_msg>Update logviewer.js<commit_after>ZBase.registerView((function() {

  var kBasePath = "/a/logviewer/";

  var query_mgr;
  var logfiles;
  var default_end_time = (new Date()).getTime() * 1000;
  var next_page_time;
  var pagination_history = [];

  var init = function(params) {
    $.showLoader();
    query_mgr = EventSourceHandler();

    $.httpGet("/api/v1/logfiles", function(r) {
      render();

      if (r.status == 200) {
        logfiles = JSON.parse(r.response).logfile_definitions;
        updateQuery(params.path);
      } else {
        renderError("Server Error");
      }

      $.hideLoader();
    });
  };

  var destroy = function() {
    query_mgr.closeAll();
  };

  var updateQuery = function(url) {
    setQueryParams(url);
    executeQuery();
  }

  var executeQuery = function() {
    showLoadingBar(0);

    var params = getQueryParams();
    params.limit = 100;

    var url = "/api/v1/logfiles/scan?" + $.buildQueryString(params);
    var query = query_mgr.get("logfile_query", url);

    query.addEventListener("message", function(e) {
      var data = JSON.parse(e.data);
      var result = data.result;

      if (result.length > 0) {
        showLoadingBar(data.rows_scanned);
        renderResult(result);
      }

      if (data.status == "finished") {
        query_mgr.close("logfile_query");
        hideLoadingBar();

        next_page_time = result[result.length - 1].time;
      }
    });

    query.addEventListener("error", function(e) {
      query_mgr.close("logfile_query");
      hideLoadingBar();
    });
  };

  var getQueryParams = function() {
    var params = {};

    // param: logfile
    params.logfile = $(".zbase_logviewer z-dropdown.logfile_control").getValue();

    // param: time
    var time_control = $(".zbase_logviewer .time_control");
    var time = time_control.getAttribute("data-timestamp");
    if (time != default_end_time) {
      params.time = time;
    }

    // param: filter
    params.filter_type = $(".zbase_logviewer .filter_type_control").getValue();
    params.filter = $(".zbase_logviewer .filter_control").getValue();

    // param: columns
    params.columns = $(".zbase_logviewer .columns_control").getValue();

    return params;
  };

  var setQueryParams = function(url) {
    // param: logfile
    var logfile = UrlUtil.getPath(url).substr(kBasePath.length);
    setLogfileParam(logfile);
    setLogfileName(logfile);

    // param: end time
    var end_time = UrlUtil.getParamValue(url, "time");
    setTimeParam(end_time);

    // param: filter type
    var filter_type = UrlUtil.getParamValue(url, "filter_type");
    var filter = UrlUtil.getParamValue(url, "filter");
    setFilterParam(filter_type, filter);

    // param: columns
    var columns = UrlUtil.getParamValue(url, "columns");
    setColumnsParam(logfile, columns);

    // param: raw
    var raw = UrlUtil.getParamValue(url, "raw");

    //pagination
    setPagination();

    // "showing historic data" hint
    var is_historical = end_time && end_time != default_end_time;
    setHistoricalDataHint(is_historical);
  };

  var setLogfileParam = function(logfile) {
    var items = [];
    logfiles.forEach(function(logfile) {
      var item = document.createElement("z-dropdown-item");
      item.innerHTML = logfile.name;
      item.setAttribute("data-value", logfile.name);
      items.push(item);
    });

    var dropdown = $(".zbase_logviewer z-dropdown.logfile_control");
    dropdown.setDropdownItems(items);
    dropdown.setValue([logfile]);
  };

  var setTimeParam = function(end_time) {
    if (typeof end_time == "string") {
      end_time = parseInt(end_time, 10);
    }

    if (!end_time) {
      end_time = default_end_time;
    }

    var time_control = $(".zbase_logviewer .time_control");
    time_control.setAttribute("data-timestamp", end_time);
    time_control.value = DateUtil.printTimestamp(end_time);
  };

  var setFilterParam = function(filter_type, filter) {
    if (!filter_type) {
      filter_type = "sql";
    }

    $(".zbase_logviewer .filter_type_control").setValue([filter_type]);
    $(".zbase_logviewer .filter_control").setValue(filter);
  }

  var setColumnsParam = function(logfile, columns_str) {
    if (!columns_str) {
      columns_str = "__raw__";
    }

    var columns = listLogfileColumns(logfile);
    var items = [];

    {
      var item = document.createElement("z-dropdown-item");
      item.innerHTML = "<z-checkbox></z-checkbox> " + "Raw Logline";
      item.setAttribute("data-value", "__raw__");
      items.push(item);
    }

    columns.forEach(function(column) {
      var item = document.createElement("z-dropdown-item");
      item.innerHTML = "<z-checkbox></z-checkbox> " + column;
      item.setAttribute("data-value", column);
      items.push(item);
    });

    var dropdown = $(".zbase_logviewer .columns_control");
    dropdown.setDropdownItems(items);
    dropdown.setValue(columns_str.split(","));
  }

  var setLogfileName = function(logfile) {
    $(".zbase_logviewer .logfile_name_crumb").innerHTML = logfile;
  }

  var setPagination = function() {
    var prev_elem = $(".zbase_logviewer .z-pager .prev");

    if (pagination_history.length == 0) {
      prev_elem.setAttribute("data-disabled", true);
    } else {
      prev_elem.removeAttribute("data-disabled");
    }
  }

  var setHistoricalDataHint = function(is_historic) {
    var elem = $(".zbase_logviewer .go_to_recent");
    if (is_historic) {
      elem.classList.remove("hidden");
    } else {
      elem.classList.add("hidden");
    }
  }

  var getQueryURL = function(params) {
    var url = kBasePath + params.logfile;
    delete params.logfile;
    url += "?" + $.buildQueryString(params);
    return url;
  }

  var submitControls = function() {
    next_page_time = null;
    pagination_history = [];

    var url = getQueryURL(getQueryParams());
    $.navigateTo(url);
  }

  var goToMostRecentPage = function() {
    next_page_time = null;
    pagination_history = [];
    default_end_time = (new Date()).getTime() * 1000;
    setTimeParam(default_end_time);

    var params = getQueryParams();
    var url = getQueryURL(params);

    $.navigateTo(url);
  }

  var goToNextPage = function() {
    if (!next_page_time) {
      return;
    }

    var params = getQueryParams();
    params.time = next_page_time;
    var url = getQueryURL(params);

    pagination_history.push(url);
    $.navigateTo(url);
  };

  var goToPreviousPage = function() {
    var url = pagination_history.pop();

    if (url) {
      $.navigateTo(url);
    }
  };

  var findLogfileDefinition = function(logfile_name) {
    for (var i = 0; i < logfiles.length; ++i) {
      if (logfiles[i].name == logfile_name) {
        return logfiles[i];
      }
    }

    return null;
  }

  var listLogfileColumns = function(logfile_name) {
    var logfile_def = findLogfileDefinition(logfile_name);
    if (!logfile_def) {
      $.fatalError();
      return null;
    }

    var columns = [];
    for (var i = 0; i < logfile_def.source_fields.length; ++i) {
      columns.push(logfile_def.source_fields[i].name);
    }

    for (var i = 0; i < logfile_def.row_fields.length; ++i) {
      columns.push(logfile_def.row_fields[i].name);
    }

    return columns;
  }

  var render = function() {
    var page = $.getTemplate("views/logviewer", "zbase_logviewer_main_tpl");

    $(".logfile_control", page).addEventListener("change", submitControls);
    $(".filter_type_control", page).addEventListener("change", submitControls);
    $(".columns_control", page).addEventListener("change", submitControls);
    $(".time_control", page).addEventListener("change", submitControls);
    $(".z-pager .next", page).addEventListener("click", goToNextPage);
    $(".z-pager .prev", page).addEventListener("click", goToPreviousPage);
    $(".go_to_recent a", page).addEventListener("click", goToMostRecentPage);
    $(".filter_control", page).addEventListener("change", submitControls);
    $(".time_control", page).addEventListener(
      "z-datetimepicker-change", submitControls);
    $(".filter_control", page).addEventListener("keyup", function(e) {
      if (e.keyCode == 13) submitControls();
    });

    $.handleLinks(page);
    $.replaceViewport(page);
    initDatePicker();
  };

  var renderResult = function(result) {
    var logtable = LogfileTable(result);
    logtable.render($(".zbase_logviewer .table_container"));
  }

  var renderError = function(error) {
    var error_msg = $.getTemplate(
        "views/logviewer",
        "zbase_logviewer_error_msg_tpl");

    $(".error_text", error_msg).innerHTML = error;
    $.replaceContent($(".zbase_logviewer .table_container"), error_msg);
  }

  var showLoadingBar = function(num_rows) {
    $(".zbase_logviewer").classList.add("loading");
    var elem = $(".zbase_logviewer .loglines_loading_bar");
    elem.classList.remove("hidden");
    $(".loading_bar_info", elem).style.visibility =
        (num_rows > 0 ? "visible" : "hidden");
    $(".num_rows", elem).innerHTML = num_rows;
  };

  var hideLoadingBar = function() {
    $(".zbase_logviewer").classList.remove("loading");
    $(".zbase_logviewer .loglines_loading_bar").classList.add("hidden");
  };

  var initDatePicker = function() {
    var datepicker = new DateTimePicker($(".zbase_logviewer .time_control"));
  };

  return {
    name: "logviewer",
    loadView: init,
    unloadView: destroy,
    handleNavigationChange: updateQuery
  };

})());
<|endoftext|>