<commit_before>var countAndOutputFormatIdx = 2;
var cyclesIdx = 3;

module.exports = function transformCSVResults(results) {
    var transformed = results.
        split('\n').
        map(function(x) {
            return x.
                split(',').
                map(function(innerX, i) {
                    if (i === countAndOutputFormatIdx) {
                        var els = innerX.
                            split(' ').
                            filter(function(x) { return x.length; }).
                            map(function(x) {
                                return x.replace(/ /g, '');
                            });

                        els[1] = els[1].substring(1, els[1].length - 1);

                        return {
                            test: els[0],
                            model: els[1].split(':')[0],
                            output: els[1].split(':')[1],
                            idx: +els[2]
                        };
                    }

                    return innerX;
                }).
                filter(function(item, i) {
                    return i === countAndOutputFormatIdx ||
                        i === cyclesIdx;
                });
        }).
        sort(function(a, b) {
            var info = a[0];
            var bInfo = b[0];
            if (info.model < bInfo.model) {
                return -1;
            }

            else if (info.model > bInfo.model) {
                return 1;
            }

            if (info.test < bInfo.test) {
                return -1;
            }

            else if (info.test > bInfo.test) {
                return 1;
            }

            if (info.output < bInfo.output) {
                return -1;
            }

            else if (info.output > bInfo.output) {
                return 1;
            }

            if (info.idx < bInfo.idx) {
                return -1;
            }

            if (info.idx < bInfo.idx) {
                return 1;
            }
            return 0;
        }).
        reduce(function(acc, x) {
            var group;
            var info = x[0];
            var model = info.model;
            var output = info.output;
            var test = info.test;

            if (acc.length === 0) {
                group = [];
                acc.push(group);
            } else {
                group = acc[acc.length - 1];
                var firstRes = group[0][0];

                if (firstRes.model !== model ||
                    firstRes.output !== output ||
                    firstRes.test !== test) {

                    group = [];
                    acc.push(group);
                }
            }

            group.push(x);
            return acc;
        }, []).
        reduce(function(acc, x) {
            x.forEach(function(infoAndCycles, i) {
                if (!acc[i + 1]) {
                    acc[i + 1] = [];
                }
                if (i === 0) {
                    acc[0].push(infoAndCycles[0].test);
                }

                acc[i + 1].push(infoAndCycles[1]);
            });
            return acc;
        }, [[]]).
        map(function(x) {
            return x.join(',');
        }).
        join('\n');

    return transformed;
};
<commit_msg>a better CSV outputter.<commit_after>var countAndOutputFormatIdx = 2;
var cyclesIdx = 3;

module.exports = function transformCSVResults(results) {
    var transformed = results.
        split('\n').
        map(function(x) {
            return x.
                split(',').
                map(function(innerX, i) {
                    if (i === countAndOutputFormatIdx) {
                        var els = innerX.
                            split(' ').
                            filter(function(x) { return x.length; }).
                            map(function(x) {
                                return x.replace(/ /g, '');
                            });

                        els[1] = els[1].substring(1, els[1].length - 1);

                        return {
                            test: els[0],
                            model: els[1].split(':')[0],
                            output: els[1].split(':')[1],
                            idx: +els[2]
                        };
                    }

                    return innerX;
                }).
                filter(function(item, i) {
                    return i === countAndOutputFormatIdx ||
                        i === cyclesIdx;
                });
        }).
        sort(function(a, b) {
            var info = a[0];
            var bInfo = b[0];
            if (info.model < bInfo.model) {
                return -1;
            }

            else if (info.model > bInfo.model) {
                return 1;
            }

            if (info.test < bInfo.test) {
                return -1;
            }

            else if (info.test > bInfo.test) {
                return 1;
            }

            if (info.output < bInfo.output) {
                return -1;
            }

            else if (info.output > bInfo.output) {
                return 1;
            }

            if (info.idx < bInfo.idx) {
                return -1;
            }

            if (info.idx < bInfo.idx) {
                return 1;
            }
            return 0;
        }).
        reduce(function(acc, x) {
            var group;
            var info = x[0];
            var model = info.model;
            var output = info.output;
            var test = info.test;

            if (acc.length === 0) {
                group = [];
                acc.push(group);
            } else {
                group = acc[acc.length - 1];
                var firstRes = group[0][0];

                if (firstRes.model !== model ||
                    firstRes.output !== output ||
                    firstRes.test !== test) {

                    group = [];
                    acc.push(group);
                }
            }

            group.push(x);
            return acc;
        }, []).
        reduce(function(acc, x) {
            x.forEach(function(infoAndCycles, i) {
                if (!acc[i + 2]) {
                    acc[i + 2] = [];
                }
                if (i === 0) {
                    acc[0].push(infoAndCycles[0].output);
                    acc[1].push(infoAndCycles[0].test);
                }

                acc[i + 2].push(infoAndCycles[1]);
            });
            return acc;
        }, [[], []]).
        map(function(x) {
            return x.join(',');
        }).
        join('\n');

    return transformed;
};
<|endoftext|>


<commit_before>'use strict';

var XpItem = require('../models/xpItem');
var itemTypes = require('../models/itemTypes');
var Build = require('../models/shipBuild');
var events = require('./events');
var headerView = require('../views/header');
var newView = require('../views/newView');
var mainView = require('../views/mainView');
var shipInfoView = require('../views/shipInfo');
var pilotSkillView = require('../views/pilotSkillView');
var changeShipView = require('../views/changeShipView');
var upgradesView = require('../views/upgradesView');
var xpHistoryView = require('../views/xpHistory');
var enemiesView = require('../views/enemiesView');
var messageView = require('../views/message');
var hashController = require('./urlHash');

var currentBuild;

module.exports = {
    init: function () {
        module.exports.bindNewViewEvents();
        module.exports.bindMainViewEvents();
        module.exports.bindOtherViewEvents();
        module.exports.bindModelEvents();

        headerView.init();
        mainView.init();
        newView.init();

        var urlHash = hashController.get();
        if (urlHash && urlHash.length > 0) {
            // We got a hash in URL, so create a build based on it
            var buildData = hashController.parseExportStringToHistory(urlHash);
            currentBuild = new Build(buildData.xpHistory, buildData.callsign, buildData.playerName);
            mainView.show();
            headerView.showButtons();
        } else {
            // No build provided via URL, so show new build form
            newView.show();
            headerView.hideButtons();
        }
    },
    bindNewViewEvents: function () {
        events.on('view.new.start', function (event, data) {
            var startingXpHistory = [
                new XpItem(itemTypes.STARTING_SHIP_TYPE, {
                    shipId: data.shipId
                })
            ];
            currentBuild = new Build(startingXpHistory, data.callsign, data.playerName);
            newView.hide();
            mainView.show();
            headerView.showButtons();
        });
    },
    bindMainViewEvents: function () {
        events.on('view.main.reset', function () {
            mainView.hide();
            newView.reset();
            newView.show();
            headerView.hideButtons();
            hashController.clear();
        });

        events.on('view.main.increasePs', function () {
            currentBuild.increasePilotSkill();
        });

        events.on('view.main.addMissionResults', function (event, xpAmount) {
            console.log('xpAmount', xpAmount);
            currentBuild.addMissionResults(xpAmount);
        });
    },
    bindOtherViewEvents: function () {
        events.on('view.upgrades.buy', function (event, upgradeId) {
            currentBuild.buyUpgrade(upgradeId);
        });

        events.on('view.pilotAbilities.buy', function (event, pilotId) {
            currentBuild.buyPilotAbility(pilotId);
        });

        events.on('view.changeShip.changeShip', function (event, shipId) {
            currentBuild.changeShip(shipId);
        });

        events.on('view.xpHistory.revert', function (event, xpItemIndex) {
            // Get the XP items up to the point specified
            var newHistory = [];
            for (var i = 0; i <= xpItemIndex; i++) {
                newHistory.push(currentBuild.xpHistory[i]);
            }
            // trash the existing build and start a new one with the new history
            currentBuild = new Build(newHistory, currentBuild.callsign, currentBuild.playerName);
            mainView.resetTabs();
        });

        events.on('view.enemies.adjustNumber', function (event, data) {
            currentBuild.adjustEnemies(data.xws, data.amount);
        });
    },
    bindModelEvents: function () {
        events.on('model.build.ready', function (event, build) {
            mainView.renderTitle(build);
            mainView.renderXp(build.currentXp);
            shipInfoView.renderShipStats(build.currentShip);
            shipInfoView.renderShipActions(build.currentShip, build.upgrades);
            shipInfoView.renderShipImage(build.currentShip);
            shipInfoView.renderShipDial(build.currentShip);
            upgradesView.renderShipUpgrades(build.currentShip, build.pilotSkill, build.upgrades);
            pilotSkillView.renderWithPs(build.pilotSkill, build.currentXp);
            upgradesView.renderUpgradesList(build);
            xpHistoryView.renderTable(build);
            changeShipView.renderShipView(build.pilotSkill, build.currentShip, build.currentXp);
            enemiesView.renderTable();
            messageView.clear();
            var newHash = hashController.generateExportString(build);
            hashController.set(newHash);
        });

        events.on('model.build.currentShip.update', function (event, build) {
            if (build.ready) {
                mainView.renderTitle(build);
                shipInfoView.renderShipStats(build.currentShip);
                shipInfoView.renderShipActions(build.currentShip, build.upgrades);
                shipInfoView.renderShipImage(build.currentShip);
                shipInfoView.renderShipDial(build.currentShip);
                upgradesView.renderShipUpgrades(build.currentShip, build.pilotSkill, build.upgrades);
                upgradesView.renderUpgradesList(build);
                changeShipView.renderShipView(build.pilotSkill, build.currentShip, build.currentXp);
            }
        });

        events.on('model.build.pilotSkill.update', function (event, build) {
            if (build.ready) {
                pilotSkillView.renderWithPs(build.pilotSkill, build.currentXp);
                upgradesView.renderUpgradesList(build);
                changeShipView.renderShipView(build.pilotSkill, build.currentShip, build.currentXp);
                upgradesView.renderShipUpgrades(build.currentShip, build.pilotSkill, build.upgrades);
            }
        });

        events.on('model.build.xp.update', function (event, build) {
            mainView.renderXp(build.currentXp);
            changeShipView.renderShipView(build.pilotSkill, build.currentShip, build.currentXp);
            pilotSkillView.renderWithPs(build.pilotSkill, build.currentXp);
        });

        events.on('model.build.upgrades.update', function (event, build) {
            if (build.ready) {
                upgradesView.renderUpgradesList(build);
                shipInfoView.renderShipActions(build.currentShip, build.upgrades);
                upgradesView.renderShipUpgrades(build.currentShip, build.pilotSkill, build.upgrades);
            }
        });

        events.on('model.build.pilotAbilities.update', function (event, build) {
            if (build.ready) {
                upgradesView.renderUpgradesList(build);
            }
        });

        events.on('model.build.xpHistory.add', function (event, data) {
            if (data.build.ready) {
                var xpItemIndex = data.build.xpHistory.length - 1;
                xpHistoryView.renderTableRow(data.xpItem, data.build.currentXp, xpItemIndex);
                messageView.renderMessage(data.xpItem, xpItemIndex);
                var newHash = hashController.generateExportString(data.build);
                hashController.set(newHash);
            }
        });

        events.on('model.build.enemies.change', function (event, enemiesData) {
            enemiesView.renderTable(enemiesData);
        });
    }
};
<commit_msg>remove console.log<commit_after>'use strict';

var XpItem = require('../models/xpItem');
var itemTypes = require('../models/itemTypes');
var Build = require('../models/shipBuild');
var events = require('./events');
var headerView = require('../views/header');
var newView = require('../views/newView');
var mainView = require('../views/mainView');
var shipInfoView = require('../views/shipInfo');
var pilotSkillView = require('../views/pilotSkillView');
var changeShipView = require('../views/changeShipView');
var upgradesView = require('../views/upgradesView');
var xpHistoryView = require('../views/xpHistory');
var enemiesView = require('../views/enemiesView');
var messageView = require('../views/message');
var hashController = require('./urlHash');

var currentBuild;

module.exports = {
    init: function () {
        module.exports.bindNewViewEvents();
        module.exports.bindMainViewEvents();
        module.exports.bindOtherViewEvents();
        module.exports.bindModelEvents();

        headerView.init();
        mainView.init();
        newView.init();

        var urlHash = hashController.get();
        if (urlHash && urlHash.length > 0) {
            // We got a hash in URL, so create a build based on it
            var buildData = hashController.parseExportStringToHistory(urlHash);
            currentBuild = new Build(buildData.xpHistory, buildData.callsign, buildData.playerName);
            mainView.show();
            headerView.showButtons();
        } else {
            // No build provided via URL, so show new build form
            newView.show();
            headerView.hideButtons();
        }
    },
    bindNewViewEvents: function () {
        events.on('view.new.start', function (event, data) {
            var startingXpHistory = [
                new XpItem(itemTypes.STARTING_SHIP_TYPE, {
                    shipId: data.shipId
                })
            ];
            currentBuild = new Build(startingXpHistory, data.callsign, data.playerName);
            newView.hide();
            mainView.show();
            headerView.showButtons();
        });
    },
    bindMainViewEvents: function () {
        events.on('view.main.reset', function () {
            mainView.hide();
            newView.reset();
            newView.show();
            headerView.hideButtons();
            hashController.clear();
        });

        events.on('view.main.increasePs', function () {
            currentBuild.increasePilotSkill();
        });

        events.on('view.main.addMissionResults', function (event, xpAmount) {
            currentBuild.addMissionResults(xpAmount);
        });
    },
    bindOtherViewEvents: function () {
        events.on('view.upgrades.buy', function (event, upgradeId) {
            currentBuild.buyUpgrade(upgradeId);
        });

        events.on('view.pilotAbilities.buy', function (event, pilotId) {
            currentBuild.buyPilotAbility(pilotId);
        });

        events.on('view.changeShip.changeShip', function (event, shipId) {
            currentBuild.changeShip(shipId);
        });

        events.on('view.xpHistory.revert', function (event, xpItemIndex) {
            // Get the XP items up to the point specified
            var newHistory = [];
            for (var i = 0; i <= xpItemIndex; i++) {
                newHistory.push(currentBuild.xpHistory[i]);
            }
            // trash the existing build and start a new one with the new history
            currentBuild = new Build(newHistory, currentBuild.callsign, currentBuild.playerName);
            mainView.resetTabs();
        });

        events.on('view.enemies.adjustNumber', function (event, data) {
            currentBuild.adjustEnemies(data.xws, data.amount);
        });
    },
    bindModelEvents: function () {
        events.on('model.build.ready', function (event, build) {
            mainView.renderTitle(build);
            mainView.renderXp(build.currentXp);
            shipInfoView.renderShipStats(build.currentShip);
            shipInfoView.renderShipActions(build.currentShip, build.upgrades);
            shipInfoView.renderShipImage(build.currentShip);
            shipInfoView.renderShipDial(build.currentShip);
            upgradesView.renderShipUpgrades(build.currentShip, build.pilotSkill, build.upgrades);
            pilotSkillView.renderWithPs(build.pilotSkill, build.currentXp);
            upgradesView.renderUpgradesList(build);
            xpHistoryView.renderTable(build);
            changeShipView.renderShipView(build.pilotSkill, build.currentShip, build.currentXp);
            enemiesView.renderTable();
            messageView.clear();
            var newHash = hashController.generateExportString(build);
            hashController.set(newHash);
        });

        events.on('model.build.currentShip.update', function (event, build) {
            if (build.ready) {
                mainView.renderTitle(build);
                shipInfoView.renderShipStats(build.currentShip);
                shipInfoView.renderShipActions(build.currentShip, build.upgrades);
                shipInfoView.renderShipImage(build.currentShip);
                shipInfoView.renderShipDial(build.currentShip);
                upgradesView.renderShipUpgrades(build.currentShip, build.pilotSkill, build.upgrades);
                upgradesView.renderUpgradesList(build);
                changeShipView.renderShipView(build.pilotSkill, build.currentShip, build.currentXp);
            }
        });

        events.on('model.build.pilotSkill.update', function (event, build) {
            if (build.ready) {
                pilotSkillView.renderWithPs(build.pilotSkill, build.currentXp);
                upgradesView.renderUpgradesList(build);
                changeShipView.renderShipView(build.pilotSkill, build.currentShip, build.currentXp);
                upgradesView.renderShipUpgrades(build.currentShip, build.pilotSkill, build.upgrades);
            }
        });

        events.on('model.build.xp.update', function (event, build) {
            mainView.renderXp(build.currentXp);
            changeShipView.renderShipView(build.pilotSkill, build.currentShip, build.currentXp);
            pilotSkillView.renderWithPs(build.pilotSkill, build.currentXp);
        });

        events.on('model.build.upgrades.update', function (event, build) {
            if (build.ready) {
                upgradesView.renderUpgradesList(build);
                shipInfoView.renderShipActions(build.currentShip, build.upgrades);
                upgradesView.renderShipUpgrades(build.currentShip, build.pilotSkill, build.upgrades);
            }
        });

        events.on('model.build.pilotAbilities.update', function (event, build) {
            if (build.ready) {
                upgradesView.renderUpgradesList(build);
            }
        });

        events.on('model.build.xpHistory.add', function (event, data) {
            if (data.build.ready) {
                var xpItemIndex = data.build.xpHistory.length - 1;
                xpHistoryView.renderTableRow(data.xpItem, data.build.currentXp, xpItemIndex);
                messageView.renderMessage(data.xpItem, xpItemIndex);
                var newHash = hashController.generateExportString(data.build);
                hashController.set(newHash);
            }
        });

        events.on('model.build.enemies.change', function (event, enemiesData) {
            enemiesView.renderTable(enemiesData);
        });
    }
};
<|endoftext|>


<commit_before>/**
 * This file is part of Superdesk.
 *
 * Copyright 2013, 2014 Sourcefabric z.u. and contributors.
 *
 * For the full copyright and license information, please see the
 * AUTHORS and LICENSE files distributed with this source code, or
 * at https://www.sourcefabric.org/superdesk/license
 */

(function() {

    'use strict';

    PackagesService.$inject = ['api', '$q'];
    function PackagesService(api, $q) {
        var currentPackage = null;

        this.fetch = function(packageId) {
            return api.find('packages', packageId).then(function(result) {
                currentPackage = result;
                return result;
            });
        };

        function getGroupFor(item, idRef) {
            var refs = [];
            if (item) {
                refs.push({
                    headline: item.headline || '',
                    residRef: item._id,
                    location: 'archive',
                    slugline: item.slugline || '',
                    renditions: item.renditions || {}
                });
            }
            return {
                refs: refs,
                id: idRef,
                role: 'grpRole:' + idRef
            };
        }

        function getReferenceFor(item) {
            return {
                headline: item.headline || '',
                residRef: item._id,
                location: 'archive',
                slugline: item.slugline || '',
                renditions: item.renditions || {}
            };
        }

        this.createPackageFromItems = function createPackageFromItems(items) {
            var idRef = 'main';
            var item = items[0];
            var new_package = {
                headline: item.headline || item.description || '',
                slugline: item.slugline || '',
                description: item.description || '',
                state: 'draft'
            };
            var groups = [{
                role: 'grpRole:NEP',
                refs: [{idRef: idRef}],
                id: 'root'
            }];
            _.forEach(items, function(item) {
                groups.push(getGroupFor(item, idRef));
            });

            new_package.groups = groups;
            return api.packages.save(new_package);
        };

        this.createEmptyPackage = function createEmptyPackage() {
            var idRef = 'main';
            var new_package = {
                headline: '',
                slugline: '',
                description: '',
                groups: [
                    {
                    role: 'grpRole:NEP',
                    refs: [{idRef: idRef}],
                    id: 'root'
                },
                getGroupFor(null, idRef)
                ]
            };

            return api.packages.save(new_package);
        };

        this.addItemsToPackage = function addToPackage(items, groupId) {
            var patch = {groups: _.cloneDeep(currentPackage.groups)};
            var targetGroup = _.find(patch.groups, function(group) { return group.id.toLowerCase() === groupId.toLowerCase(); });

            if (!targetGroup) {
                var rootGroup = _.find(patch.groups, function(group) { return group.id === 'root'; });
                rootGroup.refs.push({idRef: groupId});
                targetGroup = {
                    refs: [],
                    id: groupId,
                    role: 'grpRole:' + groupId
                };
                patch.groups.push(targetGroup);
            }
            _.forEach(items, function(item) {
                targetGroup.refs.push(getReferenceFor(item));
            });
            return api.packages.save(currentPackage, patch);
        };

        this.removeItem = function removeItem(item) {
            var patch = {groups: _.cloneDeep(currentPackage.groups)};

            _.forEach(patch.groups, function(group) {
                _.remove(group.refs, function(ref_item) {
                    return ref_item.guid === item.guid;
                });
            });
            _.remove(patch.groups, function(group) {
                return group.id !== 'root' && group.refs.length === 0;
            });

            var rootGroup = _.find(patch.groups, function(group) { return group.id === 'root'; });
            rootGroup.refs = [];
            _.forEach(patch.groups, function(group) {
                if (group.id !== 'root') {
                    rootGroup.refs.push({idRef: group.id});
                }
            });
            return api.packages.save(currentPackage, patch);
        };
    }

    PackagingCtrl.$inject = ['$scope', 'packagesService', 'superdesk', '$route', 'api', 'search', 'ContentCtrl'];
    function PackagingCtrl($scope, packagesService, superdesk, $route, api, search, ContentCtrl) {

        $scope.widget_target = 'packages';
        $scope.content = new ContentCtrl($scope);

        function fetchItem() {
            packagesService.fetch($route.current.params._id).
                then(function(fetched_package) {
                $scope.item = fetched_package;
            });
        }

        $scope.remove = function removeItem(obj) {
            packagesService.removeItem(obj.item);
        };

        fetchItem();
    }

    SearchWidgetCtrl.$inject = ['$scope', 'packagesService', 'api', 'search'];
    function SearchWidgetCtrl($scope, packagesService, api, search) {

        $scope.selected = null;
        var packageItems = null;

        $scope.itemTypes = [
            {
                icon: 'text',
                label: 'Main'
            },
            {
                icon: 'text',
                label: 'Story'
            },
            {
                icon: 'text',
                label: 'Sidebar'

            },
            {
                icon: 'text',
                label: 'Fact box'
            }
        ];

        function fetchContentItems(q) {
            var query = search.query(q || null);
            query.size(25);
            api.archive.query(query.getCriteria(true))
            .then(function(result) {
                $scope.contentItems = result._items;
            });
        }

        $scope.$watch('query', function(query) {
            fetchContentItems(query);
        });

        $scope.$watch('item.groups', function() {
            getPackageItems();
        }, true);

        $scope.addItemToGroup = function addItemsToGroup(groupId, item) {
            packagesService.addItemsToPackage([item], groupId.label.toLowerCase())
            .then(function() {
                getPackageItems();
            });
        };

        fetchContentItems();

        $scope.preview = function(item) {
            $scope.selected = item;
        };

        function getPackageItems() {
            var items = [];
            if ($scope.item.groups) {
                _.each($scope.item.groups, function(group) {
                    if (group.id !== 'root') {
                        _.each(group.refs, function(item) {
                            items.push(item.guid);
                        });
                    }
                });
            }
            packageItems = items;
        }

        $scope.itemInPackage = function(item) {
            return _.indexOf(packageItems, item.guid) > -1;
        };
    }

    function PreventPreviewDirective() {
        return {
            link: function(scope, el) {
                el.bind('click', previewOnClick);

                scope.$on('$destroy', function() {
                    el.unbind('click', previewOnClick);
                });

                function previewOnClick(event) {
                    if ($(event.target).closest('.group-select').length === 0) {
                        scope.$apply(function() {
                            scope.preview(scope.pitem);
                        });
                    }
                }
            }
        };
    }

    var app = angular.module('superdesk.packaging', [
        'superdesk.activity',
        'superdesk.api'
    ]);

    app
    .service('packagesService', PackagesService)
    .directive('sdWidgetPreventPreview', PreventPreviewDirective)
    .config(['superdeskProvider', function(superdesk) {
        superdesk
        .activity('create.package', {
            label: gettext('Create package'),
            controller: ['data', '$location', 'packagesService', 'superdesk', 'workqueue',
                function(data, $location, packagesService, superdesk, workqueue) {
                    if (data) {
                        packagesService.createPackageFromItems(data.items).then(
                            function(new_package) {
                            workqueue.add(new_package);
                            superdesk.intent('author', 'package', new_package);
                        });
                    } else {
                        packagesService.createEmptyPackage().then(
                            function(new_package) {
                            workqueue.add(new_package);
                            superdesk.intent('author', 'package', new_package);
                        });
                    }
                }],
                filters: [
                    {action: 'create', type: 'package'}
                ]
        })
        .activity('packaging', {
            when: '/packaging/:_id',
            label: gettext('Packaging'),
            templateUrl: 'scripts/superdesk-packaging/views/packaging.html',
            topTemplateUrl: 'scripts/superdesk-dashboard/views/workspace-topnav.html',
            controller: PackagingCtrl,
            filters: [{action: 'author', type: 'package'}]
        })
        .activity('edit.package', {
            label: gettext('Edit package'),
            priority: 10,
            icon: 'pencil',
            controller: ['data', '$location', 'superdesk', 'workqueue', function(data, $location, superdesk, workqueue) {
                workqueue.add(data.item);
                superdesk.intent('author', 'package', data.item);
            }],
            filters: [
                {action: 'list', type: 'archive'}
            ],
            condition: function(item) {
                return item.type === 'composite';
            }
        });
    }])
    .config(['apiProvider', function(apiProvider) {
        apiProvider.api('packages', {
            type: 'http',
            backend: {rel: 'packages'}
        });
    }])
    .config(['authoringWidgetsProvider', function(authoringWidgetsProvider) {
        authoringWidgetsProvider
            .widget('search', {
                icon: 'view',
                label: gettext('Search'),
                template: 'scripts/superdesk-packaging/views/search.html',
                side: 'left',
                extended: true,
                display: {authoring: true, packages: true}
            });
    }])
    .controller('SearchWidgetCtrl', SearchWidgetCtrl);

    return app;
})();
<commit_msg>feat(packages) - add package item action in the content list<commit_after>/**
 * This file is part of Superdesk.
 *
 * Copyright 2013, 2014 Sourcefabric z.u. and contributors.
 *
 * For the full copyright and license information, please see the
 * AUTHORS and LICENSE files distributed with this source code, or
 * at https://www.sourcefabric.org/superdesk/license
 */

(function() {

    'use strict';

    PackagesService.$inject = ['api', '$q'];
    function PackagesService(api, $q) {
        var currentPackage = null;

        this.fetch = function(packageId) {
            return api.find('packages', packageId).then(function(result) {
                currentPackage = result;
                return result;
            });
        };

        function getGroupFor(item, idRef) {
            var refs = [];
            if (item) {
                refs.push({
                    headline: item.headline || '',
                    residRef: item._id,
                    location: 'archive',
                    slugline: item.slugline || '',
                    renditions: item.renditions || {}
                });
            }
            return {
                refs: refs,
                id: idRef,
                role: 'grpRole:' + idRef
            };
        }

        function getReferenceFor(item) {
            return {
                headline: item.headline || '',
                residRef: item._id,
                location: 'archive',
                slugline: item.slugline || '',
                renditions: item.renditions || {}
            };
        }

        this.createPackageFromItems = function createPackageFromItems(items) {
            var idRef = 'main';
            var item = items[0];
            var new_package = {
                headline: item.headline || item.description || '',
                slugline: item.slugline || '',
                description: item.description || '',
                state: 'draft'
            };
            var groups = [{
                role: 'grpRole:NEP',
                refs: [{idRef: idRef}],
                id: 'root'
            }];
            _.forEach(items, function(item) {
                groups.push(getGroupFor(item, idRef));
            });

            new_package.groups = groups;
            return api.packages.save(new_package);
        };

        this.createEmptyPackage = function createEmptyPackage() {
            var idRef = 'main';
            var new_package = {
                headline: '',
                slugline: '',
                description: '',
                groups: [
                    {
                    role: 'grpRole:NEP',
                    refs: [{idRef: idRef}],
                    id: 'root'
                },
                getGroupFor(null, idRef)
                ]
            };

            return api.packages.save(new_package);
        };

        this.addItemsToPackage = function addToPackage(items, groupId) {
            var patch = {groups: _.cloneDeep(currentPackage.groups)};
            var targetGroup = _.find(patch.groups, function(group) { return group.id.toLowerCase() === groupId.toLowerCase(); });

            if (!targetGroup) {
                var rootGroup = _.find(patch.groups, function(group) { return group.id === 'root'; });
                rootGroup.refs.push({idRef: groupId});
                targetGroup = {
                    refs: [],
                    id: groupId,
                    role: 'grpRole:' + groupId
                };
                patch.groups.push(targetGroup);
            }
            _.forEach(items, function(item) {
                targetGroup.refs.push(getReferenceFor(item));
            });
            return api.packages.save(currentPackage, patch);
        };

        this.removeItem = function removeItem(item) {
            var patch = {groups: _.cloneDeep(currentPackage.groups)};

            _.forEach(patch.groups, function(group) {
                _.remove(group.refs, function(ref_item) {
                    return ref_item.guid === item.guid;
                });
            });
            _.remove(patch.groups, function(group) {
                return group.id !== 'root' && group.refs.length === 0;
            });

            var rootGroup = _.find(patch.groups, function(group) { return group.id === 'root'; });
            rootGroup.refs = [];
            _.forEach(patch.groups, function(group) {
                if (group.id !== 'root') {
                    rootGroup.refs.push({idRef: group.id});
                }
            });
            return api.packages.save(currentPackage, patch);
        };
    }

    PackagingCtrl.$inject = ['$scope', 'packagesService', 'superdesk', '$route', 'api', 'search', 'ContentCtrl'];
    function PackagingCtrl($scope, packagesService, superdesk, $route, api, search, ContentCtrl) {

        $scope.widget_target = 'packages';
        $scope.content = new ContentCtrl($scope);

        function fetchItem() {
            packagesService.fetch($route.current.params._id).
                then(function(fetched_package) {
                $scope.item = fetched_package;
            });
        }

        $scope.remove = function removeItem(obj) {
            packagesService.removeItem(obj.item);
        };

        fetchItem();
    }

    SearchWidgetCtrl.$inject = ['$scope', 'packagesService', 'api', 'search'];
    function SearchWidgetCtrl($scope, packagesService, api, search) {

        $scope.selected = null;
        var packageItems = null;

        $scope.itemTypes = [
            {
                icon: 'text',
                label: 'Main'
            },
            {
                icon: 'text',
                label: 'Story'
            },
            {
                icon: 'text',
                label: 'Sidebar'

            },
            {
                icon: 'text',
                label: 'Fact box'
            }
        ];

        function fetchContentItems(q) {
            var query = search.query(q || null);
            query.size(25);
            api.archive.query(query.getCriteria(true))
            .then(function(result) {
                $scope.contentItems = result._items;
            });
        }

        $scope.$watch('query', function(query) {
            fetchContentItems(query);
        });

        $scope.$watch('item.groups', function() {
            getPackageItems();
        }, true);

        $scope.addItemToGroup = function addItemsToGroup(groupId, item) {
            packagesService.addItemsToPackage([item], groupId.label.toLowerCase())
            .then(function() {
                getPackageItems();
            });
        };

        fetchContentItems();

        $scope.preview = function(item) {
            $scope.selected = item;
        };

        function getPackageItems() {
            var items = [];
            if ($scope.item.groups) {
                _.each($scope.item.groups, function(group) {
                    if (group.id !== 'root') {
                        _.each(group.refs, function(item) {
                            items.push(item.guid);
                        });
                    }
                });
            }
            packageItems = items;
        }

        $scope.itemInPackage = function(item) {
            return _.indexOf(packageItems, item.guid) > -1;
        };
    }

    function PreventPreviewDirective() {
        return {
            link: function(scope, el) {
                el.bind('click', previewOnClick);

                scope.$on('$destroy', function() {
                    el.unbind('click', previewOnClick);
                });

                function previewOnClick(event) {
                    if ($(event.target).closest('.group-select').length === 0) {
                        scope.$apply(function() {
                            scope.preview(scope.pitem);
                        });
                    }
                }
            }
        };
    }

    var app = angular.module('superdesk.packaging', [
        'superdesk.activity',
        'superdesk.api'
    ]);

    app
    .service('packagesService', PackagesService)
    .directive('sdWidgetPreventPreview', PreventPreviewDirective)
    .config(['superdeskProvider', function(superdesk) {
        superdesk
        .activity('create.package', {
            label: gettext('Create package'),
            controller: ['data', 'packagesService', 'superdesk', 'workqueue',
                function(data, packagesService, superdesk, workqueue) {
                    if (data) {
                        packagesService.createPackageFromItems(data.items).then(
                            function(new_package) {
                            workqueue.add(new_package);
                            superdesk.intent('author', 'package', new_package);
                        });
                    } else {
                        packagesService.createEmptyPackage().then(
                            function(new_package) {
                            workqueue.add(new_package);
                            superdesk.intent('author', 'package', new_package);
                        });
                    }
                }],
                filters: [
                    {action: 'create', type: 'package'}
                ]
        })
        .activity('packaging', {
            when: '/packaging/:_id',
            label: gettext('Packaging'),
            templateUrl: 'scripts/superdesk-packaging/views/packaging.html',
            topTemplateUrl: 'scripts/superdesk-dashboard/views/workspace-topnav.html',
            controller: PackagingCtrl,
            filters: [{action: 'author', type: 'package'}]
        })
        .activity('edit.package', {
            label: gettext('Edit package'),
            priority: 10,
            icon: 'pencil',
            controller: ['data', 'superdesk', 'workqueue', function(data, superdesk, workqueue) {
                workqueue.add(data.item);
                superdesk.intent('author', 'package', data.item);
            }],
            filters: [
                {action: 'list', type: 'archive'}
            ],
            condition: function(item) {
                return item.type === 'composite';
            }
        })
        .activity('package.item', {
            label: gettext('Package item'),
            priority: 5,
            icon: 'archive',
            controller: ['data', 'packagesService', 'superdesk', function(data, packagesService, superdesk) {
                packagesService.createPackageFromItems([data.item]).then(
                        function(new_package) {
                        superdesk.intent('author', 'package', new_package);
                    });
            }],
            filters: [
                {action: 'list', type: 'archive'}
            ]
        });

    }])
    .config(['apiProvider', function(apiProvider) {
        apiProvider.api('packages', {
            type: 'http',
            backend: {rel: 'packages'}
        });
    }])
    .config(['authoringWidgetsProvider', function(authoringWidgetsProvider) {
        authoringWidgetsProvider
            .widget('search', {
                icon: 'view',
                label: gettext('Search'),
                template: 'scripts/superdesk-packaging/views/search.html',
                side: 'left',
                extended: true,
                display: {authoring: true, packages: true}
            });
    }])
    .controller('SearchWidgetCtrl', SearchWidgetCtrl);

    return app;
})();
<|endoftext|>


<commit_before>module("baidu.dom.query")

test('1 param',function(){
	expect(11);
	var div = document.createElement('div');
	var a = document.createElement('a');
	var a2 = document.createElement('a');
	var div2 = document.createElement('div');
	var input = document.createElement('input');
	document.body.appendChild(div);
	document.body.appendChild(a);
	div.appendChild(a2);
	div.appendChild(div2);
	div.appendChild(input);
	input.disabled = 'disabled';
	div.id = 'comId';
//	a.id = 'comId';/*多个相同的id是不允许的*/
	div.className = 'class';
	div2.className = 'class';
	a2.className = 'class';
	var result = baidu.dom.query('a');
	equal(result.length,2,'2 results of a');
	equal(result[0],a2,'result 1 a');
	equal(result[1],a,'result 2 a2');
	result = baidu.dom.query('#comId');//id
	equal(result.length,1,'1 results of id comId');
	equal(result[0],div,'id comId div');

	result = baidu.dom.query('.class');//className
	equal(result.length,3,'length 3');
	equal(result[0],div,'class div');
	equal(result[1],a2,'class a2');
	equal(result[2],div2,'class div2');

	result = baidu.dom.query('input:disabled');
	equal(result.length,1,'1 result of input');
	equal(result[0],input,'input disabled');
	document.body.removeChild(div);
	document.body.removeChild(a);
})

test('2 params',function(){
	var div = document.createElement('div');
	var a = document.createElement('a');
	var a2 = document.createElement('a');
	var div2 = document.createElement('div');
	document.body.appendChild(div);
	document.body.appendChild(a);
	div.appendChild(a2);
	div.appendChild(div2);
	var result = baidu.dom.query('a',div);
	equal(result.length,1,'2 results of a');
	equal(result[0],a2,'result 1 a');
//	equal(result[1],a,'result 2 a2');

	document.body.removeChild(div);
	document.body.removeChild(a);
})<commit_msg>更新query用例<commit_after>module("baidu.dom.query");

// test('1 param', function() {
// expect(11);
// var div = document.createElement('div');
// var a = document.createElement('a');
// var a2 = document.createElement('a');
// var div2 = document.createElement('div');
// var input = document.createElement('input');
// document.body.appendChild(div);
// document.body.appendChild(a);
// div.appendChild(a2);
// div.appendChild(div2);
// div.appendChild(input);
// input.disabled = 'disabled';
// div.id = 'comId';
// // a.id = 'comId';/*多个相同的id是不允许的*/
// div.className = 'class';
// div2.className = 'class';
// a2.className = 'class';
// var result = baidu.dom.query('a');
// ok(result.length >= 2, '2 results of a');//根据标签查找的结果可能因页面而产生变化
// equal(result[1], a2, 'result 1 a');
// equal(result[0], a, 'result 2 a2');
// result = baidu.dom.query('#comId');// id
// equal(result.length, 1, '1 results of id comId');
// equal(result[0], div, 'id comId div');
//
// result = baidu.dom.query('.class');// className
// equal(result.length, 3, 'length 3');
// equal(result[0], div, 'class div');
// equal(result[1], a2, 'class a2');
// equal(result[2], div2, 'class div2');
//
// result = baidu.dom.query('input:disabled');
// equal(result.length, 1, '1 result of input');
// equal(result[0], input, 'input disabled');
// document.body.removeChild(div);
// document.body.removeChild(a);
// });

test('base', function() {
	var tag = 'input';
	var len = baidu.dom.query(tag).length;
	var a = document.createElement(tag);
	a.id = 'test_' + tag;
	a.className = 'test_class_' + tag;
	a.type = 'checkbox';
	a.disabled = true;
	a = document.body.appendChild(a);
	equal(baidu.dom.query(a.tagName)[len], a, 'query by tag');
	equal(baidu.dom.query('#' + a.id)[0], a, 'query by id');
	equal(baidu.dom.query('.' + a.className)[0], a, 'query by class');
	equal(baidu.dom.query(tag + ':disabled')[0], a, 'query by status');
	a.parentNode.removeChild(a);
});

test('2 params', function() {
	var div = document.createElement('div');
	var a = document.createElement('a');
	var a2 = document.createElement('a');
	var div2 = document.createElement('div');
	document.body.appendChild(div);
	document.body.appendChild(a);
	div.appendChild(a2);
	div.appendChild(div2);
	var result = baidu.dom.query('a', div);
	equal(result.length, 1, '2 results of a');
	equal(result[0], a2, 'result 1 a');
	// equal(result[1],a,'result 2 a2');

	document.body.removeChild(div);
	document.body.removeChild(a);
});<|endoftext|>


<commit_before><commit_msg>Create auto-debuuger.js<commit_after><|endoftext|>


<commit_before>(function(self) {
  'use strict';

  if (self.fetch) {
    return
  }

  var support = {
    searchParams: 'URLSearchParams' in self,
    iterable: 'Symbol' in self && 'iterator' in Symbol,
    blob: 'FileReader' in self && 'Blob' in self && (function() {
      try {
        new Blob()
        return true
      } catch(e) {
        return false
      }
    })(),
    formData: 'FormData' in self,
    arrayBuffer: 'ArrayBuffer' in self
  }

  function normalizeName(name) {
    if (typeof name !== 'string') {
      name = String(name)
    }
    if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
      throw new TypeError('Invalid character in header field name')
    }
    return name.toLowerCase()
  }

  function normalizeValue(value) {
    if (typeof value !== 'string') {
      value = String(value)
    }
    return value
  }

  function Headers(headers) {
    this.map = {}

    if (headers instanceof Headers) {
      headers.forEach(function(value, name) {
        this.append(name, value)
      }, this)

    } else if (headers) {
      Object.getOwnPropertyNames(headers).forEach(function(name) {
        this.append(name, headers[name])
      }, this)
    }
  }

  Headers.prototype.append = function(name, value) {
    name = normalizeName(name)
    value = normalizeValue(value)
    var list = this.map[name]
    if (!list) {
      list = []
      this.map[name] = list
    }
    list.push(value)
  }

  Headers.prototype['delete'] = function(name) {
    delete this.map[normalizeName(name)]
  }

  Headers.prototype.get = function(name) {
    var values = this.map[normalizeName(name)]
    return values ? values[0] : null
  }

  Headers.prototype.getAll = function(name) {
    return this.map[normalizeName(name)] || []
  }

  Headers.prototype.has = function(name) {
    return this.map.hasOwnProperty(normalizeName(name))
  }

  Headers.prototype.set = function(name, value) {
    this.map[normalizeName(name)] = [normalizeValue(value)]
  }

  Headers.prototype.forEach = function(callback, thisArg) {
    Object.getOwnPropertyNames(this.map).forEach(function(name) {
      this.map[name].forEach(function(value) {
        callback.call(thisArg, value, name, this)
      }, this)
    }, this)
  }

  Headers.prototype.keys = function() {
    var items = []
    this.forEach(function(value, name) { items.push(name) })
    var iterator = {
      next: function() {
        var value = items.shift()
        return {done: value === undefined, value: value}
      }
    }

    if (support.iterable) {
      iterator[Symbol.iterator] = function() {
        return iterator
      }
    }

    return iterator
  }

  Headers.prototype.values = function() {
    var items = []
    this.forEach(function(value) { items.push(value) })
    var iterator = {
      next: function() {
        var value = items.shift()
        return {done: value === undefined, value: value}
      }
    }

    if (support.iterable) {
      iterator[Symbol.iterator] = function() {
        return iterator
      }
    }

    return iterator
  }

  Headers.prototype.entries = function() {
    var items = []
    this.forEach(function(value, name) { items.push([name, value]) })
    var iterator = {
      next: function() {
        var value = items.shift()
        return {done: value === undefined, value: value}
      }
    }

    if (support.iterable) {
      iterator[Symbol.iterator] = function() {
        return iterator
      }
    }

    return iterator
  }

  if (support.iterable) {
    Headers.prototype[Symbol.iterator] = Headers.prototype.entries
  }

  function consumed(body) {
    if (body.bodyUsed) {
      return Promise.reject(new TypeError('Already read'))
    }
    body.bodyUsed = true
  }

  function fileReaderReady(reader) {
    return new Promise(function(resolve, reject) {
      reader.onload = function() {
        resolve(reader.result)
      }
      reader.onerror = function() {
        reject(reader.error)
      }
    })
  }

  function readBlobAsArrayBuffer(blob) {
    var reader = new FileReader()
    reader.readAsArrayBuffer(blob)
    return fileReaderReady(reader)
  }

  function readBlobAsText(blob) {
    var reader = new FileReader()
    reader.readAsText(blob)
    return fileReaderReady(reader)
  }

  function Body() {
    this.bodyUsed = false

    this._initBody = function(body) {
      this._bodyInit = body
      if (typeof body === 'string') {
        this._bodyText = body
      } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
        this._bodyBlob = body
      } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
        this._bodyFormData = body
      } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
        this._bodyText = body.toString()
      } else if (!body) {
        this._bodyText = ''
      } else if (support.arrayBuffer && ArrayBuffer.prototype.isPrototypeOf(body)) {
        // Only support ArrayBuffers for POST method.
        // Receiving ArrayBuffers happens via Blobs, instead.
      } else {
        throw new Error('unsupported BodyInit type')
      }

      if (!this.headers.get('content-type')) {
        if (typeof body === 'string') {
          this.headers.set('content-type', 'text/plain;charset=UTF-8')
        } else if (this._bodyBlob && this._bodyBlob.type) {
          this.headers.set('content-type', this._bodyBlob.type)
        } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
          this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')
        }
      }
    }

    if (support.blob) {
      this.blob = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return Promise.resolve(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as blob')
        } else {
          return Promise.resolve(new Blob([this._bodyText]))
        }
      }

      this.arrayBuffer = function() {
        return this.blob().then(readBlobAsArrayBuffer)
      }

      this.text = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return readBlobAsText(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as text')
        } else {
          return Promise.resolve(this._bodyText)
        }
      }
    } else {
      this.text = function() {
        var rejected = consumed(this)
        return rejected ? rejected : Promise.resolve(this._bodyText)
      }
    }

    if (support.formData) {
      this.formData = function() {
        return this.text().then(decode)
      }
    }

    this.json = function() {
      return this.text().then(JSON.parse)
    }

    return this
  }

  // HTTP methods whose capitalization should be normalized
  var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']

  function normalizeMethod(method) {
    var upcased = method.toUpperCase()
    return (methods.indexOf(upcased) > -1) ? upcased : method
  }

  function Request(input, options) {
    options = options || {}
    var body = options.body
    if (Request.prototype.isPrototypeOf(input)) {
      if (input.bodyUsed) {
        throw new TypeError('Already read')
      }
      this.url = input.url
      this.credentials = input.credentials
      if (!options.headers) {
        this.headers = new Headers(input.headers)
      }
      this.method = input.method
      this.mode = input.mode
      if (!body) {
        body = input._bodyInit
        input.bodyUsed = true
      }
    } else {
      this.url = input
    }

    this.credentials = options.credentials || this.credentials || 'omit'
    if (options.headers || !this.headers) {
      this.headers = new Headers(options.headers)
    }
    this.method = normalizeMethod(options.method || this.method || 'GET')
    this.mode = options.mode || this.mode || null
    this.referrer = null

    if ((this.method === 'GET' || this.method === 'HEAD') && body) {
      throw new TypeError('Body not allowed for GET or HEAD requests')
    }
    this._initBody(body)
  }

  Request.prototype.clone = function() {
    return new Request(this)
  }

  function decode(body) {
    var form = new FormData()
    body.trim().split('&').forEach(function(bytes) {
      if (bytes) {
        var split = bytes.split('=')
        var name = split.shift().replace(/\+/g, ' ')
        var value = split.join('=').replace(/\+/g, ' ')
        form.append(decodeURIComponent(name), decodeURIComponent(value))
      }
    })
    return form
  }

  function headers(xhr) {
    var head = new Headers()
    var pairs = (xhr.getAllResponseHeaders() || '').trim().split('\n')
    pairs.forEach(function(header) {
      var split = header.trim().split(':')
      var key = split.shift().trim()
      var value = split.join(':').trim()
      head.append(key, value)
    })
    return head
  }

  Body.call(Request.prototype)

  function Response(bodyInit, options) {
    if (!options) {
      options = {}
    }

    this.type = 'default'
    this.status = options.status
    this.ok = this.status >= 200 && this.status < 300
    this.statusText = options.statusText
    this.headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers)
    this.url = options.url || ''
    this._initBody(bodyInit)
  }

  Body.call(Response.prototype)

  Response.prototype.clone = function() {
    return new Response(this._bodyInit, {
      status: this.status,
      statusText: this.statusText,
      headers: new Headers(this.headers),
      url: this.url
    })
  }

  Response.error = function() {
    var response = new Response(null, {status: 0, statusText: ''})
    response.type = 'error'
    return response
  }

  var redirectStatuses = [301, 302, 303, 307, 308]

  Response.redirect = function(url, status) {
    if (redirectStatuses.indexOf(status) === -1) {
      throw new RangeError('Invalid status code')
    }

    return new Response(null, {status: status, headers: {location: url}})
  }

  self.Headers = Headers
  self.Request = Request
  self.Response = Response

  self.fetch = function(input, init) {
    return new Promise(function(resolve, reject) {
      var request
      if (Request.prototype.isPrototypeOf(input) && !init) {
        request = input
      } else {
        request = new Request(input, init)
      }

      var xhr = new XMLHttpRequest()

      function responseURL() {
        if ('responseURL' in xhr) {
          return xhr.responseURL
        }

        // Avoid security warnings on getResponseHeader when not allowed by CORS
        if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
          return xhr.getResponseHeader('X-Request-URL')
        }

        return
      }

      xhr.onload = function() {
        var options = {
          status: xhr.status,
          statusText: xhr.statusText,
          headers: headers(xhr),
          url: responseURL()
        }
        var body = 'response' in xhr ? xhr.response : xhr.responseText
        resolve(new Response(body, options))
      }

      xhr.onerror = function() {
        reject(new TypeError('Network request failed'))
      }

      xhr.open(request.method, request.url, true)

      if (request.credentials === 'include') {
        xhr.withCredentials = true
      }

      if ('responseType' in xhr && support.blob) {
        xhr.responseType = 'blob'
      }

      request.headers.forEach(function(value, name) {
        xhr.setRequestHeader(name, value)
      })

      xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
    })
  }
  self.fetch.polyfill = true
})(typeof self !== 'undefined' ? self : this);
<commit_msg>Reject promise on request timeout<commit_after>(function(self) {
  'use strict';

  if (self.fetch) {
    return
  }

  var support = {
    searchParams: 'URLSearchParams' in self,
    iterable: 'Symbol' in self && 'iterator' in Symbol,
    blob: 'FileReader' in self && 'Blob' in self && (function() {
      try {
        new Blob()
        return true
      } catch(e) {
        return false
      }
    })(),
    formData: 'FormData' in self,
    arrayBuffer: 'ArrayBuffer' in self
  }

  function normalizeName(name) {
    if (typeof name !== 'string') {
      name = String(name)
    }
    if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
      throw new TypeError('Invalid character in header field name')
    }
    return name.toLowerCase()
  }

  function normalizeValue(value) {
    if (typeof value !== 'string') {
      value = String(value)
    }
    return value
  }

  function Headers(headers) {
    this.map = {}

    if (headers instanceof Headers) {
      headers.forEach(function(value, name) {
        this.append(name, value)
      }, this)

    } else if (headers) {
      Object.getOwnPropertyNames(headers).forEach(function(name) {
        this.append(name, headers[name])
      }, this)
    }
  }

  Headers.prototype.append = function(name, value) {
    name = normalizeName(name)
    value = normalizeValue(value)
    var list = this.map[name]
    if (!list) {
      list = []
      this.map[name] = list
    }
    list.push(value)
  }

  Headers.prototype['delete'] = function(name) {
    delete this.map[normalizeName(name)]
  }

  Headers.prototype.get = function(name) {
    var values = this.map[normalizeName(name)]
    return values ? values[0] : null
  }

  Headers.prototype.getAll = function(name) {
    return this.map[normalizeName(name)] || []
  }

  Headers.prototype.has = function(name) {
    return this.map.hasOwnProperty(normalizeName(name))
  }

  Headers.prototype.set = function(name, value) {
    this.map[normalizeName(name)] = [normalizeValue(value)]
  }

  Headers.prototype.forEach = function(callback, thisArg) {
    Object.getOwnPropertyNames(this.map).forEach(function(name) {
      this.map[name].forEach(function(value) {
        callback.call(thisArg, value, name, this)
      }, this)
    }, this)
  }

  Headers.prototype.keys = function() {
    var items = []
    this.forEach(function(value, name) { items.push(name) })
    var iterator = {
      next: function() {
        var value = items.shift()
        return {done: value === undefined, value: value}
      }
    }

    if (support.iterable) {
      iterator[Symbol.iterator] = function() {
        return iterator
      }
    }

    return iterator
  }

  Headers.prototype.values = function() {
    var items = []
    this.forEach(function(value) { items.push(value) })
    var iterator = {
      next: function() {
        var value = items.shift()
        return {done: value === undefined, value: value}
      }
    }

    if (support.iterable) {
      iterator[Symbol.iterator] = function() {
        return iterator
      }
    }

    return iterator
  }

  Headers.prototype.entries = function() {
    var items = []
    this.forEach(function(value, name) { items.push([name, value]) })
    var iterator = {
      next: function() {
        var value = items.shift()
        return {done: value === undefined, value: value}
      }
    }

    if (support.iterable) {
      iterator[Symbol.iterator] = function() {
        return iterator
      }
    }

    return iterator
  }

  if (support.iterable) {
    Headers.prototype[Symbol.iterator] = Headers.prototype.entries
  }

  function consumed(body) {
    if (body.bodyUsed) {
      return Promise.reject(new TypeError('Already read'))
    }
    body.bodyUsed = true
  }

  function fileReaderReady(reader) {
    return new Promise(function(resolve, reject) {
      reader.onload = function() {
        resolve(reader.result)
      }
      reader.onerror = function() {
        reject(reader.error)
      }
    })
  }

  function readBlobAsArrayBuffer(blob) {
    var reader = new FileReader()
    reader.readAsArrayBuffer(blob)
    return fileReaderReady(reader)
  }

  function readBlobAsText(blob) {
    var reader = new FileReader()
    reader.readAsText(blob)
    return fileReaderReady(reader)
  }

  function Body() {
    this.bodyUsed = false

    this._initBody = function(body) {
      this._bodyInit = body
      if (typeof body === 'string') {
        this._bodyText = body
      } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
        this._bodyBlob = body
      } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
        this._bodyFormData = body
      } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
        this._bodyText = body.toString()
      } else if (!body) {
        this._bodyText = ''
      } else if (support.arrayBuffer && ArrayBuffer.prototype.isPrototypeOf(body)) {
        // Only support ArrayBuffers for POST method.
        // Receiving ArrayBuffers happens via Blobs, instead.
      } else {
        throw new Error('unsupported BodyInit type')
      }

      if (!this.headers.get('content-type')) {
        if (typeof body === 'string') {
          this.headers.set('content-type', 'text/plain;charset=UTF-8')
        } else if (this._bodyBlob && this._bodyBlob.type) {
          this.headers.set('content-type', this._bodyBlob.type)
        } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
          this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')
        }
      }
    }

    if (support.blob) {
      this.blob = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return Promise.resolve(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as blob')
        } else {
          return Promise.resolve(new Blob([this._bodyText]))
        }
      }

      this.arrayBuffer = function() {
        return this.blob().then(readBlobAsArrayBuffer)
      }

      this.text = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return readBlobAsText(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as text')
        } else {
          return Promise.resolve(this._bodyText)
        }
      }
    } else {
      this.text = function() {
        var rejected = consumed(this)
        return rejected ? rejected : Promise.resolve(this._bodyText)
      }
    }

    if (support.formData) {
      this.formData = function() {
        return this.text().then(decode)
      }
    }

    this.json = function() {
      return this.text().then(JSON.parse)
    }

    return this
  }

  // HTTP methods whose capitalization should be normalized
  var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']

  function normalizeMethod(method) {
    var upcased = method.toUpperCase()
    return (methods.indexOf(upcased) > -1) ? upcased : method
  }

  function Request(input, options) {
    options = options || {}
    var body = options.body
    if (Request.prototype.isPrototypeOf(input)) {
      if (input.bodyUsed) {
        throw new TypeError('Already read')
      }
      this.url = input.url
      this.credentials = input.credentials
      if (!options.headers) {
        this.headers = new Headers(input.headers)
      }
      this.method = input.method
      this.mode = input.mode
      if (!body) {
        body = input._bodyInit
        input.bodyUsed = true
      }
    } else {
      this.url = input
    }

    this.credentials = options.credentials || this.credentials || 'omit'
    if (options.headers || !this.headers) {
      this.headers = new Headers(options.headers)
    }
    this.method = normalizeMethod(options.method || this.method || 'GET')
    this.mode = options.mode || this.mode || null
    this.referrer = null

    if ((this.method === 'GET' || this.method === 'HEAD') && body) {
      throw new TypeError('Body not allowed for GET or HEAD requests')
    }
    this._initBody(body)
  }

  Request.prototype.clone = function() {
    return new Request(this)
  }

  function decode(body) {
    var form = new FormData()
    body.trim().split('&').forEach(function(bytes) {
      if (bytes) {
        var split = bytes.split('=')
        var name = split.shift().replace(/\+/g, ' ')
        var value = split.join('=').replace(/\+/g, ' ')
        form.append(decodeURIComponent(name), decodeURIComponent(value))
      }
    })
    return form
  }

  function headers(xhr) {
    var head = new Headers()
    var pairs = (xhr.getAllResponseHeaders() || '').trim().split('\n')
    pairs.forEach(function(header) {
      var split = header.trim().split(':')
      var key = split.shift().trim()
      var value = split.join(':').trim()
      head.append(key, value)
    })
    return head
  }

  Body.call(Request.prototype)

  function Response(bodyInit, options) {
    if (!options) {
      options = {}
    }

    this.type = 'default'
    this.status = options.status
    this.ok = this.status >= 200 && this.status < 300
    this.statusText = options.statusText
    this.headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers)
    this.url = options.url || ''
    this._initBody(bodyInit)
  }

  Body.call(Response.prototype)

  Response.prototype.clone = function() {
    return new Response(this._bodyInit, {
      status: this.status,
      statusText: this.statusText,
      headers: new Headers(this.headers),
      url: this.url
    })
  }

  Response.error = function() {
    var response = new Response(null, {status: 0, statusText: ''})
    response.type = 'error'
    return response
  }

  var redirectStatuses = [301, 302, 303, 307, 308]

  Response.redirect = function(url, status) {
    if (redirectStatuses.indexOf(status) === -1) {
      throw new RangeError('Invalid status code')
    }

    return new Response(null, {status: status, headers: {location: url}})
  }

  self.Headers = Headers
  self.Request = Request
  self.Response = Response

  self.fetch = function(input, init) {
    return new Promise(function(resolve, reject) {
      var request
      if (Request.prototype.isPrototypeOf(input) && !init) {
        request = input
      } else {
        request = new Request(input, init)
      }

      var xhr = new XMLHttpRequest()

      function responseURL() {
        if ('responseURL' in xhr) {
          return xhr.responseURL
        }

        // Avoid security warnings on getResponseHeader when not allowed by CORS
        if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
          return xhr.getResponseHeader('X-Request-URL')
        }

        return
      }

      xhr.onload = function() {
        var options = {
          status: xhr.status,
          statusText: xhr.statusText,
          headers: headers(xhr),
          url: responseURL()
        }
        var body = 'response' in xhr ? xhr.response : xhr.responseText
        resolve(new Response(body, options))
      }

      xhr.onerror = function() {
        reject(new TypeError('Network request failed'))
      }

      xhr.ontimeout = function() {
        reject(new TypeError('Network request failed'))
      }

      xhr.open(request.method, request.url, true)

      if (request.credentials === 'include') {
        xhr.withCredentials = true
      }

      if ('responseType' in xhr && support.blob) {
        xhr.responseType = 'blob'
      }

      request.headers.forEach(function(value, name) {
        xhr.setRequestHeader(name, value)
      })

      xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
    })
  }
  self.fetch.polyfill = true
})(typeof self !== 'undefined' ? self : this);
<|endoftext|>


<commit_before>var path = require('path');

module.exports = {
  entry: './public/javascripts/main.js',

  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'public/dist')
  },

  externals: {
    quill: 'Quill'
  },

  watch: true
};
<commit_msg>Remove webpack watch config<commit_after>var path = require('path');

module.exports = {
  entry: './public/javascripts/main.js',

  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'public/dist')
  },

  externals: {
    quill: 'Quill'
  }
};
<|endoftext|>


<commit_before>angular.module('ui.bootstrap-slider', [])
	.directive('slider', ['$parse', '$timeout', function ($parse, $timeout) {
		return {
			restrict: 'AE',
			replace: true,
			template: '<input type="text" />',
			link: function ($scope, element, attrs) {
				var model = $parse(attrs.ngModel);

				var options = {};
				if(attrs.sliderId) options.id = attrs.sliderId;
				if(attrs.min) options.min = parseFloat(attrs.min);
				if(attrs.max) options.max = parseFloat(attrs.max);
				if(attrs.step) options.step = parseFloat(attrs.step);
				if(attrs.precision) options.precision = parseFloat(attrs.precision);
				if(attrs.orientation) options.orientation = attrs.orientation;
				if(attrs.value) {
					if (angular.isNumber(attrs.value) || angular.isArray(attrs.value)) {
						options.value = attrs.value;
					} else if (angular.isString(attrs.value)) {
						if (attrs.value.indexOf("[") === 0) {
							options.value = angular.fromJson(attrs.value);
						} else {
							options.value = parseFloat(attrs.value);
						}
					}

				}
				if(attrs.range) options.range = attrs.range === 'true';
				if(attrs.selection) options.selection = attrs.selection;
				if(attrs.tooltip) options.tooltip = attrs.tooltip;
				if(attrs.tooltipSeparator) options.tooltip_separator = attrs.tooltipSeparator;
				if(attrs.tooltipSplit) options.tooltip_split = attrs.tooltipSplit === 'true';
				if(attrs.handle) options.handle = attrs.handle;
				if(attrs.reversed) options.reversed = attrs.reversed === 'true';
				if(attrs.enabled) options.enabled = attrs.enabled === 'true';
				if(attrs.naturalArrowKeys) options.natural_arrow_keys = attrs.naturalArrowKeys === 'true';

				if (options.range && !options.value) {
					options.value = [0,0]; // This is needed, because of value defined at $.fn.slider.defaults - default value 5 prevents creating range slider
				}

				var slider = $(element[0]).slider(options);

				slider.on('slide', function(ev) {
					model.assign($scope, ev.value);
					$timeout(function() {
						$scope.$apply();
					});
				});

				$scope.$watch(attrs.ngModel, function(value) {
					if(value) {
						slider.slider('setValue', value, false);
					}
				});
			}
		};
	}])
;
<commit_msg>Allow event option for when to update model<commit_after>angular.module('ui.bootstrap-slider', [])
	.directive('slider', ['$parse', '$timeout', function ($parse, $timeout) {
		return {
			restrict: 'AE',
			replace: true,
			template: '<input type="text" />',
			link: function ($scope, element, attrs) {
				var model = $parse(attrs.ngModel);

				var options = {};
				if(attrs.sliderId) options.id = attrs.sliderId;
				if(attrs.min) options.min = parseFloat(attrs.min);
				if(attrs.max) options.max = parseFloat(attrs.max);
				if(attrs.step) options.step = parseFloat(attrs.step);
				if(attrs.precision) options.precision = parseFloat(attrs.precision);
				if(attrs.orientation) options.orientation = attrs.orientation;
				if(attrs.value) {
					if (angular.isNumber(attrs.value) || angular.isArray(attrs.value)) {
						options.value = attrs.value;
					} else if (angular.isString(attrs.value)) {
						if (attrs.value.indexOf("[") === 0) {
							options.value = angular.fromJson(attrs.value);
						} else {
							options.value = parseFloat(attrs.value);
						}
					}

				}
				if(attrs.range) options.range = attrs.range === 'true';
				if(attrs.selection) options.selection = attrs.selection;
				if(attrs.tooltip) options.tooltip = attrs.tooltip;
				if(attrs.tooltipSeparator) options.tooltip_separator = attrs.tooltipSeparator;
				if(attrs.tooltipSplit) options.tooltip_split = attrs.tooltipSplit === 'true';
				if(attrs.handle) options.handle = attrs.handle;
				if(attrs.reversed) options.reversed = attrs.reversed === 'true';
				if(attrs.enabled) options.enabled = attrs.enabled === 'true';
				if(attrs.naturalArrowKeys) options.natural_arrow_keys = attrs.naturalArrowKeys === 'true';

				if (options.range && !options.value) {
					options.value = [0,0]; // This is needed, because of value defined at $.fn.slider.defaults - default value 5 prevents creating range slider
				}

				var slider = $(element[0]).slider(options);
        var updateEvent = attrs.updateEvent || 'slide';

				slider.on(updateEvent, function(ev) {
					model.assign($scope, ev.value);
					$timeout(function() {
						$scope.$apply();
					});
				});

				$scope.$watch(attrs.ngModel, function(value) {
					if(value) {
						slider.slider('setValue', value, false);
					}
				});
			}
		};
	}])
;
<|endoftext|>


<commit_before>function ProceduralGroundColorApplier(label, colorScheme){
	this.label = label;
	this.colorControlPoints = [
		{height: 0, hexcolor: 0xc2b280},
		{height: 20, hexcolor: 0x66dd66},
		{height: 30, hexcolor: 0xc2b280},
		{height: 90, hexcolor: 0x777777},
		{height: 110, hexcolor: 0xffffff},
	];
}

ProceduralGroundColorApplier.prototype.getColor = function(height) {
	var next = this.colorControlPoints[0];
	if(height <= next.height) {
		return new THREE.Color(next.hexcolor);
	}

	var prev = next;
	for(var i=1; i<this.colorControlPoints.length; ++i){
		next = this.colorControlPoints[i];
		if(prev.height <= height && height < next.height){
			var alpha = (height - prev.height) / (next.height - prev.height);
			var c0 = new THREE.Color(prev.hexcolor);
			var c1 = new THREE.Color(next.hexcolor);
			return c0.lerp(c1, alpha);
		}
		prev = next;
	}

	return new THREE.Color(next.hexcolor);
};

ProceduralGroundColorApplier.prototype.create = function(controls) {

	var groundMesh = controls.groundData.groundMesh;
	groundMesh.material = new THREE.MeshPhongMaterial( {
	    color: 0xffffff, specular: 0,
	    shading: THREE.FlatShading,
	    //shading: THREE.SmoothShading,
	    vertexColors: THREE.FaceColors
	});

	// Clear any previous vertex colors
	for (var faceIndex = 0; faceIndex < groundMesh.geometry.faces.length; faceIndex++) {
		var vc = groundMesh.geometry.faces[faceIndex].vertexColors = [];
	}

	// Set a color to each faces' vertices
	for (var faceIndex = 0; faceIndex < groundMesh.geometry.faces.length; faceIndex++) {
		var face = groundMesh.geometry.faces[faceIndex];
		var faceVertex = groundMesh.geometry.vertices[face.a];
		var height = faceVertex.z * controls.modelScale;

		var noiseCoords = controls.noiseCoords(faceVertex);
		var heightNoise = 50 * noise.simplex2(noiseCoords.u, noiseCoords.v);
		face.color.copy(this.getColor(height + heightNoise));
	};

	groundMesh.geometry.colorsNeedUpdate = true;
};<commit_msg>color based on sea level<commit_after>function ProceduralGroundColorApplier(label, colorScheme){
	this.label = label;
	this.colorControlPoints = [
		{height: -10, hexcolor: 0xc2b280},
		{height: 10, hexcolor: 0x66dd66},
		{height: 30, hexcolor: 0xc2b280},
		{height: 90, hexcolor: 0x777777},
		{height: 110, hexcolor: 0xffffff},
	];
}

ProceduralGroundColorApplier.prototype.getColor = function(height) {
	var next = this.colorControlPoints[0];
	if(height <= next.height) {
		return new THREE.Color(next.hexcolor);
	}

	var prev = next;
	for(var i=1; i<this.colorControlPoints.length; ++i){
		next = this.colorControlPoints[i];
		if(prev.height <= height && height < next.height){
			var alpha = (height - prev.height) / (next.height - prev.height);
			var c0 = new THREE.Color(prev.hexcolor);
			var c1 = new THREE.Color(next.hexcolor);
			return c0.lerp(c1, alpha);
		}
		prev = next;
	}

	return new THREE.Color(next.hexcolor);
};

ProceduralGroundColorApplier.prototype.create = function(controls) {

	var groundMesh = controls.groundData.groundMesh;
	groundMesh.material = new THREE.MeshPhongMaterial( {
	    color: 0xffffff, specular: 0,
	    shading: THREE.FlatShading,
	    //shading: THREE.SmoothShading,
	    vertexColors: THREE.FaceColors
	});

	// Clear any previous vertex colors
	for (var faceIndex = 0; faceIndex < groundMesh.geometry.faces.length; faceIndex++) {
		var vc = groundMesh.geometry.faces[faceIndex].vertexColors = [];
	}
	console.log(controls);
	// Set a color to each faces' vertices
	for (var faceIndex = 0; faceIndex < groundMesh.geometry.faces.length; faceIndex++) {
		var face = groundMesh.geometry.faces[faceIndex];
		var faceVertex = groundMesh.geometry.vertices[face.a];
		var height = (faceVertex.z - ((controls.sea_level-0.5)*groundMesh.size.heightLimit)) * controls.modelScale

		var noiseCoords = controls.noiseCoords(faceVertex);
		var heightNoise = 30 * noise.simplex2(2*noiseCoords.u, 2*noiseCoords.v);
		face.color.copy(this.getColor(height + heightNoise));
	};

	groundMesh.geometry.colorsNeedUpdate = true;
};<|endoftext|>


<commit_before>WYMeditor.STRINGS['nb'] = {
	Strong:			 'Fet',
	Emphasis:		 'Uthevet',
	Superscript:		'Opphøyet',
	Subscript:		'Nedsenket',
	Ordered_List:	 'Nummerert liste',
	Unordered_List:	 'Punktliste',
	Indent:			 'Rykk inn',
	Outdent:			'Rykk ut',
	Undo:			 'Angre',
	Redo:			 'Gjenta',
	Link:			 'Lenke',
	Unlink:			 'Ta bort lenken',
	Image:			'Bilde',
	Table:			'Tabell',
	HTML:			 'HTML',
	Paragraph:		'Avsnitt',
	Heading_1:		'Overskrift 1',
	Heading_2:		'Overskrift 2',
	Heading_3:		'Overskrift 3',
	Heading_4:		'Overskrift 4',
	Heading_5:		'Overskrift 5',
	Heading_6:		'Overskrift 6',
	Preformatted:	 'Preformatert',
	Blockquote:		 'Sitat',
	Table_Header:	 'Tabelloverskrift',
	URL:				'URL',
	Title:			'Tittel',
	Alternative_Text: 'Alternativ tekst',
	Caption:			'Overskrift',
	Summary:			'Sammendrag',
	Number_Of_Rows:	 'Antall rader',
	Number_Of_Cols:	 'Antall kolonner',
	Submit:			 'Ok',
	Cancel:			 'Avbryt',
	Choose:			 'Velg',
	Preview:			'Forhåndsvis',
	Paste_From_Word:	'Lim inn fra Word',
	Tools:			'Verktøy',
	Containers:		 'Formatering',
	Classes:			'Klasser',
	Status:			 'Status',
	Source_Code:		'Kildekode'
};

<commit_msg>Updated Norwegian translation of WYMEditor as well."<commit_after>WYMeditor.STRINGS['nb'] = {
	Strong:			 'Fet',
  Bold:             'Fet',
	Emphasis:		 'Uthevet',
	Superscript:		'Opphøyet',
	Subscript:		'Nedsenket',
	Ordered_List:	 'Nummerert liste',
	Unordered_List:	 'Punktliste',
	Indent:			 'Rykk inn',
	Outdent:			'Rykk ut',
	Undo:			 'Angre',
	Redo:			 'Gjenta',
	Link:			 'Lenke',
	Unlink:			 'Ta bort lenken',
	Image:			'Bilde',
	Table:			'Tabell',
	HTML:			 'HTML',
	Paragraph:		'Avsnitt',
	Heading_1:		'Overskrift 1',
	Heading_2:		'Overskrift 2',
	Heading_3:		'Overskrift 3',
	Heading_4:		'Overskrift 4',
	Heading_5:		'Overskrift 5',
	Heading_6:		'Overskrift 6',
	Preformatted:	 'Preformatert',
	Blockquote:		 'Sitat',
	Table_Header:	 'Tabelloverskrift',
	URL:				'URL',
	Title:			'Tittel',
	Alternative_Text: 'Alternativ tekst',
	Caption:			'Overskrift',
	Summary:			'Sammendrag',
	Number_Of_Rows:	 'Antall rader',
	Number_Of_Cols:	 'Antall kolonner',
  Insert:           'Sett inn',
	Submit:			 'Ok',
	Cancel:			 'Avbryt',
	Choose:			 'Velg',
	Preview:			'Forhåndsvis',
	Paste_From_Word:	'Lim inn fra Word',
	Tools:			'Verktøy',
	Containers:		 'Formatering',
	Classes:			'Klasser',
	Status:			 'Status',
	Source_Code:		'Kildekode',
  Apply_Style:      'Bruk stil'
};

<|endoftext|>


<commit_before>var pageTitleElement = document.getElementById("page-title");
// Menyeleksi DOM berdasarkan Id element dan menampungnya ke dalam variabel. Isinya merupakan object HTML element
console.log(pageTitleElement);
var pageBoxElements = document.getElementsByClassName("page-box");
// Menyeleksi DOM berdasarkan nama class element dan menampungnya ke dalam variabel. Isinya merupakan array dari object HTML element, walau
 hanya ada 1.
console.log(pageBoxElements);
var pageHeadings = document.getElementsByTagName("h1");
// Menyeleksi DOM berdasarkan tag
 dan menampungnya ke dalam variabel. Isinya merupakan array dari object HTML element
console.log(pageHeadings);

var pageTitleElementsContent = pageTitleElement.innerHTML;
console.log('isi
 :' + pageTitleElementsContent);
// isi
 adalah Sample Page Title

// Mengambil isi elemen pageBoxElements yang pertama, yaitu index ke 0
var firstPageBoxElement         = pageBoxElements[0];
var firstpageBoxElementContent  = firstPageBoxElement.innerHTML;

// Mengambil isi elemen pageBoxElements yang kedua, yaitu index ke 1
var secondPageBoxElement         = pageBoxElements[1];
var secondpageBoxElementContent  = secondPageBoxElement.innerHTML;

// Mengambil isi elemen pageBoxElements yang ketiga, yaitu index ke 2
var thirdPageBoxElement         = pageBoxElements[2];
var thirdpageBoxElementContent  = thirdPageBoxElement.innerHTML;

// Menampilkan isi elemen dengan console.log
console.log('isi
 yang pertama:' + firstpageBoxElementContent);
console.log('isi
 yang kedua:' + secondpageBoxElementContent);
console.log('isi
 yang ketiga:' + thirdpageBoxElementContent);
<commit_msg>looping for get the content of array of DOM<commit_after>var pageTitleElement = document.getElementById("page-title");
// Menyeleksi DOM berdasarkan Id element dan menampungnya ke dalam variabel. Isinya merupakan object HTML element
console.log(pageTitleElement);
var pageBoxElements = document.getElementsByClassName("page-box");
// Menyeleksi DOM berdasarkan nama class element dan menampungnya ke dalam variabel. Isinya merupakan array dari object HTML element, walau
 hanya ada 1.
console.log(pageBoxElements);
var pageHeadings = document.getElementsByTagName("h1");
// Menyeleksi DOM berdasarkan tag
 dan menampungnya ke dalam variabel. Isinya merupakan array dari object HTML element
console.log(pageHeadings);

var pageTitleElementsContent = pageTitleElement.innerHTML;
console.log('isi
 :' + pageTitleElementsContent);
// isi
 adalah Sample Page Title

// Mengambil isi elemen pageBoxElements yang pertama, yaitu index ke 0
var firstPageBoxElement         = pageBoxElements[0];
var firstpageBoxElementContent  = firstPageBoxElement.innerHTML;

// Mengambil isi elemen pageBoxElements yang kedua, yaitu index ke 1
var secondPageBoxElement         = pageBoxElements[1];
var secondpageBoxElementContent  = secondPageBoxElement.innerHTML;

// Mengambil isi elemen pageBoxElements yang ketiga, yaitu index ke 2
var thirdPageBoxElement         = pageBoxElements[2];
var thirdpageBoxElementContent  = thirdPageBoxElement.innerHTML;

// Menampilkan isi elemen dengan console.log
console.log('isi
 yang pertama:' + firstpageBoxElementContent);
console.log('isi
 yang kedua:' + secondpageBoxElementContent);
console.log('isi
 yang ketiga:' + thirdpageBoxElementContent);

// Meloop array pageBoxElements
for(var i = 0; i < pageBoxElements.length; i++) {
  var currentPageBoxElement         = pageBoxElements[i];
  var currentPageBoxElementContent  = currentPageBoxElement.innerHTML;
  console.log('isi
 index ke ' + i + ': ' + currentPageBoxElementContent);
}
<|endoftext|>


<commit_before>'use strict';

describe("ManageService", function () {

    beforeEach(module("GVA.Creation"));
    beforeEach(module("GVA.Common"));

    var manageService;
    var httpBackend;

    beforeEach(inject(function (ManageService, $httpBackend) {
        manageService = ManageService;
        httpBackend = $httpBackend;
    }));

    afterEach(function () {
        httpBackend.verifyNoOutstandingExpectation();
        httpBackend.verifyNoOutstandingRequest();

        // http://stackoverflow.com/questions/27016235/angular-js-unit-testing-httpbackend-spec-has-no-expectations
        expect('Suppress SPEC HAS NO EXPECTATIONS').toBeDefined();
    });

    describe("Delete Voters", function () {

        it("Contains the correct Content-Type header", function () {

            var pollManageGuid = '091EA404-5AAE-4AA4-A5EF-E0625ACC33D4';
            var expectedUrl = '/api/manage/' + pollManageGuid + '/voters';
            var expectedData = { "BallotDeleteRequests": [] };

            httpBackend.expect(
                    'DELETE',
                    expectedUrl,
                    expectedData,
                    function (headers) {
                        return headers['Content-Type'] === 'application/json; charset=utf-8';
                    }
                ).respond(200);

            manageService.deleteVoters(pollManageGuid, []);

            httpBackend.flush();

            //supressJasmineNoSpecMessage();
        });

        it("Creates correct DeleteBallotRequestModel", function () {

            var pollManageGuid = '091EA404-5AAE-4AA4-A5EF-E0625ACC33D4';
            var expectedUrl = '/api/manage/' + pollManageGuid + '/voters';

            var votersToDelete = [{
                BallotManageGuid: "275B1FF3-F37A-41F9-B91E-983F6D11429A",
                VoterName: "Derek",
                Votes: [
                    {
                        OptionNumber: 1,
                        OptionName: "One",
                        Value: 5
                    },
                    {
                        OptionNumber: 2,
                        OptionName: "Two",
                        Value: 1
                    }]
            },
                {
                    BallotManageGuid: "4F63A474-1136-4E8D-879C-881299A19207",
                    VoterName: "Betty",
                    Votes: [
                        {
                            OptionNumber: 1,
                            OptionName: "One",
                            Value: 1
                        },
                        {
                            OptionNumber: 3,
                            OptionName: "Three",
                            Value: 1
                        }]
                }];

            var expectedRequestBody = {
                BallotDeleteRequests: [
                    {
                        BallotManageGuid: '275B1FF3-F37A-41F9-B91E-983F6D11429A',
                        VoteDeleteRequests: [{ OptionNumber: 1 }, { OptionNumber: 2 }]
                    },
                    {
                        BallotManageGuid: '4F63A474-1136-4E8D-879C-881299A19207',
                        VoteDeleteRequests: [{ OptionNumber: 1 }, { OptionNumber: 3 }]
                    }
                ]
            };

            httpBackend
                .expect(
                    'DELETE',
                    expectedUrl,
                    expectedRequestBody,
                    function (headers) {
                        return headers['Content-Type'] === 'application/json; charset=utf-8';
                    })
                .respond(200);

            manageService.deleteVoters(pollManageGuid, votersToDelete);

            httpBackend.flush();

            //supressJasmineNoSpecMessage();
        });

    });
});<commit_msg>Remove commented out code.<commit_after>'use strict';

describe("ManageService", function () {

    beforeEach(module("GVA.Creation"));
    beforeEach(module("GVA.Common"));

    var manageService;
    var httpBackend;

    beforeEach(inject(function (ManageService, $httpBackend) {
        manageService = ManageService;
        httpBackend = $httpBackend;
    }));

    afterEach(function () {
        httpBackend.verifyNoOutstandingExpectation();
        httpBackend.verifyNoOutstandingRequest();

        // http://stackoverflow.com/questions/27016235/angular-js-unit-testing-httpbackend-spec-has-no-expectations
        expect('Suppress SPEC HAS NO EXPECTATIONS').toBeDefined();
    });

    describe("Delete Voters", function () {

        it("Contains the correct Content-Type header", function () {

            var pollManageGuid = '091EA404-5AAE-4AA4-A5EF-E0625ACC33D4';
            var expectedUrl = '/api/manage/' + pollManageGuid + '/voters';
            var expectedData = { "BallotDeleteRequests": [] };

            httpBackend.expect(
                    'DELETE',
                    expectedUrl,
                    expectedData,
                    function (headers) {
                        return headers['Content-Type'] === 'application/json; charset=utf-8';
                    }
                ).respond(200);

            manageService.deleteVoters(pollManageGuid, []);

            httpBackend.flush();
        });

        it("Creates correct DeleteBallotRequestModel", function () {

            var pollManageGuid = '091EA404-5AAE-4AA4-A5EF-E0625ACC33D4';
            var expectedUrl = '/api/manage/' + pollManageGuid + '/voters';

            var votersToDelete = [{
                BallotManageGuid: "275B1FF3-F37A-41F9-B91E-983F6D11429A",
                VoterName: "Derek",
                Votes: [
                    {
                        OptionNumber: 1,
                        OptionName: "One",
                        Value: 5
                    },
                    {
                        OptionNumber: 2,
                        OptionName: "Two",
                        Value: 1
                    }]
            },
                {
                    BallotManageGuid: "4F63A474-1136-4E8D-879C-881299A19207",
                    VoterName: "Betty",
                    Votes: [
                        {
                            OptionNumber: 1,
                            OptionName: "One",
                            Value: 1
                        },
                        {
                            OptionNumber: 3,
                            OptionName: "Three",
                            Value: 1
                        }]
                }];

            var expectedRequestBody = {
                BallotDeleteRequests: [
                    {
                        BallotManageGuid: '275B1FF3-F37A-41F9-B91E-983F6D11429A',
                        VoteDeleteRequests: [{ OptionNumber: 1 }, { OptionNumber: 2 }]
                    },
                    {
                        BallotManageGuid: '4F63A474-1136-4E8D-879C-881299A19207',
                        VoteDeleteRequests: [{ OptionNumber: 1 }, { OptionNumber: 3 }]
                    }
                ]
            };

            httpBackend
                .expect(
                    'DELETE',
                    expectedUrl,
                    expectedRequestBody,
                    function (headers) {
                        return headers['Content-Type'] === 'application/json; charset=utf-8';
                    })
                .respond(200);

            manageService.deleteVoters(pollManageGuid, votersToDelete);

            httpBackend.flush();
        });
    });
});<|endoftext|>