<commit_before>'use strict';

module.exports = function(grunt) {
    // Project Configuration
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        assets: grunt.file.readJSON('server/config/assets.json'),
        watch: {
            js: {
                files: ['gruntfile.js', 'server.js', 'server/**/*.js', 'public/js/**', 'test/**/*.js'],
                tasks: ['jshint'],
                options: {
                    livereload: true
                }
            },
            html: {
                files: ['public/views/**', 'server/views/**'],
                options: {
                    livereload: true
                }
            },
            css: {
                files: ['public/css/**'],
                tasks: ['csslint'],
                options: {
                    livereload: true
                }
            }
        },
        jshint: {
            all: {
                src: ['gruntfile.js', 'server.js', 'server/**/*.js', 'public/js/**', 'test/**/*.js', '!test/coverage/**/*.js'],
                options: {
                    jshintrc: true
                }
            }
        },
        uglify: {
            production: {
                files: '<%= assets.js %>'
            }
        },
        csslint: {
            options: {
                csslintrc: '.csslintrc'
            },
            all: {
                src: ['public/css/**/*.css']
            }
        },
        cssmin: {
            combine: {
                files: '<%= assets.css %>'
            }
        },
        nodemon: {
            dev: {
                script: 'server.js',
                options: {
                    args: [],
                    ignore: ['public/**'],
                    ext: 'js,html',
                    nodeArgs: ['--debug'],
                    delayTime: 1,
                    env: {
                        PORT: require('./server/config/config').port
                    },
                    cwd: __dirname
                }
            }
        },
        concurrent: {
            tasks: ['nodemon', 'watch'],
            options: {
                logConcurrentOutput: true
            }
        },
        mochaTest: {
            options: {
                reporter: 'spec',
                require: 'server.js'
            },
            src: ['test/mocha/**/*.js']
        },
        env: {
            test: {
                NODE_ENV: 'test'
            }
        },
        karma: {
            unit: {
                configFile: 'test/karma/karma.conf.js'
            }
        }
    });

    //Load NPM tasks
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-csslint');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-mocha-test');
    grunt.loadNpmTasks('grunt-karma');
    grunt.loadNpmTasks('grunt-nodemon');
    grunt.loadNpmTasks('grunt-concurrent');
    grunt.loadNpmTasks('grunt-env');

    //Making grunt default to force in order not to break the project.
    grunt.option('force', true);

    //Default task(s).
    if (process.env.NODE_ENV === 'production') {
        grunt.registerTask('default', ['jshint', 'csslint', 'cssmin', 'uglify', 'concurrent']);
    } else {
        grunt.registerTask('default', ['jshint', 'csslint', 'concurrent']);
    }

    //Test task.
    grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']);
};
<commit_msg>uglify with mangling option causes problems<commit_after>'use strict';

module.exports = function(grunt) {
    // Project Configuration
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        assets: grunt.file.readJSON('server/config/assets.json'),
        watch: {
            js: {
                files: ['gruntfile.js', 'server.js', 'server/**/*.js', 'public/js/**', 'test/**/*.js'],
                tasks: ['jshint'],
                options: {
                    livereload: true
                }
            },
            html: {
                files: ['public/views/**', 'server/views/**'],
                options: {
                    livereload: true
                }
            },
            css: {
                files: ['public/css/**'],
                tasks: ['csslint'],
                options: {
                    livereload: true
                }
            }
        },
        jshint: {
            all: {
                src: ['gruntfile.js', 'server.js', 'server/**/*.js', 'public/js/**', 'test/**/*.js', '!test/coverage/**/*.js'],
                options: {
                    jshintrc: true
                }
            }
        },
        uglify: {
            options: {
                mangle: false
            },
            production: {
                files: '<%= assets.js %>'
            }
        },
        csslint: {
            options: {
                csslintrc: '.csslintrc'
            },
            all: {
                src: ['public/css/**/*.css']
            }
        },
        cssmin: {
            combine: {
                files: '<%= assets.css %>'
            }
        },
        nodemon: {
            dev: {
                script: 'server.js',
                options: {
                    args: [],
                    ignore: ['public/**'],
                    ext: 'js,html',
                    nodeArgs: ['--debug'],
                    delayTime: 1,
                    env: {
                        PORT: require('./server/config/config').port
                    },
                    cwd: __dirname
                }
            }
        },
        concurrent: {
            tasks: ['nodemon', 'watch'],
            options: {
                logConcurrentOutput: true
            }
        },
        mochaTest: {
            options: {
                reporter: 'spec',
                require: 'server.js'
            },
            src: ['test/mocha/**/*.js']
        },
        env: {
            test: {
                NODE_ENV: 'test'
            }
        },
        karma: {
            unit: {
                configFile: 'test/karma/karma.conf.js'
            }
        }
    });

    //Load NPM tasks
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-csslint');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-mocha-test');
    grunt.loadNpmTasks('grunt-karma');
    grunt.loadNpmTasks('grunt-nodemon');
    grunt.loadNpmTasks('grunt-concurrent');
    grunt.loadNpmTasks('grunt-env');

    //Making grunt default to force in order not to break the project.
    grunt.option('force', true);

    //Default task(s).
    if (process.env.NODE_ENV === 'production') {
        grunt.registerTask('default', ['jshint', 'csslint', 'cssmin', 'uglify', 'concurrent']);
    } else {
        grunt.registerTask('default', ['jshint', 'csslint', 'concurrent']);
    }

    //Test task.
    grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']);
};
<|endoftext|>


<commit_before>/**
 * Prism: Lightweight, robust, elegant syntax highlighting
 * MIT license http://www.opensource.org/licenses/mit-license.php/
 * @author Lea Verou http://lea.verou.me
 */(function(){var e=/\blang(?:uage)?-(?!\*)(\w+)\b/i,t=self.Prism={languages:{insertBefore:function(e,n,r,i){i=i||t.languages;var s=i[e],o={};for(var u in s)if(s.hasOwnProperty(u)){if(u==n)for(var a in r)r.hasOwnProperty(a)&&(o[a]=r[a]);o[u]=s[u]}return i[e]=o},DFS:function(e,n){for(var r in e){n.call(e,r,e[r]);Object.prototype.toString.call(e)==="[object Object]"&&t.languages.DFS(e[r],n)}}},highlightAll:function(e,n){var r=document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code');for(var i=0,s;s=r[i++];)t.highlightElement(s,e===!0,n)},highlightElement:function(r,i,s){var o,u,a=r;while(a&&!e.test(a.className))a=a.parentNode;if(a){o=(a.className.match(e)||[,""])[1];u=t.languages[o]}if(!u)return;r.className=r.className.replace(e,"").replace(/\s+/g," ")+" language-"+o;a=r.parentNode;/pre/i.test(a.nodeName)&&(a.className=a.className.replace(e,"").replace(/\s+/g," ")+" language-"+o);var f=r.textContent.trim();if(!f)return;f=f.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\u00a0/g," ");var l={element:r,language:o,grammar:u,code:f};t.hooks.run("before-highlight",l);if(i&&self.Worker){var c=new Worker(t.filename);c.onmessage=function(e){l.highlightedCode=n.stringify(JSON.parse(e.data));l.element.innerHTML=l.highlightedCode;s&&s.call(l.element);t.hooks.run("after-highlight",l)};c.postMessage(JSON.stringify({language:l.language,code:l.code}))}else{l.highlightedCode=t.highlight(l.code,l.grammar);l.element.innerHTML=l.highlightedCode;s&&s.call(r);t.hooks.run("after-highlight",l)}},highlight:function(e,r){return n.stringify(t.tokenize(e,r))},tokenize:function(e,n){var r=t.Token,i=[e],s=n.rest;if(s){for(var o in s)n[o]=s[o];delete n.rest}e:for(var o in n){if(!n.hasOwnProperty(o)||!n[o])continue;var u=n[o],a=u.inside,f=!!u.lookbehind||0;u=u.pattern||u;for(var l=0;l<i.length;l++){var c=i[l];if(i.length>e.length)break e;if(c instanceof r)continue;u.lastIndex=0;var h=u.exec(c);if(h){f&&(f=h[1].length);var p=h.index-1+f,h=h[0].slice(f),d=h.length,v=p+d,m=c.slice(0,p+1),g=c.slice(v+1),y=[l,1];m&&y.push(m);var b=new r(o,a?t.tokenize(h,a):h);y.push(b);g&&y.push(g);Array.prototype.splice.apply(i,y)}}}return i},hooks:{all:{},add:function(e,n){var r=t.hooks.all;r[e]=r[e]||[];r[e].push(n)},run:function(e,n){var r=t.hooks.all[e];if(!r||!r.length)return;for(var i=0,s;s=r[i++];)s(n)}}},n=t.Token=function(e,t){this.type=e;this.content=t};n.stringify=function(e){if(typeof e=="string")return e;if(Object.prototype.toString.call(e)=="[object Array]"){for(var r=0;r<e.length;r++)e[r]=n.stringify(e[r]);return e.join("")}var i={type:e.type,content:n.stringify(e.content),tag:"span",classes:["token",e.type],attributes:{}};i.type=="comment"&&(i.attributes.spellcheck="true");t.hooks.run("wrap",i);var s="";for(var o in i.attributes)s+=o+'="'+(i.attributes[o]||"")+'"';return"<"+i.tag+' class="'+i.classes.join(" ")+'" '+s+">"+i.content+"</"+i.tag+">"};if(!self.document){self.addEventListener("message",function(e){var n=JSON.parse(e.data),r=n.language,i=n.code;self.postMessage(JSON.stringify(t.tokenize(i,t.languages[r])));self.close()},!1);return}var r=document.getElementsByTagName("script");r=r[r.length-1];if(r){t.filename=r.src;document.addEventListener&&!r.hasAttribute("data-manual")&&document.addEventListener("DOMContentLoaded",t.highlightAll)}})();
Prism.languages.markup={comment:/<!--[\w\W]*?--(>|>)/g,prolog:/<\?.+?\?>/,doctype:/<!DOCTYPE.+?>/,cdata:/<!\[CDATA\[[\w\W]+?]]>/i,tag:{pattern:/<\/?[\w:-]+\s*[\w\W]*?>/gi,inside:{tag:{pattern:/^<\/?[\w:-]+/i,inside:{punctuation:/^<\/?/,namespace:/^[\w-]+?:/}},"attr-value":{pattern:/=(('|")[\w\W]*?(\2)|[^\s>]+)/gi,inside:{punctuation:/=/g}},punctuation:/\/?>/g,"attr-name":{pattern:/[\w:-]+/g,inside:{namespace:/^[\w-]+?:/}}}},entity:/&#?[\da-z]{1,8};/gi};Prism.hooks.add("wrap",function(e){e.type==="entity"&&(e.attributes.title=e.content.replace(/&/,"&"))});
Prism.languages.css={comment:/\/\*[\w\W]*?\*\//g,atrule:/@[\w-]+?(\s+.+)?(?=\s*{|\s*;)/gi,url:/url\((["']?).*?\1\)/gi,selector:/[^\{\}\s][^\{\}]*(?=\s*\{)/g,property:/(\b|\B)[a-z-]+(?=\s*:)/ig,string:/("|')(\\?.)*?\1/g,important:/\B!important\b/gi,ignore:/&(lt|gt|amp);/gi,punctuation:/[\{\};:]/g};Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{style:{pattern:/(<|<)style[\w\W]*?(>|>)[\w\W]*?(<|<)\/style(>|>)/ig,inside:{tag:{pattern:/(<|<)style[\w\W]*?(>|>)|(<|<)\/style(>|>)/ig,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.css}}});
Prism.languages.javascript={comment:{pattern:/(^|[^\\])(\/\*[\w\W]*?\*\/|\/\/.*?(\r?\n|$))/g,lookbehind:!0},string:/("|')(\\?.)*?\1/g,regex:{pattern:/(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/g,lookbehind:!0},keyword:/\b(var|let|if|else|while|do|for|return|in|instanceof|function|new|with|typeof|try|catch|finally|null|break|continue)\b/g,"boolean":/\b(true|false)\b/g,number:/\b-?(0x)?\d*\.?\d+\b/g,operator:/[-+]{1,2}|!|=?<|=?>|={1,2}|(&){1,2}|\|?\||\?|\*|\//g,ignore:/&(lt|gt|amp);/gi,punctuation:/[{}[\];(),.:]/g};Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{script:{pattern:/(<|<)script[\w\W]*?(>|>)[\w\W]*?(<|<)\/script(>|>)/ig,inside:{tag:{pattern:/(<|<)script[\w\W]*?(>|>)|(<|<)\/script(>|>)/ig,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.javascript}}});
Prism.languages.java={comment:{pattern:/(^|[^\\])(\/\*[\w\W]*?\*\/|\/\/.*?(\r?\n|$))/g,lookbehind:true},string:/("|')(\\?.)*?\1/g,keyword:/\b(abstract|continue|for|new|switch|assert|default|goto|package|synchronized|boolean|do|if|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|instanceof|return|transient|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|strictfp|volatile|const|float|native|super|while)\b/g,"boolean":/\b(true|false)\b/g,number:/\b-?(0x)?\d*\.?\d+\b/g,operator:/[-+]{1,2}|!|=?<|=?>|={1,2}|(&){1,2}|\|?\||\?|\*|\/|%|\^|(<){2}|($gt;){2,3}|:|~/g,ignore:/&(lt|gt|amp);/gi,punctuation:/[{}[\];(),.:]/g}
(function(){function e(e,t){return Array.prototype.slice.call((t||document).querySelectorAll(e))}function n(e,t,n){var r=t.replace(/\s+/g,"").split(","),i=+e.getAttribute("data-line-offset")||0,s=parseFloat(getComputedStyle(e).lineHeight);for(var o=0,u;u=r[o++];){u=u.split("-");var a=+u[0],f=+u[1]||a,l=document.createElement("div");l.textContent=Array(f-a+2).join(" \r\n");l.className=(n||"")+" line-highlight";l.setAttribute("data-start",a);f>a&&l.setAttribute("data-end",f);l.style.top=(a-i-1)*s+"px";(e.querySelector("code")||e).appendChild(l)}}function r(){var t=location.hash.slice(1);e(".temporary.line-highlight").forEach(function(e){e.parentNode.removeChild(e)});var r=(t.match(/\.([\d,-]+)$/)||[,""])[1];if(!r||document.getElementById(t))return;var i=t.slice(0,t.lastIndexOf(".")),s=document.getElementById(i);if(!s)return;s.hasAttribute("data-line")||s.setAttribute("data-line","");n(s,r,"temporary ");document.querySelector(".temporary.line-highlight").scrollIntoView()}if(!window.Prism)return;var t=crlf=/\r?\n|\r/g,i=0;Prism.hooks.add("after-highlight",function(t){var s=t.element.parentNode,o=s&&s.getAttribute("data-line");if(!s||!o||!/pre/i.test(s.nodeName))return;clearTimeout(i);e(".line-highlight",s).forEach(function(e){e.parentNode.removeChild(e)});n(s,o);i=setTimeout(r,1)});addEventListener("hashchange",r)})();
<commit_msg>Delete prism.js<commit_after><|endoftext|>


<commit_before>function addNewCommand(key,value){
    var name = key + value;
    editor.commands.addCommand({
        name: name,
        bindKey: {
            win: key,
            mac: key
        },
        exec: function (editor) {
            editor.insert(value);
        },
        readOnly: true
    });
}
// default keys https://searchcode.com/codesearch/view/58959997/
editor.commands.addCommand({
    name: 'cut-1',
    bindKey: {win: 'Ctrl-X', mac: 'Command-X'},
    exec: function (editor) {

        var textRange = editor.session.getTextRange(editor.getSelectionRange());

        if (textRange.length == 0) {
            editor.removeLines();
            return;
        }

        app.cutCopy(textRange);
        editor.remove(editor.getSelectionRange());

    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'close-1',
    bindKey: {win: 'Ctrl-W', mac: 'Command-W'},
    exec: function (editor) {
        app.saveAndCloseCurrentTab();
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'copy-1',
    bindKey: {win: 'Ctrl-C', mac: 'Command-C'},
    exec: function (editor) {
        app.cutCopy(editor.session.getTextRange(editor.getSelectionRange()));
    },
    readOnly: false
});

editor.commands.addCommand({
    name: 'paste-1',
    bindKey: {win: 'Ctrl-V', mac: 'Command-V'},
    exec: function (editor) {
        editor.insert(app.paste());
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'ctrl-enter-1',
    bindKey: {win: 'Ctrl-Enter', mac: 'Command-Enter'},
    exec: function (editor) {
        editor.insert("\r\n");
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'ctrl-duplicate',
    bindKey: {win: 'Ctrl-D', mac: 'Command-D'},
    exec: function (editor) {
        editor.copyLinesDown();
    },
    readOnly: true
});

function formatText(editor, matcher, firstCharacter, lastCharacter) {
    var range = editor.getSelectionRange();
    var text = editor.session.getTextRange(range);
    var firstCharLength = firstCharacter.length;
    var lastCharLength = lastCharacter.length;

    if (matcher(text)) {
        text = text.substring(firstCharLength, text.length - lastCharLength);
        editor.session.replace(range, text);
    }
    else {
        var virtualRange = editor.getSelectionRange();
        virtualRange.setStart(range.start.row, range.start.column - firstCharLength);
        virtualRange.setEnd(range.end.row, range.end.column + lastCharLength);

        var virtualText = editor.session.getTextRange(virtualRange);
        if (matcher(virtualText)) {
            editor.session.replace(virtualRange, text);
        }
        else {
            editor.session.replace(range, firstCharacter + text + lastCharacter);
            if (range.end.column == range.start.column) {
                editor.navigateTo(range.end.row, range.end.column + firstCharLength);
            }
        }
    }
}

function boldText() {
    formatText(editor, matchBoldText, "*", "*");
}

function italicizeText() {
    formatText(editor, matchItalicizedText, "_", "_");
}

function superScript() {
    formatText(editor, matchSuperScriptText, "^", "^");
}

function subScript() {
    formatText(editor, matchSubScriptText, "~", "~");
}

function underlinedText() {
    formatText(editor, matchHtmlTagText, "+++", "+++");
}

function addStrikeThroughText() {
    formatText(editor, matchHtmlTagText, "+++", "+++");
}

function highlightedText() {
    formatText(editor, matchHighlightedText, "#", "#");
}

function isURL(text) {
    var myRegExp = /^(.*?)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i;

    return myRegExp.test(text);

}

function addHyperLink() {
    var cursorPosition = editor.getCursorPosition();
    var session = editor.getSession();
    var pasted = app.paste();
    if (isURL(pasted)) {
        if (pasted.indexOf("http") == -1)
            session.insert(cursorPosition, "http://" + pasted + "[text]");
        else
            session.insert(cursorPosition, pasted + "[text]");
        return;
    }
    session.insert(cursorPosition, "http://url[text]");
}

function addSourceCode() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[source,java]\n----\n\n----");

    editor.gotoLine(range.end.row + 3, 0, true);
}

function addQuote(){
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[quote,Rūmī]\n____\nPatience is the key to joy.\n____");

    editor.gotoLine(range.end.row + 3, 0, true);
}

function addMathBlock() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[math,file=\"\"]\n--\n\n--");

    editor.gotoLine(range.end.row + 3, 0, true);
}

function addUmlBlock() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[uml,file=\"\"]\n--\n\n--");

    editor.gotoLine(range.end.row + 3, 0, true);
}

function addTreeBlock() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[tree,file=\"\"]\n--\n#\n--");

    editor.gotoLine(range.end.row + 3, 1, true);
}

function addImageSection() {
    editor.removeToLineStart();
    editor.insert("image::images/image.png[]");
}

function addHeading() {
    var cursorPosition = editor.getCursorPosition();
    cursorPosition.column = 0;
    var session = editor.getSession();
    var line = session.getLine(cursorPosition.row);
    var first = line[0] || "";
    session.insert(cursorPosition, (first == "=") ? "=" : "= ");
}

function addOlList() {
    var cursorPosition = editor.getCursorPosition();
    cursorPosition.column = 0;
    var session = editor.getSession();
    session.insert(cursorPosition, "1. ");
}

function addUlList() {
    var cursorPosition = editor.getCursorPosition();
    cursorPosition.column = 0;
    var session = editor.getSession();
    session.insert(cursorPosition, "* ");
}

function showLineNumbers() {
    editor.renderer.getShowGutter() ? editor.renderer.setShowGutter(false) : editor.renderer.setShowGutter(true);
}

editor.commands.addCommand({
    name: 'underline-selected',
    bindKey: {win: 'Ctrl-U', mac: 'Command-U'},
    exec: underlinedText,
    readOnly: true
});

editor.commands.addCommand({
    name: 'bold-selected',
    bindKey: {win: 'Ctrl-B', mac: 'Command-B'},
    exec: boldText,
    readOnly: true
});

editor.commands.addCommand({
    name: 'highlight-selected',
    bindKey: {win: 'Ctrl-H', mac: 'Command-H'},
    exec: highlightedText,
    readOnly: true
});

editor.commands.addCommand({
    name: 'line-numbers',
    bindKey: {win: 'Ctrl-L', mac: 'Command-L'},
    exec: showLineNumbers,
    readOnly: true
});

editor.commands.addCommand({
    name: 'codify-selected',
    bindKey: {win: 'Ctrl-Shift-C', mac: 'Command-Shift-C'},
    exec: function (editor) {
        console.log("in old");
        formatText(editor, matchCode, "`", "`");
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'italicize-selected',
    bindKey: {
        win: 'Ctrl-i|Ctrl-İ|Ctrl-ı|Ctrl-I',
        mac: 'Command-i|Command-İ|Command-ı|Command-I'
    },
    exec: italicizeText,
    readOnly: true
});

editor.commands.addCommand({
    name: 'firebug-lite',
    bindKey: {
        win: 'F12',
        mac: 'F12'
    },
    exec: function () {
        if (!document.querySelectorAll("#firebug-script").length){
            var head = document.querySelector("head");
            var js = document.createElement("script");
            js.type = "text/javascript";
            js.src = "http://getfirebug.com/firebug-lite.js#startOpened=true";
            head.appendChild(js);
        }
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'source-generate',
    bindKey: {win: 'Tab', mac: 'Tab'},
    exec: function (editor, selection) {

        var cursorPosition = editor.getCursorPosition();
        var currentRow = cursorPosition.row;
        var currentColumn = cursorPosition.column;

        var range = editor.getSelectionRange();
        range.start.row = currentRow;
        range.start.column = 0;
        range.end.row = currentRow;
        range.end.column = currentColumn;

        var textRange = editor.session.getTextRange(range);

        // img tab
        if (textRange == "img") {
            addImageSection();
            return;
        }

        // book tab
        if (textRange == "book") { // source generator
            editor.removeToLineStart();

            editor.insert("= Book Name\nAuthor's Name\n:doctype: book\n:encoding: utf-8\n:lang: en\n:toc: left\n:numbered:\n:stylesheet: https://cdn.rawgit.com/asciidocfx/AsciidocFX/master/src/main/resources/public/css/asciidoctor-default.css\n\n\n");

            return;
        }

        // article tab
        if (textRange == "article") { // source generator
            editor.removeToLineStart();

            editor.insert("= Article Name\nAuthor's Name\n:doctype: article\n:encoding: utf-8\n:lang: en\n:toc: left\n:numbered:\n:stylesheet: https://cdn.rawgit.com/asciidocfx/AsciidocFX/master/src/main/resources/public/css/asciidoctor-default.css\n\n\n");

            return;
        }

        // math tab
        if (textRange == "math") { // math block generator
            addMathBlock();
            return;
        }

        // uml tab
        if (textRange == "uml") { // uml block generator
            addUmlBlock();
            return;
        }

        // tree tab
        if (textRange == "tree") { // uml block generator
            addTreeBlock();
            return;
        }

        // quote tab
        if (textRange == "quote") { // quote block generator
            addQuote();
            return;
        }

        // src tab
        if (textRange == "src") { // source generator
            addSourceCode();
            return;
        }
        // src,ruby or src.ruby tab
        var srcMatch = textRange.match(/src(\.|,)(\w+)/);
        if (Array.isArray(srcMatch)) {
            if (srcMatch.length == 3) {
                editor.removeToLineStart();

                var langName = srcMatch[2];

                editor.insert("[source," + langName + "]\n----\n\n----");

                editor.gotoLine(range.end.row + 3, 0, true);
                return;
            }
        }

//            "tbl3,2" tab
        var tableMatch = textRange.match(/tbl(\d+)(\.|,)(\d+)/);

        if (Array.isArray(tableMatch))
            if (tableMatch.length == 4) { // table generator

                editor.removeToLineStart();

                var row = tableMatch[1];
                var column = tableMatch[3];

                var tablePopupCtrl = app.getTablePopupController();
                tablePopupCtrl.createBasicTable(row, column);
                return;
            }

        editor.indent();
    },
    readOnly: true
});

editor.addEventListener("mousewheel", mouseWheelHandler);

function mouseWheelHandler(event) {
    if (!event)
        return;
    event = window.event;

    if (event.ctrlKey && editor.getValue().length) {

        var fontSize = parseInt(editor.getFontSize());

        if (event.wheelDelta < 0 && fontSize > 8) {
            //mouse scroll down - min size 8
            editor.setFontSize((fontSize - 1) + "px");
        }
        else if (event.wheelDelta >= 0 && fontSize < 24) {
            //mouse scroll up - max size 24
            editor.setFontSize((fontSize + 1) + "px");
        }
    }
}

function matchBoldText(text) {
    return text.match(/\*.*\*/g);
}

function matchItalicizedText(text) {
    return text.match(/\_.*\_/g);
}

function matchSuperScriptText(text) {
    return text.match(/\^.*\^/g);
}

function matchSubScriptText(text) {
    return text.match(/\~.*\~/g);
}

function matchCode(text) {
    return text.match(/\`.*\`/g);
}

function matchHighlightedText(text) {
    return text.match(/\#.*\#/g);
}

function matchHtmlTagText(text) {
    return text.match(/(\+\+\+\<(u|del)\>).*(\<\/(u|del)\>\+\+\+)/g);
}

<commit_msg>Invoke confirm handler after all JS executed<commit_after>function addNewCommand(key, value) {
    var name = key + value;
    editor.commands.addCommand({
        name: name,
        bindKey: {
            win: key,
            mac: key
        },
        exec: function (editor) {
            editor.insert(value);
        },
        readOnly: true
    });
}
// default keys https://searchcode.com/codesearch/view/58959997/
editor.commands.addCommand({
    name: 'cut-1',
    bindKey: {win: 'Ctrl-X', mac: 'Command-X'},
    exec: function (editor) {

        var textRange = editor.session.getTextRange(editor.getSelectionRange());

        if (textRange.length == 0) {
            editor.removeLines();
            return;
        }

        app.cutCopy(textRange);
        editor.remove(editor.getSelectionRange());

    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'close-1',
    bindKey: {win: 'Ctrl-W', mac: 'Command-W'},
    exec: function (editor) {
        app.saveAndCloseCurrentTab();
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'copy-1',
    bindKey: {win: 'Ctrl-C', mac: 'Command-C'},
    exec: function (editor) {
        app.cutCopy(editor.session.getTextRange(editor.getSelectionRange()));
    },
    readOnly: false
});

editor.commands.addCommand({
    name: 'paste-1',
    bindKey: {win: 'Ctrl-V', mac: 'Command-V'},
    exec: function (editor) {
        editor.insert(app.paste());
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'ctrl-enter-1',
    bindKey: {win: 'Ctrl-Enter', mac: 'Command-Enter'},
    exec: function (editor) {
        editor.insert("\r\n");
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'ctrl-duplicate',
    bindKey: {win: 'Ctrl-D', mac: 'Command-D'},
    exec: function (editor) {
        editor.copyLinesDown();
    },
    readOnly: true
});

function formatText(editor, matcher, firstCharacter, lastCharacter) {
    var range = editor.getSelectionRange();
    var text = editor.session.getTextRange(range);
    var firstCharLength = firstCharacter.length;
    var lastCharLength = lastCharacter.length;

    if (matcher(text)) {
        text = text.substring(firstCharLength, text.length - lastCharLength);
        editor.session.replace(range, text);
    }
    else {
        var virtualRange = editor.getSelectionRange();
        virtualRange.setStart(range.start.row, range.start.column - firstCharLength);
        virtualRange.setEnd(range.end.row, range.end.column + lastCharLength);

        var virtualText = editor.session.getTextRange(virtualRange);
        if (matcher(virtualText)) {
            editor.session.replace(virtualRange, text);
        }
        else {
            editor.session.replace(range, firstCharacter + text + lastCharacter);
            if (range.end.column == range.start.column) {
                editor.navigateTo(range.end.row, range.end.column + firstCharLength);
            }
        }
    }
}

function boldText() {
    formatText(editor, matchBoldText, "*", "*");
}

function italicizeText() {
    formatText(editor, matchItalicizedText, "_", "_");
}

function superScript() {
    formatText(editor, matchSuperScriptText, "^", "^");
}

function subScript() {
    formatText(editor, matchSubScriptText, "~", "~");
}

function underlinedText() {
    formatText(editor, matchHtmlTagText, "+++", "+++");
}

function addStrikeThroughText() {
    formatText(editor, matchHtmlTagText, "+++", "+++");
}

function highlightedText() {
    formatText(editor, matchHighlightedText, "#", "#");
}

function isURL(text) {
    var myRegExp = /^(.*?)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i;

    return myRegExp.test(text);

}

function addHyperLink() {
    var cursorPosition = editor.getCursorPosition();
    var session = editor.getSession();
    var pasted = app.paste();
    if (isURL(pasted)) {
        if (pasted.indexOf("http") == -1)
            session.insert(cursorPosition, "http://" + pasted + "[text]");
        else
            session.insert(cursorPosition, pasted + "[text]");
        return;
    }
    session.insert(cursorPosition, "http://url[text]");
}

function addSourceCode() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[source,java]\n----\n\n----");

    editor.gotoLine(range.end.row + 3, 0, true);
}

function addQuote() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[quote,Rūmī]\n____\nPatience is the key to joy.\n____");

    editor.gotoLine(range.end.row + 3, 0, true);
}

function addMathBlock() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[math,file=\"\"]\n--\n\n--");

    editor.gotoLine(range.end.row + 3, 0, true);
}

function addUmlBlock() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[uml,file=\"\"]\n--\n\n--");

    editor.gotoLine(range.end.row + 3, 0, true);
}

function addTreeBlock() {
    var range = editor.getSelectionRange();
    editor.removeToLineStart();

    editor.insert("[tree,file=\"\"]\n--\n#\n--");

    editor.gotoLine(range.end.row + 3, 1, true);
}

function addImageSection() {
    editor.removeToLineStart();
    editor.insert("image::images/image.png[]");
}

function addHeading() {
    var cursorPosition = editor.getCursorPosition();
    cursorPosition.column = 0;
    var session = editor.getSession();
    var line = session.getLine(cursorPosition.row);
    var first = line[0] || "";
    session.insert(cursorPosition, (first == "=") ? "=" : "= ");
}

function addOlList() {
    var cursorPosition = editor.getCursorPosition();
    cursorPosition.column = 0;
    var session = editor.getSession();
    session.insert(cursorPosition, "1. ");
}

function addUlList() {
    var cursorPosition = editor.getCursorPosition();
    cursorPosition.column = 0;
    var session = editor.getSession();
    session.insert(cursorPosition, "* ");
}

function showLineNumbers() {
    editor.renderer.getShowGutter() ? editor.renderer.setShowGutter(false) : editor.renderer.setShowGutter(true);
}

editor.commands.addCommand({
    name: 'underline-selected',
    bindKey: {win: 'Ctrl-U', mac: 'Command-U'},
    exec: underlinedText,
    readOnly: true
});

editor.commands.addCommand({
    name: 'bold-selected',
    bindKey: {win: 'Ctrl-B', mac: 'Command-B'},
    exec: boldText,
    readOnly: true
});

editor.commands.addCommand({
    name: 'highlight-selected',
    bindKey: {win: 'Ctrl-H', mac: 'Command-H'},
    exec: highlightedText,
    readOnly: true
});

editor.commands.addCommand({
    name: 'line-numbers',
    bindKey: {win: 'Ctrl-L', mac: 'Command-L'},
    exec: showLineNumbers,
    readOnly: true
});

editor.commands.addCommand({
    name: 'codify-selected',
    bindKey: {win: 'Ctrl-Shift-C', mac: 'Command-Shift-C'},
    exec: function (editor) {
        console.log("in old");
        formatText(editor, matchCode, "`", "`");
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'italicize-selected',
    bindKey: {
        win: 'Ctrl-i|Ctrl-İ|Ctrl-ı|Ctrl-I',
        mac: 'Command-i|Command-İ|Command-ı|Command-I'
    },
    exec: italicizeText,
    readOnly: true
});

editor.commands.addCommand({
    name: 'firebug-lite',
    bindKey: {
        win: 'F12',
        mac: 'F12'
    },
    exec: function () {
        if (!document.querySelectorAll("#firebug-script").length) {
            var head = document.querySelector("head");
            var js = document.createElement("script");
            js.type = "text/javascript";
            js.src = "http://getfirebug.com/firebug-lite.js#startOpened=true";
            head.appendChild(js);
        }
    },
    readOnly: true
});

editor.commands.addCommand({
    name: 'source-generate',
    bindKey: {win: 'Tab', mac: 'Tab'},
    exec: function (editor, selection) {

        var cursorPosition = editor.getCursorPosition();
        var currentRow = cursorPosition.row;
        var currentColumn = cursorPosition.column;

        var range = editor.getSelectionRange();
        range.start.row = currentRow;
        range.start.column = 0;
        range.end.row = currentRow;
        range.end.column = currentColumn;

        var textRange = editor.session.getTextRange(range);

        // img tab
        if (textRange == "img") {
            addImageSection();
            return;
        }

        // book tab
        if (textRange == "book") { // source generator
            editor.removeToLineStart();

            editor.insert("= Book Name\nAuthor Name\n:doctype: book\n:encoding: utf-8\n:lang: en\n:toc: left\n:numbered:\n:stylesheet: https://cdn.rawgit.com/asciidocfx/AsciidocFX/master/src/main/resources/public/css/asciidoctor-default.css\n\n\n");

            return;
        }

        // article tab
        if (textRange == "article") { // source generator
            editor.removeToLineStart();

            editor.insert("= Article Name\nAuthor Name\n:doctype: article\n:encoding: utf-8\n:lang: en\n:toc: left\n:numbered:\n:stylesheet: https://cdn.rawgit.com/asciidocfx/AsciidocFX/master/src/main/resources/public/css/asciidoctor-default.css\n\n\n");

            return;
        }

        // math tab
        if (textRange == "math") { // math block generator
            addMathBlock();
            return;
        }

        // uml tab
        if (textRange == "uml") { // uml block generator
            addUmlBlock();
            return;
        }

        // tree tab
        if (textRange == "tree") { // uml block generator
            addTreeBlock();
            return;
        }

        // quote tab
        if (textRange == "quote") { // quote block generator
            addQuote();
            return;
        }

        // src tab
        if (textRange == "src") { // source generator
            addSourceCode();
            return;
        }
        // src,ruby or src.ruby tab
        var srcMatch = textRange.match(/src(\.|,)(\w+)/);
        if (Array.isArray(srcMatch)) {
            if (srcMatch.length == 3) {
                editor.removeToLineStart();

                var langName = srcMatch[2];

                editor.insert("[source," + langName + "]\n----\n\n----");

                editor.gotoLine(range.end.row + 3, 0, true);
                return;
            }
        }

//            "tbl3,2" tab
        var tableMatch = textRange.match(/tbl(\d+)(\.|,)(\d+)/);

        if (Array.isArray(tableMatch))
            if (tableMatch.length == 4) { // table generator

                editor.removeToLineStart();

                var row = tableMatch[1];
                var column = tableMatch[3];

                var tablePopupCtrl = app.getTablePopupController();
                tablePopupCtrl.createBasicTable(row, column);
                return;
            }

        editor.indent();
    },
    readOnly: true
});

editor.addEventListener("mousewheel", mouseWheelHandler);

function mouseWheelHandler(event) {
    if (!event)
        return;
    event = window.event;

    if (event.ctrlKey && editor.getValue().length) {

        var fontSize = parseInt(editor.getFontSize());

        if (event.wheelDelta < 0 && fontSize > 8) {
            //mouse scroll down - min size 8
            editor.setFontSize((fontSize - 1) + "px");
        }
        else if (event.wheelDelta >= 0 && fontSize < 24) {
            //mouse scroll up - max size 24
            editor.setFontSize((fontSize + 1) + "px");
        }
    }
}

function matchBoldText(text) {
    return text.match(/\*.*\*/g);
}

function matchItalicizedText(text) {
    return text.match(/\_.*\_/g);
}

function matchSuperScriptText(text) {
    return text.match(/\^.*\^/g);
}

function matchSubScriptText(text) {
    return text.match(/\~.*\~/g);
}

function matchCode(text) {
    return text.match(/\`.*\`/g);
}

function matchHighlightedText(text) {
    return text.match(/\#.*\#/g);
}

function matchHtmlTagText(text) {
    return text.match(/(\+\+\+\<(u|del)\>).*(\<\/(u|del)\>\+\+\+)/g);
}

confirm("command:ready")<|endoftext|>


<commit_before>/* Experimental Slider implementation with jQuery and handlebars.js */

Slider = function(formHeight, save, landscapeNames, loadLandscape,
		jsonQuestionnaire, loadExperimentToolsPage, isWelcome) {

	var showExceptionDialog = false;

	var questionPointer = 0;

	var parsedQuestionnaire = JSON.parse(jsonQuestionnaire);
	if (!parsedQuestionnaire.questions[0]) {
		parsedQuestionnaire.questions.push({
			"answers" : [{
                "answerText": "",
                "checkboxChecked": false
            }],
			"workingTime" : "",
			"type" : "",
			"expLandscape" : "",
			"questionText" : ""
		})
	}

	var AppState = can.Map.extend({
		questionnaire : parsedQuestionnaire,
		questionPointer : 0,
		currentQuestion : parsedQuestionnaire.questions[0]
	});

    var appState = new AppState();

	setupComponents();
	setupSliderStyle();

	function setupComponents() {
		can.Component.extend({
			tag : "slider-container",
			template : can.stache($('#slider_template').html()),
			viewModel : {
				isWelcome : isWelcome
			}
		});

		can.Component
				.extend({
					tag : "slider-question",
					template : can.stache($('#slider_question').html()),
					init: function() {
						var self = this;
						this.viewModel.bind('state.currentQuestion', function() {
							self.viewModel.attr("questionType", appState.attr("currentQuestion.type"));
						})
					},
					viewModel : {
						state: appState,
						landscapeNames : landscapeNames,
						loadExplorVizLandscape : function(viewModel, $element, ev) {
							loadLandscape($element.val());
							showExceptionDialog = false;
					}
				}
		});

		can.Component.extend({
			tag : "slider-question-free",
			template : can.stache($('#slider_question_free').html()),
			viewModel : {
				state: appState
			},
			events: {
				'.answerInput:last keydown': function() {
					var answers = this.viewModel.attr('state.currentQuestion.answers')
					//debugger;
					answers.push({
						answerText: "",
						checkboxChecked: false
						})
				}
			}
		});

		can.Component.extend({
			tag : "slider-question-mc",
			template : can.stache($('#slider_question_multiple_choice').html()),
			viewModel : {
				state: appState
			},
				events: {
					'.answerInput:last keydown': function() {
						var answers = this.viewModel.attr('state.currentQuestion.answers')
						answers.push({
							answerText: "",
							checkboxChecked: false
							})
					}
				}
		});

		can.Component.extend({
			tag : "slider-buttons",
			template : can.stache($('#slider_buttons').html()),
			viewModel : {
				isWelcome : isWelcome
			},
			events : {
				"#exp_slider_question_nextButton click" : function() {
					var form = document.getElementById("exp_slider_question_form");

					if(isFormCompleted(form)) {
						var jsonForm = formValuesToJSON(form);

						can.batch.start();

						appState.attr("questionnaire.questions." + appState.attr("questionPointer"), jsonForm);
						sendCompletedData(appState.attr("questionnaire").serialize());

						appState.attr("questionPointer", appState.attr("questionPointer") + 1);
						appState.attr("currentQuestion", appState.attr("questionnaire.questions." + appState.attr("questionPointer")));

						if(!appState.attr("currentQuestion")) {
							appState.attr("questionnaire.questions." + appState.attr("questionPointer") , {
								"answers" : [{
				                    "answerText": "",
				                    "checkboxChecked": false
				                }],
								"workingTime" : "",
								"type" : "freeText",
								"expLandscape" : "",
								"questionText" : ""
							});
							appState.attr("currentQuestion", appState.attr("questionnaire.questions." + appState.attr("questionPointer")));
						}
					}
					else {
						alert("Insert all data!");
					}
					can.batch.stop();
				},
				"#exp_slider_question_saveButton click" : function() {
					sendCompletedData(appState.attr("questionnaire").serialize());
					loadExperimentToolsPage();
				},
				"#exp_slider_question_backButton click" : function() {
					var form = document
					.getElementById("exp_slider_question_form");
					var jsonForm = formValuesToJSON(form);

					can.batch.start();
					appState.attr("questionnaire.questions." + appState.attr("questionPointer"), jsonForm);

					if (appState.attr("questionPointer") > 0) {

						appState.attr("questionPointer", appState.attr("questionPointer") - 1);
						appState.attr("currentQuestion", appState.attr("questionnaire.questions." + appState.attr("questionPointer")));
					}
					can.batch.stop();
				}
			}
		});

		can.Component.extend({
			tag : "slider-error-input",
			template : can.stache($('#slider_error_input').html()),
		});

		var template = can.stache("<slider-container></slider-container>");
		$('#view').append(template());

	}

	function setupSliderStyle() {
		console.log(formHeight);
		$('#expSliderInnerContainer').height(formHeight);
		$('#expQuestionForm').css('maxHeight', formHeight - 70);

		$('#expScrollable').height(formHeight);
		$('#expScrollable').css('maxHeight', formHeight - 35);

		$('#expSlider').css('right', -315);
		$('#expSliderLabel').click(function(e) {
			e.preventDefault();
			toggle[c++ % 2]();
		});
		// Setup toggle mechanism
		var toggle = [ slideOut, slideIn ], c = 0;

		function slideOut() {
			var right = -315;

			function slideOutFrame() {
				right += 5;
				expSlider.style.right = right + 'px';
				if (right == 0)
					clearInterval(id);
			}
			var id = setInterval(slideOutFrame, 7);
		}

		function slideIn() {
			var right = 0;

			function slideInFrame() {
				right -= 5;
				expSlider.style.right = right + 'px';
				if (right == -315)
					clearInterval(id);
			}
			var id = setInterval(slideInFrame, 7);
		}
	}

	function sendCompletedData(questionnaire) {
		// filter for well-formed questions
		var wellFormedQuestions = questionnaire.questions.filter(function(
				elem, index, obj) {

			var hasAnswer = elem.answers[0] != "";

			var hasText = elem.questionText.length > 0;
			var hasWorkingTime = elem.workingTime.length > 0;

			return hasAnswer && hasText && hasWorkingTime;
		});

		var wellFormQuestionnaire = JSON.parse(JSON.stringify(questionnaire));
		wellFormQuestionnaire.questions = wellFormedQuestions;

		// send to server
		save(JSON.stringify(wellFormQuestionnaire));
	}
//
//	function updateAnswerFields(){
//		if(appState.attr("currentQuestion.answers").length == 1){
//			if(appState.attr("currentQuestion.answers.0").length>= 1){
//				appState.attr("currentQuestion.answers.1", { "answerText": "", "checkboxChecked": false});
//			}
//		}
//	}

	var isFormCompleted = function(expQuestionForm) {

		var elements = expQuestionForm.elements;

		// check if at least one answer is set
		var answerInputs = Array.prototype.slice.call(document.getElementById(
				"answers").querySelectorAll('[id^=answerInput]'));

		var answerCheckboxes = Array.prototype.slice.call(document
				.getElementById("answers").querySelectorAll(
						'[id^=answerCheckbox]'));

		var atLeastOneAnswer = answerInputs.filter(function(answer) {
			if (answer.value != "")
				return true;
		}).length > 0 ? true : false;

		// check if inputs before answers are all filled
		var upperBound = elements.length
				- (answerInputs.length + answerCheckboxes.length);

		for (var i = 0; i < upperBound; i++) {
			if (elements[i].value == "") {
				return false;
			}
		}
		return atLeastOneAnswer;
	}

	var createProperty = function(obj, key, value) {
		var config = {
			value : value,
			writable : true,
			enumerable : true,
			configurable : true
		};
		Object.defineProperty(obj, key, config);
	};

	function formValuesToJSON(expQuestionForm) {

		var container = {};

		var obj = {};

		obj["type"] = "";
		obj["questionText"] = "";
		obj["workingTime"] = "";
		obj["answers"] = [];

		var elements = expQuestionForm.elements;
		var length = elements.length - 1;

		var answers = [];

		// add ExplorViz landscape identifier
		createProperty(obj, "expLandscape", $(
				'#exp_slider_question_landscape option:selected').val());

		// add type
		createProperty(obj, "type", $(
				'#exp_slider_question_questiontype option:selected').val());

		var answerCounter = 0;

		// rename answer ids due to possible empty inputs
		// and create json
		for (var i = 0; i < length; i++) {

			if (elements[i].value != "") {

				if (elements[i].id.indexOf("answerInput") == 0) {

					if (answers.length == 0) {
						createProperty(obj, "answers", answers);
					}

					var answer = {};

					var checked = elements[("answerCheckbox" + answerCounter)].checked;

					createProperty(answer, "answerText",
							elements[i].value.toString());

					createProperty(answer, "checkboxChecked",
							checked);

					answers.push(answer);

					answerCounter++;

				} else if (elements[i].id.indexOf("answerCheckbox") != 0) {

					createProperty(obj, elements[i].id.toString(),
							elements[i].value);

				}
			}

			else if (elements[i].id.indexOf("answerInput") == 0) {

				answerCounter++;

			}
		}

		if (answers.length == 0) {
			createProperty(obj, "answers", answers);
			answers.push("");
		}

		// empty answer input
		answers.push({
            "answerText": "",
            "checkboxChecked": false
        });

		return obj;
	}

	function loadExplorViz() {
		if (qtLandscape.options[qtLandscape.selectedIndex] == undefined) {
			showExceptionDialog = true;
		} else {
			loadLandscape(qtLandscape.options[qtLandscape.selectedIndex].innerHTML);
			showExceptionDialog = false;
		}

	}
}<commit_msg>slider open on start<commit_after>/* Experimental Slider implementation with jQuery and handlebars.js */

Slider = function(formHeight, save, landscapeNames, loadLandscape,
		jsonQuestionnaire, loadExperimentToolsPage, isWelcome) {

	var showExceptionDialog = false;

	var questionPointer = 0;

	var parsedQuestionnaire = JSON.parse(jsonQuestionnaire);
	if (!parsedQuestionnaire.questions[0]) {
		parsedQuestionnaire.questions.push({
			"answers" : [{
                "answerText": "",
                "checkboxChecked": false
            }],
			"workingTime" : "",
			"type" : "",
			"expLandscape" : "",
			"questionText" : ""
		})
	}

	var AppState = can.Map.extend({
		questionnaire : parsedQuestionnaire,
		questionPointer : 0,
		currentQuestion : parsedQuestionnaire.questions[0]
	});

    var appState = new AppState();

	setupComponents();
	setupSliderStyle();

	function setupComponents() {
		can.Component.extend({
			tag : "slider-container",
			template : can.stache($('#slider_template').html()),
			viewModel : {
				isWelcome : isWelcome
			}
		});

		can.Component
				.extend({
					tag : "slider-question",
					template : can.stache($('#slider_question').html()),
					init: function() {
						var self = this;
						this.viewModel.bind('state.currentQuestion', function() {
							self.viewModel.attr("questionType", appState.attr("currentQuestion.type"));
						})
					},
					viewModel : {
						state: appState,
						landscapeNames : landscapeNames,
						loadExplorVizLandscape : function(viewModel, $element, ev) {
							loadLandscape($element.val());
							showExceptionDialog = false;
					}
				}
		});

		can.Component.extend({
			tag : "slider-question-free",
			template : can.stache($('#slider_question_free').html()),
			viewModel : {
				state: appState
			},
			events: {
				'.answerInput:last keydown': function() {
					var answers = this.viewModel.attr('state.currentQuestion.answers')
					//debugger;
					answers.push({
						answerText: "",
						checkboxChecked: false
						})
				}
			}
		});

		can.Component.extend({
			tag : "slider-question-mc",
			template : can.stache($('#slider_question_multiple_choice').html()),
			viewModel : {
				state: appState
			},
				events: {
					'.answerInput:last keydown': function() {
						var answers = this.viewModel.attr('state.currentQuestion.answers')
						answers.push({
							answerText: "",
							checkboxChecked: false
							})
					}
				}
		});

		can.Component.extend({
			tag : "slider-buttons",
			template : can.stache($('#slider_buttons').html()),
			viewModel : {
				isWelcome : isWelcome
			},
			events : {
				"#exp_slider_question_nextButton click" : function() {
					var form = document.getElementById("exp_slider_question_form");

					if(isFormCompleted(form)) {
						var jsonForm = formValuesToJSON(form);

						can.batch.start();

						appState.attr("questionnaire.questions." + appState.attr("questionPointer"), jsonForm);
						sendCompletedData(appState.attr("questionnaire").serialize());

						appState.attr("questionPointer", appState.attr("questionPointer") + 1);
						appState.attr("currentQuestion", appState.attr("questionnaire.questions." + appState.attr("questionPointer")));

						if(!appState.attr("currentQuestion")) {
							appState.attr("questionnaire.questions." + appState.attr("questionPointer") , {
								"answers" : [{
				                    "answerText": "",
				                    "checkboxChecked": false
				                }],
								"workingTime" : "",
								"type" : "freeText",
								"expLandscape" : "",
								"questionText" : ""
							});
							appState.attr("currentQuestion", appState.attr("questionnaire.questions." + appState.attr("questionPointer")));
						}
					}
					else {
						alert("Insert all data!");
					}
					can.batch.stop();
				},
				"#exp_slider_question_saveButton click" : function() {
					sendCompletedData(appState.attr("questionnaire").serialize());
					loadExperimentToolsPage();
				},
				"#exp_slider_question_backButton click" : function() {
					var form = document
					.getElementById("exp_slider_question_form");
					var jsonForm = formValuesToJSON(form);

					can.batch.start();
					appState.attr("questionnaire.questions." + appState.attr("questionPointer"), jsonForm);

					if (appState.attr("questionPointer") > 0) {

						appState.attr("questionPointer", appState.attr("questionPointer") - 1);
						appState.attr("currentQuestion", appState.attr("questionnaire.questions." + appState.attr("questionPointer")));
					}
					can.batch.stop();
				}
			}
		});

		can.Component.extend({
			tag : "slider-error-input",
			template : can.stache($('#slider_error_input').html()),
		});

		var template = can.stache("<slider-container></slider-container>");
		$('#view').append(template());

	}

	function setupSliderStyle() {
		$('#expSliderInnerContainer').height(formHeight);
		$('#expQuestionForm').css('maxHeight', formHeight - 70);

		$('#expScrollable').height(formHeight);
		$('#expScrollable').css('maxHeight', formHeight - 35);

		$('#expSlider').css('right', 0);
		$('#expSliderLabel').click(function(e) {
			e.preventDefault();
			toggle[c++ % 2]();
		});
		// Setup toggle mechanism
		var toggle = [ slideOut, slideIn ], c = 1;

		function slideOut() {
			var right = -315;

			function slideOutFrame() {
				right += 5;
				expSlider.style.right = right + 'px';
				if (right == 0)
					clearInterval(id);
			}
			var id = setInterval(slideOutFrame, 7);
		}

		function slideIn() {
			var right = 0;

			function slideInFrame() {
				right -= 5;
				expSlider.style.right = right + 'px';
				if (right == -315)
					clearInterval(id);
			}
			var id = setInterval(slideInFrame, 7);
		}
	}

	function sendCompletedData(questionnaire) {
		// filter for well-formed questions
		var wellFormedQuestions = questionnaire.questions.filter(function(
				elem, index, obj) {

			var hasAnswer = elem.answers[0] != "";

			var hasText = elem.questionText.length > 0;
			var hasWorkingTime = elem.workingTime.length > 0;

			return hasAnswer && hasText && hasWorkingTime;
		});

		var wellFormQuestionnaire = JSON.parse(JSON.stringify(questionnaire));
		wellFormQuestionnaire.questions = wellFormedQuestions;

		// send to server
		save(JSON.stringify(wellFormQuestionnaire));
	}
//
//	function updateAnswerFields(){
//		if(appState.attr("currentQuestion.answers").length == 1){
//			if(appState.attr("currentQuestion.answers.0").length>= 1){
//				appState.attr("currentQuestion.answers.1", { "answerText": "", "checkboxChecked": false});
//			}
//		}
//	}

	var isFormCompleted = function(expQuestionForm) {

		var elements = expQuestionForm.elements;

		// check if at least one answer is set
		var answerInputs = Array.prototype.slice.call(document.getElementById(
				"answers").querySelectorAll('[id^=answerInput]'));

		var answerCheckboxes = Array.prototype.slice.call(document
				.getElementById("answers").querySelectorAll(
						'[id^=answerCheckbox]'));

		var atLeastOneAnswer = answerInputs.filter(function(answer) {
			if (answer.value != "")
				return true;
		}).length > 0 ? true : false;

		// check if inputs before answers are all filled
		var upperBound = elements.length
				- (answerInputs.length + answerCheckboxes.length);

		for (var i = 0; i < upperBound; i++) {
			if (elements[i].value == "") {
				return false;
			}
		}
		return atLeastOneAnswer;
	}

	var createProperty = function(obj, key, value) {
		var config = {
			value : value,
			writable : true,
			enumerable : true,
			configurable : true
		};
		Object.defineProperty(obj, key, config);
	};

	function formValuesToJSON(expQuestionForm) {

		var container = {};

		var obj = {};

		obj["type"] = "";
		obj["questionText"] = "";
		obj["workingTime"] = "";
		obj["answers"] = [];

		var elements = expQuestionForm.elements;
		var length = elements.length - 1;

		var answers = [];

		// add ExplorViz landscape identifier
		createProperty(obj, "expLandscape", $(
				'#exp_slider_question_landscape option:selected').val());

		// add type
		createProperty(obj, "type", $(
				'#exp_slider_question_questiontype option:selected').val());

		var answerCounter = 0;

		// rename answer ids due to possible empty inputs
		// and create json
		for (var i = 0; i < length; i++) {

			if (elements[i].value != "") {

				if (elements[i].id.indexOf("answerInput") == 0) {

					if (answers.length == 0) {
						createProperty(obj, "answers", answers);
					}

					var answer = {};

					var checked = elements[("answerCheckbox" + answerCounter)].checked;

					createProperty(answer, "answerText",
							elements[i].value.toString());

					createProperty(answer, "checkboxChecked",
							checked);

					answers.push(answer);

					answerCounter++;

				} else if (elements[i].id.indexOf("answerCheckbox") != 0) {

					createProperty(obj, elements[i].id.toString(),
							elements[i].value);

				}
			}

			else if (elements[i].id.indexOf("answerInput") == 0) {

				answerCounter++;

			}
		}

		if (answers.length == 0) {
			createProperty(obj, "answers", answers);
			answers.push("");
		}

		// empty answer input
		answers.push({
            "answerText": "",
            "checkboxChecked": false
        });

		return obj;
	}

	function loadExplorViz() {
		if (qtLandscape.options[qtLandscape.selectedIndex] == undefined) {
			showExceptionDialog = true;
		} else {
			loadLandscape(qtLandscape.options[qtLandscape.selectedIndex].innerHTML);
			showExceptionDialog = false;
		}

	}
}<|endoftext|>


<commit_before>//----------------------------------------------------------------------
// Copyright (c) 2015 Raytheon BBN Technologies
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and/or hardware specification (the "Work") to
// deal in the Work without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Work, and to permit persons to whom the Work
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Work.
//
// THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
// IN THE WORK.
//----------------------------------------------------------------------

// cards.js: enable switching between tabs with nice animations

get_callback = function(tab_name) {
  return function(){};
}

// Switch to card with id new_active
function switch_to_card(new_active) {
  active.removeClass('activesection');
  oldindex = active.attr('data-tabindex');
  content.hide();

  var state = {location: new_active};
  history.pushState(state, '', new_active);

  active = $("ul.tabs a[href='" + new_active + "']");
  newindex = active.attr('data-tabindex');
  active.addClass('activesection');
  content = $(new_active);
  loadingdirection = oldindex < newindex ? "loadingright" : "loadingleft";
  content.addClass(loadingdirection);
  content.show();

  content.each(function(index, element) {
    setTimeout(function() {
      element = $(element);
      element.removeClass(loadingdirection);
    }, 0);
  });
  callback = get_callback(new_active);
  callback();
}

$(document).ready(function() {
  $('ul.tabs').each(function() {
    var links = $(this).find('a');
    try {
      var default_tab_name = DEFAULT_TAB; // the user has set a default tab for this page
    } catch(err) { default_tab_name = null; }
    active = $(links.filter('[href="'+location.hash+'"]')[0] || links.filter('[href="'+ default_tab_name +'"]')[0] || links[0]);
    active.addClass('activesection');
    content = $(active.attr('href'));
    callback = get_callback(active.attr('href'));
    callback();

    links.not(active).each(function() {
      $($(this).attr('href')).hide();
    });

    $(this).on('click', 'a', function(e) {
      switch_to_card($(this).attr('href'));
      e.preventDefault();
    });
  });

  $(window).on("popstate", function(e) {
    if (e.originalEvent.state !== null) {
      active.removeClass('activesection');
      content.hide();
      active = $('a[href="' + e.originalEvent.state.location + '"]');
      content = $(active.attr('href'));
      active.addClass('activesection');
      content.show();
    } else {
      $('ul.tabs').each(function() {
        active.removeClass('activesection');
        content.hide();
        var links = $(this).find('a');
        active = $(links.filter('[href="'+location.hash+'"]')[0] || links[0]);
        active.addClass('activesection');
        content = $(active.attr('href'));
        content.show();
      });
    }
  });
});
<commit_msg>Fix bug on Safari which stopped default slice view from working<commit_after>//----------------------------------------------------------------------
// Copyright (c) 2015 Raytheon BBN Technologies
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and/or hardware specification (the "Work") to
// deal in the Work without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Work, and to permit persons to whom the Work
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Work.
//
// THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
// IN THE WORK.
//----------------------------------------------------------------------

// cards.js: enable switching between tabs with nice animations

get_callback = function(tab_name) {
  return function(){};
}

// Switch to card with id new_active
function switch_to_card(new_active) {
  active.removeClass('activesection');
  oldindex = active.attr('data-tabindex');
  content.hide();

  var state = {location: new_active};
  history.pushState(state, '', new_active);

  active = $("ul.tabs a[href='" + new_active + "']");
  newindex = active.attr('data-tabindex');
  active.addClass('activesection');
  content = $(new_active);
  loadingdirection = oldindex < newindex ? "loadingright" : "loadingleft";
  content.addClass(loadingdirection);
  content.show();

  content.each(function(index, element) {
    setTimeout(function() {
      element = $(element);
      element.removeClass(loadingdirection);
    }, 0);
  });
  callback = get_callback(new_active);
  callback();
}

$(document).ready(function() {
  $('ul.tabs').each(function() {
    var links = $(this).find('a');
    try {
      var default_tab_name = DEFAULT_TAB; // the user has set a default tab for this page
    } catch(err) { default_tab_name = null; }
    active = $(links.filter('[href="'+location.hash+'"]')[0] || links.filter('[href="'+ default_tab_name +'"]')[0] || links[0]);
    active.addClass('activesection');
    content = $(active.attr('href'));
    callback = get_callback(active.attr('href'));
    callback();

    links.not(active).each(function() {
      $($(this).attr('href')).hide();
    });

    $(this).on('click', 'a', function(e) {
      switch_to_card($(this).attr('href'));
      e.preventDefault();
    });
  });

  $(window).on("popstate", function(e) {
    if (e.originalEvent.state !== null) {
      active.removeClass('activesection');
      content.hide();
      active = $('a[href="' + e.originalEvent.state.location + '"]');
      content = $(active.attr('href'));
      active.addClass('activesection');
      content.show();
    } else {
      $('ul.tabs').each(function() {
        active.removeClass('activesection');
        content.hide();
        var links = $(this).find('a');
        try {
          var default_tab_name = DEFAULT_TAB; // the user has set a default tab for this page
        } catch(err) { default_tab_name = null; }
        active = $(links.filter('[href="'+location.hash+'"]')[0] || links.filter('[href="'+ default_tab_name +'"]')[0] || links[0]);
        active.addClass('activesection');
        content = $(active.attr('href'));
        content.show();
      });
    }
  });
});
<|endoftext|>


<commit_before>angular.module( 'celestial.systems', [
  'ui.state', 'ui.bootstrap', 'ngResource',
  'celestial.system', 'celestial.systemAdd', 'celestial.actions',
  'angular-growl', 'ngAnimate'
])
.config(function config($stateProvider) {
  $stateProvider.state( 'systems', {
    url: '/systems',
    views: {
      "main": {
        controller: 'SystemsCtrl',
        templateUrl: 'systems/systems.tpl.html'
      }
    },
    data:{ pageTitle: 'Systems' }
  });
})
.controller( 'SystemsCtrl', function SystemsController($scope, $resource, $http, actionsService, growl) {

  var Systems = $resource('/systems/', {page:'@page',offset:'@offset'});
  var Jobs = $resource('/jobs/', {},{
   create:{method : "POST", params:{id:'@id'},url:'/jobs/create/:id'},
   provision:{method : "POST", params:{id:'@id'},url:'/jobs/provision/:id'},
   stage:{method : "POST", params:{id:'@id'},url:'/jobs/stage/:id'},
   destroy:{method : "POST", params:{id:'@id'},url:'/jobs/destroy/:id'}
  });

  $scope.perPage = 10;
  $scope.currentPage = 1;

  $scope.loadCount = function(){
     Systems.get({page:1,offset:$scope.perPage},function(data,resp){
        if(data.meta!=null){
          $scope.count = data.meta.total;
        }
     });
  };

  $scope.setPage = function () {
    var page = {page:$scope.currentPage,offset: $scope.perPage};
    Systems.get(page,function (data){
	$scope.systems = [];
      angular.forEach(data.systems,function(system){
        system[1]['id'] = system[0];
        system[1]['hypervisor'] = _.filter(['aws','proxmox','vsphere'],function(a){
           return system[1][a]!=null;
        })[0];
        system[1]['actions'] = actionsService.loadActions(system[1].type);

        $scope.systems.push(system[1]);
	});
    });
  };

  $scope.launchJob = function(id,job) {
    Jobs[job]({id:id},function(data) {
       growl.addInfoMessage(data.msg);
    });
  };

  $scope.launchAction = function(id,action) {
    actionsService.launchAction(id,action);
  };

  $scope.$watch( 'currentPage', $scope.setPage );

});

<commit_msg>Missing load count call<commit_after>angular.module( 'celestial.systems', [
  'ui.state', 'ui.bootstrap', 'ngResource',
  'celestial.system', 'celestial.systemAdd', 'celestial.actions',
  'angular-growl', 'ngAnimate'
])
.config(function config($stateProvider) {
  $stateProvider.state( 'systems', {
    url: '/systems',
    views: {
      "main": {
        controller: 'SystemsCtrl',
        templateUrl: 'systems/systems.tpl.html'
      }
    },
    data:{ pageTitle: 'Systems' }
  });
})
.controller( 'SystemsCtrl', function SystemsController($scope, $resource, $http, actionsService, growl) {

  var Systems = $resource('/systems/', {page:'@page',offset:'@offset'});
  var Jobs = $resource('/jobs/', {},{
   create:{method : "POST", params:{id:'@id'},url:'/jobs/create/:id'},
   provision:{method : "POST", params:{id:'@id'},url:'/jobs/provision/:id'},
   stage:{method : "POST", params:{id:'@id'},url:'/jobs/stage/:id'},
   destroy:{method : "POST", params:{id:'@id'},url:'/jobs/destroy/:id'}
  });

  $scope.perPage = 10;
  $scope.currentPage = 1;

  $scope.loadCount = function(){
     Systems.get({page:1,offset:$scope.perPage},function(data,resp){
        if(data.meta!=null){
          $scope.count = data.meta.total;
        }
     });
  };

  $scope.setPage = function () {
    var page = {page:$scope.currentPage,offset: $scope.perPage};
    Systems.get(page,function (data){
	$scope.systems = [];
      angular.forEach(data.systems,function(system){
        system[1]['id'] = system[0];
        system[1]['hypervisor'] = _.filter(['aws','proxmox','vsphere'],function(a){
           return system[1][a]!=null;
        })[0];
        system[1]['actions'] = actionsService.loadActions(system[1].type);

        $scope.systems.push(system[1]);
	});
    });
  };

  $scope.launchJob = function(id,job) {
    Jobs[job]({id:id},function(data) {
       growl.addInfoMessage(data.msg);
    });
  };

  $scope.launchAction = function(id,action) {
    actionsService.launchAction(id,action);
  };

  $scope.loadCount();
  $scope.$watch( 'currentPage', $scope.setPage );

});

<|endoftext|>


<commit_before>var request = require('request');
var fs = require('fs');
var spawn = require('child_process').spawn;

module.exports = {

	// Write routes object to router file
	writeRoutes: function(routes) {
		fs.writeFileSync('config/routes.js', 'module.exports.routes = ' + JSON.stringify(routes));
	},

	// Write routes object to blueprint config file
	writeBlueprint: function(config) {
		config = {controllers: {blueprints: config}};
		fs.writeFileSync('config/controllers.js', 'module.exports = ' + JSON.stringify(config));
	},

	// Starts sails server, makes request, returns response, kills sails server
	testRoute: function(method, options, callback) {

		// Prefix url with domain:port
		if (typeof options === 'string') {
			options = 'http://localhost:1337/' + options;
		} else {
			options.url = 'http://localhost:1337/'  + options.url;
		}

		// Start the sails server process
		var sailsprocess = spawn('../bin/sails.js', ['lift', '--dev']);

		sailsprocess.on('error',function(err) {
			return callback(err);
		});
		sailsprocess.stderr.on('data',function(data) {
			return callback(data);
		});

		sailsprocess.stdout.on('data',function(data) {

			// Change buffer to string
			var dataString = data + '';

			// Make request once server has sucessfully started
			if (dataString.match(/Server lifted/)) {
				sailsprocess.stdout.removeAllListeners('data');
				setTimeout(function () {
					request[method](options, function(err, response) {
						if (err) callback(err);

						// Kill server process and return response
						sailsprocess.kill();
						callback(null, response);
					});
				}, 1000);
			}
		});
	}
};
<commit_msg>Rebases the rest of https://github.com/balderdashy/sails/pull/890    aka #890<commit_after>var request = require('request');
var fs = require('fs');
var spawn = require('child_process').spawn;

module.exports = {

	// Write routes object to router file
	writeRoutes: function(routes) {
		fs.writeFileSync('config/routes.js', 'module.exports.routes = ' + JSON.stringify(routes));
	},

	// Write routes object to blueprint config file
	writeBlueprint: function(config) {
		config = {controllers: {blueprints: config}};
		fs.writeFileSync('config/controllers.js', 'module.exports = ' + JSON.stringify(config));
	},

	// Starts sails server, makes request, returns response, kills sails server
	testRoute: function(method, options, callback) {

		// Prefix url with domain:port
		if (typeof options === 'string') {
			options = 'http://localhost:1337/' + options;
		} else {
			options.url = 'http://localhost:1337/'  + options.url;
		}

		// Start the sails server process
		var sailsprocess = spawn('../bin/sails.js', ['lift', '--dev']);

		sailsprocess.on('error',function(err) {
			return callback(err);
		});
		sailsprocess.stdout.on('data',function(data) {

			// Change buffer to string
			var dataString = data + '';

			// Make request once server has sucessfully started
			if (dataString.match(/Server lifted/)) {
				sailsprocess.stdout.removeAllListeners('data');
				setTimeout(function () {
					request[method](options, function(err, response) {
						if (err) callback(err);

						// Kill server process and return response
						sailsprocess.kill();
						callback(null, response);
					});
				}, 1000);
			}
		});
	}
};
<|endoftext|>


<commit_before>/* global ga, ZeroClipboard, ActiveXObject, $, localStorage */

$(document).on('emoji:ready', function () {
  $('.input-search').focus()
  $('.loading').remove()

  var hasFlash = false
  try {
    hasFlash = Boolean(new ActiveXObject('ShockwaveFlash.ShockwaveFlash'))
  } catch (exception) {
    hasFlash = (typeof navigator.mimeTypes['application/x-shockwave-flash'] !== 'undefined')
  }

  if (!hasFlash || navigator.userAgent.match(/iPad|iPhone|Chrome/i)) {
    $(document).on('click', '.emoji-code', function () {
      this.select()
      document.execCommand('copy')
      window.getSelection().removeAllRanges()
      alertCopied(this.value)
    })
  } else {
    var clip = new ZeroClipboard($('[data-clipboard-text]'), { moviePath: '/assets/zeroclipboard.swf' })
    clip.on('complete', function (_, args) {
      alertCopied(args.text)
    })
    $('.emoji-code').attr('readonly', 'readonly')
  }
})

function alertCopied (emoji) {
  $('

').text('Copied ' + emoji).appendTo('body').fadeIn().delay(1000).fadeOut()
}

function focusOnSearch (e) {
  var searchField = $('.input-search')[0]
  if (e.keyCode === 191 && searchField) {
    if (searchField.value.length) {
      searchField.selectionStart = 0
      searchField.selectionEnd = searchField.value.length
    }
    searchField.focus()
    e.preventDefault()
    return false
  }
}

$.getJSON('/javascripts/emojilib/emojis.json', function (emojis) {
  var hasFont = window.hasAppleColorEmoji()
  var container = $('.emojis-container')
  Object.keys(emojis).forEach(function (key) {
    var emoji = emojis[key]
    var charHTML
    if ((hasFont || navigator.platform.match(/Mac/)) && emoji['char']) {
      charHTML = '
' + emoji['char'] + '
'
    } else {
      charHTML = '
' + key + '
'
    }
    container.append('
' +
      charHTML + '<input type="text" class="autofocus plain emoji-code" value=":' + key +
      ':" />' + key + ' ' + emoji['keywords'] + '
')
  })
  $(document).trigger('emoji:ready')
  $('.emojis-container').toggleClass('hide-text', localStorage.getItem('emoji-text-display') === 'false')
})

$(document).keydown(function (e) { focusOnSearch(e) })

$(document).on('keydown', '.emoji-wrapper input', function (e) {
  $('.input-search').blur()
  focusOnSearch(e)
})

$(document).on('click', '[data-clipboard-text]', function () {
  ga('send', 'event', 'copy', $(this).attr('data-clipboard-text'))
})

$(document).on('click', '.js-hide-text', function () {
  $('.emojis-container').toggleClass('hide-text')
  var showorhide = $('.emojis-container').hasClass('hide-text') ? 'hide' : 'show'
  localStorage.setItem('emoji-text-display', !$('.emojis-container').hasClass('hide-text'))
  ga('send', 'event', 'toggle text', showorhide)
  return false
})

$(document).on('click', '.js-clear-search, .mojigroup.active', function () {
  window.location.hash = ''
  return false
})

$(document).on('click', '.js-contribute', function () {
  ga('send', 'event', 'contribute', 'click')
})
<commit_msg>Add shift click to copy char (no zeroclipboard), ref: #162<commit_after>/* global ga, ZeroClipboard, ActiveXObject, $, localStorage */

$(document).on('emoji:ready', function () {
  $('.input-search').focus()
  $('.loading').remove()

  var hasFlash = false
  try {
    hasFlash = Boolean(new ActiveXObject('ShockwaveFlash.ShockwaveFlash'))
  } catch (exception) {
    hasFlash = (typeof navigator.mimeTypes['application/x-shockwave-flash'] !== 'undefined')
  }

  if (!hasFlash || navigator.userAgent.match(/iPad|iPhone|Chrome/i)) {
    $(document).on('click', '.emoji-code', function (evt) {
      if (evt.shiftKey) {
        window.getSelection().removeAllRanges()
        var range = document.createRange()
        range.selectNodeContents(this.previousElementSibling)
        window.getSelection().addRange(range)
      } else {
        this.select()
      }
      document.execCommand('copy')
      window.getSelection().removeAllRanges()
      alertCopied(evt.shiftKey ? this.previousElementSibling.innerText : this.value)
    })
  } else {
    var clip = new ZeroClipboard($('[data-clipboard-text]'), { moviePath: '/assets/zeroclipboard.swf' })
    clip.on('complete', function (_, args) {
      alertCopied(args.text)
    })
    $('.emoji-code').attr('readonly', 'readonly')
  }
})

function alertCopied (emoji) {
  $('

').text('Copied ' + emoji).appendTo('body').fadeIn().delay(1000).fadeOut()
}

function focusOnSearch (e) {
  var searchField = $('.input-search')[0]
  if (e.keyCode === 191 && searchField) {
    if (searchField.value.length) {
      searchField.selectionStart = 0
      searchField.selectionEnd = searchField.value.length
    }
    searchField.focus()
    e.preventDefault()
    return false
  }
}

$.getJSON('/javascripts/emojilib/emojis.json', function (emojis) {
  var hasFont = window.hasAppleColorEmoji()
  var container = $('.emojis-container')
  Object.keys(emojis).forEach(function (key) {
    var emoji = emojis[key]
    var charHTML
    if ((hasFont || navigator.platform.match(/Mac/)) && emoji['char']) {
      charHTML = '
' + emoji['char'] + '
'
    } else {
      charHTML = '
' + key + '
'
    }
    container.append('
' +
      charHTML + '<input type="text" class="autofocus plain emoji-code" value=":' + key +
      ':" />' + key + ' ' + emoji['keywords'] + '
')
  })
  $(document).trigger('emoji:ready')
  $('.emojis-container').toggleClass('hide-text', localStorage.getItem('emoji-text-display') === 'false')
})

$(document).keydown(function (e) { focusOnSearch(e) })

$(document).on('keydown', '.emoji-wrapper input', function (e) {
  $('.input-search').blur()
  focusOnSearch(e)
})

$(document).on('click', '[data-clipboard-text]', function () {
  ga('send', 'event', 'copy', $(this).attr('data-clipboard-text'))
})

$(document).on('click', '.js-hide-text', function () {
  $('.emojis-container').toggleClass('hide-text')
  var showorhide = $('.emojis-container').hasClass('hide-text') ? 'hide' : 'show'
  localStorage.setItem('emoji-text-display', !$('.emojis-container').hasClass('hide-text'))
  ga('send', 'event', 'toggle text', showorhide)
  return false
})

$(document).on('click', '.js-clear-search, .mojigroup.active', function () {
  window.location.hash = ''
  return false
})

$(document).on('click', '.js-contribute', function () {
  ga('send', 'event', 'contribute', 'click')
})
<|endoftext|>