<commit_before>'use strict';

/**
 * Manages the addition and editing of new evidence through two modals:
 *
 * 1. Metadata about the new evidence type (e.g. name of PI, database location, clinical lab contact info, etc.)
 * 2. The evidence itself (e.g. number of unaffected variant carriers, associated phenotypes, etc.)
 *
 */

// stdlib
import React from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';

// Third-party lib
import { FormMixin } from '../../../../libs/bootstrap/form';
import { parsePubmed } from '../../../../libs/parse-pubmed';

// Internal lib
import { RestMixin } from '../../../rest';
import { external_url_map } from '../../../globals';
import { EvidenceSheet } from './evidenceSheet';
import { extraEvidence } from './segregationData';
import { NewEvidenceModalMetadata } from './newEvidenceModalMetadata';

let EvidenceModalManager = createReactClass({
    mixins: [FormMixin, RestMixin],

    propTypes: {
        data: PropTypes.object,                     // If null, we are adding.  Otherwise, we are editing.
        allData: PropTypes.array,                   // All extra evidence we've collected
        criteriaList: PropTypes.array,              // Criteria code(s) pertinent to the category/subcategory
        evidenceType: PropTypes.string,             // Evidence source type
        subcategory: PropTypes.string,              // Subcategory (usually the panel) the evidence is part of
        evidenceCollectionDone: PropTypes.func,     // Function to call when we finish with modal 2
        isNew: PropTypes.bool,                      // If we are adding a new piece of evidence or editing an existing piece
        btnTitle: PropTypes.string,                 // Custom link text for adding/editing evidence
        useIcon: PropTypes.bool,                    // Use an icon instead of text as link text
        disableActuator: PropTypes.bool,            // Disable the actuator or not
        affiliation: PropTypes.object,              // The user's affiliation
        session: PropTypes.object,                  // The session object
        canCurrUserModifyEvidence: PropTypes.func,  // Function to check if current logged in user can modify the given evidence
        setBusy: PropTypes.func                     // Function to set case segregation page edit state
    },

    getInitData(){
        let source = {};
        // If current evidence has source data, set as default
        if (this.props.data && this.props.data.source) {
            source = this.props.data.source;
            // If pmid is not set in source metadata, check current evidence articles array
            if (source.metadata['_kind_key'] === 'PMID') {
                if (source.metadata.pmid == undefined) {
                    source.metadata.pmid = this.props.data.articles && this.props.data.articles.length > 0 ? this.props.data.articles[0].pmid : '';
                }
            }
        }
        else {
            source = {'metadata': {}, 'data': {}}
        }

        return source;
    },

    getInitialState() {
        let data = this.getInitData();
        return {
            nextModal: false,        // Flag if able to go to next data form
            sourceData: data,        // Source data being added/edited
            isNew: this.props.isNew  // This may change from T -> F if a matching identifier is found.  See metadataDone() for details.
        };
    },

    componentDidMount(){
        let data = this.getInitData();
        this.setState({
            sourceData: data
        });
    },

    componentWillReceiveProps(nextProps) {
        if(nextProps.data != null && nextProps.data.source != null) {
            this.setState({
                sourceData: nextProps.data.source
            });
        }
        if (nextProps.isNew != null && nextProps.isNew !== this.state.isNew) {
            this.setState({
                isNew: nextProps.isNew
            });
        }
    },

    /**
     * If editing current evidence, return its id.
     * If adding new one, return null.
     */
    getCurrentEvidenceId() {
        // If existing evidence has id, return its id.
        if (this.props.data && this.props.data['@id']) {
            return (this.props.data['@id']);
        }
        else {
            // If adding evidence but same evidence exits, return existing evidence id.
            let foundEvidence = this.getExistingEvidence(this.state.sourceData.metadata);
            if (foundEvidence) {
                return (foundEvidence['@id']);
            }
        }
        // If adding new evidence, return null;
        return null;
    },

    /**
     * Check if an existing evidence has same data as given metadata.
     * If yes, return that evidence; else null.
     *
     * @param {object} metadata  The metadata object
     */
    getExistingEvidence(metadata) {
        let identifierCol = extraEvidence.typeMapping[this.props.evidenceType].fields
            .filter(o => o.identifier === true)
            .map(o => o.name);

        // Determine if this is meant to be linked to an existing piece of evidence that current user can modify
        let candidates = this.props.allData ? this.props.allData
            .filter(o => identifierCol in o.source.metadata
                && o.source.metadata[identifierCol] === metadata[identifierCol]) : [];
        let result = null;
        if (candidates.length > 0) {
            candidates.forEach(candidate => {
                if (this.props.canCurrUserModifyEvidence(candidate)) {
                    result = candidate;
                }
            });
        }
        return result;
    },

    /**
     * Here, we need to check the identifier field against all other known identifier fields.  If we get a match,
     * then we know that even if we were told this is a new entry, it's really an edit of an existing entry that
     * was initially entered in a separate panel.
     *
     * @param {bool} next           T -> Move to next screen, F -> Cancel was clicked
     * @param {object} metadata     The metadata object returned from the modal
     */
    metadataDone(next, metadata) {
        if (next) {
            let candidate = this.getExistingEvidence(metadata);
            let newData = Object.assign({}, this.state.sourceData);
            if (this.props.isNew) {
                if (candidate) {
                    // Editing a piece of evidence initially input in a different panel
                    Object.assign(candidate.source.metadata, metadata);
                    Object.assign(newData, candidate.source);
                    this.setState({
                        isNew: false
                    });
                } else {
                    // Totally new piece of evidence
                    Object.assign(newData.metadata, metadata);
                    this.setState({
                        isNew: true
                    });
                }
            } else {
                // Editing existing evidence
                Object.assign(newData.metadata, metadata);
            }

            // If source is PMID and new evidence, check if Pubmed article needs to be added.
            if (metadata._kind_key === 'PMID' && metadata.pmid && this.state.isNew) {
                this.getRestData('/search/?type=article&pmid=' + metadata.pmid).then(check => {
                    // Article is new to our DB
                    if (check.total < 1) {
                        // PubMed article not in our DB; go out to PubMed itself to retrieve it as XML
                        // Disable the evidence details modal submit button until the article is added to database.
                        // If add fails, the submit will still be disabled and an error message is updated on the modal.
                        this.sheetModal.enableSubmitButton(false);
                        let data = {};
                        this.getRestDataXml(external_url_map['PubMedSearch'] + metadata.pmid).then(xml => {
                            data = parsePubmed(xml);
                            if (data.pmid) {
                                // Found the article and add it to DB
                                this.postRestData('/article/', data).then(result => {
                                    // Article is added so enable the submit button.
                                    this.sheetModal.enableSubmitButton(true);
                                    Promise.resolve(result['@graph'][0]);
                                }).catch(error => {
                                    this.sheetModal.showError('Error in saving Pubmed article to database.  Please try again later.');
                                    console.error('Error in saving Pubmed article to database.');
                                });
                            } else {
                                this.sheetModal.showError('PMID is invalid - ' + metadata.pmid);
                                console.error('PMID is invalid - ' + metadata.pmid);
                            }
                        }).catch(error => {
                            this.sheetModal.showError('PMID is invalid - ' + metadata.pmid);
                            console.error('PMID is invalid - ' + metadata.pmid);
                        });
                    }
                });
            }

            this.setState({
                sourceData: newData,
                nextModal: true
            });
        } else {
            // Cancelled
            this.setState({
                nextModal: false,
                sourceData: this.getInitData()
            });
        }
    },

    reset() {
        this.setState({
            nextModal: false,
            isNew: false,
            sourceData: this.getInitData()
        });
    },

    /**
     * Save the evidence and reset form data.
     *
     * @param {object} data  THe evidence data object returned from modal form
     */
    sheetDone(data) {
        if (data === null) {
            // No change is needed
            this.props.evidenceCollectionDone(false, this.state.sourceData, this.getCurrentEvidenceId(), this.props.subcategory, null);
        }
        else {
            this.props.setBusy(true);
            // Remove empty fields and unnecessary fields - submitted_by, last_modified, _kind_title from source data
            let hasData = Object.keys(data).reduce((object, key) => {
                if (data[key] !== '' && !key.startsWith('_') ) {
                    object[key] = data[key]
                }
                return object
            }, {})

            // Combine the changes with existing data
            let newData = Object.assign({}, this.state.sourceData);
            newData.data = {};
            Object.assign(newData.data, hasData);
            newData['relevant_criteria'] = this.props.criteriaList;
            // if editing existing evidence, get its created date.
            let dateCreated = this.props.data ? this.props.data.date_created : null;
            // Save the evidence data
            this.props.evidenceCollectionDone(true, newData, this.getCurrentEvidenceId(), this.props.subcategory, dateCreated);
        }
        this.reset();
    },

    /**
     * Return the evidence data object
     */
    getSheetData() {
        return this.state.sourceData.data;
    },

    /**
     * Return the evidence metadata object
     */
    getMetadata() {
        return this.state.sourceData.metadata;
    },

    /**
     * Bring up the second modal form for evidence data
     */
    evidenceSheet() {
        if (!this.state.nextModal) {
            return null;
        } else {
            return <EvidenceSheet
                        ready = {this.state.nextModal}
                        sheetDone = {this.sheetDone}
                        data = {this.getSheetData()}
                        allData = {this.props.data}
                        isNew = {this.state.isNew}
                        isFromMaster = {this.props.useIcon}
                        subcategory = {this.props.subcategory}
                        evidenceType = {this.props.evidenceType}
                        onRef={ref => (this.sheetModal = ref)}
                    >
                    </EvidenceSheet>
        }
    },

    render() {
        let jsx = <span>
            <NewEvidenceModalMetadata
                evidenceType = {this.props.evidenceType}
                metadataDone = {this.metadataDone}
                data = {this.getMetadata()}
                isNew = {this.props.isNew}
                btnTitle = {this.props.btnTitle}
                useIcon = {this.props.useIcon}
                disableActuator = {this.props.disableActuator}
            />
            {this.evidenceSheet()}
        </span>;
        return jsx;
    }
});

module.exports = {
    EvidenceModalManager: EvidenceModalManager
}
<commit_msg>Check if function exists before calling it.<commit_after>'use strict';

/**
 * Manages the addition and editing of new evidence through two modals:
 *
 * 1. Metadata about the new evidence type (e.g. name of PI, database location, clinical lab contact info, etc.)
 * 2. The evidence itself (e.g. number of unaffected variant carriers, associated phenotypes, etc.)
 *
 */

// stdlib
import React from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';

// Third-party lib
import { FormMixin } from '../../../../libs/bootstrap/form';
import { parsePubmed } from '../../../../libs/parse-pubmed';

// Internal lib
import { RestMixin } from '../../../rest';
import { external_url_map } from '../../../globals';
import { EvidenceSheet } from './evidenceSheet';
import { extraEvidence } from './segregationData';
import { NewEvidenceModalMetadata } from './newEvidenceModalMetadata';

let EvidenceModalManager = createReactClass({
    mixins: [FormMixin, RestMixin],

    propTypes: {
        data: PropTypes.object,                     // If null, we are adding.  Otherwise, we are editing.
        allData: PropTypes.array,                   // All extra evidence we've collected
        criteriaList: PropTypes.array,              // Criteria code(s) pertinent to the category/subcategory
        evidenceType: PropTypes.string,             // Evidence source type
        subcategory: PropTypes.string,              // Subcategory (usually the panel) the evidence is part of
        evidenceCollectionDone: PropTypes.func,     // Function to call when we finish with modal 2
        isNew: PropTypes.bool,                      // If we are adding a new piece of evidence or editing an existing piece
        btnTitle: PropTypes.string,                 // Custom link text for adding/editing evidence
        useIcon: PropTypes.bool,                    // Use an icon instead of text as link text
        disableActuator: PropTypes.bool,            // Disable the actuator or not
        affiliation: PropTypes.object,              // The user's affiliation
        session: PropTypes.object,                  // The session object
        canCurrUserModifyEvidence: PropTypes.func,  // Function to check if current logged in user can modify the given evidence
        setBusy: PropTypes.func                     // Function to set case segregation page edit state
    },

    getInitData(){
        let source = {};
        // If current evidence has source data, set as default
        if (this.props.data && this.props.data.source) {
            source = this.props.data.source;
            // If pmid is not set in source metadata, check current evidence articles array
            if (source.metadata['_kind_key'] === 'PMID') {
                if (source.metadata.pmid == undefined) {
                    source.metadata.pmid = this.props.data.articles && this.props.data.articles.length > 0 ? this.props.data.articles[0].pmid : '';
                }
            }
        }
        else {
            source = {'metadata': {}, 'data': {}}
        }

        return source;
    },

    getInitialState() {
        let data = this.getInitData();
        return {
            nextModal: false,        // Flag if able to go to next data form
            sourceData: data,        // Source data being added/edited
            isNew: this.props.isNew  // This may change from T -> F if a matching identifier is found.  See metadataDone() for details.
        };
    },

    componentDidMount(){
        let data = this.getInitData();
        this.setState({
            sourceData: data
        });
    },

    componentWillReceiveProps(nextProps) {
        if(nextProps.data != null && nextProps.data.source != null) {
            this.setState({
                sourceData: nextProps.data.source
            });
        }
        if (nextProps.isNew != null && nextProps.isNew !== this.state.isNew) {
            this.setState({
                isNew: nextProps.isNew
            });
        }
    },

    /**
     * If editing current evidence, return its id.
     * If adding new one, return null.
     */
    getCurrentEvidenceId() {
        // If existing evidence has id, return its id.
        if (this.props.data && this.props.data['@id']) {
            return (this.props.data['@id']);
        }
        else {
            // If adding evidence but same evidence exits, return existing evidence id.
            let foundEvidence = this.getExistingEvidence(this.state.sourceData.metadata);
            if (foundEvidence) {
                return (foundEvidence['@id']);
            }
        }
        // If adding new evidence, return null;
        return null;
    },

    /**
     * Check if an existing evidence has same data as given metadata.
     * If yes, return that evidence; else null.
     *
     * @param {object} metadata  The metadata object
     */
    getExistingEvidence(metadata) {
        let identifierCol = extraEvidence.typeMapping[this.props.evidenceType].fields
            .filter(o => o.identifier === true)
            .map(o => o.name);

        // Determine if this is meant to be linked to an existing piece of evidence that current user can modify
        let candidates = this.props.allData ? this.props.allData
            .filter(o => identifierCol in o.source.metadata
                && o.source.metadata[identifierCol] === metadata[identifierCol]) : [];
        let result = null;
        if (candidates.length > 0) {
            candidates.forEach(candidate => {
                if (this.props.canCurrUserModifyEvidence(candidate)) {
                    result = candidate;
                }
            });
        }
        return result;
    },

    /**
     * Here, we need to check the identifier field against all other known identifier fields.  If we get a match,
     * then we know that even if we were told this is a new entry, it's really an edit of an existing entry that
     * was initially entered in a separate panel.
     *
     * @param {bool} next           T -> Move to next screen, F -> Cancel was clicked
     * @param {object} metadata     The metadata object returned from the modal
     */
    metadataDone(next, metadata) {
        if (next) {
            let candidate = this.getExistingEvidence(metadata);
            let newData = Object.assign({}, this.state.sourceData);
            if (this.props.isNew) {
                if (candidate) {
                    // Editing a piece of evidence initially input in a different panel
                    Object.assign(candidate.source.metadata, metadata);
                    Object.assign(newData, candidate.source);
                    this.setState({
                        isNew: false
                    });
                } else {
                    // Totally new piece of evidence
                    Object.assign(newData.metadata, metadata);
                    this.setState({
                        isNew: true
                    });
                }
            } else {
                // Editing existing evidence
                Object.assign(newData.metadata, metadata);
            }

            // If source is PMID and new evidence, check if Pubmed article needs to be added.
            if (metadata._kind_key === 'PMID' && metadata.pmid && this.state.isNew) {
                this.getRestData('/search/?type=article&pmid=' + metadata.pmid).then(check => {
                    // Article is new to our DB
                    if (check.total < 1) {
                        // PubMed article not in our DB; go out to PubMed itself to retrieve it as XML
                        // Disable the evidence details modal submit button until the article is added to database.
                        // If add fails, the submit will still be disabled and an error message is updated on the modal.
                        this.sheetModal.enableSubmitButton(false);
                        let data = {};
                        this.getRestDataXml(external_url_map['PubMedSearch'] + metadata.pmid).then(xml => {
                            data = parsePubmed(xml);
                            if (data.pmid) {
                                // Found the article and add it to DB
                                this.postRestData('/article/', data).then(result => {
                                    // Article is added so enable the submit button.
                                    this.sheetModal.enableSubmitButton(true);
                                    Promise.resolve(result['@graph'][0]);
                                }).catch(error => {
                                    this.sheetModal.showError('Error in saving Pubmed article to database.  Please try again later.');
                                    console.error('Error in saving Pubmed article to database.');
                                });
                            } else {
                                this.sheetModal.showError('PMID is invalid - ' + metadata.pmid);
                                console.error('PMID is invalid - ' + metadata.pmid);
                            }
                        }).catch(error => {
                            this.sheetModal.showError('PMID is invalid - ' + metadata.pmid);
                            console.error('PMID is invalid - ' + metadata.pmid);
                        });
                    }
                });
            }

            this.setState({
                sourceData: newData,
                nextModal: true
            });
        } else {
            // Cancelled
            this.setState({
                nextModal: false,
                sourceData: this.getInitData()
            });
        }
    },

    reset() {
        this.setState({
            nextModal: false,
            isNew: false,
            sourceData: this.getInitData()
        });
    },

    /**
     * Save the evidence and reset form data.
     *
     * @param {object} data  THe evidence data object returned from modal form
     */
    sheetDone(data) {
        if (data === null) {
            // No change is needed
            this.props.evidenceCollectionDone(false, this.state.sourceData, this.getCurrentEvidenceId(), this.props.subcategory, null);
        }
        else {
            if (this.props.setBusy) {
                this.props.setBusy(true);
            }
            // Remove empty fields and unnecessary fields - submitted_by, last_modified, _kind_title from source data
            let hasData = Object.keys(data).reduce((object, key) => {
                if (data[key] !== '' && !key.startsWith('_') ) {
                    object[key] = data[key]
                }
                return object
            }, {})

            // Combine the changes with existing data
            let newData = Object.assign({}, this.state.sourceData);
            newData.data = {};
            Object.assign(newData.data, hasData);
            newData['relevant_criteria'] = this.props.criteriaList;
            // if editing existing evidence, get its created date.
            let dateCreated = this.props.data ? this.props.data.date_created : null;
            // Save the evidence data
            this.props.evidenceCollectionDone(true, newData, this.getCurrentEvidenceId(), this.props.subcategory, dateCreated);
        }
        this.reset();
    },

    /**
     * Return the evidence data object
     */
    getSheetData() {
        return this.state.sourceData.data;
    },

    /**
     * Return the evidence metadata object
     */
    getMetadata() {
        return this.state.sourceData.metadata;
    },

    /**
     * Bring up the second modal form for evidence data
     */
    evidenceSheet() {
        if (!this.state.nextModal) {
            return null;
        } else {
            return <EvidenceSheet
                        ready = {this.state.nextModal}
                        sheetDone = {this.sheetDone}
                        data = {this.getSheetData()}
                        allData = {this.props.data}
                        isNew = {this.state.isNew}
                        isFromMaster = {this.props.useIcon}
                        subcategory = {this.props.subcategory}
                        evidenceType = {this.props.evidenceType}
                        onRef={ref => (this.sheetModal = ref)}
                    >
                    </EvidenceSheet>
        }
    },

    render() {
        let jsx = <span>
            <NewEvidenceModalMetadata
                evidenceType = {this.props.evidenceType}
                metadataDone = {this.metadataDone}
                data = {this.getMetadata()}
                isNew = {this.props.isNew}
                btnTitle = {this.props.btnTitle}
                useIcon = {this.props.useIcon}
                disableActuator = {this.props.disableActuator}
            />
            {this.evidenceSheet()}
        </span>;
        return jsx;
    }
});

module.exports = {
    EvidenceModalManager: EvidenceModalManager
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 airbug inc. http://airbug.com
 *
 * bugpack-registry may be freely distributed under the MIT license.
 */

//-------------------------------------------------------------------------------
// Requires
//-------------------------------------------------------------------------------

var buildbug                = require("buildbug");

//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------

var buildProject            = buildbug.buildProject;
var buildProperties         = buildbug.buildProperties;
var buildScript             = buildbug.buildScript;
var buildTarget             = buildbug.buildTarget;
var enableModule            = buildbug.enableModule;
var parallel                = buildbug.parallel;
var series                  = buildbug.series;
var targetTask              = buildbug.targetTask;

//-------------------------------------------------------------------------------
// Enable Modules
//-------------------------------------------------------------------------------

var aws                     = enableModule("aws");
var bugpack                 = enableModule('bugpack');
var bugunit                 = enableModule('bugunit');
var core                    = enableModule('core');
var lintbug                 = enableModule("lintbug");
var nodejs                  = enableModule('nodejs');
var uglifyjs                = enableModule("uglifyjs");

//-------------------------------------------------------------------------------
// Values
//-------------------------------------------------------------------------------

var name                    = "bugpack-registry";
var version                 = "0.1.7";
var dependencies            = {
    bugpack: "0.1.14"
};

//-------------------------------------------------------------------------------
// Declare Properties
//-------------------------------------------------------------------------------

buildProperties({
    name: name,
    version: version
});

buildProperties({
    node: {
        packageJson: {
            name: "{{name}}",
            version: "{{version}}",
            description: "Registry builder for the bugpack package loader",
            main: "./scripts/bugpack-registry-node.js",
            author: "Brian Neisler <brian@airbug.com>",
            dependencies: dependencies,
            repository: {
                type: "git",
                url: "https://github.com/airbug/bugpack.git"
            },
            bugs: {
                url: "https://github.com/airbug/bugpack/issues"
            },
            licenses: [
                {
                    type : "MIT",
                    url : "https://raw.githubusercontent.com/airbug/bugpack/master/LICENSE"
                }
            ]
        },
        sourcePaths: [
            "../buganno/libraries/buganno/js/src",
            "../bugcore/libraries/bugcore/js/src",
            "../bugfs/libraries/bugfs/js/src",
            "../bugmeta/libraries/bugmeta/js/src",
            "./libraries/bugpack-registry/js/src"
        ],
        scriptPaths: [
            "../buganno/libraries/buganno/js/scripts",
            "./projects/bugpack-registry-node/js/scripts"
        ],
        readmePath: "./README.md",
        unitTest: {
            packageJson: {
                name: "{{name}}-test",
                version: "{{version}}",
                main: "./scripts/bugpack-registry-node.js",
                dependencies: dependencies,
                scripts: {
                    test: "node ./test/scripts/bugunit-run.js"
                }
            },
            sourcePaths: [
                "../bugdouble/libraries/bugdouble/js/src",
                "../bugunit/libraries/bugunit/js/src",
                "../bugyarn/libraries/bugyarn/js/src"
            ],
            scriptPaths: [
                "../bugunit/libraries/bugunit/js/scripts"
            ],
            testPaths: [
                "../buganno/libraries/buganno/js/test",
                "../bugcore/libraries/bugcore/js/test",
                "../bugfs/libraries/bugfs/js/test",
                "../bugmeta/libraries/bugmeta/js/test",
                "./libraries/bugpack-registry/js/test"
            ]
        }
    },
    lint: {
        targetPaths: [
            "."
        ],
        ignorePatterns: [
            ".*\\.buildbug$",
            ".*\\.bugunit$",
            ".*\\.git$",
            ".*node_modules$"
        ]
    }
});

//-------------------------------------------------------------------------------
// BuildTargets
//-------------------------------------------------------------------------------

// Clean BuildTarget
//-------------------------------------------------------------------------------

buildTarget("clean").buildFlow(
    targetTask("clean")
);

// Local BuildTarget
//-------------------------------------------------------------------------------

buildTarget("local").buildFlow(
    series([
        targetTask("clean"),
        targetTask('lint', {
            properties: {
                targetPaths: buildProject.getProperty("lint.targetPaths"),
                ignores: buildProject.getProperty("lint.ignorePatterns"),
                lintTasks: [
                    "cleanupExtraSpacingAtEndOfLines",
                    "ensureNewLineEnding",
                    "indentEqualSignsForPreClassVars",
                    "orderBugpackRequires",
                    "orderRequireAnnotations",
                    "updateCopyright"
                ]
            }
        }),
        parallel([
            series([
                targetTask("createNodePackage", {
                    properties: {
                        packageJson: buildProject.getProperty("node.packageJson"),
                        packagePaths: {
                            "./": [buildProject.getProperty("node.readmePath")],
                            "./lib": buildProject.getProperty("node.sourcePaths").concat(
                                buildProject.getProperty("node.unitTest.sourcePaths")
                            ),
                            "./scripts": buildProject.getProperty("node.scriptPaths").concat(
                                buildProject.getProperty("node.unitTest.scriptPaths")
                            ),
                            "./test": buildProject.getProperty("node.unitTest.testPaths")
                        }
                    }
                }),
                targetTask('generateBugPackRegistry', {
                    init: function(task, buildProject, properties) {
                        var nodePackage = nodejs.findNodePackage(
                            buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version")
                        );
                        task.updateProperties({
                            sourceRoot: nodePackage.getBuildPath()
                        });
                    }
                }),
                targetTask("packNodePackage", {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                }),
                targetTask('startNodeModuleTests', {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(
                            buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version")
                        );
                        task.updateProperties({
                            modulePath: packedNodePackage.getFilePath()
                        });
                    }
                }),
                targetTask("s3PutFile", {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version"));
                        task.updateProperties({
                            file: packedNodePackage.getFilePath(),
                            options: {
                                acl: 'public-read',
                                encrypt: true
                            }
                        });
                    },
                    properties: {
                        bucket: "{{local-bucket}}"
                    }
                })
            ])
        ])
    ])
).makeDefault();

// Prod BuildTarget
//-------------------------------------------------------------------------------

buildTarget("prod").buildFlow(
    series([
        targetTask("clean"),
        targetTask('lint', {
            properties: {
                targetPaths: buildProject.getProperty("lint.targetPaths"),
                ignores: buildProject.getProperty("lint.ignorePatterns"),
                lintTasks: [
                    "cleanupExtraSpacingAtEndOfLines",
                    "ensureNewLineEnding",
                    "indentEqualSignsForPreClassVars",
                    "orderBugpackRequires",
                    "orderRequireAnnotations",
                    "updateCopyright"
                ]
            }
        }),
        parallel([

            //Create test bugpack-registry package

            series([
                targetTask('createNodePackage', {
                    properties: {
                        packageJson: buildProject.getProperty("node.unitTest.packageJson"),
                        packagePaths: {
                            "./": [buildProject.getProperty("node.readmePath")],
                            "./lib": buildProject.getProperty("node.sourcePaths").concat(
                                buildProject.getProperty("node.unitTest.sourcePaths")
                            ),
                            "./scripts": buildProject.getProperty("node.scriptPaths").concat(
                                buildProject.getProperty("node.unitTest.scriptPaths")
                            ),
                            "./test": buildProject.getProperty("node.unitTest.testPaths")
                        }
                    }
                }),
                targetTask('generateBugPackRegistry', {
                    init: function(task, buildProject, properties) {
                        var nodePackage = nodejs.findNodePackage(
                            buildProject.getProperty("node.unitTest.packageJson.name"),
                            buildProject.getProperty("node.unitTest.packageJson.version")
                        );
                        task.updateProperties({
                            sourceRoot: nodePackage.getBuildPath()
                        });
                    }
                }),
                targetTask('packNodePackage', {
                    properties: {
                        packageName: "{{node.unitTest.packageJson.name}}",
                        packageVersion: "{{node.unitTest.packageJson.version}}"
                    }
                }),
                targetTask('startNodeModuleTests', {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(
                            buildProject.getProperty("node.unitTest.packageJson.name"),
                            buildProject.getProperty("node.unitTest.packageJson.version")
                        );
                        task.updateProperties({
                            modulePath: packedNodePackage.getFilePath(),
                            checkCoverage: true
                        });
                    }
                })
            ]),

            // Create production bugpack-registry package

            series([
                targetTask('createNodePackage', {
                    properties: {
                        packageJson: buildProject.getProperty("node.packageJson"),
                        packagePaths: {
                            "./": [buildProject.getProperty("node.readmePath")],
                            "./lib": buildProject.getProperty("node.sourcePaths"),
                            "./scripts": buildProject.getProperty("node.scriptPaths")
                        }
                    }
                }),
                targetTask('generateBugPackRegistry', {
                    init: function(task, buildProject, properties) {
                        var nodePackage = nodejs.findNodePackage(
                            buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version")
                        );
                        task.updateProperties({
                            sourceRoot: nodePackage.getBuildPath()
                        });
                    }
                }),
                targetTask('packNodePackage', {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                }),
                targetTask("s3PutFile", {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version"));
                        task.updateProperties({
                            file: packedNodePackage.getFilePath(),
                            options: {
                                acl: 'public-read',
                                encrypt: true
                            }
                        });
                    },
                    properties: {
                        bucket: "{{prod-deploy-bucket}}"
                    }
                }),
                targetTask('npmConfigSet', {
                    properties: {
                        config: buildProject.getProperty("npmConfig")
                    }
                }),
                targetTask('npmAddUser'),
                targetTask('publishNodePackage', {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                })
            ])
        ])
    ])
);

//-------------------------------------------------------------------------------
// Build Scripts
//-------------------------------------------------------------------------------

buildScript({
    dependencies: [
        "bugcore",
        "bugflow",
        "bugfs"
    ],
    script: "./lintbug.js"
});
<commit_msg>Update buildbug<commit_after>/*
 * Copyright (c) 2014 airbug inc. http://airbug.com
 *
 * bugpack-registry may be freely distributed under the MIT license.
 */

//-------------------------------------------------------------------------------
// Requires
//-------------------------------------------------------------------------------

var buildbug                = require("buildbug");

//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------

var buildProject            = buildbug.buildProject;
var buildProperties         = buildbug.buildProperties;
var buildScript             = buildbug.buildScript;
var buildTarget             = buildbug.buildTarget;
var enableModule            = buildbug.enableModule;
var parallel                = buildbug.parallel;
var series                  = buildbug.series;
var targetTask              = buildbug.targetTask;

//-------------------------------------------------------------------------------
// Enable Modules
//-------------------------------------------------------------------------------

var aws                     = enableModule("aws");
var bugpack                 = enableModule('bugpack');
var bugunit                 = enableModule('bugunit');
var core                    = enableModule('core');
var lintbug                 = enableModule("lintbug");
var nodejs                  = enableModule('nodejs');
var uglifyjs                = enableModule("uglifyjs");

//-------------------------------------------------------------------------------
// Values
//-------------------------------------------------------------------------------

var name                    = "bugpack-registry";
var version                 = "0.1.7";
var dependencies            = {
    bugpack: "0.2.0"
};

//-------------------------------------------------------------------------------
// Declare Properties
//-------------------------------------------------------------------------------

buildProperties({
    name: name,
    version: version
});

buildProperties({
    node: {
        packageJson: {
            name: "{{name}}",
            version: "{{version}}",
            description: "Registry builder for the bugpack package loader",
            main: "./scripts/bugpack-registry-node.js",
            author: "Brian Neisler <brian@airbug.com>",
            dependencies: dependencies,
            repository: {
                type: "git",
                url: "https://github.com/airbug/bugpack.git"
            },
            bugs: {
                url: "https://github.com/airbug/bugpack/issues"
            },
            licenses: [
                {
                    type : "MIT",
                    url : "https://raw.githubusercontent.com/airbug/bugpack/master/LICENSE"
                }
            ]
        },
        sourcePaths: [
            "../buganno/libraries/buganno/js/src",
            "../bugcore/libraries/bugcore/js/src",
            "../bugfs/libraries/bugfs/js/src",
            "../bugmeta/libraries/bugmeta/js/src",
            "./libraries/bugpack-registry/js/src"
        ],
        scriptPaths: [
            "../buganno/libraries/buganno/js/scripts",
            "./projects/bugpack-registry-node/js/scripts"
        ],
        readmePath: "./README.md",
        unitTest: {
            packageJson: {
                name: "{{name}}-test",
                version: "{{version}}",
                main: "./scripts/bugpack-registry-node.js",
                dependencies: dependencies,
                scripts: {
                    test: "node ./test/scripts/bugunit-run.js"
                }
            },
            sourcePaths: [
                "../bugdouble/libraries/bugdouble/js/src",
                "../bugunit/libraries/bugunit/js/src",
                "../bugyarn/libraries/bugyarn/js/src"
            ],
            scriptPaths: [
                "../bugunit/libraries/bugunit/js/scripts"
            ],
            testPaths: [
                "../buganno/libraries/buganno/js/test",
                "../bugcore/libraries/bugcore/js/test",
                "../bugfs/libraries/bugfs/js/test",
                "../bugmeta/libraries/bugmeta/js/test",
                "./libraries/bugpack-registry/js/test"
            ]
        }
    },
    lint: {
        targetPaths: [
            "."
        ],
        ignorePatterns: [
            ".*\\.buildbug$",
            ".*\\.bugunit$",
            ".*\\.git$",
            ".*node_modules$"
        ]
    }
});

//-------------------------------------------------------------------------------
// BuildTargets
//-------------------------------------------------------------------------------

// Clean BuildTarget
//-------------------------------------------------------------------------------

buildTarget("clean").buildFlow(
    targetTask("clean")
);

// Local BuildTarget
//-------------------------------------------------------------------------------

buildTarget("local").buildFlow(
    series([
        targetTask("clean"),
        targetTask('lint', {
            properties: {
                targetPaths: buildProject.getProperty("lint.targetPaths"),
                ignores: buildProject.getProperty("lint.ignorePatterns"),
                lintTasks: [
                    "cleanupExtraSpacingAtEndOfLines",
                    "ensureNewLineEnding",
                    "indentEqualSignsForPreClassVars",
                    "orderBugpackRequires",
                    "orderRequireAnnotations",
                    "updateCopyright"
                ]
            }
        }),
        parallel([
            series([
                targetTask("createNodePackage", {
                    properties: {
                        packageJson: buildProject.getProperty("node.packageJson"),
                        packagePaths: {
                            "./": [buildProject.getProperty("node.readmePath")],
                            "./lib": buildProject.getProperty("node.sourcePaths").concat(
                                buildProject.getProperty("node.unitTest.sourcePaths")
                            ),
                            "./scripts": buildProject.getProperty("node.scriptPaths").concat(
                                buildProject.getProperty("node.unitTest.scriptPaths")
                            ),
                            "./test": buildProject.getProperty("node.unitTest.testPaths")
                        }
                    }
                }),
                targetTask('generateBugPackRegistry', {
                    init: function(task, buildProject, properties) {
                        var nodePackage = nodejs.findNodePackage(
                            buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version")
                        );
                        task.updateProperties({
                            sourceRoot: nodePackage.getBuildPath()
                        });
                    }
                }),
                targetTask("packNodePackage", {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                }),
                targetTask('startNodeModuleTests', {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(
                            buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version")
                        );
                        task.updateProperties({
                            modulePath: packedNodePackage.getFilePath()
                        });
                    }
                }),
                targetTask("s3PutFile", {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version"));
                        task.updateProperties({
                            file: packedNodePackage.getFilePath(),
                            options: {
                                acl: 'public-read',
                                encrypt: true
                            }
                        });
                    },
                    properties: {
                        bucket: "{{local-bucket}}"
                    }
                })
            ])
        ])
    ])
).makeDefault();

// Prod BuildTarget
//-------------------------------------------------------------------------------

buildTarget("prod").buildFlow(
    series([
        targetTask("clean"),
        targetTask('lint', {
            properties: {
                targetPaths: buildProject.getProperty("lint.targetPaths"),
                ignores: buildProject.getProperty("lint.ignorePatterns"),
                lintTasks: [
                    "cleanupExtraSpacingAtEndOfLines",
                    "ensureNewLineEnding",
                    "indentEqualSignsForPreClassVars",
                    "orderBugpackRequires",
                    "orderRequireAnnotations",
                    "updateCopyright"
                ]
            }
        }),
        parallel([

            //Create test bugpack-registry package

            series([
                targetTask('createNodePackage', {
                    properties: {
                        packageJson: buildProject.getProperty("node.unitTest.packageJson"),
                        packagePaths: {
                            "./": [buildProject.getProperty("node.readmePath")],
                            "./lib": buildProject.getProperty("node.sourcePaths").concat(
                                buildProject.getProperty("node.unitTest.sourcePaths")
                            ),
                            "./scripts": buildProject.getProperty("node.scriptPaths").concat(
                                buildProject.getProperty("node.unitTest.scriptPaths")
                            ),
                            "./test": buildProject.getProperty("node.unitTest.testPaths")
                        }
                    }
                }),
                targetTask('generateBugPackRegistry', {
                    init: function(task, buildProject, properties) {
                        var nodePackage = nodejs.findNodePackage(
                            buildProject.getProperty("node.unitTest.packageJson.name"),
                            buildProject.getProperty("node.unitTest.packageJson.version")
                        );
                        task.updateProperties({
                            sourceRoot: nodePackage.getBuildPath()
                        });
                    }
                }),
                targetTask('packNodePackage', {
                    properties: {
                        packageName: "{{node.unitTest.packageJson.name}}",
                        packageVersion: "{{node.unitTest.packageJson.version}}"
                    }
                }),
                targetTask('startNodeModuleTests', {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(
                            buildProject.getProperty("node.unitTest.packageJson.name"),
                            buildProject.getProperty("node.unitTest.packageJson.version")
                        );
                        task.updateProperties({
                            modulePath: packedNodePackage.getFilePath(),
                            checkCoverage: true
                        });
                    }
                })
            ]),

            // Create production bugpack-registry package

            series([
                targetTask('createNodePackage', {
                    properties: {
                        packageJson: buildProject.getProperty("node.packageJson"),
                        packagePaths: {
                            "./": [buildProject.getProperty("node.readmePath")],
                            "./lib": buildProject.getProperty("node.sourcePaths"),
                            "./scripts": buildProject.getProperty("node.scriptPaths")
                        }
                    }
                }),
                targetTask('generateBugPackRegistry', {
                    init: function(task, buildProject, properties) {
                        var nodePackage = nodejs.findNodePackage(
                            buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version")
                        );
                        task.updateProperties({
                            sourceRoot: nodePackage.getBuildPath()
                        });
                    }
                }),
                targetTask('packNodePackage', {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                }),
                targetTask("s3PutFile", {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version"));
                        task.updateProperties({
                            file: packedNodePackage.getFilePath(),
                            options: {
                                acl: 'public-read',
                                encrypt: true
                            }
                        });
                    },
                    properties: {
                        bucket: "{{prod-deploy-bucket}}"
                    }
                }),
                targetTask('npmConfigSet', {
                    properties: {
                        config: buildProject.getProperty("npmConfig")
                    }
                }),
                targetTask('npmAddUser'),
                targetTask('publishNodePackage', {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                })
            ])
        ])
    ])
);

//-------------------------------------------------------------------------------
// Build Scripts
//-------------------------------------------------------------------------------

buildScript({
    dependencies: [
        "bugcore",
        "bugflow",
        "bugfs"
    ],
    script: "./lintbug.js"
});
<|endoftext|>


<commit_before>define('app/views/machine_add', ['app/views/controlled'],
    /**
     *  Machine Add View
     *
     *  @returns Class
     */
    function (ControlledComponent) {
        return App.MachineAddComponent = ControlledComponent.extend({

            layoutName: 'machine_add',
            controllerName: 'machineAddController',

            changeProviderFlag: false,
            dockerNeedScript: false,
            hasAdvancedScript: false,

            hasDocker: function() {
                var provider = Mist.machineAddController.newMachineProvider;
                return provider ? (provider.provider && provider.provider == 'docker' ? true : false) : false;
            }.property('Mist.machineAddController.newMachineProvider'),

            hasOpenstack: function() {
                var provider = Mist.machineAddController.newMachineProvider;
                return provider ? (provider.provider && provider.provider == 'openstack' ? true : false) : false;
            }.property('Mist.machineAddController.newMachineProvider'),

            hasAzure: function() {
                var provider = Mist.machineAddController.newMachineProvider;
                return provider ? (provider.provider && provider.provider == 'azure' ? true : false) : false;
            }.property('Mist.machineAddController.newMachineProvider'),

            hasPacket: function() {
                var provider = Mist.machineAddController.newMachineProvider;
                return provider ? (provider.provider && provider.provider == 'packet' ? true : false) : false;
            }.property('Mist.machineAddController.newMachineProvider'),

            hasKey: function() {
                var provider = Mist.machineAddController.newMachineProvider;
                return provider ? (provider.provider ? (provider.provider != 'docker' || (provider.provider == 'docker' && this.get('dockerNeedScript')) ? true : false) : false) : false;
            }.property('hasDocker', 'dockerNeedScript', 'Mist.machineAddController.newMachineProvider'),

            hasCloudInit: Ember.computed('Mist.machineAddController.newMachineProvider', function() {
                var provider = Mist.machineAddController.newMachineProvider,
                valids = ['openstack', 'azure', 'digitalocean', 'packet', 'gce', 'rackspace', 'rackspace_first_gen', 'vultr'];
                return provider ? (provider.provider ? ((valids.indexOf(provider.provider) != -1 || provider.provider.indexOf('ec2') > -1) ? true : false) : false) : false;
            }),

            hasScript: Ember.computed('hasKey', 'dockerNeedScript', function() {
                return this.get('hasKey') == true || this.get('dockerNeedScript');
            }),

            hasLocation: function() {
                var provider = Mist.machineAddController.newMachineProvider,
                valids = ['docker', 'indonesiancloud', 'vcloud'];
                return provider ? (provider.provider ? (valids.indexOf(provider.provider) != -1 ? false : true) : false) : false;
            }.property('Mist.machineAddController.newMachineProvider'),

            hasNetworks: function() {
                var provider = Mist.machineAddController.newMachineProvider,
                valids = ['openstack', 'hpcloud', 'vcloud'];
                return provider ? (provider.provider ? ((valids.indexOf(provider.provider) != -1 && provider.networks.model.length) ? true : false) : false) : false;
            }.property('Mist.machineAddController.newMachineProvider'),

            hasMonitoring: Ember.computed(function() {
                return Mist.email ? true : false;
            }),

            /**
             *  Properties
             */

            price: function () {

                var image = Mist.machineAddController.newMachineImage;
                var size = Mist.machineAddController.newMachineSize;
                var provider = Mist.machineAddController.newMachineProvider;
                var location = Mist.machineAddController.newMachineLocation;

                if (!image || !image.id || !size || !size.id || !provider || !provider.id) return 0;

                try { //might fail with TypeError if no size for this image
                    if (provider.provider.indexOf('ec2') > -1) {
                        if (image.name.indexOf('SUSE Linux Enterprise') > -1)
                            return size.price.sles;
                        if (image.name.indexOf('Red Hat') > -1)
                            return size.price.rhel;
                        return size.price.linux;
                    }
                    if (provider.provider.indexOf('rackspace') > -1) {
                        if (image.name.indexOf('Red Hat') > -1)
                            return size.price.rhel;
                        if (image.name.indexOf('Vyatta') > -1)
                            return size.price.vyatta;
                        return size.price.linux;
                    }
                    if (provider.provider.indexOf('gce') > -1) {
                        if (location.name.indexOf('europe-') > -1)
                            return size.price.eu;
                        if (location.name.indexOf('us-') > -1)
                            return size.price.us;
                        if (location.name.indexOf('asia-') > -1)
                            return size.price.as;
                        return size.price.eu;
                    }
                    return size.price;

                } catch (error) {
                    return 0;
                }
            }.property('Mist.machineAddController.newMachineProvider',
                       'Mist.machineAddController.newMachineImage',
                       'Mist.machineAddController.newMachineSize',
                       'Mist.machineAddController.newMachineLocation'),

            /**
             *
             *  Initialization
             *
             */

             load: function () {
                Ember.run.next(function(){
                    $( "#create-machine" ).collapsible({
                        expand: function(event, ui) {
                            Mist.machineAddController.open(null);

                            var id = $(this).attr('id'),
                            overlay = id ? $('#' + id+'-overlay') : false;
                            if (overlay) {
                                overlay.removeClass('ui-screen-hidden').addClass('in');
                            }
                            $(this).children().next().hide();
                            $(this).children().next().slideDown(250);
                        }
                    });
                });

                // Add event listeners
                Mist.scriptsController.on('onChange', this, 'renderFields');
                Mist.keysController.on('onKeyListChange', this, 'renderFields');
                Mist.cloudsController.on('onImagesChange', this, 'renderFields');

             }.on('didInsertElement'),

             unload: function () {
                Ember.run.next(function(){
                    $( "#create-machine" ).collapsible({
                        collapse: function(event, ui) {
                            $(this).children().next().slideUp(250);
                            var id = $(this).attr('id'),
                            overlay = id ? $('#' + id+'-overlay') : false;
                            if (overlay) {
                                overlay.removeClass('in').addClass('ui-screen-hidden');
                            }
                        }
                    });
                });

                // Remove event listeners
                Mist.scriptsController.off('onChange', this, 'renderFields');
                Mist.keysController.off('onKeyListChange', this, 'renderFields');
                Mist.cloudsController.off('onImagesChange', this, 'renderFields');

             }.on('willDestroyElement'),

            /**
             *
             *  Methods
             *
             */

             clear: function () {
                 this.$('select').val('basic').slider('refresh');
                 this.$('.ui-collapsible').removeClass('selected');
                 this.setProperties({
                    changeProviderFlag: false,
                    dockerNeedScript: false,
                    hasAdvancedScript: false
                });
                $('#create-machine-floating-ip .ui-checkbox > .ui-btn')
                    .removeClass('ui-checkbox-off')
                    .addClass('ui-checkbox-on');
             },

             checkImageSelected: function(image) {
                if (image) {
                    this.triggerAction({
                        action:'selectProvider',
                        target: this,
                        actionContext: image.cloud
                    });

                    this.triggerAction({
                        action:'selectImage',
                        target: this,
                        actionContext: image
                    });
                }
             },

             fieldIsReady: function (field) {
                $('#create-machine')
                    .find('.ui-collapsible')
                    .collapsible()
                    .collapsible('collapse');
                $('#create-machine-' + field).addClass('selected');
             },

             renderFields: function () {
                Ember.run.schedule('afterRender', this, function() {

                    // Render collapsibles
                    if ($('.ui-collapsible').collapsible) {
                        $('.ui-collapsible').collapsible().enhanceWithin();
                    }

                    // Render listviews
                    if ($('.ui-listview').listview) {
                        $('.ui-listview').listview().listview('refresh');
                    }

                    // Render checkboxes
                    if ($('.ember-checkbox').checkboxradio) {
                        $('.ember-checkbox').checkboxradio().checkboxradio('refresh');
                    }
                });
             },

            /**
             *
             *  Actions
             *
             */

            actions: {

                clickOverlay: function() {
                    $('#create-machine').collapsible('collapse');
                },

                switchToggled: function () {
                    var value = this.$('#script select').val();
                    Mist.machineAddController.set('newMachineScript', '');
                    Mist.machineAddController.set('newMachineScriptParams', '');
                    Mist.machineAddController.set('hasScript', value == 'advanced');
                    this.set('hasAdvancedScript', value == 'advanced');
                    this.renderFields();
                },

                selectProvider: function (cloud) {

                    if (this.fieldIsReady) {
                        this.fieldIsReady('provider');
                    }

                    cloud.networks.model.forEach(function (network, index) {
                        network.set('selected', false);
                    });
                    Mist.machineAddController.set('newMachineLocation', {'name' : 'Select Location'})
                                             .set('newMachineImage', {'name' : 'Select Image'})
                                             .set('newMachineSize', {'name' : 'Select Size'})
                                             .set('newMachineProvider', cloud);

                    // Check we are not on single image page
                    if(! Mist.machineAddController.get('selectedImage')) this.set('changeProviderFlag', true);
                },

                selectImage: function (image) {

                    if (this.fieldIsReady) {
                        this.fieldIsReady('image');
                    }

                    Mist.machineAddController.set('newMachineLocation', {'name' : 'Select Location'})
                                             .set('newMachineSize', {'name' : 'Select Size'})
                                             .set('newMachineImage', image);

                    this.set('dockerNeedScript', image.get('isMist'));
                },

                selectSize: function (size) {
                    this.fieldIsReady('size');

                    Mist.machineAddController.set('newMachineLocation', {'name' : 'Select Location'})
                                             .set('newMachineSize', size);
                },

                selectLocation: function (location) {
                    this.fieldIsReady('location');

                    Mist.machineAddController.set('newMachineLocation', location);
                },

                selectKey: function (key) {
                    this._selectKey(key)
                },

                selectProject: function(project) {
                    this.fieldIsReady('project');

                    Mist.machineAddController.set('newMachineProject', project);
                },

                selectScript: function (script) {
                    Mist.machineAddController.set('newMachineScript', script);
                    $('#create-machine-script-select').collapsible().collapsible('collapse');
                },

                toggleNetworkSelection: function (network) {
                    network.set('selected', !network.selected);
                },

                createKeyClicked: function () {
                    var that = this;
                    Mist.keyAddController.open(function (success, key) {
                        that._selectKey(key);
                    });
                },

                backClicked: function () {
                    Mist.machineAddController.close();
                },

                launchClicked: function () {
                    Mist.machineAddController.add();
                }
            },

            _selectKey: function (key) {
                this.fieldIsReady('key');

                Mist.machineAddController.set('newMachineKey', key);
            },

            /**
             *
             *  Observers
             *
             */

             bindingsObserver: function () {
                Ember.run.once(this, 'renderFields');
             }.observes('Mist.machineAddController.newMachineSize',
                        'Mist.machineAddController.newMachineImage',
                        'Mist.machineAddController.newMachineProvider',
                        'Mist.machineAddController.newMachineLocation'),

             providerObserver: function() {
                 Ember.run.once(this, function(){
                    if (this.changeProviderFlag) Mist.machineAddController._resetProvider();
                 });
             }.observes('Mist.machineAddController.newMachineProvider'),

             networksObserver: function() {
                 Ember.run.once(this, function () {
                    if (this.get('hasOpenstack')) {
                        if (Mist.machineAddController.newMachineProvider.networks.model.filterBy('selected', true).length) {
                            $('#create-machine-floating-ip').slideDown();
                        } else {
                            $('#create-machine-floating-ip').slideUp();
                        }
                    }
                 });
             }.observes('hasOpenstack', 'Mist.machineAddController.newMachineProvider.networks.model.@each.selected')
        });
    }
);
<commit_msg>add extra check for locations<commit_after>define('app/views/machine_add', ['app/views/controlled'],
    /**
     *  Machine Add View
     *
     *  @returns Class
     */
    function (ControlledComponent) {
        return App.MachineAddComponent = ControlledComponent.extend({

            layoutName: 'machine_add',
            controllerName: 'machineAddController',

            changeProviderFlag: false,
            dockerNeedScript: false,
            hasAdvancedScript: false,

            hasDocker: function() {
                var provider = Mist.machineAddController.newMachineProvider;
                return provider ? (provider.provider && provider.provider == 'docker' ? true : false) : false;
            }.property('Mist.machineAddController.newMachineProvider'),

            hasOpenstack: function() {
                var provider = Mist.machineAddController.newMachineProvider;
                return provider ? (provider.provider && provider.provider == 'openstack' ? true : false) : false;
            }.property('Mist.machineAddController.newMachineProvider'),

            hasAzure: function() {
                var provider = Mist.machineAddController.newMachineProvider;
                return provider ? (provider.provider && provider.provider == 'azure' ? true : false) : false;
            }.property('Mist.machineAddController.newMachineProvider'),

            hasPacket: function() {
                var provider = Mist.machineAddController.newMachineProvider;
                return provider ? (provider.provider && provider.provider == 'packet' ? true : false) : false;
            }.property('Mist.machineAddController.newMachineProvider'),

            hasKey: function() {
                var provider = Mist.machineAddController.newMachineProvider;
                return provider ? (provider.provider ? (provider.provider != 'docker' || (provider.provider == 'docker' && this.get('dockerNeedScript')) ? true : false) : false) : false;
            }.property('hasDocker', 'dockerNeedScript', 'Mist.machineAddController.newMachineProvider'),

            hasCloudInit: Ember.computed('Mist.machineAddController.newMachineProvider', function() {
                var provider = Mist.machineAddController.newMachineProvider,
                valids = ['openstack', 'azure', 'digitalocean', 'packet', 'gce', 'rackspace', 'rackspace_first_gen', 'vultr'];
                return provider ? (provider.provider ? ((valids.indexOf(provider.provider) != -1 || provider.provider.indexOf('ec2') > -1) ? true : false) : false) : false;
            }),

            hasScript: Ember.computed('hasKey', 'dockerNeedScript', function() {
                return this.get('hasKey') == true || this.get('dockerNeedScript');
            }),

            hasLocation: function() {
                var provider = Mist.machineAddController.newMachineProvider,
                invalids = ['docker', 'indonesiancloud', 'vcloud'];
                return provider ? (provider.provider ? ((invalids.indexOf(provider.provider) != -1 || provider.locations.model.length == 1) ? false : true) : false) : false;
            }.property('Mist.machineAddController.newMachineProvider'),

            hasNetworks: function() {
                var provider = Mist.machineAddController.newMachineProvider,
                valids = ['openstack', 'hpcloud', 'vcloud'];
                return provider ? (provider.provider ? ((valids.indexOf(provider.provider) != -1 && provider.networks.model.length) ? true : false) : false) : false;
            }.property('Mist.machineAddController.newMachineProvider'),

            hasMonitoring: Ember.computed(function() {
                return Mist.email ? true : false;
            }),

            /**
             *  Properties
             */

            price: function () {

                var image = Mist.machineAddController.newMachineImage;
                var size = Mist.machineAddController.newMachineSize;
                var provider = Mist.machineAddController.newMachineProvider;
                var location = Mist.machineAddController.newMachineLocation;

                if (!image || !image.id || !size || !size.id || !provider || !provider.id) return 0;

                try { //might fail with TypeError if no size for this image
                    if (provider.provider.indexOf('ec2') > -1) {
                        if (image.name.indexOf('SUSE Linux Enterprise') > -1)
                            return size.price.sles;
                        if (image.name.indexOf('Red Hat') > -1)
                            return size.price.rhel;
                        return size.price.linux;
                    }
                    if (provider.provider.indexOf('rackspace') > -1) {
                        if (image.name.indexOf('Red Hat') > -1)
                            return size.price.rhel;
                        if (image.name.indexOf('Vyatta') > -1)
                            return size.price.vyatta;
                        return size.price.linux;
                    }
                    if (provider.provider.indexOf('gce') > -1) {
                        if (location.name.indexOf('europe-') > -1)
                            return size.price.eu;
                        if (location.name.indexOf('us-') > -1)
                            return size.price.us;
                        if (location.name.indexOf('asia-') > -1)
                            return size.price.as;
                        return size.price.eu;
                    }
                    return size.price;

                } catch (error) {
                    return 0;
                }
            }.property('Mist.machineAddController.newMachineProvider',
                       'Mist.machineAddController.newMachineImage',
                       'Mist.machineAddController.newMachineSize',
                       'Mist.machineAddController.newMachineLocation'),

            /**
             *
             *  Initialization
             *
             */

             load: function () {
                Ember.run.next(function(){
                    $( "#create-machine" ).collapsible({
                        expand: function(event, ui) {
                            Mist.machineAddController.open(null);

                            var id = $(this).attr('id'),
                            overlay = id ? $('#' + id+'-overlay') : false;
                            if (overlay) {
                                overlay.removeClass('ui-screen-hidden').addClass('in');
                            }
                            $(this).children().next().hide();
                            $(this).children().next().slideDown(250);
                        }
                    });
                });

                // Add event listeners
                Mist.scriptsController.on('onChange', this, 'renderFields');
                Mist.keysController.on('onKeyListChange', this, 'renderFields');
                Mist.cloudsController.on('onImagesChange', this, 'renderFields');

             }.on('didInsertElement'),

             unload: function () {
                Ember.run.next(function(){
                    $( "#create-machine" ).collapsible({
                        collapse: function(event, ui) {
                            $(this).children().next().slideUp(250);
                            var id = $(this).attr('id'),
                            overlay = id ? $('#' + id+'-overlay') : false;
                            if (overlay) {
                                overlay.removeClass('in').addClass('ui-screen-hidden');
                            }
                        }
                    });
                });

                // Remove event listeners
                Mist.scriptsController.off('onChange', this, 'renderFields');
                Mist.keysController.off('onKeyListChange', this, 'renderFields');
                Mist.cloudsController.off('onImagesChange', this, 'renderFields');

             }.on('willDestroyElement'),

            /**
             *
             *  Methods
             *
             */

             clear: function () {
                 this.$('select').val('basic').slider('refresh');
                 this.$('.ui-collapsible').removeClass('selected');
                 this.setProperties({
                    changeProviderFlag: false,
                    dockerNeedScript: false,
                    hasAdvancedScript: false
                });
                $('#create-machine-floating-ip .ui-checkbox > .ui-btn')
                    .removeClass('ui-checkbox-off')
                    .addClass('ui-checkbox-on');
             },

             checkImageSelected: function(image) {
                if (image) {
                    this.triggerAction({
                        action:'selectProvider',
                        target: this,
                        actionContext: image.cloud
                    });

                    this.triggerAction({
                        action:'selectImage',
                        target: this,
                        actionContext: image
                    });
                }
             },

             fieldIsReady: function (field) {
                $('#create-machine')
                    .find('.ui-collapsible')
                    .collapsible()
                    .collapsible('collapse');
                $('#create-machine-' + field).addClass('selected');
             },

             renderFields: function () {
                Ember.run.schedule('afterRender', this, function() {

                    // Render collapsibles
                    if ($('.ui-collapsible').collapsible) {
                        $('.ui-collapsible').collapsible().enhanceWithin();
                    }

                    // Render listviews
                    if ($('.ui-listview').listview) {
                        $('.ui-listview').listview().listview('refresh');
                    }

                    // Render checkboxes
                    if ($('.ember-checkbox').checkboxradio) {
                        $('.ember-checkbox').checkboxradio().checkboxradio('refresh');
                    }
                });
             },

            /**
             *
             *  Actions
             *
             */

            actions: {

                clickOverlay: function() {
                    $('#create-machine').collapsible('collapse');
                },

                switchToggled: function () {
                    var value = this.$('#script select').val();
                    Mist.machineAddController.set('newMachineScript', '');
                    Mist.machineAddController.set('newMachineScriptParams', '');
                    Mist.machineAddController.set('hasScript', value == 'advanced');
                    this.set('hasAdvancedScript', value == 'advanced');
                    this.renderFields();
                },

                selectProvider: function (cloud) {

                    if (this.fieldIsReady) {
                        this.fieldIsReady('provider');
                    }

                    cloud.networks.model.forEach(function (network, index) {
                        network.set('selected', false);
                    });
                    Mist.machineAddController.set('newMachineLocation', {'name' : 'Select Location'})
                                             .set('newMachineImage', {'name' : 'Select Image'})
                                             .set('newMachineSize', {'name' : 'Select Size'})
                                             .set('newMachineProvider', cloud);

                    // Check we are not on single image page
                    if(! Mist.machineAddController.get('selectedImage')) this.set('changeProviderFlag', true);
                },

                selectImage: function (image) {

                    if (this.fieldIsReady) {
                        this.fieldIsReady('image');
                    }

                    Mist.machineAddController.set('newMachineLocation', {'name' : 'Select Location'})
                                             .set('newMachineSize', {'name' : 'Select Size'})
                                             .set('newMachineImage', image);

                    this.set('dockerNeedScript', image.get('isMist'));
                },

                selectSize: function (size) {
                    this.fieldIsReady('size');

                    Mist.machineAddController.set('newMachineLocation', {'name' : 'Select Location'})
                                             .set('newMachineSize', size);
                },

                selectLocation: function (location) {
                    this.fieldIsReady('location');

                    Mist.machineAddController.set('newMachineLocation', location);
                },

                selectKey: function (key) {
                    this._selectKey(key)
                },

                selectProject: function(project) {
                    this.fieldIsReady('project');

                    Mist.machineAddController.set('newMachineProject', project);
                },

                selectScript: function (script) {
                    Mist.machineAddController.set('newMachineScript', script);
                    $('#create-machine-script-select').collapsible().collapsible('collapse');
                },

                toggleNetworkSelection: function (network) {
                    network.set('selected', !network.selected);
                },

                createKeyClicked: function () {
                    var that = this;
                    Mist.keyAddController.open(function (success, key) {
                        that._selectKey(key);
                    });
                },

                backClicked: function () {
                    Mist.machineAddController.close();
                },

                launchClicked: function () {
                    Mist.machineAddController.add();
                }
            },

            _selectKey: function (key) {
                this.fieldIsReady('key');

                Mist.machineAddController.set('newMachineKey', key);
            },

            /**
             *
             *  Observers
             *
             */

             bindingsObserver: function () {
                Ember.run.once(this, 'renderFields');
             }.observes('Mist.machineAddController.newMachineSize',
                        'Mist.machineAddController.newMachineImage',
                        'Mist.machineAddController.newMachineProvider',
                        'Mist.machineAddController.newMachineLocation'),

             providerObserver: function() {
                 Ember.run.once(this, function(){
                    if (this.changeProviderFlag) Mist.machineAddController._resetProvider();
                 });
             }.observes('Mist.machineAddController.newMachineProvider'),

             networksObserver: function() {
                 Ember.run.once(this, function () {
                    if (this.get('hasOpenstack')) {
                        if (Mist.machineAddController.newMachineProvider.networks.model.filterBy('selected', true).length) {
                            $('#create-machine-floating-ip').slideDown();
                        } else {
                            $('#create-machine-floating-ip').slideUp();
                        }
                    }
                 });
             }.observes('hasOpenstack', 'Mist.machineAddController.newMachineProvider.networks.model.@each.selected')
        });
    }
);
<|endoftext|>


<commit_before>function render_workflow_classifier() {
    var AppView = Backbone.View.extend({
        initialize: function() {
            _.bindAll(this, 'render');
            this.collection.bind('sync', this.render);
            this.render();
        },
        events: {'change #preprocess_select': 'renderPreprocessor',
                 'change #feature_select': 'renderFeature',
                 'change #classifier_select': 'renderClassifier'},
        renderPreprocessor: function {
            $('#params_preprocessor').html('');
            var name = $('#preprocess_select').val();
            if (_.isUndefined(name))
                return;
            model_create_selector($('#slices_select'), $('#params_preprocessor'), 'image_preprocessor', name, true);
        },
        renderFeature: function () {
            $('#params_feature').html('');
            var name = $('#feature_select').val();
            if (_.isUndefined(name))
                return;
            model_create_selector($('#slices_select'), $('#params_feature'), 'feature', name, true);
        },
        renderClassifier: function () {
            $('#params_classifier').html('');
            var name = $('#classifier_select').val();
            if (_.isUndefined(name))
                return;
            model_create_selector($('#slices_select'), $('#params_classifier'), 'classifier', name, true);
        },
        render: function() {
            $('#slices_select').html('');
            $('#slices_select').append(document.getElementById('bpl_slices_select').innerHTML);
            // NOTE(brandyn): Factory parameters needs more specification of output_type
            // as we can't do this automatically without it, for now it is hardcoded
            var preprocessors = PARAMETERS.filter(function (x) {
                return _.contains(['preprocessor'], x.get('name'));
            });
            var features = PARAMETERS.filter(function (x) {
                return _.contains(['bovw', 'picarus.GISTImageFeature', 'picarus.HistogramImageFeature'], x.get('name'));
            });
            var classifiers = PARAMETERS.filter(function (x) {
                return _.contains(['svmlinear', 'svmkernel'], x.get('name'));
            });
            var select_template = "{{#models}}<option value='{{.}}'>{{.}}</option>{{/models}};" // text is escaped already
            $('#preprocess_select').html(Mustache.render(select_template, {models: preprocessors.pluck('name')}));
            $('#feature_select').html(Mustache.render(select_template, {models: features.pluck('name')}));
            $('#classifier_select').html(Mustache.render(select_template, {models: classifiers.pluck('name')}));
            slices_selector();
            renderPreprocessor();
            renderFeature();
            renderClassifier();
        }
    });
    new AppView({collection: PARAMETERS, el: $('#params')});
}<commit_msg>Updated<commit_after>function render_workflow_classifier() {
    var AppView = Backbone.View.extend({
        initialize: function() {
            _.bindAll(this, 'render');
            this.collection.bind('sync', this.render);
            this.render();
        },
        events: {'change #preprocess_select': 'renderPreprocessor',
                 'change #feature_select': 'renderFeature',
                 'change #classifier_select': 'renderClassifier'},
        renderPreprocessor: function () {
            $('#params_preprocessor').html('');
            var name = $('#preprocess_select').val();
            if (_.isUndefined(name))
                return;
            model_create_selector($('#slices_select'), $('#params_preprocessor'), 'image_preprocessor', name, true);
        },
        renderFeature: function () {
            $('#params_feature').html('');
            var name = $('#feature_select').val();
            if (_.isUndefined(name))
                return;
            model_create_selector($('#slices_select'), $('#params_feature'), 'feature', name, true);
        },
        renderClassifier: function () {
            $('#params_classifier').html('');
            var name = $('#classifier_select').val();
            if (_.isUndefined(name))
                return;
            model_create_selector($('#slices_select'), $('#params_classifier'), 'classifier', name, true);
        },
        render: function() {
            $('#slices_select').html('');
            $('#slices_select').append(document.getElementById('bpl_slices_select').innerHTML);
            // NOTE(brandyn): Factory parameters needs more specification of output_type
            // as we can't do this automatically without it, for now it is hardcoded
            var preprocessors = PARAMETERS.filter(function (x) {
                return _.contains(['preprocessor'], x.get('name'));
            });
            var features = PARAMETERS.filter(function (x) {
                return _.contains(['bovw', 'picarus.GISTImageFeature', 'picarus.HistogramImageFeature'], x.get('name'));
            });
            var classifiers = PARAMETERS.filter(function (x) {
                return _.contains(['svmlinear', 'svmkernel'], x.get('name'));
            });
            var select_template = "{{#models}}<option value='{{.}}'>{{.}}</option>{{/models}};" // text is escaped already
            $('#preprocess_select').html(Mustache.render(select_template, {models: preprocessors.pluck('name')}));
            $('#feature_select').html(Mustache.render(select_template, {models: features.pluck('name')}));
            $('#classifier_select').html(Mustache.render(select_template, {models: classifiers.pluck('name')}));
            slices_selector();
            renderPreprocessor();
            renderFeature();
            renderClassifier();
        }
    });
    new AppView({collection: PARAMETERS, el: $('#params')});
}<|endoftext|>


<commit_before>'use strict';

function Checkout(reference, checkoutUri, confirmationUri, notificationUri, termsUri) {
	this.merchant = {
		checkoutUri: checkoutUri,
		confirmationUri: checkoutUri,
		notificationUri: checkoutUri,
		termsUri: checkoutUri,
		reference: reference,
		integrationInfo: 'Custom integration from the lovely open source community'
	};
	this.order = {
		currency: 'sek',
		items: []
	};
	this.gui = {
		locale: 'sv'
	};

	this.addItem = function(item) {
		this.order.items.push(item);
	};
}

module.exports = Checkout;
<commit_msg>fixed notification uri<commit_after>'use strict';

function Checkout(reference, checkoutUri, confirmationUri, notificationUri, termsUri) {
	this.merchant = {
		checkoutUri: checkoutUri,
		confirmationUri: checkoutUri,
		notificationUri: notificationUri,
		termsUri: checkoutUri,
		reference: reference,
		integrationInfo: 'Custom integration from the lovely open source community'
	};
	this.order = {
		currency: 'sek',
		items: []
	};
	this.gui = {
		locale: 'sv'
	};

	this.addItem = function(item) {
		this.order.items.push(item);
	};
}

module.exports = Checkout;
<|endoftext|>