<commit_before>SceneJS.Services.addService(
        SceneJS.Services.COMMAND_SERVICE_ID,
        (function() {
            var commands = {};
            return {

                addCommand: function(commandId, command) {
                    if (!command.execute) {
                        throw  SceneJS_errorModule.fatalError("SceneJS Command Service (ID '"
                                + SceneJS.Services.COMMAND_SERVICE_ID
                                + ") requires an 'execute' method on your '" + commandId + " command implementation");
                    }
                    commands[commandId] = command;
                },

                hasCommand: function(commandId) {
                    var command = commands[commandId];
                    return (command != null && command != undefined);
                },

                getCommand: function(commandId) {
                    return commands[commandId];
                },

                executeCommand : function (ctx, params) {
                    if (!params) {
                        throw  SceneJS_errorModule.fatalError("sendMessage param 'message' null or undefined");
                    }
                    var commandId = params.command;
                    if (!commandId) {
                        throw  SceneJS_errorModule.fatalError("Message element expected: 'command'");
                    }
                    var commandService = SceneJS.Services.getService(SceneJS.Services.COMMAND_SERVICE_ID);
                    var command = commandService.getCommand(commandId);

                    if (!command) {
                        throw  SceneJS_errorModule.fatalError("Message command not supported: '" + commandId + "' - perhaps this command needs to be added to the SceneJS Command Service?");
                    }
                    command.execute(ctx, params);
                }
            };
        })());

(function() {
    var commandService = SceneJS.Services.getService(SceneJS.Services.COMMAND_SERVICE_ID);

    function createNodes(scene, target, nodes) {
        var node;
        var targetNode;
        for (var i = 0; i < nodes.length; i++) {
            node = nodes[i];
            if (target) {
                targetNode = scene.findNode(target);
                if (!targetNode) {
                    continue;
                }
                targetNode.add("node", nodes[i]);
            } else {
                scene.addNode(nodes[i]);
            }
        }
    }

    commandService.addCommand("create",
            (function() {
                return {
                    execute: function(ctx, params) {
                        var nodes = params.nodes;

                        if (nodes) {

                            var target = params.target;
                            var scenes;
                            var scene;

                            if (ctx.scenes) {
                                scenes = ctx.scenes;
                                for (var i = 0, len = scenes.length; i < len; i++) {
                                    scene = scenes[i];
                                    if (scene) { // Scene might have been blown away by some other command
                                        createNodes(scene, target, nodes);
                                    }
                                }

                            } else {
                                scenes = SceneJS._scenes;
                                for (var sceneId in scenes) {
                                    if (scenes.hasOwnProperty(sceneId)) {
                                        scene = scenes[sceneId];
                                        if (scene) { // Scene might have been blown away by some other command
                                            createNodes(scene, target, nodes);
                                        }
                                    }
                                }
                            }

                        }
                    }
                };
            })());

    function updateNode(scene, target, params) {
        var targetNode = scene.findNode(target);
        if (!targetNode) { // Node might have been blown away by some other command
            return;
        }
        var sett = params["set"];
        if (sett) {
            callNodeMethods("set", sett, targetNode);
        }
        if (params.insert) {
            callNodeMethods("insert", params.insert, targetNode);
        }
        if (params.inc) {
            callNodeMethods("inc", params.inc, targetNode);
        }
        if (params.dec) {
            callNodeMethods("dec", params.dec, targetNode);
        }
        if (params.add) {
            callNodeMethods("add", params.add, targetNode);
        }
        if (params.remove) {
            callNodeMethods("remove", params.remove, targetNode);
        }
    }

    commandService.addCommand("update", {
        execute: function(ctx, params) {

            var scenes;
            var target = params.target;
            var scene;

            if (ctx.scenes) {
                scenes = ctx.scenes;
                for (var i = 0, len = scenes.length; i < len; i++) {
                    scene = scenes[i];
                    if (scene) { // Scene might have been blown away by some other command
                        updateNode(scene, target, params);
                    }
                }

            } else {

                scenes = SceneJS._scenes;
                for (var sceneId in scenes) {
                    if (scenes.hasOwnProperty(sceneId)) {
                        scene = scenes[sceneId];
                        if (scene) { // Scene might have been blown away by some other command
                            updateNode(scene, target, params);
                        }
                    }
                }
            }

            /* Further messages
             */
            var messages = params.messages;
            if (messages && messages.length > 0) {
                for (var i = 0; i < messages.length; i++) {
                    commandService.executeCommand(ctx, messages[i]);
                }
            }
        }
    });

    commandService.addCommand("selectScenes", {
        execute: function(ctx, params) {
            var scenes = params.scenes;
            if (scenes) {

                /* Filter out the scenes that actually exist so sub-commands don't have to check
                 */
                var existingScenes = [];
                var sceneId;
                var scene;
                for (var i = 0, len = scenes.length; i < len; i++) {
                    sceneId = scenes[i];
                    if (SceneJS._scenes[sceneId]) {
                        existingScenes.push(SceneJS.scene(sceneId));
                    }
                }
                ctx = SceneJS._shallowClone(ctx);   // Feed scenes into command context for sub-messages
                ctx.scenes = existingScenes;
            }

            /* Further messages
             */
            var messages = params.messages;
            if (messages) {
                for (var i = 0; i < messages.length; i++) {
                    commandService.executeCommand(ctx, messages[i]);
                }
            }
        }
    });

    function callNodeMethods(prefix, attr, targetNode) {
        for (var key in attr) {
            if (attr.hasOwnProperty(key)) {
                targetNode[prefix](attr);
            }
        }
    }
})();

<commit_msg>avoid redeclaration of variables<commit_after>SceneJS.Services.addService(
        SceneJS.Services.COMMAND_SERVICE_ID,
        (function() {
            var commands = {};
            return {

                addCommand: function(commandId, command) {
                    if (!command.execute) {
                        throw  SceneJS_errorModule.fatalError("SceneJS Command Service (ID '"
                                + SceneJS.Services.COMMAND_SERVICE_ID
                                + ") requires an 'execute' method on your '" + commandId + " command implementation");
                    }
                    commands[commandId] = command;
                },

                hasCommand: function(commandId) {
                    var command = commands[commandId];
                    return (command != null && command != undefined);
                },

                getCommand: function(commandId) {
                    return commands[commandId];
                },

                executeCommand : function (ctx, params) {
                    if (!params) {
                        throw  SceneJS_errorModule.fatalError("sendMessage param 'message' null or undefined");
                    }
                    var commandId = params.command;
                    if (!commandId) {
                        throw  SceneJS_errorModule.fatalError("Message element expected: 'command'");
                    }
                    var commandService = SceneJS.Services.getService(SceneJS.Services.COMMAND_SERVICE_ID);
                    var command = commandService.getCommand(commandId);

                    if (!command) {
                        throw  SceneJS_errorModule.fatalError("Message command not supported: '" + commandId + "' - perhaps this command needs to be added to the SceneJS Command Service?");
                    }
                    command.execute(ctx, params);
                }
            };
        })());

(function() {
    var commandService = SceneJS.Services.getService(SceneJS.Services.COMMAND_SERVICE_ID);

    function createNodes(scene, target, nodes) {
        var node;
        var targetNode;
        for (var i = 0; i < nodes.length; i++) {
            node = nodes[i];
            if (target) {
                targetNode = scene.findNode(target);
                if (!targetNode) {
                    continue;
                }
                targetNode.add("node", nodes[i]);
            } else {
                scene.addNode(nodes[i]);
            }
        }
    }

    commandService.addCommand("create",
            (function() {
                return {
                    execute: function(ctx, params) {
                        var nodes = params.nodes;

                        if (nodes) {

                            var target = params.target;
                            var scenes;
                            var scene;

                            if (ctx.scenes) {
                                scenes = ctx.scenes;
                                for (var i = 0, len = scenes.length; i < len; i++) {
                                    scene = scenes[i];
                                    if (scene) { // Scene might have been blown away by some other command
                                        createNodes(scene, target, nodes);
                                    }
                                }

                            } else {
                                scenes = SceneJS._scenes;
                                for (var sceneId in scenes) {
                                    if (scenes.hasOwnProperty(sceneId)) {
                                        scene = scenes[sceneId];
                                        if (scene) { // Scene might have been blown away by some other command
                                            createNodes(scene, target, nodes);
                                        }
                                    }
                                }
                            }

                        }
                    }
                };
            })());

    function updateNode(scene, target, params) {
        var targetNode = scene.findNode(target);
        if (!targetNode) { // Node might have been blown away by some other command
            return;
        }
        var sett = params["set"];
        if (sett) {
            callNodeMethods("set", sett, targetNode);
        }
        if (params.insert) {
            callNodeMethods("insert", params.insert, targetNode);
        }
        if (params.inc) {
            callNodeMethods("inc", params.inc, targetNode);
        }
        if (params.dec) {
            callNodeMethods("dec", params.dec, targetNode);
        }
        if (params.add) {
            callNodeMethods("add", params.add, targetNode);
        }
        if (params.remove) {
            callNodeMethods("remove", params.remove, targetNode);
        }
    }

    commandService.addCommand("update", {
        execute: function(ctx, params) {

            var i, len;
            var scenes;
            var target = params.target;
            var scene;

            if (ctx.scenes) {
                scenes = ctx.scenes;
                for (i = 0, len = scenes.length; i < len; i++) {
                    scene = scenes[i];
                    if (scene) { // Scene might have been blown away by some other command
                        updateNode(scene, target, params);
                    }
                }

            } else {

                scenes = SceneJS._scenes;
                for (var sceneId in scenes) {
                    if (scenes.hasOwnProperty(sceneId)) {
                        scene = scenes[sceneId];
                        if (scene) { // Scene might have been blown away by some other command
                            updateNode(scene, target, params);
                        }
                    }
                }
            }

            /* Further messages
             */
            var messages = params.messages;
            if (messages && messages.length > 0) {
                for (i = 0; i < messages.length; i++) {
                    commandService.executeCommand(ctx, messages[i]);
                }
            }
        }
    });

    commandService.addCommand("selectScenes", {
        execute: function(ctx, params) {

            var i, len;
            var scenes = params.scenes;
            if (scenes) {

                /* Filter out the scenes that actually exist so sub-commands don't have to check
                 */
                var existingScenes = [];
                var sceneId;
                var scene;
                for (i = 0, len = scenes.length; i < len; i++) {
                    sceneId = scenes[i];
                    if (SceneJS._scenes[sceneId]) {
                        existingScenes.push(SceneJS.scene(sceneId));
                    }
                }
                ctx = SceneJS._shallowClone(ctx);   // Feed scenes into command context for sub-messages
                ctx.scenes = existingScenes;
            }

            /* Further messages
             */
            var messages = params.messages;
            if (messages) {
                for (i = 0; i < messages.length; i++) {
                    commandService.executeCommand(ctx, messages[i]);
                }
            }
        }
    });

    function callNodeMethods(prefix, attr, targetNode) {
        for (var key in attr) {
            if (attr.hasOwnProperty(key)) {
                targetNode[prefix](attr);
            }
        }
    }
})();

<|endoftext|>


<commit_before>const search = require("../../src/search")

describe('Search', function() {
    it('should not crash', function() {
        search.findParametersAndVariables({}, {}, "");
    });
});
<commit_msg>Test single-word research<commit_after>import {addNormalizedDescription, findParametersAndVariables} from '../../src/search'
import {equals} from "ramda"
import assert from "assert"

const parameters = addNormalizedDescription({
    'aah': {description: 'Allocation adulte handicapé'},
    'cotisation': {description: 'cotisation payée sur le salaire'},
    'salaire_de_base': {description: 'Salaire brut'},
});

describe('Search', function() {
    it('should filter variables that don’t contain the query', function() {
        const results = findParametersAndVariables(parameters, {}, 'salaire')
            .map(item => item.name);
        assert(equals(results, ['salaire_de_base', 'cotisation']))
    });
});
<|endoftext|>


<commit_before>var conv = Bitcoin.convert;

var    exodus = '36PrZ1KHYMpqSyAQXSG8VwbUiq2EogxLo2';

function mkrandom() {
    var r = [];
    while (r.length < 32) r.push(Math.floor(Math.random()*256));
    return r;
}

function pbkdf2(s) {
    if (typeof s != "string") s = conv.bytesToString(s);
    return conv.hexToBytes(CryptoJS.PBKDF2(s,s,{
                              hasher: CryptoJS.algo.SHA256,
                              iterations: 2000
                           }).toString());
}

function encrypt(key,data) {
    var iv = mkrandom().slice(0,16);
    if (typeof data == 'string')
        data = conv.stringToBytes(data);
    return iv.concat(slowAES.encrypt(data,slowAES.modeOfOperation.CBC,key,iv));
}

function decrypt(key,data) {
    var iv = data.slice(0,16),
        ctext = data.slice(16);
    return slowAES.decrypt(ctext,slowAES.modeOfOperation.CBC,key,iv);
}

function eth_privtoaddr(priv) {
    var pub = Bitcoin.ECKey(priv).getPub().export('bytes').slice(1),
        addr = conv.bytesToHex(binSHA3(pub).slice(12));
    return addr;
}

function getseed(encseed,pwkey,ethaddr) {
    var seed = conv.bytesToString(decrypt(pwkey,conv.hexToBytes(encseed))),
        ethpriv = binSHA3(seed),
        ethaddr2 = eth_privtoaddr(ethpriv);
    if (ethaddr != ethaddr2) throw("Incorrect password, try again");
    return seed;
}

function mkbackup(wallet,pwkey) {
    var seed = getseed(wallet.encseed,pwkey,wallet.ethaddr);
    return {
        withpw: conv.bytesToHex(encrypt(pwkey,seed)),
        withwallet: conv.bytesToHex(encrypt(wallet.bkp,seed))
    };
}

function bytesToWords(b) {
    var o = [];
    for (var i = 0; i < b.length; i += 4) {
        o.push(b[i] * 16777216 + b[i+1] * 65536 + b[i+2] * 256 + b[i+3]);
    }
    return CryptoJS.lib.WordArray.create(o);
}

function binSHA3(x) {
    if (typeof x != "string") x = bytesToWords(x);
    return conv.hexToBytes(CryptoJS.SHA3(x,{ outputLength: 256 }).toString());
}

function genwallet(seed,pwkey,email) {
    if (!seed) seed = mkrandom();
    var encseed = encrypt(pwkey,seed),
        ethpriv = binSHA3(seed),
        btcpriv = binSHA3(seed+'\x01'),
        ethaddr = eth_privtoaddr(ethpriv),
        btcaddr = Bitcoin.ECKey(btcpriv).getBitcoinAddress().toString(),
        bkp = binSHA3(seed+'\x02');
    return {
        encseed: conv.bytesToHex(encseed),
        bkp: conv.bytesToHex(bkp),
        ethaddr: ethaddr,
        btcaddr: btcaddr,
        email: email
    };
}

function recover_bkp_pw(bkp,pwkey) {
    return getseed(bkp.withpw,pwkey,bkp.ethaddr);
}

function recover_bkp_wallet(bkp,wallet) {
    return getseed(bkp.withpw,wallet.bkp,bkp.ethaddr);
}

function finalize(wallet,unspent,pwkey,amount) {
    // Check password
    var seed = getseed(wallet.encseed,pwkey,wallet.ethaddr);
    balance = unspent.reduce(function(t,o) { return t + o.value; },0);
    if (balance < amount*100000000)
        return false;
    console.log('using unspent outputs:', unspent);
    var outputs = [
        exodus + ':' + (balance - 30000),
        Bitcoin.Address(wallet.ethaddr).toString() + ':10000'
    ];
    var btcpriv = Bitcoin.ECKey(binSHA3(seed+'\x01'));
    var tx = Bitcoin.Transaction();
    unspent.map(function(u) { tx.addInput(u.output);});
    outputs.map(function(o) { tx.addOutput(o);});
    unspent.map(function(u,i) {
        tx.sign(i,btcpriv);
    });
    // console.log(tx);
    return tx;
}
<commit_msg>removed amount check<commit_after>var conv = Bitcoin.convert;

var    exodus = '36PrZ1KHYMpqSyAQXSG8VwbUiq2EogxLo2';

function mkrandom() {
    var r = [];
    while (r.length < 32) r.push(Math.floor(Math.random()*256));
    return r;
}

function pbkdf2(s) {
    if (typeof s != "string") s = conv.bytesToString(s);
    return conv.hexToBytes(CryptoJS.PBKDF2(s,s,{
                              hasher: CryptoJS.algo.SHA256,
                              iterations: 2000
                           }).toString());
}

function encrypt(key,data) {
    var iv = mkrandom().slice(0,16);
    if (typeof data == 'string')
        data = conv.stringToBytes(data);
    return iv.concat(slowAES.encrypt(data,slowAES.modeOfOperation.CBC,key,iv));
}

function decrypt(key,data) {
    var iv = data.slice(0,16),
        ctext = data.slice(16);
    return slowAES.decrypt(ctext,slowAES.modeOfOperation.CBC,key,iv);
}

function eth_privtoaddr(priv) {
    var pub = Bitcoin.ECKey(priv).getPub().export('bytes').slice(1),
        addr = conv.bytesToHex(binSHA3(pub).slice(12));
    return addr;
}

function getseed(encseed,pwkey,ethaddr) {
    var seed = conv.bytesToString(decrypt(pwkey,conv.hexToBytes(encseed))),
        ethpriv = binSHA3(seed),
        ethaddr2 = eth_privtoaddr(ethpriv);
    if (ethaddr != ethaddr2) throw("Incorrect password, try again");
    return seed;
}

function mkbackup(wallet,pwkey) {
    var seed = getseed(wallet.encseed,pwkey,wallet.ethaddr);
    return {
        withpw: conv.bytesToHex(encrypt(pwkey,seed)),
        withwallet: conv.bytesToHex(encrypt(wallet.bkp,seed))
    };
}

function bytesToWords(b) {
    var o = [];
    for (var i = 0; i < b.length; i += 4) {
        o.push(b[i] * 16777216 + b[i+1] * 65536 + b[i+2] * 256 + b[i+3]);
    }
    return CryptoJS.lib.WordArray.create(o);
}

function binSHA3(x) {
    if (typeof x != "string") x = bytesToWords(x);
    return conv.hexToBytes(CryptoJS.SHA3(x,{ outputLength: 256 }).toString());
}

function genwallet(seed,pwkey,email) {
    if (!seed) seed = mkrandom();
    var encseed = encrypt(pwkey,seed),
        ethpriv = binSHA3(seed),
        btcpriv = binSHA3(seed+'\x01'),
        ethaddr = eth_privtoaddr(ethpriv),
        btcaddr = Bitcoin.ECKey(btcpriv).getBitcoinAddress().toString(),
        bkp = binSHA3(seed+'\x02');
    return {
        encseed: conv.bytesToHex(encseed),
        bkp: conv.bytesToHex(bkp),
        ethaddr: ethaddr,
        btcaddr: btcaddr,
        email: email
    };
}

function recover_bkp_pw(bkp,pwkey) {
    return getseed(bkp.withpw,pwkey,bkp.ethaddr);
}

function recover_bkp_wallet(bkp,wallet) {
    return getseed(bkp.withpw,wallet.bkp,bkp.ethaddr);
}

function finalize(wallet,unspent,pwkey,amount) {
    // Check password
    var seed = getseed(wallet.encseed,pwkey,wallet.ethaddr);
    balance = unspent.reduce(function(t,o) { return t + o.value; },0);
    if (balance < 100000000)
        return false;
    console.log('using unspent outputs:', unspent);
    var outputs = [
        exodus + ':' + (balance - 30000),
        Bitcoin.Address(wallet.ethaddr).toString() + ':10000'
    ];
    var btcpriv = Bitcoin.ECKey(binSHA3(seed+'\x01'));
    var tx = Bitcoin.Transaction();
    unspent.map(function(u) { tx.addInput(u.output);});
    outputs.map(function(o) { tx.addOutput(o);});
    unspent.map(function(u,i) {
        tx.sign(i,btcpriv);
    });
    // console.log(tx);
    return tx;
}
<|endoftext|>


<commit_before>/** @jsx React.DOM */
var socket = io();

var data = {
    listeners: [],
    subscribe: function(func) {
        this.listeners.push(func);
    },
    unSubscribe: function(func) {
        var index = this.listeners.indexOf(func);
        if (index > -1) {
            this.listeners.splice(index, 1);
        }
    },
    publish: function(data) {
        this.listeners.forEach(function(listener) {
            listener(data);
        });
    }
};

socket.on('quiz result', function(msg){
    console.log('message: ' + msg);
});

var joined = false;
socket.on('ready?', function(mesg) {
    data.publish({mode: 'ready'});
});

socket.on('next?', function(mesg) {
    data.publish({mode: 'next'});
});

socket.on('wait', function(msg) {
    data.publish({mode: 'wait'});
});

socket.on('next game', function(gameType) {
    console.log('gameType: ' + gameType);
    data.publish({mode: gameType});
});

socket.on('game over', function(players) {
    data.publish({mode: 'gameOver'});
    socket.emit('leave', true);
    joined = false;
});

var Join = React.createClass({
    getInitialState: function() {
        return {name: null};
    },
    handleNameChanged: function(e) {
        var name = e.target.value;
        this.setState({name: name});
        e.preventDefault();
    },
    handleOnSubmit: function(e) {
        if(this.state.name) {
            joined = true;
            socket.emit('join', this.state.name);
        }
    },
    render: function() {
        var name = this.state.name;
        return (

Velg ditt brukernavn:

                    <input id="username" className="username form-control" type="text" placeholder="Brukernavn" value={name} onChange={this.handleNameChanged}/>

                        <button id="join" type="submit" className="btn btn-success" onClick={this.handleOnSubmit}>GO!</button>

        );
    }
});

var Ready = React.createClass({
    handleReady: function(e) {
        socket.emit('ready', true);
        data.publish({mode: 'wait'});
    },
    render: function() {
        return (

                    <button id="ready" type="submit" className="btn btn-primary btn-lg" onClick={this.handleReady}>Ready to rumble!</button>

        );
    }
});

var Waiting = React.createClass({
    render: function() {
        return (

Waiting..

        );
    }
});

var Next = React.createClass({
    handleReady: function(e) {
        socket.emit('next', true);
        data.publish({mode: 'wait'});
    },
    render: function() {
        return (

                    <button id="next" type="submit" className="btn btn-primary btn-lg" onClick={this.handleReady}>Next!</button>

        );
    }
});

var GameOver = React.createClass({
    render: function() {
        return (

                GAME OVER!

        );
    }
});

var Quiz = React.createClass({
    handleClick: function(e) {
        var color = e.target.id;
        socket.emit('quiz answer', color);
        data.publish({mode: 'wait'});
    },
    render: function() {
        return (

                    <button id="red" className="col-xs-6" onClick={this.handleClick}></button>
                    <button id="green" className="col-xs-6" onClick={this.handleClick}></button>
                    <button id="blue" className="col-xs-6" onClick={this.handleClick}></button>
                    <button id="yellow" className="col-xs-6" onClick={this.handleClick}></button>

        );
    }
});

var PsychOut = React.createClass({
   handleClick: function(e){
       socket.emit('psych out answer', true);
       data.publish({mode: 'wait'});
   },
    render: function(){
        return <button className="col-xs-12" onClick={this.handleClick}></button>
    }
});

var GameClient = React.createClass({
    modes: {
        join: <Join />,
        ready: <Ready />,
        next: <Next />,
        wait: <Waiting />,
        quiz: <Quiz />,
        gameOver: <GameOver />
    },
    selectMode: function(mode) {
        if(joined) {
            var modeComponent = this.modes[mode];
            if(!modeComponent) {
                console.err(mode + ' not found');
                modeComponent = this.modes.wait;
            }
            return modeComponent;
        } else {
            return this.modes.join;
        }
    },
    getInitialState: function() {
        return {mode: 'join'};
    },
    componentDidMount: function() {
        data.subscribe(this.handleData);
    },
    componentWillUnmount: function() {
        data.unSubscribe(this.handleData);
    },
    handleData: function(data) {
        if(data.mode) {
            this.setState({mode: data.mode});
        }
    },
    render: function() {
        var mode = this.selectMode(this.state.mode);
        return (

                {mode}

        );
    }
});

React.renderComponent(<GameClient/>, document.getElementById('content'));
<commit_msg>sentrerte 'game over'<commit_after>/** @jsx React.DOM */
var socket = io();

var data = {
    listeners: [],
    subscribe: function(func) {
        this.listeners.push(func);
    },
    unSubscribe: function(func) {
        var index = this.listeners.indexOf(func);
        if (index > -1) {
            this.listeners.splice(index, 1);
        }
    },
    publish: function(data) {
        this.listeners.forEach(function(listener) {
            listener(data);
        });
    }
};

socket.on('quiz result', function(msg){
    console.log('message: ' + msg);
});

var joined = false;
socket.on('ready?', function(mesg) {
    data.publish({mode: 'ready'});
});

socket.on('next?', function(mesg) {
    data.publish({mode: 'next'});
});

socket.on('wait', function(msg) {
    data.publish({mode: 'wait'});
});

socket.on('next game', function(gameType) {
    console.log('gameType: ' + gameType);
    data.publish({mode: gameType});
});

socket.on('game over', function(players) {
    data.publish({mode: 'gameOver'});
    socket.emit('leave', true);
    joined = false;
});

var Join = React.createClass({
    getInitialState: function() {
        return {name: null};
    },
    handleNameChanged: function(e) {
        var name = e.target.value;
        this.setState({name: name});
        e.preventDefault();
    },
    handleOnSubmit: function(e) {
        if(this.state.name) {
            joined = true;
            socket.emit('join', this.state.name);
        }
    },
    render: function() {
        var name = this.state.name;
        return (

Velg ditt brukernavn:

                    <input id="username" className="username form-control" type="text" placeholder="Brukernavn" value={name} onChange={this.handleNameChanged}/>

                        <button id="join" type="submit" className="btn btn-success" onClick={this.handleOnSubmit}>GO!</button>

        );
    }
});

var Ready = React.createClass({
    handleReady: function(e) {
        socket.emit('ready', true);
        data.publish({mode: 'wait'});
    },
    render: function() {
        return (

                    <button id="ready" type="submit" className="btn btn-primary btn-lg" onClick={this.handleReady}>Ready to rumble!</button>

        );
    }
});

var Waiting = React.createClass({
    render: function() {
        return (

Waiting..

        );
    }
});

var Next = React.createClass({
    handleReady: function(e) {
        socket.emit('next', true);
        data.publish({mode: 'wait'});
    },
    render: function() {
        return (

                    <button id="next" type="submit" className="btn btn-primary btn-lg" onClick={this.handleReady}>Next!</button>

        );
    }
});

var GameOver = React.createClass({
    render: function() {
        return (

GAME OVER!

        );
    }
});

var Quiz = React.createClass({
    handleClick: function(e) {
        var color = e.target.id;
        socket.emit('quiz answer', color);
        data.publish({mode: 'wait'});
    },
    render: function() {
        return (

                    <button id="red" className="col-xs-6" onClick={this.handleClick}></button>
                    <button id="green" className="col-xs-6" onClick={this.handleClick}></button>
                    <button id="blue" className="col-xs-6" onClick={this.handleClick}></button>
                    <button id="yellow" className="col-xs-6" onClick={this.handleClick}></button>

        );
    }
});

var PsychOut = React.createClass({
   handleClick: function(e){
       socket.emit('psych out answer', true);
       data.publish({mode: 'wait'});
   },
    render: function(){
        return <button className="col-xs-12" onClick={this.handleClick}></button>
    }
});

var GameClient = React.createClass({
    modes: {
        join: <Join />,
        ready: <Ready />,
        next: <Next />,
        wait: <Waiting />,
        quiz: <Quiz />,
        gameOver: <GameOver />
    },
    selectMode: function(mode) {
        if(joined) {
            var modeComponent = this.modes[mode];
            if(!modeComponent) {
                console.err(mode + ' not found');
                modeComponent = this.modes.wait;
            }
            return modeComponent;
        } else {
            return this.modes.join;
        }
    },
    getInitialState: function() {
        return {mode: 'join'};
    },
    componentDidMount: function() {
        data.subscribe(this.handleData);
    },
    componentWillUnmount: function() {
        data.unSubscribe(this.handleData);
    },
    handleData: function(data) {
        if(data.mode) {
            this.setState({mode: data.mode});
        }
    },
    render: function() {
        var mode = this.selectMode(this.state.mode);
        return (

                {mode}

        );
    }
});

React.renderComponent(<GameClient/>, document.getElementById('content'));
<|endoftext|>


<commit_before>const layoutTemplate = `

`;

const Articles = Backbone.Collection.extend({
  url: 'http://modelo.mobi:1337/articles'
});

const LayoutView = Marionette.LayoutView.extend({
  el: 'main',
  template: _.template(layoutTemplate),
  regions: {
    header: '#header',
    drawer: '#drawer',
    content: '#content',
    toast: '#toast'
  },
  onRender() {
    this.getRegion('content').show(new Marionette.Form({
      text: 'Eres mayor de edad?',
      buttons: [
        {
          label: 'SI',
          onClick: function() {
            $('.mdl-layout__drawer-button').css({ display: 'initial' });
            Backbone.history.navigate('/order', true);
          }
        },
        {
          label: 'NO',
          onClick: function() {
            document.location.href = 'http://www.google.com';
          }
        }
      ]
    }));
  }
});

const layout = new LayoutView();

layout.render();

layout.getRegion('drawer').show(new Marionette.Modelo.DrawerView({
  menu: [{
    label: '  Pedir ahora',
    href: '/order'
  }, {
    label: '  Historial de pedidos',
    href: '/orders'
  }, {
    label: '  Mi Perfil',
    href: '/profile'
  }, {
    label: '  Eventos',
    href: '/events'
  }],
  user: new Backbone.Model({ name: 'Barney', lastName: 'Gumble', image: 'http://assets.fxnetworks.com/shows/the-simpsons/photos/swsb_character_fact_barney_550x960.png' })
}));
//layout.getRegion('header').show(new Marionette.form());

const articles = new Articles();
const Router = Marionette.AppRouter.extend({
  appRoutes: {
    'order': 'order',
    'orders': 'orders',
    'events': 'events',
    'profile': 'profile'
  },
  controller: {
    order() {
      var self = this;
      this._showTotal = _.debounce(this._showTotal, 500);
      articles.fetch().done(function(){
        articles.listenTo(articles, 'change', self._showTotal);
      });
      layout.getRegion('content').show(new Marionette.ArticleList({ collection: articles }))
    },
    orders() {

    },
    events() {

    },
    profile() {

    },
    _showTotal: function() {
      var total = 0;
      articles.each(function(article){
        total+= parseFloat(article.get('currentPrice'));
      });
      total = total.toFixed(2);
      var showTotal = new Marionette.ShowTotal({
        total: total
      });
      layout.getRegion('toast').show(showTotal);
      $('#toast').addClass('active');
      setTimeout(function(){
        $('#toast').removeClass('active');
      }, 1600);
    }
  },
  onRoute: function () {
    if (document.body.querySelector('.mdl-layout__obfuscator.is-visible')) {
      document.body.querySelector('.mdl-layout__obfuscator.is-visible').click();
    }
  }
});

if (document.location.pathname != '/') {
  document.location.href = '/';
}

new Router();

Backbone.Intercept.start();
Backbone.history.start({
  pushState: true
});

const userChannel = Backbone.Radio.channel('user');

userChannel.on('joined', () => {
  console.log(pushcrew.subscriberId);
});

(function(p,u,s,h){
    p._pcq=p._pcq||[];
    p._pcq.push(['_currentTime',Date.now()]);
    p._pcq.push(['APIReady', () => {
      alert('1');
    }]);
    s=u.createElement('script');
    s.type='text/javascript';
    s.async=true;
    s.src='https://cdn.pushcrew.com/js/7a8474c7728d7f23e99c77939824f57e.js';
    h=u.getElementsByTagName('script')[0];
    h.parentNode.insertBefore(s,h);
})(window,document);
<commit_msg>INT show total fix background<commit_after>const layoutTemplate = `

`;

const Articles = Backbone.Collection.extend({
  url: 'http://modelo.mobi:1337/articles'
});

const LayoutView = Marionette.LayoutView.extend({
  el: 'main',
  template: _.template(layoutTemplate),
  regions: {
    header: '#header',
    drawer: '#drawer',
    content: '#content',
    toast: '#toast'
  },
  onRender() {
    this.getRegion('content').show(new Marionette.Form({
      text: 'Eres mayor de edad?',
      buttons: [
        {
          label: 'SI',
          onClick: function() {
            $('.mdl-layout__drawer-button').css({ display: 'initial' });
            Backbone.history.navigate('/order', true);
          }
        },
        {
          label: 'NO',
          onClick: function() {
            document.location.href = 'http://www.google.com';
          }
        }
      ]
    }));
  }
});

const layout = new LayoutView();

layout.render();

layout.getRegion('drawer').show(new Marionette.Modelo.DrawerView({
  menu: [{
    label: '  Pedir ahora',
    href: '/order'
  }, {
    label: '  Historial de pedidos',
    href: '/orders'
  }, {
    label: '  Mi Perfil',
    href: '/profile'
  }, {
    label: '  Eventos',
    href: '/events'
  }],
  user: new Backbone.Model({ name: 'Barney', lastName: 'Gumble', image: 'http://assets.fxnetworks.com/shows/the-simpsons/photos/swsb_character_fact_barney_550x960.png' })
}));
//layout.getRegion('header').show(new Marionette.form());

const articles = new Articles();
const Router = Marionette.AppRouter.extend({
  appRoutes: {
    'order': 'order',
    'orders': 'orders',
    'events': 'events',
    'profile': 'profile'
  },
  controller: {
    order() {
      var self = this;
      this._showTotal = _.debounce(this._showTotal.bind(this), 500);
      this._closeTotal = _.debounce(this._closeTotal, 1600);
      articles.fetch().done(function(){
        articles.listenTo(articles, 'change', self._showTotal);
      });
      layout.getRegion('content').show(new Marionette.ArticleList({ collection: articles }))
    },
    orders() {

    },
    events() {

    },
    profile() {

    },
    _showTotal: function() {
      var total = 0;
      articles.each(function(article){
        total+= parseFloat(article.get('currentPrice'));
      });
      total = total.toFixed(2);
      var showTotal = new Marionette.ShowTotal({
        total: total
      });
      layout.getRegion('toast').show(showTotal);
      $('#toast').addClass('active');
      this._closeTotal();
    },
    _closeTotal: function() {
      console.log('close total')
      $('#toast').removeClass('active');
    }
  },
  onRoute: function () {
    if (document.body.querySelector('.mdl-layout__obfuscator.is-visible')) {
      document.body.querySelector('.mdl-layout__obfuscator.is-visible').click();
    }
  }
});

if (document.location.pathname != '/') {
  document.location.href = '/';
}

new Router();

Backbone.Intercept.start();
Backbone.history.start({
  pushState: true
});

const userChannel = Backbone.Radio.channel('user');

userChannel.on('joined', () => {
  console.log(pushcrew.subscriberId);
});

(function(p,u,s,h){
    p._pcq=p._pcq||[];
    p._pcq.push(['_currentTime',Date.now()]);
    p._pcq.push(['APIReady', () => {
      alert('1');
    }]);
    s=u.createElement('script');
    s.type='text/javascript';
    s.async=true;
    s.src='https://cdn.pushcrew.com/js/7a8474c7728d7f23e99c77939824f57e.js';
    h=u.getElementsByTagName('script')[0];
    h.parentNode.insertBefore(s,h);
})(window,document);
<|endoftext|>


<commit_before>/**
 * Prepare a Webref package release pull request if needed.
 *
 * The pull request contains the diff as description, and bumps the version
 * patch number of the corresponding `package.json` file.
 *
 * Pre-requisites:
 * - The local repo must be up-to-date with the remote repo on GitHub. That is
 * typically the case when this script runs as part of a GitHub job.
 * - The current branch in the local repo should be the main branch.
 * - The `prepare-curated.js` and `prepare-packages.js` utilities must have
 * been run to generate the relevant data in the `packages` folder.
 *
 * If the PR is merged, the "release-package.js" job should run and actually
 * release the package at the commit on which the pre-release PR was based.
 *
 * If the PR is closed, nothing should happen.
 *
 * If a PR created by this script is still open, the script (force) updates the
 * PR.
 *
 * Possible TODO improvements:
 * - Invalidate or re-request review when PR is updated?
 */

const Octokit = require("./octokit");
const fs = require("fs");
const path = require("path");
const os = require("os");
const { execSync } = require("child_process");
const rimraf = require("rimraf");

// Repository to process
const owner = "w3c";
const repo = "webref";

// Current package version in npm
let latestReleasedVersion = "";

function btoa(str) {
  return Buffer.from(str).toString("base64");
}

/**
 * Compute diff between the released npm package and the contents of the repo
 *
 * @function
 * @param {String} type Package name. Must match one of the existing folder
 *  names under "packages" (e.g. "css", "elements", "idl")
 * @return {String} The results of running the diff. An empty string if contents
 *   match.
 */
function computeDiff(type) {
  // Install @webref package in tmp folder
  const tmpFolder = fs.mkdtempSync(path.join(os.tmpdir(), "webref-"));
  execSync(`npm install @webref/${type}`, {
    cwd: tmpFolder
  });

  // Extract released version (will be used in the body of the pre-release PR)
  latestReleasedVersion = require(path.join(tmpFolder, "node_modules", "@webref", type, "package.json")).version;

  // Diff does not take the package.json file into account because "npm install"
  // adds properties that start with "_" to that file which do not exist in the
  // repo version of the file.
  // The "diff" command exits with a non zero status code when there is a diff,
  // which would throw an exception. Final "echo" command turns that status
  // code to 0 to avoid the exception.
  const installedFiles = path.join(tmpFolder, "node_modules", "@webref", type);
  let diff = execSync(
    `diff ${installedFiles} packages/${type} --ignore-trailing-space --exclude=package.json --unified=3 || echo -n`,
    { encoding: "utf8" });

  // Diff includes added/removed files but they are hard to detect inline,
  // let's extract them and list them separately
  const reAdded = new RegExp(`^Only in packages/${type}: (.*)$`, "gm");
  const added = Array.from(diff.matchAll(reAdded)).map(res => res[1]);
  diff = diff.replace(reAdded, "");

  const reDeleted = new RegExp(`^Only in ${installedFiles.replace(/\\/g, "\\\\")}: (.*)$`, "gm");
  const deleted = Array.from(diff.matchAll(reDeleted)).map(res => res[1]);
  diff = diff.replace(reDeleted, "");

  // Clean up tmp folder
  try {
    rimraf.sync(tmpFolder);
  }
  catch {
  }

  // On Windows, the "echo -n" command actually outputs "-n"
  // Also replace tmp folder name and file date in diff to make it possible to
  // compare diff with diff that may already exist in a pending pre-release PR
  // Note the diff command doubles backslashes, which also need to be doubled
  // in the string passed to RegExp for them not to be interpreted (In practice,
  // these backslashes also only appear on Windows)
  // Note: Regexp to replace date looks for lines that start with "---" or "+++"
  // followed by the right path (that can sometimes be enclosed in double quotes
  // in Windows environments) and that ends with something that looks like a
  // full date with time and timezone offset.
  diff = diff
    .replace(/\-n\s*$/, "")
    .replace(new RegExp(tmpFolder.replace(/\\/g, "\\\\\\\\"), "g"), "webref")
    .replace(/^(\-\-\- "?webref[^" ]+?"?)\s+[\d\-\s:\.\+]+$/mg, "$1")
    .replace(/^(\+\+\+ "?packages[^" ]+?"?)\s+[\d\-\s:\.\+]+$/mg, "$1");

  // Prepend diff with new and deleted files
  diff = diff
    .replace(/\n+(diff --ignore-trailing-space )/g, "\n\n$1")
    .trim();

  if (deleted.length > 0) {
    diff = "Released package files that no longer exist in the repo:\n" +
      deleted.map(file => `- ${file}`).join("\n") +
      "\n\n" +
      diff;
  }

  if (added.length > 0) {
    diff = "New repo files that are not yet in the released package:\n" +
      added.map(file => `- ${file}`).join("\n") +
      "\n\n" +
      diff;
  }

  return diff;
}

/**
 * Create or update pre-release pull request
 *
 * @function
 * @param {String} type Package name. Must match one of the existing folder
 *  names under "packages" (e.g. "css", "elements", "idl")
 */
async function prepareRelease(type) {
  // Compute a reasonably unique ID
  const uid = (new Date()).toISOString().replace(/[\-T:\.Z]/g, "");

  console.log("Get latest commit on current branch");
  const latestCommitSha = execSync('git log -n 1 --pretty=format:"%H"', { encoding: 'utf8' }).trim();
  console.log(`- Current branch is at ${latestCommitSha}`);

  console.log();
  console.log("Get corresponding commit on curated branch");
  const latestCommitCuratedSha = execSync(
    `git log -n 1 --pretty=format:"%H" --grep="Publish curated data from ${latestCommitSha}" --branches`,
    { encoding: 'utf8' }).trim();
  if (latestCommitCuratedSha) {
    console.log(`- Corresponding commit on curated branch: ${latestCommitCuratedSha}`);
  }
  else {
    console.log(`- No corresponding commit on curated branch`);
    return;
  }

  // Note the reference to the commit on the curated branch is more than purely
  // informational. The `release-package.js` script will use it to tag the
  // commit when a package is released.
  const curatedRef = latestCommitCuratedSha ?
    ` triggered by curated data at ${latestCommitCuratedSha}` : '';

  console.log();
  console.log("Look for a pending pre-release PR");
  const searchResponse = await octokit.search.issuesAndPullRequests({
    q: `repo:${owner}/${repo} type:pr state:open head:release-${type}-`
  });
  const found = searchResponse?.data?.items?.[0];

  const pendingPRResponse = found ?
    await octokit.pulls.get({
      owner, repo,
      pull_number: found.number
    }) :
    null;
  const pendingPR = pendingPRResponse?.data;
  console.log(pendingPR ?
    `- Found pending pre-release PR: ${pendingPR.title} (#${pendingPR.number})` :
    "- No pending pre-release PR");

  console.log();
  console.log("Compute diff between package and repo contents");
  let diff = computeDiff(type);
  console.log(`- Diff length: ${diff?.length}`);
  if (!diff) {
    if (pendingPR) {
      console.log("- No release needed, close pending pre-release PR");
      await octokit.pulls.update({
        owner, repo, pull_number: pendingPR.number,
        body: "This pull request is no longer needed. No more diff to release.",
        state: "closed"
      });
    }

    console.log("- No diff found, return");
    return;
  }
  if (diff.length > 60000) {
    console.log("- Diff is too long, dump it to the console and truncate");
    console.log();
    console.log("----- DIFF BEGINS -----")
    console.log(diff);
    console.log("----- DIFF ENDS -----")
    diff = `IMPORTANT:
- Diff is too long to render in a PR description: ${diff.length} characters
- First 60000 characters shown below
- Check the action log for the full diff

${diff.substring(0, 60000)}`;
  }

  console.log();
  console.log("Extract and bump version number");
  const packageFile = require(`../packages/${type}/package.json`);
  const version = packageFile.version;
  const bumpedVersion = version
    .split(".")
    .map((nb, idx) => parseInt(nb, 10) + ((idx === 2) ? 1 : 0))
    .join(".");
  packageFile.version = bumpedVersion;
  const bumpedPackageFileContents = btoa(JSON.stringify(packageFile, null, 2));
  console.log(`- Version to release: ${version}`);
  console.log(`- Bumped version: ${bumpedVersion}`);

  console.log();
  console.log("Prepare pre-release PR title and body");
  const title = `📦 Release @webref/${type}@${version}`;
  const body = `
**⚠ NEVER add commits to this pull request.**

🤖 This pull request was automatically created to facilitate human review of \`@webref/${type}\` changes${curatedRef}.

🧐 Please review the diff below and version numbers. If all looks good, merge this pull request to release the changes to npm.

📦 Latest released \`@webref/${type}\` package was **v${latestReleasedVersion}**. Merging this pull request will release **v${version}**. Make sure that the bump is the right one for the changes.

✍ If any change needs to be made before release, **do not add a commit** to this pull request. Changes should rather be handled in a separate pull request and pushed to the main branch. You may leave this pull request open in the meantime, or close it. The pre-release job will automatically update this pull request or create a new one once the updates have made their way to the main branch.

🛈 The actual change introduced by this pull request is a version bump in \`packages/${type}/package.json\`. You do not need to review that change. The bumped version is not the version that will be released when this pull request is merged, but rather the version that will be released next time.

\`\`\`diff
${diff}
\`\`\``;
  console.log(`- title: ${title}`);

  console.log();
  console.log("Prepare branch for pre-release PR");
  const prRef = `release-${type}-${uid}`;
  const commitBumpedVersion =       // Create a new branch for the PR if:
    !pendingPR ||                   // 1. it does not exist yet; or
    pendingPR.title !== title ||    // 2. version to release has changed; or
    pendingPR.body !== body;        // 3. diff has changed
  if (commitBumpedVersion) {
    console.log(`- Create new branch ${prRef} for the PR`);
    await octokit.git.createRef({
      owner, repo,
      ref: `refs/heads/${prRef}`,
      sha: latestCommitSha
    });
  }
  else {
    console.log("- No additional changes to release, no need to rebase existing pre-release PR");
  }

  console.log();
  console.log("Commit bumped version to PR branch");
  if (commitBumpedVersion) {
    console.log(`- Bump version to ${bumpedVersion}`);
    const fileResponse = await octokit.repos.getContent({
      owner, repo, path: `packages/${type}/package.json`
    });

    const resp = await octokit.repos.createOrUpdateFileContents({
      owner, repo,
      branch: prRef,
      path: `packages/${type}/package.json`,
      message: `Bump @webref/${type} version from ${version} to ${bumpedVersion}`,
      content: bumpedPackageFileContents,
      sha: fileResponse.data.sha,
    });
    const bumpedVersionSha = resp.data.commit.sha;
    console.log(`- Bumped version commit is ${bumpedVersionSha}`);

    if (pendingPR) {
      // Note: when a pending PR exists, we could in theory reuse the PR branch
      // directly instead of creating (and then deleting) another one. However,
      // that would mean force updating that branch to the latest commit of the
      // main branch before adding a commit with the bumped version. The force
      // update would effectively close the PR (because the PR would then have
      // no commit).
      console.log(`- Force update PR branch ${pendingPR.head.ref} to target ${prRef} branch commit`);
      await octokit.git.updateRef({
        owner, repo,
        ref: `heads/${pendingPR.head.ref}`,
        sha: bumpedVersionSha, force: true
      });

      console.log(`- Delete now useless ${prRef} branch`);
      await octokit.git.deleteRef({
        owner, repo,
        ref: `heads/${prRef}`
      });
    }
  }
  else {
    console.log("- No need to bump version, PR already up-to-date");
  }

  console.log();
  console.log("Create/Update pre-release PR");
  if (pendingPR) {
    if (pendingPR.title === title && pendingPR.body === body) {
      console.log("- Pre-release PR already exists and no need to update title and body");
    }
    else {
      console.log("- Update title and body of existing pre-release PR");
      await octokit.pulls.update({
        owner, repo,
        pull_number: pendingPR.number,
        title, body
      });
    }
  }
  else {
    console.log("- Create pre-release PR");
    const defaultBranchResponse = await octokit.repos.get({ owner, repo });
    const defaultBranch = defaultBranchResponse.data.default_branch;
    const prResponse = await octokit.pulls.create({
      owner, repo,
      head: prRef,
      base: defaultBranch,
      title, body
    });
  }
}

/*******************************************************************************
Retrieve GH_TOKEN from environment, prepare Octokit and kick things off
*******************************************************************************/
const GH_TOKEN = (() => {
  try {
    return require("../config.json").GH_TOKEN;
  } catch {
    return process.env.GH_TOKEN;
  }
})();
if (!GH_TOKEN) {
  console.error("GH_TOKEN must be set to some personal access token as an env variable or in a config.json file");
  process.exit(1);
}

const octokit = new Octokit({
  auth: GH_TOKEN,
  //log: console
});

const packageType = process.argv[2] ?? "idl";

prepareRelease(packageType)
  .then(() => {
    console.log();
    console.log("== The end ==");
  })
  .catch(err => {
    console.error(err);
    process.exit(1);
  });<commit_msg>Mark new files in pre-release diff as an addition (#485)<commit_after>/**
 * Prepare a Webref package release pull request if needed.
 *
 * The pull request contains the diff as description, and bumps the version
 * patch number of the corresponding `package.json` file.
 *
 * Pre-requisites:
 * - The local repo must be up-to-date with the remote repo on GitHub. That is
 * typically the case when this script runs as part of a GitHub job.
 * - The current branch in the local repo should be the main branch.
 * - The `prepare-curated.js` and `prepare-packages.js` utilities must have
 * been run to generate the relevant data in the `packages` folder.
 *
 * If the PR is merged, the "release-package.js" job should run and actually
 * release the package at the commit on which the pre-release PR was based.
 *
 * If the PR is closed, nothing should happen.
 *
 * If a PR created by this script is still open, the script (force) updates the
 * PR.
 *
 * Possible TODO improvements:
 * - Invalidate or re-request review when PR is updated?
 */

const Octokit = require("./octokit");
const fs = require("fs");
const path = require("path");
const os = require("os");
const { execSync } = require("child_process");
const rimraf = require("rimraf");

// Repository to process
const owner = "w3c";
const repo = "webref";

// Current package version in npm
let latestReleasedVersion = "";

function btoa(str) {
  return Buffer.from(str).toString("base64");
}

/**
 * Compute diff between the released npm package and the contents of the repo
 *
 * @function
 * @param {String} type Package name. Must match one of the existing folder
 *  names under "packages" (e.g. "css", "elements", "idl")
 * @return {String} The results of running the diff. An empty string if contents
 *   match.
 */
function computeDiff(type) {
  // Install @webref package in tmp folder
  const tmpFolder = fs.mkdtempSync(path.join(os.tmpdir(), "webref-"));
  execSync(`npm install @webref/${type}`, {
    cwd: tmpFolder
  });

  // Extract released version (will be used in the body of the pre-release PR)
  latestReleasedVersion = require(path.join(tmpFolder, "node_modules", "@webref", type, "package.json")).version;

  // Diff does not take the package.json file into account because "npm install"
  // adds properties that start with "_" to that file which do not exist in the
  // repo version of the file.
  // The "diff" command exits with a non zero status code when there is a diff,
  // which would throw an exception. Final "echo" command turns that status
  // code to 0 to avoid the exception.
  const installedFiles = path.join(tmpFolder, "node_modules", "@webref", type);
  let diff = execSync(
    `diff ${installedFiles} packages/${type} --ignore-trailing-space --exclude=package.json --unified=3 || echo -n`,
    { encoding: "utf8" });

  // Diff includes added/removed files but they are hard to detect inline,
  // let's extract them and list them separately
  const reAdded = new RegExp(`^Only in packages/${type}: (.*)$`, "gm");
  const added = Array.from(diff.matchAll(reAdded)).map(res => res[1]);
  diff = diff.replace(reAdded, "");

  const reDeleted = new RegExp(`^Only in ${installedFiles.replace(/\\/g, "\\\\")}: (.*)$`, "gm");
  const deleted = Array.from(diff.matchAll(reDeleted)).map(res => res[1]);
  diff = diff.replace(reDeleted, "");

  // Clean up tmp folder
  try {
    rimraf.sync(tmpFolder);
  }
  catch {
  }

  // On Windows, the "echo -n" command actually outputs "-n"
  // Also replace tmp folder name and file date in diff to make it possible to
  // compare diff with diff that may already exist in a pending pre-release PR
  // Note the diff command doubles backslashes, which also need to be doubled
  // in the string passed to RegExp for them not to be interpreted (In practice,
  // these backslashes also only appear on Windows)
  // Note: Regexp to replace date looks for lines that start with "---" or "+++"
  // followed by the right path (that can sometimes be enclosed in double quotes
  // in Windows environments) and that ends with something that looks like a
  // full date with time and timezone offset.
  diff = diff
    .replace(/\-n\s*$/, "")
    .replace(new RegExp(tmpFolder.replace(/\\/g, "\\\\\\\\"), "g"), "webref")
    .replace(/^(\-\-\- "?webref[^" ]+?"?)\s+[\d\-\s:\.\+]+$/mg, "$1")
    .replace(/^(\+\+\+ "?packages[^" ]+?"?)\s+[\d\-\s:\.\+]+$/mg, "$1");

  // Prepend diff with new and deleted files
  diff = diff
    .replace(/\n+(diff --ignore-trailing-space )/g, "\n\n$1")
    .trim();

  if (deleted.length > 0) {
    diff = "Released package files that no longer exist in the repo:\n" +
      deleted.map(file => `- ${file}`).join("\n") +
      "\n\n" +
      diff;
  }

  if (added.length > 0) {
    diff = "New repo files that are not yet in the released package:\n" +
      added.map(file => `+ ${file}`).join("\n") +
      "\n\n" +
      diff;
  }

  return diff;
}

/**
 * Create or update pre-release pull request
 *
 * @function
 * @param {String} type Package name. Must match one of the existing folder
 *  names under "packages" (e.g. "css", "elements", "idl")
 */
async function prepareRelease(type) {
  // Compute a reasonably unique ID
  const uid = (new Date()).toISOString().replace(/[\-T:\.Z]/g, "");

  console.log("Get latest commit on current branch");
  const latestCommitSha = execSync('git log -n 1 --pretty=format:"%H"', { encoding: 'utf8' }).trim();
  console.log(`- Current branch is at ${latestCommitSha}`);

  console.log();
  console.log("Get corresponding commit on curated branch");
  const latestCommitCuratedSha = execSync(
    `git log -n 1 --pretty=format:"%H" --grep="Publish curated data from ${latestCommitSha}" --branches`,
    { encoding: 'utf8' }).trim();
  if (latestCommitCuratedSha) {
    console.log(`- Corresponding commit on curated branch: ${latestCommitCuratedSha}`);
  }
  else {
    console.log(`- No corresponding commit on curated branch`);
    return;
  }

  // Note the reference to the commit on the curated branch is more than purely
  // informational. The `release-package.js` script will use it to tag the
  // commit when a package is released.
  const curatedRef = latestCommitCuratedSha ?
    ` triggered by curated data at ${latestCommitCuratedSha}` : '';

  console.log();
  console.log("Look for a pending pre-release PR");
  const searchResponse = await octokit.search.issuesAndPullRequests({
    q: `repo:${owner}/${repo} type:pr state:open head:release-${type}-`
  });
  const found = searchResponse?.data?.items?.[0];

  const pendingPRResponse = found ?
    await octokit.pulls.get({
      owner, repo,
      pull_number: found.number
    }) :
    null;
  const pendingPR = pendingPRResponse?.data;
  console.log(pendingPR ?
    `- Found pending pre-release PR: ${pendingPR.title} (#${pendingPR.number})` :
    "- No pending pre-release PR");

  console.log();
  console.log("Compute diff between package and repo contents");
  let diff = computeDiff(type);
  console.log(`- Diff length: ${diff?.length}`);
  if (!diff) {
    if (pendingPR) {
      console.log("- No release needed, close pending pre-release PR");
      await octokit.pulls.update({
        owner, repo, pull_number: pendingPR.number,
        body: "This pull request is no longer needed. No more diff to release.",
        state: "closed"
      });
    }

    console.log("- No diff found, return");
    return;
  }
  if (diff.length > 60000) {
    console.log("- Diff is too long, dump it to the console and truncate");
    console.log();
    console.log("----- DIFF BEGINS -----")
    console.log(diff);
    console.log("----- DIFF ENDS -----")
    diff = `IMPORTANT:
- Diff is too long to render in a PR description: ${diff.length} characters
- First 60000 characters shown below
- Check the action log for the full diff

${diff.substring(0, 60000)}`;
  }

  console.log();
  console.log("Extract and bump version number");
  const packageFile = require(`../packages/${type}/package.json`);
  const version = packageFile.version;
  const bumpedVersion = version
    .split(".")
    .map((nb, idx) => parseInt(nb, 10) + ((idx === 2) ? 1 : 0))
    .join(".");
  packageFile.version = bumpedVersion;
  const bumpedPackageFileContents = btoa(JSON.stringify(packageFile, null, 2));
  console.log(`- Version to release: ${version}`);
  console.log(`- Bumped version: ${bumpedVersion}`);

  console.log();
  console.log("Prepare pre-release PR title and body");
  const title = `📦 Release @webref/${type}@${version}`;
  const body = `
**⚠ NEVER add commits to this pull request.**

🤖 This pull request was automatically created to facilitate human review of \`@webref/${type}\` changes${curatedRef}.

🧐 Please review the diff below and version numbers. If all looks good, merge this pull request to release the changes to npm.

📦 Latest released \`@webref/${type}\` package was **v${latestReleasedVersion}**. Merging this pull request will release **v${version}**. Make sure that the bump is the right one for the changes.

✍ If any change needs to be made before release, **do not add a commit** to this pull request. Changes should rather be handled in a separate pull request and pushed to the main branch. You may leave this pull request open in the meantime, or close it. The pre-release job will automatically update this pull request or create a new one once the updates have made their way to the main branch.

🛈 The actual change introduced by this pull request is a version bump in \`packages/${type}/package.json\`. You do not need to review that change. The bumped version is not the version that will be released when this pull request is merged, but rather the version that will be released next time.

\`\`\`diff
${diff}
\`\`\``;
  console.log(`- title: ${title}`);

  console.log();
  console.log("Prepare branch for pre-release PR");
  const prRef = `release-${type}-${uid}`;
  const commitBumpedVersion =       // Create a new branch for the PR if:
    !pendingPR ||                   // 1. it does not exist yet; or
    pendingPR.title !== title ||    // 2. version to release has changed; or
    pendingPR.body !== body;        // 3. diff has changed
  if (commitBumpedVersion) {
    console.log(`- Create new branch ${prRef} for the PR`);
    await octokit.git.createRef({
      owner, repo,
      ref: `refs/heads/${prRef}`,
      sha: latestCommitSha
    });
  }
  else {
    console.log("- No additional changes to release, no need to rebase existing pre-release PR");
  }

  console.log();
  console.log("Commit bumped version to PR branch");
  if (commitBumpedVersion) {
    console.log(`- Bump version to ${bumpedVersion}`);
    const fileResponse = await octokit.repos.getContent({
      owner, repo, path: `packages/${type}/package.json`
    });

    const resp = await octokit.repos.createOrUpdateFileContents({
      owner, repo,
      branch: prRef,
      path: `packages/${type}/package.json`,
      message: `Bump @webref/${type} version from ${version} to ${bumpedVersion}`,
      content: bumpedPackageFileContents,
      sha: fileResponse.data.sha,
    });
    const bumpedVersionSha = resp.data.commit.sha;
    console.log(`- Bumped version commit is ${bumpedVersionSha}`);

    if (pendingPR) {
      // Note: when a pending PR exists, we could in theory reuse the PR branch
      // directly instead of creating (and then deleting) another one. However,
      // that would mean force updating that branch to the latest commit of the
      // main branch before adding a commit with the bumped version. The force
      // update would effectively close the PR (because the PR would then have
      // no commit).
      console.log(`- Force update PR branch ${pendingPR.head.ref} to target ${prRef} branch commit`);
      await octokit.git.updateRef({
        owner, repo,
        ref: `heads/${pendingPR.head.ref}`,
        sha: bumpedVersionSha, force: true
      });

      console.log(`- Delete now useless ${prRef} branch`);
      await octokit.git.deleteRef({
        owner, repo,
        ref: `heads/${prRef}`
      });
    }
  }
  else {
    console.log("- No need to bump version, PR already up-to-date");
  }

  console.log();
  console.log("Create/Update pre-release PR");
  if (pendingPR) {
    if (pendingPR.title === title && pendingPR.body === body) {
      console.log("- Pre-release PR already exists and no need to update title and body");
    }
    else {
      console.log("- Update title and body of existing pre-release PR");
      await octokit.pulls.update({
        owner, repo,
        pull_number: pendingPR.number,
        title, body
      });
    }
  }
  else {
    console.log("- Create pre-release PR");
    const defaultBranchResponse = await octokit.repos.get({ owner, repo });
    const defaultBranch = defaultBranchResponse.data.default_branch;
    const prResponse = await octokit.pulls.create({
      owner, repo,
      head: prRef,
      base: defaultBranch,
      title, body
    });
  }
}

/*******************************************************************************
Retrieve GH_TOKEN from environment, prepare Octokit and kick things off
*******************************************************************************/
const GH_TOKEN = (() => {
  try {
    return require("../config.json").GH_TOKEN;
  } catch {
    return process.env.GH_TOKEN;
  }
})();
if (!GH_TOKEN) {
  console.error("GH_TOKEN must be set to some personal access token as an env variable or in a config.json file");
  process.exit(1);
}

const octokit = new Octokit({
  auth: GH_TOKEN,
  //log: console
});

const packageType = process.argv[2] ?? "idl";

prepareRelease(packageType)
  .then(() => {
    console.log();
    console.log("== The end ==");
  })
  .catch(err => {
    console.error(err);
    process.exit(1);
  });
<|endoftext|>


<commit_before>var wrappy = (typeof require !== "undefined") ? require("../wrappy.js") : window.wrappy,
    expect = require('chai').expect;

// shim node Promise
Promise = (typeof Promise !== "undefined") ? Promise : require("es6-promise").Promise,

//------------------------------------------------------------------------------
// Actual tests
//------------------------------------------------------------------------------

describe("Wrappy global object", function() {

    it("Should have 2 methods, wrappy.wrapMethod() and wrappy.wrapFunction()", function() {
        expect(wrappy).to.have.property('wrapMethod');
        expect(wrappy).to.have.property('wrapFunction');
    });

});

describe("Wrapping a method on an object", function() {

    var myObject;

    it("Should throw an error if incorrect arguments are passed", function() {

        expect(wrappy.wrapMethod).to.throw(Error);

        expect(function() {
            wrappy.wrapMethod('im a string');
        }).to.throw(Error);

        expect(function() {
            wrappy.wrapMethod(null, {});
        }).to.throw(Error);

        expect(function() {
            wrappy.wrapMethod(null, 'methodName');
        }).to.throw(Error);

    });

    // create test object and wrap it
    beforeEach(function() {

        myObject = {
            method1: function(val, promise) {

                if (val === 'resolveMe') {
                    promise.resolve(val + ' was resolved');
                }
                else {
                    promise.reject(val + ' was not resolved');
                }

            }
        };

        wrappy.wrapMethod(myObject, 'method1');

    });

    it("Should wrap original method as a promise proxy", function() {
        expect(myObject.method1.name).to.equal('promiseProxy');
    });

    it("Should be chainable with then() function", function() {
        expect(myObject.method1('resolveMe').then).to.exist;
    });

    it("Should resolve and pass any returned values to then()", function() {
        myObject.method1('resolveMe').then(function(result) {
           expect(result).to.equal('resolveMe was resolved');
        });
    });

    it("Should reject and pass any returned values to then()", function() {
        myObject.method1('random').then(function(result) {
           expect(result).to.equal('random was not resolved');
        });
    });

});

describe("Wrapping a function", function() {

    var myFunction;

    it("Should throw an error if incorrect arguments are passed", function() {

        expect(wrappy.wrapFunction).to.throw(Error);

        expect(function() {
            wrappy.wrapFunction('im a string');
        }).to.throw(Error);

        expect(function() {
            wrappy.wrapFunction({});
        }).to.throw(Error);

    });

    // create test function and wrap it
    beforeEach(function() {

        myFunction = function(val, promise) {

            if (val === 'resolveMe') {
                promise.resolve(val + ' was resolved');
            }
            else {
                promise.reject(val + ' was not resolved');
            }

        };

        myFunction = wrappy.wrapFunction(myFunction);

    });

    it("Should wrap original function as a promise proxy", function() {
        expect(myFunction.name).to.equal('promiseProxy');
    });

    it("Should be chainable with then() function", function() {
        expect(myFunction('resolveMe').then).to.exist;
    });

    it("Should resolve and pass any returned values to then()", function() {
        myFunction('resolveMe').then(function(result) {
           expect(result).to.equal('resolveMe was resolved');
        });
    });

    it("Should reject and pass any returned values to then()", function() {
        myFunction('random').then(function(result) {
           expect(result).to.equal('random was not resolved');
        });
    });

});

<commit_msg>comma should be line ending<commit_after>var wrappy = (typeof require !== "undefined") ? require("../wrappy.js") : window.wrappy,
    expect = require('chai').expect;

// shim node Promise
Promise = (typeof Promise !== "undefined") ? Promise : require("es6-promise").Promise;

//------------------------------------------------------------------------------
// Actual tests
//------------------------------------------------------------------------------

describe("Wrappy global object", function() {

    it("Should have 2 methods, wrappy.wrapMethod() and wrappy.wrapFunction()", function() {
        expect(wrappy).to.have.property('wrapMethod');
        expect(wrappy).to.have.property('wrapFunction');
    });

});

describe("Wrapping a method on an object", function() {

    var myObject;

    it("Should throw an error if incorrect arguments are passed", function() {

        expect(wrappy.wrapMethod).to.throw(Error);

        expect(function() {
            wrappy.wrapMethod('im a string');
        }).to.throw(Error);

        expect(function() {
            wrappy.wrapMethod(null, {});
        }).to.throw(Error);

        expect(function() {
            wrappy.wrapMethod(null, 'methodName');
        }).to.throw(Error);

    });

    // create test object and wrap it
    beforeEach(function() {

        myObject = {
            method1: function(val, promise) {

                if (val === 'resolveMe') {
                    promise.resolve(val + ' was resolved');
                }
                else {
                    promise.reject(val + ' was not resolved');
                }

            }
        };

        wrappy.wrapMethod(myObject, 'method1');

    });

    it("Should wrap original method as a promise proxy", function() {
        expect(myObject.method1.name).to.equal('promiseProxy');
    });

    it("Should be chainable with then() function", function() {
        expect(myObject.method1('resolveMe').then).to.exist;
    });

    it("Should resolve and pass any returned values to then()", function() {
        myObject.method1('resolveMe').then(function(result) {
           expect(result).to.equal('resolveMe was resolved');
        });
    });

    it("Should reject and pass any returned values to then()", function() {
        myObject.method1('random').then(function(result) {
           expect(result).to.equal('random was not resolved');
        });
    });

});

describe("Wrapping a function", function() {

    var myFunction;

    it("Should throw an error if incorrect arguments are passed", function() {

        expect(wrappy.wrapFunction).to.throw(Error);

        expect(function() {
            wrappy.wrapFunction('im a string');
        }).to.throw(Error);

        expect(function() {
            wrappy.wrapFunction({});
        }).to.throw(Error);

    });

    // create test function and wrap it
    beforeEach(function() {

        myFunction = function(val, promise) {

            if (val === 'resolveMe') {
                promise.resolve(val + ' was resolved');
            }
            else {
                promise.reject(val + ' was not resolved');
            }

        };

        myFunction = wrappy.wrapFunction(myFunction);

    });

    it("Should wrap original function as a promise proxy", function() {
        expect(myFunction.name).to.equal('promiseProxy');
    });

    it("Should be chainable with then() function", function() {
        expect(myFunction('resolveMe').then).to.exist;
    });

    it("Should resolve and pass any returned values to then()", function() {
        myFunction('resolveMe').then(function(result) {
           expect(result).to.equal('resolveMe was resolved');
        });
    });

    it("Should reject and pass any returned values to then()", function() {
        myFunction('random').then(function(result) {
           expect(result).to.equal('random was not resolved');
        });
    });

});

<|endoftext|>


<commit_before><commit_msg>Touch<commit_after><|endoftext|>


<commit_before>function getTextFile(src, callback) {
  var http = new XMLHttpRequest();
  http.open("GET", src);
  http.onreadystatechange = function() {
    if (http.readyState === 4) {
      var text = http.responseText;
      callback(text);
    }
  };
  http.send();
}

var converter = new Showdown.converter();

getTextFile('../src/devizr.tests.js', function(file_content) {

  var lines, html, name,
  comments = file_content.match(/(?:\/\*\*\*(?:[\s\S]*?)\*\/[^\*\/:]*)/gm);

  comments.forEach(function(comment) {

    name = '';
    browser = -1;
    html = '';
    lines = comment.trim().split('\n');

    lines.forEach(function(line) {

      line = line.trim();
      line = line.replace(/^\* /, '');
      if (/^## /.test(line.trim())) {
        line = line + '\n' + '{{name}}';
      }
      if (/^\>/.test(line.trim())) {
        browser = line.split(',').length;
      }
      if (/^'\w+'/.test(line.trim())) {
        name = '' + line.replace(/'/g, '');
        //name = line;
      } else if (!~line.indexOf('/***') && !~line.indexOf('*/')) {
        html += line + '\n';
      }

    });

    var checked = browser >= 4 || browser === -1 ? 'checked' : '';
    var className = checked ? 'checked' : 'unchecked';
    html = html.replace(
			'{{name}}',
		  '#### ' +
		  '<input class="checkbox_input" type="checkbox" ' + checked + ' id="' + name + '" value="' + name + '"> ' +
			' Add test ' + name + ''
		);

    html = converter.makeHtml(html);
    document.querySelector('body').innerHTML += '' +
		  '
' + html + '
';

  });

	document.querySelector('button').addEventListener('click', function(){
		var divs = document.getElementsByTagName('div');
 	  for(var i = 0; i < divs.length; i++) {
		  divs[i].className+= ' hide';
 	  }
	}, false);

	var inputs = document.getElementsByTagName('input');
  for(var i = 0; i < inputs.length; i++) {
	 inputs[i].addEventListener('click', function(){
		 var id = 'wrapper_' + this.value;
		 var hide = !!~document.getElementById(id).className.indexOf('hide') ? 'hide ' : '';
		 if(this.checked) {
			 document.getElementById(id).className = hide + 'checked';
		 } else {
			 document.getElementById(id).className = hide + 'unchecked';
		 }
	 }, false);
 }

 hljs.initHighlighting();

});
<commit_msg>some cleanup<commit_after>function getTextFile(src, callback) {
  var http = new XMLHttpRequest();
  http.open("GET", src);
  http.onreadystatechange = function() {
    if (http.readyState === 4) {
      var text = http.responseText;
      callback(text);
    }
  };
  http.send();
}

var converter = new Showdown.converter();

getTextFile('../src/devizr.tests.js', function(file_content) {

  var lines, html, name,
  comments = file_content.match(/(?:\/\*\*\*(?:[\s\S]*?)\*\/[^\*\/:]*)/gm);

  comments.forEach(function(comment) {

    name = '';
    browser = -1;
    html = '';
    lines = comment.trim().split('\n');

    lines.forEach(function(line) {

      line = line.trim();
      line = line.replace(/^\* /, '');
      if (/^## /.test(line.trim())) {
        line = line + '\n' + '{{name}}';
      }
      if (/^\>/.test(line.trim())) {
        browser = line.split(',').length;
      }
      if (/^'\w+'/.test(line.trim())) {
        name = '' + line.replace(/'/g, '');
        //name = line;
      } else if (!~line.indexOf('/***') && !~line.indexOf('*/')) {
        html += line + '\n';
      }

    });

    var checked = browser >= 4 || browser === -1 ? 'checked' : '';
    var className = checked ? 'checked' : 'unchecked';
    html = html.replace(
      '{{name}}',
      '#### ' +
      '<input class="checkbox_input" type="checkbox" ' + checked + ' id="' + name + '" value="' + name + '"> ' +
      ' Add test ' + name + ''
    );

    html = converter.makeHtml(html);
    document.querySelector('body').innerHTML += '' +
      '
' + html + '
';

  });

  document.querySelector('button').addEventListener('click', function(){
    var divs = document.getElementsByTagName('div');
    for(var i = 0; i < divs.length; i++) {
      divs[i].className+= ' hide';
    }
  }, false);

  var inputs = document.getElementsByTagName('input');
  for(var i = 0; i < inputs.length; i++) {
    inputs[i].addEventListener('click', function(){
      var id = 'wrapper_' + this.value;
      var hide = !!~document.getElementById(id).className.indexOf('hide') ? 'hide ' : '';
      if(this.checked) {
        document.getElementById(id).className = hide + 'checked';
      } else {
        document.getElementById(id).className = hide + 'unchecked';
      }
    }, false);
  }

  hljs.initHighlighting();

});
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Route.extend({
  userEvents: Ember.inject.service(),
  schoolEvents: Ember.inject.service(),
  model(params){
    let slug = params.slug;
    let container = slug.substring(0, 1);
    let service;
    if(container === 'S'){
      service = this.get('schoolEvents');
    }
    if(container === 'U'){
      service = this.get('userEvents');
    }

    return service.getEventForSlug(slug);
  }
});
<commit_msg>refactored events route use authn route mixin.<commit_after>import Ember from "ember";
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

const { Route, inject } = Ember;
const { service } = inject;

export default Route.extend(AuthenticatedRouteMixin, {

  userEvents: service(),
  schoolEvents: service(),
  model(params){
    let slug = params.slug;
    let container = slug.substring(0, 1);
    let service;
    if(container === 'S'){
      service = this.get('schoolEvents');
    }
    if(container === 'U'){
      service = this.get('userEvents');
    }

    return service.getEventForSlug(slug);
  }
});
<|endoftext|>


<commit_before>import Ember from "ember";
import ResetScroll from '../mixins/reset-scroll';
import config from '../config/environment';

export default Ember.Route.extend(ResetScroll, {
	model: function(params) {
		this.set("thread_id", params["thread_id"]);
		return this.store.find("thread", params["thread_id"]);
	},
	afterModel: function() {
		// Non-system hack
		Ember.$.ajax({
            url: config.API_LOC + "/threads/" + this.get("thread_id"),
            data: {},
            contentType: "application/json",
            type: 'PUT',
        });
	},
	titleToken: function(model) {
		return model.get("title");
	},
	title: function(tokens) {
		return "KSI: " + tokens.pop();
	},
	thread_id: undefined
});<commit_msg>Fix PUT request for marking as visite<commit_after>import Ember from "ember";
import ResetScroll from '../mixins/reset-scroll';
import config from '../config/environment';

export default Ember.Route.extend(ResetScroll, {
	model: function(params) {
		return this.store.find("thread", params["thread_id"]);
	},
	afterModel: function() {
		console.log("After model called!");
		// Non-system hack
		Ember.$.ajax({
            url: config.API_LOC + "/threads/" + this.modelFor(this.routeName).get("id"),
            data: {},
            contentType: "application/json",
            type: 'PUT',
        });
	},
	titleToken: function(model) {
		return model.get("title");
	},
	title: function(tokens) {
		return "KSI: " + tokens.pop();
	}
});<|endoftext|>