<commit_before>define(
    [
        'jquery',
        'Magento_Checkout/js/view/payment/default',
        'CheckoutCom_Magento2/js/view/payment/utilities',
        'Magento_Checkout/js/model/payment/additional-validators',
        'Magento_Customer/js/model/customer',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/model/url-builder',
        'framesjs'
    ],
    function ($, Component, Utilities, AdditionalValidators, Customer, Quote, urlBuilder) {
        'use strict';
        window.checkoutConfig.reloadOnBillingAddress = true;
        const METHOD_ID = 'checkoutcom_card_payment';

        return Component.extend(
            {
                defaults: {
                    template: 'CheckoutCom_Magento2/payment/' + METHOD_ID + '.html',
                    buttonId: METHOD_ID + '_btn',
                    formId: METHOD_ID + '_frm',
                    cardToken: null,
                    cardBin: null,
                    saveCard: false,
                    supportedCards: null,
                    redirectAfterPlaceOrder: false
                },

                /**
                 * @returns {exports}
                 */
                initialize: function () {
                    this._super();
                    this.initAddressObserver();
                    Utilities.setEmail();

                    return this;
                },

                initAddressObserver: function () {
                    var self = this;
                    Quote.billingAddress.subscribe(function () {
                        if (AdditionalValidators.validate() && Frames.isCardValid()) {
                            Utilities.allowPlaceOrder(self.buttonId, true);
                        }
                    });
                },

                /**
                 * @returns {string}
                 */
                getCode: function () {
                    return METHOD_ID;
                },

                /**
                 * @returns {string}
                 */
                getValue: function (field) {
                    return Utilities.getValue(METHOD_ID, field);
                },

                /**
                 * @returns {string}
                 */
                isVaultEnabled: function () {
                    return this.getValue('active');
                },

                /**
                 * @returns {string}
                 */
                isSaveCardEnabled: function () {
                    return this.getValue('save_card_option');
                },

                /**
                 * @returns {bool}
                 */
                shouldDisplayCardIcons: function () {
                    return this.getValue('display_card_icons');
                },

                /**
                 * @returns {array}
                 */
                getCardIcons: function () {
                    return Utilities.getSupportedCards();
                },

                /**
                 * @returns {bool}
                 */
                isLoggedIn: function () {
                    return Customer.isLoggedIn();
                },

                /**
                 * @returns {void}
                 */
                initEvents: function () {
                    var self = this;
                    $('input[name="saveCard"]').on(
                        'click',
                        function () {
                            self.saveCard = this.checked;
                        }
                    );
                },

                /**
                 * Events
                 */

                /**
                 * Gets the payment form
                 *
                 * @return {void}
                 */
                getPaymentForm: function () {

                    var self = this;

                    var address = Utilities.getBillingAddress(),
                        line1 = address.street[0] !== undefined ? address.street[0] : '',
                        line2 = address.street[1] !== undefined ? address.street[1] : '';

                    // Initialize the payment form
                    Frames.init(
                        {
                            publicKey: self.getValue('public_key'),
                            debug: Boolean(self.getValue('debug') && self.getValue('console_logging')),
                            localization: self.getValue('language_fallback'),
                            cardholder: {
                                name: Utilities.getCustomerName(),
                                phone: address.telephone,
                                billingAddress: {
                                    addressLine1: line1,
                                    addressLine2: line2,
                                    postcode: address.postcode,
                                    city: address.city,
                                    state: address.region,
                                    country: address.countryId,
                                }
                            }
                        }
                    );

                    self.addFramesEvents();
                    // Initialize other events
                    this.initEvents();
                },

                /**
                 * Add events to Frames.
                 * @returns {void}
                 */
                addFramesEvents: function () {
                    var self = this;
                    Frames.addEventHandler(
                      Frames.Events.CARD_VALIDATION_CHANGED,
                      function (event) {
                        var valid = Frames.isCardValid() && Utilities.getBillingAddress() != null;
                        if (valid) {
                            Frames.submitCard();
                        }
                        Utilities.allowPlaceOrder(self.buttonId, valid);
                      }
                    );

                    Frames.addEventHandler(
                      Frames.Events.CARD_TOKENIZED,
                        function (event) {
                            // Store the card token and the card bin
                            self.cardToken = event.token;
                            self.cardBin =  event.bin;
                            // Add the card token to the form
                            Frames.addCardToken(
                                document.getElementById(self.formId),
                                event.token
                            );
                            Frames.enableSubmitForm();
                        }
                    );
                },

                /**
                 * @returns {void}
                 */
                placeOrder: function () {
                    // Prepare some variables
                    var self = this;

                    // Validate the order placement
                    if (AdditionalValidators.validate() && Frames.isCardValid()) {
                        // Prepare the payload
                        var payload = {
                            methodId: METHOD_ID,
                            cardToken: self.cardToken,
                            cardBin: self.cardBin,
                            saveCard: self.saveCard,
                            source: METHOD_ID
                        };

                        // Place the order
                        Utilities.placeOrder(payload, METHOD_ID);
                    }
                }
            }
        );
    }
);
<commit_msg>Added code formatting<commit_after>define(
    [
        'jquery',
        'Magento_Checkout/js/view/payment/default',
        'CheckoutCom_Magento2/js/view/payment/utilities',
        'Magento_Checkout/js/model/payment/additional-validators',
        'Magento_Customer/js/model/customer',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/model/url-builder',
        'framesjs'
    ],
    function ($, Component, Utilities, AdditionalValidators, Customer, Quote, urlBuilder) {
        'use strict';
        window.checkoutConfig.reloadOnBillingAddress = true;
        const METHOD_ID = 'checkoutcom_card_payment';

        return Component.extend(
            {
                defaults: {
                    template: 'CheckoutCom_Magento2/payment/' + METHOD_ID + '.html',
                    buttonId: METHOD_ID + '_btn',
                    formId: METHOD_ID + '_frm',
                    cardToken: null,
                    cardBin: null,
                    saveCard: false,
                    supportedCards: null,
                    redirectAfterPlaceOrder: false
                },

                /**
                 * @returns {exports}
                 */
                initialize: function () {
                    this._super();
                    this.initAddressObserver();
                    Utilities.setEmail();

                    return this;
                },

                initAddressObserver: function () {
                    var self = this;
                    Quote.billingAddress.subscribe(function () {
                        if (AdditionalValidators.validate() && Frames.isCardValid()) {
                            Utilities.allowPlaceOrder(self.buttonId, true);
                        }
                    });
                },

                /**
                 * @returns {string}
                 */
                getCode: function () {
                    return METHOD_ID;
                },

                /**
                 * @returns {string}
                 */
                getValue: function (field) {
                    return Utilities.getValue(METHOD_ID, field);
                },

                /**
                 * @returns {string}
                 */
                isVaultEnabled: function () {
                    return this.getValue('active');
                },

                /**
                 * @returns {string}
                 */
                isSaveCardEnabled: function () {
                    return this.getValue('save_card_option');
                },

                /**
                 * @returns {bool}
                 */
                shouldDisplayCardIcons: function () {
                    return this.getValue('display_card_icons');
                },

                /**
                 * @returns {array}
                 */
                getCardIcons: function () {
                    return Utilities.getSupportedCards();
                },

                /**
                 * @returns {bool}
                 */
                isLoggedIn: function () {
                    return Customer.isLoggedIn();
                },

                /**
                 * @returns {void}
                 */
                initEvents: function () {
                    var self = this;
                    $('input[name="saveCard"]').on(
                        'click',
                        function () {
                            self.saveCard = this.checked;
                        }
                    );
                },

                /**
                 * Gets the payment form
                 *
                 * @return {void}
                 */
                getPaymentForm: function () {
                    var self = this;
                    var address = Utilities.getBillingAddress(),
                        line1 = address.street[0] !== undefined ? address.street[0] : '',
                        line2 = address.street[1] !== undefined ? address.street[1] : '';

                    // Initialize the payment form
                    Frames.init(
                        {
                            publicKey: self.getValue('public_key'),
                            debug: Boolean(self.getValue('debug') && self.getValue('console_logging')),
                            localization: self.getValue('language_fallback'),
                            cardholder: {
                                name: Utilities.getCustomerName(),
                                phone: address.telephone,
                                billingAddress: {
                                    addressLine1: line1,
                                    addressLine2: line2,
                                    postcode: address.postcode,
                                    city: address.city,
                                    state: address.region,
                                    country: address.countryId,
                                }
                            }
                        }
                    );

                    self.addFramesEvents();
                    // Initialize other events
                    this.initEvents();
                },

                /**
                 * Add events to Frames.
                 * @returns {void}
                 */
                addFramesEvents: function () {
                    var self = this;

                    // Card validation changed event
                    Frames.addEventHandler(
                      Frames.Events.CARD_VALIDATION_CHANGED,
                      function (event) {
                        var valid = Frames.isCardValid() && Utilities.getBillingAddress() != null;
                        if (valid) {
                            Frames.submitCard();
                        }
                        Utilities.allowPlaceOrder(self.buttonId, valid);
                      }
                    );

                    // Card tokenized event
                    Frames.addEventHandler(
                      Frames.Events.CARD_TOKENIZED,
                        function (event) {
                            // Store the card token and the card bin
                            self.cardToken = event.token;
                            self.cardBin =  event.bin;
                            // Add the card token to the form
                            Frames.addCardToken(
                                document.getElementById(self.formId),
                                event.token
                            );
                            Frames.enableSubmitForm();
                        }
                    );
                },

                /**
                 * @returns {void}
                 */
                placeOrder: function () {
                    // Prepare some variables
                    var self = this;

                    // Validate the order placement
                    if (AdditionalValidators.validate() && Frames.isCardValid()) {
                        // Prepare the payload
                        var payload = {
                            methodId: METHOD_ID,
                            cardToken: self.cardToken,
                            cardBin: self.cardBin,
                            saveCard: self.saveCard,
                            source: METHOD_ID
                        };

                        // Place the order
                        Utilities.placeOrder(payload, METHOD_ID);
                    }
                }
            }
        );
    }
);
<|endoftext|>


<commit_before>var fs = require('fs');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var url = 'http://pokedata.c4e3f8c7.svc.dockerapp.io:65014/api/pokemon/sighting/';

var destination = 'arff/apiData.arff';

httpGetAsync(url, destination, 'pokemonID');

function httpGetAsync(url, destination, classKey) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            try {
                var apiData = JSON.parse(xmlHttp.responseText);
            } catch (e) {
                console.log(e.stack);
            }
            jsonToArff(apiData, classKey, 'apiData', destination);
        }
    };
    xmlHttp.open("GET", url, true);
    xmlHttp.send();
    return xmlHttp.responseText;
}

function jsonToArff(json_data, classKey, fileName, destination) {
    var classLabels = allValuesForKeyInData(classKey, json_data);
    var arff = '';
    arff = arff + '@RELATION ' + fileName + '\n' + '\n';

    var firstElement = json_data[0];
    for (var key in firstElement) {
        if (key !== classKey) {
            if (typeof firstElement[key] === 'string') {
                arff = arff + '@ATTRIBUTE ' + key + ' string\n';
            }
            if (typeof firstElement[key] === 'number'
                || typeof firstElement[key] === 'boolean') {
                arff = arff + '@ATTRIBUTE ' + key + ' numeric\n';
            }
        }
    }
    arff = arff + '@ATTRIBUTE class {' + classLabels.join(', ') + '}\n\n';

    arff = arff + '@DATA\n';
    for (var i = 0; i < json_data.length; i++) {
        var element = json_data[i];
        for (var key in element) {
            if (key !== classKey) {
                if (typeof element[key] === 'string') {
                    arff = arff + element[key].replace(/\s+/g, '') + ',';
                } else {
                    arff = arff + element[key] + ',';
                }
            }
        }
        arff = arff + element[classKey] + '\n';
    }

    fs.writeFileSync(destination, arff, 'utf8');
}

function allValuesForKeyInData(key, json_data) {
    var values = [];

    json_data.forEach(function (row) {
        values.push(row[key]);
    });

    return Array.from(new Set(values));
}<commit_msg>remove try-catch<commit_after>var fs = require('fs');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var url = 'http://pokedata.c4e3f8c7.svc.dockerapp.io:65014/api/pokemon/sighting/';

var destination = 'arff/apiData.arff';

httpGetAsync(url, destination, 'pokemonID');

function httpGetAsync(url, destination, classKey) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            var apiData = JSON.parse(xmlHttp.responseText);
            jsonToArff(apiData, classKey, 'apiData', destination);
        }
    };
    xmlHttp.open("GET", url, true);
    xmlHttp.send();
    return xmlHttp.responseText;
}

function jsonToArff(json_data, classKey, fileName, destination) {
    var classLabels = allValuesForKeyInData(classKey, json_data);
    var arff = '';
    arff = arff + '@RELATION ' + fileName + '\n' + '\n';

    var firstElement = json_data[0];
    for (var key in firstElement) {
        if (key !== classKey) {
            if (typeof firstElement[key] === 'string') {
                arff = arff + '@ATTRIBUTE ' + key + ' string\n';
            }
            if (typeof firstElement[key] === 'number'
                || typeof firstElement[key] === 'boolean') {
                arff = arff + '@ATTRIBUTE ' + key + ' numeric\n';
            }
        }
    }
    arff = arff + '@ATTRIBUTE class {' + classLabels.join(', ') + '}\n\n';

    arff = arff + '@DATA\n';
    for (var i = 0; i < json_data.length; i++) {
        var element = json_data[i];
        for (var key in element) {
            if (key !== classKey) {
                if (typeof element[key] === 'string') {
                    arff = arff + element[key].replace(/\s+/g, '') + ',';
                } else {
                    arff = arff + element[key] + ',';
                }
            }
        }
        arff = arff + element[classKey] + '\n';
    }

    fs.writeFileSync(destination, arff, 'utf8');
}

function allValuesForKeyInData(key, json_data) {
    var values = [];

    json_data.forEach(function (row) {
        values.push(row[key]);
    });

    return Array.from(new Set(values));
}<|endoftext|>


<commit_before>define(
    [
        'jquery',
        'Magento_Checkout/js/view/payment/default',
        'CheckoutCom_Magento2/js/view/payment/utilities',
        'Magento_Checkout/js/model/payment/additional-validators',
        'Magento_Customer/js/model/customer',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/model/url-builder',
        'framesjs'
    ],
    function ($, Component, Utilities, AdditionalValidators, Customer, Quote, urlBuilder) {
        'use strict';
        window.checkoutConfig.reloadOnBillingAddress = true;
        const METHOD_ID = 'checkoutcom_card_payment';

        return Component.extend(
            {
                defaults: {
                    template: 'CheckoutCom_Magento2/payment/' + METHOD_ID + '.html',
                    buttonId: METHOD_ID + '_btn',
                    formId: METHOD_ID + '_frm',
                    cardToken: null,
                    cardBin: null,
                    saveCard: false,
                    supportedCards: null,
                    redirectAfterPlaceOrder: false
                },

                /**
                 * @returns {exports}
                 */
                initialize: function () {
                    this._super();
                    this.initAddressObserver();
                    Utilities.setEmail();

                    return this;
                },

                initAddressObserver: function () {
                    var self = this;
                    Quote.billingAddress.subscribe(function () {
                        if (AdditionalValidators.validate() && Frames.isCardValid()) {
                            Utilities.allowPlaceOrder(self.buttonId, true);
                        }
                    });
                },

                /**
                 * @returns {string}
                 */
                getCode: function () {
                    return METHOD_ID;
                },

                /**
                 * @returns {string}
                 */
                getValue: function (field) {
                    return Utilities.getValue(METHOD_ID, field);
                },

                /**
                 * @returns {string}
                 */
                isVaultEnabled: function () {
                    return this.getValue('active');
                },

                /**
                 * @returns {string}
                 */
                isSaveCardEnabled: function () {
                    return this.getValue('save_card_option');
                },

                /**
                 * @returns {bool}
                 */
                shouldDisplayCardIcons: function () {
                    return this.getValue('display_card_icons');
                },

                /**
                 * @returns {array}
                 */
                getCardIcons: function () {
                    return Utilities.getSupportedCards();
                },

                /**
                 * @returns {bool}
                 */
                isLoggedIn: function () {
                    return Customer.isLoggedIn();
                },

                /**
                 * @returns {void}
                 */
                initEvents: function () {
                    var self = this;
                    $('input[name="saveCard"]').on(
                        'click',
                        function () {
                            self.saveCard = this.checked;
                        }
                    );
                },

                /**
                 * @returns {void}
                 */
                cleanEvents: function () {
                    Frames.removeAllEventHandlers(Frames.Events.CARD_VALIDATION_CHANGED);
                    Frames.removeAllEventHandlers(Frames.Events.CARD_TOKENISED);
                    Frames.removeAllEventHandlers(Frames.Events.FRAME_ACTIVATED);
                },

                /**
                 * Events
                 */

                /**
                 * Gets the payment form
                 *
                 * @return {void}
                 */
                getPaymentForm: function () {

                    var self = this;

                    // Remove any existing event handlers
                    this.cleanEvents();

                    // Initialize the payment form
                    Frames.init(
                        {
                            publicKey: self.getValue('public_key'),
                            debug: (self.getValue('debug') && self.getValue('console_logging')),
                            localization: self.getValue('language_fallback'),
                            name: Utilities.getCustomerName(),
                            frameValidationChanged: function() {
                                if (Frames.isCardValid() && Utilities.getBillingAddress() != null) {
                                    Utilities.allowPlaceOrder(self.buttonId, true);
                                    Frames.submitCard();
                                    Frames.unblockFields();
                                } else {
                                    Utilities.allowPlaceOrder(self.buttonId, false);
                                }
                            }
                        }
                    );
                    this.addFramesEvents();

                    // Initialize other events
                    this.initEvents();
                },

                /**
                 * Add events to Frames.
                 * @returns {void}
                 */
                addFramesEvents: function () {

                    var self = this;
                    Frames.addEventHandler(
                      Frames.Events.CARD_VALIDATION_CHANGED,
                      function (event) {

                        if (Frames.isCardValid() && Utilities.getBillingAddress() != null) {
                            Utilities.allowPlaceOrder(self.buttonId, true);
                            Frames.submitCard();
                            Frames.unblockFields();
                        } else {
                            Utilities.allowPlaceOrder(self.buttonId, false);
                        }
                      }

                    );

                    Frames.addEventHandler(
                      Frames.Events.CARD_TOKENIZED,
                        function (event) {

                            // Store the card token and the card bin
                            self.cardToken = event.token;
                            self.cardBin =  event.bin;

                            // Add the card token to the form
                            Frames.addCardToken(
                                document.getElementById(self.formId),
                                event.token
                            );

                        }
                    );

                },

                /**
                 * @returns {void}
                 */
                placeOrder: function () {
                    // Prepare some variables
                    var self = this;

                    // Validate the order placement
                    if (AdditionalValidators.validate() && Frames.isCardValid()) {
                        // Prepare the payload
                        var payload = {
                            methodId: METHOD_ID,
                            cardToken: self.cardToken,
                            cardBin: self.cardBin,
                            saveCard: self.saveCard,
                            source: METHOD_ID
                        };

                        // Place the order
                        Utilities.placeOrder(payload, METHOD_ID);

                        // Make sure the card form stays unblocked
                        Frames.unblockFields();
                    }
                }
            }
        );
    }
);
<commit_msg>Include enableSubmitForm function.<commit_after>define(
    [
        'jquery',
        'Magento_Checkout/js/view/payment/default',
        'CheckoutCom_Magento2/js/view/payment/utilities',
        'Magento_Checkout/js/model/payment/additional-validators',
        'Magento_Customer/js/model/customer',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/model/url-builder',
        'framesjs'
    ],
    function ($, Component, Utilities, AdditionalValidators, Customer, Quote, urlBuilder) {
        'use strict';
        window.checkoutConfig.reloadOnBillingAddress = true;
        const METHOD_ID = 'checkoutcom_card_payment';

        return Component.extend(
            {
                defaults: {
                    template: 'CheckoutCom_Magento2/payment/' + METHOD_ID + '.html',
                    buttonId: METHOD_ID + '_btn',
                    formId: METHOD_ID + '_frm',
                    cardToken: null,
                    cardBin: null,
                    saveCard: false,
                    supportedCards: null,
                    redirectAfterPlaceOrder: false
                },

                /**
                 * @returns {exports}
                 */
                initialize: function () {
                    this._super();
                    this.initAddressObserver();
                    Utilities.setEmail();

                    return this;
                },

                initAddressObserver: function () {
                    var self = this;
                    Quote.billingAddress.subscribe(function () {
                        if (AdditionalValidators.validate() && Frames.isCardValid()) {
                            Utilities.allowPlaceOrder(self.buttonId, true);
                        }
                    });
                },

                /**
                 * @returns {string}
                 */
                getCode: function () {
                    return METHOD_ID;
                },

                /**
                 * @returns {string}
                 */
                getValue: function (field) {
                    return Utilities.getValue(METHOD_ID, field);
                },

                /**
                 * @returns {string}
                 */
                isVaultEnabled: function () {
                    return this.getValue('active');
                },

                /**
                 * @returns {string}
                 */
                isSaveCardEnabled: function () {
                    return this.getValue('save_card_option');
                },

                /**
                 * @returns {bool}
                 */
                shouldDisplayCardIcons: function () {
                    return this.getValue('display_card_icons');
                },

                /**
                 * @returns {array}
                 */
                getCardIcons: function () {
                    return Utilities.getSupportedCards();
                },

                /**
                 * @returns {bool}
                 */
                isLoggedIn: function () {
                    return Customer.isLoggedIn();
                },

                /**
                 * @returns {void}
                 */
                initEvents: function () {
                    var self = this;
                    $('input[name="saveCard"]').on(
                        'click',
                        function () {
                            self.saveCard = this.checked;
                        }
                    );
                },

                /**
                 * @returns {void}
                 */
                cleanEvents: function () {
                    Frames.removeAllEventHandlers(Frames.Events.CARD_VALIDATION_CHANGED);
                    Frames.removeAllEventHandlers(Frames.Events.CARD_TOKENISED);
                    Frames.removeAllEventHandlers(Frames.Events.FRAME_ACTIVATED);
                },

                /**
                 * Events
                 */

                /**
                 * Gets the payment form
                 *
                 * @return {void}
                 */
                getPaymentForm: function () {

                    var self = this;

                    // Remove any existing event handlers
                    this.cleanEvents();

                    // Initialize the payment form
                    Frames.init(
                        {
                            publicKey: self.getValue('public_key'),
                            debug: (self.getValue('debug') && self.getValue('console_logging')) == 'true',
                            localization: self.getValue('language_fallback'),
                            name: Utilities.getCustomerName(),
                            frameValidationChanged: function() {
                                if (Frames.isCardValid() && Utilities.getBillingAddress() != null) {
                                    Utilities.allowPlaceOrder(self.buttonId, true);
                                    Frames.submitCard();
                                    Frames.unblockFields();
                                } else {
                                    Utilities.allowPlaceOrder(self.buttonId, false);
                                }
                            }
                        }
                    );
                    this.addFramesEvents();

                    // Initialize other events
                    this.initEvents();
                },

                /**
                 * Add events to Frames.
                 * @returns {void}
                 */
                addFramesEvents: function () {

                    var self = this;
                    Frames.addEventHandler(
                      Frames.Events.CARD_VALIDATION_CHANGED,
                      function (event) {

                        if (Frames.isCardValid() && Utilities.getBillingAddress() != null) {
                            Utilities.allowPlaceOrder(self.buttonId, true);
                            Frames.submitCard();
                            Frames.unblockFields();
                        } else {
                            Utilities.allowPlaceOrder(self.buttonId, false);
                        }
                      }

                    );

                    Frames.addEventHandler(
                      Frames.Events.CARD_TOKENIZED,
                        function (event) {

                            // Store the card token and the card bin
                            self.cardToken = event.token;
                            self.cardBin =  event.bin;

                            // Add the card token to the form
                            Frames.addCardToken(
                                document.getElementById(self.formId),
                                event.token
                            );

                            Frames.enableSubmitForm();
                        }
                    );

                },

                /**
                 * @returns {void}
                 */
                placeOrder: function () {
                    // Prepare some variables
                    var self = this;

                    // Validate the order placement
                    if (AdditionalValidators.validate() && Frames.isCardValid()) {
                        // Prepare the payload
                        var payload = {
                            methodId: METHOD_ID,
                            cardToken: self.cardToken,
                            cardBin: self.cardBin,
                            saveCard: self.saveCard,
                            source: METHOD_ID
                        };

                        // Place the order
                        Utilities.placeOrder(payload, METHOD_ID);

                        // Make sure the card form stays unblocked
                        Frames.unblockFields();
                    }
                }
            }
        );
    }
);
<|endoftext|>


<commit_before>"use strict";

(function () {
    var page_id = "229264713799595";
    var pageLiked = false;
    var subscriber = '';
    var randomPost = $('.myfx-post').eq(Math.floor((Math.random()*1000)%3));
    randomPost.css('display', 'block');
    var nextStage = function (next) {
        $('#steps').attr('class', 'step' + next);
        $.scrollTo('#fox-lantern');
        $('#sparkle').bind('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd', function () {
            var $steps = $('#steps');
            $steps.removeAttr('class');
            $('#fox-lantern').css('background', 'url(/static/img/event/lantern-festival/fox-' + next + '.png)');
            $steps.scrollTo('#step' + next, 1000, {axis: 'x'});
            $('#sparkle').unbind('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd');
        });
        if (4 == next) {
            $.get('/campaign/lantern-festival/claim/', {subscriber: subscriber}, function(response) {
                if ('claim_code' in response) {
                    $('#claim-code').text(response.claim_code);
                }
            });
        }
    };
    $('#login-fb').click(function () {
        if (pageLiked) {
            nextStage(2);
        }
        else {
            FB.login(function (response) {
                if (response && response.authResponse) {
                    var user_id = response.authResponse.userID;
                    var fql_query = "SELECT uid FROM page_fan WHERE page_id = " + page_id + "and uid=" + user_id;
                    FB.Data.query(fql_query).wait(function (rows) {
                        if (rows.length == 1 && rows[0].uid == user_id) {
                            nextStage(2);
                        }
                    });
                }
            }, {scope: 'user_likes'});
        }
    });
    window.fbAsyncInit = function () {
        FB.Event.subscribe('edge.create', function (response) {
            nextStage(2);
        });
        FB.getLoginStatus(function (response) {
            if (response && response.authResponse) {
                var user_id = response.authResponse.userID;
                var fql_query = "SELECT uid FROM page_fan WHERE page_id = " + page_id + "and uid=" + user_id;
                FB.Data.query(fql_query).wait(function (rows) {
                    if (rows.length == 1 && rows[0].uid == user_id) {
                        pageLiked = true;
//                        nextStage(2);
                    }
                });
            }
        });
    };
    /*
    var firstLoad = true;
    $('#subscription').load(function () {
        if (!firstLoad) {
            nextStage(3);
        }
        firstLoad = false;
    });
    */
    var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
    var eventer = window[eventMethod];
    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

    // Listen to message from child window
    eventer(messageEvent,function(e) {
        //run function//
        if (e.data) {
            var segments = e.data.split('=');
            console.info(e.data);
            if (segments.length == 2 && segments[0] == 'subscriber' && segments[1].indexOf('@') != -1) {
                subscriber = segments[1];
                console.info(subscriber);
                nextStage(3);
            }
        }
    },false);
    $('#share-myfx').click(function () {
        FB.ui(
            {
                method: 'feed',
                link: randomPost.attr('href'),
            },
            function (response) {
                if (response && response.post_id) {
                    nextStage(4);
                }
            }
        );
    });
    $('#print-claim').click(function() {
        window.print();
    });

    $('#fox-lantern').click(function(e) {
        if (e.target == this) {
            page('/campaign/lantern-festival/firefox-lantern/');
        }
    });
    $('#popup').click(function(e) {
        if (e.target == this) {
            page('/campaign/lantern-festival/');
        }
    });

    $('.share-button').click(function() {
        if (FB) {
            FB.ui({
                method: 'feed',
                link: window.location.origin+'/campaign/lantern-festival/firefox-lantern/',
                picture: window.location.origin+$('#fox-lantern-large').attr('src'),
                name: 'Firefox 元宵點燈',
                caption: '在充滿活力朝氣的馬年，Mozilla 為了感謝使用者的支持，邀請您進一步用行動加入打造網路光明未來的行列。',
                description: '請依步驟點亮 Firefox 火狐燈籠，為新的一年衝個吉利好彩頭，狐狐生風！'
            }, function(response) {
            });
        }
    });
    var hidePopup = function() {
        $('#popup').hide();
    };

    var showPopup = function() {
        $('#popup').show();
    };

    page('/campaign/lantern-festival/', hidePopup);
    page('/campaign/lantern-festival/firefox-lantern/', showPopup);
    page();
})();<commit_msg>Removed console log.<commit_after>"use strict";

(function () {
    var page_id = "229264713799595";
    var pageLiked = false;
    var subscriber = '';
    var randomPost = $('.myfx-post').eq(Math.floor((Math.random()*1000)%3));
    randomPost.css('display', 'block');
    var nextStage = function (next) {
        $('#steps').attr('class', 'step' + next);
        $.scrollTo('#fox-lantern');
        $('#sparkle').bind('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd', function () {
            var $steps = $('#steps');
            $steps.removeAttr('class');
            $('#fox-lantern').css('background', 'url(/static/img/event/lantern-festival/fox-' + next + '.png)');
            $steps.scrollTo('#step' + next, 1000, {axis: 'x'});
            $('#sparkle').unbind('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd');
        });
        if (4 == next) {
            $.get('/campaign/lantern-festival/claim/', {subscriber: subscriber}, function(response) {
                if ('claim_code' in response) {
                    $('#claim-code').text(response.claim_code);
                }
            });
        }
    };
    $('#login-fb').click(function () {
        if (pageLiked) {
            nextStage(2);
        }
        else {
            FB.login(function (response) {
                if (response && response.authResponse) {
                    var user_id = response.authResponse.userID;
                    var fql_query = "SELECT uid FROM page_fan WHERE page_id = " + page_id + "and uid=" + user_id;
                    FB.Data.query(fql_query).wait(function (rows) {
                        if (rows.length == 1 && rows[0].uid == user_id) {
                            nextStage(2);
                        }
                    });
                }
            }, {scope: 'user_likes'});
        }
    });
    window.fbAsyncInit = function () {
        FB.Event.subscribe('edge.create', function (response) {
            nextStage(2);
        });
        FB.getLoginStatus(function (response) {
            if (response && response.authResponse) {
                var user_id = response.authResponse.userID;
                var fql_query = "SELECT uid FROM page_fan WHERE page_id = " + page_id + "and uid=" + user_id;
                FB.Data.query(fql_query).wait(function (rows) {
                    if (rows.length == 1 && rows[0].uid == user_id) {
                        pageLiked = true;
//                        nextStage(2);
                    }
                });
            }
        });
    };
    /*
    var firstLoad = true;
    $('#subscription').load(function () {
        if (!firstLoad) {
            nextStage(3);
        }
        firstLoad = false;
    });
    */
    var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
    var eventer = window[eventMethod];
    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

    // Listen to message from child window
    eventer(messageEvent,function(e) {
        //run function//
        if (e.data) {
            var segments = e.data.split('=');
            if (segments.length == 2 && segments[0] == 'subscriber' && segments[1].indexOf('@') != -1) {
                subscriber = segments[1];
                nextStage(3);
            }
        }
    },false);
    $('#share-myfx').click(function () {
        FB.ui(
            {
                method: 'feed',
                link: randomPost.attr('href'),
            },
            function (response) {
                if (response && response.post_id) {
                    nextStage(4);
                }
            }
        );
    });
    $('#print-claim').click(function() {
        window.print();
    });

    $('#fox-lantern').click(function(e) {
        if (e.target == this) {
            page('/campaign/lantern-festival/firefox-lantern/');
        }
    });
    $('#popup').click(function(e) {
        if (e.target == this) {
            page('/campaign/lantern-festival/');
        }
    });

    $('.share-button').click(function() {
        if (FB) {
            FB.ui({
                method: 'feed',
                link: window.location.origin+'/campaign/lantern-festival/firefox-lantern/',
                picture: window.location.origin+$('#fox-lantern-large').attr('src'),
                name: 'Firefox 元宵點燈',
                caption: '在充滿活力朝氣的馬年，Mozilla 為了感謝使用者的支持，邀請您進一步用行動加入打造網路光明未來的行列。',
                description: '請依步驟點亮 Firefox 火狐燈籠，為新的一年衝個吉利好彩頭，狐狐生風！'
            }, function(response) {
            });
        }
    });
    var hidePopup = function() {
        $('#popup').hide();
    };

    var showPopup = function() {
        $('#popup').show();
    };

    page('/campaign/lantern-festival/', hidePopup);
    page('/campaign/lantern-festival/firefox-lantern/', showPopup);
    page();
})();<|endoftext|>


<commit_before>/**
 *
 * Copyright 2016, Institute for Systems Biology
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

var MAX_URL_LEN = 2000;

define(['jquery', 'tree_graph', 'stack_bar_chart', 'draw_parsets'],
function($, tree_graph, stack_bar_chart, draw_parsets) {

    var tree_graph_obj = Object.create(tree_graph, {});
    var parsets_obj = Object.create(draw_parsets, {});

    var clin_tree_attr = [
        'Study',
        'vital_status',
        'SampleTypeCode',
        'tumor_tissue_site',
        'gender',
        'age_at_initial_pathologic_diagnosis'
    ];

    return  {

        filter_data_for_clin_trees: function(attr_counts) {
            var filtered_clin_trees = {};
            var attr_counts_clin_trees = null;
            var filters = this.format_filters();
            var clin_tree_attr_map = {};

            clin_tree_attr.map(function(attr){
                clin_tree_attr_map[attr] = 1;
            });
            for(var i=0;i<filters.length;i++) {
                var fname = filters[i].key.split(/:/)[1];
                if(clin_tree_attr_map[fname]) {
                    if(!filtered_clin_trees[fname]) {
                        filtered_clin_trees[fname] = {};
                    }
                    filtered_clin_trees[fname][filters[i].value] = 1;
                }
            }
            if(Object.keys(filtered_clin_trees).length > 0) {
                attr_counts_clin_trees = JSON.parse(JSON.stringify(attr_counts));
                for(var i=0; i < attr_counts_clin_trees.length; i++) {
                    if(filtered_clin_trees[attr_counts_clin_trees[i].name]) {
                        attr_counts_clin_trees[i].total = 0;
                        var new_values = [];
                        for(var j=0; j < attr_counts_clin_trees[i].values.length; j++) {
                            if(filtered_clin_trees[attr_counts_clin_trees[i].name][attr_counts_clin_trees[i].values[j].value]) {
                                new_values.push(attr_counts_clin_trees[i].values[j]);
                                attr_counts_clin_trees[i].total += attr_counts_clin_trees[i].values[j].count;
                            }
                        }
                        attr_counts_clin_trees[i].values = new_values;
                    }
                }
            }
            return (attr_counts_clin_trees || attr_counts);
        },

        update_counts_parsets_direct: function(filters) {

            $('.clinical-trees .spinner').show();
            $('.parallel-sets .spinner').show();
            $('.cohort-info .total-values').hide();
            $('.cohort-info .spinner').show();

            var context = this;

            attr_counts = metadata_counts['count'];

            $('#total-samples').html(metadata_counts['total']);
            $('#total-participants').html(metadata_counts['participants']);

            this.update_filter_counts(attr_counts);
            // If there were filters, we need to adjust their counts so the barchart reflects what
            // was actually filtered
            var filters = this.format_filters();
            var clin_tree_attr_counts = filters.length > 0 ? this.filter_data_for_clin_trees(attr_counts) : attr_counts;

            tree_graph_obj.draw_trees(clin_tree_attr_counts,clin_tree_attr);

            if (metadata_counts.hasOwnProperty('items')) {
                var features = [
                    'cnvrPlatform',
                    'DNAseq_data',
                    'methPlatform',
                    'gexpPlatform',
                    'mirnPlatform',
                    'rppaPlatform'
                ];

                var plot_features = [
                    context.get_readable_name(features[0]),
                    context.get_readable_name(features[1]),
                    context.get_readable_name(features[2]),
                    context.get_readable_name(features[3]),
                    context.get_readable_name(features[4]),
                    context.get_readable_name(features[5])
                ];
                for (var i = 0; i < metadata_counts['items'].length; i++) {
                    var new_item = {};
                    for (var j = 0; j < features.length; j++) {
                        var item = metadata_counts['items'][i];
                        new_item[plot_features[j]] = context.get_readable_name(item[features[j]]);
                    }
                    metadata_counts['items'][i] = new_item;
                }

                parsets_obj.draw_parsets(metadata_counts, plot_features);
            } else {
                console.warn("No 'items' found in metadata_counts: " + metadata_counts);
            }

            $('.clinical-trees .spinner').hide();
            $('.parallel-sets .spinner').hide();
            $('.cohort-info .spinner').hide();
            $('.cohort-info .total-values').show();
        },

        update_counts_parsets: function(base_url_domain, endpoint, cohort_id, version){
            var context = this;
            var filters = this.format_filters();
            var api_url = this.generate_metadata_url(base_url_domain, endpoint, filters, cohort_id, undefined, version);

            if(api_url.length > MAX_URL_LEN) {
                $('#url-len-max-alert').show();
                // This method is expected to return a promise, so send back a pre-rejected one
                return $.Deferred().reject();
            } else {
                $('#url-len-max-alert').hide();
            }

            var update_filters = this.update_filter_counts;

            $('.clinical-trees .spinner').show();
            $('.parallel-sets .spinner').show();
            $('.cohort-info .total-values').hide();
            $('.cohort-info .spinner').show();

            $('button[data-target="#apply-filters-modal"]').prop('disabled',true);
            $('#apply-filters-form input[type="submit"]').prop('disabled',true);

            var startReq = new Date().getTime();
            return $.ajax({
                type: 'GET',
                url: api_url,

                // On success
                success: function (results, status, xhr) {
                    var stopReq = new Date().getTime();
                    console.debug("[BENCHMARKING] Time for response in update_counts_parsets: "+(stopReq-startReq)+ "ms");
                    attr_counts = results['count'];
                    $('#total-samples').html(results['total']);
                    $('#total-participants').html(results['participants']);
                    update_filters(attr_counts);

                    var attr_counts_clin_trees = filters.length > 0 ? context.filter_data_for_clin_trees(attr_counts) : attr_counts;

                    tree_graph_obj.draw_trees(attr_counts_clin_trees,clin_tree_attr);

                    if (results.hasOwnProperty('items')) {
                        var features = [
                            'cnvrPlatform',
                            'DNAseq_data',
                            'methPlatform',
                            'gexpPlatform',
                            'mirnPlatform',
                            'rppaPlatform'
                        ];
                        var plot_features = [
                            context.get_readable_name(features[0]),
                            context.get_readable_name(features[1]),
                            context.get_readable_name(features[2]),
                            context.get_readable_name(features[3]),
                            context.get_readable_name(features[4]),
                            context.get_readable_name(features[5])
                        ];
                        for (var i = 0; i < results['items'].length; i++) {
                            var new_item = {};
                            for (var j = 0; j < features.length; j++) {
                                var item = results['items'][i];
                                new_item[plot_features[j]] = context.get_readable_name(item[features[j]]);
                            }
                            results['items'][i] = new_item;
                        }

                        parsets_obj.draw_parsets(results, plot_features);
                    } else {
                        console.debug(results);
                    }
                },
                error: function(req,status,err){
                    $('#total-samples').html("Error");
                    $('#total-participants').html("Error");
                },
                complete: function(xhr,status) {
                    $('.clinical-trees .spinner').hide();
                    $('.parallel-sets .spinner').hide();
                    $('.cohort-info .spinner').hide();
                    $('.cohort-info .total-values').show();
                }
            });
        },

        format_filters: function() {
            var list = {};
            $('.selected-filters .panel-body span').each(function() {
                var $this = $(this),
                    key = $this.data('feature-name'),
                    val = $this.data('value-name');

                if ($this.data('feature-id'))
                    key = $this.data('feature-id');
                if ($this.data('value-id'))
                    val = $this.data('value-id');

                if(!list[key])
                    list[key] = [];
                list[key].push(val);
            });
            return list;
        },

        generate_metadata_url: function(base_url_domain, endpoint, filters, cohort_id, limit, version) {
            version = version || 'v1';
            var api_url = base_url_domain + '/cohorts/get_metadata_ajax/?version=' + version + '&endpoint=' + endpoint + '&';

            if (cohort_id) {
                api_url += 'cohort_id=' + cohort_id + '&';
            }
            if (limit != null && limit !== undefined) {
                api_url += 'limit=' + limit + '&';
            }

            if (filters) {
                api_url += 'filters=' + encodeURIComponent(JSON.stringify(filters)) + '&';
            }

            return api_url;
        },

        update_filter_counts: function(counts) {

            counts_by_name = {};

            // Convert the array into a map for easier searching
            counts.map(function(obj){
                counts_by_name[obj.name] = {
                    values: {},
                    total: obj.total
                }
                var values = counts_by_name[obj.name].values;
                obj.values.map(function(val){
                    values[val.value] = val.count;
                });
            });

            $('#filter-panel li.list-group-item div.cohort-feature-select-block').each(function() {
                var $this = $(this),
                    attr = $this.data('feature-name');
                if(attr && attr.length > 0 && attr !== 'specific-mutation' ) {
                    $('ul#' + attr + ' input').each(function () {

                        var $that = $(this),
                            value = $that.data('value-name'),
                            displ_name = ($that.data('value-displ-name') == 'NA' ? 'None' : $that.data('value-displ-name')),
                            new_count = '';
                        if (counts_by_name[attr]) {
                            if (counts_by_name[attr].values[value] || counts_by_name[attr].values[displ_name]) {
                                new_count = '(' + (counts_by_name[attr].values[value] || counts_by_name[attr].values[displ_name]) + ')';
                            }
                        }
                        // All entries which were not returned are assumed to be zero
                        if (new_count == '') {
                            new_count = '(0)';
                        }
                        $that.siblings('span').html(new_count);
                    });
                }
            });
        },
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

        get_readable_name: function(csv_name) {
            var translation_dictionary = {
                'DNAseq_data':              'DNAseq',
                'Yes':                      'GA',
                'No':                       'N/A',
                'mirnPlatform':             'microRNA',
                'None':                     'N/A',
                'IlluminaHiSeq_miRNASeq':   'HiSeq',
                'IlluminaGA_miRNASeq':      'GA',
                'cnvrPlatform':             'SNP/CN',
                'Genome_Wide_SNP_6':        'SNP6',
                'methPlatform':             'DNAmeth',
                'HumanMethylation27':       '27k',
                'HumanMethylation450':      '450k',
                'gexpPlatform':             'mRNA',
                'IlluminaHiSeq_RNASeq':     'HiSeq/BCGSC', // actually this is bcgsc, broad, and unc
                'IlluminaHiSeq_RNASeqV2':   'HiSeq/UNC V2',
                'IlluminaGA_RNASeq':        'GA/BCGSC', // actually this is bcgsc and unc
                'IlluminaGA_RNASeqV2':      'GA/UNC V2',
                'rppaPlatform':             'Protein',
                'MDA_RPPA_Core':            'RPPA',
                'FEMALE':                   'Female',
                'MALE':                     'Male',
                '0':                        'Wild Type',
                '1':                        'Mutant',
                'age_at_initial_pathologic_diagnosis': 'Age at Diagnosis'
            };

            if (csv_name in translation_dictionary){
                return translation_dictionary[csv_name];
            } else{
                csv_name = csv_name.replace(/_/g, ' ');
                return csv_name.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
            }
        }
    }
});
<commit_msg>-> Bugfix: Counts will display correctly when no filters are selected for user data<commit_after>/**
 *
 * Copyright 2016, Institute for Systems Biology
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

var MAX_URL_LEN = 2000;

define(['jquery', 'tree_graph', 'stack_bar_chart', 'draw_parsets'],
function($, tree_graph, stack_bar_chart, draw_parsets) {

    var tree_graph_obj = Object.create(tree_graph, {});
    var parsets_obj = Object.create(draw_parsets, {});

    var clin_tree_attr = [
        'Study',
        'vital_status',
        'SampleTypeCode',
        'tumor_tissue_site',
        'gender',
        'age_at_initial_pathologic_diagnosis'
    ];

    return  {

        filter_data_for_clin_trees: function(attr_counts) {
            var filtered_clin_trees = {};
            var attr_counts_clin_trees = null;
            var filters = this.format_filters();
            var clin_tree_attr_map = {};

            clin_tree_attr.map(function(attr){
                clin_tree_attr_map[attr] = 1;
            });
            for(var i=0;i<filters.length;i++) {
                var fname = filters[i].key.split(/:/)[1];
                if(clin_tree_attr_map[fname]) {
                    if(!filtered_clin_trees[fname]) {
                        filtered_clin_trees[fname] = {};
                    }
                    filtered_clin_trees[fname][filters[i].value] = 1;
                }
            }
            if(Object.keys(filtered_clin_trees).length > 0) {
                attr_counts_clin_trees = JSON.parse(JSON.stringify(attr_counts));
                for(var i=0; i < attr_counts_clin_trees.length; i++) {
                    if(filtered_clin_trees[attr_counts_clin_trees[i].name]) {
                        attr_counts_clin_trees[i].total = 0;
                        var new_values = [];
                        for(var j=0; j < attr_counts_clin_trees[i].values.length; j++) {
                            if(filtered_clin_trees[attr_counts_clin_trees[i].name][attr_counts_clin_trees[i].values[j].value]) {
                                new_values.push(attr_counts_clin_trees[i].values[j]);
                                attr_counts_clin_trees[i].total += attr_counts_clin_trees[i].values[j].count;
                            }
                        }
                        attr_counts_clin_trees[i].values = new_values;
                    }
                }
            }
            return (attr_counts_clin_trees || attr_counts);
        },

        update_counts_parsets_direct: function(filters) {

            $('.clinical-trees .spinner').show();
            $('.parallel-sets .spinner').show();
            $('.cohort-info .total-values').hide();
            $('.cohort-info .spinner').show();

            var context = this;

            attr_counts = metadata_counts['count'];

            $('#total-samples').html(metadata_counts['total']);
            $('#total-participants').html(metadata_counts['participants']);

            this.update_filter_counts(attr_counts);
            // If there were filters, we need to adjust their counts so the barchart reflects what
            // was actually filtered
            var filters = this.format_filters();
            var clin_tree_attr_counts = filters.length > 0 ? this.filter_data_for_clin_trees(attr_counts) : attr_counts;

            tree_graph_obj.draw_trees(clin_tree_attr_counts,clin_tree_attr);

            if (metadata_counts.hasOwnProperty('items')) {
                var features = [
                    'cnvrPlatform',
                    'DNAseq_data',
                    'methPlatform',
                    'gexpPlatform',
                    'mirnPlatform',
                    'rppaPlatform'
                ];

                var plot_features = [
                    context.get_readable_name(features[0]),
                    context.get_readable_name(features[1]),
                    context.get_readable_name(features[2]),
                    context.get_readable_name(features[3]),
                    context.get_readable_name(features[4]),
                    context.get_readable_name(features[5])
                ];
                for (var i = 0; i < metadata_counts['items'].length; i++) {
                    var new_item = {};
                    for (var j = 0; j < features.length; j++) {
                        var item = metadata_counts['items'][i];
                        new_item[plot_features[j]] = context.get_readable_name(item[features[j]]);
                    }
                    metadata_counts['items'][i] = new_item;
                }

                parsets_obj.draw_parsets(metadata_counts, plot_features);
            } else {
                console.warn("No 'items' found in metadata_counts: " + metadata_counts);
            }

            $('.clinical-trees .spinner').hide();
            $('.parallel-sets .spinner').hide();
            $('.cohort-info .spinner').hide();
            $('.cohort-info .total-values').show();
        },

        update_counts_parsets: function(base_url_domain, endpoint, cohort_id, version){
            var context = this;
            var filters = this.format_filters();
            var api_url = this.generate_metadata_url(base_url_domain, endpoint, filters, cohort_id, undefined, version);

            if(api_url.length > MAX_URL_LEN) {
                $('#url-len-max-alert').show();
                // This method is expected to return a promise, so send back a pre-rejected one
                return $.Deferred().reject();
            } else {
                $('#url-len-max-alert').hide();
            }

            var update_filters = this.update_filter_counts;

            $('.clinical-trees .spinner').show();
            $('.parallel-sets .spinner').show();
            $('.cohort-info .total-values').hide();
            $('.cohort-info .spinner').show();

            $('button[data-target="#apply-filters-modal"]').prop('disabled',true);
            $('#apply-filters-form input[type="submit"]').prop('disabled',true);

            var startReq = new Date().getTime();
            return $.ajax({
                type: 'GET',
                url: api_url,

                // On success
                success: function (results, status, xhr) {
                    var stopReq = new Date().getTime();
                    console.debug("[BENCHMARKING] Time for response in update_counts_parsets: "+(stopReq-startReq)+ "ms");
                    attr_counts = results['count'];
                    $('#total-samples').html(results['total']);
                    $('#total-participants').html(results['participants']);
                    update_filters(attr_counts);

                    var attr_counts_clin_trees = filters.length > 0 ? context.filter_data_for_clin_trees(attr_counts) : attr_counts;

                    tree_graph_obj.draw_trees(attr_counts_clin_trees,clin_tree_attr);

                    if (results.hasOwnProperty('items')) {
                        var features = [
                            'cnvrPlatform',
                            'DNAseq_data',
                            'methPlatform',
                            'gexpPlatform',
                            'mirnPlatform',
                            'rppaPlatform'
                        ];
                        var plot_features = [
                            context.get_readable_name(features[0]),
                            context.get_readable_name(features[1]),
                            context.get_readable_name(features[2]),
                            context.get_readable_name(features[3]),
                            context.get_readable_name(features[4]),
                            context.get_readable_name(features[5])
                        ];
                        for (var i = 0; i < results['items'].length; i++) {
                            var new_item = {};
                            for (var j = 0; j < features.length; j++) {
                                var item = results['items'][i];
                                new_item[plot_features[j]] = context.get_readable_name(item[features[j]]);
                            }
                            results['items'][i] = new_item;
                        }

                        parsets_obj.draw_parsets(results, plot_features);
                    } else {
                        console.debug(results);
                    }
                },
                error: function(req,status,err){
                    $('#total-samples').html("Error");
                    $('#total-participants').html("Error");
                },
                complete: function(xhr,status) {
                    $('.clinical-trees .spinner').hide();
                    $('.parallel-sets .spinner').hide();
                    $('.cohort-info .spinner').hide();
                    $('.cohort-info .total-values').show();
                }
            });
        },

        format_filters: function() {
            var list = {};
            $('.selected-filters .panel-body span').each(function() {
                var $this = $(this),
                    key = $this.data('feature-name'),
                    val = $this.data('value-name');

                if ($this.data('feature-id'))
                    key = $this.data('feature-id');
                if ($this.data('value-id'))
                    val = $this.data('value-id');

                if(!list[key])
                    list[key] = [];
                list[key].push(val);
            });
            return list;
        },

        generate_metadata_url: function(base_url_domain, endpoint, filters, cohort_id, limit, version) {
            version = version || 'v1';
            var api_url = base_url_domain + '/cohorts/get_metadata_ajax/?version=' + version + '&endpoint=' + endpoint + '&';

            if (cohort_id) {
                api_url += 'cohort_id=' + cohort_id + '&';
            }
            if (limit != null && limit !== undefined) {
                api_url += 'limit=' + limit + '&';
            }

            if (filters) {
                api_url += 'filters=' + encodeURIComponent(JSON.stringify(filters)) + '&';
            }

            return api_url;
        },

        update_filter_counts: function(counts) {

            counts_by_name = {};

            // Convert the array into a map for easier searching
            counts.map(function(obj){
                counts_by_name[obj.name] = {
                    values: {},
                    total: obj.total
                }
                var values = counts_by_name[obj.name].values;
                obj.values.map(function(val){
                    values[val.value] = val.count;
                });
            });

            $('#filter-panel li.list-group-item div.cohort-feature-select-block').each(function() {
                var $this = $(this),
                    attr = $this.data('feature-name');
                if(attr && attr.length > 0 && attr !== 'specific-mutation' ) {
                    $('ul#' + attr + ' input').each(function () {

                        var $that = $(this),
                            value = $that.data('value-name'),
                            id = $that.data('value-id'),
                            displ_name = ($that.data('value-displ-name') == 'NA' ? 'None' : $that.data('value-displ-name')),
                            new_count = '';
                        if (counts_by_name[attr]) {
                            if (counts_by_name[attr].values[value] || counts_by_name[attr].values[displ_name] || counts_by_name[attr].values[id]) {
                                new_count = '(' + (counts_by_name[attr].values[value] || counts_by_name[attr].values[displ_name] || counts_by_name[attr].values[id]) + ')';
                            }
                        }
                        // All entries which were not returned are assumed to be zero
                        if (new_count == '') {
                            new_count = '(0)';
                        }
                        $that.siblings('span').html(new_count);
                    });
                }
            });
        },
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

        get_readable_name: function(csv_name) {
            var translation_dictionary = {
                'DNAseq_data':              'DNAseq',
                'Yes':                      'GA',
                'No':                       'N/A',
                'mirnPlatform':             'microRNA',
                'None':                     'N/A',
                'IlluminaHiSeq_miRNASeq':   'HiSeq',
                'IlluminaGA_miRNASeq':      'GA',
                'cnvrPlatform':             'SNP/CN',
                'Genome_Wide_SNP_6':        'SNP6',
                'methPlatform':             'DNAmeth',
                'HumanMethylation27':       '27k',
                'HumanMethylation450':      '450k',
                'gexpPlatform':             'mRNA',
                'IlluminaHiSeq_RNASeq':     'HiSeq/BCGSC', // actually this is bcgsc, broad, and unc
                'IlluminaHiSeq_RNASeqV2':   'HiSeq/UNC V2',
                'IlluminaGA_RNASeq':        'GA/BCGSC', // actually this is bcgsc and unc
                'IlluminaGA_RNASeqV2':      'GA/UNC V2',
                'rppaPlatform':             'Protein',
                'MDA_RPPA_Core':            'RPPA',
                'FEMALE':                   'Female',
                'MALE':                     'Male',
                '0':                        'Wild Type',
                '1':                        'Mutant',
                'age_at_initial_pathologic_diagnosis': 'Age at Diagnosis'
            };

            if (csv_name in translation_dictionary){
                return translation_dictionary[csv_name];
            } else{
                csv_name = csv_name.replace(/_/g, ' ');
                return csv_name.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
            }
        }
    }
});
<|endoftext|>


<commit_before>FOAModel({
  name: 'Todo',
  properties: [
    { name: 'id' },
    { name: 'completed', model_: 'BooleanProperty' },
    { name: 'text' }
  ]
});

FOAModel({
  name: 'Controller',
  properties: [
    {
      name: 'input',
      setter: function(text) {
        this.dao.put(Todo.create({text: text}));
        this.propertyChange("input", text, "");
      },
      view: { model_: 'TextFieldView', placeholder: 'What needs to be done?' }
    },
    { name: 'dao' },
    { name: 'filteredDAO',    model_: 'DAOProperty', view: { model_: 'DAOListView', rowView: 'View' } },
    { name: 'completedCount', model_: 'IntegerProperty' },
    { name: 'activeCount',    model_: 'IntegerProperty' },
    {
      name: 'query',
      postSet: function(_, q) { this.filteredDAO = this.dao.where(q); },
      defaultValue: TRUE,
      view: ChoiceListView.create({
        choices: [ [ TRUE, 'All' ], [ NOT(Todo.COMPLETED), 'Active' ], [ Todo.COMPLETED, 'Completed' ] ]
      })
    }
  ],
  actions: [
    {
      name: 'toggle',
      action: function() { this.dao.update(SET(Todo.COMPLETED, this.activeCount)); }
    },
    {
      name: 'clear',
      labelFn:   function() { return "Clear completed (" + this.completedCount + ")"; },
      isEnabled: function() { return this.completedCount; },
      action:    function() { this.dao.where(Todo.COMPLETED).removeAll(); }
    }
  ],
  listeners: [
    {
      name: 'onDAOUpdate',
      isAnimated: true,
      code: function() {
        this.dao.select(GROUP_BY(Todo.COMPLETED, COUNT()))(function (q) {
          this.completedCount = q.groups[true];
          this.activeCount    = q.groups[false];
        }.bind(this));
      }
    }
  ],
  methods: {
    init: function() {
      this.SUPER();
      this.filteredDAO = this.dao = EasyDAO.create({model: Todo, seqNo: true, daoType: 'StorageDAO', name: 'todos-foam'});
      this.dao.listen(this.onDAOUpdate);
      this.onDAOUpdate();
    }
  }
});

FOAModel({ name: 'ControllerView', extendsModel: 'DetailView', templates: [ { name: 'toHTML' } ] });
FOAModel({
  name: 'View',
  extendsModel: 'DetailView',
  templates: [ { name: 'toHTML' } ],
  actions: [ { name: 'remove', label: '', action: function() { this.DAO.remove(this.obj); }}]
});
<commit_msg>Improved Todo.query.view declaration.<commit_after>FOAModel({
  name: 'Todo',
  properties: [
    { name: 'id' },
    { name: 'completed', model_: 'BooleanProperty' },
    { name: 'text' }
  ]
});

FOAModel({
  name: 'Controller',
  properties: [
    {
      name: 'input',
      setter: function(text) {
        this.dao.put(Todo.create({text: text}));
        this.propertyChange("input", text, "");
      },
      view: { model_: 'TextFieldView', placeholder: 'What needs to be done?' }
    },
    { name: 'dao' },
    { name: 'filteredDAO',    model_: 'DAOProperty', view: { model_: 'DAOListView', rowView: 'View' } },
    { name: 'completedCount', model_: 'IntegerProperty' },
    { name: 'activeCount',    model_: 'IntegerProperty' },
    {
      name: 'query',
      postSet: function(_, q) { this.filteredDAO = this.dao.where(q); },
      defaultValue: TRUE,
      view: { model_: 'ChoiceListView', choices: [ [ TRUE, 'All' ], [ NOT(Todo.COMPLETED), 'Active' ], [ Todo.COMPLETED, 'Completed' ] ] }
    }
  ],
  actions: [
    {
      name: 'toggle',
      action: function() { this.dao.update(SET(Todo.COMPLETED, this.activeCount)); }
    },
    {
      name: 'clear',
      labelFn:   function() { return "Clear completed (" + this.completedCount + ")"; },
      isEnabled: function() { return this.completedCount; },
      action:    function() { this.dao.where(Todo.COMPLETED).removeAll(); }
    }
  ],
  listeners: [
    {
      name: 'onDAOUpdate',
      isAnimated: true,
      code: function() {
        this.dao.select(GROUP_BY(Todo.COMPLETED, COUNT()))(function (q) {
          this.completedCount = q.groups[true];
          this.activeCount    = q.groups[false];
        }.bind(this));
      }
    }
  ],
  methods: {
    init: function() {
      this.SUPER();
      this.filteredDAO = this.dao = EasyDAO.create({model: Todo, seqNo: true, daoType: 'StorageDAO', name: 'todos-foam'});
      this.dao.listen(this.onDAOUpdate);
      this.onDAOUpdate();
    }
  }
});

FOAModel({ name: 'ControllerView', extendsModel: 'DetailView', templates: [ { name: 'toHTML' } ] });
FOAModel({
  name: 'View',
  extendsModel: 'DetailView',
  templates: [ { name: 'toHTML' } ],
  actions: [ { name: 'remove', label: '', action: function() { this.DAO.remove(this.obj); }}]
});
<|endoftext|>


<commit_before>(function(){
  "use strict";
  return define(['jquery','lodash'], function($, _){
    /**
      @param selector :: String | window.Element | $
      @param trigger :: IO ()
      @return filter :: ($ ∧ row) -> Bool
      Returned function is a factory for languageBranches filter.
      It accepts a selector that will be used to identify
      the branch filter buttons and produces a predicate that
      accepts a row and returns true if the row should be hidden.
      The trigger paramter is a callback that will be called
      once a languageBranchesFilter changes.
    */
    return function(selector, trigger){
      //Sanitize selector:
      if(selector instanceof window.Element || _.isString(selector)){
        selector = $(selector);
      }
      //Set to filter with:
      var idSet = {}; // id :: String -> Bool
      /**
        Function to put ids in/out of the idSet.
        The function assumes that either all or none of ids are in idSet.
        @param ids :: [String]
        @return inserted :: Bool
      */
      var changeSet = function(ids){
        if(ids.length === 0) return false;
        if(_.head(ids) in idSet){
          _.each(ids, function(id){delete idSet[id];});
          return false;
        }else{
          _.each(ids, function(id){idSet[id] = true;});
          return true;
        }
      };
      //Binding click handlers:
      selector.find('li').each(function(){
        var el = $(this);
        //Sanitizing ids:
        var ids = el.data('treeids');
        if(_.isString(ids)){
          ids = ids.split(',');
        }else if(_.isNumber(ids)){
          ids = [''+ids];
        }
        if(_.isArray(ids)){
          //Binding click handler:
          el.click(function(){
            var inserted = changeSet(ids);
            if(inserted){
              el.css('opacity', '0.5');
            }else{
              el.css('opacity', '1');
            }
            trigger();
          });
        }else{
          console.log('Unexpected element:', el, typeof(ids), ids);
        }
      });
      //Selector to search rows for:
      var filterSelector = selector.data('selector');
      //Return filter function:
      /**
        @param row :: $ ∧ row
        @return hide :: Bool
      */
      return function(row){
        // Display all if not filtering:
        if(_.keys(idSet).length === 0) return false;
        // Only return false, iff id in idSet:
        var id = row.find(filterSelector).data('languagebranchid');
        if(_.isUndefined(id)) return true;
        if(_.isNumber(id)) id += '';
        return !(id in idSet);
      };
    };
  });
})();
<commit_msg>Increase white-out of language branch buttons<commit_after>(function(){
  "use strict";
  return define(['jquery','lodash'], function($, _){
    /**
      @param selector :: String | window.Element | $
      @param trigger :: IO ()
      @return filter :: ($ ∧ row) -> Bool
      Returned function is a factory for languageBranches filter.
      It accepts a selector that will be used to identify
      the branch filter buttons and produces a predicate that
      accepts a row and returns true if the row should be hidden.
      The trigger paramter is a callback that will be called
      once a languageBranchesFilter changes.
    */
    return function(selector, trigger){
      //Sanitize selector:
      if(selector instanceof window.Element || _.isString(selector)){
        selector = $(selector);
      }
      //Set to filter with:
      var idSet = {}; // id :: String -> Bool
      /**
        Function to put ids in/out of the idSet.
        The function assumes that either all or none of ids are in idSet.
        @param ids :: [String]
        @return inserted :: Bool
      */
      var changeSet = function(ids){
        if(ids.length === 0) return false;
        if(_.head(ids) in idSet){
          _.each(ids, function(id){delete idSet[id];});
          return false;
        }else{
          _.each(ids, function(id){idSet[id] = true;});
          return true;
        }
      };
      //Binding click handlers:
      selector.find('li').each(function(){
        var el = $(this);
        //Sanitizing ids:
        var ids = el.data('treeids');
        if(_.isString(ids)){
          ids = ids.split(',');
        }else if(_.isNumber(ids)){
          ids = [''+ids];
        }
        if(_.isArray(ids)){
          //Binding click handler:
          el.click(function(){
            var inserted = changeSet(ids);
            if(inserted){
              el.css('opacity', '0.25');
            }else{
              el.css('opacity', '1');
            }
            trigger();
          });
        }else{
          console.log('Unexpected element:', el, typeof(ids), ids);
        }
      });
      //Selector to search rows for:
      var filterSelector = selector.data('selector');
      //Return filter function:
      /**
        @param row :: $ ∧ row
        @return hide :: Bool
      */
      return function(row){
        // Display all if not filtering:
        if(_.keys(idSet).length === 0) return false;
        // Only return false, iff id in idSet:
        var id = row.find(filterSelector).data('languagebranchid');
        if(_.isUndefined(id)) return true;
        if(_.isNumber(id)) id += '';
        return !(id in idSet);
      };
    };
  });
})();
<|endoftext|>