<commit_before>"use strict";

var _ = require('lodash'),
    Marionette = require('../../../../shim/backbone.marionette'),
    modalViews = require('../../../core/modals/views'),
    settings = require('../../../core/settings'),
    coreUnits = require('../../../core/units'),
    round = require('../../../core/utils').round,
    CropTillageEfficiencyValues = require('../../gwlfeModificationConfig').CropTillageEfficiencyValues,
    GWLFE_LAND_COVERS = require('../../constants').GWLFE_LAND_COVERS,
    GwlfeModificationModel = require('../../models').GwlfeModificationModel,
    modelingUtils = require('../../utils'),
    models = require('./models'),
    calcs = require('./calcs'),
    fieldTmpl = require('./templates/field.html'),
    fieldWithLabelTmpl = require('./templates/fieldWithLabel.html'),
    modalTmpl = require('./templates/modal.html'),
    landCoverModalTmpl = require('./templates/landCoverModal.html'),
    landCoverTotalTmpl = require('./templates/landCoverTotal.html'),
    sectionTmpl = require('./templates/section.html'),
    tabContentTmpl = require('./templates/tabContent.html'),
    tabPanelTmpl = require('./templates/tabPanel.html'),
    tripletSectionTmpl = require('./templates/tripletSection.html'),
    tripletTabContentTmpl = require('./templates/tripletTabContent.html');

var LandCoverModal = modalViews.ModalBaseView.extend({
    template: landCoverModalTmpl,

    id: 'land-cover-modal',
    className: 'modal modal-large fade',

    ui: {
        saveButton: '.btn-active',
        landCoverPreset: '#land-cover-preset',
    },

    events: _.defaults({
        'click @ui.saveButton': 'saveAndClose',
        'change @ui.landCoverPreset': 'onPresetChange',
    }, modalViews.ModalBaseView.prototype.events),

    regions: {
        fieldsRegion: '#fields-region',
        totalRegion: '.total-content',
    },

    initialize: function(options) {
        this.mergeOptions(options, ['scenario', 'analyzeCollection']);

        var onFieldUpdated = _.bind(this.onFieldUpdated, this),
            fields = this.model.get('fields');

        this.listenTo(fields, 'change', onFieldUpdated);
    },

    templateHelpers: function() {
        var presetMod = this.scenario.get('modifications').findWhere({ modKey: 'entry_landcover_preset' }),
            preset = presetMod && presetMod.get('userInput').entry_landcover_preset;

        return {
            preset: preset,
        };
    },

    // Override to populate fields
    onRender: function() {
        this.fieldsRegion.show(new FieldsView({
            collection: this.model.get('fields'),
        }));
        this.totalRegion.show(new LandCoverTotalView({
            model: this.model,
        }));

        this.$el.modal('show');
    },

    onFieldUpdated: function() {
        var areas = _.cloneDeep(this.model.get('dataModel')['Area']),
            fields = this.model.get('fields'),
            hasUserValue = function(field) {
                return field.get('userValue') !== null;
            };

        fields.filter(hasUserValue).forEach(function(field) {
            var index = parseInt(field.get('name').split('__')[1]);

            areas[index] = parseFloat(field.get('userValue'));
        });

        this.model.set('userTotal', _.sum(areas));

        this.validateModal();
    },

    validateModal: function() {
        var get = function(value) {
                return coreUnits.get('AREA_L_FROM_HA', value).value;
            },
            autoTotal = round(get(this.model.get('autoTotal')), 1),
            userTotal = round(get(this.model.get('userTotal')), 1);

        this.ui.saveButton.prop('disabled', autoTotal !== userTotal);
    },

    onPresetChange: function(e) {
        var self = this;

        if (e.target.value) {
            // One of the non-default presets has been selected. Fetch the
            // NLCD-style landcover distribution from the relevant Analyze
            // results, convert them to Mapshed-style, and populate all the
            // field boxes. Then recalculate the total to ensure it still
            // fits.
            var task = self.analyzeCollection
                           .findWhere({ name: 'land' })
                           .get('tasks')
                           .findWhere({ name: e.target.value });

            if (!task) {
                throw new Error('Could not find analysis results for ' + e.target.value);
            }

            task.fetchAnalysisIfNeeded()
                .then(function() {
                    var categories = task.get('result').survey.categories;

                    if (!categories) {
                        throw new Error('Invalid analysis results for ' + e.target.value);
                    }

                    var m2ToHa = function(m2) { return m2 / coreUnits.METRIC.AREA_L.factor; },
                        // Convert list of NLCD results to dictionary mapping
                        // NLCD to Hectares
                        nlcd = categories.reduce(function(acc, category) {
                                acc[category.nlcd] = category.area;
                                return acc;
                            }, {}),
                        landcover = modelingUtils.nlcdToMapshedLandCover(nlcd).map(m2ToHa);

                    self.model.get('fields').forEach(function(field) {
                        var index = parseInt(field.get('name').split('__')[1]);

                        field.set('userValue', landcover[index]);<commit_msg>Proportion land cover distribution to match<commit_after>"use strict";

var _ = require('lodash'),
    Marionette = require('../../../../shim/backbone.marionette'),
    modalViews = require('../../../core/modals/views'),
    settings = require('../../../core/settings'),
    coreUnits = require('../../../core/units'),
    round = require('../../../core/utils').round,
    CropTillageEfficiencyValues = require('../../gwlfeModificationConfig').CropTillageEfficiencyValues,
    GWLFE_LAND_COVERS = require('../../constants').GWLFE_LAND_COVERS,
    GwlfeModificationModel = require('../../models').GwlfeModificationModel,
    modelingUtils = require('../../utils'),
    models = require('./models'),
    calcs = require('./calcs'),
    fieldTmpl = require('./templates/field.html'),
    fieldWithLabelTmpl = require('./templates/fieldWithLabel.html'),
    modalTmpl = require('./templates/modal.html'),
    landCoverModalTmpl = require('./templates/landCoverModal.html'),
    landCoverTotalTmpl = require('./templates/landCoverTotal.html'),
    sectionTmpl = require('./templates/section.html'),
    tabContentTmpl = require('./templates/tabContent.html'),
    tabPanelTmpl = require('./templates/tabPanel.html'),
    tripletSectionTmpl = require('./templates/tripletSection.html'),
    tripletTabContentTmpl = require('./templates/tripletTabContent.html');

var LandCoverModal = modalViews.ModalBaseView.extend({
    template: landCoverModalTmpl,

    id: 'land-cover-modal',
    className: 'modal modal-large fade',

    ui: {
        saveButton: '.btn-active',
        landCoverPreset: '#land-cover-preset',
    },

    events: _.defaults({
        'click @ui.saveButton': 'saveAndClose',
        'change @ui.landCoverPreset': 'onPresetChange',
    }, modalViews.ModalBaseView.prototype.events),

    regions: {
        fieldsRegion: '#fields-region',
        totalRegion: '.total-content',
    },

    initialize: function(options) {
        this.mergeOptions(options, ['scenario', 'analyzeCollection']);

        var onFieldUpdated = _.bind(this.onFieldUpdated, this),
            fields = this.model.get('fields');

        this.listenTo(fields, 'change', onFieldUpdated);
    },

    templateHelpers: function() {
        var presetMod = this.scenario.get('modifications').findWhere({ modKey: 'entry_landcover_preset' }),
            preset = presetMod && presetMod.get('userInput').entry_landcover_preset;

        return {
            preset: preset,
        };
    },

    // Override to populate fields
    onRender: function() {
        this.fieldsRegion.show(new FieldsView({
            collection: this.model.get('fields'),
        }));
        this.totalRegion.show(new LandCoverTotalView({
            model: this.model,
        }));

        this.$el.modal('show');
    },

    onFieldUpdated: function() {
        var areas = _.cloneDeep(this.model.get('dataModel')['Area']),
            fields = this.model.get('fields'),
            hasUserValue = function(field) {
                return field.get('userValue') !== null;
            };

        fields.filter(hasUserValue).forEach(function(field) {
            var index = parseInt(field.get('name').split('__')[1]);

            areas[index] = parseFloat(field.get('userValue'));
        });

        this.model.set('userTotal', _.sum(areas));

        this.validateModal();
    },

    validateModal: function() {
        var get = function(value) {
                return coreUnits.get('AREA_L_FROM_HA', value).value;
            },
            autoTotal = round(get(this.model.get('autoTotal')), 1),
            userTotal = round(get(this.model.get('userTotal')), 1);

        this.ui.saveButton.prop('disabled', autoTotal !== userTotal);
    },

    onPresetChange: function(e) {
        var self = this;

        if (e.target.value) {
            // One of the non-default presets has been selected. Fetch the
            // NLCD-style landcover distribution from the relevant Analyze
            // results, convert them to Mapshed-style, and populate all the
            // field boxes. Then recalculate the total to ensure it still
            // fits.
            var task = self.analyzeCollection
                           .findWhere({ name: 'land' })
                           .get('tasks')
                           .findWhere({ name: e.target.value });

            if (!task) {
                throw new Error('Could not find analysis results for ' + e.target.value);
            }

            task.fetchAnalysisIfNeeded()
                .then(function() {
                    var categories = task.get('result').survey.categories;

                    if (!categories) {
                        throw new Error('Invalid analysis results for ' + e.target.value);
                    }

                    var m2ToHa = function(m2) { return m2 / coreUnits.METRIC.AREA_L.factor; },
                        // Convert list of NLCD results to dictionary mapping
                        // NLCD to Hectares
                        nlcd = categories.reduce(function(acc, category) {
                                acc[category.nlcd] = category.area;
                                return acc;
                            }, {}),
                        landcoverRaw = modelingUtils.nlcdToMapshedLandCover(nlcd).map(m2ToHa),
                        // Proportion land cover with base NLCD 2011 total
                        // so that the user doesn't have to manually update it
                        autoTotal = self.model.get('autoTotal'),
                        presetTotal = _.sum(landcoverRaw),
                        landcover = landcoverRaw.map(function(l) {
                            return l * autoTotal / presetTotal;
                        });

                    self.model.get('fields').forEach(function(field) {
                        var index = parseInt(field.get('name').split('__')[1]);

                        field.set('userValue', landcover[index]);
{'fraction_non_alphanumeric': 0.1415110800907346, 'fraction_numerical': 0.0017448961786773686, 'mean_word_length': 2.024538258575198, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4659961', 'n_tokens_mistral': 3159, 'n_tokens_neox': 3013, 'n_words': 566}