<commit_before>const Config = require('utils/config');
const App = require('utils/sanaAppInstance');
const Helpers = require('utils/helpers');
const CountedMap = require('utils/countedMap');

const Elements = require('collections/elements');
const Element = require('models/element');
const ShowIfs = require('collections/conditionals/showIfs');
const ShowIf = require('models/conditionals/showIf');

module.exports = Backbone.Model.extend({

    urlRoot: '/api/pages',

    constructor: function(attributes, options = {}) {
        // See model/procedure.js for explaination
        this.elements = new Elements(null, { parentPage: this });
        this.showIfs = new ShowIfs(null, { parentPage: this });

        // A cache that maps this page's Criteria Elements to their original pages
        this.dependentElementsToPage = new CountedMap();

        options.parse = true;
        Backbone.Model.prototype.constructor.call(this, attributes, options);
    },

    initialize: function() {
        // Propagate AJAX events from child to this model so that the status bar can be notified
        this.listenTo(this.elements, 'add', function(model, collection, options) {
            Helpers.propagateEvents(model, this);
        });
        this.listenTo(this.elements, 'reset', function(collection, options) {
            for (let model of collection.models) {
                Helpers.propagateEvents(model, this);
            }
        });
        this.listenTo(this.showIfs, 'add', function(model, collection, options) {
            Helpers.propagateEvents(model, this);
        });
        this.listenTo(this.showIfs, 'reset', function(collection, options) {
            for (let model of collection.models) {
                Helpers.propagateEvents(model, this);
            }
        });

        // When the Procedure has finished loading all the Pages, need to regenerate
        // all of this Page's dependents
        this.listenTo(this.collection, 'reset', function() {
            if (!this.collection) {
                this.stopListening(); // Model is about to be destroyed
                return;
            }

            this._computeDependentPages();
        });
    },

    destroy: function(options) {
        let myDisplayIndex = this.get('display_index');
        let pagesAfterMe = this.collection.filter(function(page) {
            return page.get('display_index') > myDisplayIndex;
        });

        if (myDisplayIndex === 0 && pagesAfterMe.length > 0) {
            let pageOne = this.collection.at(1);
            if (pageOne.showIfs.length > 0) {
                if (!confirm("Deleting this page will cause the second page to lose their conditionals. Are you sure you wish to continue?")) {
                    return;
                }

                pageOne.clearCriteria();
            }
        }

        for (let page of pagesAfterMe) {
            page._clearDependentElementsFromPage(this.get('id'));
        }

        Backbone.Model.prototype.destroy.call(this, options);
    },

    parse: function(response, options) {
        response.created = new Date(Date.parse(response.created));
        response.last_modified = new Date(Date.parse(response.last_modified));

        this.elements.reset(response.elements, { parse: true });
        delete response.elements;

        this.showIfs.reset(response.show_if, { parse: true });
        delete response.show_if;

        return response;
    },

    //--------------------------------------------------------------------------
    // View events
    //--------------------------------------------------------------------------

    createNewElement: function(concept, type) {
        let position = 0;
        if (!_.isEmpty(this.elements.models)) {
            let lastElement = _.max(this.elements.models, element => element.get('display_index'));
            position = lastElement.get('display_index') + 1;
        }

        // TODO(connor): call through to _onFormUpdate so that the eid can be generated
        let element = new Element({
            display_index: position,
            page: this.get('id'),
            question: concept.get('description'),
            concept: concept.get('id'),
            element_type: type,
        });

        let self = this;
        element.save({}, {
            beforeSend: function() {
                console.info('Creating Element');
                self.trigger('request');
            },
            success: function() {
                console.info('Created Element', element.get('id'));
                self.elements.add(element);
            },
            error: function() {
                console.warn('Failed to create Element', element.get('id'));
                App().RootView.showNotification('Failed to create Element!');
            },
        });
    },

    createNewCriteria: function() {
        let showIf = new ShowIf({
            page: this.get('id'),
            conditions: {
                node_type: 'EQUALS',
            },
        }, {
            parentPage: this,
        });

        let self = this;
        let pageId = this.get('id');
        showIf.save({}, {
            beforeSend: function() {
                console.info('Creating Criteria');
                self.trigger('request');
            },
            success: function() {
                console.info('Created Criteria', showIf.get('id'));
                self.showIfs.reset([ showIf ], { parse: true });
            },
            error: function() {
                console.warn('Failed to create Criteria', showIf.get('id'));
                App().RootView.showNotification('Failed to create Criteria!');
            },
        });
    },

    clearCriteria: function() {
        for (let model of this.showIfs.models) {
            model.destroy();
        }

        this.dependentElementsToPage.clear();
        this.save();
    },

    shouldConfirmBeforeSort: function(newIndex) {
        let oldIndex = this.get('display_index');
        let message;

        message = this._checkPagesBelowMeBeforeSort(oldIndex, newIndex);
        if (message) {
            return message;
        }

        message = this._checkPagesAboveMeBeforeSort(oldIndex, newIndex);
        if (message) {
            return message;
        }

        return false;
    },

    _checkPagesBelowMeBeforeSort: function(oldIndex, newIndex) {
        // Moving to a slot below current slot won't invalidate any conditions on this page
        // BUT it may invalidate some conditions on other pages
        if (oldIndex < newIndex) {
            let pagesAfterMe = this.collection.filter(function(page) {
                return page.get('display_index') > oldIndex && page.get('display_index') <= newIndex;
            });
            let pagesAfterMeDependingOnMe = [];

            for (let page of pagesAfterMe) {
                for (let myElement of this.elements.models) {
                    if (page.dependentElementsToPage.has(myElement.get('id'))) {
                        pagesAfterMeDependingOnMe.push(page);
                    }
                }
            }

            if (pagesAfterMeDependingOnMe.length > 0) {
                let self = this;
                return {
                    warningMessage: i18n.t("Reordering this page will cause some of your other pages' conditionals to lose their dependent elements because they appear before this page's new location."),
                    callback: function() {
                        for (let page of pagesAfterMeDependingOnMe) {
                            page._clearDependentElementsFromPage(self.get('id'));
                        }
                    },
                };
            }
        }

        if (oldIndex === 0) {
            let pageOne = this.collection.at(1);
            if (pageOne.showIfs.length > 0) {
                return {
                    warningMessage: i18n.t("Reordering this page will cause some of your other pages' conditionals to lose their dependent elements because they appear before this page's new location."),
                    callback: function() {
                        pageOne.clearCriteria();
                    },
                };
            }
        }

        return false;
    },

    _checkPagesAboveMeBeforeSort: function(oldIndex, newIndex) {
        // When newIndex < oldIndex (moving page up), then there may be pages inbetween that contain
        // elements that this page depends on
        if (this.showIfs.length === 0) {
            // Don't need to warn user if there's no side effects to sorting
            return false;
        }

        let self = this;
        let clearAllCriteria = function() {
            self.clearCriteria();
        };
        let clearElementsFromCriteria = function() {
            self._clearDependentElementsAfterPosition(newIndex);
        };

        if (newIndex === 0) {
            // Moving to first slot always remove all conditions
            return {
                warningMessage: i18n.t("Reordering this page will remove all of your conditionals."),
                callback: clearAllCriteria,
            };
        }

        let dependentPages = this.dependentElementsToPage.values();
        for (let dependentPage of dependentPages) {
            if (!dependentPage) {
                break;
            }

            let dependentPageIndex = dependentPage.item.get('display_index');
            if (dependentPageIndex >= newIndex) {
                // Dependant appears after this page so warn the user
                return {
                    warningMessage: i18n.t("Reordering this page will cause some of your conditionals to lose their dependent elements because they appear after this page's new location."),
                    callback: clearElementsFromCriteria,
                };
            }
        }

        return false;
    },

    //--------------------------------------------------------------------------
    // Template helpers
    //--------------------------------------------------------------------------

    isActive: function() {
        let activePageId = this.collection.parentProcedure.activePageId;
        return _.isNumber(activePageId) && this.get('id') === activePageId;
    },

    isBeingDependedUpon: function() {
        if (!this.collection.parentProcedure.activePageId) {
            // No active page so nobody is depending on me
            return false;
        }

        let activePage = this.collection.parentProcedure.getActivePage();
        for (let element of this.elements.models) {
            if (activePage.dependentElementsToPage.has(element.get('id'))) {
                return true;
            }
        }

        return false;
    },

    canHaveConditions: function() {
        return this.get('id') !== this.collection.at(0).get('id');
    },

    getPossibleOperandElements: function() {
        let myDisplayIndex = this.get('display_index');
        let pagesBeforeMe = this.collection.filter(function(page) {
            return page.get('display_index') < myDisplayIndex;
        });

        let elementsByPage = [];

        for (let page of pagesBeforeMe) {
            let pageElements = [];

            for (let element of page.elements.models) {
                if (element.isPluginBased()) {
                    // Plugin-based elements do not have any answers so they cannot be compared
                    continue;
                }

                let attributes = _.clone(element.attributes);
                attributes.question = attributes.question || i18n.t(element.get('element_type'));
                pageElements.push(element.attributes);
            }

            elementsByPage.push({
                pageLabel: i18n.t('Page displayIndex', { displayIndex: (page.get('display_index') + 1) }),
                pageElements: pageElements,
            });
        }

        return elementsByPage;
    },

    //--------------------------------------------------------------------------
    // Misc helpers
    //--------------------------------------------------------------------------

    _computeDependentPages: function() {
        this.dependentElementsToPage.clear();

        if (this.showIfs.length === 0) { // Page with no conditions
            return;
        }

        // WARNING:
        // This method is quite slow and can stall the UI thread when there's
        // more than 10 ConditionalNodes. Use this method sparingly

        let dependentElements = this.showIfs.at(0).rootConditionalNode.getDependentElements();

        for (let elementId of dependentElements) {
            let dependentPage = this.collection.find(function(page) {
                return !!page.elements.get(elementId);
            });

            this.dependentElementsToPage.set(elementId, dependentPage);
        }

        console.log('onReset', this.dependentElementsToPage);
    },

    _clearDependentElementsAfterPosition: function(position) {
        if (this.showIfs.length === 0) { // Page with no conditions
            return;
        }

        this.showIfs.at(0).rootConditionalNode.clearDependentElementsAfterPosition(position);
    },

    _clearDependentElementsFromPage: function(pageId) {
        if (this.showIfs.length === 0) { // Page with no conditions
            return;
        }

        this.showIfs.at(0).rootConditionalNode.clearDependentElementsFromPage(pageId);
    },

});
<commit_msg>Fixed checking if page is actually first page<commit_after>const Config = require('utils/config');
const App = require('utils/sanaAppInstance');
const Helpers = require('utils/helpers');
const CountedMap = require('utils/countedMap');

const Elements = require('collections/elements');
const Element = require('models/element');
const ShowIfs = require('collections/conditionals/showIfs');
const ShowIf = require('models/conditionals/showIf');

module.exports = Backbone.Model.extend({

    urlRoot: '/api/pages',

    constructor: function(attributes, options = {}) {
        // See model/procedure.js for explaination
        this.elements = new Elements(null, { parentPage: this });
        this.showIfs = new ShowIfs(null, { parentPage: this });

        // A cache that maps this page's Criteria Elements to their original pages
        this.dependentElementsToPage = new CountedMap();

        options.parse = true;
        Backbone.Model.prototype.constructor.call(this, attributes, options);
    },

    initialize: function() {
        // Propagate AJAX events from child to this model so that the status bar can be notified
        this.listenTo(this.elements, 'add', function(model, collection, options) {
            Helpers.propagateEvents(model, this);
        });
        this.listenTo(this.elements, 'reset', function(collection, options) {
            for (let model of collection.models) {
                Helpers.propagateEvents(model, this);
            }
        });
        this.listenTo(this.showIfs, 'add', function(model, collection, options) {
            Helpers.propagateEvents(model, this);
        });
        this.listenTo(this.showIfs, 'reset', function(collection, options) {
            for (let model of collection.models) {
                Helpers.propagateEvents(model, this);
            }
        });

        // When the Procedure has finished loading all the Pages, need to regenerate
        // all of this Page's dependents
        this.listenTo(this.collection, 'reset', function() {
            if (!this.collection) {
                this.stopListening(); // Model is about to be destroyed
                return;
            }

            this._computeDependentPages();
        });
    },

    destroy: function(options) {
        let myDisplayIndex = this.get('display_index');
        let pagesAfterMe = this.collection.filter(function(page) {
            return page.get('display_index') > myDisplayIndex;
        });

        if (this.collection.at(0) === this && pagesAfterMe.length > 0) {
            let pageOne = this.collection.at(1);
            if (pageOne.showIfs.length > 0) {
                if (!confirm("Deleting this page will cause the second page to lose their conditionals. Are you sure you wish to continue?")) {
                    return;
                }

                pageOne.clearCriteria();
            }
        }

        for (let page of pagesAfterMe) {
            page._clearDependentElementsFromPage(this.get('id'));
        }

        Backbone.Model.prototype.destroy.call(this, options);
    },

    parse: function(response, options) {
        response.created = new Date(Date.parse(response.created));
        response.last_modified = new Date(Date.parse(response.last_modified));

        this.elements.reset(response.elements, { parse: true });
        delete response.elements;

        this.showIfs.reset(response.show_if, { parse: true });
        delete response.show_if;

        return response;
    },

    //--------------------------------------------------------------------------
    // View events
    //--------------------------------------------------------------------------

    createNewElement: function(concept, type) {
        let position = 0;
        if (!_.isEmpty(this.elements.models)) {
            let lastElement = _.max(this.elements.models, element => element.get('display_index'));
            position = lastElement.get('display_index') + 1;
        }

        // TODO(connor): call through to _onFormUpdate so that the eid can be generated
        let element = new Element({
            display_index: position,
            page: this.get('id'),
            question: concept.get('description'),
            concept: concept.get('id'),
            element_type: type,
        });

        let self = this;
        element.save({}, {
            beforeSend: function() {
                console.info('Creating Element');
                self.trigger('request');
            },
            success: function() {
                console.info('Created Element', element.get('id'));
                self.elements.add(element);
            },
            error: function() {
                console.warn('Failed to create Element', element.get('id'));
                App().RootView.showNotification('Failed to create Element!');
            },
        });
    },

    createNewCriteria: function() {
        let showIf = new ShowIf({
            page: this.get('id'),
            conditions: {
                node_type: 'EQUALS',
            },
        }, {
            parentPage: this,
        });

        let self = this;
        let pageId = this.get('id');
        showIf.save({}, {
            beforeSend: function() {
                console.info('Creating Criteria');
                self.trigger('request');
            },
            success: function() {
                console.info('Created Criteria', showIf.get('id'));
                self.showIfs.reset([ showIf ], { parse: true });
            },
            error: function() {
                console.warn('Failed to create Criteria', showIf.get('id'));
                App().RootView.showNotification('Failed to create Criteria!');
            },
        });
    },

    clearCriteria: function() {
        for (let model of this.showIfs.models) {
            model.destroy();
        }

        this.dependentElementsToPage.clear();
        this.save();
    },

    shouldConfirmBeforeSort: function(newIndex) {
        let oldIndex = this.get('display_index');
        let message;

        message = this._checkPagesBelowMeBeforeSort(oldIndex, newIndex);
        if (message) {
            return message;
        }

        message = this._checkPagesAboveMeBeforeSort(oldIndex, newIndex);
        if (message) {
            return message;
        }

        return false;
    },

    _checkPagesBelowMeBeforeSort: function(oldIndex, newIndex) {
        // Moving to a slot below current slot won't invalidate any conditions on this page
        // BUT it may invalidate some conditions on other pages
        if (oldIndex < newIndex) {
            let pagesAfterMe = this.collection.filter(function(page) {
                return page.get('display_index') > oldIndex && page.get('display_index') <= newIndex;
            });
            let pagesAfterMeDependingOnMe = [];

            for (let page of pagesAfterMe) {
                for (let myElement of this.elements.models) {
                    if (page.dependentElementsToPage.has(myElement.get('id'))) {
                        pagesAfterMeDependingOnMe.push(page);
                    }
                }
            }

            if (pagesAfterMeDependingOnMe.length > 0) {
                let self = this;
                return {
                    warningMessage: i18n.t("Reordering this page will cause some of your other pages' conditionals to lose their dependent elements because they appear before this page's new location."),
                    callback: function() {
                        for (let page of pagesAfterMeDependingOnMe) {
                            page._clearDependentElementsFromPage(self.get('id'));
                        }
                    },
                };
            }
        }

        if (this.collection.at(0) === this) {
            let pageOne = this.collection.at(1);
            if (pageOne.showIfs.length > 0) {
                return {
                    warningMessage: i18n.t("Reordering this page will cause some of your other pages' conditionals to lose their dependent elements because they appear before this page's new location."),
                    callback: function() {
                        pageOne.clearCriteria();
                    },
                };
            }
        }

        return false;
    },

    _checkPagesAboveMeBeforeSort: function(oldIndex, newIndex) {
        // When newIndex < oldIndex (moving page up), then there may be pages inbetween that contain
        // elements that this page depends on
        if (this.showIfs.length === 0) {
            // Don't need to warn user if there's no side effects to sorting
            return false;
        }

        let self = this;
        let clearAllCriteria = function() {
            self.clearCriteria();
        };
        let clearElementsFromCriteria = function() {
            self._clearDependentElementsAfterPosition(newIndex);
        };

        if (newIndex === 0) {
            // Moving to first slot always remove all conditions
            return {
                warningMessage: i18n.t("Reordering this page will remove all of your conditionals."),
                callback: clearAllCriteria,
            };
        }

        let dependentPages = this.dependentElementsToPage.values();
        for (let dependentPage of dependentPages) {
            if (!dependentPage) {
                break;
            }

            let dependentPageIndex = dependentPage.item.get('display_index');
            if (dependentPageIndex >= newIndex) {
                // Dependant appears after this page so warn the user
                return {
                    warningMessage: i18n.t("Reordering this page will cause some of your conditionals to lose their dependent elements because they appear after this page's new location."),
                    callback: clearElementsFromCriteria,
                };
            }
        }

        return false;
    },

    //--------------------------------------------------------------------------
    // Template helpers
    //--------------------------------------------------------------------------

    isActive: function() {
        let activePageId = this.collection.parentProcedure.activePageId;
        return _.isNumber(activePageId) && this.get('id') === activePageId;
    },

    isBeingDependedUpon: function() {
        if (!this.collection.parentProcedure.activePageId) {
            // No active page so nobody is depending on me
            return false;
        }

        let activePage = this.collection.parentProcedure.getActivePage();
        for (let element of this.elements.models) {
            if (activePage.dependentElementsToPage.has(element.get('id'))) {
                return true;
            }
        }

        return false;
    },

    canHaveConditions: function() {
        return this.get('id') !== this.collection.at(0).get('id');
    },

    getPossibleOperandElements: function() {
        let myDisplayIndex = this.get('display_index');
        let pagesBeforeMe = this.collection.filter(function(page) {
            return page.get('display_index') < myDisplayIndex;
        });

        let elementsByPage = [];

        for (let page of pagesBeforeMe) {
            let pageElements = [];

            for (let element of page.elements.models) {
                if (element.isPluginBased()) {
                    // Plugin-based elements do not have any answers so they cannot be compared
                    continue;
                }

                let attributes = _.clone(element.attributes);
                attributes.question = attributes.question || i18n.t(element.get('element_type'));
                pageElements.push(element.attributes);
            }

            elementsByPage.push({
                pageLabel: i18n.t('Page displayIndex', { displayIndex: (page.get('display_index') + 1) }),
                pageElements: pageElements,
            });
        }

        return elementsByPage;
    },

    //--------------------------------------------------------------------------
    // Misc helpers
    //--------------------------------------------------------------------------

    _computeDependentPages: function() {
        this.dependentElementsToPage.clear();

        if (this.showIfs.length === 0) { // Page with no conditions
            return;
        }

        // WARNING:
        // This method is quite slow and can stall the UI thread when there's
        // more than 10 ConditionalNodes. Use this method sparingly

        let dependentElements = this.showIfs.at(0).rootConditionalNode.getDependentElements();

        for (let elementId of dependentElements) {
            let dependentPage = this.collection.find(function(page) {
                return !!page.elements.get(elementId);
            });

            this.dependentElementsToPage.set(elementId, dependentPage);
        }

        console.log('onReset', this.dependentElementsToPage);
    },

    _clearDependentElementsAfterPosition: function(position) {
        if (this.showIfs.length === 0) { // Page with no conditions
            return;
        }

        this.showIfs.at(0).rootConditionalNode.clearDependentElementsAfterPosition(position);
    },

    _clearDependentElementsFromPage: function(pageId) {
        if (this.showIfs.length === 0) { // Page with no conditions
            return;
        }

        this.showIfs.at(0).rootConditionalNode.clearDependentElementsFromPage(pageId);
    },

});
<|endoftext|>


<commit_before>const ENUMS = require('./enums.js');

exports.getHAPTypeByAttributeType = function(attributeType) {
    let HAPType;

    switch (attributeType) {
        case ENUMS.CAAttributeType.CAAttributeTypeOnOff:
        case ENUMS.CAAttributeType.CAAttributeTypeSiren:
            HAPType = 'On';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeDimmingLevel:
            HAPType = 'Brightness';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeTemperature:
            HAPType = 'CurrentTemperature';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeTargetTemperature:
            HAPType = 'TargetTemperature';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeRelativeHumidity:
            HAPType = 'CurrentRelativeHumidity';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeBatteryLevel:
            HAPType = 'BatteryLevel';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeWindowPosition:
        case ENUMS.CAAttributeType.CAAttributeTypeOpenClose:
            HAPType = 'ContactSensorState';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeBrightness:
            HAPType = 'CurrentAmbientLightLevel';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeFloodAlarm:
        case ENUMS.CAAttributeType.CAAttributeTypeLeakAlarm:
        case ENUMS.CAAttributeType.CAAttributeTypeOilAlarm:
        case ENUMS.CAAttributeType.CAAttributeTypeWaterAlarm:
            HAPType = 'LeakDetected';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypePosition:
            HAPType = 'CurrentPosition';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeSmokeAlarm:
            HAPType = 'SmokeDetected';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeCO2Level:
            HAPType = 'CarbonDioxideLevel';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeMotionAlarm:
        case ENUMS.CAAttributeType.CAAttributeTypePresenceAlarm:
            HAPType = 'MotionDetected';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypePresenceAlarm:
            HAPType = 'OccupancyDetected';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeTamperAlarm:
            HAPType = 'StatusTampered';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeBatteryLowAlarm:
            HAPType = 'StatusLowBattery';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeCOAlarm:
            HAPType = 'CarbonMonoxideDetected';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeMalfunctionAlarm:
            HAPType = 'StatusFault';
            break;
    }

    return HAPType;
};
<commit_msg>fixed mapping<commit_after>const ENUMS = require('./enums.js');

exports.getHAPTypeByAttributeType = function(attributeType) {
    let HAPType;

    switch (attributeType) {
        case ENUMS.CAAttributeType.CAAttributeTypeOnOff:
        case ENUMS.CAAttributeType.CAAttributeTypeSiren:
            HAPType = 'On';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeDimmingLevel:
            HAPType = 'Brightness';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeTemperature:
            HAPType = 'CurrentTemperature';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeTargetTemperature:
            HAPType = 'TargetTemperature';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeRelativeHumidity:
            HAPType = 'CurrentRelativeHumidity';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeBatteryLevel:
            HAPType = 'BatteryLevel';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeWindowPosition:
        case ENUMS.CAAttributeType.CAAttributeTypeOpenClose:
            HAPType = 'ContactSensorState';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeBrightness:
            HAPType = 'CurrentAmbientLightLevel';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeFloodAlarm:
        case ENUMS.CAAttributeType.CAAttributeTypeLeakAlarm:
        case ENUMS.CAAttributeType.CAAttributeTypeOilAlarm:
        case ENUMS.CAAttributeType.CAAttributeTypeWaterAlarm:
            HAPType = 'LeakDetected';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypePosition:
            HAPType = 'CurrentPosition';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeSmokeAlarm:
            HAPType = 'SmokeDetected';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeCO2Level:
            HAPType = 'CarbonDioxideLevel';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeMotionAlarm:
            HAPType = 'MotionDetected';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypePresenceAlarm:
            HAPType = 'OccupancyDetected';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeTamperAlarm:
            HAPType = 'StatusTampered';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeBatteryLowAlarm:
            HAPType = 'StatusLowBattery';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeCOAlarm:
            HAPType = 'CarbonMonoxideDetected';
            break;
        case ENUMS.CAAttributeType.CAAttributeTypeMalfunctionAlarm:
            HAPType = 'StatusFault';
            break;
    }

    return HAPType;
};
<|endoftext|>


<commit_before>/**
 * @file
 * Search results are collected and rendered here
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import request from 'superagent';

import {SearchFieldComponent} from '../SearchField/SearchField.component';
import Link from '../Link';
import {Spinner} from '../General/spinner.component';
import {CartButton} from '../Cart/CartButton.component';

function parseSearchResult(result) {
  return result.map(level => {
    const {title, items, decommissioned, index, parent} = level;
    const subLevel = items && items.length && parseSearchResult(items) || [];
    return {
      title,
      dk5: index && {index, title} || null,
      decommissioned: decommissioned || false,
      items: subLevel,
      parent: parent && parent.title
    };
  });
}

const SearchResultSingle = ({title, dk5, parent, pro, cart, decommissioned}) => {
  const infoDecommissioned = decommissioned ? 'decommissioned' : '';
  return (
    <div className={`result-element ${infoDecommissioned}`}>

        {title},
        se <Link to={`/hierarchy/${dk5.index}`}>{dk5.index}</Link> {parent}
        {pro && <CartButton index={dk5.index} cart={cart}/>}

  );
};

const SearchResultGroup = ({title, items, pro, cart}) => {
  return (

{title}

        {items.map(el =>
<SearchResultSingle pro={pro} cart={cart} {...el}/>
)}

  );
};

export class SearchResultsContainerComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      corrections: {},
      searchResults: {},
      query: '',
      suggestions: {}, // As in spelling suggestions
      pendingSearch: false,
      error: ''
    };
  }

  componentDidMount() {
    this.searchWasTriggered(this.props);
  }

  componentDidUpdate() {
    this.searchWasTriggered(this.props);
  }

  searchWasTriggered(props) {
    const searchResults = this.state.searchResults;
    const {limit = 10, offset = 0, q = null, sort = 'relevance', spell = 'dictionary'} = props.params;
    const searchUrl = encodeURI(`/api/search?q=${q}&limit=${limit}&offset=${offset}&sort=${sort}&spell=${spell}`);

    if (q && !searchResults[searchUrl]) {
      searchResults[searchUrl] = [];
      this.setState({
        searchResults: searchResults,
        query: searchUrl
      });

      setTimeout(() => {
        this.setState({pendingSearch: true});
      }, 100);

      request
        .get(searchUrl)
        .set('Accept', 'application/json')
        .end((err, res) => {
          let error = '';

          if (err) {
            console.error(err); // eslint-disable-line no-console
          }

          if (res.body.isIndex) {
            window.location = `/#!/hierarchy/${res.body.parameters.query}`;
          }

          try {
            const bd = JSON.parse(res.text);
            searchResults[searchUrl] = parseSearchResult(bd.result || []);
            const corrections = this.state.corrections;
            const suggestions = this.state.suggestions;

            if (bd.correction && bd.correction.q) {
              corrections[searchUrl] = bd.correction;
            }

            if (bd.correction && bd.correction.suggestions) {
              suggestions[searchUrl] = bd.correction.suggestions;
            }

            this.setState({
              corrections,
              suggestions,
              searchResults: searchResults
            });

          }
          catch (e) {
            error = 'Der skete desværre en fejl. Prøv evt. at ændre din søgning en smule og søg igen';
          }

          this.setState({
            query: searchUrl,
            pendingSearch: false,
            error: error
          });
        });
    }
    else if (q && this.state.query !== searchUrl) {
      this.setState({
        query: searchUrl
      });
    }
  }

  renderCategoryTile(categoryIndex, category) {
    const styles = {
      backgroundImage: `url(${category.backgroundImage})`
    };

    return (
      <a style={styles} href={`#!/hierarchy/${category.index}`} className='category-tile--container' id={`category-tile--container--${category.index}`}>

            {category.label}
            {categoryIndex}

    );
  }

  renderCategoryTiles(categories) {
    const tiles = Object.keys(categories)
      .map(categoryIndex => this.renderCategoryTile(categoryIndex, categories[categoryIndex]));

    return (

Eller vælg her

          {tiles}

    );
  }

  renderSpellingError(correction) {
    return (

          Din søgning gav ikke nogle resultater, vi har i stedet søgt på {correction.q}.
          Hvis du vil prøve din søgning alligevel <Link to={correction.href}>klik her!</Link>

    );
  }

  renderNoResults() {
    let message = '';
    let suggestions = '';

    if (this.state.pendingSearch) {
      message = 'Søger efter emner...';
    }
    else if (this.state.error.length) {
      message = this.state.error;
    }
    else if (this.state.suggestions[this.state.query] && this.state.suggestions[this.state.query].length) {
      message = 'Vi fandt ikke nogen resultater denne gang, prøv med nogle af disse søgninger!';
      suggestions = this.state.suggestions[this.state.query].map(sug => {
        return (

            <Link to={sug.href} key={sug.match}>{sug.match}</Link>

        );
      });
    }

    return (

          {this.state.pendingSearch && <Spinner size="medium"/>}

        {message}
        {suggestions}

    );
  }

  render() {
    const params = this.props.params || {};
    const searchField = (
      <SearchFieldComponent
        search={this.props.search}
        suggest={this.props.suggest}
        params={params}
        pro={false}
      />
    );

    const results = (this.state.searchResults[this.state.query] || []).map(entry => {
      if (!entry.dk5) {
        return null;
      }
      if (entry.items.length === 0) {
        return (

            <SearchResultSingle key={entry.dk5.index} cart={this.props.cart} {...entry} />

        );
      }

      return (<SearchResultGroup key={entry.title} pro={this.props.pro} cart={this.props.cart} {...entry} />);
    });

    return (
      <div className={`container ${Object.keys(this.props.cart.contents).length ? 'show-cart' : ''}`}>
        {searchField}
        {this.state.corrections[this.state.query] && this.renderSpellingError(this.state.corrections[this.state.query])}
        {results.length && results || !this.state.query && this.renderCategoryTiles(this.props.search.categories) || this.renderNoResults()}

    );
  }
}

SearchResultsContainerComponent.displayName = 'SearchResults';
SearchResultsContainerComponent.propTypes = {
  cart: PropTypes.object.isRequired,
  params: PropTypes.object,
  search: PropTypes.object,
  suggest: PropTypes.object
};
<commit_msg>#245: search result skip decommisioned records<commit_after>/**
 * @file
 * Search results are collected and rendered here
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import request from 'superagent';

import {SearchFieldComponent} from '../SearchField/SearchField.component';
import Link from '../Link';
import {Spinner} from '../General/spinner.component';
import {CartButton} from '../Cart/CartButton.component';

function parseSearchResult(result) {
  return result.map(level => {
    const {title, items, decommissioned, index, parent} = level;
    const subLevel = items && items.length && parseSearchResult(items) || [];
    return {
      title,
      dk5: index && {index, title} || null,
      decommissioned: decommissioned || false,
      items: subLevel,
      parent: parent && parent.title
    };
  });
}

const SearchResultSingle = ({title, dk5, parent, pro, cart, decommissioned}) => {
  const infoDecommissioned = decommissioned ? 'decommissioned' : '';
  return ( !decommissioned &&
    <div className={`result-element ${infoDecommissioned}`}>

        {title},
        se <Link to={`/hierarchy/${dk5.index}`}>{dk5.index}</Link> {parent}
        {pro && <CartButton index={dk5.index} cart={cart}/>}

  );
};

const SearchResultGroup = ({title, items, pro, cart}) => {
  return (

{title}

        {items.map(el =>
<SearchResultSingle pro={pro} cart={cart} {...el}/>
)}

  );
};

export class SearchResultsContainerComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      corrections: {},
      searchResults: {},
      query: '',
      suggestions: {}, // As in spelling suggestions
      pendingSearch: false,
      error: ''
    };
  }

  componentDidMount() {
    this.searchWasTriggered(this.props);
  }

  componentDidUpdate() {
    this.searchWasTriggered(this.props);
  }

  searchWasTriggered(props) {
    const searchResults = this.state.searchResults;
    const {limit = 10, offset = 0, q = null, sort = 'relevance', spell = 'dictionary'} = props.params;
    const searchUrl = encodeURI(`/api/search?q=${q}&limit=${limit}&offset=${offset}&sort=${sort}&spell=${spell}`);

    if (q && !searchResults[searchUrl]) {
      searchResults[searchUrl] = [];
      this.setState({
        searchResults: searchResults,
        query: searchUrl
      });

      setTimeout(() => {
        this.setState({pendingSearch: true});
      }, 100);

      request
        .get(searchUrl)
        .set('Accept', 'application/json')
        .end((err, res) => {
          let error = '';

          if (err) {
            console.error(err); // eslint-disable-line no-console
          }

          if (res.body.isIndex) {
            window.location = `/#!/hierarchy/${res.body.parameters.query}`;
          }

          try {
            const bd = JSON.parse(res.text);
            searchResults[searchUrl] = parseSearchResult(bd.result || []);
            const corrections = this.state.corrections;
            const suggestions = this.state.suggestions;

            if (bd.correction && bd.correction.q) {
              corrections[searchUrl] = bd.correction;
            }

            if (bd.correction && bd.correction.suggestions) {
              suggestions[searchUrl] = bd.correction.suggestions;
            }

            this.setState({
              corrections,
              suggestions,
              searchResults: searchResults
            });

          }
          catch (e) {
            error = 'Der skete desværre en fejl. Prøv evt. at ændre din søgning en smule og søg igen';
          }

          this.setState({
            query: searchUrl,
            pendingSearch: false,
            error: error
          });
        });
    }
    else if (q && this.state.query !== searchUrl) {
      this.setState({
        query: searchUrl
      });
    }
  }

  renderCategoryTile(categoryIndex, category) {
    const styles = {
      backgroundImage: `url(${category.backgroundImage})`
    };

    return (
      <a style={styles} href={`#!/hierarchy/${category.index}`} className='category-tile--container' id={`category-tile--container--${category.index}`}>

            {category.label}
            {categoryIndex}

    );
  }

  renderCategoryTiles(categories) {
    const tiles = Object.keys(categories)
      .map(categoryIndex => this.renderCategoryTile(categoryIndex, categories[categoryIndex]));

    return (

Eller vælg her

          {tiles}

    );
  }

  renderSpellingError(correction) {
    return (

          Din søgning gav ikke nogle resultater, vi har i stedet søgt på {correction.q}.
          Hvis du vil prøve din søgning alligevel <Link to={correction.href}>klik her!</Link>

    );
  }

  renderNoResults() {
    let message = '';
    let suggestions = '';

    if (this.state.pendingSearch) {
      message = 'Søger efter emner...';
    }
    else if (this.state.error.length) {
      message = this.state.error;
    }
    else if (this.state.suggestions[this.state.query] && this.state.suggestions[this.state.query].length) {
      message = 'Vi fandt ikke nogen resultater denne gang, prøv med nogle af disse søgninger!';
      suggestions = this.state.suggestions[this.state.query].map(sug => {
        return (

            <Link to={sug.href} key={sug.match}>{sug.match}</Link>

        );
      });
    }

    return (

          {this.state.pendingSearch && <Spinner size="medium"/>}

        {message}
        {suggestions}

    );
  }

  render() {
    const params = this.props.params || {};
    const searchField = (
      <SearchFieldComponent
        search={this.props.search}
        suggest={this.props.suggest}
        params={params}
        pro={false}
      />
    );

    const results = (this.state.searchResults[this.state.query] || []).map(entry => {
      if (!entry.dk5) {
        return null;
      }
      if (entry.items.length === 0) {
        return (

            <SearchResultSingle key={entry.dk5.index} cart={this.props.cart} {...entry} />

        );
      }

      return (<SearchResultGroup key={entry.title} pro={this.props.pro} cart={this.props.cart} {...entry} />);
    });

    return (
      <div className={`container ${Object.keys(this.props.cart.contents).length ? 'show-cart' : ''}`}>
        {searchField}
        {this.state.corrections[this.state.query] && this.renderSpellingError(this.state.corrections[this.state.query])}
        {results.length && results || !this.state.query && this.renderCategoryTiles(this.props.search.categories) || this.renderNoResults()}

    );
  }
}

SearchResultsContainerComponent.displayName = 'SearchResults';
SearchResultsContainerComponent.propTypes = {
  cart: PropTypes.object.isRequired,
  params: PropTypes.object,
  search: PropTypes.object,
  suggest: PropTypes.object
};
<|endoftext|>


<commit_before>-ace.define("ace/mode/verilog_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function(e, t, n) {
    "use strict";
    var r = e("../lib/oop"),
        i = e("./text_highlight_rules").TextHighlightRules,
        s = function() {
            var e = "if|endif|else\sif",
                t = "use",
                n = "near|with|around|mention",
                r = this.createKeywordMapper({
                    "support.function": n,
                    keyword: e,
                    "constant.language": t
                }, "identifier", !0);
            this.$rules = {
                start: [{
                    token: "comment",
                    regex: "//.*$"
                }, {
                    token: "comment.start",
                    regex: "/\\*",
                    next: [{
                        token: "comment.end",
                        regex: "\\*/",
                        next: "start"
                    }, {
                        defaultToken: "comment"
                    }]
                }, {
                    token: "string",
                    regex: '".*?"'
                }, {
                    token: "string",
                    regex: "'.*?'"
                }, {
                    token: "constant.numeric",
                    regex: "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
                }, {
                    token: r,
                    regex: "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
                }, {
                    token: "keyword.operator",
                    regex: "\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|=|or"
                }, {
                    token: "paren.lparen",
                    regex: "[\\(]"
                }, {
                    token: "paren.rparen",
                    regex: "[\\)]"
                }, {
                    token: "text",
                    regex: "\\s+"
                }, {
                    token: "if.start",
                    regex: "IF"
                }, {
                    token: "if.end",
                    regex: "ENDIF"
                }]
            }, this.normalizeRules()
        };
    r.inherits(s, i), t.VerilogHighlightRules = s
}), ace.define("ace/mode/verilog", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text", "ace/mode/verilog_highlight_rules", "ace/range"], function(e, t, n) {
    "use strict";
    var r = e("../lib/oop"),
        i = e("./text").Mode,
        s = e("./verilog_highlight_rules").VerilogHighlightRules,
        o = e("../range").Range,
        u = function() {
            this.HighlightRules = s, this.$behaviour = this.$defaultBehaviour
        };
    r.inherits(u, i),
        function() {
            this.lineCommentStart = "//", this.blockComment = {
                start: "/*",
                end: "*/"
            }, this.$id = "ace/mode/verilog"
        }.call(u.prototype), t.Mode = u
})
<commit_msg>Update mode-verilog.js<commit_after>-ace.define("ace/mode/verilog_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function(e, t, n) {
    "use strict";
    var r = e("../lib/oop"),
        i = e("./text_highlight_rules").TextHighlightRules,
        s = function() {
            var e = "if|endif|else\\sif",
                t = "use",
                n = "near|with|around|mention",
                r = this.createKeywordMapper({
                    "support.function": n,
                    keyword: e,
                    "constant.language": t
                }, "identifier", !0);
            this.$rules = {
                start: [{
                    token: "comment",
                    regex: "//.*$"
                }, {
                    token: "comment.start",
                    regex: "/\\*",
                    next: [{
                        token: "comment.end",
                        regex: "\\*/",
                        next: "start"
                    }, {
                        defaultToken: "comment"
                    }]
                }, {
                    token: "string",
                    regex: '".*?"'
                }, {
                    token: "string",
                    regex: "'.*?'"
                }, {
                    token: "constant.numeric",
                    regex: "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
                }, {
                    token: r,
                    regex: "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
                }, {
                    token: "keyword.operator",
                    regex: "\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|=|or"
                }, {
                    token: "paren.lparen",
                    regex: "[\\(]"
                }, {
                    token: "paren.rparen",
                    regex: "[\\)]"
                }, {
                    token: "text",
                    regex: "\\s+"
                }, {
                    token: "if.start",
                    regex: "IF"
                }, {
                    token: "if.end",
                    regex: "ENDIF"
                }]
            }, this.normalizeRules()
        };
    r.inherits(s, i), t.VerilogHighlightRules = s
}), ace.define("ace/mode/verilog", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text", "ace/mode/verilog_highlight_rules", "ace/range"], function(e, t, n) {
    "use strict";
    var r = e("../lib/oop"),
        i = e("./text").Mode,
        s = e("./verilog_highlight_rules").VerilogHighlightRules,
        o = e("../range").Range,
        u = function() {
            this.HighlightRules = s, this.$behaviour = this.$defaultBehaviour
        };
    r.inherits(u, i),
        function() {
            this.lineCommentStart = "//", this.blockComment = {
                start: "/*",
                end: "*/"
            }, this.$id = "ace/mode/verilog"
        }.call(u.prototype), t.Mode = u
})
<|endoftext|>


<commit_before>/*
*	Code to display coderwall.com badges
*/

$(document).ready(function(){
        var member = $('#github_user').text();
        var coderwallJSONurl ="http://www.coderwall.com/" + member + ".json?callback=?";
        var height = 75;
        var width = 75;

        $.getJSON(coderwallJSONurl, function(data) {
        $("
Coderwall Achievements

").appendTo("#coderwall");
          $.each(data.data.badges, function(i, item) {
            $("").attr("src", item.badge)
              .attr("float", "left")
              .attr("title", item.name + ": " + item.description)
              .attr("alt", item.name)
              .attr("height", height)
              .attr("width", width)
              .appendTo("#coderwall")
              .hover(
                  function(){
                      $(this).css("opacity","0.6");
                  },
                  function(){
                      $(this).css("opacity","1.0");
                  }
              )
            });
        });
});
<commit_msg>Added link to member's coderwall page<commit_after>/*
*	Code to display coderwall.com badges
*/

$(document).ready(function(){
        var member = $('#github_user').text();
        var coderwallJSONurl ="http://www.coderwall.com/" + member + ".json?callback=?";
        var height = 75;
        var width = 75;

        $.getJSON(coderwallJSONurl, function(data) {
        $("Coderwall Achievements

").appendTo("#coderwall");
          $.each(data.data.badges, function(i, item) {
            $("").attr("src", item.badge)
              .attr("float", "left")
              .attr("title", item.name + ": " + item.description)
              .attr("alt", item.name)
              .attr("height", height)
              .attr("width", width)
              .appendTo("#coderwall")
              .hover(
                  function(){
                      $(this).css("opacity","0.6");
                  },
                  function(){
                      $(this).css("opacity","1.0");
                  }
              )
            });
        });
});
<|endoftext|>


<commit_before>// Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import SpawnNacl from 'axiom_pnacl/spawn_nacl';

import AxiomError from 'axiom/core/error';

// @note ExecuteContext from 'axiom/bindings/fs/execute_context'

/**
 * Invokes the vim editor.
 */
export var VimCommand = function(sourceUrl) {
  this.sourceUrl = sourceUrl;
};

VimCommand.prototype.run = function(cx) {
  return new Promise(function(resolve, reject) {
    // SpawnNacl notifies ok/error completion on the execution context.
    cx.onClose.listenOnce(function(reason, value) {
      if (reason === 'ok') {
        resolve(value);
      } else {
        reject(value);
      }
    }.bind(this));

    navigator.webkitPersistentStorage.requestQuota(1024 * 1024,
      function(bytes) {
        window.webkitRequestFileSystem(window.TEMPORARAY, bytes, function(fs) {
          this.runWithFileSystem(cx, fs);
        }.bind(this));
      }.bind(this),
      function() {
        this.executeContext.closeErrorValue(
            new AxiomError.Runtime('Failed to allocate DOM file system space.'));
      }.bind(this)
    );
  }.bind(this));
};

VimCommand.prototype.runWithFileSystem = function(cx, fs) {
  // TODO(rpaquay): Cleaner URL handling.
  var url = this.sourceUrl;
  url = url.replace('/import.html', '/pnacl/vim.nmf');

  // Execute pnacl vim.
  var nacl = new SpawnNacl('application/x-pnacl', url, cx);
  nacl.run();
};

export default VimCommand;
<commit_msg>Remove temporary filesystem creation from vim command.<commit_after>// Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import SpawnNacl from 'axiom_pnacl/spawn_nacl';

import AxiomError from 'axiom/core/error';

// @note ExecuteContext from 'axiom/bindings/fs/execute_context'

/**
 * Invokes the vim editor.
 */
export var VimCommand = function(sourceUrl) {
  this.sourceUrl = sourceUrl;
};

VimCommand.prototype.run = function(cx) {
  return new Promise(function(resolve, reject) {
    // SpawnNacl notifies ok/error completion on the execution context.
    cx.onClose.listenOnce(function(reason, value) {
      if (reason === 'ok') {
        resolve(value);
      } else {
        reject(value);
      }
    }.bind(this));

    // TODO(rpaquay): Cleaner URL handling.
    var url = this.sourceUrl;
    url = url.replace('/import.html', '/pnacl/vim.nmf');

    // Execute pnacl vim.
    var nacl = new SpawnNacl('application/x-pnacl', url, cx);
    nacl.run();
  }.bind(this));
};

export default VimCommand;
<|endoftext|>


<commit_before>function mergeData(data) {
  map = {};
  for (var key in data["people"]) {
    if(map[key] === undefined) {
      map[key] = {};
    }
    for(k2 in data) {
      map[key][k2] = data[k2][key];
    }
  }

  return map;
}

function calculateHappines(data) {
  return data["people"];
}

function drawMap(data) {
  mergedData = mergeData(data);
  console.log(data);
  mapData = calculateHappines(data);
  console.log(mapData);
  regionName = "";

  $('#map').vectorMap({
    map: 'se_merc_en',
    backgroundColor: 'transparent', /*#e1f7ff*/
    regionsSelectable: true,
    regionsSelectableOne: true,
    regionStyle: {
      initial: {
        fill: 'white',
        "fill-opacity": 1,
        stroke: 'black',
        "stroke-width": 2,
        "stroke-opacity": 1
      },
      hover: { // other style when hovering a region
        "fill-opacity": 0.5
      },
      selected: { // other style when a region is selected
        stroke: "#FCFCC9",
        "stroke-width": 4,
      },
      selectedHover: {} // other styles when hovering a selected region
    },
    regionLabelStyle: {
      initial: {
        fill: 'red'
      },
      hover: {
        fill: 'blue'
      }
    },

    //Text on label shown when hovering
    //event.preventDefault(); // remove label
    onRegionTipShow: function(event, label, code){
      regionName = label.html();
      console.log(mapData);
      label.html(''+label.html()+'s län
'+ mapData[code]);

    },
    /*onRegionClick: function(event, code){
      event.preventDefault();
      // your "some code" of region selected
    },*/

    series: {
     regions: [{
         //define the range of color values
         //Blue scale ['#DEEBF7', '#08519C']
         scale: ['#DEEBF7', '#08519C'],
         //define the function that maps data to color range polynomial/linear
         normalizeFunction: 'linear',
         //define the coloration method
         attribute: 'fill',
         //define the array of country data
         values: mapData
       }]
     },
     onRegionSelected: function(event, label, isSelected){
      if(!isSelected) {
        return;
      }

      regionData = mergedData[label];

      var htmlString =
      '
'+
      '

Statistik för '+regionName+'s län

'+
      '
'+
      '
'+
      '

'+
      '
Medelinkomst: ' + regionData["money"] + '
'+
      '

'+
      '
Andel sysselsatta: ' + regionData["work"] + '
'+
      '
'+
      '
'+
      '

'+
      '
Sjukfall: ' + regionData["health"] + '
'+
      '

'+
      '
Nygifta:

' + regionData["married"] + '
'+
      '
'
      $('#stats').html(htmlString);
    }

  });
}

$(document).ready(function() {
  data = {};
  money(function(money) {
    data["money"] = money;
    health(function(health) {
      data["health"] = health;
      people(function(people) {
        data["people"] = people;
        married(function(married) {
          data["married"] = married;
          work(function(work) {
            data["work"] = work;
            drawMap(data);
          });
        });
      });
    });
  });
});
<commit_msg>Remove code by @arkenson<commit_after>function mergeData(data) {
  map = {};
  for (var key in data["people"]) {
    if(map[key] === undefined) {
      map[key] = {};
    }
    for(k2 in data) {
      map[key][k2] = data[k2][key];
    }
  }

  return map;
}

function calculateHappines(data) {
  return data["people"];
}

function drawMap(data) {
  mergedData = mergeData(data);
  console.log(data);
  mapData = calculateHappines(data);
  console.log(mapData);
  regionName = "";

  $('#map').vectorMap({
    map: 'se_merc_en',
    backgroundColor: 'transparent', /*#e1f7ff*/
    regionsSelectable: true,
    regionsSelectableOne: true,
    regionStyle: {
      initial: {
        fill: 'white',
        "fill-opacity": 1,
        stroke: 'black',
        "stroke-width": 2,
        "stroke-opacity": 1
      },
      hover: { // other style when hovering a region
        "fill-opacity": 0.5
      },
      selected: { // other style when a region is selected
        stroke: "#FCFCC9",
        "stroke-width": 4,
      },
      selectedHover: {} // other styles when hovering a selected region
    },

    //Text on label shown when hovering
    //event.preventDefault(); // remove label
    onRegionTipShow: function(event, label, code){
      regionName = label.html();
      console.log(mapData);
      label.html(''+label.html()+'s län
'+ mapData[code]);

    },
    /*onRegionClick: function(event, code){
      event.preventDefault();
      // your "some code" of region selected
    },*/

    series: {
     regions: [{
         //define the range of color values
         //Blue scale ['#DEEBF7', '#08519C']
         scale: ['#DEEBF7', '#08519C'],
         //define the function that maps data to color range polynomial/linear
         normalizeFunction: 'linear',
         //define the coloration method
         attribute: 'fill',
         //define the array of country data
         values: mapData
       }]
     },
     onRegionSelected: function(event, label, isSelected){
      if(!isSelected) {
        return;
      }

      regionData = mergedData[label];

      var htmlString =
      '
'+
      '

Statistik för '+regionName+'s län

'+
      '
'+
      '
'+
      '

'+
      '
Medelinkomst: ' + regionData["money"] + '
'+
      '

'+
      '
Andel sysselsatta: ' + regionData["work"] + '
'+
      '
'+
      '
'+
      '

'+
      '
Sjukfall: ' + regionData["health"] + '
'+
      '

'+
      '
Nygifta:

' + regionData["married"] + '
'+
      '
'
      $('#stats').html(htmlString);
    }

  });
}

$(document).ready(function() {
  data = {};
  money(function(money) {
    data["money"] = money;
    health(function(health) {
      data["health"] = health;
      people(function(people) {
        data["people"] = people;
        married(function(married) {
          data["married"] = married;
          work(function(work) {
            data["work"] = work;
            drawMap(data);
          });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>import PropTypes from "prop-types";
import React, { useMemo, useState } from "react";
import styled from "styled-components";

import Button from "@agir/front/genericComponents/Button";
import CheckboxField from "@agir/front/formComponents/CheckboxField";
import Link from "@agir/front/app/Link";
import { RawFeatherIcon } from "@agir/front/genericComponents/FeatherIcon";
import Spacer from "@agir/front/genericComponents/Spacer";

import { StyledTitle } from "@agir/front/genericComponents/ObjectManagement/styledComponents";

import { CERTIFICATION_CRITERIA } from "@agir/groups/utils/group";

const StyledWarning = styled.div`
  font-size: 0.875rem;
  color: ${(props) => props.theme.black700};
  background-color: ${(props) => props.theme.secondary100};
  border-radius: 0.5rem;
  padding: 1rem;
  margin: 1rem 0;

  strong {
    font-weight: 600;
  }
`;

const StyledContent = styled.article`
  color: ${(props) => props.theme.black700};

  ul {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
    flex-flow: column nowrap;
    gap: 1.25rem;

    li {
      display: flex;
      flex-flow: row nowrap;
      align-items: flex-start;
      gap: 1rem;
      font-size: 1rem;

      ${RawFeatherIcon} {
        flex: 0 0 2rem;
        color: white;
        border-radius: 100%;
        width: 2rem;
        height: 2rem;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      strong {
        font-weight: 600;
        color: ${(props) => props.theme.black1000};
      }
    }
  }

  footer {
    width: 100%;
    text-align: center;
    font-size: 0.875rem;

    ${Button} {
      &[disabled] {
        opacity: 0.3;
      }
    }
  }
`;

const MissingCriteriaWarning = () => (

);

const GroupCertification = (props) => {
  const { routes, isCertified, certificationCriteria = {} } = props;

  const [hasConsent, setHasConsent] = useState(false);

  const toggleConsent = (e) => {
    setHasConsent(e.target.checked);
  };

  const criteria = useMemo(
    () =>
      Object.keys(certificationCriteria)
        .sort(
          (a, b) =>
            Object.keys(CERTIFICATION_CRITERIA).indexOf(b) -
            Object.keys(CERTIFICATION_CRITERIA).indexOf(a)
        )
        .map((key) => ({
          ...(CERTIFICATION_CRITERIA[key] || {}),
          key,
          checked: certificationCriteria[key],
        })),
    [certificationCriteria]
  );

  const checkedCriteria = criteria.filter((criterion) => criterion.checked);
  const isCertifiable = checkedCriteria.length === criteria.length;

  return (
    <>

      <Spacer size="0.5rem" />

    </>
  );
};
GroupCertification.propTypes = {
  routes: PropTypes.shape({
    certificationRequest: PropTypes.string,
  }),
  isCertified: PropTypes.bool,
  certificationCriteria: PropTypes.shape({
    gender: PropTypes.bool,
    activity: PropTypes.bool,
    members: PropTypes.bool,
    creation: PropTypes.bool,
  }),
};
export default GroupCertification;
<commit_msg>feat: update group certification warning text<commit_after>import PropTypes from "prop-types";
import React, { useMemo, useState } from "react";
import styled from "styled-components";

import Button from "@agir/front/genericComponents/Button";
import CheckboxField from "@agir/front/formComponents/CheckboxField";
import Link from "@agir/front/app/Link";
import { RawFeatherIcon } from "@agir/front/genericComponents/FeatherIcon";
import Spacer from "@agir/front/genericComponents/Spacer";

import { StyledTitle } from "@agir/front/genericComponents/ObjectManagement/styledComponents";

import { CERTIFICATION_CRITERIA } from "@agir/groups/utils/group";

const StyledWarning = styled.div`
  font-size: 0.875rem;
  color: ${(props) => props.theme.black700};
  background-color: ${(props) => props.theme.secondary100};
  border-radius: 0.5rem;
  padding: 1rem;
  margin: 1rem 0;

  strong {
    font-weight: 600;
  }

  small {
    font-size: 0.875rem;
  }
`;

const StyledContent = styled.article`
  color: ${(props) => props.theme.black700};

  ul {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
    flex-flow: column nowrap;
    gap: 1.25rem;

    li {
      display: flex;
      flex-flow: row nowrap;
      align-items: flex-start;
      gap: 1rem;
      font-size: 1rem;

      ${RawFeatherIcon} {
        flex: 0 0 2rem;
        color: white;
        border-radius: 100%;
        width: 2rem;
        height: 2rem;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      strong {
        font-weight: 600;
        color: ${(props) => props.theme.black1000};
      }
    }
  }

  footer {
    width: 100%;
    text-align: center;
    font-size: 0.875rem;

    ${Button} {
      &[disabled] {
        opacity: 0.3;
      }
    }
  }
`;

const MissingCriteriaWarning = () => (

);

const GroupCertification = (props) => {
  const { routes, isCertified, certificationCriteria = {} } = props;

  const [hasConsent, setHasConsent] = useState(false);

  const toggleConsent = (e) => {
    setHasConsent(e.target.checked);
  };

  const criteria = useMemo(
    () =>
      Object.keys(certificationCriteria)
        .sort(
          (a, b) =>
            Object.keys(CERTIFICATION_CRITERIA).indexOf(b) -
            Object.keys(CERTIFICATION_CRITERIA).indexOf(a)
        )
        .map((key) => ({
          ...(CERTIFICATION_CRITERIA[key] || {}),
          key,
          checked: certificationCriteria[key],
        })),
    [certificationCriteria]
  );

  const checkedCriteria = criteria.filter((criterion) => criterion.checked);
  const isCertifiable = checkedCriteria.length === criteria.length;

  return (
    <>

      <Spacer size="0.5rem" />

    </>
  );
};
GroupCertification.propTypes = {
  routes: PropTypes.shape({
    certificationRequest: PropTypes.string,
  }),
  isCertified: PropTypes.bool,
  certificationCriteria: PropTypes.shape({
    gender: PropTypes.bool,
    activity: PropTypes.bool,
    members: PropTypes.bool,
    creation: PropTypes.bool,
  }),
};
export default GroupCertification;
<|endoftext|>


<commit_before>function isBackboneBase(node, settings) {
    "use strict";
    var prefixes = settings.Collection.concat(settings.Model, settings.View).map(function(item) {
        return item.prefix;
    });
    return node.type === "CallExpression" &&
        node.callee.type === "MemberExpression" &&
        (
            (node.callee.object.type === "MemberExpression" && prefixes.indexOf(node.callee.object.object.name) > -1) ||
            (node.callee.object.type === "Identifier" && prefixes.indexOf(node.callee.object.name) > -1)
        ) &&
        node.callee.property.name === "extend";
}

function parseSettings(settings) {
    "use strict";
    return settings.map(function(setting) {
        if (typeof setting === "object") {
            return setting;
        }
        var splitValue = setting.split(".");
        return splitValue.length > 1 ? { prefix: splitValue[0], postfix: splitValue[1] } : { prefix: splitValue[0] };
    });
}

function normalizeSettings(settings) {
    "use strict";
    settings = settings || {};
    settings.Collection = settings.Collection ? settings.Collection.concat("Backbone.Collection") : ["Backbone.Collection"];
    settings.Collection = parseSettings(settings.Collection);
    settings.Model = settings.Model ? settings.Model.concat("Backbone.Model") : ["Backbone.Model"];
    settings.Model = parseSettings(settings.Model);
    settings.View = settings.View ? settings.View.concat("Backbone.View") : ["Backbone.View"];
    settings.View = parseSettings(settings.View);
    return settings;
}

function checkForBackboneType(settings, object) {
    "use strict";
    return settings.some(function(item) {
        return item.postfix && object.property ? item.postfix === object.property.name : item.prefix === object.name;
    });
}

function isBackboneModel(node, settings) {
    "use strict";
    settings = normalizeSettings(settings);
    return isBackboneBase(node, settings) && checkForBackboneType(settings.Model, node.callee.object);
}

function isBackboneView(node, settings) {
    "use strict";
    settings = normalizeSettings(settings);
    return isBackboneBase(node, settings) && checkForBackboneType(settings.View, node.callee.object);
}

function isBackboneCollection(node, settings) {
    "use strict";
    settings = normalizeSettings(settings);
    return isBackboneBase(node, settings) && checkForBackboneType(settings.Collection, node.callee.object);
}

function isBackboneAny(node, settings) {
    "use strict";
    settings = normalizeSettings(settings);
    return isBackboneBase(node, settings) && node.callee && node.callee.object && (checkForBackboneType(settings.Model, node.callee.object) || checkForBackboneType(settings.View, node.callee.object) || checkForBackboneType(settings.Collection, node.callee.object));
}

exports.isBackboneAny = isBackboneAny;
exports.isBackboneModel = isBackboneModel;
exports.isBackboneView = isBackboneView;
exports.isBackboneCollection = isBackboneCollection;

exports.checkIfPropertyInBackbone = function(node, settings) {
    "use strict";
    var parent = node.parent, grandparent = parent.parent, greatgrandparent = grandparent.parent;
    return isBackboneAny(greatgrandparent, settings);
};

exports.checkIfPropertyInBackboneModel = function(node, settings) {
    "use strict";
    var parent = node.parent, grandparent = parent.parent, greatgrandparent = grandparent.parent;
    return isBackboneModel(greatgrandparent, settings);
};

exports.checkIfPropertyInBackboneView = function(node, settings) {
    "use strict";
    var parent = node.parent, grandparent = parent.parent, greatgrandparent = grandparent.parent;
    return isBackboneView(greatgrandparent, settings);
};

exports.checkIfPropertyInBackboneCollection = function(node, settings) {
    "use strict";
    var parent = node.parent, grandparent = parent.parent, greatgrandparent = grandparent.parent;
    return isBackboneCollection(greatgrandparent, settings);
};
<commit_msg>Fix exponentially growing settings arrays.<commit_after>function isBackboneBase(node, settings) {
    "use strict";
    var prefixes = settings.Collection.concat(settings.Model, settings.View).map(function(item) {
        return item.prefix;
    });
    return node.type === "CallExpression" &&
        node.callee.type === "MemberExpression" &&
        (
            (node.callee.object.type === "MemberExpression" && prefixes.indexOf(node.callee.object.object.name) > -1) ||
            (node.callee.object.type === "Identifier" && prefixes.indexOf(node.callee.object.name) > -1)
        ) &&
        node.callee.property.name === "extend";
}

function parseSettings(settings) {
    "use strict";
    return settings.map(function(setting) {
        if (typeof setting === "object") {
            return setting;
        }
        var splitValue = setting.split(".");
        return splitValue.length > 1 ? { prefix: splitValue[0], postfix: splitValue[1] } : { prefix: splitValue[0] };
    });
}

function normalizeSettings(originalSettings) {
    "use strict";
    originalSettings = originalSettings || {};

    var settings = {};
    settings.Collection = originalSettings.Collection ? originalSettings.Collection.concat("Backbone.Collection") : ["Backbone.Collection"];
    settings.Collection = parseSettings(settings.Collection);
    settings.Model = originalSettings.Model ? originalSettings.Model.concat("Backbone.Model") : ["Backbone.Model"];
    settings.Model = parseSettings(settings.Model);
    settings.View = originalSettings.View ? originalSettings.View.concat("Backbone.View") : ["Backbone.View"];
    settings.View = parseSettings(settings.View);
    return settings;
}

function checkForBackboneType(settings, object) {
    "use strict";
    return settings.some(function(item) {
        return item.postfix && object.property ? item.postfix === object.property.name : item.prefix === object.name;
    });
}

function isBackboneModel(node, settings) {
    "use strict";
    settings = normalizeSettings(settings);
    return isBackboneBase(node, settings) && checkForBackboneType(settings.Model, node.callee.object);
}

function isBackboneView(node, settings) {
    "use strict";
    settings = normalizeSettings(settings);
    return isBackboneBase(node, settings) && checkForBackboneType(settings.View, node.callee.object);
}

function isBackboneCollection(node, settings) {
    "use strict";
    settings = normalizeSettings(settings);
    return isBackboneBase(node, settings) && checkForBackboneType(settings.Collection, node.callee.object);
}

function isBackboneAny(node, settings) {
    "use strict";
    settings = normalizeSettings(settings);
    return isBackboneBase(node, settings) && node.callee && node.callee.object && (checkForBackboneType(settings.Model, node.callee.object) || checkForBackboneType(settings.View, node.callee.object) || checkForBackboneType(settings.Collection, node.callee.object));
}

exports.isBackboneAny = isBackboneAny;
exports.isBackboneModel = isBackboneModel;
exports.isBackboneView = isBackboneView;
exports.isBackboneCollection = isBackboneCollection;

exports.checkIfPropertyInBackbone = function(node, settings) {
    "use strict";
    var parent = node.parent, grandparent = parent.parent, greatgrandparent = grandparent.parent;
    return isBackboneAny(greatgrandparent, settings);
};

exports.checkIfPropertyInBackboneModel = function(node, settings) {
    "use strict";
    var parent = node.parent, grandparent = parent.parent, greatgrandparent = grandparent.parent;
    return isBackboneModel(greatgrandparent, settings);
};

exports.checkIfPropertyInBackboneView = function(node, settings) {
    "use strict";
    var parent = node.parent, grandparent = parent.parent, greatgrandparent = grandparent.parent;
    return isBackboneView(greatgrandparent, settings);
};

exports.checkIfPropertyInBackboneCollection = function(node, settings) {
    "use strict";
    var parent = node.parent, grandparent = parent.parent, greatgrandparent = grandparent.parent;
    return isBackboneCollection(greatgrandparent, settings);
};
<|endoftext|>


<commit_before>/*
  Used as an entry file to generate vendor/brace.min.js
*/
var brace = require('brace')

require('brace/mode/c_cpp')
require('brace/mode/javascript')
require('brace/mode/json')
require('brace/mode/html')
require('brace/mode/markdown')
require('brace/mode/python')
require('brace/mode/r')
require('brace/mode/ruby')
require('brace/mode/sh')
require('brace/theme/monokai')

module.exports = brace
<commit_msg>Add sql mode, comment out other unused ones<commit_after>/*
  Used as an entry file to generate vendor/brace.min.js
*/
var brace = require('brace')

//require('brace/mode/c_cpp')
require('brace/mode/javascript')
//require('brace/mode/json')
//require('brace/mode/html')
//require('brace/mode/markdown')
require('brace/mode/python')
require('brace/mode/r')
//require('brace/mode/ruby')
//require('brace/mode/sh')
require('brace/mode/sql')

require('brace/theme/monokai')

module.exports = brace
<|endoftext|>


<commit_before>// Files Adapter
//
// Allows you to change the file storage mechanism.
//
// Adapter classes must implement the following functions:
// * createFile(config, filename, data)
// * getFileData(config, filename)
// * getFileLocation(config, request, filename)
//
// Default is GridStoreAdapter, which requires mongo
// and for the API server to be using the DatabaseController with Mongo
// database adapter.

export class FilesAdapter {
  /* this method is responsible to store the file in order to be retrived later by it's file name
   *
   *
   * @param config the current config
   * @param filename the filename to save
   * @param data the buffer of data from the file
   * @param contentType the supposed contentType
   * @discussion the contentType can be undefined if the controller was not able to determine it
   *
   * @return a promise that should fail if the storage didn't succeed
   *
   */
  createFile(filename: string, data, contentType: string) { }

  deleteFile(filename) { }

  getFileData(filename) { }

  getFileLocation(config, filename) { }
}

export default FilesAdapter;
<commit_msg>remove inaccurate comment<commit_after>// Files Adapter
//
// Allows you to change the file storage mechanism.
//
// Adapter classes must implement the following functions:
// * createFile(config, filename, data)
// * getFileData(config, filename)
// * getFileLocation(config, request, filename)
//
// Default is GridStoreAdapter, which requires mongo
// and for the API server to be using the DatabaseController with Mongo
// database adapter.

export class FilesAdapter {
  /* this method is responsible to store the file in order to be retrived later by it's file name
   *
   * @param filename the filename to save
   * @param data the buffer of data from the file
   * @param contentType the supposed contentType
   * @discussion the contentType can be undefined if the controller was not able to determine it
   *
   * @return a promise that should fail if the storage didn't succeed
   *
   */
  createFile(filename: string, data, contentType: string) { }

  deleteFile(filename) { }

  getFileData(filename) { }

  getFileLocation(config, filename) { }
}

export default FilesAdapter;
<|endoftext|>


<commit_before>var nroonga = require('nroonga');
var translator = require('./translator');
var Deferred = require('jsdeferred').Deferred;

function Processor(options) {
  this.database = options.database || null;
  this.databasePath = options.databasePath;
  this.domain = options.domain;
  this.initialize();
}

Processor.prototype = {
  initialize: function() {
    if (!this.database) {
      if (!this.databasePath)
        throw new Error('no database path');
      this.database = new nroonga.Database(this.databasePath);
    }
    this.translator = new translator.Translator(this.domain);
  },
  process: function(batchs) {
    var commandSets = this.translator.translate(batchs);
    var self = this;
    return Deferred.loop(commandSets.length, function(i) {
             return self.sendOneCommandSet(commandSets[i]);
           });
  },
  sendOneCommandSet: function(commandSet) {
    var deferred = new Deferred();
    var callback = function(error, data) {
          if (error)
            deferred.fail(error);
          else
            deferred.call(data);
        };

    if (commandSet.options)
      this.database.command(commandSet.command, commandSet.options, callback);
    else
      this.database.command(commandSet.command, callback);

    return deferred;
  }
};

exports.Processor = Processor;
<commit_msg>Processor#process() should return an array of results<commit_after>var nroonga = require('nroonga');
var translator = require('./translator');
var Deferred = require('jsdeferred').Deferred;

function Processor(options) {
  this.database = options.database || null;
  this.databasePath = options.databasePath;
  this.domain = options.domain;
  this.initialize();
}

Processor.prototype = {
  initialize: function() {
    if (!this.database) {
      if (!this.databasePath)
        throw new Error('no database path');
      this.database = new nroonga.Database(this.databasePath);
    }
    this.translator = new translator.Translator(this.domain);
  },
  process: function(batchs) {
    var commandSets = this.translator.translate(batchs);
    var results = [];
    var self = this;
    return Deferred.loop(commandSets.length, function(i) {
             return self.sendOneCommandSet(commandSets[i])
                        .next(function(result) {
                          results.push(result);
                        });
           })
           .next(function() {
             return results;
           });
  },
  sendOneCommandSet: function(commandSet) {
    var deferred = new Deferred();
    var callback = function(error, data) {
          if (error)
            deferred.fail(error);
          else
            deferred.call(data);
        };

    if (commandSet.options)
      this.database.command(commandSet.command, commandSet.options, callback);
    else
      this.database.command(commandSet.command, callback);

    return deferred;
  }
};

exports.Processor = Processor;
<|endoftext|>