<commit_before>'use strict';

angular.module('mean.icu.ui.membersfooter', [])
    .directive('icuMembersFooter', function() {
        function controller($scope, $state, $injector, context, $stateParams, $timeout,
                            circlesService,PermissionsService, UsersService, ActivitiesService,TasksService,
                            ProjectsService, DiscussionsService, OfficeDocumentsService, FoldersService,
                            OfficesService) {

            var serviceMap = {
                task: 'TasksService',
                tasks: 'TasksService',
                project: 'ProjectsService',
                projects: 'ProjectsService',
                discussion: 'DiscussionsService',
                discussions: 'DiscussionsService',
                office: 'OfficesService',
                offices: 'OfficesService',
                folder: 'FoldersService',
                folders: 'FoldersService',
                officeDocument: 'OfficeDocumentsService',
                officeDocuments: 'OfficeDocumentsService',
                templateDoc: 'TemplateDocsService',
                templateDocs: 'TemplateDocsService',
            };
            $scope.hideAddButton = context.main=="templateDocs" ? false:true;
            $scope.me = UsersService.getMe().$$state.value;

            if($state.current.name.indexOf('search') !== -1){
                let entity = $state.current.name.split('.')[2];
                let service = $injector.get(serviceMap[entity]);

                service.getById($scope.entity._id)
                    .then(res => $scope.entity.watchers = res.watchers);
            }

            UsersService.getAll().then(users=>{
                if(!$scope.entity.watchers)return;

                for(var i = 0; i < $scope.entity.watchers.length; i++){
                    if(typeof $scope.entity.watchers[i] === 'string'){
                        $scope.entity.watchers[i] = _.find(users, { '_id': $scope.entity.watchers[i]});
                    }
                }
            });

            function changePerms(member, newPerms){
                $scope.entity = PermissionsService.changeUsersPermissions($scope.entity, member, newPerms, context);
            }

            $scope.userPermissionStatus = function(member){
                if(member) return PermissionsService.getPermissionStatus(member, $scope.entity) || "";
            };

            $scope.setEditor = function(user){
                return changePerms(user, 'editor');
            };

            $scope.setCommenter = function(user){
                return changePerms(user, 'commenter');
            };

            $scope.setViewer = function(user){
                return changePerms(user, 'viewer');
            };

            console.log("permissions: " + JSON.stringify($scope.entity.permissions,null,2)) ;
            var groupTypes = config.circles.footer;

            var getWatchersGroups = function() {
                $scope.watchersGroups = [];
                var obj;
                for (var i = 0; i < groupTypes.length; i++) {
                    if ($scope.entity.circles && $scope.entity.circles[groupTypes[i]])
                        for (var j = 0; j < $scope.entity.circles[groupTypes[i]].length; j++) {
                            obj = groups.filter(function(obj) {
                                if (obj._id === $scope.entity.circles[groupTypes[i]][j]) {
                                    return obj;
                                }
                            })[0];
                            if (obj) {
                                obj.type = groupTypes[i];
                                $scope.watchersGroups.push(obj);
                            }
                        }
                }
            };

            $scope.selfTest = function(member){
                member.selfTest = $scope.me._id === member._id;
                return member;
            };

            var getNotAssigned = function() {
                var arr1 = _.filter($scope.users, function(u) {
                    return u._id;
                });
                arr1 = _.pluck(arr1, '_id');
                var arr2 = _.pluck($scope.entity.watchers, '_id');
                var diff = _.difference(arr1, arr2);
                var notAssigned = _.filter($scope.users, function(obj) {
                    return diff.indexOf(obj._id) >= 0;
                });
                arr1 = _.pluck(groups, '_id');
                var arr3;
                for (var i = 0; i < groupTypes.length; i++) {
                    arr3 = $scope.entity.circles && $scope.entity.circles[groupTypes[i]] ? $scope.entity.circles[groupTypes[i]] : [];
                    arr1 = _.difference(arr1, arr3);
                }

                var groupsNotAssigned = _.filter(groups, function(obj) {
                    return arr1.indexOf(obj._id) >= 0;
                });
                return groupsNotAssigned.concat(notAssigned);
            }

            $scope.notAssigned = getNotAssigned();
            for(var i =0 ; i<$scope.notAssigned.length;i++){
                if($scope.notAssigned[i] && ($scope.notAssigned[i].job == undefined || $scope.notAssigned[i].job==null)){
                    $scope.notAssigned[i].job = $scope.notAssigned[i].name;
                }
            }

            var update = function(entity, member, action) {
                $scope.notAssigned = getNotAssigned();
                for(var i =0 ; i<$scope.notAssigned.length;i++){
                    if($scope.notAssigned[i] && ($scope.notAssigned[i].job == undefined || $scope.notAssigned[i].job==null)){
                        $scope.notAssigned[i].job = $scope.notAssigned[i].name;
                    }
                }
                var serviceName = serviceMap[$stateParams.id ? context.main : context.entityName];
                var service = $injector.get(serviceName);
                var data = {
                    name: member.name,
                    type: member.type ? member.type : 'user',
                    action: action,
                    frequentUser: member._id
                }

                if(entity.serial != undefined){
                    let serviceName = "OfficeDocumentsService",
                      service = $injector.get(serviceName);
                    let a = [];
                    entity.watchers.forEach(function(watcher){
                        if(watcher instanceof Object) {
                            a.push(String(watcher._id)) ;
                        }
                        else {
                            a.push(String(watcher)) ;
                        }
                    });

                    var json = {
                        'name':'watchers',
                        'newVal':a
                    }
                    entity.watchers = a;
                    service.update(entity,json, action, member._id);
                }
                else{
                    service.update(entity, data, action, member._id);
                }

                getWatchersGroups();
            };

            $scope.showSelect = false;
            var groups = [], allowed;

            circlesService.getmine().then(function(data) {
                for (var i = 0; data && i < groupTypes.length; i++){
                    allowed = data.allowed[groupTypes[i]];
                    allowed.forEach(function(g) {
                        g.type = groupTypes[i]
                    });
                    groups = groups.concat(allowed);
                }
                $scope.notAssigned = getNotAssigned();
                getWatchersGroups();
            });

            $scope.triggerSelect = function() {
                $scope.showSelect = !$scope.showSelect;
                if ($scope.showSelect) {
                    $scope.animate = false;
                }
            };

            $scope.otherWatchers = [];

            function idArrayToObjects(array){
                for(let i = 0; i < array.length; i++){
                    if(typeof array[i] === 'string'){
                        UsersService.getById(array[i]).then(user=>{
                            array[i] = user;
                        });
                    }
                }
            }

            $scope.showMoreWatchers = function() {
                let listWidth = $(".watchersList").width(),
                    watcherWidth = 45,
                    watchers = _.compact($scope.entity.watchers.concat($scope.watchersGroups)),
                    lastIndex = 0;

                for (let i = 0; i < watchers.length; i++) {
                    let elementPosition = (i + 1) * watcherWidth;
                    let isVisible = listWidth > elementPosition;
                    let isLast = i === watchers.length - 1;

                    if(isVisible){
                        lastIndex = i;
                        $scope.showMore = false;
                        $scope.otherWatchers = [];
                    }

                    if(isLast){
                        $scope.otherWatchers = watchers.slice(lastIndex, watchers.length - 1);
                        $scope.showMore = $scope.otherWatchers.length > 1;
                        idArrayToObjects($scope.otherWatchers);
                    }
                }
            };

            $scope.addMember = function(member) {
                $scope.showSelect = false;
                if (member.type) {

                    if (!$scope.entity.circles) $scope.entity.circles = {};
                    if (!$scope.entity.circles[member.type]) $scope.entity.circles[member.type] = [];
                    $scope.entity.circles[member.type].push(member._id);
                } else {
                    $scope.entity.watchers.push(member);
                    if($scope.entity.subTasks){
                        $scope.entity.subTasks.forEach((subTask)=>{
                            subTask.watchers.push(member);
                        });
                    }
                    if($scope.entity.subProjects){
                        $scope.entity.subProjects.forEach((subProject)=>{
                            subProject.watchers.push(member);
                        });
                    }
                }

                update($scope.entity, member, 'added');
                $scope.animate = true;

                var task = $scope.entity ;
                var me = $scope.me ;
                if (context.entityName === 'discussion') {
                    task.discussion = context.entityId;
                }
                switch(context.main) {
                    case 'projects':
                        ProjectsService.updateWatcher(task, me, member).then(function(result) {
                            ActivitiesService.data.push(result);
                        });
                        break ;
                    case 'tasks':
                        TasksService.updateWatcher(task, me, member).then(function(result) {
                            ActivitiesService.data.push(result);
                        });
                        break ;
                    case 'discussions':
                        DiscussionsService.updateWatcher(task, me, member).then(function(result) {
                            ActivitiesService.data = ActivitiesService.data || [] ;
                            ActivitiesService.data.push(result);
                        });
                        break ;
                    case 'officeDocuments':
                        OfficeDocumentsService.updateWatcher(task, me, member).then(function(result) {
                            ActivitiesService.data = ActivitiesService.data || [] ;
                            ActivitiesService.data.push(result);
                        });
                        break ;
                    case 'folders':
                        FoldersService.updateWatcher(task, me, member).then(function(result) {
                            ActivitiesService.data = ActivitiesService.data || [] ;
                            ActivitiesService.data.push(result);
                        });
                        break ;
                    case 'offices':
                        OfficesService.updateWatcher(task, me, member).then(function(result) {
                            ActivitiesService.data = ActivitiesService.data || [] ;
                            ActivitiesService.data.push(result);
                        });
                        break ;
                }
            };

          $scope.isDropdownwatchersOpen = false;

            $scope.toggled = function() {
                $scope.isDropdownwatchersOpen = !$scope.isDropdownwatchersOpen;
            };

            $scope.deleteMember = function(member) {
                if (member.type) {
                    $scope.entity.circles[member.type] = _.reject($scope.entity.circles[member.type], function(mem) {
                        return _.isEqual(member._id, mem);
                    });
                } else {
                    $scope.entity.watchers = _.reject($scope.entity.watchers, function(mem) {
                        return _.isEqual(member, mem);
                    });
                }

                update($scope.entity, member, 'removed');

                var task = $scope.entity ;
                var me = $scope.me ;
                if (context.entityName === 'discussion') {
                    task.discussion = context.entityId;
                }

                switch(context.main) {
                    case 'projects':
                        ProjectsService.updateWatcher(task, me, member, 'removeWatcher').then(function(result) {
                            ActivitiesService.data = ActivitiesService.data || [] ;
                            ActivitiesService.data.push(result);
                        });
                        break ;

                    case 'tasks':
                        TasksService.updateWatcher(task, me, member, 'removeWatcher').then(function(result) {
                            ActivitiesService.data.push(result);
                        });
                        break ;
                    case 'discussions':
                        DiscussionsService.updateWatcher(task, me, member, 'removeWatcher').then(function(result) {
                            ActivitiesService.data = ActivitiesService.data || [] ;
                            ActivitiesService.data.push(result);
                        });
                        break ;
                    case 'officeDocuments':
                        OfficeDocumentsService.updateWatcher(task, me, member, 'removeWatcher').then(function(result) {
                            ActivitiesService.data = ActivitiesService.data || [] ;
                            ActivitiesService.data.push(result);
                        });
                        break ;
                    case 'folders':
                        FoldersService.updateWatcher(task, me, member, 'removeWatcher').then(function(result) {
                            ActivitiesService.data = ActivitiesService.data || [] ;
                            ActivitiesService.data.push(result);
                        });
                        break ;
                    case 'offices':
                        OfficesService.updateWatcher(task, me, member, 'removeWatcher').then(function(result) {
                            ActivitiesService.data = ActivitiesService.data || [] ;
                            ActivitiesService.data.push(result);
                        });
                        break ;
                }
                $scope.showMoreWatchers();
            };
        }

        return {
            restrict: 'EA',
            scope: {
                entity: '=',
                users: '=',
                groups: '='
            },
            controller: controller,
            templateUrl: '/icu/components/members-footer/members-footer.html'
        };
    })
<commit_msg>fixed showing new watcher after adding<commit_after>'use strict';

angular.module('mean.icu.ui.membersfooter', [])
    .directive('icuMembersFooter', function() {
        function controller($scope, $state, $injector, context, $stateParams, $timeout,
                            circlesService,PermissionsService, UsersService, ActivitiesService,TasksService,
                            ProjectsService, DiscussionsService, OfficeDocumentsService, FoldersService,
                            OfficesService) {

            var serviceMap = {
                task: 'TasksService',
                tasks: 'TasksService',
                project: 'ProjectsService',
                projects: 'ProjectsService',
                discussion: 'DiscussionsService',
                discussions: 'DiscussionsService',
                office: 'OfficesService',
                offices: 'OfficesService',
                folder: 'FoldersService',
                folders: 'FoldersService',
                officeDocument: 'OfficeDocumentsService',
                officeDocuments: 'OfficeDocumentsService',
                templateDoc: 'TemplateDocsService',
                templateDocs: 'TemplateDocsService',
            };
            $scope.hideAddButton = context.main=="templateDocs" ? false:true;
            $scope.me = UsersService.getMe().$$state.value;

            if($state.current.name.indexOf('search') !== -1){
                let entity = $state.current.name.split('.')[2];
                let service = $injector.get(serviceMap[entity]);

                service.getById($scope.entity._id)
                    .then(res => $scope.entity.watchers = res.watchers);
            }

            UsersService.getAll().then(users=>{
                if(!$scope.entity.watchers)return;

                for(var i = 0; i < $scope.entity.watchers.length; i++){
                    if(typeof $scope.entity.watchers[i] === 'string'){
                        $scope.entity.watchers[i] = _.find(users, { '_id': $scope.entity.watchers[i]});
                    }
                }
            });

            function changePerms(member, newPerms){
                $scope.entity = PermissionsService.changeUsersPermissions($scope.entity, member, newPerms, context);
            }

            $scope.userPermissionStatus = function(member){
                if(member) return PermissionsService.getPermissionStatus(member, $scope.entity) || "";
            };

            $scope.setEditor = function(user){
                return changePerms(user, 'editor');
            };

            $scope.setCommenter = function(user){
                return changePerms(user, 'commenter');
            };

            $scope.setViewer = function(user){
                return changePerms(user, 'viewer');
            };

            console.log("permissions: " + JSON.stringify($scope.entity.permissions,null,2)) ;
            var groupTypes = config.circles.footer;

            var getWatchersGroups = function() {
                $scope.watchersGroups = [];
                var obj;
                for (var i = 0; i < groupTypes.length; i++) {
                    if ($scope.entity.circles && $scope.entity.circles[groupTypes[i]])
                        for (var j = 0; j < $scope.entity.circles[groupTypes[i]].length; j++) {
                            obj = groups.filter(function(obj) {
                                if (obj._id === $scope.entity.circles[groupTypes[i]][j]) {
                                    return obj;
                                }
                            })[0];
                            if (obj) {
                                obj.type = groupTypes[i];
                                $scope.watchersGroups.push(obj);
                            }
                        }
                }
            };

            $scope.selfTest = function(member){
                member.selfTest = $scope.me._id === member._id;
                return member;
            };

            var getNotAssigned = function() {
                var arr1 = _.filter($scope.users, function(u) {
                    return u._id;
                });
                arr1 = _.pluck(arr1, '_id');
                var arr2 = _.pluck($scope.entity.watchers, '_id');
                var diff = _.difference(arr1, arr2);
                var notAssigned = _.filter($scope.users, function(obj) {
                    return diff.indexOf(obj._id) >= 0;
                });
                arr1 = _.pluck(groups, '_id');
                var arr3;
                for (var i = 0; i < groupTypes.length; i++) {
                    arr3 = $scope.entity.circles && $scope.entity.circles[groupTypes[i]] ? $scope.entity.circles[groupTypes[i]] : [];
                    arr1 = _.difference(arr1, arr3);
                }

                var groupsNotAssigned = _.filter(groups, function(obj) {
                    return arr1.indexOf(obj._id) >= 0;
                });
                return groupsNotAssigned.concat(notAssigned);
            }

            $scope.notAssigned = getNotAssigned();
            for(var i =0 ; i<$scope.notAssigned.length;i++){
                if($scope.notAssigned[i] && ($scope.notAssigned[i].job == undefined || $scope.notAssigned[i].job==null)){
                    $scope.notAssigned[i].job = $scope.notAssigned[i].name;
                }
            }

            var update = function(entity, member, action) {
                $scope.notAssigned = getNotAssigned();
                for(var i =0 ; i<$scope.notAssigned.length;i++){
                    if($scope.notAssigned[i] && ($scope.notAssigned[i].job == undefined || $scope.notAssigned[i].job==null)){
                        $scope.notAssigned[i].job = $scope.notAssigned[i].name;
                    }
                }
                var serviceName = serviceMap[$stateParams.id ? context.main : context.entityName];
                var service = $injector.get(serviceName);
                var data = {
                    name: member.name,
                    type: member.type ? member.type : 'user',
                    action: action,
                    frequentUser: member._id
                }

                if(entity.serial != undefined){
                    let serviceName = "OfficeDocumentsService",
                      service = $injector.get(serviceName);
                    let a = [];
                    entity.watchers.forEach(function(watcher){
                        if(watcher instanceof Object) {
                            a.push(String(watcher._id)) ;
                        }
                        else {
                            a.push(String(watcher)) ;
                        }
                    });

                    var json = {
                        'name':'watchers',
                        'newVal':a
                    }
                    entity.watchers = a;
                    return service.update(entity,json, action, member._id);
                }
                else{
                    return service.update(entity, data, action, member._id);
                }

                getWatchersGroups();
            };

            $scope.showSelect = false;
            var groups = [], allowed;

            circlesService.getmine().then(function(data) {
                for (var i = 0; data && i < groupTypes.length; i++){
                    allowed = data.allowed[groupTypes[i]];
                    allowed.forEach(function(g) {
                        g.type = groupTypes[i]
                    });
                    groups = groups.concat(allowed);
                }
                $scope.notAssigned = getNotAssigned();
                getWatchersGroups();
            });

            $scope.triggerSelect = function() {
                $scope.showSelect = !$scope.showSelect;
                if ($scope.showSelect) {
                    $scope.animate = false;
                }
            };

            $scope.otherWatchers = [];

            function idArrayToObjects(array){
                for(let i = 0; i < array.length; i++){
                    if(typeof array[i] === 'string'){
                        UsersService.getById(array[i]).then(user=>{
                            array[i] = user;
                        });
                    }
                }
            }

            $scope.showMoreWatchers = function() {
                let listWidth = $(".watchersList").width(),
                    watcherWidth = 45,
                    watchers = _.compact($scope.entity.watchers.concat($scope.watchersGroups)),
                    lastIndex = 0;

                for (let i = 0; i < watchers.length; i++) {
                    let elementPosition = (i + 1) * watcherWidth;
                    let isVisible = listWidth > elementPosition;
                    let isLast = i === watchers.length - 1;

                    if(isVisible){
                        lastIndex = i;
                        $scope.showMore = false;
                        $scope.otherWatchers = [];
                    }

                    if(isLast){
                        $scope.otherWatchers = watchers.slice(lastIndex, watchers.length - 1);
                        $scope.showMore = $scope.otherWatchers.length > 1;
                        idArrayToObjects($scope.otherWatchers);
                    }
                }
            };

            $scope.addMember = function(member) {
                $scope.showSelect = false;
                if (member.type) {

                    if (!$scope.entity.circles) $scope.entity.circles = {};
                    if (!$scope.entity.circles[member.type]) $scope.entity.circles[member.type] = [];
                    $scope.entity.circles[member.type].push(member._id);
                } else {
                    $scope.entity.watchers.push(member);
                    if($scope.entity.subTasks){
                        $scope.entity.subTasks.forEach((subTask)=>{
                            subTask.watchers.push(member);
                        });
                    }
                    if($scope.entity.subProjects){
                        $scope.entity.subProjects.forEach((subProject)=>{
                            subProject.watchers.push(member);
                        });
                    }
                }
                update($scope.entity, member, 'added')
                  .then(updatedEntity => {
                    let { watchers, permissions } = updatedEntity;
                    Object.assign($scope.entity, watchers, permissions);
                    $scope.animate = true;

                    var task = $scope.entity;
                    var me = $scope.me ;
                    if (context.entityName === 'discussion') {
                      task.discussion = context.entityId;
                    }
                    switch(context.main) {
                      case 'projects':
                        ProjectsService.updateWatcher(task, me, member).then(function (result) {
                          ActivitiesService.data.push(result);
                        });
                        break;
                      case 'tasks':
                        TasksService.updateWatcher(task, me, member).then(function (result) {
                          ActivitiesService.data.push(result);
                        });
                        break;
                      case 'discussions':
                        DiscussionsService.updateWatcher(task, me, member).then(function (result) {
                          ActivitiesService.data = ActivitiesService.data || [];
                          ActivitiesService.data.push(result);
                        });
                        break;
                      case 'officeDocuments':
                        OfficeDocumentsService.updateWatcher(task, me, member).then(function (result) {
                          ActivitiesService.data = ActivitiesService.data || [];
                          ActivitiesService.data.push(result);
                        });
                        break;
                      case 'folders':
                        FoldersService.updateWatcher(task, me, member).then(function (result) {
                          ActivitiesService.data = ActivitiesService.data || [];
                          ActivitiesService.data.push(result);
                        });
                        break;
                      case 'offices':
                        OfficesService.updateWatcher(task, me, member).then(function (result) {
                          ActivitiesService.data = ActivitiesService.data || [];
                          ActivitiesService.data.push(result);
                        });
                        break;
                    }
                  });
            };

          $scope.isDropdownwatchersOpen = false;

            $scope.toggled = function() {
                $scope.isDropdownwatchersOpen = !$scope.isDropdownwatchersOpen;
            };

            $scope.deleteMember = function(member) {
                if (member.type) {
                    $scope.entity.circles[member.type] = _.reject($scope.entity.circles[member.type], function(mem) {
                        return _.isEqual(member._id, mem);
                    });
                } else {
                    $scope.entity.watchers = _.reject($scope.entity.watchers, function(mem) {
                        return _.isEqual(member, mem);
                    });
                }

                update($scope.entity, member, 'removed');

                var task = $scope.entity ;
                var me = $scope.me ;
                if (context.entityName === 'discussion') {
                    task.discussion = context.entityId;
                }

                switch(context.main) {
                    case 'projects':
                        ProjectsService.updateWatcher(task, me, member, 'removeWatcher').then(function(result) {
                            ActivitiesService.data = ActivitiesService.data || [] ;
                            ActivitiesService.data.push(result);
                        });
                        break ;

                    case 'tasks':
                        TasksService.updateWatcher(task, me, member, 'removeWatcher').then(function(result) {
                            ActivitiesService.data.push(result);
                        });
                        break ;
                    case 'discussions':
                        DiscussionsService.updateWatcher(task, me, member, 'removeWatcher').then(function(result) {
                            ActivitiesService.data = ActivitiesService.data || [] ;
                            ActivitiesService.data.push(result);
                        });
                        break ;
                    case 'officeDocuments':
                        OfficeDocumentsService.updateWatcher(task, me, member, 'removeWatcher').then(function(result) {
                            ActivitiesService.data = ActivitiesService.data || [] ;
                            ActivitiesService.data.push(result);
                        });
                        break ;
                    case 'folders':
                        FoldersService.updateWatcher(task, me, member, 'removeWatcher').then(function(result) {
                            ActivitiesService.data = ActivitiesService.data || [] ;
                            ActivitiesService.data.push(result);
                        });
                        break ;
                    case 'offices':
                        OfficesService.updateWatcher(task, me, member, 'removeWatcher').then(function(result) {
                            ActivitiesService.data = ActivitiesService.data || [] ;
                            ActivitiesService.data.push(result);
                        });
                        break ;
                }
                $scope.showMoreWatchers();
            };
        }

        return {
            restrict: 'EA',
            scope: {
                entity: '=',
                users: '=',
                groups: '='
            },
            controller: controller,
            templateUrl: '/icu/components/members-footer/members-footer.html'
        };
    })
<|endoftext|>


<commit_before>
function get_thumb_of(name) {
	if (name.match(".avi"))
		return name.replace(".avi", ".thm");
	if (name.match(".AVI"))
		return name.replace(".AVI", ".THM");
	return name;
}

var hash = null;

function anchor() {
	var anchor;

	if (hash != document.location.hash) {
		// store complete hash including #
		hash = document.location.hash;
		// but strip # for anchor part to pass to select()
		anchor = hash.substring(1);
		// when opening from the index, assume no anchor
		if (hash == "")
			anchor = "all"; //entries[0];
	} else {
		anchor = "all"; //entries[0];
	}

	return anchor;
}

function select(entry) {
	var selected = 0;

	for (count = 0; count < entries.length; count++)
		if (entry == entries[count])
			selected = count;

	// are we looking at an album index?
	if (entry == "all") {
		var thumbs = "
\n";
		// paint all the thumbnails
		for (count = 0; count < entries.length; count++) {
			var thumbnailimage = get_thumb_of(entries[count]);
			if ((count % 5) == 0)
				thumbs += "

\n";
			thumbs += "
";
// doesn't work because backrefs are broken atm
// thumbs += "
";
			thumbs += " \n
\n";
		}
		thumbs += "
\n";

		// Finished constructing the thumbs div
		document.getElementById('thumbs').innerHTML = thumbs;
		return;
	}

	// determine the range over 9 images to show
	var start = Math.max(selected - 4, 0);
	start = Math.min(start, Math.max(0, entries.length - 9));
	var stop = Math.min(start + 9, entries.length);

	// links to previous 9 images in the thumbs index
	var thumbs = "";
	if (start > 0) {
		var center = Math.max(selected - 9, 0);
		thumbs += "\n";
	}

	// show images start -> stop and put "entry" in display box
	for (count = start; count < stop; count++) {
		// thumbnail this
		var thumbnailimage = get_thumb_of(entries[count]);
		thumbs += "<img style=\"vertical-align: text-top;\" ";
		if (selected == count) {
			thumbs += "class=\"selected\" ";
		}
		if (Math.abs(selected - count) <= 1) {
			thumbs += "src=\"/image.php?r=1&x=100&y=100&i=" + album + "/" + thumbnailimage + "\" /> \n";
		} else {
			thumbs += "src=\"/image.php?r=1&x=50&y=50&i=" + album + "/" + thumbnailimage + "\" /> \n";
		}
	}

	// fill preload div
	var preload = "";
	if (stop < entries.length) {
		var thumbnailimage = get_thumb_of(entries[stop]);
		preload += "\n";
	}

	if (selected + 2 < entries.length) {
		var thumbnailimage = get_thumb_of(entries[selected + 2]);
		preload += "\n";
	}

	if ((selected + 1) < entries.length) {
		if (!(entry.match(".avi") || entry.match(".AVI"))) {
			preload += "\n";
		}
	}
	document.getElementById('preload').innerHTML = preload;

	// links to next 9 images in the thumbs index
	if (stop < entries.length) {
		var center = Math.min(stop + 5, entries.length)
		thumbs += "\n";
	}

	// Finished constructing the thumbs div
	document.getElementById('thumbs').innerHTML = thumbs;

	var content = "\n";

	// construct the map
	content += "<map name=\"map-" + entry + "\">\n";
	if (selected > 0) {
		content += "<area shape=\"rect\" coords=\"0,0,250,800\" href=\"javascript: select('" + entries[selected - 1] + "')\" />\n";
	}
	if (selected < (entries.length - 1)) {
		content += "<area shape=\"rect\" coords=\"400,0,800,800\" href=\"javascript: select('" + entries[selected + 1] + "')\" />\n";
	}
	content += "</map>\n";

	if (selected > 0) {
		content += "\n";
	}

	// display selected image
	if (entry.match(".avi") || entry.match(".AVI")) {
		// Video display
		content += "<embed autoplay=\"true\" autostart=\"true\" uimode=\"true\" type=\"application/x-mplayer2\" id=\"MediaPlayer\" src=\"/" + album + "/" + entry + "\" style=\"visibility: visible;\" height=\"480\" width=\"640\" pluginspage=\"http://www.microsoft.com/windows/windowsmedia/download/\">\n";
	} else {
		// image display
		content += "\n";
	}

	if (selected + 1 < entries.length)
		content += "\n";

	content += "
\n" + album + " / " + "" + entry + "\n";

	// and display
	document.getElementById('content').innerHTML = content;
	document.location.hash = entry;
}

<commit_msg>Add basic album navigation keybindings, wooo<commit_after>
function get_thumb_of(name) {
	if (name.match(".avi"))
		return name.replace(".avi", ".thm");
	if (name.match(".AVI"))
		return name.replace(".AVI", ".THM");
	return name;
}

var hash = null;

function anchor() {
	var anchor;

	if (hash != document.location.hash) {
		// store complete hash including #
		hash = document.location.hash;
		// but strip # for anchor part to pass to select()
		anchor = hash.substring(1);
		// when opening from the index, assume no anchor
		if (hash == "")
			anchor = "all"; //entries[0];
	} else {
		anchor = "all"; //entries[0];
	}

	return anchor;
}

function select(entry) {
	var selected = 0;

	for (count = 0; count < entries.length; count++)
		if (entry == entries[count])
			selected = count;

	// are we looking at an album index?
	if (entry == "all") {
		var thumbs = "
\n";
		// paint all the thumbnails
		for (count = 0; count < entries.length; count++) {
			var thumbnailimage = get_thumb_of(entries[count]);
			if ((count % 5) == 0)
				thumbs += "

\n";
			thumbs += "
";
// doesn't work because backrefs are broken atm
// thumbs += "
";
			thumbs += " \n
\n";
		}
		thumbs += "
\n";

		// Finished constructing the thumbs div
		document.getElementById('thumbs').innerHTML = thumbs;
		return;
	}

	// determine the range over 9 images to show
	var start = Math.max(selected - 4, 0);
	start = Math.min(start, Math.max(0, entries.length - 9));
	var stop = Math.min(start + 9, entries.length);

	// links to previous 9 images in the thumbs index
	var thumbs = "";
	if (start > 0) {
		var center = Math.max(selected - 9, 0);
		thumbs += "\n";
	}

	// show images start -> stop and put "entry" in display box
	for (count = start; count < stop; count++) {
		// thumbnail this
		var thumbnailimage = get_thumb_of(entries[count]);
		thumbs += "<img style=\"vertical-align: text-top;\" ";
		if (selected == count) {
			thumbs += "class=\"selected\" ";
		}
		if (Math.abs(selected - count) <= 1) {
			thumbs += "src=\"/image.php?r=1&x=100&y=100&i=" + album + "/" + thumbnailimage + "\" /> \n";
		} else {
			thumbs += "src=\"/image.php?r=1&x=50&y=50&i=" + album + "/" + thumbnailimage + "\" /> \n";
		}
	}

	// fill preload div
	var preload = "";
	if (stop < entries.length) {
		var thumbnailimage = get_thumb_of(entries[stop]);
		preload += "\n";
	}

	if (selected + 2 < entries.length) {
		var thumbnailimage = get_thumb_of(entries[selected + 2]);
		preload += "\n";
	}

	if ((selected + 1) < entries.length) {
		if (!(entry.match(".avi") || entry.match(".AVI"))) {
			preload += "\n";
		}
	}
	document.getElementById('preload').innerHTML = preload;

	// links to next 9 images in the thumbs index
	if (stop < entries.length) {
		var center = Math.min(stop + 5, entries.length)
		thumbs += "\n";
	}

	// Finished constructing the thumbs div
	document.getElementById('thumbs').innerHTML = thumbs;

	var content = "\n";

	// construct the map
	content += "<map name=\"map-" + entry + "\">\n";
	if (selected > 0) {
		content += "<area shape=\"rect\" coords=\"0,0,250,800\" href=\"javascript: select('" + entries[selected - 1] + "')\" />\n";
	}
	if (selected < (entries.length - 1)) {
		content += "<area shape=\"rect\" coords=\"400,0,800,800\" href=\"javascript: select('" + entries[selected + 1] + "')\" />\n";
	}
	content += "</map>\n";

	if (selected > 0) {
		content += "\n";
	}

	// display selected image
	if (entry.match(".avi") || entry.match(".AVI")) {
		// Video display
		content += "<embed autoplay=\"true\" autostart=\"true\" uimode=\"true\" type=\"application/x-mplayer2\" id=\"MediaPlayer\" src=\"/" + album + "/" + entry + "\" style=\"visibility: visible;\" height=\"480\" width=\"640\" pluginspage=\"http://www.microsoft.com/windows/windowsmedia/download/\">\n";
	} else {
		// image display
		content += "\n";
	}

	if (selected + 1 < entries.length)
		content += "\n";

	content += "
\n" + album + " / " + "" + entry + "\n";

	// and display
	document.getElementById('content').innerHTML = content;
	document.location.hash = entry;
	document.selected = selected;
}

function keypressed(e) {
	e = e || window.event;

	var k = e.keyCode || e.which;

	switch(k) {
	case 78: //left
	case 32: // space
	case 39: // right
		if (document.selected < entries.length - 1)
			select(entries[document.selected + 1]);
		break;
	case 80: // p
	case 8:  // backspace
	case 37: // left
		if (document.selected > 0)
			select(entries[document.selected - 1]);
		break;
	case 38: // up
		select("all");
		break;
	case 40: // down
		select(entries[document.selected]);
		break;
	default:
		alert(k);
		break;
	}

	return true;
}

document.onkeydown = keypressed;

<|endoftext|>


<commit_before>var util = require('util');
var EventEmitter = require('events').EventEmitter;

function GenieMini() {
    this.btServiceIds = ['f000474d04514000b000000000000000'];

    this._gmCh = null;
    this._dev = null;
    this._moving = false;
    this._angle = null;
    this._position = 0;
    this._currentMove = null;
    this._stepsPerDegree = 186.56716418;
}

util.inherits(GenieMini, EventEmitter);

GenieMini.prototype._connectBt = function(btPeripheral, callback) {
    var self = this;
    btPeripheral.connect(function(err1) {
        if (err1) {
            if (callback) callback(false);
            return;
        }
        console.log('GenieMini: connecting via BLE');
        btPeripheral.discoverServices(self.btServiceIds, function(err2, services) {
            if (services && services[0]) {
                services[0].discoverCharacteristics([], function(err, characteristics) {
                    //console.log("characteristics:", characteristics);
                    self._gmCh = null;
                    self._dev = null;
                    for (var i = 0; i < characteristics.length; i++) {
                        ch = characteristics[i];
                        console.log("ch.uuid", ch.uuid);
                        if (ch.uuid == "0000000200001000800000805f9b34fb") {
                            self._gmCh = ch;
                        }
                    }
                    if (self._gmCh) {
                        self._gmCh.write(new Buffer("012600", 'hex'));
                        self._gmCh.subscribe(function(){
                            self._dev = btPeripheral;
                            self._dev.connected = true;
                            self.connected = true;
                            self._dev.type = "bt";
                            self._gmCh.subscribe();
                            self._gmCh.on('data', function(data, isNotification) {
                                if(isNotification) {
                                    self._parseIncoming(data);
                                }
                            });
                            console.log("GenieMini: connected!");
                            self._init();
                            if (callback) callback(true);
                        });
                    } else {
                        btPeripheral.disconnect();
                        if (callback) callback(false);
                    }
                });
            } else {
                btPeripheral.disconnect();
                if (callback) callback(false);
            }

        });

        btPeripheral.once('disconnect', function() {
            console.log("GenieMini: disconnected");
            self._dev = null;
            self.connected = false;
            self.emit("status", self.getStatus());
        });

    });

}

GenieMini.prototype._init = function() {

}

GenieMini.prototype._parseIncoming = function(data) {
    var id = data.readUInt16LE(1);
    if(id == 0xB000) { // current state
        var state = data.readUInt8(5);
        var angle = data.readInt16LE(12);
        this._angle = angle;
        this._moving = (state == 0x01);
        if(this._currentMove != null && this._lastAngle != null) {
            if(Math.abs(angle - this._lastAngle) < 180) {
                this._currentMove += angle - this._lastAngle;
            } else {
                if(this._lastAngle < angle) {
                    this._currentMove += 360 - (angle - this._lastAngle);
                } else {
                    this._currentMove -= 360 - (this._lastAngle - angle);
                }
            }
        }
        this._lastAngle = angle;
    }
}

GenieMini.prototype.connect = function(device, callback) {
    if (device && device.connect) {
        console.log("GenieMini: connecting...");
        this._connectBt(device, callback);
    } else {
        console.log("GenieMini: invalid device, cannot connect");
        if (callback) callback("invalid device");
    }
}

GenieMini.prototype.disconnect = function() {
    if (this._dev && this._dev.connected) {
        this._dev.connected = false;
        this._dev.disconnect();
    } else {
        this._dev = null;
    }
    this.emit("status", this.getStatus());
}

GenieMini.prototype.getStatus = function() {
    var type = (this._dev && this._dev.type) ? this._dev.type : null;
    return {
        connected: this._dev && this._dev.connected,
        connectionType: type,
        motor1: true,
        motor1pos: this._position / this._stepsPerDegree,
    }
}

GenieMini.prototype.disable = function(motor) {
    this._enabled = false;
}

GenieMini.prototype.enable = function(motor) {
    this._enabled = true;
}

GenieMini.prototype.move = function(motor, degrees, callback) {
    if (this._moving) {
        if (callback) callback("GenieMini: motor already running");
        return console.log("GenieMini: motor already running");
    }
    var steps = degrees * this._stepsPerDegree;
    console.log("GenieMini: moving motor", steps, "steps");
    if(!_enabled) enable();

    var dataBuf = new Buffer(5);
    dataBuf.fill(0);
    if (steps < 0) {
        dataBuf[4] = 1;
        steps = 0 - steps;
    }
    dataBuf.writeUInt32BE(steps, 0, 4);
    this._moving = true;

    var self = this;
    self._write(0x005E, dataBuf, function(err) {
        if (!err) {
            var check = function() {
                setTimeout(function() {
                    if(self._moving === undefined) return;
                    if(self._moving) {
                        check(); // keep checking until stop
                    } else {
                        self._position += steps;
                        if (callback) callback(null, self._position);
                    }
                }, 200);
            }
            check();
        } else {
            if (callback) callback(err);
            self._moving = false;
        }
    });
}

GenieMini.prototype._write = function(command, dataBuf, callback) {
    var template = new Buffer("000000", 'hex');
    var len = dataBuf ? dataBuf.length : 0;
    var COMMAND = 0;

    template.writeUInt16LE(parseInt(command));

    var cmd;
    if (dataBuf) {
        cmd = Buffer.concat([template, dataBuf]);
    } else {
        cmd = template;
    }
}

GenieMini.prototype.constantMove = function(motor, speed, callback) {
    if (this._moving) return console.log("GenieMini: motor already running");
    console.log("GenieMini: moving motor", steps, "steps");
    if(!_enabled) enable();

    var dataBuf = new Buffer(3);
    dataBuf.fill(0);
    dataBuf.writeInt8(speed, 0, 1);
    dataBuf.writeUInt16LE(speed ? 0x01 : 0x00, 2, 2);
    this._moving = true;

    var self = this;
    if(this._endTimer) clearTimeout(this._endTimer);
    if(self._currentMove == null) {
        self._lastAngle = self._angle;
        self._currentMove = 0;
    }
    self._write(0x003F, dataBuf, function(err) {
        if (!err) {
            var check = function() {
                if(this._endTimer) clearTimeout(this._endTimer);
                if(!speed) {
                    self._endTimer = setTimeout(function() {
                        if(self._moving === undefined) return;
                        if(self._moving) {
                            check(); // keep checking until stop
                        } else {
                            self._position += self._currentMove * self._stepsPerDegree;
                            self._currentMove = null;
                            if (callback) callback(null, self._position);
                        }
                    }, 200);
                } else {
                    if (callback) callback(null, null);
                }
            }
            check();
        } else {
            if (callback) callback(err);
            self._moving = false;
        }
    });
}

GenieMini.prototype.resetMotorPosition = function(motor, callback) {
    var check = function() {
        if(self._moving) {
            setTimeout(check, 200); // keep checking until stop
        } else {
            self._position = 0;
            if (callback) callback(null, self._position);
        }
    }
    check();
}

module.exports = GenieMini;
<commit_msg>corrections<commit_after>var util = require('util');
var EventEmitter = require('events').EventEmitter;

function GenieMini() {
    this.btServiceIds = ['f000474d04514000b000000000000000'];

    this._gmCh = null;
    this._dev = null;
    this._moving = false;
    this._angle = null;
    this._position = 0;
    this._currentMove = null;
    this._stepsPerDegree = 186.56716418;
}

util.inherits(GenieMini, EventEmitter);

GenieMini.prototype._connectBt = function(btPeripheral, callback) {
    var self = this;
    btPeripheral.connect(function(err1) {
        if (err1) {
            if (callback) callback(false);
            return;
        }
        console.log('GenieMini: connecting via BLE');
        btPeripheral.discoverServices(self.btServiceIds, function(err2, services) {
            if (services && services[0]) {
                services[0].discoverCharacteristics([], function(err, characteristics) {
                    //console.log("characteristics:", characteristics);
                    self._gmCh = null;
                    self._dev = null;
                    for (var i = 0; i < characteristics.length; i++) {
                        ch = characteristics[i];
                        console.log("ch.uuid", ch.uuid);
                        if (ch.uuid == "2") {
                            self._gmCh = ch;
                        }
                    }
                    if (self._gmCh) {
                        self._gmCh.write(new Buffer("012600", 'hex'));
                        self._gmCh.subscribe(function(){
                            self._dev = btPeripheral;
                            self._dev.connected = true;
                            self.connected = true;
                            self._dev.type = "bt";
                            self._gmCh.subscribe();
                            self._gmCh.on('data', function(data, isNotification) {
                                if(isNotification) {
                                    self._parseIncoming(data);
                                }
                            });
                            console.log("GenieMini: connected!");
                            self._init();
                            if (callback) callback(true);
                        });
                    } else {
                        btPeripheral.disconnect();
                        if (callback) callback(false);
                    }
                });
            } else {
                btPeripheral.disconnect();
                if (callback) callback(false);
            }

        });

        btPeripheral.once('disconnect', function() {
            console.log("GenieMini: disconnected");
            self._dev = null;
            self.connected = false;
            self.emit("status", self.getStatus());
        });

    });

}

GenieMini.prototype._init = function() {

}

GenieMini.prototype._parseIncoming = function(data) {
    var id = data.readUInt16LE(1);
    if(id == 0xB000) { // current state
        var state = data.readUInt8(5);
        var angle = data.readInt16LE(12);
        this._angle = angle;
        this._moving = (state == 0x01);
        if(this._currentMove != null && this._lastAngle != null) {
            if(Math.abs(angle - this._lastAngle) < 180) {
                this._currentMove += angle - this._lastAngle;
            } else {
                if(this._lastAngle < angle) {
                    this._currentMove += 360 - (angle - this._lastAngle);
                } else {
                    this._currentMove -= 360 - (this._lastAngle - angle);
                }
            }
        }
        this._lastAngle = angle;
    }
}

GenieMini.prototype.connect = function(device, callback) {
    if (device && device.connect) {
        console.log("GenieMini: connecting...");
        this._connectBt(device, callback);
    } else {
        console.log("GenieMini: invalid device, cannot connect");
        if (callback) callback("invalid device");
    }
}

GenieMini.prototype.disconnect = function() {
    if (this._dev && this._dev.connected) {
        this._dev.connected = false;
        this._dev.disconnect();
    } else {
        this._dev = null;
    }
    this.emit("status", this.getStatus());
}

GenieMini.prototype.getStatus = function() {
    var type = (this._dev && this._dev.type) ? this._dev.type : null;
    return {
        connected: this._dev && this._dev.connected,
        connectionType: type,
        motor1: true,
        motor1pos: this._position / this._stepsPerDegree,
    }
}

GenieMini.prototype.disable = function(motor) {
    this._enabled = false;
}

GenieMini.prototype.enable = function(motor) {
    this._enabled = true;
}

GenieMini.prototype.move = function(motor, degrees, callback) {
    if (this._moving) {
        if (callback) callback("GenieMini: motor already running");
        return console.log("GenieMini: motor already running");
    }
    var steps = degrees * this._stepsPerDegree;
    console.log("GenieMini: moving motor", steps, "steps");
    if(!_enabled) enable();

    var dataBuf = new Buffer(5);
    dataBuf.fill(0);
    if (steps < 0) {
        dataBuf[4] = 1;
        steps = 0 - steps;
    }
    dataBuf.writeUInt32BE(steps, 0, 4);
    this._moving = true;

    var self = this;
    self._write(0x005E, dataBuf, function(err) {
        if (!err) {
            var check = function() {
                setTimeout(function() {
                    if(self._moving === undefined) return;
                    if(self._moving) {
                        check(); // keep checking until stop
                    } else {
                        self._position += steps;
                        if (callback) callback(null, self._position);
                    }
                }, 200);
            }
            check();
        } else {
            if (callback) callback(err);
            self._moving = false;
        }
    });
}

GenieMini.prototype._write = function(command, dataBuf, callback) {
    var template = new Buffer("000000", 'hex');
    var len = dataBuf ? dataBuf.length : 0;
    var COMMAND = 0;

    template.writeUInt16LE(parseInt(command));

    var cmd;
    if (dataBuf) {
        cmd = Buffer.concat([template, dataBuf]);
    } else {
        cmd = template;
    }
}

GenieMini.prototype.constantMove = function(motor, speed, callback) {
    if (this._moving) return console.log("GenieMini: motor already running");
    console.log("GenieMini: moving motor", steps, "steps");
    if(!_enabled) enable();

    var dataBuf = new Buffer(3);
    dataBuf.fill(0);
    dataBuf.writeInt8(speed, 0, 1);
    dataBuf.writeUInt16LE(speed ? 0x01 : 0x00, 2, 2);
    this._moving = true;

    var self = this;
    if(this._endTimer) clearTimeout(this._endTimer);
    if(self._currentMove == null) {
        self._lastAngle = self._angle;
        self._currentMove = 0;
    }
    self._write(0x003F, dataBuf, function(err) {
        if (!err) {
            var check = function() {
                if(this._endTimer) clearTimeout(this._endTimer);
                if(!speed) {
                    self._endTimer = setTimeout(function() {
                        if(self._moving === undefined) return;
                        if(self._moving) {
                            check(); // keep checking until stop
                        } else {
                            self._position += self._currentMove * self._stepsPerDegree;
                            self._currentMove = null;
                            if (callback) callback(null, self._position);
                        }
                    }, 200);
                } else {
                    if (callback) callback(null, null);
                }
            }
            check();
        } else {
            if (callback) callback(err);
            self._moving = false;
        }
    });
}

GenieMini.prototype.resetMotorPosition = function(motor, callback) {
    var check = function() {
        if(self._moving) {
            setTimeout(check, 200); // keep checking until stop
        } else {
            self._position = 0;
            if (callback) callback(null, self._position);
        }
    }
    check();
}

module.exports = GenieMini;
<|endoftext|>


<commit_before>'use strict';
const _ = require('lodash');

const SpeechBuilder = require('./../speechBuilder').SpeechBuilder;
/**
 * Class AlexaSpeechBuilder
 */
class AlexaSpeechBuilder extends SpeechBuilder {
    /**
     * @param {Jovo=} jovo instance
     * Constructor
     */
    constructor(jovo) {
        super(jovo);
    }
    /**
     * Adds audio tag to speech
     * @public
     * @param {string} url secure url to audio
     * @param {string} text
     * @param {boolean} condition
     * @param {float} probability
     * @return {SpeechBuilder}
     */
    addAudio(url, text, condition, probability) {
        // gets random element from array if url
        // is of type array
        if (_.isArray(url)) {
            let rand = Math.floor(Math.random() * url.length);
            url = url[rand];
        }
        return this.addText('<audio src="' + url + '"/>', condition, probability);
    }
}

module.exports.AlexaSpeechBuilder = AlexaSpeechBuilder;
<commit_msg>:bug: Fixed addAudio condition in Alexa speech builder<commit_after>'use strict';
const _ = require('lodash');

const SpeechBuilder = require('./../speechBuilder').SpeechBuilder;
/**
 * Class AlexaSpeechBuilder
 */
class AlexaSpeechBuilder extends SpeechBuilder {
    /**
     * @param {Jovo=} jovo instance
     * Constructor
     */
    constructor(jovo) {
        super(jovo);
    }
    /**
     * Adds audio tag to speech
     * @public
     * @param {string} url secure url to audio
     * @param {boolean} condition
     * @param {float} probability
     * @return {SpeechBuilder}
     */
    addAudio(url, condition, probability) {
        // gets random element from array if url
        // is of type array
        if (_.isArray(url)) {
            let rand = Math.floor(Math.random() * url.length);
            url = url[rand];
        }
        return this.addText('<audio src="' + url + '"/>', condition, probability);
    }
}

module.exports.AlexaSpeechBuilder = AlexaSpeechBuilder;
<|endoftext|>


<commit_before>(function() {
  require.config({
    urlArgs: "bust=" + (new Date()).getTime()
  });

  require(['main'], function(ice) {
    var displayMessage, messageElement, paletteElement;
    window.editor = new ice.Editor(document.getElementById('editor'), (function() {
      var _i, _len, _ref, _results;
      _ref = ['fd 100', 'bk 100', 'rt 90', 'lt 90', 'see \'hi\'', 'for i in [1..10]\n  fd 10', 'if touches \'red\'\n  fd 10', 'rtFd = (arg) ->\n  rt 90\n  fd arg\n  return arg'];
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        paletteElement = _ref[_i];
        _results.push(ice.parse(paletteElement).next.block);
      }
      return _results;
    })());
    editor.setValue('for i in [1..1000]\n  if i % 15 is 0\n    see \'fizzbuzz\'\n  else\n    if i % 5 is 0\n      see \'fizz\'\n    if i % 3 is 0\n      see \'buzz\'\n    if i % 3 isnt 0 and i % 5 isnt 0\n      see i');
    editor.onChange = function() {};
    editor.onChange();
    document.getElementById('undo').addEventListener('click', function() {
      return editor.undo();
    });
    messageElement = document.getElementById('message');
    displayMessage = function(text) {
      messageElement.style.display = 'inline';
      messageElement.innerText = text;
      return setTimeout((function() {
        return messageElement.style.display = 'none';
      }), 2000);
    };
    return document.getElementById('toggle').addEventListener('click', function() {
      if (!editor.toggleBlocks()) {
        if (!(editor.currentlyUsingBlocks || editor.currentlyAnimating)) {
          return displayMessage('Syntax error');
        }
      }
    });
    /*
    logsElement = document.getElementById 'logs'
    logsContentElement = document.getElementById 'logsContent'
    closeLogsElement = document.getElementById 'closeLogs'
    document.getElementById('run').addEventListener 'click', ->
      logs = []
      see = (arg) ->
        logs.push arg
      eval CoffeeScript.compile editor.getValue()
      see = null

      logsContentElement.innerText = logs.join '\n'
      logsElement.style.right = '0px'
      closeLogsElement.style.top = '30px'

    document.getElementById('closeLogs').addEventListener 'click', ->
      logsElement.style.right = '-500px'
      closeLogsElement.style.top = '0px'
    */

  });

}).call(this);

/*
//@ sourceMappingURL=example.js.map
*/<commit_msg>Oops, remove another compiled file<commit_after><|endoftext|>


<commit_before>
define([
    "tracemon.env.utils",
    "tracemon.env.config",
    "tracemon.env.languages.en",
    "tracemon.lib.jquery-amd",
    "tracemon.lib.d3-amd",
    "tracemon.lib.parsePrefix"
], function(utils, config, lang, $, d3, prefixUtils){

    var LocationView = function(env){
        var $this, aggregationBy;

        $this = this;
        this.nodes = {};
        this.edges = {};
        aggregationBy = "country";

        this._getLocationKey = function(host){

            if (!host.location){
                return host.getId();
            }

            switch(aggregationBy) {

                case "country":
                    return host.location["country"];
                    break;

                case "city":
                    return host.location["country"] + '-' + host.location["city"];
                    break;

                default:
                    throw "Select an aggregation"

            }

        };

        this._locatePrivateHosts = function(traceroutesToDraw){
            var traceroute, host, attempt, hostTmp, hop, lastLocatedHost, hops;

            var cagata1;

            for (var n=0,length=traceroutesToDraw.length; n<length; n++) {
                traceroute = traceroutesToDraw[n];
                hops = traceroute.getHops();
                lastLocatedHost = null;
                cagata1 = [];
                lastLocatedHost = traceroute.source;

                for (var n1=0,length1=hops.length; n1<length1; n1++) {

                    hop = hops[n1];
                    attempt = hop.getMainAttempt();
                    host = attempt.host;

                    cagata1.push(host);

                    if (host.location){ // This node has a location
                        lastLocatedHost = host;

                    } else if (lastLocatedHost){ // No location

                        for (var n2=n1; n2<length1; n2++) { // Find the next valid location
                            hostTmp = hops[n2].getMainAttempt().host;
                            if (hostTmp.location && hostTmp.location.country == lastLocatedHost.location.country) { // Its a cycle on the same location
                                host.location = lastLocatedHost.location;
                                break;
                            }
                        }
                    }
                }

                // console.log($.map(cagata1, function(item){return ((item.location) ? item.location.country : item.getId())}));
            }
        };

        this.draw = function(traceroutesToDraw, callback){
            console.log("Loading...");

            this._init(traceroutesToDraw, function () {
                var traceroute, host, attempt, nodeKey, previousNode, nodeObj;

                $this._locatePrivateHosts(traceroutesToDraw);
                for (var n=0,length=traceroutesToDraw.length; n<length; n++) {
                    traceroute = traceroutesToDraw[n];

                    nodeKey = $this._getLocationKey(traceroute.source);
                    if (!$this.nodes[nodeKey]) {
                        $this.nodes[nodeKey] = { hosts: {}, label: nodeKey, id: utils.getIdFromIp(nodeKey) };
                    }
                    $this.nodes[nodeKey]["hosts"][traceroute.source.getId()] = traceroute.source;
                    previousNode = $this.nodes[nodeKey];

                    nodeKey = traceroute.target.ip;
                    if (!$this.nodes[nodeKey]) {
                        $this.nodes[nodeKey] = { hosts: {}, label: nodeKey, id: utils.getIdFromIp(nodeKey) };
                    }
                    $this.nodes[nodeKey]["hosts"][traceroute.target.getId()] = traceroute.target;

                    traceroute.forEachHop(function(hop){
                        attempt = hop.getMainAttempt();
                        host = attempt.host;

                        if (host.ip != traceroute.target.ip) {
                            nodeKey = $this._getLocationKey(host);
                        } else {
                            nodeKey = traceroute.target.ip;
                        }

                        // nodeKey = $this._getLocationKey(host);

                        if (!$this.nodes[nodeKey]) {
                            $this.nodes[nodeKey] = {hosts: {}, label: nodeKey, id: utils.getIdFromIp(nodeKey)};
                        }
                        $this.nodes[nodeKey]["hosts"][host.getId()] = host;

                        nodeObj = $this.nodes[nodeKey];
                        if (previousNode && previousNode.id != nodeObj.id){ // check existence of previous node and remove cycles
                            $this.edges[previousNode.id + '-' + nodeObj.id] = [previousNode, nodeObj];
                        }
                        previousNode = nodeObj;
                    });

                    previousNode = null;
                }

                $this._drawPlain();
                callback();

                console.log("Loaded");
            });

        };

        this._init = function(traceroutesToDraw, callback){
            var traceroute, host, attempt, calls;

            calls = [];
            for (var n=0,length=traceroutesToDraw.length; n<length; n++){
                traceroute = traceroutesToDraw[n];

                calls.push(env.connector.getGeolocation(traceroute.source));
                traceroute.forEachHop(function(hop){
                    attempt = hop.getMainAttempt();
                    host = attempt.host;
                    calls.push(env.connector.getGeolocation(host));
                });

            }

            $.when
                .apply($, calls)
                .done(callback)
                .fail($this._onLoadingError);
        };

        this._onLoadingError = function(error){
            console.log("Loading error: " + error);
        };

        this._drawPlain = function(){
            var nodeObj, edgeObj;

            for (var node in this.nodes) {

                nodeObj = this.nodes[node];

                env.mainView.graph.setNode(nodeObj.id, {
                    label: nodeObj.label,
                    class: "type-" + nodeObj.id
                });

            }

            for (var edge in this.edges) {
                edgeObj = this.edges[edge];
                env.mainView.graph.setEdge(edgeObj[0].id, edgeObj[1].id, { lineInterpolate: 'basis' });
            }

        };
    };

    return LocationView;
});<commit_msg>removed debugging logs<commit_after>
define([
    "tracemon.env.utils",
    "tracemon.env.config",
    "tracemon.env.languages.en",
    "tracemon.lib.jquery-amd",
    "tracemon.lib.d3-amd",
    "tracemon.lib.parsePrefix"
], function(utils, config, lang, $, d3, prefixUtils){

    var LocationView = function(env){
        var $this, aggregationBy;

        $this = this;
        this.nodes = {};
        this.edges = {};
        aggregationBy = "country";

        this._getLocationKey = function(host){

            if (!host.location){
                return host.getId();
            }

            switch(aggregationBy) {

                case "country":
                    return host.location["country"];
                    break;

                case "city":
                    return host.location["country"] + '-' + host.location["city"];
                    break;

                default:
                    throw "Select an aggregation"

            }

        };

        this._locatePrivateHosts = function(traceroutesToDraw){
            var traceroute, host, attempt, hostTmp, hop, lastLocatedHost, hops;

            for (var n=0,length=traceroutesToDraw.length; n<length; n++) {
                traceroute = traceroutesToDraw[n];
                hops = traceroute.getHops();
                lastLocatedHost = null;
                lastLocatedHost = traceroute.source;

                for (var n1=0,length1=hops.length; n1<length1; n1++) {

                    hop = hops[n1];
                    attempt = hop.getMainAttempt();
                    host = attempt.host;

                    if (host.location){ // This node has a location
                        lastLocatedHost = host;

                    } else if (lastLocatedHost){ // No location

                        for (var n2=n1; n2<length1; n2++) { // Find the next valid location
                            hostTmp = hops[n2].getMainAttempt().host;
                            if (hostTmp.location && hostTmp.location.country == lastLocatedHost.location.country) { // Its a cycle on the same location
                                host.location = lastLocatedHost.location;
                                break;
                            }
                        }
                    }
                }

            }
        };

        this.draw = function(traceroutesToDraw, callback){
            console.log("Loading...");

            this._init(traceroutesToDraw, function () {
                var traceroute, host, attempt, nodeKey, previousNode, nodeObj;

                $this._locatePrivateHosts(traceroutesToDraw);
                for (var n=0,length=traceroutesToDraw.length; n<length; n++) {
                    traceroute = traceroutesToDraw[n];

                    nodeKey = $this._getLocationKey(traceroute.source);
                    if (!$this.nodes[nodeKey]) {
                        $this.nodes[nodeKey] = { hosts: {}, label: nodeKey, id: utils.getIdFromIp(nodeKey) };
                    }
                    $this.nodes[nodeKey]["hosts"][traceroute.source.getId()] = traceroute.source;
                    previousNode = $this.nodes[nodeKey];

                    nodeKey = traceroute.target.ip;
                    if (!$this.nodes[nodeKey]) {
                        $this.nodes[nodeKey] = { hosts: {}, label: nodeKey, id: utils.getIdFromIp(nodeKey) };
                    }
                    $this.nodes[nodeKey]["hosts"][traceroute.target.getId()] = traceroute.target;

                    traceroute.forEachHop(function(hop){
                        attempt = hop.getMainAttempt();
                        host = attempt.host;

                        if (host.ip != traceroute.target.ip) {
                            nodeKey = $this._getLocationKey(host);
                        } else {
                            nodeKey = traceroute.target.ip;
                        }

                        // nodeKey = $this._getLocationKey(host);

                        if (!$this.nodes[nodeKey]) {
                            $this.nodes[nodeKey] = {hosts: {}, label: nodeKey, id: utils.getIdFromIp(nodeKey)};
                        }
                        $this.nodes[nodeKey]["hosts"][host.getId()] = host;

                        nodeObj = $this.nodes[nodeKey];
                        if (previousNode && previousNode.id != nodeObj.id){ // check existence of previous node and remove cycles
                            $this.edges[previousNode.id + '-' + nodeObj.id] = [previousNode, nodeObj];
                        }
                        previousNode = nodeObj;
                    });

                    previousNode = null;
                }

                $this._drawPlain();
                callback();

                console.log("Loaded");
            });

        };

        this._init = function(traceroutesToDraw, callback){
            var traceroute, host, attempt, calls;

            calls = [];
            for (var n=0,length=traceroutesToDraw.length; n<length; n++){
                traceroute = traceroutesToDraw[n];

                calls.push(env.connector.getGeolocation(traceroute.source));
                traceroute.forEachHop(function(hop){
                    attempt = hop.getMainAttempt();
                    host = attempt.host;
                    calls.push(env.connector.getGeolocation(host));
                });

            }

            $.when
                .apply($, calls)
                .done(callback)
                .fail($this._onLoadingError);
        };

        this._onLoadingError = function(error){
            console.log("Loading error: " + error);
        };

        this._drawPlain = function(){
            var nodeObj, edgeObj;

            for (var node in this.nodes) {

                nodeObj = this.nodes[node];

                env.mainView.graph.setNode(nodeObj.id, {
                    label: nodeObj.label,
                    class: "type-" + nodeObj.id
                });

            }

            for (var edge in this.edges) {
                edgeObj = this.edges[edge];
                env.mainView.graph.setEdge(edgeObj[0].id, edgeObj[1].id, { lineInterpolate: 'basis' });
            }

        };
    };

    return LocationView;
});<|endoftext|>