<commit_before>//# require=d3

var margin = { top: 20, right: 30, bottom: 60, left: 80 };

d3.select(root)
  .append('div')
    .attr('class', 'background-image');

d3.select('.background-image')
  .append('img')
    .attr('src', baseUrl + '/man_left.png')
    .attr('class', 'man');

d3.select('.background-image')
  .append('img')
    .attr('src', baseUrl + '/table.png')
    .attr('class', 'table');

d3.select('.background-image')
  .append('img')
    .attr('src', baseUrl + '/man_right.png')
    .attr('class', 'man');

var chart = d3.select(root)
  .append('div')
    .attr('class', 'svg-area')
  .append('svg')
    .attr('width', root.clientWidth)
    .attr('height', root.clientHeight)
    .append('g')
    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

var xs = [],
    x,
    start = -100,
    end = 101,
    len = end - start - 1,
    ys = [],
    xys = [],
    f,
    y,
    width = 600,
    height = 300,
    padding = 20,
    svg,
    xscale,
    yaxis,
    yscale,
    yaxis;

function update(data) {
    // 要素を更新するまえにグラフを削除する
    chart.selectAll("g").remove();
    chart.selectAll("text").remove();
    chart.selectAll("line").remove();

    console.log(data.toList());
    var list = data.toList();

    var a = list[0]['a'];
    var b = list[0]['b'];
    var c = list[0]['c'];

    f = function (x, a, b, c) {
        return - a * Math.pow(x, 2) + b * x + c;
    };

    for (x = start; x < end; x += 1) {
        y = f(x, a, b, c);
        xs.push(x);
        ys.push(y);
        xys.push([x, y]);
    }

    xscale = d3.scale.linear()
        .domain([start, end])
        .range([padding, width - padding]);

    xaxis = d3.svg.axis()
        .scale(xscale)
        .orient('bottom');

    yscale = d3.scale.linear()
        .domain([d3.min(ys) - 1000, d3.max(ys)])
        .range([height - padding, padding]);

    yaxis = d3.svg.axis()
        .scale(yscale)
        .orient('left')

    chart.selectAll('line')
        .data(xys)
        .enter()
        .append('line')
        .attr('x1', function (d, i) {
            if (i === len) {
                return xscale(start);
            }
            return xscale(d[0]);
        })
        .attr('y1', function (d, i) {
            if (i === len) {
                return yscale(0);
            }
            return yscale(d[1]);
        })
        .attr('x2', function (d, i) {
            if (i === len) {
                return xscale(end);
            }
            return xscale(xys[i+1][0]);
        })
        .attr('y2', function (d, i) {
            if (i === len) {
                return yscale(0);
            }
            return yscale(xys[i+1][1]);
        })
        .attr('stroke', function (d, i) {
            if (i === len) {
                return 'blue';
            }
            return 'green';
        });

    chart.append('g')
        .attr('transform', 'translate(0, ' + (height - padding) + ')')
        .call(xaxis);

    chart.append('g')
        .attr('transform', 'translate(' + padding + ', 0)')
        .call(yaxis);

    chart.append('text')
        .attr('x', xscale(0))
        .attr('y', padding / 2)
        .attr('text-anchor', 'middle')
        .text('y = - ' + a + ' * x^2 + ' + b + '* x + ' + c);

    chart.append('text')
        .attr('x', xscale(0))
        .attr('y', height - padding / 4)
        .attr('text-anchor', 'middle')
        .text('x');

    chart.append('text')
        .attr('x', padding / 5)
        .attr('y', (height - padding) / 2 )
        .attr('text-anchor', 'middle')
        .text('y');

    // ボールの描画
    chart.append("circle")
        .attr("cx", 300)
        .attr("cy", 20)
        .attr("r", 10)
        .attr("fill","orange");
}

<commit_msg>remove x & y label<commit_after>//# require=d3

var margin = { top: 20, right: 30, bottom: 60, left: 80 };

d3.select(root)
  .append('div')
    .attr('class', 'background-image');

d3.select('.background-image')
  .append('img')
    .attr('src', baseUrl + '/man_left.png')
    .attr('class', 'man');

d3.select('.background-image')
  .append('img')
    .attr('src', baseUrl + '/table.png')
    .attr('class', 'table');

d3.select('.background-image')
  .append('img')
    .attr('src', baseUrl + '/man_right.png')
    .attr('class', 'man');

var chart = d3.select(root)
  .append('div')
    .attr('class', 'svg-area')
  .append('svg')
    .attr('width', root.clientWidth)
    .attr('height', root.clientHeight)
    .append('g')
    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

var xs = [],
    x,
    start = -100,
    end = 101,
    len = end - start - 1,
    ys = [],
    xys = [],
    f,
    y,
    width = 600,
    height = 300,
    padding = 20,
    svg,
    xscale,
    yaxis,
    yscale,
    yaxis;

function update(data) {
    // 要素を更新するまえにグラフを削除する
    chart.selectAll("g").remove();
    chart.selectAll("text").remove();
    chart.selectAll("line").remove();

    console.log(data.toList());
    var list = data.toList();

    var a = list[0]['a'];
    var b = list[0]['b'];
    var c = list[0]['c'];

    f = function (x, a, b, c) {
        return - a * Math.pow(x, 2) + b * x + c;
    };

    for (x = start; x < end; x += 1) {
        y = f(x, a, b, c);
        xs.push(x);
        ys.push(y);
        xys.push([x, y]);
    }

    xscale = d3.scale.linear()
        .domain([start, end])
        .range([padding, width - padding]);

    xaxis = d3.svg.axis()
        .scale(xscale)
        .orient('bottom');

    yscale = d3.scale.linear()
        .domain([d3.min(ys) - 1000, d3.max(ys)])
        .range([height - padding, padding]);

    yaxis = d3.svg.axis()
        .scale(yscale)
        .orient('left')

    chart.selectAll('line')
        .data(xys)
        .enter()
        .append('line')
        .attr('x1', function (d, i) {
            if (i === len) {
                return xscale(start);
            }
            return xscale(d[0]);
        })
        .attr('y1', function (d, i) {
            if (i === len) {
                return yscale(0);
            }
            return yscale(d[1]);
        })
        .attr('x2', function (d, i) {
            if (i === len) {
                return xscale(end);
            }
            return xscale(xys[i+1][0]);
        })
        .attr('y2', function (d, i) {
            if (i === len) {
                return yscale(0);
            }
            return yscale(xys[i+1][1]);
        })
        .attr('stroke', function (d, i) {
            if (i === len) {
                return 'blue';
            }
            return 'green';
        });

    chart.append('g')
        .attr('transform', 'translate(0, ' + (height - padding) + ')')
        .call(xaxis);

    chart.append('g')
        .attr('transform', 'translate(' + padding + ', 0)')
        .call(yaxis);

    chart.append('text')
        .attr('x', xscale(0))
        .attr('y', padding / 2)
        .attr('text-anchor', 'middle')
        .text('y = - ' + a + ' * x^2 + ' + b + '* x + ' + c);

    // ボールの描画
    chart.append("circle")
        .attr("cx", 300)
        .attr("cy", 20)
        .attr("r", 10)
        .attr("fill","orange");
}

<|endoftext|>


<commit_before>var _actions = {};

var action = function(description, callback) {
    if (callback === undefined) {
        //TODO: error logging like applebot
        _actions[description]();
    }
    else {
        _actions[description] = callback;
    }
};

var step = function(description, waitFunction, callback) {
    waitFunction();
    callback();
};

var runScript = function(client, appSettings) {

    action("Login", function(){
        client.url('https://play.google.com/apps/publish');
        client.setValue('#Email', appSettings.email, function(err, res) {

        });
        client.setValue('#Passwd', appSettings.password, function(err, res) {

        });
        client.submitForm('form#gaia_loginform', function(err, res) {

        });
    });

    step("Log in to page", function() {

    }, function() {
        action("Login");
    });

    action("Click on Add new app", function() {
        client.execute(function() {
            var spans = document.getElementsByTagName('span');
            correct_span = null;
            for(var i = 0; i < spans.length; i++) {
                var span = spans[i];
                if (span.innerHTML.trim() === "Add new application") {
                    correct_span = span;
                }
            }
        var buttonId = correct_span.parentElement.parentElement.id;
        document.querySelector("button#" + buttonId).click();
        }, [], function(err, res) {
            var value = res.value;
        });
    });

    step("Wait for login to complete", function() {
        client.waitFor('table tr a', TIMEOUT, function(err, res) {

        });
    }, function() {
            action("Click on Add new app");
    });

    action("Fill in and submit initial app information", function() {
        client.setValue(".popupContent .gwt-TextBox", appSettings.name, function(err, res) {

        });
        client.execute(function() {
            var divs = document.getElementsByTagName('div');
            var correct_div = null;
            for (var i = 0; i <divs.length; i++){
                var div = divs[i];
                if (div.innerHTML.trim() === "Upload APK"){
                    correct_div = div;
                }
            }
            var buttonId = correct_div.parentElement.id;
            document.querySelector("button#" + buttonId).click();
        }, [], function(err, res) {
            var value = res.value;
        });
    });

    step("Wait for app dialogue", function() {
        client.waitFor(".popupContent fieldset", TIMEOUT, function(err, res) {

        });
    }, function() {
        action("Fill in and submit initial app information");
    });

    action("Go to APK upload", function() {
        client.execute(function() {
            var divs = document.getElementsByTagName('div');
            matching_divs = [];

            for (var i = 0; i <divs.length; i++){
                var div = divs[i];
                if (div.innerHTML.trim() === "Upload your first APK to Production"){
                    matching_divs[matching_divs.length] = div;
                }
            }

            var correct_div = null;
            for (var i = 0; i <matching_divs.length ; i++){
                var div = matching_divs[i];
                if (div.parentElement.parentElement.children.length===3){
                    if (div.parentElement.parentElement.tagName === "DIV"){
                        correct_div = div;
                    }
                }
            }

            var buttonId = correct_div.parentElement.id;
            document.querySelector("button#" + buttonId).click();
        }, [], function(err, res) {
            var value = res.value;
        });
    });

    action("Find APK input element", function() {

        client.execute(function(specialId) {
            var interval = window.setInterval(function() {
                var divs = document.getElementsByTagName('div');
                var correct_div = null;
                for (var i = 0; i <divs.length; i++){
                    var div = divs[i];
                    if (div.innerHTML.trim() === "Browse files"){
                        console.log("HIT");
                        correct_div = div;
                    }
                }

                var anyHit = false;
                if (correct_div) {
                    var nodes = correct_div.parentElement.parentElement.children;
                    for (var i =0; i <nodes.length; i++){
                        var node = nodes[i];
                        if (node.tagName==="INPUT"){
                            console.log("hit");
                            node.id= specialId;
                            node.addEventListener("change", function(e) {
                                console.log("NODE CHANGE");
                            });
                            anyHit = true;
                        }
                    }
                }

                if (anyHit) {
                    correct_div.innerHTML = "shit";
                    correct_div.id = "correct_div";
                    window.clearInterval(interval);
                }
            }, 1000);

        }, [specialId], function(err, res) {

        });
    });

    step("Wait for APK page", function() {
        client.waitFor("div[data-stickyscrolling-placeholder]", TIMEOUT, function(err, res) {

        });
    }, function() {
        action("Go to APK upload");
        action("Find APK input element");
    });

    var upload_id = 'apk_uploading_id';

    action("Upload APK", function() {
        client.chooseFile("#" + specialId, appSettings.apk_path, function(err, res) {

        });

        client.execute(function(upload_id){
            var p = document.getElementsByTagName('p');
            for (i in p) {
                if (p[i].innerText.trim()==="Supported devices") {
                    p[i].parentElement.id = upload_id;
                    break;
                }
            }

        }, [upload_id]);
    });

    step("Wait for APK box", function() {
        client.waitFor("#correct_div", TIMEOUT, function(err, res) {

        });
    }, function() {
        action("Upload APK");
    });

    action("Go to Store Listing page", function() {
        client.execute(function(){
            var links =  document.getElementsByTagName('a');
            for (i in links){
                var link = links[i];
                if (link.innerText === "Store Listing"){
                    link.click();
                    break;
                }
            }
        });
    });

    step("Wait for APK upload", function() {
        client.waitForVisible('#' + upload_id, TIMEOUT * 10, function(err, res){

        });
    }, function() {
        action("Go to Store Listing page");
    });

    action("Fill in Store Listing information - text and select", function() {

        client.execute(function(){
            var textAreas = document.getElementsByTagName('textArea');
            textAreas[0].id = "textArea0Id";
            textAreas[1].id = "textArea1Id";

            var selectAreas = document.querySelectorAll('select');
            selectAreas[0].id = "selectArea0Id";
            selectAreas[1].id = "selectArea1Id";
            selectAreas[2].id = "selectArea2Id";
        });

        client.setValue("textarea#textArea0Id", appSettings.subtext, function(err, res){

        });

        client.setValue("textarea#textArea1Id", appSettings.promo, function(err,res){

        });

        client.click('#selectArea0Id option[value = ' + appSettings.category + ']');
        client.click('#selectArea1Id option[value = ' + appSettings.subcategory + ']');
        client.click('#selectArea2Id option[value = ' + appSettings.rating + ']');
    });

    action("Fill in Store Listing information - other info", function() {

        function searchForChild(parentTag, attribute, match, nested, childTag, childID, client){
            client.execute(function(parentTag, attribute, match, nested, childTag, childID) {
                var elements = document.querySelectorAll(parentTag);
                var correct_element = null;
                for(var i = 0; i < elements.length; i++) {
                    var element = elements[i];
                    if (element[attribute] === null) {}
                    else if (element[attribute].trim() === match) {
                        correct_element = element;
                    }
                }
                var i = 0;
                while (i < nested){
                    correct_element = correct_element.parentElement;
                    i++;
                }

                var child = correct_element.querySelector(childTag);
                child.id = childID;

            }, [parentTag, attribute, match, nested, childTag, childID]);

            return childID;
        }

        var promo_video_id = searchForChild('p', 'innerText', 'Promo Video', 2, 'input', 'promo_vid_child_id', client);
        var website_id = searchForChild('div', 'innerText', 'Website', 1, 'input', 'website_text_id', client);
        var email_id = searchForChild('div', 'innerText', 'Email', 1, 'input', 'email_text_id', client);
        var phone_id = searchForChild('div', 'innerText', 'Phone', 1, 'input', 'phone_text_id', client);
        var privacy_id = searchForChild('div', 'innerText' ,'Privacy Policy', 1, 'input', 'privacy_policy_id', client);

        client.setValue("#"+promo_video_id, appSettings.promo_vid, function(err, res){});
        client.setValue("#"+website_id, appSettings.website, function(err, res){});
        client.setValue("#"+email_id, appSettings.public_email, function(err, res){});
        client.setValue("#"+phone_id, appSettings.phone, function(err, res){});

        if (appSettings.privacy === null || appSettings.privacy === ""){
            client.execute(function(privacy_id){
                var elem = document.getElementById(privacy_id);
                var checkbox = elem.parentElement.querySelector('input[type="checkbox"]');
                checkbox.click();
            }, [privacy_id]);
        }
        else{
            client.setValue("#"+privacy_id, appSettings.privacy, function(err, res){});
        }
    });

    //not sure how to do this part
    action("Upload screenshots and graphics", function() {

    });

    action("Click save button", function() {
        client.execute(function(){
            var divs = document.querySelectorAll('div');
            correct_div = null;
            for (var i = 0; i <divs.length; i++){
                var div = divs[i];

                if (div.innerHTML.trim() === "Save"){
                    correct_div = div;
                }
            }
            correct_div.parentElement.click()
            correct_div.id = "documentSaved";

        });

        client.waitFor("#documentSaved", TIMEOUT, function(err,res){

        });

        client.execute(function(){
            var spans = document.querySelectorAll('span');

            for (var i in spans){
                var span = spans[i];

                if (span.innerText === "Your application has been saved."){
                    span.id = "documentCompletelySaved";
                }
            }
        });
    });

    step("Wait for Store Listing page", function() {
        client.waitFor('select', TIMEOUT, function(err, res){

            });
    }, function() {
        action("Fill in Store Listing information - text and select");
        action("Fill in Store Listing information - other info");
        action("Upload screenshots and graphics");
        action("Click save button");
    });

    action("Go to Pricing & Distribution page", function() {
        client.execute(function(){
            var links =  document.getElementsByTagName('a');
            for (i in links){
                var link = links[i];
                if (link.innerText === "Pricing & Distribution"){
                    link.click();
                    break;
                }
            }
        });
    });

    step("Wait for completely saved document", function() {
        client.waitFor("#documentCompletelySaved", TIMEOUT, function(err,res) {
        });
    }, function() {
        action("Go to Pricing & Distribution page");
    });

    action("Fill in Pricing & Distribution information - locations", function() {
        client.execute(function(listOfCountries){
            var toReturn = []

            var labels = document.querySelector('h4').parentElement.getElementsByTagName('label');
            for (var i in labels) {
                var label = labels[i];

                if (listOfCountries.indexOf(label.innerText) !== -1 ){
                    var input = label.querySelector('input');
                    if (input.id=== ""){
                        input.id = "languageToClickID" + i;
                    }
                    toReturn[toReturn.length] = input.id;
                }
            }

            for (language in toReturn){
                var elem = document.getElementById(toReturn[language]);
                elem.click();
            }
        }, [appSettings.locations]);
    });

    action("Fill in Pricing & Distribution information - education", function() {

        if (appSettings.education){
            client.execute(function(){
                var field = document.getElementsByTagName('fieldset')[1];
                field.querySelector('input').click();
            });

            client.waitFor('div.popupContent', TIMEOUT, function(err,res){

            });

            client.execute(function(ads, purchases){
                var divs = document.getElementsByTagName('div');
                for (i in divs){
                    var div = divs[i];
                    if (div.innerText === 'Continue'){
                        correct_div.parentElement.click();
                    }
                }

                var popUp = document.querySelector('div.popupContent');

                var inputs = popUp.getElementsByTagName('input');

                if (ads){
                    inputs[0].click();
                }
                else{
                    inputs[1].click();
                }
                if (purchases){
                    inputs[2].click();
                }
                else{
                    inputs[3].click();
                }

                var buttons = popUp.getElementsByTagName('button');
                for (i in buttons){
                    var button = buttons[i];
                    if (button.innerText.trim() === 'Save'){
                        button.click();
                        break;
                    }
                }

            }, [appSettings.education_ads, appSettings.education_purchases]);
        }
    });

    action("Fill in Pricing & Distribution information - opt in", function() {
        client.execute(function(optInValues){
            toReturn = [];
            var field = document.querySelectorAll('fieldset')[2];
            for (i in field.children){
                var child = field.children[i];
                if (child.tagName === "LABEL"){
                    if (optInValues[i]){
                        var input = child.querySelector('input');
                        if (input.id === ""){
                            input.id = "optInButtonToClickID" + child;
                        }
                        toReturn[toReturn.length] = input.id;
                    }
                }
            }

            for (opt in toReturn){
                var elem = document.getElementById(toReturn[opt]);
                elem.click();
            }

        }, [ [appSettings.marketing_opt_out, appSettings.content_guidelines, appSettings.us_export_laws] ]);
    });

    step("Wait for Pricing & Distribution page", function() {
        client.waitFor('colgroup', TIMEOUT, function(err, res){

        });
    }, function() {
        action("Fill in Pricing & Distribution information - locations");
        action("Fill in Pricing & Distribution information - education");
        action("Fill in Pricing & Distribution information - opt in");
        action("Click save button");
    });

    step("Wait for completely saved document", function() {
        client.waitFor("#documentCompletelySaved", TIMEOUT, function(err,res) {

        });
    }, function() {

    });

}

var ScriptRunner = {
    run: function(namespace, action, userOptions) {
        console.log("running " + namespace + ":" + action + " with " + JSON.stringify(userOptions));

        startSelenium(function(client) {

            var selenium = require('selenium-standalone');
            var seleniumServer = selenium({stdio: 'pipe'});

            seleniumServer.stdout.on('data', function(output) {
                var val = output.toString().trim();
                console.log(val);
                if(val.indexOf('jetty.jetty.Server')>-1){
                    client = client.init();
                    start();
                }
            });

            seleniumServer.stderr.on('data', function (data) {
              console.log('stderr: ' + data);
            });

            seleniumServer.on('close', function (code) {
              console.log('child process exited with code ' + code);
            });

            function start() {
                runScript(client, userOptions);
            }

        });
    },
    startSelenium: function(callback) {

        var webdriverjs = require('webdriverjs');
        var driverOptions = {
            desiredCapabilities: {
                browserName: 'chrome'
            }
        };
        var client = webdriverjs.remote(driverOptions);

        callback(client);
    }
};

exports = module.exports = ScriptRunner;
<commit_msg>fixed scope + missing variables<commit_after>var _actions = {};

var action = function(description, callback) {
    if (callback === undefined) {
        //TODO: error logging like applebot
        _actions[description]();
    }
    else {
        _actions[description] = callback;
    }
};

var step = function(description, waitFunction, callback) {
    waitFunction();
    callback();
};

var runScript = function(client, appSettings) {

    var specialId = "fileInputIdSecretString";

    var TIMEOUT = 5 * 1000;

    action("Login", function(){
        client.url('https://play.google.com/apps/publish');
        client.setValue('#Email', appSettings.email, function(err, res) {

        });
        client.setValue('#Passwd', appSettings.password, function(err, res) {

        });
        client.submitForm('form#gaia_loginform', function(err, res) {

        });
    });

    step("Log in to page", function() {

    }, function() {
        action("Login");
    });

    action("Click on Add new app", function() {
        client.execute(function() {
            var spans = document.getElementsByTagName('span');
            correct_span = null;
            for(var i = 0; i < spans.length; i++) {
                var span = spans[i];
                if (span.innerHTML.trim() === "Add new application") {
                    correct_span = span;
                }
            }
        var buttonId = correct_span.parentElement.parentElement.id;
        document.querySelector("button#" + buttonId).click();
        }, [], function(err, res) {
            var value = res.value;
        });
    });

    step("Wait for login to complete", function() {
        client.waitFor('table tr a', TIMEOUT, function(err, res) {

        });
    }, function() {
            action("Click on Add new app");
    });

    action("Fill in and submit initial app information", function() {
        client.setValue(".popupContent .gwt-TextBox", appSettings.name, function(err, res) {

        });
        client.execute(function() {
            var divs = document.getElementsByTagName('div');
            var correct_div = null;
            for (var i = 0; i <divs.length; i++){
                var div = divs[i];
                if (div.innerHTML.trim() === "Upload APK"){
                    correct_div = div;
                }
            }
            var buttonId = correct_div.parentElement.id;
            document.querySelector("button#" + buttonId).click();
        }, [], function(err, res) {
            var value = res.value;
        });
    });

    step("Wait for app dialogue", function() {
        client.waitFor(".popupContent fieldset", TIMEOUT, function(err, res) {

        });
    }, function() {
        action("Fill in and submit initial app information");
    });

    action("Go to APK upload", function() {
        client.execute(function() {
            var divs = document.getElementsByTagName('div');
            matching_divs = [];

            for (var i = 0; i <divs.length; i++){
                var div = divs[i];
                if (div.innerHTML.trim() === "Upload your first APK to Production"){
                    matching_divs[matching_divs.length] = div;
                }
            }

            var correct_div = null;
            for (var i = 0; i <matching_divs.length ; i++){
                var div = matching_divs[i];
                if (div.parentElement.parentElement.children.length===3){
                    if (div.parentElement.parentElement.tagName === "DIV"){
                        correct_div = div;
                    }
                }
            }

            var buttonId = correct_div.parentElement.id;
            document.querySelector("button#" + buttonId).click();
        }, [], function(err, res) {
            var value = res.value;
        });
    });

    action("Find APK input element", function() {

        client.execute(function(specialId) {
            var interval = window.setInterval(function() {
                var divs = document.getElementsByTagName('div');
                var correct_div = null;
                for (var i = 0; i <divs.length; i++){
                    var div = divs[i];
                    if (div.innerHTML.trim() === "Browse files"){
                        console.log("HIT");
                        correct_div = div;
                    }
                }

                var anyHit = false;
                if (correct_div) {
                    var nodes = correct_div.parentElement.parentElement.children;
                    for (var i =0; i <nodes.length; i++){
                        var node = nodes[i];
                        if (node.tagName==="INPUT"){
                            console.log("hit");
                            node.id= specialId;
                            node.addEventListener("change", function(e) {
                                console.log("NODE CHANGE");
                            });
                            anyHit = true;
                        }
                    }
                }

                if (anyHit) {
                    correct_div.innerHTML = "shit";
                    correct_div.id = "correct_div";
                    window.clearInterval(interval);
                }
            }, 1000);

        }, [specialId], function(err, res) {

        });
    });

    step("Wait for APK page", function() {
        client.waitFor("div[data-stickyscrolling-placeholder]", TIMEOUT, function(err, res) {

        });
    }, function() {
        action("Go to APK upload");
        action("Find APK input element");
    });

    var upload_id = 'apk_uploading_id';

    action("Upload APK", function() {
        client.chooseFile("#" + specialId, appSettings.apk_path, function(err, res) {

        });

        client.execute(function(upload_id){
            var p = document.getElementsByTagName('p');
            for (i in p) {
                if (p[i].innerText.trim()==="Supported devices") {
                    p[i].parentElement.id = upload_id;
                    break;
                }
            }

        }, [upload_id]);
    });

    step("Wait for APK box", function() {
        client.waitFor("#correct_div", TIMEOUT, function(err, res) {

        });
    }, function() {
        action("Upload APK");
    });

    action("Go to Store Listing page", function() {
        client.execute(function(){
            var links =  document.getElementsByTagName('a');
            for (i in links){
                var link = links[i];
                if (link.innerText === "Store Listing"){
                    link.click();
                    break;
                }
            }
        });
    });

    step("Wait for APK upload", function() {
        client.waitForVisible('#' + upload_id, TIMEOUT * 10, function(err, res){

        });
    }, function() {
        action("Go to Store Listing page");
    });

    action("Fill in Store Listing information - text and select", function() {

        client.execute(function(){
            var textAreas = document.getElementsByTagName('textArea');
            textAreas[0].id = "textArea0Id";
            textAreas[1].id = "textArea1Id";

            var selectAreas = document.querySelectorAll('select');
            selectAreas[0].id = "selectArea0Id";
            selectAreas[1].id = "selectArea1Id";
            selectAreas[2].id = "selectArea2Id";
        });

        client.setValue("textarea#textArea0Id", appSettings.subtext, function(err, res){

        });

        client.setValue("textarea#textArea1Id", appSettings.promo, function(err,res){

        });

        client.click('#selectArea0Id option[value = ' + appSettings.category + ']');
        client.click('#selectArea1Id option[value = ' + appSettings.subcategory + ']');
        client.click('#selectArea2Id option[value = ' + appSettings.rating + ']');
    });

    action("Fill in Store Listing information - other info", function() {

        function searchForChild(parentTag, attribute, match, nested, childTag, childID, client){
            client.execute(function(parentTag, attribute, match, nested, childTag, childID) {
                var elements = document.querySelectorAll(parentTag);
                var correct_element = null;
                for(var i = 0; i < elements.length; i++) {
                    var element = elements[i];
                    if (element[attribute] === null) {}
                    else if (element[attribute].trim() === match) {
                        correct_element = element;
                    }
                }
                var i = 0;
                while (i < nested){
                    correct_element = correct_element.parentElement;
                    i++;
                }

                var child = correct_element.querySelector(childTag);
                child.id = childID;

            }, [parentTag, attribute, match, nested, childTag, childID]);

            return childID;
        }

        var promo_video_id = searchForChild('p', 'innerText', 'Promo Video', 2, 'input', 'promo_vid_child_id', client);
        var website_id = searchForChild('div', 'innerText', 'Website', 1, 'input', 'website_text_id', client);
        var email_id = searchForChild('div', 'innerText', 'Email', 1, 'input', 'email_text_id', client);
        var phone_id = searchForChild('div', 'innerText', 'Phone', 1, 'input', 'phone_text_id', client);
        var privacy_id = searchForChild('div', 'innerText' ,'Privacy Policy', 1, 'input', 'privacy_policy_id', client);

        client.setValue("#"+promo_video_id, appSettings.promo_vid, function(err, res){});
        client.setValue("#"+website_id, appSettings.website, function(err, res){});
        client.setValue("#"+email_id, appSettings.public_email, function(err, res){});
        client.setValue("#"+phone_id, appSettings.phone, function(err, res){});

        if (appSettings.privacy === null || appSettings.privacy === ""){
            client.execute(function(privacy_id){
                var elem = document.getElementById(privacy_id);
                var checkbox = elem.parentElement.querySelector('input[type="checkbox"]');
                checkbox.click();
            }, [privacy_id]);
        }
        else{
            client.setValue("#"+privacy_id, appSettings.privacy, function(err, res){});
        }
    });

    //not sure how to do this part
    action("Upload screenshots and graphics", function() {

    });

    action("Click save button", function() {
        client.execute(function(){
            var divs = document.querySelectorAll('div');
            correct_div = null;
            for (var i = 0; i <divs.length; i++){
                var div = divs[i];

                if (div.innerHTML.trim() === "Save"){
                    correct_div = div;
                }
            }
            correct_div.parentElement.click()
            correct_div.id = "documentSaved";

        });

        client.waitFor("#documentSaved", TIMEOUT, function(err,res){

        });

        client.execute(function(){
            var spans = document.querySelectorAll('span');

            for (var i in spans){
                var span = spans[i];

                if (span.innerText === "Your application has been saved."){
                    span.id = "documentCompletelySaved";
                }
            }
        });
    });

    step("Wait for Store Listing page", function() {
        client.waitFor('select', TIMEOUT, function(err, res){

            });
    }, function() {
        action("Fill in Store Listing information - text and select");
        action("Fill in Store Listing information - other info");
        action("Upload screenshots and graphics");
        action("Click save button");
    });

    action("Go to Pricing & Distribution page", function() {
        client.execute(function(){
            var links =  document.getElementsByTagName('a');
            for (i in links){
                var link = links[i];
                if (link.innerText === "Pricing & Distribution"){
                    link.click();
                    break;
                }
            }
        });
    });

    step("Wait for completely saved document", function() {
        client.waitFor("#documentCompletelySaved", TIMEOUT, function(err,res) {
        });
    }, function() {
        action("Go to Pricing & Distribution page");
    });

    action("Fill in Pricing & Distribution information - locations", function() {
        client.execute(function(listOfCountries){
            var toReturn = []

            var labels = document.querySelector('h4').parentElement.getElementsByTagName('label');
            for (var i in labels) {
                var label = labels[i];

                if (listOfCountries.indexOf(label.innerText) !== -1 ){
                    var input = label.querySelector('input');
                    if (input.id=== ""){
                        input.id = "languageToClickID" + i;
                    }
                    toReturn[toReturn.length] = input.id;
                }
            }

            for (language in toReturn){
                var elem = document.getElementById(toReturn[language]);
                elem.click();
            }
        }, [appSettings.locations]);
    });

    action("Fill in Pricing & Distribution information - education", function() {

        if (appSettings.education){
            client.execute(function(){
                var field = document.getElementsByTagName('fieldset')[1];
                field.querySelector('input').click();
            });

            client.waitFor('div.popupContent', TIMEOUT, function(err,res){

            });

            client.execute(function(ads, purchases){
                var divs = document.getElementsByTagName('div');
                for (i in divs){
                    var div = divs[i];
                    if (div.innerText === 'Continue'){
                        correct_div.parentElement.click();
                    }
                }

                var popUp = document.querySelector('div.popupContent');

                var inputs = popUp.getElementsByTagName('input');

                if (ads){
                    inputs[0].click();
                }
                else{
                    inputs[1].click();
                }
                if (purchases){
                    inputs[2].click();
                }
                else{
                    inputs[3].click();
                }

                var buttons = popUp.getElementsByTagName('button');
                for (i in buttons){
                    var button = buttons[i];
                    if (button.innerText.trim() === 'Save'){
                        button.click();
                        break;
                    }
                }

            }, [appSettings.education_ads, appSettings.education_purchases]);
        }
    });

    action("Fill in Pricing & Distribution information - opt in", function() {
        client.execute(function(optInValues){
            toReturn = [];
            var field = document.querySelectorAll('fieldset')[2];
            for (i in field.children){
                var child = field.children[i];
                if (child.tagName === "LABEL"){
                    if (optInValues[i]){
                        var input = child.querySelector('input');
                        if (input.id === ""){
                            input.id = "optInButtonToClickID" + child;
                        }
                        toReturn[toReturn.length] = input.id;
                    }
                }
            }

            for (opt in toReturn){
                var elem = document.getElementById(toReturn[opt]);
                elem.click();
            }

        }, [ [appSettings.marketing_opt_out, appSettings.content_guidelines, appSettings.us_export_laws] ]);
    });

    step("Wait for Pricing & Distribution page", function() {
        client.waitFor('colgroup', TIMEOUT, function(err, res){

        });
    }, function() {
        action("Fill in Pricing & Distribution information - locations");
        action("Fill in Pricing & Distribution information - education");
        action("Fill in Pricing & Distribution information - opt in");
        action("Click save button");
    });

    step("Wait for completely saved document", function() {
        client.waitFor("#documentCompletelySaved", TIMEOUT, function(err,res) {

        });
    }, function() {

    });

}

var ScriptRunner = {
    run: function(namespace, action, userOptions) {
        console.log("running " + namespace + ":" + action + " with " + JSON.stringify(userOptions));

        this.startSelenium(function(client) {

            var selenium = require('selenium-standalone');
            var seleniumServer = selenium({stdio: 'pipe'});

            seleniumServer.stdout.on('data', function(output) {
                var val = output.toString().trim();
                console.log(val);
                if(val.indexOf('jetty.jetty.Server')>-1){
                    client = client.init();
                    start();
                }
            });

            seleniumServer.stderr.on('data', function (data) {
              console.log('stderr: ' + data);
            });

            seleniumServer.on('close', function (code) {
              console.log('child process exited with code ' + code);
            });

            function start() {
                runScript(client, userOptions);
            }

        });
    },
    startSelenium: function(callback) {

        var webdriverjs = require('webdriverjs');
        var driverOptions = {
            desiredCapabilities: {
                browserName: 'chrome'
            }
        };
        var client = webdriverjs.remote(driverOptions);

        callback(client);
    }
};

exports = module.exports = ScriptRunner;
<|endoftext|>


<commit_before>/**
 * @author Sebastien Valette sebastien.valette@creatis.insa-lyon.fr
 */

THREE.VTKLoader = function ( showStatus ) {

	THREE.Loader.call( this, showStatus );

};

THREE.VTKLoader.prototype = new THREE.Loader();
THREE.VTKLoader.prototype.constructor = THREE.VTKLoader;
THREE.VTKLoader.prototype.supr = THREE.Loader.prototype;

THREE.VTKLoader.prototype.load = function( url, callback) {

	this.onLoadStart();

	function  parseGeometry(text){
		var geometry=new THREE.Geometry();
		var lines=text.split("\n");

		function v( x, y, z ) {

			geometry.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );

		}

		function f3( a, b, c ) {

			geometry.faces.push( new THREE.Face3( a, b, c ) );

		}

		var lineIndex=0;

		var line=lines[0].split(" ");
		var lineLength=line.length;
		var columnIndex=-1;

		function readNextString ()
		{
			while (1)
			{
				var nextWord=line[columnIndex];
				columnIndex++;
				if (columnIndex==lineLength)
				{
					lineIndex++;
					columnIndex=0;
					if (lineIndex>lines.length)
						return ("");
					line=lines[lineIndex].split(" ");
					lineLength=line.length;
				}
				if (nextWord!=null)
					if (nextWord.length>0)
						return (nextWord);
			}
		}

		// read point data
		var found=false;
		while (!found)
		{
			var readString=readNextString();
			switch (readString.toUpperCase())
			{
				case "POINTS":
					found=true;
					break;
				case "":
					alert ("error while reading "+url+" : \n");
					return;
				default:
			}

		}

		var newIndex;
		var new2old;

		var numberOfPoints=parseInt(readNextString());

		if (numberOfPoints>5000000)
		{
			alert ("mesh is too big : "+numberOfPoints+" vertices");
			return;
		}

		var coord=[0,0,0];
		var index2=0;

		var number;
		var coordIndex;
		for (var j=0;j!=numberOfPoints;j++)
		{
			for (coordIndex=0;coordIndex<3;coordIndex++)
			{
				do
				{
					number=parseFloat(line[columnIndex]);
					columnIndex++;
					if (columnIndex==lineLength)
					{
						lineIndex++;
						columnIndex=0;
						if (lineIndex>lines.length)
						{
							alert ("error while reading "+url+" : \n");
							return;
						}
						line=lines[lineIndex].split(" ");
						lineLength=line.length;
					}
				} while (isNaN(number))
				coord[coordIndex]=number;
			}
			v(coord[0],coord[1],coord[2]);
		}

		found=false;
		while (!found)
		{
			var readString=readNextString();
			switch (readString)
			{
				case "POLYGONS":
					found=true;
					break;
				case "":
					alert ("error while reading "+url+" : \n");
					return;
				default:
			}
		}

		var numberOfPolygons=parseInt(readNextString());
		var numberOfpolygonElements=parseInt(readNextString());

		index2=0;
		var connectivity=[];
		for (var p=0;p!=numberOfpolygonElements;p++)
		{
			do
			{
				number=parseInt(line[columnIndex]);
				columnIndex++;
				if (columnIndex==lineLength)
				{
					lineIndex++;
					columnIndex=0;
					if (lineIndex>lines.length)
					{
						alert ("error while reading "+url+" : \n");
						return;
					}
					line=lines[lineIndex].split(" ");
					lineLength=line.length;
				}
			} while (isNaN(number))

			connectivity[index2]=number;
			index2++;

			if (index2==connectivity[0]+1)
			{
				var triangle=[0,0,0];
				index2=0;
				var numberOfTrianglesInCell=connectivity[0]-2;
				var vertex1=triangle[0]=connectivity[1];

				for (var i=0;i<numberOfTrianglesInCell;i++)
				{
					var vertex2=connectivity[i+2];
					var vertex3=triangle[2]=connectivity[i+3];
					f3(vertex1,vertex2,vertex3);
				}
			}
		}

		geometry.computeCentroids();
		geometry.computeFaceNormals();
		geometry.computeVertexNormals();
		geometry.computeBoundingSphere();
		return (geometry);
	}

	var xmlhttp=new XMLHttpRequest();
	xmlhttp.open("GET",url,true);

	function handler()
	{
		if(xmlhttp.readyState == 4)
		{
			if (xmlhttp.status!=200)
			{
				alert("Could not read file "+url+": error"+xmlhttp.status);
				return;
			}
			var myGeometry=parseGeometry(xmlhttp.responseText);
			callback(myGeometry);
		}
	}
	xmlhttp.onreadystatechange=handler;
	xmlhttp.send();

};

<commit_msg>fix VTKLoader for dev branch<commit_after>/**
 * @author Sebastien Valette sebastien.valette@creatis.insa-lyon.fr
 */

THREE.VTKLoader = function ( showStatus ) {

	THREE.Loader.call( this, showStatus );

};

THREE.VTKLoader.prototype = new THREE.Loader();
THREE.VTKLoader.prototype.constructor = THREE.VTKLoader;
THREE.VTKLoader.prototype.supr = THREE.Loader.prototype;

THREE.VTKLoader.prototype.load = function( url, callback) {

	this.onLoadStart();

	function  parseGeometry(text){
		var geometry=new THREE.Geometry();
		var lines=text.split("\n");

		function v( x, y, z ) {

			geometry.vertices.push( new THREE.Vector3( x, y, z ) );

		}

		function f3( a, b, c ) {

			geometry.faces.push( new THREE.Face3( a, b, c ) );

		}

		var lineIndex=0;

		var line=lines[0].split(" ");
		var lineLength=line.length;
		var columnIndex=-1;

		function readNextString ()
		{
			while (1)
			{
				var nextWord=line[columnIndex];
				columnIndex++;
				if (columnIndex==lineLength)
				{
					lineIndex++;
					columnIndex=0;
					if (lineIndex>lines.length)
						return ("");
					line=lines[lineIndex].split(" ");
					lineLength=line.length;
				}
				if (nextWord!=null)
					if (nextWord.length>0)
						return (nextWord);
			}
		}

		// read point data
		var found=false;
		while (!found)
		{
			var readString=readNextString();
			switch (readString.toUpperCase())
			{
				case "POINTS":
					found=true;
					break;
				case "":
					alert ("error while reading "+url+" : \n");
					return;
				default:
			}

		}

		var newIndex;
		var new2old;

		var numberOfPoints=parseInt(readNextString());

		if (numberOfPoints>5000000)
		{
			alert ("mesh is too big : "+numberOfPoints+" vertices");
			return;
		}

		var coord=[0,0,0];
		var index2=0;

		var number;
		var coordIndex;
		for (var j=0;j!=numberOfPoints;j++)
		{
			for (coordIndex=0;coordIndex<3;coordIndex++)
			{
				do
				{
					number=parseFloat(line[columnIndex]);
					columnIndex++;
					if (columnIndex==lineLength)
					{
						lineIndex++;
						columnIndex=0;
						if (lineIndex>lines.length)
						{
							alert ("error while reading "+url+" : \n");
							return;
						}
						line=lines[lineIndex].split(" ");
						lineLength=line.length;
					}
				} while (isNaN(number))
				coord[coordIndex]=number;
			}
			v(coord[0],coord[1],coord[2]);
		}

		found=false;
		while (!found)
		{
			var readString=readNextString();
			switch (readString)
			{
				case "POLYGONS":
					found=true;
					break;
				case "":
					alert ("error while reading "+url+" : \n");
					return;
				default:
			}
		}

		var numberOfPolygons=parseInt(readNextString());
		var numberOfpolygonElements=parseInt(readNextString());

		index2=0;
		var connectivity=[];
		for (var p=0;p!=numberOfpolygonElements;p++)
		{
			do
			{
				number=parseInt(line[columnIndex]);
				columnIndex++;
				if (columnIndex==lineLength)
				{
					lineIndex++;
					columnIndex=0;
					if (lineIndex>lines.length)
					{
						alert ("error while reading "+url+" : \n");
						return;
					}
					line=lines[lineIndex].split(" ");
					lineLength=line.length;
				}
			} while (isNaN(number))

			connectivity[index2]=number;
			index2++;

			if (index2==connectivity[0]+1)
			{
				var triangle=[0,0,0];
				index2=0;
				var numberOfTrianglesInCell=connectivity[0]-2;
				var vertex1=triangle[0]=connectivity[1];

				for (var i=0;i<numberOfTrianglesInCell;i++)
				{
					var vertex2=connectivity[i+2];
					var vertex3=triangle[2]=connectivity[i+3];
					f3(vertex1,vertex2,vertex3);
				}
			}
		}

		geometry.computeCentroids();
		geometry.computeFaceNormals();
		geometry.computeVertexNormals();
		geometry.computeBoundingSphere();
		return (geometry);
	}

	var xmlhttp=new XMLHttpRequest();
	xmlhttp.open("GET",url,true);

	function handler()
	{
		if(xmlhttp.readyState == 4)
		{
			if (xmlhttp.status!=200)
			{
				alert("Could not read file "+url+": error"+xmlhttp.status);
				return;
			}
			var myGeometry=parseGeometry(xmlhttp.responseText);
			callback(myGeometry);
		}
	}
	xmlhttp.onreadystatechange=handler;
	xmlhttp.send();

};

<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.socketIOMiddleware = exports.onSocketEvents = exports.defaultSocketEvents = exports.initialStateEvents = exports.defaultOpts = undefined;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };

var _socket = require('socket.io-client');

var _socket2 = _interopRequireDefault(_socket);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var defaultOpts = exports.defaultOpts = {
  transports: ['websocket']
};

var initialStateEvents = exports.initialStateEvents = [{
  action: 'connecting',
  dispatch: function dispatch(store, next, action) {
    return function (socket) {
      console.log('Socket is connecting.');
    };
  }
}, {
  action: 'connect',
  dispatch: function dispatch(store, next, action) {
    return function (socket) {
      console.log('Socket connected.');
    };
  }
}, {
  action: 'disconnect',
  dispatch: function dispatch(store, next, action) {
    return function (socket) {
      console.log('Socket disconnected.');
    };
  }
}, {
  action: 'reconnecting',
  dispatch: function dispatch(store, next, action) {
    return function (socket) {
      console.log('Socket reconnecting.');
    };
  }
}];

var defaultSocketEvents = exports.defaultSocketEvents = [{
  action: 'NOOP',
  dispatch: function dispatch(socket, store, action) {
    console.debug('NOOP event called. Have you implemented your events?');
  }
}];

var onSocketEvents = exports.onSocketEvents = function onSocketEvents(socket, store, next, action) {
  return function (event, data) {
    console.error('Socket not listening for any events.');
  };
};

var socketIOMiddleware = exports.socketIOMiddleware = function socketIOMiddleware() {
  var initialSocket = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0];
  var dispatchEvents = arguments.length <= 1 || arguments[1] === undefined ? defaultSocketEvents : arguments[1];
  var listenEvents = arguments.length <= 2 || arguments[2] === undefined ? onSocketEvents : arguments[2];
  var stateEvents = arguments.length <= 3 || arguments[3] === undefined ? initialStateEvents : arguments[3];
  var connectAction = arguments.length <= 4 || arguments[4] === undefined ? 'CONNECT' : arguments[4];
  var options = arguments.length <= 5 || arguments[5] === undefined ? defaultOpts : arguments[5];

  var socket = initialSocket;
  var onEvent = listenEvents;

  return function (store) {
    return function (next) {
      return function (action) {
        if (action.type === connectAction || socket != null) {
          var _ret = function () {
            var nextAction = false;
            if (socket === null) {
              nextAction = true;
              var connStr = action.payload.host + ':' + action.payload.port;
              if (socket !== null) {
                socket.close();
              }

              socket = _socket2.default.connect(connStr, options);
            }

            var onevent = socket.onevent;
            socket.onevent = function (packet) {
              var args = packet.data || [];
              packet.data = ['*'].concat(args);
              onevent.call(socket, packet);
            };

            socket.on('*', onEvent(socket, store, next, action));
            stateEvents.map(function (evt) {
              var eventAction = evt.dispatch;
              socket.on(evt.action.toString(), eventAction(store, next, action));
            });

            if (nextAction) {
              return {
                v: next(action)
              };
            }
          }();

          if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
        }

        if (socket != null) {
          if (!socket.connected) {
            throw new Error('Socket must call a connect event before dispatching any actions.');
          }

          dispatchEvents.map(function (event) {
            if (action.type === event.action) {
              return event.dispatch(socket, store, action);
            }
          });
        }

        return next(action);
      };
    };
  };
};

exports.default = socketIOMiddleware;<commit_msg>Update dist<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.socketIOMiddleware = exports.onSocketEvents = exports.defaultSocketEvents = exports.initialStateEvents = exports.defaultOpts = undefined;

var _socket = require('socket.io-client');

var _socket2 = _interopRequireDefault(_socket);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var defaultOpts = exports.defaultOpts = {
  transports: ['websocket']
};

var initialStateEvents = exports.initialStateEvents = [{
  action: 'connecting',
  dispatch: function dispatch(store, next, action) {
    return function (socket) {
      console.log('Socket is connecting.');
    };
  }
}, {
  action: 'connect',
  dispatch: function dispatch(store, next, action) {
    return function (socket) {
      console.log('Socket connected.');
    };
  }
}, {
  action: 'disconnect',
  dispatch: function dispatch(store, next, action) {
    return function (socket) {
      console.log('Socket disconnected.');
    };
  }
}, {
  action: 'reconnecting',
  dispatch: function dispatch(store, next, action) {
    return function (socket) {
      console.log('Socket reconnecting.');
    };
  }
}];

var defaultSocketEvents = exports.defaultSocketEvents = [{
  action: 'NOOP',
  dispatch: function dispatch(socket, store, action) {
    console.debug('NOOP event called. Have you implemented your events?');
  }
}];

var onSocketEvents = exports.onSocketEvents = function onSocketEvents(socket, store, next, action) {
  return function (event, data) {
    console.error('Socket not listening for any events.');
  };
};

var initializedSocket = [];

var socketIOMiddleware = exports.socketIOMiddleware = function socketIOMiddleware() {
  var initialSocket = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0];
  var dispatchEvents = arguments.length <= 1 || arguments[1] === undefined ? defaultSocketEvents : arguments[1];
  var listenEvents = arguments.length <= 2 || arguments[2] === undefined ? onSocketEvents : arguments[2];
  var stateEvents = arguments.length <= 3 || arguments[3] === undefined ? initialStateEvents : arguments[3];
  var connectAction = arguments.length <= 4 || arguments[4] === undefined ? 'CONNECT' : arguments[4];
  var options = arguments.length <= 5 || arguments[5] === undefined ? defaultOpts : arguments[5];

  var socket = initialSocket;
  var onEvent = listenEvents;
  initializedSocket[connectAction] = false;

  return function (store) {
    return function (next) {
      return function (action) {
        if (action.type === connectAction && !initializedSocket[connectAction]) {
          (function () {
            var nextAction = false;
            if (socket === null) {
              nextAction = true;
              var connStr = action.payload.host + ':' + action.payload.port;
              if (socket !== null) {
                socket.close();
              }

              socket = _socket2.default.connect(connStr, options);
            }

            var onevent = socket.onevent;
            socket.onevent = function (packet) {
              var args = packet.data || [];
              packet.data = ['*'].concat(args);
              onevent.call(socket, packet);
            };

            socket.on('*', onEvent(socket, store, next, action));
            stateEvents.map(function (evt) {
              var eventAction = evt.dispatch;
              socket.on(evt.action.toString(), eventAction(store, next, action));
            });
            initializedSocket[connectAction] = true;
          })();
        }

        if (socket != null) {
          dispatchEvents.map(function (event) {
            if (action.type === event.action) {
              return event.dispatch(socket, store, action);
            }
          });
        }

        return next(action);
      };
    };
  };
};

exports.default = socketIOMiddleware;<|endoftext|>


<commit_before>"use strict";

let mongoose = require('mongoose');

let schemaUser = mongoose.Schema({
    vCoin: {
        type: Number,
        default: 0
    },
    roles: [{type: String}],
    facebook: {
        id: String,
        token: String,
        email: String,
        name: String
    }
});

schemaUser.virtual('is_manager').get(function () {
    return this.roles && this.roles.includes('manager')
});

schemaUser.virtual('name').get(function () {
    return this.facebook.name
});

module.exports = mongoose.model('User', schemaUser);
<commit_msg>exposing virtuals to JSON<commit_after>"use strict";

let mongoose = require('mongoose');

let schemaUser = mongoose.Schema({
    vCoin: {
        type: Number,
        default: 0
    },
    roles: [{type: String}],
    facebook: {
        id: String,
        token: String,
        email: String,
        name: String
    }
}, {
    toJSON: { virtuals: true }
});

schemaUser.virtual('is_manager').get(function () {
    return this.roles && this.roles.includes('manager')
});

schemaUser.virtual('name').get(function () {
    return this.facebook.name
});

module.exports = mongoose.model('User', schemaUser);
<|endoftext|>


<commit_before><commit_msg>Rebuild v1.3.0<commit_after>(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory(require("vue"));
	else if(typeof define === 'function' && define.amd)
		define(["vue"], factory);
	else if(typeof exports === 'object')
		exports["vue-notification"] = factory(require("vue"));
	else
		root["vue-notification"] = factory(root["vue"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_3__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// identity function for calling harmony imports with the correct context
/******/ 	__webpack_require__.i = function(value) { return value; };
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "/dist/";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 2);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {

// this module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle

module.exports = function normalizeComponent (
  rawScriptExports,
  compiledTemplate,
  scopeId,
  cssModules
) {
  var esModule
  var scriptExports = rawScriptExports = rawScriptExports || {}

  // ES6 modules interop
  var type = typeof rawScriptExports.default
  if (type === 'object' || type === 'function') {
    esModule = rawScriptExports
    scriptExports = rawScriptExports.default
  }

  // Vue.extend constructor export interop
  var options = typeof scriptExports === 'function'
    ? scriptExports.options
    : scriptExports

  // render functions
  if (compiledTemplate) {
    options.render = compiledTemplate.render
    options.staticRenderFns = compiledTemplate.staticRenderFns
  }

  // scopedId
  if (scopeId) {
    options._scopeId = scopeId
  }

  // inject cssModules
  if (cssModules) {
    var computed = Object.create(options.computed || null)
    Object.keys(cssModules).forEach(function (key) {
      var module = cssModules[key]
      computed[key] = function () { return module }
    })
    options.computed = computed
  }

  return {
    esModule: esModule,
    exports: scriptExports,
    options: options
  }
}

/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return events; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_vue__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_vue___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_vue__);

var events = new __WEBPACK_IMPORTED_MODULE_0_vue___default.a();

/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Notifications_vue__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Notifications_vue___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__Notifications_vue__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__events__ = __webpack_require__(1);
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var Notify = {
  install: function install(Vue) {
    if (this.installed) {
      return;
    }

    this.installed = true;

    Vue.component('notifications', __WEBPACK_IMPORTED_MODULE_0__Notifications_vue___default.a);
    Vue.prototype.$notify = function (params) {
      if (typeof params === 'string') {
        params = { title: '', text: params };
      }

      if ((typeof params === 'undefined' ? 'undefined' : _typeof(params)) === 'object') {
        __WEBPACK_IMPORTED_MODULE_1__events__["a" /* events */].$emit('add', params);
      }
    };
  }
};

/* harmony default export */ __webpack_exports__["default"] = (Notify);

/***/ }),
/* 3 */
/***/ (function(module, exports) {

module.exports = __WEBPACK_EXTERNAL_MODULE_3__;

/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {

/* styles */
__webpack_require__(17)

var Component = __webpack_require__(0)(
  /* script */
  __webpack_require__(6),
  /* template */
  __webpack_require__(15),
  /* scopeId */
  null,
  /* cssModules */
  null
)

module.exports = Component.exports

/***/ }),
/* 5 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });

/* harmony default export */ __webpack_exports__["default"] = ({
  name: 'CssGroup',
  props: ['name']
});

/***/ }),
/* 6 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_vue__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_vue___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_vue__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__index__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__events__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__defaults__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__VelocityGroup_vue__ = __webpack_require__(13);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__VelocityGroup_vue___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_5__VelocityGroup_vue__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__CssGroup_vue__ = __webpack_require__(12);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__CssGroup_vue___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_6__CssGroup_vue__);
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var STATE = {
  idle: 0,
  destroyed: 2
};

/* harmony default export */ __webpack_exports__["default"] = ({
  name: 'Notifications',
  components: {
    VelocityGroup: __WEBPACK_IMPORTED_MODULE_5__VelocityGroup_vue___default.a,
    CssGroup: __WEBPACK_IMPORTED_MODULE_6__CssGroup_vue___default.a
  },
  props: {
    group: {
      type: String
    },

    width: {
      type: Number,
      default: 300
    },

    reverse: {
      type: Boolean,
      default: false
    },

    position: {
      type: String,
      default: __WEBPACK_IMPORTED_MODULE_4__defaults__["a" /* default */].position
    },

    classes: {
      type: String,
      default: 'vue-notification'
    },

    animationType: {
      type: String,
      default: 'css',
      validator: function validator(value) {
        return value === 'css' || value === 'velocity';
      }
    },

    animation: {
      type: Object,
      default: function _default() {
        return __WEBPACK_IMPORTED_MODULE_4__defaults__["a" /* default */].velocityAnimation;
      }
    },

    animationName: {
      type: String,
      default: __WEBPACK_IMPORTED_MODULE_4__defaults__["a" /* default */].cssAnimation
    },

    speed: {
      type: Number,
      default: 300
    },

    duration: {
      type: Number,
      default: 3000
    },

    delay: {
      type: Number,
      default: 0
    }
  },
  data: function data() {
    return {
      list: []
    };
  },
  created: function created() {
    var _this = this;

    __WEBPACK_IMPORTED_MODULE_2__events__["a" /* events */].$on('add', function (event) {
      if (_this.group && _this.group != event.group) {
        return;
      }

      var duration = typeof event.duration === 'number' ? event.duration : _this.duration;

      var speed = typeof event.speed === 'number' ? event.speed : _this.speed;

      var title = event.title,
          text = event.text,
          type = event.type;

      var item = {
        id: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__util__["a" /* Id */])(),
        title: title,
        text: text,
        type: type,
        state: STATE.idle,
        speed: speed,
        length: duration + 2 * speed
      };

      if (duration >= 0) {
        item.timer = setTimeout(function () {
          _this.destroy(item);
        }, item.length);
      }

      var direction = _this.reverse ? !_this.botToTop : _this.botToTop;

      if (direction) {
        _this.list.push(item);
      } else {
        _this.list.unshift(item);
      }
    });
  },

  computed: {
    isVA: function isVA() {
      return this.animationType === 'velocity';
    },
    componentName: function componentName() {
      return this.isVA ? 'VelocityGroup' : 'CssGroup';
    },
    styles: function styles() {
      var _listToDirection = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__util__["b" /* listToDirection */])(this.position),
          x = _listToDirection.x,
          y = _listToDirection.y;

      var styles = _defineProperty({
        width: this.width + 'px'
      }, y, '0px');

      if (x === 'center') {
        styles['left'] = 'calc(50% - ' + this.width / 2 + 'px)';
      } else {
        styles[x] = '0px';
      }

      return styles;
    },
    botToTop: function botToTop() {
      return this.styles.hasOwnProperty('bottom');
    }
  },
  methods: {
    nСlass: function nLass(item) {
      return ['notification', this.classes, item.type];
    },
    nwStyle: function nwStyle(item) {
      return this.isVA ? null : {
        transition: 'all ' + item.speed + 'ms'
      };
    },
    destroy: function destroy(item) {
      clearTimeout(item.timer);
      item.state = STATE.destroyed;

      if (!this.isVA) {
        this.clean();
      }
    },
    getAnimation: function getAnimation(index, el) {
      var anim = this.animation[index];

      return typeof anim === 'function' ? anim.call(this, el) : anim;
    },
    enter: function enter(_ref) {
      var el = _ref.el,
          complete = _ref.complete;

      var animation = this.getAnimation('enter', el);

      this.velocity(el, animation, {

        duration: this.speed,
        complete: complete
      });
    },
    leave: function leave(_ref2) {
      var el = _ref2.el,
          complete = _ref2.complete;

      var animation = this.getAnimation('leave', el);

      this.velocity(el, animation, {
        duration: this.speed,
        complete: complete
      });
    },
    clean: function clean() {
      this.list = this.list.filter(function (v) {
        return v.state !== STATE.destroyed;
      });
    }
  }
});

/***/ }),
/* 7 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });

/* harmony default export */ __webpack_exports__["default"] = ({
  name: 'VelocityGroup',
  methods: {
    enter: function enter(el, complete) {
      this.$emit('enter', { el: el, complete: complete });
    },
    leave: function leave(el, complete) {
      this.$emit('leave', { el: el, complete: complete });
    },
    afterLeave: function afterLeave() {
      this.$emit('afterLeave');
    }
  }
});

/***/ }),
/* 8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony default export */ __webpack_exports__["a"] = ({
  position: ['top', 'right'],
  cssAnimation: 'vn-fade',
  velocityAnimation: {
    enter: function enter(el) {
      var height = el.clientHeight;

      return {
        height: [height, 0],
        opacity: [1, 0]
      };
    },
    leave: {
      height: 0,
      opacity: [0, 1]
    }
  }
});

/***/ }),
/* 9 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Id; });
/* unused harmony export split */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return listToDirection; });
var directions = {
  x: ['left', 'center', 'right'],
  y: ['top', 'bottom']
};

var Id = function (i) {
  return function () {
    return i++;
  };
}(0);

var split = function split(value) {
  if (typeof value !== 'string') {
    return [];
  }

  return value.split(/\s+/gi).filter(function (v) {
    return v;
  });
};

var listToDirection = function listToDirection(value) {
  if (typeof value === 'string') {
    value = split(value);
  }

  var x = null;
  var y = null;

  value.forEach(function (v) {
    if (directions.y.indexOf(v) !== -1) {
      y = v;
    }
    if (directions.x.indexOf(v) !== -1) {
      x = v;
    }
  });

  return { x: x, y: y };
};

/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(11)();
// imports

// module
exports.push([module.i, ".notifications{display:block;position:fixed;z-index:5000}.notification-wrapper{display:block;overflow:hidden;width:100%;margin:0;padding:0}.notification{display:block;box-sizing:border-box;background:#fff;text-align:left}.notification-title{font-weight:600}.vue-notification{font-size:12px;padding:10px;margin:0 5px 5px;color:#fff;background:#44a4fc;border-left:5px solid #187fe7}.vue-notification.warn{background:#ffb648;border-left-color:#f48a06}.vue-notification.error{background:#e54d42;border-left-color:#b82e24}.vue-notification.success{background:#68cd86;border-left-color:#42a85f}.vn-fade-enter-active,.vn-fade-leave-active,.vn-fade-move{transition:all .5s}.vn-fade-enter,.vn-fade-leave-to{opacity:0}", ""]);

// exports

/***/ }),
/* 11 */
/***/ (function(module, exports) {

/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
module.exports = function() {
	var list = [];

	// return the list of modules as css string
	list.toString = function toString() {
		var result = [];
		for(var i = 0; i < this.length; i++) {
			var item = this[i];
			if(item[2]) {
				result.push("@media " + item[2] + "{" + item[1] + "}");
			} else {
				result.push(item[1]);
			}
		}
		return result.join("");
	};

	// import a list of modules into the list
	list.i = function(modules, mediaQuery) {
		if(typeof modules === "string")
			modules = [[null, modules, ""]];
		var alreadyImportedModules = {};
		for(var i = 0; i < this.length; i++) {
			var id = this[i][0];
			if(typeof id === "number")
				alreadyImportedModules[id] = true;
		}
		for(i = 0; i < modules.length; i++) {
			var item = modules[i];
			// skip already imported module
			// this implementation is not 100% perfect for weird media query combinations
			//  when a module is imported multiple times with different media queries.
			//  I hope this will never occur (Hey this way we have smaller bundles)
			if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) {
				if(mediaQuery && !item[2]) {
					item[2] = mediaQuery;
				} else if(mediaQuery) {
					item[2] = "(" + item[2] + ") and (" + mediaQuery + ")";
				}
				list.push(item);
			}
		}
	};
	return list;
};

/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {

var Component = __webpack_require__(0)(
  /* script */
  __webpack_require__(5),
  /* template */
  __webpack_require__(16),
  /* scopeId */
  null,
  /* cssModules */
  null
)

module.exports = Component.exports

/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {

var Component = __webpack_require__(0)(
  /* script */
  __webpack_require__(7),
  /* template */
  __webpack_require__(14),
  /* scopeId */
  null,
  /* cssModules */
  null
)

module.exports = Component.exports

/***/ }),
/* 14 */
/***/ (function(module, exports) {

module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
  return _c('transition-group', {
    attrs: {
      "css": false
    },
    on: {
      "enter": _vm.enter,
      "leave": _vm.leave,
      "after-leave": _vm.afterLeave
    }
  }, [_vm._t("default")], 2)
},staticRenderFns: []}

/***/ }),
/* 15 */
/***/ (function(module, exports) {

module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
  return _c('div', {
    staticClass: "notifications",
    style: (_vm.styles)
  }, [_c(_vm.componentName, {
    tag: "component",
    attrs: {
      "name": _vm.animationName
    },
    on: {
      "enter": _vm.enter,
      "leave": _vm.leave,
      "after-leave": _vm.clean
    }
  }, _vm._l((_vm.list), function(item) {
    return (item.state != 2) ? _c('div', {
      key: item.id,
      staticClass: "notification-wrapper",
      style: (_vm.nwStyle(item)),
      attrs: {
        "data-id": item.id
      }
    }, [_vm._t("body", [_c('div', {
      class: _vm.nСlass(item),
      on: {
        "click": function($event) {
          _vm.destroy(item)
        }
      }
    }, [(item.title) ? _c('div', {
      staticClass: "notification-title",
      domProps: {
        "innerHTML": _vm._s(item.title)
      }
    }) : _vm._e(), _vm._v(" "), _c('div', {
      staticClass: "notification-content",
      domProps: {
        "innerHTML": _vm._s(item.text)
      }
    })])], {
      item: item,
      close: function () { return _vm.destroy(item); }
    })], 2) : _vm._e()
  }))], 1)
},staticRenderFns: []}

/***/ }),
/* 16 */
/***/ (function(module, exports) {

module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
  return _c('transition-group', {
    attrs: {
      "name": _vm.name
    }
  }, [_vm._t("default")], 2)
},staticRenderFns: []}

/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {

// style-loader: Adds some css to the DOM by adding a <style> tag

// load the styles
var content = __webpack_require__(10);
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add the styles to the DOM
var update = __webpack_require__(18)("2901aeae", content, true);

/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {

/*
  MIT License http://www.opensource.org/licenses/mit-license.php
  Author Tobias Koppers @sokra
  Modified by Evan You @yyx990803
*/

var hasDocument = typeof document !== 'undefined'

if (typeof DEBUG !== 'undefined' && DEBUG) {
  if (!hasDocument) {
    throw new Error(
    'vue-style-loader cannot be used in a non-browser environment. ' +
    "Use { target: 'node' } in your Webpack config to indicate a server-rendering environment."
  ) }
}

var listToStyles = __webpack_require__(19)

/*
type StyleObject = {
  id: number;
  parts: Array<StyleObjectPart>
}

type StyleObjectPart = {
  css: string;
  media: string;
  sourceMap: ?string
}
*/

var stylesInDom = {/*
  [id: number]: {
    id: number,
    refs: number,
    parts: Array<(obj?: StyleObjectPart) => void>
  }
*/}

var head = hasDocument && (document.head || document.getElementsByTagName('head')[0])
var singletonElement = null
var singletonCounter = 0
var isProduction = false
var noop = function () {}

// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
// tags it will allow on a page
var isOldIE = typeof navigator !== 'undefined' && /msie [6-9]\b/.test(navigator.userAgent.toLowerCase())

module.exports = function (parentId, list, _isProduction) {
  isProduction = _isProduction

  var styles = listToStyles(parentId, list)
  addStylesToDom(styles)

  return function update (newList) {
    var mayRemove = []
    for (var i = 0; i < styles.length; i++) {
      var item = styles[i]
      var domStyle = stylesInDom[item.id]
      domStyle.refs--
      mayRemove.push(domStyle)
    }
    if (newList) {
      styles = listToStyles(parentId, newList)
      addStylesToDom(styles)
    } else {
      styles = []
    }
    for (var i = 0; i < mayRemove.length; i++) {
      var domStyle = mayRemove[i]
      if (domStyle.refs === 0) {
        for (var j = 0; j < domStyle.parts.length; j++) {
          domStyle.parts[j]()
        }
        delete stylesInDom[domStyle.id]
      }
    }
  }
}

function addStylesToDom (styles /* Array<StyleObject> */) {
  for (var i = 0; i < styles.length; i++) {
    var item = styles[i]
    var domStyle = stylesInDom[item.id]
    if (domStyle) {
      domStyle.refs++
      for (var j = 0; j < domStyle.parts.length; j++) {
        domStyle.parts[j](item.parts[j])
      }
      for (; j < item.parts.length; j++) {
        domStyle.parts.push(addStyle(item.parts[j]))
      }
      if (domStyle.parts.length > item.parts.length) {
        domStyle.parts.length = item.parts.length
      }
    } else {
      var parts = []
      for (var j = 0; j < item.parts.length; j++) {
        parts.push(addStyle(item.parts[j]))
      }
      stylesInDom[item.id] = { id: item.id, refs: 1, parts: parts }
    }
  }
}

function createStyleElement () {
  var styleElement = document.createElement('style')
  styleElement.type = 'text/css'
  head.appendChild(styleElement)
  return styleElement
}

function addStyle (obj /* StyleObjectPart */) {
  var update, remove
  var styleElement = document.querySelector('style[data-vue-ssr-id~="' + obj.id + '"]')

  if (styleElement) {
    if (isProduction) {
      // has SSR styles and in production mode.
      // simply do nothing.
      return noop
    } else {
      // has SSR styles but in dev mode.
      // for some reason Chrome can't handle source map in server-rendered
      // style tags - source maps in <style> only works if the style tag is
      // created and inserted dynamically. So we remove the server rendered
      // styles and inject new ones.
      styleElement.parentNode.removeChild(styleElement)
    }
  }

  if (isOldIE) {
    // use singleton mode for IE9.
    var styleIndex = singletonCounter++
    styleElement = singletonElement || (singletonElement = createStyleElement())
    update = applyToSingletonTag.bind(null, styleElement, styleIndex, false)
    remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true)
  } else {
    // use multi-style-tag mode in all other cases
    styleElement = createStyleElement()
    update = applyToTag.bind(null, styleElement)
    remove = function () {
      styleElement.parentNode.removeChild(styleElement)
    }
  }

  update(obj)

  return function updateStyle (newObj /* StyleObjectPart */) {
    if (newObj) {
      if (newObj.css === obj.css &&
          newObj.media === obj.media &&
          newObj.sourceMap === obj.sourceMap) {
        return
      }
      update(obj = newObj)
    } else {
      remove()
    }
  }
}

var replaceText = (function () {
  var textStore = []

  return function (index, replacement) {
    textStore[index] = replacement
    return textStore.filter(Boolean).join('\n')
  }
})()

function applyToSingletonTag (styleElement, index, remove, obj) {
  var css = remove ? '' : obj.css

  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = replaceText(index, css)
  } else {
    var cssNode = document.createTextNode(css)
    var childNodes = styleElement.childNodes
    if (childNodes[index]) styleElement.removeChild(childNodes[index])
    if (childNodes.length) {
      styleElement.insertBefore(cssNode, childNodes[index])
    } else {
      styleElement.appendChild(cssNode)
    }
  }
}

function applyToTag (styleElement, obj) {
  var css = obj.css
  var media = obj.media
  var sourceMap = obj.sourceMap

  if (media) {
    styleElement.setAttribute('media', media)
  }

  if (sourceMap) {
    // https://developer.chrome.com/devtools/docs/javascript-debugging
    // this makes source maps inside style tags work properly in Chrome
    css += '\n/*# sourceURL=' + sourceMap.sources[0] + ' */'
    // http://stackoverflow.com/a/26603875
    css += '\n/*# sourceMappingURL=data:application/json;base64,' + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + ' */'
  }

  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = css
  } else {
    while (styleElement.firstChild) {
      styleElement.removeChild(styleElement.firstChild)
    }
    styleElement.appendChild(document.createTextNode(css))
  }
}

/***/ }),
/* 19 */
/***/ (function(module, exports) {

/**
 * Translates the list format produced by css-loader into something
 * easier to manipulate.
 */
module.exports = function listToStyles (parentId, list) {
  var styles = []
  var newStyles = {}
  for (var i = 0; i < list.length; i++) {
    var item = list[i]
    var id = item[0]
    var css = item[1]
    var media = item[2]
    var sourceMap = item[3]
    var part = {
      id: parentId + ':' + i,
      css: css,
      media: media,
      sourceMap: sourceMap
    }
    if (!newStyles[id]) {
      styles.push(newStyles[id] = { id: id, parts: [part] })
    } else {
      newStyles[id].parts.push(part)
    }
  }
  return styles
}

/***/ })
/******/ ]);
});
//# sourceMappingURL=index.js.map<|endoftext|>


<commit_before>import ScratchBlocks from 'scratch-blocks';

/**
 * Connect scratch blocks with the vm
 * @param {VirtualMachine} vm - The scratch vm
 * @return {ScratchBlocks} ScratchBlocks connected with the vm
 */
export default function (vm) {

    const jsonForMenuBlock = function (name, menuOptionsFn, colors, start) {
        return {
            message0: '%1',
            args0: [
                {
                    type: 'field_dropdown',
                    name: name,
                    options: function () {
                        return start.concat(menuOptionsFn());
                    }
                }
            ],
            inputsInline: true,
            output: 'String',
            colour: colors.secondary,
            colourSecondary: colors.secondary,
            colourTertiary: colors.tertiary,
            outputShape: ScratchBlocks.OUTPUT_SHAPE_ROUND
        };
    };

    const soundsMenu = function () {
        if (vm.editingTarget && vm.editingTarget.sprite.sounds.length > 0) {
            return vm.editingTarget.sprite.sounds.map(sound => [sound.name, sound.name]);
        }
        return [['', '']];
    };

    const costumesMenu = function () {
        if (vm.editingTarget && vm.editingTarget.sprite.costumes.length > 0) {
            return vm.editingTarget.sprite.costumes.map(costume => [costume.name, costume.name]);
        }
        return [['', '']];
    };

    const backdropsMenu = function () {
        if (vm.runtime.targets[0] && vm.runtime.targets[0].sprite.costumes.length > 0) {
            var a = vm.runtime.targets[0].sprite.costumes.map(costume => [costume.name, costume.name]);
            a.push(["next backdrop", "next backdrop"], ["previous backdrop", "previous backdrop"]);
            return a;
        }
        return [['', '']];
    };

    const spriteMenu = function () {
        const sprites = [];
        for (const targetId in vm.runtime.targets) {
            if (!vm.runtime.targets.hasOwnProperty(targetId)) continue;
            if (vm.runtime.targets[targetId].isOriginal) {
                if (!vm.runtime.targets[targetId].isStage) {
                    if (vm.runtime.targets[targetId] === vm.editingTarget) {
                        continue;
                    }
                    sprites.push([vm.runtime.targets[targetId].sprite.name, vm.runtime.targets[targetId].sprite.name]);
                }
            }
        }
        return sprites;
    };

    const cloneMenu = function () {
        if (vm.editingTarget && vm.editingTarget.isStage) {
            const menu = spriteMenu();
            if (menu.length === 0) {
                return [['', '']]; // Empty menu matches Scratch 2 behavior
            }
            return menu;
        }
        return [['myself', '_myself_']].concat(spriteMenu());
    };

    const soundColors = ScratchBlocks.Colours.sounds;

    const looksColors = ScratchBlocks.Colours.looks;

    const motionColors = ScratchBlocks.Colours.motion;

    const sensingColors = ScratchBlocks.Colours.sensing;

    const controlColors = ScratchBlocks.Colours.control;

    ScratchBlocks.Blocks.sound_sounds_menu.init = function () {
        const json = jsonForMenuBlock('SOUND_MENU', soundsMenu, soundColors, []);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.looks_costume.init = function () {
        const json = jsonForMenuBlock('COSTUME', costumesMenu, looksColors, []);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.looks_backdrops.init = function () {
        const json = jsonForMenuBlock('BACKDROP', backdropsMenu, looksColors, []);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.motion_pointtowards_menu.init = function () {
        const json = jsonForMenuBlock('TOWARDS', spriteMenu, motionColors, [
            ['mouse-pointer', '_mouse_']
        ]);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.motion_goto_menu.init = function () {
        const json = jsonForMenuBlock('TO', spriteMenu, motionColors, [
            ['random position', '_random_'],
            ['mouse-pointer', '_mouse_']
        ]);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.motion_glideto_menu.init = function () {
        const json = jsonForMenuBlock('TO', spriteMenu, motionColors, [
            ['random position', '_random_'],
            ['mouse-pointer', '_mouse_']
        ]);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.sensing_of_object_menu.init = function () {
        const json = jsonForMenuBlock('OBJECT', spriteMenu, sensingColors, [
            ['Stage', '_stage_']
        ]);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.sensing_videoonmenutwo.init = function () {
        const json = jsonForMenuBlock('VIDEOONMENU2', spriteMenu, sensingColors, [
            ['stage', 'STAGE']
        ]);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.sensing_distancetomenu.init = function () {
        const json = jsonForMenuBlock('DISTANCETOMENU', spriteMenu, sensingColors, [
            ['mouse-pointer', '_mouse_']
        ]);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.sensing_touchingobjectmenu.init = function () {
        const json = jsonForMenuBlock('TOUCHINGOBJECTMENU', spriteMenu, sensingColors, [
            ['mouse-pointer', '_mouse_'],
            ['edge', '_edge_']
        ]);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.control_create_clone_of_menu.init = function () {
        const json = jsonForMenuBlock('CLONE_OPTION', cloneMenu, controlColors, []);
        this.jsonInit(json);
    };

    ScratchBlocks.VerticalFlyout.getCheckboxState = function (blockId) {
        const monitoredBlock = vm.runtime.monitorBlocks._blocks[blockId];
        return monitoredBlock ? monitoredBlock.isMonitored : false;
    };

    return ScratchBlocks;
}
<commit_msg>Single quotes on strings<commit_after>import ScratchBlocks from 'scratch-blocks';

/**
 * Connect scratch blocks with the vm
 * @param {VirtualMachine} vm - The scratch vm
 * @return {ScratchBlocks} ScratchBlocks connected with the vm
 */
export default function (vm) {

    const jsonForMenuBlock = function (name, menuOptionsFn, colors, start) {
        return {
            message0: '%1',
            args0: [
                {
                    type: 'field_dropdown',
                    name: name,
                    options: function () {
                        return start.concat(menuOptionsFn());
                    }
                }
            ],
            inputsInline: true,
            output: 'String',
            colour: colors.secondary,
            colourSecondary: colors.secondary,
            colourTertiary: colors.tertiary,
            outputShape: ScratchBlocks.OUTPUT_SHAPE_ROUND
        };
    };

    const soundsMenu = function () {
        if (vm.editingTarget && vm.editingTarget.sprite.sounds.length > 0) {
            return vm.editingTarget.sprite.sounds.map(sound => [sound.name, sound.name]);
        }
        return [['', '']];
    };

    const costumesMenu = function () {
        if (vm.editingTarget && vm.editingTarget.sprite.costumes.length > 0) {
            return vm.editingTarget.sprite.costumes.map(costume => [costume.name, costume.name]);
        }
        return [['', '']];
    };

    const backdropsMenu = function () {
        if (vm.runtime.targets[0] && vm.runtime.targets[0].sprite.costumes.length > 0) {
            var a = vm.runtime.targets[0].sprite.costumes.map(costume => [costume.name, costume.name]);
            a.push(['next backdrop', 'next backdrop'], ['previous backdrop', 'previous backdrop']);
            return a;
        }
        return [['', '']];
    };

    const spriteMenu = function () {
        const sprites = [];
        for (const targetId in vm.runtime.targets) {
            if (!vm.runtime.targets.hasOwnProperty(targetId)) continue;
            if (vm.runtime.targets[targetId].isOriginal) {
                if (!vm.runtime.targets[targetId].isStage) {
                    if (vm.runtime.targets[targetId] === vm.editingTarget) {
                        continue;
                    }
                    sprites.push([vm.runtime.targets[targetId].sprite.name, vm.runtime.targets[targetId].sprite.name]);
                }
            }
        }
        return sprites;
    };

    const cloneMenu = function () {
        if (vm.editingTarget && vm.editingTarget.isStage) {
            const menu = spriteMenu();
            if (menu.length === 0) {
                return [['', '']]; // Empty menu matches Scratch 2 behavior
            }
            return menu;
        }
        return [['myself', '_myself_']].concat(spriteMenu());
    };

    const soundColors = ScratchBlocks.Colours.sounds;

    const looksColors = ScratchBlocks.Colours.looks;

    const motionColors = ScratchBlocks.Colours.motion;

    const sensingColors = ScratchBlocks.Colours.sensing;

    const controlColors = ScratchBlocks.Colours.control;

    ScratchBlocks.Blocks.sound_sounds_menu.init = function () {
        const json = jsonForMenuBlock('SOUND_MENU', soundsMenu, soundColors, []);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.looks_costume.init = function () {
        const json = jsonForMenuBlock('COSTUME', costumesMenu, looksColors, []);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.looks_backdrops.init = function () {
        const json = jsonForMenuBlock('BACKDROP', backdropsMenu, looksColors, []);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.motion_pointtowards_menu.init = function () {
        const json = jsonForMenuBlock('TOWARDS', spriteMenu, motionColors, [
            ['mouse-pointer', '_mouse_']
        ]);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.motion_goto_menu.init = function () {
        const json = jsonForMenuBlock('TO', spriteMenu, motionColors, [
            ['random position', '_random_'],
            ['mouse-pointer', '_mouse_']
        ]);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.motion_glideto_menu.init = function () {
        const json = jsonForMenuBlock('TO', spriteMenu, motionColors, [
            ['random position', '_random_'],
            ['mouse-pointer', '_mouse_']
        ]);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.sensing_of_object_menu.init = function () {
        const json = jsonForMenuBlock('OBJECT', spriteMenu, sensingColors, [
            ['Stage', '_stage_']
        ]);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.sensing_videoonmenutwo.init = function () {
        const json = jsonForMenuBlock('VIDEOONMENU2', spriteMenu, sensingColors, [
            ['stage', 'STAGE']
        ]);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.sensing_distancetomenu.init = function () {
        const json = jsonForMenuBlock('DISTANCETOMENU', spriteMenu, sensingColors, [
            ['mouse-pointer', '_mouse_']
        ]);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.sensing_touchingobjectmenu.init = function () {
        const json = jsonForMenuBlock('TOUCHINGOBJECTMENU', spriteMenu, sensingColors, [
            ['mouse-pointer', '_mouse_'],
            ['edge', '_edge_']
        ]);
        this.jsonInit(json);
    };

    ScratchBlocks.Blocks.control_create_clone_of_menu.init = function () {
        const json = jsonForMenuBlock('CLONE_OPTION', cloneMenu, controlColors, []);
        this.jsonInit(json);
    };

    ScratchBlocks.VerticalFlyout.getCheckboxState = function (blockId) {
        const monitoredBlock = vm.runtime.monitorBlocks._blocks[blockId];
        return monitoredBlock ? monitoredBlock.isMonitored : false;
    };

    return ScratchBlocks;
}
<|endoftext|>