<commit_before>/* global io, sha256 */

// Assumes socket.io loaded from script tag to define io

import { StreamBackendUsingServer } from "./StreamBackendUsingServer.js"

// defines sha256
import "./vendor/sha256.js"
const calculateSHA256 = sha256

export function uuidv4() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0, v = c == "x" ? r : (r & 0x3 | 0x8)
        return v.toString(16)
    })
}

let userID = localStorage.getItem("userID") || "anonymous"

export class Pointrel20190820 {

    constructor() {
        this.clearData()

        this.backend = StreamBackendUsingServer(m.redraw, this.streamId, userID)

        this.redrawFunction = null

        // The "application" name is a debugging hint about what app made the transaction and why
        // use "app/method" for more details
        this.defaultApplicationName = "test"
    }

    clearData() {
        this.tripleIndex = {}
        this.indexedTransactions = {}
        this.latestSHA256 = null
        this.latestSequence = null
        this.streamId = null
        this._isLoaded = false
        this.currentTransaction = null
    }

    newTransaction(application) {
        // The "application" is a debugging hint about what app made the transaction and why -- use "app/method" for more details
        if (!application) application = this.defaultApplicationName
        if (this.currentTransaction) {
            throw new Error("Transaction already in progress")
        }
        this.currentTransaction = {
            previous: undefined,
            sequence: undefined,
            application,
            triples: [],
            type: "triples"
        }
    }

    sendCurrentTransaction() {
        // TODO -- Faking it for now, copying a little code from processNextSend
        const transaction = this.currentTransaction
        const latest = this.getLatestSHA256()
        // const latestTransaction = latest ? await getTransactionFromCache(latest) : null
        const latestTransaction = latest ? this.indexedTransactions[latest] : null
        const sequence = latestTransaction ? latestTransaction.sequence + 1 : 0
        transaction.previous = latest
        transaction.sequence = sequence
        const sha256 = calculateSHA256(JSON.stringify(this.currentTransaction))
        this.addTransactionToTripleIndex(sha256, this.currentTransaction)

        console.log("TODO sendCurrentTransaction")
        // TODO: sendQueue.push(currentTransaction)
        setTimeout(() => this.backend.addItem(transaction), 10)
        this.currentTransaction = null
        this.setLatest(sha256, transaction)
        // TODO if (!sending) processNextSend()
    }

    cancelCurrentTransaction() {
        this.currentTransaction = null
    }

    addTransactionToTripleIndex(sha256, transaction) {
        if (!transaction) {
            console.log("missing transaction")
            return
        }
        if (this.indexedTransactions[sha256]) {
            console.log("transaction already indexed", sha256, transaction)
            return
        }
        if (transaction.type === "triples") {
            const triples = transaction.triples
            // Most recent triples are at end
            for (let i = 0; i < triples.length; i++) {
                const triple = triples[i]
                let aIndex = this.tripleIndex[triple.a]
                if (!aIndex) {
                    aIndex = {}
                    this.tripleIndex[triple.a] = aIndex
                }
                const bJSON = JSON.stringify(triple.b)
                let bIndex = aIndex[bJSON]
                if (!bIndex) {
                    bIndex = {c: triple.c, sequence: transaction.sequence}
                    aIndex[bJSON] = bIndex
                } else {
                    if (bIndex.sequence < transaction.sequence) {
                        bIndex.c = triple.c
                        bIndex.sequence = transaction.sequence
                    }
                }
            }
        }
        // Kludge to use memory storage
        this.indexedTransactions[sha256] = transaction
        // this.indexedTransactions[sha256] = true
    }

    getLatestSHA256() {
        return this.latestSHA256
    }

    setLatest(sha256, newTransaction) {
        if (newTransaction.sequence === undefined || newTransaction.sequence === null) return
        if (this.latestSequence !== null && this.latestSequence >= newTransaction.sequence) return
        this.latestSHA256 = sha256
        this.latestSequence = newTransaction.sequence
    }

    setDefaultApplicationName(name) {
        this.defaultApplicationName = name
    }

    uuidv4() {
        return uuidv4()
    }

    findC(a, b) {
        /*
        // first check any pending transactions -- most recent are at end
        for (let queueIndex = sendQueue.length - 1; queueIndex >= 0; queueIndex--) {
            const transaction = sendQueue[queueIndex]
            if (transaction.type === "triples") {
                const triples = transaction.triples
                // Most recent triples are at end
                for (let i = triples.length - 1; i >= 0; i--) {
                    const triple = triples[i]
                    if (triple.a === a && triple.b === b) return triple.c
                }
            }
        }
        */

        // console.log("this.tripleIndex", this.tripleIndex)
        const aIndex = this.tripleIndex[a]
        if (aIndex) {
            const bJSON = JSON.stringify(b)
            const bIndex = aIndex[bJSON]
            if (bIndex) return bIndex.c
        }

        return undefined
    }

    addTriple(a, b, c) {
        console.log("addTriple", a, b, c)

        const triple = {a, b, c}

        if (this.currentTransaction) {
            this.currentTransaction.triples.push(triple)
        } else {
            this.newTransaction()
            this.currentTransaction.triples.push(triple)
            this.sendCurrentTransaction()
        }
    }

    // setId is optional
    findBC(a, setId) {
        const result = {}

        /*
        // first check any pending transactions -- most recent are at end
        for (let queueIndex = sendQueue.length - 1; queueIndex >= 0; queueIndex--) {
            const transaction = sendQueue[queueIndex]
            if (transaction.type === "triples") {
                const triples = transaction.triples
                // Most recent triples are at end
                for (let i = triples.length - 1; i >= 0; i--) {
                    const triple = triples[i]
                    const bJSON = JSON.stringify(triple.b)
                    if (triple.a === a && result[bJSON] === undefined) {
                        if (!setId || triple.b[setId]) {
                            result[bJSON] = triple.c
                        }
                    }
                }
            }
        }
        */

        const aIndex = this.tripleIndex[a]
        if (aIndex) {
            const keys = Object.keys(aIndex)
            for (let bJSON of keys) {
                if (result[bJSON] === undefined) {
                    if (!setId || JSON.parse(bJSON)[setId]) {
                        result[bJSON] = aIndex[bJSON].c
                    }
                }
            }
        }

        return result
    }

    isOffline() {
        return !this.backend.isOnline()
    }

    goOnline() {
        // Not sure what to do here that is similar to Twirlip9
        console.log("goOnline TODO")
    }

    isLoaded() {
        return this._isLoaded
    }

    getLatestSequence() {
        return this.latestSequence
    }

    setRedrawFunction(f) {
        this.redrawFunction = f
    }

    setStreamId(streamId, keepData) {
        console.log("setStreamId", streamId)
        if (this.streamId === streamId) return
        if (!keepData) this.clearData()
        this.streamId = streamId
        this.backend.configure(this.streamId)
    }

    // Returns promise that resolves when loaded
    async updateFromStorage() {
        return new Promise((resolve, reject) => {
            this.backend.connect({
                onLoaded: () => {
                    this._isLoaded = true
                    console.log("onLoaded")
                    resolve()
                },
                addItem: (item, isAlreadyStored) => {
                    console.log("addItem", item)
                    const sha256 = calculateSHA256(JSON.stringify(item))
                    this.addTransactionToTripleIndex(sha256, item)
                    this.setLatest(sha256, item)
                }
            })
            try {
                console.log("backend setup start")
                this.backend.setup(io)
            } catch(e) {
                alert("This app requires a backend server supporting socket.io (i.e. won't work correctly on rawgit)")
                reject(e)
            }
        })
    }
}
<commit_msg>pointrel: remove some logging<commit_after>/* global io, sha256 */

// Assumes socket.io loaded from script tag to define io

import { StreamBackendUsingServer } from "./StreamBackendUsingServer.js"

// defines sha256
import "./vendor/sha256.js"
const calculateSHA256 = sha256

export function uuidv4() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0, v = c == "x" ? r : (r & 0x3 | 0x8)
        return v.toString(16)
    })
}

let userID = localStorage.getItem("userID") || "anonymous"

export class Pointrel20190820 {

    constructor() {
        this.clearData()

        this.backend = StreamBackendUsingServer(m.redraw, this.streamId, userID)

        this.redrawFunction = null

        // The "application" name is a debugging hint about what app made the transaction and why
        // use "app/method" for more details
        this.defaultApplicationName = "test"
    }

    clearData() {
        this.tripleIndex = {}
        this.indexedTransactions = {}
        this.latestSHA256 = null
        this.latestSequence = null
        this.streamId = null
        this._isLoaded = false
        this.currentTransaction = null
    }

    newTransaction(application) {
        // The "application" is a debugging hint about what app made the transaction and why -- use "app/method" for more details
        if (!application) application = this.defaultApplicationName
        if (this.currentTransaction) {
            throw new Error("Transaction already in progress")
        }
        this.currentTransaction = {
            previous: undefined,
            sequence: undefined,
            application,
            triples: [],
            type: "triples"
        }
    }

    sendCurrentTransaction() {
        // TODO -- Faking it for now, copying a little code from processNextSend
        const transaction = this.currentTransaction
        const latest = this.getLatestSHA256()
        // const latestTransaction = latest ? await getTransactionFromCache(latest) : null
        const latestTransaction = latest ? this.indexedTransactions[latest] : null
        const sequence = latestTransaction ? latestTransaction.sequence + 1 : 0
        transaction.previous = latest
        transaction.sequence = sequence
        const sha256 = calculateSHA256(JSON.stringify(this.currentTransaction))
        this.addTransactionToTripleIndex(sha256, this.currentTransaction)

        // TODO: sendQueue.push(currentTransaction)
        setTimeout(() => this.backend.addItem(transaction), 10)
        this.currentTransaction = null
        this.setLatest(sha256, transaction)
        // TODO if (!sending) processNextSend()
    }

    cancelCurrentTransaction() {
        this.currentTransaction = null
    }

    addTransactionToTripleIndex(sha256, transaction) {
        if (!transaction) {
            console.log("missing transaction")
            return
        }
        if (this.indexedTransactions[sha256]) {
            // console.log("transaction already indexed", sha256, transaction)
            return
        }
        if (transaction.type === "triples") {
            const triples = transaction.triples
            // Most recent triples are at end
            for (let i = 0; i < triples.length; i++) {
                const triple = triples[i]
                let aIndex = this.tripleIndex[triple.a]
                if (!aIndex) {
                    aIndex = {}
                    this.tripleIndex[triple.a] = aIndex
                }
                const bJSON = JSON.stringify(triple.b)
                let bIndex = aIndex[bJSON]
                if (!bIndex) {
                    bIndex = {c: triple.c, sequence: transaction.sequence}
                    aIndex[bJSON] = bIndex
                } else {
                    if (bIndex.sequence < transaction.sequence) {
                        bIndex.c = triple.c
                        bIndex.sequence = transaction.sequence
                    }
                }
            }
        }
        // Kludge to use memory storage
        this.indexedTransactions[sha256] = transaction
        // this.indexedTransactions[sha256] = true
    }

    getLatestSHA256() {
        return this.latestSHA256
    }

    setLatest(sha256, newTransaction) {
        if (newTransaction.sequence === undefined || newTransaction.sequence === null) return
        if (this.latestSequence !== null && this.latestSequence >= newTransaction.sequence) return
        this.latestSHA256 = sha256
        this.latestSequence = newTransaction.sequence
    }

    setDefaultApplicationName(name) {
        this.defaultApplicationName = name
    }

    uuidv4() {
        return uuidv4()
    }

    findC(a, b) {
        /*
        // first check any pending transactions -- most recent are at end
        for (let queueIndex = sendQueue.length - 1; queueIndex >= 0; queueIndex--) {
            const transaction = sendQueue[queueIndex]
            if (transaction.type === "triples") {
                const triples = transaction.triples
                // Most recent triples are at end
                for (let i = triples.length - 1; i >= 0; i--) {
                    const triple = triples[i]
                    if (triple.a === a && triple.b === b) return triple.c
                }
            }
        }
        */

        // console.log("this.tripleIndex", this.tripleIndex)
        const aIndex = this.tripleIndex[a]
        if (aIndex) {
            const bJSON = JSON.stringify(b)
            const bIndex = aIndex[bJSON]
            if (bIndex) return bIndex.c
        }

        return undefined
    }

    addTriple(a, b, c) {
        // console.log("addTriple", a, b, c)

        const triple = {a, b, c}

        if (this.currentTransaction) {
            this.currentTransaction.triples.push(triple)
        } else {
            this.newTransaction()
            this.currentTransaction.triples.push(triple)
            this.sendCurrentTransaction()
        }
    }

    // setId is optional
    findBC(a, setId) {
        const result = {}

        /*
        // first check any pending transactions -- most recent are at end
        for (let queueIndex = sendQueue.length - 1; queueIndex >= 0; queueIndex--) {
            const transaction = sendQueue[queueIndex]
            if (transaction.type === "triples") {
                const triples = transaction.triples
                // Most recent triples are at end
                for (let i = triples.length - 1; i >= 0; i--) {
                    const triple = triples[i]
                    const bJSON = JSON.stringify(triple.b)
                    if (triple.a === a && result[bJSON] === undefined) {
                        if (!setId || triple.b[setId]) {
                            result[bJSON] = triple.c
                        }
                    }
                }
            }
        }
        */

        const aIndex = this.tripleIndex[a]
        if (aIndex) {
            const keys = Object.keys(aIndex)
            for (let bJSON of keys) {
                if (result[bJSON] === undefined) {
                    if (!setId || JSON.parse(bJSON)[setId]) {
                        result[bJSON] = aIndex[bJSON].c
                    }
                }
            }
        }

        return result
    }

    isOffline() {
        return !this.backend.isOnline()
    }

    goOnline() {
        // Not sure what to do here that is similar to Twirlip9
        console.log("goOnline TODO")
    }

    isLoaded() {
        return this._isLoaded
    }

    getLatestSequence() {
        return this.latestSequence
    }

    setRedrawFunction(f) {
        this.redrawFunction = f
    }

    setStreamId(streamId, keepData) {
        console.log("setStreamId", streamId)
        if (this.streamId === streamId) return
        if (!keepData) this.clearData()
        this.streamId = streamId
        this.backend.configure(this.streamId)
    }

    // Returns promise that resolves when loaded
    async updateFromStorage() {
        return new Promise((resolve, reject) => {
            this.backend.connect({
                onLoaded: () => {
                    this._isLoaded = true
                    console.log("onLoaded")
                    resolve()
                },
                addItem: (item, isAlreadyStored) => {
                    // console.log("addItem", item)
                    const sha256 = calculateSHA256(JSON.stringify(item))
                    this.addTransactionToTripleIndex(sha256, item)
                    this.setLatest(sha256, item)
                }
            })
            try {
                console.log("backend setup start")
                this.backend.setup(io)
            } catch(e) {
                alert("This app requires a backend server supporting socket.io (i.e. won't work correctly on rawgit)")
                reject(e)
            }
        })
    }
}
<|endoftext|>


<commit_before>define(['sprd/view/svg/ConfigurationRenderer', 'underscore'], function(ConfigurationRenderer, _) {

    return ConfigurationRenderer.inherit("sprd.view.svg.TextConfigurationRendererClass", {

        defaults: {
            tagName: "g",
            componentClass: "text-configuration",
            textArea: null
        },

        ctor: function() {
            this.callBase();

            this.bind("configuration", "formatChanged", function() {
                this._loadFonts();
                var textArea = this.$.textArea;
                textArea && textArea._renderTextFlow(textArea.$.textFlow);
            }, this);
        },

        _initialize: function() {
            this.callBase();
            this._loadFonts();
        },

        _loadFonts: function() {
            var fonts = this.getFonts(),
                svgRoot = this.getSvgRoot();

            for (var i = 0; i < fonts.length; i++) {
                var font = fonts[i];
                svgRoot.fontManager.loadExternalFont(font.getUniqueFontName(), "fonts/svg/" + font.$.id + ".svg#font");
            }
        },

        getFonts: function() {
            var fonts = [];

            var configuration = this.$.configuration;
            if (configuration && configuration.$.textFlow) {
                addFonts(configuration.$.textFlow);
            }

            return fonts;

            function addFonts(flowElement) {
                if (flowElement) {
                    var font = flowElement.get("style.font");

                    if (font && _.indexOf(fonts, font) === -1) {
                        fonts.push(font);
                    }

                    !flowElement.isLeaf && flowElement.$.children.each(function(child) {
                        addFonts(child);
                    });
                }
            }
        },

        handleKeyPress: function(e){
            this.$.textArea.handleKeyPress(e);
        },

        handleKeyDown: function(e){
            console.log(e);
            this.$.textArea.handleKeyDown(e);
        }

    });
});
<commit_msg>removed console.log<commit_after>define(['sprd/view/svg/ConfigurationRenderer', 'underscore'], function(ConfigurationRenderer, _) {

    return ConfigurationRenderer.inherit("sprd.view.svg.TextConfigurationRendererClass", {

        defaults: {
            tagName: "g",
            componentClass: "text-configuration",
            textArea: null
        },

        ctor: function() {
            this.callBase();

            this.bind("configuration", "formatChanged", function() {
                this._loadFonts();
                var textArea = this.$.textArea;
                textArea && textArea._renderTextFlow(textArea.$.textFlow);
            }, this);
        },

        _initialize: function() {
            this.callBase();
            this._loadFonts();
        },

        _loadFonts: function() {
            var fonts = this.getFonts(),
                svgRoot = this.getSvgRoot();

            for (var i = 0; i < fonts.length; i++) {
                var font = fonts[i];
                svgRoot.fontManager.loadExternalFont(font.getUniqueFontName(), "fonts/svg/" + font.$.id + ".svg#font");
            }
        },

        getFonts: function() {
            var fonts = [];

            var configuration = this.$.configuration;
            if (configuration && configuration.$.textFlow) {
                addFonts(configuration.$.textFlow);
            }

            return fonts;

            function addFonts(flowElement) {
                if (flowElement) {
                    var font = flowElement.get("style.font");

                    if (font && _.indexOf(fonts, font) === -1) {
                        fonts.push(font);
                    }

                    !flowElement.isLeaf && flowElement.$.children.each(function(child) {
                        addFonts(child);
                    });
                }
            }
        },

        handleKeyPress: function(e){
            this.$.textArea.handleKeyPress(e);
        },

        handleKeyDown: function(e){
            this.$.textArea.handleKeyDown(e);
        }

    });
});
<|endoftext|>


<commit_before>"use strict";
var deployService = soajsApp.components;
deployService.service('deploySrv', ['ngDataApi', '$timeout', '$modal', function(ngDataApi, $timeout, $modal) {

    function deployEnvironment(currentScope, envCode, haMode) {
        var formConfig = angular.copy(environmentsConfig.form.deploy);
        var kubeConfig = environmentsConfig.deployer.kubernetes;

        currentScope.isKubernetes = (currentScope.deployer.selected.split('.')[1] === "kubernetes");
        if(currentScope.isKubernetes){
            formConfig.entries[0].entries[1].min = kubeConfig.minPort;
            formConfig.entries[0].entries[1].max = kubeConfig.maxPort;
            formConfig.entries[0].entries[1].fieldMsg += ". Kubernetees port range: " + kubeConfig.minPort + " - " + kubeConfig.maxPort;
        }

        getControllerBranches(currentScope, function (branchInfo) {
            for (var i = 0; i < formConfig.entries.length; i++) {
                if (formConfig.entries[i].name === 'controllers') {
                    var ctrlEntries = formConfig.entries[i].entries;
                    for (var j = 0; j < ctrlEntries.length; j++) {
                        if (ctrlEntries[j].name === 'branch') {
                            branchInfo.branches.forEach(function (oneBranch) {
                                delete oneBranch.commit.url;
                                ctrlEntries[j].value.push({'v': oneBranch, 'l': oneBranch.name});
                            });
                        }
                    }
                }
            }

            var customUIEntry = {
                'name': 'useCustomUI',
                'label': 'Do you want to bundle static content?',
                'type': 'radio',
                'value': [{'v': true, 'l': 'Yes'}, {'v': false, 'l': 'No', 'selected': true}],
                'required': true,
                'onAction': function (label, selected, formConfig) {
                    if (selected === 'true' && (!formConfig.entries[0].entries[5] || formConfig.entries[0].entries[5].name !== 'selectCustomUI')) {
                        listStaticContent(currentScope, function (staticContentSources) {
                            var selectCustomUI = {
                                'name': 'selectCustomUI',
                                'label': 'Choose Static Content',
                                'type': 'select',
                                'value': [],
                                'required': true,
                                'onAction': function (label, selected, formConfig) {
                                    var selectUIBranch = {
                                        'name': 'selectUIBranch',
                                        'label': 'Choose Static Content Branch',
                                        'type': 'select',
                                        'value': [],
                                        'required': true
                                    };
                                    selected = JSON.parse(selected);
                                    overlayLoading.show();
                                    getSendDataFromServer(currentScope, ngDataApi, {
                                        method: 'get',
                                        routeName: '/dashboard/gitAccounts/getBranches',
                                        params: {
                                            name: selected.name,
                                            type: 'static'
                                        }
                                    }, function (error, response) {
                                        overlayLoading.hide();
                                        if (error) {
                                            currentScope.generateNewMsg(envCode, 'danger', error.message);
                                        }
                                        else {
                                            response.branches.forEach(function (oneBranch) {
                                                selectUIBranch.value.push({'v': oneBranch, 'l': oneBranch.name});
                                            });

                                            formConfig.entries[0].entries.splice(6, 0, selectUIBranch);
                                        }
                                    });
                                }
                            };
                            staticContentSources.forEach (function (oneSource) {
                                selectCustomUI.value.push ({'v': oneSource, 'l': oneSource.name});
                            });
                            formConfig.entries[0].entries.splice(5, 0, selectCustomUI);
                        });
                    } else if (selected === 'false' && formConfig.entries[0].entries[5].name === 'selectCustomUI') {
                        if (formConfig.entries[0].entries[6] && formConfig.entries[0].entries[6].name === 'selectUIBranch') {
                            formConfig.entries[0].entries.splice(6, 1);
                            delete formConfig.formData.selectUIBranch;
                        }
                        formConfig.entries[0].entries.splice(5, 1);
                        delete formConfig.formData.selectCustomUI;
                    }
                }
            };
            formConfig.entries[0].entries.splice(4, 0, customUIEntry);

            for (var i = 0; i < formConfig.entries[1].entries.length; i++) {
                if (formConfig.entries[1].entries[i].name === 'defaultENVVAR') {
                    formConfig.entries[1].entries[i].value = formConfig.entries[1].entries[i].value.replace("%envName%", envCode);
                    formConfig.entries[1].entries[i].value = formConfig.entries[1].entries[i].value.replace("%profilePathToUse%", currentScope.profile);
                }
            }

            var options = {
                timeout: $timeout,
                form: formConfig,
                name: 'deployEnv',
                label: translation.deployEnvironment[LANG] + ' ' + envCode,
                actions: [
                    {
                        'type': 'submit',
                        'label': translation.submit[LANG],
                        'btn': 'primary',
                        'action': function(formData) {
                            if(!formData.controllers || formData.controllers < 1) {
                                $timeout(function() {
                                    alert(translation.youMustChooseLeastControllerDeployEnvironment[LANG]);
                                }, 100);
                            }
                            else {
                                currentScope.modalInstance.dismiss("ok");
                                var text = "
" + translation.deployingNew[LANG] + envCode + " Environment
";
                                text += "
" +  translation.deploying[LANG] + formData.controllers + translation.newControllersEnvironment[LANG] + envCode + ".
";
                                text += "
" + translation.doNotRefreshThisPageThisWillTakeFewMinutes[LANG] + "
";
                                text += "

";
                                jQuery('#overlay').html("

" + text + "
");
                                jQuery("#overlay .content").css("width", "40%").css("left", "30%");
                                overlay.show();

                                formData.owner = branchInfo.owner;
                                formData.repo = branchInfo.repo;

                                deployEnvironment(formData);
                            }

                        }
                    },
                    {
                        'type': 'reset',
                        'label': translation.cancel[LANG],
                        'btn': 'danger',
                        'action': function() {
                            currentScope.modalInstance.dismiss('cancel');
                            currentScope.form.formData = {};
                        }
                    }
                ]
            };
            buildFormWithModal(currentScope, $modal, options);
        });

        function deployEnvironment(formData) {
            var branchObj = JSON.parse(formData.branch);
            var params = {
                'envCode': envCode,
                "number": formData.controllers,
                'owner': formData.owner,
                'repo': formData.repo,
                'branch': branchObj.name,
                'commit': branchObj.commit.sha,
                'useLocalSOAJS': formData.useLocalSOAJS,
                'imagePrefix': formData.ctrlImagePrefix
            };

            if(currentScope.isKubernetes) {
                params.isKubernetes = true;
            }

            if (formData.exposedPort) {
                params.exposedPort = formData.exposedPort;
            }

            if (formData.useCustomUI) {
                formData.selectUIBranch = JSON.parse(formData.selectUIBranch);
                formData.selectCustomUI = JSON.parse(formData.selectCustomUI);
                params.nginxConfig = {
                    customUIId: formData.selectCustomUI._id,
                    branch: formData.selectUIBranch.name,
                    commit: formData.selectUIBranch.commit.sha
                };
            }

            if(formData.variables && formData.variables !== ''){
                params.variables = formData.variables.split(",");
                for(var i =0; i < params.variables.length; i++){
                    params.variables[i] = params.variables[i].trim();
                }
            }

            if (haMode) {
                params.name = 'controller';
                params.haService = true;
                params.haCount = formData.controllers;
                params.memoryLimit = (formData.ctrlMemoryLimit * 1048576);
            }

            getSendDataFromServer(currentScope, ngDataApi, {
                "method": "send",
                "routeName": "/dashboard/hosts/deployController",
                "data": params
            }, function(error, response) {
                if(error) {
                    overlay.hide();
                    //currentScope.generateNewMsg(envCode, 'danger', error.message);
                    currentScope.displayAlert('danger', error.message);
                }
                else {
                    params.supportSSL = formData.supportSSL;
                    params.haCount = formData.nginxCount;
                    params.memoryLimit = (formData.nginxMemoryLimit * 1048576);
                    params.imagePrefix = formData.nginxImagePrefix;
                    getSendDataFromServer(currentScope, ngDataApi, {
                        "method": "send",
                        "routeName": "/dashboard/hosts/deployNginx",
                        "data": params
                    }, function(error, response) {
                        if(error) {
                            currentScope.generateNewMsg(envCode, 'danger', error.message);
                            overlay.hide();
                        }
                        else {
                            overlay.hide(function(){
                                if (!haMode) {
                                    currentScope.listNginxHosts(envCode);
                                    currentScope.listHosts(envCode);
                                }
                                else {
                                    currentScope.isDeploying = true;
                                    $timeout(function () {
                                        currentScope.listNginxServices();
                                        currentScope.listServices();
                                    }, 15000);
                                }
                            });
                        }
                    });
                }
            });
        }

        function listStaticContent (currentScope, cb) {
            getSendDataFromServer(currentScope, ngDataApi, {
                'method': 'send',
                'routeName': '/dashboard/staticContent/list'
            }, function (error, response) {
                if (error) {
                    currentScope.$parent.displayAlert('danger', error.code, true, 'dashboard', error.message);
                } else {
                    cb(response);
                }
            });
        }

        function getControllerBranches (currentScope, cb) {
            overlayLoading.show();
            getSendDataFromServer(currentScope, ngDataApi, {
                method: 'get',
                routeName: '/dashboard/gitAccounts/getBranches',
                params: {
                    name: 'controller',
                    type: 'service'
                }
            }, function (error, response) {
                overlayLoading.hide();
                if (error) {
                    currentScope.displayAlert('danger', error.code, true, 'dashboard', error.message);
                }
                else {
                    return cb (response);
                }
            });
        }
    }

    return {
        'deployEnvironment': deployEnvironment
    }
}]);
<commit_msg>minor updates.<commit_after>"use strict";
var deployService = soajsApp.components;
deployService.service('deploySrv', ['ngDataApi', '$timeout', '$modal', function(ngDataApi, $timeout, $modal) {

    function deployEnvironment(currentScope, envCode, haMode) {
        var formConfig = angular.copy(environmentsConfig.form.deploy);
        var kubeConfig = environmentsConfig.deployer.kubernetes;

        currentScope.isKubernetes = (currentScope.deployer.selected.split('.')[1] === "kubernetes");
        if(currentScope.isKubernetes){
            formConfig.entries[0].entries[1].min = kubeConfig.minPort;
            formConfig.entries[0].entries[1].max = kubeConfig.maxPort;
            formConfig.entries[0].entries[1].fieldMsg += ". Kubernetes port range: " + kubeConfig.minPort + " - " + kubeConfig.maxPort;
        }

        getControllerBranches(currentScope, function (branchInfo) {
            for (var i = 0; i < formConfig.entries.length; i++) {
                if (formConfig.entries[i].name === 'controllers') {
                    var ctrlEntries = formConfig.entries[i].entries;
                    for (var j = 0; j < ctrlEntries.length; j++) {
                        if (ctrlEntries[j].name === 'branch') {
                            branchInfo.branches.forEach(function (oneBranch) {
                                delete oneBranch.commit.url;
                                ctrlEntries[j].value.push({'v': oneBranch, 'l': oneBranch.name});
                            });
                        }
                    }
                }
            }

            var customUIEntry = {
                'name': 'useCustomUI',
                'label': 'Do you want to bundle static content?',
                'type': 'radio',
                'value': [{'v': true, 'l': 'Yes'}, {'v': false, 'l': 'No', 'selected': true}],
                'required': true,
                'onAction': function (label, selected, formConfig) {
                    if (selected === 'true' && (!formConfig.entries[0].entries[5] || formConfig.entries[0].entries[5].name !== 'selectCustomUI')) {
                        listStaticContent(currentScope, function (staticContentSources) {
                            var selectCustomUI = {
                                'name': 'selectCustomUI',
                                'label': 'Choose Static Content',
                                'type': 'select',
                                'value': [],
                                'required': true,
                                'onAction': function (label, selected, formConfig) {
                                    var selectUIBranch = {
                                        'name': 'selectUIBranch',
                                        'label': 'Choose Static Content Branch',
                                        'type': 'select',
                                        'value': [],
                                        'required': true
                                    };
                                    selected = JSON.parse(selected);
                                    overlayLoading.show();
                                    getSendDataFromServer(currentScope, ngDataApi, {
                                        method: 'get',
                                        routeName: '/dashboard/gitAccounts/getBranches',
                                        params: {
                                            name: selected.name,
                                            type: 'static'
                                        }
                                    }, function (error, response) {
                                        overlayLoading.hide();
                                        if (error) {
                                            currentScope.generateNewMsg(envCode, 'danger', error.message);
                                        }
                                        else {
                                            response.branches.forEach(function (oneBranch) {
                                                selectUIBranch.value.push({'v': oneBranch, 'l': oneBranch.name});
                                            });

                                            formConfig.entries[0].entries.splice(6, 0, selectUIBranch);
                                        }
                                    });
                                }
                            };
                            staticContentSources.forEach (function (oneSource) {
                                selectCustomUI.value.push ({'v': oneSource, 'l': oneSource.name});
                            });
                            formConfig.entries[0].entries.splice(5, 0, selectCustomUI);
                        });
                    } else if (selected === 'false' && formConfig.entries[0].entries[5].name === 'selectCustomUI') {
                        if (formConfig.entries[0].entries[6] && formConfig.entries[0].entries[6].name === 'selectUIBranch') {
                            formConfig.entries[0].entries.splice(6, 1);
                            delete formConfig.formData.selectUIBranch;
                        }
                        formConfig.entries[0].entries.splice(5, 1);
                        delete formConfig.formData.selectCustomUI;
                    }
                }
            };
            formConfig.entries[0].entries.splice(4, 0, customUIEntry);

            for (var i = 0; i < formConfig.entries[1].entries.length; i++) {
                if (formConfig.entries[1].entries[i].name === 'defaultENVVAR') {
                    formConfig.entries[1].entries[i].value = formConfig.entries[1].entries[i].value.replace("%envName%", envCode);
                    formConfig.entries[1].entries[i].value = formConfig.entries[1].entries[i].value.replace("%profilePathToUse%", currentScope.profile);
                }
            }

            var options = {
                timeout: $timeout,
                form: formConfig,
                name: 'deployEnv',
                label: translation.deployEnvironment[LANG] + ' ' + envCode,
                actions: [
                    {
                        'type': 'submit',
                        'label': translation.submit[LANG],
                        'btn': 'primary',
                        'action': function(formData) {
                            if(!formData.controllers || formData.controllers < 1) {
                                $timeout(function() {
                                    alert(translation.youMustChooseLeastControllerDeployEnvironment[LANG]);
                                }, 100);
                            }
                            else {
                                currentScope.modalInstance.dismiss("ok");
                                var text = "
" + translation.deployingNew[LANG] + envCode + " Environment
";
                                text += "
" +  translation.deploying[LANG] + formData.controllers + translation.newControllersEnvironment[LANG] + envCode + ".
";
                                text += "
" + translation.doNotRefreshThisPageThisWillTakeFewMinutes[LANG] + "
";
                                text += "

";
                                jQuery('#overlay').html("

" + text + "
");
                                jQuery("#overlay .content").css("width", "40%").css("left", "30%");
                                overlay.show();

                                formData.owner = branchInfo.owner;
                                formData.repo = branchInfo.repo;

                                return deployEnvironment(formData);
                            }

                        }
                    },
                    {
                        'type': 'reset',
                        'label': translation.cancel[LANG],
                        'btn': 'danger',
                        'action': function() {
                            currentScope.modalInstance.dismiss('cancel');
                            currentScope.form.formData = {};
                        }
                    }
                ]
            };
            buildFormWithModal(currentScope, $modal, options);
        });

        function deployEnvironment(formData) {
            var branchObj = JSON.parse(formData.branch);
            var params = {
                'envCode': envCode,
                "number": formData.controllers,
                'owner': formData.owner,
                'repo': formData.repo,
                'branch': branchObj.name,
                'commit': branchObj.commit.sha,
                'useLocalSOAJS': formData.useLocalSOAJS,
                'imagePrefix': formData.ctrlImagePrefix
            };

            if(currentScope.isKubernetes) {
                params.isKubernetes = true;
            }

            if (formData.exposedPort) {
                params.exposedPort = formData.exposedPort;
            }

            if (formData.useCustomUI) {
                formData.selectUIBranch = JSON.parse(formData.selectUIBranch);
                formData.selectCustomUI = JSON.parse(formData.selectCustomUI);
                params.nginxConfig = {
                    customUIId: formData.selectCustomUI._id,
                    branch: formData.selectUIBranch.name,
                    commit: formData.selectUIBranch.commit.sha
                };
            }

            if(formData.variables && formData.variables !== ''){
                params.variables = formData.variables.split(",");
                for(var i =0; i < params.variables.length; i++){
                    params.variables[i] = params.variables[i].trim();
                }
            }

            if (haMode) {
                params.name = 'controller';
                params.haService = true;
                params.haCount = formData.controllers;
                params.memoryLimit = (formData.ctrlMemoryLimit * 1048576);
            }

            getSendDataFromServer(currentScope, ngDataApi, {
                "method": "send",
                "routeName": "/dashboard/hosts/deployController",
                "data": params
            }, function(error, response) {
                if(error) {
                    overlay.hide();
                    currentScope.form.displayAlert('danger', error.message);
                    return false;
                }
                else {
                    params.supportSSL = formData.supportSSL;
                    params.haCount = formData.nginxCount;
                    params.memoryLimit = (formData.nginxMemoryLimit * 1048576);
                    params.imagePrefix = formData.nginxImagePrefix;
                    getSendDataFromServer(currentScope, ngDataApi, {
                        "method": "send",
                        "routeName": "/dashboard/hosts/deployNginx",
                        "data": params
                    }, function(error, response) {
                        if(error) {
                            currentScope.form.displayAlert('danger', error.message);
                            overlay.hide();
                            return false;
                        }
                        else {
                            return true;
                            overlay.hide(function(){
                                if (!haMode) {
                                    currentScope.listNginxHosts(envCode);
                                    currentScope.listHosts(envCode);
                                }
                                else {
                                    currentScope.isDeploying = true;
                                    $timeout(function () {
                                        currentScope.listNginxServices();
                                        currentScope.listServices();
                                    }, 15000);
                                }
                            });
                        }
                    });
                }
            });
        }

        function listStaticContent (currentScope, cb) {
            getSendDataFromServer(currentScope, ngDataApi, {
                'method': 'send',
                'routeName': '/dashboard/staticContent/list'
            }, function (error, response) {
                if (error) {
                    currentScope.$parent.displayAlert('danger', error.code, true, 'dashboard', error.message);
                } else {
                    cb(response);
                }
            });
        }

        function getControllerBranches (currentScope, cb) {
            overlayLoading.show();
            getSendDataFromServer(currentScope, ngDataApi, {
                method: 'get',
                routeName: '/dashboard/gitAccounts/getBranches',
                params: {
                    name: 'controller',
                    type: 'service'
                }
            }, function (error, response) {
                overlayLoading.hide();
                if (error) {
                    currentScope.displayAlert('danger', error.code, true, 'dashboard', error.message);
                }
                else {
                    return cb (response);
                }
            });
        }
    }

    return {
        'deployEnvironment': deployEnvironment
    }
}]);
<|endoftext|>


<commit_before>/*global define*/
define([
        '../Core/defined',
        './ImageryState'
    ], function(
        defined,
        ImageryState) {
    'use strict';

    /**
     * The assocation between a terrain tile and an imagery tile.
     *
     * @alias TileImagery
     * @private
     *
     * @param {Imagery} imagery The imagery tile.
     * @param {Cartesian4} textureCoordinateRectangle The texture rectangle of the tile that is covered
     *        by the imagery, where X=west, Y=south, Z=east, W=north.
     * @param {Boolean} useWebMercatorT true to use the Web Mercator texture coordinates for this imagery tile.
     */
    function TileImagery(imagery, textureCoordinateRectangle, useWebMercatorT) {
        this.readyImagery = undefined;
        this.loadingImagery = imagery;
        this.textureCoordinateRectangle = textureCoordinateRectangle;
        this.textureTranslationAndScale = undefined;
        this.useWebMercatorT = useWebMercatorT;
    }

    /**
     * Frees the resources held by this instance.
     */
    TileImagery.prototype.freeResources = function() {
        if (defined(this.readyImagery)) {
            this.readyImagery.releaseReference();
        }

        if (defined(this.loadingImagery)) {
            this.loadingImagery.releaseReference();
        }
    };

    /**
     * Processes the load state machine for this instance.
     *
     * @param {Tile} tile The tile to which this instance belongs.
     * @param {FrameState} frameState The frameState.
     * @returns {Boolean} True if this instance is done loading; otherwise, false.
     */
    TileImagery.prototype.processStateMachine = function(tile, frameState) {
        var loadingImagery = this.loadingImagery;
        var imageryLayer = loadingImagery.imageryLayer;

        loadingImagery.processStateMachine(frameState, !this.useWebMercatorT);

        if (loadingImagery.state === ImageryState.READY) {
            if (defined(this.readyImagery)) {
                this.readyImagery.releaseReference();
            }
            this.readyImagery = this.loadingImagery;
            this.loadingImagery = undefined;
            this.textureTranslationAndScale = imageryLayer._calculateTextureTranslationAndScale(tile, this);
            return true; // done loading
        }

        // Find some ancestor imagery we can use while this imagery is still loading.
        var ancestor = loadingImagery.parent;
        var closestAncestorThatNeedsLoading;
        while (defined(ancestor) && ancestor.state !== ImageryState.READY) {
            if (ancestor.state !== ImageryState.FAILED && ancestor.state !== ImageryState.INVALID) {
                // ancestor is still loading
                closestAncestorThatNeedsLoading = closestAncestorThatNeedsLoading || ancestor;
            }
            ancestor = ancestor.parent;
        }

        if (this.readyImagery !== ancestor) {
            if (defined(this.readyImagery)) {
                this.readyImagery.releaseReference();
            }

            this.readyImagery = ancestor;

            if (defined(ancestor)) {
                ancestor.addReference();
                this.textureTranslationAndScale = imageryLayer._calculateTextureTranslationAndScale(tile, this);
            }
        }

        if (loadingImagery.state === ImageryState.FAILED || loadingImagery.state === ImageryState.INVALID) {
            // The imagery tile is failed or invalid, so we'd like to use an ancestor instead.
            if (defined(closestAncestorThatNeedsLoading)) {
                // Push the ancestor's load process along a bit.  This is necessary because some ancestor imagery
                // tiles may not be attached directly to a terrain tile.  Such tiles will never load if
                // we don't do it here.
                closestAncestorThatNeedsLoading.processStateMachine(frameState, !this.useWebMercatorT);
                return false; // not done loading
            } else {
                // This imagery tile is failed or invalid, and we have the "best available" substitute.
                return true; // done loading
            }
        }

        return false; // not done loading
    };

    return TileImagery;
});
<commit_msg>Don't use an ancestor tile if it needs to be reprojected and hasn't been.<commit_after>/*global define*/
define([
        '../Core/defined',
        './ImageryState'
    ], function(
        defined,
        ImageryState) {
    'use strict';

    /**
     * The assocation between a terrain tile and an imagery tile.
     *
     * @alias TileImagery
     * @private
     *
     * @param {Imagery} imagery The imagery tile.
     * @param {Cartesian4} textureCoordinateRectangle The texture rectangle of the tile that is covered
     *        by the imagery, where X=west, Y=south, Z=east, W=north.
     * @param {Boolean} useWebMercatorT true to use the Web Mercator texture coordinates for this imagery tile.
     */
    function TileImagery(imagery, textureCoordinateRectangle, useWebMercatorT) {
        this.readyImagery = undefined;
        this.loadingImagery = imagery;
        this.textureCoordinateRectangle = textureCoordinateRectangle;
        this.textureTranslationAndScale = undefined;
        this.useWebMercatorT = useWebMercatorT;
    }

    /**
     * Frees the resources held by this instance.
     */
    TileImagery.prototype.freeResources = function() {
        if (defined(this.readyImagery)) {
            this.readyImagery.releaseReference();
        }

        if (defined(this.loadingImagery)) {
            this.loadingImagery.releaseReference();
        }
    };

    /**
     * Processes the load state machine for this instance.
     *
     * @param {Tile} tile The tile to which this instance belongs.
     * @param {FrameState} frameState The frameState.
     * @returns {Boolean} True if this instance is done loading; otherwise, false.
     */
    TileImagery.prototype.processStateMachine = function(tile, frameState) {
        var loadingImagery = this.loadingImagery;
        var imageryLayer = loadingImagery.imageryLayer;

        loadingImagery.processStateMachine(frameState, !this.useWebMercatorT);

        if (loadingImagery.state === ImageryState.READY) {
            if (defined(this.readyImagery)) {
                this.readyImagery.releaseReference();
            }
            this.readyImagery = this.loadingImagery;
            this.loadingImagery = undefined;
            this.textureTranslationAndScale = imageryLayer._calculateTextureTranslationAndScale(tile, this);
            return true; // done loading
        }

        // Find some ancestor imagery we can use while this imagery is still loading.
        var ancestor = loadingImagery.parent;
        var closestAncestorThatNeedsLoading;
        while (defined(ancestor) && (ancestor.state !== ImageryState.READY || (!this.useWebMercatorT && !defined(ancestor.texture)))) {
            if (ancestor.state !== ImageryState.FAILED && ancestor.state !== ImageryState.INVALID) {
                // ancestor is still loading
                closestAncestorThatNeedsLoading = closestAncestorThatNeedsLoading || ancestor;
            }
            ancestor = ancestor.parent;
        }

        if (this.readyImagery !== ancestor) {
            if (defined(this.readyImagery)) {
                this.readyImagery.releaseReference();
            }

            this.readyImagery = ancestor;

            if (defined(ancestor)) {
                ancestor.addReference();
                this.textureTranslationAndScale = imageryLayer._calculateTextureTranslationAndScale(tile, this);
            }
        }

        if (loadingImagery.state === ImageryState.FAILED || loadingImagery.state === ImageryState.INVALID) {
            // The imagery tile is failed or invalid, so we'd like to use an ancestor instead.
            if (defined(closestAncestorThatNeedsLoading)) {
                // Push the ancestor's load process along a bit.  This is necessary because some ancestor imagery
                // tiles may not be attached directly to a terrain tile.  Such tiles will never load if
                // we don't do it here.
                closestAncestorThatNeedsLoading.processStateMachine(frameState, !this.useWebMercatorT);
                return false; // not done loading
            } else {
                // This imagery tile is failed or invalid, and we have the "best available" substitute.
                return true; // done loading
            }
        }

        return false; // not done loading
    };

    return TileImagery;
});
<|endoftext|>


<commit_before>

var tables;
$(document).ready(function() {
    tables = $('.table-datatable')
    if(!tables) {
        return;
    }
    options = {
        //stateSave: true,
        "pagingType": "full_numbers",
    };
    sortingCol = tables.data('datatable-sorting-col');
    if (sortingCol != '')
    {
        options.order = [ sortingCol, 'asc' ];
    }

    tables.DataTable(options);
    //new $.fn.dataTable.FixedHeader( tables );
    //new $.fn.dataTable.KeyTable( tables );
});
<commit_msg>* fix '' vs undefined, which lead to non working datatable<commit_after>

var tables;
$(document).ready(function() {
    tables = $('.table-datatable')
    if(!tables) {
        return;
    }
    options = {
        //stateSave: true,
        "pagingType": "full_numbers",
    };
    sortingCol = tables.data('datatable-sorting-col');
    if (sortingCol != undefined)
    {
        options.order = [ sortingCol, 'asc' ];
    }

    tables.DataTable(options);
    //new $.fn.dataTable.FixedHeader( tables );
    //new $.fn.dataTable.KeyTable( tables );
});
<|endoftext|>


<commit_before>function convertObjectToArray(obj) {
  var outputArray = [];

  Object.keys(obj).forEach(function (key) {
    var keyAsIndex = Number(key);
    if (!isNaN(keyAsIndex) && keyAsIndex > -1) {
      outputArray[keyAsIndex] = obj[key];
    } else {
      // attach it as a property
      outputArray[key] = obj[key];
    }
  });

  return outputArray;
}

function isComparingObjectAndArray(lhs, rhs) {
  var typeLhs = lhs && typeof lhs;
  var typeRhs = rhs && typeof rhs;

  return ((Array.isArray(lhs) && isObject(rhs)) ||
          (Array.isArray(rhs) && isObject(lhs)));
}

function isDate(x) {
  if (!x) {
    return false;
  }

  return Object.prototype.toString.call(x) === '[object Date]';
}

function isObject(x) {
  return typeof x === 'object';
}

function isRegExp(x) {
  return x instanceof RegExp;
}

function isString(x) {
  return typeof x === 'string';
}

function assertTheUnexpected(expect) {
  function AssertionError(err, assertMessage) {
    Error.call(this, '');

    this.name = 'AssertionError';

    if (assertMessage) {
      assertMessage = this.name + ': ' + assertMessage;
    }

    this.stack = (assertMessage ? assertMessage + '\n\n' : '') + err.stack;
    this.message = (assertMessage || '');
  }

  AssertionError.prototype = Object.create(Error.prototype);

  function createWrappedExpect(localExpect) {
    return function wrappedExpect() {
      var args = Array.prototype.slice.apply(arguments);
      // convert UnexpectedError to AssertionError
      try {
        localExpect.apply(localExpect, args);
      } catch (err) {
        throw new AssertionError(err);
      }
    };
  }

  var wrappedExpect = createWrappedExpect(expect);

  function checkTruthy(value) {
    wrappedExpect(value, 'to be truthy');
  }

  function prepareDeepEqual(actual, expected) {
    var a = actual;
    var b = expected;

    if (Array.isArray(a) && Array.isArray(b)) {
      a = a.slice(0);
      b = b.slice(0);

      for (var i = 0; i < a.length; i += 1) {
        var comparisonValues = prepareEqual(a[i], b[i]);
        a[i] = comparisonValues.a;
        b[i] = comparisonValues.b;
      }

      return {
        a: a,
        b: b
      };
    } else if (
        (isObject(a) && isObject(b)) &&
        !(isDate(a) && isDate(b)) &&
        !(isRegExp(a) && isRegExp(b)) &&
        !(a === null || b === null)
    ) {
      return {
        a: Object.assign({}, a),
        b: Object.assign({}, b)
      }
    } else if (isComparingObjectAndArray(a, b)) {
      if (Array.isArray(a)) {
        return {
          a: a,
          b: convertObjectToArray(b)
        };
      } else {
        return {
          a: convertObjectToArray(a),
          b: b
        };
      }
    }

    return null;
  }

  function prepareEqual(actual, expected) {
    var a = !actual;
    var b = !expected;

    // undo the null and undefined evaluate equal
    if (!(a && b) && !(typeof actual === 'boolean' || typeof expected === 'boolean')) {
      a = actual;
      b = expected;
    }

    if ((Number(a) || Number(b)) && (isString(a) || isString(b))) {
      a = String(a);
      b = String(b);
    }

    return {
      a: a,
      b: b
    };
  }

  return Object.assign(function (value) {
    checkTruthy(value);
  }, {
    AssertionError: AssertionError,
    deepEqual: function deepEqual(actual, expected) {
      var a = actual;
      var b = expected;
      var comparisonValues;

      // first type deep equal preparation
      comparisonValues = prepareDeepEqual(a, b);

      if (!comparisonValues && !(isObject(a) || isObject(b))) {
        comparisonValues = prepareEqual(a, b);
      }

      if (comparisonValues) {
        a = comparisonValues.a;
        b = comparisonValues.b;
      }

      wrappedExpect(a, 'to equal', b);

      // handle the lastIndex property
      if (actual instanceof RegExp && actual.hasOwnProperty('lastIndex')) {
        wrappedExpect(actual.lastIndex, 'to equal', expected.lastIndex);
      }
    },
    deepStrictEqual: function deepStrictEqual(actual, expected) {
      wrappedExpect(actual, 'to equal', expected);
    },
    equal: function equal(actual, expected) {
      var comarisonValues = prepareEqual(actual, expected);
      var a = comarisonValues.a;
      var b = comarisonValues.b;

      wrappedExpect(a, 'to be', b);
    },
    ifError: function ifError(value) {
      wrappedExpect(value, 'to be falsy').then(function () {
        throw value;
      });
    },
    notEqual: function notEqual(actual, expected) {
      wrappedExpect(actual, 'not to be', expected);
    },
    notDeepEqual: function notDeepEqual(actual, expected) {
      wrappedExpect(actual, 'not to equal', expected);
    },
    notDeepStrictEqual: function notDeepStrictEqual(actual, expected) {
      wrappedExpect(actual, 'not to equal', expected);
    },
    notStrictEqual: function notStrictEqual(actual, expected) {
      wrappedExpect(actual, 'not to equal', expected);
    },
    ok: function (value) {
      checkTruthy(value);
    },
    strictEqual: function strictEqual(actual, expected) {
      wrappedExpect(actual, 'to equal', expected);
    },
  });
}

module.exports = assertTheUnexpected(require('unexpected'));
<commit_msg>Include the lastIndex comparison in deepStrictEqual().<commit_after>function convertObjectToArray(obj) {
  var outputArray = [];

  Object.keys(obj).forEach(function (key) {
    var keyAsIndex = Number(key);
    if (!isNaN(keyAsIndex) && keyAsIndex > -1) {
      outputArray[keyAsIndex] = obj[key];
    } else {
      // attach it as a property
      outputArray[key] = obj[key];
    }
  });

  return outputArray;
}

function isComparingObjectAndArray(lhs, rhs) {
  var typeLhs = lhs && typeof lhs;
  var typeRhs = rhs && typeof rhs;

  return ((Array.isArray(lhs) && isObject(rhs)) ||
          (Array.isArray(rhs) && isObject(lhs)));
}

function isDate(x) {
  if (!x) {
    return false;
  }

  return Object.prototype.toString.call(x) === '[object Date]';
}

function isObject(x) {
  return typeof x === 'object';
}

function isRegExp(x) {
  return x instanceof RegExp;
}

function isString(x) {
  return typeof x === 'string';
}

function assertTheUnexpected(expect) {
  function AssertionError(err, assertMessage) {
    Error.call(this, '');

    this.name = 'AssertionError';

    if (assertMessage) {
      assertMessage = this.name + ': ' + assertMessage;
    }

    this.stack = (assertMessage ? assertMessage + '\n\n' : '') + err.stack;
    this.message = (assertMessage || '');
  }

  AssertionError.prototype = Object.create(Error.prototype);

  function createWrappedExpect(localExpect) {
    return function wrappedExpect() {
      var args = Array.prototype.slice.apply(arguments);
      // convert UnexpectedError to AssertionError
      try {
        localExpect.apply(localExpect, args);
      } catch (err) {
        throw new AssertionError(err);
      }
    };
  }

  var wrappedExpect = createWrappedExpect(expect);

  function checkTruthy(value) {
    wrappedExpect(value, 'to be truthy');
  }

  function prepareDeepEqual(actual, expected) {
    var a = actual;
    var b = expected;

    if (Array.isArray(a) && Array.isArray(b)) {
      a = a.slice(0);
      b = b.slice(0);

      for (var i = 0; i < a.length; i += 1) {
        var comparisonValues = prepareEqual(a[i], b[i]);
        a[i] = comparisonValues.a;
        b[i] = comparisonValues.b;
      }

      return {
        a: a,
        b: b
      };
    } else if (
        (isObject(a) && isObject(b)) &&
        !(isDate(a) && isDate(b)) &&
        !(isRegExp(a) && isRegExp(b)) &&
        !(a === null || b === null)
    ) {
      return {
        a: Object.assign({}, a),
        b: Object.assign({}, b)
      }
    } else if (isComparingObjectAndArray(a, b)) {
      if (Array.isArray(a)) {
        return {
          a: a,
          b: convertObjectToArray(b)
        };
      } else {
        return {
          a: convertObjectToArray(a),
          b: b
        };
      }
    }

    return null;
  }

  function prepareEqual(actual, expected) {
    var a = !actual;
    var b = !expected;

    // undo the null and undefined evaluate equal
    if (!(a && b) && !(typeof actual === 'boolean' || typeof expected === 'boolean')) {
      a = actual;
      b = expected;
    }

    if ((Number(a) || Number(b)) && (isString(a) || isString(b))) {
      a = String(a);
      b = String(b);
    }

    return {
      a: a,
      b: b
    };
  }

  return Object.assign(function (value) {
    checkTruthy(value);
  }, {
    AssertionError: AssertionError,
    deepEqual: function deepEqual(actual, expected) {
      var a = actual;
      var b = expected;
      var comparisonValues;

      // first type deep equal preparation
      comparisonValues = prepareDeepEqual(a, b);

      if (!comparisonValues && !(isObject(a) || isObject(b))) {
        comparisonValues = prepareEqual(a, b);
      }

      if (comparisonValues) {
        a = comparisonValues.a;
        b = comparisonValues.b;
      }

      wrappedExpect(a, 'to equal', b);

      // handle the lastIndex property
      if (actual instanceof RegExp && actual.hasOwnProperty('lastIndex')) {
        wrappedExpect(actual.lastIndex, 'to equal', expected.lastIndex);
      }
    },
    deepStrictEqual: function deepStrictEqual(actual, expected) {
      wrappedExpect(actual, 'to equal', expected);

      // handle the lastIndex property
      if (actual instanceof RegExp && actual.hasOwnProperty('lastIndex')) {
        wrappedExpect(actual.lastIndex, 'to equal', expected.lastIndex);
      }
    },
    equal: function equal(actual, expected) {
      var comarisonValues = prepareEqual(actual, expected);
      var a = comarisonValues.a;
      var b = comarisonValues.b;

      wrappedExpect(a, 'to be', b);
    },
    ifError: function ifError(value) {
      wrappedExpect(value, 'to be falsy').then(function () {
        throw value;
      });
    },
    notEqual: function notEqual(actual, expected) {
      wrappedExpect(actual, 'not to be', expected);
    },
    notDeepEqual: function notDeepEqual(actual, expected) {
      wrappedExpect(actual, 'not to equal', expected);
    },
    notDeepStrictEqual: function notDeepStrictEqual(actual, expected) {
      wrappedExpect(actual, 'not to equal', expected);
    },
    notStrictEqual: function notStrictEqual(actual, expected) {
      wrappedExpect(actual, 'not to equal', expected);
    },
    ok: function (value) {
      checkTruthy(value);
    },
    strictEqual: function strictEqual(actual, expected) {
      wrappedExpect(actual, 'to equal', expected);
    },
  });
}

module.exports = assertTheUnexpected(require('unexpected'));
<|endoftext|>


<commit_before>'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(<%= configFile %>)[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) !== '.js');
  })
  .forEach(function(file) {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
<commit_msg>[Fixed] Filtering of js files in models/index.js<commit_after>'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(<%= configFile %>)[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(function(file) {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
<|endoftext|>


<commit_before>const NodeInterface = Jymfony.Component.Config.Definition.NodeInterface;
const ForbiddenOverwriteException = Jymfony.Component.Config.Definition.Exception.ForbiddenOverwriteException;

/**
 * The base node class.
 *
 * @memberOf Jymfony.Component.Config.Definition
 * @abstract
 */
class BaseNode extends implementationOf(NodeInterface) {
    /**
     * @throws \InvalidArgumentException if the name contains a period
     */
    __construct(name, parent = undefined) {
        if (-1 !== name.indexOf('.')) {
            throw new InvalidArgumentException('The name must not contain ".".');
        }

        /**
         * @type {string}
         * @protected
         */
        this._name = name;

        /**
         * @type {Jymfony.Component.Config.Definition.NodeInterface}
         * @protected
         */
        this._parent = parent;
        this._normalizationClosures = [];
        this._finalValidationClosures = [];
        this._allowOverwrite = true;
        this._required = false;
        this._deprecationMessage = undefined;
        this._equivalentValues = [];
        this._attributes = {};
    }

    setAttribute(key, value) {
        this._attributes[key] = value;
    }

    getAttribute(key, defaultValue = undefined) {
        return this._attributes[key] || defaultValue;
    }

    hasAttribute(key) {
        return undefined !== this._attributes[key];
    }

    getAttributes() {
        return this._attributes;
    }

    setAttributes(_attributes) {
        this._attributes = _attributes;
    }

    removeAttribute(key) {
        delete this._attributes[key];
    }

    /**
     * Sets an info message.
     *
     * @param {string} info
     */
    setInfo(info) {
        this.setAttribute('info', info);
    }

    /**
     * Returns info message.
     *
     * @returns {string} The info text
     */
    getInfo() {
        return this.getAttribute('info');
    }

    /**
     * Sets the example configuration for this node.
     *
     * @param {string|[string]} example
     */
    setExample(example) {
        this.setAttribute('example', example);
    }

    /**
     * Retrieves the example configuration for this node.
     *
     * @returns {string|[string]} The example
     */
    getExample() {
        return this.getAttribute('example');
    }

    /**
     * Adds an equivalent value.
     *
     * @param {*} originalValue
     * @param {*} equivalentValue
     */
    addEquivalentValue(originalValue, equivalentValue) {
        this._equivalentValues.push([ originalValue, equivalentValue ]);
    }

    /**
     * Set this node as _required.
     *
     * @param {boolean} bool Required node
     */
    setRequired(bool) {
        this._required = !! bool;
    }

    /**
     * Sets this node as deprecated.
     *
     * You can use %node% and %path% placeholders in your message to display,
     * respectively, the node name and its complete path.
     *
     * @param {string|undefined} message Deprecated message
     */
    setDeprecated(message) {
        this._deprecationMessage = message;
    }

    /**
     * Sets if this node can be overridden.
     *
     * @param {boolean} allow
     */
    setAllowOverwrite(allow) {
        this._allowOverwrite = !! allow;
    }

    /**
     * Sets the closures used for normalization.
     *
     * @param {[Function]} closures An array of Closures used for normalization
     */
    setNormalizationClosures(closures) {
        this._normalizationClosures = closures;
    }

    /**
     * Sets the closures used for final validation.
     *
     * @param {[Function]} closures An array of Closures used for final validation
     */
    setFinalValidationClosures(closures) {
        this._finalValidationClosures = closures;
    }

    /**
     * Checks if this node is _required.
     *
     * @returns {boolean}
     */
    isRequired() {
        return this._required;
    }

    /**
     * Checks if this node is deprecated.
     *
     * @returns {boolean}
     */
    isDeprecated() {
        return undefined !== this._deprecationMessage;
    }

    /**
     * Returns the deprecated message.
     *
     * @param {string} node the configuration node name
     * @param {string} path the path of the node
     *
     * @returns {string}
     */
    getDeprecationMessage(node, path) {
        return __jymfony.strtr(this._deprecationMessage, {'%node%': node, '%path%': path});
    }

    /**
     * Returns the name of this node.
     *
     * @returns {string} The Node's name
     */
    getName() {
        return this._name;
    }

    /**
     * Retrieves the path of this node.
     *
     * @returns {string} The Node's path
     */
    getPath() {
        let path = this._name;

        if (undefined !== this._parent) {
            path = this._parent.getPath() + '.' + path;
        }

        return path;
    }

    /**
     * Merges two values together.
     *
     * @param {*} leftSide
     * @param {*} rightSide
     *
     * @returns {*} The merged value
     *
     * @throws {Jymfony.Component.Config.Definition.Exception.ForbiddenOverwriteException}
     *
     * @final
     */
    merge(leftSide, rightSide) {
        if (! this._allowOverwrite) {
            throw new ForbiddenOverwriteException(__jymfony.sprintf(
                'Configuration path "%s" cannot be overwritten. You have to ' +
                'define all options for this path, and any of its sub-paths in ' +
                'one configuration section.',
                this.getPath()
            ));
        }

        this.validateType(leftSide);
        this.validateType(rightSide);

        return this.mergeValues(leftSide, rightSide);
    }

    /**
     * Normalizes a value, applying all normalization closures.
     *
     * @param {*} value Value to normalize
     *
     * @returns {*} The normalized value
     */
    normalize(value) {
        value = this._preNormalize(value);

        // Run custom normalization closures
        for (const closure of this._normalizationClosures) {
            value = closure(value);
        }

        // Replace value with their equivalent
        for (const data of this._equivalentValues) {
            if (data[0] === value) {
                value = data[1];
            }
        }

        // Validate type
        this.validateType(value);

        // Normalize value
        return this.normalizeValue(value);
    }

    /**
     * Normalizes the value before any other normalization is applied.
     *
     * @param {*} value
     *
     * @returns {*} The normalized array value
     */
    _preNormalize(value) {
        return value;
    }

    /**
     * Returns parent node for this node.
     *
     * @returns {Jymfony.Component.Config.Definition.NodeInterface|undefined}
     */
    getParent() {
        return this._parent;
    }

    /**
     * Finalizes a value, applying all finalization closures.
     *
     * @param {*} value The value to finalize
     *
     * @returns {*} The finalized value
     *
     * @throws {Exception}
     * @throws {Jymfony.Component.Config.Definition.Exception.InvalidConfigurationException}
     *
     * @final
     */
    finalize(value) {
        this.validateType(value);

        value = this.finalizeValue(value);

        // Perform validation on the final value if a closure has been set.
        // The closure is also allowed to return another value.
        for (const closure of this._finalValidationClosures) {
            try {
                value = closure(value);
            } catch (e) {
                throw e;
                // Throw new InvalidConfigurationException(sprintf('Invalid configuration for path "%s": %s', this.getPath(), $e->getMessage()), $e->getCode(), $e);
            }
        }

        return value;
    }

    /**
     * Validates the type of a Node.
     *
     * @param {*} value The value to validate
     *
     * @throws {Jymfony.Component.Config.Definition.Exception.InvalidTypeException} when the value is invalid
     * @abstract
     */
    validateType(value) { // eslint-disable-line no-unused-vars
        throw new Error('validateType must be implemented');
    }

    /**
     * Normalizes the value.
     *
     * @param {*} value The value to normalize
     *
     * @return mixed The normalized value
     * @abstract
     */
    normalizeValue(value) { // eslint-disable-line no-unused-vars
        throw new Error('normalizeValue must be implemented');
    }

    /**
     * Merges two values together.
     *
     * @param {*} leftSide
     * @param {*} rightSide
     *
     * @returns {*} The merged value
     * @abstract
     */
    mergeValues(leftSide, rightSide) { // eslint-disable-line no-unused-vars
        throw new Error('mergeValues must be implemented');
    }

    /**
     * Finalizes a value.
     *
     * @param {*} value The value to finalize
     *
     * @returns {*} The finalized value
     * @abstract
     */
    finalizeValue(value) { // eslint-disable-line no-unused-vars
        throw new Error('finalizeValue must be implemented');
    }
}

module.exports = BaseNode;
<commit_msg>fix cs<commit_after>const NodeInterface = Jymfony.Component.Config.Definition.NodeInterface;
const ForbiddenOverwriteException = Jymfony.Component.Config.Definition.Exception.ForbiddenOverwriteException;

/**
 * The base node class.
 *
 * @memberOf Jymfony.Component.Config.Definition
 * @abstract
 */
class BaseNode extends implementationOf(NodeInterface) {
    /**
     * @throws \InvalidArgumentException if the name contains a period
     */
    __construct(name, parent = undefined) {
        if (-1 !== name.indexOf('.')) {
            throw new InvalidArgumentException('The name must not contain ".".');
        }

        /**
         * @type {string}
         * @protected
         */
        this._name = name;

        /**
         * @type {Jymfony.Component.Config.Definition.NodeInterface}
         * @protected
         */
        this._parent = parent;
        this._normalizationClosures = [];
        this._finalValidationClosures = [];
        this._allowOverwrite = true;
        this._required = false;
        this._deprecationMessage = undefined;
        this._equivalentValues = [];
        this._attributes = {};
    }

    setAttribute(key, value) {
        this._attributes[key] = value;
    }

    getAttribute(key, defaultValue = undefined) {
        return this._attributes[key] || defaultValue;
    }

    hasAttribute(key) {
        return undefined !== this._attributes[key];
    }

    getAttributes() {
        return this._attributes;
    }

    setAttributes(_attributes) {
        this._attributes = _attributes;
    }

    removeAttribute(key) {
        delete this._attributes[key];
    }

    /**
     * Sets an info message.
     *
     * @param {string} info
     */
    setInfo(info) {
        this.setAttribute('info', info);
    }

    /**
     * Returns info message.
     *
     * @returns {string} The info text
     */
    getInfo() {
        return this.getAttribute('info');
    }

    /**
     * Sets the example configuration for this node.
     *
     * @param {string|[string]} example
     */
    setExample(example) {
        this.setAttribute('example', example);
    }

    /**
     * Retrieves the example configuration for this node.
     *
     * @returns {string|[string]} The example
     */
    getExample() {
        return this.getAttribute('example');
    }

    /**
     * Adds an equivalent value.
     *
     * @param {*} originalValue
     * @param {*} equivalentValue
     */
    addEquivalentValue(originalValue, equivalentValue) {
        this._equivalentValues.push([ originalValue, equivalentValue ]);
    }

    /**
     * Set this node as _required.
     *
     * @param {boolean} bool Required node
     */
    setRequired(bool) {
        this._required = !! bool;
    }

    /**
     * Sets this node as deprecated.
     *
     * You can use %node% and %path% placeholders in your message to display,
     * respectively, the node name and its complete path.
     *
     * @param {string|undefined} message Deprecated message
     */
    setDeprecated(message) {
        this._deprecationMessage = message;
    }

    /**
     * Sets if this node can be overridden.
     *
     * @param {boolean} allow
     */
    setAllowOverwrite(allow) {
        this._allowOverwrite = !! allow;
    }

    /**
     * Sets the closures used for normalization.
     *
     * @param {[Function]} closures An array of Closures used for normalization
     */
    setNormalizationClosures(closures) {
        this._normalizationClosures = closures;
    }

    /**
     * Sets the closures used for final validation.
     *
     * @param {[Function]} closures An array of Closures used for final validation
     */
    setFinalValidationClosures(closures) {
        this._finalValidationClosures = closures;
    }

    /**
     * Checks if this node is _required.
     *
     * @returns {boolean}
     */
    isRequired() {
        return this._required;
    }

    /**
     * Checks if this node is deprecated.
     *
     * @returns {boolean}
     */
    isDeprecated() {
        return undefined !== this._deprecationMessage;
    }

    /**
     * Returns the deprecated message.
     *
     * @param {string} node the configuration node name
     * @param {string} path the path of the node
     *
     * @returns {string}
     */
    getDeprecationMessage(node, path) {
        return __jymfony.strtr(this._deprecationMessage, {'%node%': node, '%path%': path});
    }

    /**
     * Returns the name of this node.
     *
     * @returns {string} The Node's name
     */
    getName() {
        return this._name;
    }

    /**
     * Retrieves the path of this node.
     *
     * @returns {string} The Node's path
     */
    getPath() {
        let path = this._name;

        if (undefined !== this._parent) {
            path = this._parent.getPath() + '.' + path;
        }

        return path;
    }

    /**
     * Merges two values together.
     *
     * @param {*} leftSide
     * @param {*} rightSide
     *
     * @returns {*} The merged value
     *
     * @throws {Jymfony.Component.Config.Definition.Exception.ForbiddenOverwriteException}
     *
     * @final
     */
    merge(leftSide, rightSide) {
        if (! this._allowOverwrite) {
            throw new ForbiddenOverwriteException(__jymfony.sprintf(
                'Configuration path "%s" cannot be overwritten. You have to ' +
                'define all options for this path, and any of its sub-paths in ' +
                'one configuration section.',
                this.getPath()
            ));
        }

        this.validateType(leftSide);
        this.validateType(rightSide);

        return this.mergeValues(leftSide, rightSide);
    }

    /**
     * Normalizes a value, applying all normalization closures.
     *
     * @param {*} value Value to normalize
     *
     * @returns {*} The normalized value
     */
    normalize(value) {
        value = this._preNormalize(value);

        // Run custom normalization closures
        for (const closure of this._normalizationClosures) {
            value = closure(value);
        }

        // Replace value with their equivalent
        for (const data of this._equivalentValues) {
            if (data[0] === value) {
                value = data[1];
            }
        }

        // Validate type
        this.validateType(value);

        // Normalize value
        return this.normalizeValue(value);
    }

    /**
     * Normalizes the value before any other normalization is applied.
     *
     * @param {*} value
     *
     * @returns {*} The normalized array value
     */
    _preNormalize(value) {
        return value;
    }

    /**
     * Returns parent node for this node.
     *
     * @returns {Jymfony.Component.Config.Definition.NodeInterface|undefined}
     */
    getParent() {
        return this._parent;
    }

    /**
     * Finalizes a value, applying all finalization closures.
     *
     * @param {*} value The value to finalize
     *
     * @returns {*} The finalized value
     *
     * @throws {Exception}
     * @throws {Jymfony.Component.Config.Definition.Exception.InvalidConfigurationException}
     *
     * @final
     */
    finalize(value) {
        this.validateType(value);

        value = this.finalizeValue(value);

        // Perform validation on the final value if a closure has been set.
        // The closure is also allowed to return another value.
        for (const closure of this._finalValidationClosures) {
            try {
                value = closure(value);
            } catch (e) {
                throw e;
                // Throw new InvalidConfigurationException(sprintf('Invalid configuration for path "%s": %s', this.getPath(), $e->getMessage()), $e->getCode(), $e);
            }
        }

        return value;
    }

    /**
     * Validates the type of a Node.
     *
     * @param {*} value The value to validate
     *
     * @throws {Jymfony.Component.Config.Definition.Exception.InvalidTypeException} when the value is invalid
     * @abstract
     */
    validateType(value) { // eslint-disable-line no-unused-vars
        throw new Error('validateType must be implemented');
    }

    /**
     * Normalizes the value.
     *
     * @param {*} value The value to normalize
     *
     * @return mixed The normalized value
     * @abstract
     */
    normalizeValue(value) { // eslint-disable-line no-unused-vars
        throw new Error('normalizeValue must be implemented');
    }

    /**
     * Merges two values together.
     *
     * @param {*} leftSide
     * @param {*} rightSide
     *
     * @returns {*} The merged value
     * @abstract
     */
    mergeValues(leftSide, rightSide) { // eslint-disable-line no-unused-vars
        throw new Error('mergeValues must be implemented');
    }

    /**
     * Finalizes a value.
     *
     * @param {*} value The value to finalize
     *
     * @returns {*} The finalized value
     * @abstract
     */
    finalizeValue(value) { // eslint-disable-line no-unused-vars
        throw new Error('finalizeValue must be implemented');
    }
}

module.exports = BaseNode;
<|endoftext|>


<commit_before>'use strict';

var utils = require('utils');

module.exports = {
  className: 'pv-illust',
  template: require('./template.html'),
  data: {
    done: false,
    fail: false
  },
  computed: {
    src: function src() {
      var illust = this.pix.illust;

      return illust.prefix + illust.suffix + illust.cache;
    },
    filename: function filename() {
      var pix = this.pix;

      return utils.format(
        '%s - %s%s',
        pix.author.name,
        pix.desc.title,
        pix.illust.suffix
      );
    }
  },
  methods: {
    load: function load() {
      this.done = true;
      this.fail = false;
    },
    error: function error() {
      var illust = this.pix.illust;
      var suffix = illust.suffix;

      if (suffix === '_p0.jpg') {
        illust.suffix = '_p0.png';
        return;
      } else if (suffix === '_p0.png') {
        illust.suffix = '_p0.gif';
        return;
      }
      this.done = false;
      this.fail = true;
    }
  },
  created: function created() {
    var scroll = new utils.Scroll({
      el: this.$el,
      easing: 'linear',
      duration: 200
    });

    this.$on('app:move', function(step) {
      this.$root.$emit('app:skip', step);
    });

    this.$on('img:download', function() {
      utils.download(this.src, this.filename);
    });

    this.$on('img:scroll', function(value) {
      scroll.by(value);
    });
  }
};
<commit_msg>fix(illust): モデルの書式変更に追従<commit_after>'use strict';

var utils = require('utils');

module.exports = {
  className: 'pv-illust',
  template: require('./template.html'),
  data: {
    done: false,
    fail: false
  },
  computed: {
    src: function src() {
      return this.pix.illust.path;
    },
    filename: function filename() {
      var pix = this.pix;

      return utils.format(
        '%s - %s%s',
        pix.author.name,
        pix.desc.title,
        pix.illust.path.slice(pix.illust.path.lastIndexOf('.'))
      );
    }
  },
  methods: {
    load: function load() {
      this.done = true;
      this.fail = false;
    },
    error: function error() {
      var illust = this.pix.illust;

      if (/_p0\.jpg/.test(illust.path)) {
        illust.path = illust.path.replace(/jpg$/, 'png');
        return;
      } else if (/_p0\.png/.test(illust.path)) {
        illust.path = illust.path.replace(/png$/, 'gif');
        return;
      }

      this.done = false;
      this.fail = true;
    }
  },
  created: function created() {
    var scroll = new utils.Scroll({
      el: this.$el,
      easing: 'linear',
      duration: 200
    });

    this.$on('app:move', function(step) {
      this.$root.$emit('app:skip', step);
    });

    this.$on('img:download', function() {
      utils.download(this.src, this.filename);
    });

    this.$on('img:scroll', function(value) {
      scroll.by(value);
    });
  }
};
<|endoftext|>


<commit_before>
/*
 * Takes a filename, mimetype, and string content and initiates a file download
 * of the content from the current page, without leaving the page.
 */

import { saveAs } from 'file-saver';

var downloadStringAsFile = function( filename, mimetype, content ) {

	try {

		console.log( "downloadStringAsFile_OnlyJS called." );

		var blob = new Blob([content], {type: "text/plain;charset=utf-8"});

		saveAs(blob, filename);

	} catch( e ) {
		reportWebErrorToServer.reportErrorObjectToServer( { errorException : e } );
		throw e;
	}
};

export { downloadStringAsFile }
<commit_msg>Change text downloads from UTF-8 to ISO-8859-1 (ascii).<commit_after>
/*
 * Takes a filename, mimetype, and string content and initiates a file download
 * of the content from the current page, without leaving the page.
 */

import { saveAs } from 'file-saver';

var downloadStringAsFile = function( filename, mimetype, content ) {

	try {

		console.log( "downloadStringAsFile_OnlyJS called." );

		var blob = new Blob([content], {type: "text/plain;charset=ISO-8859-1"});

		saveAs(blob, filename);

	} catch( e ) {
		reportWebErrorToServer.reportErrorObjectToServer( { errorException : e } );
		throw e;
	}
};

export { downloadStringAsFile }
<|endoftext|>